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
9aba1645de
23 changed files with 2191 additions and 35 deletions
|
|
@ -3,7 +3,7 @@
|
|||
"version": "0.1.1",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"description": "LogicSRC credentials — Express app on Postgres (@profullstack/libsql-pg): auth + end-to-end-encrypted team credential sharing.",
|
||||
"description": "LogicSRC credentials \u2014 Express app on Postgres (@profullstack/libsql-pg): auth + end-to-end-encrypted team credential sharing.",
|
||||
"scripts": {
|
||||
"start": "bun src/server.mjs",
|
||||
"dev": "bun --watch src/server.mjs",
|
||||
|
|
@ -11,6 +11,7 @@
|
|||
"test": "node --test"
|
||||
},
|
||||
"dependencies": {
|
||||
"@logicsrc/cli": "workspace:*",
|
||||
"@profullstack/footer": "0.5.0",
|
||||
"@profullstack/libsql-pg": "^0.1.4",
|
||||
"@profullstack/profile": "0.1.6",
|
||||
|
|
|
|||
157
apps/pwa/src/lib/rotation.mjs
Normal file
157
apps/pwa/src/lib/rotation.mjs
Normal file
|
|
@ -0,0 +1,157 @@
|
|||
// Key rotation: the plan per key and the run queue, for the Rotation page, the
|
||||
// API and the MCP tools.
|
||||
//
|
||||
// The server never sees a value (E2E rule). The plan is computed from what it
|
||||
// does see: key names, value fingerprints and update times, matched against the
|
||||
// same built-in catalog the CLI uses (@logicsrc/cli's rotation-catalog). A key's
|
||||
// own `__ROTATE__<KEY>` entry is encrypted, so the page can only say that one
|
||||
// exists; the CLI, which can decrypt it, is the authority on what it says.
|
||||
import { all } from "../db.mjs";
|
||||
import { planRotations, isoTime } from "@logicsrc/cli/dist/rotation-catalog.js";
|
||||
import { DESKTOP_RECIPES } from "@logicsrc/cli/dist/desktop-recipes.js";
|
||||
|
||||
const ROTATE_PREFIX = "__ROTATE__";
|
||||
|
||||
/** Vault names split the way the CLI does: <project>--<env>. */
|
||||
export function splitVaultName(name) {
|
||||
const i = String(name).lastIndexOf("--");
|
||||
return i > 0 ? { project: name.slice(0, i), env: name.slice(i + 2) } : { project: name, env: "" };
|
||||
}
|
||||
|
||||
/**
|
||||
* The rotation plan for a team: one row per distinct (key, value), like
|
||||
* `logicsrc teams rotation`. `vaultFilter(name)` limits it to vaults the caller
|
||||
* may see (a machine key's scope).
|
||||
*/
|
||||
export async function rotationPlan(teamId, { project, env, keys, vaultFilter = () => true } = {}) {
|
||||
const rows = (await all(
|
||||
`SELECT v.name AS vault, s.name AS key, s.fingerprint, s.updated_at
|
||||
FROM credshare_secrets s JOIN credshare_vaults v ON v.id = s.vault_id
|
||||
WHERE v.team_id = ?`,
|
||||
[teamId]
|
||||
)).filter((r) => vaultFilter(r.vault));
|
||||
const entries = new Set(rows.filter((r) => r.key.startsWith(ROTATE_PREFIX)).map((r) => `${r.vault}\u0000${r.key.slice(ROTATE_PREFIX.length)}`));
|
||||
// Every vault:key per fingerprint across the team (a value pasted under other names counts).
|
||||
const byFp = new Map();
|
||||
for (const r of rows) {
|
||||
if (r.key.startsWith(ROTATE_PREFIX)) continue;
|
||||
byFp.set(r.fingerprint, [...(byFp.get(r.fingerprint) ?? []), `${r.vault}:${r.key}`]);
|
||||
}
|
||||
const inFilter = (vault) => {
|
||||
const p = splitVaultName(vault);
|
||||
return (!project || p.project === project) && (!env || p.env === env);
|
||||
};
|
||||
const wanted = keys?.length ? new Set(keys.map((k) => String(k).toUpperCase())) : null;
|
||||
const plan = planRotations(
|
||||
rows.filter((r) => inFilter(r.vault)).map((r) => ({ vault: r.vault, key: r.key, fingerprint: r.fingerprint, updatedAt: Number(r.updated_at) })),
|
||||
new Map()
|
||||
).filter((p) => !wanted || wanted.has(p.key.toUpperCase()));
|
||||
return plan.map((p) => {
|
||||
const spec = p.spec ?? {};
|
||||
const recipe = spec.method === "desktop" ? DESKTOP_RECIPES[spec.recipe] : null;
|
||||
const everywhere = byFp.get(p.fingerprint) ?? [];
|
||||
return {
|
||||
key: p.key,
|
||||
method: p.method,
|
||||
...(spec.provider ? { provider: spec.provider } : {}),
|
||||
...(recipe ? { recipe: recipe.id, desktopMode: recipe.mode } : {}),
|
||||
automatic: p.automatic,
|
||||
owner: spec.owner ?? null,
|
||||
family: spec.family ?? null,
|
||||
url: spec.url ?? null,
|
||||
steps: spec.steps ?? [],
|
||||
consumers: spec.consumers ?? [],
|
||||
disruptive: spec.disruptive ?? null,
|
||||
never: Boolean(spec.never),
|
||||
note: spec.note ?? null,
|
||||
vaults: p.vaults,
|
||||
vaultCount: everywhere.length || p.vaults.length,
|
||||
alsoIn: everywhere.filter((vk) => !p.vaults.some((v) => vk === `${v}:${p.key}`)),
|
||||
lastRotated: isoTime(p.oldestUpdate),
|
||||
// The key's own encrypted instructions override the catalog; only the CLI can read them.
|
||||
hasEntry: p.vaults.some((v) => entries.has(`${v}\u0000${p.key}`))
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
// ---- runs ------------------------------------------------------------------------------
|
||||
|
||||
const KEY_NAME = /^[A-Za-z_][A-Za-z0-9_]{0,127}$/;
|
||||
const HOST = /^[A-Za-z0-9._@-]{1,100}$/;
|
||||
const RESULT_STATUSES = new Set(["rotated", "would-rotate", "todo", "failed", "rolled-back", "skipped", "covered", "needs-login", "busy"]);
|
||||
|
||||
export class RotationRunError extends Error {}
|
||||
|
||||
/** Validate a queue request. Throws RotationRunError with a message for the caller. */
|
||||
export function parseRunRequest(body = {}) {
|
||||
const keys = [...new Set((Array.isArray(body.keys) ? body.keys : String(body.keys ?? "").split(/[\s,]+/)).map((k) => String(k).trim()).filter(Boolean))];
|
||||
if (!keys.length) throw new RotationRunError("Pick at least one key to rotate.");
|
||||
if (keys.length > 200) throw new RotationRunError("At most 200 keys per run.");
|
||||
const bad = keys.find((k) => !KEY_NAME.test(k));
|
||||
if (bad) throw new RotationRunError(`Not a key name: ${bad.slice(0, 60)}`);
|
||||
const desktop = body.desktop ? String(body.desktop).trim() : "";
|
||||
if (desktop && !HOST.test(desktop)) throw new RotationRunError("desktop must be an ssh host alias");
|
||||
const name = (v) => (v ? String(v).trim() : "") || null;
|
||||
const project = name(body.project);
|
||||
const env = name(body.env);
|
||||
for (const v of [project, env]) if (v && !/^[a-z0-9][a-z0-9-]{0,62}$/.test(v)) throw new RotationRunError(`Bad project/env name: ${v.slice(0, 60)}`);
|
||||
const truthy = (v) => v === true || v === "1" || v === "on" || v === "true";
|
||||
return {
|
||||
keys,
|
||||
project,
|
||||
env,
|
||||
approve: truthy(body.approve),
|
||||
options: {
|
||||
...(desktop ? { desktop } : {}),
|
||||
...(truthy(body.propagate) ? { propagate: true } : {}),
|
||||
...(truthy(body.allowRoll) ? { allowRoll: true } : {})
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Keep only the fields a runner may report, so a buggy or hostile runner cannot
|
||||
* park arbitrary text (or a value) in the database: statuses, names, short notes.
|
||||
*/
|
||||
export function sanitizeResults(results) {
|
||||
if (!Array.isArray(results)) return [];
|
||||
const str = (v, n = 300) => (typeof v === "string" ? v.slice(0, n) : undefined);
|
||||
const names = (v) => (Array.isArray(v) ? v.filter((x) => typeof x === "string").slice(0, 100).map((x) => x.slice(0, 200)) : undefined);
|
||||
return results.slice(0, 500).map((r) => ({
|
||||
key: str(r?.key, 128) ?? "?",
|
||||
method: str(r?.method, 64),
|
||||
status: RESULT_STATUSES.has(r?.status) ? r.status : "failed",
|
||||
vaults: names(r?.vaults),
|
||||
written: names(r?.written),
|
||||
sites: Array.isArray(r?.sites) ? r.sites.slice(0, 50).map((s) => ({ site: str(s?.site, 120), ok: typeof s?.ok === "boolean" ? s.ok : undefined, health: str(s?.health, 120) })) : undefined,
|
||||
note: str(r?.note),
|
||||
error: str(r?.error)
|
||||
}));
|
||||
}
|
||||
|
||||
export function runRow(r) {
|
||||
const parse = (s, d) => { try { return s ? JSON.parse(s) : d; } catch { return d; } };
|
||||
return {
|
||||
id: r.id,
|
||||
keys: parse(r.keys, []),
|
||||
project: r.project ?? null,
|
||||
env: r.env ?? null,
|
||||
approve: Boolean(Number(r.approve)),
|
||||
options: parse(r.options, {}),
|
||||
status: r.status,
|
||||
requestedBy: r.requested_by_email ?? r.requested_by,
|
||||
claimedBy: r.claimed_by ?? null,
|
||||
claimedAt: r.claimed_at ? Number(r.claimed_at) : null,
|
||||
finishedAt: r.finished_at ? Number(r.finished_at) : null,
|
||||
createdAt: Number(r.created_at),
|
||||
summary: r.summary ?? null,
|
||||
results: parse(r.results, null)
|
||||
};
|
||||
}
|
||||
|
||||
/** "3 rotated, 1 todo" from a result list. */
|
||||
export function summarize(results) {
|
||||
const counts = {};
|
||||
for (const r of results) counts[r.status] = (counts[r.status] ?? 0) + 1;
|
||||
return Object.entries(counts).map(([k, n]) => `${n} ${k}`).join(", ") || "nothing";
|
||||
}
|
||||
26
apps/pwa/src/migrations-pg/010_rotation_runs.sql
Normal file
26
apps/pwa/src/migrations-pg/010_rotation_runs.sql
Normal file
|
|
@ -0,0 +1,26 @@
|
|||
-- Postgres copy of migrations/010_rotation_runs.sql (INTEGER -> bigint). Additive only.
|
||||
-- Key rotation runs queued from the Rotation page (or the API / MCP) and
|
||||
-- executed by a CLI or agent with `logicsrc teams rotate-keys --from-queue`.
|
||||
--
|
||||
-- The server never sees a secret value (E2E rule): a run records WHICH keys to
|
||||
-- rotate and how (dry run or approved, desktop host, propagate), and later the
|
||||
-- runner's per-key outcome (statuses, vault and site names, errors), never a
|
||||
-- value. Additive only.
|
||||
CREATE TABLE IF NOT EXISTS credshare_rotation_runs (
|
||||
id TEXT PRIMARY KEY,
|
||||
team_id TEXT NOT NULL REFERENCES credshare_teams(id) ON DELETE CASCADE,
|
||||
requested_by TEXT NOT NULL REFERENCES users(id),
|
||||
keys TEXT NOT NULL, -- JSON array of key names
|
||||
project TEXT,
|
||||
env TEXT,
|
||||
approve bigint NOT NULL DEFAULT 0, -- 0 = dry run
|
||||
options TEXT, -- JSON: { desktop?, propagate?, allowRoll? }
|
||||
status TEXT NOT NULL DEFAULT 'queued', -- queued | running | done | failed | cancelled
|
||||
claimed_by TEXT, -- api key id or user id of the runner
|
||||
claimed_at bigint,
|
||||
finished_at bigint,
|
||||
summary TEXT,
|
||||
results TEXT, -- JSON array of per-key results (never values)
|
||||
created_at bigint NOT NULL
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS idx_rotation_runs_team ON credshare_rotation_runs(team_id, status, created_at);
|
||||
25
apps/pwa/src/migrations/010_rotation_runs.sql
Normal file
25
apps/pwa/src/migrations/010_rotation_runs.sql
Normal file
|
|
@ -0,0 +1,25 @@
|
|||
-- Key rotation runs queued from the Rotation page (or the API / MCP) and
|
||||
-- executed by a CLI or agent with `logicsrc teams rotate-keys --from-queue`.
|
||||
--
|
||||
-- The server never sees a secret value (E2E rule): a run records WHICH keys to
|
||||
-- rotate and how (dry run or approved, desktop host, propagate), and later the
|
||||
-- runner's per-key outcome (statuses, vault and site names, errors), never a
|
||||
-- value. Additive only.
|
||||
CREATE TABLE IF NOT EXISTS credshare_rotation_runs (
|
||||
id TEXT PRIMARY KEY,
|
||||
team_id TEXT NOT NULL REFERENCES credshare_teams(id) ON DELETE CASCADE,
|
||||
requested_by TEXT NOT NULL REFERENCES users(id),
|
||||
keys TEXT NOT NULL, -- JSON array of key names
|
||||
project TEXT,
|
||||
env TEXT,
|
||||
approve INTEGER NOT NULL DEFAULT 0, -- 0 = dry run
|
||||
options TEXT, -- JSON: { desktop?, propagate?, allowRoll? }
|
||||
status TEXT NOT NULL DEFAULT 'queued', -- queued | running | done | failed | cancelled
|
||||
claimed_by TEXT, -- api key id or user id of the runner
|
||||
claimed_at INTEGER,
|
||||
finished_at INTEGER,
|
||||
summary TEXT,
|
||||
results TEXT, -- JSON array of per-key results (never values)
|
||||
created_at INTEGER NOT NULL
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS idx_rotation_runs_team ON credshare_rotation_runs(team_id, status, created_at);
|
||||
|
|
@ -50,7 +50,7 @@ async function actor(req) {
|
|||
* "write" allowed unless the key is read-only
|
||||
* "register" allowed even for a read-only key (its own public key)
|
||||
*/
|
||||
function api(handler, { machine = false } = {}) {
|
||||
export function api(handler, { machine = false } = {}) {
|
||||
return async (req, res) => {
|
||||
const found = await actor(req);
|
||||
if (!found) return res.status(401).json({ error: "Not authenticated, or the API key is revoked or expired. Run: logicsrc login" });
|
||||
|
|
@ -73,7 +73,7 @@ function api(handler, { machine = false } = {}) {
|
|||
};
|
||||
}
|
||||
|
||||
async function requireMember(res, slug, userId, key = null) {
|
||||
export async function requireMember(res, slug, userId, key = null) {
|
||||
const team = await get(`SELECT * FROM credshare_teams WHERE slug = ?`, [slug]);
|
||||
if (!team) { res.status(404).json({ error: `Unknown team: ${slug}` }); return null; }
|
||||
if (isMachine(key) && key.team_id !== team.id) { res.status(403).json({ error: "This API key is scoped to another team." }); return null; }
|
||||
|
|
@ -96,7 +96,7 @@ function auditStatement(ev) {
|
|||
};
|
||||
}
|
||||
|
||||
async function audit(ev) {
|
||||
export async function audit(ev) {
|
||||
const st = auditStatement(ev);
|
||||
await run(st.sql, st.args);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -69,7 +69,7 @@ async function teamCard(team, uid) {
|
|||
<input type="email" name="email" placeholder="teammate@example.com" required style="flex:1">
|
||||
${me.role === "owner" ? `<select name="role" aria-label="Permission" style="width:auto"><option value="member">member</option><option value="admin">admin</option><option value="owner">owner</option></select>` : `<input type="hidden" name="role" value="member">`}
|
||||
<button class="btn">Invite</button></form>` : ""}
|
||||
<div class="label" style="margin:18px 0 6px">Vaults</div>
|
||||
<div class="label" style="margin:18px 0 6px">Vaults <a class="faint" style="margin-left:10px;font-weight:400" href="/teams/${esc(team.slug)}/rotation">Key rotation →</a></div>
|
||||
${vaults.length ? `<table><thead><tr><th>Vault</th><th>Secrets</th><th>Your access</th></tr></thead><tbody>${vaultRows.join("")}</tbody></table>`
|
||||
: `<p class="faint mono" style="font-size:.82rem">No vaults yet — create one from the CLI: <code>logicsrc teams push ${esc(team.slug)} <project> <env></code></p>`}
|
||||
<div class="label" style="margin:18px 0 6px">Recent access <span class="faint">(full trail: <code>logicsrc teams audit ${esc(team.slug)}</code>)</span></div>
|
||||
|
|
|
|||
226
apps/pwa/src/routes/rotation.mjs
Normal file
226
apps/pwa/src/routes/rotation.mjs
Normal file
|
|
@ -0,0 +1,226 @@
|
|||
// Key rotation: the plan per key, and a queue of rotation runs.
|
||||
//
|
||||
// GET /api/credshare/teams/:slug/rotation the plan (never values)
|
||||
// GET /api/credshare/teams/:slug/rotation/runs queued / past runs (?status=queued)
|
||||
// POST /api/credshare/teams/:slug/rotation/runs queue a run {keys, project?, env?, approve?, desktop?, propagate?, allowRoll?}
|
||||
// POST /api/credshare/teams/:slug/rotation/runs/:id/claim a runner takes a queued run
|
||||
// POST /api/credshare/teams/:slug/rotation/runs/:id/result the runner reports per-key outcomes
|
||||
// POST /api/credshare/teams/:slug/rotation/runs/:id/cancel
|
||||
// GET /teams/:slug/rotation the Rotation page
|
||||
//
|
||||
// The server only ever holds ciphertext, so it cannot rotate anything itself: a
|
||||
// run is a request that a CLI or agent executes with
|
||||
// `logicsrc teams rotate-keys <team> --from-queue` (the CLI decrypts, mints,
|
||||
// writes the vaults and redeploys), then reports outcomes, never values.
|
||||
// Queueing an APPROVED run takes an owner or admin; any member may queue a dry run.
|
||||
import { Router } from "express";
|
||||
import { get, all, run } from "../db.mjs";
|
||||
import { id } from "../lib/crypto.mjs";
|
||||
import { page, footer, appBar, esc } from "../lib/html.mjs";
|
||||
import { requireAuth, csrfInput } from "../lib/session.mjs";
|
||||
import { keyCoversVault } from "../lib/apikey.mjs";
|
||||
import { api, requireMember, audit } from "./credshare.mjs";
|
||||
import { rotationPlan, parseRunRequest, sanitizeResults, runRow, summarize, RotationRunError } from "../lib/rotation.mjs";
|
||||
|
||||
export const rotationRouter = Router();
|
||||
|
||||
const isMachine = (key) => key?.kind === "machine";
|
||||
const canApprove = (member) => member.role === "owner" || member.role === "admin";
|
||||
|
||||
async function listRuns(teamId, { status, limit = 50 } = {}) {
|
||||
const rows = await all(
|
||||
`SELECT r.*, u.email AS requested_by_email FROM credshare_rotation_runs r LEFT JOIN users u ON u.id = r.requested_by
|
||||
WHERE r.team_id = ?${status ? " AND r.status = ?" : ""} ORDER BY r.created_at DESC LIMIT ?`,
|
||||
status ? [teamId, status, limit] : [teamId, limit]
|
||||
);
|
||||
return rows.map(runRow);
|
||||
}
|
||||
|
||||
async function queueRun(team, member, user, body, req) {
|
||||
const r = parseRunRequest(body);
|
||||
if (r.approve && !canApprove(member)) throw new RotationRunError("Only a team owner or admin can queue an approved rotation. Queue a dry run instead.");
|
||||
const runId = id();
|
||||
await run(
|
||||
`INSERT INTO credshare_rotation_runs (id, team_id, requested_by, keys, project, env, approve, options, status, created_at) VALUES (?,?,?,?,?,?,?,?,?,?)`,
|
||||
[runId, team.id, user.id, JSON.stringify(r.keys), r.project, r.env, r.approve ? 1 : 0, JSON.stringify(r.options), "queued", Date.now()]
|
||||
);
|
||||
await audit({ req, teamId: team.id, actorUserId: user.id, action: r.approve ? "rotation.queue.approve" : "rotation.queue.dry-run", keyName: r.keys.slice(0, 5).join(",") + (r.keys.length > 5 ? ",..." : "") });
|
||||
return runRow(await get(`SELECT * FROM credshare_rotation_runs WHERE id = ?`, [runId]));
|
||||
}
|
||||
|
||||
rotationRouter.get("/api/credshare/teams/:slug/rotation", api(async (req, res, user, key) => {
|
||||
const ctx = await requireMember(res, req.params.slug, user.id, key); if (!ctx) return;
|
||||
const keys = req.query.key ? String(req.query.key).split(",").filter(Boolean) : undefined;
|
||||
const plan = await rotationPlan(ctx.team.id, {
|
||||
project: req.query.project ? String(req.query.project) : undefined,
|
||||
env: req.query.env ? String(req.query.env) : undefined,
|
||||
keys,
|
||||
vaultFilter: isMachine(key) ? (name) => keyCoversVault(key, name) : undefined
|
||||
});
|
||||
res.json({ team: ctx.team.slug, plan, source: "catalog", note: "Computed from key names and fingerprints with the built-in catalog. Encrypted __ROTATE__ entries (hasEntry) can override it: logicsrc teams rotation shows the decrypted spec." });
|
||||
}, { machine: "read" }));
|
||||
|
||||
rotationRouter.get("/api/credshare/teams/:slug/rotation/runs", api(async (req, res, user, key) => {
|
||||
const ctx = await requireMember(res, req.params.slug, user.id, key); if (!ctx) return;
|
||||
const status = req.query.status ? String(req.query.status) : undefined;
|
||||
res.json({ runs: await listRuns(ctx.team.id, { status, limit: Math.min(Number(req.query.limit) || 50, 200) }) });
|
||||
}, { machine: "read" }));
|
||||
|
||||
rotationRouter.post("/api/credshare/teams/:slug/rotation/runs", api(async (req, res, user, key) => {
|
||||
const ctx = await requireMember(res, req.params.slug, user.id, key); if (!ctx) return;
|
||||
try {
|
||||
res.status(201).json({ run: await queueRun(ctx.team, ctx.member, user, req.body ?? {}, req) });
|
||||
} catch (e) {
|
||||
if (e instanceof RotationRunError) return res.status(400).json({ error: e.message });
|
||||
throw e;
|
||||
}
|
||||
}));
|
||||
|
||||
/** Load a run of this team, or answer 404. */
|
||||
async function teamRun(res, teamId, runId) {
|
||||
const r = await get(`SELECT * FROM credshare_rotation_runs WHERE id = ? AND team_id = ?`, [runId, teamId]);
|
||||
if (!r) res.status(404).json({ error: "No such rotation run." });
|
||||
return r;
|
||||
}
|
||||
|
||||
rotationRouter.post("/api/credshare/teams/:slug/rotation/runs/:id/claim", api(async (req, res, user, key) => {
|
||||
const ctx = await requireMember(res, req.params.slug, user.id, key); if (!ctx) return;
|
||||
const r = await teamRun(res, ctx.team.id, req.params.id); if (!r) return;
|
||||
// Atomic: only one runner wins a queued run.
|
||||
const claimer = key?.id ?? user.id;
|
||||
const upd = await run(`UPDATE credshare_rotation_runs SET status = 'running', claimed_by = ?, claimed_at = ? WHERE id = ? AND status = 'queued'`, [claimer, Date.now(), r.id]);
|
||||
if (!Number(upd.rowsAffected)) return res.status(409).json({ error: `Run is ${r.status}, not queued.` });
|
||||
await audit({ req, teamId: ctx.team.id, actorUserId: user.id, action: "rotation.claim", keyName: r.id });
|
||||
res.json({ run: runRow(await get(`SELECT * FROM credshare_rotation_runs WHERE id = ?`, [r.id])) });
|
||||
}, { machine: "write" }));
|
||||
|
||||
rotationRouter.post("/api/credshare/teams/:slug/rotation/runs/:id/result", api(async (req, res, user, key) => {
|
||||
const ctx = await requireMember(res, req.params.slug, user.id, key); if (!ctx) return;
|
||||
const r = await teamRun(res, ctx.team.id, req.params.id); if (!r) return;
|
||||
const claimer = key?.id ?? user.id;
|
||||
if (r.status !== "running" || r.claimed_by !== claimer) return res.status(409).json({ error: "Only the runner that claimed this run can report it." });
|
||||
const results = sanitizeResults(req.body?.results);
|
||||
const failed = req.body?.status === "failed" || results.some((x) => x.status === "failed" || x.status === "rolled-back");
|
||||
const summary = (typeof req.body?.error === "string" ? `${req.body.error.slice(0, 300)}; ` : "") + summarize(results);
|
||||
await run(`UPDATE credshare_rotation_runs SET status = ?, finished_at = ?, results = ?, summary = ? WHERE id = ?`, [failed ? "failed" : "done", Date.now(), JSON.stringify(results), summary, r.id]);
|
||||
await audit({ req, teamId: ctx.team.id, actorUserId: user.id, action: "rotation.result", keyName: r.id });
|
||||
res.json({ run: runRow(await get(`SELECT * FROM credshare_rotation_runs WHERE id = ?`, [r.id])) });
|
||||
}, { machine: "write" }));
|
||||
|
||||
rotationRouter.post("/api/credshare/teams/:slug/rotation/runs/:id/cancel", api(async (req, res, user, key) => {
|
||||
const ctx = await requireMember(res, req.params.slug, user.id, key); if (!ctx) return;
|
||||
const r = await teamRun(res, ctx.team.id, req.params.id); if (!r) return;
|
||||
if (r.requested_by !== user.id && !canApprove(ctx.member)) return res.status(403).json({ error: "Only who queued it, or an owner/admin, can cancel it." });
|
||||
const upd = await run(`UPDATE credshare_rotation_runs SET status = 'cancelled', finished_at = ? WHERE id = ? AND status = 'queued'`, [Date.now(), r.id]);
|
||||
if (!Number(upd.rowsAffected)) return res.status(409).json({ error: `Run is ${r.status}: only a queued run can be cancelled.` });
|
||||
res.json({ ok: true });
|
||||
}));
|
||||
|
||||
// ---- the page --------------------------------------------------------------------------
|
||||
|
||||
async function pageContext(req) {
|
||||
const team = await get(`SELECT * FROM credshare_teams WHERE slug = ?`, [req.params.slug]);
|
||||
const member = team && await get(`SELECT * FROM credshare_members WHERE team_id = ? AND user_id = ? AND status = 'active'`, [team.id, req.user.id]);
|
||||
return team && member ? { team, member } : null;
|
||||
}
|
||||
|
||||
const when = (ms) => (ms ? new Date(Number(ms)).toISOString().slice(0, 16).replace("T", " ") : "");
|
||||
|
||||
function planTable(plan, selectable) {
|
||||
if (!plan.length) return `<p class="faint mono" style="font-size:.82rem">No secrets to rotate in this filter.</p>`;
|
||||
const row = (p) => {
|
||||
const how = p.method === "desktop" ? `desktop: ${p.recipe}${p.desktopMode && p.desktopMode !== "two-phase" ? ` (${p.desktopMode})` : ""}` : p.method === "provider" ? `provider: ${p.provider}` : p.method;
|
||||
const pill = p.never ? `<span class="pill warn">never auto</span>` : p.automatic ? `<span class="pill on">auto</span>` : `<span class="pill">manual</span>`;
|
||||
const details = [
|
||||
p.note ? `<p>${esc(p.note)}</p>` : "",
|
||||
p.disruptive ? `<p><b>Breaks:</b> ${esc(p.disruptive)}</p>` : "",
|
||||
p.url ? `<p><a href="${esc(p.url)}" rel="noopener noreferrer" target="_blank">${esc(p.url)}</a></p>` : "",
|
||||
p.steps.length ? `<ol>${p.steps.map((s) => `<li>${esc(s)}</li>`).join("")}</ol>` : "",
|
||||
p.consumers.length ? `<p><b>Consumers:</b> ${p.consumers.map(esc).join(", ")}</p>` : "",
|
||||
`<p class="faint mono" style="font-size:.74rem">Vaults: ${p.vaults.map(esc).join(", ")}${p.alsoIn.length ? `; same value also in ${p.alsoIn.map(esc).join(", ")}` : ""}</p>`,
|
||||
p.hasEntry ? `<p class="faint">Has its own encrypted rotation entry: <code>logicsrc teams rotation</code> shows it.</p>` : ""
|
||||
].join("");
|
||||
return `<tr>
|
||||
${selectable ? `<td><input type="checkbox" name="keys" value="${esc(p.key)}" aria-label="Rotate ${esc(p.key)}"${p.never ? " disabled" : ""}></td>` : ""}
|
||||
<td><details><summary><code>${esc(p.key)}</code></summary><div style="font-size:.84rem;padding:6px 0">${details}</div></details></td>
|
||||
<td class="mono" style="font-size:.78rem">${esc(how)}</td>
|
||||
<td>${pill}</td>
|
||||
<td class="mono" style="font-size:.78rem">${esc(p.owner ?? "")}</td>
|
||||
<td>${p.vaultCount}</td>
|
||||
<td class="mono" style="font-size:.76rem;white-space:nowrap">${esc(String(p.lastRotated).slice(0, 10))}</td>
|
||||
</tr>`;
|
||||
};
|
||||
return `<div class="table-scroll"><table><thead><tr>${selectable ? "<th></th>" : ""}<th>Key</th><th>Method</th><th></th><th>Owner</th><th>Vaults</th><th>Last rotated</th></tr></thead><tbody>${plan.map(row).join("")}</tbody></table></div>`;
|
||||
}
|
||||
|
||||
function runsTable(runs, csrf, slug) {
|
||||
if (!runs.length) return `<p class="faint mono" style="font-size:.82rem">No runs yet.</p>`;
|
||||
return `<div class="table-scroll"><table><thead><tr><th>Queued (UTC)</th><th>Keys</th><th>Mode</th><th>Status</th><th>Outcome</th><th></th></tr></thead><tbody>${runs.map((r) => `<tr>
|
||||
<td class="mono" style="font-size:.76rem;white-space:nowrap">${esc(when(r.createdAt))}<div class="faint">${esc(r.requestedBy ?? "")}</div></td>
|
||||
<td class="mono" style="font-size:.76rem">${r.keys.slice(0, 6).map(esc).join(", ")}${r.keys.length > 6 ? ` +${r.keys.length - 6}` : ""}</td>
|
||||
<td class="mono" style="font-size:.76rem">${r.approve ? "approved" : "dry run"}${r.options.desktop ? `, desktop ${esc(r.options.desktop)}` : ""}${r.options.propagate ? ", propagate" : ""}${r.options.allowRoll ? ", allow-roll" : ""}</td>
|
||||
<td><span class="pill ${r.status === "done" ? "on" : r.status === "failed" ? "warn" : ""}">${esc(r.status)}</span></td>
|
||||
<td style="font-size:.8rem">${esc(r.summary ?? "")}${r.results?.length ? `<details><summary class="faint">per key</summary><ul>${r.results.map((x) => `<li><code>${esc(x.key)}</code> ${esc(x.status)}${x.error ? `: ${esc(x.error)}` : x.note ? `: ${esc(x.note)}` : ""}</li>`).join("")}</ul></details>` : ""}</td>
|
||||
<td>${r.status === "queued" ? `<form method="post" action="/teams/${esc(slug)}/rotation/runs/${esc(r.id)}/cancel" style="margin:0">${csrf}<button class="btn compact">Cancel</button></form>` : ""}</td>
|
||||
</tr>`).join("")}</tbody></table></div>`;
|
||||
}
|
||||
|
||||
rotationRouter.get("/teams/:slug/rotation", requireAuth, async (req, res, next) => {
|
||||
const ctx = await pageContext(req);
|
||||
if (!ctx) return next();
|
||||
const project = req.query.project ? String(req.query.project) : undefined;
|
||||
const env = req.query.env ? String(req.query.env) : undefined;
|
||||
const plan = await rotationPlan(ctx.team.id, { project, env });
|
||||
const runs = await listRuns(ctx.team.id, { limit: 25 });
|
||||
const approver = canApprove(ctx.member);
|
||||
const slug = ctx.team.slug;
|
||||
const msg = { queued: "Rotation run queued. A runner picks it up with the command below.", cancelled: "Run cancelled." }[String(req.query.ok || "")];
|
||||
const err = req.query.err ? String(req.query.err).slice(0, 200) : "";
|
||||
const auto = plan.filter((p) => p.automatic).length;
|
||||
const body = `${appBar(req)}
|
||||
<main class="wrap" style="max-width:980px;padding:26px 0 40px">
|
||||
<div class="section-title"><h1 style="font-size:1.6rem">Rotation <span class="faint">/${esc(slug)}</span></h1><span class="count">${plan.length}</span></div>
|
||||
${msg ? `<div class="notice ok">${esc(msg)}</div>` : ""}${err ? `<div class="notice err">${esc(err)}</div>` : ""}
|
||||
<p class="dim" style="font-size:.9rem">How each secret in this team is rotated: ${auto} automatic, ${plan.length - auto} by hand or report-only. Values never reach this server, so a queued run is executed by the CLI or an agent:
|
||||
<code>logicsrc teams rotate-keys ${esc(slug)} --from-queue [--approve] [--propagate] [--desktop <ssh-host>]</code>. The runner's own <code>--approve</code> is needed for approved runs to write anything. Runbook: <a href="https://logicsrc.com/docs/rotation">logicsrc.com/docs/rotation</a>.</p>
|
||||
<form method="get" style="display:flex;gap:8px;margin:10px 0"><input name="project" placeholder="project" value="${esc(project ?? "")}"><input name="env" placeholder="env" value="${esc(env ?? "")}"><button class="btn compact">Filter</button></form>
|
||||
<form method="post" action="/teams/${esc(slug)}/rotation/runs">${csrfInput(req)}
|
||||
${project ? `<input type="hidden" name="project" value="${esc(project)}">` : ""}${env ? `<input type="hidden" name="env" value="${esc(env)}">` : ""}
|
||||
<div class="card"><div class="card-body">${planTable(plan, true)}
|
||||
<div style="display:flex;gap:14px;flex-wrap:wrap;align-items:center;margin-top:12px;font-size:.86rem">
|
||||
<label><input type="checkbox" name="approve" value="1"${approver ? "" : " disabled"}> approved (writes new values${approver ? "" : "; owner/admin only"})</label>
|
||||
<label><input type="checkbox" name="propagate" value="1"> propagate to consumer sites</label>
|
||||
<label>desktop host <input name="desktop" placeholder="bonita" style="width:110px"></label>
|
||||
<label><input type="checkbox" name="allowRoll" value="1"> allow roll (Cloudflare Global API Key: old key dies at once)</label>
|
||||
<button class="btn acid">Queue rotation run</button>
|
||||
</div></div></div>
|
||||
</form>
|
||||
<div class="label" style="margin:22px 0 6px">Runs</div>
|
||||
${runsTable(runs, csrfInput(req), slug)}
|
||||
</main>${footer}`;
|
||||
res.set("Cache-Control", "no-store");
|
||||
res.type("html").send(page({ title: `LogicSRC ▸ ${slug} rotation`, body }));
|
||||
});
|
||||
|
||||
rotationRouter.post("/teams/:slug/rotation/runs", requireAuth, async (req, res, next) => {
|
||||
const ctx = await pageContext(req);
|
||||
if (!ctx) return next();
|
||||
const back = `/teams/${encodeURIComponent(ctx.team.slug)}/rotation`;
|
||||
try {
|
||||
await queueRun(ctx.team, ctx.member, req.user, req.body ?? {}, req);
|
||||
res.redirect(`${back}?ok=queued`);
|
||||
} catch (e) {
|
||||
if (e instanceof RotationRunError) return res.redirect(`${back}?err=${encodeURIComponent(e.message)}`);
|
||||
throw e;
|
||||
}
|
||||
});
|
||||
|
||||
rotationRouter.post("/teams/:slug/rotation/runs/:id/cancel", requireAuth, async (req, res, next) => {
|
||||
const ctx = await pageContext(req);
|
||||
if (!ctx) return next();
|
||||
const back = `/teams/${encodeURIComponent(ctx.team.slug)}/rotation`;
|
||||
const r = await get(`SELECT * FROM credshare_rotation_runs WHERE id = ? AND team_id = ?`, [req.params.id, ctx.team.id]);
|
||||
if (!r || (r.requested_by !== req.user.id && !canApprove(ctx.member))) return res.redirect(`${back}?err=${encodeURIComponent("Not allowed.")}`);
|
||||
await run(`UPDATE credshare_rotation_runs SET status = 'cancelled', finished_at = ? WHERE id = ? AND status = 'queued'`, [Date.now(), r.id]);
|
||||
res.redirect(`${back}?ok=cancelled`);
|
||||
});
|
||||
|
|
@ -10,6 +10,7 @@ import { authRouter } from "./routes/auth.mjs";
|
|||
import { passkeyRouter } from "./routes/passkey.mjs";
|
||||
import { coinpayRouter } from "./routes/coinpay.mjs";
|
||||
import { credshareRouter } from "./routes/credshare.mjs";
|
||||
import { rotationRouter } from "./routes/rotation.mjs";
|
||||
import { apiKeysRouter } from "./routes/apikeys.mjs";
|
||||
import { opencredsRouter } from "./routes/opencreds.mjs";
|
||||
import { keyringRouter } from "./routes/keyring.mjs";
|
||||
|
|
@ -79,6 +80,7 @@ app.use(authRouter); // GET / (+ /auth/login|register|logout)
|
|||
app.use(passkeyRouter);
|
||||
app.use(coinpayRouter);
|
||||
app.use(credshareRouter); // /api/credshare/* (session or lsk_ Bearer)
|
||||
app.use(rotationRouter); // /api/credshare/teams/:slug/rotation* + /teams/:slug/rotation (plan + run queue, never values)
|
||||
app.use(apiKeysRouter); // /api/keys (session or a person's lsk_ key; never a machine key)
|
||||
app.use(opencredsRouter); // /api/opencreds/* — personal vault sync (session or lsk_ Bearer)
|
||||
app.use(keyringShareRouter); // /api/keyring/share: the public-keys share link (session or person key)
|
||||
|
|
|
|||
163
apps/pwa/test/rotation.test.mjs
Normal file
163
apps/pwa/test/rotation.test.mjs
Normal file
|
|
@ -0,0 +1,163 @@
|
|||
// Rotation plan + run queue (routes/rotation.mjs). The server holds only names,
|
||||
// fingerprints and ciphertext: these tests check the plan comes from those, that
|
||||
// a run carries no values, and who may queue, claim, report and cancel.
|
||||
process.env.DATABASE_URL = process.env.PWA_TEST_DATABASE_URL || ":memory:";
|
||||
|
||||
import test from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import { readFileSync } from "node:fs";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { dirname, join } from "node:path";
|
||||
import express from "express";
|
||||
|
||||
const here = dirname(fileURLToPath(import.meta.url));
|
||||
const { db, run, isPostgres } = await import("../src/db.mjs");
|
||||
const { rotationRouter } = await import("../src/routes/rotation.mjs");
|
||||
const { parseRunRequest, sanitizeResults } = await import("../src/lib/rotation.mjs");
|
||||
|
||||
async function migrate() {
|
||||
if (isPostgres) {
|
||||
await db.execute("DROP SCHEMA public CASCADE");
|
||||
await db.execute("CREATE SCHEMA public");
|
||||
}
|
||||
for (const file of ["001_auth.sql", "002_credshare.sql", "005_machine_keys.sql", "007_hardening.sql", "010_rotation_runs.sql"]) {
|
||||
const sql = readFileSync(join(here, "..", "src", isPostgres ? "migrations-pg" : "migrations", file), "utf8");
|
||||
for (const statement of sql.split(/;\s*$/m).map((s) => s.trim()).filter(Boolean)) await db.execute(statement);
|
||||
}
|
||||
}
|
||||
|
||||
async function serve(userId) {
|
||||
const app = express();
|
||||
app.use(express.json());
|
||||
app.use((req, _res, next) => { req.user = { id: userId }; next(); });
|
||||
app.use(rotationRouter);
|
||||
const server = app.listen(0);
|
||||
await new Promise((r) => server.once("listening", r));
|
||||
const base = `http://127.0.0.1:${server.address().port}`;
|
||||
const call = async (method, path, body) => {
|
||||
const res = await fetch(`${base}${path}`, { method, headers: body ? { "content-type": "application/json" } : {}, body: body ? JSON.stringify(body) : undefined });
|
||||
const text = await res.text();
|
||||
return { status: res.status, body: text.startsWith("{") ? JSON.parse(text) : text };
|
||||
};
|
||||
return { call, close: () => new Promise((r) => server.close(r)) };
|
||||
}
|
||||
|
||||
const now = Date.now();
|
||||
await migrate();
|
||||
for (const [uid, email] of [["u_owner", "owner@example.com"], ["u_member", "member@example.com"], ["u_out", "out@example.com"]]) {
|
||||
await run(`INSERT INTO users (id, email, created_at) VALUES (?,?,?)`, [uid, email, now]);
|
||||
}
|
||||
await run(`INSERT INTO credshare_teams (id, slug, name, created_by, created_at) VALUES (?,?,?,?,?)`, ["t1", "acme", "acme", "u_owner", now]);
|
||||
await run(`INSERT INTO credshare_members (id, team_id, user_id, email, role, status, created_at) VALUES (?,?,?,?,?,?,?)`, ["m1", "t1", "u_owner", "owner@example.com", "owner", "active", now]);
|
||||
await run(`INSERT INTO credshare_members (id, team_id, user_id, email, role, status, created_at) VALUES (?,?,?,?,?,?,?)`, ["m2", "t1", "u_member", "member@example.com", "member", "active", now]);
|
||||
for (const v of ["app--prod", "web--prod"]) await run(`INSERT INTO credshare_vaults (id, team_id, name, created_by, created_at) VALUES (?,?,?,?,?)`, [v, "t1", v, "u_owner", now]);
|
||||
const secret = (vault, name, fp) =>
|
||||
run(`INSERT INTO credshare_secrets (vault_id, name, nonce, ciphertext, fingerprint, version, updated_by, updated_at) VALUES (?,?,?,?,?,?,?,?)`, [vault, name, "n", "CIPHERTEXT", fp, 1, "u_owner", now]);
|
||||
await secret("app--prod", "OPENAI_API_KEY", "fp-openai");
|
||||
await secret("web--prod", "OPENAI_KEY_COPY", "fp-openai"); // same value under another name
|
||||
await secret("app--prod", "CRON_SECRET", "fp-cron");
|
||||
await secret("app--prod", "__ROTATE__CRON_SECRET", "fp-entry");
|
||||
await secret("app--prod", "STRIPE_SECRET_KEY", "fp-stripe");
|
||||
await secret("app--prod", "CLOUDFLARE_GLOBAL_API_KEY", "fp-cfg");
|
||||
await secret("app--prod", "PUBLIC_SITE_URL", "fp-url");
|
||||
|
||||
test("plan: catalog methods by key name, vault counts by fingerprint, never ciphertext", async (t) => {
|
||||
const app = await serve("u_member");
|
||||
t.after(app.close);
|
||||
const { status, body } = await app.call("GET", "/api/credshare/teams/acme/rotation");
|
||||
assert.equal(status, 200);
|
||||
const by = Object.fromEntries(body.plan.map((p) => [p.key, p]));
|
||||
assert.equal(by.OPENAI_API_KEY.method, "desktop");
|
||||
assert.equal(by.OPENAI_API_KEY.recipe, "openai");
|
||||
assert.equal(by.OPENAI_API_KEY.automatic, true);
|
||||
assert.equal(by.OPENAI_API_KEY.vaultCount, 2);
|
||||
assert.deepEqual(by.OPENAI_API_KEY.alsoIn, ["web--prod:OPENAI_KEY_COPY"]);
|
||||
assert.equal(by.CLOUDFLARE_GLOBAL_API_KEY.desktopMode, "roll");
|
||||
assert.equal(by.CRON_SECRET.method, "random");
|
||||
assert.equal(by.CRON_SECRET.hasEntry, true);
|
||||
assert.equal(by.STRIPE_SECRET_KEY.never, true);
|
||||
assert.equal(by.PUBLIC_SITE_URL, undefined);
|
||||
assert.equal(by.__ROTATE__CRON_SECRET, undefined);
|
||||
assert.ok(by.OPENAI_API_KEY.steps.length > 3);
|
||||
assert.ok(!JSON.stringify(body).includes("CIPHERTEXT"));
|
||||
assert.ok(!JSON.stringify(body).includes("fp-openai"));
|
||||
});
|
||||
|
||||
test("plan: outsiders get 403", async (t) => {
|
||||
const app = await serve("u_out");
|
||||
t.after(app.close);
|
||||
assert.equal((await app.call("GET", "/api/credshare/teams/acme/rotation")).status, 403);
|
||||
});
|
||||
|
||||
test("queue: a member may queue a dry run but not an approved run", async (t) => {
|
||||
const app = await serve("u_member");
|
||||
t.after(app.close);
|
||||
const denied = await app.call("POST", "/api/credshare/teams/acme/rotation/runs", { keys: ["CRON_SECRET"], approve: true });
|
||||
assert.equal(denied.status, 400);
|
||||
assert.match(denied.body.error, /owner or admin/);
|
||||
const ok = await app.call("POST", "/api/credshare/teams/acme/rotation/runs", { keys: ["CRON_SECRET"], desktop: "bonita" });
|
||||
assert.equal(ok.status, 201);
|
||||
assert.equal(ok.body.run.status, "queued");
|
||||
assert.equal(ok.body.run.approve, false);
|
||||
assert.deepEqual(ok.body.run.options, { desktop: "bonita" });
|
||||
});
|
||||
|
||||
test("queue -> claim (once) -> result (sanitized) -> listed", async (t) => {
|
||||
const owner = await serve("u_owner");
|
||||
t.after(owner.close);
|
||||
const q = await owner.call("POST", "/api/credshare/teams/acme/rotation/runs", { keys: ["OPENAI_API_KEY", "CRON_SECRET"], approve: true, propagate: true });
|
||||
assert.equal(q.status, 201);
|
||||
const runId = q.body.run.id;
|
||||
const queued = await owner.call("GET", "/api/credshare/teams/acme/rotation/runs?status=queued");
|
||||
assert.ok(queued.body.runs.some((r) => r.id === runId));
|
||||
const c1 = await owner.call("POST", `/api/credshare/teams/acme/rotation/runs/${runId}/claim`);
|
||||
assert.equal(c1.status, 200);
|
||||
assert.equal(c1.body.run.status, "running");
|
||||
assert.equal((await owner.call("POST", `/api/credshare/teams/acme/rotation/runs/${runId}/claim`)).status, 409);
|
||||
// Another member cannot report a run they did not claim.
|
||||
const other = await serve("u_member");
|
||||
t.after(other.close);
|
||||
assert.equal((await other.call("POST", `/api/credshare/teams/acme/rotation/runs/${runId}/result`, { results: [] })).status, 409);
|
||||
const done = await owner.call("POST", `/api/credshare/teams/acme/rotation/runs/${runId}/result`, {
|
||||
results: [
|
||||
{ key: "OPENAI_API_KEY", status: "needs-login", error: "login wall", value: "sk-SHOULD-NOT-BE-STORED" },
|
||||
{ key: "CRON_SECRET", status: "rotated", written: ["app--prod:CRON_SECRET"], secret: "nope" }
|
||||
]
|
||||
});
|
||||
assert.equal(done.status, 200);
|
||||
assert.equal(done.body.run.status, "done");
|
||||
assert.match(done.body.run.summary, /1 needs-login, 1 rotated/);
|
||||
assert.ok(!JSON.stringify(done.body).includes("SHOULD-NOT"));
|
||||
assert.ok(!JSON.stringify(done.body).includes("nope"));
|
||||
});
|
||||
|
||||
test("cancel: only queued runs", async (t) => {
|
||||
const app = await serve("u_member");
|
||||
t.after(app.close);
|
||||
const q = await app.call("POST", "/api/credshare/teams/acme/rotation/runs", { keys: "CRON_SECRET" });
|
||||
assert.equal((await app.call("POST", `/api/credshare/teams/acme/rotation/runs/${q.body.run.id}/cancel`)).status, 200);
|
||||
assert.equal((await app.call("POST", `/api/credshare/teams/acme/rotation/runs/${q.body.run.id}/cancel`)).status, 409);
|
||||
});
|
||||
|
||||
test("parseRunRequest rejects junk", () => {
|
||||
assert.throws(() => parseRunRequest({ keys: [] }), /at least one/);
|
||||
assert.throws(() => parseRunRequest({ keys: ["BAD KEY;"] }), /Not a key name/);
|
||||
assert.throws(() => parseRunRequest({ keys: ["A"], desktop: "bonita; rm -rf /" }), /ssh host/);
|
||||
assert.deepEqual(parseRunRequest({ keys: "A, B", approve: "1", allowRoll: "on" }).options, { allowRoll: true });
|
||||
assert.equal(sanitizeResults([{ key: "A", status: "weird" }])[0].status, "failed");
|
||||
});
|
||||
|
||||
test("the Rotation page lists the plan with checkboxes, no values, and the runner command", async (t) => {
|
||||
const app = await serve("u_member");
|
||||
t.after(app.close);
|
||||
const { status, body } = await app.call("GET", "/teams/acme/rotation");
|
||||
assert.equal(status, 200);
|
||||
assert.match(body, /OPENAI_API_KEY/);
|
||||
assert.match(body, /desktop: openai/);
|
||||
assert.match(body, /name="keys" value="CRON_SECRET"/);
|
||||
assert.match(body, /value="STRIPE_SECRET_KEY" aria-label="Rotate STRIPE_SECRET_KEY" disabled/);
|
||||
assert.match(body, /--from-queue/);
|
||||
assert.match(body, /owner\/admin only/); // a member cannot queue an approved run
|
||||
assert.ok(!body.includes("CIPHERTEXT"));
|
||||
assert.ok(!/<script>/.test(body));
|
||||
});
|
||||
3
bun.lock
3
bun.lock
|
|
@ -82,6 +82,7 @@
|
|||
"name": "@logicsrc/pwa",
|
||||
"version": "0.1.1",
|
||||
"dependencies": {
|
||||
"@logicsrc/cli": "workspace:*",
|
||||
"@profullstack/footer": "0.5.0",
|
||||
"@profullstack/libsql-pg": "^0.1.4",
|
||||
"@profullstack/profile": "0.1.6",
|
||||
|
|
@ -147,7 +148,7 @@
|
|||
},
|
||||
"packages/cli": {
|
||||
"name": "@logicsrc/cli",
|
||||
"version": "0.14.0",
|
||||
"version": "0.15.0",
|
||||
"bin": {
|
||||
"logicsrc": "./dist/index.js",
|
||||
},
|
||||
|
|
|
|||
126
docs/rotation.md
126
docs/rotation.md
|
|
@ -60,6 +60,7 @@ new-value-command | logicsrc teams rotate-keys <team> <project> <env> --key NAME
|
|||
| --- | --- | --- |
|
||||
| `random` | the CLI, matching the old value's alphabet and length (min 32) | yes |
|
||||
| `provider` | a built-in rotator calls the provider's API (below) | yes |
|
||||
| `desktop` | an agent drives the provider's dashboard on a W3BS desktop (below) | yes, with `--desktop <host>` |
|
||||
| `ssh-keygen` | the CLI makes an ed25519 pair; you install the public half | value yes, install no |
|
||||
| `command` | your command prints the new value on stdout | yes, with `--approve` |
|
||||
| `manual` | a person or agent follows the steps | no |
|
||||
|
|
@ -132,8 +133,8 @@ health-check, then revoke the old one.
|
|||
Reading and creating tokens needs "API Tokens Write": set
|
||||
`CLOUDFLARE_ADMIN_API_TOKEN`, or give the token that permission.
|
||||
- Revoke: `DELETE /user/tokens/<old id>`.
|
||||
- Not covered: account-owned tokens and the Global API Key. Rotate those in the
|
||||
dashboard (dash.cloudflare.com/profile/api-tokens).
|
||||
- Not covered: account-owned tokens. The Global API Key is a desktop roll
|
||||
(below).
|
||||
|
||||
### CoinPay business API keys (`coinpay-api-key`)
|
||||
|
||||
|
|
@ -182,6 +183,125 @@ health-check, then revoke the old one.
|
|||
`supabase_auth_admin`, `supabase_functions_admin`, `supabase_storage_admin`)
|
||||
and by the stack's own `.env`. See the Supabase section.
|
||||
|
||||
## Desktop rotators: dashboard-only keys
|
||||
|
||||
Some providers only issue keys in their web dashboard. For those the catalog
|
||||
says `method: desktop` with a recipe, and an agent rotates them in a signed-in
|
||||
browser on a [W3BS Agentic Desktop Layer](https://w3bs.org/desktop) host:
|
||||
|
||||
```sh
|
||||
logicsrc teams rotate-keys <team> --key OPENAI_API_KEY --desktop bonita --propagate # dry run: checks the layer
|
||||
logicsrc teams rotate-keys <team> --key OPENAI_API_KEY --desktop bonita --propagate --approve
|
||||
```
|
||||
|
||||
The host is `--desktop <ssh-host>` or `LOGICSRC_DESKTOP_HOST`. Without one, a
|
||||
desktop key comes back `todo` with the same steps written out for a person.
|
||||
|
||||
| recipe | keys | mode |
|
||||
| --- | --- | --- |
|
||||
| `openai` | `OPENAI_API_KEY`, `OPENAI_*_API_KEY` | two-phase |
|
||||
| `elevenlabs` | `ELEVENLABS_API_KEY`, `XI_API_KEY` | two-phase |
|
||||
| `brave-search` | `BRAVE_API_KEY`, `BRAVE_SEARCH_API_KEY` | two-phase |
|
||||
| `civitai` | `CIVITAI_API_KEY`, `CIVITAI_TOKEN` | two-phase |
|
||||
| `cloudflare-global-api-key` | `CLOUDFLARE_GLOBAL_API_KEY`, `CLOUDFLARE_API_KEY`, `CF_API_KEY` | roll (needs `--allow-roll`) |
|
||||
| `anthropic` | `ANTHROPIC_API_KEY` | report-only |
|
||||
| `claude-oauth` | `CLAUDE_CODE_OAUTH_TOKEN` | report-only |
|
||||
|
||||
How one rotation runs:
|
||||
|
||||
1. `ssh <host> w3bs-desktop status`. Agent access must be on. When it is off the
|
||||
key is left as it is and the error says to enable it from the W3BS tray. When
|
||||
the input lease is held (a person is using the desk) the key comes back
|
||||
`busy`.
|
||||
2. The CLI runs `claude -p` on the host, allowed only the w3bs-desktop tools,
|
||||
`w3bs`, `jq`, `wl-paste`/`wl-copy`, `mkdir`, `chmod` and `wc`. The prompt
|
||||
gives the provider URL and the old key's **last four characters**, never a
|
||||
value. The agent works only in the layer's own agent browser (TronBrowser,
|
||||
`w3bs desktop browser launch`; the everyday Firefox is not in its grants),
|
||||
so the provider login has to exist in that browser profile.
|
||||
3. It creates the new key with the same permissions, then writes it from the
|
||||
reveal dialog's DOM straight into `~/.cache/rot/<id>` (mode 600) through a
|
||||
shell pipeline whose output never reaches the agent. The site's Copy button
|
||||
plus `wl-paste` is the fallback (clipboard cleared after).
|
||||
4. The CLI reads that file over ssh into memory, checks it looks like a key of
|
||||
that kind, writes every vault holding the old value, and runs the normal
|
||||
`--propagate` flow: rewrite, restart three at a time, health check.
|
||||
5. Only when every consumer is healthy does a second agent job delete the old
|
||||
key (found by its tail, and only after it has confirmed the new key's tail is
|
||||
listed). Then the CLI shreds the remote file. On any failure before that, the
|
||||
rollback job deletes the NEW key instead and the old value goes back
|
||||
everywhere.
|
||||
|
||||
Outcomes that are not failures: `needs-login` (a login page, 2FA, passkey or
|
||||
captcha: sign in in the agent browser and run it again) and `busy` (a person at
|
||||
the desk). The run carries on with the other keys either way.
|
||||
|
||||
**Roll** (the Cloudflare Global API Key): the provider replaces the key in
|
||||
place, so the old one dies the moment the new one exists and there is nothing to
|
||||
roll back to. It runs only with `--allow-roll`, and only after a capture
|
||||
self-test in the same run: the agent saves a random value from a scratch page
|
||||
through the same capture path and the CLI checks it read back exactly. The
|
||||
weekly job never rolls.
|
||||
|
||||
**Report-only** (Anthropic API keys, Claude OAuth tokens): these keys run the
|
||||
agents themselves. With `--approve` and a desktop host the agent only looks the
|
||||
key up and reports its name and last use; it never creates or revokes one. A
|
||||
person rotates them (`claude setup-token` for an OAuth token), stores the new
|
||||
value with `--set-from-stdin`, then revokes the old one.
|
||||
|
||||
The weekly job leaves desktop keys alone unless it is given `--desktop`; even
|
||||
then only two-phase recipes run unattended.
|
||||
|
||||
## Every surface
|
||||
|
||||
Rotation works the same from the CLI, the credentials app and MCP. Values only
|
||||
ever exist on the machine that runs the CLI: the server stores ciphertext, so
|
||||
the app and MCP plan and queue, and a CLI or agent executes.
|
||||
|
||||
### Credentials app (app.logicsrc.com)
|
||||
|
||||
Each team has a **Rotation** page (`/teams/<team>/rotation`, linked from the
|
||||
team card). It lists every value once, with its method, recipe or provider,
|
||||
owner, steps, URL, consumers, how many vaults hold it, and when it last changed.
|
||||
The plan comes from the built-in catalog by key name; a key with its own
|
||||
encrypted `__ROTATE__` entry is flagged, and `logicsrc teams rotation` shows
|
||||
what that entry says.
|
||||
|
||||
Tick keys and **Queue rotation run**. Any member can queue a dry run; an
|
||||
approved run takes an owner or admin. Options: propagate, desktop host, allow
|
||||
roll. A runner picks the queue up:
|
||||
|
||||
```sh
|
||||
logicsrc teams rotate-keys <team> --from-queue # every queued run, as a dry run
|
||||
logicsrc teams rotate-keys <team> --from-queue --approve --propagate --desktop bonita
|
||||
```
|
||||
|
||||
The runner claims each run (one runner wins it), runs it, and posts back the
|
||||
per-key outcome: statuses, vault and site names, errors, never values. An
|
||||
approved run writes only when the runner also has `--approve`, so a click in a
|
||||
browser alone never changes a secret. A roll needs `--allow-roll` on both the
|
||||
run and the runner.
|
||||
|
||||
API (session or `lsk_` key; machine keys may read and run, not queue):
|
||||
|
||||
| route | what |
|
||||
| --- | --- |
|
||||
| `GET /api/credshare/teams/:slug/rotation` | the plan (`?project=&env=&key=`) |
|
||||
| `GET /api/credshare/teams/:slug/rotation/runs` | runs (`?status=queued`) |
|
||||
| `POST /api/credshare/teams/:slug/rotation/runs` | queue `{keys, project?, env?, approve?, propagate?, desktop?, allowRoll?}` |
|
||||
| `POST .../rotation/runs/:id/claim` | a runner takes a queued run |
|
||||
| `POST .../rotation/runs/:id/result` | the runner reports `{results}` |
|
||||
| `POST .../rotation/runs/:id/cancel` | cancel a queued run |
|
||||
|
||||
### MCP (`logicsrc mcp`)
|
||||
|
||||
| tool | what |
|
||||
| --- | --- |
|
||||
| `rotation_plan` | the plan, from the local CLI (`source: "server"` reads the app's plan) |
|
||||
| `rotation_set` | store a key's `__ROTATE__` spec |
|
||||
| `rotate_keys` | dry run unless `approve: true`; `propagate`, `desktop`, `allowRoll`, `max`; `queue: true` queues it on the app instead |
|
||||
| `rotation_runs` | queued and finished runs |
|
||||
|
||||
## Manual rotations, by family
|
||||
|
||||
Every family below is in the catalog, so every key gets steps in the plan. The
|
||||
|
|
@ -195,7 +315,7 @@ ceremony, a personal login behind 2FA).
|
|||
| turso | agent | `turso db tokens create <db>`; store; redeploy; then `turso db tokens invalidate <db>` (kills every token for that db, so only after all consumers moved) |
|
||||
| github tokens, OAuth apps | agent | github.com/settings/tokens: new fine-grained token with the same repos and permissions. OAuth app secrets: Generate a new client secret (two can be live), switch, delete the old |
|
||||
| google | agent | console.cloud.google.com/apis/credentials: new key with the same API restrictions, or Add secret on the OAuth client, then disable the old |
|
||||
| ai providers | agent | each provider's API keys page (Anthropic console, OpenAI project keys, and so on): create, store, redeploy, delete the old |
|
||||
| ai providers | agent | OpenAI, ElevenLabs, Brave and Civitai are desktop recipes (above); others: each provider's API keys page, create, store, redeploy, delete the old |
|
||||
| twilio | agent | Console > API keys & tokens: create a secondary auth token, switch, promote it |
|
||||
| telnyx, porkbun, storage, social, browser stores | agent | the provider's key page named in the plan |
|
||||
| coinpay OAuth client secrets | agent | our own CoinPay: Developer > OAuth apps > regenerate secret |
|
||||
|
|
|
|||
|
|
@ -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;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -150,6 +150,34 @@ export class TeamApiError extends Error {
|
|||
}
|
||||
}
|
||||
|
||||
export interface RemoteRotationPlanItem {
|
||||
key: string;
|
||||
method: string;
|
||||
provider?: string;
|
||||
recipe?: string;
|
||||
automatic: boolean;
|
||||
owner: string | null;
|
||||
url: string | null;
|
||||
steps: string[];
|
||||
vaults: string[];
|
||||
vaultCount: number;
|
||||
lastRotated: string;
|
||||
hasEntry: boolean;
|
||||
[k: string]: unknown;
|
||||
}
|
||||
|
||||
export interface RemoteRotationRun {
|
||||
id: string;
|
||||
keys: string[];
|
||||
project: string | null;
|
||||
env: string | null;
|
||||
approve: boolean;
|
||||
options: { desktop?: string; propagate?: boolean; allowRoll?: boolean };
|
||||
status: string;
|
||||
createdAt: number;
|
||||
summary: string | null;
|
||||
}
|
||||
|
||||
export class TeamClient {
|
||||
private readonly apiUrl: string;
|
||||
private token?: string;
|
||||
|
|
@ -272,6 +300,24 @@ export class TeamClient {
|
|||
putGrant(vaultId: string, email: string, wrappedDek: string) {
|
||||
return this.request<{ ok: boolean }>("POST", `/vaults/${encodeURIComponent(vaultId)}/grants`, { email, wrappedDek });
|
||||
}
|
||||
// ---- key rotation: plan + run queue (never values) ----
|
||||
rotationPlan(slug: string, query: { project?: string; env?: string; key?: string } = {}) {
|
||||
const qs = new URLSearchParams(Object.entries(query).filter((e): e is [string, string] => Boolean(e[1]))).toString();
|
||||
return this.request<{ team: string; plan: RemoteRotationPlanItem[] }>("GET", `/teams/${encodeURIComponent(slug)}/rotation${qs ? `?${qs}` : ""}`);
|
||||
}
|
||||
listRotationRuns(slug: string, status?: string) {
|
||||
return this.request<{ runs: RemoteRotationRun[] }>("GET", `/teams/${encodeURIComponent(slug)}/rotation/runs${status ? `?status=${encodeURIComponent(status)}` : ""}`);
|
||||
}
|
||||
queueRotationRun(slug: string, body: { keys: string[]; project?: string; env?: string; approve?: boolean; desktop?: string; propagate?: boolean; allowRoll?: boolean }) {
|
||||
return this.request<{ run: RemoteRotationRun }>("POST", `/teams/${encodeURIComponent(slug)}/rotation/runs`, body);
|
||||
}
|
||||
claimRotationRun(slug: string, id: string) {
|
||||
return this.request<{ run: RemoteRotationRun }>("POST", `/teams/${encodeURIComponent(slug)}/rotation/runs/${encodeURIComponent(id)}/claim`);
|
||||
}
|
||||
reportRotationRun(slug: string, id: string, body: { status?: "failed"; error?: string; results: unknown[] }) {
|
||||
return this.request<{ run: RemoteRotationRun }>("POST", `/teams/${encodeURIComponent(slug)}/rotation/runs/${encodeURIComponent(id)}/result`, body);
|
||||
}
|
||||
|
||||
listSecrets(vaultId: string) {
|
||||
return this.request<{ vaultId: string; keyVersion?: number; secrets: RemoteSecret[] }>("GET", `/vaults/${encodeURIComponent(vaultId)}/secrets`);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -84,7 +84,9 @@ export {
|
|||
type RemoteApiKey,
|
||||
type RemoteKeyGrant,
|
||||
type RemoteAuditRow,
|
||||
type CreateApiKeyInput
|
||||
type CreateApiKeyInput,
|
||||
type RemoteRotationPlanItem,
|
||||
type RemoteRotationRun
|
||||
} from "./client.js";
|
||||
export {
|
||||
ensureApiKeyIdentity,
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue