83 lines · 3.6 KBRaw
| 1 | import { AuthorizationError, type OAuthHelpers } from "@cloudflare/workers-oauth-provider"; |
| 2 | import type { Person } from "./contract/actor.ts"; |
| 3 | import type { Outcome } from "./contract/common.ts"; |
| 4 | import { refsErrorCode } from "./contract/errors.ts"; |
| 5 | import type { AgentConsent } from "./contract/handles.ts"; |
| 6 | import type { AgentGrant } from "./contract/views.ts"; |
| 7 | import { resolveActor } from "./identity.ts"; |
| 8 | import { ok, problem, raise } from "./outcomes.ts"; |
| 9 | |
| 10 | /** The OAuth helpers the provider injects into `env` for every non-API request. */ |
| 11 | export function oauth(env: Env): OAuthHelpers { |
| 12 | const helpers = (env as Env & { OAUTH_PROVIDER?: OAuthHelpers }).OAUTH_PROVIDER; |
| 13 | if (!helpers) throw new Error("The OAuth provider is not wrapping this Worker."); |
| 14 | return helpers; |
| 15 | } |
| 16 | |
| 17 | async function settle<T>(work: () => Promise<T>): Promise<Outcome<T | { redirectTo: string; headers: Headers }>> { |
| 18 | try { |
| 19 | return ok(await work()); |
| 20 | } catch (error) { |
| 21 | if (error instanceof AuthorizationError && error.redirectTo) return ok({ redirectTo: error.redirectTo, headers: new Headers() }); |
| 22 | if (error instanceof AuthorizationError) return problem("invalid", error.description); |
| 23 | if (error instanceof Error && !refsErrorCode(error)) return problem("invalid", error.message); |
| 24 | throw error; |
| 25 | } |
| 26 | } |
| 27 | |
| 28 | /** Consent for an agent client asking, over OAuth, to act for the human signed in to this browser. */ |
| 29 | export function openAgentConsent(env: Env, ctx: ExecutionContext, request: Request): AgentConsent { |
| 30 | const helpers = oauth(env); |
| 31 | |
| 32 | async function person(): Promise<Person> { |
| 33 | const { actor } = await resolveActor(env.DB, ctx, request); |
| 34 | if (actor.kind !== "human" || actor.via !== "session") raise("sign_in_required", "Sign in to connect an agent."); |
| 35 | return actor.person; |
| 36 | } |
| 37 | |
| 38 | return { |
| 39 | async begin() { |
| 40 | const signedIn = await person(); |
| 41 | return settle(async () => { |
| 42 | const authRequest = await helpers.parseAuthRequest(request); |
| 43 | const consent = await helpers.describeConsent(authRequest); |
| 44 | const transaction = await helpers.beginConsent(authRequest); |
| 45 | const view = { client: consent.clientName, redirectHost: consent.redirectHost, loopback: consent.redirectIsLoopback, person: { id: signedIn.id, name: signedIn.name }, handle: transaction.handle }; |
| 46 | return { view, headers: transaction.headers }; |
| 47 | }); |
| 48 | }, |
| 49 | |
| 50 | async approve(handle) { |
| 51 | const signedIn = await person(); |
| 52 | return settle(async () => { |
| 53 | const approved = await helpers.approveConsent(request, handle); |
| 54 | const client = await helpers.lookupClient(approved.request.clientId); |
| 55 | const { redirectTo } = await helpers.completeAuthorization({ |
| 56 | request: approved.request, |
| 57 | userId: signedIn.id, |
| 58 | metadata: { client: client?.clientName ?? "Agent client" }, |
| 59 | scope: approved.request.scope, |
| 60 | props: { userId: signedIn.id }, |
| 61 | }); |
| 62 | return { redirectTo, headers: approved.headers }; |
| 63 | }); |
| 64 | }, |
| 65 | |
| 66 | async deny(handle) { |
| 67 | await person(); |
| 68 | return settle(async () => { |
| 69 | const denied = await helpers.denyConsent(request, handle); |
| 70 | return { redirectTo: denied.redirectTo, headers: denied.headers }; |
| 71 | }); |
| 72 | }, |
| 73 | }; |
| 74 | } |
| 75 | |
| 76 | export async function agentGrants(env: Env, userId: string): Promise<AgentGrant[]> { |
| 77 | const { items } = await oauth(env).listUserGrants(userId); |
| 78 | return items.map((grant) => ({ id: grant.id, client: String((grant.metadata as { client?: unknown } | null)?.client ?? grant.clientId), createdAt: grant.createdAt })); |
| 79 | } |
| 80 | |
| 81 | export async function revokeAgentGrant(env: Env, userId: string, grantId: string): Promise<void> { |
| 82 | await oauth(env).revokeGrant(grantId, userId); |
| 83 | } |