Skip to content

abso-core

Public

abso is version control for agents: the client, the engine and a server you can run on your own Cloudflare account.

Check passed

Versions 116 to 318

Compare

+152 −0 in 1 place
new file, 152 lines
1+// abso flag: read, flip and audit a server's feature flags, with no deploy. Each flag has its values, a safe default,
2+// and a line of what it gates; a value is set for the whole server, one project, or one person. The server decides who
3+// 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
4+// header and only to a server ABSO_ADMIN_SERVERS names, and never printed.
5+import { type Parsed, str, UsageError } from "./args.ts";
6+import { type Env, type Output, open } from "./commands.ts";
7+import type { Config } from "./config.ts";
8+import { fromEnv } from "./env-names.ts";
9+import { adminGoesTo, adminToken, adminTokenWords } from "./key-admin.ts";
10+import { shortWhen } from "./times.ts";
12+/** One flag as GET /admin/flags answers it: what it takes and gates, and where it's set. */
13+export interface ListedFlag {
14+ readonly values: readonly string[];
15+ readonly safe: string;
16+ readonly what: string;
17+ readonly stagingOnly?: boolean;
18+ readonly env?: string;
19+ readonly projects?: Readonly<Record<string, string>>;
20+ readonly people?: Readonly<Record<string, string>>;
21+}
23+export type FlagScope = { readonly env: true } | { readonly project: string } | { readonly person: string };
25+/** One change as GET /admin/flags/audit answers it. */
26+export interface FlagChange {
27+ readonly at: string;
28+ readonly by: string;
29+ readonly flag: string;
30+ readonly scope: FlagScope;
31+ readonly old: string | null;
32+ readonly new: string | null;
33+ readonly why: string;
34+}
36+const USAGE =
37+ '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>]';
39+/** The admin token when there is one for this server, else none: a server that takes an owner's key answers without it. */
40+export function adminFor(server: string, env: Readonly<Record<string, string | undefined>>): string | undefined {
41+ if (!adminGoesTo(server, fromEnv(env, "ADMIN_SERVERS"))) return undefined;
42+ try {
43+ return adminToken(env);
44+ } catch {
45+ return undefined;
46+ }
47+}
49+function scrub(text: string, secrets: readonly string[]): string {
50+ let out = text.replace(/abso_sk_[A-Za-z0-9_-]+/g, "[redacted]");
51+ for (const secret of secrets) if (secret.length > 0) out = out.split(secret).join("[redacted]");
52+ return out;
53+}
55+async function call(config: Config, admin: string | undefined, path: string, body?: unknown): Promise<unknown> {
56+ const secrets = [admin ?? "", config.token ?? ""].filter((s) => s.length > 0);
57+ let response: Response;
58+ try {
59+ response = await fetch(`${config.server.replace(/\/+$/, "")}${path}`, {
60+ method: body === undefined ? "GET" : "POST",
61+ headers: {
62+ ...(config.token ? { authorization: `Bearer ${config.token}` } : {}),
63+ ...(admin ? { "x-abso-admin": admin } : {}),
64+ ...(body === undefined ? {} : { "content-type": "application/json" }),
65+ },
66+ ...(body === undefined ? {} : { body: JSON.stringify(body) }),
67+ signal: AbortSignal.timeout(30_000),
68+ });
69+ } catch (err) {
70+ throw new UsageError(scrub(err instanceof Error ? err.message : String(err), secrets));
71+ }
72+ const text = await response.text();
73+ let parsed: unknown;
74+ try {
75+ parsed = JSON.parse(text);
76+ } catch {
77+ throw new UsageError(
78+ response.ok ? "the server's answer was not JSON" : scrub(text.slice(0, 500), secrets) || `${response.status}`,
79+ );
80+ }
81+ if (!response.ok) {
82+ const error = (parsed as { error?: unknown }).error;
83+ if (response.status === 404) throw new UsageError(`${config.server} keeps no feature flags`);
84+ throw new UsageError(scrub(typeof error === "string" ? error : `the server answered ${response.status}`, secrets));
85+ }
86+ return parsed;
87+}
89+/** Where a value is set, in words: "here", "project game", "person:p1". */
90+export function scopeWords(scope: FlagScope): string {
91+ return "project" in scope ? `project ${scope.project}` : "person" in scope ? scope.person : "here";
92+}
94+/** What abso flag list prints: each flag, what it takes, its safe value, and every place it's set. */
95+export function flagListText(flags: Readonly<Record<string, ListedFlag>>): string {
96+ const names = Object.keys(flags).sort();
97+ if (names.length === 0) return "No flags.";
98+ return names
99+ .map((name) => {
100+ const f = flags[name]!;
101+ return [
102+ `${name}: ${f.env ?? `${f.safe} (unset)`}. Takes ${f.values.join(", ")}; safe ${f.safe}${f.stagingOnly ? "; staging only" : ""}.`,
103+ ` ${f.what}`,
104+ ...Object.entries(f.projects ?? {}).map(([p, v]) => ` project ${p}: ${v}`),
105+ ...Object.entries(f.people ?? {}).map(([p, v]) => ` ${p}: ${v}`),
106+ ].join("\n");
107+ })
108+ .join("\n");
109+}
111+/** One audited change in a line: when, who, which flag where, old to new, and why. */
112+export function changeText(c: FlagChange, now: number = Date.now()): string {
113+ return `${shortWhen(Date.parse(c.at), now)} ${c.by} ${c.flag} ${scopeWords(c.scope)}: ${c.old ?? "unset"} to ${c.new ?? "unset"}. "${c.why}"`;
114+}
116+export async function runFlag(args: Parsed, env: Env): Promise<Output> {
117+ const [sub = "list", flag, value, ...extra] = args.positionals;
118+ const { config } = open(env);
119+ const admin = adminFor(config.server, env.env);
120+ if (admin) (env.writeErr ?? env.write)(`${adminTokenWords(env.env)}\n`);
121+ if (sub === "list" && flag === undefined) {
122+ const body = (await call(config, admin, "/admin/flags")) as {
123+ revision: number;
124+ flags: Record<string, ListedFlag>;
125+ };
126+ return { text: `${flagListText(body.flags)}\n`, json: { ...body } };
127+ }
128+ if (sub === "log" && flag === undefined) {
129+ const limit = str(args, "limit") ?? "20";
130+ if (!/^[0-9]{1,3}$/.test(limit) || Number(limit) < 1) throw new UsageError("--limit is a number from 1 to 999");
131+ const body = (await call(config, admin, `/admin/flags/audit?limit=${limit}`)) as { changes: FlagChange[] };
132+ const text = body.changes.length === 0 ? "No changes yet." : body.changes.map((c) => changeText(c)).join("\n");
133+ return { text: `${text}\n`, json: { ...body } };
134+ }
135+ const setting = sub === "set" && flag !== undefined && value !== undefined && extra.length === 0;
136+ const unsetting = sub === "unset" && flag !== undefined && value === undefined;
137+ if (!setting && !unsetting) throw new UsageError(USAGE);
138+ const why = str(args, "why");
139+ if (why === undefined || why.trim().length < 3) throw new UsageError('every change says why: --why "..."');
140+ const project = str(args, "project");
141+ const person = str(args, "person");
142+ if (project !== undefined && person !== undefined)
143+ throw new UsageError("a value is set for a project or a person, not both");
144+ if (person !== undefined && !person.startsWith("person:")) throw new UsageError("--person is person:<id>");
145+ const body = (await call(config, admin, `/admin/flags/${encodeURIComponent(flag!)}`, {
146+ value: setting ? value : null,
147+ why,
148+ ...(project === undefined ? {} : { project }),
149+ ...(person === undefined ? {} : { person }),
150+ })) as { revision: number; change: FlagChange };
151+ return { text: `${changeText(body.change)}\n`, json: { ...body } };
152+}
MCP
compare on this site's /mcp
CLI
abso diff 116 318 client/src/flag-commands.ts --json
JSON
/christopher/abso-core/compare/116..318?file=client%2Fsrc%2Fflag-commands.ts&format=json