mirror of
https://github.com/profullstack/logicsrc.git
synced 2026-11-29 15:51:52 +00:00
Machine API keys: headless teams pull for deploy boxes and CI (#230)
A person's lsk_ key acts as the person, with one identity key per user. Logging a fresh box in with `login --token` uploaded the box's new keypair as the person's identity and replaced the real one. Machine keys fix that: a key made for a box, scoped to one team (and optionally named vaults), read-only unless --read-write, optionally expiring, with its OWN identity key registered on the key row. A vault key reaches it as a grant sealed to that public key (credshare_key_grants), never through the person. Schema (005_machine_keys, SQLite + Postgres): api_keys gains kind, team_id, vault_scope, read_only (default 0, so existing person keys keep writing), expires_at, public_key; new credshare_key_grants; credshare_audit.actor_key_id. Server: each credshare route declares what a machine key may do (read / write / register); the rest are people-only. Machine keys see only their team and scoped vaults, read their grant from credshare_key_grants (audited as vault:read with the key id), are refused every write when read-only, and cannot mint/list/revoke keys, read /api/me or touch the personal vault. Expired and revoked keys are 401. New GET|POST /api/keys, DELETE /api/keys/:id, and GET|POST|DELETE /api/credshare/vaults/:id/key-grants. A re-key re-seals the machine grants it is given and drops the rest. CLI 0.8.0: `logicsrc keys create|list|revoke` (--team, --vault, --read-only / --read-write, --expires, --out 0600); LOGICSRC_API_KEY and `login --api-key` with a per-key identity in keys/<prefix>.json (0600), generated and registered on first use; `login --token` with a machine key takes that path instead of replacing the person's key; `teams grant … --key <name>`; `credentials rotate` re-seals machine keys. PWA: settings creates machine keys (team, vaults, read-only, expiry); a vault page grants or revokes a machine key in the browser after unlock. MCP: list_api_keys / create_api_key / revoke_api_key over /api/keys with a Bearer LOGICSRC_API_KEY. Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
4df342a064
commit
ade33efd17
35 changed files with 2220 additions and 106 deletions
|
|
@ -1,6 +1,6 @@
|
|||
{
|
||||
"name": "@logicsrc/cli",
|
||||
"version": "0.7.0",
|
||||
"version": "0.8.0",
|
||||
"description": "LogicSRC CLI: every LogicSRC standard and tool as one command.",
|
||||
"type": "module",
|
||||
"main": "./dist/index.js",
|
||||
|
|
|
|||
|
|
@ -30,8 +30,10 @@ import {
|
|||
teamsPullAction,
|
||||
secretsTeamsLinkAction,
|
||||
secretsUpAction,
|
||||
secretsDownAction
|
||||
secretsDownAction,
|
||||
prepareApiKeyAuth
|
||||
} from "./teams.js";
|
||||
import { registerKeysCommands } from "./keys.js";
|
||||
import { sshAgentAction, sshListAction, sshPullAction, sshPushAction } from "./ssh.js";
|
||||
import { credentialsRotateAction } from "./rotate.js";
|
||||
import { boards, tasks } from "./fixtures.js";
|
||||
|
|
@ -111,11 +113,13 @@ program
|
|||
.command("login")
|
||||
.option("--api-url <url>", "LogicSRC credentials app URL (default: $LOGICSRC_API, else the hosted app)")
|
||||
.option("--token <lsk_key>", "Use an existing API key instead of the browser flow (CI)")
|
||||
.option("--api-key <lsk_key>", "Log this box in with a machine API key; it gets its own identity key (never yours)")
|
||||
.option("--reregister", "With --api-key: move a machine key that registered on another box here (drops its grants)")
|
||||
.option("--device", "Force the device-code flow (approve from a browser on another machine)")
|
||||
.option("--web", "Force the loopback browser flow (needs a browser on THIS machine)")
|
||||
.description("Log in via your browser for team credential sharing; registers your device identity key.")
|
||||
.action(async (options) => {
|
||||
await loginAction({ apiUrl: options.apiUrl, token: options.token, device: options.device, web: options.web });
|
||||
await loginAction({ apiUrl: options.apiUrl, token: options.token, apiKey: options.apiKey, reregister: options.reregister, device: options.device, web: options.web });
|
||||
});
|
||||
|
||||
program.command("logout").description("Clear local auth token (keeps your identity key).").action(async () => {
|
||||
|
|
@ -738,6 +742,12 @@ Quick start (<team> is e.g. profullstack; see yours with "logicsrc teams list"):
|
|||
logicsrc teams grant <team> <project> <env> dev@example.com
|
||||
logicsrc teams key your key, to read values in the web app
|
||||
|
||||
Deploy boxes and CI (a machine API key: one team, scoped vaults, read-only, its own identity):
|
||||
logicsrc keys create <name> --team <team> --vault <project>--<env> --out deploy.key
|
||||
LOGICSRC_API_KEY=$(cat deploy.key) logicsrc whoami on the box, once
|
||||
logicsrc teams grant <team> <project> <env> --key <name> from your machine
|
||||
LOGICSRC_API_KEY=$(cat deploy.key) logicsrc teams pull <team> <project> <env> --env .env
|
||||
|
||||
Categories: logicsrc teams categories. Help for one command: logicsrc teams <command> --help
|
||||
`
|
||||
);
|
||||
|
|
@ -892,10 +902,11 @@ teams
|
|||
.argument("<slug>", "Team slug")
|
||||
.argument("<project>", "Project name")
|
||||
.argument("<env>", "Environment name (prod, staging, …)")
|
||||
.argument("<email>", "Teammate email to grant vault access")
|
||||
.argument("[email]", "Teammate email to grant vault access")
|
||||
.option("--key <name>", "Grant one of your machine API keys instead of a person (name, id, or prefix)")
|
||||
.option("--format <format>", "table, json, or markdown", "table")
|
||||
.description("Grant a member decryption access to a vault (re-wraps the vault key to their key).")
|
||||
.action((slug, project, env, email, options) => teamsGrantAction(slug, project, env, email, options.format as OutputFormat));
|
||||
.description("Grant a member, or a machine API key, decryption access to a vault (re-seals the vault key to their key).")
|
||||
.action((slug, project, env, email, options) => teamsGrantAction(slug, project, env, email, options.format as OutputFormat, { key: options.key }));
|
||||
|
||||
teams
|
||||
.command("push")
|
||||
|
|
@ -1172,6 +1183,17 @@ async function runYoloArcade(game: string, repo?: string) {
|
|||
});
|
||||
}
|
||||
|
||||
registerKeysCommands(program);
|
||||
|
||||
// LOGICSRC_API_KEY: prepare the key's identity (first use registers a machine
|
||||
// key's own public key) before any command that talks to the credentials app.
|
||||
const API_KEY_COMMANDS = new Set(["teams", "secrets", "credentials", "whoami", "keys"]);
|
||||
program.hook("preAction", async (_root, actionCommand) => {
|
||||
let top: Command = actionCommand;
|
||||
while (top.parent && top.parent !== program) top = top.parent;
|
||||
if (API_KEY_COMMANDS.has(top.name())) await prepareApiKeyAuth();
|
||||
});
|
||||
|
||||
registerOpenContextCommands(program);
|
||||
registerOpenCredsCommands(program);
|
||||
registerOntologyCommands(program);
|
||||
|
|
|
|||
168
packages/cli/src/keys.ts
Normal file
168
packages/cli/src/keys.ts
Normal file
|
|
@ -0,0 +1,168 @@
|
|||
import { chmodSync, writeFileSync } from "node:fs";
|
||||
import type { Command } from "commander";
|
||||
import { TeamClient, requireAuth, resolveApiUrl, type RemoteApiKey } from "@logicsrc/plugin-credential-sharing";
|
||||
import { print, type OutputFormat } from "./format.js";
|
||||
|
||||
/**
|
||||
* `logicsrc keys create|list|revoke` — API keys, from the terminal.
|
||||
*
|
||||
* The usual one is a MACHINE key for a deploy box or CI: one team, the vaults
|
||||
* you name, read-only unless --read-write, optionally expiring. On the box:
|
||||
*
|
||||
* LOGICSRC_API_KEY=lsk_… logicsrc teams pull <team> <project> <env>
|
||||
*
|
||||
* The first command run with it creates and registers the box's own identity
|
||||
* key; then a member grants it a vault with `logicsrc teams grant … --key <name>`.
|
||||
*/
|
||||
|
||||
function keysClient(): TeamClient {
|
||||
const identity = requireAuth();
|
||||
return new TeamClient({ apiUrl: resolveApiUrl(identity), token: identity.apiToken });
|
||||
}
|
||||
|
||||
const when = (ms: number | null): string => (ms ? new Date(ms).toISOString().slice(0, 10) : "never");
|
||||
|
||||
export function keyRow(k: RemoteApiKey): Record<string, unknown> {
|
||||
return {
|
||||
name: k.name,
|
||||
prefix: `${k.prefix}…`,
|
||||
kind: k.kind,
|
||||
team: k.team ?? "—",
|
||||
vaults: k.kind === "machine" ? (k.vaults?.join(",") || "all") : "—",
|
||||
access: k.kind === "machine" ? (k.readOnly ? "read-only" : "read-write") : "as you",
|
||||
expires: k.expired ? `${when(k.expiresAt)} (expired)` : when(k.expiresAt),
|
||||
identity: k.kind === "machine" ? (k.publicKey ? "registered" : "not used yet") : "—",
|
||||
lastUsed: when(k.lastUsedAt),
|
||||
id: k.id
|
||||
};
|
||||
}
|
||||
|
||||
/** Find one of the caller's keys by id, exact name, or prefix. */
|
||||
export function findKey(keys: RemoteApiKey[], ref: string): RemoteApiKey {
|
||||
const byId = keys.find((k) => k.id === ref);
|
||||
if (byId) return byId;
|
||||
const byName = keys.filter((k) => k.name === ref);
|
||||
if (byName.length === 1) return byName[0]!;
|
||||
if (byName.length > 1) {
|
||||
throw new Error(`${byName.length} keys are named "${ref}" (${byName.map((k) => `${k.prefix}… ${k.id}`).join(", ")}). Use the id.`);
|
||||
}
|
||||
const bare = ref.replace(/…$/, "");
|
||||
const byPrefix = keys.filter((k) => bare.length >= 6 && k.prefix.startsWith(bare));
|
||||
if (byPrefix.length === 1) return byPrefix[0]!;
|
||||
throw new Error(`No API key "${ref}" on your account. See them: logicsrc keys list`);
|
||||
}
|
||||
|
||||
export interface KeysCreateOptions {
|
||||
kind?: string;
|
||||
team?: string;
|
||||
vault?: string[];
|
||||
readOnly?: boolean;
|
||||
readWrite?: boolean;
|
||||
expires?: string;
|
||||
out?: string;
|
||||
format: OutputFormat;
|
||||
}
|
||||
|
||||
export async function keysCreateAction(name: string, options: KeysCreateOptions): Promise<void> {
|
||||
const kind = (options.kind ?? "machine") as "user" | "machine";
|
||||
if (kind !== "user" && kind !== "machine") throw new Error('--kind must be "machine" or "user".');
|
||||
if (options.readOnly && options.readWrite) throw new Error("Pick one of --read-only and --read-write.");
|
||||
if (kind === "machine" && !options.team) {
|
||||
throw new Error("A machine key needs --team <slug> (and usually --vault <project>--<env>). For a key that acts as you, pass --kind user.");
|
||||
}
|
||||
if (kind === "user" && (options.team || options.vault?.length || options.readWrite || options.readOnly)) {
|
||||
throw new Error("--team, --vault, --read-only and --read-write only apply to machine keys; a user key acts as you.");
|
||||
}
|
||||
const client = keysClient();
|
||||
const { key, secret } = await client.createApiKey({
|
||||
name,
|
||||
kind,
|
||||
...(kind === "machine"
|
||||
? { team: options.team, vaults: options.vault ?? [], readOnly: !options.readWrite }
|
||||
: {}),
|
||||
...(options.expires ? { expiresAt: options.expires } : {})
|
||||
});
|
||||
|
||||
// The secret goes ONE place: a 0600 file with --out, else stdout on its own
|
||||
// line (so `> file` captures exactly it). Everything else goes to stderr.
|
||||
if (options.out) {
|
||||
writeFileSync(options.out, `${secret}\n`, { mode: 0o600 });
|
||||
try { chmodSync(options.out, 0o600); } catch { /* no modes on this platform */ }
|
||||
} else {
|
||||
process.stdout.write(`${secret}\n`);
|
||||
}
|
||||
const where = options.out ? `written to ${options.out} (0600)` : "printed above";
|
||||
console.error(`Created ${key.kind} key "${key.name}" (${key.prefix}…), ${where}. It is shown once; the server keeps only a hash.`);
|
||||
if (key.kind === "machine") {
|
||||
const scope = key.vaults?.length ? key.vaults.join(", ") : `every vault in ${key.team}`;
|
||||
console.error(`Scope: team ${key.team}, ${scope}, ${key.readOnly ? "read-only" : "read-write"}, expires ${when(key.expiresAt)}.`);
|
||||
console.error("Next:");
|
||||
console.error(` 1. on the box, once: LOGICSRC_API_KEY=<key> logicsrc whoami (creates and registers its identity)`);
|
||||
console.error(` 2. here, per vault: logicsrc teams grant ${key.team} <project> <env> --key ${key.name}`);
|
||||
console.error(` 3. on the box: LOGICSRC_API_KEY=<key> logicsrc teams pull ${key.team} <project> <env> --env .env`);
|
||||
}
|
||||
if (options.format !== "table") print(keyRow(key), options.format);
|
||||
}
|
||||
|
||||
export async function keysListAction(format: OutputFormat): Promise<void> {
|
||||
const { keys } = await keysClient().listApiKeys();
|
||||
print(keys.length ? keys.map(keyRow) : [{ note: "No API keys. Make a machine key: logicsrc keys create <name> --team <slug> --vault <project>--<env>" }], format);
|
||||
}
|
||||
|
||||
export async function keysRevokeAction(ref: string, format: OutputFormat): Promise<void> {
|
||||
const client = keysClient();
|
||||
const { keys } = await client.listApiKeys();
|
||||
const key = findKey(keys, ref);
|
||||
await client.revokeApiKey(key.id);
|
||||
console.error(`Revoked "${key.name}" (${key.prefix}…). Anything using it now gets a 401, and its vault grants are gone.`);
|
||||
print({ revoked: key.name, id: key.id }, format);
|
||||
}
|
||||
|
||||
const collect = (value: string, previous: string[] = []): string[] => [...previous, ...value.split(",").map((v) => v.trim()).filter(Boolean)];
|
||||
|
||||
export function registerKeysCommands(program: Command): void {
|
||||
const keys = program
|
||||
.command("keys")
|
||||
.description("API keys: machine keys for deploy boxes and CI (create, list, revoke).")
|
||||
.addHelpText(
|
||||
"after",
|
||||
`
|
||||
A machine key reads (or, with --read-write, writes) only the vaults you scope it to,
|
||||
with its own identity key. Headless use on the box:
|
||||
|
||||
logicsrc keys create dev2-deploy --team acme --vault web--prod --expires 90d --out deploy.key
|
||||
LOGICSRC_API_KEY=$(cat deploy.key) logicsrc whoami # once: registers the box's key
|
||||
logicsrc teams grant acme web prod --key dev2-deploy # from a member's machine
|
||||
LOGICSRC_API_KEY=$(cat deploy.key) logicsrc teams pull acme web prod --env .env
|
||||
|
||||
Or store it on the box with: logicsrc login --api-key <key>`
|
||||
);
|
||||
|
||||
keys
|
||||
.command("create")
|
||||
.argument("<name>", "A name for the key (e.g. dev2-deploy)")
|
||||
.option("--team <slug>", "Team the machine key is scoped to (required for a machine key)")
|
||||
.option("--vault <name>", "Vault the key may read, as <project>--<env>; repeat or comma-separate. Default: every vault in the team", collect)
|
||||
.option("--read-only", "Pull only, never push (the default for a machine key)")
|
||||
.option("--read-write", "Also allow pushing to the vaults it is granted")
|
||||
.option("--expires <when>", "30d, 12h, 1y, or a date (2027-01-01). Default: never")
|
||||
.option("--kind <kind>", "machine (default) or user (acts as you, like logicsrc login)", "machine")
|
||||
.option("--out <file>", "Write the secret to this file (0600) instead of stdout")
|
||||
.option("--format <format>", "table, json, or markdown", "table")
|
||||
.description("Create an API key. The secret is shown once.")
|
||||
.action((name, options) => keysCreateAction(name, { ...options, format: options.format as OutputFormat }));
|
||||
|
||||
keys
|
||||
.command("list")
|
||||
.alias("ls")
|
||||
.option("--format <format>", "table, json, or markdown", "table")
|
||||
.description("List your API keys (never their secrets).")
|
||||
.action((options) => keysListAction(options.format as OutputFormat));
|
||||
|
||||
keys
|
||||
.command("revoke")
|
||||
.argument("<key>", "Key name, id, or prefix")
|
||||
.option("--format <format>", "table, json, or markdown", "table")
|
||||
.description("Revoke an API key now; its vault grants go with it.")
|
||||
.action((ref, options) => keysRevokeAction(ref, options.format as OutputFormat));
|
||||
}
|
||||
177
packages/cli/src/machine-keys.test.ts
Normal file
177
packages/cli/src/machine-keys.test.ts
Normal file
|
|
@ -0,0 +1,177 @@
|
|||
import { afterAll, beforeAll, describe, expect, it } from "vitest";
|
||||
import { mkdtempSync, readFileSync, rmSync, statSync, writeFileSync, existsSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import { dirname, join } from "node:path";
|
||||
import { fileURLToPath, pathToFileURL } from "node:url";
|
||||
import type { Server } from "node:http";
|
||||
|
||||
/**
|
||||
* The headless path end to end, against the real credentials-app routes
|
||||
* (apps/pwa) on an in-memory database:
|
||||
*
|
||||
* person: login, push a vault, `keys create --team --vault --out`
|
||||
* box: LOGICSRC_API_KEY=… (first command registers the box's own key)
|
||||
* person: `teams grant … --key`
|
||||
* box: `teams pull` decrypts the same .env; a push is refused (read-only)
|
||||
*
|
||||
* and the property the feature exists for: the box never replaces the
|
||||
* person's identity key, which is what `login --token` on a fresh box did.
|
||||
*/
|
||||
|
||||
const here = dirname(fileURLToPath(import.meta.url));
|
||||
const pwa = (rel: string) => pathToFileURL(join(here, "..", "..", "..", "apps", "pwa", "src", rel)).href;
|
||||
|
||||
// Loaded at runtime: plain .mjs outside this package, so tsc never follows them.
|
||||
type Db = { execute(stmt: string | { sql: string; args: unknown[] }): Promise<{ rows: Array<Record<string, unknown>> }> };
|
||||
let db: Db;
|
||||
let server: Server;
|
||||
let base = "";
|
||||
let annToken = "";
|
||||
const scratch = mkdtempSync(join(process.env.LOGICSRC_TEST_TMP || tmpdir(), "logicsrc-machine-keys-"));
|
||||
const personHome = join(scratch, "person");
|
||||
const boxHome = join(scratch, "box");
|
||||
const saved = { ...process.env };
|
||||
|
||||
function asPerson() {
|
||||
process.env.LOGICSRC_HOME = personHome;
|
||||
delete process.env.LOGICSRC_API_KEY;
|
||||
}
|
||||
function asBox(secret: string) {
|
||||
process.env.LOGICSRC_HOME = boxHome;
|
||||
process.env.LOGICSRC_API_KEY = secret;
|
||||
}
|
||||
async function personPublicKey(): Promise<string> {
|
||||
const r = await db.execute({ sql: "SELECT public_key FROM credshare_keys WHERE user_id = ?", args: ["u_ann"] });
|
||||
return String(r.rows[0]?.public_key ?? "");
|
||||
}
|
||||
|
||||
beforeAll(async () => {
|
||||
process.env.DATABASE_URL = ":memory:";
|
||||
process.env.LOGICSRC_IDENTITY_FILE = "";
|
||||
delete process.env.LOGICSRC_IDENTITY_FILE;
|
||||
({ db } = (await import(pwa("db.mjs"))) as { db: Db });
|
||||
for (const file of ["001_auth.sql", "002_credshare.sql", "005_machine_keys.sql"]) {
|
||||
const sql = readFileSync(fileURLToPath(pwa(join("migrations", file))), "utf8");
|
||||
for (const statement of sql.split(/;\s*$/m).map((s) => s.trim()).filter(Boolean)) await db.execute(statement);
|
||||
}
|
||||
await db.execute({ sql: "INSERT INTO users (id, email, created_at) VALUES (?,?,?)", args: ["u_ann", "ann@example.com", Date.now()] });
|
||||
|
||||
// A variable specifier keeps tsc from demanding @types/express for a test-only import.
|
||||
const expressModule = "express";
|
||||
const { default: express } = (await import(expressModule)) as { default: any };
|
||||
const { credshareRouter } = await import(pwa("routes/credshare.mjs"));
|
||||
const { apiKeysRouter } = await import(pwa("routes/apikeys.mjs"));
|
||||
const { createApiKey } = await import(pwa("lib/apikey.mjs"));
|
||||
const app = express();
|
||||
app.use(express.json());
|
||||
app.use(credshareRouter);
|
||||
app.use(apiKeysRouter);
|
||||
server = app.listen(0);
|
||||
await new Promise((resolve) => server.once("listening", resolve));
|
||||
base = `http://127.0.0.1:${(server.address() as { port: number }).port}`;
|
||||
process.env.LOGICSRC_API = base;
|
||||
annToken = (await createApiKey("u_ann", "ann-laptop")).plaintext;
|
||||
});
|
||||
|
||||
afterAll(async () => {
|
||||
await new Promise((resolve) => server?.close(resolve));
|
||||
for (const key of Object.keys(process.env)) if (!(key in saved)) delete process.env[key];
|
||||
Object.assign(process.env, saved);
|
||||
rmSync(scratch, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
describe("machine API keys, headless", () => {
|
||||
let secret = "";
|
||||
const source = join(scratch, "source.env");
|
||||
const pulled = join(scratch, "pulled.env");
|
||||
const keyFile = join(scratch, "deploy.key");
|
||||
|
||||
it("a person logs in, pushes a vault and makes a scoped, read-only machine key", async () => {
|
||||
const { loginAction, teamsPushAction } = await import("./teams.js");
|
||||
const { keysCreateAction } = await import("./keys.js");
|
||||
const { TeamClient } = await import("@logicsrc/plugin-credential-sharing");
|
||||
asPerson();
|
||||
await loginAction({ token: annToken });
|
||||
await new TeamClient({ apiUrl: base, token: annToken }).createTeam("acme");
|
||||
writeFileSync(source, "DATABASE_URL=postgres://db/app\nSTRIPE_KEY=sk_live_123\n");
|
||||
await teamsPushAction("acme", "web", "prod", { env: source, format: "json" });
|
||||
|
||||
await keysCreateAction("dev2-deploy", { team: "acme", vault: ["web--prod"], out: keyFile, format: "json" });
|
||||
secret = readFileSync(keyFile, "utf8").trim();
|
||||
expect(secret).toMatch(/^lsk_/);
|
||||
expect(statSync(keyFile).mode & 0o777).toBe(0o600);
|
||||
});
|
||||
|
||||
it("refuses to grant a key that has not registered its identity yet", async () => {
|
||||
const { teamsGrantAction } = await import("./teams.js");
|
||||
asPerson();
|
||||
await expect(teamsGrantAction("acme", "web", "prod", undefined, "json", { key: "dev2-deploy" })).rejects.toThrow(
|
||||
/run any command with the key once first/i
|
||||
);
|
||||
});
|
||||
|
||||
it("the box's first command registers its OWN identity, leaving the person's key alone", async () => {
|
||||
const { prepareApiKeyAuth } = await import("./teams.js");
|
||||
const before = await personPublicKey();
|
||||
asBox(secret);
|
||||
await prepareApiKeyAuth();
|
||||
const file = join(boxHome, "keys", `${secret.slice(0, 12)}.json`);
|
||||
expect(existsSync(file)).toBe(true);
|
||||
expect(statSync(file).mode & 0o777).toBe(0o600);
|
||||
const stored = JSON.parse(readFileSync(file, "utf8"));
|
||||
expect(stored.keyKind).toBe("machine");
|
||||
expect(stored.team).toBe("acme");
|
||||
expect(stored.apiToken).toBeUndefined(); // env-var use never writes the secret to disk
|
||||
expect(existsSync(join(boxHome, "identity.json"))).toBe(false);
|
||||
expect(await personPublicKey()).toBe(before);
|
||||
|
||||
const keyRow = await db.execute({ sql: "SELECT public_key FROM api_keys WHERE prefix = ?", args: [secret.slice(0, 12)] });
|
||||
expect(keyRow.rows[0]?.public_key).toBe(stored.keys.publicKey);
|
||||
});
|
||||
|
||||
it("before a grant, the box is told exactly what to run", async () => {
|
||||
const { teamsPullAction } = await import("./teams.js");
|
||||
asBox(secret);
|
||||
await expect(teamsPullAction("acme", "web", "prod", { env: pulled, format: "json" })).rejects.toThrow(
|
||||
/logicsrc teams grant acme web prod --key dev2-deploy/
|
||||
);
|
||||
});
|
||||
|
||||
it("after `teams grant --key`, the box pulls the same values with only the API key", async () => {
|
||||
const { teamsGrantAction, teamsPullAction, prepareApiKeyAuth } = await import("./teams.js");
|
||||
asPerson();
|
||||
await teamsGrantAction("acme", "web", "prod", undefined, "json", { key: "dev2-deploy" });
|
||||
|
||||
asBox(secret);
|
||||
await prepareApiKeyAuth(); // already set up: a file read, no re-registration
|
||||
await teamsPullAction("acme", "web", "prod", { env: pulled, format: "json" });
|
||||
const keys = (text: string) => text.split("\n").filter(Boolean).map((l) => l.split("=")[0]).sort();
|
||||
expect(keys(readFileSync(pulled, "utf8"))).toEqual(keys(readFileSync(source, "utf8")));
|
||||
expect(readFileSync(pulled, "utf8")).toContain("STRIPE_KEY=sk_live_123");
|
||||
});
|
||||
|
||||
it("a read-only machine key cannot push", async () => {
|
||||
const { teamsPushAction } = await import("./teams.js");
|
||||
asBox(secret);
|
||||
writeFileSync(source, "DATABASE_URL=postgres://db/app\nSTRIPE_KEY=sk_live_456\n");
|
||||
await expect(teamsPushAction("acme", "web", "prod", { env: source, format: "json" })).rejects.toThrow(/read-only/i);
|
||||
});
|
||||
|
||||
it("whoami with the key describes the key, and keys cannot be minted with it", async () => {
|
||||
const { TeamClient } = await import("@logicsrc/plugin-credential-sharing");
|
||||
const box = new TeamClient({ apiUrl: base, token: secret });
|
||||
const me = await box.me();
|
||||
expect(me.key).toMatchObject({ kind: "machine", name: "dev2-deploy", team: "acme", vaults: ["web--prod"], readOnly: true });
|
||||
expect(me.teams.map((t) => t.slug)).toEqual(["acme"]);
|
||||
await expect(box.createApiKey({ name: "escalate", kind: "user" })).rejects.toThrow(/machine API key cannot manage/);
|
||||
});
|
||||
|
||||
it("revoking the key cuts the box off", async () => {
|
||||
const { keysRevokeAction } = await import("./keys.js");
|
||||
const { teamsPullAction } = await import("./teams.js");
|
||||
asPerson();
|
||||
await keysRevokeAction("dev2-deploy", "json");
|
||||
asBox(secret);
|
||||
await expect(teamsPullAction("acme", "web", "prod", { env: pulled, format: "json" })).rejects.toThrow(/revoked or expired/);
|
||||
});
|
||||
});
|
||||
|
|
@ -89,7 +89,16 @@ async function rotateOne(
|
|||
throw error;
|
||||
}
|
||||
|
||||
const [{ secrets }, { grants }] = await Promise.all([client.listSecrets(vault.id), client.listGrants(vault.id)]);
|
||||
const [{ secrets }, { grants }, keyGrants] = await Promise.all([
|
||||
client.listSecrets(vault.id),
|
||||
client.listGrants(vault.id),
|
||||
// Machine keys holding the vault get the new DEK too. A server from before
|
||||
// machine keys has no such route; then there are none to carry over.
|
||||
client.listKeyGrants(vault.id).then((r) => r.keyGrants).catch((error: unknown) => {
|
||||
if (error instanceof TeamApiError && error.status === 404) return [];
|
||||
throw error;
|
||||
})
|
||||
]);
|
||||
|
||||
const members: RekeyMember[] = grants.map((g) => ({
|
||||
email: g.email,
|
||||
|
|
@ -103,7 +112,8 @@ async function rotateOne(
|
|||
identity: identity.keys,
|
||||
secrets: secrets.map((s) => ({ name: s.name, nonce: s.nonce, ciphertext: s.ciphertext, fingerprint: s.fingerprint })),
|
||||
members,
|
||||
scope: options.scope
|
||||
scope: options.scope,
|
||||
machineKeys: keyGrants.map((k) => ({ keyId: k.keyId, name: k.name, owner: k.owner, publicKey: k.publicKey }))
|
||||
});
|
||||
|
||||
const summary: Record<string, unknown> = {
|
||||
|
|
@ -112,6 +122,8 @@ async function rotateOne(
|
|||
keeps: plan.grants.map((g) => g.email),
|
||||
revokes: plan.revoked,
|
||||
skipped: plan.skipped,
|
||||
machineKeys: plan.keyGrants.length,
|
||||
machineKeysDropped: plan.keysDropped,
|
||||
applied: false
|
||||
};
|
||||
|
||||
|
|
@ -122,7 +134,8 @@ async function rotateOne(
|
|||
const result = await client.rekeyVault(vault.id, {
|
||||
grants: plan.grants,
|
||||
secrets: plan.secrets,
|
||||
revoke: plan.revoked
|
||||
revoke: plan.revoked,
|
||||
keyGrants: plan.keyGrants
|
||||
});
|
||||
summary.applied = true;
|
||||
summary.rekeyed = result.rekeyed;
|
||||
|
|
|
|||
|
|
@ -3,7 +3,7 @@ import { createHash, randomBytes } from "node:crypto";
|
|||
import { hostname } from "node:os";
|
||||
import { spawn } from "node:child_process";
|
||||
import { createInterface } from "node:readline/promises";
|
||||
import { chmodSync, writeFileSync } from "node:fs";
|
||||
import { chmodSync, rmSync, writeFileSync } from "node:fs";
|
||||
import { OTHER_CATEGORY, SECRET_CATEGORIES, categorizeSecret, csvLine, parseCategories } from "@logicsrc/opencreds";
|
||||
import {
|
||||
TeamClient,
|
||||
|
|
@ -20,9 +20,15 @@ import {
|
|||
unwrapVaultKey,
|
||||
wrapVaultKey,
|
||||
decryptValue,
|
||||
ensureApiKeyIdentity,
|
||||
envApiKey,
|
||||
setActiveKey,
|
||||
activeKeyPath,
|
||||
readActiveKeyIdentity,
|
||||
type CredentialEndpoint,
|
||||
type RemoteVault
|
||||
} from "@logicsrc/plugin-credential-sharing";
|
||||
import { findKey } from "./keys.js";
|
||||
import { print, printColumns, type OutputFormat } from "./format.js";
|
||||
import { linkedDirectory, requireSecretsLink, writeSecretsLink } from "./secrets-link.js";
|
||||
|
||||
|
|
@ -244,7 +250,46 @@ async function resolveVaultId(client: TeamClient, slug: string, vault: string):
|
|||
throw new Error(`Vault "${vault}" not found in team "${slug}". Create it by pushing to it.${hint}`);
|
||||
}
|
||||
|
||||
export async function loginAction(options: { apiUrl?: string; token?: string; device?: boolean; web?: boolean }): Promise<void> {
|
||||
/**
|
||||
* Before a command that talks to the credentials app: when LOGICSRC_API_KEY is
|
||||
* set, make sure that key's identity exists (and, for a machine key, that its
|
||||
* own public key is registered). After the first run this is a file read.
|
||||
*/
|
||||
export async function prepareApiKeyAuth(): Promise<void> {
|
||||
const token = envApiKey();
|
||||
if (!token) return;
|
||||
const result = await ensureApiKeyIdentity(token, { apiUrl: resolveApiUrl() });
|
||||
if (result.registeredNow) {
|
||||
const { identity } = result;
|
||||
console.error(
|
||||
`Registered this machine's identity for API key "${identity.keyName}" (${result.file}). ` +
|
||||
`A member can now grant it a vault: logicsrc teams grant ${identity.team ?? "<team>"} <project> <env> --key ${identity.keyName}`
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/** `logicsrc login --api-key` (or --token with a machine key): store the key and its own identity on this box. */
|
||||
async function apiKeyLogin(token: string, apiUrl: string, reregister?: boolean): Promise<void> {
|
||||
const result = await ensureApiKeyIdentity(token, { apiUrl, persistToken: true, reregister });
|
||||
setActiveKey(result.file);
|
||||
const { identity } = result;
|
||||
if (identity.keyKind === "machine") {
|
||||
console.error(
|
||||
`Logged in with machine key "${identity.keyName}" (team ${identity.team}). Its own identity is in ${result.file}; ` +
|
||||
"your personal identity was not touched."
|
||||
);
|
||||
console.error(`Grant it a vault from a member's machine: logicsrc teams grant ${identity.team} <project> <env> --key ${identity.keyName}`);
|
||||
} else {
|
||||
console.error(`Logged in with a person's API key${identity.email ? ` (${identity.email})` : ""}. It uses this machine's identity.json.`);
|
||||
}
|
||||
print({ email: identity.email ?? null, key: identity.keyName ?? null, kind: identity.keyKind, team: identity.team ?? null, apiUrl }, "table");
|
||||
}
|
||||
|
||||
export async function loginAction(options: { apiUrl?: string; token?: string; apiKey?: string; reregister?: boolean; device?: boolean; web?: boolean }): Promise<void> {
|
||||
if (options.apiKey) {
|
||||
await apiKeyLogin(options.apiKey.trim(), resolveApiUrl(undefined, options.apiUrl), options.reregister);
|
||||
return;
|
||||
}
|
||||
const identity = await loadOrCreateIdentity();
|
||||
const apiUrl = resolveApiUrl(identity, options.apiUrl);
|
||||
|
||||
|
|
@ -256,6 +301,12 @@ export async function loginAction(options: { apiUrl?: string; token?: string; de
|
|||
if (token) {
|
||||
const client = new TeamClient({ apiUrl, token });
|
||||
const me = await client.me();
|
||||
// A machine key must never upload this box's keypair as the person's
|
||||
// identity (that silently replaced the real one). It gets its own instead.
|
||||
if (me.key?.kind === "machine") {
|
||||
await apiKeyLogin(token, apiUrl, options.reregister);
|
||||
return;
|
||||
}
|
||||
email = me.user.email;
|
||||
userId = me.user.id;
|
||||
} else {
|
||||
|
|
@ -281,17 +332,43 @@ export async function loginAction(options: { apiUrl?: string; token?: string; de
|
|||
const client = new TeamClient({ apiUrl, token: token! });
|
||||
await client.uploadPublicKey(identity.keys.publicKey);
|
||||
await updateIdentity({ email: email ?? undefined, userId, apiToken: token, apiUrl });
|
||||
// A person login takes over from any key chosen with --api-key.
|
||||
rmSync(activeKeyPath(), { force: true });
|
||||
|
||||
console.error(`Logged in${email ? ` as ${email}` : ""}. Identity key registered on ${apiUrl}.`);
|
||||
print({ email, apiUrl }, "table");
|
||||
}
|
||||
|
||||
export async function logoutAction(): Promise<void> {
|
||||
const active = readActiveKeyIdentity();
|
||||
if (active) {
|
||||
rmSync(activeKeyPath(), { force: true });
|
||||
console.error(`Stopped using API key "${active.keyName ?? "?"}" on this machine. Revoke it with: logicsrc keys revoke ${active.keyName ?? "<name>"}`);
|
||||
return;
|
||||
}
|
||||
await updateIdentity({ apiToken: undefined, email: undefined, userId: undefined });
|
||||
console.error(`Logged out (local token cleared; revoke the key at /settings). Identity key retained — delete ${identityPath()} to remove it.`);
|
||||
}
|
||||
|
||||
export async function whoamiAction(format: OutputFormat): Promise<void> {
|
||||
if (envApiKey() || readActiveKeyIdentity()) {
|
||||
const { client, identity } = authedClient();
|
||||
const me = await client.me();
|
||||
print({
|
||||
loggedIn: true,
|
||||
via: envApiKey() ? "LOGICSRC_API_KEY" : "logicsrc login --api-key",
|
||||
email: me.user.email,
|
||||
key: me.key?.name ?? null,
|
||||
kind: me.key?.kind ?? "user",
|
||||
teams: me.teams.map((t) => t.slug),
|
||||
vaults: me.key?.kind === "machine" ? (me.key.vaults?.join(",") || "all in team") : undefined,
|
||||
readOnly: me.key?.kind === "machine" ? me.key.readOnly : undefined,
|
||||
expires: me.key?.expiresAt ? new Date(me.key.expiresAt).toISOString() : "never",
|
||||
publicKey: me.user.publicKey,
|
||||
apiUrl: resolveApiUrl(identity)
|
||||
}, format);
|
||||
return;
|
||||
}
|
||||
const identity = readIdentity();
|
||||
if (!identity?.apiToken) {
|
||||
print({ loggedIn: false, apiUrl: defaultApiUrl(), hint: "Run: logicsrc login" }, format);
|
||||
|
|
@ -402,9 +479,35 @@ export async function teamsVaultsAction(slug: string, format: OutputFormat): Pro
|
|||
);
|
||||
}
|
||||
|
||||
export async function teamsGrantAction(slug: string, project: string, env: string, email: string, format: OutputFormat): Promise<void> {
|
||||
export async function teamsGrantAction(
|
||||
slug: string,
|
||||
project: string,
|
||||
env: string,
|
||||
email: string | undefined,
|
||||
format: OutputFormat,
|
||||
options: { key?: string } = {}
|
||||
): Promise<void> {
|
||||
if (!email && !options.key) throw new Error("Grant whom? Give a teammate's email, or --key <name> for a machine API key.");
|
||||
if (email && options.key) throw new Error("Give an email or --key, not both.");
|
||||
const { client, identity } = authedClient();
|
||||
const vault = vaultName(project, env);
|
||||
|
||||
// Resolve the machine key before touching the vault, so a typo fails fast.
|
||||
let machineKey: Awaited<ReturnType<TeamClient["listApiKeys"]>>["keys"][number] | undefined;
|
||||
if (options.key) {
|
||||
machineKey = findKey((await client.listApiKeys()).keys, options.key);
|
||||
if (machineKey.kind !== "machine") {
|
||||
throw new Error(`"${machineKey.name}" is a person's key; it reads through that person's own grant. Grant the person by email instead.`);
|
||||
}
|
||||
if (machineKey.expired) throw new Error(`"${machineKey.name}" has expired. Make a new one: logicsrc keys create …`);
|
||||
if (!machineKey.publicKey) {
|
||||
throw new Error(
|
||||
`The key "${machineKey.name}" has not registered its public key yet, so there is nothing to seal the vault key to. ` +
|
||||
`Run any command with the key once first, on the box: LOGICSRC_API_KEY=<key> logicsrc whoami`
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
const vaultId = await resolveVaultId(client, slug, vault);
|
||||
|
||||
// Unwrap the vault DEK with our own key, then re-wrap it to the target member.
|
||||
|
|
@ -419,6 +522,17 @@ export async function teamsGrantAction(slug: string, project: string, env: strin
|
|||
}
|
||||
const dek = await unwrapVaultKey(myWrapped, identity.keys);
|
||||
|
||||
if (machineKey) {
|
||||
await client.putKeyGrant(vaultId, machineKey.id, await wrapVaultKey(dek, machineKey.publicKey!));
|
||||
console.error(
|
||||
`Granted machine key "${machineKey.name}" ${machineKey.readOnly ? "read-only " : ""}access to ${slug}/${vault}. ` +
|
||||
`On the box: LOGICSRC_API_KEY=<key> logicsrc teams pull ${slug} ${project} ${env} --env .env`
|
||||
);
|
||||
print({ granted: machineKey.name, key: `${machineKey.prefix}…`, team: slug, project, env, vault }, format);
|
||||
return;
|
||||
}
|
||||
if (!email) throw new Error("unreachable: no grant target");
|
||||
|
||||
const target = await client.lookupUser(email);
|
||||
if (!target.userId) throw new Error(`${email} has not logged in yet. Ask them to run: logicsrc login --email ${email}`);
|
||||
if (!target.publicKey) throw new Error(`${email} has not registered a key yet. Ask them to run: logicsrc login --email ${email}`);
|
||||
|
|
|
|||
78
packages/logicsrc-mcp/src/apikeys.test.ts
Normal file
78
packages/logicsrc-mcp/src/apikeys.test.ts
Normal file
|
|
@ -0,0 +1,78 @@
|
|||
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";
|
||||
|
||||
type Call = { url: string; method: string; auth: string | null; body: unknown };
|
||||
|
||||
/** A fake credentials app: records each request and answers like /api/keys does. */
|
||||
function fakeApi(calls: Call[], status = 200, payload: unknown = { keys: [] }): typeof fetch {
|
||||
return (async (input: string | URL | Request, init?: RequestInit) => {
|
||||
const headers = new Headers(init?.headers);
|
||||
calls.push({
|
||||
url: String(input),
|
||||
method: init?.method ?? "GET",
|
||||
auth: headers.get("authorization"),
|
||||
body: init?.body ? JSON.parse(String(init.body)) : undefined
|
||||
});
|
||||
return new Response(JSON.stringify(payload), { status, headers: { "content-type": "application/json" } });
|
||||
}) as typeof fetch;
|
||||
}
|
||||
|
||||
async function connect(env: NodeJS.ProcessEnv, doFetch: typeof fetch) {
|
||||
const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair();
|
||||
const server = createLogicSrcMcpServer({ apiKeys: { env, fetch: doFetch } });
|
||||
const client = new Client({ name: "test-client", version: "0.1.0" });
|
||||
await server.connect(serverTransport);
|
||||
await client.connect(clientTransport);
|
||||
return { client, close: async () => { await client.close(); await server.close(); } };
|
||||
}
|
||||
|
||||
function text(result: unknown): string {
|
||||
const content = (result as { content?: Array<{ type: string; text?: string }> }).content ?? [];
|
||||
return content[0]?.text ?? "";
|
||||
}
|
||||
|
||||
describe("API key tools", () => {
|
||||
it("lists keys with the Bearer key against LOGICSRC_API", async () => {
|
||||
const calls: Call[] = [];
|
||||
const { client, close } = await connect({ LOGICSRC_API_KEY: "lsk_person", LOGICSRC_API: "https://example.test/" }, fakeApi(calls));
|
||||
const tools = await client.listTools();
|
||||
expect(tools.tools.map((t) => t.name)).toEqual(expect.arrayContaining(["list_api_keys", "create_api_key", "revoke_api_key"]));
|
||||
const result = await client.callTool({ name: "list_api_keys", arguments: {} });
|
||||
expect(text(result)).toContain('"keys"');
|
||||
expect(calls).toEqual([{ url: "https://example.test/api/keys", method: "GET", auth: "Bearer lsk_person", body: undefined }]);
|
||||
await close();
|
||||
});
|
||||
|
||||
it("creates a read-only machine key by default and revokes by id", async () => {
|
||||
const calls: Call[] = [];
|
||||
const { client, close } = await connect({ LOGICSRC_API_KEY: "lsk_person" }, fakeApi(calls, 201, { key: { name: "dev2" }, secret: "lsk_new" }));
|
||||
await client.callTool({ name: "create_api_key", arguments: { name: "dev2", team: "acme", vaults: ["web--prod"], expires: "30d" } });
|
||||
expect(calls[0]).toMatchObject({
|
||||
url: "https://app.logicsrc.com/api/keys",
|
||||
method: "POST",
|
||||
body: { name: "dev2", kind: "machine", team: "acme", vaults: ["web--prod"], readOnly: true, expiresAt: "30d" }
|
||||
});
|
||||
await client.callTool({ name: "revoke_api_key", arguments: { id: "k/1" } });
|
||||
expect(calls[1]).toMatchObject({ url: "https://app.logicsrc.com/api/keys/k%2F1", method: "DELETE" });
|
||||
await close();
|
||||
});
|
||||
|
||||
it("says what is missing instead of calling out without a key, and passes server refusals through", async () => {
|
||||
const calls: Call[] = [];
|
||||
const noKey = await connect({}, fakeApi(calls));
|
||||
const missing = await noKey.client.callTool({ name: "list_api_keys", arguments: {} });
|
||||
expect((missing as { isError?: boolean }).isError).toBe(true);
|
||||
expect(text(missing)).toContain("LOGICSRC_API_KEY is not set");
|
||||
expect(calls).toHaveLength(0);
|
||||
await noKey.close();
|
||||
|
||||
const machine = await connect({ LOGICSRC_API_KEY: "lsk_machine" }, fakeApi(calls, 403, { error: "A machine API key cannot manage API keys." }));
|
||||
const refused = await machine.client.callTool({ name: "create_api_key", arguments: { name: "x", team: "acme" } });
|
||||
expect((refused as { isError?: boolean }).isError).toBe(true);
|
||||
expect(text(refused)).toContain("403");
|
||||
expect(text(refused)).toContain("machine API key cannot manage");
|
||||
await machine.close();
|
||||
});
|
||||
});
|
||||
115
packages/logicsrc-mcp/src/apikeys.ts
Normal file
115
packages/logicsrc-mcp/src/apikeys.ts
Normal file
|
|
@ -0,0 +1,115 @@
|
|||
import type { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
|
||||
import { z } from "zod";
|
||||
|
||||
/**
|
||||
* API-key tools for the MCP server: list, create and revoke LogicSRC API keys
|
||||
* by calling the credentials app's /api/keys over HTTPS.
|
||||
*
|
||||
* Auth is a Bearer token from LOGICSRC_API_KEY (and LOGICSRC_API for a server
|
||||
* other than https://app.logicsrc.com). It must be a PERSON's key (`logicsrc
|
||||
* keys create <name> --kind user`, or the one `logicsrc login` stored): the
|
||||
* server refuses to let a machine key mint, list or revoke keys, and these
|
||||
* tools pass that refusal through rather than working around it.
|
||||
*
|
||||
* Secrets: `create_api_key` returns the new key's secret exactly once, in its
|
||||
* result. Nothing here stores it.
|
||||
*/
|
||||
|
||||
export const DEFAULT_API_URL = "https://app.logicsrc.com";
|
||||
|
||||
export interface ApiKeyToolsOptions {
|
||||
env?: NodeJS.ProcessEnv;
|
||||
fetch?: typeof fetch;
|
||||
}
|
||||
|
||||
class ToolError extends Error {}
|
||||
|
||||
function client(options: ApiKeyToolsOptions) {
|
||||
const env = options.env ?? process.env;
|
||||
const doFetch = options.fetch ?? fetch;
|
||||
return async function call(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) in its environment."
|
||||
);
|
||||
}
|
||||
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;
|
||||
};
|
||||
}
|
||||
|
||||
function textResult(text: string, isError = false) {
|
||||
return { content: [{ type: "text" as const, text }], ...(isError ? { isError: true } : {}) };
|
||||
}
|
||||
|
||||
async function guarded(fn: () => Promise<unknown>) {
|
||||
try {
|
||||
return textResult(JSON.stringify(await fn(), null, 2));
|
||||
} catch (error) {
|
||||
return textResult(error instanceof Error ? error.message : String(error), true);
|
||||
}
|
||||
}
|
||||
|
||||
export function registerApiKeys(server: McpServer, options: ApiKeyToolsOptions = {}): void {
|
||||
const call = client(options);
|
||||
|
||||
server.registerTool(
|
||||
"list_api_keys",
|
||||
{
|
||||
title: "List LogicSRC API Keys",
|
||||
description: "Lists the caller's LogicSRC API keys (person and machine keys): name, prefix, team and vault scope, read-only, expiry, whether a machine key has registered its identity. Never returns secrets. Needs LOGICSRC_API_KEY (a person's key).",
|
||||
annotations: { readOnlyHint: true, openWorldHint: true }
|
||||
},
|
||||
async () => guarded(() => call("GET", "/api/keys"))
|
||||
);
|
||||
|
||||
server.registerTool(
|
||||
"create_api_key",
|
||||
{
|
||||
title: "Create LogicSRC API Key",
|
||||
description: "Creates a LogicSRC API key. A machine key (the default) is scoped to one team and optionally some vaults (<project>--<env>), read-only unless readOnly is false, and may expire. The secret is in this result only; hand it to the deploy box and do not repeat it. Needs LOGICSRC_API_KEY (a person's key).",
|
||||
inputSchema: {
|
||||
name: z.string().min(1).max(40).describe("A name for the key, e.g. dev2-deploy."),
|
||||
kind: z.enum(["machine", "user"]).optional().describe("machine (default) or user (acts as the person)."),
|
||||
team: z.string().optional().describe("Team slug; required for a machine key."),
|
||||
vaults: z.array(z.string()).optional().describe("Vault names the key may read, e.g. [\"web--prod\"]. Omit for every vault in the team."),
|
||||
readOnly: z.boolean().optional().describe("Machine keys: true (default) pulls only."),
|
||||
expires: z.string().optional().describe("30d, 12h, 1y, or a date such as 2027-01-01. Omit for no expiry.")
|
||||
},
|
||||
annotations: { readOnlyHint: false, destructiveHint: false, openWorldHint: true }
|
||||
},
|
||||
async ({ name, kind, team, vaults, readOnly, expires }) =>
|
||||
guarded(async () => {
|
||||
const k = kind ?? "machine";
|
||||
if (k === "machine" && !team) throw new ToolError("A machine key needs a team.");
|
||||
return call("POST", "/api/keys", {
|
||||
name,
|
||||
kind: k,
|
||||
...(k === "machine" ? { team, vaults: vaults ?? [], readOnly: readOnly ?? true } : {}),
|
||||
...(expires ? { expiresAt: expires } : {})
|
||||
});
|
||||
})
|
||||
);
|
||||
|
||||
server.registerTool(
|
||||
"revoke_api_key",
|
||||
{
|
||||
title: "Revoke LogicSRC API Key",
|
||||
description: "Revokes one of the caller's LogicSRC API keys by id (from list_api_keys). Anything using it gets a 401 from then on, and its vault grants are deleted. Needs LOGICSRC_API_KEY (a person's key).",
|
||||
inputSchema: { id: z.string().min(1).describe("The key id from list_api_keys.") },
|
||||
annotations: { readOnlyHint: false, destructiveHint: true, idempotentHint: true, openWorldHint: true }
|
||||
},
|
||||
async ({ id }) => guarded(() => call("DELETE", `/api/keys/${encodeURIComponent(id)}`))
|
||||
);
|
||||
}
|
||||
|
|
@ -3,6 +3,7 @@ import { z } from "zod";
|
|||
import { assertSchemaKind, parseDocument, schemas, validate, type SchemaKind } from "@logicsrc/validators";
|
||||
import { registerOpenOntology } from "./openontology.js";
|
||||
import { registerOpenPrd } from "./openprd.js";
|
||||
import { registerApiKeys, type ApiKeyToolsOptions } from "./apikeys.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.`,
|
||||
|
|
@ -15,7 +16,7 @@ CommandBoard.run is a hosted product by Profullstack, Inc., built on LogicSRC. L
|
|||
|
||||
const schemaKinds = Object.keys(schemas) as SchemaKind[];
|
||||
|
||||
export function createLogicSrcMcpServer() {
|
||||
export function createLogicSrcMcpServer(options: { apiKeys?: ApiKeyToolsOptions } = {}) {
|
||||
const server = new McpServer(
|
||||
{
|
||||
name: "@profullstack/logicsrc-mcp",
|
||||
|
|
@ -27,7 +28,7 @@ export function createLogicSrcMcpServer() {
|
|||
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. 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, 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."
|
||||
}
|
||||
);
|
||||
|
||||
|
|
@ -155,6 +156,7 @@ export function createLogicSrcMcpServer() {
|
|||
|
||||
registerOpenOntology(server);
|
||||
registerOpenPrd(server);
|
||||
registerApiKeys(server, options.apiKeys);
|
||||
|
||||
return server;
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue