mirror of
https://github.com/profullstack/logicsrc.git
synced 2026-12-01 09:24:46 +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
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