Skip to content

Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure

TypeScript

feat(control-api): broker Codex subscription OAuth lifecycle

Alfredo Lopeza6e348797f8a
diff --git a/control-api/src/config.ts b/control-api/src/config.ts
index 97917cfe5..150322452 100644
--- a/control-api/src/config.ts
+++ b/control-api/src/config.ts
@@ -113,6 +113,9 @@ type Config = {
// Default OFF. Codex subscription management/admission stays dark until
// CONTROL_API_CODEX_SUBSCRIPTION_ENABLED=true.
codexSubscriptionEnabled: boolean
+ // Public Codex CLI OAuth client id. Not a secret; PKCE/device flow protect the
+ // grant. Override only to pin a documented registration.
+ codexOAuthClientId: string
llmCatalogSyncIntervalMs: number
// §4.5 sanity guard, layer 3: absolute plausibility floor. If a LIVE run's
// TOTAL mapped model count is below this, the whole run SKIPS stale-marking
@@ -779,6 +782,10 @@ export const config: Config = {
// Default OFF. Absent or any value other than the exact token `true` keeps
// Codex subscription management and admission dark.
codexSubscriptionEnabled: process.env.CONTROL_API_CODEX_SUBSCRIPTION_ENABLED === 'true',
+ // Public native client used by the Codex CLI ChatGPT login. This is not a
+ // confidential client secret.
+ codexOAuthClientId:
+ process.env.CONTROL_API_CODEX_OAUTH_CLIENT_ID || 'app_EMoamEEZ73f0CkXaXp7hrann',
// Default 24h. Validated (not merely parsed): the value goes straight into
// setInterval and each tick opens a Postgres transaction + advisory lock. A
// 60s floor is orders of magnitude below the default and far above a hot loop.
diff --git a/control-api/src/routes/admin/codexSubscription.ts b/control-api/src/routes/admin/codexSubscription.ts
new file mode 100644
index 000000000..fea7e4a70
--- /dev/null
+++ b/control-api/src/routes/admin/codexSubscription.ts
@@ -0,0 +1,160 @@
+import { Router } from 'express'
+import { config } from '../../config.js'
+import { pool } from '../../db.js'
+import { asyncHandler } from '../../http/asyncHandler.js'
+import { deriveOAuthEncryptionKey } from '../../oauth/encryption.js'
+import { rootLogger } from '../../observability/logger.js'
+import {
+ type CodexOAuthDeps,
+ CodexSubscriptionOAuthError,
+ getCodexSubscriptionConnection,
+ pollCodexDevice,
+ refreshCodexSubscriptionConnection,
+ revokeCodexSubscription,
+ startCodexBrowserConnect,
+ startCodexDeviceConnect,
+} from '../../services/codexSubscriptionOAuth.js'
+import type { CodexSubscriptionOAuthIntent } from '../../services/codexSubscriptionOAuthState.js'
+
+const log = rootLogger.child({ module: 'admin-codex-subscription' })
+const BASE = '/admin/llm/providers/codex-subscription'
+
+function dbClient() {
+ return { query: (text: string, values?: unknown[]) => pool.query(text, values) }
+}
+
+function buildRedirectUri(req: {
+ protocol: string
+ get: (h: string) => string | undefined
+}): string {
+ const origin =
+ config.oauthCallbackBaseUrl && config.oauthCallbackBaseUrl.length > 0
+ ? config.oauthCallbackBaseUrl.replace(/\/+$/, '')
+ : `${req.protocol}://${req.get('host') ?? 'localhost'}`
+ return `${origin}/api/v1/auth/codex-subscription/callback`
+}
+
+function oauthDeps(req: {
+ protocol: string
+ get: (h: string) => string | undefined
+}): CodexOAuthDeps {
+ return {
+ db: dbClient(),
+ encryptionKey: deriveOAuthEncryptionKey(config.oauthEncryptionKey),
+ fetchFn: fetch,
+ clientId: config.codexOAuthClientId,
+ redirectUri: buildRedirectUri(req),
+ enabled: config.codexSubscriptionEnabled,
+ }
+}
+
+function parseIntent(value: unknown): CodexSubscriptionOAuthIntent {
+ return value === 'reconnect' || value === 'replace' ? value : 'connect'
+}
+
+function sendOAuthError(
+ res: { status: (n: number) => { json: (body: unknown) => void } },
+ err: unknown
+) {
+ if (err instanceof CodexSubscriptionOAuthError) {
+ const status =
+ err.code === 'disabled'
+ ? 404
+ : err.code === 'replacement_required'
+ ? 409
+ : err.code === 'refresh_in_flight' || err.code === 'stale_revision'
+ ? 409
+ : err.code === 'not_connected' || err.code === 'no_grant'
+ ? 404
+ : 400
+ log.warn(
+ { event: 'codex_oauth_admin_denied', code: err.code },
+ 'Codex subscription OAuth denied'
+ )
+ res.status(status).json({ error: err.code })
+ return
+ }
+ throw err
+}
+
+export function createAdminCodexSubscriptionRouter(): Router {
+ const router = Router()
+
+ router.get(
+ `${BASE}/connection`,
+ asyncHandler(async (req, res) => {
+ try {
+ const connection = await getCodexSubscriptionConnection(oauthDeps(req))
+ res.status(200).json(connection)
+ } catch (err) {
+ sendOAuthError(res, err)
+ }
+ })
+ )
+
+ router.post(
+ `${BASE}/browser/start`,
+ asyncHandler(async (req, res) => {
+ try {
+ const started = await startCodexBrowserConnect(
+ oauthDeps(req),
+ parseIntent(req.body?.intent)
+ )
+ res.status(200).json(started)
+ } catch (err) {
+ sendOAuthError(res, err)
+ }
+ })
+ )
+
+ router.post(
+ `${BASE}/device/start`,
+ asyncHandler(async (req, res) => {
+ try {
+ const started = await startCodexDeviceConnect(oauthDeps(req), parseIntent(req.body?.intent))
+ res.status(200).json(started)
+ } catch (err) {
+ sendOAuthError(res, err)
+ }
+ })
+ )
+
+ router.get(
+ `${BASE}/device/poll`,
+ asyncHandler(async (req, res) => {
+ try {
+ const state = typeof req.query.state === 'string' ? req.query.state : ''
+ const result = await pollCodexDevice(oauthDeps(req), state)
+ res.status(200).json(result)
+ } catch (err) {
+ sendOAuthError(res, err)
+ }
+ })
+ )
+
+ router.post(
+ `${BASE}/refresh`,
+ asyncHandler(async (req, res) => {
+ try {
+ const connection = await refreshCodexSubscriptionConnection(oauthDeps(req))
+ res.status(200).json(connection)
+ } catch (err) {
+ sendOAuthError(res, err)
+ }
+ })
+ )
+
+ router.post(
+ `${BASE}/revoke`,
+ asyncHandler(async (req, res) => {
+ try {
+ const connection = await revokeCodexSubscription(oauthDeps(req))
+ res.status(200).json(connection)
+ } catch (err) {
+ sendOAuthError(res, err)
+ }
+ })
+ )
+
+ return router
+}
diff --git a/control-api/src/routes/admin/index.ts b/control-api/src/routes/admin/index.ts
index 3e2d0e1d9..88491c831 100644
--- a/control-api/src/routes/admin/index.ts
+++ b/control-api/src/routes/admin/index.ts
@@ -2,6 +2,7 @@ import { Router } from 'express'
import { K8sGateway } from '../../k8s.js'
import { createAdminAgentsRouter } from './agents.js'
import { createAdminBudgetsRouter } from './budgets.js'
+import { createAdminCodexSubscriptionRouter } from './codexSubscription.js'
import { createAdminContextRouter } from './context.js'
import { createAdminControlAdminsRouter } from './controlAdmins.js'
import { createAdminHostArtifactsRouter } from './hostArtifacts.js'
@@ -47,6 +48,7 @@ export function createAdminRouter(gateway: K8sGateway): Router {
router.use(createAdminUsageRouter())
router.use(createAdminLlmPricesRouter())
router.use(createAdminLlmModelsRouter(gateway))
+ router.use(createAdminCodexSubscriptionRouter())
router.use(createAdminBudgetsRouter())
router.use(createAdminTracingRouter())
return router
diff --git a/control-api/src/routes/auth/codexSubscription.ts b/control-api/src/routes/auth/codexSubscription.ts
new file mode 100644
index 000000000..1259c5bfd
--- /dev/null
+++ b/control-api/src/routes/auth/codexSubscription.ts
@@ -0,0 +1,65 @@
+import { Router } from 'express'
+import { config } from '../../config.js'
+import { pool } from '../../db.js'
+import { asyncHandler } from '../../http/asyncHandler.js'
+import { deriveOAuthEncryptionKey } from '../../oauth/encryption.js'
+import { rootLogger } from '../../observability/logger.js'
+import {
+ type CodexOAuthDeps,
+ CodexSubscriptionOAuthError,
+ handleCodexBrowserCallback,
+} from '../../services/codexSubscriptionOAuth.js'
+
+const log = rootLogger.child({ module: 'auth-codex-subscription' })
+
+function dbClient() {
+ return { query: (text: string, values?: unknown[]) => pool.query(text, values) }
+}
+
+function oauthDeps(req: {
+ protocol: string
+ get: (h: string) => string | undefined
+}): CodexOAuthDeps {
+ const origin =
+ config.oauthCallbackBaseUrl && config.oauthCallbackBaseUrl.length > 0
+ ? config.oauthCallbackBaseUrl.replace(/\/+$/, '')
+ : `${req.protocol}://${req.get('host') ?? 'localhost'}`
+ return {
+ db: dbClient(),
+ encryptionKey: deriveOAuthEncryptionKey(config.oauthEncryptionKey),
+ fetchFn: fetch,
+ clientId: config.codexOAuthClientId,
+ redirectUri: `${origin}/api/v1/auth/codex-subscription/callback`,
+ enabled: config.codexSubscriptionEnabled,
+ }
+}
+
+export function createAuthCodexSubscriptionRouter(): Router {
+ const router = Router()
+
+ router.get(
+ '/auth/codex-subscription/callback',
+ asyncHandler(async (req, res) => {
+ const code = typeof req.query.code === 'string' ? req.query.code : ''
+ const state = typeof req.query.state === 'string' ? req.query.state : ''
+ try {
+ const connection = await handleCodexBrowserCallback(oauthDeps(req), { code, state })
+ res.status(200).json({
+ status: connection.status,
+ accountFingerprint: connection.accountFingerprint,
+ credentialRevision: connection.credentialRevision,
+ })
+ } catch (err) {
+ if (err instanceof CodexSubscriptionOAuthError) {
+ const status = err.code === 'disabled' ? 404 : 400
+ log.warn({ event: 'codex_oauth_callback_denied', code: err.code }, 'callback denied')
+ res.status(status).json({ error: err.code })
+ return
+ }
+ throw err
+ }
+ })
+ )
+
+ return router
+}
diff --git a/control-api/src/routes/auth/index.ts b/control-api/src/routes/auth/index.ts
index 2107c3fdf..b11cbf81c 100644
--- a/control-api/src/routes/auth/index.ts
+++ b/control-api/src/routes/auth/index.ts
@@ -1,11 +1,13 @@
import { Router } from 'express'
import { K8sGateway } from '../../k8s.js'
+import { createAuthCodexSubscriptionRouter } from './codexSubscription.js'
import { createAuthMcpHostRoutes } from './mcp-host/index.js'
import { createAuthRecipeOauthRoutes } from './recipe-oauth/index.js'
export function createAuthRoutes(gateway: K8sGateway): Router {
const router = Router()
router.use(createAuthMcpHostRoutes())
+ router.use(createAuthCodexSubscriptionRouter())
router.use(createAuthRecipeOauthRoutes(gateway))
return router
}
diff --git a/control-api/src/services/codexSubscriptionConnection.ts b/control-api/src/services/codexSubscriptionConnection.ts
index c36e14035..c658cb9cd 100644
--- a/control-api/src/services/codexSubscriptionConnection.ts
+++ b/control-api/src/services/codexSubscriptionConnection.ts
@@ -216,7 +216,6 @@ export async function rotateCodexSubscriptionCredentials(
updated_at = now()
WHERE connection_key = $6
AND credential_revision = $7
- AND revoked_at IS NULL
RETURNING ${SAFE_CONNECTION_COLUMNS}`,
[
refreshTokenEncrypted,
@@ -233,6 +232,30 @@ export async function rotateCodexSubscriptionCredentials(
return toSafeConnection(row)
}
+export async function revokeCodexSubscriptionConnection(
+ db: DbClient
+): Promise<CodexSubscriptionSafeConnection | null> {
+ const result = await db.query(
+ `UPDATE codex_subscription_connections
+ SET status = 'revoked',
+ refresh_token_encrypted = NULL,
+ access_token_encrypted = NULL,
+ access_token_expires_at = NULL,
+ account_fingerprint = NULL,
+ credential_revision = credential_revision + 1,
+ refresh_lock_token = NULL,
+ refresh_lock_expires_at = NULL,
+ revoked_at = now(),
+ updated_at = now()
+ WHERE connection_key = $1
+ AND revoked_at IS NULL
+ RETURNING ${SAFE_CONNECTION_COLUMNS}`,
+ [CODEX_SUBSCRIPTION_CONNECTION_KEY]
+ )
+ const row = result.rows[0] as SafeConnectionRow | undefined
+ return row ? toSafeConnection(row) : getSafeCodexSubscriptionConnection(db)
+}
+
export async function acquireCodexSubscriptionRefreshLock(
db: DbClient,
lockToken: string,
diff --git a/control-api/src/services/codexSubscriptionOAuth.ts b/control-api/src/services/codexSubscriptionOAuth.ts
new file mode 100644
index 000000000..a15ea7374
--- /dev/null
+++ b/control-api/src/services/codexSubscriptionOAuth.ts
@@ -0,0 +1,526 @@
+import { createHash, randomBytes } from 'node:crypto'
+import type { DbClient } from '../db.js'
+import { rootLogger } from '../observability/logger.js'
+import {
+ type CodexSubscriptionSafeConnection,
+ CodexSubscriptionStaleRevisionError,
+ acquireCodexSubscriptionRefreshLock,
+ getSafeCodexSubscriptionConnection,
+ insertInitialCodexSubscriptionConnection,
+ loadCodexSubscriptionSecrets,
+ releaseCodexSubscriptionRefreshLock,
+ revokeCodexSubscriptionConnection,
+ rotateCodexSubscriptionCredentials,
+} from './codexSubscriptionConnection.js'
+import {
+ type CodexSubscriptionOAuthIntent,
+ type CodexSubscriptionOAuthSafeState,
+ cancelCodexSubscriptionOAuthState,
+ consumeCodexSubscriptionOAuthState,
+ expireCodexSubscriptionOAuthState,
+ insertCodexSubscriptionOAuthState,
+ peekPendingCodexSubscriptionOAuthState,
+} from './codexSubscriptionOAuthState.js'
+
+const log = rootLogger.child({ module: 'codex-subscription-oauth' })
+
+export const CODEX_OAUTH_AUTHORIZE_URL = 'https://auth.openai.com/oauth/authorize'
+export const CODEX_OAUTH_TOKEN_URL = 'https://auth.openai.com/oauth/token'
+export const CODEX_OAUTH_DEVICE_URL = 'https://auth.openai.com/api/accounts/deviceauth'
+export const CODEX_OAUTH_REVOKE_URL = 'https://auth.openai.com/oauth/revoke'
+export const CODEX_OAUTH_SCOPES = ['openid', 'profile', 'email', 'offline_access'] as const
+
+const TOKEN_TIMEOUT_MS = 15_000
+const REFRESH_LOCK_TTL_MS = 30_000
+const BROWSER_STATE_TTL_MS = 10 * 60_000
+
+export type CodexOAuthErrorCode =
+ | 'disabled'
+ | 'not_connected'
+ | 'state_replayed'
+ | 'state_expired'
+ | 'state_cancelled'
+ | 'replacement_required'
+ | 'stale_revision'
+ | 'refresh_in_flight'
+ | 'provider_unavailable'
+ | 'no_grant'
+ | 'invalid_callback'
+
+export class CodexSubscriptionOAuthError extends Error {
+ readonly code: CodexOAuthErrorCode
+
+ constructor(code: CodexOAuthErrorCode, message: string) {
+ super(message)
+ this.name = 'CodexSubscriptionOAuthError'
+ this.code = code
+ }
+}
+
+export type CodexOAuthDeps = {
+ db: DbClient
+ encryptionKey: Buffer
+ fetchFn: typeof fetch
+ clientId: string
+ redirectUri: string
+ enabled: boolean
+}
+
+export type CodexBrowserStartResult = {
+ authorizeUrl: string
+ state: string
+ intent: CodexSubscriptionOAuthIntent
+ expiresAt: Date
+}
+
+export type CodexDeviceStartResult = {
+ userCode: string
+ verificationUri: string
+ verificationUriComplete: string | null
+ intervalSeconds: number
+ expiresAt: Date
+ state: string
+ intent: CodexSubscriptionOAuthIntent
+}
+
+export type CodexDevicePollResult =
+ | { status: 'pending'; intervalSeconds: number; state: CodexSubscriptionOAuthSafeState }
+ | { status: 'slow_down'; intervalSeconds: number; state: CodexSubscriptionOAuthSafeState }
+ | { status: 'connected'; connection: CodexSubscriptionSafeConnection }
+ | { status: 'expired' }
+ | { status: 'denied' }
+
+function requireEnabled(deps: CodexOAuthDeps): void {
+ if (!deps.enabled) {
+ throw new CodexSubscriptionOAuthError('disabled', 'Codex subscription is disabled')
+ }
+}
+
+export async function getCodexSubscriptionConnection(
+ deps: CodexOAuthDeps
+): Promise<
+ CodexSubscriptionSafeConnection | { connectionKey: 'deployment-default'; status: 'disconnected' }
+> {
+ requireEnabled(deps)
+ const row = await getSafeCodexSubscriptionConnection(deps.db)
+ return row ?? { connectionKey: 'deployment-default', status: 'disconnected' }
+}
+
+export async function startCodexBrowserConnect(
+ deps: CodexOAuthDeps,
+ intent: CodexSubscriptionOAuthIntent = 'connect'
+): Promise<CodexBrowserStartResult> {
+ requireEnabled(deps)
+ const state = randomBytes(24).toString('base64url')
+ const pkceVerifier = randomBytes(32).toString('base64url')
+ const expiresAt = new Date(Date.now() + BROWSER_STATE_TTL_MS)
+ const safe = await insertCodexSubscriptionOAuthState(deps.db, deps.encryptionKey, {
+ state,
+ flow: 'browser',
+ intent,
+ pkceVerifier,
+ expiresAt,
+ })
+ const challenge = createHash('sha256').update(pkceVerifier).digest('base64url')
+ const url = new URL(CODEX_OAUTH_AUTHORIZE_URL)
+ url.searchParams.set('response_type', 'code')
+ url.searchParams.set('client_id', deps.clientId)
+ url.searchParams.set('redirect_uri', deps.redirectUri)
+ url.searchParams.set('scope', CODEX_OAUTH_SCOPES.join(' '))
+ url.searchParams.set('state', state)
+ url.searchParams.set('code_challenge', challenge)
+ url.searchParams.set('code_challenge_method', 'S256')
+ log.info({ event: 'codex_oauth_browser_start', intent: safe.intent }, 'browser OAuth start')
+ return { authorizeUrl: url.toString(), state, intent: safe.intent, expiresAt: safe.expiresAt }
+}
+
+export async function startCodexDeviceConnect(
+ deps: CodexOAuthDeps,
+ intent: CodexSubscriptionOAuthIntent = 'connect'
+): Promise<CodexDeviceStartResult> {
+ requireEnabled(deps)
+ const started = await postJson(deps, CODEX_OAUTH_DEVICE_URL, {
+ client_id: deps.clientId,
+ scope: CODEX_OAUTH_SCOPES.join(' '),
+ })
+ if (!started.ok) {
+ throw new CodexSubscriptionOAuthError('provider_unavailable', 'device authorization failed')
+ }
+ const body = started.body as Record<string, unknown>
+ const deviceCode = requiredString(body.device_code, 'device_code')
+ const userCode = requiredString(body.user_code, 'user_code')
+ const verificationUri = requiredString(
+ body.verification_uri ?? body.verification_uri_complete,
+ 'verification_uri'
+ )
+ const intervalSeconds = positiveNumber(body.interval, 5)
+ const expiresIn = positiveNumber(body.expires_in, 600)
+ const expiresAt = new Date(Date.now() + expiresIn * 1000)
+ const state = randomBytes(24).toString('base64url')
+ const safe = await insertCodexSubscriptionOAuthState(deps.db, deps.encryptionKey, {
+ state,
+ flow: 'device',
+ intent,
+ deviceCode,
+ expiresAt,
+ })
+ log.info({ event: 'codex_oauth_device_start', intent: safe.intent }, 'device OAuth start')
+ return {
+ userCode,
+ verificationUri,
+ verificationUriComplete:
+ typeof body.verification_uri_complete === 'string' ? body.verification_uri_complete : null,
+ intervalSeconds,
+ expiresAt: safe.expiresAt,
+ state,
+ intent: safe.intent,
+ }
+}
+
+export async function handleCodexBrowserCallback(
+ deps: CodexOAuthDeps,
+ input: { code: string; state: string }
+): Promise<CodexSubscriptionSafeConnection> {
+ requireEnabled(deps)
+ if (!input.code || !input.state) {
+ throw new CodexSubscriptionOAuthError('invalid_callback', 'missing code or state')
+ }
+ const consumed = await consumeCodexSubscriptionOAuthState(
+ deps.db,
+ deps.encryptionKey,
+ input.state
+ )
+ if (!consumed) {
+ throw new CodexSubscriptionOAuthError('state_replayed', 'OAuth state is not reusable')
+ }
+ if (consumed.safe.flow !== 'browser' || !consumed.pkceVerifier) {
+ throw new CodexSubscriptionOAuthError('invalid_callback', 'state is not a browser PKCE flow')
+ }
+ const token = await exchangeAuthorizationCode(deps, input.code, consumed.pkceVerifier)
+ return persistGrantedTokens(deps, consumed.safe.intent, token)
+}
+
+export async function pollCodexDevice(
+ deps: CodexOAuthDeps,
+ state: string
+): Promise<CodexDevicePollResult> {
+ requireEnabled(deps)
+ const pending = await peekPendingCodexSubscriptionOAuthState(deps.db, deps.encryptionKey, state)
+ if (!pending) {
+ throw new CodexSubscriptionOAuthError('state_replayed', 'device state is not pending')
+ }
+ if (pending.safe.expiresAt.getTime() <= Date.now()) {
+ await expireCodexSubscriptionOAuthState(deps.db, state)
+ return { status: 'expired' }
+ }
+ if (!pending.deviceCode) {
+ throw new CodexSubscriptionOAuthError(
+ 'invalid_callback',
+ 'device state is missing a device code'
+ )
+ }
+ const tokenResult = await exchangeDeviceCode(deps, pending.deviceCode)
+ if (tokenResult.kind === 'pending') {
+ return { status: 'pending', intervalSeconds: tokenResult.intervalSeconds, state: pending.safe }
+ }
+ if (tokenResult.kind === 'slow_down') {
+ return {
+ status: 'slow_down',
+ intervalSeconds: tokenResult.intervalSeconds,
+ state: pending.safe,
+ }
+ }
+ if (tokenResult.kind === 'expired') {
+ await expireCodexSubscriptionOAuthState(deps.db, state)
+ return { status: 'expired' }
+ }
+ if (tokenResult.kind === 'denied') {
+ await cancelCodexSubscriptionOAuthState(deps.db, state)
+ return { status: 'denied' }
+ }
+ const consumed = await consumeCodexSubscriptionOAuthState(deps.db, deps.encryptionKey, state)
+ if (!consumed) {
+ throw new CodexSubscriptionOAuthError(
+ 'state_replayed',
+ 'device state was consumed concurrently'
+ )
+ }
+ const connection = await persistGrantedTokens(deps, consumed.safe.intent, tokenResult.token)
+ return { status: 'connected', connection }
+}
+
+export async function refreshCodexSubscriptionConnection(
+ deps: CodexOAuthDeps
+): Promise<CodexSubscriptionSafeConnection> {
+ requireEnabled(deps)
+ const current = await getSafeCodexSubscriptionConnection(deps.db)
+ if (!current || current.status === 'revoked' || current.status === 'disconnected') {
+ throw new CodexSubscriptionOAuthError('not_connected', 'no active Codex subscription')
+ }
+ const lockToken = randomBytes(16).toString('hex')
+ const locked = await acquireCodexSubscriptionRefreshLock(deps.db, lockToken, REFRESH_LOCK_TTL_MS)
+ if (!locked) {
+ throw new CodexSubscriptionOAuthError('refresh_in_flight', 'another refresh holds the lock')
+ }
+ try {
+ const secrets = await loadCodexSubscriptionSecrets(deps.db, deps.encryptionKey)
+ if (!secrets)
+ throw new CodexSubscriptionOAuthError('no_grant', 'encrypted refresh token missing')
+ const token = await exchangeRefreshToken(deps, secrets.refreshToken)
+ try {
+ return await rotateCodexSubscriptionCredentials(
+ deps.db,
+ deps.encryptionKey,
+ secrets.credentialRevision,
+ {
+ refreshToken: token.refreshToken ?? secrets.refreshToken,
+ accessToken: token.accessToken,
+ accessTokenExpiresAt: token.expiresAt,
+ accountFingerprint: token.accountFingerprint,
+ }
+ )
+ } catch (err) {
+ if (err instanceof CodexSubscriptionStaleRevisionError) {
+ throw new CodexSubscriptionOAuthError('stale_revision', 'refresh lost the credential race')
+ }
+ throw err
+ }
+ } finally {
+ await releaseCodexSubscriptionRefreshLock(deps.db, lockToken)
+ }
+}
+
+export async function revokeCodexSubscription(
+ deps: CodexOAuthDeps
+): Promise<
+ CodexSubscriptionSafeConnection | { connectionKey: 'deployment-default'; status: 'disconnected' }
+> {
+ requireEnabled(deps)
+ const secrets = await loadCodexSubscriptionSecrets(deps.db, deps.encryptionKey)
+ const local = await revokeCodexSubscriptionConnection(deps.db)
+ if (secrets?.refreshToken) {
+ try {
+ await postForm(deps, CODEX_OAUTH_REVOKE_URL, {
+ token: secrets.refreshToken,
+ token_type_hint: 'refresh_token',
+ client_id: deps.clientId,
+ })
+ } catch (err) {
+ log.warn({ event: 'codex_oauth_upstream_revoke_failed', err }, 'upstream revoke failed')
+ }
+ }
+ log.info({ event: 'codex_oauth_revoked_local' }, 'local Codex subscription revoked')
+ return local ?? { connectionKey: 'deployment-default', status: 'disconnected' }
+}
+
+async function persistGrantedTokens(
+ deps: CodexOAuthDeps,
+ intent: CodexSubscriptionOAuthIntent,
+ token: ParsedCodexToken
+): Promise<CodexSubscriptionSafeConnection> {
+ const existing = await getSafeCodexSubscriptionConnection(deps.db)
+ if (
+ existing?.accountFingerprint &&
+ existing.accountFingerprint !== token.accountFingerprint &&
+ intent !== 'replace'
+ ) {
+ throw new CodexSubscriptionOAuthError(
+ 'replacement_required',
+ 'different account requires an explicit replace intent'
+ )
+ }
+ const write = {
+ refreshToken: token.refreshToken ?? '',
+ accessToken: token.accessToken,
+ accessTokenExpiresAt: token.expiresAt,
+ accountFingerprint: token.accountFingerprint,
+ status: 'connected' as const,
+ }
+ if (!write.refreshToken) {
+ throw new CodexSubscriptionOAuthError(
+ 'provider_unavailable',
+ 'token response omitted refresh token'
+ )
+ }
+ if (!existing) {
+ return insertInitialCodexSubscriptionConnection(deps.db, deps.encryptionKey, write)
+ }
+ try {
+ return await rotateCodexSubscriptionCredentials(
+ deps.db,
+ deps.encryptionKey,
+ existing.credentialRevision,
+ write
+ )
+ } catch (err) {
+ if (err instanceof CodexSubscriptionStaleRevisionError) {
+ throw new CodexSubscriptionOAuthError(
+ 'stale_revision',
+ 'connection was replaced concurrently'
+ )
+ }
+ throw err
+ }
+}
+
+type ParsedCodexToken = {
+ accessToken: string
+ refreshToken: string | null
+ expiresAt: Date | null
+ accountFingerprint: string
+}
+
+async function exchangeAuthorizationCode(
+ deps: CodexOAuthDeps,
+ code: string,
+ pkceVerifier: string
+): Promise<ParsedCodexToken> {
+ const result = await postForm(deps, CODEX_OAUTH_TOKEN_URL, {
+ grant_type: 'authorization_code',
+ code,
+ redirect_uri: deps.redirectUri,
+ client_id: deps.clientId,
+ code_verifier: pkceVerifier,
+ })
+ if (!result.ok) {
+ throw new CodexSubscriptionOAuthError(
+ 'provider_unavailable',
+ 'authorization code exchange failed'
+ )
+ }
+ return parseTokenResponse(result.body)
+}
+
+async function exchangeRefreshToken(
+ deps: CodexOAuthDeps,
+ refreshToken: string
+): Promise<ParsedCodexToken> {
+ const result = await postForm(deps, CODEX_OAUTH_TOKEN_URL, {
+ grant_type: 'refresh_token',
+ refresh_token: refreshToken,
+ client_id: deps.clientId,
+ })
+ if (!result.ok) {
+ throw new CodexSubscriptionOAuthError('provider_unavailable', 'refresh token exchange failed')
+ }
+ return parseTokenResponse(result.body)
+}
+
+async function exchangeDeviceCode(
+ deps: CodexOAuthDeps,
+ deviceCode: string
+): Promise<
+ | { kind: 'ok'; token: ParsedCodexToken }
+ | { kind: 'pending'; intervalSeconds: number }
+ | { kind: 'slow_down'; intervalSeconds: number }
+ | { kind: 'expired' }
+ | { kind: 'denied' }
+> {
+ const result = await postForm(deps, CODEX_OAUTH_TOKEN_URL, {
+ grant_type: 'urn:ietf:params:oauth:grant-type:device_code',
+ device_code: deviceCode,
+ client_id: deps.clientId,
+ })
+ if (result.ok) return { kind: 'ok', token: parseTokenResponse(result.body) }
+ const error = typeof result.body.error === 'string' ? result.body.error : ''
+ if (error === 'authorization_pending') return { kind: 'pending', intervalSeconds: 5 }
+ if (error === 'slow_down') return { kind: 'slow_down', intervalSeconds: 10 }
+ if (error === 'expired_token') return { kind: 'expired' }
+ if (error === 'access_denied') return { kind: 'denied' }
+ throw new CodexSubscriptionOAuthError('provider_unavailable', 'device token poll failed')
+}
+
+function parseTokenResponse(body: Record<string, unknown>): ParsedCodexToken {
+ const accessToken = requiredString(body.access_token, 'access_token')
+ const refreshToken = typeof body.refresh_token === 'string' ? body.refresh_token : null
+ const expiresIn = typeof body.expires_in === 'number' ? body.expires_in : null
+ const subject = subjectFromIdToken(typeof body.id_token === 'string' ? body.id_token : null)
+ return {
+ accessToken,
+ refreshToken,
+ expiresAt: expiresIn ? new Date(Date.now() + expiresIn * 1000) : null,
+ accountFingerprint: fingerprintAccount(subject),
+ }
+}
+
+function subjectFromIdToken(idToken: string | null): string {
+ if (!idToken) {
+ throw new CodexSubscriptionOAuthError('invalid_callback', 'token response omitted id_token')
+ }
+ const parts = idToken.split('.')
+ if (parts.length < 2) {
+ throw new CodexSubscriptionOAuthError('invalid_callback', 'id_token is malformed')
+ }
+ try {
+ const payload = JSON.parse(Buffer.from(parts[1]!, 'base64url').toString('utf8')) as {
+ sub?: unknown
+ }
+ if (typeof payload.sub !== 'string' || payload.sub.length === 0) {
+ throw new Error('missing sub')
+ }
+ return payload.sub
+ } catch {
+ throw new CodexSubscriptionOAuthError('invalid_callback', 'id_token subject is unreadable')
+ }
+}
+
+function fingerprintAccount(subject: string): string {
+ return createHash('sha256').update(subject, 'utf8').digest('hex')
+}
+
+async function postForm(
+ deps: CodexOAuthDeps,
+ url: string,
+ params: Record<string, string>
+): Promise<{ ok: boolean; body: Record<string, unknown> }> {
+ return post(
+ deps,
+ url,
+ 'application/x-www-form-urlencoded',
+ new URLSearchParams(params).toString()
+ )
+}
+
+async function postJson(
+ deps: CodexOAuthDeps,
+ url: string,
+ payload: Record<string, string>
+): Promise<{ ok: boolean; body: Record<string, unknown> }> {
+ return post(deps, url, 'application/json', JSON.stringify(payload))
+}
+
+async function post(
+ deps: CodexOAuthDeps,
+ url: string,
+ contentType: string,
+ body: string
+): Promise<{ ok: boolean; body: Record<string, unknown> }> {
+ let response: Response
+ try {
+ response = await deps.fetchFn(url, {
+ method: 'POST',
+ headers: { 'content-type': contentType, accept: 'application/json' },
+ body,
+ signal: AbortSignal.timeout(TOKEN_TIMEOUT_MS),
+ })
+ } catch (err) {
+ log.warn({ event: 'codex_oauth_upstream_unreachable', err }, 'Codex OAuth upstream unreachable')
+ throw new CodexSubscriptionOAuthError(
+ 'provider_unavailable',
+ 'Codex OAuth upstream unreachable'
+ )
+ }
+ const json = (await response.json().catch(() => ({}))) as Record<string, unknown>
+ return { ok: response.ok, body: json }
+}
+
+function requiredString(value: unknown, field: string): string {
+ if (typeof value !== 'string' || value.length === 0) {
+ throw new CodexSubscriptionOAuthError('provider_unavailable', `upstream omitted ${field}`)
+ }
+ return value
+}
+
+function positiveNumber(value: unknown, fallback: number): number {
+ return typeof value === 'number' && Number.isFinite(value) && value > 0 ? value : fallback
+}
diff --git a/control-api/src/services/codexSubscriptionOAuthState.ts b/control-api/src/services/codexSubscriptionOAuthState.ts
index 6ecbd4595..afeab0ed6 100644
--- a/control-api/src/services/codexSubscriptionOAuthState.ts
+++ b/control-api/src/services/codexSubscriptionOAuthState.ts
@@ -131,25 +131,44 @@ export async function insertCodexSubscriptionOAuthState(
return toSafeOAuthState(result.rows[0] as SafeOAuthStateRow)
}
-export async function consumeCodexSubscriptionOAuthState(
+export async function peekPendingCodexSubscriptionOAuthState(
db: DbClient,
encryptionKey: Buffer,
state: string
): Promise<CodexSubscriptionConsumedOAuthState | null> {
const result = await db.query(
- `UPDATE codex_subscription_oauth_states
- SET status = 'consumed',
- consumed_at = now()
+ `SELECT ${SAFE_OAUTH_STATE_COLUMNS},
+ pkce_verifier_encrypted,
+ device_code_encrypted
+ FROM codex_subscription_oauth_states
WHERE state = $1
AND status = 'pending'
- AND expires_at > now()
- RETURNING ${SAFE_OAUTH_STATE_COLUMNS},
- pkce_verifier_encrypted,
- device_code_encrypted`,
+ AND expires_at > now()`,
[state]
)
const row = result.rows[0] as ConsumedOAuthStateRow | undefined
if (!row) return null
+ return toConsumedOAuthState(row, encryptionKey)
+}
+
+export async function expireCodexSubscriptionOAuthState(
+ db: DbClient,
+ state: string
+): Promise<boolean> {
+ const result = await db.query(
+ `UPDATE codex_subscription_oauth_states
+ SET status = 'expired'
+ WHERE state = $1
+ AND status = 'pending'`,
+ [state]
+ )
+ return (result.rowCount ?? 0) > 0
+}
+
+function toConsumedOAuthState(
+ row: ConsumedOAuthStateRow,
+ encryptionKey: Buffer
+): CodexSubscriptionConsumedOAuthState {
return {
safe: toSafeOAuthState(row),
pkceVerifier: row.pkce_verifier_encrypted
@@ -161,6 +180,28 @@ export async function consumeCodexSubscriptionOAuthState(
}
}
+export async function consumeCodexSubscriptionOAuthState(
+ db: DbClient,
+ encryptionKey: Buffer,
+ state: string
+): Promise<CodexSubscriptionConsumedOAuthState | null> {
+ const result = await db.query(
+ `UPDATE codex_subscription_oauth_states
+ SET status = 'consumed',
+ consumed_at = now()
+ WHERE state = $1
+ AND status = 'pending'
+ AND expires_at > now()
+ RETURNING ${SAFE_OAUTH_STATE_COLUMNS},
+ pkce_verifier_encrypted,
+ device_code_encrypted`,
+ [state]
+ )
+ const row = result.rows[0] as ConsumedOAuthStateRow | undefined
+ if (!row) return null
+ return toConsumedOAuthState(row, encryptionKey)
+}
+
export async function cancelCodexSubscriptionOAuthState(
db: DbClient,
state: string
diff --git a/control-api/test/routes.admin.codexSubscription.test.ts b/control-api/test/routes.admin.codexSubscription.test.ts
new file mode 100644
index 000000000..679435baa
--- /dev/null
+++ b/control-api/test/routes.admin.codexSubscription.test.ts
@@ -0,0 +1,143 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest'
+import express, { type NextFunction, type Request, type Response } from 'express'
+import request from 'supertest'
+import { CodexSubscriptionOAuthError } from '../src/services/codexSubscriptionOAuth.js'
+
+const oauth = vi.hoisted(() => ({
+ getConnection: vi.fn(),
+ startBrowser: vi.fn(),
+ startDevice: vi.fn(),
+ pollDevice: vi.fn(),
+ refresh: vi.fn(),
+ revoke: vi.fn(),
+}))
+
+vi.mock('../src/services/codexSubscriptionOAuth.js', async () => {
+ const actual = await vi.importActual('../src/services/codexSubscriptionOAuth.js')
+ return {
+ ...actual,
+ getCodexSubscriptionConnection: oauth.getConnection,
+ startCodexBrowserConnect: oauth.startBrowser,
+ startCodexDeviceConnect: oauth.startDevice,
+ pollCodexDevice: oauth.pollDevice,
+ refreshCodexSubscriptionConnection: oauth.refresh,
+ revokeCodexSubscription: oauth.revoke,
+ }
+})
+
+vi.mock('../src/db.js', () => ({
+ pool: { query: vi.fn() },
+}))
+
+const { config } = await import('../src/config.js')
+const { createAdminCodexSubscriptionRouter } =
+ await import('../src/routes/admin/codexSubscription.js')
+
+function makeAuthedApp() {
+ const app = express()
+ app.use(express.json())
+ app.use((req: Request & { adminAuth?: { sub: string } }, _res: Response, next: NextFunction) => {
+ req.adminAuth = { sub: 'admin-1' }
+ next()
+ })
+ app.use(createAdminCodexSubscriptionRouter())
+ return app
+}
+
+function assertNoLeak(body: unknown): void {
+ const serialized = JSON.stringify(body)
+ expect(serialized).not.toMatch(/sk-|Bearer |eyJ[A-Za-z0-9_-]+\.|refresh-secret|access-secret/i)
+ expect(serialized).not.toMatch(/cookie|set-cookie|authorization/i)
+ expect(serialized).not.toContain('acct_raw_123')
+}
+
+describe('admin Codex subscription routes', () => {
+ let app: ReturnType<typeof makeAuthedApp>
+
+ beforeEach(() => {
+ app = makeAuthedApp()
+ config.codexSubscriptionEnabled = true
+ for (const fn of Object.values(oauth)) fn.mockReset()
+ })
+
+ it('returns 404 while the feature flag is off', async () => {
+ oauth.getConnection.mockRejectedValue(new CodexSubscriptionOAuthError('disabled', 'off'))
+ const res = await request(app).get('/admin/llm/providers/codex-subscription/connection')
+ expect(res.status).toBe(404)
+ expect(res.body).toEqual({ error: 'disabled' })
+ assertNoLeak(res.body)
+ })
+
+ it('returns safe connection metadata', async () => {
+ oauth.getConnection.mockResolvedValue({
+ connectionKey: 'deployment-default',
+ status: 'connected',
+ accountFingerprint: 'fp',
+ credentialRevision: 2,
+ })
+ const res = await request(app).get('/admin/llm/providers/codex-subscription/connection')
+ expect(res.status).toBe(200)
+ expect(res.body.connectionKey).toBe('deployment-default')
+ assertNoLeak(res.body)
+ })
+
+ it('starts browser and device flows without tokens or cookies', async () => {
+ oauth.startBrowser.mockResolvedValue({
+ authorizeUrl: 'https://auth.openai.com/oauth/authorize?state=abc',
+ state: 'abc',
+ intent: 'connect',
+ expiresAt: new Date().toISOString(),
+ })
+ oauth.startDevice.mockResolvedValue({
+ userCode: 'ABCD-EFGH',
+ verificationUri: 'https://auth.openai.com/codex/device',
+ intervalSeconds: 5,
+ state: 'dev',
+ intent: 'connect',
+ })
+ const browser = await request(app)
+ .post('/admin/llm/providers/codex-subscription/browser/start')
+ .send({ intent: 'connect' })
+ expect(browser.status).toBe(200)
+ expect(browser.body.authorizeUrl).toContain('https://auth.openai.com/oauth/authorize')
+ expect(browser.headers['set-cookie']).toBeUndefined()
+ assertNoLeak(browser.body)
+
+ const device = await request(app)
+ .post('/admin/llm/providers/codex-subscription/device/start')
+ .send({ intent: 'replace' })
+ expect(device.status).toBe(200)
+ expect(device.body.userCode).toBe('ABCD-EFGH')
+ expect(device.body).not.toHaveProperty('deviceCode')
+ assertNoLeak(device.body)
+ })
+
+ it('maps replacement and refresh races to 409 without leaking tokens', async () => {
+ oauth.startBrowser.mockRejectedValue(
+ new CodexSubscriptionOAuthError('replacement_required', 'replace')
+ )
+ const replace = await request(app)
+ .post('/admin/llm/providers/codex-subscription/browser/start')
+ .send({ intent: 'connect' })
+ expect(replace.status).toBe(409)
+ expect(replace.body).toEqual({ error: 'replacement_required' })
+
+ oauth.refresh.mockRejectedValue(new CodexSubscriptionOAuthError('refresh_in_flight', 'lock'))
+ const refresh = await request(app).post('/admin/llm/providers/codex-subscription/refresh')
+ expect(refresh.status).toBe(409)
+ expect(refresh.body).toEqual({ error: 'refresh_in_flight' })
+ assertNoLeak(refresh.body)
+ })
+
+ it('revokes without returning secrets', async () => {
+ oauth.revoke.mockResolvedValue({
+ connectionKey: 'deployment-default',
+ status: 'revoked',
+ credentialRevision: 9,
+ })
+ const res = await request(app).post('/admin/llm/providers/codex-subscription/revoke')
+ expect(res.status).toBe(200)
+ expect(res.body.status).toBe('revoked')
+ assertNoLeak(res.body)
+ })
+})
diff --git a/control-api/test/routes.auth.codexSubscriptionCallback.test.ts b/control-api/test/routes.auth.codexSubscriptionCallback.test.ts
new file mode 100644
index 000000000..470d106c7
--- /dev/null
+++ b/control-api/test/routes.auth.codexSubscriptionCallback.test.ts
@@ -0,0 +1,84 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest'
+import express from 'express'
+import request from 'supertest'
+import { CodexSubscriptionOAuthError } from '../src/services/codexSubscriptionOAuth.js'
+
+const oauth = vi.hoisted(() => ({
+ callback: vi.fn(),
+}))
+
+vi.mock('../src/services/codexSubscriptionOAuth.js', async () => {
+ const actual = await vi.importActual('../src/services/codexSubscriptionOAuth.js')
+ return {
+ ...actual,
+ handleCodexBrowserCallback: oauth.callback,
+ }
+})
+
+vi.mock('../src/db.js', () => ({
+ pool: { query: vi.fn() },
+}))
+
+const { createAuthCodexSubscriptionRouter } =
+ await import('../src/routes/auth/codexSubscription.js')
+
+function makeApp() {
+ const app = express()
+ app.use(createAuthCodexSubscriptionRouter())
+ return app
+}
+
+function assertNoLeak(body: unknown): void {
+ const serialized = JSON.stringify(body)
+ expect(serialized).not.toMatch(/sk-|Bearer |eyJ[A-Za-z0-9_-]+\.|refresh-secret|access-secret/i)
+ expect(serialized).not.toMatch(/cookie|set-cookie|authorization/i)
+ expect(serialized).not.toContain('acct_raw_123')
+}
+
+describe('GET /auth/codex-subscription/callback', () => {
+ let app: ReturnType<typeof makeApp>
+
+ beforeEach(() => {
+ app = makeApp()
+ oauth.callback.mockReset()
+ })
+
+ it('rejects a missing code or state', async () => {
+ oauth.callback.mockRejectedValue(new CodexSubscriptionOAuthError('invalid_callback', 'missing'))
+ const res = await request(app).get('/auth/codex-subscription/callback')
+ expect(res.status).toBe(400)
+ expect(res.body).toEqual({ error: 'invalid_callback' })
+ assertNoLeak(res.body)
+ })
+
+ it('rejects callback replay', async () => {
+ oauth.callback.mockRejectedValue(new CodexSubscriptionOAuthError('state_replayed', 'replay'))
+ const res = await request(app)
+ .get('/auth/codex-subscription/callback')
+ .query({ code: 'code-1', state: 'state-1' })
+ expect(res.status).toBe(400)
+ expect(res.body).toEqual({ error: 'state_replayed' })
+ assertNoLeak(res.body)
+ })
+
+ it('returns only safe connection fields on success', async () => {
+ oauth.callback.mockResolvedValue({
+ status: 'connected',
+ accountFingerprint: 'fp',
+ credentialRevision: 1,
+ refreshToken: 'refresh-secret',
+ accessToken: 'access-secret',
+ })
+ const res = await request(app)
+ .get('/auth/codex-subscription/callback')
+ .query({ code: 'code-1', state: 'state-1' })
+ expect(res.status).toBe(200)
+ expect(res.body).toEqual({
+ status: 'connected',
+ accountFingerprint: 'fp',
+ credentialRevision: 1,
+ })
+ expect(res.headers['set-cookie']).toBeUndefined()
+ assertNoLeak(res.body)
+ })
+})
diff --git a/control-api/test/services.codexSubscriptionOAuth.realPostgres.integration.test.ts b/control-api/test/services.codexSubscriptionOAuth.realPostgres.integration.test.ts
new file mode 100644
index 000000000..c64fa75a9
--- /dev/null
+++ b/control-api/test/services.codexSubscriptionOAuth.realPostgres.integration.test.ts
@@ -0,0 +1,106 @@
+import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest'
+import { createHash, randomBytes } from 'node:crypto'
+import { Pool } from 'pg'
+import { initDb } from '../src/db.js'
+import { deriveOAuthEncryptionKey } from '../src/oauth/encryption.js'
+import { insertInitialCodexSubscriptionConnection } from '../src/services/codexSubscriptionConnection.js'
+import {
+ type CodexOAuthDeps,
+ CodexSubscriptionOAuthError,
+ refreshCodexSubscriptionConnection,
+ revokeCodexSubscription,
+} from '../src/services/codexSubscriptionOAuth.js'
+
+const adminUrl = process.env.CONTROL_API_REAL_PG_ADMIN_URL
+const describeRealPostgres = adminUrl ? describe : describe.skip
+const KEY = deriveOAuthEncryptionKey('ab'.repeat(32))
+
+function databaseUrl(baseUrl: string, database: string): string {
+ const url = new URL(baseUrl)
+ url.pathname = `/${database}`
+ return url.toString()
+}
+
+function quoteIdent(value: string): string {
+ return `"${value.replace(/"/g, '""')}"`
+}
+
+function idTokenFor(subject: string): string {
+ const payload = Buffer.from(JSON.stringify({ sub: subject })).toString('base64url')
+ return `hdr.${payload}.sig`
+}
+
+describeRealPostgres('Codex subscription OAuth on real PostgreSQL', () => {
+ const database = `codex_oauth_${randomBytes(6).toString('hex')}`
+ const connectionString = databaseUrl(
+ adminUrl ?? 'postgresql://[email protected]/postgres',
+ database
+ )
+ let adminPool: Pool
+ let pool: Pool
+
+ beforeAll(async () => {
+ adminPool = new Pool({ connectionString: adminUrl })
+ await adminPool.query(`CREATE DATABASE ${quoteIdent(database)}`)
+ pool = new Pool({ connectionString })
+ await initDb({ connect: () => pool.connect() })
+ await insertInitialCodexSubscriptionConnection(pool, KEY, {
+ refreshToken: 'seed-refresh',
+ accountFingerprint: createHash('sha256').update('acct-seed', 'utf8').digest('hex'),
+ })
+ }, 60_000)
+
+ afterAll(async () => {
+ await pool?.end()
+ if (adminPool) {
+ await adminPool
+ .query(`DROP DATABASE IF EXISTS ${quoteIdent(database)}`)
+ .catch(() => undefined)
+ await adminPool.end()
+ }
+ })
+
+ function deps(fetchFn: typeof fetch): CodexOAuthDeps {
+ return {
+ db: pool,
+ encryptionKey: KEY,
+ fetchFn,
+ clientId: 'app_test_client',
+ redirectUri: 'https://control.example/api/v1/auth/codex-subscription/callback',
+ enabled: true,
+ }
+ }
+
+ it('lets only one concurrent refresh win the single-flight lock', async () => {
+ const fetchFn = vi.fn().mockResolvedValue({
+ ok: true,
+ json: async () => ({
+ access_token: 'access-secret',
+ refresh_token: 'winner-refresh',
+ id_token: idTokenFor('acct-seed'),
+ }),
+ })
+ const results = await Promise.allSettled([
+ refreshCodexSubscriptionConnection(deps(fetchFn)),
+ refreshCodexSubscriptionConnection(deps(fetchFn)),
+ ])
+ const fulfilled = results.filter(result => result.status === 'fulfilled')
+ const rejected = results.filter(result => result.status === 'rejected')
+ expect(fulfilled).toHaveLength(1)
+ expect(rejected).toHaveLength(1)
+ expect((rejected[0] as PromiseRejectedResult).reason).toBeInstanceOf(
+ CodexSubscriptionOAuthError
+ )
+ expect((rejected[0] as PromiseRejectedResult).reason).toMatchObject({
+ code: expect.stringMatching(/refresh_in_flight|stale_revision/),
+ })
+ })
+
+ it('revokes locally first when upstream revoke fails', async () => {
+ const fetchFn = vi.fn().mockRejectedValue(new Error('upstream revoke down'))
+ const revoked = await revokeCodexSubscription(deps(fetchFn))
+ expect(revoked.status).toBe('revoked')
+ expect(JSON.stringify(revoked)).not.toContain('seed-refresh')
+ expect(JSON.stringify(revoked)).not.toContain('winner-refresh')
+ })
+})
diff --git a/control-api/test/services.codexSubscriptionOAuth.test.ts b/control-api/test/services.codexSubscriptionOAuth.test.ts
new file mode 100644
index 000000000..7002615b3
--- /dev/null
+++ b/control-api/test/services.codexSubscriptionOAuth.test.ts
@@ -0,0 +1,395 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest'
+import { createHash } from 'node:crypto'
+import { deriveOAuthEncryptionKey } from '../src/oauth/encryption.js'
+import { CodexSubscriptionStaleRevisionError } from '../src/services/codexSubscriptionConnection.js'
+
+const repos = vi.hoisted(() => ({
+ insertState: vi.fn(),
+ consumeState: vi.fn(),
+ peekState: vi.fn(),
+ expireState: vi.fn(),
+ cancelState: vi.fn(),
+ getSafe: vi.fn(),
+ insertInitial: vi.fn(),
+ rotate: vi.fn(),
+ acquireLock: vi.fn(),
+ releaseLock: vi.fn(),
+ loadSecrets: vi.fn(),
+ revokeConnection: vi.fn(),
+}))
+
+vi.mock('../src/services/codexSubscriptionOAuthState.js', async () => {
+ const actual = await vi.importActual('../src/services/codexSubscriptionOAuthState.js')
+ return {
+ ...actual,
+ insertCodexSubscriptionOAuthState: repos.insertState,
+ consumeCodexSubscriptionOAuthState: repos.consumeState,
+ peekPendingCodexSubscriptionOAuthState: repos.peekState,
+ expireCodexSubscriptionOAuthState: repos.expireState,
+ cancelCodexSubscriptionOAuthState: repos.cancelState,
+ }
+})
+
+vi.mock('../src/services/codexSubscriptionConnection.js', async () => {
+ const actual = await vi.importActual('../src/services/codexSubscriptionConnection.js')
+ return {
+ ...actual,
+ getSafeCodexSubscriptionConnection: repos.getSafe,
+ insertInitialCodexSubscriptionConnection: repos.insertInitial,
+ rotateCodexSubscriptionCredentials: repos.rotate,
+ acquireCodexSubscriptionRefreshLock: repos.acquireLock,
+ releaseCodexSubscriptionRefreshLock: repos.releaseLock,
+ loadCodexSubscriptionSecrets: repos.loadSecrets,
+ revokeCodexSubscriptionConnection: repos.revokeConnection,
+ }
+})
+
+const {
+ CodexSubscriptionOAuthError,
+ CODEX_OAUTH_AUTHORIZE_URL,
+ handleCodexBrowserCallback,
+ pollCodexDevice,
+ refreshCodexSubscriptionConnection,
+ revokeCodexSubscription,
+ startCodexBrowserConnect,
+ startCodexDeviceConnect,
+} = await import('../src/services/codexSubscriptionOAuth.js')
+
+const KEY = deriveOAuthEncryptionKey('ab'.repeat(32))
+
+function idTokenFor(subject: string): string {
+ const payload = Buffer.from(JSON.stringify({ sub: subject })).toString('base64url')
+ return `hdr.${payload}.sig`
+}
+
+function fingerprint(subject: string): string {
+ return createHash('sha256').update(subject, 'utf8').digest('hex')
+}
+
+function assertNoLeak(value: unknown): void {
+ const serialized = JSON.stringify(value)
+ expect(serialized).not.toMatch(
+ /sk-|Bearer |eyJ[A-Za-z0-9_-]+\.|refresh-secret|access-secret|cookie/i
+ )
+ expect(serialized).not.toContain('acct_raw_123')
+}
+
+function deps(fetchFn: typeof fetch) {
+ return {
+ db: { query: vi.fn() },
+ encryptionKey: KEY,
+ fetchFn,
+ clientId: 'app_test_client',
+ redirectUri: 'https://control.example/api/v1/auth/codex-subscription/callback',
+ enabled: true,
+ }
+}
+
+describe('codex subscription OAuth broker', () => {
+ beforeEach(() => {
+ for (const fn of Object.values(repos)) fn.mockReset()
+ })
+
+ it('starts a browser PKCE flow without leaking secrets', async () => {
+ repos.insertState.mockImplementation(
+ async (
+ _db: unknown,
+ _key: Buffer,
+ input: { state: string; intent: string; expiresAt: Date }
+ ) => ({
+ state: input.state,
+ flow: 'browser',
+ intent: input.intent,
+ status: 'pending',
+ expiresAt: input.expiresAt,
+ consumedAt: null,
+ cancelledAt: null,
+ createdAt: new Date(),
+ })
+ )
+ const result = await startCodexBrowserConnect(deps(vi.fn()), 'connect')
+ expect(result.authorizeUrl.startsWith(CODEX_OAUTH_AUTHORIZE_URL)).toBe(true)
+ expect(result.authorizeUrl).toContain('code_challenge_method=S256')
+ expect(result.authorizeUrl).toContain('state=')
+ expect(repos.insertState.mock.calls[0]?.[2]).toMatchObject({
+ flow: 'browser',
+ intent: 'connect',
+ })
+ expect(repos.insertState.mock.calls[0]?.[2].pkceVerifier).toEqual(expect.any(String))
+ assertNoLeak(result)
+ expect(JSON.stringify(result)).not.toContain(repos.insertState.mock.calls[0]?.[2].pkceVerifier)
+ })
+
+ it('rejects a replayed browser callback', async () => {
+ repos.consumeState.mockResolvedValueOnce(null)
+ await expect(
+ handleCodexBrowserCallback(deps(vi.fn()), { code: 'code-1', state: 'state-1' })
+ ).rejects.toMatchObject({ code: 'state_replayed' })
+ })
+
+ it('reconnects the same account and requires replace for a different account', async () => {
+ const fetchFn = vi.fn().mockResolvedValue({
+ ok: true,
+ json: async () => ({
+ access_token: 'access-secret',
+ refresh_token: 'refresh-secret',
+ expires_in: 60,
+ id_token: idTokenFor('acct_raw_123'),
+ }),
+ })
+ repos.consumeState.mockResolvedValue({
+ safe: {
+ state: 'state-1',
+ flow: 'browser',
+ intent: 'connect',
+ status: 'consumed',
+ expiresAt: new Date(Date.now() + 1000),
+ consumedAt: new Date(),
+ cancelledAt: null,
+ createdAt: new Date(),
+ },
+ pkceVerifier: 'verifier',
+ })
+ repos.getSafe.mockResolvedValue({
+ connectionKey: 'deployment-default',
+ status: 'connected',
+ credentialRevision: 2,
+ catalogRevision: 0,
+ accountFingerprint: fingerprint('acct_raw_123'),
+ catalogStatus: 'ready',
+ catalogSyncedAt: null,
+ lastRefreshAt: null,
+ lastAuthAt: null,
+ refreshLockHeld: false,
+ revokedAt: null,
+ createdAt: new Date(),
+ updatedAt: new Date(),
+ })
+ repos.rotate.mockResolvedValue({
+ connectionKey: 'deployment-default',
+ status: 'connected',
+ credentialRevision: 3,
+ accountFingerprint: fingerprint('acct_raw_123'),
+ })
+
+ const same = await handleCodexBrowserCallback(deps(fetchFn), {
+ code: 'code-1',
+ state: 'state-1',
+ })
+ expect(same.credentialRevision).toBe(3)
+ assertNoLeak(same)
+
+ repos.consumeState.mockResolvedValue({
+ safe: {
+ state: 'state-2',
+ flow: 'browser',
+ intent: 'connect',
+ status: 'consumed',
+ expiresAt: new Date(Date.now() + 1000),
+ consumedAt: new Date(),
+ cancelledAt: null,
+ createdAt: new Date(),
+ },
+ pkceVerifier: 'verifier',
+ })
+ fetchFn.mockResolvedValue({
+ ok: true,
+ json: async () => ({
+ access_token: 'access-secret',
+ refresh_token: 'refresh-secret',
+ id_token: idTokenFor('acct_other'),
+ }),
+ })
+ await expect(
+ handleCodexBrowserCallback(deps(fetchFn), { code: 'code-2', state: 'state-2' })
+ ).rejects.toMatchObject({ code: 'replacement_required' })
+ expect(repos.rotate).toHaveBeenCalledTimes(1)
+ })
+
+ it('persists a different account only with explicit replace intent', async () => {
+ const fetchFn = vi.fn().mockResolvedValue({
+ ok: true,
+ json: async () => ({
+ access_token: 'access-secret',
+ refresh_token: 'refresh-secret',
+ id_token: idTokenFor('acct_other'),
+ }),
+ })
+ repos.consumeState.mockResolvedValue({
+ safe: {
+ state: 'state-r',
+ flow: 'browser',
+ intent: 'replace',
+ status: 'consumed',
+ expiresAt: new Date(Date.now() + 1000),
+ consumedAt: new Date(),
+ cancelledAt: null,
+ createdAt: new Date(),
+ },
+ pkceVerifier: 'verifier',
+ })
+ repos.getSafe.mockResolvedValue({
+ connectionKey: 'deployment-default',
+ status: 'connected',
+ credentialRevision: 4,
+ accountFingerprint: fingerprint('acct_raw_123'),
+ })
+ repos.rotate.mockResolvedValue({
+ connectionKey: 'deployment-default',
+ status: 'connected',
+ credentialRevision: 5,
+ accountFingerprint: fingerprint('acct_other'),
+ })
+ const replaced = await handleCodexBrowserCallback(deps(fetchFn), {
+ code: 'code-r',
+ state: 'state-r',
+ })
+ expect(replaced.credentialRevision).toBe(5)
+ expect(replaced.accountFingerprint).toBe(fingerprint('acct_other'))
+ assertNoLeak(replaced)
+ })
+
+ it('polls device authorization with expiry and backoff', async () => {
+ repos.peekState.mockResolvedValue({
+ safe: {
+ state: 'dev-1',
+ flow: 'device',
+ intent: 'connect',
+ status: 'pending',
+ expiresAt: new Date(Date.now() + 60_000),
+ consumedAt: null,
+ cancelledAt: null,
+ createdAt: new Date(),
+ },
+ deviceCode: 'device-secret',
+ })
+ const fetchFn = vi
+ .fn()
+ .mockResolvedValueOnce({
+ ok: false,
+ json: async () => ({ error: 'authorization_pending' }),
+ })
+ .mockResolvedValueOnce({
+ ok: false,
+ json: async () => ({ error: 'slow_down' }),
+ })
+ await expect(pollCodexDevice(deps(fetchFn), 'dev-1')).resolves.toMatchObject({
+ status: 'pending',
+ intervalSeconds: 5,
+ })
+ await expect(pollCodexDevice(deps(fetchFn), 'dev-1')).resolves.toMatchObject({
+ status: 'slow_down',
+ intervalSeconds: 10,
+ })
+
+ repos.peekState.mockResolvedValue({
+ safe: {
+ state: 'dev-exp',
+ flow: 'device',
+ intent: 'connect',
+ status: 'pending',
+ expiresAt: new Date(Date.now() - 1),
+ consumedAt: null,
+ cancelledAt: null,
+ createdAt: new Date(),
+ },
+ deviceCode: 'device-secret',
+ })
+ await expect(pollCodexDevice(deps(fetchFn), 'dev-exp')).resolves.toEqual({ status: 'expired' })
+ expect(repos.expireState).toHaveBeenCalled()
+ })
+
+ it('rejects a stale refresh and persists a rotated refresh token', async () => {
+ repos.getSafe.mockResolvedValue({
+ connectionKey: 'deployment-default',
+ status: 'connected',
+ credentialRevision: 7,
+ })
+ repos.acquireLock.mockResolvedValueOnce(true)
+ repos.loadSecrets.mockResolvedValue({
+ refreshToken: 'old-refresh',
+ accessToken: null,
+ accessTokenExpiresAt: null,
+ credentialRevision: 7,
+ })
+ const fetchFn = vi.fn().mockResolvedValue({
+ ok: true,
+ json: async () => ({
+ access_token: 'access-secret',
+ refresh_token: 'rotated-refresh',
+ id_token: idTokenFor('acct_raw_123'),
+ }),
+ })
+ repos.rotate.mockRejectedValueOnce(new CodexSubscriptionStaleRevisionError())
+ await expect(refreshCodexSubscriptionConnection(deps(fetchFn))).rejects.toMatchObject({
+ code: 'stale_revision',
+ })
+ expect(repos.releaseLock).toHaveBeenCalled()
+
+ repos.acquireLock.mockResolvedValueOnce(true)
+ repos.rotate.mockResolvedValueOnce({
+ connectionKey: 'deployment-default',
+ status: 'connected',
+ credentialRevision: 8,
+ accountFingerprint: fingerprint('acct_raw_123'),
+ })
+ const refreshed = await refreshCodexSubscriptionConnection(deps(fetchFn))
+ expect(repos.rotate.mock.calls.at(-1)?.[3]).toMatchObject({ refreshToken: 'rotated-refresh' })
+ assertNoLeak(refreshed)
+ })
+
+ it('revokes locally even when upstream revoke fails', async () => {
+ repos.loadSecrets.mockResolvedValue({
+ refreshToken: 'refresh-secret',
+ accessToken: 'access-secret',
+ accessTokenExpiresAt: null,
+ credentialRevision: 3,
+ })
+ repos.revokeConnection.mockResolvedValue({
+ connectionKey: 'deployment-default',
+ status: 'revoked',
+ credentialRevision: 4,
+ accountFingerprint: null,
+ })
+ const fetchFn = vi.fn().mockRejectedValue(new Error('upstream down'))
+ const revoked = await revokeCodexSubscription(deps(fetchFn))
+ expect(revoked.status).toBe('revoked')
+ expect(repos.revokeConnection).toHaveBeenCalled()
+ assertNoLeak(revoked)
+ })
+
+ it('starts device flow without returning the device code', async () => {
+ const fetchFn = vi.fn().mockResolvedValue({
+ ok: true,
+ json: async () => ({
+ device_code: 'device-secret',
+ user_code: 'ABCD-EFGH',
+ verification_uri: 'https://auth.openai.com/codex/device',
+ expires_in: 600,
+ interval: 5,
+ }),
+ })
+ repos.insertState.mockImplementation(
+ async (_db: unknown, _key: Buffer, input: { state: string }) => ({
+ state: input.state,
+ flow: 'device',
+ intent: 'connect',
+ status: 'pending',
+ expiresAt: new Date(Date.now() + 600_000),
+ consumedAt: null,
+ cancelledAt: null,
+ createdAt: new Date(),
+ })
+ )
+ const started = await startCodexDeviceConnect(deps(fetchFn), 'connect')
+ expect(started.userCode).toBe('ABCD-EFGH')
+ assertNoLeak(started)
+ expect(JSON.stringify(started)).not.toContain('device-secret')
+ })
+
+ it('exposes only bounded error classes', () => {
+ const err = new CodexSubscriptionOAuthError('replacement_required', 'need replace')
+ expect(err).toBeInstanceOf(Error)
+ expect(err.code).toBe('replacement_required')
+ })
+})