{"draft":null,"from":175,"to":318,"files":[{"path":"client/src/flag-commands.ts","added":152,"removed":0,"diff":"--- /dev/null\n+++ b/client/src/flag-commands.ts\n@@ -0,0 +1,152 @@\n+// abso flag: read, flip and audit a server's feature flags, with no deploy. Each flag has its values, a safe default,\n+// and a line of what it gates; a value is set for the whole server, one project, or one person. The server decides who\n+// may: its admin token always, and an owner's key where it says so. The admin token is read at run time, sent only as a\n+// header and only to a server ABSO_ADMIN_SERVERS names, and never printed.\n+import { type Parsed, str, UsageError } from \"./args.ts\";\n+import { type Env, type Output, open } from \"./commands.ts\";\n+import type { Config } from \"./config.ts\";\n+import { fromEnv } from \"./env-names.ts\";\n+import { adminGoesTo, adminToken, adminTokenWords } from \"./key-admin.ts\";\n+import { shortWhen } from \"./times.ts\";\n+\n+/** One flag as GET /admin/flags answers it: what it takes and gates, and where it's set. */\n+export interface ListedFlag {\n+\treadonly values: readonly string[];\n+\treadonly safe: string;\n+\treadonly what: string;\n+\treadonly stagingOnly?: boolean;\n+\treadonly env?: string;\n+\treadonly projects?: Readonly<Record<string, string>>;\n+\treadonly people?: Readonly<Record<string, string>>;\n+}\n+\n+export type FlagScope = { readonly env: true } | { readonly project: string } | { readonly person: string };\n+\n+/** One change as GET /admin/flags/audit answers it. */\n+export interface FlagChange {\n+\treadonly at: string;\n+\treadonly by: string;\n+\treadonly flag: string;\n+\treadonly scope: FlagScope;\n+\treadonly old: string | null;\n+\treadonly new: string | null;\n+\treadonly why: string;\n+}\n+\n+const USAGE =\n+\t'abso flag [list] | abso flag log [--limit N] | abso flag set <flag> <value> --why \"...\" [--project <name> | --person person:<id>] | abso flag unset <flag> --why \"...\" [--project <name> | --person person:<id>]';\n+\n+/** The admin token when there is one for this server, else none: a server that takes an owner's key answers without it. */\n+export function adminFor(server: string, env: Readonly<Record<string, string | undefined>>): string | undefined {\n+\tif (!adminGoesTo(server, fromEnv(env, \"ADMIN_SERVERS\"))) return undefined;\n+\ttry {\n+\t\treturn adminToken(env);\n+\t} catch {\n+\t\treturn undefined;\n+\t}\n+}\n+\n+function scrub(text: string, secrets: readonly string[]): string {\n+\tlet out = text.replace(/abso_sk_[A-Za-z0-9_-]+/g, \"[redacted]\");\n+\tfor (const secret of secrets) if (secret.length > 0) out = out.split(secret).join(\"[redacted]\");\n+\treturn out;\n+}\n+\n+async function call(config: Config, admin: string | undefined, path: string, body?: unknown): Promise<unknown> {\n+\tconst secrets = [admin ?? \"\", config.token ?? \"\"].filter((s) => s.length > 0);\n+\tlet response: Response;\n+\ttry {\n+\t\tresponse = await fetch(`${config.server.replace(/\\/+$/, \"\")}${path}`, {\n+\t\t\tmethod: body === undefined ? \"GET\" : \"POST\",\n+\t\t\theaders: {\n+\t\t\t\t...(config.token ? { authorization: `Bearer ${config.token}` } : {}),\n+\t\t\t\t...(admin ? { \"x-abso-admin\": admin } : {}),\n+\t\t\t\t...(body === undefined ? {} : { \"content-type\": \"application/json\" }),\n+\t\t\t},\n+\t\t\t...(body === undefined ? {} : { body: JSON.stringify(body) }),\n+\t\t\tsignal: AbortSignal.timeout(30_000),\n+\t\t});\n+\t} catch (err) {\n+\t\tthrow new UsageError(scrub(err instanceof Error ? err.message : String(err), secrets));\n+\t}\n+\tconst text = await response.text();\n+\tlet parsed: unknown;\n+\ttry {\n+\t\tparsed = JSON.parse(text);\n+\t} catch {\n+\t\tthrow new UsageError(\n+\t\t\tresponse.ok ? \"the server's answer was not JSON\" : scrub(text.slice(0, 500), secrets) || `${response.status}`,\n+\t\t);\n+\t}\n+\tif (!response.ok) {\n+\t\tconst error = (parsed as { error?: unknown }).error;\n+\t\tif (response.status === 404) throw new UsageError(`${config.server} keeps no feature flags`);\n+\t\tthrow new UsageError(scrub(typeof error === \"string\" ? error : `the server answered ${response.status}`, secrets));\n+\t}\n+\treturn parsed;\n+}\n+\n+/** Where a value is set, in words: \"here\", \"project game\", \"person:p1\". */\n+export function scopeWords(scope: FlagScope): string {\n+\treturn \"project\" in scope ? `project ${scope.project}` : \"person\" in scope ? scope.person : \"here\";\n+}\n+\n+/** What abso flag list prints: each flag, what it takes, its safe value, and every place it's set. */\n+export function flagListText(flags: Readonly<Record<string, ListedFlag>>): string {\n+\tconst names = Object.keys(flags).sort();\n+\tif (names.length === 0) return \"No flags.\";\n+\treturn names\n+\t\t.map((name) => {\n+\t\t\tconst f = flags[name]!;\n+\t\t\treturn [\n+\t\t\t\t`${name}: ${f.env ?? `${f.safe} (unset)`}. Takes ${f.values.join(\", \")}; safe ${f.safe}${f.stagingOnly ? \"; staging only\" : \"\"}.`,\n+\t\t\t\t`  ${f.what}`,\n+\t\t\t\t...Object.entries(f.projects ?? {}).map(([p, v]) => `  project ${p}: ${v}`),\n+\t\t\t\t...Object.entries(f.people ?? {}).map(([p, v]) => `  ${p}: ${v}`),\n+\t\t\t].join(\"\\n\");\n+\t\t})\n+\t\t.join(\"\\n\");\n+}\n+\n+/** One audited change in a line: when, who, which flag where, old to new, and why. */\n+export function changeText(c: FlagChange, now: number = Date.now()): string {\n+\treturn `${shortWhen(Date.parse(c.at), now)}  ${c.by}  ${c.flag} ${scopeWords(c.scope)}: ${c.old ?? \"unset\"} to ${c.new ?? \"unset\"}. \"${c.why}\"`;\n+}\n+\n+export async function runFlag(args: Parsed, env: Env): Promise<Output> {\n+\tconst [sub = \"list\", flag, value, ...extra] = args.positionals;\n+\tconst { config } = open(env);\n+\tconst admin = adminFor(config.server, env.env);\n+\tif (admin) (env.writeErr ?? env.write)(`${adminTokenWords(env.env)}\\n`);\n+\tif (sub === \"list\" && flag === undefined) {\n+\t\tconst body = (await call(config, admin, \"/admin/flags\")) as {\n+\t\t\trevision: number;\n+\t\t\tflags: Record<string, ListedFlag>;\n+\t\t};\n+\t\treturn { text: `${flagListText(body.flags)}\\n`, json: { ...body } };\n+\t}\n+\tif (sub === \"log\" && flag === undefined) {\n+\t\tconst limit = str(args, \"limit\") ?? \"20\";\n+\t\tif (!/^[0-9]{1,3}$/.test(limit) || Number(limit) < 1) throw new UsageError(\"--limit is a number from 1 to 999\");\n+\t\tconst body = (await call(config, admin, `/admin/flags/audit?limit=${limit}`)) as { changes: FlagChange[] };\n+\t\tconst text = body.changes.length === 0 ? \"No changes yet.\" : body.changes.map((c) => changeText(c)).join(\"\\n\");\n+\t\treturn { text: `${text}\\n`, json: { ...body } };\n+\t}\n+\tconst setting = sub === \"set\" && flag !== undefined && value !== undefined && extra.length === 0;\n+\tconst unsetting = sub === \"unset\" && flag !== undefined && value === undefined;\n+\tif (!setting && !unsetting) throw new UsageError(USAGE);\n+\tconst why = str(args, \"why\");\n+\tif (why === undefined || why.trim().length < 3) throw new UsageError('every change says why: --why \"...\"');\n+\tconst project = str(args, \"project\");\n+\tconst person = str(args, \"person\");\n+\tif (project !== undefined && person !== undefined)\n+\t\tthrow new UsageError(\"a value is set for a project or a person, not both\");\n+\tif (person !== undefined && !person.startsWith(\"person:\")) throw new UsageError(\"--person is person:<id>\");\n+\tconst body = (await call(config, admin, `/admin/flags/${encodeURIComponent(flag!)}`, {\n+\t\tvalue: setting ? value : null,\n+\t\twhy,\n+\t\t...(project === undefined ? {} : { project }),\n+\t\t...(person === undefined ? {} : { person }),\n+\t})) as { revision: number; change: FlagChange };\n+\treturn { text: `${changeText(body.change)}\\n`, json: { ...body } };\n+}"}],"unmatched":[]}