Skip to content
refs
History
61 lines · 2.8 KBRaw
1import { AGENT_TOKEN_PREFIX, SESSION_COOKIE, accessTokenUser, agentSession, now, sessionUser, type AgentSessionRow, type User } from "./auth.ts";
2import type { Actor, Person } from "./contract/actor.ts";
3
4export function toPerson(user: User): Person {
5 return { id: user.id, name: user.name, email: user.email };
6}
7
8export function readCookie(request: Request, name: string): string | null {
9 for (const part of (request.headers.get("cookie") ?? "").split(";")) {
10 const [key, ...value] = part.trim().split("=");
11 if (key === name) return value.join("=");
12 }
13 return null;
14}
15
16export function bearerSecret(request: Request): string | null {
17 const header = request.headers.get("authorization");
18 if (header?.startsWith("Bearer ")) return header.slice(7).trim() || null;
19 if (!header?.startsWith("Basic ")) return null;
20 try {
21 const decoded = atob(header.slice(6));
22 return decoded.slice(decoded.indexOf(":") + 1) || null;
23 } catch {
24 return null;
25 }
26}
27
28/** 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. */
29export function agentActor(session: AgentSessionRow): Actor {
30 return {
31 kind: "agent",
32 agent: { id: session.id, name: session.runtime, runtime: session.runtime },
33 onBehalfOf: { id: session.user_id, name: session.name, email: session.email },
34 sessionId: session.id,
35 grant: {
36 repos: [{ name: session.repo_name, access: "write", branches: session.branch === null ? [] : [session.branch] }],
37 org: "none",
38 expiresAt: session.expires_at,
39 },
40 };
41}
42
43export type Resolved = { actor: Actor; badCredentials: boolean };
44
45/** Session cookies identify browsers; access tokens identify Git clients and API callers. */
46export async function resolveActor(db: D1Database, ctx: ExecutionContext, request: Request): Promise<Resolved> {
47 const secret = bearerSecret(request);
48 if (secret?.startsWith(AGENT_TOKEN_PREFIX)) {
49 const session = await agentSession(db, secret);
50 return session ? { actor: agentActor(session), badCredentials: false } : { actor: { kind: "anonymous" }, badCredentials: true };
51 }
52 if (secret) {
53 const user = await accessTokenUser(db, secret);
54 if (!user) return { actor: { kind: "anonymous" }, badCredentials: true };
55 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());
56 return { actor: { kind: "human", person: toPerson(user), via: "token" }, badCredentials: false };
57 }
58 const session = readCookie(request, SESSION_COOKIE);
59 const user = session ? await sessionUser(db, session) : null;
60 return { actor: user ? { kind: "human", person: toPerson(user), via: "session" } : { kind: "anonymous" }, badCredentials: false };
61}