feat(rotation): provider rotators, consumer propagation, weekly job, runbook (CLI 0.14.0) (#265)

- Catalog covers every key in the team plan (unknown 275 -> 0): new methods
  `provider` and `not-secret`, plus family/owner/never/disruptive on every
  spec. Wallets, treasury, Lightning, exchanges, Stripe, npm, GitHub App keys,
  signing identities and the personal vault are `never` and owner-only; an
  __ROTATE__ entry cannot make them automatic.
- Two-phase provider rotators (rotators.ts): resend, cloudflare-token,
  coinpay-api-key, coinpay-webhook-secret, vapid, postgres-role (SCRAM
  verifier over stdin, refuses self-hosted Supabase).
- rotate-keys --propagate [root]: finds consumer env files by value, backs
  up (.bak-rotate-<date>, 600), rewrites, restarts with the site's deploy.env
  through deploy-gate 3 at a time, health-checks local + public URL, revokes
  the old credential only after; any failure restores vaults, files and the
  provider. --scheduled, --max, --max-sites, --exclude-site, --report.
- scripts/logicsrc-rotate: weekly job, dry run unless LOGICSRC_ROTATE_LIVE=1,
  mails rotated / skipped / manual-by-owner report (never values).
- docs/rotation.md (logicsrc.com/docs/rotation) + docs/ROTATION.md pointer,
  including the wallets and signing keys section.

Co-authored-by: Anthony Ettinger <anthony@profullstack.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
sh1pt-actions-fleet[bot] 2026-10-29 00:43:55 +00:00 • committed by GitHub
parent b5f875837a
commit 3254b2706b
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
17 changed files with 2609 additions and 91 deletions

View file

@ -1,6 +1,6 @@
{
"name": "@logicsrc/cli",
"version": "0.13.0",
"version": "0.14.0",
"description": "LogicSRC CLI: every LogicSRC standard and tool as one command.",
"type": "module",
"main": "./dist/index.js",

View file

@ -1,6 +1,8 @@
#!/usr/bin/env node
import { spawnSync } from "node:child_process";
import { readFileSync } from "node:fs";
import { homedir } from "node:os";
import { join } from "node:path";
import { evaluateAccountPolicy, scoreAccountActionRisk } from "@logicsrc/account-core";
import { Command } from "commander";
import { createCredentialEngine, listCredentialProviders, logicsrcHome, type CredentialEndpoint } from "@logicsrc/plugin-credential-sharing";
@ -949,6 +951,12 @@ teams
.option("-k, --key <names>", "only these keys (comma-separated or repeated)", collectList)
.option("--approve", "write the new values (dry run by default)")
.option("--set-from-stdin", "store a value you rotated by hand (exactly one --key), everywhere the old value lives")
.option("--propagate [root]", "also rewrite, restart and health-check the sites holding the old value (default root ~/www); rolls back on failure")
.option("--scheduled", "unattended mode: only non-disruptive random secrets and two-phase provider rotators with known consumers")
.option("--max <n>", "stop after n live rotations")
.option("--exclude-site <sites>", "never rewrite or restart these sites; a value they hold is skipped (comma-separated or repeated)", collectList)
.option("--max-sites <n>", "with --scheduled: skip values read by more than n sites (default 5)")
.option("--report <file>", "also write the JSON results (never values) to this file, mode 600")
.option("--format <format>", "table, json, or markdown", "table")
.description("Rotate secret values: automatic ones are minted and written to every vault holding the old value; manual ones come back as steps.")
.addHelpText(
@ -959,19 +967,33 @@ Dry run first, then apply:
logicsrc teams rotate-keys profullstack b1dz prod --approve rotate one vault's automatic keys
logicsrc teams rotate-keys profullstack --key SSH_ID_ED25519 --approve
new-key | logicsrc teams rotate-keys profullstack b1dz prod --key RESEND_API_KEY --set-from-stdin --approve
logicsrc teams rotate-keys profullstack wx93 prod --key CRON_SECRET --propagate --approve
logicsrc teams rotate-keys profullstack --scheduled --propagate --approve --report r.json (the weekly job)
Provider rotators (method provider): resend, cloudflare-token, coinpay-api-key,
coinpay-webhook-secret, vapid, postgres-role. Each mints the new credential,
writes the vaults, redeploys consumers, health-checks them, and only then
revokes the old one; any failure restores the old value everywhere.
Runbook: https://logicsrc.com/docs/rotation
Values never print. The same value stored in other vaults (same fingerprint) is
rotated there too. Vaults you cannot decrypt are named and keep the OLD value.
After rotating: redeploy the consumers, install new SSH public keys, revoke the old values.
`
)
.action((slug, project, env, options) =>
teamsRotateKeysAction(slug, { project, env, keys: options.key }, {
.action(async (slug, project, env, options) => {
await teamsRotateKeysAction(slug, { project, env, keys: options.key }, {
approve: Boolean(options.approve),
setFromStdin: Boolean(options.setFromStdin),
format: options.format as OutputFormat
})
);
format: options.format as OutputFormat,
propagate: options.propagate === undefined ? undefined : options.propagate === true ? join(homedir(), "www") : String(options.propagate),
scheduled: Boolean(options.scheduled),
max: options.max === undefined ? undefined : Number(options.max),
report: options.report,
excludeSites: options.excludeSite,
maxSites: options.maxSites === undefined ? undefined : Number(options.maxSites)
});
});
teams
.command("clean")

View file

@ -0,0 +1,74 @@
import { mkdtempSync, mkdirSync, readFileSync, rmSync, statSync, writeFileSync, readdirSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { afterEach, describe, expect, it } from "vitest";
import { envFilesIn, findConsumers, inBatches, replaceInValue, restoreBackup, rewriteEnvFile, strayCopies } from "./propagate.js";
const dirs: string[] = [];
function www(): string {
const d = mkdtempSync(join(tmpdir(), "logicsrc-propagate-"));
dirs.push(d);
return d;
}
afterEach(() => {
for (const d of dirs.splice(0)) rmSync(d, { recursive: true, force: true });
});
const OLD = "old-secret-0123456789";
const NEW = "new-secret-abcdefghij";
describe("propagate", () => {
it("finds consumers by value, skipping backups, and flags build-time keys", () => {
const root = www();
mkdirSync(join(root, "a.com"));
mkdirSync(join(root, "b.com"));
writeFileSync(join(root, "a.com", "app.env"), `X=1\nCRON_SECRET=${OLD}\nRENAMED="${OLD}"\n`);
writeFileSync(join(root, "a.com", "app.env.bak-001"), `CRON_SECRET=${OLD}\n`);
writeFileSync(join(root, "a.com", "app.bak-002.env"), `CRON_SECRET=${OLD}\n`);
writeFileSync(join(root, "b.com", "deploy.env"), `NEXT_PUBLIC_THING=${OLD}\n`);
expect(envFilesIn(join(root, "a.com")).map((f) => f.split("/").pop())).toEqual(["app.env"]);
const hits = findConsumers(root, [{ oldValue: OLD, newValue: NEW }]);
expect(hits.map((h) => [h.site, h.keys, h.needsBuild])).toEqual([
["a.com", ["CRON_SECRET", "RENAMED"], false],
["b.com", ["NEXT_PUBLIC_THING"], true]
]);
});
it("rewrites in place with a 600 backup, keeps mode and quotes, and restores", () => {
const root = www();
const f = join(root, "app.env");
writeFileSync(f, `A=${OLD}\nB='${OLD}'\nDATABASE_URL=postgres://u:${OLD}@h:5432/d\nC=keep\n`, { mode: 0o600 });
const { backup, keys } = rewriteEnvFile(f, [{ oldValue: OLD, newValue: NEW }], "20261029");
expect(keys).toEqual(["A", "B", "DATABASE_URL"]);
expect(readFileSync(f, "utf8")).toBe(`A=${NEW}\nB='${NEW}'\nDATABASE_URL=postgres://u:${NEW}@h:5432/d\nC=keep\n`);
expect(statSync(f).mode & 0o777).toBe(0o600);
expect(statSync(backup).mode & 0o777).toBe(0o600);
expect(backup).toMatch(/app\.env\.bak-rotate-20261029$/);
restoreBackup(f, backup);
expect(readFileSync(f, "utf8")).toContain(`A=${OLD}`);
const second = rewriteEnvFile(f, [{ oldValue: OLD, newValue: NEW }], "20261029");
expect(second.backup).toMatch(/-2$/);
expect(readdirSync(root).filter((n) => n.includes("rotate-tmp"))).toEqual([]);
});
it("ignores short values that could collide with unrelated text", () => {
expect(replaceInValue("abc", [{ oldValue: "abc", newValue: "x" }])).toBeNull();
});
it("finds stray copies (crontab, scripts)", () => {
const root = www();
writeFileSync(join(root, "s"), `curl -H "x: ${OLD}"`);
expect(strayCopies([join(root, "s"), join(root, "missing")], [{ oldValue: OLD, newValue: NEW }])).toEqual([join(root, "s")]);
});
it("runs at most 3 at a time", async () => {
let running = 0;
let peak = 0;
await inBatches([1, 2, 3, 4, 5, 6, 7], 3, async () => {
peak = Math.max(peak, ++running);
await new Promise((r) => setTimeout(r, 5));
running--;
});
expect(peak).toBe(3);
});
});

View file

@ -0,0 +1,268 @@
import { spawn } from "node:child_process";
import { chmodSync, copyFileSync, existsSync, readFileSync, readdirSync, statSync, writeFileSync, renameSync } from "node:fs";
import { join } from "node:path";
/**
* After a rotation is written to the vaults, the running sites still hold the
* old value in their env files. This finds them by VALUE (not key name, so a
* renamed copy is found too), rewrites them with a backup, restarts each site
* with its own deploy.env, and health-checks it.
*
* Layout (dev2): <root>/<site>/{app.env,deploy.env,docker-compose.app.yml,
* deploy-app.sh,.deploy-state}. A site may ship `rotate-restart.sh` to restart
* itself differently. Values are never printed; reports name files and keys.
*/
export interface Replacement {
oldValue: string;
newValue: string;
}
export interface EnvHit {
site: string;
dir: string;
file: string;
keys: string[];
/** A NEXT_PUBLIC_* value changed: the image has to be rebuilt, not just recreated. */
needsBuild: boolean;
}
const ENV_FILE = /^(app|deploy|prober|worker|web|api)?\.?env$|^[a-z0-9_-]+\.env$/i;
const BACKUP = /bak|orig|\.old$|\.example$|\.sample$|\.tmp$/i;
/** Shorter values could collide with unrelated text. */
const MIN_MATCH = 12;
export function envFilesIn(dir: string): string[] {
let names: string[];
try {
names = readdirSync(dir);
} catch {
return [];
}
return names.filter((n) => ENV_FILE.test(n) && !BACKUP.test(n)).map((n) => join(dir, n)).filter((f) => {
try {
return statSync(f).isFile();
} catch {
return false;
}
});
}
function splitLine(line: string): { key: string; value: string; quote: string } | null {
const m = /^\s*(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*)$/.exec(line);
if (!m) return null;
let value = m[2]!;
let quote = "";
if ((value.startsWith('"') && value.endsWith('"') && value.length >= 2) || (value.startsWith("'") && value.endsWith("'") && value.length >= 2)) {
quote = value[0]!;
value = value.slice(1, -1);
}
return { key: m[1]!, value, quote };
}
/** The new value for a line, or null when the line does not hold an old value. Connection strings match on the embedded password. */
export function replaceInValue(value: string, reps: Replacement[]): string | null {
for (const r of reps) {
if (r.oldValue.length < MIN_MATCH) continue;
if (value === r.oldValue) return r.newValue;
}
for (const r of reps) {
if (r.oldValue.length < MIN_MATCH) continue;
const enc = encodeURIComponent(r.oldValue);
for (const old of new Set([r.oldValue, enc])) {
const at = value.indexOf(`:${old}@`);
if (at !== -1) return value.slice(0, at + 1) + (old === enc ? encodeURIComponent(r.newValue) : r.newValue) + value.slice(at + 1 + old.length);
}
}
return null;
}
/** Every env file under root/<site>/ holding one of the old values. */
export function findConsumers(root: string, reps: Replacement[]): EnvHit[] {
const hits: EnvHit[] = [];
let sites: string[];
try {
sites = readdirSync(root);
} catch {
return [];
}
for (const site of sites.sort()) {
const dir = join(root, site);
for (const file of envFilesIn(dir)) {
let text: string;
try {
text = readFileSync(file, "utf8");
} catch {
continue;
}
if (!reps.some((r) => r.oldValue.length >= MIN_MATCH && (text.includes(r.oldValue) || text.includes(encodeURIComponent(r.oldValue))))) continue;
const keys: string[] = [];
for (const line of text.split("\n")) {
const kv = splitLine(line);
if (kv && replaceInValue(kv.value, reps) !== null) keys.push(kv.key);
}
if (keys.length) hits.push({ site, dir, file, keys, needsBuild: keys.some((k) => /^NEXT_PUBLIC_|^VITE_|^EXPO_PUBLIC_/.test(k)) });
}
}
return hits;
}
/** Other places a value can hide that we do not rewrite: crontab, scripts. A hit there blocks unattended rotation. */
export function strayCopies(paths: string[], reps: Replacement[]): string[] {
const out: string[] = [];
for (const p of paths) {
let text = "";
try {
text = readFileSync(p, "utf8");
} catch {
continue;
}
if (reps.some((r) => r.oldValue.length >= MIN_MATCH && text.includes(r.oldValue))) out.push(p);
}
return out;
}
/** Rewrite one env file in place (same mode), after copying it to <file>.bak-rotate-<stamp>. */
export function rewriteEnvFile(file: string, reps: Replacement[], stamp: string): { backup: string; keys: string[] } {
const text = readFileSync(file, "utf8");
const keys: string[] = [];
const out = text
.split("\n")
.map((line) => {
const kv = splitLine(line);
if (!kv) return line;
const next = replaceInValue(kv.value, reps);
if (next === null) return line;
keys.push(kv.key);
const eq = line.indexOf("=");
return `${line.slice(0, eq + 1)}${kv.quote}${next}${kv.quote}`;
})
.join("\n");
const mode = statSync(file).mode & 0o777;
let backup = `${file}.bak-rotate-${stamp}`;
for (let i = 2; existsSync(backup); i++) backup = `${file}.bak-rotate-${stamp}-${i}`;
copyFileSync(file, backup);
chmodSync(backup, 0o600);
const tmp = `${file}.rotate-tmp`;
writeFileSync(tmp, out, { mode });
chmodSync(tmp, mode);
renameSync(tmp, file);
return { backup, keys };
}
export function restoreBackup(file: string, backup: string): void {
const mode = statSync(file).mode & 0o777;
copyFileSync(backup, file);
chmodSync(file, mode);
}
export function readEnv(file: string): Record<string, string> {
const out: Record<string, string> = {};
try {
for (const line of readFileSync(file, "utf8").split("\n")) {
const kv = splitLine(line);
if (kv) out[kv.key] = kv.value;
}
} catch {
/* missing */
}
return out;
}
export interface RestartResult {
site: string;
ok: boolean;
detail: string;
}
export interface SiteOps {
/** Restart a site so it reads its env files again. */
restart(dir: string, site: string, needsBuild: boolean): Promise<RestartResult>;
/** Healthy = local port and public URL answer below 500. */
health(dir: string, site: string): Promise<RestartResult>;
}
function sh(cmd: string, args: string[], cwd: string, timeoutMs: number): Promise<{ code: number | null; tail: string }> {
return new Promise((resolve) => {
const child = spawn(cmd, args, { cwd, stdio: ["ignore", "pipe", "pipe"], env: process.env });
let tail = "";
const keep = (b: Buffer) => {
tail = (tail + b.toString()).slice(-600);
};
child.stdout.on("data", keep);
child.stderr.on("data", keep);
const t = setTimeout(() => child.kill("SIGTERM"), timeoutMs);
child.on("close", (code) => {
clearTimeout(t);
resolve({ code, tail });
});
child.on("error", (e) => {
clearTimeout(t);
resolve({ code: -1, tail: String(e.message) });
});
});
}
async function status(url: string): Promise<number> {
try {
const r = await fetch(url, { redirect: "manual", signal: AbortSignal.timeout(10_000) });
return r.status;
} catch {
return 0;
}
}
/** dev2: recreate with the site's own deploy.env through deploy-gate (3 slots); rebuild via deploy-app.sh when a build-time value changed. */
export const dev2Ops: SiteOps = {
async restart(dir, site, needsBuild) {
const gate = [join(process.env.HOME ?? "", ".local/bin/deploy-gate"), "/usr/local/bin/deploy-gate"].find((g) => existsSync(g));
if (existsSync(join(dir, "rotate-restart.sh"))) {
const r = await sh(join(dir, "rotate-restart.sh"), [], dir, 900_000);
return { site, ok: r.code === 0, detail: r.code === 0 ? "rotate-restart.sh" : `rotate-restart.sh exit ${r.code}: ${r.tail}` };
}
if (needsBuild) {
const sha = readEnv(join(dir, ".deploy-state")).DEPLOYED_SHA;
if (!sha || !existsSync(join(dir, "deploy-app.sh"))) return { site, ok: false, detail: "build-time value changed and there is no deploy-app.sh/.deploy-state to rebuild with" };
const r = await sh(join(dir, "deploy-app.sh"), [sha], dir, 1_800_000);
return { site, ok: r.code === 0, detail: r.code === 0 ? `rebuilt ${sha.slice(0, 8)}` : `deploy-app.sh exit ${r.code}: ${r.tail}` };
}
const compose = ["docker-compose.app.yml", "docker-compose.yml", "compose.yml"].find((f) => existsSync(join(dir, f)));
if (!compose) return { site, ok: false, detail: "no compose file: restart it by hand" };
// Never without the site's deploy.env: compose would drop APP_PORT and friends.
if (!existsSync(join(dir, "deploy.env"))) return { site, ok: false, detail: "no deploy.env: refusing a bare docker compose up" };
const args = ["compose", "-f", compose, "--env-file", "deploy.env", "up", "-d", "--no-build", "--force-recreate"];
const r = gate ? await sh(gate, ["--name", site, "--", "docker", ...args], dir, 900_000) : await sh("docker", args, dir, 900_000);
return { site, ok: r.code === 0, detail: r.code === 0 ? "recreated" : `compose exit ${r.code}: ${r.tail}` };
},
async health(dir, site) {
const port = readEnv(join(dir, "deploy.env")).APP_PORT;
const deadline = Date.now() + 180_000;
let local = 0;
if (port) {
while (Date.now() < deadline) {
local = await status(`http://127.0.0.1:${port}/`);
if (local > 0 && local < 500) break;
await new Promise((r) => setTimeout(r, 5000));
}
if (!(local > 0 && local < 500)) return { site, ok: false, detail: `127.0.0.1:${port} answered ${local || "nothing"}` };
}
if (/^[a-z0-9.-]+\.[a-z]{2,}$/i.test(site)) {
let pub = 0;
while (Date.now() < deadline) {
pub = await status(`https://${site}/`);
if (pub > 0 && pub < 500) break;
await new Promise((r) => setTimeout(r, 5000));
}
if (!(pub > 0 && pub < 500)) return { site, ok: false, detail: `https://${site}/ answered ${pub || "nothing"}` };
return { site, ok: true, detail: `local ${local || "-"}, public ${pub}` };
}
return { site, ok: Boolean(port), detail: port ? `local ${local}` : "no APP_PORT and not a hostname: health unknown" };
}
};
/** Run fn over items, at most `limit` at a time (the fleet rule is 3). */
export async function inBatches<T, R>(items: T[], limit: number, fn: (t: T) => Promise<R>): Promise<R[]> {
const out: R[] = [];
for (let i = 0; i < items.length; i += limit) out.push(...(await Promise.all(items.slice(i, i + limit).map(fn))));
return out;
}

View file

@ -0,0 +1,214 @@
import { mkdtempSync, mkdirSync, readFileSync, rmSync, writeFileSync, readdirSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import {
decryptValue,
encryptValue,
fingerprintValue,
generateIdentityKeyPair,
generateVaultKey,
wrapVaultKey
} from "@logicsrc/plugin-credential-sharing";
import type { SiteOps } from "./propagate.js";
/** An in-memory team server: vaults of sealed values, exactly what the real API returns. */
const server = vi.hoisted(() => ({ client: null as any, identity: null as any }));
vi.mock("./teams.js", async (orig) => ({ ...(await orig<typeof import("./teams.js")>()), authedClient: () => ({ client: server.client, identity: server.identity }) }));
const { teamsRotateKeysAction } = await import("./rotate-keys.js");
interface Row {
name: string;
nonce: string;
ciphertext: string;
fingerprint: string;
updatedAt: string;
}
async function makeTeam(vaults: Record<string, Record<string, string>>) {
const keys = await generateIdentityKeyPair();
const dek = await generateVaultKey();
const wrapped = await wrapVaultKey(dek, keys.publicKey);
const store = new Map<string, Row[]>();
for (const [name, values] of Object.entries(vaults)) {
const rows: Row[] = [];
for (const [k, v] of Object.entries(values)) rows.push({ name: k, ...(await encryptValue(v, dek)), fingerprint: fingerprintValue(v), updatedAt: "2026-01-01T00:00:00Z" });
store.set(name, rows);
}
const puts: string[][] = [];
server.identity = { keys, apiToken: "t" };
server.client = {
listVaults: async () => ({ vaults: [...store.keys()].map((n) => ({ id: n, name: n, hasAccess: true })) }),
listSecrets: async (id: string) => ({ secrets: store.get(id)!.map((r) => ({ ...r })) }),
getMyGrant: async () => ({ wrappedDek: wrapped }),
putSecrets: async (id: string, upserts: Row[]) => {
const rows = store.get(id)!;
for (const u of upserts) {
const i = rows.findIndex((r) => r.name === u.name);
const row = { ...u, updatedAt: "2026-10-29T00:00:00Z" };
if (i === -1) rows.push(row);
else rows[i] = row;
}
puts.push(upserts.map((u) => `${id}:${u.name}`));
return { ok: true, applied: upserts.map((u) => u.name) };
}
};
const read = async (vault: string, key: string) => {
const r = store.get(vault)!.find((x) => x.name === key);
return r ? decryptValue(r, dek) : undefined;
};
return { read, puts };
}
const OLD = "0123456789abcdef0123456789abcdef";
let root: string;
beforeEach(() => {
root = mkdtempSync(join(tmpdir(), "logicsrc-flow-"));
for (const s of ["a.com", "b.com"]) mkdirSync(join(root, s));
writeFileSync(join(root, "a.com", "app.env"), `CRON_SECRET=${OLD}\nOTHER=1\n`, { mode: 0o600 });
writeFileSync(join(root, "b.com", "app.env"), `CALLER_TOKEN=${OLD}\n`, { mode: 0o600 });
});
afterEach(() => rmSync(root, { recursive: true, force: true }));
function ops(fail: string[] = []): SiteOps & { restarts: string[] } {
const restarts: string[] = [];
return {
restarts,
async restart(_dir, site) {
restarts.push(site);
return { site, ok: true, detail: "recreated" };
},
async health(_dir, site) {
const bad = fail.includes(site) && restarts.includes(site);
return { site, ok: !bad, detail: bad ? "503" : "200" };
}
};
}
const quiet = { format: "json" as const };
describe("rotate-keys two-phase flow", () => {
beforeEach(() => {
vi.spyOn(console, "log").mockImplementation(() => {});
vi.spyOn(console, "error").mockImplementation(() => {});
});
it("random: writes every vault and every consumer file, restarts both sites, health-checks", async () => {
const team = await makeTeam({ "a--prod": { CRON_SECRET: OLD }, "a--local": { CRON_SECRET: OLD } });
const o = ops();
const [r] = await teamsRotateKeysAction("t", { keys: ["CRON_SECRET"] }, { ...quiet, approve: true, propagate: root }, { ops: o, strayText: () => [] });
expect(r!.status).toBe("rotated");
const now = (await team.read("a--prod", "CRON_SECRET"))!;
expect(now).not.toBe(OLD);
expect(await team.read("a--local", "CRON_SECRET")).toBe(now);
expect(readFileSync(join(root, "a.com", "app.env"), "utf8")).toBe(`CRON_SECRET=${now}\nOTHER=1\n`);
expect(readFileSync(join(root, "b.com", "app.env"), "utf8")).toBe(`CALLER_TOKEN=${now}\n`);
expect(readdirSync(join(root, "a.com")).some((n) => n.startsWith("app.env.bak-rotate-"))).toBe(true);
expect(o.restarts.sort()).toEqual(["a.com", "b.com"]);
expect(JSON.stringify(r)).not.toContain(now);
expect(JSON.stringify(r)).not.toContain(OLD);
});
it("rolls back vaults and files when a consumer fails health after the switch", async () => {
const team = await makeTeam({ "a--prod": { CRON_SECRET: OLD } });
const o = ops(["b.com"]);
const [r] = await teamsRotateKeysAction("t", { keys: ["CRON_SECRET"] }, { ...quiet, approve: true, propagate: root }, { ops: o, strayText: () => [] });
expect(r!.status).toBe("rolled-back");
expect(await team.read("a--prod", "CRON_SECRET")).toBe(OLD);
expect(readFileSync(join(root, "a.com", "app.env"), "utf8")).toContain(`CRON_SECRET=${OLD}`);
expect(readFileSync(join(root, "b.com", "app.env"), "utf8")).toBe(`CALLER_TOKEN=${OLD}\n`);
process.exitCode = 0;
});
it("dry run writes nothing, but reports the consumers it found", async () => {
const team = await makeTeam({ "a--prod": { CRON_SECRET: OLD, SSH_ID_ED25519: "-----BEGIN OPENSSH PRIVATE KEY-----xxxxxxxx" } });
const o = ops();
const results = await teamsRotateKeysAction("t", {}, { ...quiet, approve: false, propagate: root }, { ops: o, strayText: () => [] });
const cron = results.find((r) => r.key === "CRON_SECRET")!;
expect(cron.status).toBe("would-rotate");
expect(cron.sites!.map((s) => s.site).sort()).toEqual(["a.com", "b.com"]);
expect(results.find((r) => r.key === "SSH_ID_ED25519")!.status).toBe("would-rotate");
expect(team.puts).toEqual([]);
expect(o.restarts).toEqual([]);
expect(readFileSync(join(root, "a.com", "app.env"), "utf8")).toContain(OLD);
});
it("scheduled dry run applies the same checks as a live run", async () => {
await makeTeam({ "a--prod": { CRON_SECRET: OLD, PIT_ADMIN_TOKEN: "f".repeat(40) } });
const results = await teamsRotateKeysAction("t", {}, { ...quiet, approve: false, scheduled: true, propagate: root }, { ops: ops(), strayText: () => [] });
expect(results.find((r) => r.key === "CRON_SECRET")!.status).toBe("would-rotate");
expect(results.find((r) => r.key === "PIT_ADMIN_TOKEN")!.status).toBe("skipped");
});
it("scheduled mode skips values with no consumer, values in the crontab, disruptive and manual ones", async () => {
await makeTeam({
"a--prod": { CRON_SECRET: OLD, SESSION_SECRET: "s".repeat(40), STRIPE_SECRET_KEY: "sk_live_xxxxxxxxxxxxxxxx", PIT_ADMIN_TOKEN: "f".repeat(40) }
});
const results = await teamsRotateKeysAction("t", {}, { ...quiet, approve: true, scheduled: true, propagate: root }, { ops: ops(), strayText: () => [`0 * * * * curl -H 'x: ${OLD}'`] });
const by = Object.fromEntries(results.map((r) => [r.key, r]));
expect(by.CRON_SECRET!.status).toBe("skipped");
expect(by.CRON_SECRET!.error).toMatch(/crontab/);
expect(by.SESSION_SECRET!.error).toMatch(/disruptive/);
expect(by.STRIPE_SECRET_KEY!.status).toBe("todo");
expect(by.STRIPE_SECRET_KEY!.never).toBe(true);
expect(by.PIT_ADMIN_TOKEN!.error).toMatch(/no consumer/);
});
it("never touches an excluded site, and caps consumers in unattended mode", async () => {
const team = await makeTeam({ "a--prod": { CRON_SECRET: OLD } });
const [r] = await teamsRotateKeysAction("t", { keys: ["CRON_SECRET"] }, { ...quiet, approve: true, propagate: root, excludeSites: ["b.com"] }, { ops: ops(), strayText: () => [] });
expect(r!.status).toBe("skipped");
expect(r!.error).toMatch(/excluded site holds it: b\.com/);
const [s] = await teamsRotateKeysAction("t", { keys: ["CRON_SECRET"] }, { ...quiet, approve: true, scheduled: true, propagate: root, maxSites: 1 }, { ops: ops(), strayText: () => [] });
expect(s!.error).toMatch(/too many consumers/);
expect(await team.read("a--prod", "CRON_SECRET")).toBe(OLD);
});
it("skips when a consumer is already unhealthy, so the rotation is never blamed", async () => {
const team = await makeTeam({ "a--prod": { CRON_SECRET: OLD } });
const sick: SiteOps = { restart: async (_d, site) => ({ site, ok: true, detail: "" }), health: async (_d, site) => ({ site, ok: site !== "a.com", detail: "502" }) };
const [r] = await teamsRotateKeysAction("t", { keys: ["CRON_SECRET"] }, { ...quiet, approve: true, propagate: root }, { ops: sick, strayText: () => [] });
expect(r!.status).toBe("skipped");
expect(await team.read("a--prod", "CRON_SECRET")).toBe(OLD);
});
it("provider: mints via the rotator, revokes the old key only after health, saves the new id", async () => {
const team = await makeTeam({ "a--prod": { RESEND_API_KEY: "re_old_xxxxxxxxxxxxxxxx" } });
writeFileSync(join(root, "a.com", "app.env"), "RESEND_API_KEY=re_old_xxxxxxxxxxxxxxxx\n");
writeFileSync(join(root, "b.com", "app.env"), "X=1\n");
const order: string[] = [];
const fetch = (async (url: any, init: any = {}) => {
const m = init.method ?? "GET";
order.push(`${m} ${new URL(String(url)).pathname}`);
if (m === "POST") return new Response(JSON.stringify({ id: "new-id", token: "re_new_yyyyyyyyyyyyyyyy" }), { status: 201 });
return new Response(JSON.stringify({ data: [] }), { status: 200 });
}) as typeof globalThis.fetch;
const o = ops();
const wrapped: SiteOps = { restart: async (d, s, b) => (order.push(`restart ${s}`), o.restart(d, s, b)), health: (d, s) => o.health(d, s) };
const [r] = await teamsRotateKeysAction("t", { keys: ["RESEND_API_KEY"] }, { ...quiet, approve: true, propagate: root }, { ops: wrapped, fetch, strayText: () => [], env: {} });
expect(r!.status).toBe("rotated");
expect(await team.read("a--prod", "RESEND_API_KEY")).toBe("re_new_yyyyyyyyyyyyyyyy");
expect(order.indexOf("restart a.com")).toBeGreaterThan(order.indexOf("POST /api-keys"));
expect(r!.note).toMatch(/delete the previous key/); // first rotation: old id unknown
expect(JSON.parse((await team.read("a--prod", "__ROTATE__RESEND_API_KEY"))!).state).toEqual({ keyId: "new-id" });
});
it("provider rollback deletes the new credential and restores the old value", async () => {
const team = await makeTeam({ "a--prod": { RESEND_API_KEY: "re_old_xxxxxxxxxxxxxxxx" } });
writeFileSync(join(root, "a.com", "app.env"), "RESEND_API_KEY=re_old_xxxxxxxxxxxxxxxx\n");
const deletes: string[] = [];
const fetch = (async (url: any, init: any = {}) => {
const m = init.method ?? "GET";
if (m === "DELETE") deletes.push(new URL(String(url)).pathname);
if (m === "POST") return new Response(JSON.stringify({ id: "new-id", token: "re_new_yyyyyyyyyyyyyyyy" }), { status: 201 });
return new Response(JSON.stringify({ data: [] }), { status: 200 });
}) as typeof globalThis.fetch;
const [r] = await teamsRotateKeysAction("t", { keys: ["RESEND_API_KEY"] }, { ...quiet, approve: true, propagate: root }, { ops: ops(["a.com"]), fetch, strayText: () => [], env: {} });
expect(r!.status).toBe("rolled-back");
expect(deletes).toEqual(["/api-keys/new-id"]);
expect(await team.read("a--prod", "RESEND_API_KEY")).toBe("re_old_xxxxxxxxxxxxxxxx");
expect(readFileSync(join(root, "a.com", "app.env"), "utf8")).toBe("RESEND_API_KEY=re_old_xxxxxxxxxxxxxxxx\n");
process.exitCode = 0;
});
});

View file

@ -38,8 +38,8 @@ describe("catalog", () => {
expect(catalogSpec("SSH_ID_ED25519")?.method).toBe("ssh-keygen");
expect(catalogSpec("SSH_ID_ED25519_DEPLOY")?.method).toBe("ssh-keygen");
expect(catalogSpec("DEPLOY_KEY")?.method).toBe("ssh-keygen");
expect(catalogSpec("SSH_ID_ED25519_PUB")).toBeNull();
expect(catalogSpec("SSH_CONFIG")).toBeNull();
expect(catalogSpec("SSH_ID_ED25519_PUB")?.method).toBe("not-secret");
expect(catalogSpec("SSH_CONFIG")?.method).toBe("not-secret");
expect(isNotSecret("SSH_KNOWN_HOSTS")).toBe(true);
});
@ -52,7 +52,7 @@ describe("catalog", () => {
});
it("knows nothing about plain config", () => {
expect(catalogSpec("SOLANA_RPC_URL")).toBeNull();
expect(catalogSpec("SOLANA_RPC_URL")?.method).toBe("not-secret");
expect(catalogSpec("NODE_ENV")).toBeNull();
});
});

View file

@ -1,6 +1,6 @@
import { spawnSync } from "node:child_process";
import { mkdtempSync, readFileSync, rmSync } from "node:fs";
import { tmpdir } from "node:os";
import { chmodSync, mkdtempSync, readFileSync, readdirSync, rmSync, statSync, writeFileSync } from "node:fs";
import { homedir, tmpdir } from "node:os";
import { join } from "node:path";
import {
decodeSshFile,
@ -25,6 +25,8 @@ import {
type PlannedRotation,
type RotationSpec
} from "./rotation-catalog.js";
import { ROTATORS, defaultRun, rewriteUrls, type Minted, type ProviderRotator, type RotatorContext } from "./rotators.js";
import { dev2Ops, findConsumers, inBatches, restoreBackup, rewriteEnvFile, type SiteOps } from "./propagate.js";
/**
* `logicsrc teams rotation` what rotating each secret takes (never values)
@ -146,6 +148,8 @@ export async function teamsRotationAction(slug: string, filter: RotationFilter,
key: p.key,
method: p.method,
auto: p.automatic ? "yes" : "no",
family: p.spec?.family ?? "",
owner: p.spec?.owner ?? "",
source: p.source,
vaults: p.vaults.length + ((p as { alsoIn?: string[] }).alsoIn?.length ?? 0),
since: String(p.oldestUpdate).slice(0, 10),
@ -153,7 +157,9 @@ export async function teamsRotationAction(slug: string, filter: RotationFilter,
}))
);
const auto = plan.filter((p) => p.automatic).length;
console.error(`\n${plan.length} value(s): ${auto} automatic, ${plan.length - auto} need a person or agent. Steps per key: --format json.`);
const unknown = plan.filter((p) => p.method === "unknown").length;
const never = plan.filter((p) => p.spec?.never).length;
console.error(`\n${plan.length} value(s): ${auto} automatic, ${plan.length - auto - unknown} manual (${never} never automated), ${unknown} without instructions. Steps per key: --format json.`);
console.error(`Rotate: logicsrc teams rotate-keys ${slug}${filter.project ? ` ${filter.project}` : ""}${filter.env ? ` ${filter.env}` : ""} [--key NAME] --approve`);
} else {
print(plan.map(({ fingerprint: _fp, ...p }) => p), options.format);
@ -215,6 +221,18 @@ export interface RotateKeysOptions {
approve: boolean;
setFromStdin?: boolean;
format: OutputFormat;
/** Rewrite + restart + health-check consumer sites under this root (dev2: ~/www). */
propagate?: string;
/** Unattended mode: only methods that are automatic, non-disruptive, and two-phase (or a plain random secret with known consumers). */
scheduled?: boolean;
/** Stop after this many live rotations. */
max?: number;
/** Write the JSON results (never values) to this file as well. */
report?: string;
/** Sites never rewritten or restarted: a value they hold is skipped. */
excludeSites?: string[];
/** Unattended mode: skip values read by more sites than this (default 5). */
maxSites?: number;
}
interface KeyPair {
@ -286,10 +304,20 @@ async function makeReplacement(p: PlannedRotation, oldValue: string, stdinValue?
}
}
export interface ConsumerReport {
site: string;
file: string;
keys: string[];
backup?: string;
restart?: string;
health?: string;
ok?: boolean;
}
export interface RotationResult {
key: string;
method: string;
status: "rotated" | "would-rotate" | "todo" | "failed" | "covered";
status: "rotated" | "would-rotate" | "todo" | "failed" | "rolled-back" | "skipped" | "covered";
/** Every vault:key holding the old value. */
vaults?: string[];
written: string[];
@ -297,6 +325,13 @@ export interface RotationResult {
steps?: string[];
url?: string;
consumers?: string[];
/** Sites found holding the value (with --propagate) and what happened to each. */
sites?: ConsumerReport[];
family?: string;
owner?: string;
never?: boolean;
disruptive?: string;
note?: string;
error?: string;
}
@ -306,9 +341,230 @@ async function readStdin(): Promise<string> {
return Buffer.concat(chunks).toString("utf8").replace(/\r?\n$/, "");
}
export async function teamsRotateKeysAction(slug: string, filter: RotationFilter, options: RotateKeysOptions): Promise<void> {
/** Why the unattended job leaves this one to a person, or null when it may rotate it. */
export function scheduledBlock(p: PlannedRotation): string | null {
const spec = p.spec;
if (!spec || !p.automatic) return "needs a person";
if (spec.never) return "never automated";
if (spec.disruptive) return `disruptive: ${spec.disruptive}`;
if (spec.method === "random") return null;
if (spec.method === "provider") {
const r = ROTATORS[spec.provider ?? ""];
if (!r) return `unknown rotator ${spec.provider}`;
return r.overlap ? null : `${r.title} has no overlap window`;
}
return `${spec.method} needs a person (public key install / command review)`;
}
const STRAY_PLACES = (): string[] => {
const home = homedir();
const dirs = [join(home, ".local/bin"), join(home, "scripts/bin")];
const files: string[] = [];
for (const d of dirs) {
try {
for (const n of readdirSync(d)) files.push(join(d, n));
} catch {
/* missing */
}
}
return files;
};
/** The crontab and small scripts under ~/.local/bin and ~/scripts/bin: places a secret hides outside env files. */
function defaultStrayText(): string[] {
const out = [crontabText()];
for (const f of STRAY_PLACES()) {
try {
if (statSync(f).isFile() && statSync(f).size < 1 << 20) out.push(readFileSync(f, "utf8"));
} catch {
/* unreadable */
}
}
return out;
}
function crontabText(): string {
const r = spawnSync("crontab", ["-l"], { encoding: "utf8" });
return r.status === 0 ? r.stdout : "";
}
export interface RotateDeps {
ops?: SiteOps;
fetch?: typeof fetch;
now?: Date;
env?: Record<string, string | undefined>;
/** Extra text to search for stray copies (tests). */
strayText?: () => string[];
}
interface VaultWrite {
vault: VaultState;
name: string;
oldValue: string;
newValue: string;
}
async function writeValues(team: Loaded, writes: VaultWrite[], which: "newValue" | "oldValue"): Promise<string[]> {
const written: string[] = [];
for (const vault of [...new Set(writes.map((w) => w.vault))]) {
const upserts = [];
for (const w of writes.filter((x) => x.vault === vault)) {
const value = w[which];
upserts.push({ name: w.name, ...(await encryptValue(value, await team.dek(vault))), fingerprint: fingerprintValue(value) });
}
const { applied } = await team.client.putSecrets(vault.id, upserts, []);
for (const name of applied) written.push(`${vault.name}:${name}`);
}
return written;
}
async function vaultValues(team: Loaded, v: VaultState): Promise<Record<string, string>> {
const out: Record<string, string> = {};
for (const s of v.secrets) {
if (isRotationEntry(s.name) || s.fingerprint === EMPTY_FINGERPRINT) continue;
out[s.name] = await readValue(team, v, s.name);
}
return out;
}
/**
* Rotate one value with a new one we can make ourselves (random, provider):
* mint -> vaults -> consumers -> health -> revoke, with a full rollback when
* any step after mint fails.
*/
async function rotateTwoPhase(
team: Loaded,
p: PlannedRotation,
targets: Array<{ vault: VaultState; key: string }>,
base: RotationResult,
options: RotateKeysOptions,
deps: Required<Pick<RotateDeps, "ops" | "fetch" | "now" | "env">> & { strayText: () => string[] }
): Promise<RotationResult> {
const spec = p.spec!;
const first = targets[0]!;
const oldValue = await readValue(team, first.vault, first.key);
const firstValues = await vaultValues(team, first.vault);
const stamp = deps.now.toISOString().slice(0, 10).replace(/-/g, "");
// Who reads it today. Found by value, so renamed copies count too.
const probe = [{ oldValue, newValue: oldValue }];
const hits = options.propagate ? findConsumers(options.propagate, probe) : [];
const sites: ConsumerReport[] = hits.map((h) => ({ site: h.site, file: h.file, keys: h.keys }));
const strays = deps.strayText().some((t) => oldValue.length >= 12 && t.includes(oldValue));
const excluded = hits.filter((h) => options.excludeSites?.includes(h.site));
if (excluded.length) return { ...base, status: "skipped", sites, error: `excluded site holds it: ${[...new Set(excluded.map((h) => h.site))].join(", ")}` };
if (options.scheduled) {
const n = new Set(hits.map((h) => h.site)).size;
if (n > (options.maxSites ?? 5)) return { ...base, status: "skipped", sites, error: `too many consumers for unattended rotation: ${n} sites (run it by hand with --propagate)` };
if (!options.propagate) return { ...base, status: "skipped", sites, error: "unattended rotation needs --propagate" };
if (!hits.length) return { ...base, status: "skipped", sites, error: "no consumer found on this box: rotate by hand where it is used" };
if (strays) return { ...base, status: "skipped", sites, error: "also in the crontab or a script under ~/.local/bin or ~/scripts/bin: update those by hand" };
}
if (spec.method === "provider") {
const r = ROTATORS[spec.provider ?? ""];
if (!r) return { ...base, status: "todo", sites, error: `unknown rotator ${spec.provider}` };
const why = await r.preflight({ key: p.key, oldValue, vaultValues: firstValues, state: spec.state ?? {}, env: deps.env, fetch: deps.fetch, run: defaultRun, now: deps.now });
if (why) return { ...base, status: "todo", sites, error: why };
}
if (!options.approve) return { ...base, status: "would-rotate", sites };
// A site that is already down would make the rotation look guilty.
const siteDirs = [...new Map(hits.map((h) => [h.dir, h])).values()];
const before = await inBatches(siteDirs, 3, (h) => deps.ops.health(h.dir, h.site));
const sick = before.filter((b) => !b.ok);
if (sick.length) return { ...base, status: "skipped", sites, error: `unhealthy before rotation: ${sick.map((s) => `${s.site} (${s.detail})`).join(", ")}` };
let rotator: ProviderRotator | undefined;
let minted: Minted;
if (spec.method === "provider") {
rotator = ROTATORS[spec.provider ?? ""];
if (!rotator) return { ...base, status: "todo", error: `unknown rotator ${spec.provider}` };
const ctx: RotatorContext = { key: p.key, oldValue, vaultValues: firstValues, state: spec.state ?? {}, env: deps.env, fetch: deps.fetch, run: defaultRun, now: deps.now };
minted = await rotator.mint(ctx);
} else {
const replacement = await makeReplacement(p, oldValue);
const value = replacement.valueFor(first.key, oldValue);
minted = { value, revokeOld: async () => undefined, rollback: async () => undefined };
}
// Vault writes: the value itself everywhere, plus companions (public halves, connection strings) where they live.
const writes: VaultWrite[] = [];
const companionReps: Array<{ oldValue: string; newValue: string }> = [];
for (const vault of [...new Set(targets.map((t) => t.vault))]) {
const values = vault === first.vault ? firstValues : await vaultValues(team, vault);
for (const t of targets.filter((x) => x.vault === vault)) writes.push({ vault, name: t.key, oldValue: values[t.key] ?? oldValue, newValue: minted.value });
const extra: Record<string, string> = { ...rewriteUrls(values, oldValue, minted.value) };
for (const [name, v] of Object.entries(minted.companions ?? {})) if (name in values && !rewriteUrls({ [name]: values[name]! }, oldValue, minted.value)[name]) extra[name] = v;
for (const [name, v] of Object.entries(extra)) {
if (writes.some((w) => w.vault === vault && w.name === name)) continue;
writes.push({ vault, name, oldValue: values[name]!, newValue: v });
if (values[name] !== v && values[name]!.length >= 12 && !values[name]!.includes(oldValue)) companionReps.push({ oldValue: values[name]!, newValue: v });
}
}
const undo = async (why: string, rewritten: Array<{ file: string; backup: string; dir: string; site: string }>): Promise<RotationResult> => {
const notes: string[] = [why];
try {
await writeValues(team, writes, "oldValue");
} catch (err) {
notes.push(`VAULTS NOT RESTORED: ${(err as Error).message}`);
}
for (const r of rewritten) restoreBackup(r.file, r.backup);
const restarted = await inBatches([...new Map(rewritten.map((r) => [r.dir, r])).values()], 3, (r) => deps.ops.restart(r.dir, r.site, false));
for (const r of restarted.filter((x) => !x.ok)) notes.push(`${r.site} did not come back on the old value: ${r.detail}`);
const rb = await minted.rollback().catch((e: Error) => e.message);
if (rb) notes.push(rb);
return { ...base, status: "rolled-back", sites, error: notes.join("; ") };
};
let written: string[];
try {
written = await writeValues(team, writes, "newValue");
} catch (err) {
return undo(`vault write failed: ${(err as Error).message}`, []);
}
// Consumers: rewrite env files (with backups), restart 3 at a time, health-check.
const reps = [{ oldValue, newValue: minted.value }, ...companionReps];
const rewritten: Array<{ file: string; backup: string; dir: string; site: string }> = [];
if (options.propagate) {
const now = findConsumers(options.propagate, reps);
for (const h of now) {
const { backup } = rewriteEnvFile(h.file, reps, stamp);
rewritten.push({ file: h.file, backup, dir: h.dir, site: h.site });
const rep = sites.find((s) => s.file === h.file);
if (rep) rep.backup = backup;
else sites.push({ site: h.site, file: h.file, keys: h.keys, backup });
}
const dirs = [...new Map(now.map((h) => [h.dir, { ...h, needsBuild: now.some((x) => x.dir === h.dir && x.needsBuild) }])).values()];
const results = await inBatches(dirs, 3, async (h) => {
const r = await deps.ops.restart(h.dir, h.site, h.needsBuild);
const hl = r.ok ? await deps.ops.health(h.dir, h.site) : { site: h.site, ok: false, detail: "not restarted" };
for (const s of sites.filter((x) => x.site === h.site)) Object.assign(s, { restart: r.detail, health: hl.detail, ok: r.ok && hl.ok });
return r.ok && hl.ok;
});
if (results.some((ok) => !ok)) return undo("a consumer failed after the switch; rolled back", rewritten);
}
const revokeNote = await minted.revokeOld().catch((e: Error) => `revoking the old credential failed (it is still live): ${e.message}`);
// Remember provider ids for next time (the old key's id is what revokeOld needs).
if (minted.state && Object.keys(minted.state).length) {
const entry = rotationEntryName(first.key);
const value = JSON.stringify({ ...spec, state: minted.state });
await team.client.putSecrets(first.vault.id, [{ name: entry, ...(await encryptValue(value, await team.dek(first.vault))), fingerprint: fingerprintValue(value) }], []);
}
return { ...base, status: "rotated", written, sites, ...(revokeNote ? { note: revokeNote } : {}) };
}
export async function teamsRotateKeysAction(slug: string, filter: RotationFilter, options: RotateKeysOptions, depsIn: RotateDeps = {}): Promise<RotationResult[]> {
const { team, plan, invalid } = await buildPlan(slug, filter);
if (plan.length === 0) throw new Error("Nothing to rotate: no matching keys. See: logicsrc teams rotation " + slug);
const deps = {
ops: depsIn.ops ?? dev2Ops,
fetch: depsIn.fetch ?? fetch,
now: depsIn.now ?? new Date(),
env: depsIn.env ?? process.env,
strayText: depsIn.strayText ?? defaultStrayText
};
let stdinValue: string | undefined;
if (options.setFromStdin) {
@ -320,6 +576,7 @@ export async function teamsRotateKeysAction(slug: string, filter: RotationFilter
const results: RotationResult[] = [];
// One value stored under two names is one rotation, not two.
const handled = new Map<string, string>();
let live = 0;
for (const p of plan) {
const earlier = handled.get(p.fingerprint);
if (earlier && (p.automatic || stdinValue !== undefined)) {
@ -327,18 +584,56 @@ export async function teamsRotateKeysAction(slug: string, filter: RotationFilter
continue;
}
handled.set(p.fingerprint, p.key);
const base = { key: p.key, method: stdinValue !== undefined ? "set" : p.method, steps: p.spec?.steps, url: p.spec?.url, consumers: p.spec?.consumers };
const spec = p.spec;
const base: RotationResult = {
key: p.key,
method: stdinValue !== undefined ? "set" : spec?.method === "provider" ? `provider:${spec.provider}` : p.method,
status: "todo",
written: [],
steps: spec?.steps,
url: spec?.url,
consumers: spec?.consumers,
family: spec?.family,
owner: spec?.owner ?? (spec?.method === "manual" ? "agent" : undefined),
never: spec?.never,
disruptive: spec?.disruptive,
note: spec?.note
};
const targets = siblings(team, p.fingerprint);
const where = targets.map((t) => `${t.vault.name}:${t.key}`);
base.vaults = targets.map((t) => `${t.vault.name}:${t.key}`);
if (stdinValue === undefined && !p.automatic) {
results.push({ ...base, status: "todo", vaults: where, written: [], steps: p.spec?.steps ?? ["No instructions: add some with logicsrc teams rotation-set."] });
results.push({ ...base, status: "todo", steps: spec?.steps ?? ["No instructions: add some with logicsrc teams rotation-set."] });
continue;
}
if (!options.approve) {
results.push({ ...base, status: "would-rotate", vaults: where, written: [] });
if (options.scheduled && stdinValue === undefined) {
const why = scheduledBlock(p);
if (why) {
results.push({ ...base, status: "skipped", error: why });
continue;
}
}
// A plain dry run only plans; with --propagate or --scheduled it also runs the read-only checks.
if (!options.approve && !options.propagate && !options.scheduled) {
results.push({ ...base, status: "would-rotate" });
continue;
}
if (options.approve && options.max !== undefined && live >= options.max) {
results.push({ ...base, status: "skipped", error: `--max ${options.max} reached` });
continue;
}
try {
if (stdinValue === undefined && (spec?.method === "random" || spec?.method === "provider")) {
const r = await rotateTwoPhase(team, p, targets, base, options, deps);
if (r.status === "rotated" || r.status === "rolled-back") live++;
results.push(r);
continue;
}
// ssh-keygen, command and --set-from-stdin: vault write only, consumers by hand.
if (!options.approve) {
results.push({ ...base, status: "would-rotate" });
continue;
}
live++;
const first = targets[0]!;
const oldValue = await readValue(team, first.vault, first.key);
const replacement = await makeReplacement(p, oldValue, stdinValue);
@ -368,22 +663,36 @@ export async function teamsRotateKeysAction(slug: string, filter: RotationFilter
const { applied } = await team.client.putSecrets(vault.id, upserts, []);
for (const name of applied) written.push(`${vault.name}:${name}`);
}
results.push({ ...base, status: "rotated", vaults: where, written, publicKey: replacement.publicKey });
results.push({ ...base, status: "rotated", written, publicKey: replacement.publicKey });
} catch (err) {
results.push({ ...base, status: "failed", written: [], error: (err as Error).message });
}
}
if (options.report) {
writeFileSync(options.report, JSON.stringify({ team: slug, at: deps.now.toISOString(), approve: options.approve, scheduled: Boolean(options.scheduled), results, locked: team.locked }, null, 2), { mode: 0o600 });
chmodSync(options.report, 0o600);
}
if (options.format === "table") {
printColumns(results.map((r) => ({ key: r.key, method: r.method, status: r.status, vaults: (r.status === "rotated" ? r.written : r.vaults ?? []).length, next: r.status === "todo" ? (r.url ?? "see --format json") : r.error ?? "" })));
printColumns(
results.map((r) => ({
key: r.key,
method: r.method,
status: r.status,
vaults: (r.status === "rotated" ? r.written : r.vaults ?? []).length,
sites: r.sites?.length ?? "",
next: r.status === "todo" ? (r.error ?? r.url ?? "see --format json") : r.error ?? r.note ?? ""
}))
);
for (const r of results.filter((x) => x.publicKey)) console.error(`\n${r.key} new public key (install it, remove the old one):\n${r.publicKey}`);
const todo = results.filter((r) => r.status === "todo").length;
if (!options.approve) console.error(`\nDry run. Apply with --approve.${todo ? ` ${todo} key(s) need a person or agent: --format json lists the steps.` : ""}`);
else console.error(`\nRestart or redeploy whatever reads the rotated values, then revoke the old ones where they were issued.`);
else if (!options.propagate) console.error(`\nRestart or redeploy whatever reads the rotated values (or pass --propagate ~/www), then revoke the old ones where they were issued.`);
} else {
print(results, options.format);
}
if (invalid.length) console.error(`Unreadable rotation entries (ignored): ${invalid.join("; ")}`);
if (team.locked.length) console.error(`Not covered (no access): ${team.locked.join(", ")}. Copies of these values there stay OLD.`);
if (results.some((r) => r.status === "failed")) process.exitCode = 1;
if (results.some((r) => r.status === "failed" || r.status === "rolled-back")) process.exitCode = 1;
return results;
}

View file

@ -0,0 +1,136 @@
import { describe, expect, it } from "vitest";
import { catalogSpec, isAutomatic, isNotSecret, planRotations, baseKeyName, EMPTY_FINGERPRINT } from "./rotation-catalog.js";
import { scheduledBlock } from "./rotate-keys.js";
const method = (k: string) => catalogSpec(k)?.method;
describe("catalog coverage (2026-10-29 plan)", () => {
it("never automates money, signing, the personal vault, Stripe, npm or GitHub App keys", () => {
for (const k of [
"SYSTEM_MNEMONIC_SOL__1",
"TREASURY_MNEMONIC_ETH",
"PRIVATE_KEY",
"LN_HSM_SECRET_HEX",
"LNBITS_ADMIN_KEY",
"KRAKEN_API_SECRET",
"COINBASE_API_PRIVATE_KEY_B64",
"STRIPE_SECRET_KEY",
"STRIPE_WEBHOOK_SECRET",
"NPM_TOKEN",
"GITHUB_APP_PRIVATE_KEY",
"OPENCREDS_MASTER_PASSWORD",
"OPENCREDS_RECOVERY_KEY",
"W3BS_TUF_ROOT_KEY_PK8_B64",
"DID_PRIVATE_KEY_BASE64",
"MOSHPIT_CA_ROOT_KEY",
"FTB_BUSINESS_PASSWORD"
]) {
const s = catalogSpec(k);
expect(s?.never, k).toBe(true);
expect(s?.owner, k).toBe("anthony");
expect(isAutomatic(s), k).toBe(false);
}
});
it("never mints random bytes for provider secrets that look like ours", () => {
for (const k of ["SLACK_SIGNING_SECRET", "JWT_SECRET", "SUPABASE_JWT_SECRET", "FIREFOX_JWT_SECRET", "META_APP_SECRET", "GITHUB_WEBHOOK_SECRET"]) {
expect(method(k), k).not.toBe("random");
}
});
it("routes keys with clean APIs to provider rotators", () => {
expect(catalogSpec("RESEND_API_KEY")?.provider).toBe("resend");
expect(catalogSpec("RESEND_PITWORLD_ADMIN_KEY")?.provider).toBe("resend");
expect(catalogSpec("CLOUDFLARE_API_TOKEN")?.provider).toBe("cloudflare-token");
expect(catalogSpec("COINPAY_API_KEY")?.provider).toBe("coinpay-api-key");
expect(catalogSpec("COINPAYPORTAL_WEBHOOK_SECRET")?.provider).toBe("coinpay-webhook-secret");
expect(catalogSpec("VAPID_PRIVATE_KEY")?.provider).toBe("vapid");
expect(catalogSpec("VAPID_PRIVATE")?.provider).toBe("vapid");
expect(catalogSpec("SUPABASE_DB_PASSWORD")?.provider).toBe("postgres-role");
});
it("classifies public config as not-secret", () => {
for (const k of [
"COINPAY_OAUTH_CLIENT_ID",
"COINPAY_OAUTH_REDIRECT_URI",
"COINPAY_OAUTH_SCOPES",
"COINPAY_OAUTH_ISSUER",
"STRIPE_PUBLISHABLE_KEY",
"SUPABASE_PUBLISHABLE_KEY",
"HCAPTCHA_SITE_KEY",
"SENTRY_DSN",
"EXPO_PUBLIC_SENTRY_DSN",
"WEBAUTHN_RP_ID",
"SESSION_COOKIE_SECURE",
"TURSO_DATABASE_URL",
"AUTHOR_BATCH_SIZE",
"SYSTEM_KEY_GENERATION",
"JWT_PUBLIC_KEY_JWK",
"R2_ACCESS_KEY_ID",
"__ARCHIVE__SUPABASE_SERVICE_ROLE_KEY"
]) {
expect(isNotSecret(k), k).toBe(true);
}
// ...but a connection string can hold a password.
expect(isNotSecret("DATABASE_URL")).toBe(false);
expect(catalogSpec("DATABASE_URL")?.family).toBe("postgres");
expect(isNotSecret("NEXT_PUBLIC_SUPABASE_ANON_KEY")).toBe(false);
});
it("gives every secret-looking name from the 2026-10-29 unknown list some instructions", () => {
const unknownBefore = [
"ADMIN_KEY", "ADNETWORK_KEY", "ANON_KEY", "API_KEY_SALT", "BITTORRENTED_SUPABASE_KEY", "BUILTINDIE_KEY", "CRAWLPROOF_ACTOR_TOKEN_ANTHONY",
"CRYPTO_APIS_KEY", "DB_PASS", "DEALDASH_COOKIE", "FAL_KEY", "GROUPCALL_AGENT_WORKER_KEY", "IMAP_PASS", "IP_HASH_SALT", "OPENACCESS_KEY_UGIG_NET",
"PAYAGENT_KEY", "PG_META_CRYPTO_KEY", "SALAD_AI_GATEWAY_KEY", "SECRET_KEY_BASE", "SEEDBOX_HTTP_AUTH", "SERVICE_ROLE_KEY", "SMTP_PASS",
"SOCIAL_VAULT_KEY", "SUPABASE_SECRETMAT_KEY", "TOKEN_ENC_KEY", "TURN_SERVER_CREDENTIAL", "VOTE_SALT", "SP_TOKEN_PEPPER", "AUR_SSH_KEY__1"
];
for (const k of unknownBefore) expect(catalogSpec(k), k).not.toBeNull();
});
it("strips __n duplicate suffixes before matching", () => {
expect(baseKeyName("SYSTEM_MNEMONIC_BTC__2")).toBe("SYSTEM_MNEMONIC_BTC");
expect(method("CRON_SECRET__1")).toBe("random");
});
it("marks session signers disruptive so the weekly job leaves them", () => {
expect(catalogSpec("SESSION_SECRET")?.disruptive).toBeTruthy();
expect(catalogSpec("CRON_SECRET")?.disruptive).toBeUndefined();
});
});
describe("planRotations", () => {
const row = (vault: string, key: string, fingerprint: string) => ({ vault, key, fingerprint, updatedAt: "2026-10-01T00:00:00Z" });
it("drops not-secret, archive and empty values; an entry can declare not-secret", () => {
const plan = planRotations(
[row("a--prod", "COINPAY_OAUTH_CLIENT_ID", "f1"), row("a--prod", "__ARCHIVE__X", "f2"), row("a--prod", "CRON_SECRET", EMPTY_FINGERPRINT), row("a--prod", "WEIRD_TOKEN", "f3"), row("a--prod", "CRON_SECRET", "f4")],
new Map([["a--prod\u0000WEIRD_TOKEN", { method: "not-secret" as const }]])
);
expect(plan.map((p) => p.key)).toEqual(["CRON_SECRET"]);
});
});
describe("entry specs", () => {
it("cannot make a wallet key automatic", () => {
const plan = planRotations([{ vault: "c--prod", key: "TREASURY_MNEMONIC_SOL", fingerprint: "f", updatedAt: "" }], new Map([["c--prod\u0000TREASURY_MNEMONIC_SOL", { method: "random" as const }]]));
expect(plan[0]!.automatic).toBe(false);
expect(plan[0]!.spec?.never).toBe(true);
});
it("TURN secrets are manual (coturn config holds a copy)", () => {
expect(catalogSpec("TURN_SERVER_CREDENTIAL")?.method).toBe("manual");
});
});
describe("scheduledBlock", () => {
const p = (spec: any) => ({ key: "K", vaults: ["a--prod"], fingerprint: "f", oldestUpdate: "", method: spec.method, source: "catalog" as const, automatic: isAutomatic(spec), spec });
it("lets plain random secrets and overlapping provider rotators through, nothing else", () => {
expect(scheduledBlock(p(catalogSpec("CRON_SECRET")))).toBeNull();
expect(scheduledBlock(p(catalogSpec("RESEND_API_KEY")))).toBeNull();
expect(scheduledBlock(p(catalogSpec("CLOUDFLARE_API_TOKEN")))).toBeNull();
expect(scheduledBlock(p(catalogSpec("COINPAY_API_KEY")))).toBeNull();
expect(scheduledBlock(p(catalogSpec("SESSION_SECRET")))).toMatch(/disruptive/);
expect(scheduledBlock(p(catalogSpec("COINPAY_WEBHOOK_SECRET")))).toMatch(/disruptive/);
expect(scheduledBlock(p(catalogSpec("SUPABASE_DB_PASSWORD")))).toMatch(/disruptive/);
expect(scheduledBlock(p(catalogSpec("SSH_ID_ED25519")))).toMatch(/person/);
expect(scheduledBlock(p(catalogSpec("SYSTEM_MNEMONIC_SOL")))).toMatch(/person|never/);
});
});

View file

@ -25,12 +25,19 @@ export function isoTime(value: unknown): string {
* public key has to be installed where the old one was.
* command a shell command that prints the new value on stdout (a
* provider CLI that can mint keys). Runs only with --approve.
* provider a built-in rotator (rotators.ts) that creates the new
* credential by API, and revokes the old one only after every
* consumer is healthy on the new one.
* manual a person or agent follows `steps` at `url`. Never automatic:
* provider-issued keys, wallet seeds, encryption keys that
* protect stored data.
* provider-issued keys without a rotator, wallet seeds,
* encryption keys that protect stored data.
* not-secret public config that happens to look like a secret (URLs,
* client ids, publishable keys). Dropped from the plan.
*/
export type RotationMethod = "random" | "ssh-keygen" | "command" | "manual";
export type RotationMethod = "random" | "ssh-keygen" | "command" | "provider" | "manual" | "not-secret";
export type RandomFormat = "hex" | "base64" | "base64url" | "alnum";
/** Who has to do a manual rotation: an agent with dashboard/CLI access, or Anthony (money, signing ceremonies, his logins). */
export type RotationOwner = "agent" | "anthony";
export interface RotationSpec {
method: RotationMethod;
@ -40,6 +47,8 @@ export interface RotationSpec {
length?: number;
/** command: prints the new value on stdout. */
command?: string;
/** provider: the rotator id (see rotators.ts). */
provider?: string;
/** Where to do it (provider dashboard, docs). */
url?: string;
/** What to do, in order. For manual rotations this is the whole job. */
@ -48,9 +57,21 @@ export interface RotationSpec {
consumers?: string[];
/** Why this method; shown in the plan. */
note?: string;
/** Grouping for reports and the runbook (stripe, supabase, wallet, ...). */
family?: string;
/** Manual rotations: who must do it. */
owner?: RotationOwner;
/** Never automated, whatever the method says (moves money, signing ceremony, banned provider). */
never?: boolean;
/** What a rotation breaks for users (sessions end, push subscriptions die). The weekly job skips these. */
disruptive?: string;
/** Rotator bookkeeping (e.g. the provider's id for the current key), written back after a rotation. */
state?: Record<string, string>;
}
export const ROTATE_PREFIX = ROTATION_ENTRY_PREFIX;
/** `teams clean` archive records: metadata about an archived value, never consumed. */
export const ARCHIVE_PREFIX = "__ARCHIVE__";
export function isRotationEntry(name: string): boolean {
return name.startsWith(ROTATE_PREFIX);
@ -60,7 +81,7 @@ export function rotationEntryName(key: string): string {
return `${ROTATE_PREFIX}${key}`;
}
const METHODS: readonly RotationMethod[] = ["random", "ssh-keygen", "command", "manual"];
const METHODS: readonly RotationMethod[] = ["random", "ssh-keygen", "command", "provider", "manual", "not-secret"];
const FORMATS: readonly RandomFormat[] = ["hex", "base64", "base64url", "alnum"];
/** Parse and validate a stored spec. Throws with a message naming the problem. */
@ -79,139 +100,349 @@ export function parseRotationSpec(raw: string): RotationSpec {
throw new Error("length must be an integer between 16 and 512");
}
if (v.method === "command" && (typeof v.command !== "string" || !v.command.trim())) throw new Error("method command needs a command");
if (v.method === "provider" && (typeof v.provider !== "string" || !v.provider.trim())) throw new Error("method provider needs a provider");
if (v.owner !== undefined && v.owner !== "agent" && v.owner !== "anthony") throw new Error("owner must be agent or anthony");
const strings = (x: unknown): string[] | undefined =>
Array.isArray(x) ? x.filter((s): s is string => typeof s === "string" && s.trim() !== "") : undefined;
const state =
v.state && typeof v.state === "object" && !Array.isArray(v.state)
? Object.fromEntries(Object.entries(v.state as Record<string, unknown>).filter((e): e is [string, string] => typeof e[1] === "string"))
: undefined;
return {
method: v.method as RotationMethod,
...(v.format ? { format: v.format as RandomFormat } : {}),
...(v.length ? { length: v.length as number } : {}),
...(typeof v.command === "string" ? { command: v.command } : {}),
...(typeof v.provider === "string" ? { provider: v.provider } : {}),
...(typeof v.url === "string" ? { url: v.url } : {}),
...(strings(v.steps) ? { steps: strings(v.steps) } : {}),
...(strings(v.consumers) ? { consumers: strings(v.consumers) } : {}),
...(typeof v.note === "string" ? { note: v.note } : {})
...(typeof v.note === "string" ? { note: v.note } : {}),
...(typeof v.family === "string" ? { family: v.family } : {}),
...(v.owner ? { owner: v.owner as RotationOwner } : {}),
...(v.never === true ? { never: true } : {}),
...(typeof v.disruptive === "string" ? { disruptive: v.disruptive } : {}),
...(state && Object.keys(state).length ? { state } : {})
};
}
const STORE = "Store it: logicsrc teams rotate-keys <team> <project> <env> --key <KEY> --set-from-stdin --approve (writes every vault holding the old value).";
const REDEPLOY = "Redeploy every consumer the plan lists, check each health URL.";
const REVOKE = "Revoke the old key once every consumer runs on the new one.";
function provider(name: string, url: string, extra: string[] = []): RotationSpec {
function provider(name: string, url: string, extra: string[] = [], more: Partial<RotationSpec> = {}): RotationSpec {
return {
method: "manual",
owner: "agent",
url,
steps: [`Create a new key in ${name} (${url}).`, ...extra, "Store it: logicsrc teams rotate-keys <team> <project> <env> --key <KEY> --set-from-stdin", REVOKE]
steps: [`Create a new key in ${name}${url ? ` (${url})` : ""}.`, ...extra, STORE, REDEPLOY, REVOKE],
...more
};
}
/** Anthony has to do it: his login/2FA, a signing ceremony, or money. */
function anthony(family: string, note: string, steps: string[], url?: string): RotationSpec {
return { method: "manual", owner: "anthony", never: true, family, note, steps, ...(url ? { url } : {}) };
}
function auto(provider: string, family: string, extra: Partial<RotationSpec> = {}): RotationSpec {
return { method: "provider", provider, family, ...extra };
}
interface CatalogRule {
test: RegExp;
spec: RotationSpec;
}
const WALLET_STEPS = [
"Generate a new wallet on a trusted machine (never on a server).",
"Move every balance (tokens and native gas) from the old address to the new one. A person signs this: it moves money.",
"Store the new key/seed under the same name (CoinPay system keys go in the CoinPay operator vault, not app.env), then update anything that pays to or watches the old address.",
"Never reuse the old seed: assume it is public."
];
const SIGNING_STEPS = [
"Generate the new key pair on a trusted machine.",
"Publish the new public half where verifiers look for it (DID document, TUF root, PLC directory, keyserver, MCP registry) BEFORE switching signers.",
"Store the new private key, redeploy the signer, keep the old public key trusted until everything signed with it has expired.",
"Revoke the old key in the same place you published the new one."
];
/**
* Order matters: the first match wins, so specific names come before the broad
* suffix rules at the bottom.
* suffix rules at the bottom. Names are matched upper-cased with any `__<n>`
* duplicate suffix removed (KEY__1 is the second copy of KEY).
*/
const CATALOG: CatalogRule[] = [
// Things whose "rotation" moves money or re-encrypts data: never automatic.
// ---- never automated: personal vault, money, signing ceremonies, banned providers --------
{
test: /(MNEMONIC|SEED_PHRASE|WALLET_PRIVATE_KEY|^(EVM|SOLANA|SOL|ETH|BTC|TRON)_PRIVATE_KEY$|X402_.*PRIVATE_KEY)/,
test: /^OPENCREDS_(MASTER_PASSWORD|RECOVERY_KEY)$/,
spec: anthony("personal-vault", "unlocks Anthony's personal vault", [
"Anthony only: logicsrc vault passwd (new master password), then save the new recovery key it prints.",
"Update the copy in the anthony-personal vault by hand at a terminal."
])
},
{
test: /(MNEMONIC|SEED_PHRASE|^TREASURY_|WALLET_PRIVATE_KEY|^(EVM|SOLANA|SOL|ETH|BTC|TRON|XRP|PRIVATE)_?(PRIVATE_)?KEY$|^PRIVATE_KEY$|X402_.*PRIVATE_KEY|TREASURY|LN_HSM_SECRET|HSM_SECRET|^LNBITS_.*(ADMIN|INVOICE|PAYLINK)_KEY$|^LNBITS_SUPERUSER_PASSWORD$|RELAYER.*KEY|^QRYPT_WEB_ISSUER_SEED$)/,
spec: anthony("wallet", "a wallet or Lightning key: rotating it means moving funds", WALLET_STEPS)
},
{
test: /^(KRAKEN|BINANCE(_US)?|COINBASE|ALPACA|APCA|CHANGENOW|SIDESHIFT|ZEROX|MOONPAY|PLAID|PAYPAL(_PLATFORM|_SANDBOX)?|WATCHWALLET)_.*(KEY|SECRET|PASSWORD|B64)$/,
spec: anthony("exchange", "an exchange, ramp or bank-link credential: it can move money", [
"Anthony: create a new key in the provider dashboard with the same (least) permissions; 2FA is his.",
STORE,
REDEPLOY,
"Delete the old key in the dashboard."
])
},
{
test: /^STRIPE_/,
spec: anthony("stripe", "Stripe is banned for new work: never rotated by automation", [
"Anthony: Stripe dashboard > Developers > API keys > Roll key (or the webhook endpoint > Roll secret).",
STORE,
REDEPLOY
], "https://dashboard.stripe.com/apikeys")
},
{
test: /^NPM_TOKEN$|^PYPI_API_TOKEN$|^CHOCOLATEY_API_KEY$/,
spec: anthony("package-registry", "publishes packages: a person creates it", [
"Anthony: create a granular automation token on the registry (npmjs.com > Access Tokens), scoped to the packages it publishes.",
STORE,
"Delete the old token on the registry."
], "https://www.npmjs.com/settings/~/tokens")
},
{
test: /^GITHUB_APP_(PRIVATE_KEY|CLIENT_SECRET|WEBHOOK_SECRET)$|^GITHUB_MARKETPLACE_WEBHOOK_SECRET$/,
spec: anthony("github-app", "GitHub App credentials are made in the App settings UI", [
"Anthony: github.com/settings/apps/<app> (or the org's) > Generate a private key / new client secret / webhook secret.",
STORE,
REDEPLOY,
"Delete the old private key in the App settings."
], "https://github.com/settings/apps")
},
{
test: /(^|_)(DID_PRIVATE_KEY|MCP_(REGISTRY|PUBLISHER)_PRIVATE_KEY|PLC_ROTATION_KEY|TUF_.*_KEY|PUBLISHER_KEY|POWER_KEY_PRIVATE_KEY|GPG_PRIVATE_KEY|CA_(ROOT_)?KEY|NOSTR_PRIVATE_KEY|CLIENT_JWT_PRIVATE_KEY|JWT_KEYS|FIREBASE_PRIVATE_KEY)/,
spec: anthony("signing", "a signing identity: verifiers pin the public half", SIGNING_STEPS)
},
{
test: /^(FTB|IRS|EFTPS|MAIL|CAL|NVIDIA|REDDIT|BLUESKY|MASTODON|BRAVE|APPLE|RIOTCODER|CHA0SPUNK|SEED\d*|OUTREACHGRAPH|THREATCRUSH|MOSHPIT|COINPAY|W3BS_SOCIAL|GIT_CHOVY|MYNA_CLOUD|EPIC|EXTELLA|PDL|HUNTER|CONTACTOUT|FULLENRICH|ROCKETREACH|SERPAPI|SERPER|DATAFORSEO|STOPFORUMSPAM|ABUSEIPDB|PROXIWARE|SALAD|OPENSUBTITLES|WEBSHARE|[A-Z0-9]+_AFFILIATE)(_[A-Z0-9]+)*_(PASSWORD|APP_SPECIFIC_PASSWORD|SUDO_PASSWORD)$/,
spec: anthony("account-login", "a human account login (often behind 2FA or email confirmation)", [
"Sign in to the account and change the password there (2FA/email confirmation goes to Anthony).",
"Save it in the personal vault (logicsrc vault) and, if an app logs in with it, store it: " + STORE.slice(10)
])
},
// ---- data at rest: a new value makes stored data unreadable ------------------------------
{
test: /(^|_)(ENCRYPTION_KEY|MASTER_KEY|DB_ENCRYPTION_KEY|SETTINGS_ENCRYPTION_KEY|LN_KEY_ENCRYPTION_KEY|TOKEN_ENC_KEY|CRYPTO_KEY|VAULT_KEY|KEYS_SECRET|API_KEY_SALT|TOKEN_PEPPER|SUPPRESSION_HASH_SALT|VOTE_SALT|SUBMISSION_SALT|OTR_SALT|DHT_API_KEY_SALT)$/,
spec: {
method: "manual",
note: "a wallet key: rotating it means moving funds",
owner: "agent",
family: "data-at-rest",
note: "protects or indexes stored data: a new value makes old ciphertext or hashes unreadable",
steps: [
"Generate a new wallet on a trusted machine.",
"Move every balance (tokens and native gas) from the old address to the new one.",
"Store the new key/seed under the same name, then update anything that pays to or watches the old address.",
"Never reuse the old seed: assume it is public."
"Add the new key next to the old one (dual-read), or run the app's re-encryption / re-hash migration.",
"Re-encrypt (or re-hash) stored data under the new key.",
"Remove the old key only after every row decrypts or matches with the new one."
]
}
},
{
test: /(^|_)(ENCRYPTION_KEY|MASTER_KEY|DB_ENCRYPTION_KEY|SETTINGS_ENCRYPTION_KEY|LN_KEY_ENCRYPTION_KEY|NEXT_SERVER_ACTIONS_ENCRYPTION_KEY)$/,
spec: {
method: "manual",
note: "protects data at rest: a new value makes old ciphertext unreadable",
steps: [
"Add the new key next to the old one (dual-read), or run the app's re-encryption migration.",
"Re-encrypt stored data under the new key.",
"Remove the old key only after every row decrypts with the new one."
]
}
// Next's server-actions key encrypts closures in flight only: a redeploy is all it needs.
test: /^NEXT_SERVER_ACTIONS_ENCRYPTION_KEY$/,
spec: { method: "random", family: "internal", format: "base64", length: 44, note: "Next server actions key: in-flight only", disruptive: "open tabs lose pending server actions until reload" }
},
// ---- SSH -----------------------------------------------------------------------------------
{
// Raw keys (DEPLOY_KEY=...) and the ssh provider's file envelopes (SSH_ID_ED25519).
test: /(^|_)(SSH_PRIVATE_KEY|DEPLOY_KEY|SSH_KEY)$|^SSH_(.*_)?ID_(RSA|ED25519|ECDSA|DSA)(_[A-Z0-9_]+)?$|^SSH_.*_(KEY|PEM)$/,
spec: {
method: "ssh-keygen",
family: "ssh",
steps: [
"Install the new public key everywhere the old one was authorized (authorized_keys on every host, GitHub deploy/user keys, CI secrets).",
"Remove the old public key from all of those places.",
"Pull the new private key onto the machines that use it: logicsrc teams pull / logicsrc ssh pull."
"Pull the new private key onto the machines that use it: logicsrc teams pull / logicsrc ssh pull / logicsrc keyring."
]
}
},
// Secrets we invent and only we check: mint a new random value.
// ---- built-in API rotators --------------------------------------------------------------
{ test: /^RESEND(_[A-Z0-9]+)*_(API|ADMIN)_KEY$/, spec: auto("resend", "resend", { url: "https://resend.com/api-keys" }) },
{
test: /^(CLOUDFLARE|CF)(_[A-Z0-9]+)*_(API_TOKEN|TOKEN)$/,
spec: auto("cloudflare-token", "cloudflare", { url: "https://dash.cloudflare.com/profile/api-tokens" })
},
{
test: /^(COINPAY|COINPAYPORTAL|CHOVY_COINPAY)(_[A-Z0-9]+)*_API_KEY$|^COINPAY_X402_KEY$/,
spec: auto("coinpay-api-key", "coinpay", { url: "https://coinpayportal.com/dashboard" })
},
{
test: /^(COINPAY|COINPAYPORTAL|CHOVY_COINPAY)(_[A-Z0-9]+)*_WEBHOOK_SECRET$/,
spec: auto("coinpay-webhook-secret", "coinpay", {
url: "https://coinpayportal.com/dashboard",
disruptive: "CoinPay has one webhook secret per business: webhooks fail signature checks until the consumer restarts (CoinPay retries them)"
})
},
{
test: /^VAPID_PRIVATE(_KEY)?$/,
spec: auto("vapid", "vapid", { disruptive: "every existing push subscription stops working; browsers must subscribe again" })
},
{
test: /^(POSTGRES_PASSWORD|DB_PASS(WORD)?|PG_?PASSWORD|[A-Z0-9_]*_DB_PASSWORD)$/,
spec: auto("postgres-role", "postgres", {
disruptive: "Postgres keeps one password per role: consumers that are not restarted fail to connect",
note: "self-hosted Supabase shares this password across its service roles: see the runbook"
})
},
// ---- provider-issued keys without a rotator (yet) ----------------------------------------
{ test: /^(GITHUB|GH)(_[A-Z0-9]+)*_(TOKEN|PAT)$/, spec: provider("GitHub (fine-grained token, same repos and permissions)", "https://github.com/settings/tokens", [], { family: "github" }) },
{ test: /^GITHUB(_[A-Z0-9]+)*_(CLIENT_SECRET|WEBHOOK_SECRET)$|^GL_WEBHOOK_SECRET$/, spec: provider("the GitHub OAuth app / webhook settings (Generate a new client secret; GitHub keeps two live)", "https://github.com/settings/developers", [], { family: "github" }) },
{ test: /^ANTHROPIC_API_KEY$/, spec: provider("the Anthropic console", "https://console.anthropic.com/settings/keys", [], { family: "ai" }) },
{ test: /^OPENAI_API_KEY$/, spec: provider("the OpenAI dashboard (same project)", "https://platform.openai.com/api-keys", [], { family: "ai" }) },
{ test: /^(GEMINI|GOOGLE)_API_(KEY|SECRET)$|^EXPO_PUBLIC_GOOGLE_API_KEY$/, spec: provider("Google Cloud credentials (same API restrictions)", "https://console.cloud.google.com/apis/credentials", [], { family: "google" }) },
{ test: /^GOOGLE(_OAUTH)?_CLIENT_SECRET$|^CHROME_(CLIENT_SECRET|REFRESH_TOKEN)$/, spec: provider("Google Cloud OAuth client (Add secret, then disable the old one)", "https://console.cloud.google.com/apis/credentials", [], { family: "google" }) },
{
test: /^SUPABASE_ACCESS_TOKEN$/,
spec: provider("Supabase account tokens", "https://supabase.com/dashboard/account/tokens", [], { family: "supabase" })
},
{
test: /^(SUPABASE_SERVICE_ROLE_KEY|SUPABASE_SERVICE_KEY|SUPABASE_SECRET_KEY|SUPABASE_SECRETMAT_KEY|SERVICE_ROLE_KEY(_ASYMMETRIC)?|SUPABASE_JWT_SECRET|JWT_SECRET|NEXT_PUBLIC_SUPABASE_ANON_KEY|VITE_SUPABASE_ANON_KEY|PUBLIC_SUPABASE_ANON_KEY|SUPABASE_ANON_KEY|ANON_KEY(_ASYMMETRIC)?|[A-Z0-9]+_SUPABASE_KEY|SUPABASE_S3_(ACCESS|SECRET)_KEY|S3_PROTOCOL_ACCESS_KEY_SECRET|SUPABASE_SMS_HOOK_SECRET|SEND_SMS_HOOK_SECRET|LOGFLARE_.*(KEY|TOKEN))$/,
spec: {
method: "manual",
owner: "agent",
family: "supabase",
note: "the Supabase JWT secret signs every key and session",
disruptive: "a new JWT secret signs everyone out and re-issues the anon and service_role keys",
url: "https://supabase.com/docs/guides/self-hosting/docker#securing-your-services",
steps: [
"Self-hosted: generate a new JWT_SECRET (40+ chars), mint new anon + service_role JWTs from it, write all three to the stack's .env.",
"Restart the stack (docker compose up -d with the stack's own env file); every session ends.",
"Hosted: Project settings > API > generate new JWT secret / new API keys.",
"Store each new value with --set-from-stdin (every vault sharing the old fingerprint is updated), redeploy the apps, then confirm the old anon key gets 401."
]
}
},
{
test: /^(TURSO|DATABASE|[A-Z0-9]+_DB|[A-Z0-9]+_DATABASE)_AUTH_TOKEN$|^TURSO_AUTH_TOKEN$/,
spec: provider("Turso: turso db tokens create <db> (old tokens keep working)", "https://docs.turso.tech/cli/db/tokens/create", [
"turso db tokens invalidate <db> kills EVERY token for that database: run it only after all consumers use the new one."
], { family: "turso" })
},
{ test: /^TWILIO_(AUTH_TOKEN|SECRET)$/, spec: provider("Twilio (Console > Account > API keys & tokens > secondary auth token, then promote)", "https://console.twilio.com/us1/account/keys-credentials/api-keys", [], { family: "twilio" }) },
{ test: /^TELNYX_(API_KEY|.*SECRET)$/, spec: provider("Telnyx", "https://portal.telnyx.com/#/app/api-keys", [], { family: "telnyx" }) },
{ test: /^PORKBUN_(API|SECRET)(_API)?_KEY$|^PORKBUN_API_SECRET$/, spec: provider("Porkbun (create a new API key pair)", "https://porkbun.com/account/api", [], { family: "porkbun" }) },
{ test: /^ELEVENLABS_API_KEY$/, spec: provider("ElevenLabs", "https://elevenlabs.io/app/settings/api-keys", [], { family: "ai" }) },
{ test: /^(DEEPSEEK|MOONSHOT|QWEN|DASHSCOPE|ZAI|PERPLEXITY|OLLAMA|GLAMA|FAL|HUGGINGFACE|NGC|NVIDIA_NIM|ABLITERATION|SALAD_AI_GATEWAY|EXA|LINKUP|BRAVE)(_API)?_(KEY|TOKEN)$/, spec: provider("the model/search provider's API keys page", "", [], { family: "ai" }) },
{ test: /^(COINPAY|[A-Z0-9]+_COINPAY|ADNETWORK_COINPAY)(_OAUTH)?_CLIENT_SECRET$/, spec: provider("CoinPay OAuth apps (our own: coinpayportal.com > Developer > OAuth apps > regenerate secret)", "https://coinpayportal.com/dashboard", [], { family: "coinpay" }) },
{ test: /^FIREFOX_JWT_(SECRET|ISSUER)$/, spec: provider("addons.mozilla.org API credentials (Developer Hub > Manage API Keys > Generate new credentials)", "https://addons.mozilla.org/developers/addon/api/key/", [], { family: "browser-store" }) },
{ test: /^EDGE_(API_KEY|CLIENT_SECRET)$/, spec: provider("Microsoft Partner Center (Edge Add-ons API)", "https://partner.microsoft.com/dashboard/microsoftedge/publishapi", [], { family: "browser-store" }) },
{ test: /^SLACK_|^META_APP_SECRET$|^THREADS_APP_SECRET$|^LINKEDIN_|^MASTODON_(ACCESS_TOKEN|CLIENT_SECRET)$|^DEVTO_API_KEY$|^BLUESKY_APP_PASSWORD$/, spec: provider("the social platform's developer settings", "", [], { family: "social" }) },
{ test: /^(R2|S3|AWS|MINIO)_(SECRET_ACCESS_KEY|ROOT_PASSWORD)$/, spec: provider("the object store (Cloudflare R2 > Manage API tokens, or MinIO admin)", "https://dash.cloudflare.com/?to=/:account/r2/api-tokens", [], { family: "storage" }) },
{
test: /^TURN_(SECRET|SERVER_CREDENTIAL)$/,
spec: {
method: "manual",
owner: "agent",
family: "internal",
note: "the coturn static-auth-secret lives in turnserver.conf as well as the app env",
steps: ["Generate a new value (openssl rand -hex 32).", "Set static-auth-secret in turnserver.conf and the app's env together, restart coturn and the app.", STORE]
}
},
{
test: /^OPENACCESS_KEY_[A-Z0-9_]+$/,
spec: provider("the OpenAccess hub (logicsrc.com/app, site keys): mint a new key for that site", "https://logicsrc.com/docs/openaccess", [], { family: "fleet-app" })
},
{
test: /(DEALDASH_COOKIE|SESSION_COOKIES|AUTO_COOKIE|SEEDBOX_.*_(AUTH|TOKEN)|SIRIUSXM_TOKEN|TUNEIN_TOKEN)$/,
spec: { method: "manual", owner: "agent", family: "scraped-session", note: "a logged-in browser session for a third-party site", steps: ["Sign in to the site again in the scraping browser profile and copy the fresh cookie/token.", STORE, REDEPLOY] }
},
// ---- secrets we invent: mint a random value --------------------------------------------
{
// Session signers: rotating signs everybody out.
test: /^(AUTH_SECRET|BETTER_AUTH_SECRET|NEXTAUTH_SECRET|SESSION_SECRET|COOKIE_SECRET|JWT_SIGNING_SECRET|SECRET_KEY_BASE|([A-Z0-9]+_)*(SESSION_SECRET|JWT_SECRET|OIDC_SIGNING_SECRET|CLI_SESSION_SECRET))$/,
spec: { method: "random", family: "internal", disruptive: "signs sessions or tokens: everyone signs in again", steps: ["Redeploy every consumer so both sides use the new value."] }
},
{
// Exact names, or our own *_CRON_SECRET / *_ADMIN_TOKEN style suffixes. A
// provider prefix (META_APP_SECRET, GOOGLE_AUTH_SECRET) is THEIR secret and
// must never be replaced with random bytes.
test: /^(APP_SECRET|AUTH_SECRET|BETTER_AUTH_SECRET|NEXTAUTH_SECRET|SESSION_SECRET|COOKIE_SECRET|JWT_SIGNING_SECRET|([A-Z0-9]+_)*(CRON_SECRET|INTERNAL_API_KEY|ADMIN_TOKEN|CLI_SESSION_SECRET|WEBHOOK_SIGNING_SECRET|REPUTATION_SIGNING_SECRET|OIDC_SIGNING_SECRET))$/,
spec: { method: "random", steps: ["Redeploy every consumer so both sides use the new value."] }
test: /^(APP_SECRET|IP_HASH_SALT|RATE_LIMIT_SALT|([A-Z0-9]+_)*(CRON_SECRET|CRON_TOKEN|INTERNAL_API_KEY|ADMIN_TOKEN|WEBHOOK_SIGNING_SECRET|REPUTATION_SIGNING_SECRET|SHARED_SECRET|HMAC_SECRET|TICKET_SECRET|BRIDGE_SECRET|HOOKS_SECRET|FORM_SECRET|PARTNER_VERIFY_SECRET|SIGN_SECRET|SIGNING_SECRET|BOOTSTRAP_SECRET|HOST_TOOL_SECRET|IP_HASH_SALT))$/,
spec: { method: "random", family: "internal", steps: ["Redeploy every consumer so both sides use the new value."] }
},
// Provider-issued keys.
{ test: /^STRIPE_(SECRET|RESTRICTED)_KEY$/, spec: provider("the Stripe dashboard (Developers > API keys > Roll key)", "https://dashboard.stripe.com/apikeys") },
{ test: /^STRIPE.*WEBHOOK_SECRET$/, spec: provider("the Stripe webhook endpoint (Roll secret)", "https://dashboard.stripe.com/webhooks") },
{ test: /^(GITHUB|GH)_(TOKEN|PAT)$|^GITHUB_APP_PRIVATE_KEY$/, spec: provider("GitHub", "https://github.com/settings/tokens") },
{ test: /^ANTHROPIC_API_KEY$/, spec: provider("the Anthropic console", "https://console.anthropic.com/settings/keys") },
{ test: /^OPENAI_API_KEY$/, spec: provider("the OpenAI dashboard", "https://platform.openai.com/api-keys") },
{ test: /^GEMINI_API_KEY$|^GOOGLE_API_KEY$/, spec: provider("Google AI Studio", "https://aistudio.google.com/app/apikey") },
{ test: /^RESEND_API_KEY$/, spec: provider("Resend", "https://resend.com/api-keys") },
{ test: /^TELNYX_API_KEY$/, spec: provider("Telnyx", "https://portal.telnyx.com/#/app/api-keys") },
{ test: /^ELEVENLABS_API_KEY$/, spec: provider("ElevenLabs", "https://elevenlabs.io/app/settings/api-keys") },
{ test: /^(COINPAY|COINPAYPORTAL)_API_KEY$|^COINPAY_X402_KEY$/, spec: provider("CoinPay (business > API keys)", "https://coinpayportal.com/dashboard") },
{ test: /^COINPAY.*WEBHOOK_SECRET$/, spec: provider("CoinPay (business > webhook secret > regenerate)", "https://coinpayportal.com/dashboard") },
{ test: /^CLOUDFLARE_API_TOKEN$|^CF_API_TOKEN$/, spec: provider("Cloudflare", "https://dash.cloudflare.com/profile/api-tokens") },
{ test: /^PORKBUN_(API|SECRET)_KEY$/, spec: provider("Porkbun", "https://porkbun.com/account/api") },
{
test: /^(SUPABASE_SERVICE_ROLE_KEY|SUPABASE_SECRET_KEY|SUPABASE_JWT_SECRET|NEXT_PUBLIC_SUPABASE_ANON_KEY|SUPABASE_ANON_KEY|JWT_SECRET)$/,
spec: {
method: "manual",
note: "the Supabase JWT secret signs every key and session",
steps: [
"Self-hosted: set a new JWT secret, mint new anon + service_role keys from it, restart the stack (all sessions end).",
"Hosted: Project settings > API > generate new JWT secret / new API keys.",
"Update every vault holding the old keys (they share a fingerprint), redeploy, then revoke the old ones."
]
}
// Our own apps issue these (listing keys, agent keys, bridge keys, admin keys).
test: /^([A-Z0-9]+_)*(LISTING_KEY|AGENT_KEY|AGENT_WORKER_KEY|PARTNER_KEY|PROJECT_KEY|ACTOR_TOKEN(_[A-Z0-9]+)?|BRIDGE_KEY|PAYAGENT_KEY|LIBRARY_KEY|LYRICS_KEY|OWNER_KEY|ADMIN_KEY|HOUSE_API_KEY|PUBLISHER_TOKEN|ADVERTISER_TOKEN|POST_TOKEN|DEV_BOX_TOKEN|SUBMIT_TOKEN|GATEWAY_TOKEN|NOBODY_KEY|HEALTH_TOKEN_KEY|COMP_KEYS|API_KEYS|ALERT_API_KEY)$|^(ADNETWORK|BUILTINDIE|GROUPCALL|MEDIAANALYZER|UGIG_API_KEY_[A-Z0-9_]+|RSSAMPLIFIER_API|SMSHUB_API|WX93_API|SEORANK_API|BUFFEROVERRIDE|CRAWLPROOF(_API)?|MOSHPIT_API|SUBMITFLEET_SECRET)_?(KEY|TOKEN)?$/,
spec: provider("our own app that issues it (its admin page or API: mint a new key for the same account, then revoke the old one there)", "", [], { family: "fleet-app" })
},
{ test: /(^|_)WEBHOOK_SECRET$/, spec: provider("the service that signs the webhook (its webhook settings: regenerate/roll the signing secret)", "", [], { family: "webhook" }) },
{
test: /^(SMTP|IMAP)_PASS(WORD)?$|_EMAIL_PASSWORD$/,
spec: provider("the mailbox (Forward Email > Domains > Aliases > Generate password)", "https://forwardemail.net/my-account/domains", [], { family: "email" })
},
{ test: /(^|_)WEBHOOK_SECRET$/, spec: provider("the service that signs the webhook", "") },
// Broad fallbacks for anything provider-issued.
{ test: /(_API_KEY|_API_SECRET|_SECRET_KEY|_ACCESS_KEY|_TOKEN|_PRIVATE_KEY|_PASSWORD|_SECRET)$/, spec: provider("the issuing provider's dashboard", "") }
{
test: /(_API_KEY|_API_SECRET|_SECRET_KEY|_ACCESS_KEY|_TOKEN|_PRIVATE_KEY|_PASSWORD|_SECRET|_KEY|_PASS|_AUTH|_CREDENTIAL|_COOKIE|_SALT|_PEPPER)$|^(API_TOKEN|ADMIN_PASSWORD|ACCESS_PASSWORD|DASHBOARD_PASSWORD)$/,
spec: provider("the issuing provider's dashboard (the key name's prefix names it)", "", [], { family: "other" })
}
];
/** KEY__1 is the second copy of KEY (keyring/pull dedupe); match on KEY. */
export function baseKeyName(key: string): string {
return key.toUpperCase().replace(/__\d+$/, "");
}
/** Names that read like credentials. Plain config (MODE, URL, *_USD) is not planned at all. */
export function looksSecret(key: string): boolean {
return /(KEY|SECRET|TOKEN(?!S)|PASSWORD|PASSWD|_PASS$|PRIVATE|MNEMONIC|SEED_PHRASE|_SEED$|CREDENTIAL|AUTH|SALT|SIGNING|COOKIE|SESSION|DSN|CONNECTION_STRING|DATABASE_URL|_PEM|_P12|CERT)/i.test(key);
return /(KEY|SECRET|TOKEN(?!S)|PASSWORD|PASSWD|_PASS$|PRIVATE|MNEMONIC|SEED_PHRASE|_SEED$|CREDENTIAL|AUTH|SALT|PEPPER|SIGNING|COOKIE|SESSION|DSN|CONNECTION_STRING|DATABASE_URL|_PEM|_P12|CERT)/i.test(key);
}
/** Built-in instructions for a key name, or null when we know nothing. */
/** Public halves, ssh config and browser-public values: nothing to rotate. */
/** URLs that can carry a password in their userinfo. Turso/libsql URLs carry none. */
const CREDENTIAL_URL = /(^|_)(DATABASE|DB|POSTGRES|PG|REDIS|MONGO|MONGODB|AMQP|RABBITMQ|CONNECTION)(_URL|_URI|_STRING|_DSN)$/;
/**
* Public halves, ssh config, browser-public values and plain config whose name
* merely contains KEY/TOKEN/AUTH: nothing to rotate.
*/
export function isNotSecret(key: string): boolean {
const name = key.toUpperCase();
return /^SSH_.*(_PUB|CONFIG|KNOWN_HOSTS|AUTHORIZED_KEYS|_CONF)$/.test(name) || /_PUBLIC_KEY$|^NEXT_PUBLIC_(?!SUPABASE_ANON_KEY)/.test(name);
const name = baseKeyName(key);
if (name.startsWith(ARCHIVE_PREFIX)) return true;
if (/^SSH_.*(_PUB|CONFIG|KNOWN_HOSTS|AUTHORIZED_KEYS|_CONF)$/.test(name)) return true;
if (/_PUBLIC_KEY(_JWK)?$|_PUBLIC$|^NEXT_PUBLIC_(?!SUPABASE_ANON_KEY)|^EXPO_PUBLIC_(?!GOOGLE_API_KEY)/.test(name)) return true;
if (/^TURSO_|^[A-Z0-9]+_TURSO_/.test(name) && /_URL$/.test(name)) return true;
if (CREDENTIAL_URL.test(name) && !/^TURSO_/.test(name)) return false;
return /(_URL|_URI|_ISSUER|_SCOPES?|_CLIENT_ID|_KEY_ID|_KEY_NAME|_ACCESS_KEY_ID|_BATCH_SIZE|_CONCURRENCY|_INTERVAL_SECONDS|_ENRICH|_EMAIL|_LIFETIME|_TTL|_PER_HOUR|_DAILY_LIMIT|_SITE_KEY|_PUBLISHABLE_KEY|_KID|_CONNECTION_ID|_RP_ID|_ORIGIN|_COOKIE_SECURE|_KEY_GENERATION|_AUTH_USER|_USER|_USERNAME|_CA_CERT|_CERT|_DSN|_VERIFICATION_KEY|_GPG_KEY_ID|_KEY_CONCURRENCY|_KEY_DAILY_LIMIT)$|^(AUTH_EMAIL|CERTBOT_EMAIL|SESSION_LIFETIME|GPG_KEY_ID|AUTHOR_[A-Z_]+|SYSTEM_KEY_GENERATION)$/.test(name);
}
export function catalogSpec(key: string): RotationSpec | null {
const name = key.toUpperCase();
if (isNotSecret(name)) return null;
const name = baseKeyName(key);
if (isNotSecret(name)) return { method: "not-secret", note: "public or plain config" };
if (CREDENTIAL_URL.test(name)) {
return {
method: "manual",
owner: "agent",
family: "postgres",
note: "a connection string: it changes when the password inside it rotates",
steps: ["Rotate the role password (postgres-role rotator or the runbook); the rotator rewrites every connection string holding the old password."]
};
}
const rule = CATALOG.find((r) => r.test.test(name));
if (!rule) return null;
const spec = { ...rule.spec, steps: rule.spec.steps ? [...rule.spec.steps] : undefined };
if (spec.url === "") delete spec.url;
if (!spec.steps) delete spec.steps;
return spec;
}
/** Automatic = we can produce the new value without a person. */
export function isAutomatic(spec: RotationSpec | null): boolean {
if (!spec || spec.never) return false;
return spec.method === "random" || spec.method === "ssh-keygen" || spec.method === "command" || spec.method === "provider";
}
/** The alphabet an existing value looks like it was drawn from. */
export function detectFormat(value: string): RandomFormat {
if (/^[0-9a-f]+$/i.test(value)) return "hex";
@ -263,14 +494,17 @@ export interface PlannedRotation {
/**
* One row per distinct (key name, value): the same value stored under the same
* name in several vaults rotates once and is written to all of them. Rotation
* entries themselves are never rotated.
* entries, archive records and not-secret config are never planned.
*/
export function planRotations(rows: PlanInput[], entrySpecs: Map<string, RotationSpec>): PlannedRotation[] {
const groups = new Map<string, PlanInput[]>();
for (const r of rows) {
if (isRotationEntry(r.key) || isNotSecret(r.key) || r.fingerprint === EMPTY_FINGERPRINT) continue;
if (isRotationEntry(r.key) || r.key.startsWith(ARCHIVE_PREFIX) || r.fingerprint === EMPTY_FINGERPRINT) continue;
const entry = entrySpecs.get(`${r.vault}\u0000${r.key}`);
if (entry?.method === "not-secret") continue;
if (!entry && isNotSecret(r.key)) continue;
// Config with no instructions is not a secret to rotate; an explicit entry overrides.
if (!looksSecret(r.key) && !catalogSpec(r.key) && !entrySpecs.has(`${r.vault}\u0000${r.key}`)) continue;
if (!entry && !looksSecret(r.key) && !catalogSpec(r.key)) continue;
const id = `${r.key}\u0000${r.fingerprint}`;
groups.set(id, [...(groups.get(id) ?? []), r]);
}
@ -279,7 +513,9 @@ export function planRotations(rows: PlanInput[], entrySpecs: Map<string, Rotatio
const first = members[0]!;
// An entry spec in any vault holding this value applies to all of them.
const fromEntry = members.map((m) => entrySpecs.get(`${m.vault}\u0000${m.key}`)).find(Boolean) ?? null;
const spec = fromEntry ?? catalogSpec(first.key);
const fromCatalog = catalogSpec(first.key);
// An entry can add steps, but it cannot make a never-automated key (wallet, signing, Stripe) automatic.
const spec = fromEntry && fromCatalog?.never ? { ...fromEntry, never: true, owner: fromCatalog.owner, family: fromEntry.family ?? fromCatalog.family } : fromEntry ?? fromCatalog;
out.push({
key: first.key,
vaults: members.map((m) => m.vault).sort(),
@ -287,7 +523,7 @@ export function planRotations(rows: PlanInput[], entrySpecs: Map<string, Rotatio
oldestUpdate: members.map((m) => isoTime(m.updatedAt)).sort()[0]!,
method: spec?.method ?? "unknown",
source: fromEntry ? "entry" : spec ? "catalog" : "none",
automatic: spec?.method === "random" || spec?.method === "ssh-keygen" || spec?.method === "command",
automatic: isAutomatic(spec),
spec
});
}

View file

@ -0,0 +1,260 @@
import { createHash, createHmac, pbkdf2Sync } from "node:crypto";
import { describe, expect, it } from "vitest";
import {
cloudflareTokenRotator,
coinpayApiKeyRotator,
coinpayWebhookSecretRotator,
newVapidPair,
postgresRoleRotator,
resendRotator,
rewriteUrls,
scramVerifier,
vapidRotator,
type RotatorContext
} from "./rotators.js";
type Handler = (method: string, url: URL, auth: string, body: any) => { status: number; body?: any };
function fakeFetch(handler: Handler): { fetch: typeof fetch; calls: Array<{ method: string; path: string; auth: string }> } {
const calls: Array<{ method: string; path: string; auth: string }> = [];
const f = (async (input: any, init: any = {}) => {
const url = new URL(String(input));
const method = (init.method ?? "GET").toUpperCase();
const auth = String(init.headers?.authorization ?? "").replace(/^Bearer /, "");
calls.push({ method, path: url.pathname, auth });
const r = handler(method, url, auth, init.body ? JSON.parse(init.body) : null);
return new Response(r.body === undefined ? "" : JSON.stringify(r.body), { status: r.status });
}) as typeof fetch;
return { fetch: f, calls };
}
const ctx = (over: Partial<RotatorContext>): RotatorContext => ({
key: "K",
oldValue: "old-value-xxxxxxxxxxxx",
vaultValues: {},
state: {},
env: {},
fetch: fetch,
now: new Date("2026-10-29T00:00:00Z"),
...over
});
describe("resend", () => {
it("mints with the old full-access key, revokes the old id from state only after revokeOld, rolls back the new one", async () => {
const keys = new Map([["old-id", "re_old_xxxxxxxxxxxxxxxx"]]);
const { fetch, calls } = fakeFetch((m, url, auth, body) => {
const live = [...keys.values()].includes(auth);
if (!live) return { status: 401, body: { message: "API key is invalid" } };
if (m === "GET" && url.pathname === "/api-keys") return { status: 200, body: { data: [...keys.keys()].map((id) => ({ id })) } };
if (m === "POST" && url.pathname === "/api-keys") {
keys.set("new-id", "re_new_yyyyyyyyyyyyyyyy");
expect(body.permission).toBe("full_access");
return { status: 201, body: { id: "new-id", token: "re_new_yyyyyyyyyyyyyyyy" } };
}
if (m === "DELETE") {
keys.delete(url.pathname.split("/").pop()!);
return { status: 200, body: {} };
}
return { status: 404 };
});
const c = ctx({ key: "RESEND_API_KEY", oldValue: "re_old_xxxxxxxxxxxxxxxx", state: { keyId: "old-id" }, fetch });
expect(await resendRotator.preflight(c)).toBeNull();
const minted = await resendRotator.mint(c);
expect(minted.value).toBe("re_new_yyyyyyyyyyyyyyyy");
expect(minted.state).toEqual({ keyId: "new-id" });
expect(keys.has("old-id")).toBe(true); // both live until revokeOld
expect(await minted.revokeOld()).toBeUndefined();
expect(keys.has("old-id")).toBe(false);
expect(calls.some((x) => x.auth.includes("yyyy"))).toBe(true);
});
it("asks for a manual revoke when the old key's id was never recorded, and rollback deletes the new key", async () => {
const deleted: string[] = [];
const { fetch } = fakeFetch((m, url) => {
if (m === "GET") return { status: 200, body: { data: [] } };
if (m === "POST") return { status: 201, body: { id: "n1", token: "re_n1_zzzzzzzzzzzzzz" } };
if (m === "DELETE") deleted.push(url.pathname);
return { status: 200, body: {} };
});
const minted = await resendRotator.mint(ctx({ key: "RESEND_API_KEY", fetch }));
expect(await minted.revokeOld()).toMatch(/delete the previous key/);
await minted.rollback();
expect(deleted).toEqual(["/api-keys/n1"]);
});
it("preflight fails for a sending-only key without an admin key", async () => {
const { fetch } = fakeFetch(() => ({ status: 401, body: { message: "restricted" } }));
expect(await resendRotator.preflight(ctx({ fetch }))).toMatch(/RESEND_ADMIN_API_KEY/);
});
});
describe("cloudflare-token", () => {
it("clones the old token's policies, deletes the old token only on revokeOld", async () => {
const tokens = new Map<string, any>([["t-old", { id: "t-old", name: "dns edit", value: "cf_old_xxxxxxxxxxxxxx", policies: [{ id: "p", effect: "allow", resources: { "com.cloudflare.api.account.zone.*": "*" }, permission_groups: [{ id: "g1", name: "DNS Write" }] }] }]]);
let created: any = null;
const { fetch } = fakeFetch((m, url, auth, body) => {
const me = [...tokens.values()].find((t) => t.value === auth);
if (!me) return { status: 401, body: { errors: [{ message: "Invalid API Token" }] } };
if (url.pathname.endsWith("/user/tokens/verify")) return { status: 200, body: { result: { id: me.id, status: "active" } } };
const id = url.pathname.split("/").pop()!;
if (m === "GET") return tokens.has(id) ? { status: 200, body: { result: tokens.get(id) } } : { status: 404 };
if (m === "POST") {
created = body;
tokens.set("t-new", { id: "t-new", value: "cf_new_yyyyyyyyyyyyyy", ...body });
return { status: 200, body: { result: { id: "t-new", value: "cf_new_yyyyyyyyyyyyyy" } } };
}
if (m === "DELETE") {
tokens.delete(id);
return { status: 200, body: { result: { id } } };
}
return { status: 404 };
});
const c = ctx({ key: "CLOUDFLARE_API_TOKEN", oldValue: "cf_old_xxxxxxxxxxxxxx", fetch });
expect(await cloudflareTokenRotator.preflight(c)).toBeNull();
const minted = await cloudflareTokenRotator.mint(c);
expect(created.policies[0].permission_groups).toEqual([{ id: "g1" }]);
expect(created.name).toBe("dns edit (rotated 2026-10-29)");
expect(tokens.has("t-old")).toBe(true);
await minted.revokeOld();
expect(tokens.has("t-old")).toBe(false);
expect(tokens.has("t-new")).toBe(true);
});
it("refuses a token it cannot verify", async () => {
const { fetch } = fakeFetch(() => ({ status: 401, body: {} }));
expect(await cloudflareTokenRotator.preflight(ctx({ fetch }))).toMatch(/not a live user API token/);
});
});
describe("coinpay", () => {
const legacy = "cp_live_legacyAAAAAAAAAAAAAAAA";
function coinpay() {
const state = { legacy, scoped: new Map<string, any>(), regenerated: 0, webhook: "whsec_old_xxxxxxxxxxxx" };
const { fetch, calls } = fakeFetch((m, url, auth, body) => {
const p = url.pathname;
if (p === "/api/auth/login") return body.password === "pw" ? { status: 200, body: { success: true, token: "session-jwt" } } : { status: 401 };
if (p === "/api/businesses" && m === "GET") {
const ok = auth === state.legacy || [...state.scoped.values()].some((k) => k.raw === auth && !k.revoked_at) || auth === "session-jwt";
return ok ? { status: 200, body: { success: true, businesses: [{ id: "b1", api_key: state.legacy, webhook_secret: state.webhook }] } } : { status: 401 };
}
if (auth !== "session-jwt") return { status: 401 };
if (p === "/api/businesses/b1/api-keys" && m === "POST") {
const id = `k${state.scoped.size + 1}`;
state.scoped.set(id, { id, raw: `cp_live_scoped${id}BBBBBBBBBB`, scopes: body.scopes, prefix: `cp_live_scoped${id}`.slice(0, 16) });
return { status: 201, body: { success: true, apiKey: state.scoped.get(id).raw, key: { id } } };
}
if (p === "/api/businesses/b1/api-keys" && m === "GET") return { status: 200, body: { keys: [...state.scoped.values()].map(({ raw: _r, ...k }) => k) } };
if (p.startsWith("/api/businesses/b1/api-keys/") && m === "DELETE") {
const k = state.scoped.get(p.split("/").pop()!);
if (!k) return { status: 404 };
k.revoked_at = "now";
return { status: 200, body: { success: true } };
}
if (p === "/api/businesses/b1/api-key" && m === "POST") {
state.legacy = `cp_live_regen${++state.regenerated}`;
return { status: 200, body: { success: true, apiKey: state.legacy } };
}
if (p === "/api/businesses/b1/webhook-secret" && m === "POST") {
state.webhook = "whsec_new_yyyyyyyyyyyy";
return { status: 200, body: { success: true, secret: state.webhook } };
}
return { status: 404 };
});
return { state, fetch, calls };
}
const env = { COINPAY_ROTATE_URL: "https://coinpay.test", COINPAY_ROTATE_EMAIL: "o@x", COINPAY_ROTATE_PASSWORD: "pw" };
it("legacy key: mints a wildcard scoped key, old key still works until revokeOld regenerates the legacy slot", async () => {
const { state, fetch } = coinpay();
const c = ctx({ key: "COINPAY_API_KEY", oldValue: legacy, fetch, env });
expect(await coinpayApiKeyRotator.preflight(c)).toBeNull();
const minted = await coinpayApiKeyRotator.mint(c);
expect(minted.value).toBe("cp_live_scopedk1BBBBBBBBBB");
expect(state.scoped.get("k1").scopes).toEqual(["*"]);
expect(state.legacy).toBe(legacy);
await minted.revokeOld();
expect(state.legacy).not.toBe(legacy);
expect(minted.state).toEqual({ businessId: "b1", keyId: "k1" });
});
it("scoped key: the next rotation keeps its scopes and deletes it; rollback revokes the new key", async () => {
const { state, fetch } = coinpay();
const first = await coinpayApiKeyRotator.mint(ctx({ key: "COINPAY_API_KEY", oldValue: legacy, fetch, env }));
const second = await coinpayApiKeyRotator.mint(ctx({ key: "COINPAY_API_KEY", oldValue: first.value, fetch, env }));
expect(state.scoped.get("k2").scopes).toEqual(["*"]);
await second.revokeOld();
expect(state.scoped.get("k1").revoked_at).toBe("now");
await second.rollback();
expect(state.scoped.get("k2").revoked_at).toBe("now");
});
it("refuses to run without a merchant session", async () => {
expect(await coinpayApiKeyRotator.preflight(ctx({ env: {} }))).toMatch(/COINPAY_ROTATE_TOKEN/);
});
it("webhook secret: finds the business by its secret and regenerates it (no overlap)", async () => {
const { state, fetch } = coinpay();
expect(coinpayWebhookSecretRotator.overlap).toBe(false);
const c = ctx({ key: "COINPAY_WEBHOOK_SECRET", oldValue: "whsec_old_xxxxxxxxxxxx", vaultValues: { COINPAY_API_KEY: legacy }, fetch, env });
expect(await coinpayWebhookSecretRotator.preflight(c)).toBeNull();
const minted = await coinpayWebhookSecretRotator.mint(c);
expect(minted.value).toBe("whsec_new_yyyyyyyyyyyy");
expect(state.webhook).toBe(minted.value);
expect(await minted.rollback()).toMatch(/cannot restore/);
});
});
describe("vapid", () => {
it("makes a valid P-256 pair and writes the public half to every VAPID public companion", async () => {
const pair = newVapidPair();
expect(Buffer.from(pair.publicKey, "base64url")).toHaveLength(65);
expect(Buffer.from(pair.privateKey, "base64url")).toHaveLength(32);
const c = ctx({ key: "VAPID_PRIVATE_KEY", vaultValues: { VAPID_PRIVATE_KEY: "x", VAPID_PUBLIC_KEY: "y", NEXT_PUBLIC_VAPID_PUBLIC_KEY: "y" } });
expect(await vapidRotator.preflight(c)).toBeNull();
const minted = await vapidRotator.mint(c);
expect(Object.keys(minted.companions!)).toEqual(["VAPID_PUBLIC_KEY", "NEXT_PUBLIC_VAPID_PUBLIC_KEY"]);
expect(await vapidRotator.preflight(ctx({ vaultValues: { VAPID_PRIVATE_KEY: "x" } }))).toMatch(/no VAPID public key/);
});
});
describe("postgres-role", () => {
it("SCRAM verifier matches the RFC 7677 construction", () => {
const salt = Buffer.from("0123456789abcdef");
const v = scramVerifier("pencil", salt, 4096);
const salted = pbkdf2Sync("pencil", salt, 4096, 32, "sha256");
const stored = createHash("sha256").update(createHmac("sha256", salted).update("Client Key").digest()).digest("base64");
expect(v).toBe(`SCRAM-SHA-256$4096:${salt.toString("base64")}$${stored}:${createHmac("sha256", salted).update("Server Key").digest("base64")}`);
});
it("alters its own role over stdin (never argv), rewrites URLs, rolls back to the old password", async () => {
const runs: Array<{ args: string[]; input?: string; env?: Record<string, string> }> = [];
const old = "oldpassword123456";
const c = ctx({
key: "POSTGRES_PASSWORD",
oldValue: old,
vaultValues: { POSTGRES_PASSWORD: old, DATABASE_URL: `postgres://app:${old}@db.local:5432/app` },
run: (_cmd, args, opts) => {
runs.push({ args, ...opts });
return { status: 0, stdout: "", stderr: "" };
}
});
expect(await postgresRoleRotator.preflight(c)).toBeNull();
const minted = await postgresRoleRotator.mint(c);
expect(runs[0]!.args.join(" ")).not.toContain(old);
expect(runs[0]!.args.join(" ")).not.toContain(minted.value);
expect(runs[0]!.input).toMatch(/^ALTER ROLE CURRENT_USER PASSWORD 'SCRAM-SHA-256\$/);
expect(runs[0]!.input).not.toContain(minted.value);
expect(runs[0]!.env!.PGPASSWORD).toBe(old);
expect(minted.companions!.DATABASE_URL).toBe(`postgres://app:${minted.value}@db.local:5432/app`);
await minted.rollback();
expect(runs[1]!.env!.PGPASSWORD).toBe(minted.value);
});
it("refuses self-hosted Supabase passwords", async () => {
expect(await postgresRoleRotator.preflight(ctx({ key: "SUPABASE_DB_PASSWORD" }))).toMatch(/Supabase/);
});
it("rewriteUrls only touches URLs holding the old password", () => {
expect(rewriteUrls({ A: "postgres://u:old@h/d", B: "postgres://u:other@h/d", C: "plain" }, "old", "n w")).toEqual({ A: "postgres://u:n%20w@h/d" });
});
});

View file

@ -0,0 +1,476 @@
import { createHash, createHmac, generateKeyPairSync, pbkdf2Sync, randomBytes } from "node:crypto";
import { spawnSync } from "node:child_process";
import { generateRandomSecret } from "./rotation-catalog.js";
/**
* Built-in rotators for `method: "provider"`. Each one is two-phase:
*
* mint() create the new credential at the provider; the old one stays live
* (caller) write it to every vault holding the old value, redeploy the
* consumers, health-check them
* revokeOld() only now kill the old credential
* rollback() on any failure before revokeOld: undo mint, so the old value
* (still in the vaults' history and in the consumers) keeps working
*
* `overlap` says whether old and new really are valid at the same time. When
* the provider has a single slot (a CoinPay webhook secret, a Postgres role
* password) it is false: the caller still rolls back, but consumers see a short
* window of failures, so the weekly job leaves those to a person.
*
* Nothing here prints or logs a secret value; errors carry provider status
* codes and messages only.
*/
export interface RotatorContext {
key: string;
oldValue: string;
/** Decrypted values of the first vault holding the key, by name (companions: public halves, DB URLs). */
vaultValues: Record<string, string>;
/** Rotator bookkeeping saved after the last rotation (provider key ids). */
state: Record<string, string>;
/** Admin credentials for rotators that need them (CLOUDFLARE_ADMIN_API_TOKEN, ...). */
env: Record<string, string | undefined>;
fetch: typeof fetch;
/** Runs a process with stdin; secrets travel on stdin or env, never argv. */
run?: (cmd: string, args: string[], opts: { input?: string; env?: Record<string, string> }) => { status: number | null; stdout: string; stderr: string };
now: Date;
}
export interface Minted {
value: string;
/** Extra values written beside it in the same vaults (by key name): the VAPID public key, rewritten DB URLs. */
companions?: Record<string, string>;
/** Saved to the key's __ROTATE__ entry so the next rotation can revoke this credential by id. */
state?: Record<string, string>;
/** Kill the old credential. Returns a note when it has to be done by hand. */
revokeOld(): Promise<string | undefined>;
/** Undo mint (delete the new credential / restore the old password). */
rollback(): Promise<string | undefined>;
}
export interface ProviderRotator {
id: string;
title: string;
overlap: boolean;
/** null when it can run; otherwise why not (missing admin credential, wrong key type). */
preflight(ctx: RotatorContext): Promise<string | null>;
mint(ctx: RotatorContext): Promise<Minted>;
}
export class RotatorError extends Error {}
const day = (d: Date) => d.toISOString().slice(0, 10);
async function call(ctx: RotatorContext, url: string, init: RequestInit & { token: string }): Promise<{ status: number; body: any }> {
const { token, headers, ...rest } = init;
const res = await ctx.fetch(url, {
...rest,
headers: { authorization: `Bearer ${token}`, "content-type": "application/json", accept: "application/json", ...(headers as Record<string, string> | undefined) }
});
const text = await res.text();
let body: any = null;
try {
body = text ? JSON.parse(text) : null;
} catch {
body = { raw: text.slice(0, 200) };
}
return { status: res.status, body };
}
function fail(what: string, r: { status: number; body: any }): never {
const msg = r.body?.message ?? r.body?.error ?? r.body?.errors?.[0]?.message ?? r.body?.raw ?? "";
throw new RotatorError(`${what}: HTTP ${r.status}${msg ? ` ${String(msg).slice(0, 160)}` : ""}`);
}
// ---- Resend -------------------------------------------------------------------------------
const RESEND = "https://api.resend.com";
/**
* Resend: POST /api-keys mints, DELETE /api-keys/:id revokes; both need a
* full-access key. The old key itself is used when it has full access,
* otherwise RESEND_ADMIN_API_KEY. Resend never shows which id a token is, so
* the old key is revoked by the id saved at the previous rotation; the first
* time round that id is unknown and revoking is a one-line manual step.
*/
export const resendRotator: ProviderRotator = {
id: "resend",
title: "Resend API key",
overlap: true,
async preflight(ctx) {
const token = adminFor(ctx);
const r = await call(ctx, `${RESEND}/api-keys`, { method: "GET", token });
if (r.status === 200) return null;
if (!ctx.env.RESEND_ADMIN_API_KEY) return `this key cannot manage API keys (HTTP ${r.status}); set RESEND_ADMIN_API_KEY to a full-access key`;
return `RESEND_ADMIN_API_KEY cannot manage API keys (HTTP ${r.status})`;
},
async mint(ctx) {
const token = adminFor(ctx);
// A full-access old key gets a full-access successor; anything else gets sending only.
const own = await call(ctx, `${RESEND}/api-keys`, { method: "GET", token: ctx.oldValue });
const permission = own.status === 200 ? "full_access" : "sending_access";
const name = `logicsrc ${ctx.key.toLowerCase()} ${day(ctx.now)}`;
const r = await call(ctx, `${RESEND}/api-keys`, { method: "POST", token, body: JSON.stringify({ name, permission }) });
if (r.status !== 200 && r.status !== 201) fail("Resend create key", r);
const id = String(r.body?.id ?? "");
const value = String(r.body?.token ?? "");
if (!id || !value) throw new RotatorError("Resend create key: response had no id/token");
const oldId = ctx.state.keyId;
return {
value,
state: { keyId: id },
async revokeOld() {
if (!oldId) return `Resend does not say which key id the old token is: delete the previous key in ${"https://resend.com/api-keys"} (keep "${name}").`;
const d = await call(ctx, `${RESEND}/api-keys/${oldId}`, { method: "DELETE", token: value });
if (d.status !== 200 && d.status !== 204 && d.status !== 404) fail("Resend delete old key", d);
return undefined;
},
async rollback() {
const d = await call(ctx, `${RESEND}/api-keys/${id}`, { method: "DELETE", token });
return d.status < 300 || d.status === 404 ? undefined : `delete the new Resend key "${name}" by hand (HTTP ${d.status})`;
}
};
}
};
function adminFor(ctx: RotatorContext): string {
return ctx.env.RESEND_ADMIN_API_KEY || ctx.oldValue;
}
// ---- Cloudflare ---------------------------------------------------------------------------
const CF = "https://api.cloudflare.com/client/v4";
/**
* Cloudflare user API tokens: /user/tokens/verify names the token id, the
* token's policies are copied into a new token, and the old one is deleted
* after the consumers are healthy. Reading and creating tokens needs "API
* Tokens Write": CLOUDFLARE_ADMIN_API_TOKEN, or the token itself if it has it.
*/
export const cloudflareTokenRotator: ProviderRotator = {
id: "cloudflare-token",
title: "Cloudflare API token",
overlap: true,
async preflight(ctx) {
const v = await call(ctx, `${CF}/user/tokens/verify`, { method: "GET", token: ctx.oldValue });
if (v.status !== 200 || !v.body?.result?.id) return `not a live user API token (verify HTTP ${v.status}); account tokens and Global API keys rotate by hand`;
const admin = ctx.env.CLOUDFLARE_ADMIN_API_TOKEN || ctx.oldValue;
const r = await call(ctx, `${CF}/user/tokens/${v.body.result.id}`, { method: "GET", token: admin });
if (r.status !== 200) return `cannot read token policies (HTTP ${r.status}); set CLOUDFLARE_ADMIN_API_TOKEN to a token with "API Tokens Write"`;
return null;
},
async mint(ctx) {
const admin = ctx.env.CLOUDFLARE_ADMIN_API_TOKEN || ctx.oldValue;
const v = await call(ctx, `${CF}/user/tokens/verify`, { method: "GET", token: ctx.oldValue });
const oldId = String(v.body?.result?.id ?? "");
if (!oldId) fail("Cloudflare verify", v);
const cur = await call(ctx, `${CF}/user/tokens/${oldId}`, { method: "GET", token: admin });
if (cur.status !== 200) fail("Cloudflare read token", cur);
const t = cur.body.result;
const policies = (t.policies ?? []).map((p: any) => ({
effect: p.effect,
resources: p.resources,
permission_groups: (p.permission_groups ?? []).map((g: any) => ({ id: g.id }))
}));
const baseName = String(t.name ?? ctx.key).replace(/ \(rotated \d{4}-\d{2}-\d{2}\)$/, "");
const body: Record<string, unknown> = { name: `${baseName} (rotated ${day(ctx.now)})`, policies };
if (t.condition) body.condition = t.condition;
if (t.expires_on) body.expires_on = t.expires_on;
if (t.not_before) body.not_before = t.not_before;
const r = await call(ctx, `${CF}/user/tokens`, { method: "POST", token: admin, body: JSON.stringify(body) });
if (r.status !== 200) fail("Cloudflare create token", r);
const id = String(r.body?.result?.id ?? "");
const value = String(r.body?.result?.value ?? "");
if (!id || !value) throw new RotatorError("Cloudflare create token: no id/value in the response");
return {
value,
state: { tokenId: id },
async revokeOld() {
const d = await call(ctx, `${CF}/user/tokens/${oldId}`, { method: "DELETE", token: admin === ctx.oldValue ? value : admin });
if (d.status !== 200 && d.status !== 404) fail("Cloudflare delete old token", d);
return undefined;
},
async rollback() {
const d = await call(ctx, `${CF}/user/tokens/${id}`, { method: "DELETE", token: admin });
return d.status === 200 || d.status === 404 ? undefined : `delete the new Cloudflare token "${body.name}" by hand (HTTP ${d.status})`;
}
};
}
};
// ---- CoinPay (our own API) ----------------------------------------------------------------
function coinpayBase(ctx: RotatorContext): string {
// COINPAY_API_URL elsewhere in the fleet carries an /api suffix; accept both.
return (ctx.env.COINPAY_ROTATE_URL || ctx.env.COINPAY_API_URL || "https://coinpayportal.com").replace(/\/+$/, "").replace(/\/api$/, "");
}
/** A merchant session: COINPAY_ROTATE_TOKEN, or log in with COINPAY_ROTATE_EMAIL + COINPAY_ROTATE_PASSWORD. */
async function coinpaySession(ctx: RotatorContext): Promise<string | null> {
if (ctx.env.COINPAY_ROTATE_TOKEN) return ctx.env.COINPAY_ROTATE_TOKEN;
if (!ctx.env.COINPAY_ROTATE_EMAIL || !ctx.env.COINPAY_ROTATE_PASSWORD) return null;
const res = await ctx.fetch(`${coinpayBase(ctx)}/api/auth/login`, {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({ email: ctx.env.COINPAY_ROTATE_EMAIL, password: ctx.env.COINPAY_ROTATE_PASSWORD })
});
const body = (await res.json().catch(() => null)) as any;
return res.ok && body?.token ? String(body.token) : null;
}
/** The business that owns a key: GET /api/businesses accepts the key itself and lists the owner's businesses. */
async function coinpayBusiness(ctx: RotatorContext, match: (b: any) => boolean): Promise<any | null> {
const r = await call(ctx, `${coinpayBase(ctx)}/api/businesses`, { method: "GET", token: ctx.oldValue });
if (r.status !== 200) return null;
return (r.body?.businesses ?? []).find(match) ?? null;
}
/**
* CoinPay business API keys. A business has one legacy key (businesses.api_key)
* and any number of scoped keys (business_api_keys, cp_live_ + 8 char prefix).
* Rotation always mints a scoped key with the old key's scopes ("*" for the
* legacy key) so old and new work side by side; revoking the old one means
* DELETE for a scoped key, or regenerating the legacy slot (its new value is
* thrown away unread) for the legacy key.
*/
export const coinpayApiKeyRotator: ProviderRotator = {
id: "coinpay-api-key",
title: "CoinPay business API key",
overlap: true,
async preflight(ctx) {
if (!(await coinpaySession(ctx))) return "needs a CoinPay merchant session: set COINPAY_ROTATE_TOKEN, or COINPAY_ROTATE_EMAIL + COINPAY_ROTATE_PASSWORD (owner of the business)";
return null;
},
async mint(ctx) {
const session = await coinpaySession(ctx);
if (!session) throw new RotatorError("no CoinPay merchant session");
const base = coinpayBase(ctx);
const r = await call(ctx, `${base}/api/businesses`, { method: "GET", token: ctx.oldValue });
if (r.status !== 200) fail("CoinPay: the old key does not authenticate", r);
const businesses: any[] = r.body?.businesses ?? [];
let business = businesses.find((b) => b.api_key === ctx.oldValue) ?? null;
let scoped: any = null;
if (!business) {
const prefix = ctx.oldValue.startsWith("cp_live_") ? ctx.oldValue.slice(0, 16) : "";
for (const b of businesses) {
const k = await call(ctx, `${base}/api/businesses/${b.id}/api-keys`, { method: "GET", token: session });
const hit = (k.body?.keys ?? []).find((x: any) => !x.revoked_at && prefix && x.prefix === prefix);
if (hit) {
business = b;
scoped = hit;
break;
}
}
}
if (!business) throw new RotatorError("CoinPay: no business of this merchant owns the key (wrong COINPAY_ROTATE_* account?)");
const name = `logicsrc ${ctx.key.toLowerCase()} ${day(ctx.now)}`;
const created = await call(ctx, `${base}/api/businesses/${business.id}/api-keys`, {
method: "POST",
token: session,
body: JSON.stringify({ name, scopes: scoped?.scopes?.length ? scoped.scopes : ["*"] })
});
if (created.status !== 201 && created.status !== 200) fail("CoinPay create scoped key", created);
const value = String(created.body?.apiKey ?? "");
const newId = String(created.body?.key?.id ?? "");
if (!value || !newId) throw new RotatorError("CoinPay create scoped key: no key in the response");
return {
value,
state: { businessId: String(business.id), keyId: newId },
async revokeOld() {
const d = scoped
? await call(ctx, `${base}/api/businesses/${business.id}/api-keys/${scoped.id}`, { method: "DELETE", token: session })
: await call(ctx, `${base}/api/businesses/${business.id}/api-key`, { method: "POST", token: session });
if (d.status >= 300 && d.status !== 404) fail("CoinPay revoke old key", d);
return undefined;
},
async rollback() {
const d = await call(ctx, `${base}/api/businesses/${business.id}/api-keys/${newId}`, { method: "DELETE", token: session });
return d.status < 300 || d.status === 404 ? undefined : `revoke the new CoinPay key "${name}" by hand (HTTP ${d.status})`;
}
};
}
};
/**
* CoinPay webhook secret: one per business, regenerated in place, so there is
* no overlap and no way back to the old value. Consumers fail signature
* checks until they restart; CoinPay retries failed deliveries.
*/
export const coinpayWebhookSecretRotator: ProviderRotator = {
id: "coinpay-webhook-secret",
title: "CoinPay webhook secret",
overlap: false,
async preflight(ctx) {
if (!(await coinpaySession(ctx))) return "needs a CoinPay merchant session: set COINPAY_ROTATE_TOKEN, or COINPAY_ROTATE_EMAIL + COINPAY_ROTATE_PASSWORD";
if (!findApiKey(ctx)) return "no CoinPay API key in the same vault to find the business with";
return null;
},
async mint(ctx) {
const session = await coinpaySession(ctx);
const apiKey = findApiKey(ctx);
if (!session || !apiKey) throw new RotatorError("needs a CoinPay merchant session and the vault's CoinPay API key");
const base = coinpayBase(ctx);
const r = await call(ctx, `${base}/api/businesses`, { method: "GET", token: apiKey });
const business = (r.body?.businesses ?? []).find((b: any) => b.webhook_secret === ctx.oldValue);
if (!business) throw new RotatorError("CoinPay: no business has this webhook secret");
const g = await call(ctx, `${base}/api/businesses/${business.id}/webhook-secret`, { method: "POST", token: session });
if (g.status !== 200) fail("CoinPay regenerate webhook secret", g);
const value = String(g.body?.secret ?? "");
if (!value) throw new RotatorError("CoinPay regenerate webhook secret: no secret in the response");
return {
value,
async revokeOld() {
return undefined; // regenerating already killed it
},
async rollback() {
return "CoinPay cannot restore an old webhook secret: the new one is live, so keep it and finish redeploying the consumers";
}
};
}
};
function findApiKey(ctx: RotatorContext): string | undefined {
const name = Object.keys(ctx.vaultValues).find((k) => /^(COINPAY|COINPAYPORTAL)(_[A-Z0-9]+)*_API_KEY$/.test(k) && ctx.vaultValues[k]);
return name ? ctx.vaultValues[name] : undefined;
}
// ---- VAPID (local) ------------------------------------------------------------------------
/** A Web Push VAPID pair: P-256, public as uncompressed point, both base64url. */
export function newVapidPair(): { publicKey: string; privateKey: string } {
const { publicKey, privateKey } = generateKeyPairSync("ec", { namedCurve: "prime256v1" });
const pub = publicKey.export({ format: "jwk" });
const priv = privateKey.export({ format: "jwk" });
const raw = Buffer.concat([Buffer.from([4]), Buffer.from(pub.x!, "base64url"), Buffer.from(pub.y!, "base64url")]);
return { publicKey: raw.toString("base64url"), privateKey: String(priv.d) };
}
export const vapidRotator: ProviderRotator = {
id: "vapid",
title: "Web Push VAPID key pair",
overlap: false,
async preflight(ctx) {
return vapidPublicNames(ctx).length ? null : "no VAPID public key beside the private one: the browser side would not get the new key";
},
async mint(ctx) {
const pair = newVapidPair();
const companions = Object.fromEntries(vapidPublicNames(ctx).map((n) => [n, pair.publicKey]));
return {
value: pair.privateKey,
companions,
async revokeOld() {
return undefined; // nothing to revoke: subscriptions made with the old public key just stop
},
async rollback() {
return undefined; // the caller restores the old pair from the vaults
}
};
}
};
function vapidPublicNames(ctx: RotatorContext): string[] {
return Object.keys(ctx.vaultValues).filter((k) => /VAPID/.test(k) && /PUB/.test(k));
}
// ---- Postgres role password ---------------------------------------------------------------
/** A SCRAM-SHA-256 verifier, so the plaintext password never reaches the server log. */
export function scramVerifier(password: string, salt = randomBytes(16), iterations = 4096): string {
const salted = pbkdf2Sync(password.normalize("NFKC"), salt, iterations, 32, "sha256");
const clientKey = createHmac("sha256", salted).update("Client Key").digest();
const storedKey = createHash("sha256").update(clientKey).digest();
const serverKey = createHmac("sha256", salted).update("Server Key").digest();
return `SCRAM-SHA-256$${iterations}:${salt.toString("base64")}$${storedKey.toString("base64")}:${serverKey.toString("base64")}`;
}
interface PgTarget {
urlKey: string;
url: URL;
}
function pgTargets(ctx: RotatorContext): PgTarget[] {
const out: PgTarget[] = [];
for (const [k, v] of Object.entries(ctx.vaultValues)) {
if (!/^postgres(ql)?:\/\//.test(v)) continue;
try {
const url = new URL(v);
if (decodeURIComponent(url.password) === ctx.oldValue) out.push({ urlKey: k, url });
} catch {
/* not a URL */
}
}
return out;
}
/** Every connection string in the vault holding the old password, rewritten to the new one. */
export function rewriteUrls(values: Record<string, string>, oldPassword: string, newPassword: string): Record<string, string> {
const out: Record<string, string> = {};
for (const [k, v] of Object.entries(values)) {
if (!/^[a-z][a-z0-9+.-]*:\/\//i.test(v)) continue;
try {
const url = new URL(v);
if (url.password && decodeURIComponent(url.password) === oldPassword) {
url.password = encodeURIComponent(newPassword);
out[k] = url.toString();
}
} catch {
/* not a URL */
}
}
return out;
}
/**
* ALTER ROLE CURRENT_USER for the role in the vault's connection string (a
* role may always change its own password). Sends a SCRAM verifier on stdin of
* psql, never the plaintext. Rollback sets the old password back. Self-hosted
* Supabase stacks are refused: the same password is shared by six service roles
* and the stack's own .env, which this rotator does not restart.
*/
export const postgresRoleRotator: ProviderRotator = {
id: "postgres-role",
title: "Postgres role password",
overlap: false,
async preflight(ctx) {
if (/^SUPABASE_/.test(ctx.key) || Object.keys(ctx.vaultValues).some((k) => k === "POSTGRES_PASSWORD" && "JWT_SECRET" in ctx.vaultValues))
return "self-hosted Supabase shares this password with its service roles: follow the runbook (Postgres / Supabase section)";
if (!pgTargets(ctx).length) return "no postgres:// URL with this password in the vault, so the host and role are unknown";
if (!ctx.run) return "no process runner (psql) available";
return null;
},
async mint(ctx) {
const target = pgTargets(ctx)[0];
if (!target || !ctx.run) throw new RotatorError("no postgres target");
const value = generateRandomSecret({ format: "alnum", length: 40 });
const apply = (password: string, current: string): string | undefined => {
const url = new URL(target.url.toString());
url.password = "";
const r = ctx.run!("psql", ["-X", "-q", "-v", "ON_ERROR_STOP=1", url.toString()], {
env: { PGPASSWORD: current, PGCONNECT_TIMEOUT: "10" },
input: `ALTER ROLE CURRENT_USER PASSWORD '${scramVerifier(password)}';\n`
});
return r.status === 0 ? undefined : `psql exited ${r.status}: ${r.stderr.trim().slice(0, 200)}`;
};
const err = apply(value, ctx.oldValue);
if (err) throw new RotatorError(`ALTER ROLE failed: ${err}`);
return {
value,
companions: rewriteUrls(ctx.vaultValues, ctx.oldValue, value),
async revokeOld() {
return undefined; // the old password died with ALTER ROLE
},
async rollback() {
return apply(ctx.oldValue, value);
}
};
}
};
export const ROTATORS: Record<string, ProviderRotator> = Object.fromEntries(
[resendRotator, cloudflareTokenRotator, coinpayApiKeyRotator, coinpayWebhookSecretRotator, vapidRotator, postgresRoleRotator].map((r) => [r.id, r])
);
export function defaultRun(cmd: string, args: string[], opts: { input?: string; env?: Record<string, string> }) {
const r = spawnSync(cmd, args, { input: opts.input, env: { ...process.env, ...opts.env }, encoding: "utf8", timeout: 60_000 });
return { status: r.status, stdout: r.stdout ?? "", stderr: r.stderr ?? (r.error ? String(r.error.message) : "") };
}