Archilyzer · Source

archilyzer

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

commit e49ba3f58a78906a396fdf8d3a6ce553e108a7da
parent 75d07b9cabe7e1babcd8b025abf33b41b48b57f0
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Tue, 10 Nov 2026 10:35:44 -0500

umtool: L4 review -- another site's write refused on the one-press routes; a link's YouTube id may start with -; calls age in a running process; the case index opened once (redesign L4)

- links POST, takes/verdict POST and window PUT call crossSiteRefusal (sameOrigin.mjs); the verdict
  route gains refuseCaller like its siblings. needs-you.test.ts: a cross-site and a rebinding
  write are 403 on all three, this app's own page still writes.
- momentLink.mjs: a typed `<channel>/<video>@…` or `<video>@…` still refuses a video starting with
  `-`; a link's id is the platform's and may (`-`/`_`, ~1 in 64 YouTube ids). quickClipSpec takes a
  dash video id only when YouTube-shaped (11 chars; the channel never), and POST
  /api/report/quick-clip passes the spec after `--` (`umtool clip` reads `--`). parseTime refuses
  `:` and empty parts.
- projectCalls.ts: a 6-hour clock bucket in the signature, so rows go Quiet at RECENT_DAYS.
- caseCues.ts: the transcript index opened once per read, lazily, cases read in turn.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

Diffstat:
Mumtool/app/api/report/links/route.ts | 4++++
Mumtool/app/api/report/quick-clip/route.ts | 4+++-
Mumtool/app/api/report/takes/verdict/route.ts | 7+++++++
Mumtool/app/api/report/window/route.ts | 4++++
Mumtool/lib/inbox/caseCues.ts | 64+++++++++++++++++++++++++++++++++++++++++++---------------------
Mumtool/lib/inbox/needs-you.test.ts | 26++++++++++++++++++++++++++
Mumtool/lib/inbox/projectCalls.ts | 4+++-
Mumtool/lib/report/momentLink.mjs | 17+++++++++++++----
Mumtool/lib/report/momentLink.test.mjs | 10++++++++++
Mumtool/lib/report/quickClip.mjs | 19++++++++++++++++---
Mumtool/lib/report/quickClipStrip.test.mjs | 16++++++++++++++++
11 files changed, 145 insertions(+), 30 deletions(-)

diff --git a/umtool/app/api/report/links/route.ts b/umtool/app/api/report/links/route.ts @@ -2,6 +2,7 @@ import { projectRef } from "@/lib/projects"; import { readManifest } from "@/lib/projects/report.mjs"; import { linkVerdicts, readLinkCheck, runLinkCheck } from "@/lib/report/linkCheck.mjs"; import { refuseCaller } from "@/lib/report/caller"; +import { crossSiteRefusal } from "@/lib/report/sameOrigin.mjs"; import { applyLinkFixes } from "@/lib/report/linksCli.mjs"; export const dynamic = "force-dynamic"; @@ -38,6 +39,9 @@ export async function GET(request: Request) { export async function POST(request: Request) { const refused = refuseCaller(request, "/api/report/links"); if (refused) return refused; + // Another site's page may not write here (lib/report/sameOrigin.mjs: Sec-Fetch-Site, Origin, a loopback Host). + const cross = crossSiteRefusal(request.headers); + if (cross) return Response.json({ error: cross }, { status: 403 }); const b = (await request.json().catch(() => null)) as { project?: unknown; fix?: unknown } | null; if (!b || typeof b !== "object") return Response.json({ error: "bad json" }, { status: 400, headers }); const project = await projectRef(String(b.project ?? "")); diff --git a/umtool/app/api/report/quick-clip/route.ts b/umtool/app/api/report/quick-clip/route.ts @@ -37,8 +37,10 @@ export async function POST(request: Request) { const running = runningJob(); if (running) return Response.json({ error: `a job is already running (${running.kind}) — make the clip when it is done`, running: jobView(running) }, { status: 409, headers }); const argv = [ - process.execPath, path.join(/* turbopackIgnore: true */ UMTOOL_DIR, "bin", "umtool.mjs"), "clip", spec, + process.execPath, path.join(/* turbopackIgnore: true */ UMTOOL_DIR, "bin", "umtool.mjs"), "clip", ...(snap ? ["--snap", snap] : []), ...(title ? ["--title", title] : []), ...(site ? ["--site", site] : []), "--progress", "ndjson", + // The spec after `--`: never read as a flag, whatever its ids (a YouTube id may start with `-`). + "--", spec, ]; const job = startJob(`quick clip ${spec}`, [{ cwd: UMTOOL_DIR, env: {}, label: `quick clip ${spec}${snap ? " (snapped to the words)" : ""}`, argv, ndjson: true, timeoutMs: 90 * 60_000 }]); return Response.json({ ok: true, job: jobView(job) }, { status: 202, headers }); diff --git a/umtool/app/api/report/takes/verdict/route.ts b/umtool/app/api/report/takes/verdict/route.ts @@ -1,5 +1,7 @@ import { projectRef } from "@/lib/projects"; import { isTakeId, listTakes, readVerdicts, setTakeVerdict } from "@/lib/report/takes.mjs"; +import { refuseCaller } from "@/lib/report/caller"; +import { crossSiteRefusal } from "@/lib/report/sameOrigin.mjs"; export const dynamic = "force-dynamic"; @@ -18,6 +20,11 @@ export async function GET(request: Request) { } export async function POST(request: Request) { + const refused = refuseCaller(request, "/api/report/takes/verdict"); + if (refused) return refused; + // Another site's page may not write here (lib/report/sameOrigin.mjs: Sec-Fetch-Site, Origin, a loopback Host). + const cross = crossSiteRefusal(request.headers); + if (cross) return Response.json({ error: cross }, { status: 403 }); const body = (await request.json().catch(() => null)) as { project?: string; take?: string; diff --git a/umtool/app/api/report/window/route.ts b/umtool/app/api/report/window/route.ts @@ -3,6 +3,7 @@ import { MarksOutside, StaleToken, updateClip } from "@/lib/report/manifest.mjs" import { updateTakeClip } from "@/lib/report/takeEdit.mjs"; import { resolveClip } from "@/lib/report/serve.mjs"; import { refuseCaller } from "@/lib/report/caller"; +import { crossSiteRefusal } from "@/lib/report/sameOrigin.mjs"; export const dynamic = "force-dynamic"; @@ -19,6 +20,9 @@ export const dynamic = "force-dynamic"; export async function PUT(request: Request) { const refused = refuseCaller(request, "/api/report/window"); if (refused) return refused; + // Another site's page may not write here (lib/report/sameOrigin.mjs: Sec-Fetch-Site, Origin, a loopback Host). + const cross = crossSiteRefusal(request.headers); + if (cross) return Response.json({ error: cross }, { status: 403 }); let body: Record<string, unknown>; try { body = await request.json(); diff --git a/umtool/lib/inbox/caseCues.ts b/umtool/lib/inbox/caseCues.ts @@ -35,25 +35,19 @@ const memo: Memo = (g.__umtoolCaseCuesMemo ??= new Map()); /** A cue file's name: the transcript and its sidecars, a caption track. */ const CUE_FILE = /^(transcript\..+|.+\.vtt)$/; -/** Per video of `slugs`, when its cues were last written (ms), from the index. */ -async function fromIndex(lmdbPath: string, slugs: string[]): Promise<Row[]> { - const { open } = await import("lmdb"); - const root = open({ path: lmdbPath, readOnly: true, maxDbs: 14 }); - try { - const mtimes = root.openDB<{ transcriptMs?: number | null; subsMs?: number | null }, [string, string]>({ name: "mtimes", encoding: "msgpack" }); - const out: Row[] = []; - for (const slug of slugs) { - for (const { key, value } of mtimes.getRange({ start: [slug], end: [slug, "￿"] })) { - const k = key as [string, string]; - if (k[0] !== slug) break; - const at = Math.max(value?.transcriptMs ?? 0, value?.subsMs ?? 0); - if (at > 0) out.push({ channel: slug, id: k[1], at }); - } +/** Per video of `slugs`, when its cues were last written (ms), from an index already open. */ +type MtimesDb = { getRange(o: { start: unknown; end: unknown }): Iterable<{ key: unknown; value: { transcriptMs?: number | null; subsMs?: number | null } }> }; +function fromIndex(mtimes: MtimesDb, slugs: string[]): Row[] { + const out: Row[] = []; + for (const slug of slugs) { + for (const { key, value } of mtimes.getRange({ start: [slug], end: [slug, "\uffff"] })) { + const k = key as [string, string]; + if (k[0] !== slug) break; + const at = Math.max(value?.transcriptMs ?? 0, value?.subsMs ?? 0); + if (at > 0) out.push({ channel: slug, id: k[1], at }); } - return out; - } finally { - await root.close(); } + return out; } /** The same from the files: each video directory's newest cue file. */ @@ -77,7 +71,7 @@ async function fromFiles(channelsDir: string, slugs: string[]): Promise<Row[]> { return out; } -async function caseRow(id: string): Promise<Decision | null> { +async function caseRow(id: string, index: () => Promise<MtimesDb | null>): Promise<Decision | null> { const dir = caseDir(REPORTS_ROOT, id); const def = await readDefinition(dir, id); if (!def || def.status === "done") return null; @@ -88,7 +82,8 @@ async function caseRow(id: string): Promise<Decision | null> { if (hit && Date.now() - hit.at < MEMO_MS) return hit.value; const paths = corpusPaths(); const { slugs } = await caseChannels(paths, def); - const rows = existsSync(/* turbopackIgnore: true */ paths.lmdbPath) ? await fromIndex(paths.lmdbPath, slugs) : await fromFiles(CHANNELS_DIR, slugs); + const mtimes = await index(); + const rows = mtimes ? fromIndex(mtimes, slugs) : await fromFiles(CHANNELS_DIR, slugs); const title = (await readCase(REPORTS_ROOT, id).catch(() => null))?.title ?? id; const value = caseCuesDecision({ id, title, since, fresh: newSince(rows, since), href: researchCasePipelineHref(id) }) as Decision | null; for (const k of memo.keys()) if (k.startsWith(`${id}:`)) memo.delete(k); @@ -101,8 +96,35 @@ export async function caseCuesDecisions(): Promise<Decision[]> { try { const names = await readdir(/* turbopackIgnore: true */ researchDir(REPORTS_ROOT), { withFileTypes: true }).catch(() => []); const ids = names.filter((d) => d.isDirectory() && isCaseId(d.name)).map((d) => d.name); - const rows = await Promise.all(ids.map((id) => caseRow(id).catch(() => null))); - return rows.filter((r): r is Decision => r !== null); + if (!ids.length) return []; + // The index opened ONCE for every case (lmdb-js shares an environment by path: a close per case could + // end another case's range read), and the cases read one after another. + // Opened only when a case is not answered from the memo. + const lmdbPath = corpusPaths().lmdbPath; + type Env = { openDB: (o: object) => unknown; close: () => Promise<void> }; + let root = null as Env | null; + let opened: Promise<MtimesDb | null> | null = null; + const index = () => + (opened ??= (async () => { + if (!existsSync(/* turbopackIgnore: true */ lmdbPath)) return null; + try { + const { open } = await import("lmdb"); + root = open({ path: lmdbPath, readOnly: true, maxDbs: 14 }) as unknown as Env; + return root.openDB({ name: "mtimes", encoding: "msgpack" }) as MtimesDb; + } catch { + return null; + } + })()); + try { + const out: Decision[] = []; + for (const id of ids) { + const r = await caseRow(id, index).catch(() => null); + if (r) out.push(r); + } + return out; + } finally { + await root?.close().catch(() => {}); + } } catch { return []; } diff --git a/umtool/lib/inbox/needs-you.test.ts b/umtool/lib/inbox/needs-you.test.ts @@ -248,3 +248,29 @@ test("from the editor: no row while no X work waits; the row once the jar's aler await new Promise<void>((r) => editor.close(() => r())); assert.deepEqual(await xJarDecisions(), []); }); + +test("the one-press routes refuse another site's write (sameOrigin.mjs) and still take this app's own", async () => { + const routes = [ + { mod: await import("../../app/api/report/links/route"), method: "POST" as const, body: { project: "ny-cut", fix: true } }, + { mod: await import("../../app/api/report/takes/verdict/route"), method: "POST" as const, body: { project: "ny-cut", take: "v2", verdict: "like" } }, + { mod: await import("../../app/api/report/window/route"), method: "PUT" as const, body: { project: "ny-cut", clip: "c02", lockCut: true } }, + ]; + for (const { mod, method, body } of routes) { + const handler = (mod as unknown as Record<string, (r: Request) => Promise<Response>>)[method]; + // A text/plain form post from evil.example to this app: no preflight, refused before the body is read. + const cross = await handler( + new Request("http://localhost:3050/api/x", { method, headers: { host: "localhost:3050", origin: "https://evil.example", "sec-fetch-site": "cross-site", "content-type": "text/plain" }, body: JSON.stringify(body) }), + ); + assert.equal(cross.status, 403, method); + assert.match(((await cross.json()) as { error: string }).error, /refused/); + // A rebinding page (Host: evil.example) is refused too. + const rebound = await handler(new Request("http://evil.example/api/x", { method, headers: { host: "evil.example:3050" }, body: JSON.stringify(body) })); + assert.equal(rebound.status, 403); + } + // This app's own page (same-origin) gets past the guard: the verdict is written. + const verdict = (await import("../../app/api/report/takes/verdict/route")) as unknown as { POST: (r: Request) => Promise<Response> }; + const own = await verdict.POST( + new Request("http://localhost:3050/api/report/takes/verdict", { method: "POST", headers: { host: "localhost:3050", origin: "http://localhost:3050", "sec-fetch-site": "same-origin", "content-type": "application/json" }, body: JSON.stringify({ project: "ny-cut", take: "v2", verdict: "no" }) }), + ); + assert.equal(own.status, 200, await own.clone().text()); +}); diff --git a/umtool/lib/inbox/projectCalls.ts b/umtool/lib/inbox/projectCalls.ts @@ -45,7 +45,9 @@ async function signatureOf(dir: string): Promise<string> { const entries = await readdir(/* turbopackIgnore: true */ takes).catch(() => [] as string[]); const per = await Promise.all(entries.filter((n) => !n.startsWith(".")).sort().map(async (n) => `${n}@${await stamp(path.join(takes, n))}`)); const [man, qc, verdicts] = await Promise.all([stamp(path.join(dir, "video.manifest.json")), stamp(path.join(dir, QUOTE_CHECK_FILE)), stamp(verdictsFileOf(dir))]); - return [man, qc, verdicts, per.join(",")].join("|"); + // A coarse clock too: versions.mjs and walk.mjs age rows into Quiet at RECENT_DAYS, which no file says. + const bucket = Math.floor(Date.now() / (6 * 3600_000)); + return [man, qc, verdicts, per.join(","), bucket].join("|"); } /** A quick clip's project (lib/report/quickClip.mjs: `<reports>/quick-clips/<slug>`): a share, not a piece in the making. */ diff --git a/umtool/lib/report/momentLink.mjs b/umtool/lib/report/momentLink.mjs @@ -23,14 +23,23 @@ export function parseTime(v) { if (/^\d+(\.\d+)?s?$/.test(s)) return Number(s.replace(/s$/, "")); const hms = /^(?:(\d+)h)?(?:(\d+)m)?(?:(\d+(?:\.\d+)?)s)?$/.exec(s); if (hms && (hms[1] || hms[2] || hms[3])) return Number(hms[1] ?? 0) * 3600 + Number(hms[2] ?? 0) * 60 + Number(hms[3] ?? 0); - const parts = s.split(":").map(Number); + const raw = s.split(":"); + // `:` alone, or an empty part (`1:`, `:30`), is not a time. + if (raw.some((p) => !/^\d+(\.\d+)?$/.test(p))) return null; + const parts = raw.map(Number); if (parts.length >= 2 && parts.length <= 3 && parts.every((n) => Number.isFinite(n))) return parts.reduce((a, n) => a * 60 + n, 0); return null; } const ID = /^[A-Za-z0-9_-]{2,}$/; const CHANNEL = /^[A-Za-z0-9][A-Za-z0-9._-]*$/; -const ok = (channel, video) => (channel === null || (CHANNEL.test(channel) && !/^\.+$/.test(channel))) && ID.test(video) && !video.startsWith("-"); +/** + * The ids of a moment. TYPED forms (`<channel>/<video>@…`, `<video>@…`) refuse a video starting with `-`: typed, + * it is likelier a slip than an id. A LINK's video id is the platform's, and a YouTube id may start with `-` or `_` + * (about 1 in 64): accepted -- it reaches a child's argv only inside the `<channel>/<video>@…` word, after `--`. + */ +const ok = (channel, video, { typed = false } = {}) => + (channel === null || (CHANNEL.test(channel) && !/^\.+$/.test(channel))) && ID.test(video) && !(typed && video.startsWith("-")); /** The time a link names: `t=` / `start=` in its query, else `t=` in its hash; 0 when none. */ function linkTime(u) { @@ -52,14 +61,14 @@ export function parseMomentInput(raw) { const [, channel, video, a, b] = span; const start = Number(a); const end = Number(b); - return ok(channel, video) && end > start ? { channel, video, start, end, via: "spec" } : null; + return ok(channel, video, { typed: true }) && end > start ? { channel, video, start, end, via: "spec" } : null; } // [<channel>/]<video>@<time> const short = /^(?:([A-Za-z0-9][A-Za-z0-9._-]*)\/)?([A-Za-z0-9_-]{2,})@([0-9:hms.]+)$/.exec(s); if (short) { const t = parseTime(short[3]); const channel = short[1] ?? null; - return t === null || !ok(channel, short[2]) ? null : { channel, video: short[2], start: t, end: null, via: "short" }; + return t === null || !ok(channel, short[2], { typed: true }) ? null : { channel, video: short[2], start: t, end: null, via: "short" }; } let u; diff --git a/umtool/lib/report/momentLink.test.mjs b/umtool/lib/report/momentLink.test.mjs @@ -11,6 +11,7 @@ test("times: seconds, h:m:s, 62m32s, 1h2m32s; nothing else", () => { assert.equal(parseTime("62m32s"), 3752); assert.equal(parseTime("1h2m32s"), 3752); assert.equal(parseTime("soon"), null); + for (const bad of [":", "1:", ":30", "1::2"]) assert.equal(parseTime(bad), null, bad); assert.equal(parseTime(""), null); }); @@ -41,3 +42,12 @@ test("YouTube and Rumble links: the video and the second; the channel is the dis assert.equal(parseMomentInput("https://rumble.com/c/SomeChannel"), null); assert.equal(parseMomentInput("https://example.com/watch?v=abcdef&t=nope"), null); }); + +test("a link's YouTube id may start with - or _ (about 1 in 64); a typed one may not start with -", () => { + assert.deepEqual(parseMomentInput("https://www.youtube.com/watch?v=-abcDEF1234&t=5"), { channel: null, video: "-abcDEF1234", start: 5, end: null, via: "youtube" }); + assert.deepEqual(parseMomentInput("https://youtu.be/_abcDEF1234?t=7"), { channel: null, video: "_abcDEF1234", start: 7, end: null, via: "youtube" }); + assert.deepEqual(parseMomentInput("https://jeralyzer.pages.dev/?v=chan%2F-abcDEF1234&t=9"), { channel: "chan", video: "-abcDEF1234", start: 9, end: null, via: "archive" }); + assert.deepEqual(parseMomentInput("chan/_abcDEF1234@1-2"), { channel: "chan", video: "_abcDEF1234", start: 1, end: 2, via: "spec" }); + assert.equal(parseMomentInput("chan/-abcDEF1234@1-2"), null); + assert.equal(parseMomentInput("-abcDEF1234@12"), null); +}); diff --git a/umtool/lib/report/quickClip.mjs b/umtool/lib/report/quickClip.mjs @@ -63,17 +63,25 @@ const fin = (v) => typeof v === "number" && Number.isFinite(v); /** * A quick clip's spec, parsed and checked: `<channel>/<video>@<start>-<end>`, the end after the start, and - * neither id a path trick -- not all dots (`..`) and not starting with `-` (an argv flag) -- so the names - * that reach the disk and a child's argv are ids. Null when it is not one. Pure. + * neither id a path trick -- not all dots (`..`); the channel not starting with `-` (an argv flag), the video + * only when it is a YouTube id (redesign L4: those can start with `-`) -- so the names that reach the disk and a + * child's argv are ids. Null when it is not one. Pure. * @param {unknown} spec */ export function quickClipSpec(spec) { const c = parseClipSpec(spec); if (!c || !(c.end > c.start)) return null; - for (const id of [c.channel, c.video]) if (/^\.+$/.test(id) || id.startsWith("-")) return null; + for (const id of [c.channel, c.video]) if (/^\.+$/.test(id)) return null; + // The channel heads the argv word, so it never starts with `-`. A video id may only when it is YouTube-shaped + // (11 of [A-Za-z0-9_-]: about 1 id in 64 starts with `-`): the app's job passes the spec after `--` anyway. + if (c.channel.startsWith("-")) return null; + if (c.video.startsWith("-") && !YOUTUBE_ID.test(c.video)) return null; return c; } +/** A YouTube video id: 11 characters of the URL-safe base64 alphabet. */ +const YOUTUBE_ID = /^[A-Za-z0-9_-]{11}$/; + /** A project slug from words: lower-case letters, digits and dashes, at most 48, never `share-…` (a deliverables link's name). */ export function quickClipSlug({ title = null, channel, video, start }) { const clean = (words) => String(words).toLowerCase().normalize("NFKD").replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 48).replace(/-+$/, ""); @@ -278,6 +286,11 @@ export async function quickClipCommand(args, { root = REPORTS_ROOT, log = consol try { for (let i = 0; i < args.length; i += 1) { const a = args[i]; + // `--`: every word after it is the spec, never a flag (the app's job passes it so). + if (a === "--") { + words.push(...args.slice(i + 1)); + break; + } if (!a.startsWith("--")) words.push(a); else if (valued.has(a)) { if (i + 1 >= args.length) throw new CliError(`${a} needs a value`); diff --git a/umtool/lib/report/quickClipStrip.test.mjs b/umtool/lib/report/quickClipStrip.test.mjs @@ -6,6 +6,7 @@ import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises"; import os from "node:os"; import path from "node:path"; import { MomentError, findRecording, quickClipStrip, spanOf } from "./quickClipStrip.mjs"; +import { quickClipCommand, quickClipSpec } from "./quickClip.mjs"; const cues = [ { start: 0, end: 4, text: "first we go" }, @@ -54,3 +55,18 @@ test("the recording found on the disk: by its channel, by the one channel holdin await rm(root, { recursive: true, force: true }); } }); + +test("a quick clip's spec: a YouTube id starting with - is one (the job passes the spec after --); `-x`, a dash channel or dots are not", () => { + assert.deepEqual(quickClipSpec("chan/-abcDEF1234@1-2"), { channel: "chan", video: "-abcDEF1234", start: 1, end: 2 }); + assert.ok(quickClipSpec("chan/_abcDEF1234@1-2")); + for (const bad of ["chan/-x@1-2", "-rf/vid@1-2", "../vid@1-2", "chan/..@1-2", "chan/vid@2-1"]) assert.equal(quickClipSpec(bad), null, bad); +}); + +test("umtool clip -- <spec>: the word after -- is the spec, never a flag", async () => { + const out = []; + const err = []; + // A spec that parses but names no recording here: the command reaches the spec check, not "unknown flag". + const code = await quickClipCommand(["--json", "--", "nochan/-abcDEF1234@1-2"], { root: "/nonexistent-umtool-root", log: (s) => out.push(s), err: (s) => err.push(s), channelsDir: "/nonexistent-umtool-channels" }); + assert.notEqual(code, 0); + assert.doesNotMatch(err.join("\n"), /unknown flag/); +});