// OpenAI protocol portions are adapted in TypeScript; see third-party-notices.md. import type { IOpenAiChatGptAuthCredentials, IOpenAiChatGptAuthOptions, IOpenAiChatGptBrowserAuthorization, IOpenAiChatGptBrowserAuthorizationOptions, IOpenAiChatGptBrowserCallbackOptions, IOpenAiChatGptBrowserExchangeOptions, IOpenAiChatGptCompleteDeviceCodeOptions, IOpenAiChatGptDeviceCode, IOpenAiChatGptDeviceCodePollOptions, IOpenAiChatGptRevokeOptions, IOpenAiChatGptTokenData, IOpenAiChatGptTokenInfo, TOpenAiChatGptBrowserCallback, } from './interfaces.js'; import * as plugins from './plugins.js'; export { OPENAI_CHATGPT_CODEX_BASE_URL, OPENAI_CHATGPT_DEFAULT_ORIGINATOR, OpenAiChatGptAuthError, } from './plugins.js'; export const OPENAI_CHATGPT_AUTH_ISSUER = 'https://auth.openai.com'; export const OPENAI_CHATGPT_CLIENT_ID = 'app_EMoamEEZ73f0CkXaXp7hrann'; const DEVICE_CODE_TIMEOUT_MS = 15 * 60 * 1000; const SAFE_MAX_RESPONSE_BYTES = 64 * 1024; const SAFE_MAX_TOKEN_BYTES = 16 * 1024; const SAFE_MAX_AUTHORIZATION_CODE_BYTES = 8 * 1024; const SAFE_MAX_IDENTIFIER_BYTES = 1024; const SAFE_MAX_URL_BYTES = 4096; const AUTH_REQUEST_TIMEOUT_MS = 30_000; const browserRedirectUris = new Set([ 'http://localhost:1455/auth/callback', 'http://localhost:1457/auth/callback', ]); const browserScope = 'openid profile email offline_access api.connectors.read api.connectors.invoke'; const base64UrlPattern = /^[A-Za-z0-9_-]+$/; const textEncoder = new TextEncoder(); const textDecoder = new TextDecoder(); const usesSafeErrors = (optionsArg: IOpenAiChatGptAuthOptions): boolean => optionsArg.safeErrors !== false; const utf8ByteLength = (valueArg: string): number => textEncoder.encode(valueArg).byteLength; export interface IOpenAiChatGptAuthorizationCode { authorizationCode: string; codeChallenge: string; codeVerifier: string; } interface IOpenAiChatGptTokenResponse { id_token?: unknown; access_token?: unknown; refresh_token?: unknown; } function getFetch(options: IOpenAiChatGptAuthOptions): typeof fetch { const fetchFunction = options.fetch ?? globalThis.fetch; if (!fetchFunction) { throw new plugins.OpenAiChatGptAuthError('fetch is not available for OpenAI ChatGPT authentication.'); } return fetchFunction; } function authError( message: string, options: IOpenAiChatGptAuthOptions, details: { status?: number; body?: string } = {}, ): plugins.OpenAiChatGptAuthError { return new plugins.OpenAiChatGptAuthError( message, usesSafeErrors(options) ? { ...(details.status === undefined ? {} : { status: details.status }) } : details, ); } function throwIfAborted(options: IOpenAiChatGptAuthOptions): void { if (options.signal?.aborted) { throw authError('OpenAI ChatGPT authentication was aborted.', options); } } function getIssuer(): string { return OPENAI_CHATGPT_AUTH_ISSUER; } function getClientId(): string { return OPENAI_CHATGPT_CLIENT_ID; } function asString( value: unknown, name: string, options: IOpenAiChatGptAuthOptions = {}, maximumBytes = SAFE_MAX_IDENTIFIER_BYTES, ): string { if (typeof value !== 'string' || value.length === 0) { throw authError(`OpenAI ChatGPT auth response is missing ${name}.`, options); } if (usesSafeErrors(options) && utf8ByteLength(value) > maximumBytes) { throw authError(`OpenAI ChatGPT auth response contains an invalid ${name}.`, options); } return value; } function asOptionalString( value: unknown, options: IOpenAiChatGptAuthOptions = {}, maximumBytes = SAFE_MAX_IDENTIFIER_BYTES, ): string | undefined { if (typeof value !== 'string' || value.length === 0) return undefined; if (usesSafeErrors(options) && utf8ByteLength(value) > maximumBytes) { throw authError('OpenAI ChatGPT auth response contains an oversized string.', options); } return value; } function asIntervalSeconds(value: unknown, options: IOpenAiChatGptAuthOptions = {}): number { const interval = typeof value === 'number' ? value : Number.parseInt(String(value ?? ''), 10); if (!Number.isFinite(interval) || interval <= 0 || (usesSafeErrors(options) && interval > 300)) { throw authError('OpenAI ChatGPT device-code response has an invalid interval.', options); } return interval; } async function readResponseText( response: Response, options: IOpenAiChatGptAuthOptions, ): Promise { if (!usesSafeErrors(options)) return response.text(); const contentLength = response.headers.get('content-length'); if ( contentLength !== null && (!/^\d+$/.test(contentLength) || Number(contentLength) > SAFE_MAX_RESPONSE_BYTES) ) { await response.body?.cancel().catch(() => undefined); throw authError('OpenAI ChatGPT auth response exceeded its size limit.', options, { status: response.status, }); } if (!response.body) return ''; const reader = response.body.getReader(); const chunks: Uint8Array[] = []; let byteLength = 0; let completed = false; const onAbort = (): void => { void reader.cancel().catch(() => undefined); }; options.signal?.addEventListener('abort', onAbort, { once: true }); if (options.signal?.aborted) onAbort(); try { while (true) { throwIfAborted(options); const { done, value } = await reader.read(); throwIfAborted(options); if (done) break; byteLength += value.byteLength; if (byteLength > SAFE_MAX_RESPONSE_BYTES) { await reader.cancel().catch(() => undefined); throw authError('OpenAI ChatGPT auth response exceeded its size limit.', options, { status: response.status, }); } chunks.push(value); } completed = true; } finally { options.signal?.removeEventListener('abort', onAbort); if (!completed) void reader.cancel().catch(() => undefined); reader.releaseLock(); } const bytes = new Uint8Array(byteLength); let offset = 0; for (const chunk of chunks) { bytes.set(chunk, offset); offset += chunk.byteLength; } return new TextDecoder().decode(bytes); } async function readJson( response: Response, context: string, options: IOpenAiChatGptAuthOptions, ): Promise { const body = await readResponseText(response, options); if (!response.ok) { throw authError(`${context} failed with status ${response.status}.`, options, { status: response.status, body, }); } try { return body ? JSON.parse(body) : {}; } catch (error) { throw authError( usesSafeErrors(options) ? `${context} returned invalid JSON.` : `${context} returned invalid JSON: ${(error as Error).message}`, options, { status: response.status, body }, ); } } const parseRetryAfterMs = (headerArg: string | null): number | undefined => { if (!headerArg || headerArg.length > 128) return undefined; const maximumDelayMs = 24 * 60 * 60 * 1000; if (/^\d{1,10}$/.test(headerArg)) { return Math.min(Number(headerArg) * 1000, maximumDelayMs); } const retryAt = Date.parse(headerArg); if (!Number.isFinite(retryAt)) return undefined; return Math.min(Math.max(0, retryAt - Date.now()), maximumDelayMs); }; async function runFetch( url: string, init: RequestInit, options: IOpenAiChatGptAuthOptions, responseHandlerArg: ( response: Response, requestOptions: IOpenAiChatGptAuthOptions, ) => Promise, timeoutMsArg = AUTH_REQUEST_TIMEOUT_MS, ): Promise { if (options.signal?.aborted) { throw new plugins.OpenAiChatGptAuthError('OpenAI ChatGPT authentication was aborted.', { requestOutcome: 'notSent', }); } const controller = new AbortController(); let response: Response | undefined; let requestStarted = false; const onExternalAbort = (): void => controller.abort(); const onRequestAbort = (): void => { void response?.body?.cancel().catch(() => undefined); }; options.signal?.addEventListener('abort', onExternalAbort, { once: true }); let rejectOnAbort!: () => void; const aborted = new Promise((_resolve, reject) => { rejectOnAbort = () => reject(new Error('OpenAI ChatGPT authentication request aborted.')); controller.signal.addEventListener('abort', rejectOnAbort, { once: true }); }); controller.signal.addEventListener('abort', onRequestAbort, { once: true }); if (options.signal?.aborted) controller.abort(); const timer = setTimeout(() => controller.abort(), Math.min(timeoutMsArg, AUTH_REQUEST_TIMEOUT_MS)); const requestOptions = { ...options, signal: controller.signal }; try { return await Promise.race([ (async () => { const fetchImplementation = getFetch(options); requestStarted = true; response = await fetchImplementation(url, { ...init, redirect: 'error', signal: controller.signal, }); if (controller.signal.aborted) { await response.body?.cancel().catch(() => undefined); } throwIfAborted(requestOptions); return responseHandlerArg(response, requestOptions); })(), aborted, ]); } catch (error) { const requestOutcome: plugins.TOpenAiChatGptRequestOutcome = requestStarted ? 'outcomeUnknown' : 'notSent'; const retryAfterMs = response ? parseRetryAfterMs(response.headers.get('retry-after')) : undefined; if (error instanceof plugins.OpenAiChatGptAuthError) { throw new plugins.OpenAiChatGptAuthError(error.message, { ...(error.status !== undefined ? { status: error.status } : response ? { status: response.status } : {}), ...(error.body !== undefined ? { body: error.body } : {}), requestOutcome, ...(retryAfterMs !== undefined ? { retryAfterMs } : {}), }); } if (!usesSafeErrors(options)) throw error; throw new plugins.OpenAiChatGptAuthError( options.signal?.aborted ? 'OpenAI ChatGPT authentication was aborted.' : 'OpenAI ChatGPT authentication request failed.', { requestOutcome, ...(response ? { status: response.status } : {}), ...(retryAfterMs !== undefined ? { retryAfterMs } : {}), }, ); } finally { clearTimeout(timer); options.signal?.removeEventListener('abort', onExternalAbort); controller.signal.removeEventListener('abort', rejectOnAbort); controller.signal.removeEventListener('abort', onRequestAbort); } } async function postJson( url: string, body: unknown, options: IOpenAiChatGptAuthOptions, ): Promise { return runFetch(url, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body), }, options, (response, requestOptions) => readJson(response, `POST ${url}`, requestOptions)); } async function postForm( url: string, body: URLSearchParams, options: IOpenAiChatGptAuthOptions, ): Promise { return runFetch(url, { method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, body: body.toString(), }, options, (response, requestOptions) => readJson(response, `POST ${url}`, requestOptions)); } function sleep(ms: number): Promise { return new Promise((resolve) => setTimeout(resolve, ms)); } async function sleepWithAbort( milliseconds: number, options: IOpenAiChatGptDeviceCodePollOptions, ): Promise { throwIfAborted(options); if (!options.signal || options.sleep) { if (!options.signal) { await (options.sleep ?? sleep)(milliseconds); return; } let abortListener: (() => void) | undefined; try { await Promise.race([ options.sleep!(milliseconds), new Promise((_resolve, reject) => { abortListener = () => reject(authError('OpenAI ChatGPT authentication was aborted.', options)); options.signal!.addEventListener('abort', abortListener, { once: true }); }), ]); } finally { if (abortListener) options.signal.removeEventListener('abort', abortListener); } return; } await new Promise((resolve, reject) => { const onAbort = (): void => { clearTimeout(timer); options.signal!.removeEventListener('abort', onAbort); reject(authError('OpenAI ChatGPT authentication was aborted.', options)); }; const timer = setTimeout(() => { options.signal!.removeEventListener('abort', onAbort); resolve(); }, milliseconds); options.signal!.addEventListener('abort', onAbort, { once: true }); if (options.signal!.aborted) onAbort(); }); } function parseJwtPayload(jwt: string): Record { const parts = jwt.split('.'); if (parts.length !== 3 || !parts[1]) { throw new plugins.OpenAiChatGptAuthError('OpenAI ChatGPT auth returned an invalid token.'); } try { const base64 = parts[1].replace(/-/g, '+').replace(/_/g, '/'); const binary = atob(base64.padEnd(Math.ceil(base64.length / 4) * 4, '=')); const bytes = Uint8Array.from(binary, (character) => character.charCodeAt(0)); return JSON.parse(textDecoder.decode(bytes)) as Record; } catch (error) { throw new plugins.OpenAiChatGptAuthError(`OpenAI ChatGPT token could not be parsed: ${(error as Error).message}`); } } export function parseOpenAiChatGptTokenInfo(token: string): IOpenAiChatGptTokenInfo { const claims = parseJwtPayload(token); const profile = claims['https://api.openai.com/profile'] as Record | undefined; const auth = claims['https://api.openai.com/auth'] as Record | undefined; const expiresAtSeconds = typeof claims.exp === 'number' ? claims.exp : undefined; return { email: asOptionalString(claims.email) ?? asOptionalString(profile?.email), chatgptPlanType: asOptionalString(auth?.chatgpt_plan_type), chatgptUserId: asOptionalString(auth?.chatgpt_user_id) ?? asOptionalString(auth?.user_id), chatgptAccountId: asOptionalString(auth?.chatgpt_account_id), chatgptAccountIsFedramp: auth?.chatgpt_account_is_fedramp === true, expiresAt: expiresAtSeconds !== undefined ? new Date(expiresAtSeconds * 1000).toISOString() : undefined, rawJwt: token, }; } function createTokenData( response: IOpenAiChatGptTokenResponse, existingTokenData?: IOpenAiChatGptTokenData, options: IOpenAiChatGptAuthOptions = {}, ): IOpenAiChatGptTokenData { const accessToken = asOptionalString(response.access_token, options, SAFE_MAX_TOKEN_BYTES) ?? existingTokenData?.accessToken; const refreshToken = asOptionalString(response.refresh_token, options, SAFE_MAX_TOKEN_BYTES) ?? existingTokenData?.refreshToken; const idToken = asOptionalString(response.id_token, options, SAFE_MAX_TOKEN_BYTES) ?? existingTokenData?.idToken; if (usesSafeErrors(options)) { for (const token of [accessToken, refreshToken, idToken]) { if (token !== undefined && utf8ByteLength(token) > SAFE_MAX_TOKEN_BYTES) { throw authError('OpenAI ChatGPT auth returned an oversized token.', options); } } } if (!accessToken) { throw authError('OpenAI ChatGPT auth response is missing access_token.', options); } if (!refreshToken) { throw authError('OpenAI ChatGPT auth response is missing refresh_token.', options); } let tokenInfo: IOpenAiChatGptTokenInfo; try { tokenInfo = parseOpenAiChatGptTokenInfo(idToken ?? accessToken); } catch (error) { if (!usesSafeErrors(options)) throw error; throw authError('OpenAI ChatGPT auth returned an invalid token.', options); } return { accessToken, refreshToken, idToken, accountId: tokenInfo.chatgptAccountId, tokenInfo, }; } export async function requestOpenAiChatGptDeviceCode( options: IOpenAiChatGptAuthOptions = {}, ): Promise { const issuer = getIssuer(); const response = await postJson(`${issuer}/api/accounts/deviceauth/usercode`, { client_id: getClientId(), }, options) as Record; return { verificationUrl: `${issuer}/codex/device`, userCode: asString(response.user_code ?? response.usercode, 'user_code', options), deviceAuthId: asString(response.device_auth_id, 'device_auth_id', options), intervalSeconds: asIntervalSeconds(response.interval, options), }; } export async function pollOpenAiChatGptDeviceCode( deviceCode: IOpenAiChatGptDeviceCode, options: IOpenAiChatGptDeviceCodePollOptions = {}, ): Promise { const issuer = getIssuer(); const pollUrl = `${issuer}/api/accounts/deviceauth/token`; const timeoutMs = options.timeoutMs ?? DEVICE_CODE_TIMEOUT_MS; if (!Number.isSafeInteger(timeoutMs) || timeoutMs < 1 || timeoutMs > DEVICE_CODE_TIMEOUT_MS) { throw authError('OpenAI ChatGPT device-code timeout is invalid.', options); } if ( usesSafeErrors(options) && ( utf8ByteLength(deviceCode.deviceAuthId) > SAFE_MAX_IDENTIFIER_BYTES || utf8ByteLength(deviceCode.userCode) > SAFE_MAX_IDENTIFIER_BYTES || !Number.isSafeInteger(deviceCode.intervalSeconds) || deviceCode.intervalSeconds < 1 || deviceCode.intervalSeconds > 300 ) ) { throw authError('OpenAI ChatGPT device-code input is invalid.', options); } const startedAt = Date.now(); while (Date.now() - startedAt < timeoutMs) { const remainingBeforeRequest = timeoutMs - (Date.now() - startedAt); const pollResult = await runFetch(pollUrl, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ device_auth_id: deviceCode.deviceAuthId, user_code: deviceCode.userCode, }), }, options, async (response, requestOptions) => { if (response.ok) { return { status: 'complete' as const, body: await readJson(response, `POST ${pollUrl}`, requestOptions) as Record, }; } if (response.status !== 403 && response.status !== 404) { const body = await readResponseText(response, requestOptions); throw authError(`OpenAI ChatGPT device-code polling failed with status ${response.status}.`, requestOptions, { status: response.status, body, }); } await readResponseText(response, requestOptions); return { status: 'pending' as const }; }, Math.max(remainingBeforeRequest, 1)); if (pollResult.status === 'complete') { return { authorizationCode: asString( pollResult.body.authorization_code, 'authorization_code', options, SAFE_MAX_AUTHORIZATION_CODE_BYTES, ), codeChallenge: asString(pollResult.body.code_challenge, 'code_challenge', options), codeVerifier: asString(pollResult.body.code_verifier, 'code_verifier', options), }; } const remaining = timeoutMs - (Date.now() - startedAt); await sleepWithAbort( Math.min(deviceCode.intervalSeconds * 1000, Math.max(remaining, 0)), options, ); } throw authError('OpenAI ChatGPT device-code login timed out.', options); } export async function exchangeOpenAiChatGptAuthorizationCode( authorizationCode: IOpenAiChatGptAuthorizationCode, options: IOpenAiChatGptAuthOptions = {}, ): Promise { const issuer = getIssuer(); const response = await postForm(`${issuer}/oauth/token`, new URLSearchParams({ grant_type: 'authorization_code', code: authorizationCode.authorizationCode, redirect_uri: `${issuer}/deviceauth/callback`, client_id: getClientId(), code_verifier: authorizationCode.codeVerifier, }), options) as IOpenAiChatGptTokenResponse; return createTokenData(response, undefined, options); } export function ensureOpenAiChatGptWorkspaceAllowed( tokenData: IOpenAiChatGptTokenData, forcedChatGptWorkspaceId?: string, ): void { if (!forcedChatGptWorkspaceId) { return; } if (tokenData.tokenInfo.chatgptAccountId !== forcedChatGptWorkspaceId) { throw new plugins.OpenAiChatGptAuthError(`OpenAI ChatGPT login is restricted to workspace ${forcedChatGptWorkspaceId}.`); } } export async function completeOpenAiChatGptDeviceCodeLogin( deviceCode: IOpenAiChatGptDeviceCode, options: IOpenAiChatGptCompleteDeviceCodeOptions = {}, ): Promise { const authorizationCode = await pollOpenAiChatGptDeviceCode(deviceCode, options); const tokenData = await exchangeOpenAiChatGptAuthorizationCode(authorizationCode, options); ensureOpenAiChatGptWorkspaceAllowed(tokenData, options.forcedChatGptWorkspaceId); return tokenData; } export async function refreshOpenAiChatGptTokenData( tokenData: IOpenAiChatGptTokenData, options: IOpenAiChatGptAuthOptions = {}, ): Promise { const issuer = getIssuer(); const response = await postJson(`${issuer}/oauth/token`, { client_id: getClientId(), grant_type: 'refresh_token', refresh_token: tokenData.refreshToken, }, options) as IOpenAiChatGptTokenResponse; return createTokenData({ id_token: response.id_token ?? tokenData.idToken, access_token: response.access_token ?? tokenData.accessToken, refresh_token: response.refresh_token ?? tokenData.refreshToken, }, tokenData, options); } const requireBrowserRedirectUri = ( redirectUri: string, options: IOpenAiChatGptAuthOptions, ): string => { if (!browserRedirectUris.has(redirectUri)) { throw authError('OpenAI ChatGPT browser redirect URI is not registered.', options); } return redirectUri; }; const requireBase64UrlValue = ( value: string, label: string, minimumBytes: number, maximumBytes: number, ): string => { if ( typeof value !== 'string' || !base64UrlPattern.test(value) || value.length < minimumBytes || value.length > maximumBytes ) { throw new plugins.OpenAiChatGptAuthError(`OpenAI ChatGPT ${label} is invalid.`); } return value; }; const encodeBase64Url = (bytesArg: Uint8Array): string => { let binary = ''; for (const byte of bytesArg) binary += String.fromCharCode(byte); return btoa(binary).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, ''); }; export async function createOpenAiChatGptBrowserAuthorization( options: IOpenAiChatGptBrowserAuthorizationOptions, ): Promise { const issuer = getIssuer(); const redirectUri = requireBrowserRedirectUri(options.redirectUri, options); const webCrypto = globalThis.crypto; if (!webCrypto?.subtle) { throw authError('Web Crypto is required for OpenAI ChatGPT browser authentication.', options); } const codeVerifier = encodeBase64Url(webCrypto.getRandomValues(new Uint8Array(64))); const state = encodeBase64Url(webCrypto.getRandomValues(new Uint8Array(32))); const codeChallenge = encodeBase64Url(new Uint8Array( await webCrypto.subtle.digest('SHA-256', textEncoder.encode(codeVerifier)), )); const originator = options.originator ?? plugins.OPENAI_CHATGPT_DEFAULT_ORIGINATOR; if ( utf8ByteLength(originator) > 128 || !/^[A-Za-z0-9._-]+$/.test(originator) ) { throw authError('OpenAI ChatGPT browser originator is invalid.', options); } const allowedWorkspaceIds = options.allowedWorkspaceIds ?? []; if ( !Array.isArray(allowedWorkspaceIds) || allowedWorkspaceIds.length > 16 || allowedWorkspaceIds.some((id) => ( typeof id !== 'string' || id.length === 0 || utf8ByteLength(id) > 256 || /[,\s]/.test(id) )) ) { throw authError('OpenAI ChatGPT allowed workspace IDs are invalid.', options); } const authUrl = new URL(`${issuer}/oauth/authorize`); authUrl.searchParams.set('response_type', 'code'); authUrl.searchParams.set('client_id', getClientId()); authUrl.searchParams.set('redirect_uri', redirectUri); authUrl.searchParams.set('scope', browserScope); authUrl.searchParams.set('code_challenge', codeChallenge); authUrl.searchParams.set('code_challenge_method', 'S256'); authUrl.searchParams.set('id_token_add_organizations', 'true'); authUrl.searchParams.set('codex_cli_simplified_flow', 'true'); authUrl.searchParams.set('state', state); authUrl.searchParams.set('originator', originator); if (allowedWorkspaceIds.length > 0) { authUrl.searchParams.set('allowed_workspace_id', allowedWorkspaceIds.join(',')); } if (utf8ByteLength(authUrl.href) > SAFE_MAX_URL_BYTES) { throw authError('OpenAI ChatGPT browser authorization URL is too large.', options); } return { authUrl: authUrl.href, state, codeVerifier, redirectUri }; } export function parseOpenAiChatGptBrowserCallback( callbackUrl: string, options: IOpenAiChatGptBrowserCallbackOptions, ): TOpenAiChatGptBrowserCallback { if ( typeof callbackUrl !== 'string' || utf8ByteLength(callbackUrl) > SAFE_MAX_URL_BYTES ) { throw new plugins.OpenAiChatGptAuthError('OpenAI ChatGPT browser callback is invalid.'); } const expectedRedirectUri = requireBrowserRedirectUri(options.expectedRedirectUri, {}); const expectedState = requireBase64UrlValue(options.expectedState, 'browser state', 32, 128); let parsed: URL; try { parsed = new URL(callbackUrl); } catch { throw new plugins.OpenAiChatGptAuthError('OpenAI ChatGPT browser callback is invalid.'); } const expectedUrl = new URL(expectedRedirectUri); if (parsed.origin !== expectedUrl.origin || parsed.pathname !== expectedUrl.pathname) { throw new plugins.OpenAiChatGptAuthError('OpenAI ChatGPT browser callback target is invalid.'); } const allowedKeys = new Set(['code', 'state', 'error', 'error_description']); const keys = [...parsed.searchParams.keys()]; if ( parsed.hash.length > 0 || keys.some((key) => !allowedKeys.has(key)) || new Set(keys).size !== keys.length ) { throw new plugins.OpenAiChatGptAuthError('OpenAI ChatGPT browser callback parameters are invalid.'); } const state = parsed.searchParams.get('state'); if (state !== expectedState) { throw new plugins.OpenAiChatGptAuthError('OpenAI ChatGPT browser callback state does not match.'); } const providerError = parsed.searchParams.get('error'); if (providerError !== null) { if (!/^[A-Za-z0-9._-]{1,128}$/.test(providerError)) { throw new plugins.OpenAiChatGptAuthError('OpenAI ChatGPT browser login was denied.'); } return { providerError }; } const authorizationCode = parsed.searchParams.get('code'); if ( !authorizationCode || utf8ByteLength(authorizationCode) > SAFE_MAX_AUTHORIZATION_CODE_BYTES ) { throw new plugins.OpenAiChatGptAuthError('OpenAI ChatGPT browser callback has no valid code.'); } return { authorizationCode }; } export async function exchangeOpenAiChatGptBrowserAuthorizationCode( authorizationCode: string, options: IOpenAiChatGptBrowserExchangeOptions, ): Promise { const issuer = getIssuer(); const redirectUri = requireBrowserRedirectUri(options.redirectUri, options); if ( typeof authorizationCode !== 'string' || authorizationCode.length === 0 || utf8ByteLength(authorizationCode) > SAFE_MAX_AUTHORIZATION_CODE_BYTES ) { throw authError('OpenAI ChatGPT browser authorization code is invalid.', options); } const codeVerifier = requireBase64UrlValue(options.codeVerifier, 'PKCE verifier', 43, 128); const response = await postForm(`${issuer}/oauth/token`, new URLSearchParams({ grant_type: 'authorization_code', code: authorizationCode, redirect_uri: redirectUri, client_id: getClientId(), code_verifier: codeVerifier, }), options) as IOpenAiChatGptTokenResponse; return createTokenData(response, undefined, options); } export async function revokeOpenAiChatGptToken( token: string, options: IOpenAiChatGptRevokeOptions, ): Promise { if ( typeof token !== 'string' || token.length === 0 || (usesSafeErrors(options) && utf8ByteLength(token) > SAFE_MAX_TOKEN_BYTES) ) { throw authError('OpenAI ChatGPT revoke token is invalid.', options); } const issuer = getIssuer(); await runFetch(`${issuer}/oauth/revoke`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ token, token_type_hint: options.tokenTypeHint, client_id: getClientId(), }), }, options, async (response, requestOptions) => { const body = await readResponseText(response, requestOptions); if (!response.ok) { throw authError(`POST ${issuer}/oauth/revoke failed with status ${response.status}.`, requestOptions, { status: response.status, body, }); } }); } export function createOpenAiChatGptProviderSettings(credentials: IOpenAiChatGptAuthCredentials): { apiKey: string; baseURL: string; headers: Record; } { const currentTokenInfo = parseOpenAiChatGptTokenInfo(credentials.accessToken); if ( currentTokenInfo.expiresAt === undefined || Date.parse(currentTokenInfo.expiresAt) <= Date.now() ) { throw new plugins.OpenAiChatGptAuthError('OpenAI ChatGPT access token has no valid future expiry.'); } const tokenAccountId = currentTokenInfo.chatgptAccountId; if ( credentials.accountId !== undefined && credentials.accountId !== tokenAccountId ) { throw new plugins.OpenAiChatGptAuthError('OpenAI ChatGPT account ID does not match the token claim.'); } if ( credentials.tokenInfo !== undefined && ( credentials.tokenInfo.chatgptAccountId !== tokenAccountId || credentials.tokenInfo.chatgptAccountIsFedramp !== currentTokenInfo.chatgptAccountIsFedramp ) ) { throw new plugins.OpenAiChatGptAuthError('OpenAI ChatGPT token information does not match the current access token.'); } if ( credentials.isFedrampAccount !== undefined && ( typeof credentials.isFedrampAccount !== 'boolean' || credentials.isFedrampAccount !== currentTokenInfo.chatgptAccountIsFedramp ) ) { throw new plugins.OpenAiChatGptAuthError('OpenAI ChatGPT FedRAMP status does not match the token claim.'); } const accountId = tokenAccountId; const isFedrampAccount = currentTokenInfo.chatgptAccountIsFedramp; const headers: Record = { originator: credentials.originator ?? plugins.OPENAI_CHATGPT_DEFAULT_ORIGINATOR, }; if (accountId) { headers['ChatGPT-Account-ID'] = accountId; } if (isFedrampAccount) { headers['X-OpenAI-Fedramp'] = 'true'; } return { apiKey: credentials.accessToken, baseURL: plugins.OPENAI_CHATGPT_CODEX_BASE_URL, headers, }; }