import { AuthorizationError, type OAuthHelpers } from "@cloudflare/workers-oauth-provider"; import type { Person } from "./contract/actor.ts"; import type { Outcome } from "./contract/common.ts"; import { refsErrorCode } from "./contract/errors.ts"; import type { AgentConsent } from "./contract/handles.ts"; import type { AgentGrant } from "./contract/views.ts"; import { resolveActor } from "./identity.ts"; import { ok, problem, raise } from "./outcomes.ts"; /** The OAuth helpers the provider injects into `env` for every non-API request. */ export function oauth(env: Env): OAuthHelpers { const helpers = (env as Env & { OAUTH_PROVIDER?: OAuthHelpers }).OAUTH_PROVIDER; if (!helpers) throw new Error("The OAuth provider is not wrapping this Worker."); return helpers; } async function settle(work: () => Promise): Promise> { try { return ok(await work()); } catch (error) { if (error instanceof AuthorizationError && error.redirectTo) return ok({ redirectTo: error.redirectTo, headers: new Headers() }); if (error instanceof AuthorizationError) return problem("invalid", error.description); if (error instanceof Error && !refsErrorCode(error)) return problem("invalid", error.message); throw error; } } /** Consent for an agent client asking, over OAuth, to act for the human signed in to this browser. */ export function openAgentConsent(env: Env, ctx: ExecutionContext, request: Request): AgentConsent { const helpers = oauth(env); async function person(): Promise { const { actor } = await resolveActor(env.DB, ctx, request); if (actor.kind !== "human" || actor.via !== "session") raise("sign_in_required", "Sign in to connect an agent."); return actor.person; } return { async begin() { const signedIn = await person(); return settle(async () => { const authRequest = await helpers.parseAuthRequest(request); const consent = await helpers.describeConsent(authRequest); const transaction = await helpers.beginConsent(authRequest); const view = { client: consent.clientName, redirectHost: consent.redirectHost, loopback: consent.redirectIsLoopback, git: authRequest.scope.includes("git"), person: { id: signedIn.id, name: signedIn.name }, handle: transaction.handle }; return { view, headers: transaction.headers }; }); }, async approve(handle) { const signedIn = await person(); return settle(async () => { const approved = await helpers.approveConsent(request, handle); const client = await helpers.lookupClient(approved.request.clientId); const { redirectTo } = await helpers.completeAuthorization({ request: approved.request, userId: signedIn.id, metadata: { client: client?.clientName ?? "Agent client" }, scope: approved.request.scope, props: { userId: signedIn.id }, }); return { redirectTo, headers: approved.headers }; }); }, async deny(handle) { await person(); return settle(async () => { const denied = await helpers.denyConsent(request, handle); return { redirectTo: denied.redirectTo, headers: denied.headers }; }); }, }; } export async function agentGrants(env: Env, userId: string): Promise { const { items } = await oauth(env).listUserGrants(userId); return items.map((grant) => ({ id: grant.id, client: String((grant.metadata as { client?: unknown } | null)?.client ?? grant.clientId), createdAt: grant.createdAt })); } export async function revokeAgentGrant(env: Env, userId: string, grantId: string): Promise { await oauth(env).revokeGrant(grantId, userId); }