Archilyzer · Source

archilyzer

Archilyzer
git clone https://archilyzer.pages.dev/source/archilyzer.git
Log | Files | Refs | README | LICENSE

commit cc07dadffe4d74662736e92b5a2345c1268886d7
parent 59bdb4dfcd8a154395a42f01498a974b5603f789
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Wed, 18 Nov 2026 06:45:11 -0500

umtool: the Posts library's routes -- /api/library/judge, /watch and /purge are the editor's actions with `by: "operator"` stamped on the server (a `by` in the body is not read, and a request carrying an Authorization header is sent to `pnpm ops`); a bulk press judges every post a view matches in chunks of at most 500 and refuses when the match is no longer the count the confirm showed; /seen is Mark seen; /api/library/media/<lib>/<id>/<name> serves one captured picture or video of a marked library, read only, with byte ranges, refusing a cross-site request, and lists nothing

Co-Authored-By: Claude <noreply@anthropic.com>

Diffstat:
Aumtool/app/api/library/judge/route.ts | 20++++++++++++++++++++
Aumtool/app/api/library/media/[lib]/[id]/[name]/route.ts | 53+++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/app/api/library/purge/route.ts | 15+++++++++++++++
Aumtool/app/api/library/seen/route.ts | 22++++++++++++++++++++++
Aumtool/app/api/library/watch/route.ts | 14++++++++++++++
Aumtool/lib/library/presses.mjs | 131+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/lib/library/presses.test.mjs | 110+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/lib/library/route.ts | 34++++++++++++++++++++++++++++++++++
8 files changed, 399 insertions(+), 0 deletions(-)

diff --git a/umtool/app/api/library/judge/route.ts b/umtool/app/api/library/judge/route.ts @@ -0,0 +1,20 @@ +import { judgePress } from "@/lib/library/presses.mjs"; +import { ask, press } from "@/lib/library/route"; +import { seenOf } from "@/lib/library/seen.mjs"; +import { REPORTS_ROOT } from "@/lib/paths.mjs"; + +export const dynamic = "force-dynamic"; + +// POST { lib, set: [{id | thread, state, note?}], undo? } +// POST { lib, bulk: { view, state, note? }, expect } +// -> { ok, written, skipped, kept, archives, sentence, undo? } +// +// THE POSTS LIBRARY PAGE'S KEEP / DROP / LATER / CLEAR (lane posts-library): +// the editor's `judge-trending`, written as the OPERATOR's whatever the body +// says (lib/library/presses.mjs). umtool writes no file of the library and +// asks X nothing: a keep's archiving is the editor's one paced capture job. +// `bulk` judges every post the view's filters match, in chunks of at most +// 500, and refuses when the match is no longer the `expect`ed count. +export async function POST(request: Request) { + return press(request, (body) => judgePress(ask, body, { seenAt: async (lib: string, topic: string) => (await seenOf(REPORTS_ROOT, lib))[topic] ?? null })); +} diff --git a/umtool/app/api/library/media/[lib]/[id]/[name]/route.ts b/umtool/app/api/library/media/[lib]/[id]/[name]/route.ts @@ -0,0 +1,53 @@ +import { resolveLibraryMedia } from "@/lib/library/media.mjs"; +import { CHANNELS_DIR } from "@/lib/paths.mjs"; +import { crossSiteRefusal } from "@/lib/report/sameOrigin.mjs"; +import { rangeResponse } from "@/lib/report/serve.mjs"; + +export const dynamic = "force-dynamic"; + +// GET /api/library/media/<lib>/<id>/<name> one captured picture or video of a library post (byte ranges) +// +// THE ONE ROUTE THAT SERVES A TRENDING LIBRARY'S MEDIA (lane posts-library), +// for the Posts library page. A library is PRIVATE, so this route is narrow +// (lib/library/media.mjs resolveLibraryMedia is the whole rule): +// +// - `lib` must carry the library marker; any other channel is a 404 +// - only `channels/<lib>/trending/posts-media/<id>/<name>`: digits for the +// id, one plain segment for the name, a picture's or a video's extension +// (never capture.json, an article, the raw reads, the judgements), and +// the file's real path inside that library's posts-media +// - it lists nothing: there is no directory answer and no index of ids +// - READ ONLY: GET and HEAD; the corpus is never written from here +// - another site's page cannot embed or fetch it: a cross-site request, or +// one naming a host that is not this machine, is refused +// (crossSiteRefusal, asked of a READ here), and the answer says +// `Cross-Origin-Resource-Policy: same-origin` +// - never cached by a shared cache: `private, no-store` +// +// umtool is bound to the LAN (the operator's phone), as every media route of +// it is: anyone on that network who knows a post's id and file name can ask. +const PRIVATE = { + "cache-control": "private, no-store", + "cross-origin-resource-policy": "same-origin", + "x-content-type-options": "nosniff", + "x-robots-tag": "noindex", +}; + +async function serve(request: Request, params: Promise<{ lib: string; id: string; name: string }>): Promise<Response> { + const refused = crossSiteRefusal(request.headers); + if (refused) return Response.json({ error: "refused: this file is served to umtool's own pages only" }, { status: 403, headers: PRIVATE }); + const { lib, id, name } = await params; + const found = await resolveLibraryMedia({ channelsDir: CHANNELS_DIR, lib, id, name }); + if (!found.ok) return Response.json({ error: found.status === 400 ? "bad request" : "not found" }, { status: found.status, headers: PRIVATE }); + return rangeResponse(request, { abs: found.abs, size: found.size, headers: { ...PRIVATE, "content-type": found.type, "accept-ranges": "bytes" } }); +} + +export async function GET(request: Request, { params }: { params: Promise<{ lib: string; id: string; name: string }> }) { + return serve(request, params); +} + +export async function HEAD(request: Request, { params }: { params: Promise<{ lib: string; id: string; name: string }> }) { + const res = await serve(request, params); + await res.body?.cancel(); + return new Response(null, { status: res.status, headers: res.headers }); +} diff --git a/umtool/app/api/library/purge/route.ts b/umtool/app/api/library/purge/route.ts @@ -0,0 +1,15 @@ +import { purgePress } from "@/lib/library/presses.mjs"; +import { ask, press } from "@/lib/library/route"; + +export const dynamic = "force-dynamic"; + +// POST { lib, topic?, dryRun: true } -> what would be removed: { posts, files, bytes, confirm, sentence, … } +// POST { lib, topic?, confirm } -> removed, when the set is still the one the dry run showed +// +// THE POSTS LIBRARY PAGE'S PURGE (lane posts-library): the editor's +// `purge-trending`, the OPERATOR's, in two presses. umtool removes nothing +// itself. Only dropped posts' captures go; the judgements stay, and media +// another post still uses is left. +export async function POST(request: Request) { + return press(request, (body) => purgePress(ask, body)); +} diff --git a/umtool/app/api/library/seen/route.ts b/umtool/app/api/library/seen/route.ts @@ -0,0 +1,22 @@ +import { PressError } from "@/lib/library/presses.mjs"; +import { press } from "@/lib/library/route"; +import { markSeen } from "@/lib/library/seen.mjs"; +import { REPORTS_ROOT } from "@/lib/paths.mjs"; + +export const dynamic = "force-dynamic"; + +// POST { lib, topics: [<topicId>, …] } -> { ok, slug, topics: { <id>: { seenAt, previous? } } } +// +// MARK SEEN (lane posts-library): the one thing that moves "new since last +// visit". umtool's OWN state (REPORTS_ROOT/.umtool/posts-library.json, +// lib/library/seen.mjs), never a file of the library. +export async function POST(request: Request) { + return press(request, async (body) => { + const b = (body && typeof body === "object" ? body : {}) as { lib?: unknown; topics?: unknown }; + try { + return { ok: true, ...(await markSeen(REPORTS_ROOT, { slug: String(b.lib ?? ""), topics: b.topics as string[] })) }; + } catch (err) { + throw new PressError(err instanceof Error ? err.message : String(err)); + } + }); +} diff --git a/umtool/app/api/library/watch/route.ts b/umtool/app/api/library/watch/route.ts @@ -0,0 +1,14 @@ +import { watchPress } from "@/lib/library/presses.mjs"; +import { ask, press } from "@/lib/library/route"; + +export const dynamic = "force-dynamic"; + +// POST { lib, topic, on, intervalMinutes?, hours?, shots? } -> the editor's { ok, topic, watch, sentence } +// +// THE POSTS LIBRARY PAGE'S WATCH SWITCH (lane posts-library): the editor's +// `watch-trending` for one topic, as the OPERATOR (so it is the press that +// restarts a watch paused as failing). umtool reads no page of X: the editor's +// own scan starts each read, on X's queue, under the watch's jar rule. +export async function POST(request: Request) { + return press(request, (body) => watchPress(ask, body)); +} diff --git a/umtool/lib/library/presses.mjs b/umtool/lib/library/presses.mjs @@ -0,0 +1,131 @@ +// THE POSTS LIBRARY PAGE'S PRESSES (lane posts-library): what +// /api/library/{judge,watch,purge} do with a body, apart from Next. Each is +// the editor's action, asked through `ask` (lib/library/client.mjs). +// +// EVERY PRESS FROM THE PAGE IS THE OPERATOR'S: `by: "operator"` is stamped +// HERE, on the server. A `by` in the body is not read, so nothing a browser +// (or anything else posting to these routes) sends can say otherwise; an +// agent's hand is `pnpm ops` or `umtool library`, which say "agent". +// +// Plain ESM. +import { JUDGE_STATES, archiveSentence, judge, listLibraryRows, purge, watch } from "./client.mjs"; +import { listingParamsOf, parseLibraryView } from "./filters.mjs"; +import { pressSetOf, undoSetOf } from "./undo.mjs"; + +export const OPERATOR = "operator"; +const SLUG = /^[A-Za-z0-9][A-Za-z0-9._-]*$/; +const ID = /^\d{1,32}$/; + +export class PressError extends Error { + constructor(message, status = 400) { + super(message); + this.name = "PressError"; + this.status = status; + } +} + +function libOf(body) { + if (!body || typeof body !== "object" || Array.isArray(body)) throw new PressError("the body is a JSON object"); + if (typeof body.lib !== "string" || !SLUG.test(body.lib)) throw new PressError(`"lib" is the library's slug`); + return body.lib; +} + +function cleanSet(set) { + if (!Array.isArray(set) || set.length === 0) throw new PressError(`"set" is a list of judgements: [{"id" | "thread", "state", "note"?}, …]`); + return set.map((item, i) => { + const at = `set[${i}]`; + if (!item || typeof item !== "object") throw new PressError(`${at} is an object`); + const hasId = typeof item.id === "string"; + const hasThread = typeof item.thread === "string"; + if (hasId === hasThread) throw new PressError(`${at} names a post ("id") or a thread ("thread"), one of them`); + const key = hasId ? item.id : item.thread; + if (!ID.test(key)) throw new PressError(`${at}: "${key}" is not a post id`); + if (!JUDGE_STATES.includes(item.state)) throw new PressError(`${at}: "state" is one of ${JUDGE_STATES.join(", ")}`); + if (item.note !== undefined && typeof item.note !== "string") throw new PressError(`${at}: a note is text`); + return { ...(hasId ? { id: key } : { thread: key }), state: item.state, ...(item.note && item.state !== "undecided" ? { note: item.note } : {}) }; + }); +} + +const n = (k, what = "post") => `${k} ${what}${k === 1 ? "" : "s"}`; + +function judgedSentence(out, state) { + const skipped = out.skipped.length ? ` ${n(out.skipped.length, "id")} skipped: ${out.skipped[0].reason ?? "not judged"}.` : ""; + const did = state === "undecided" ? "cleared" : state === "keep" ? "kept" : state === "drop" ? "dropped" : state === "later" ? "marked later" : "judged"; + const archive = archiveSentence(out); + return `${n(out.written.length, "judgement")} ${state ? did : "written"}.${skipped}${archive ? ` ${archive}` : ""}`; +} + +/** + * POST /api/library/judge. + * { lib, set: [{id | thread, state, note?}], undo? } the posts or threads named. `undo: true` is the + * undo of a press: it archives nothing (and cancels no capture already queued). + * { lib, bulk: { view, state, note? }, expect } every post the VIEW's filters match (the page's + * URL parameters), judged post by post in chunks of at most 500. `expect` is the count the confirm + * showed: when the filter no longer matches that many, nothing is judged. + * Answers { ok, written, skipped, kept, archives, sentence, undo? } — `undo` (bulk) is the set that puts + * every judged post back. + * + * @param {(route: string, init?: object) => Promise<any>} ask + * @param {any} body + * @param {{ seenAt?: (lib: string, topic: string) => Promise<string | null> }} [deps] + */ +export async function judgePress(ask, body, deps = {}) { + const lib = libOf(body); + if ((body.set === undefined) === (body.bulk === undefined)) throw new PressError(`give "set" (the posts or threads named) or "bulk" (everything a view's filters match), one of them`); + if (body.set !== undefined) { + const set = cleanSet(body.set); + const out = await judge(ask, { slug: lib, by: OPERATOR, set, ...(body.undo === true ? { archive: false } : {}) }); + const states = new Set(set.map((s) => s.state)); + return { ok: true, ...out, sentence: body.undo === true ? `Undone: ${n(out.written.length, "judgement")} put back.` : judgedSentence(out, states.size === 1 ? set[0].state : null) }; + } + const bulk = body.bulk; + if (!bulk || typeof bulk !== "object") throw new PressError(`"bulk" is {view, state, note?}`); + if (!JUDGE_STATES.includes(bulk.state)) throw new PressError(`"bulk.state" is one of ${JUDGE_STATES.join(", ")}`); + if (bulk.note !== undefined && typeof bulk.note !== "string") throw new PressError(`"bulk.note" is text`); + if (!Number.isInteger(body.expect) || body.expect < 1) throw new PressError(`"expect" is the number of posts the confirm showed`); + const view = { ...parseLibraryView(bulk.view && typeof bulk.view === "object" ? bulk.view : {}), lib }; + const seenAt = view.fresh && view.topic && deps.seenAt ? await deps.seenAt(lib, view.topic) : null; + // The rows as they are NOW, with their own judgements: the targets, and what an undo puts back. + const rows = await listLibraryRows(ask, listingParamsOf(view, { seenAt })); + if (rows.length !== body.expect) { + throw new PressError(`The filter now matches ${n(rows.length)}, not the ${body.expect} the confirm showed: nothing was judged. Look again and press once more.`, 409); + } + const targets = rows.map((r) => ({ id: r.id })); + const out = await judge(ask, { slug: lib, by: OPERATOR, set: pressSetOf(targets, bulk.state, bulk.note ?? "") }); + return { ok: true, ...out, undo: undoSetOf(rows, targets), sentence: judgedSentence(out, bulk.state) }; +} + +/** + * POST /api/library/watch: { lib, topic, on, intervalMinutes?, hours?, shots? } — one topic's switch, the + * operator's (so it restarts a failing watch). Answers the editor's { ok, topic, watch, sentence }. + */ +export async function watchPress(ask, body) { + const lib = libOf(body); + if (typeof body.topic !== "string" || !body.topic) throw new PressError(`"topic" is the topic's id`); + if (typeof body.on !== "boolean") throw new PressError(`"on" is true (watch the topic) or false (stop watching it)`); + const int = (k) => { + if (body[k] === undefined || body[k] === null || body[k] === "") return {}; + if (!Number.isInteger(body[k])) throw new PressError(`"${k}" is a whole number`); + return { [k]: body[k] }; + }; + return watch(ask, { + slug: lib, + topic: body.topic, + on: body.on, + ...(body.on ? { ...int("intervalMinutes"), ...int("hours"), ...(typeof body.shots === "boolean" ? { shots: body.shots } : {}) } : {}), + by: OPERATOR, + }); +} + +/** + * POST /api/library/purge: { lib, topic?, dryRun: true } counts; { lib, topic?, confirm } removes what that + * dry run showed. The operator's, in two steps. Answers the editor's purge-trending answer. + */ +export async function purgePress(ask, body) { + const lib = libOf(body); + if (body.topic !== undefined && body.topic !== null && (typeof body.topic !== "string" || !body.topic)) throw new PressError(`"topic" is a topic's id`); + const scope = { slug: lib, ...(body.topic ? { topic: body.topic } : {}) }; + if (body.dryRun === true) return purge(ask, { ...scope, dryRun: true, by: OPERATOR }); + if (typeof body.confirm !== "string" || !/^[0-9a-f]{16}$/.test(body.confirm)) throw new PressError(`A removal carries the "confirm" its dry run answered: press Purge, read what it would remove, then confirm.`); + return purge(ask, { ...scope, confirm: body.confirm, by: OPERATOR }); +} diff --git a/umtool/lib/library/presses.test.mjs b/umtool/lib/library/presses.test.mjs @@ -0,0 +1,110 @@ +// The Posts library page's presses (lane posts-library): each one the +// editor's action with `by: "operator"` stamped on the server, whatever the +// body says. A fake `ask`: no socket. +// +// Run with: pnpm test:scripts +import assert from "node:assert/strict"; +import test from "node:test"; +import { judgePress, PressError, purgePress, watchPress } from "./presses.mjs"; + +function editor(rows = []) { + const asked = []; + const ask = async (route, init = {}) => { + asked.push({ route, ...init }); + if (route.startsWith("/api/ops/trending")) { + const offset = Number(new URL(route, "http://x").searchParams.get("offset") ?? 0); + return { ok: true, total: rows.length, posts: rows.slice(offset, offset + 500) }; + } + if (route === "/api/ops/judge-trending") { + const kept = init.body.set.filter((s) => s.state === "keep" && s.id).map((s) => s.id); + return { ok: true, written: init.body.set.map(({ note: _n, ...s }) => s), skipped: [], kept, ...(kept.length && init.body.archive !== false ? { archive: { jobId: `cap-${asked.length}`, ids: kept } } : {}) }; + } + return { ok: true, echoed: init.body }; + }; + return { ask, asked, posts: () => asked.filter((a) => a.method === "POST") }; +} + +test("a press on the posts named is the operator's, whatever the body says about who", async () => { + const e = editor(); + const out = await judgePress(e.ask, { lib: "lib", by: "agent", set: [{ id: "1900000000000001001", state: "keep", note: "the opening", by: "agent" }, { thread: "1900000000000001002", state: "drop" }] }); + assert.equal(e.posts().length, 1); + assert.deepEqual(e.posts()[0].body, { slug: "lib", by: "operator", set: [{ id: "1900000000000001001", state: "keep", note: "the opening" }, { thread: "1900000000000001002", state: "drop" }] }); + assert.equal(out.ok, true); + assert.match(out.sentence, /^2 judgements written\. 1 post queued for archiving \(the editor's capture job cap-1\)\.$/); +}); + +test("an undo archives nothing", async () => { + const e = editor(); + const out = await judgePress(e.ask, { lib: "lib", undo: true, set: [{ id: "1900000000000001001", state: "keep" }, { id: "1900000000000001002", state: "undecided", note: "dropped" }] }); + assert.equal(e.posts()[0].body.archive, false); + assert.equal(e.posts()[0].body.by, "operator"); + assert.deepEqual(e.posts()[0].body.set[1], { id: "1900000000000001002", state: "undecided" }); + assert.equal(out.sentence, "Undone: 2 judgements put back."); +}); + +test("bulk: every post the view matches, in chunks of at most 500 (one capture job per chunk), with the set that undoes it", async () => { + const rows = Array.from({ length: 620 }, (_, i) => ({ id: String(1900000000000002000n + BigInt(i)), thread: String(1900000000000002000n + BigInt(i)), detail: i === 0 ? { ownJudgement: { state: "later", note: "check", by: "agent", at: "t" } } : {} })); + const e = editor(rows); + const seen = []; + const out = await judgePress(e.ask, { lib: "lib", by: "agent", bulk: { view: { lib: "other", topic: "kettles", state: "unjudged", media: "1", new: "1" }, state: "keep", note: "all of it" }, expect: 620 }, { seenAt: async (lib, topic) => (seen.push([lib, topic]), "2026-11-17T10:00:00.000Z") }); + // The view's library is the body's `lib`, never the view's own. + const lists = e.asked.filter((a) => a.route.startsWith("/api/ops/trending")); + assert.deepEqual(seen, [["lib", "kettles"]]); + assert.equal(lists[0].route, "/api/ops/trending?slug=lib&topic=kettles&limit=500&state=unjudged&media=1&since=2026-11-17T10%3A00%3A00.000Z&detail=1"); + const judged = e.posts(); + assert.deepEqual(judged.map((p) => p.body.set.length), [500, 120]); + assert.ok(judged.every((p) => p.body.by === "operator" && p.body.set.every((s) => s.state === "keep" && s.note === "all of it" && s.id))); + assert.equal(out.archives.length, 2); + assert.equal(out.undo.length, 620); + assert.deepEqual(out.undo[0], { id: rows[0].id, state: "later", note: "check" }); + assert.deepEqual(out.undo[1], { id: rows[1].id, state: "undecided" }); + assert.match(out.sentence, /^620 judgements kept\. 620 posts queued for archiving \(the editor's capture jobs cap-\d+, cap-\d+\)\.$/); +}); + +test("bulk judges nothing when the filter no longer matches the count the confirm showed", async () => { + const e = editor([{ id: "1900000000000001001", thread: "1900000000000001001" }]); + await assert.rejects(judgePress(e.ask, { lib: "lib", bulk: { view: {}, state: "drop" }, expect: 3 }), (err) => err instanceof PressError && err.status === 409 && /now matches 1 post, not the 3 the confirm showed: nothing was judged/.test(err.message)); + assert.equal(e.posts().length, 0); + await assert.rejects(judgePress(e.ask, { lib: "lib", bulk: { view: {}, state: "drop" } }), /"expect"/); +}); + +test("refused before anything is asked: no library, both or neither of set and bulk, an ill-shaped set", async () => { + const e = editor(); + for (const [body, re] of [ + [null, /JSON object/], + [{ set: [] }, /"lib"/], + [{ lib: "../x", set: [{ id: "1", state: "keep" }] }, /"lib"/], + [{ lib: "lib" }, /one of them/], + [{ lib: "lib", set: [{ id: "1", state: "keep" }], bulk: {} }, /one of them/], + [{ lib: "lib", set: [] }, /"set" is a list/], + [{ lib: "lib", set: [{ id: "1", thread: "1", state: "keep" }] }, /one of them/], + [{ lib: "lib", set: [{ id: "../x", state: "keep" }] }, /not a post id/], + [{ lib: "lib", set: [{ id: "1", state: "deleted" }] }, /"state" is one of keep, drop, later, undecided/], + [{ lib: "lib", bulk: { view: {}, state: "purge" }, expect: 1 }, /"bulk.state"/], + ]) { + await assert.rejects(judgePress(e.ask, body), re); + } + assert.equal(e.asked.length, 0); +}); + +test("the watch's switch is the operator's; off sends no terms", async () => { + const e = editor(); + await watchPress(e.ask, { lib: "lib", topic: "kettles", on: true, intervalMinutes: 30, hours: 48, shots: true, by: "agent", settings: { maxTopics: 12 }, tick: true }); + assert.deepEqual(e.posts()[0], { route: "/api/ops/watch-trending", method: "POST", body: { slug: "lib", topic: "kettles", on: true, intervalMinutes: 30, hours: 48, shots: true, by: "operator" } }); + await watchPress(e.ask, { lib: "lib", topic: "kettles", on: false, intervalMinutes: 30 }); + assert.deepEqual(e.posts()[1].body, { slug: "lib", topic: "kettles", on: false, by: "operator" }); + await assert.rejects(watchPress(e.ask, { lib: "lib", topic: "kettles" }), /"on"/); + await assert.rejects(watchPress(e.ask, { lib: "lib", on: true }), /"topic"/); + await assert.rejects(watchPress(e.ask, { lib: "lib", topic: "kettles", on: true, hours: "48" }), /"hours" is a whole number/); +}); + +test("the purge is two presses: the dry run, then the removal with the dry run's digest, both the operator's", async () => { + const e = editor(); + await purgePress(e.ask, { lib: "lib", topic: "kettles", dryRun: true, by: "agent", ids: ["1"] }); + assert.deepEqual(e.posts()[0], { route: "/api/ops/purge-trending", method: "POST", body: { slug: "lib", topic: "kettles", dryRun: true, by: "operator" } }); + await purgePress(e.ask, { lib: "lib", confirm: "FAKE-TEST-VALUE" }); + assert.deepEqual(e.posts()[1].body, { slug: "lib", confirm: "FAKE-TEST-VALUE", by: "operator" }); + await assert.rejects(purgePress(e.ask, { lib: "lib" }), /carries the "confirm" its dry run answered/); + await assert.rejects(purgePress(e.ask, { lib: "lib", confirm: "yes" }), /confirm/); + assert.equal(e.posts().length, 2); +}); diff --git a/umtool/lib/library/route.ts b/umtool/lib/library/route.ts @@ -0,0 +1,34 @@ +import { askEditor, EditorError } from "@/lib/articles/generation"; +import { PressError } from "@/lib/library/presses.mjs"; + +// What the Posts library's press routes share (lane posts-library). +// +// THESE ROUTES ARE THE PAGE'S: every press through them is stamped the +// operator's (lib/library/presses.mjs). A request carrying an Authorization +// header is an agent or the editor, and is refused here: an agent judges +// through `pnpm ops` or `umtool library`, where it says who it is. + +export const NO_STORE = { "cache-control": "no-store" }; + +export const AGENTS_GO_ELSEWHERE = + "This route is the Posts library page's: its presses are written as the operator's. An agent uses `pnpm ops judge-trending` / `watch-trending` / `purge-trending` or `umtool library`, and says \"by\": \"agent\"."; + +export function refuseAgent(request: Request): Response | null { + return request.headers.get("authorization") === null ? null : Response.json({ error: AGENTS_GO_ELSEWHERE }, { status: 403, headers: NO_STORE }); +} + +export const ask = (route: string, init?: { method?: "GET" | "POST"; body?: unknown }) => askEditor<Record<string, unknown>>(route, init); + +/** Run one press: the body parsed, the press's answer, or its refusal in its own words. */ +export async function press(request: Request, run: (body: unknown) => Promise<unknown>): Promise<Response> { + const refused = refuseAgent(request); + if (refused) return refused; + const body = await request.json().catch(() => null); + try { + return Response.json(await run(body), { headers: NO_STORE }); + } catch (err) { + const status = err instanceof PressError || err instanceof EditorError ? err.status : 500; + const reason = err instanceof EditorError ? { reason: err.reason } : {}; + return Response.json({ error: err instanceof Error ? err.message : String(err), ...reason }, { status, headers: NO_STORE }); + } +}