logicsrc/apps/pwa/src/routes/apikeys.mjs
Anthony Ettinger ade33efd17
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>
2026-10-05 23:08:32 -07:00

69 lines
2.8 KiB
JavaScript

// API keys as an API: list, mint and revoke the caller's own lsk_ keys.
//
// GET /api/keys the caller's keys (never a hash, never a secret)
// POST /api/keys mint one; the plaintext is in this response only
// DELETE /api/keys/:id revoke (delete) one, with its vault grants
//
// Auth: a browser session or a person's (`user`) key. A machine key cannot
// mint keys, list them or revoke them: a deploy box that could make itself a
// broader credential would make the scoping pointless.
import { Router } from "express";
import {
ApiKeyError,
bearer,
createApiKey,
keyForBearer,
keyJson,
listApiKeys,
machineKeyOptions,
revokeApiKey
} from "../lib/apikey.mjs";
export const apiKeysRouter = Router();
function personOnly(handler) {
return async (req, res) => {
let user = req.user;
let key = null;
if (!user) {
const found = await keyForBearer(bearer(req));
if (!found) return res.status(401).json({ error: "Not authenticated, or the API key is revoked or expired. Run: logicsrc login" });
({ user, key } = found);
}
if (key?.kind === "machine") {
return res.status(403).json({ error: "A machine API key cannot manage API keys.", code: "machine_key_forbidden" });
}
try {
await handler(req, res, user);
} catch (e) {
if (e instanceof ApiKeyError) return res.status(e.status).json({ error: e.message });
console.error("apikeys:", e);
res.status(500).json({ error: e.message || String(e) });
}
};
}
apiKeysRouter.get("/api/keys", personOnly(async (_req, res, user) => {
res.json({ keys: (await listApiKeys(user.id)).map(keyJson) });
}));
apiKeysRouter.post("/api/keys", personOnly(async (req, res, user) => {
const body = req.body || {};
const name = String(body.name || "").trim().slice(0, 40);
if (!name) return res.status(422).json({ error: "Give the key a name (e.g. dev2-deploy)." });
const kind = body.kind === undefined ? "user" : String(body.kind);
if (kind !== "user" && kind !== "machine") return res.status(422).json({ error: 'kind must be "user" or "machine".' });
const opts = kind === "machine"
? await machineKeyOptions(user.id, { team: body.team, vaults: body.vaults, readOnly: body.readOnly, expires: body.expiresAt ?? body.expires })
: {};
const { plaintext, row } = await createApiKey(user.id, name, opts);
const listed = (await listApiKeys(user.id)).find((k) => k.id === row.id);
res.status(201).json({ key: keyJson(listed), secret: plaintext });
}));
apiKeysRouter.delete("/api/keys/:id", personOnly(async (req, res, user) => {
const ok = await revokeApiKey(user.id, req.params.id);
if (!ok) return res.status(404).json({ error: "No such API key on your account." });
res.json({ ok: true, revoked: req.params.id });
}));