import { Hono } from "hono"; import { describeRoute, validator } from "hono-openapi"; import { generatePat, normalizeScopes } from "@/worker/auth/pats"; import { authObject } from "@/worker/auth/session-cookie"; import { createControlPlaneDb } from "@/worker/db/d1/client"; import type { PatProjectionRow } from "@/worker/db/d1/schema"; import { createPatProjection, getPatProjection, listPatProjections, updatePatProjection, } from "@/worker/db/d1/repository"; import { PatCreateRequestSchema, PatCreateResponseSchema, PatPatchRequestSchema, PatResponseSchema, } from "@/worker/openapi/schemas"; import { describeJson, jsonErrorResponse } from "@/worker/routes/api/openapi"; import { msToIso, requireSession } from "@/worker/routes/api/session"; import type { AppEnv } from "@/worker/types"; import { safeAudit } from "@/worker/util/audit"; import { jsonError } from "@/worker/util/response"; function patResponse(row: PatProjectionRow) { return { id: row.id, name: row.name, scopes: row.scopes, created_at: new Date(row.createdAtMs).toISOString(), expires_at: msToIso(row.expiresAtMs), revoked_at: msToIso(row.revokedAtMs), last_used_at: msToIso(row.lastUsedAtMs), }; } function parseExpiresAt(value: string | null | undefined): number | null { if (value === null || value === undefined) return null; const parsed = Date.parse(value); if (!Number.isFinite(parsed)) throw new Error("Invalid expires_at"); return parsed; } export function createPatApiRoutes(): Hono { const api = new Hono(); api.get("/", describeJson("List Personal Access Tokens", "pats", PatResponseSchema.array()), async (c) => { const session = requireSession(c); const rows = await listPatProjections(createControlPlaneDb(c.env.DAV_CONTROL_PLANE), session.subjectId); return c.json(rows.map(patResponse)); }); api.post( "/", describeJson("Create Personal Access Token", "pats", PatCreateResponseSchema, 201), validator("json", PatCreateRequestSchema), async (c) => { const session = requireSession(c); const body = c.req.valid("json"); const scopes = normalizeScopes(body.scopes); if (!scopes || scopes.length === 0) return jsonError("invalid_pat_scopes", "PAT scopes are invalid.", 400); let expiresAtMs: number | null; try { expiresAtMs = parseExpiresAt(body.expires_at); } catch { return jsonError("invalid_expires_at", "expires_at must be an ISO datetime.", 400); } const generated = await generatePat(); const nowMs = Date.now(); const pat = await authObject(c.env, session.storageId).createPat({ id: generated.id, name: body.name, tokenDigest: generated.tokenDigest, scopes, createdAtMs: nowMs, expiresAtMs, revokedAtMs: null, lastUsedAtMs: null, }); await createPatProjection(createControlPlaneDb(c.env.DAV_CONTROL_PLANE), { id: pat.id, subjectId: session.subjectId, name: pat.name, scopes: pat.scopes, createdAtMs: pat.createdAtMs, expiresAtMs: pat.expiresAtMs, revokedAtMs: pat.revokedAtMs, lastUsedAtMs: pat.lastUsedAtMs, }); await safeAudit(c, { subjectId: session.subjectId, actorSubjectId: session.subjectId, eventType: "pat.create", data: { patId: pat.id, scopes: pat.scopes }, createdAtMs: nowMs, }); return c.json({ ...patResponse({ ...pat, subjectId: session.subjectId }), token: generated.token }, 201); }, ); api.get("/:pat_id", describeJson("Get Personal Access Token", "pats", PatResponseSchema), async (c) => { const session = requireSession(c); const row = await getPatProjection( createControlPlaneDb(c.env.DAV_CONTROL_PLANE), session.subjectId, c.req.param("pat_id"), ); if (!row) return jsonError("not_found", "PAT not found.", 404); return c.json(patResponse(row)); }); api.patch( "/:pat_id", describeJson("Update Personal Access Token", "pats", PatResponseSchema), validator("json", PatPatchRequestSchema), async (c) => { const session = requireSession(c); const patId = c.req.param("pat_id"); const existing = await getPatProjection(createControlPlaneDb(c.env.DAV_CONTROL_PLANE), session.subjectId, patId); if (!existing) return jsonError("not_found", "PAT not found.", 404); let expiresAtMs: number | null | undefined; try { const body = c.req.valid("json"); expiresAtMs = body.expires_at === undefined ? undefined : parseExpiresAt(body.expires_at); await authObject(c.env, session.storageId).updatePat({ patId, name: body.name, expiresAtMs }); await updatePatProjection(createControlPlaneDb(c.env.DAV_CONTROL_PLANE), session.subjectId, patId, { name: body.name, expiresAtMs, }); await safeAudit(c, { subjectId: session.subjectId, actorSubjectId: session.subjectId, eventType: "pat.update", data: { patId }, }); } catch { return jsonError("invalid_pat_update", "PAT update payload is invalid.", 400); } const row = await getPatProjection(createControlPlaneDb(c.env.DAV_CONTROL_PLANE), session.subjectId, patId); return c.json(patResponse(row ?? existing)); }, ); api.delete( "/:pat_id", describeRoute({ summary: "Revoke Personal Access Token", tags: ["pats"], responses: { 204: { description: "PAT revoked" }, 404: jsonErrorResponse }, }), async (c) => { const session = requireSession(c); const patId = c.req.param("pat_id"); const existing = await getPatProjection(createControlPlaneDb(c.env.DAV_CONTROL_PLANE), session.subjectId, patId); if (!existing) return jsonError("not_found", "PAT not found.", 404); const nowMs = Date.now(); await authObject(c.env, session.storageId).updatePat({ patId, revokedAtMs: nowMs }); await updatePatProjection(createControlPlaneDb(c.env.DAV_CONTROL_PLANE), session.subjectId, patId, { revokedAtMs: nowMs, }); await safeAudit(c, { subjectId: session.subjectId, actorSubjectId: session.subjectId, eventType: "pat.revoke", data: { patId }, createdAtMs: nowMs, }); return new Response(null, { status: 204 }); }, ); return api; }