SPB Git

Repository Public

api.ts 23.3 KB 241 lines typescript

1/**2 * The studio's private API: one table of routes, one dispatcher. Every entry names the permission it needs3 * and the dispatcher checks it — with the session, the origin and the CSRF token — before the handler runs,4 * so no handler can be reached without authorisation by forgetting a line. The only entries open to5 * anonymous requests are the passkey ceremonies, which are same-origin and rate limited per address.6 */7import "server-only";8import { join } from "node:path";9import { existsSync } from "node:fs";10import { searchIndexJson } from "@/lib/search-index";11import { audit, getBlob, getBlobText, listAudit } from "@/server/audit";12import {13  ROLE_LABEL, authenticationOptions, can, createEditor, enrollTokenInfo, issueEnrollToken, listEditors, listPasskeys, listSessions as listAuthSessions,14  registrationOptions, revokePasskey, revokeSessions, updateEditor, verifyAuthentication, verifyRegistration, type Permission, type Role, type StudioSession, type TokenPurpose,15} from "@/server/auth";16import { exportTarGz, listBackups } from "@/server/backup";17import { validateCaptions } from "@/server/captions";18import {19  createCapsule, createSession, deleteCapsule, deleteResource, deleteSection, getCapsule, getCourseRow, getSection, getSessionRow, listCapsules, listResources, listSections,20  listSessions, moveSession, putSection, reorderCapsules, restoreResourceVersion, sectionBody, setSessionState, updateCapsule, updateCourse, updateResource, updateSession,21  type SessionRow,22} from "@/server/content";23import { get, run } from "@/server/db";24import { ApiError, assertSameOrigin, clientIp, json, rateLimit, readJson } from "@/server/http";25import { getJob, jobCounts, listJobs, requestCancel, retryJob } from "@/server/jobs";26import { importLessonPack } from "@/server/lessons";27import { log } from "@/server/log";28import { acceptedExtensions } from "@/server/magic";29import { brokenItems, checkLinks, healthDetails, validateAllCaptions } from "@/server/ops";30import {31  COURSE_TARGET, cancelScheduled, history, planChanges, planDirty, planPublication, publishPlan, publishSession, retireSession, rollbackSession, scheduledEntries, sessionStatus,32} from "@/server/publish";33import { storageUsage } from "@/server/storage";34import { applyImport, discardImport, diffIsEmpty, importDiff, listImports, prepareImport, type Decision } from "@/server/sync";35import { configuredLadder } from "@/server/transcode";36import { CHUNK_SIZE, abortUpload, attachMaster, completeUpload, getUpload, initUpload, putChunk, readSidecar, receivedChunks, removeCaptions, saveChapters } from "@/server/uploads";37import { env } from "../env";38import { endSession, preauthBinding, requireEditor, startSession, studioEnabled } from "./guard";3940interface Ctx { req: Request; url: URL; p: string[]; session: StudioSession; actor: string; body: <T = Record<string, unknown>>() => Promise<T> }41type Handler = (c: Ctx) => Promise<Response | unknown> | Response | unknown;42type Route = [method: string, pattern: RegExp, permission: Permission, handler: Handler];4344const sessionSummary = (s: SessionRow) => {45  const status = sessionStatus(s);46  return { id: s.id, number: s.data.number, title: s.data.title, short: s.data.short, part: s.data.part, level: s.data.level, slug: s.data.slug, state: s.state, inSource: s.inSource, rev: s.rev, updatedAt: s.updatedAt,47    public: status.public, dirty: status.dirty, liveVersion: status.live?.version ?? null, liveSince: status.live?.liveFrom ?? null, scheduled: status.scheduled.map((e) => ({ id: e.id, version: e.version, liveFrom: e.liveFrom })),48    sections: listSections(s.id).map((x) => ({ key: x.key, visibility: x.visibility, count: x.count, edited: x.baseSha !== null && x.baseSha !== x.sha256 })),49    capsules: listCapsules(s.id).map((c) => ({ id: c.id, title: c.data.title, status: c.status, visibility: c.data.visibility })), resources: listResources(s.id).length,50    editedFields: s.base ? (Object.keys(s.base) as (keyof typeof s.base)[]).filter((k) => JSON.stringify(s.base![k]) !== JSON.stringify(s.data[k])) : [] };51};52const sessionDetail = (id: string) => {53  const s = getSessionRow(id);54  return { ...sessionSummary(s), data: s.data, base: s.base, updatedBy: s.updatedBy, sectionRows: listSections(id), capsuleRows: listCapsules(id), resourceRows: listResources(id), status: sessionStatus(s), history: history(id), plan: (({ snapshot: _s, ...rest }) => { void _s; return rest; })(planPublication(s)) };55};56const courseDetail = () => { const c = getCourseRow(); return { data: c.data, rev: c.rev, planDirty: planDirty(), planChanges: planChanges(), history: history(COURSE_TARGET), scheduled: scheduledEntries(COURSE_TARGET) }; };57const num = (s: string | undefined) => { const n = Number(s); if (!Number.isInteger(n)) throw new ApiError(400, "invalid", "Identifiant invalide."); return n; };5859const ROUTES: Route[] = [60  /* ---- Overview ---- */61  ["GET", /^dashboard$/, "edit", async () => {62    const sessions = listSessions().map(sessionSummary), usage = await storageUsage(), health = await healthDetails();63    return { sessions, jobs: { counts: jobCounts(), recent: listJobs({ limit: 8 }) }, storage: usage, health, broken: await brokenItems(), ladder: configuredLadder(), planDirty: planDirty(), backups: (await listBackups()).slice(0, 3).map((b) => ({ createdAt: b.manifest.createdAt, bytes: b.bytes })) };64  }],65  ["GET", /^health$/, "edit", () => healthDetails()],6667  /* ---- Sessions ---- */68  ["GET", /^sessions$/, "edit", () => ({ sessions: listSessions().map(sessionSummary), parts: getCourseRow().data.parts })],69  ["POST", /^sessions$/, "edit", async (c) => sessionDetail(createSession(await c.body(), c.actor).id)],70  ["GET", /^sessions\/(S\d{2,3})$/, "edit", (c) => ({ session: sessionDetail(c.p[0]!), parts: getCourseRow().data.parts, all: listSessions().map((s) => ({ id: s.id, number: s.data.number, short: s.data.short })), license: getCourseRow().data.course.license })],71  ["PATCH", /^sessions\/(S\d{2,3})$/, "edit", async (c) => { const b = await c.body<{ patch: unknown; rev: unknown }>(); updateSession(c.p[0]!, b.patch, b.rev, c.actor); return sessionDetail(c.p[0]!); }],72  ["POST", /^sessions\/(S\d{2,3})\/state$/, "edit", async (c) => { setSessionState(c.p[0]!, (await c.body()).state, c.actor); return sessionDetail(c.p[0]!); }],73  ["POST", /^sessions\/(S\d{2,3})\/move$/, "edit", async (c) => { moveSession(c.p[0]!, (await c.body()).direction, c.actor); return { sessions: listSessions().map(sessionSummary) }; }],7475  /* ---- Sections ---- */76  ["GET", /^sessions\/(S\d{2,3})\/sections\/([a-z]+)$/, "edit", (c) => { const s = getSection(c.p[0]!, c.p[1] as never); if (!s) throw new ApiError(404, "not_found", "Section introuvable."); return { row: s, body: sectionBody(s), baseBody: s.baseSha && s.baseSha !== s.sha256 ? getBlobText(s.baseSha) : null }; }],77  ["PUT", /^sessions\/(S\d{2,3})\/sections\/([a-z]+)$/, "edit", async (c) => { putSection(c.p[0]!, c.p[1], await c.body(), c.actor); return sessionDetail(c.p[0]!); }],78  ["DELETE", /^sessions\/(S\d{2,3})\/sections\/([a-z]+)$/, "edit", (c) => { deleteSection(c.p[0]!, c.p[1], c.actor); return sessionDetail(c.p[0]!); }],7980  // An interactive-lesson pack (SXX-lesson.json), as text: validated, hashed and installed private.81  ["POST", /^sessions\/(S\d{2,3})\/lesson-pack$/, "edit", async (c) => { const b = await c.body<{ pack?: unknown; force?: unknown }>(); if (typeof b.pack !== "string") throw new ApiError(400, "invalid", "Paquet manquant."); const result = importLessonPack(b.pack, c.actor, { expectSession: c.p[0]!, force: b.force === true }); return { result, session: sessionDetail(c.p[0]!) }; }],8283  // A figure of a session's working copy, by hash: served only if that session's figures section lists it.84  ["GET", /^figures\/(S\d{2,3})\/([a-f0-9]{64})$/, "edit", (c) => {85    const sec = getSection(c.p[0]!, "figures"), listed = sec ? (JSON.parse(sectionBody(sec)) as { figures: { sha256: string }[] }).figures.some((f) => f.sha256 === c.p[1]) : false, bytes = listed ? getBlob(c.p[1]!) : null;86    if (!bytes) throw new ApiError(404, "not_found", "Figure introuvable.");87    return new Response(new Uint8Array(bytes), { headers: { "Content-Type": "image/svg+xml", "Cache-Control": "private, max-age=300", "X-Content-Type-Options": "nosniff", "Content-Security-Policy": "default-src 'none'; style-src 'unsafe-inline'; sandbox" } });88  }],8990  /* ---- Capsules ---- */91  ["POST", /^sessions\/(S\d{2,3})\/capsules$/, "edit", async (c) => { createCapsule(c.p[0]!, await c.body(), c.actor); return sessionDetail(c.p[0]!); }],92  ["POST", /^sessions\/(S\d{2,3})\/capsules\/order$/, "edit", async (c) => { reorderCapsules(c.p[0]!, (await c.body()).order, c.actor); return sessionDetail(c.p[0]!); }],93  ["PATCH", /^sessions\/(S\d{2,3})\/capsules\/([a-z0-9-]+)$/, "edit", async (c) => { updateCapsule(c.p[0]!, c.p[1]!, await c.body(), c.actor); return sessionDetail(c.p[0]!); }],94  ["DELETE", /^sessions\/(S\d{2,3})\/capsules\/([a-z0-9-]+)$/, "edit", (c) => { deleteCapsule(c.p[0]!, c.p[1]!, c.actor); return sessionDetail(c.p[0]!); }],95  ["GET", /^sessions\/(S\d{2,3})\/capsules\/([a-z0-9-]+)\/sidecars$/, "edit", async (c) => {96    const cap = getCapsule(c.p[0]!, c.p[1]!), m = cap.data.media;97    return { captions: await Promise.all(m.captions.map(async (t) => ({ ...t, text: await readSidecar(t.path) }))), transcript: JSON.parse((await readSidecar(m.transcript)) ?? "null") as unknown, chapters: JSON.parse((await readSidecar(m.chapters)) ?? "[]") as unknown };98  }],99  ["PUT", /^sessions\/(S\d{2,3})\/capsules\/([a-z0-9-]+)\/chapters$/, "edit", async (c) => { await saveChapters(c.p[0]!, c.p[1]!, (await c.body()).chapters, c.actor); return sessionDetail(c.p[0]!); }],100  ["POST", /^sessions\/(S\d{2,3})\/capsules\/([a-z0-9-]+)\/captions\/validate$/, "edit", async (c) => { const b = await c.body<{ text?: unknown }>(); if (typeof b.text !== "string") throw new ApiError(400, "invalid", "Texte manquant."); return validateCaptions(b.text, { videoDuration: getCapsule(c.p[0]!, c.p[1]!).data.durationSeconds }); }],101  ["DELETE", /^sessions\/(S\d{2,3})\/capsules\/([a-z0-9-]+)\/captions\/([A-Za-z0-9-]+)$/, "edit", (c) => { removeCaptions(c.p[0]!, c.p[1]!, c.p[2]!, c.actor); return sessionDetail(c.p[0]!); }],102  ["POST", /^sessions\/(S\d{2,3})\/capsules\/([a-z0-9-]+)\/master$/, "edit", async (c) => { const b = await c.body<{ sha256?: unknown }>(); if (typeof b.sha256 !== "string" || !/^[a-f0-9]{64}$/.test(b.sha256)) throw new ApiError(400, "invalid", "Empreinte invalide."); const r = attachMaster(c.p[0]!, c.p[1]!, b.sha256, c.actor); return { jobId: r.jobId, session: sessionDetail(c.p[0]!) }; }],103104  /* ---- Resources ---- */105  ["PATCH", /^sessions\/(S\d{2,3})\/resources\/([A-Za-z0-9._-]+)$/, "edit", async (c) => { updateResource(c.p[0]!, c.p[1]!, await c.body(), c.actor); return sessionDetail(c.p[0]!); }],106  ["DELETE", /^sessions\/(S\d{2,3})\/resources\/([A-Za-z0-9._-]+)$/, "edit", (c) => { deleteResource(c.p[0]!, c.p[1]!, c.actor); return sessionDetail(c.p[0]!); }],107  ["POST", /^sessions\/(S\d{2,3})\/resources\/([A-Za-z0-9._-]+)\/restore$/, "edit", async (c) => { restoreResourceVersion(c.p[0]!, c.p[1]!, (await c.body()).version, c.actor); return sessionDetail(c.p[0]!); }],108109  /* ---- Publication of a session: only for those allowed to publish ---- */110  ["POST", /^sessions\/(S\d{2,3})\/publish$/, "publish", async (c) => { const entry = publishSession(c.p[0]!, await c.body(), c.actor); return { entry, session: sessionDetail(c.p[0]!) }; }],111  ["POST", /^sessions\/(S\d{2,3})\/rollback$/, "publish", async (c) => { const entry = rollbackSession(c.p[0]!, await c.body(), c.actor); return { entry, session: sessionDetail(c.p[0]!) }; }],112  ["POST", /^sessions\/(S\d{2,3})\/(withdraw|archive)$/, "publish", async (c) => { const entry = retireSession(c.p[0]!, c.p[1] as "withdraw" | "archive", await c.body(), c.actor); return { entry, session: sessionDetail(c.p[0]!) }; }],113  ["POST", /^sessions\/(S\d{2,3})\/schedule\/cancel$/, "publish", async (c) => { cancelScheduled(c.p[0]!, (await c.body()).entryId, c.actor); return sessionDetail(c.p[0]!); }],114115  /* ---- Course and public plan ---- */116  ["GET", /^course$/, "edit", () => courseDetail()],117  ["PATCH", /^course$/, "edit", async (c) => { const b = await c.body<{ patch: unknown; rev: unknown }>(); updateCourse(b.patch, b.rev, c.actor); return courseDetail(); }],118  ["POST", /^course\/publish$/, "publish", async (c) => { publishPlan(await c.body(), c.actor); return courseDetail(); }],119  ["POST", /^course\/rollback$/, "publish", async (c) => { rollbackSession(COURSE_TARGET, await c.body(), c.actor); return courseDetail(); }],120  ["POST", /^course\/schedule\/cancel$/, "publish", async (c) => { cancelScheduled(COURSE_TARGET, (await c.body()).entryId, c.actor); return courseDetail(); }],121122  /* ---- Uploads ---- */123  ["GET", /^uploads\/config$/, "edit", async () => ({ chunkSize: CHUNK_SIZE, accepted: { master: acceptedExtensions("master"), resource: acceptedExtensions("resource"), captions: acceptedExtensions("captions"), transcript: acceptedExtensions("transcript"), archive: acceptedExtensions("archive"), slides: acceptedExtensions("slides") }, limits: { master: env.maxMasterBytes, resource: env.maxResourceBytes, archive: env.maxArchiveBytes }, storage: await storageUsage() })],124  ["POST", /^uploads$/, "edit", async (c) => initUpload(await c.body(), c.actor)],125  ["GET", /^uploads\/(up_[a-f0-9]{16})$/, "edit", (c) => ({ upload: getUpload(c.p[0]!), received: receivedChunks(c.p[0]!) })],126  ["PUT", /^uploads\/(up_[a-f0-9]{16})\/chunks\/(\d{1,7})$/, "edit", async (c) => {127    const declared = Number(c.req.headers.get("content-length") ?? 0);128    if (declared > CHUNK_SIZE + 1024) throw new ApiError(413, "too_large", "Morceau trop volumineux.");129    const body = Buffer.from(await c.req.arrayBuffer());130    if (body.length > CHUNK_SIZE) throw new ApiError(413, "too_large", "Morceau trop volumineux.");131    return putChunk(c.p[0]!, Number(c.p[1]), body, c.req.headers.get("x-chunk-sha256"));132  }],133  ["POST", /^uploads\/(up_[a-f0-9]{16})\/complete$/, "edit", (c) => completeUpload(c.p[0]!, c.actor)],134  ["DELETE", /^uploads\/(up_[a-f0-9]{16})$/, "edit", async (c) => { await abortUpload(c.p[0]!, c.actor); return { ok: true }; }],135136  /* ---- Import from the course repository (always as drafts) ---- */137  ["GET", /^imports$/, "edit", () => {138    const list = listImports(), pending = list.find((i) => i.status === "pending");139    return { imports: list, pending: pending ? { record: pending, diff: importDiff(pending.id) } : null, repo: env.courseRepo ? { configured: true, readable: existsSync(join(env.courseRepo, "course.yaml")) } : { configured: false, readable: false } };140  }],141  ["POST", /^imports$/, "edit", async (c) => {142    if (!env.courseRepo) throw new ApiError(409, "no_repo", "Aucun dépôt n'est configuré sur ce serveur (ATLAS_COURSE_REPO). Téléversez une archive du dépôt.");143    if (!existsSync(join(env.courseRepo, "course.yaml"))) throw new ApiError(409, "no_repo", "Le dépôt configuré est introuvable ou ne contient pas de course.yaml.");144    const r = await prepareImport(env.courseRepo, "Dépôt du cours configuré sur le serveur", c.actor);145    return { ...r, empty: diffIsEmpty(r.diff) };146  }],147  ["POST", /^imports\/(imp_[a-f0-9]{12})\/apply$/, "edit", async (c) => {148    const b = await c.body<{ decisions?: Record<string, Decision>; confirm?: unknown }>();149    if (b.confirm !== c.p[0]) throw new ApiError(400, "confirmation_required", "L'importation doit être confirmée explicitement.");150    const decisions = Object.fromEntries(Object.entries(b.decisions ?? {}).filter(([, v]) => v === "local" || v === "incoming"));151    return applyImport(c.p[0]!, decisions, c.actor);152  }],153  ["POST", /^imports\/(imp_[a-f0-9]{12})\/discard$/, "edit", (c) => { discardImport(c.p[0]!, c.actor); return { ok: true }; }],154155  /* ---- Processing jobs ---- */156  ["GET", /^jobs$/, "edit", () => ({ jobs: listJobs({ limit: 100 }), counts: jobCounts() })],157  ["GET", /^jobs\/(\d+)$/, "edit", (c) => { const j = getJob(num(c.p[0])); if (!j) throw new ApiError(404, "not_found", "Traitement introuvable."); return j; }],158  ["POST", /^jobs\/(\d+)\/cancel$/, "edit", (c) => { const j = requestCancel(num(c.p[0])); audit("job.cancel_requested", { actor: c.actor, target: `job:${j.id}` }); return j; }],159  ["POST", /^jobs\/(\d+)\/retry$/, "edit", (c) => {160    const j = retryJob(num(c.p[0]));161    if (j.kind === "transcode") { const p = j.payload as { sessionId: string; capsuleId: string; masterSha: string }; if (get("SELECT 1 FROM capsules WHERE session_id = ? AND id = ? AND master_sha = ?", p.sessionId, p.capsuleId, p.masterSha)) { const cap = getCapsule(p.sessionId, p.capsuleId); if (cap.status !== "processing") run("UPDATE capsules SET status = 'queued' WHERE session_id = ? AND id = ?", p.sessionId, p.capsuleId); } }162    audit("job.retried", { actor: c.actor, target: `job:${j.id}` });163    return j;164  }],165166  /* ---- Tools ---- */167  ["POST", /^tools\/search-index$/, "edit", async (c) => {168    const t0 = Date.now(), body = await searchIndexJson(true), docs = (JSON.parse(body) as { docs: { type: string }[] }).docs, byType: Record<string, number> = {};169    for (const d of docs) byType[d.type] = (byType[d.type] ?? 0) + 1;170    audit("tools.search_index_rebuilt", { actor: c.actor, detail: { documents: docs.length } });171    return { documents: docs.length, byType, bytes: Buffer.byteLength(body), milliseconds: Date.now() - t0 };172  }],173  ["POST", /^tools\/links$/, "edit", async (c) => checkLinks({ deep: (await c.body()).deep === true })],174  ["POST", /^tools\/captions$/, "edit", () => validateAllCaptions()],175  ["GET", /^tools\/export$/, "admin", async (c) => {176    const body = await exportTarGz();177    audit("tools.exported", { actor: c.actor, detail: { bytes: body.length } });178    return new Response(new Uint8Array(body), { headers: { "Content-Type": "application/gzip", "Content-Disposition": `attachment; filename="atlas-ia-export-${new Date().toISOString().slice(0, 10)}.tar.gz"`, "Cache-Control": "private, no-store", "X-Robots-Tag": "noindex" } });179  }],180  ["GET", /^tools\/backups$/, "admin", async () => ({ backups: (await listBackups()).map((b) => ({ createdAt: b.manifest.createdAt, bytes: b.bytes, files: b.manifest.files.length, includes: b.manifest.includes, name: b.dir.split("/").pop() })) })],181182  /* ---- Audit log ---- */183  ["GET", /^audit$/, "edit", (c) => ({ entries: listAudit({ limit: 100, before: Number(c.url.searchParams.get("before")) || undefined, action: c.url.searchParams.get("action")?.slice(0, 60) || undefined, target: c.url.searchParams.get("target")?.slice(0, 120) || undefined }), editors: Object.fromEntries(listEditors().map((e) => [e.id, e.name])) })],184  ["GET", /^audit\/(\d+)$/, "edit", (c) => {185    const e = get<{ before_ref: string | null; after_ref: string | null }>("SELECT before_ref, after_ref FROM audit WHERE id = ?", num(c.p[0]));186    if (!e) throw new ApiError(404, "not_found", "Entrée introuvable.");187    const read = (ref: string | null) => { const text = ref ? getBlobText(ref) : null; if (text === null) return null; try { return JSON.parse(text) as unknown; } catch { return text.slice(0, 20_000); } };188    return { before: read(e.before_ref), after: read(e.after_ref) };189  }],190191  /* ---- Access: editors, passkeys, sessions — the owner only ---- */192  ["GET", /^access$/, "admin", (c) => ({ editors: listEditors(), passkeys: listPasskeys(), sessions: listAuthSessions().map((s) => ({ ...s, current: c.session.tokenHash.startsWith(s.id) })), roles: ROLE_LABEL, me: c.session.editor.id })],193  ["POST", /^access\/editors$/, "admin", async (c) => { const b = await c.body<{ name?: unknown; role?: unknown }>(); const editor = createEditor(String(b.name ?? ""), b.role as Role, c.actor); const t = issueEnrollToken(editor.id, "setup", c.actor, 60); return { editor, link: `${env.studioOrigin}/admin/enrolement?jeton=${t.raw}`, expiresAt: t.expiresAt }; }],194  ["PATCH", /^access\/editors\/(ed_[a-f0-9]+)$/, "admin", async (c) => { const b = await c.body<{ role?: Role; disabled?: boolean; name?: string }>(); return updateEditor(c.p[0]!, { role: b.role, disabled: typeof b.disabled === "boolean" ? b.disabled : undefined, name: typeof b.name === "string" ? b.name : undefined }, c.actor); }],195  ["POST", /^access\/editors\/(ed_[a-f0-9]+)\/token$/, "admin", async (c) => { const b = await c.body<{ purpose?: TokenPurpose }>(); const t = issueEnrollToken(c.p[0]!, b.purpose === "recovery" ? "recovery" : "setup", c.actor, 60); return { link: `${env.studioOrigin}/admin/enrolement?jeton=${t.raw}`, expiresAt: t.expiresAt }; }],196  ["POST", /^access\/editors\/(ed_[a-f0-9]+)\/sessions\/revoke$/, "admin", (c) => ({ revoked: revokeSessions({ editorId: c.p[0]! }, c.actor) })],197  ["DELETE", /^access\/passkeys\/([A-Za-z0-9_-]{8,})$/, "admin", (c) => { revokePasskey(c.p[0]!, c.actor); return { ok: true }; }],198  ["DELETE", /^access\/sessions\/([a-f0-9]{16})$/, "admin", (c) => ({ revoked: revokeSessions({ id: c.p[0]! }, c.actor) })],199];200201/** Passkey ceremonies and sign-out. Same-origin only, rate limited per client address, no session required. */202async function auth(step: string, req: Request): Promise<Response> {203  if (req.method !== "POST") throw new ApiError(405, "method", "Méthode non permise.");204  assertSameOrigin(req);205  const ip = clientIp(req);206  rateLimit("auth", ip, 30, 60);207  const body = await readJson<Record<string, unknown>>(req, 64_000);208  if (!body || typeof body !== "object") throw new ApiError(400, "bad_request", "Requête mal formée.");209  if (step.endsWith("/verify") && (typeof body.challengeId !== "string" || typeof body.response !== "object" || !body.response)) throw new ApiError(400, "bad_request", "Réponse de cérémonie mal formée.");210  switch (step) {211    case "register/info": return json({ token: enrollTokenInfo(body.token) });212    case "register/options": return json(await registrationOptions(body.token, (await preauthBinding(true))!));213    case "register/verify": { const editor = await verifyRegistration(body, await preauthBinding(false), ip); await startSession(editor, req); return json({ ok: true }); }214    case "login/options": return json(await authenticationOptions((await preauthBinding(true))!));215    case "login/verify": { const editor = await verifyAuthentication(body, await preauthBinding(false), ip); await startSession(editor, req); return json({ ok: true }); }216    case "logout": { await endSession(); audit("auth.logout", { ip }); return json({ ok: true }); }217    default: throw new ApiError(404, "not_found", "Introuvable.");218  }219}220221export async function dispatch(req: Request, segments: string[]): Promise<Response> {222  if (!studioEnabled()) throw new ApiError(404, "not_found", "Introuvable.");223  const path = segments.join("/"), url = new URL(req.url);224  if (path.startsWith("auth/")) return auth(path.slice(5), req);225  // Authentication comes first, whatever the path: an anonymous caller learns nothing about which routes exist.226  const session = await requireEditor(req, "edit");227  for (const [method, pattern, permission, handler] of ROUTES) {228    if (method !== req.method) continue;229    const m = pattern.exec(path);230    if (!m) continue;231    if (!can(session.editor.role, permission)) throw new ApiError(403, "forbidden", "Votre rôle ne permet pas cette action.");232    let cached: unknown;233    const ctx: Ctx = { req, url, p: m.slice(1), session, actor: session.editor.id, body: async <T,>() => (cached ??= await readJson(req)) as T };234    const out = await handler(ctx);235    if (req.method !== "GET") log("info", "studio.write", { actor: session.editor.id, method: req.method, path });236    return out instanceof Response ? out : json(out);237  }238  throw new ApiError(ROUTES.some(([, pattern]) => pattern.test(path)) ? 405 : 404, "not_found", "Introuvable.");239}240241
Files main
Menu

Theme