Repository Public
1import { z } from "zod";2import { ApiError, body, clientIp, readBody } from "../http";3import { audit } from "../audit";4import { rateLimit } from "../ratelimit";5import type { UserContext } from "../auth";6import type { RouteDef } from "./router";7import { emptySheet, FORMATS, LOCALES, mustParseSheet, stableStringify, THEMES, TONES } from "@/schema";8import { BriefSchema, OutlineSchema } from "@/ai/prompts";9import { listModels } from "@/ai/client";10import { priceOf } from "@/ai/pricing";11import { sanitizeSvg } from "@/renderer/sanitize-svg";12import { buildTemplate, findTemplate, TEMPLATES } from "@/templates";13import { createAsset, datasetRows, deleteAsset, getAssetRow, listAssets, readAsset, updateAsset } from "@/server/assets";14import { ExportRequest, getExport, listExports, requestExport } from "@/server/exports";15import { cancelJob, enqueueJob, getJob, listJobs } from "@/server/jobs";16import { adminTopics, conversation, createPreviewLink, customTemplateDoc, dashboard, deleteCustomTemplate, deleteTopic, listAudit, listCustomTemplates, revokePreviewLinks, saveAsTemplate, updateTopic } from "@/server/misc";17import { qualityReport } from "@/server/quality";18import { getSettings, setSettings, SettingsSchema } from "@/server/settings";19import { createSheet, deleteSheet, getRevision, getSheetDetail, listRevisions, listSheets, publish, revertTo, saveDoc, unpublish, updateSettings, validDoc } from "@/server/sheets";20import { env } from "../env";2122type Ctx = UserContext;23const id = (v: string) => z.string().uuid().parse(v);24const page = (url: URL, max = 100) => ({ limit: Math.min(max, Math.max(1, Number(url.searchParams.get("limit") ?? 30) || 30)), offset: Math.max(0, Number(url.searchParams.get("offset") ?? 0) || 0) });25const slug = z.string().regex(/^[a-z0-9]+(?:-[a-z0-9]+)*$/).max(96);26const idem = z.string().min(8).max(80).optional();2728/** Largest JSON body accepted for a document (a full sheet is typically 20–80 kB). */29const MAX_DOC_BYTES = 2_000_000;30function assertSmall(req: Request, max: number) {31 const len = Number(req.headers.get("content-length") ?? 0);32 if (len > max) throw new ApiError(413, "payload_too_large", "The request body is too large");33}3435/**36 * /api/admin/* — every route below runs behind requireAdmin (passkey session; CSRF header + same-origin check on37 * anything that is not a GET). Inputs are validated with Zod; documents with the Sheet schema.38 */39export const adminRoutes: RouteDef<Ctx>[] = [40 ["GET", "dashboard", async () => dashboard()],4142 // ── Sheets ────────────────────────────────────────────────────────────────────────────────────────43 ["GET", "sheets", async ({ url }) => listSheets({ ...page(url), status: z.enum(["draft", "in_review", "published", "archived"]).optional().parse(url.searchParams.get("status") ?? undefined), search: url.searchParams.get("q")?.slice(0, 120) || undefined })],44 ["POST", "sheets", async ({ req, ctx }) => {45 assertSmall(req, MAX_DOC_BYTES);46 const b = await body(req, z.object({ title: z.string().min(1).max(160).optional(), locale: z.enum(LOCALES).default("fr"), template: z.string().max(80).optional(), doc: z.unknown().optional() }));47 let doc, origin: "manual" | "template" | "import" = "manual";48 if (b.doc !== undefined) {49 // Import of an exported Sheet JSON: validated like any other document; it never arrives published.50 doc = validDoc(b.doc); origin = "import";51 // Uploads do not travel with the file: image blocks and dataset links are dropped (chart points are kept).52 const strip = <B extends { type: string }>(x: B): B => (x.type === "chart" ? (({ datasetRef: _d, ...rest }) => rest as unknown as B)(x as B & { datasetRef?: string }) : x);53 doc = { ...doc, assets: [], blocks: doc.blocks.filter((x) => x.type !== "image").map((x) => (x.type === "tabs" ? { ...x, tabs: x.tabs.map((t) => ({ ...t, blocks: t.blocks.filter((c) => c.type !== "image").map(strip) })) } : strip(x))) };54 doc = validDoc(doc);55 } else if (b.template) {56 doc = findTemplate(b.template) ? buildTemplate(b.template, b.locale) : await customTemplateDoc(b.template);57 doc = { ...doc, metadata: { ...doc.metadata, title: b.title ?? doc.metadata.title } };58 origin = "template";59 } else doc = emptySheet(b.locale, b.title ?? (b.locale === "fr" ? "Nouvelle fiche" : "New sheet"));60 return createSheet({ doc, origin, userId: ctx.userId });61 }],62 ["GET", "sheets/:id", async ({ params }) => getSheetDetail(id(params.id))],63 ["PATCH", "sheets/:id", async ({ req, params, ctx }) => {64 assertSmall(req, MAX_DOC_BYTES);65 const b = await body(req, z.object({66 doc: z.unknown().optional(), expectedVersion: z.number().int().optional(), summary: z.string().max(300).optional(),67 settings: z.object({68 slug: slug.optional(), status: z.enum(["draft", "in_review", "archived"]).optional(), featured: z.boolean().optional(), featuredPosition: z.number().int().min(0).max(999).optional(),69 allowDownload: z.boolean().optional(), seoTitle: z.string().max(120).nullable().optional(), seoDescription: z.string().max(300).nullable().optional(),70 canonicalUrl: z.string().url().max(500).startsWith("https://").nullable().optional(), ogAssetId: z.string().uuid().nullable().optional(),71 }).strict().optional(),72 }).strict());73 const sheetId = id(params.id);74 if (b.settings) await updateSettings(sheetId, b.settings, ctx.userId);75 if (b.doc !== undefined) {76 if (b.expectedVersion === undefined) throw new ApiError(400, "invalid_input", "expectedVersion is required with doc");77 return saveDoc({ sheetId, doc: validDoc(b.doc), expectedVersion: b.expectedVersion, origin: "manual", summary: b.summary, userId: ctx.userId });78 }79 return { ok: true };80 }],81 ["DELETE", "sheets/:id", async ({ params, ctx }) => { await deleteSheet(id(params.id), ctx.userId); return { ok: true }; }],82 ["POST", "sheets/:id/publish", async ({ req, params, ctx }) => publish(id(params.id), (await body(req, z.object({ expectedVersion: z.number().int() }))).expectedVersion, ctx.userId)],83 ["POST", "sheets/:id/unpublish", async ({ params, ctx }) => { await unpublish(id(params.id), ctx.userId); return { ok: true }; }],84 ["POST", "sheets/:id/revert", async ({ req, params, ctx }) => { const b = await body(req, z.object({ revisionId: z.string().uuid(), expectedVersion: z.number().int() })); return revertTo(id(params.id), b.revisionId, b.expectedVersion, ctx.userId); }],85 ["GET", "sheets/:id/revisions", async ({ params }) => ({ revisions: await listRevisions(id(params.id)) })],86 ["GET", "sheets/:id/revisions/:rid", async ({ params }) => getRevision(id(params.id), id(params.rid))],87 ["GET", "sheets/:id/conversation", async ({ params }) => ({ messages: await conversation(id(params.id)), jobs: await listJobs({ sheetId: id(params.id), limit: 5 }) })],88 ["GET", "sheets/:id/exports", async ({ params }) => ({ exports: await listExports(id(params.id)) })],89 ["POST", "sheets/:id/preview-link", async ({ params, ctx }) => createPreviewLink(id(params.id), ctx.userId)],90 ["DELETE", "sheets/:id/preview-link", async ({ params }) => { await revokePreviewLinks(id(params.id)); return { ok: true }; }],91 ["GET", "sheets/:id/export.json", async ({ params }) => {92 const s = await getSheetDetail(id(params.id));93 // Portable, versioned, stable key order. Uploads are referenced by id and do not travel with the file.94 return new Response(stableStringify(s.doc, 2), { headers: { "Content-Type": "application/json; charset=utf-8", "Content-Disposition": `attachment; filename="${s.slug}.sheet.json"`, "Cache-Control": "no-store" } });95 }],96 ["POST", "sheets/:id/save-as-template", async ({ req, params, ctx }) => { const b = await body(req, z.object({ title: z.string().min(1).max(120), description: z.string().max(300).default("") })); const s = await getSheetDetail(id(params.id)); return saveAsTemplate({ doc: s.doc, title: b.title, description: b.description, userId: ctx.userId }); }],97 // Quality report of a document that is not saved yet (live panel in the editor).98 ["POST", "quality", async ({ req }) => { assertSmall(req, MAX_DOC_BYTES); return qualityReport(validDoc((await body(req, z.object({ doc: z.unknown() }))).doc)); }],99100 // ── Claude studio ─────────────────────────────────────────────────────────────────────────────────101 ["POST", "generations", async ({ req, ctx }) => {102 const b = await body(req, z.object({ kind: z.enum(["outline", "generate"]), brief: BriefSchema, outline: OutlineSchema.nullable().optional(), idempotencyKey: idem }).strict());103 if (!env.anthropicApiKey) throw new ApiError(503, "ai_not_configured", "ANTHROPIC_API_KEY is not set on the server");104 for (const a of b.brief.attachments) if (!(await getAssetRow(a))) throw new ApiError(422, "bad_attachment", "An attachment was not found");105 return enqueueJob({ kind: b.kind, payload: b.kind === "outline" ? { brief: b.brief } : { brief: b.brief, outline: b.outline ?? null }, userId: ctx.userId, idempotencyKey: b.idempotencyKey, ip: clientIp(req) });106 }],107 ["GET", "generations", async ({ url }) => ({ jobs: await listJobs({ limit: page(url, 50).limit }) })],108 ["GET", "generations/:id", async ({ params }) => getJob(id(params.id))],109 ["POST", "generations/:id/cancel", async ({ params, ctx }) => cancelJob(id(params.id), ctx.userId)],110 // Progress as server-sent events: one event each time the job row changes, closing when the job ends.111 ["GET", "generations/:id/events", async ({ req, params }) => {112 const jobId = id(params.id);113 await getJob(jobId);114 const enc = new TextEncoder();115 const stream = new ReadableStream<Uint8Array>({116 async start(controller) {117 let last = "", open = true;118 req.signal.addEventListener("abort", () => { open = false; });119 const send = (event: string, data: unknown) => controller.enqueue(enc.encode(`event: ${event}\ndata: ${JSON.stringify(data)}\n\n`));120 for (let i = 0; open && i < 3600; i++) {121 const job = await getJob(jobId).catch(() => null);122 if (!job) break;123 const snapshot = JSON.stringify([job.status, job.stage, job.progress, job.usage.costUsd]);124 if (snapshot !== last) { last = snapshot; send("job", job); } else if (i % 30 === 0) controller.enqueue(enc.encode(": keep-alive\n\n"));125 if (job.status === "succeeded" || job.status === "failed" || job.status === "cancelled") break;126 await new Promise((r) => setTimeout(r, 500));127 }128 try { controller.close(); } catch { /* already closed by the client */ }129 },130 });131 return new Response(stream, { headers: { "Content-Type": "text/event-stream; charset=utf-8", "Cache-Control": "no-store, no-transform", "X-Accel-Buffering": "no", Connection: "keep-alive" } });132 }],133 ["POST", "sheets/:id/ai-edit", async ({ req, params, ctx }) => {134 const b = await body(req, z.object({ instruction: z.string().min(2).max(4000), baseVersion: z.number().int(), scope: z.array(z.string().max(48)).max(40).nullable().optional(), idempotencyKey: idem }).strict());135 if (!env.anthropicApiKey) throw new ApiError(503, "ai_not_configured", "ANTHROPIC_API_KEY is not set on the server");136 return enqueueJob({ kind: "edit", sheetId: id(params.id), payload: { instruction: b.instruction, baseVersion: b.baseVersion, scope: b.scope ?? null }, userId: ctx.userId, idempotencyKey: b.idempotencyKey, ip: clientIp(req) });137 }],138 ["POST", "sheets/:id/translate", async ({ req, params, ctx }) => {139 const b = await body(req, z.object({ targetLocale: z.enum(LOCALES), idempotencyKey: idem }).strict());140 if (!env.anthropicApiKey) throw new ApiError(503, "ai_not_configured", "ANTHROPIC_API_KEY is not set on the server");141 return enqueueJob({ kind: "translate", sheetId: id(params.id), payload: { targetLocale: b.targetLocale }, userId: ctx.userId, idempotencyKey: b.idempotencyKey, ip: clientIp(req) });142 }],143 ["POST", "sheets/:id/verify-sources", async ({ req, params, ctx }) => enqueueJob({ kind: "verify_sources", sheetId: id(params.id), payload: {}, userId: ctx.userId, ip: clientIp(req) })],144145 // ── Assets ────────────────────────────────────────────────────────────────────────────────────────146 ["GET", "assets", async ({ url }) => listAssets({ ...page(url, 60), kind: z.enum(["image", "svg", "pdf", "text", "csv", "json"]).optional().parse(url.searchParams.get("kind") ?? undefined) })],147 ["POST", "assets", async ({ req, ctx }) => {148 await rateLimit(`upload:${ctx.userId}`, 120, 3600);149 // The body is read under a hard cap before it is parsed (the declared length is not trusted).150 const raw = await readBody(req, env.maxUploadBytes + 100_000);151 let form: FormData;152 try { form = await new Response(new Uint8Array(raw), { headers: { "Content-Type": req.headers.get("content-type") ?? "" } }).formData(); } catch { throw new ApiError(400, "invalid_input", "Expected multipart/form-data with a file"); }153 const file = form.get("file");154 if (!(file instanceof File)) throw new ApiError(400, "invalid_input", "Missing file");155 if (file.size > env.maxUploadBytes) throw new ApiError(413, "file_too_large", `Files are limited to ${Math.round(env.maxUploadBytes / 1048576)} MB`);156 const str = (k: string) => { const v = form.get(k); return typeof v === "string" ? v : undefined; };157 return createAsset({ filename: file.name, data: Buffer.from(await file.arrayBuffer()), userId: ctx.userId, alt: str("alt"), credit: str("credit"), license: str("license"), ip: clientIp(req) });158 }],159 ["PATCH", "assets/:id", async ({ req, params }) => updateAsset(id(params.id), await body(req, z.object({ alt: z.string().max(400).optional(), credit: z.string().max(300).optional(), license: z.string().max(120).optional() }).strict()))],160 ["DELETE", "assets/:id", async ({ params, ctx }) => { await deleteAsset(id(params.id), ctx.userId); return { ok: true }; }],161 ["GET", "assets/:id/dataset", async ({ params }) => datasetRows(id(params.id))],162 ["GET", "assets/:id/file", async ({ params, url }) => {163 const a = await getAssetRow(id(params.id));164 if (!a) throw new ApiError(404, "not_found");165 const data = await readAsset(a);166 const inline = !url.searchParams.has("download") && (a.kind === "image" || a.mime === "image/png");167 return new Response(new Uint8Array(data), { headers: {168 "Content-Type": a.mime, "Cache-Control": "private, max-age=300", "X-Content-Type-Options": "nosniff",169 // Uploaded SVG and PDF are never rendered as documents in our origin.170 "Content-Security-Policy": "default-src 'none'; style-src 'unsafe-inline'; sandbox",171 "Content-Disposition": `${inline ? "inline" : "attachment"}; filename="${a.filename.replace(/[^\w.@-]+/g, "_")}"`,172 } });173 }],174 ["POST", "svg/sanitize", async ({ req }) => {175 assertSmall(req, 600_000);176 const r = sanitizeSvg((await body(req, z.object({ markup: z.string().min(1).max(400_000) }))).markup);177 if (!r.ok) throw new ApiError(422, "bad_svg", r.error);178 return { tree: r.tree, removed: r.removed };179 }],180181 // ── Exports ───────────────────────────────────────────────────────────────────────────────────────182 ["POST", "exports", async ({ req, ctx }) => { await rateLimit(`export:${ctx.userId}`, 120, 3600); return requestExport(await body(req, ExportRequest), ctx.userId); }],183 ["GET", "exports/:id", async ({ params }) => getExport(id(params.id))],184185 // ── Templates, topics, settings, audit ────────────────────────────────────────────────────────────186 ["GET", "templates", async () => ({187 builtin: TEMPLATES.map((t) => ({ id: t.id, title: t.title, description: t.description, category: t.category })),188 custom: await listCustomTemplates(),189 })],190 ["GET", "templates/:key/preview", async ({ params, url }) => {191 const locale = z.enum(LOCALES).parse(url.searchParams.get("locale") ?? "fr");192 return { doc: findTemplate(params.key) ? buildTemplate(params.key, locale) : await customTemplateDoc(z.string().max(80).parse(params.key)) };193 }],194 ["DELETE", "templates/:id", async ({ params }) => { await deleteCustomTemplate(id(params.id)); return { ok: true }; }],195 ["GET", "topics", async () => ({ topics: await adminTopics() })],196 ["PATCH", "topics/:id", async ({ req, params }) => { await updateTopic(id(params.id), await body(req, z.object({ nameFr: z.string().min(1).max(60).optional(), nameEn: z.string().min(1).max(60).optional(), descriptionFr: z.string().max(300).optional(), descriptionEn: z.string().max(300).optional(), tone: z.enum(TONES).optional(), position: z.number().int().min(0).max(999).optional() }).strict())); return { ok: true }; }],197 ["DELETE", "topics/:id", async ({ params }) => { await deleteTopic(id(params.id)); return { ok: true }; }],198 ["GET", "settings", async () => {199 const settings = await getSettings();200 let models: Awaited<ReturnType<typeof listModels>> = [], modelsError: string | null = null;201 try { models = await listModels(); } catch (e) { modelsError = (e as Error).message; }202 return {203 settings, models: models.map((m) => ({ ...m, price: priceOf(m.id) })), modelsError,204 // What the page needs to know about secrets: whether they are set. Never their value.205 environment: { anthropicKeySet: !!env.anthropicApiKey, defaultModel: env.anthropicDefaultModel, rpId: env.rpId, appUrl: env.appUrl, storageDriver: env.storageDriver, clamdConfigured: !!env.clamd, backupDirSet: !!env.backupDir, maxUploadMb: Math.round(env.maxUploadBytes / 1048576) },206 options: { themes: THEMES, formats: FORMATS },207 };208 }],209 ["PATCH", "settings", async ({ req, ctx }) => {210 const patch = await body(req, SettingsSchema.partial().strict());211 if (patch.aiModel) { const models = await listModels(true).catch((e: unknown) => { throw new ApiError(503, "ai_unavailable", e instanceof Error ? e.message : "The Anthropic API is unavailable"); }); if (!models.some((m) => m.id === patch.aiModel)) throw new ApiError(422, "unknown_model", "This model is not available to the configured API key"); }212 const next = await setSettings(patch, ctx.userId);213 await audit({ userId: ctx.userId, actor: "admin", action: "settings.updated", meta: { keys: Object.keys(patch) }, ip: clientIp(req) });214 return { settings: next };215 }],216 ["GET", "audit", async ({ url }) => listAudit({ ...page(url, 200), action: url.searchParams.get("action")?.slice(0, 60) || undefined })],217 // Used by the document import dialog to show what a file contains before it becomes a sheet.218 ["POST", "validate", async ({ req }) => { assertSmall(req, MAX_DOC_BYTES); const d = mustParseSheet(validDoc((await body(req, z.object({ doc: z.unknown() }))).doc)); return { ok: true, title: d.metadata.title, blocks: d.blocks.length, locale: d.metadata.locale }; }],219];220