import * as plugins from './plugins.js'; export type TOpenAiChatGptAuthSource = 'smartai' | 'opencode' | 'codex'; export type TOpenAiChatGptAuthFileFormat = TOpenAiChatGptAuthSource | 'auto'; export interface IOpenAiChatGptAuthSourceConfig { source: TOpenAiChatGptAuthSource; filePath?: string; format?: TOpenAiChatGptAuthFileFormat; writeBack?: boolean; } export interface IOpenAiChatGptAuthSourceInspection { source: TOpenAiChatGptAuthSource; filePath: string; exists: boolean; usable: boolean; expired?: boolean; accountId?: string; email?: string; plan?: string; expiresAt?: string; error?: string; } export interface IInspectOpenAiChatGptAuthSourcesOptions { sources?: Array; homeDir?: string; now?: Date; } export interface IResolveOpenAiChatGptAuthOptions extends IInspectOpenAiChatGptAuthSourcesOptions { refresh?: 'ifNeeded' | false; writeBack?: Partial>; authOptions?: plugins.IOpenAiChatGptAuthOptions; } export interface IResolvedOpenAiChatGptAuth { source: TOpenAiChatGptAuthSource; filePath: string; tokenData: plugins.IOpenAiChatGptTokenData; refreshed: boolean; } interface INormalizedOpenAiChatGptAuthSourceConfig { source: TOpenAiChatGptAuthSource; filePath: string; format: TOpenAiChatGptAuthFileFormat; writeBack?: boolean; } const defaultSources: TOpenAiChatGptAuthSource[] = ['smartai', 'opencode', 'codex']; const refreshWindowMs = 5 * 60 * 1000; const lockWaitTimeoutMs = 30_000; const lockStaleMs = 60_000; const maximumAuthFileBytes = 1024 * 1024; const inProcessFileLocks = new Map>(); const canonicalizeFilePath = async (filePathArg: string): Promise => { const resolvedPath = plugins.path.resolve(filePathArg); await plugins.fs.mkdir(plugins.path.dirname(resolvedPath), { recursive: true, mode: 0o700 }); try { return await plugins.fs.realpath(resolvedPath); } catch (errorArg) { if ((errorArg as NodeJS.ErrnoException).code !== 'ENOENT') throw errorArg; const parentPath = await plugins.fs.realpath(plugins.path.dirname(resolvedPath)); return plugins.path.join(parentPath, plugins.path.basename(resolvedPath)); } }; const acquireCrossProcessFileLock = async ( filePathArg: string, ): Promise<() => Promise> => plugins.properLockfile.lock(filePathArg, { lockfilePath: `${filePathArg}.smartai.lock`, realpath: false, stale: lockStaleMs, update: 10_000, retries: { retries: Math.ceil(lockWaitTimeoutMs / 50), factor: 1, minTimeout: 50, maxTimeout: 50, randomize: false, }, }); const withAuthFileLock = async ( filePathArg: string, taskArg: (canonicalFilePathArg: string) => Promise, ): Promise => { const canonicalFilePath = await canonicalizeFilePath(filePathArg); const previous = inProcessFileLocks.get(canonicalFilePath) ?? Promise.resolve(); let releaseInProcess!: () => void; const current = new Promise((resolve) => { releaseInProcess = resolve; }); const tail = previous.then(() => current); inProcessFileLocks.set(canonicalFilePath, tail); await previous; try { const releaseCrossProcess = await acquireCrossProcessFileLock(canonicalFilePath); try { return await taskArg(canonicalFilePath); } finally { await releaseCrossProcess(); } } finally { releaseInProcess(); if (inProcessFileLocks.get(canonicalFilePath) === tail) { inProcessFileLocks.delete(canonicalFilePath); } } }; export const getDefaultOpenAiChatGptAuthPath = ( source: TOpenAiChatGptAuthSource, homeDir = plugins.os.homedir(), ): string => { switch (source) { case 'smartai': return plugins.path.join(homeDir, '.git.zone', 'ide', 'openai-chatgpt-auth.json'); case 'opencode': return plugins.path.join(homeDir, '.local', 'share', 'opencode', 'auth.json'); case 'codex': return plugins.path.join(homeDir, '.codex', 'auth.json'); default: throw new Error(`Unsupported OpenAI ChatGPT auth source: ${source satisfies never}`); } }; export const normalizeOpenAiChatGptAuth = ( input: unknown, format: TOpenAiChatGptAuthFileFormat = 'auto', ): plugins.IOpenAiChatGptTokenData | undefined => { if (format === 'auto') { return normalizeOpenAiChatGptAuth(input, 'smartai') ?? normalizeOpenAiChatGptAuth(input, 'opencode') ?? normalizeOpenAiChatGptAuth(input, 'codex'); } if (!isRecord(input)) return undefined; if (format === 'opencode') { return normalizeOpenCodeAuth(input); } return normalizeTokenObject(isRecord(input.tokens) ? input.tokens : input); }; const readBoundedAuthFileText = async (filePathArg: string): Promise => { const canonicalFilePath = await plugins.fs.realpath(filePathArg); let handle: plugins.FileHandle | undefined; try { handle = await plugins.fs.open( canonicalFilePath, plugins.fsConstants.O_RDONLY | plugins.fsConstants.O_NONBLOCK, ); const stat = await handle.stat(); if (!stat.isFile() || stat.size > maximumAuthFileBytes) { throw new Error('Authentication file is not a bounded regular file.'); } const bytes = new Uint8Array(maximumAuthFileBytes + 1); let offset = 0; while (offset < bytes.byteLength) { const result = await handle.read(bytes, offset, bytes.byteLength - offset, offset); if (result.bytesRead === 0) break; offset += result.bytesRead; } if (offset > maximumAuthFileBytes) { throw new Error('Authentication file exceeds its size limit.'); } return new TextDecoder().decode(bytes.subarray(0, offset)); } finally { await handle?.close(); } }; const readBoundedAuthJson = async (filePathArg: string): Promise => JSON.parse(await readBoundedAuthFileText(filePathArg)) as unknown; export const readOpenAiChatGptAuthFile = async ( filePath: string, format: TOpenAiChatGptAuthFileFormat = 'auto', ): Promise => { const parsed = await readBoundedAuthJson(filePath); return normalizeOpenAiChatGptAuth(parsed, format); }; export const inspectOpenAiChatGptAuthSources = async ( options: IInspectOpenAiChatGptAuthSourcesOptions = {}, ): Promise => { const now = options.now ?? new Date(); const sourceConfigs = normalizeSourceConfigs(options.sources, options.homeDir); return Promise.all(sourceConfigs.map(async (sourceConfig) => { try { const tokenData = await readOpenAiChatGptAuthFile(sourceConfig.filePath!, sourceConfig.format ?? sourceConfig.source); if (!tokenData) { return { source: sourceConfig.source, filePath: sourceConfig.filePath!, exists: true, usable: false, error: 'No OpenAI ChatGPT auth token found in file.', }; } return toInspection(sourceConfig.source, sourceConfig.filePath!, tokenData, now); } catch (error) { const nodeError = error as NodeJS.ErrnoException; return { source: sourceConfig.source, filePath: sourceConfig.filePath!, exists: nodeError.code !== 'ENOENT', usable: false, error: nodeError.code === 'ENOENT' ? undefined : 'Authentication file could not be read.', }; } })); }; export const resolveOpenAiChatGptAuth = async ( options: IResolveOpenAiChatGptAuthOptions = {}, ): Promise => { const now = options.now ?? new Date(); const sourceConfigs = normalizeSourceConfigs(options.sources, options.homeDir); const refresh = options.refresh ?? 'ifNeeded'; for (const sourceConfig of sourceConfigs) { let tokenData: plugins.IOpenAiChatGptTokenData | undefined; try { tokenData = await readOpenAiChatGptAuthFile(sourceConfig.filePath!, sourceConfig.format ?? sourceConfig.source); } catch (error) { const nodeError = error as NodeJS.ErrnoException; if (nodeError.code === 'ENOENT') continue; continue; } if (!tokenData) continue; const shouldRefresh = refresh === 'ifNeeded' && shouldRefreshToken(tokenData, now); const writeBack = sourceConfig.writeBack ?? options.writeBack?.[sourceConfig.source] ?? sourceConfig.source === 'smartai'; if (writeBack && sourceConfig.format === 'auto') { throw new Error('The auto auth-file format cannot be used for write-back.'); } if (!shouldRefresh) { return { source: sourceConfig.source, filePath: sourceConfig.filePath!, tokenData, refreshed: false }; } if (!writeBack) { if (!isExpired(tokenData, now)) { return { source: sourceConfig.source, filePath: sourceConfig.filePath!, tokenData, refreshed: false }; } continue; } try { const resolved = await withAuthFileLock(sourceConfig.filePath!, async (canonicalFilePath) => { const latestTokenData = await readOpenAiChatGptAuthFile( canonicalFilePath, sourceConfig.format ?? sourceConfig.source, ); if (!latestTokenData) return undefined; if (!shouldRefreshToken(latestTokenData, now)) { return { source: sourceConfig.source, filePath: sourceConfig.filePath!, tokenData: latestTokenData, refreshed: false, }; } const refreshed = await plugins.refreshOpenAiChatGptTokenData( latestTokenData, options.authOptions ?? {}, ); await writeOpenAiChatGptAuthFileUnlocked( canonicalFilePath, refreshed, sourceConfig.format ?? sourceConfig.source, ); return { source: sourceConfig.source, filePath: sourceConfig.filePath!, tokenData: refreshed, refreshed: true, }; }); if (resolved) return resolved; } catch { continue; } } return undefined; }; export const writeOpenAiChatGptAuthFile = async ( filePath: string, tokenData: plugins.IOpenAiChatGptTokenData, format: TOpenAiChatGptAuthFileFormat = 'smartai', ): Promise => { if (format === 'auto') throw new Error('The auto auth-file format cannot be written.'); return withAuthFileLock(filePath, async (canonicalFilePath) => { await writeOpenAiChatGptAuthFileUnlocked(canonicalFilePath, tokenData, format); }); }; const writeOpenAiChatGptAuthFileUnlocked = async ( filePath: string, tokenData: plugins.IOpenAiChatGptTokenData, format: TOpenAiChatGptAuthFileFormat, ): Promise => { const current = await readJsonFileIfExists(filePath); const payload = format === 'opencode' ? toOpenCodeAuthFile(current, tokenData) : format === 'codex' ? toCodexAuthFile(current, tokenData) : toSmartAiAuthFile(tokenData); await writeJsonAtomic(filePath, payload); }; const normalizeSourceConfigs = ( sources: Array | undefined, homeDir = plugins.os.homedir(), ): INormalizedOpenAiChatGptAuthSourceConfig[] => { return (sources ?? defaultSources).map((sourceInput) => { const sourceConfig = typeof sourceInput === 'string' ? { source: sourceInput } : sourceInput; return { source: sourceConfig.source, filePath: sourceConfig.filePath ?? getDefaultOpenAiChatGptAuthPath(sourceConfig.source, homeDir), format: sourceConfig.format ?? sourceConfig.source, writeBack: sourceConfig.writeBack, }; }); }; const toInspection = ( source: TOpenAiChatGptAuthSource, filePath: string, tokenData: plugins.IOpenAiChatGptTokenData, now: Date, ): IOpenAiChatGptAuthSourceInspection => { const expired = isExpired(tokenData, now); return { source, filePath, exists: true, usable: !expired, expired, accountId: tokenData.accountId ?? tokenData.tokenInfo.chatgptAccountId, email: tokenData.tokenInfo.email, plan: tokenData.tokenInfo.chatgptPlanType, expiresAt: tokenData.tokenInfo.expiresAt, }; }; const normalizeTokenObject = (input: Record): plugins.IOpenAiChatGptTokenData | undefined => { const accessToken = stringValue(input.accessToken) ?? stringValue(input.access_token); const refreshToken = stringValue(input.refreshToken) ?? stringValue(input.refresh_token); const idToken = stringValue(input.idToken) ?? stringValue(input.id_token); const accountId = stringValue(input.accountId) ?? stringValue(input.account_id); return createTokenDataFromValues({ accessToken, refreshToken, idToken, accountId }); }; const normalizeOpenCodeAuth = (input: Record): plugins.IOpenAiChatGptTokenData | undefined => { if (!isRecord(input.openai)) return undefined; const accessToken = stringValue(input.openai.access); const refreshToken = stringValue(input.openai.refresh); const accountId = stringValue(input.openai.accountId); const expiresAt = typeof input.openai.expires === 'number' ? new Date(input.openai.expires).toISOString() : undefined; return createTokenDataFromValues({ accessToken, refreshToken, accountId, fallbackExpiresAt: expiresAt }); }; const createTokenDataFromValues = (input: { accessToken?: string; refreshToken?: string; idToken?: string; accountId?: string; fallbackExpiresAt?: string; }): plugins.IOpenAiChatGptTokenData | undefined => { if (!input.accessToken || !input.refreshToken) return undefined; const parseToken = input.idToken ?? input.accessToken; const tokenInfo = parseTokenInfo(parseToken, input.accountId, input.fallbackExpiresAt); if ( input.accountId !== undefined && tokenInfo.chatgptAccountId !== undefined && input.accountId !== tokenInfo.chatgptAccountId ) { return undefined; } const accountId = tokenInfo.chatgptAccountId ?? input.accountId; return { accessToken: input.accessToken, refreshToken: input.refreshToken, idToken: input.idToken, accountId, tokenInfo: { ...tokenInfo, chatgptAccountId: accountId }, }; }; const parseTokenInfo = (token: string, accountId?: string, fallbackExpiresAt?: string): plugins.IOpenAiChatGptTokenInfo => { try { const tokenInfo = plugins.parseOpenAiChatGptTokenInfo(token); return { ...tokenInfo, chatgptAccountId: tokenInfo.chatgptAccountId ?? accountId, expiresAt: tokenInfo.expiresAt ?? fallbackExpiresAt, }; } catch { return { chatgptAccountId: accountId, chatgptAccountIsFedramp: false, expiresAt: fallbackExpiresAt, rawJwt: token, }; } }; const toSmartAiAuthFile = (tokenData: plugins.IOpenAiChatGptTokenData): Record => ({ accessToken: tokenData.accessToken, refreshToken: tokenData.refreshToken, idToken: tokenData.idToken, accountId: tokenData.accountId, tokenInfo: tokenData.tokenInfo, }); const toCodexAuthFile = (current: Record, tokenData: plugins.IOpenAiChatGptTokenData): Record => ({ ...current, OPENAI_API_KEY: current.OPENAI_API_KEY ?? null, tokens: { ...(isRecord(current.tokens) ? current.tokens : {}), id_token: tokenData.idToken, access_token: tokenData.accessToken, refresh_token: tokenData.refreshToken, account_id: tokenData.accountId ?? tokenData.tokenInfo.chatgptAccountId, }, last_refresh: new Date().toISOString(), }); const toOpenCodeAuthFile = (current: Record, tokenData: plugins.IOpenAiChatGptTokenData): Record => ({ ...current, openai: { ...(isRecord(current.openai) ? current.openai : {}), type: 'oauth', refresh: tokenData.refreshToken, access: tokenData.accessToken, expires: tokenData.tokenInfo.expiresAt ? Date.parse(tokenData.tokenInfo.expiresAt) : undefined, accountId: tokenData.accountId ?? tokenData.tokenInfo.chatgptAccountId, }, }); const shouldRefreshToken = (tokenData: plugins.IOpenAiChatGptTokenData, now: Date): boolean => { if (!tokenData.tokenInfo.expiresAt) return false; return Date.parse(tokenData.tokenInfo.expiresAt) - now.getTime() < refreshWindowMs; }; const isExpired = (tokenData: plugins.IOpenAiChatGptTokenData, now: Date): boolean => { if (!tokenData.tokenInfo.expiresAt) return false; return Date.parse(tokenData.tokenInfo.expiresAt) <= now.getTime(); }; const readJsonFileIfExists = async (filePath: string): Promise> => { try { const parsed = await readBoundedAuthJson(filePath); return isRecord(parsed) ? parsed : {}; } catch (error) { const nodeError = error as NodeJS.ErrnoException; if (nodeError.code === 'ENOENT') return {}; throw error; } }; const writeJsonAtomic = async (filePath: string, payload: unknown): Promise => { const tempPath = `${filePath}.${plugins.crypto.randomUUID()}.tmp`; await plugins.fs.mkdir(plugins.path.dirname(filePath), { recursive: true, mode: 0o700 }); try { await plugins.fs.writeFile(tempPath, `${JSON.stringify(payload, undefined, 2)}\n`, { flag: 'wx', mode: 0o600, }); await plugins.fs.rename(tempPath, filePath); } finally { await plugins.fs.unlink(tempPath).catch((errorArg: NodeJS.ErrnoException) => { if (errorArg.code !== 'ENOENT') throw errorArg; }); } }; const isRecord = (value: unknown): value is Record => { return !!value && typeof value === 'object' && !Array.isArray(value); }; const stringValue = (value: unknown): string | undefined => { return typeof value === 'string' && value.length > 0 ? value : undefined; };