import { first, run } from "./db"; import { sha256Hex } from "./crypto"; export type AuthTokenKind = "email-verify" | "password-reset" | "webauthn" | "pending-login" | "editor-session"; type Row = { user_id: string | null; payload: string; created_at: number }; export type ConsumedToken = { userId: string | null; payload: string; createdAt: number }; /** Stores single-use state keyed by the hash of a secret token. */ export async function storeAuthToken( kind: AuthTokenKind, token: string, userId: string | null, payload: string, ttlSeconds: number, ): Promise { const now = Date.now(); await run( "INSERT INTO auth_tokens (token_hash, kind, user_id, payload, created_at, expires_at) VALUES (?, ?, ?, ?, ?, ?)", await sha256Hex(token), kind, userId, payload, now, now + ttlSeconds * 1000, ); } /** Atomically consumes a token: concurrent callers can't both succeed. */ export async function consumeAuthToken(kind: AuthTokenKind, token: string): Promise { const row = await first( "DELETE FROM auth_tokens WHERE token_hash = ? AND kind = ? AND expires_at > ? RETURNING user_id, payload, created_at", await sha256Hex(token), kind, Date.now(), ); return row ? { userId: row.user_id, payload: row.payload, createdAt: row.created_at } : null; } /** Counts an attempt against a token, returning it only while under `maxAttempts`. */ export async function attemptAuthToken( kind: AuthTokenKind, token: string, maxAttempts: number, ): Promise { const row = await first( `UPDATE auth_tokens SET attempts = attempts + 1 WHERE token_hash = ? AND kind = ? AND expires_at > ? AND attempts < ? RETURNING user_id, payload, created_at`, await sha256Hex(token), kind, Date.now(), maxAttempts, ); return row ? { userId: row.user_id, payload: row.payload, createdAt: row.created_at } : null; } export async function peekAuthToken( kind: AuthTokenKind, token: string, maxAttempts: number, ): Promise { const row = await first( "SELECT user_id, payload, created_at FROM auth_tokens WHERE token_hash = ? AND kind = ? AND expires_at > ? AND attempts < ?", await sha256Hex(token), kind, Date.now(), maxAttempts, ); return row ? { userId: row.user_id, payload: row.payload, createdAt: row.created_at } : null; } export async function deleteAuthToken(kind: AuthTokenKind, token: string): Promise { await run("DELETE FROM auth_tokens WHERE token_hash = ? AND kind = ?", await sha256Hex(token), kind); } /** Invalidates outstanding tokens of one kind for a user (e.g. older email-change links). */ export async function revokeUserAuthTokens(kind: AuthTokenKind, userId: string): Promise { await run("DELETE FROM auth_tokens WHERE kind = ? AND user_id = ?", kind, userId); } export async function purgeExpiredAuthTokens(): Promise { await run("DELETE FROM auth_tokens WHERE expires_at < ?", Date.now()); }