import { batch, first, run, stmt } from "../db"; import { randomId, randomToken, sha256Hex } from "../crypto"; import { PAT_PREFIX } from "../auth"; import { assertBelowCap, CAPS } from "../limits"; import type { TokenPermissions } from "../token-scope"; const VISIBLE_TOKEN_CHARS = 6; /** OAuth-issued tokens are tracked separately so agents cannot crowd out a user's personal tokens. */ const OAUTH_TOKENS_PER_USER = 100; export type GrantSpec = { permissions: TokenPermissions; allRepos: boolean; repoIds: string[]; agent: string; }; export type MintedToken = { id: string; token: string; expiresAt: number | null }; /** * Issues an ordinary fine-grained personal access token (`access_tokens` + `access_token_repos`) and * records the agent it belongs to, so OAuth grants inherit every existing permission check unchanged. */ export async function mintFineGrainedToken(input: { userId: string; name: string; scopes: string; grant: GrantSpec; ttlMs: number | null; clientId: string | null; /** Set for tokens delegated by another token; they are revoked along with it. */ parentTokenId?: string; /** Hard ceiling on the expiry, e.g. the delegating token's own expiry. */ notAfter?: number | null; }): Promise { const oauth = input.scopes.startsWith("oauth:") || input.parentTokenId !== undefined; const count = await first<{ count: number }>( oauth ? "SELECT COUNT(*) AS count FROM access_tokens WHERE user_id = ? AND scopes LIKE 'oauth:%' AND (expires_at IS NULL OR expires_at > ?)" : "SELECT COUNT(*) AS count FROM access_tokens WHERE user_id = ? AND (expires_at IS NULL OR expires_at > ?)", input.userId, Date.now(), ); assertBelowCap(count?.count ?? 0, oauth ? OAUTH_TOKENS_PER_USER : CAPS.tokensPerUser, "tokens"); const id = randomId(); const token = randomToken(PAT_PREFIX); const now = Date.now(); const requested = input.ttlMs === null ? null : now + input.ttlMs; const ceiling = input.notAfter ?? null; const expiresAt = ceiling === null ? requested : Math.min(requested ?? ceiling, ceiling); await batch([ stmt( `INSERT INTO access_tokens (id, user_id, name, token_hash, token_prefix, scopes, permissions, all_repos, expires_at, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, id, input.userId, input.name.slice(0, 100), await sha256Hex(token), token.slice(0, PAT_PREFIX.length + 1 + VISIBLE_TOKEN_CHARS), input.scopes, JSON.stringify(input.grant.permissions), input.grant.allRepos ? 1 : 0, expiresAt, now, ), ...input.grant.repoIds.map((repoId) => stmt("INSERT INTO access_token_repos (token_id, repo_id) VALUES (?, ?)", id, repoId), ), stmt( `INSERT INTO mcp_token_agents (token_id, agent_name, client_id, authorized_by, parent_token_id, created_at) VALUES (?, ?, ?, ?, ?, ?)`, id, input.grant.agent.slice(0, 100), input.clientId, input.userId, input.parentTokenId ?? null, now, ), ]); return { id, token, expiresAt }; } /** The access_tokens trigger also drops the token's refresh tokens and every token it delegated. */ export async function deleteAccessToken(tokenId: string, userId: string): Promise { await run("DELETE FROM access_tokens WHERE id = ? AND user_id = ?", tokenId, userId); } /** * Refreshing an OAuth grant rotates the secret of its single access_tokens row in place, so the grant * keeps its id (sessions, claims and delegations stay attached) and the old secret stops working. * `successor` (the new refresh token insert) runs in the same transaction; its foreign key makes the * whole rotation fail if the grant was revoked meanwhile. */ export async function rotateAccessToken( tokenId: string, userId: string, repoIds: string[], ttlMs: number, successor: D1PreparedStatement, ): Promise { const token = randomToken(PAT_PREFIX); const expiresAt = Date.now() + ttlMs; await batch([ stmt( "UPDATE access_tokens SET token_hash = ?, token_prefix = ?, expires_at = ? WHERE id = ? AND user_id = ?", await sha256Hex(token), token.slice(0, PAT_PREFIX.length + 1 + VISIBLE_TOKEN_CHARS), expiresAt, tokenId, userId, ), stmt("DELETE FROM access_token_repos WHERE token_id = ?", tokenId), ...repoIds.map((repoId) => stmt("INSERT INTO access_token_repos (token_id, repo_id) VALUES (?, ?)", tokenId, repoId), ), successor, ]); return { id: tokenId, token, expiresAt }; } export type TokenLineage = { parent_token_id: string | null; /** When the grant can last until: a PAT's expiry, or an OAuth grant's live refresh token expiry. */ lifetime_ends_at: number | null; }; export async function tokenLineage(tokenId: string): Promise { return first( `SELECT m.parent_token_id, CASE WHEN t.scopes LIKE 'oauth:%' THEN COALESCE( (SELECT MAX(r.expires_at) FROM oauth_refresh_tokens r WHERE r.access_token_id = t.id AND r.used_at IS NULL), t.expires_at) ELSE t.expires_at END AS lifetime_ends_at FROM access_tokens t LEFT JOIN mcp_token_agents m ON m.token_id = t.id WHERE t.id = ?`, tokenId, ); } /** Drops expired OAuth tokens whose grant can no longer be refreshed. */ export async function purgeExpiredOAuthTokens(userId: string): Promise { const now = Date.now(); await run( `DELETE FROM access_tokens WHERE user_id = ? AND scopes LIKE 'oauth:%' AND expires_at IS NOT NULL AND expires_at < ? AND NOT EXISTS (SELECT 1 FROM oauth_refresh_tokens r WHERE r.access_token_id = access_tokens.id AND r.used_at IS NULL AND r.expires_at > ?)`, userId, now, now, ); } export async function agentForToken( tokenId: string, ): Promise<{ agent_name: string; client_id: string | null; authorized_by: string } | null> { return first("SELECT agent_name, client_id, authorized_by FROM mcp_token_agents WHERE token_id = ?", tokenId); }