// WHO IS WRITING A NOTE over HTTP (release 23 F3; ruled 2026-10-10: agents get // their own write path, attributed "agent", never as the operator). // // The app's /api/notes POST stamps every write from the page as the // OPERATOR's. An agent — the MCP's `notes` reply — writes through the same // route with `Authorization: Bearer `, and its write is stamped // "agent": // // no Authorization header "operator" (the page, as before) // Bearer "agent" // any other Authorization header 401, nothing written — including any // bearer when umtool holds no token // // `by` is never read from the request body: who wrote a note is what the // request proves, not what it says. // // umtool's WORKER_TOKEN is read the way the editor's clients read it (`pnpm // ops`'s loadEditorEnv, release 19 A1): the environment — an explicit value, // even "", wins — else the first of this checkout's `editor/.env.local`, // `editor/.env`, then the main worktree's, that names it. The same secret the // editor's /api/ops takes. Read per request: a token set in editor/.env after // umtool started is honoured without a restart. import crypto from "node:crypto"; import { readFileSync } from "node:fs"; import path from "node:path"; import { REPO_ROOT } from "../paths.mjs"; import { writeNote } from "./targets.mjs"; /** * The value of one key in a dotenv text (`KEY=value`, `export KEY=value`, * quotes stripped, an unquoted value ending at an inline comment), or * undefined. scripts/archilyzer-ops.mjs parseDotenv's rules. * @param {string} text * @param {string} key * @returns {string | undefined} */ export function dotenvValue(text, key) { let out; for (const raw of text.split(/\r?\n/)) { const line = raw.trim(); if (!line || line.startsWith("#")) continue; const m = /^(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*)$/.exec(line); if (!m || m[1] !== key) continue; let value = m[2].trim(); const q = value[0]; if ((q === '"' || q === "'") && value.length >= 2 && value.endsWith(q)) value = value.slice(1, -1); else value = value.replace(/\s+#.*$/, ""); out = value; } return out; } /** * The main worktree of a linked worktree, or null (read off disk, as * scripts/archilyzer-ops.mjs mainWorktreeOf does). * @param {string} root */ function mainWorktreeOf(root) { try { const m = /^gitdir:\s*(.+)$/m.exec(readFileSync(path.join(/* turbopackIgnore: true */ root, ".git"), "utf8")); if (!m) return null; const gitdir = path.resolve(/* turbopackIgnore: true */ root, m[1].trim()); const common = path.resolve( /* turbopackIgnore: true */ gitdir, readFileSync(path.join(/* turbopackIgnore: true */ gitdir, "commondir"), "utf8").trim(), ); return path.dirname(common); } catch { return null; } } /** * The editor env files consulted, in order. * @param {string} [root] * @returns {string[]} */ export function editorEnvFiles(root = REPO_ROOT) { const roots = [root]; const main = mainWorktreeOf(root); if (main && path.resolve(/* turbopackIgnore: true */ main) !== path.resolve(/* turbopackIgnore: true */ root)) roots.push(main); return roots.flatMap((r) => [ path.join(/* turbopackIgnore: true */ r, "editor", ".env.local"), path.join(/* turbopackIgnore: true */ r, "editor", ".env"), ]); } /** * umtool's WORKER_TOKEN: the environment's, else the editor's env files'. "" * when none is set — and then no bearer matches. * @param {Record} [env] * @param {string[]} [files] * @returns {string} */ export function agentToken(env = process.env, files = editorEnvFiles()) { if (env.WORKER_TOKEN !== undefined) return env.WORKER_TOKEN; for (const file of files) { let text; try { text = readFileSync(file, "utf8"); } catch { continue; } const v = dotenvValue(text, "WORKER_TOKEN"); if (v !== undefined) return v; } return ""; } /** * Who a request's Authorization header says is writing. * @param {string | null | undefined} authorization * @param {string} token umtool's WORKER_TOKEN ("" for none) * @returns {{ ok: true, by: "operator" | "agent" } | { ok: false, status: 401, error: string }} */ export function noteWriter(authorization, token) { if (authorization === null || authorization === undefined || authorization === "") return { ok: true, by: "operator" }; const m = /^Bearer\s+(.+)$/i.exec(authorization); if (!m) return { ok: false, status: 401, error: "notes: an Authorization header must be `Bearer `" }; if (!token) { return { ok: false, status: 401, error: "notes: umtool holds no WORKER_TOKEN, so no agent can write here" }; } const given = Buffer.from(m[1].trim()); const want = Buffer.from(token); if (given.length !== want.length || !crypto.timingSafeEqual(given, want)) { return { ok: false, status: 401, error: "notes: that bearer token is not umtool's WORKER_TOKEN" }; } return { ok: true, by: "agent" }; } /** * Who is calling an editor-facing route (release 36: /api/report/clips): the * same rule as noteWriter. No Authorization header is the app's own page (as * before); `Bearer ` is the editor (or an agent); any * other header is a 401. * @param {string | null | undefined} authorization * @param {string} token umtool's WORKER_TOKEN ("" for none) * @param {string} [what] the route, for the refusal * @returns {{ ok: true, by: "page" | "worker" } | { ok: false, status: 401, error: string }} */ export function routeCaller(authorization, token, what = "this route") { const w = noteWriter(authorization, token); if (w.ok) return { ok: true, by: w.by === "agent" ? "worker" : "page" }; return { ok: false, status: 401, error: w.error.replace(/^notes:/, `${what}:`).replace("no agent can write here", "no editor can call it") }; } /** * The POST: one op on a target's notes, by whoever the header proves. A refusal * is `{ status, body: { error } }`; a write `{ status: 200, body }` with what * writeNote returns. A stale token or a refused op THROWS (the route's * errorResponse gives each its status). * @param {Parameters[0]} target * @param {unknown} body `{ token?, op }` — any `by` in it is ignored * @param {{ authorization?: string | null, workerToken: string }} auth */ export async function postNoteOp(target, body, auth) { const who = noteWriter(auth.authorization, auth.workerToken); if (!who.ok) return { status: who.status, body: { error: who.error } }; const b = /** @type {{ token?: unknown, op?: unknown } | null} */ (body && typeof body === "object" ? body : null); if (!b || typeof b.op !== "object" || b.op === null) return { status: 400, body: { error: "body needs an op" } }; const token = typeof b.token === "string" ? b.token : null; const out = await writeNote(target, /** @type {Record} */ (b.op), { by: who.by, token }); return { status: 200, body: out }; }