feat(teams): rotate secret values, with per-entry rotation instructions (CLI 0.9.0)

`credentials rotate` only re-keys a vault: values stay the same, so it does
nothing after a value leaks. This adds value rotation that agents can run.

- `teams rotation <team> [project] [env]`: per value, the method (random,
  ssh-keygen, command, manual), where the instructions come from, how many
  vaults hold it, and since when. --format json carries the steps for agents.
- `teams rotation-set <team> <project> <env> <KEY>`: store instructions as an
  encrypted `__ROTATE__<KEY>` entry. The team provider hides that prefix
  from sync, so it never lands in a .env and a push never deletes it.
- `teams rotate-keys <team> [project] [env] [--key] [--approve]`: dry run by
  default. random/ssh-keygen/command values are minted and written to EVERY
  vault holding the same value (by fingerprint); manual ones come back as
  steps. `--set-from-stdin` stores a hand-rotated value everywhere the old
  one lives. Values never print.
- Built-in catalog by key name: wallet keys and data-encryption keys are
  never automatic; provider keys point at the provider's dashboard; only
  secrets we mint ourselves are random (META_APP_SECRET etc. are not).
- Empty values (one shared fingerprint) are never planned or overwritten.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Anthony Ettinger 2026-10-28 14:31:15 +00:00
parent ced6c5ac20
commit 31d7375f58
9 changed files with 923 additions and 2 deletions

View file

@ -147,7 +147,7 @@
},
"packages/cli": {
"name": "@logicsrc/cli",
"version": "0.8.0",
"version": "0.9.0",
"bin": {
"logicsrc": "./dist/index.js",
},

View file

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

View file

@ -36,6 +36,7 @@ import {
import { registerKeysCommands } from "./keys.js";
import { sshAgentAction, sshListAction, sshPullAction, sshPushAction } from "./ssh.js";
import { credentialsRotateAction } from "./rotate.js";
import { teamsRotateKeysAction, teamsRotationAction, teamsRotationSetAction } from "./rotate-keys.js";
import { boards, tasks } from "./fixtures.js";
import { print, type OutputFormat } from "./format.js";
import { parsePositiveInteger } from "./numeric-options.js";
@ -741,6 +742,8 @@ Quick start (<team> is e.g. profullstack; see yours with "logicsrc teams list"):
logicsrc teams push <team> <project> <env> ./.env -> vault
logicsrc teams grant <team> <project> <env> dev@example.com
logicsrc teams key your key, to read values in the web app
logicsrc teams rotation <team> how each secret is rotated (agents: --format json)
logicsrc teams rotate-keys <team> [project] [env] rotate values (dry run; --approve to write)
Deploy boxes and CI (a machine API key: one team, scoped vaults, read-only, its own identity):
logicsrc keys create <name> --team <team> --vault <project>--<env> --out deploy.key
@ -873,6 +876,95 @@ Vaults you have no access to are skipped and listed at the end.
teamsExportAction(slug, { project, env, category: options.category, search: options.search }, { out: options.out, yes: options.yes })
);
const collectList = (value: string, previous: string[] = []): string[] => [...previous, ...value.split(",").map((v) => v.trim()).filter(Boolean)];
const collectRepeat = (value: string, previous: string[] = []): string[] => [...previous, value];
teams
.command("rotation")
.argument("<slug>", "Team slug")
.argument("[project]", "Only this project")
.argument("[env]", "Only this environment")
.option("-k, --key <names>", "only these keys (comma-separated or repeated)", collectList)
.option("--format <format>", "table, json, or markdown", "table")
.description("Show how each secret value is rotated: method, instructions, which vaults share it. Never shows values.")
.addHelpText(
"after",
`
Methods: random (we mint it), ssh-keygen (new ed25519 keypair), command (a CLI prints
the new value), manual (steps + url for a person or agent). Instructions come from the
key's own __ROTATE__<KEY> entry, else a built-in catalog by key name.
logicsrc teams rotation profullstack every value in the team
logicsrc teams rotation profullstack b1dz prod --format json steps per key, for agents
`
)
.action((slug, project, env, options) =>
teamsRotationAction(slug, { project, env, keys: options.key }, { format: options.format as OutputFormat })
);
teams
.command("rotation-set")
.argument("<slug>", "Team slug")
.argument("<project>", "Project name")
.argument("<env>", "Environment name")
.argument("<key>", "Secret name the instructions are for")
.option("--method <method>", "random, ssh-keygen, command, or manual")
.option("--json <spec>", "the whole spec as JSON instead of flags")
.option("--format <alphabet>", "random: hex, base64, base64url, alnum (default: like the old value)")
.option("--length <n>", "random: length in characters (default: like the old value, min 32)")
.option("--command <cmd>", "command: shell command that prints the new value on stdout")
.option("--url <url>", "where to rotate it (provider dashboard)")
.option("--step <text>", "one step; repeat for several", collectRepeat)
.option("--consumer <name>", "what reads this value and must be redeployed; repeat", collectRepeat)
.option("--note <text>", "why, shown in the plan")
.option("--output <format>", "table, json, or markdown", "table")
.description("Store rotation instructions with a secret (as __ROTATE__<KEY>, encrypted, never pulled into .env).")
.addHelpText(
"after",
`
Examples:
logicsrc teams rotation-set profullstack infernet prod CRON_SECRET --method random --consumer "dev2 crontab"
logicsrc teams rotation-set profullstack b1dz prod RESEND_API_KEY --method manual \
--url https://resend.com/api-keys --step "Create a key named b1dz-prod" --step "Revoke the old key"
logicsrc teams rotation-set profullstack app prod CF_TOKEN --method command --command "my-cf-mint-token"
`
)
.action((slug, project, env, key, options) =>
teamsRotationSetAction(slug, project, env, key, { ...options, outputFormat: options.output as OutputFormat })
);
teams
.command("rotate-keys")
.argument("<slug>", "Team slug")
.argument("[project]", "Only this project")
.argument("[env]", "Only this environment")
.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("--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(
"after",
`
Dry run first, then apply:
logicsrc teams rotate-keys profullstack plan for the whole team
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
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 }, {
approve: Boolean(options.approve),
setFromStdin: Boolean(options.setFromStdin),
format: options.format as OutputFormat
})
);
teams
.command("key")
.description("Print this machine's identity secret key, to read vault values in the web app.")

View file

@ -0,0 +1,137 @@
import { describe, expect, it } from "vitest";
import {
catalogSpec,
detectFormat,
generateRandomSecret,
isNotSecret,
parseRotationSpec,
planRotations,
rotationEntryName,
ROTATE_PREFIX,
EMPTY_FINGERPRINT,
isoTime
} from "./rotation-catalog.js";
import { newEd25519, specFromOptions } from "./rotate-keys.js";
import { ROTATION_ENTRY_PREFIX } from "@logicsrc/plugin-credential-sharing";
describe("catalog", () => {
it("never automates wallet keys or keys that protect stored data", () => {
for (const k of ["SYSTEM_MNEMONIC_SOL", "SOLANA_PRIVATE_KEY", "EVM_PRIVATE_KEY", "X402_CRAWLER_PRIVATE_KEY", "SETTINGS_ENCRYPTION_KEY", "ENCRYPTION_KEY"]) {
expect(catalogSpec(k)?.method, k).toBe("manual");
}
});
it("mints our own shared secrets automatically", () => {
for (const k of ["CRON_SECRET", "INTERNAL_API_KEY", "NEXTAUTH_SECRET", "INFERNET_ADMIN_TOKEN"]) {
expect(catalogSpec(k)?.method, k).toBe("random");
}
});
it("never mints random values for provider-issued secrets with our-looking names", () => {
for (const k of ["META_APP_SECRET", "GOOGLE_AUTH_SECRET", "FACEBOOK_APP_SECRET"]) expect(catalogSpec(k)?.method, k).toBe("manual");
expect(catalogSpec("REMINDERS_CRON_SECRET")?.method).toBe("random");
expect(catalogSpec("PIT_ADMIN_TOKEN")?.method).toBe("random");
expect(catalogSpec("INFERNET_CLI_SESSION_SECRET")?.method).toBe("random");
});
it("rotates ssh private keys with ssh-keygen, never their public halves or config", () => {
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(isNotSecret("SSH_KNOWN_HOSTS")).toBe(true);
});
it("points provider keys at the provider, with a url", () => {
const stripe = catalogSpec("STRIPE_SECRET_KEY");
expect(stripe?.method).toBe("manual");
expect(stripe?.url).toContain("stripe.com");
expect(catalogSpec("ANTHROPIC_API_KEY")?.url).toContain("anthropic.com");
expect(catalogSpec("SOME_VENDOR_API_KEY")?.method).toBe("manual");
});
it("knows nothing about plain config", () => {
expect(catalogSpec("SOLANA_RPC_URL")).toBeNull();
expect(catalogSpec("NODE_ENV")).toBeNull();
});
});
describe("random secrets", () => {
it("keep the old value's alphabet and length, never shorter than 32", () => {
const hex = "a".repeat(64);
expect(detectFormat(hex)).toBe("hex");
const next = generateRandomSecret({}, hex);
expect(next).toMatch(/^[0-9a-f]{64}$/);
expect(next).not.toBe(hex);
expect(generateRandomSecret({}, "short")).toHaveLength(32);
expect(generateRandomSecret({ format: "alnum", length: 40 })).toMatch(/^[A-Za-z0-9]{40}$/);
expect(generateRandomSecret({ format: "base64url", length: 48 })).toMatch(/^[A-Za-z0-9_-]{48}$/);
});
});
describe("specs", () => {
it("validate what agents will follow", () => {
expect(parseRotationSpec('{"method":"manual","steps":["a",""," ","b"]}').steps).toEqual(["a", "b"]);
expect(() => parseRotationSpec('{"method":"delete-everything"}')).toThrow(/method/);
expect(() => parseRotationSpec('{"method":"command"}')).toThrow(/command/);
expect(() => parseRotationSpec('{"method":"random","length":4}')).toThrow(/length/);
expect(() => parseRotationSpec("not json")).toThrow(/JSON/);
});
it("can be built from CLI flags", () => {
const spec = specFromOptions({ method: "manual", url: "https://x.test", step: ["one", "two"], consumer: ["dev2"], outputFormat: "json" });
expect(spec).toMatchObject({ method: "manual", url: "https://x.test", steps: ["one", "two"], consumers: ["dev2"] });
});
it("are stored under the prefix the team provider hides from .env sync", () => {
expect(ROTATE_PREFIX).toBe(ROTATION_ENTRY_PREFIX);
expect(rotationEntryName("CRON_SECRET")).toBe("__ROTATE__CRON_SECRET");
});
});
describe("planRotations", () => {
const row = (vault: string, key: string, fingerprint: string, updatedAt = "2026-10-01") => ({ vault, key, fingerprint, updatedAt });
it("rotates one value once, however many vaults hold it", () => {
const plan = planRotations(
[row("a--prod", "ANTHROPIC_API_KEY", "f1"), row("b--prod", "ANTHROPIC_API_KEY", "f1", "2026-09-01"), row("c--prod", "ANTHROPIC_API_KEY", "f2")],
new Map()
);
expect(plan).toHaveLength(2);
expect(plan[0]).toMatchObject({ vaults: ["a--prod", "b--prod"], oldestUpdate: "2026-09-01", source: "catalog" });
});
it("prefers the entry's own instructions, and never plans rotation entries or public keys", () => {
const plan = planRotations(
[row("a--prod", "CRON_SECRET", "f1"), row("a--prod", "__ROTATE__CRON_SECRET", "f9"), row("a--prod", "SSH_ID_ED25519_PUB", "f8")],
new Map([["a--prod\u0000CRON_SECRET", { method: "command" as const, command: "mint" }]])
);
expect(plan.map((p) => p.key)).toEqual(["CRON_SECRET"]);
expect(plan[0]).toMatchObject({ method: "command", source: "entry", automatic: true });
});
it("never plans or propagates empty values, which all share one fingerprint", () => {
const plan = planRotations([row("a--prod", "SHOPIFY_ACCESS_TOKEN", EMPTY_FINGERPRINT), row("b--prod", "OPENAI_API_KEY", EMPTY_FINGERPRINT)], new Map());
expect(plan).toEqual([]);
});
it("treats trading knobs named *_SEED_* as config, not wallet seeds", () => {
expect(planRotations([row("a--prod", "ARB_AUTO_SEED_MIN_USD", "f1")], new Map())).toEqual([]);
expect(isoTime(1785867760)).toMatch(/^2026-/);
});
it("flags secret-looking keys nobody wrote instructions for, and skips plain config", () => {
const plan = planRotations([row("a--prod", "MYSTERY_SIGNING_THING", "f1"), row("a--prod", "SNIPE_MODE", "f2"), row("a--prod", "V2_SIZE_USD", "f3")], new Map());
expect(plan.map((p) => p.key)).toEqual(["MYSTERY_SIGNING_THING"]);
expect(plan[0]).toMatchObject({ method: "unknown", source: "none", automatic: false });
});
});
describe("newEd25519", () => {
it("returns an OpenSSH keypair and leaves no files behind", () => {
const pair = newEd25519("test");
expect(pair.privateKey).toContain("BEGIN OPENSSH PRIVATE KEY");
expect(pair.publicKey).toMatch(/^ssh-ed25519 \S+ test$/);
});
});

View file

@ -0,0 +1,389 @@
import { spawnSync } from "node:child_process";
import { mkdtempSync, readFileSync, rmSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import {
decodeSshFile,
decryptValue,
encodeSshFile,
encryptValue,
fingerprintValue,
secretNameForPath,
unwrapVaultKey,
type RemoteSecret,
type TeamClient
} from "@logicsrc/plugin-credential-sharing";
import { print, printColumns, type OutputFormat } from "./format.js";
import { authedClient, splitVaultName, vaultName } from "./teams.js";
import {
EMPTY_FINGERPRINT,
generateRandomSecret,
isRotationEntry,
parseRotationSpec,
planRotations,
rotationEntryName,
type PlannedRotation,
type RotationSpec
} from "./rotation-catalog.js";
/**
* `logicsrc teams rotation` what rotating each secret takes (never values)
* `logicsrc teams rotation-set` store per-entry rotation instructions
* `logicsrc teams rotate-keys` rotate secret VALUES (dry run unless --approve)
*
* A value is identified by its fingerprint, so one rotation is written to every
* vault holding the same value, whatever the key is called there: a key pasted
* into fourteen vaults is rotated once, not left stale in thirteen.
*/
export interface RotationFilter {
project?: string;
env?: string;
keys?: string[];
}
interface VaultState {
id: string;
name: string;
project: string;
env: string;
secrets: RemoteSecret[];
dek?: string;
}
interface Loaded {
client: TeamClient;
/** Every vault in the team this identity can open. */
vaults: VaultState[];
/** Vaults we cannot decrypt: values there cannot be rotated by us. */
locked: string[];
dek(v: VaultState): Promise<string>;
}
async function loadTeam(slug: string): Promise<Loaded> {
const { client, identity } = authedClient();
const { vaults } = await client.listVaults(slug);
const locked: string[] = [];
const states: VaultState[] = [];
for (const v of vaults) {
if (!v.hasAccess) {
locked.push(v.name);
continue;
}
const parts = splitVaultName(v.name);
const { secrets } = await client.listSecrets(v.id);
states.push({ id: v.id, name: v.name, project: parts?.project ?? v.name, env: parts?.env ?? "", secrets });
}
return {
client,
vaults: states,
locked,
async dek(v) {
v.dek ??= await unwrapVaultKey((await client.getMyGrant(v.id)).wrappedDek, identity.keys);
return v.dek;
}
};
}
function inFilter(v: VaultState, filter: RotationFilter): boolean {
return (!filter.project || v.project === filter.project) && (!filter.env || v.env === filter.env);
}
async function readValue(team: Loaded, v: VaultState, name: string): Promise<string> {
const s = v.secrets.find((x) => x.name === name);
if (!s) throw new Error(`${name} is not in ${v.name}`);
return decryptValue({ nonce: s.nonce, ciphertext: s.ciphertext }, await team.dek(v));
}
/** Per-entry specs from `__ROTATE__<KEY>` entries, keyed by vault + key. */
async function readEntrySpecs(team: Loaded): Promise<{ specs: Map<string, RotationSpec>; invalid: string[] }> {
const specs = new Map<string, RotationSpec>();
const invalid: string[] = [];
for (const v of team.vaults) {
for (const s of v.secrets.filter((x) => isRotationEntry(x.name))) {
const key = s.name.slice(rotationEntryName("").length);
try {
specs.set(`${v.name}\u0000${key}`, parseRotationSpec(await readValue(team, v, s.name)));
} catch (err) {
invalid.push(`${v.name}/${s.name}: ${(err as Error).message}`);
}
}
}
return { specs, invalid };
}
async function buildPlan(slug: string, filter: RotationFilter): Promise<{ team: Loaded; plan: PlannedRotation[]; invalid: string[] }> {
const team = await loadTeam(slug);
const { specs, invalid } = await readEntrySpecs(team);
const rows = team.vaults
.filter((v) => inFilter(v, filter))
.flatMap((v) => v.secrets.map((s) => ({ vault: v.name, key: s.name, fingerprint: s.fingerprint, updatedAt: s.updatedAt })));
if (rows.length === 0) throw new Error(`No secrets match ${[slug, filter.project, filter.env].filter(Boolean).join("/")}.`);
const wanted = filter.keys?.length ? new Set(filter.keys.map((k) => k.toUpperCase())) : null;
const plan = planRotations(rows, specs).filter((p) => !wanted || wanted.has(p.key.toUpperCase()));
return { team, plan, invalid };
}
/** Every (vault, key) in the team holding this exact value, inside the filter or not. */
function siblings(team: Loaded, fingerprint: string): Array<{ vault: VaultState; key: string }> {
if (fingerprint === EMPTY_FINGERPRINT) return [];
return team.vaults.flatMap((v) =>
v.secrets.filter((s) => s.fingerprint === fingerprint && !isRotationEntry(s.name)).map((s) => ({ vault: v, key: s.name }))
);
}
// ---- plan ------------------------------------------------------------------
export async function teamsRotationAction(slug: string, filter: RotationFilter, options: { format: OutputFormat }): Promise<void> {
const { team, plan, invalid } = await buildPlan(slug, filter);
for (const p of plan) {
const elsewhere = siblings(team, p.fingerprint).filter((s) => !p.vaults.includes(s.vault.name) || s.key !== p.key);
(p as PlannedRotation & { alsoIn?: string[] }).alsoIn = elsewhere.map((s) => `${s.vault.name}:${s.key}`);
}
if (options.format === "table") {
printColumns(
plan.map((p) => ({
key: p.key,
method: p.method,
auto: p.automatic ? "yes" : "no",
source: p.source,
vaults: p.vaults.length + ((p as { alsoIn?: string[] }).alsoIn?.length ?? 0),
since: String(p.oldestUpdate).slice(0, 10),
note: p.spec?.note ?? (p.source === "none" ? "no instructions: logicsrc teams rotation-set" : "")
}))
);
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.`);
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);
}
if (invalid.length) console.error(`Unreadable rotation entries (ignored): ${invalid.join("; ")}`);
if (team.locked.length) console.error(`Vaults you cannot decrypt (not covered): ${team.locked.join(", ")}`);
}
// ---- set -------------------------------------------------------------------
export interface RotationSetOptions {
method?: string;
json?: string;
format?: string;
length?: string;
command?: string;
url?: string;
step?: string[];
consumer?: string[];
note?: string;
outputFormat: OutputFormat;
}
export function specFromOptions(options: RotationSetOptions): RotationSpec {
if (options.json) return parseRotationSpec(options.json);
if (!options.method) throw new Error("Give --method (random, ssh-keygen, command, manual) or --json '<spec>'.");
return parseRotationSpec(
JSON.stringify({
method: options.method,
format: options.format,
length: options.length ? Number(options.length) : undefined,
command: options.command,
url: options.url,
steps: options.step,
consumers: options.consumer,
note: options.note
})
);
}
export async function teamsRotationSetAction(slug: string, project: string, env: string, key: string, options: RotationSetOptions): Promise<void> {
const spec = specFromOptions(options);
const team = await loadTeam(slug);
const name = vaultName(project, env);
const v = team.vaults.find((x) => x.name === name);
if (!v) throw new Error(`Vault ${slug}/${name} not found, or you have no access.`);
if (!v.secrets.some((s) => s.name === key)) console.error(`Note: ${key} is not in ${name} yet; the instructions are stored anyway.`);
const entry = rotationEntryName(key);
const value = JSON.stringify(spec);
const sealed = await encryptValue(value, await team.dek(v));
await team.client.putSecrets(v.id, [{ name: entry, ...sealed, fingerprint: fingerprintValue(value) }], []);
console.error(`Stored rotation instructions for ${key} in ${slug}/${name} (${entry}).`);
print({ team: slug, vault: name, key, entry, spec }, options.outputFormat);
}
// ---- rotate ----------------------------------------------------------------
export interface RotateKeysOptions {
approve: boolean;
setFromStdin?: boolean;
format: OutputFormat;
}
interface KeyPair {
privateKey: string;
publicKey: string;
}
/** A fresh passphrase-less ed25519 key via ssh-keygen; the temp dir is removed either way. */
export function newEd25519(comment: string): KeyPair {
const dir = mkdtempSync(join(tmpdir(), "logicsrc-rotate-"));
try {
const file = join(dir, "key");
const run = spawnSync("ssh-keygen", ["-q", "-t", "ed25519", "-N", "", "-C", comment, "-f", file], { stdio: ["ignore", "ignore", "pipe"] });
if (run.status !== 0) throw new Error(`ssh-keygen failed: ${run.stderr?.toString().trim() || run.error?.message || run.status}`);
return { privateKey: readFileSync(file, "utf8"), publicKey: readFileSync(`${file}.pub`, "utf8").trim() };
} finally {
rmSync(dir, { recursive: true, force: true });
}
}
function runCommand(command: string, key: string): string {
const run = spawnSync("sh", ["-c", command], {
env: { ...process.env, LOGICSRC_ROTATE_KEY: key },
stdio: ["ignore", "pipe", "pipe"],
timeout: 120_000,
maxBuffer: 1 << 20
});
if (run.status !== 0) throw new Error(`rotation command failed (${run.status ?? run.signal}): ${run.stderr?.toString().trim().slice(0, 300)}`);
const value = run.stdout.toString().trim();
if (!value) throw new Error("rotation command printed nothing");
return value;
}
interface Replacement {
/** New value per target secret name (ssh envelopes keep their own path). */
valueFor(key: string, oldValue: string): string;
publicKey?: string;
}
async function makeReplacement(p: PlannedRotation, oldValue: string, stdinValue?: string): Promise<Replacement> {
if (stdinValue !== undefined) return { valueFor: () => stdinValue };
const spec = p.spec!;
switch (spec.method) {
case "random": {
const value = generateRandomSecret(spec, oldValue);
return { valueFor: () => value };
}
case "command": {
const value = runCommand(spec.command!, p.key);
return { valueFor: () => value };
}
case "ssh-keygen": {
const pair = newEd25519(`logicsrc-rotated-${p.key.toLowerCase()}-${new Date().toISOString().slice(0, 10)}`);
return {
publicKey: pair.publicKey,
valueFor(key, old) {
// ssh-provider envelopes keep path and mode; raw values become the key text.
try {
const file = decodeSshFile(key, old);
return encodeSshFile({ ...file, body: pair.privateKey });
} catch {
return pair.privateKey;
}
}
};
}
default:
throw new Error(`${p.key} is ${spec.method}: not automatic`);
}
}
export interface RotationResult {
key: string;
method: string;
status: "rotated" | "would-rotate" | "todo" | "failed" | "covered";
/** Every vault:key holding the old value. */
vaults?: string[];
written: string[];
publicKey?: string;
steps?: string[];
url?: string;
consumers?: string[];
error?: string;
}
async function readStdin(): Promise<string> {
const chunks: Buffer[] = [];
for await (const c of process.stdin) chunks.push(c as Buffer);
return Buffer.concat(chunks).toString("utf8").replace(/\r?\n$/, "");
}
export async function teamsRotateKeysAction(slug: string, filter: RotationFilter, options: RotateKeysOptions): Promise<void> {
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);
let stdinValue: string | undefined;
if (options.setFromStdin) {
if (plan.length !== 1) throw new Error("--set-from-stdin needs exactly one value: narrow it with --key (and project/env).");
stdinValue = await readStdin();
if (!stdinValue) throw new Error("stdin was empty");
}
const results: RotationResult[] = [];
// One value stored under two names is one rotation, not two.
const handled = new Map<string, string>();
for (const p of plan) {
const earlier = handled.get(p.fingerprint);
if (earlier && (p.automatic || stdinValue !== undefined)) {
results.push({ key: p.key, method: p.method, status: "covered", written: [], error: `same value as ${earlier}` });
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 targets = siblings(team, p.fingerprint);
const where = 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."] });
continue;
}
if (!options.approve) {
results.push({ ...base, status: "would-rotate", vaults: where, written: [] });
continue;
}
try {
const first = targets[0]!;
const oldValue = await readValue(team, first.vault, first.key);
const replacement = await makeReplacement(p, oldValue, stdinValue);
const written: string[] = [];
for (const vault of [...new Set(targets.map((t) => t.vault))]) {
const upserts = [];
for (const t of targets.filter((x) => x.vault === vault)) {
const old = t === first ? oldValue : await readValue(team, vault, t.key);
const value = replacement.valueFor(t.key, old);
upserts.push({ name: t.key, ...(await encryptValue(value, await team.dek(vault))), fingerprint: fingerprintValue(value) });
// The ssh provider keeps the public half beside the private key.
if (replacement.publicKey) {
let pubName: string | undefined;
try {
pubName = secretNameForPath(`${decodeSshFile(t.key, old).path}.pub`);
} catch {
pubName = undefined;
}
const pub = pubName && vault.secrets.find((s) => s.name === pubName);
if (pub) {
const pubFile = decodeSshFile(pub.name, await readValue(team, vault, pub.name));
const pubValue = encodeSshFile({ ...pubFile, body: `${replacement.publicKey}\n` });
upserts.push({ name: pub.name, ...(await encryptValue(pubValue, await team.dek(vault))), fingerprint: fingerprintValue(pubValue) });
}
}
}
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 });
} catch (err) {
results.push({ ...base, status: "failed", written: [], error: (err as Error).message });
}
}
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 ?? "" })));
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 {
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;
}

View file

@ -0,0 +1,295 @@
import { randomBytes, randomInt } from "node:crypto";
import { ROTATION_ENTRY_PREFIX, fingerprintValue } from "@logicsrc/plugin-credential-sharing";
/** Every empty value shares this fingerprint; an empty value is nothing to rotate. */
export const EMPTY_FINGERPRINT = fingerprintValue("");
/** Server timestamps arrive as ISO strings or epoch seconds; normalise to ISO. */
export function isoTime(value: unknown): string {
if (typeof value === "number") return new Date(value < 1e12 ? value * 1000 : value).toISOString();
if (typeof value === "string" && /^\d+$/.test(value)) return isoTime(Number(value));
return String(value ?? "");
}
/**
* How to rotate a secret's VALUE (not the vault key: that is `credentials
* rotate`). Every vault entry can carry its own instructions in a companion
* entry `__ROTATE__<KEY>` (JSON, encrypted like any other value), so an agent
* that can read the vault can also rotate what is in it. Entries without one
* fall back to the built-in catalog below, matched on the key name.
*
* Methods:
* random we mint the new value ourselves (shared secrets we invented:
* cron tokens, session secrets). Safe to automate.
* ssh-keygen new ed25519 keypair; the private key goes in the vault, the
* 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.
* manual a person or agent follows `steps` at `url`. Never automatic:
* provider-issued keys, wallet seeds, encryption keys that
* protect stored data.
*/
export type RotationMethod = "random" | "ssh-keygen" | "command" | "manual";
export type RandomFormat = "hex" | "base64" | "base64url" | "alnum";
export interface RotationSpec {
method: RotationMethod;
/** random: alphabet; defaults to the old value's shape. */
format?: RandomFormat;
/** random: length in characters; defaults to the old value's length (min 32). */
length?: number;
/** command: prints the new value on stdout. */
command?: string;
/** Where to do it (provider dashboard, docs). */
url?: string;
/** What to do, in order. For manual rotations this is the whole job. */
steps?: string[];
/** What reads this value and needs a restart/redeploy after it changes. */
consumers?: string[];
/** Why this method; shown in the plan. */
note?: string;
}
export const ROTATE_PREFIX = ROTATION_ENTRY_PREFIX;
export function isRotationEntry(name: string): boolean {
return name.startsWith(ROTATE_PREFIX);
}
export function rotationEntryName(key: string): string {
return `${ROTATE_PREFIX}${key}`;
}
const METHODS: readonly RotationMethod[] = ["random", "ssh-keygen", "command", "manual"];
const FORMATS: readonly RandomFormat[] = ["hex", "base64", "base64url", "alnum"];
/** Parse and validate a stored spec. Throws with a message naming the problem. */
export function parseRotationSpec(raw: string): RotationSpec {
let value: unknown;
try {
value = JSON.parse(raw);
} catch {
throw new Error("rotation instructions are not valid JSON");
}
if (!value || typeof value !== "object" || Array.isArray(value)) throw new Error("rotation instructions must be a JSON object");
const v = value as Record<string, unknown>;
if (!METHODS.includes(v.method as RotationMethod)) throw new Error(`method must be one of ${METHODS.join(", ")}`);
if (v.format !== undefined && !FORMATS.includes(v.format as RandomFormat)) throw new Error(`format must be one of ${FORMATS.join(", ")}`);
if (v.length !== undefined && !(Number.isInteger(v.length) && (v.length as number) >= 16 && (v.length as number) <= 512)) {
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");
const strings = (x: unknown): string[] | undefined =>
Array.isArray(x) ? x.filter((s): s is string => typeof s === "string" && s.trim() !== "") : 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.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 } : {})
};
}
const REVOKE = "Revoke the old key once every consumer runs on the new one.";
function provider(name: string, url: string, extra: string[] = []): RotationSpec {
return {
method: "manual",
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]
};
}
interface CatalogRule {
test: RegExp;
spec: RotationSpec;
}
/**
* Order matters: the first match wins, so specific names come before the broad
* suffix rules at the bottom.
*/
const CATALOG: CatalogRule[] = [
// Things whose "rotation" moves money or re-encrypts data: never automatic.
{
test: /(MNEMONIC|SEED_PHRASE|WALLET_PRIVATE_KEY|^(EVM|SOLANA|SOL|ETH|BTC|TRON)_PRIVATE_KEY$|X402_.*PRIVATE_KEY)/,
spec: {
method: "manual",
note: "a wallet key: rotating it means moving funds",
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."
]
}
},
{
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."
]
}
},
{
// 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",
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."
]
}
},
// Secrets we invent and only we check: mint a new random 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."] }
},
// 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."
]
}
},
{ 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", "") }
];
/** 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);
}
/** Built-in instructions for a key name, or null when we know nothing. */
/** Public halves, ssh config and browser-public values: 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);
}
export function catalogSpec(key: string): RotationSpec | null {
const name = key.toUpperCase();
if (isNotSecret(name)) return null;
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;
return spec;
}
/** 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";
if (/^[A-Za-z0-9]+$/.test(value)) return "alnum";
if (/^[A-Za-z0-9_-]+$/.test(value)) return "base64url";
return "base64";
}
const ALNUM = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
/**
* A new random value. Matches the old value's alphabet and length unless the
* spec says otherwise, so a consumer that validates the shape keeps working;
* never shorter than 32 characters.
*/
export function generateRandomSecret(spec: Pick<RotationSpec, "format" | "length">, oldValue = ""): string {
const format = spec.format ?? (oldValue ? detectFormat(oldValue) : "hex");
const length = Math.max(32, spec.length ?? oldValue.length);
switch (format) {
case "hex":
return randomBytes(Math.ceil(length / 2)).toString("hex").slice(0, length);
case "base64":
return randomBytes(Math.ceil((length * 3) / 4) + 2).toString("base64").slice(0, length);
case "base64url":
return randomBytes(Math.ceil((length * 3) / 4) + 2).toString("base64url").slice(0, length);
case "alnum":
return Array.from({ length }, () => ALNUM[randomInt(ALNUM.length)]).join("");
}
}
export interface PlanInput {
vault: string;
key: string;
fingerprint: string;
updatedAt: string;
}
export interface PlannedRotation {
key: string;
vaults: string[];
fingerprint: string;
oldestUpdate: string;
method: RotationMethod | "unknown";
source: "entry" | "catalog" | "none";
automatic: boolean;
spec: RotationSpec | null;
}
/**
* 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.
*/
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;
// 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;
const id = `${r.key}\u0000${r.fingerprint}`;
groups.set(id, [...(groups.get(id) ?? []), r]);
}
const out: PlannedRotation[] = [];
for (const members of groups.values()) {
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);
out.push({
key: first.key,
vaults: members.map((m) => m.vault).sort(),
fingerprint: first.fingerprint,
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",
spec
});
}
return out.sort((a, b) => a.key.localeCompare(b.key) || a.vaults[0]!.localeCompare(b.vaults[0]!));
}

View file

@ -55,6 +55,7 @@ export {
githubSecretsProvider,
sshProvider,
teamProvider,
ROTATION_ENTRY_PREFIX,
parseEnv,
applyEnv,
classifySshFile,

View file

@ -25,6 +25,7 @@ export function listCredentialProviderManifests(): CredentialProviderManifest[]
}
export { envProvider, dopplerProvider, railwayProvider, githubSecretsProvider, sh1ptProvider, sshProvider, teamProvider };
export { ROTATION_ENTRY_PREFIX } from "./team.js";
export { parseEnv, applyEnv } from "./env.js";
export {
classifySshFile,

View file

@ -1,4 +1,7 @@
import { fingerprintValue } from "../fingerprint.js";
/** Vault entries holding a secret's rotation instructions: `__ROTATE__<KEY>`. */
export const ROTATION_ENTRY_PREFIX = "__ROTATE__";
import { TeamClient, TeamApiError, type RemoteSecret } from "../client.js";
import { requireAuth, defaultApiUrl } from "../identity.js";
import { generateVaultKey, wrapVaultKey, unwrapVaultKey, encryptValue, decryptValue } from "../crypto.js";
@ -112,7 +115,10 @@ export const teamProvider: CredentialProvider = {
provider: "team",
endpoint,
valuesReadable,
// Rotation instructions ride along in the vault but are not app config:
// never pulled into a .env, never deleted by a push that lacks them.
keys: secrets
.filter((s: RemoteSecret) => !s.name.startsWith(ROTATION_ENTRY_PREFIX))
.map((s: RemoteSecret) => ({ name: s.name, present: true, fingerprint: s.fingerprint, lastModifiedAt: s.updatedAt }))
.sort((a, b) => a.name.localeCompare(b.name)),
inspectedAt: new Date().toISOString()