150 lines · 7.5 KB · TypeScriptRaw
/** * THREE ADMIN VERBS ON ONE ACCOUNT, run by the coordinator: * * pnpm -s media:cap --base <url> --token-file <path> --bytes <n|default> * pnpm -s retired:erase --base <url> --token-file <path> [--yes] * pnpm -s erase --base <url> --token-file <path> --set <tables|unlinked_photos|old_prompts> * [--tables a,b,…] [--ignore table.column,…] [--days <n>] [--yes] * * --base the account's address: https://cottondb.com/b/p-<database id> * on live, or http://127.0.0.1:8787/b/<slug> under `wrangler dev` * --token-file a file holding the admin token; never printed. Every * /v1/admin route takes the admin token alone on live * (NEXT-ADMIN-KEYS part 1, src/admin_door.ts): an owner `ctn_` * token is refused there, token scopes on or off. * --bytes the account's own media limit, or `default` to put it back * --yes erase; without it the verb prints what would go and changes * nothing * --set erase's set (src/erase.ts): every row of `--tables`, the * photos and videos nothing names (`--ignore` the groups the dry * run named that may go anyway), or prompts older than `--days` * (30). The verb asks again until the account says done, and * prints each answer's phase and the last answer whole. * * Prints the account's answer as JSON. * * Tests: `pnpm -s test:scripts` (account-verbs.test.ts); the routes themselves * are test/caps.test.ts, test/retired-erase.test.ts and test/erase.test.ts. */import { readFileSync } from "node:fs";import { homedir } from "node:os";import { isAbsolute, join, resolve } from "node:path";import { pathToFileURL } from "node:url";export class VerbRefusal extends Error {}export type Verb = "media:cap" | "retired:erase" | "erase";export interface VerbCall { base: string; token: string; path: string; body: Record<string, unknown>;}const USAGE: Record<Verb, string> = { "media:cap": "pnpm -s media:cap --base <url> --token-file <path> --bytes <n|default>", "retired:erase": "pnpm -s retired:erase --base <url> --token-file <path> [--yes]", erase: "pnpm -s erase --base <url> --token-file <path> --set <tables|unlinked_photos|old_prompts> [--tables a,b] [--ignore t.c] [--days n] [--yes]",};function readToken(file: string, cwd: string): string { const path = file.startsWith("~/") ? join(homedir(), file.slice(2)) : isAbsolute(file) ? file : resolve(cwd, file); let token: string; try { token = readFileSync(path, "utf8").trim(); } catch { throw new VerbRefusal(`--token-file ${file} cannot be read`); } if (!token) throw new VerbRefusal(`--token-file ${file} is empty`); return token;}export function parseVerb(verb: Verb, argv: string[], cwd = process.env.INIT_CWD ?? process.cwd()): VerbCall { const usage = USAGE[verb]; const valued = verb === "media:cap" ? ["base", "token-file", "bytes"] : verb === "erase" ? ["base", "token-file", "set", "tables", "ignore", "days"] : ["base", "token-file"]; const values = new Map<string, string>(); let yes = false; for (let i = 0; i < argv.length; i++) { const flag = argv[i]!; if (!flag.startsWith("--")) throw new VerbRefusal(`unexpected ${flag}: ${usage}`); const name = flag.slice(2); if ((verb === "retired:erase" || verb === "erase") && name === "yes") { yes = true; continue; } if (!valued.includes(name)) throw new VerbRefusal(`no option --${name}: ${usage}`); const value = argv[++i]; if (value === undefined || value.startsWith("--")) throw new VerbRefusal(`--${name} needs a value`); values.set(name, value); } const base = values.get("base"); const file = values.get("token-file"); if (!base || !file) throw new VerbRefusal(`--base and --token-file are needed: ${usage}`); if (!/^https?:\/\//.test(base)) throw new VerbRefusal("--base is the account's address, http(s)://…"); const call = { base: base.replace(/\/+$/, ""), token: readToken(file, cwd) }; if (verb === "retired:erase") return { ...call, path: "/v1/admin/retired/erase", body: yes ? { confirm: "erase" } : {} }; if (verb === "erase") { const set = values.get("set"); const list = (name: string): string[] | undefined => values.get(name)?.split(",").map((x) => x.trim()).filter(Boolean); const confirm = yes ? { confirm: "erase" } : {}; if (set === "tables") { const tables = list("tables"); if (!tables?.length) throw new VerbRefusal(`--tables is needed for --set tables: ${usage}`); return { ...call, path: "/v1/admin/erase", body: { set, tables, ...confirm } }; } if (set === "unlinked_photos") return { ...call, path: "/v1/admin/erase", body: { set, ...(list("ignore") ? { ignore: list("ignore") } : {}), ...confirm } }; if (set === "old_prompts") { const days = values.get("days"); if (days !== undefined && !/^\d+$/.test(days)) throw new VerbRefusal("--days is a whole number"); return { ...call, path: "/v1/admin/erase", body: { set, ...(days ? { days: Number(days) } : {}), ...confirm } }; } throw new VerbRefusal(`--set is tables, unlinked_photos or old_prompts: ${usage}`); } const bytes = values.get("bytes"); if (bytes === undefined) throw new VerbRefusal(`--bytes is needed: ${usage}`); if (bytes !== "default" && !/^\d+$/.test(bytes)) throw new VerbRefusal("--bytes is a whole number of bytes, or default"); return { ...call, path: "/v1/admin/media/cap", body: { bytes: bytes === "default" ? null : Number(bytes) } };}/** The route at the account; its refusal said in its own words, never with the token. */export async function callVerb(call: VerbCall, fetcher: typeof fetch = fetch): Promise<Record<string, unknown>> { const res = await fetcher(`${call.base}${call.path}`, { method: "POST", headers: { authorization: `Bearer ${call.token}`, "content-type": "application/json" }, body: JSON.stringify(call.body), signal: AbortSignal.timeout(300_000), }); const text = await res.text(); let answer: Record<string, unknown>; try { answer = text ? (JSON.parse(text) as Record<string, unknown>) : {}; } catch { throw new VerbRefusal(`the account answered ${res.status}: ${text.slice(0, 200)}`); } if (!res.ok) throw new VerbRefusal(`the account refused (${res.status} ${String(answer.code ?? "")}): ${String(answer.message ?? text.slice(0, 200))}`); return answer;}/** erase's calls, asked again with the same body until the account says done (src/erase.ts): each answer's phase said on stderr, the last answer returned. */export async function callUntilDone(call: VerbCall, fetcher: typeof fetch = fetch, say: (line: string) => void = (line) => console.error(line)): Promise<Record<string, unknown>> { for (let calls = 1; ; calls++) { const answer = await callVerb(call, fetcher); say(`erase: call ${calls}: ${String(answer.phase)}${answer.done ? ", done" : ""}`); if (answer.done || calls >= 100_000) return answer; }}async function main(): Promise<void> { const [verb, ...argv] = process.argv.slice(2); if (verb !== "media:cap" && verb !== "retired:erase" && verb !== "erase") throw new VerbRefusal("the verb is media:cap, retired:erase or erase"); const call = parseVerb(verb, argv); console.log(JSON.stringify(verb === "erase" ? await callUntilDone(call) : await callVerb(call), null, 2));}if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) { main().catch((error: unknown) => { console.error(`account-verbs: ${error instanceof VerbRefusal ? error.message : String(error)}`); process.exit(1); });}