-
Notifications
You must be signed in to change notification settings - Fork 34
Expand file tree
/
Copy pathdevice-auth.ts
More file actions
539 lines (492 loc) · 15.2 KB
/
Copy pathdevice-auth.ts
File metadata and controls
539 lines (492 loc) · 15.2 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
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
import type { TokenResult } from "../types.js";
import {
CLIENT_ID,
exchangeAuthorizationCode,
sanitizeOAuthResponseBodyForLog,
} from "./auth.js";
const DEVICE_AUTH_BASE_URL = "https://auth.openai.com";
const DEVICE_AUTH_API_BASE_URL = `${DEVICE_AUTH_BASE_URL}/api/accounts`;
export const DEVICE_AUTH_VERIFICATION_URL = `${DEVICE_AUTH_BASE_URL}/codex/device`;
export const DEVICE_AUTH_REDIRECT_URI = `${DEVICE_AUTH_BASE_URL}/deviceauth/callback`;
const DEVICE_AUTH_TIMEOUT_MS = 15 * 60 * 1000;
const DEVICE_AUTH_DEFAULT_INTERVAL_MS = 5_000;
const DEVICE_AUTH_ABORTED_MESSAGE = "aborted";
const DEVICE_AUTH_TRANSIENT_PENDING_STATUSES = new Set([
408,
429,
502,
503,
504,
]);
type FetchLike = typeof fetch;
export interface DeviceAuthCode {
verificationUrl: string;
userCode: string;
deviceAuthId: string;
intervalMs: number;
expiresAtMs?: number;
}
export interface DeviceAuthCompletion {
authorizationCode: string;
codeVerifier: string;
}
export type DeviceAuthCodeResult =
| { type: "success"; deviceCode: DeviceAuthCode }
| Extract<TokenResult, { type: "failed" }>;
export type DeviceAuthCompletionResult =
| { type: "success"; completion: DeviceAuthCompletion }
| Extract<TokenResult, { type: "failed" }>;
export interface DeviceAuthFlowOptions {
fetchImpl?: FetchLike;
now?: () => number;
sleep?: (ms: number) => Promise<void>;
signal?: AbortSignal;
timeoutMs?: number;
log?: (message: string) => void;
random?: () => number;
// When true, sleep timers are not unref'd, so the Node event loop is held
// open while polling. Required for foreground CLI use where the process
// would otherwise exit while a top-level await is still pending. Defaults
// to false so library/background consumers keep the existing unref'd
// behavior and don't accidentally block process exit.
keepAlive?: boolean;
}
function getFetch(options: DeviceAuthFlowOptions): FetchLike {
return options.fetchImpl ?? fetch;
}
function getNow(options: DeviceAuthFlowOptions): () => number {
return options.now ?? Date.now;
}
function unrefTimer(timer: ReturnType<typeof setTimeout>): void {
(timer as { unref?: () => void }).unref?.();
}
function getSleep(options: DeviceAuthFlowOptions): (ms: number) => Promise<void> {
return (
options.sleep ??
((ms: number) =>
new Promise<void>((resolve) => {
const timeout = setTimeout(resolve, ms);
if (!options.keepAlive) {
unrefTimer(timeout);
}
}))
);
}
function getRandom(options: DeviceAuthFlowOptions): () => number {
return options.random ?? Math.random;
}
function failedResult(
reason: Extract<TokenResult, { type: "failed" }>["reason"],
message: string,
statusCode?: number,
): Extract<TokenResult, { type: "failed" }> {
return {
type: "failed",
reason,
statusCode,
message,
};
}
function createAbortError(): Error {
const error = new Error(DEVICE_AUTH_ABORTED_MESSAGE);
error.name = "AbortError";
return error;
}
function isAbortError(error: unknown): boolean {
return error instanceof Error && error.name === "AbortError";
}
function abortedResult(): Extract<TokenResult, { type: "failed" }> {
return failedResult("network_error", DEVICE_AUTH_ABORTED_MESSAGE);
}
function sleepWithAbort(
ms: number,
options: DeviceAuthFlowOptions,
): Promise<void> {
const signal = options.signal;
if (!signal) {
return getSleep(options)(ms);
}
if (signal.aborted) {
return Promise.reject(createAbortError());
}
const customSleep = options.sleep;
if (customSleep) {
let removeAbortListener = () => {};
const abortPromise = new Promise<void>((_resolve, reject) => {
const onAbort = () => reject(createAbortError());
signal.addEventListener("abort", onAbort, { once: true });
removeAbortListener = () => signal.removeEventListener("abort", onAbort);
});
return Promise.race([customSleep(ms), abortPromise]).finally(
removeAbortListener,
);
}
return new Promise<void>((resolve, reject) => {
const onAbort = () => {
clearTimeout(timeout);
cleanup();
reject(createAbortError());
};
const cleanup = () => signal.removeEventListener("abort", onAbort);
const timeout = setTimeout(() => {
cleanup();
resolve();
}, ms);
if (!options.keepAlive) {
unrefTimer(timeout);
}
signal.addEventListener("abort", onAbort, { once: true });
});
}
function formatWaitBudget(timeoutMs: number): string {
const totalSeconds = Math.max(1, Math.ceil(timeoutMs / 1000));
if (totalSeconds < 60) {
return `${totalSeconds} second${totalSeconds === 1 ? "" : "s"}`;
}
const totalMinutes = Math.ceil(totalSeconds / 60);
return `${totalMinutes} minute${totalMinutes === 1 ? "" : "s"}`;
}
// The OpenAI Codex device-code token endpoint is NOT RFC 8628 compliant: it
// does not return a 400 + {"error":"authorization_pending"} body while waiting.
// Instead, `POST /api/accounts/deviceauth/token` returns a bare 403 while the
// user has not yet approved the code in the browser, and a bare 404 while the
// `device_auth_id` is not yet recognized (propagation lag right after the
// usercode request). Both are normal mid-flight states that must keep polling
// until the user completes the browser step or the deadline/server expiry hits;
// treating either as terminal would abort every login the instant the first
// poll fires, before the user could ever approve. This is exercised by
// test/device-auth.test.ts, where a 403 (and a 404) is the happy-path waiting
// state immediately preceding success. Do not move 403/404 out of the pending
// set without first re-confirming the live endpoint contract, including how a
// user-initiated denial is signaled — if denial is reported with its own
// distinguishable status or body, add that as a separate terminal branch rather
// than reclassifying the bare 403/404 pending responses.
function isPendingStatus(status: number): boolean {
return (
status === 403 ||
status === 404 ||
DEVICE_AUTH_TRANSIENT_PENDING_STATUSES.has(status)
);
}
function parseRetryAfterMs(value: string | null, nowMs: number): number | null {
if (!value) return null;
const trimmed = value.trim();
if (!trimmed) return null;
const seconds = Number(trimmed);
if (Number.isFinite(seconds) && seconds >= 0) {
return Math.ceil(seconds * 1000);
}
const dateMs = Date.parse(trimmed);
if (Number.isFinite(dateMs)) {
return Math.max(0, dateMs - nowMs);
}
return null;
}
function applyLightJitter(
delayMs: number,
options: DeviceAuthFlowOptions,
): number {
const jitterRatio = 1 + (getRandom(options)() - 0.5) * 0.2;
return Math.max(1_000, Math.round(delayMs * jitterRatio));
}
function resolvePollDelayMs(
response: Response,
deviceCode: DeviceAuthCode,
nowMs: number,
options: DeviceAuthFlowOptions,
): number {
const retryAfterMs = parseRetryAfterMs(
response.headers.get("retry-after"),
nowMs,
);
if (retryAfterMs !== null) {
return Math.max(1_000, retryAfterMs);
}
if (response.status === 403 || response.status === 404) {
return deviceCode.intervalMs;
}
return applyLightJitter(deviceCode.intervalMs, options);
}
function asRecord(value: unknown): Record<string, unknown> | null {
if (value === null || typeof value !== "object" || Array.isArray(value)) {
return null;
}
return value as Record<string, unknown>;
}
async function readJsonRecord(response: Response): Promise<Record<string, unknown> | null> {
const text = await response.text().catch(() => "");
if (!text.trim()) {
return null;
}
try {
return asRecord(JSON.parse(text) as unknown);
} catch {
return null;
}
}
function parseIntervalMs(value: unknown): number {
if (typeof value === "number" && Number.isFinite(value) && value > 0) {
return Math.trunc(value * 1000);
}
if (typeof value === "string") {
const parsed = Number.parseFloat(value.trim());
if (Number.isFinite(parsed) && parsed > 0) {
return Math.trunc(parsed * 1000);
}
}
return DEVICE_AUTH_DEFAULT_INTERVAL_MS;
}
function parseAbsoluteExpirationMs(value: unknown): number | null {
if (typeof value === "number" && Number.isFinite(value) && value > 0) {
// Unix epoch in seconds if < 10^10, otherwise already in ms
return value < 10_000_000_000 ? value * 1000 : value;
}
if (typeof value === "string") {
const trimmed = value.trim();
if (/^\d+(?:\.\d+)?$/.test(trimmed)) {
const n = Number.parseFloat(trimmed);
return n < 10_000_000_000 ? n * 1000 : n;
}
const dateMs = Date.parse(trimmed);
if (Number.isFinite(dateMs)) return dateMs;
}
return null;
}
function parseExpirationMs(value: unknown, nowMs: number): number | null {
if (typeof value === "number" && Number.isFinite(value) && value > 0) {
return nowMs + Math.trunc(value * 1000);
}
if (typeof value === "string") {
const trimmed = value.trim();
if (/^\d+(?:\.\d+)?$/.test(trimmed)) {
const seconds = Number.parseFloat(trimmed);
return nowMs + Math.trunc(seconds * 1000);
}
const dateMs = Date.parse(trimmed);
if (Number.isFinite(dateMs)) {
return dateMs;
}
}
return null;
}
function parseNonEmptyString(value: unknown): string | null {
if (typeof value !== "string") {
return null;
}
const trimmed = value.trim();
return trimmed.length > 0 ? trimmed : null;
}
function parseDeviceCodePayload(
payload: Record<string, unknown>,
nowMs: number,
): DeviceAuthCode | null {
const deviceAuthId = parseNonEmptyString(payload.device_auth_id);
const userCode =
parseNonEmptyString(payload.user_code) ??
parseNonEmptyString(payload.usercode);
if (!deviceAuthId || !userCode) {
return null;
}
const expiresAtMs =
parseAbsoluteExpirationMs(payload.expires_at) ??
parseExpirationMs(payload.expires_in, nowMs);
return {
verificationUrl: DEVICE_AUTH_VERIFICATION_URL,
userCode,
deviceAuthId,
intervalMs: parseIntervalMs(payload.interval),
...(expiresAtMs === null ? {} : { expiresAtMs }),
};
}
function parseCompletionPayload(
payload: Record<string, unknown>,
): DeviceAuthCompletion | null {
const authorizationCode = parseNonEmptyString(payload.authorization_code);
const codeVerifier = parseNonEmptyString(payload.code_verifier);
if (!authorizationCode || !codeVerifier) {
return null;
}
// OpenAI Codex's device-code endpoint intentionally returns the PKCE
// verifier with the issued authorization code. This mirrors the upstream
// Codex CLI flow. The verifier is never persisted to account storage; keep
// this poll response out of logs and only hand it directly to the token
// exchange.
return { authorizationCode, codeVerifier };
}
async function readFailureText(response: Response): Promise<string> {
const text = await response.text().catch(() => "");
return sanitizeOAuthResponseBodyForLog(text);
}
export async function requestDeviceAuthorization(
options: DeviceAuthFlowOptions = {},
): Promise<DeviceAuthCodeResult> {
if (options.signal?.aborted) {
return abortedResult();
}
try {
const response = await getFetch(options)(
`${DEVICE_AUTH_API_BASE_URL}/deviceauth/usercode`,
{
method: "POST",
headers: { "Content-Type": "application/json" },
signal: options.signal,
body: JSON.stringify({ client_id: CLIENT_ID }),
},
);
if (!response.ok) {
if (response.status === 404) {
return failedResult(
"http_error",
"Device auth login is not enabled for this Codex server. Use browser login or --manual.",
response.status,
);
}
const safeText = await readFailureText(response);
return failedResult(
"http_error",
safeText || `Device code request failed with status ${response.status}`,
response.status,
);
}
const payload = await readJsonRecord(response);
const deviceCode = payload
? parseDeviceCodePayload(payload, getNow(options)())
: null;
if (!deviceCode) {
return failedResult(
"invalid_response",
"Device code request response failed schema validation",
);
}
return { type: "success", deviceCode };
} catch (error) {
if (isAbortError(error) || options.signal?.aborted) {
return abortedResult();
}
return failedResult(
"network_error",
error instanceof Error ? error.message : String(error),
);
}
}
function printDeviceAuthorizationPrompt(
deviceCode: DeviceAuthCode,
log: (message: string) => void = console.log,
timeoutMs = DEVICE_AUTH_TIMEOUT_MS,
nowMs = Date.now(),
): void {
const effectiveTimeoutMs =
deviceCode.expiresAtMs === undefined
? timeoutMs
: Math.min(timeoutMs, Math.max(0, deviceCode.expiresAtMs - nowMs));
log("Device auth login");
log(`Open: ${deviceCode.verificationUrl}`);
log(`Code: ${deviceCode.userCode}`);
log(
`This code expires in ${formatWaitBudget(effectiveTimeoutMs)}. Never share it.`,
);
}
export async function pollDeviceAuthorization(
deviceCode: DeviceAuthCode,
options: DeviceAuthFlowOptions = {},
): Promise<DeviceAuthCompletionResult> {
const now = getNow(options);
const startMs = now();
const timeoutMs = options.timeoutMs ?? DEVICE_AUTH_TIMEOUT_MS;
const deadline = Math.min(
startMs + timeoutMs,
deviceCode.expiresAtMs ?? Number.POSITIVE_INFINITY,
);
const effectiveTimeoutMs = Math.max(0, deadline - startMs);
try {
while (true) {
if (options.signal?.aborted) {
return abortedResult();
}
const response = await getFetch(options)(
`${DEVICE_AUTH_API_BASE_URL}/deviceauth/token`,
{
method: "POST",
headers: { "Content-Type": "application/json" },
signal: options.signal,
body: JSON.stringify({
device_auth_id: deviceCode.deviceAuthId,
user_code: deviceCode.userCode,
}),
},
);
if (response.ok) {
const payload = await readJsonRecord(response);
const completion = payload ? parseCompletionPayload(payload) : null;
if (!completion) {
return failedResult(
"invalid_response",
"Device auth token response failed schema validation",
);
}
return { type: "success", completion };
}
if (isPendingStatus(response.status)) {
const nowMs = now();
const remainingMs = deadline - nowMs;
if (remainingMs <= 0) {
return failedResult(
"timeout",
`Device auth timed out after ${formatWaitBudget(effectiveTimeoutMs)}`,
);
}
const delayMs = resolvePollDelayMs(
response,
deviceCode,
nowMs,
options,
);
await sleepWithAbort(Math.min(delayMs, remainingMs), options);
continue;
}
const safeText = await readFailureText(response);
return failedResult(
"http_error",
safeText || `Device auth failed with status ${response.status}`,
response.status,
);
}
} catch (error) {
if (isAbortError(error) || options.signal?.aborted) {
return abortedResult();
}
return failedResult(
"network_error",
error instanceof Error ? error.message : String(error),
);
}
}
export async function runDeviceAuthFlow(
options: DeviceAuthFlowOptions = {},
): Promise<TokenResult> {
const deviceCodeResult = await requestDeviceAuthorization(options);
if (deviceCodeResult.type !== "success") {
return deviceCodeResult;
}
if (options.signal?.aborted) {
return abortedResult();
}
printDeviceAuthorizationPrompt(
deviceCodeResult.deviceCode,
options.log ?? console.log,
options.timeoutMs ?? DEVICE_AUTH_TIMEOUT_MS,
getNow(options)(),
);
const completionResult = await pollDeviceAuthorization(
deviceCodeResult.deviceCode,
options,
);
if (completionResult.type !== "success") {
return completionResult;
}
return exchangeAuthorizationCode(
completionResult.completion.authorizationCode,
completionResult.completion.codeVerifier,
DEVICE_AUTH_REDIRECT_URI,
);
}