154 lines · 7.1 KBRaw
| 1 | import { MIN_PASSWORD_LENGTH, SESSION_COOKIE } from "./contract/limits.ts"; |
| 2 | |
| 3 | export type Role = "owner" | "admin" | "member"; |
| 4 | |
| 5 | export interface User { |
| 6 | id: string; |
| 7 | email: string; |
| 8 | name: string; |
| 9 | } |
| 10 | |
| 11 | export { SESSION_COOKIE }; |
| 12 | export const SESSION_TTL_SECONDS = 60 * 60 * 24 * 30; |
| 13 | |
| 14 | const PBKDF2_ITERATIONS = 100_000; |
| 15 | const DUMMY_PASSWORD_HASH = `pbkdf2-sha256$${PBKDF2_ITERATIONS}$${"00".repeat(16)}$${"00".repeat(32)}`; |
| 16 | const encoder = new TextEncoder(); |
| 17 | |
| 18 | type WorkersSubtleCrypto = SubtleCrypto & { timingSafeEqual(a: ArrayBufferView, b: ArrayBufferView): boolean }; |
| 19 | |
| 20 | export function now(): number { |
| 21 | return Math.floor(Date.now() / 1000); |
| 22 | } |
| 23 | |
| 24 | function hex(bytes: ArrayBuffer | Uint8Array): string { |
| 25 | return Array.from(new Uint8Array(bytes), (b) => b.toString(16).padStart(2, "0")).join(""); |
| 26 | } |
| 27 | |
| 28 | function fromHex(value: string): Uint8Array<ArrayBuffer> { |
| 29 | return Uint8Array.from(value.match(/../g) ?? [], (pair) => parseInt(pair, 16)); |
| 30 | } |
| 31 | |
| 32 | export function randomToken(bytes = 32): string { |
| 33 | return hex(crypto.getRandomValues(new Uint8Array(bytes))); |
| 34 | } |
| 35 | |
| 36 | export async function sha256(value: string): Promise<string> { |
| 37 | return hex(await crypto.subtle.digest("SHA-256", encoder.encode(value))); |
| 38 | } |
| 39 | |
| 40 | async function pbkdf2(password: string, salt: Uint8Array<ArrayBuffer>, iterations: number): Promise<Uint8Array> { |
| 41 | const key = await crypto.subtle.importKey("raw", encoder.encode(password), "PBKDF2", false, ["deriveBits"]); |
| 42 | const bits = await crypto.subtle.deriveBits({ name: "PBKDF2", hash: "SHA-256", salt, iterations }, key, 256); |
| 43 | return new Uint8Array(bits); |
| 44 | } |
| 45 | |
| 46 | export async function hashPassword(password: string): Promise<string> { |
| 47 | const salt = crypto.getRandomValues(new Uint8Array(16)); |
| 48 | const hash = await pbkdf2(password, salt, PBKDF2_ITERATIONS); |
| 49 | return `pbkdf2-sha256$${PBKDF2_ITERATIONS}$${hex(salt)}$${hex(hash)}`; |
| 50 | } |
| 51 | |
| 52 | export async function verifyPassword(password: string, stored: string | undefined): Promise<boolean> { |
| 53 | const [scheme, iterations, salt, expected] = (stored ?? DUMMY_PASSWORD_HASH).split("$"); |
| 54 | if (scheme !== "pbkdf2-sha256") return false; |
| 55 | const actual = await pbkdf2(password, fromHex(salt), Number(iterations)); |
| 56 | const wanted = fromHex(expected); |
| 57 | return stored !== undefined && actual.length === wanted.length && (crypto.subtle as WorkersSubtleCrypto).timingSafeEqual(actual, wanted); |
| 58 | } |
| 59 | |
| 60 | export async function createSession(db: D1Database, userId: string): Promise<string> { |
| 61 | const token = randomToken(); |
| 62 | await db.batch([ |
| 63 | db.prepare("DELETE FROM sessions WHERE expires_at < ?").bind(now()), |
| 64 | db.prepare("INSERT INTO sessions (token_hash, user_id, expires_at) VALUES (?, ?, ?)").bind(await sha256(token), userId, now() + SESSION_TTL_SECONDS), |
| 65 | ]); |
| 66 | return token; |
| 67 | } |
| 68 | |
| 69 | export async function sessionUser(db: D1Database, token: string): Promise<User | null> { |
| 70 | return db |
| 71 | .prepare("SELECT u.id, u.email, u.name FROM sessions s JOIN users u ON u.id = s.user_id WHERE s.token_hash = ? AND s.expires_at > ? AND u.status = 'active'") |
| 72 | .bind(await sha256(token), now()) |
| 73 | .first<User>(); |
| 74 | } |
| 75 | |
| 76 | export async function deleteSession(db: D1Database, token: string): Promise<void> { |
| 77 | await db.prepare("DELETE FROM sessions WHERE token_hash = ?").bind(await sha256(token)).run(); |
| 78 | } |
| 79 | |
| 80 | export async function createAccessToken(db: D1Database, userId: string, name: string): Promise<string> { |
| 81 | const token = `refs_${randomToken(20)}`; |
| 82 | await db |
| 83 | .prepare("INSERT INTO access_tokens (id, user_id, name, token_hash, created_at) VALUES (?, ?, ?, ?, ?)") |
| 84 | .bind(crypto.randomUUID(), userId, name, await sha256(token), now()) |
| 85 | .run(); |
| 86 | return token; |
| 87 | } |
| 88 | |
| 89 | export async function accessTokenUser(db: D1Database, token: string): Promise<(User & { token_id: string }) | null> { |
| 90 | return db |
| 91 | .prepare("SELECT u.id, u.email, u.name, t.id AS token_id FROM access_tokens t JOIN users u ON u.id = t.user_id WHERE t.token_hash = ? AND u.status = 'active'") |
| 92 | .bind(await sha256(token)) |
| 93 | .first(); |
| 94 | } |
| 95 | |
| 96 | export const AGENT_TOKEN_PREFIX = "refs_agent_"; |
| 97 | export const AGENT_SESSION_TTL_SECONDS = 60 * 60 * 12; |
| 98 | |
| 99 | export interface AgentSessionRow { |
| 100 | id: string; |
| 101 | runtime: string; |
| 102 | expires_at: number; |
| 103 | /** The one branch the session may push, or null while it has none. */ |
| 104 | branch: string | null; |
| 105 | repo_id: string; |
| 106 | repo_name: string; |
| 107 | user_id: string; |
| 108 | email: string; |
| 109 | name: string; |
| 110 | } |
| 111 | |
| 112 | export async function createAgentSession(db: D1Database, input: { userId: string; repoId: string; runtime: string; mcpSession: string | null; clientSession: string | null; machine: string | null; parent: string | null; grantId: string | null }): Promise<{ id: string; token: string; expiresAt: number; insert: D1PreparedStatement }> { |
| 113 | const id = crypto.randomUUID(); |
| 114 | const token = `${AGENT_TOKEN_PREFIX}${randomToken(20)}`; |
| 115 | const at = now(); |
| 116 | const expiresAt = at + AGENT_SESSION_TTL_SECONDS; |
| 117 | const insert = db |
| 118 | .prepare("INSERT INTO agent_sessions (id, token_hash, user_id, repo_id, runtime, created_at, expires_at, last_seen_at, mcp_session, client_session, machine, parent_session, grant_id) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)") |
| 119 | .bind(id, await sha256(token), input.userId, input.repoId, input.runtime, at, expiresAt, at, input.mcpSession, input.clientSession, input.machine, input.parent, input.grantId); |
| 120 | return { id, token, expiresAt, insert }; |
| 121 | } |
| 122 | |
| 123 | /** Replaces a session's git token, so only the newest copy works. */ |
| 124 | export async function rotateAgentToken(db: D1Database, sessionId: string): Promise<string> { |
| 125 | const token = `${AGENT_TOKEN_PREFIX}${randomToken(20)}`; |
| 126 | await db.prepare("UPDATE agent_sessions SET token_hash = ? WHERE id = ? AND ended_at IS NULL").bind(await sha256(token), sessionId).run(); |
| 127 | return token; |
| 128 | } |
| 129 | |
| 130 | const SELECT_AGENT_SESSION = |
| 131 | "SELECT s.id, s.runtime, s.expires_at, s.branch, r.id AS repo_id, (SELECT slug FROM namespaces WHERE id = r.namespace_id) || '/' || r.name AS repo_name, u.id AS user_id, u.email, u.name FROM agent_sessions s JOIN users u ON u.id = s.user_id JOIN repos r ON r.id = s.repo_id"; |
| 132 | |
| 133 | export async function agentSession(db: D1Database, token: string): Promise<AgentSessionRow | null> { |
| 134 | return db.prepare(`${SELECT_AGENT_SESSION} WHERE s.token_hash = ? AND s.ended_at IS NULL AND s.expires_at > ? AND u.status = 'active'`).bind(await sha256(token), now()).first<AgentSessionRow>(); |
| 135 | } |
| 136 | |
| 137 | /** A session by id, live or ended, for attributing work it started before it ended. */ |
| 138 | export async function agentSessionById(db: D1Database, id: string): Promise<AgentSessionRow | null> { |
| 139 | return db.prepare(`${SELECT_AGENT_SESSION} WHERE s.id = ?`).bind(id).first<AgentSessionRow>(); |
| 140 | } |
| 141 | |
| 142 | export const EMAIL_PATTERN = /^[^\s@]+@[^\s@]+$/; |
| 143 | |
| 144 | export function accountError(name: string, password: ReturnType<FormData["get"]>): string | undefined { |
| 145 | if (!name || name.length > 64) return "Name must be 1–64 characters."; |
| 146 | if (typeof password !== "string" || password.length < MIN_PASSWORD_LENGTH) return `Password must be at least ${MIN_PASSWORD_LENGTH} characters.`; |
| 147 | } |
| 148 | |
| 149 | export async function pendingInvite(db: D1Database, token: string): Promise<{ email: string; role: Role; namespace_id: string } | null> { |
| 150 | return db |
| 151 | .prepare("SELECT email, role, namespace_id FROM invitations WHERE token_hash = ? AND status = 'pending' AND expires_at > ?") |
| 152 | .bind(await sha256(token), now()) |
| 153 | .first(); |
| 154 | } |