82 lines
5.8 KiB
JavaScript
82 lines
5.8 KiB
JavaScript
// Sage, 2026-10-12: Vikunja #151, a key for Mos (Q58, Q109; Mos sage-0083). svc-mosaic-stack mints the
|
|
// bot user bot-mosaic-stack-mos and one API key for it. The key goes straight to a 0600 file (flag wx,
|
|
// never overwritten) and never reaches stdout. Scopes are Mos's catalogue (projects*, tasks*, labels,
|
|
// filters, reactions) cut to Q61a's limit: no delete or duplicate on tasks, projects, views, buckets,
|
|
// labels or filters, and no share, team, user, token, webhook, migration, other or notification group.
|
|
// The deletes kept are join rows the pm already holds (assignees, labels, relations) and own reactions.
|
|
// svc left both teams on 2026-10-11 (decision 85), so adding the bot to team 1 is Jason's step; until
|
|
// then the key reaches no project. Inverse: svc revokes the key (DELETE /api/v1/tokens/:id).
|
|
// Usage: node mint-mos.mjs https://tasks.woltje.com SVC_PASSWORD_FILE TOKEN_FILE OUT_JSON
|
|
import { readFileSync, writeFileSync, existsSync, statSync } from "node:fs";
|
|
const [ORIGIN, PW, TOKEN_FILE, OUT] = process.argv.slice(2);
|
|
if (!/^https:\/\/tasks\.woltje\.com$/.test(ORIGIN)) throw new Error("tasks.woltje.com only");
|
|
if (!OUT || existsSync(OUT)) throw new Error("OUT_JSON missing or exists; refusing to rerun");
|
|
if (!TOKEN_FILE || existsSync(TOKEN_FILE)) throw new Error("TOKEN_FILE missing or exists; refusing");
|
|
const USER = "bot-mosaic-stack-mos", EXP = "2027-01-07T00:00:00Z", TITLE = "mosaic-stack-mos-2026-10-12-151";
|
|
const GROUPS = ["projects", "projects_views", "projects_views_tasks", "tasks", "tasks_assignees", "tasks_attachments",
|
|
"tasks_comments", "tasks_labels", "tasks_relations", "labels", "filters", "reactions"];
|
|
const JOIN_DELETES = ["tasks_assignees", "tasks_labels", "tasks_relations", "reactions"];
|
|
const forbidden = (g, p) => !GROUPS.includes(g) || (/delete|duplicate/.test(p) && !JOIN_DELETES.includes(g));
|
|
async function api(method, path, body, auth) {
|
|
const headers = { "Content-Type": "application/json" };
|
|
if (auth) headers.Authorization = `Bearer ${auth}`;
|
|
const r = await fetch(ORIGIN + path, { method, headers, body: body === undefined ? undefined : JSON.stringify(body), redirect: "error" });
|
|
const t = await r.text(); let json = null; try { json = JSON.parse(t); } catch {}
|
|
return { status: r.status, json };
|
|
}
|
|
const must = (r, l) => { if (r.status >= 300) throw new Error(`${l}: ${r.status} ${r.json?.code ?? ""} ${r.json?.message ?? ""}`); return r.json; };
|
|
const password = readFileSync(PW, "utf8").trim();
|
|
const tok = must(await api("POST", "/api/v2/login", { username: "svc-mosaic-stack", password }), "login svc").token;
|
|
if (!tok) throw new Error("login svc: no token field");
|
|
const secrets = [password, tok];
|
|
const rec = { at: new Date().toISOString(), user: USER, problems: [] };
|
|
const save = () => {
|
|
const out = JSON.stringify(rec, null, 1) + "\n";
|
|
if (secrets.some((s) => s && out.includes(s))) throw new Error("secret in the record; not written");
|
|
writeFileSync(OUT, out);
|
|
};
|
|
|
|
// Preconditions before any write: the bot doesn't exist, and the scope set is clean.
|
|
const bots = must(await api("GET", "/api/v1/user/bots", undefined, tok), "list bots");
|
|
const botList = bots?.items ?? bots;
|
|
if (!Array.isArray(botList)) throw new Error("list bots: no array");
|
|
if (botList.some((b) => b.username === USER)) throw new Error(`${USER} exists; refusing`);
|
|
const routes = must(await api("GET", "/api/v2/routes", undefined, tok), "routes");
|
|
const permissions = {};
|
|
for (const g of GROUPS) {
|
|
const ps = Object.keys(routes[g] ?? {}).filter((p) => !forbidden(g, p)).sort();
|
|
if (ps.length) permissions[g] = ps;
|
|
}
|
|
for (const [g, ps] of Object.entries(permissions)) for (const p of ps) if (forbidden(g, p)) throw new Error(`forbidden ${g}.${p}`);
|
|
rec.permissions = permissions;
|
|
writeFileSync(OUT, "", { flag: "wx" });
|
|
|
|
const b = await api("PUT", "/api/v1/user/bots", { username: USER, name: "mosaic-stack mos" }, tok);
|
|
rec.botCreate = b.status;
|
|
if (b.status >= 300 || !Number.isSafeInteger(b.json?.id)) { rec.problems.push(`bot create: ${b.status} ${b.json?.message ?? ""}`); save(); process.exit(2); }
|
|
rec.botId = b.json.id;
|
|
save();
|
|
const t = await api("PUT", "/api/v1/tokens", { title: TITLE, owner_id: rec.botId, expires_at: EXP, permissions }, tok);
|
|
rec.tokenCreate = t.status;
|
|
if (t.status >= 300 || !Number.isSafeInteger(t.json?.id) || typeof t.json?.token !== "string") { rec.problems.push(`token create: ${t.status} ${t.json?.message ?? ""}`); save(); process.exit(2); }
|
|
const key = t.json.token;
|
|
secrets.push(key);
|
|
writeFileSync(TOKEN_FILE, key + "\n", { flag: "wx", mode: 0o600 });
|
|
Object.assign(rec, { tokenId: t.json.id, expires: t.json.expires_at, startsTk: key.startsWith("tk_"), file: TOKEN_FILE, mode: (statSync(TOKEN_FILE).mode & 0o777).toString(8),
|
|
inverse: `svc: DELETE /api/v1/tokens/${t.json.id}` });
|
|
// Read back as svc: the bot holds exactly this key with these scopes.
|
|
const keys = must(await api("GET", `/api/v2/tokens?owner_id=${rec.botId}&per_page=50`, undefined, tok), "bot keys").items ?? [];
|
|
rec.keysNow = keys.map((k) => k.id);
|
|
const back = keys.find((k) => k.id === rec.tokenId);
|
|
const norm = (p) => JSON.stringify(Object.fromEntries(Object.entries(p ?? {}).map(([g, l]) => [g, [...l].sort()]).sort(([a], [c]) => a.localeCompare(c))));
|
|
if (!back || norm(back.permissions) !== norm(permissions)) rec.problems.push("key read-back scopes differ");
|
|
if (rec.keysNow.length !== 1) rec.problems.push("bot keys are not exactly the new one");
|
|
// Reads only with the new key. Until Jason adds the bot to team 1 it should reach no project.
|
|
const k = await api("GET", "/api/v2/projects?per_page=50", undefined, key);
|
|
rec.newKeyProjects = { status: k.status, count: (k.json?.items ?? []).length };
|
|
const t151 = await api("GET", "/api/v2/tasks/151", undefined, key);
|
|
rec.newKeyTask151 = t151.status;
|
|
save();
|
|
process.stdout.write(JSON.stringify(rec, null, 1) + "\n");
|
|
if (rec.problems.length) process.exit(2);
|