-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathdevice-auth.ts
More file actions
216 lines (190 loc) · 6.57 KB
/
Copy pathdevice-auth.ts
File metadata and controls
216 lines (190 loc) · 6.57 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
/**
* Device Authorization Flow
*
* Implements OAuth 2.0 Device Authorization Grant (RFC 8628) for CLI authentication.
* Extracted from login.ts for reuse in wizard credential gathering.
*/
import { logInfo, logError } from '../utils/debug.js';
export interface DeviceAuthResponse {
device_code: string;
user_code: string;
verification_uri: string;
verification_uri_complete: string;
expires_in: number;
interval: number;
}
export interface DeviceAuthOptions {
clientId: string;
authkitDomain: string;
scopes?: string[];
timeoutMs?: number;
onPoll?: () => void;
onSlowDown?: (newIntervalMs: number) => void;
}
export interface DeviceAuthResult {
accessToken: string;
idToken: string;
expiresAt: number;
userId: string;
email?: string;
refreshToken?: string;
}
interface TokenResponse {
access_token: string;
id_token: string;
token_type: string;
expires_in: number;
refresh_token?: string;
}
interface AuthErrorResponse {
error: string;
error_description?: string;
}
export class DeviceAuthError extends Error {
constructor(message: string) {
super(message);
this.name = 'DeviceAuthError';
}
}
const DEFAULT_TIMEOUT_MS = 5 * 60 * 1000; // 5 minutes
const DEFAULT_POLL_INTERVAL_SECONDS = 5;
const POLL_REQUEST_TIMEOUT_MS = 30_000;
const DEFAULT_SCOPES = ['openid', 'email', 'staging-environment:credentials:read', 'offline_access'];
function sleep(ms: number): Promise<void> {
return new Promise((resolve) => setTimeout(resolve, ms));
}
/**
* Parse JWT payload
*/
function parseJwt(token: string): Record<string, unknown> | null {
try {
const parts = token.split('.');
if (parts.length !== 3) return null;
return JSON.parse(Buffer.from(parts[1], 'base64url').toString('utf-8'));
} catch {
return null;
}
}
/**
* Extract expiry time from JWT token
*/
function getJwtExpiry(token: string): number | null {
const payload = parseJwt(token);
if (!payload || typeof payload.exp !== 'number') return null;
return payload.exp * 1000;
}
/**
* Request a device code from the OAuth authorization server.
* Returns the device code, user code, and verification URIs.
*/
export async function requestDeviceCode(options: DeviceAuthOptions): Promise<DeviceAuthResponse> {
const scopes = options.scopes ?? DEFAULT_SCOPES;
const url = `${options.authkitDomain}/oauth2/device_authorization`;
logInfo('[device-auth] Requesting device code from:', url);
const res = await fetch(url, {
method: 'POST',
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
body: new URLSearchParams({
client_id: options.clientId,
scope: scopes.join(' '),
}),
});
logInfo('[device-auth] Device code response status:', res.status);
if (!res.ok) {
const text = await res.text();
logError('[device-auth] Device authorization failed:', res.status, text);
throw new DeviceAuthError(`Device authorization failed: ${res.status} ${text}`);
}
const data = (await res.json()) as DeviceAuthResponse;
logInfo('[device-auth] Device code received, user_code:', data.user_code);
return data;
}
/**
* Poll for token after user has authorized in the browser.
* Handles authorization_pending and slow_down responses per RFC 8628.
*/
export async function pollForToken(
deviceCode: string,
options: DeviceAuthOptions & { interval: number },
): Promise<DeviceAuthResult> {
const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;
const startTime = Date.now();
let pollInterval = (options.interval || DEFAULT_POLL_INTERVAL_SECONDS) * 1000;
const tokenUrl = `${options.authkitDomain}/oauth2/token`;
let pollCount = 0;
let lastPollSummary = 'no token response received';
logInfo('[device-auth] Starting token polling, timeout:', timeoutMs);
while (Date.now() - startTime < timeoutMs) {
await sleep(pollInterval);
pollCount++;
options.onPoll?.();
let res: Response;
const controller = new AbortController();
const timeout = setTimeout(() => controller.abort(), POLL_REQUEST_TIMEOUT_MS);
try {
res = await fetch(tokenUrl, {
method: 'POST',
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
body: new URLSearchParams({
grant_type: 'urn:ietf:params:oauth:grant-type:device_code',
device_code: deviceCode,
client_id: options.clientId,
}),
signal: controller.signal,
});
} catch (error) {
logInfo(
'[device-auth] Token poll network error, retrying:',
error instanceof Error ? error.message : String(error),
);
continue;
} finally {
clearTimeout(timeout);
}
let data;
try {
data = await res.json();
} catch (error) {
const message = error instanceof Error ? error.message : String(error);
logError('[device-auth] Invalid JSON response from auth server:', message);
throw new DeviceAuthError(`Invalid response from auth server: ${message}`);
}
const errorData = data as AuthErrorResponse;
const elapsedMs = Date.now() - startTime;
lastPollSummary = res.ok
? `${res.status} success`
: `${res.status} ${errorData.error ?? 'unknown_error'}${errorData.error_description ? ` (${errorData.error_description})` : ''}`;
logInfo('[device-auth] Token poll response:', `attempt=${pollCount}`, `elapsedMs=${elapsedMs}`, lastPollSummary);
if (res.ok) {
logInfo('[device-auth] Token received successfully');
return parseTokenResponse(data as TokenResponse);
}
if (errorData.error === 'authorization_pending') {
continue;
}
if (errorData.error === 'slow_down') {
pollInterval += 5000;
logInfo('[device-auth] Slowing down, new interval:', pollInterval);
options.onSlowDown?.(pollInterval);
continue;
}
logError('[device-auth] Token error:', errorData.error);
throw new DeviceAuthError(`Token error: ${errorData.error}`);
}
logError('[device-auth] Authentication timed out, last poll:', lastPollSummary);
throw new DeviceAuthError(
`Authentication timed out after ${Math.round(timeoutMs / 1000)} seconds (last token response: ${lastPollSummary})`,
);
}
function parseTokenResponse(data: TokenResponse): DeviceAuthResult {
const idPayload = parseJwt(data.id_token);
const jwtExpiry = getJwtExpiry(data.access_token);
return {
accessToken: data.access_token,
idToken: data.id_token,
expiresAt: jwtExpiry ?? (data.expires_in ? Date.now() + data.expires_in * 1000 : Date.now() + 15 * 60 * 1000),
userId: String(idPayload?.sub ?? 'unknown'),
email: idPayload?.email as string | undefined,
refreshToken: data.refresh_token,
};
}