From 08325502900414584dfd6f059b5dc72b3679ba27 Mon Sep 17 00:00:00 2001 From: Neil Date: Tue, 10 Nov 2026 04:39:25 -0800 Subject: [PATCH] feat(cloud): provider-specific onUnauthorized hook (default: revoke) --- cloud/apps/sandbox-control/src/account-providers.ts | 5 +++++ cloud/apps/sandbox-control/src/index.ts | 6 +++++- 2 files changed, 10 insertions(+), 1 deletion(-) diff --git a/cloud/apps/sandbox-control/src/account-providers.ts b/cloud/apps/sandbox-control/src/account-providers.ts index 4efc6fa1caa..d91956c246f 100644 --- a/cloud/apps/sandbox-control/src/account-providers.ts +++ b/cloud/apps/sandbox-control/src/account-providers.ts @@ -20,6 +20,11 @@ export type AccountProvider = { format(credential: string): string /** Extra headers derived from the real credential (e.g. Codex's ChatGPT account id). */ extraHeaders?(credential: string): Record + /** + * The provider answered 401 to this credential. Default (absent): mark it revoked. Codex instead + * kicks a single-flight lease refresh, which marks it expired/revoked itself if the refresh token is dead. + */ + onUnauthorized?(ctx: { db: D1Database; keyring: Keyring; userId: string; now: number; waitUntil: (work: Promise) => void }): Promise /** The real value for this person, or null (none, expired, revoked). */ credential(db: D1Database, keyring: Keyring, userId: string, now: number): Promise } diff --git a/cloud/apps/sandbox-control/src/index.ts b/cloud/apps/sandbox-control/src/index.ts index 0f9eac1eba8..ffc9a2ffbe9 100644 --- a/cloud/apps/sandbox-control/src/index.ts +++ b/cloud/apps/sandbox-control/src/index.ts @@ -347,7 +347,11 @@ function egressRoutes(env: Env, deps: Deps): (row: SandboxRow, host: string) => if (status === 401) { // The provider no longer accepts it (revoked at the source): stop using it until renewed. const now = (deps.now ?? Date.now)() - const work = markAgentCredentialRevoked(env.SANDBOX_DB, row.user_id, agent, now).then(() => { + const waitUntil = (work: Promise) => (deps.waitUntil ? deps.waitUntil(work.catch(() => undefined)) : void work.catch(() => undefined)) + const handled = provider.onUnauthorized + ? keyring.then((ring) => provider.onUnauthorized!({ db: env.SANDBOX_DB, keyring: ring, userId: row.user_id, now, waitUntil })) + : markAgentCredentialRevoked(env.SANDBOX_DB, row.user_id, agent, now) + const work = handled.then(() => { forgetAccountCredential(row.user_id, agent) scheduleEnvRefresh(env, deps, row) })