mirror of
https://github.com/profullstack/logicsrc.git
synced 2026-11-29 15:51:52 +00:00
Rotation on every surface: desktop rotator, Rotation page + run queue, MCP tools (CLI 0.15.0) (#269)
- method "desktop": dashboard-only keys (OpenAI, ElevenLabs, Brave Search, Civitai, Cloudflare Global API Key roll, Anthropic/Claude OAuth report-only) rotated by an agent on a W3BS Agentic Desktop Layer host (--desktop / LOGICSRC_DESKTOP_HOST). Agent browser only, old key by its last 4 chars, DOM-to-file capture (wl-paste fallback), two-phase revoke after health, rollback deletes the new key, remote file shredded. needs-login and busy are waits, not failures. Roll needs --allow-roll plus a capture self-test. - app.logicsrc.com: /teams/:slug/rotation plan page + rotation run queue (migration 010), API routes; runner: rotate-keys --from-queue. - MCP: rotation_plan, rotation_set, rotate_keys (dry run default), rotation_runs. - docs/rotation.md: desktop rotators and every surface. Co-authored-by: Anthony Ettinger <anthony@profullstack.com> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
aec3e5f5fa
commit
87bbc50423
23 changed files with 2191 additions and 35 deletions
|
|
@ -1,6 +1,6 @@
|
|||
{
|
||||
"name": "@logicsrc/cli",
|
||||
"version": "0.14.0",
|
||||
"version": "0.15.0",
|
||||
"description": "LogicSRC CLI: every LogicSRC standard and tool as one command.",
|
||||
"type": "module",
|
||||
"main": "./dist/index.js",
|
||||
|
|
|
|||
348
packages/cli/src/desktop-flow.test.ts
Normal file
348
packages/cli/src/desktop-flow.test.ts
Normal file
|
|
@ -0,0 +1,348 @@
|
|||
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, teamsRotateFromQueue } = await import("./rotate-keys.js");
|
||||
import { createPrompt, parseAgentResult, desktopHost } from "./desktop-rotator.js";
|
||||
import type { DesktopExec } from "./desktop-rotator.js";
|
||||
import { DESKTOP_RECIPES } from "./desktop-recipes.js";
|
||||
import { catalogSpec, isAutomatic } from "./rotation-catalog.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 };
|
||||
|
||||
|
||||
const OLD_OAI = "sk-proj-OLDOLDOLDOLDOLDOLDOLDabcd";
|
||||
const NEW_OAI = "sk-proj-NEWNEWNEWNEWNEWNEWNEWwxyz";
|
||||
|
||||
interface FakeDesk {
|
||||
exec: DesktopExec;
|
||||
prompts: string[];
|
||||
commands: string[];
|
||||
files: Map<string, string>;
|
||||
shredded: string[];
|
||||
}
|
||||
|
||||
/** A fake bonita: w3bs-desktop status, a claude -p that "drives" the browser, cat and shred. */
|
||||
function fakeDesk(o: { status?: string; statusCode?: number; create?: string; captured?: string; selfTest?: "ok" | "wrong"; revoke?: string } = {}): FakeDesk {
|
||||
const files = new Map<string, string>();
|
||||
const prompts: string[] = [];
|
||||
const commands: string[] = [];
|
||||
const shredded: string[] = [];
|
||||
const exec: DesktopExec = async (host, command, opts = {}) => {
|
||||
expect(host).toBe("bonita");
|
||||
commands.push(command);
|
||||
if (command.includes("w3bs-desktop status")) return { status: o.statusCode ?? 0, stdout: o.status ?? "Agent access: ENABLED\nInput lease: free\n", stderr: "" };
|
||||
if (command.includes("claude -p")) {
|
||||
const prompt = opts.input ?? "";
|
||||
prompts.push(prompt);
|
||||
const file = /> (~\/\.cache\/rot\/[a-z0-9-]+)/.exec(prompt)?.[1];
|
||||
if (prompt.includes("capture self-test")) {
|
||||
const nonce = /value="([0-9a-f]+)"/.exec(prompt)![1]!;
|
||||
files.set(file!, o.selfTest === "wrong" ? "zzz" : nonce);
|
||||
return { status: 0, stdout: "saved 36 bytes\nROTATION_RESULT: ok\n", stderr: "" };
|
||||
}
|
||||
if (prompt.startsWith("Task: rotate")) {
|
||||
const code = o.create ?? "ok";
|
||||
if (code === "ok") files.set(file!, o.captured ?? NEW_OAI);
|
||||
return { status: 0, stdout: `working...\nROTATION_RESULT: ${code}\n`, stderr: "" };
|
||||
}
|
||||
if (prompt.startsWith("Task: revoke")) return { status: 0, stdout: `ROTATION_RESULT: ${o.revoke ?? "ok"}\n`, stderr: "" };
|
||||
if (prompt.startsWith("Task: report")) return { status: 0, stdout: "ROTATION_RESULT: ok key ci-agents, last used 2026-10-28\n", stderr: "" };
|
||||
}
|
||||
const cat = /^cat (\S+)$/.exec(command);
|
||||
if (cat) return files.has(cat[1]!) ? { status: 0, stdout: `${files.get(cat[1]!)}\n`, stderr: "" } : { status: 1, stdout: "", stderr: "no such file" };
|
||||
const shred = /^shred -u (\S+)/.exec(command);
|
||||
if (shred) {
|
||||
shredded.push(shred[1]!);
|
||||
files.delete(shred[1]!);
|
||||
return { status: 0, stdout: "", stderr: "" };
|
||||
}
|
||||
throw new Error(`unexpected command: ${command}`);
|
||||
};
|
||||
return { exec, prompts, commands, files, shredded };
|
||||
}
|
||||
|
||||
function noValueAnywhere(desk: FakeDesk, ...values: string[]) {
|
||||
for (const v of values) {
|
||||
for (const p of desk.prompts) expect(p).not.toContain(v);
|
||||
for (const c of desk.commands) expect(c).not.toContain(v);
|
||||
}
|
||||
}
|
||||
|
||||
describe("desktop rotator", () => {
|
||||
beforeEach(() => {
|
||||
vi.spyOn(console, "log").mockImplementation(() => {});
|
||||
vi.spyOn(console, "error").mockImplementation(() => {});
|
||||
writeFileSync(join(root, "a.com", "app.env"), `OPENAI_API_KEY=${OLD_OAI}\n`, { mode: 0o600 });
|
||||
writeFileSync(join(root, "b.com", "app.env"), "X=1\n");
|
||||
});
|
||||
|
||||
it("catalog: dashboard-only keys are desktop, report-only ones are not automatic", () => {
|
||||
expect(catalogSpec("OPENAI_API_KEY")).toMatchObject({ method: "desktop", recipe: "openai" });
|
||||
expect(catalogSpec("ELEVENLABS_API_KEY")).toMatchObject({ method: "desktop", recipe: "elevenlabs" });
|
||||
expect(catalogSpec("BRAVE_SEARCH_API_KEY")).toMatchObject({ method: "desktop", recipe: "brave-search" });
|
||||
expect(catalogSpec("BRAVE_API_KEY")).toMatchObject({ method: "desktop", recipe: "brave-search" });
|
||||
expect(catalogSpec("CIVITAI_API_KEY")).toMatchObject({ method: "desktop", recipe: "civitai" });
|
||||
expect(catalogSpec("CLOUDFLARE_GLOBAL_API_KEY")).toMatchObject({ method: "desktop", recipe: "cloudflare-global-api-key" });
|
||||
expect(catalogSpec("CLOUDFLARE_API_TOKEN")).toMatchObject({ method: "provider" });
|
||||
expect(isAutomatic(catalogSpec("OPENAI_API_KEY"))).toBe(true);
|
||||
expect(isAutomatic(catalogSpec("ANTHROPIC_API_KEY"))).toBe(false);
|
||||
expect(isAutomatic(catalogSpec("CLAUDE_CODE_OAUTH_TOKEN"))).toBe(false);
|
||||
expect(catalogSpec("ANTHROPIC_API_KEY")!.steps!.length).toBeGreaterThan(1);
|
||||
});
|
||||
|
||||
it("prompts use the agent browser, the old key's tail, and a capture that never echoes", () => {
|
||||
const p = createPrompt(DESKTOP_RECIPES.openai!, { oldTail: "abcd", name: "logicsrc openai_api_key 2026-10-29", file: "~/.cache/rot/x" });
|
||||
expect(p).toMatch(/agent browser/);
|
||||
expect(p).toMatch(/Never use or focus Firefox/);
|
||||
expect(p).toMatch(/ends in abcd/);
|
||||
expect(p).toMatch(/browser_evaluate_script/);
|
||||
expect(p).toMatch(/wl-paste -n > ~\/\.cache\/rot\/x/);
|
||||
expect(p).toMatch(/ROTATION_RESULT: busy/);
|
||||
expect(parseAgentResult("x\nROTATION_RESULT: ok\nROTATION_RESULT: needs-login openai.com").code).toBe("needs-login");
|
||||
expect(() => desktopHost("bonita; rm -rf /", {})).toThrow(/ssh host/);
|
||||
expect(desktopHost(undefined, { LOGICSRC_DESKTOP_HOST: "bonita" })).toBe("bonita");
|
||||
});
|
||||
|
||||
it("without a desktop host, a desktop key is todo with steps", async () => {
|
||||
await makeTeam({ "a--prod": { OPENAI_API_KEY: OLD_OAI } });
|
||||
const [r] = await teamsRotateKeysAction("t", {}, { ...quiet, approve: true }, { env: {}, strayText: () => [] });
|
||||
expect(r!.status).toBe("todo");
|
||||
expect(r!.error).toMatch(/--desktop/);
|
||||
expect(r!.steps!.length).toBeGreaterThan(3);
|
||||
});
|
||||
|
||||
it("layer disabled: a clear error to enable it in the tray, nothing created", async () => {
|
||||
await makeTeam({ "a--prod": { OPENAI_API_KEY: OLD_OAI } });
|
||||
const desk = fakeDesk({ status: "Agent access: DISABLED\n" });
|
||||
const [r] = await teamsRotateKeysAction("t", {}, { ...quiet, approve: true, desktop: "bonita" }, { env: {}, desktopExec: desk.exec, strayText: () => [] });
|
||||
expect(r!.status).toBe("todo");
|
||||
expect(r!.error).toMatch(/DISABLED: enable it from the W3BS tray/);
|
||||
expect(desk.prompts).toEqual([]);
|
||||
});
|
||||
|
||||
it("dry run checks the layer but never starts an agent", async () => {
|
||||
await makeTeam({ "a--prod": { OPENAI_API_KEY: OLD_OAI } });
|
||||
const desk = fakeDesk();
|
||||
const [r] = await teamsRotateKeysAction("t", {}, { ...quiet, approve: false, desktop: "bonita", propagate: root }, { env: {}, desktopExec: desk.exec, ops: ops(), strayText: () => [] });
|
||||
expect(r!.status).toBe("would-rotate");
|
||||
expect(r!.sites!.map((s) => s.site)).toEqual(["a.com"]);
|
||||
expect(desk.prompts).toEqual([]);
|
||||
});
|
||||
|
||||
it("two-phase: create on the desktop, vaults + consumers, revoke the old key only after health, shred the file", async () => {
|
||||
const team = await makeTeam({ "a--prod": { OPENAI_API_KEY: OLD_OAI }, "b--prod": { OAI_COPY_API_KEY: OLD_OAI } });
|
||||
const desk = fakeDesk();
|
||||
const o = ops();
|
||||
const order: string[] = [];
|
||||
const exec: DesktopExec = async (h, c, opts) => {
|
||||
if (c.includes("claude -p")) order.push((opts?.input ?? "").split(" ")[1]!);
|
||||
if (c.startsWith("shred")) order.push("shred");
|
||||
return desk.exec(h, c, opts);
|
||||
};
|
||||
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 results = await teamsRotateKeysAction("t", { keys: ["OPENAI_API_KEY"] }, { ...quiet, approve: true, desktop: "bonita", propagate: root }, { env: {}, desktopExec: exec, ops: wrapped, strayText: () => [] });
|
||||
const r = results[0]!;
|
||||
expect(r.status).toBe("rotated");
|
||||
expect(r.method).toBe("desktop");
|
||||
expect(await team.read("a--prod", "OPENAI_API_KEY")).toBe(NEW_OAI);
|
||||
expect(await team.read("b--prod", "OAI_COPY_API_KEY")).toBe(NEW_OAI);
|
||||
expect(readFileSync(join(root, "a.com", "app.env"), "utf8")).toBe(`OPENAI_API_KEY=${NEW_OAI}\n`);
|
||||
expect(order).toEqual(["rotate", "restart a.com", "revoke", "shred"]);
|
||||
const revoke = desk.prompts.find((p) => p.startsWith("Task: revoke"))!;
|
||||
expect(revoke).toMatch(/ends in abcd/);
|
||||
expect(revoke).toMatch(/NEVER delete the key ending in wxyz/);
|
||||
expect(desk.files.size).toBe(0);
|
||||
noValueAnywhere(desk, OLD_OAI, NEW_OAI);
|
||||
expect(JSON.stringify(r)).not.toContain(NEW_OAI);
|
||||
expect(JSON.stringify(r)).not.toContain(OLD_OAI);
|
||||
expect(JSON.parse((await team.read("a--prod", "__ROTATE__OPENAI_API_KEY"))!).state).toMatchObject({ desktopTail: "wxyz" });
|
||||
});
|
||||
|
||||
it("rollback: an unhealthy consumer deletes the NEW key on the desktop and restores the old value", async () => {
|
||||
const team = await makeTeam({ "a--prod": { OPENAI_API_KEY: OLD_OAI } });
|
||||
const desk = fakeDesk();
|
||||
const [r] = await teamsRotateKeysAction("t", {}, { ...quiet, approve: true, desktop: "bonita", propagate: root }, { env: {}, desktopExec: desk.exec, ops: ops(["a.com"]), strayText: () => [] });
|
||||
expect(r!.status).toBe("rolled-back");
|
||||
expect(await team.read("a--prod", "OPENAI_API_KEY")).toBe(OLD_OAI);
|
||||
const revoke = desk.prompts.find((p) => p.startsWith("Task: revoke"))!;
|
||||
expect(revoke).toMatch(/ends in wxyz/);
|
||||
expect(revoke).toMatch(/NEVER delete the key ending in abcd/);
|
||||
expect(desk.files.size).toBe(0);
|
||||
process.exitCode = 0;
|
||||
});
|
||||
|
||||
it("needs-login and busy wait; the other keys go on", async () => {
|
||||
const team = await makeTeam({ "a--prod": { OPENAI_API_KEY: OLD_OAI, CRON_SECRET: OLD } });
|
||||
const desk = fakeDesk({ create: "needs-login platform.openai.com" });
|
||||
const results = await teamsRotateKeysAction("t", {}, { ...quiet, approve: true, desktop: "bonita" }, { env: {}, desktopExec: desk.exec, strayText: () => [] });
|
||||
const by = Object.fromEntries(results.map((x) => [x.key, x]));
|
||||
expect(by.OPENAI_API_KEY!.status).toBe("needs-login");
|
||||
expect(by.CRON_SECRET!.status).toBe("rotated");
|
||||
expect(await team.read("a--prod", "OPENAI_API_KEY")).toBe(OLD_OAI);
|
||||
expect(desk.files.size).toBe(0);
|
||||
const busy = fakeDesk({ status: "Agent access: ENABLED\nInput lease: held by human\n" });
|
||||
const [b] = await teamsRotateKeysAction("t", { keys: ["OPENAI_API_KEY"] }, { ...quiet, approve: true, desktop: "bonita" }, { env: {}, desktopExec: busy.exec, strayText: () => [] });
|
||||
expect(b!.status).toBe("busy");
|
||||
expect(b!.error).toMatch(/in use/);
|
||||
const refuses = fakeDesk({ create: "busy" });
|
||||
const [c] = await teamsRotateKeysAction("t", { keys: ["OPENAI_API_KEY"] }, { ...quiet, approve: true, desktop: "bonita" }, { env: {}, desktopExec: refuses.exec, strayText: () => [] });
|
||||
expect(c!.status).toBe("busy");
|
||||
expect(process.exitCode ?? 0).toBe(0);
|
||||
});
|
||||
|
||||
it("a capture that is not a key of that kind is refused and shredded", async () => {
|
||||
const team = await makeTeam({ "a--prod": { OPENAI_API_KEY: OLD_OAI } });
|
||||
const desk = fakeDesk({ captured: "hello world" });
|
||||
const [r] = await teamsRotateKeysAction("t", {}, { ...quiet, approve: true, desktop: "bonita" }, { env: {}, desktopExec: desk.exec, strayText: () => [] });
|
||||
expect(r!.status).toBe("failed");
|
||||
expect(r!.error).toMatch(/does not look like/);
|
||||
expect(r!.error).not.toContain("hello");
|
||||
expect(desk.shredded.length).toBe(1);
|
||||
expect(await team.read("a--prod", "OPENAI_API_KEY")).toBe(OLD_OAI);
|
||||
process.exitCode = 0;
|
||||
});
|
||||
|
||||
it("roll (Cloudflare Global API Key): refused without --allow-roll; with it, a capture self-test runs first", async () => {
|
||||
const CF_OLD = "0123456789abcdef0123456789abcdef01234";
|
||||
const CF_NEW = "fedcba9876543210fedcba9876543210fedcb";
|
||||
const team = await makeTeam({ "a--prod": { CLOUDFLARE_GLOBAL_API_KEY: CF_OLD } });
|
||||
const d1 = fakeDesk();
|
||||
const [r1] = await teamsRotateKeysAction("t", {}, { ...quiet, approve: true, desktop: "bonita" }, { env: {}, desktopExec: d1.exec, strayText: () => [] });
|
||||
expect(r1!.status).toBe("todo");
|
||||
expect(r1!.error).toMatch(/--allow-roll/);
|
||||
expect(d1.prompts).toEqual([]);
|
||||
|
||||
const bad = fakeDesk({ selfTest: "wrong", captured: CF_NEW });
|
||||
const [r2] = await teamsRotateKeysAction("t", {}, { ...quiet, approve: true, desktop: "bonita", allowRoll: true }, { env: {}, desktopExec: bad.exec, strayText: () => [] });
|
||||
expect(r2!.status).toBe("failed");
|
||||
expect(r2!.error).toMatch(/self-test/);
|
||||
expect(bad.prompts.some((p) => p.startsWith("Task: rotate"))).toBe(false);
|
||||
|
||||
const good = fakeDesk({ captured: CF_NEW });
|
||||
const [r3] = await teamsRotateKeysAction("t", {}, { ...quiet, approve: true, desktop: "bonita", allowRoll: true }, { env: {}, desktopExec: good.exec, strayText: () => [] });
|
||||
expect(r3!.status).toBe("rotated");
|
||||
expect(good.prompts[0]).toMatch(/capture self-test/);
|
||||
expect(good.prompts[1]).toMatch(/^Task: rotate/);
|
||||
expect(good.prompts.some((p) => p.startsWith("Task: revoke"))).toBe(false);
|
||||
expect(await team.read("a--prod", "CLOUDFLARE_GLOBAL_API_KEY")).toBe(CF_NEW);
|
||||
process.exitCode = 0;
|
||||
});
|
||||
|
||||
it("report-only (Anthropic): the agent looks, nothing is created or revoked", async () => {
|
||||
const team = await makeTeam({ "a--prod": { ANTHROPIC_API_KEY: "sk-ant-api03-xxxxxxxxxxxxxxxxxxxx1234" } });
|
||||
const desk = fakeDesk();
|
||||
const [r] = await teamsRotateKeysAction("t", {}, { ...quiet, approve: true, desktop: "bonita" }, { env: {}, desktopExec: desk.exec, strayText: () => [] });
|
||||
expect(r!.status).toBe("todo");
|
||||
expect(r!.note).toMatch(/last used/);
|
||||
expect(desk.prompts).toHaveLength(1);
|
||||
expect(desk.prompts[0]).toMatch(/^Task: report/);
|
||||
expect(desk.prompts[0]).toMatch(/ending in 1234/);
|
||||
expect(team.puts).toEqual([]);
|
||||
});
|
||||
|
||||
it("--from-queue: claims each queued run, runs it, reports results without values; approve needs both sides", async () => {
|
||||
const team = await makeTeam({ "a--prod": { CRON_SECRET: OLD } });
|
||||
const calls: string[] = [];
|
||||
const reported: any[] = [];
|
||||
Object.assign(server.client, {
|
||||
listRotationRuns: async () => ({ runs: [
|
||||
{ id: "r2", keys: ["CRON_SECRET"], project: null, env: null, approve: true, options: {}, status: "queued", createdAt: 2, summary: null },
|
||||
{ id: "r1", keys: ["CRON_SECRET"], project: "a", env: "prod", approve: false, options: {}, status: "queued", createdAt: 1, summary: null }
|
||||
] }),
|
||||
claimRotationRun: async (_s: string, id: string) => (calls.push(`claim ${id}`), { run: {} }),
|
||||
reportRotationRun: async (_s: string, id: string, body: any) => (calls.push(`report ${id}`), reported.push(body), { run: { summary: "ok" } })
|
||||
});
|
||||
const reports = await teamsRotateFromQueue("t", { ...quiet, approve: false }, { env: {}, strayText: () => [] });
|
||||
expect(calls).toEqual(["claim r1", "report r1", "claim r2", "report r2"]);
|
||||
expect(reports.map((r) => r.ran)).toEqual(["dry run", "dry run"]);
|
||||
expect(reported[1].error).toMatch(/no --approve/);
|
||||
expect(await team.read("a--prod", "CRON_SECRET")).toBe(OLD);
|
||||
const live = await teamsRotateFromQueue("t", { ...quiet, approve: true, maxRuns: 2 }, { env: {}, strayText: () => [] });
|
||||
expect(live[1]!.ran).toBe("approved");
|
||||
expect(await team.read("a--prod", "CRON_SECRET")).not.toBe(OLD);
|
||||
expect(JSON.stringify(reported)).not.toContain(OLD);
|
||||
});
|
||||
});
|
||||
164
packages/cli/src/desktop-recipes.ts
Normal file
164
packages/cli/src/desktop-recipes.ts
Normal file
|
|
@ -0,0 +1,164 @@
|
|||
/**
|
||||
* Dashboard recipes for `method: "desktop"`: how an agent on a W3BS Agentic
|
||||
* Desktop Layer host finds, creates and revokes one provider's API key in a
|
||||
* signed-in browser. Pure data, so the catalog, the CLI and the credentials app
|
||||
* can all read it.
|
||||
*
|
||||
* Wording rules for every recipe:
|
||||
* - the old key is found by its LAST 4 CHARACTERS (`{oldTail}`), never by value;
|
||||
* - the new key is captured from the reveal dialog (DOM to file, Copy + wl-paste
|
||||
* as the fallback), never typed or echoed;
|
||||
* - when a step is ambiguous the agent stops and reports instead of guessing.
|
||||
*
|
||||
* Modes:
|
||||
* two-phase create the new key (old still works), switch consumers, then revoke the old one
|
||||
* roll the site replaces the key in place: the old one dies on create (no overlap)
|
||||
* report the agent only checks the key is listed and reports; nothing is created or revoked
|
||||
*/
|
||||
|
||||
export type DesktopMode = "two-phase" | "roll" | "report";
|
||||
|
||||
export interface DesktopRecipe {
|
||||
id: string;
|
||||
title: string;
|
||||
/** Where the keys are listed. */
|
||||
url: string;
|
||||
mode: DesktopMode;
|
||||
/** How the page shows a key, so the agent can find the one ending in {oldTail}. */
|
||||
locate: string;
|
||||
/** Steps to create the new key, up to the dialog that shows the new key (the capture steps follow). */
|
||||
create: string[];
|
||||
/** Steps to delete one key, identified by {tail}. Absent: never revoked by automation. */
|
||||
revoke?: string[];
|
||||
/** Why the old key is never revoked automatically (shown as the revoke note). */
|
||||
revokeNote?: string;
|
||||
/** A rough shape check for the captured value (never a full validation). */
|
||||
pattern?: string;
|
||||
/** Who reads this kind of key (used in steps). */
|
||||
family: string;
|
||||
/** What breaks during a rotation (roll mode). */
|
||||
disruptive?: string;
|
||||
}
|
||||
|
||||
const KEEP = "Never touch any other key. If more than one key ends in {tail}, or you cannot tell which one it is, stop and report ambiguous.";
|
||||
|
||||
export const DESKTOP_RECIPES: Record<string, DesktopRecipe> = {
|
||||
openai: {
|
||||
id: "openai",
|
||||
title: "OpenAI API key",
|
||||
url: "https://platform.openai.com/api-keys",
|
||||
mode: "two-phase",
|
||||
family: "ai",
|
||||
pattern: "^sk-[A-Za-z0-9_-]{20,}$",
|
||||
locate: "The API keys table masks each secret key like sk-...abcd: the old key is the row whose masked key ends in {oldTail}. Note its project and permissions.",
|
||||
create: [
|
||||
"Click \"Create new secret key\".",
|
||||
"Name it {name}. Choose the same owner type, project and permissions as the old key (the row ending in {oldTail}).",
|
||||
"Click \"Create secret key\". Leave the dialog that shows the new key open."
|
||||
],
|
||||
revoke: [
|
||||
"Find the row whose masked key ends in {tail}. Click its delete (trash) icon and confirm \"Revoke key\".",
|
||||
KEEP
|
||||
]
|
||||
},
|
||||
elevenlabs: {
|
||||
id: "elevenlabs",
|
||||
title: "ElevenLabs API key",
|
||||
url: "https://elevenlabs.io/app/settings/api-keys",
|
||||
mode: "two-phase",
|
||||
family: "ai",
|
||||
pattern: "^(sk_)?[A-Za-z0-9]{24,}$",
|
||||
locate: "The API keys list shows each key's name and its last characters: the old key is the one ending in {oldTail}. Note its permissions and credit limit.",
|
||||
create: [
|
||||
"Click \"Create API key\" (or \"Create Key\").",
|
||||
"Name it {name}. Give it the same permissions (endpoint access) and credit limit as the old key ending in {oldTail}.",
|
||||
"Create it. Leave the dialog that shows the new key open."
|
||||
],
|
||||
revoke: ["Open the menu (three dots) on the key ending in {tail}, choose Delete, and confirm.", KEEP]
|
||||
},
|
||||
"brave-search": {
|
||||
id: "brave-search",
|
||||
title: "Brave Search API key",
|
||||
url: "https://api-dashboard.search.brave.com/app/keys",
|
||||
mode: "two-phase",
|
||||
family: "ai",
|
||||
pattern: "^[A-Za-z0-9_-]{20,}$",
|
||||
locate: "The API Keys page lists each key with a masked token: the old key is the one ending in {oldTail} (reveal is not needed). Note which subscription it belongs to.",
|
||||
create: [
|
||||
"Click \"Add API key\".",
|
||||
"Name it {name} and pick the same subscription as the old key ending in {oldTail}.",
|
||||
"Save. Leave the new key's token shown (reveal it if the page hides it)."
|
||||
],
|
||||
revoke: ["On the key ending in {tail}, click the delete (trash) icon and confirm.", KEEP]
|
||||
},
|
||||
civitai: {
|
||||
id: "civitai",
|
||||
title: "Civitai API key",
|
||||
url: "https://civitai.com/user/account",
|
||||
mode: "two-phase",
|
||||
family: "ai",
|
||||
pattern: "^[A-Za-z0-9]{24,}$",
|
||||
locate: "Scroll to the \"API Keys\" section. Civitai lists keys by name and creation date; if it shows the last characters, the old key ends in {oldTail}. If you cannot tell which listed key is the old one, stop and report ambiguous.",
|
||||
create: [
|
||||
"In \"API Keys\", click \"Add API key\".",
|
||||
"Name it {name} and save.",
|
||||
"Leave the dialog that shows the new key open."
|
||||
],
|
||||
revoke: ["In \"API Keys\", delete the key identified as {tail} (the old key you located before), and confirm.", KEEP]
|
||||
},
|
||||
"cloudflare-global-api-key": {
|
||||
id: "cloudflare-global-api-key",
|
||||
title: "Cloudflare Global API Key",
|
||||
url: "https://dash.cloudflare.com/profile/api-tokens",
|
||||
mode: "roll",
|
||||
family: "cloudflare",
|
||||
pattern: "^[a-f0-9]{37}$",
|
||||
disruptive: "Cloudflare has one Global API Key per user: changing it kills the old one at once, so consumers fail until they restart",
|
||||
locate: "Under \"API Keys\", the \"Global API Key\" row. There is exactly one; the current key ends in {oldTail}.",
|
||||
create: [
|
||||
"On the \"Global API Key\" row click \"Change\" (it may ask for the account password or a captcha: if it does, stop and report needs-login).",
|
||||
"Confirm the change. Leave the new key shown."
|
||||
],
|
||||
revokeNote: "changing the Global API Key already killed the old one"
|
||||
},
|
||||
anthropic: {
|
||||
id: "anthropic",
|
||||
title: "Anthropic API key",
|
||||
url: "https://console.anthropic.com/settings/keys",
|
||||
mode: "report",
|
||||
family: "ai",
|
||||
locate: "The API keys table masks each key like sk-ant-api03-...abcd: the old key is the row ending in {oldTail}. Report its name, workspace and \"last used\" date.",
|
||||
create: [],
|
||||
revokeNote: "Anthropic keys run the agents themselves: report-only, a person creates the new key and revokes the old one"
|
||||
},
|
||||
"claude-oauth": {
|
||||
id: "claude-oauth",
|
||||
title: "Claude OAuth token",
|
||||
url: "https://claude.ai/settings/claude-code",
|
||||
mode: "report",
|
||||
family: "ai",
|
||||
locate: "The page lists Claude Code sessions and long-lived tokens. Report whether one created for this key (or ending in {oldTail}, if tails are shown) is listed, and when it was created.",
|
||||
create: [],
|
||||
revokeNote: "a Claude OAuth token signs in the agents themselves: report-only, never revoked by automation (a person runs claude setup-token, stores it, then revokes the old one)"
|
||||
}
|
||||
};
|
||||
|
||||
/** Placeholders in recipe text: {oldTail}, {tail}, {name}. */
|
||||
export function fillRecipe(text: string, vars: Record<string, string>): string {
|
||||
return text.replace(/\{(\w+)\}/g, (m, k: string) => (k in vars ? vars[k]! : m));
|
||||
}
|
||||
|
||||
/** The human steps for a recipe, for the plan (no desktop host needed to read them). */
|
||||
export function recipeSteps(r: DesktopRecipe): string[] {
|
||||
const vars = { oldTail: "<last 4 of the old key>", tail: "<last 4 of the old key>", name: "logicsrc <key> <date>" };
|
||||
if (r.mode === "report") return [`Open ${r.url}.`, fillRecipe(r.locate, vars), r.revokeNote ?? "Report only."];
|
||||
return [
|
||||
`Open ${r.url} in a browser signed in to the provider (on a W3BS desktop: the layer's agent browser).`,
|
||||
fillRecipe(r.locate, vars),
|
||||
...r.create.map((s) => fillRecipe(s, vars)),
|
||||
"Copy the new key (the site's Copy button) without pasting it anywhere else.",
|
||||
"Store it: logicsrc teams rotate-keys <team> <project> <env> --key <KEY> --set-from-stdin --approve.",
|
||||
"Redeploy every consumer the plan lists, check each health URL.",
|
||||
...(r.revoke ? ["Then revoke the old key:", ...r.revoke.map((s) => fillRecipe(s, vars))] : [r.revokeNote ?? ""])
|
||||
].filter(Boolean);
|
||||
}
|
||||
402
packages/cli/src/desktop-rotator.ts
Normal file
402
packages/cli/src/desktop-rotator.ts
Normal file
|
|
@ -0,0 +1,402 @@
|
|||
import { spawn } from "node:child_process";
|
||||
import { randomBytes } from "node:crypto";
|
||||
import { DESKTOP_RECIPES, fillRecipe, type DesktopRecipe } from "./desktop-recipes.js";
|
||||
import type { Minted, ProviderRotator, RotatorContext } from "./rotators.js";
|
||||
|
||||
/**
|
||||
* `method: "desktop"`: rotate a dashboard-only provider key by driving the
|
||||
* signed-in browser on a W3BS Agentic Desktop Layer host.
|
||||
*
|
||||
* 1. ssh <host> w3bs-desktop status agent access must be enabled (tray)
|
||||
* 2. ssh <host> claude -p (create job) in the layer's own agent browser
|
||||
* (TronBrowser, DevTools channel; the
|
||||
* everyday Firefox is not in the agent's
|
||||
* grants) finds the old key by its LAST 4
|
||||
* chars, creates the new key, and writes it
|
||||
* to ~/.cache/rot/<id> (mode 600) straight
|
||||
* from the reveal dialog's DOM through a
|
||||
* shell pipeline whose output never reaches
|
||||
* the agent; the site's Copy button plus
|
||||
* wl-paste is the fallback
|
||||
* 3. ssh <host> cat ~/.cache/rot/<id> the CLI reads it into memory; the
|
||||
* caller writes vaults, propagates,
|
||||
* health-checks (rotate-keys.ts)
|
||||
* 4. ssh <host> claude -p (revoke job) only after consumers are healthy
|
||||
* 5. ssh <host> shred -u ~/.cache/rot/<id>
|
||||
*
|
||||
* The remote agent is told only the old key's tail, never a value, and it never
|
||||
* types or prints the new value. Nothing here prints a value; errors carry
|
||||
* result codes only.
|
||||
*
|
||||
* A person at the desk wins: when the layer's input lease is held, or the agent
|
||||
* refuses because someone is typing, the key comes back `busy` (retry later),
|
||||
* not failed. A roll recipe (Cloudflare Global API Key: the old key dies on
|
||||
* create) runs only with --allow-roll AND after a capture self-test in the same
|
||||
* run proved the DOM-to-file path on a scratch page holding a random nonce.
|
||||
*/
|
||||
|
||||
export interface RunResult {
|
||||
status: number | null;
|
||||
stdout: string;
|
||||
stderr: string;
|
||||
}
|
||||
|
||||
/** Runs one shell command on a host (ssh). Tests pass a fake. */
|
||||
export type DesktopExec = (host: string, command: string, opts?: { input?: string; timeoutMs?: number }) => Promise<RunResult>;
|
||||
|
||||
export class DesktopError extends Error {
|
||||
constructor(
|
||||
message: string,
|
||||
readonly code: "layer-disabled" | "no-layer" | "unreachable" | "needs-login" | "busy" | "ambiguous" | "not-found" | "bad-capture" | "roll-refused" | "agent-failed"
|
||||
) {
|
||||
super(message);
|
||||
}
|
||||
}
|
||||
|
||||
/** The session the desktop layer runs in (Wayland + user D-Bus), for a non-interactive ssh. */
|
||||
export const DESKTOP_ENV =
|
||||
'export PATH="$HOME/.local/bin:$PATH" XDG_RUNTIME_DIR="/run/user/$(id -u)" WAYLAND_DISPLAY="${WAYLAND_DISPLAY:-wayland-0}" DBUS_SESSION_BUS_ADDRESS="unix:path=/run/user/$(id -u)/bus";';
|
||||
|
||||
/**
|
||||
* Exactly what the remote agent may do: drive the desktop and its agent browser
|
||||
* (MCP or `w3bs desktop browser call`), write a captured value to a file
|
||||
* (jq / wl-paste), clear the clipboard, check a file's size.
|
||||
*/
|
||||
export const DESKTOP_TOOLS = [
|
||||
'"mcp__w3bs-desktop__*"',
|
||||
'"Bash(w3bs:*)"',
|
||||
'"Bash(jq:*)"',
|
||||
'"Bash(mkdir:*)"',
|
||||
'"Bash(wl-paste:*)"',
|
||||
'"Bash(wl-copy:*)"',
|
||||
'"Bash(chmod:*)"',
|
||||
'"Bash(wc:*)"'
|
||||
];
|
||||
|
||||
const AGENT_TIMEOUT = 15 * 60_000;
|
||||
|
||||
export const defaultDesktopExec: DesktopExec = (host, command, opts = {}) =>
|
||||
new Promise((resolve) => {
|
||||
const child = spawn("ssh", ["-o", "BatchMode=yes", "-o", "ConnectTimeout=15", host, command], { stdio: ["pipe", "pipe", "pipe"] });
|
||||
let stdout = "";
|
||||
let stderr = "";
|
||||
const timer = setTimeout(() => child.kill("SIGTERM"), opts.timeoutMs ?? 60_000);
|
||||
child.stdout.on("data", (d) => (stdout += d));
|
||||
child.stderr.on("data", (d) => (stderr += d));
|
||||
child.on("error", (e) => {
|
||||
clearTimeout(timer);
|
||||
resolve({ status: null, stdout, stderr: stderr || e.message });
|
||||
});
|
||||
child.on("close", (status) => {
|
||||
clearTimeout(timer);
|
||||
resolve({ status, stdout, stderr });
|
||||
});
|
||||
child.stdin.end(opts.input ?? "");
|
||||
});
|
||||
|
||||
/** The desktop host: --desktop, else LOGICSRC_DESKTOP_HOST. */
|
||||
export function desktopHost(option: string | undefined, env: Record<string, string | undefined>): string | undefined {
|
||||
const h = (option || env.LOGICSRC_DESKTOP_HOST || "").trim();
|
||||
if (!h) return undefined;
|
||||
if (!/^[A-Za-z0-9._@-]+$/.test(h)) throw new Error(`--desktop must be an ssh host alias (got ${JSON.stringify(h)})`);
|
||||
return h;
|
||||
}
|
||||
|
||||
export function tail(value: string): string {
|
||||
return value.slice(-4);
|
||||
}
|
||||
|
||||
/** Job ids go into a remote path: keep them boring. */
|
||||
function jobId(key: string): string {
|
||||
return `${key.toLowerCase().replace(/[^a-z0-9]+/g, "-").slice(0, 40)}-${randomBytes(4).toString("hex")}`;
|
||||
}
|
||||
|
||||
const RESULT = /^ROTATION_RESULT:\s*([a-z-]+)\s*(.*)$/m;
|
||||
|
||||
/** The agent's last ROTATION_RESULT line. Anything else is a failure. */
|
||||
export function parseAgentResult(stdout: string): { code: string; detail: string } {
|
||||
const lines = stdout.split(/\r?\n/).filter((l) => RESULT.test(l));
|
||||
const m = lines.length ? RESULT.exec(lines[lines.length - 1]!) : null;
|
||||
return m ? { code: m[1]!, detail: m[2]!.trim().slice(0, 200) } : { code: "none", detail: "" };
|
||||
}
|
||||
|
||||
const BROWSER =
|
||||
"Work only in the desktop layer's agent browser (TronBrowser, driven through the w3bs-desktop browser tools / `w3bs desktop browser call browser_*`). If it is not running, start it with `w3bs desktop browser launch`. Never use or focus Firefox or any other window.";
|
||||
|
||||
const RULES = [
|
||||
"Rules (all of them, always):",
|
||||
"- Use only the w3bs-desktop tools to see and drive the screen and the agent browser, and only the shell commands named here.",
|
||||
"- Prefer the browser's DOM tools (snapshot, click by uid) over screenshots and coordinates; re-observe before every click.",
|
||||
"- Never type, read aloud, print, describe or summarise any API key value, and never let one appear in your own output. Identify keys only by their last 4 characters.",
|
||||
"- If you hit a login page, a 2FA/passkey prompt, a captcha or a password confirmation, stop at once and finish with: ROTATION_RESULT: needs-login <site>",
|
||||
"- If a person is using the desktop (the input lease is held, the layer reports busy, or you see live typing), do not take over: change nothing and finish with: ROTATION_RESULT: busy",
|
||||
"- If a step is ambiguous (two candidate keys, a missing button, an unexpected dialog), do nothing destructive and finish with: ROTATION_RESULT: ambiguous <what>",
|
||||
"- If the key you are told to find is not listed, finish with: ROTATION_RESULT: not-found",
|
||||
"- Finish with exactly one line starting ROTATION_RESULT: (codes: ok, needs-login, busy, ambiguous, not-found, error)."
|
||||
];
|
||||
|
||||
/** How the agent gets a value shown in the page into a file without ever seeing it. */
|
||||
export function captureSteps(file: string, what: string): string[] {
|
||||
return [
|
||||
`Save ${what} to ${file} WITHOUT the value passing through your own output. Preferred: one shell pipeline that reads it from the page's DOM and writes it straight to the file, for example`,
|
||||
` mkdir -p ~/.cache/rot && w3bs desktop browser call browser_evaluate_script '{"function":"() => <expression returning the text of the input/code element that holds it>"}' --json | jq -r '<path to the returned string>' > ${file} && chmod 600 ${file} && wc -c < ${file}`,
|
||||
" (look up the element with a DOM snapshot first; use the tool and JSON path the browser channel really has; the command's own output must be only the byte count).",
|
||||
` Fallback only if that is impossible: click the site's Copy button, then: mkdir -p ~/.cache/rot && wl-paste -n > ${file} && chmod 600 ${file} && wc -c < ${file} ; then clear the clipboard: wl-copy --clear`,
|
||||
` The byte count must be more than 0; if it is 0, try the other way once, then finish with: ROTATION_RESULT: error capture`
|
||||
];
|
||||
}
|
||||
|
||||
export function createPrompt(r: DesktopRecipe, vars: { oldTail: string; name: string; file: string }): string {
|
||||
const create = r.create.map((s) => fillRecipe(s, vars));
|
||||
return [
|
||||
`Task: rotate the ${r.title} on ${r.url}.`,
|
||||
BROWSER,
|
||||
`1. Open ${r.url} in the agent browser (new tab). The provider login must already exist in that browser profile; if it does not, finish with ROTATION_RESULT: needs-login.`,
|
||||
`2. ${fillRecipe(r.locate, vars)}`,
|
||||
...create.map((s, i) => `${i + 3}. ${s}`),
|
||||
`${create.length + 3}. While the dialog shows the new key:`,
|
||||
...captureSteps(vars.file, "the new key"),
|
||||
`${create.length + 4}. Close the dialog. Finish with: ROTATION_RESULT: ok`,
|
||||
"",
|
||||
...RULES
|
||||
].join("\n");
|
||||
}
|
||||
|
||||
/** Proves the capture path on a scratch page holding a random nonce: no provider, no key. */
|
||||
export function selfTestPrompt(nonce: string, file: string): string {
|
||||
const page = `data:text/html,<title>logicsrc capture test</title><input id="k" readonly value="${nonce}"><button onclick="navigator.clipboard.writeText(document.getElementById('k').value)">Copy</button>`;
|
||||
return [
|
||||
"Task: a capture self-test. No account and no real key are involved.",
|
||||
BROWSER,
|
||||
`1. Open this page in the agent browser (new tab): ${page}`,
|
||||
"2. The input with id k holds a test value.",
|
||||
...captureSteps(file, "the input's value"),
|
||||
"3. Close the tab. Finish with: ROTATION_RESULT: ok",
|
||||
"",
|
||||
...RULES
|
||||
].join("\n");
|
||||
}
|
||||
|
||||
export function revokePrompt(r: DesktopRecipe, vars: { tail: string; keepTail: string }): string {
|
||||
return [
|
||||
`Task: revoke one ${r.title} on ${r.url}.`,
|
||||
BROWSER,
|
||||
`1. Open ${r.url} in the agent browser (new tab).`,
|
||||
`2. First confirm that a key ending in ${vars.keepTail} is listed (the new key). If it is not, change nothing and finish with: ROTATION_RESULT: not-found new key`,
|
||||
...(r.revoke ?? []).map((s, i) => `${i + 3}. ${fillRecipe(s, vars)}`),
|
||||
`${(r.revoke?.length ?? 0) + 3}. NEVER delete the key ending in ${vars.keepTail}. Finish with: ROTATION_RESULT: ok`,
|
||||
"",
|
||||
...RULES
|
||||
].join("\n");
|
||||
}
|
||||
|
||||
export function reportPrompt(r: DesktopRecipe, vars: { oldTail: string }): string {
|
||||
return [
|
||||
`Task: report on one ${r.title} on ${r.url}. Look only; change nothing.`,
|
||||
BROWSER,
|
||||
`1. Open ${r.url} in the agent browser (new tab).`,
|
||||
`2. ${fillRecipe(r.locate, vars)}`,
|
||||
"3. Do not create, edit or delete anything. Finish with: ROTATION_RESULT: ok <name, created and last-used, no values>",
|
||||
"",
|
||||
...RULES
|
||||
].join("\n");
|
||||
}
|
||||
|
||||
export interface DesktopDeps {
|
||||
host: string;
|
||||
exec?: DesktopExec;
|
||||
/** Roll recipes (old key dies on create) run only with this (--allow-roll). */
|
||||
allowRoll?: boolean;
|
||||
/** Shared by every desktop key in one run: one status check, one capture self-test. */
|
||||
session?: DesktopSession;
|
||||
}
|
||||
|
||||
export interface DesktopSession {
|
||||
status?: Promise<DesktopProblem | null>;
|
||||
/** Set once a capture (self-test or a real create) round-tripped in this run. */
|
||||
captureProven?: boolean;
|
||||
}
|
||||
|
||||
export interface DesktopProblem {
|
||||
code: DesktopError["code"];
|
||||
message: string;
|
||||
}
|
||||
|
||||
/** null when the layer accepts agents right now, else why not. */
|
||||
export function desktopStatus(host: string, exec: DesktopExec, session: DesktopSession = {}): Promise<DesktopProblem | null> {
|
||||
session.status ??= checkStatus(host, exec);
|
||||
return session.status;
|
||||
}
|
||||
|
||||
async function checkStatus(host: string, exec: DesktopExec): Promise<DesktopProblem | null> {
|
||||
const r = await exec(host, `${DESKTOP_ENV} w3bs-desktop status 2>&1`, { timeoutMs: 30_000 });
|
||||
const out = `${r.stdout}\n${r.stderr}`;
|
||||
if (r.status === 255 || r.status === null) return { code: "unreachable", message: `cannot reach desktop host ${host} over ssh (${(r.stderr.trim().split("\n").pop() ?? "").slice(0, 120)})` };
|
||||
if (r.status === 127 || /command not found/.test(out)) return { code: "no-layer", message: `the W3BS Agentic Desktop Layer (w3bs-desktop) is not installed on ${host}` };
|
||||
if (/Agent access:\s*DISABLED/i.test(out) || r.status === 4)
|
||||
return { code: "layer-disabled", message: `the W3BS Agentic Desktop Layer on ${host} has agent access DISABLED: enable it from the W3BS tray icon on ${host} (Agent access: on), then run this again` };
|
||||
if (r.status !== 0) return { code: "no-layer", message: `w3bs-desktop status failed on ${host} (exit ${r.status})` };
|
||||
// Someone at the desk holds the input lease: their turn, not ours.
|
||||
const lease = /Input lease:\s*(.+)/i.exec(out)?.[1]?.trim() ?? "free";
|
||||
if (!/^free\b/i.test(lease)) return { code: "busy", message: `the desktop on ${host} is in use (input lease: ${lease.slice(0, 60)}): retry later` };
|
||||
return null;
|
||||
}
|
||||
|
||||
function problemError(p: DesktopProblem): DesktopError {
|
||||
return new DesktopError(p.message, p.code);
|
||||
}
|
||||
|
||||
async function readCapture(host: string, exec: DesktopExec, file: string): Promise<string> {
|
||||
const read = await exec(host, `cat ${file}`, { timeoutMs: 30_000 });
|
||||
return read.status === 0 ? read.stdout.replace(/\r?\n$/, "").trim() : "";
|
||||
}
|
||||
|
||||
/**
|
||||
* Before a roll (no way back), prove the capture path: the agent saves a random
|
||||
* nonce from a scratch page through the same DOM/clipboard path, and the CLI
|
||||
* compares it. A real two-phase capture earlier in the run proves it too.
|
||||
*/
|
||||
export async function captureSelfTest(host: string, exec: DesktopExec, session: DesktopSession): Promise<void> {
|
||||
if (session.captureProven) return;
|
||||
const nonce = randomBytes(18).toString("hex");
|
||||
const file = `~/.cache/rot/selftest-${randomBytes(4).toString("hex")}`;
|
||||
try {
|
||||
const res = await runAgent(host, exec, selfTestPrompt(nonce, file));
|
||||
if (res.code !== "ok") raise(res, "capture self-test");
|
||||
const got = await readCapture(host, exec, file);
|
||||
if (got !== nonce) throw new DesktopError(`capture self-test read back ${got ? `a different value (${got.length} chars)` : "nothing"}: the capture path is not proven`, "bad-capture");
|
||||
session.captureProven = true;
|
||||
} finally {
|
||||
await shred(host, exec, file);
|
||||
}
|
||||
}
|
||||
|
||||
async function runAgent(host: string, exec: DesktopExec, prompt: string): Promise<{ code: string; detail: string }> {
|
||||
const cmd = `${DESKTOP_ENV} claude -p --output-format text --allowedTools ${DESKTOP_TOOLS.join(" ")}`;
|
||||
const r = await exec(host, cmd, { input: prompt, timeoutMs: AGENT_TIMEOUT });
|
||||
const res = parseAgentResult(r.stdout);
|
||||
// The layer's "busy" exit (another holder of the input lease) without a result line.
|
||||
if (res.code === "none" && r.status === 5) return { code: "busy", detail: "input lease held" };
|
||||
if (res.code === "none") {
|
||||
throw new DesktopError(`desktop agent on ${host} gave no result (exit ${r.status}${r.stderr ? `: ${r.stderr.trim().slice(0, 160)}` : ""})`, "agent-failed");
|
||||
}
|
||||
return res;
|
||||
}
|
||||
|
||||
function raise(res: { code: string; detail: string }, what: string): never {
|
||||
const msg = `${what}: ${res.code}${res.detail ? ` (${res.detail})` : ""}`;
|
||||
if (res.code === "needs-login") throw new DesktopError(msg, "needs-login");
|
||||
if (res.code === "busy") throw new DesktopError(`${msg}: a person is using the desktop, retry later`, "busy");
|
||||
if (res.code === "ambiguous") throw new DesktopError(msg, "ambiguous");
|
||||
if (res.code === "not-found") throw new DesktopError(msg, "not-found");
|
||||
throw new DesktopError(msg, "agent-failed");
|
||||
}
|
||||
|
||||
async function shred(host: string, exec: DesktopExec, file: string): Promise<string | undefined> {
|
||||
const r = await exec(host, `shred -u ${file} 2>/dev/null || rm -f ${file}; test ! -e ${file}`, { timeoutMs: 30_000 });
|
||||
return r.status === 0 ? undefined : `remove ${host}:${file} by hand (shred -u)`;
|
||||
}
|
||||
|
||||
/**
|
||||
* A ProviderRotator for one desktop recipe, so rotate-keys runs it through the
|
||||
* same two-phase flow (vaults, --propagate, health, rollback) as API rotators.
|
||||
*/
|
||||
export function desktopRotator(recipeId: string, deps: DesktopDeps): ProviderRotator {
|
||||
const recipe = DESKTOP_RECIPES[recipeId];
|
||||
const exec = deps.exec ?? defaultDesktopExec;
|
||||
const host = deps.host;
|
||||
const session = deps.session ?? {};
|
||||
return {
|
||||
id: `desktop:${recipeId}`,
|
||||
title: recipe ? `${recipe.title} (desktop ${host})` : recipeId,
|
||||
overlap: recipe?.mode === "two-phase",
|
||||
async preflight(ctx) {
|
||||
if (!recipe) return `unknown desktop recipe ${recipeId}`;
|
||||
if (recipe.mode === "report") return `${recipe.title}: report-only (${recipe.revokeNote})`;
|
||||
if (ctx.oldValue.length < 8) return "the old value is too short to identify by its last 4 characters";
|
||||
if (recipe.mode === "roll" && !deps.allowRoll)
|
||||
return `${recipe.title} rolls in place (the old key dies at once): pass --allow-roll to let the desktop agent change it (a capture self-test runs first)`;
|
||||
const p = await desktopStatus(host, exec, session);
|
||||
// A person at the desk is a wait, not a todo: the caller reports it as busy.
|
||||
if (p?.code === "busy") throw problemError(p);
|
||||
return p ? p.message : null;
|
||||
},
|
||||
async mint(ctx: RotatorContext): Promise<Minted> {
|
||||
if (!recipe || recipe.mode === "report") throw new DesktopError(`${recipeId} cannot be minted on the desktop`, "agent-failed");
|
||||
const p = await desktopStatus(host, exec, session);
|
||||
if (p) throw problemError(p);
|
||||
if (recipe.mode === "roll") {
|
||||
if (!deps.allowRoll) throw new DesktopError(`${recipe.title} rolls in place: needs --allow-roll`, "roll-refused");
|
||||
await captureSelfTest(host, exec, session);
|
||||
}
|
||||
const id = jobId(ctx.key);
|
||||
const file = `~/.cache/rot/${id}`;
|
||||
const oldTail = tail(ctx.oldValue);
|
||||
const name = `logicsrc ${ctx.key.toLowerCase()} ${ctx.now.toISOString().slice(0, 10)}`;
|
||||
let value = "";
|
||||
try {
|
||||
const res = await runAgent(host, exec, createPrompt(recipe, { oldTail, name, file }));
|
||||
if (res.code !== "ok") raise(res, `create ${recipe.title}`);
|
||||
value = await readCapture(host, exec, file);
|
||||
if (!value) throw new DesktopError(`the desktop agent saved nothing to ${host}:${file}`, "bad-capture");
|
||||
if (value === ctx.oldValue) throw new DesktopError("the captured key is the OLD key (the agent copied the wrong one)", "bad-capture");
|
||||
if (/\s/.test(value) || value.length < 16 || (recipe.pattern && !new RegExp(recipe.pattern).test(value))) {
|
||||
throw new DesktopError(`the captured value (${value.length} chars) does not look like a ${recipe.title}`, "bad-capture");
|
||||
}
|
||||
session.captureProven = true;
|
||||
} catch (err) {
|
||||
await shred(host, exec, file);
|
||||
// A key may have been created before the failure: say so, with its name, never its value.
|
||||
if (err instanceof DesktopError && err.code === "bad-capture") err.message += `; delete the key named "${name}" at ${recipe.url} if it was created`;
|
||||
throw err;
|
||||
}
|
||||
const newTail = tail(value);
|
||||
return {
|
||||
value,
|
||||
state: { desktopKeyName: name, desktopTail: newTail },
|
||||
async revokeOld() {
|
||||
try {
|
||||
if (recipe.mode === "roll") return undefined; // the roll already killed it
|
||||
if (!recipe.revoke) return `${recipe.title}: ${recipe.revokeNote ?? "revoke the old key by hand"} (old key ends in ${oldTail})`;
|
||||
if (newTail === oldTail) return `old and new ${recipe.title}s both end in ${oldTail}: revoke the old one by hand at ${recipe.url} (keep "${name}")`;
|
||||
const res = await runAgent(host, exec, revokePrompt(recipe, { tail: oldTail, keepTail: newTail }));
|
||||
if (res.code === "ok") return undefined;
|
||||
return `revoking the old ${recipe.title} (ends in ${oldTail}) failed on the desktop (${res.code}${res.detail ? `: ${res.detail}` : ""}): it is still live, delete it at ${recipe.url}`;
|
||||
} finally {
|
||||
const left = await shred(host, exec, file);
|
||||
if (left) console.error(`Warning: ${left}`);
|
||||
}
|
||||
},
|
||||
async rollback() {
|
||||
const notes: string[] = [];
|
||||
try {
|
||||
if (recipe.mode === "roll") {
|
||||
notes.push(`${recipe.title} cannot be changed back: the new key is live, keep it and finish redeploying the consumers`);
|
||||
} else if (recipe.revoke && newTail !== oldTail) {
|
||||
const res = await runAgent(host, exec, revokePrompt(recipe, { tail: newTail, keepTail: oldTail })).catch((e: Error) => ({ code: "error", detail: e.message }));
|
||||
if (res.code !== "ok") notes.push(`delete the new ${recipe.title} "${name}" (ends in ${newTail}) at ${recipe.url} by hand`);
|
||||
} else {
|
||||
notes.push(`delete the new ${recipe.title} "${name}" at ${recipe.url} by hand`);
|
||||
}
|
||||
} finally {
|
||||
const left = await shred(host, exec, file);
|
||||
if (left) notes.push(left);
|
||||
}
|
||||
return notes.length ? notes.join("; ") : undefined;
|
||||
}
|
||||
};
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
/** Report-only recipes: look the key up on the desktop, change nothing. */
|
||||
export async function desktopReport(recipeId: string, oldValue: string, deps: DesktopDeps): Promise<string> {
|
||||
const recipe = DESKTOP_RECIPES[recipeId];
|
||||
if (!recipe) return `unknown desktop recipe ${recipeId}`;
|
||||
const exec = deps.exec ?? defaultDesktopExec;
|
||||
const p = await desktopStatus(deps.host, exec, deps.session ?? {});
|
||||
if (p) throw problemError(p);
|
||||
const res = await runAgent(deps.host, exec, reportPrompt(recipe, { oldTail: tail(oldValue) }));
|
||||
if (res.code === "needs-login" || res.code === "busy") raise(res, `report ${recipe.title}`);
|
||||
return `desktop report (${res.code}): ${res.detail || "no detail"}. ${recipe.revokeNote ?? ""}`.trim();
|
||||
}
|
||||
|
|
@ -39,7 +39,7 @@ import { registerKeysCommands } from "./keys.js";
|
|||
import { registerKeyringCommands } from "./keyring-cmd.js";
|
||||
import { sshAgentAction, sshListAction, sshPullAction, sshPushAction } from "./ssh.js";
|
||||
import { credentialsRotateAction } from "./rotate.js";
|
||||
import { teamsRotateKeysAction, teamsRotationAction, teamsRotationSetAction } from "./rotate-keys.js";
|
||||
import { teamsRotateFromQueue, teamsRotateKeysAction, teamsRotationAction, teamsRotationSetAction } from "./rotate-keys.js";
|
||||
import { teamsAuditAction, teamsKeyImportAction, teamsRekeyAction, teamsRotateIdentityAction } from "./hardening.js";
|
||||
import { teamsCleanAction } from "./vault-clean.js";
|
||||
import { boards, tasks } from "./fixtures.js";
|
||||
|
|
@ -957,6 +957,10 @@ teams
|
|||
.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("--desktop <ssh-host>", "W3BS Agentic Desktop Layer host for desktop keys (default: $LOGICSRC_DESKTOP_HOST)")
|
||||
.option("--allow-roll", "let desktop roll recipes run (Cloudflare Global API Key: the old key dies at once; a capture self-test runs first)")
|
||||
.option("--from-queue", "run the rotations queued on app.logicsrc.com (Rotation page / API / MCP) and report back; approved runs write only with --approve here too")
|
||||
.option("--max-runs <n>", "with --from-queue: stop after n runs")
|
||||
.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(
|
||||
|
|
@ -974,6 +978,15 @@ 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.
|
||||
|
||||
Desktop rotators (method desktop): openai, elevenlabs, brave-search, civitai,
|
||||
cloudflare-global-api-key (roll: --allow-roll), anthropic + claude-oauth
|
||||
(report-only). An agent on a W3BS Agentic Desktop Layer host (--desktop bonita)
|
||||
creates the new key in the layer's agent browser, the CLI reads it over ssh,
|
||||
writes the vaults, propagates, and only then has the agent revoke the old key.
|
||||
A login wall comes back needs-login, a person at the desk busy: the rest go on.
|
||||
logicsrc teams rotate-keys profullstack --key OPENAI_API_KEY --desktop bonita --propagate (dry run)
|
||||
logicsrc teams rotate-keys profullstack --from-queue --desktop bonita --propagate --approve
|
||||
Runbook: https://logicsrc.com/docs/rotation
|
||||
|
||||
Values never print. The same value stored in other vaults (same fingerprint) is
|
||||
|
|
@ -982,7 +995,28 @@ After rotating: redeploy the consumers, install new SSH public keys, revoke the
|
|||
`
|
||||
)
|
||||
.action(async (slug, project, env, options) => {
|
||||
const common = {
|
||||
approve: Boolean(options.approve),
|
||||
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),
|
||||
desktop: options.desktop,
|
||||
allowRoll: Boolean(options.allowRoll)
|
||||
};
|
||||
if (options.fromQueue) {
|
||||
if (project || env || options.key || options.setFromStdin) throw new Error("--from-queue takes its keys, project and env from each queued run.");
|
||||
const reports = await teamsRotateFromQueue(slug, { ...common, maxRuns: options.maxRuns === undefined ? undefined : Number(options.maxRuns) }, {}, join(homedir(), "www"));
|
||||
if (options.format !== "table") print(reports.map(({ results: _r, ...r }) => r), options.format as OutputFormat);
|
||||
if (reports.some((r) => r.status === "failed")) process.exitCode = 1;
|
||||
return;
|
||||
}
|
||||
await teamsRotateKeysAction(slug, { project, env, keys: options.key }, {
|
||||
desktop: options.desktop,
|
||||
allowRoll: Boolean(options.allowRoll),
|
||||
approve: Boolean(options.approve),
|
||||
setFromStdin: Boolean(options.setFromStdin),
|
||||
format: options.format as OutputFormat,
|
||||
|
|
|
|||
|
|
@ -26,6 +26,8 @@ import {
|
|||
type RotationSpec
|
||||
} from "./rotation-catalog.js";
|
||||
import { ROTATORS, defaultRun, rewriteUrls, type Minted, type ProviderRotator, type RotatorContext } from "./rotators.js";
|
||||
import { DesktopError, desktopHost, desktopReport, desktopRotator, type DesktopExec, type DesktopSession } from "./desktop-rotator.js";
|
||||
import { DESKTOP_RECIPES } from "./desktop-recipes.js";
|
||||
import { dev2Ops, findConsumers, inBatches, restoreBackup, rewriteEnvFile, type SiteOps } from "./propagate.js";
|
||||
|
||||
/**
|
||||
|
|
@ -233,6 +235,10 @@ export interface RotateKeysOptions {
|
|||
excludeSites?: string[];
|
||||
/** Unattended mode: skip values read by more sites than this (default 5). */
|
||||
maxSites?: number;
|
||||
/** ssh host of a W3BS Agentic Desktop Layer for `method: desktop` keys (else LOGICSRC_DESKTOP_HOST). */
|
||||
desktop?: string;
|
||||
/** Let desktop roll recipes (old key dies on create, e.g. Cloudflare Global API Key) run. */
|
||||
allowRoll?: boolean;
|
||||
}
|
||||
|
||||
interface KeyPair {
|
||||
|
|
@ -317,7 +323,7 @@ export interface ConsumerReport {
|
|||
export interface RotationResult {
|
||||
key: string;
|
||||
method: string;
|
||||
status: "rotated" | "would-rotate" | "todo" | "failed" | "rolled-back" | "skipped" | "covered";
|
||||
status: "rotated" | "would-rotate" | "todo" | "failed" | "rolled-back" | "skipped" | "covered" | "needs-login" | "busy";
|
||||
/** Every vault:key holding the old value. */
|
||||
vaults?: string[];
|
||||
written: string[];
|
||||
|
|
@ -342,12 +348,18 @@ async function readStdin(): Promise<string> {
|
|||
}
|
||||
|
||||
/** Why the unattended job leaves this one to a person, or null when it may rotate it. */
|
||||
export function scheduledBlock(p: PlannedRotation): string | null {
|
||||
export function scheduledBlock(p: PlannedRotation, ctx: { desktop?: string } = {}): 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 === "desktop") {
|
||||
const r = DESKTOP_RECIPES[spec.recipe ?? ""];
|
||||
if (!r) return `unknown desktop recipe ${spec.recipe}`;
|
||||
if (!ctx.desktop) return "a desktop rotation: run it with --desktop <ssh-host> (or LOGICSRC_DESKTOP_HOST)";
|
||||
return r.mode === "two-phase" ? null : `${r.title} has no overlap window`;
|
||||
}
|
||||
if (spec.method === "provider") {
|
||||
const r = ROTATORS[spec.provider ?? ""];
|
||||
if (!r) return `unknown rotator ${spec.provider}`;
|
||||
|
|
@ -390,6 +402,8 @@ function crontabText(): string {
|
|||
|
||||
export interface RotateDeps {
|
||||
ops?: SiteOps;
|
||||
/** Runs commands on the desktop host (tests: a fake ssh). */
|
||||
desktopExec?: DesktopExec;
|
||||
fetch?: typeof fetch;
|
||||
now?: Date;
|
||||
env?: Record<string, string | undefined>;
|
||||
|
|
@ -438,7 +452,7 @@ async function rotateTwoPhase(
|
|||
targets: Array<{ vault: VaultState; key: string }>,
|
||||
base: RotationResult,
|
||||
options: RotateKeysOptions,
|
||||
deps: Required<Pick<RotateDeps, "ops" | "fetch" | "now" | "env">> & { strayText: () => string[] }
|
||||
deps: Required<Pick<RotateDeps, "ops" | "fetch" | "now" | "env">> & { strayText: () => string[]; rotatorFor: (spec: RotationSpec) => ProviderRotator | undefined }
|
||||
): Promise<RotationResult> {
|
||||
const spec = p.spec!;
|
||||
const first = targets[0]!;
|
||||
|
|
@ -460,9 +474,10 @@ async function rotateTwoPhase(
|
|||
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 minter = spec.method === "provider" || spec.method === "desktop";
|
||||
if (minter) {
|
||||
const r = deps.rotatorFor(spec);
|
||||
if (!r) return { ...base, status: "todo", sites, error: spec.method === "desktop" ? "a desktop rotation needs --desktop <ssh-host> (or LOGICSRC_DESKTOP_HOST)" : `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 };
|
||||
}
|
||||
|
|
@ -475,9 +490,9 @@ async function rotateTwoPhase(
|
|||
|
||||
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}` };
|
||||
if (minter) {
|
||||
rotator = deps.rotatorFor(spec);
|
||||
if (!rotator) return { ...base, status: "todo", error: `unknown rotator ${spec.provider ?? spec.recipe}` };
|
||||
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 {
|
||||
|
|
@ -558,12 +573,22 @@ async function rotateTwoPhase(
|
|||
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 env = depsIn.env ?? process.env;
|
||||
const host = desktopHost(options.desktop, env);
|
||||
// One desktop status check and one capture self-test per run, shared by every desktop key.
|
||||
const session: DesktopSession = {};
|
||||
const rotatorFor = (spec: RotationSpec): ProviderRotator | undefined => {
|
||||
if (spec.method === "provider") return ROTATORS[spec.provider ?? ""];
|
||||
if (spec.method === "desktop" && host) return desktopRotator(spec.recipe ?? "", { host, exec: depsIn.desktopExec, allowRoll: options.allowRoll, session });
|
||||
return undefined;
|
||||
};
|
||||
const deps = {
|
||||
ops: depsIn.ops ?? dev2Ops,
|
||||
fetch: depsIn.fetch ?? fetch,
|
||||
now: depsIn.now ?? new Date(),
|
||||
env: depsIn.env ?? process.env,
|
||||
strayText: depsIn.strayText ?? defaultStrayText
|
||||
env,
|
||||
strayText: depsIn.strayText ?? defaultStrayText,
|
||||
rotatorFor
|
||||
};
|
||||
|
||||
let stdinValue: string | undefined;
|
||||
|
|
@ -602,18 +627,32 @@ export async function teamsRotateKeysAction(slug: string, filter: RotationFilter
|
|||
const targets = siblings(team, p.fingerprint);
|
||||
base.vaults = targets.map((t) => `${t.vault.name}:${t.key}`);
|
||||
if (stdinValue === undefined && !p.automatic) {
|
||||
results.push({ ...base, status: "todo", steps: spec?.steps ?? ["No instructions: add some with logicsrc teams rotation-set."] });
|
||||
const todo: RotationResult = { ...base, status: "todo", steps: spec?.steps ?? ["No instructions: add some with logicsrc teams rotation-set."] };
|
||||
// Report-only desktop keys: with --approve and a desktop host, an agent looks the key up (changes nothing).
|
||||
if (spec?.method === "desktop" && host && options.approve && !options.scheduled && targets.length) {
|
||||
try {
|
||||
todo.note = await desktopReport(spec.recipe ?? "", await readValue(team, targets[0]!.vault, targets[0]!.key), { host, exec: depsIn.desktopExec, session });
|
||||
} catch (err) {
|
||||
if (err instanceof DesktopError && (err.code === "needs-login" || err.code === "busy")) todo.status = err.code;
|
||||
todo.error = (err as Error).message;
|
||||
}
|
||||
}
|
||||
results.push(todo);
|
||||
continue;
|
||||
}
|
||||
if (stdinValue === undefined && spec?.method === "desktop" && !host) {
|
||||
results.push({ ...base, status: "todo", error: "a desktop rotation: pass --desktop <ssh-host> (or set LOGICSRC_DESKTOP_HOST) to let an agent drive it, or follow the steps" });
|
||||
continue;
|
||||
}
|
||||
if (options.scheduled && stdinValue === undefined) {
|
||||
const why = scheduledBlock(p);
|
||||
const why = scheduledBlock(p, { desktop: host });
|
||||
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) {
|
||||
if (!options.approve && !options.propagate && !options.scheduled && spec?.method !== "desktop") {
|
||||
results.push({ ...base, status: "would-rotate" });
|
||||
continue;
|
||||
}
|
||||
|
|
@ -622,7 +661,7 @@ export async function teamsRotateKeysAction(slug: string, filter: RotationFilter
|
|||
continue;
|
||||
}
|
||||
try {
|
||||
if (stdinValue === undefined && (spec?.method === "random" || spec?.method === "provider")) {
|
||||
if (stdinValue === undefined && (spec?.method === "random" || spec?.method === "provider" || spec?.method === "desktop")) {
|
||||
const r = await rotateTwoPhase(team, p, targets, base, options, deps);
|
||||
if (r.status === "rotated" || r.status === "rolled-back") live++;
|
||||
results.push(r);
|
||||
|
|
@ -665,7 +704,9 @@ export async function teamsRotateKeysAction(slug: string, filter: RotationFilter
|
|||
}
|
||||
results.push({ ...base, status: "rotated", written, publicKey: replacement.publicKey });
|
||||
} catch (err) {
|
||||
results.push({ ...base, status: "failed", written: [], error: (err as Error).message });
|
||||
// A login wall or a person at the desk is not a failure: that key waits, the others go on.
|
||||
const status = err instanceof DesktopError && (err.code === "needs-login" || err.code === "busy") ? err.code : "failed";
|
||||
results.push({ ...base, status, written: [], error: (err as Error).message });
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -686,6 +727,8 @@ export async function teamsRotateKeysAction(slug: string, filter: RotationFilter
|
|||
);
|
||||
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;
|
||||
const waiting = results.filter((r) => r.status === "needs-login" || r.status === "busy");
|
||||
if (waiting.length) console.error(`\n${waiting.length} desktop key(s) waiting: ${waiting.map((r) => `${r.key} (${r.status})`).join(", ")}. Sign in in the desktop's agent browser / wait until the desk is free, then run again.`);
|
||||
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 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 {
|
||||
|
|
@ -696,3 +739,88 @@ export async function teamsRotateKeysAction(slug: string, filter: RotationFilter
|
|||
if (results.some((r) => r.status === "failed" || r.status === "rolled-back")) process.exitCode = 1;
|
||||
return results;
|
||||
}
|
||||
|
||||
// ---- the run queue (app.logicsrc.com Rotation page, API, MCP) ----------------------------
|
||||
|
||||
export interface FromQueueOptions extends RotateKeysOptions {
|
||||
/** Stop after this many runs (default: every queued run). */
|
||||
maxRuns?: number;
|
||||
}
|
||||
|
||||
export interface QueueRunReport {
|
||||
id: string;
|
||||
keys: string[];
|
||||
requested: "approved" | "dry run";
|
||||
ran: "approved" | "dry run" | "not run";
|
||||
status: "done" | "failed";
|
||||
summary: string;
|
||||
results: RotationResult[];
|
||||
}
|
||||
|
||||
/**
|
||||
* Run the rotations queued for a team, oldest first: claim one (only one runner
|
||||
* wins it), run rotate-keys with its keys and options, report the outcomes
|
||||
* (never values). An approved run writes only when THIS runner was also given
|
||||
* --approve; otherwise it runs as a dry run and says so. A roll recipe needs
|
||||
* --allow-roll from both the queue and the runner.
|
||||
*/
|
||||
export async function teamsRotateFromQueue(slug: string, options: FromQueueOptions, deps: RotateDeps = {}, defaultPropagate?: string): Promise<QueueRunReport[]> {
|
||||
const { client } = authedClient();
|
||||
const { runs } = await client.listRotationRuns(slug, "queued");
|
||||
const queue = [...runs].sort((a, b) => a.createdAt - b.createdAt).slice(0, options.maxRuns ?? runs.length);
|
||||
const reports: QueueRunReport[] = [];
|
||||
if (!queue.length) console.error(`No queued rotation runs for ${slug}.`);
|
||||
for (const q of queue) {
|
||||
try {
|
||||
await client.claimRotationRun(slug, q.id);
|
||||
} catch (err) {
|
||||
console.error(`Run ${q.id}: not claimed (${(err as Error).message}); another runner has it.`);
|
||||
continue;
|
||||
}
|
||||
const approve = Boolean(q.approve && options.approve);
|
||||
const propagate = options.propagate ?? (q.options.propagate ? defaultPropagate : undefined);
|
||||
let results: RotationResult[] = [];
|
||||
let error: string | undefined;
|
||||
try {
|
||||
results = await teamsRotateKeysAction(
|
||||
slug,
|
||||
{ project: q.project ?? undefined, env: q.env ?? undefined, keys: q.keys },
|
||||
{
|
||||
...options,
|
||||
approve,
|
||||
propagate,
|
||||
desktop: q.options.desktop ?? options.desktop,
|
||||
allowRoll: Boolean(q.options.allowRoll && options.allowRoll),
|
||||
setFromStdin: false,
|
||||
report: undefined
|
||||
},
|
||||
deps
|
||||
);
|
||||
} catch (err) {
|
||||
error = (err as Error).message;
|
||||
}
|
||||
const note = q.approve && !options.approve ? "approved in the queue, but this runner had no --approve: ran as a dry run" : undefined;
|
||||
const failed = Boolean(error) || results.some((r) => r.status === "failed" || r.status === "rolled-back");
|
||||
const reported = await client
|
||||
.reportRotationRun(slug, q.id, { ...(failed && error ? { status: "failed" as const } : {}), ...(error || note ? { error: [error, note].filter(Boolean).join("; ") } : {}), results })
|
||||
.catch((e: Error) => {
|
||||
console.error(`Run ${q.id}: could not report the result (${e.message}).`);
|
||||
return null;
|
||||
});
|
||||
reports.push({
|
||||
id: q.id,
|
||||
keys: q.keys,
|
||||
requested: q.approve ? "approved" : "dry run",
|
||||
ran: error && !results.length ? "not run" : approve ? "approved" : "dry run",
|
||||
status: failed ? "failed" : "done",
|
||||
summary: reported?.run.summary ?? error ?? "",
|
||||
results
|
||||
});
|
||||
if (note) console.error(`Run ${q.id}: ${note}.`);
|
||||
}
|
||||
if (options.report) {
|
||||
writeFileSync(options.report, JSON.stringify({ team: slug, at: new Date().toISOString(), fromQueue: true, runs: reports }, null, 2), { mode: 0o600 });
|
||||
chmodSync(options.report, 0o600);
|
||||
}
|
||||
return reports;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,5 +1,6 @@
|
|||
import { randomBytes, randomInt } from "node:crypto";
|
||||
import { ROTATION_ENTRY_PREFIX, fingerprintValue } from "@logicsrc/plugin-credential-sharing";
|
||||
import { DESKTOP_RECIPES, recipeSteps } from "./desktop-recipes.js";
|
||||
|
||||
/** Every empty value shares this fingerprint; an empty value is nothing to rotate. */
|
||||
export const EMPTY_FINGERPRINT = fingerprintValue("");
|
||||
|
|
@ -28,13 +29,16 @@ export function isoTime(value: unknown): string {
|
|||
* 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.
|
||||
* desktop an agent drives the provider's dashboard in a signed-in browser
|
||||
* on a W3BS Agentic Desktop Layer host (desktop-recipes.ts):
|
||||
* two-phase like provider; needs --desktop <ssh-host>.
|
||||
* manual a person or agent follows `steps` at `url`. Never automatic:
|
||||
* 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" | "provider" | "manual" | "not-secret";
|
||||
export type RotationMethod = "random" | "ssh-keygen" | "command" | "provider" | "desktop" | "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";
|
||||
|
|
@ -49,6 +53,8 @@ export interface RotationSpec {
|
|||
command?: string;
|
||||
/** provider: the rotator id (see rotators.ts). */
|
||||
provider?: string;
|
||||
/** desktop: the dashboard recipe id (see desktop-recipes.ts). */
|
||||
recipe?: string;
|
||||
/** Where to do it (provider dashboard, docs). */
|
||||
url?: string;
|
||||
/** What to do, in order. For manual rotations this is the whole job. */
|
||||
|
|
@ -81,7 +87,7 @@ export function rotationEntryName(key: string): string {
|
|||
return `${ROTATE_PREFIX}${key}`;
|
||||
}
|
||||
|
||||
const METHODS: readonly RotationMethod[] = ["random", "ssh-keygen", "command", "provider", "manual", "not-secret"];
|
||||
const METHODS: readonly RotationMethod[] = ["random", "ssh-keygen", "command", "provider", "desktop", "manual", "not-secret"];
|
||||
const FORMATS: readonly RandomFormat[] = ["hex", "base64", "base64url", "alnum"];
|
||||
|
||||
/** Parse and validate a stored spec. Throws with a message naming the problem. */
|
||||
|
|
@ -101,6 +107,9 @@ export function parseRotationSpec(raw: string): RotationSpec {
|
|||
}
|
||||
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.method === "desktop" && !(typeof v.recipe === "string" && v.recipe in DESKTOP_RECIPES)) {
|
||||
throw new Error(`method desktop needs a recipe: one of ${Object.keys(DESKTOP_RECIPES).join(", ")}`);
|
||||
}
|
||||
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;
|
||||
|
|
@ -114,6 +123,7 @@ export function parseRotationSpec(raw: string): RotationSpec {
|
|||
...(v.length ? { length: v.length as number } : {}),
|
||||
...(typeof v.command === "string" ? { command: v.command } : {}),
|
||||
...(typeof v.provider === "string" ? { provider: v.provider } : {}),
|
||||
...(typeof v.recipe === "string" ? { recipe: v.recipe } : {}),
|
||||
...(typeof v.url === "string" ? { url: v.url } : {}),
|
||||
...(strings(v.steps) ? { steps: strings(v.steps) } : {}),
|
||||
...(strings(v.consumers) ? { consumers: strings(v.consumers) } : {}),
|
||||
|
|
@ -149,6 +159,21 @@ function auto(provider: string, family: string, extra: Partial<RotationSpec> = {
|
|||
return { method: "provider", provider, family, ...extra };
|
||||
}
|
||||
|
||||
/** A dashboard-only key an agent rotates on a W3BS desktop (falls back to these steps by hand). */
|
||||
function desktop(recipe: string): RotationSpec {
|
||||
const r = DESKTOP_RECIPES[recipe]!;
|
||||
return {
|
||||
method: "desktop",
|
||||
recipe,
|
||||
owner: "agent",
|
||||
family: r.family,
|
||||
url: r.url,
|
||||
steps: recipeSteps(r),
|
||||
...(r.disruptive ? { disruptive: r.disruptive } : {}),
|
||||
...(r.mode === "report" ? { note: r.revokeNote } : {})
|
||||
};
|
||||
}
|
||||
|
||||
interface CatalogRule {
|
||||
test: RegExp;
|
||||
spec: RotationSpec;
|
||||
|
|
@ -300,8 +325,14 @@ const CATALOG: CatalogRule[] = [
|
|||
// ---- 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" }) },
|
||||
// ---- dashboard-only keys: an agent rotates them on a W3BS desktop (--desktop <host>) ------
|
||||
{ test: /^OPENAI(_[A-Z0-9]+)*_API_KEY$/, spec: desktop("openai") },
|
||||
{ test: /^(ELEVENLABS|ELEVEN_LABS|XI)(_[A-Z0-9]+)*_API_KEY$/, spec: desktop("elevenlabs") },
|
||||
{ test: /^BRAVE(_SEARCH)?(_[A-Z0-9]+)*_API_(KEY|TOKEN)$|^BRAVE_(SEARCH_)?KEY$/, spec: desktop("brave-search") },
|
||||
{ test: /^CIVITAI(_API)?_(KEY|TOKEN)$/, spec: desktop("civitai") },
|
||||
{ test: /^(CLOUDFLARE|CF)_(GLOBAL_)?API_KEY$/, spec: desktop("cloudflare-global-api-key") },
|
||||
{ test: /^ANTHROPIC(_[A-Z0-9]+)*_API_KEY$|^CLAUDE_API_KEY$/, spec: desktop("anthropic") },
|
||||
{ test: /^(CLAUDE_CODE|CLAUDE|ANTHROPIC)_OAUTH_(TOKEN|REFRESH_TOKEN)$/, spec: desktop("claude-oauth") },
|
||||
{ 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" }) },
|
||||
{
|
||||
|
|
@ -334,7 +365,6 @@ const CATALOG: CatalogRule[] = [
|
|||
{ 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" }) },
|
||||
|
|
@ -440,6 +470,7 @@ export function catalogSpec(key: string): RotationSpec | null {
|
|||
/** Automatic = we can produce the new value without a person. */
|
||||
export function isAutomatic(spec: RotationSpec | null): boolean {
|
||||
if (!spec || spec.never) return false;
|
||||
if (spec.method === "desktop") return Boolean(spec.recipe && DESKTOP_RECIPES[spec.recipe] && DESKTOP_RECIPES[spec.recipe]!.mode !== "report");
|
||||
return spec.method === "random" || spec.method === "ssh-keygen" || spec.method === "command" || spec.method === "provider";
|
||||
}
|
||||
|
||||
|
|
|
|||
63
packages/logicsrc-mcp/src/rotation.test.ts
Normal file
63
packages/logicsrc-mcp/src/rotation.test.ts
Normal file
|
|
@ -0,0 +1,63 @@
|
|||
import { describe, expect, it } from "vitest";
|
||||
import { Client } from "@modelcontextprotocol/sdk/client/index.js";
|
||||
import { InMemoryTransport } from "@modelcontextprotocol/sdk/inMemory.js";
|
||||
import { createLogicSrcMcpServer } from "./server.js";
|
||||
|
||||
const text = (r: unknown) => ((r as { content: Array<{ text: string }> }).content[0]?.text ?? "");
|
||||
|
||||
async function connect(o: { cli?: string[][]; fetched?: Array<{ url: string; method: string; body: unknown }> } = {}) {
|
||||
const runCli = async (args: string[]) => {
|
||||
o.cli?.push(args);
|
||||
return { code: 0, stdout: JSON.stringify([{ key: "OPENAI_API_KEY", status: "would-rotate" }]), stderr: "Dry run. Apply with --approve." };
|
||||
};
|
||||
const fetchFn = (async (input: string | URL | Request, init?: RequestInit) => {
|
||||
o.fetched?.push({ url: String(input), method: init?.method ?? "GET", body: init?.body ? JSON.parse(String(init.body)) : undefined });
|
||||
return new Response(JSON.stringify({ ok: true }), { status: 200 });
|
||||
}) as typeof fetch;
|
||||
const [c, s] = InMemoryTransport.createLinkedPair();
|
||||
const server = createLogicSrcMcpServer({ apiKeys: { env: { LOGICSRC_API_KEY: "lsk_person" }, fetch: fetchFn }, rotation: { runCli } });
|
||||
const client = new Client({ name: "t", version: "0.1.0" });
|
||||
await server.connect(s);
|
||||
await client.connect(c);
|
||||
return { client, close: async () => { await client.close(); await server.close(); } };
|
||||
}
|
||||
|
||||
describe("rotation tools", () => {
|
||||
it("rotate_keys is a dry run by default and passes desktop/propagate through to the CLI", async () => {
|
||||
const cli: string[][] = [];
|
||||
const { client, close } = await connect({ cli });
|
||||
const names = (await client.listTools()).tools.map((t) => t.name);
|
||||
expect(names).toEqual(expect.arrayContaining(["rotation_plan", "rotation_set", "rotate_keys", "rotation_runs"]));
|
||||
const out = text(await client.callTool({ name: "rotate_keys", arguments: { team: "profullstack", keys: ["OPENAI_API_KEY"], desktop: "bonita", propagate: true } }));
|
||||
expect(out).toContain("would-rotate");
|
||||
expect(cli[0]).toEqual(["teams", "rotate-keys", "profullstack", "--key", "OPENAI_API_KEY", "--propagate", "--desktop", "bonita", "--format", "json"]);
|
||||
await client.callTool({ name: "rotate_keys", arguments: { team: "profullstack", project: "b1dz", env: "prod", approve: true } });
|
||||
expect(cli[1]).toEqual(["teams", "rotate-keys", "profullstack", "b1dz", "prod", "--approve", "--format", "json"]);
|
||||
await close();
|
||||
});
|
||||
|
||||
it("rejects shell-ish arguments", async () => {
|
||||
const cli: string[][] = [];
|
||||
const { client, close } = await connect({ cli });
|
||||
const r = await client.callTool({ name: "rotate_keys", arguments: { team: "profullstack", desktop: "bonita; rm -rf ~" } });
|
||||
expect((r as { isError?: boolean }).isError).toBe(true);
|
||||
expect(cli).toEqual([]);
|
||||
await close();
|
||||
});
|
||||
|
||||
it("rotation_plan and rotation_set go through the CLI; queue and server plan go to the API", async () => {
|
||||
const cli: string[][] = [];
|
||||
const fetched: Array<{ url: string; method: string; body: unknown }> = [];
|
||||
const { client, close } = await connect({ cli, fetched });
|
||||
await client.callTool({ name: "rotation_plan", arguments: { team: "profullstack", project: "b1dz" } });
|
||||
expect(cli[0]).toEqual(["teams", "rotation", "profullstack", "b1dz", "--format", "json"]);
|
||||
await client.callTool({ name: "rotation_set", arguments: { team: "profullstack", project: "b1dz", env: "prod", key: "OPENAI_API_KEY", spec: { method: "desktop", recipe: "openai" } } });
|
||||
expect(cli[1]).toEqual(["teams", "rotation-set", "profullstack", "b1dz", "prod", "OPENAI_API_KEY", "--json", '{"method":"desktop","recipe":"openai"}', "--output", "json"]);
|
||||
await client.callTool({ name: "rotation_plan", arguments: { team: "profullstack", source: "server", keys: ["A"] } });
|
||||
expect(fetched[0]!.url).toBe("https://app.logicsrc.com/api/credshare/teams/profullstack/rotation?key=A");
|
||||
await client.callTool({ name: "rotate_keys", arguments: { team: "profullstack", keys: ["OPENAI_API_KEY"], queue: true, desktop: "bonita" } });
|
||||
expect(fetched[1]).toMatchObject({ method: "POST", url: "https://app.logicsrc.com/api/credshare/teams/profullstack/rotation/runs", body: { keys: ["OPENAI_API_KEY"], approve: false, desktop: "bonita" } });
|
||||
expect(cli.length).toBe(2);
|
||||
await close();
|
||||
});
|
||||
});
|
||||
215
packages/logicsrc-mcp/src/rotation.ts
Normal file
215
packages/logicsrc-mcp/src/rotation.ts
Normal file
|
|
@ -0,0 +1,215 @@
|
|||
import { spawn } from "node:child_process";
|
||||
import type { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
|
||||
import { z } from "zod";
|
||||
import { DEFAULT_API_URL, type ApiKeyToolsOptions } from "./apikeys.js";
|
||||
|
||||
/**
|
||||
* Key rotation tools, mirroring `logicsrc teams rotation | rotation-set | rotate-keys`.
|
||||
*
|
||||
* Rotating needs the vault keys, which only the person's machine holds (the
|
||||
* server sees ciphertext only), so these tools run the local `logicsrc` CLI
|
||||
* (LOGICSRC_BIN, default `logicsrc`) with --format json and return its JSON.
|
||||
* The CLI never prints a value, and rotate_keys is a DRY RUN unless
|
||||
* `approve: true`. With `queue: true` rotate_keys instead queues a run on
|
||||
* app.logicsrc.com (LOGICSRC_API_KEY) for a runner (`rotate-keys --from-queue`).
|
||||
* `source: "server"` on rotation_plan reads the server's catalog plan over
|
||||
* HTTPS instead of the CLI (no local identity needed; encrypted per-key
|
||||
* entries are then only flagged, not read).
|
||||
*/
|
||||
|
||||
export interface RotationToolsOptions extends ApiKeyToolsOptions {
|
||||
/** Runs the CLI (tests pass a fake). */
|
||||
runCli?: (args: string[], env: NodeJS.ProcessEnv) => Promise<{ code: number | null; stdout: string; stderr: string }>;
|
||||
}
|
||||
|
||||
class ToolError extends Error {}
|
||||
|
||||
const NAME = /^[A-Za-z0-9][A-Za-z0-9_-]{0,62}$/;
|
||||
const KEY = /^[A-Za-z_][A-Za-z0-9_]{0,127}$/;
|
||||
const HOST = /^[A-Za-z0-9._@-]{1,100}$/;
|
||||
|
||||
function defaultRunCli(args: string[], env: NodeJS.ProcessEnv) {
|
||||
return new Promise<{ code: number | null; stdout: string; stderr: string }>((resolve) => {
|
||||
const child = spawn(env.LOGICSRC_BIN || "logicsrc", args, { env, stdio: ["ignore", "pipe", "pipe"] });
|
||||
let stdout = "";
|
||||
let stderr = "";
|
||||
child.stdout.on("data", (d) => (stdout += d));
|
||||
child.stderr.on("data", (d) => (stderr += d));
|
||||
child.on("error", (e) => resolve({ code: null, stdout, stderr: e.message }));
|
||||
child.on("close", (code) => resolve({ code, stdout, stderr }));
|
||||
});
|
||||
}
|
||||
|
||||
const textResult = (text: string, isError = false) => ({ content: [{ type: "text" as const, text }], ...(isError ? { isError: true } : {}) });
|
||||
|
||||
async function guarded(fn: () => Promise<unknown>) {
|
||||
try {
|
||||
const out = await fn();
|
||||
return textResult(typeof out === "string" ? out : JSON.stringify(out, null, 2));
|
||||
} catch (error) {
|
||||
return textResult(error instanceof Error ? error.message : String(error), true);
|
||||
}
|
||||
}
|
||||
|
||||
const check = (re: RegExp, what: string) => (v: string | undefined) => {
|
||||
if (v !== undefined && !re.test(v)) throw new ToolError(`bad ${what}: ${JSON.stringify(v).slice(0, 60)}`);
|
||||
return v;
|
||||
};
|
||||
const team = check(NAME, "team");
|
||||
const proj = check(NAME, "project");
|
||||
const envName = check(NAME, "env");
|
||||
const host = check(HOST, "desktop host");
|
||||
function keys(list: string[] | undefined): string[] {
|
||||
for (const k of list ?? []) check(KEY, "key")(k);
|
||||
return list ?? [];
|
||||
}
|
||||
|
||||
export function registerRotation(server: McpServer, options: RotationToolsOptions = {}): void {
|
||||
const env = options.env ?? process.env;
|
||||
const runCli = options.runCli ?? defaultRunCli;
|
||||
const doFetch = options.fetch ?? fetch;
|
||||
|
||||
async function cli(args: string[]): Promise<unknown> {
|
||||
const r = await runCli(args, env);
|
||||
if (r.code === null) throw new ToolError(`could not run the logicsrc CLI (${r.stderr.trim().slice(0, 200)}). Install it: curl -fsSL https://logicsrc.com/install.sh | sh`);
|
||||
const out = r.stdout.trim();
|
||||
let parsed: unknown;
|
||||
try {
|
||||
parsed = out ? JSON.parse(out) : null;
|
||||
} catch {
|
||||
parsed = undefined;
|
||||
}
|
||||
// stderr carries the CLI's notes (dry-run hints, locked vaults); never values.
|
||||
const notes = r.stderr.trim().split("\n").filter(Boolean).slice(-20);
|
||||
if (r.code !== 0 && parsed === undefined) throw new ToolError(`logicsrc ${args.slice(0, 2).join(" ")} failed (exit ${r.code}): ${notes.join(" | ").slice(0, 600)}`);
|
||||
return { exitCode: r.code, result: parsed ?? out, notes };
|
||||
}
|
||||
|
||||
async function api(method: string, path: string, body?: unknown): Promise<unknown> {
|
||||
const token = env.LOGICSRC_API_KEY?.trim();
|
||||
if (!token) throw new ToolError("LOGICSRC_API_KEY is not set: give this MCP server a person's LogicSRC API key (logicsrc keys create <name> --kind user).");
|
||||
const base = (env.LOGICSRC_API || env.LOGICSRC_API_URL || DEFAULT_API_URL).replace(/\/+$/, "");
|
||||
const headers: Record<string, string> = { accept: "application/json", authorization: `Bearer ${token}` };
|
||||
if (body !== undefined) headers["content-type"] = "application/json";
|
||||
const res = await doFetch(`${base}${path}`, { method, headers, body: body === undefined ? undefined : JSON.stringify(body) });
|
||||
const text = await res.text();
|
||||
let parsed: unknown;
|
||||
try { parsed = text ? JSON.parse(text) : undefined; } catch { parsed = undefined; }
|
||||
if (!res.ok) {
|
||||
const message = parsed && typeof parsed === "object" && "error" in parsed ? String((parsed as { error: unknown }).error) : `${res.status} ${res.statusText}`;
|
||||
throw new ToolError(`${method} ${path} failed (${res.status}): ${message}`);
|
||||
}
|
||||
return parsed;
|
||||
}
|
||||
|
||||
const scope = {
|
||||
team: z.string().describe("Team slug, e.g. profullstack"),
|
||||
project: z.string().optional().describe("Only this project"),
|
||||
env: z.string().optional().describe("Only this environment (prod, staging, ...)"),
|
||||
keys: z.array(z.string()).optional().describe("Only these key names")
|
||||
};
|
||||
const positional = (a: { team: string; project?: string; env?: string }) => [team(a.team)!, ...(a.project ? [proj(a.project)!] : []), ...(a.project && a.env ? [envName(a.env)!] : [])];
|
||||
const keyArgs = (k: string[]) => (k.length ? ["--key", k.join(",")] : []);
|
||||
|
||||
server.registerTool(
|
||||
"rotation_plan",
|
||||
{
|
||||
title: "Key Rotation Plan",
|
||||
description:
|
||||
"How each secret in a LogicSRC team is rotated: method (random, provider, desktop, ssh-keygen, command, manual), whether it is automatic, owner, steps, url, consumers, which vaults hold the value, last rotated. Never returns values. Default source: the local logicsrc CLI (reads encrypted per-key instructions); source 'server' asks app.logicsrc.com (catalog only, needs LOGICSRC_API_KEY).",
|
||||
inputSchema: { ...scope, source: z.enum(["cli", "server"]).optional() },
|
||||
annotations: { readOnlyHint: true, openWorldHint: true }
|
||||
},
|
||||
async (a) =>
|
||||
guarded(async () => {
|
||||
const k = keys(a.keys);
|
||||
if (a.source === "server") {
|
||||
const qs = new URLSearchParams(Object.entries({ project: proj(a.project), env: envName(a.env), key: k.join(",") || undefined }).filter((e): e is [string, string] => Boolean(e[1]))).toString();
|
||||
return api("GET", `/api/credshare/teams/${encodeURIComponent(team(a.team)!)}/rotation${qs ? `?${qs}` : ""}`);
|
||||
}
|
||||
return cli(["teams", "rotation", ...positional(a), ...keyArgs(k), "--format", "json"]);
|
||||
})
|
||||
);
|
||||
|
||||
server.registerTool(
|
||||
"rotation_set",
|
||||
{
|
||||
title: "Set Key Rotation Instructions",
|
||||
description:
|
||||
"Store rotation instructions for one key as its encrypted __ROTATE__<KEY> entry (logicsrc teams rotation-set). spec is the JSON spec: {method, url?, steps?, consumers?, note?, provider?, recipe?, format?, length?, command?}. A wallet, signing or banned-provider key can never be made automatic.",
|
||||
inputSchema: {
|
||||
team: z.string(),
|
||||
project: z.string(),
|
||||
env: z.string(),
|
||||
key: z.string(),
|
||||
spec: z.record(z.string(), z.unknown()).describe("The rotation spec, e.g. {\"method\":\"desktop\",\"recipe\":\"openai\"}")
|
||||
},
|
||||
annotations: { destructiveHint: false, openWorldHint: true }
|
||||
},
|
||||
async (a) =>
|
||||
guarded(async () => {
|
||||
check(KEY, "key")(a.key);
|
||||
return cli(["teams", "rotation-set", team(a.team)!, proj(a.project)!, envName(a.env)!, a.key, "--json", JSON.stringify(a.spec), "--output", "json"]);
|
||||
})
|
||||
);
|
||||
|
||||
server.registerTool(
|
||||
"rotate_keys",
|
||||
{
|
||||
title: "Rotate Keys",
|
||||
description:
|
||||
"Rotate secret values (logicsrc teams rotate-keys). DRY RUN unless approve is true. propagate rewrites, restarts and health-checks consumer sites (rolls back on failure). desktop names a W3BS Agentic Desktop Layer ssh host for dashboard-only keys (OpenAI, ElevenLabs, Brave, Civitai; Cloudflare Global API Key also needs allowRoll). queue: true queues the run on app.logicsrc.com for a runner (logicsrc teams rotate-keys --from-queue) instead of running it here. Results name keys, vaults, sites and statuses, never values.",
|
||||
inputSchema: {
|
||||
...scope,
|
||||
approve: z.boolean().optional().describe("Write new values. Default false (dry run)."),
|
||||
propagate: z.boolean().optional(),
|
||||
desktop: z.string().optional().describe("ssh host of a W3BS desktop, e.g. bonita"),
|
||||
allowRoll: z.boolean().optional(),
|
||||
max: z.number().int().positive().optional().describe("Stop after n live rotations"),
|
||||
queue: z.boolean().optional().describe("Queue on app.logicsrc.com instead of running locally")
|
||||
},
|
||||
annotations: { destructiveHint: true, openWorldHint: true }
|
||||
},
|
||||
async (a) =>
|
||||
guarded(async () => {
|
||||
const k = keys(a.keys);
|
||||
host(a.desktop);
|
||||
if (a.queue) {
|
||||
if (!k.length) throw new ToolError("queue needs keys: pick the keys to rotate (rotation_plan lists them).");
|
||||
return api("POST", `/api/credshare/teams/${encodeURIComponent(team(a.team)!)}/rotation/runs`, {
|
||||
keys: k,
|
||||
project: proj(a.project),
|
||||
env: envName(a.env),
|
||||
approve: Boolean(a.approve),
|
||||
propagate: Boolean(a.propagate),
|
||||
allowRoll: Boolean(a.allowRoll),
|
||||
...(a.desktop ? { desktop: a.desktop } : {})
|
||||
});
|
||||
}
|
||||
return cli([
|
||||
"teams",
|
||||
"rotate-keys",
|
||||
...positional(a),
|
||||
...keyArgs(k),
|
||||
...(a.approve ? ["--approve"] : []),
|
||||
...(a.propagate ? ["--propagate"] : []),
|
||||
...(a.desktop ? ["--desktop", a.desktop] : []),
|
||||
...(a.allowRoll ? ["--allow-roll"] : []),
|
||||
...(a.max ? ["--max", String(a.max)] : []),
|
||||
"--format",
|
||||
"json"
|
||||
]);
|
||||
})
|
||||
);
|
||||
|
||||
server.registerTool(
|
||||
"rotation_runs",
|
||||
{
|
||||
title: "Key Rotation Runs",
|
||||
description: "Rotation runs queued on app.logicsrc.com and their per-key outcomes (never values). Needs LOGICSRC_API_KEY.",
|
||||
inputSchema: { team: z.string(), status: z.enum(["queued", "running", "done", "failed", "cancelled"]).optional() },
|
||||
annotations: { readOnlyHint: true, openWorldHint: true }
|
||||
},
|
||||
async (a) => guarded(() => api("GET", `/api/credshare/teams/${encodeURIComponent(team(a.team)!)}/rotation/runs${a.status ? `?status=${a.status}` : ""}`))
|
||||
);
|
||||
}
|
||||
|
|
@ -5,6 +5,7 @@ import { registerOpenOntology } from "./openontology.js";
|
|||
import { registerOpenPrd } from "./openprd.js";
|
||||
import { registerApiKeys, type ApiKeyToolsOptions } from "./apikeys.js";
|
||||
import { registerKeyring } from "./keyring.js";
|
||||
import { registerRotation, type RotationToolsOptions } from "./rotation.js";
|
||||
|
||||
const docs = {
|
||||
"communication-accounts": `LogicSRC Communication Accounts defines shared contracts for connecting social and email identities, granting scoped human/agent/plugin access, evaluating policy gates, brokering credentials, and auditing every account action without exposing raw secrets.`,
|
||||
|
|
@ -17,7 +18,7 @@ CommandBoard.run is a hosted product by Profullstack, Inc., built on LogicSRC. L
|
|||
|
||||
const schemaKinds = Object.keys(schemas) as SchemaKind[];
|
||||
|
||||
export function createLogicSrcMcpServer(options: { apiKeys?: ApiKeyToolsOptions } = {}) {
|
||||
export function createLogicSrcMcpServer(options: { apiKeys?: ApiKeyToolsOptions; rotation?: RotationToolsOptions } = {}) {
|
||||
const server = new McpServer(
|
||||
{
|
||||
name: "@profullstack/logicsrc-mcp",
|
||||
|
|
@ -29,7 +30,7 @@ export function createLogicSrcMcpServer(options: { apiKeys?: ApiKeyToolsOptions
|
|||
tools: {},
|
||||
prompts: {}
|
||||
},
|
||||
instructions: "Use this server for LogicSRC standards, schema resources, validation, draft object generation, OpenOntology knowledge (entities, claims, provenance, governed change sets), and OpenPRD product requirements documents, and LogicSRC API keys (list/create/revoke over the credentials app, with LOGICSRC_API_KEY). Treat CommandBoard.run as a reference implementation, not the standards identity. Ontology and PRD write tools propose; they never apply."
|
||||
instructions: "Use this server for LogicSRC standards, schema resources, validation, draft object generation, OpenOntology knowledge (entities, claims, provenance, governed change sets), and OpenPRD product requirements documents, LogicSRC API keys (list/create/revoke over the credentials app, with LOGICSRC_API_KEY), and secret rotation (rotation_plan, rotation_set, rotate_keys, rotation_runs: dry run unless approve, never values). Treat CommandBoard.run as a reference implementation, not the standards identity. Ontology and PRD write tools propose; they never apply."
|
||||
}
|
||||
);
|
||||
|
||||
|
|
@ -159,6 +160,7 @@ export function createLogicSrcMcpServer(options: { apiKeys?: ApiKeyToolsOptions
|
|||
registerOpenPrd(server);
|
||||
registerApiKeys(server, options.apiKeys);
|
||||
registerKeyring(server, options.apiKeys);
|
||||
registerRotation(server, { ...options.apiKeys, ...options.rotation });
|
||||
|
||||
return server;
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue