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:
Anthony Ettinger 2026-10-05 23:08:32 -07:00 • committed by GitHub
parent 4df342a064
commit ade33efd17
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
35 changed files with 2220 additions and 106 deletions

View file

@ -0,0 +1,69 @@
// 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 });
}));

View file

@ -16,7 +16,7 @@ import { get, run } from "../db.mjs";
import { token, sha256 } from "../lib/crypto.mjs";
import { page, footer, appBar, esc } from "../lib/html.mjs";
import { requireAuth, csrfInput } from "../lib/session.mjs";
import { createApiKey, bearer, userForApiKey } from "../lib/apikey.mjs";
import { createApiKey, bearer, keyForBearer } from "../lib/apikey.mjs";
import { requestOrigin } from "../lib/origin.mjs";
import { config } from "../config.mjs";
@ -226,7 +226,11 @@ cliRouter.post("/cli/device/token", async (req, res) => {
});
cliRouter.get("/api/me", async (req, res) => {
const user = await userForApiKey(bearer(req));
if (!user) return res.status(401).json({ error: "invalid or missing API key" });
const found = await keyForBearer(bearer(req));
if (!found) return res.status(401).json({ error: "invalid, revoked, expired or missing API key" });
// /api/me answers "which person is this" -- a machine key is not one. It asks
// /api/credshare/me, which describes the key and its scope instead.
if (found.key.kind === "machine") return res.status(403).json({ error: "A machine API key has no person to describe. Use /api/credshare/me.", code: "machine_key_forbidden" });
const { user } = found;
res.json({ id: user.id, email: user.email || null, name: user.display_name });
});

View file

@ -5,10 +5,17 @@
//
// Auth: the acting user comes from a browser session (req.user) OR a
// `Bearer lsk_…` API key (the logicsrc CLI). Mounted at /api/credshare.
//
// A MACHINE key (api_keys.kind = 'machine') is narrower than its owner: it sees
// one team, optionally only some of its vaults, holds its own identity key, and
// opens vaults only through credshare_key_grants. Each route says whether a
// machine key may call it at all (`machine: "read" | "write" | "register"`);
// anything unmarked is people-only. A read-only machine key gets a 403 on every
// write except registering its own public key.
import { Router } from "express";
import { get, all, run, batch } from "../db.mjs";
import { id, sha256 } from "../lib/crypto.mjs";
import { bearer, userForApiKey } from "../lib/apikey.mjs";
import { bearer, keyForBearer, keyCoversVault, normalizeKey } from "../lib/apikey.mjs";
import {
TeamMemberError,
normEmail,
@ -25,17 +32,37 @@ const slugify = (s) => {
return /^[a-z0-9][a-z0-9-]{0,62}$/.test(v) ? v : null;
};
// Resolve the acting user from session or API key.
const isMachine = (key) => key?.kind === "machine";
// Resolve the acting user (and the API key, when there is one) from session or Bearer.
async function actor(req) {
if (req.user) return req.user;
return userForApiKey(bearer(req));
if (req.user) return { user: req.user, key: null };
return keyForBearer(bearer(req));
}
function api(handler) {
/**
* Wrap a route. `machine` says what a machine key may do here:
* false (default) people only — a machine key gets a 403
* "read" allowed, GET only
* "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 } = {}) {
return async (req, res) => {
const user = await actor(req);
if (!user) return res.status(401).json({ error: "Not authenticated. Run: logicsrc login" });
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" });
const { user, key } = found;
req.apiKey = key;
if (isMachine(key)) {
if (!machine) {
return res.status(403).json({ error: "A machine API key cannot do this. Use a person's login (logicsrc login).", code: "machine_key_forbidden" });
}
if (key.readOnly && machine !== "register" && req.method !== "GET") {
return res.status(403).json({ error: "This machine API key is read-only.", code: "read_only_key" });
}
}
try {
await handler(req, res, user);
await handler(req, res, user, key);
} catch (e) {
console.error("credshare:", e);
res.status(500).json({ error: e.message || String(e) });
@ -43,9 +70,10 @@ function api(handler) {
};
}
async function requireMember(res, slug, userId) {
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; }
const member = await get(`SELECT * FROM credshare_members WHERE team_id = ? AND user_id = ?`, [team.id, userId]);
if (!member || member.status !== "active") { res.status(403).json({ error: "You are not a member of this team." }); return null; }
return { team, member };
@ -57,23 +85,59 @@ async function publicKeyFor(userId) {
}
async function audit(ev) {
await run(`INSERT INTO credshare_audit (id, team_id, vault_id, actor_user_id, action, key_name, fingerprint, created_at) VALUES (?,?,?,?,?,?,?,?)`,
[id(), ev.teamId ?? null, ev.vaultId ?? null, ev.actorUserId, ev.action, ev.keyName ?? null, ev.fingerprint ?? null, Date.now()]);
await run(`INSERT INTO credshare_audit (id, team_id, vault_id, actor_user_id, action, key_name, fingerprint, created_at, actor_key_id) VALUES (?,?,?,?,?,?,?,?,?)`,
[id(), ev.teamId ?? null, ev.vaultId ?? null, ev.actorUserId, ev.action, ev.keyName ?? null, ev.fingerprint ?? null, Date.now(), ev.actorKeyId ?? null]);
}
/** The key facts a client needs about its own credential (null for a browser session). */
function keyInfo(key, teamSlug = null) {
if (!key) return null;
return {
id: key.id,
name: key.name,
prefix: key.prefix,
kind: key.kind,
team: isMachine(key) ? teamSlug : null,
vaults: isMachine(key) ? key.vaultScope : null,
readOnly: isMachine(key) ? key.readOnly : false,
expiresAt: key.expiresAt ?? null
};
}
// ---- identity key + lookup ----
credshareRouter.post("/api/credshare/keys", api(async (req, res, user) => {
credshareRouter.post("/api/credshare/keys", api(async (req, res, user, key) => {
const publicKey = req.body?.publicKey;
if (typeof publicKey !== "string" || !publicKey) return res.status(422).json({ error: "Expected { publicKey }." });
if (isMachine(key)) {
// A machine key registers ITS OWN identity, on its own row. It never
// touches the person's credshare_keys entry. Replacing a different key
// drops this key's grants: they were sealed to the old key and cannot be
// opened with the new one, so keeping them would only hide the breakage.
let dropped = 0;
if (key.public_key && key.public_key !== publicKey) {
dropped = Number((await get(`SELECT COUNT(*) AS n FROM credshare_key_grants WHERE api_key_id = ?`, [key.id]))?.n || 0);
await run(`DELETE FROM credshare_key_grants WHERE api_key_id = ?`, [key.id]);
}
if (key.public_key !== publicKey) {
await run(`UPDATE api_keys SET public_key = ? WHERE id = ?`, [publicKey, key.id]);
await audit({ teamId: key.team_id, actorUserId: user.id, actorKeyId: key.id, action: "key:register", keyName: key.name });
}
return res.json({ email: user.email, publicKey, keyId: key.id, droppedGrants: dropped });
}
await run(`INSERT INTO credshare_keys (user_id, public_key, updated_at) VALUES (?,?,?) ON CONFLICT(user_id) DO UPDATE SET public_key = excluded.public_key, updated_at = excluded.updated_at`,
[user.id, publicKey, Date.now()]);
res.json({ email: user.email, publicKey });
}));
}, { machine: "register" }));
credshareRouter.get("/api/credshare/me", api(async (_req, res, user) => {
credshareRouter.get("/api/credshare/me", api(async (_req, res, user, key) => {
if (isMachine(key)) {
const teams = await all(`SELECT t.id, t.slug, t.name FROM credshare_teams t JOIN credshare_members m ON m.team_id = t.id WHERE m.user_id = ? AND m.status = 'active' AND t.id = ?`, [user.id, key.team_id]);
const team = await get(`SELECT slug FROM credshare_teams WHERE id = ?`, [key.team_id]);
return res.json({ user: { id: user.id, email: user.email, publicKey: key.public_key ?? null }, teams, key: keyInfo(key, team?.slug ?? null) });
}
const teams = await all(`SELECT t.id, t.slug, t.name FROM credshare_teams t JOIN credshare_members m ON m.team_id = t.id WHERE m.user_id = ? AND m.status = 'active'`, [user.id]);
res.json({ user: { id: user.id, email: user.email, publicKey: await publicKeyFor(user.id) }, teams });
}));
res.json({ user: { id: user.id, email: user.email, publicKey: await publicKeyFor(user.id) }, teams, key: keyInfo(key) });
}, { machine: "read" }));
credshareRouter.get("/api/credshare/users", api(async (req, res) => {
const email = norm(req.query.email);
@ -91,14 +155,16 @@ credshareRouter.post("/api/credshare/teams", api(async (req, res, user) => {
await run(`INSERT INTO credshare_teams (id, slug, name, created_by, created_at) VALUES (?,?,?,?,?)`, [team.id, team.slug, team.name, team.createdBy, team.createdAt]);
await run(`INSERT INTO credshare_members (id, team_id, user_id, email, role, status, joined_at, created_at) VALUES (?,?,?,?,?,?,?,?)`,
[id(), team.id, user.id, norm(user.email) || user.id, "owner", "active", Date.now(), Date.now()]);
await audit({ teamId: team.id, actorUserId: user.id, action: "team:create" });
await audit({ teamId: team.id, actorUserId: user.id, actorKeyId: req.apiKey?.id, action: "team:create" });
res.status(201).json({ team: { id: team.id, slug: team.slug, name: team.name } });
}));
credshareRouter.get("/api/credshare/teams", api(async (_req, res, user) => {
const teams = await all(`SELECT t.id, t.slug, t.name FROM credshare_teams t JOIN credshare_members m ON m.team_id = t.id WHERE m.user_id = ? AND m.status = 'active' ORDER BY t.created_at`, [user.id]);
credshareRouter.get("/api/credshare/teams", api(async (_req, res, user, key) => {
const teams = isMachine(key)
? await all(`SELECT t.id, t.slug, t.name FROM credshare_teams t JOIN credshare_members m ON m.team_id = t.id WHERE m.user_id = ? AND m.status = 'active' AND t.id = ? ORDER BY t.created_at`, [user.id, key.team_id])
: await all(`SELECT t.id, t.slug, t.name FROM credshare_teams t JOIN credshare_members m ON m.team_id = t.id WHERE m.user_id = ? AND m.status = 'active' ORDER BY t.created_at`, [user.id]);
res.json({ teams });
}));
}, { machine: "read" }));
credshareRouter.get("/api/credshare/teams/:slug/members", api(async (req, res, user) => {
const ctx = await requireMember(res, req.params.slug, user.id); if (!ctx) return;
@ -171,14 +237,35 @@ credshareRouter.post("/api/credshare/invites/accept", api(async (req, res, user)
if (norm(invite.email) !== norm(user.email)) return res.status(403).json({ error: `This invite is for ${invite.email}, not ${user.email}.` });
await run(`UPDATE credshare_members SET user_id = ?, status = 'active', joined_at = ? WHERE team_id = ? AND email = ?`, [user.id, Date.now(), invite.team_id, norm(invite.email)]);
await run(`UPDATE credshare_invites SET accepted_at = ? WHERE id = ?`, [Date.now(), invite.id]);
await audit({ teamId: invite.team_id, actorUserId: user.id, action: "team:join" });
await audit({ teamId: invite.team_id, actorUserId: user.id, actorKeyId: req.apiKey?.id, action: "team:join" });
const team = await get(`SELECT id, slug, name FROM credshare_teams WHERE id = ?`, [invite.team_id]);
res.json({ ok: true, team });
}));
// ---- vaults ----
credshareRouter.get("/api/credshare/teams/:slug/vaults", api(async (req, res, user) => {
const ctx = await requireMember(res, req.params.slug, user.id); if (!ctx) return;
credshareRouter.get("/api/credshare/teams/:slug/vaults", api(async (req, res, user, key) => {
const ctx = await requireMember(res, req.params.slug, user.id, key); if (!ctx) return;
if (isMachine(key)) {
// A machine key sees the vaults in its scope, and "access" means a grant
// sealed to ITS key, not to the person who made it.
const rows = await all(
`SELECT v.id,
v.name,
(SELECT COUNT(*) FROM credshare_secrets s
WHERE s.vault_id = v.id) AS secret_count,
EXISTS(SELECT 1 FROM credshare_key_grants g
WHERE g.vault_id = v.id AND g.api_key_id = ?) AS has_access
FROM credshare_vaults v
WHERE v.team_id = ?
ORDER BY v.name`,
[key.id, ctx.team.id]
);
return res.json({
vaults: rows
.filter((v) => keyCoversVault(key, v.name))
.map((v) => ({ id: v.id, name: v.name, hasAccess: Boolean(v.has_access), secretCount: Number(v.secret_count || 0) }))
});
}
// One statement, not one per vault. libSQL is remote, so every execute() is a
// network round trip: the previous loop cost 2N+1 of them, and a team with 176
// vaults spent ~10s here -- doubled by `teams pull`, which resolves the vault
@ -206,7 +293,7 @@ credshareRouter.get("/api/credshare/teams/:slug/vaults", api(async (req, res, us
secretCount: Number(v.secret_count || 0)
}))
});
}));
}, { machine: "read" }));
credshareRouter.post("/api/credshare/teams/:slug/vaults", api(async (req, res, user) => {
const ctx = await requireMember(res, req.params.slug, user.id); if (!ctx) return;
@ -216,25 +303,35 @@ credshareRouter.post("/api/credshare/teams/:slug/vaults", api(async (req, res, u
if (existing) return res.json({ vault: { id: existing.id, name: existing.name } });
const vault = { id: id(), name };
await run(`INSERT INTO credshare_vaults (id, team_id, name, created_by, created_at) VALUES (?,?,?,?,?)`, [vault.id, ctx.team.id, name, user.id, Date.now()]);
await audit({ teamId: ctx.team.id, vaultId: vault.id, actorUserId: user.id, action: "vault:create" });
await audit({ teamId: ctx.team.id, vaultId: vault.id, actorUserId: user.id, actorKeyId: req.apiKey?.id, action: "vault:create" });
res.status(201).json({ vault });
}));
// ---- vault grants / secrets / audit (by vault id) ----
async function vaultCtx(res, vaultId, userId) {
async function vaultCtx(res, vaultId, userId, key = null) {
const vault = await get(`SELECT * FROM credshare_vaults WHERE id = ?`, [vaultId]);
if (!vault) { res.status(404).json({ error: "Unknown vault." }); return null; }
if (isMachine(key) && (vault.team_id !== key.team_id || !keyCoversVault(key, vault.name))) {
res.status(403).json({ error: "This API key is not scoped to this vault." }); return null;
}
const member = await get(`SELECT * FROM credshare_members WHERE team_id = ? AND user_id = ?`, [vault.team_id, userId]);
if (!member || member.status !== "active") { res.status(403).json({ error: "You are not a member of this vault's team." }); return null; }
return vault;
}
credshareRouter.get("/api/credshare/vaults/:id/grant", api(async (req, res, user) => {
const vault = await vaultCtx(res, req.params.id, user.id); if (!vault) return;
credshareRouter.get("/api/credshare/vaults/:id/grant", api(async (req, res, user, key) => {
const vault = await vaultCtx(res, req.params.id, user.id, key); if (!vault) return;
if (isMachine(key)) {
const kg = await get(`SELECT wrapped_dek FROM credshare_key_grants WHERE vault_id = ? AND api_key_id = ?`, [vault.id, key.id]);
if (!kg) return res.status(403).json({ error: `This machine key (${key.name}) has not been granted this vault yet. A member runs: logicsrc teams grant <team> <project> <env> --key ${key.name}`, code: "no_key_grant" });
// The one moment a machine can decrypt: worth a line in the vault's audit trail.
await audit({ teamId: vault.team_id, vaultId: vault.id, actorUserId: user.id, actorKeyId: key.id, action: "vault:read", keyName: key.name });
return res.json({ wrappedDek: kg.wrapped_dek });
}
const grant = await get(`SELECT wrapped_dek FROM credshare_vault_grants WHERE vault_id = ? AND user_id = ?`, [vault.id, user.id]);
if (!grant) return res.status(403).json({ error: "You do not have access to this vault yet. Ask a member to grant you." });
res.json({ wrappedDek: grant.wrapped_dek });
}));
}, { machine: "read" }));
credshareRouter.get("/api/credshare/vaults/:id/grants", api(async (req, res, user) => {
const vault = await vaultCtx(res, req.params.id, user.id); if (!vault) return;
@ -314,6 +411,28 @@ credshareRouter.post("/api/credshare/vaults/:id/rekey", api(async (req, res, use
resolved.push({ email, userId: target.id, wrappedDek: g.wrappedDek });
}
// Machine keys hold the DEK through credshare_key_grants. A re-key makes every
// one of those dead, so each is either re-sealed in this same transaction
// (keyGrants: [{ keyId, wrappedDek }]) or dropped -- never left stale.
const keyGrantsIn = Array.isArray(req.body?.keyGrants) ? req.body.keyGrants : [];
const currentKeyGrants = await all(
`SELECT g.api_key_id, k.name FROM credshare_key_grants g JOIN api_keys k ON k.id = g.api_key_id WHERE g.vault_id = ?`,
[vault.id]
);
const currentKeyIds = new Map(currentKeyGrants.map((g) => [g.api_key_id, g.name]));
const resealed = [];
for (const g of keyGrantsIn) {
if (!g || typeof g.keyId !== "string" || typeof g.wrappedDek !== "string" || !g.wrappedDek) {
return res.status(422).json({ error: "Each key grant needs { keyId, wrappedDek }." });
}
if (!currentKeyIds.has(g.keyId)) {
return res.status(409).json({ error: `Key ${g.keyId} holds no grant on this vault; grant it after the re-key instead.` });
}
resealed.push(g);
}
const resealedIds = new Set(resealed.map((g) => g.keyId));
const droppedKeys = currentKeyGrants.filter((g) => !resealedIds.has(g.api_key_id)).map((g) => g.name);
const revokedUsers = [];
for (const email of revoke) {
const target = await get(`SELECT id FROM users WHERE email = ?`, [email]);
@ -337,6 +456,13 @@ credshareRouter.post("/api/credshare/vaults/:id/rekey", api(async (req, res, use
for (const r of revokedUsers) {
statements.push({ sql: `DELETE FROM credshare_vault_grants WHERE vault_id = ? AND user_id = ?`, args: [vault.id, r.userId] });
}
statements.push({ sql: `DELETE FROM credshare_key_grants WHERE vault_id = ?`, args: [vault.id] });
for (const g of resealed) {
statements.push({
sql: `INSERT INTO credshare_key_grants (vault_id, api_key_id, wrapped_dek, granted_by, created_at) VALUES (?,?,?,?,?)`,
args: [vault.id, g.keyId, g.wrappedDek, user.id, now]
});
}
statements.push({
sql: `INSERT INTO credshare_audit (id, team_id, vault_id, actor_user_id, action, key_name, fingerprint, created_at) VALUES (?,?,?,?,?,?,?,?)`,
args: [id(), vault.team_id, vault.id, user.id, "vault:rekey", null, null, now]
@ -349,7 +475,14 @@ credshareRouter.post("/api/credshare/vaults/:id/rekey", api(async (req, res, use
}
await batch(statements);
res.json({ ok: true, rekeyed: secrets.length, granted: resolved.map((g) => g.email), revoked: revokedUsers.map((r) => r.email) });
res.json({
ok: true,
rekeyed: secrets.length,
granted: resolved.map((g) => g.email),
revoked: revokedUsers.map((r) => r.email),
keysResealed: resealed.map((g) => currentKeyIds.get(g.keyId)),
keysDropped: droppedKeys
});
}));
credshareRouter.post("/api/credshare/vaults/:id/grants", api(async (req, res, user) => {
@ -364,18 +497,93 @@ credshareRouter.post("/api/credshare/vaults/:id/grants", api(async (req, res, us
if (!(await publicKeyFor(target.id))) return res.status(409).json({ error: "Target user has not uploaded a public key yet." });
await run(`INSERT INTO credshare_vault_grants (vault_id, user_id, wrapped_dek, granted_by, created_at) VALUES (?,?,?,?,?) ON CONFLICT(vault_id, user_id) DO UPDATE SET wrapped_dek = excluded.wrapped_dek, granted_by = excluded.granted_by, created_at = excluded.created_at`,
[vault.id, target.id, wrappedDek, user.id, Date.now()]);
await audit({ teamId: vault.team_id, vaultId: vault.id, actorUserId: user.id, action: "vault:grant", keyName: email });
await audit({ teamId: vault.team_id, vaultId: vault.id, actorUserId: user.id, actorKeyId: req.apiKey?.id, action: "vault:grant", keyName: email });
res.status(201).json({ ok: true });
}));
credshareRouter.get("/api/credshare/vaults/:id/secrets", api(async (req, res, user) => {
// ---- machine-key grants: the vault key sealed to a machine key's own public key ----
/** Machine keys holding this vault, with their public keys (so a re-key can re-seal to them). */
credshareRouter.get("/api/credshare/vaults/:id/key-grants", api(async (req, res, user) => {
const vault = await vaultCtx(res, req.params.id, user.id); if (!vault) return;
const rows = await all(`SELECT * FROM credshare_secrets WHERE vault_id = ? ORDER BY name`, [vault.id]);
res.json({ vaultId: vault.id, secrets: rows.map((s) => ({ name: s.name, nonce: s.nonce, ciphertext: s.ciphertext, fingerprint: s.fingerprint, version: s.version, updatedAt: s.updated_at })) });
const rows = await all(
`SELECT g.api_key_id, g.created_at, k.name, k.prefix, k.public_key, k.read_only, k.expires_at, u.email AS owner
FROM credshare_key_grants g
JOIN api_keys k ON k.id = g.api_key_id
LEFT JOIN users u ON u.id = k.user_id
WHERE g.vault_id = ?
ORDER BY k.name`,
[vault.id]
);
res.json({
keyGrants: rows.map((r) => ({
keyId: r.api_key_id,
name: r.name,
prefix: r.prefix,
owner: r.owner ?? null,
publicKey: r.public_key ?? null,
readOnly: Number(r.read_only) === 1,
expiresAt: r.expires_at == null ? null : Number(r.expires_at),
grantedAt: Number(r.created_at)
}))
});
}));
credshareRouter.put("/api/credshare/vaults/:id/secrets", api(async (req, res, user) => {
/**
* Seal this vault's key to one of YOUR machine keys. The client unwraps the DEK
* with the person's identity and re-seals it to the key's public key, exactly
* as a member grant does; the server only checks who may and stores the box.
*/
credshareRouter.post("/api/credshare/vaults/:id/key-grants", api(async (req, res, user) => {
const vault = await vaultCtx(res, req.params.id, user.id); if (!vault) return;
const iHold = await get(`SELECT 1 FROM credshare_vault_grants WHERE vault_id = ? AND user_id = ?`, [vault.id, user.id]);
if (!iHold) return res.status(403).json({ error: "Only a member with vault access can grant a key." });
const keyId = req.body?.keyId, wrappedDek = req.body?.wrappedDek;
if (typeof keyId !== "string" || !keyId || typeof wrappedDek !== "string" || !wrappedDek) {
return res.status(422).json({ error: "Expected { keyId, wrappedDek }." });
}
const raw = await get(`SELECT * FROM api_keys WHERE id = ? AND user_id = ?`, [keyId, user.id]);
if (!raw) return res.status(404).json({ error: "No such API key on your account." });
const target = normalizeKey(raw);
if (target.kind !== "machine") return res.status(422).json({ error: "Only a machine key can be granted a vault. A person's key reads through the person's own grant." });
if (target.expiresAt !== null && target.expiresAt <= Date.now()) return res.status(409).json({ error: "That key has expired." });
if (target.team_id !== vault.team_id) return res.status(409).json({ error: "That key is scoped to another team." });
if (!keyCoversVault(target, vault.name)) return res.status(409).json({ error: `That key is not scoped to ${vault.name}. Its vaults: ${(target.vaultScope || []).join(", ")}.` });
if (!target.public_key) {
return res.status(409).json({ error: "That key has not registered its public key yet. Run any logicsrc command with the key once first (LOGICSRC_API_KEY=… logicsrc whoami).", code: "no_public_key" });
}
await run(`INSERT INTO credshare_key_grants (vault_id, api_key_id, wrapped_dek, granted_by, created_at) VALUES (?,?,?,?,?) ON CONFLICT(vault_id, api_key_id) DO UPDATE SET wrapped_dek = excluded.wrapped_dek, granted_by = excluded.granted_by, created_at = excluded.created_at`,
[vault.id, target.id, wrappedDek, user.id, Date.now()]);
await audit({ teamId: vault.team_id, vaultId: vault.id, actorUserId: user.id, actorKeyId: req.apiKey?.id, action: "vault:grant:key", keyName: target.name });
res.status(201).json({ ok: true, keyId: target.id, name: target.name });
}));
credshareRouter.delete("/api/credshare/vaults/:id/key-grants/:keyId", api(async (req, res, user) => {
const vault = await vaultCtx(res, req.params.id, user.id); if (!vault) return;
const row = await get(
`SELECT k.id, k.name, k.user_id FROM credshare_key_grants g JOIN api_keys k ON k.id = g.api_key_id WHERE g.vault_id = ? AND g.api_key_id = ?`,
[vault.id, req.params.keyId]
);
if (!row) return res.status(404).json({ error: "That key holds no grant on this vault." });
const iHold = await get(`SELECT 1 FROM credshare_vault_grants WHERE vault_id = ? AND user_id = ?`, [vault.id, user.id]);
if (!iHold && row.user_id !== user.id) return res.status(403).json({ error: "Only the key's owner or a member with vault access can revoke it." });
await run(`DELETE FROM credshare_key_grants WHERE vault_id = ? AND api_key_id = ?`, [vault.id, row.id]);
await audit({ teamId: vault.team_id, vaultId: vault.id, actorUserId: user.id, actorKeyId: req.apiKey?.id, action: "vault:revoke:key", keyName: row.name });
res.json({ ok: true, revoked: row.name });
}));
credshareRouter.get("/api/credshare/vaults/:id/secrets", api(async (req, res, user, key) => {
const vault = await vaultCtx(res, req.params.id, user.id, key); if (!vault) return;
const rows = await all(`SELECT * FROM credshare_secrets WHERE vault_id = ? ORDER BY name`, [vault.id]);
res.json({ vaultId: vault.id, secrets: rows.map((s) => ({ name: s.name, nonce: s.nonce, ciphertext: s.ciphertext, fingerprint: s.fingerprint, version: s.version, updatedAt: s.updated_at })) });
}, { machine: "read" }));
credshareRouter.put("/api/credshare/vaults/:id/secrets", api(async (req, res, user, key) => {
const vault = await vaultCtx(res, req.params.id, user.id, key); if (!vault) return;
if (isMachine(key) && !(await get(`SELECT 1 FROM credshare_key_grants WHERE vault_id = ? AND api_key_id = ?`, [vault.id, key.id]))) {
return res.status(403).json({ error: "A machine key can only write a vault it has been granted.", code: "no_key_grant" });
}
const actorKeyId = key?.id ?? null;
const upserts = Array.isArray(req.body?.upserts) ? req.body.upserts : [];
const deletes = Array.isArray(req.body?.deletes) ? req.body.deletes : [];
const applied = [];
@ -387,21 +595,21 @@ credshareRouter.put("/api/credshare/vaults/:id/secrets", api(async (req, res, us
const version = (prev?.version ?? 0) + 1;
await run(`INSERT INTO credshare_secrets (vault_id, name, nonce, ciphertext, fingerprint, version, updated_by, updated_at) VALUES (?,?,?,?,?,?,?,?) ON CONFLICT(vault_id, name) DO UPDATE SET nonce = excluded.nonce, ciphertext = excluded.ciphertext, fingerprint = excluded.fingerprint, version = excluded.version, updated_by = excluded.updated_by, updated_at = excluded.updated_at`,
[vault.id, u.name, u.nonce, u.ciphertext, u.fingerprint, version, user.id, Date.now()]);
await audit({ teamId: vault.team_id, vaultId: vault.id, actorUserId: user.id, action: prev ? "secret:update" : "secret:add", keyName: u.name, fingerprint: u.fingerprint });
await audit({ teamId: vault.team_id, vaultId: vault.id, actorUserId: user.id, action: prev ? "secret:update" : "secret:add", keyName: u.name, fingerprint: u.fingerprint, actorKeyId });
applied.push(u.name);
}
for (const raw of deletes) {
const name = typeof raw === "string" ? raw : null;
if (!name) continue;
await run(`DELETE FROM credshare_secrets WHERE vault_id = ? AND name = ?`, [vault.id, name]);
await audit({ teamId: vault.team_id, vaultId: vault.id, actorUserId: user.id, action: "secret:remove", keyName: name });
await audit({ teamId: vault.team_id, vaultId: vault.id, actorUserId: user.id, action: "secret:remove", keyName: name, actorKeyId });
applied.push(name);
}
res.json({ ok: true, applied });
}));
}, { machine: "write" }));
credshareRouter.get("/api/credshare/vaults/:id/audit", api(async (req, res, user) => {
const vault = await vaultCtx(res, req.params.id, user.id); if (!vault) return;
credshareRouter.get("/api/credshare/vaults/:id/audit", api(async (req, res, user, key) => {
const vault = await vaultCtx(res, req.params.id, user.id, key); if (!vault) return;
const auditRows = await all(`SELECT * FROM credshare_audit WHERE vault_id = ? ORDER BY created_at DESC`, [vault.id]);
res.json({ audit: auditRows });
}));
}, { machine: "read" }));

View file

@ -13,7 +13,7 @@
// Auth: browser session or `Bearer lsk_…` (the logicsrc CLI). Mounted at /api/opencreds.
import { Router } from "express";
import { get, all, run } from "../db.mjs";
import { bearer, userForApiKey } from "../lib/apikey.mjs";
import { bearer, keyForBearer } from "../lib/apikey.mjs";
export const opencredsRouter = Router();
@ -22,8 +22,14 @@ export const MAX_ITEMS_PER_PUSH = 500;
function api(handler) {
return async (req, res) => {
const user = req.user || (await userForApiKey(bearer(req)));
if (!user) return res.status(401).json({ error: "Not authenticated. Run: logicsrc login" });
let user = req.user;
if (!user) {
const found = await keyForBearer(bearer(req));
if (!found) return res.status(401).json({ error: "Not authenticated. Run: logicsrc login" });
// The personal vault is the person's alone; a machine key never reaches it.
if (found.key.kind === "machine") return res.status(403).json({ error: "A machine API key cannot read the personal vault.", code: "machine_key_forbidden" });
user = found.user;
}
try {
await handler(req, res, user);
} catch (e) {

View file

@ -7,7 +7,7 @@ import { get, all, run } from "../db.mjs";
import { id, sha256 } from "../lib/crypto.mjs";
import { page, footer, appBar, esc } from "../lib/html.mjs";
import { requireAuth, csrfInput } from "../lib/session.mjs";
import { createApiKey, listApiKeys, revokeApiKey } from "../lib/apikey.mjs";
import { ApiKeyError, createApiKey, keyCoversVault, listApiKeys, machineKeyOptions, revokeApiKey } from "../lib/apikey.mjs";
import { requestOrigin } from "../lib/origin.mjs";
import { CLI_HINT } from "../lib/cli-hint.mjs";
import { vaultPageBody } from "../lib/vault-page.mjs";
@ -117,7 +117,14 @@ pagesRouter.get("/teams/:slug/vaults/:vaultId", requireAuth, async (req, res, ne
const secrets = await all(`SELECT name, version, updated_at FROM credshare_secrets WHERE vault_id = ? ORDER BY name`, [vault.id]);
const grant = await get(`SELECT 1 FROM credshare_vault_grants WHERE vault_id = ? AND user_id = ?`, [vault.id, req.user.id]);
const key = await get(`SELECT public_key FROM credshare_keys WHERE user_id = ?`, [req.user.id]);
// The caller's own machine keys that could hold this vault, and which already do.
const granted = new Set((await all(`SELECT api_key_id FROM credshare_key_grants WHERE vault_id = ?`, [vault.id])).map((r) => r.api_key_id));
const machineKeys = (await listApiKeys(req.user.id))
.filter((k) => k.kind === "machine" && k.team_id === vault.team_id && keyCoversVault(k, vault.name))
.filter((k) => k.expiresAt === null || k.expiresAt > Date.now())
.map((k) => ({ id: k.id, name: k.name, prefix: k.prefix, publicKey: k.public_key || "", readOnly: k.readOnly, granted: granted.has(k.id) }));
const body = `${appBar(req)}${vaultPageBody({
machineKeys,
team: ctx.team,
vault,
secrets,
@ -238,32 +245,87 @@ pagesRouter.post("/teams/accept", requireAuth, async (req, res) => {
res.redirect("/dashboard");
});
// ---- settings: CLI API keys ----
// ---- settings: API keys (person keys for the CLI, machine keys for boxes) ----
const KEY_ERRORS = {
"no-name": "Give the key a name.",
};
function keyRow(req, k) {
const when = (ms) => (ms ? new Date(Number(ms)).toISOString().slice(0, 10) : "never");
const facts = k.kind === "machine"
? [
`<span class="pill">machine</span>`,
`<span class="pill">${esc(k.team_slug || "?")}</span>`,
`<span class="pill ${k.readOnly ? "" : "warn"}">${k.readOnly ? "read-only" : "read-write"}</span>`,
k.vaultScope ? `<span class="faint">vaults: ${k.vaultScope.map(esc).join(", ")}</span>` : `<span class="faint">every vault in the team</span>`,
`<span class="faint">expires ${esc(when(k.expiresAt))}${k.expiresAt && k.expiresAt <= Date.now() ? " (expired)" : ""}</span>`,
k.public_key ? `<span class="pill on">identity registered</span>` : `<span class="pill warn">not used yet</span>`
].join(" ")
: `<span class="pill">person</span> <span class="faint">acts as you</span>`;
return `
<div style="display:flex;gap:12px;align-items:center;padding:10px 0;border-bottom:1px solid var(--line)" class="mono">
<div style="flex:1;min-width:0"><div>${esc(k.name)} <span class="faint">${esc(k.prefix)}…</span></div>
<div style="font-size:.74rem;margin-top:4px;display:flex;gap:6px;flex-wrap:wrap;align-items:center">${facts}<span class="faint">last used ${esc(when(k.last_used_at))}</span></div></div>
<form method="post" action="/settings/apikeys/${esc(k.id)}/delete" style="margin:0">${csrfInput(req)}<button class="btn danger" style="padding:5px 10px;font-size:.72rem">revoke</button></form>
</div>`;
}
pagesRouter.get("/settings", requireAuth, async (req, res) => {
const keys = await listApiKeys(req.user.id);
const teams = await all(`SELECT t.slug FROM credshare_teams t JOIN credshare_members m ON m.team_id = t.id WHERE m.user_id = ? AND m.status = 'active' ORDER BY t.slug`, [req.user.id]);
const newKey = req.query.key ? String(req.query.key) : "";
const keysHtml = keys.length ? keys.map((k) => `
<div style="display:flex;gap:12px;align-items:center;padding:10px 0;border-bottom:1px solid var(--line)" class="mono">
<span style="flex:1">${esc(k.name)} <span class="faint">${esc(k.prefix)}…</span></span>
<form method="post" action="/settings/apikeys/${k.id}/delete" style="margin:0">${csrfInput(req)}<button class="btn danger" style="padding:5px 10px;font-size:.72rem">revoke</button></form>
</div>`).join("") : `<div class="faint mono" style="font-size:.78rem;padding:6px 0">no keys yet</div>`;
const err = req.query.err ? String(req.query.err).slice(0, 200) : "";
const keysHtml = keys.length ? keys.map((k) => keyRow(req, k)).join("") : `<div class="faint mono" style="font-size:.78rem;padding:6px 0">no keys yet</div>`;
const body = `${appBar(req)}
<main class="wrap" style="max-width:640px;padding-top:30px">
<main class="wrap" style="max-width:720px;padding-top:30px">
<h1 style="font-size:1.5rem;margin-bottom:20px">Settings</h1>
${newKey ? `<div class="notice ok">New API key (copy it now — shown once):<br><b class="mono" style="word-break:break-all">${esc(newKey)}</b></div>` : ""}
<div class="card"><div class="card-head"><span class="h">API keys · for the logicsrc CLI</span></div>
${err ? `<div class="notice err">${esc(KEY_ERRORS[err] || err)}</div>` : ""}
<div class="card"><div class="card-head"><span class="h">API keys</span></div>
<div class="card-body">
<p class="dim" style="font-size:.85rem;margin-top:0">Usually you don't need these — <code>logicsrc login</code> creates one automatically. Manual keys are for CI.</p>
<p class="dim" style="font-size:.85rem;margin-top:0">A <b>person</b> key acts as you; <code>logicsrc login</code> makes one for you. A <b>machine</b> key is for a deploy box or CI: one team, the vaults you list, read-only unless you say otherwise, its own identity key. After the box runs one command with it, grant it a vault from the vault page or with <code>logicsrc teams grant &lt;team&gt; &lt;project&gt; &lt;env&gt; --key &lt;name&gt;</code>.</p>
${keysHtml}
<form method="post" action="/settings/apikeys" style="margin-top:14px;display:flex;gap:10px">${csrfInput(req)}
<input name="name" placeholder="key name (e.g. ci)" style="flex:1"><button class="btn">Create key</button></form>
<form method="post" action="/settings/apikeys" style="margin-top:16px" data-role="new-key">${csrfInput(req)}
<div style="display:flex;gap:10px;flex-wrap:wrap">
<label class="field" style="flex:2;min-width:160px"><span>Name</span><input name="name" placeholder="e.g. dev2-deploy" required maxlength="40"></label>
<label class="field" style="flex:1;min-width:120px"><span>Kind</span><select name="kind"><option value="user">person</option><option value="machine">machine</option></select></label>
</div>
<fieldset data-role="machine-fields" style="border:1px solid var(--line);border-radius:9px;padding:12px 14px 0;margin:0 0 14px">
<legend class="faint mono" style="font-size:.7rem;padding:0 6px">machine keys only</legend>
<div style="display:flex;gap:10px;flex-wrap:wrap">
<label class="field" style="flex:1;min-width:140px"><span>Team</span><select name="team">${teams.length ? teams.map((t) => `<option value="${esc(t.slug)}">${esc(t.slug)}</option>`).join("") : `<option value="">(no teams)</option>`}</select></label>
<label class="field" style="flex:2;min-width:200px"><span>Vaults (blank = all in the team)</span><input name="vaults" placeholder="web--prod, api--prod"></label>
</div>
<div style="display:flex;gap:10px;flex-wrap:wrap;align-items:center">
<label class="field" style="flex:1;min-width:140px"><span>Expires</span><select name="expires"><option value="">never</option><option value="30d">in 30 days</option><option value="90d" selected>in 90 days</option><option value="365d">in a year</option></select></label>
<label class="dim" style="flex:1;min-width:160px;display:flex;gap:8px;align-items:center;font-size:.85rem;margin-bottom:14px"><input type="checkbox" name="readOnly" value="1" checked style="width:auto"> Read-only (pull, never push)</label>
</div>
</fieldset>
<button class="btn">Create key</button>
</form>
</div></div>
</main>${footer}`;
res.type("html").send(page({ title: "LogicSRC ▸ settings", body }));
});
pagesRouter.post("/settings/apikeys", requireAuth, async (req, res) => {
const { plaintext } = await createApiKey(req.user.id, String(req.body.name || "cli").slice(0, 40));
const name = String(req.body.name || "").trim().slice(0, 40);
if (!name) return res.redirect("/settings?err=no-name");
let opts = {};
if (req.body.kind === "machine") {
try {
opts = await machineKeyOptions(req.user.id, {
team: req.body.team,
vaults: req.body.vaults,
readOnly: req.body.readOnly === "1",
expires: req.body.expires || null
});
} catch (error) {
if (error instanceof ApiKeyError) return res.redirect("/settings?err=" + encodeURIComponent(error.message));
throw error;
}
}
const { plaintext } = await createApiKey(req.user.id, name, opts);
res.redirect("/settings?key=" + encodeURIComponent(plaintext));
});
pagesRouter.post("/settings/apikeys/:id/delete", requireAuth, async (req, res) => {