79 lines · 4.0 KBRaw
| 1 | import type { OAuthHelpers } from "@cloudflare/workers-oauth-provider"; |
| 2 | import { AGENT_TOKEN_PREFIX, SESSION_COOKIE, accessTokenUser, agentSession, now, sessionUser, type AgentSessionRow, type User } from "./auth.ts"; |
| 3 | import type { Actor, Person } from "./contract/actor.ts"; |
| 4 | |
| 5 | export function toPerson(user: User): Person { |
| 6 | return { id: user.id, name: user.name, email: user.email }; |
| 7 | } |
| 8 | |
| 9 | export function readCookie(request: Request, name: string): string | null { |
| 10 | for (const part of (request.headers.get("cookie") ?? "").split(";")) { |
| 11 | const [key, ...value] = part.trim().split("="); |
| 12 | if (key === name) return value.join("="); |
| 13 | } |
| 14 | return null; |
| 15 | } |
| 16 | |
| 17 | export function bearerSecret(request: Request): string | null { |
| 18 | const header = request.headers.get("authorization"); |
| 19 | if (header?.startsWith("Bearer ")) return header.slice(7).trim() || null; |
| 20 | if (!header?.startsWith("Basic ")) return null; |
| 21 | try { |
| 22 | const decoded = atob(header.slice(6)); |
| 23 | return decoded.slice(decoded.indexOf(":") + 1) || null; |
| 24 | } catch { |
| 25 | return null; |
| 26 | } |
| 27 | } |
| 28 | |
| 29 | /** A session token reads its repository as its human, and writes only its current branch. A session without one may claim a new branch by pushing it. */ |
| 30 | export function agentActor(session: AgentSessionRow): Actor { |
| 31 | return { |
| 32 | kind: "agent", |
| 33 | agent: { id: session.id, name: session.runtime, runtime: session.runtime }, |
| 34 | onBehalfOf: { id: session.user_id, name: session.name, email: session.email }, |
| 35 | sessionId: session.id, |
| 36 | grant: { |
| 37 | repos: [{ name: session.repo_name, access: "write", branches: session.branch === null ? [] : [session.branch] }], |
| 38 | org: "none", |
| 39 | expiresAt: session.expires_at, |
| 40 | }, |
| 41 | }; |
| 42 | } |
| 43 | |
| 44 | export type Resolved = { actor: Actor; badCredentials: boolean }; |
| 45 | |
| 46 | /** The refs CLI's sign-in token, when its grant includes the `git` scope: the human, for Git only. */ |
| 47 | async function cliUser(db: D1Database, oauth: OAuthHelpers, secret: string): Promise<User | null> { |
| 48 | const token = await oauth.unwrapToken<{ userId?: string }>(secret).catch(() => null); |
| 49 | if (!token?.grant.scope.includes("git") || !token.grant.props?.userId) return null; |
| 50 | return db.prepare("SELECT id, name, email FROM users WHERE id = ?1 AND status = 'active'").bind(token.grant.props.userId).first<User>(); |
| 51 | } |
| 52 | |
| 53 | function markSeen(db: D1Database, ctx: ExecutionContext, userId: string): void { |
| 54 | ctx.waitUntil(db.prepare("UPDATE users SET last_seen_at = ?1 WHERE id = ?2 AND (last_seen_at IS NULL OR last_seen_at < ?1 - 300)").bind(now(), userId).run()); |
| 55 | } |
| 56 | |
| 57 | /** Session cookies identify browsers; access tokens identify Git clients and API callers. With `oauth`, the refs CLI's sign-in token works too. */ |
| 58 | export async function resolveActor(db: D1Database, ctx: ExecutionContext, request: Request, oauth?: OAuthHelpers): Promise<Resolved> { |
| 59 | const secret = bearerSecret(request); |
| 60 | if (oauth && secret?.split(":").length === 3) { |
| 61 | const user = await cliUser(db, oauth, secret); |
| 62 | return user ? { actor: { kind: "human", person: toPerson(user), via: "cli" }, badCredentials: false } : { actor: { kind: "anonymous" }, badCredentials: true }; |
| 63 | } |
| 64 | if (secret?.startsWith(AGENT_TOKEN_PREFIX)) { |
| 65 | const session = await agentSession(db, secret); |
| 66 | return session ? { actor: agentActor(session), badCredentials: false } : { actor: { kind: "anonymous" }, badCredentials: true }; |
| 67 | } |
| 68 | if (secret) { |
| 69 | const user = await accessTokenUser(db, secret); |
| 70 | if (!user) return { actor: { kind: "anonymous" }, badCredentials: true }; |
| 71 | ctx.waitUntil(db.prepare("UPDATE access_tokens SET last_used_at = ?1 WHERE id = ?2 AND (last_used_at IS NULL OR last_used_at < ?1 - 60)").bind(now(), user.token_id).run()); |
| 72 | markSeen(db, ctx, user.id); |
| 73 | return { actor: { kind: "human", person: toPerson(user), via: "token" }, badCredentials: false }; |
| 74 | } |
| 75 | const session = readCookie(request, SESSION_COOKIE); |
| 76 | const user = session ? await sessionUser(db, session) : null; |
| 77 | if (user) markSeen(db, ctx, user.id); |
| 78 | return { actor: user ? { kind: "human", person: toPerson(user), via: "session" } : { kind: "anonymous" }, badCredentials: false }; |
| 79 | } |