Machine API keys: headless teams pull for deploy boxes and CI

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-06 06:02:26 +00:00
parent 4df342a064
commit 77075ea1e2
35 changed files with 2220 additions and 106 deletions

View file

@ -38,3 +38,12 @@ Postgres (it drops and recreates the `public` schema of that database).
The CLI connects with `LOGICSRC_API=<origin> logicsrc login` (browser OAuth-PKCE
loopback → an `lsk_` key). See `docs/credential-sharing.md` in the repo root.
Deploy boxes and CI use a **machine key** instead (`logicsrc keys create`, or
Settings ▸ API keys): one team, optional vault list, read-only by default,
optional expiry, and its own identity public key on the `api_keys` row. Vault
keys reach it through `credshare_key_grants`. Routes: `GET|POST /api/keys`,
`DELETE /api/keys/:id` (session or a person's key only) and
`GET|POST /api/credshare/vaults/:id/key-grants`,
`DELETE /api/credshare/vaults/:id/key-grants/:keyId`. Migration
`005_machine_keys.sql`; tests in `test/machine-keys.test.mjs`.

View file

@ -16,6 +16,8 @@
var STORE = "logicsrc.identityKey";
var status = card.querySelector("[data-role=status]");
var values = null; // name -> plaintext, once unlocked
var vaultDek = null; // the vault key (bytes), once unlocked -- only ever used to seal it to a machine key
var keysCard = document.getElementById("machine-keys");
function say(msg) { if (status) status.textContent = msg || ""; }
@ -90,7 +92,7 @@
out[s.name] = na.to_string(na.crypto_secretbox_open_easy(na.from_base64(s.ciphertext, V), na.from_base64(s.nonce, V), dek));
} catch (_) { failed.push(s.name); }
});
return { values: out, failed: failed };
return { values: out, failed: failed, dek: dek };
});
});
});
@ -107,6 +109,13 @@
function render(result) {
values = result.values;
vaultDek = result.dek || null;
if (keysCard && vaultDek) {
Array.prototype.forEach.call(keysCard.querySelectorAll("[data-action=grant-key]"), function (b) {
b.disabled = false;
b.removeAttribute("title");
});
}
var rows = main.querySelectorAll("tr[data-key-name]");
Array.prototype.forEach.call(rows, function (tr) {
var name = tr.getAttribute("data-key-name");
@ -195,6 +204,61 @@
}
}
function csrfHeader() {
var m = document.cookie.match(/(?:^|; )mc_csrf=([^;]+)/);
return m ? decodeURIComponent(m[1]) : "";
}
function keySay(msg, bad) {
var el = keysCard && keysCard.querySelector("[data-role=key-status]");
if (!el) return;
el.textContent = msg || "";
el.style.color = bad ? "var(--danger,#c23a3a)" : "";
}
// Machine keys: seal the vault key to the machine's own public key, here.
if (keysCard) {
keysCard.addEventListener("click", function (e) {
var btn = e.target && e.target.closest ? e.target.closest("[data-action]") : null;
if (!btn) return;
var action = btn.getAttribute("data-action");
var keyId = btn.getAttribute("data-key-id");
var url = "/api/credshare/vaults/" + encodeURIComponent(vaultId) + "/key-grants";
if (action === "grant-key") {
if (!vaultDek) { keySay("Unlock the vault with your key first.", true); return; }
btn.disabled = true;
sodium().then(function (na) {
var V = na.base64_variants.ORIGINAL;
var sealed = na.to_base64(na.crypto_box_seal(vaultDek, na.from_base64(btn.getAttribute("data-key-public"), V)), V);
return fetch(url, {
method: "POST",
credentials: "same-origin",
headers: { "content-type": "application/json", "x-csrf-token": csrfHeader() },
body: JSON.stringify({ keyId: keyId, wrappedDek: sealed })
});
}).then(function (res) {
return res.json().catch(function () { return {}; }).then(function (body) {
if (!res.ok) throw new Error(body.error || ("HTTP " + res.status));
keySay("Granted " + btn.getAttribute("data-key-name") + ". Reload to see it listed.");
btn.textContent = "Granted";
});
}).catch(function (err) { btn.disabled = false; keySay(err.message, true); });
} else if (action === "revoke-key") {
btn.disabled = true;
fetch(url + "/" + encodeURIComponent(keyId), {
method: "DELETE",
credentials: "same-origin",
headers: { "x-csrf-token": csrfHeader() }
}).then(function (res) {
return res.json().catch(function () { return {}; }).then(function (body) {
if (!res.ok) throw new Error(body.error || ("HTTP " + res.status));
location.reload();
});
}).catch(function (err) { btn.disabled = false; keySay(err.message, true); });
}
});
}
// No identity registered yet: make one here and register only its public half.
function generate(btn) {
btn.disabled = true;

View file

@ -1,33 +1,197 @@
// API keys (lsk_…) for the logicsrc CLI to authenticate.
// API keys (lsk_…) for the logicsrc CLI, CI and deploy boxes.
//
// Two kinds share one table:
// user what `logicsrc login` mints. Acts as the person, with the person's
// identity key. Unchanged since before machine keys existed.
// machine made on purpose for a box. Scoped to one team (and optionally a
// list of vault names), read-only unless asked otherwise, may expire,
// and carries its OWN identity public key (api_keys.public_key),
// registered by the machine on first use. Vault keys reach it through
// credshare_key_grants, never through the person's grants.
//
// Only sha256(key) is stored; the plaintext is shown once, at creation.
import { get, all, run } from "../db.mjs";
import { id, token, sha256 } from "./crypto.mjs";
// Returns { plaintext, row } — plaintext shown ONCE.
export async function createApiKey(userId, name = "cli") {
export const KEY_KINDS = ["user", "machine"];
const VAULT_NAME = /^[a-z0-9][a-z0-9-]{0,62}$/;
export class ApiKeyError extends Error {
constructor(status, message) {
super(message);
this.status = status;
}
}
/**
* Mint a key. Returns { plaintext, row } — plaintext is shown ONCE.
*
* `opts` is only meaningful for machine keys: { kind, teamId, vaultScope
* (array of vault names, or null for every vault in the team), readOnly
* (default true), expiresAt (ms epoch, or null) }.
*/
export async function createApiKey(userId, name = "cli", opts = {}) {
const kind = opts.kind === "machine" ? "machine" : "user";
const plaintext = "lsk_" + token(24);
const prefix = plaintext.slice(0, 12);
const row = { id: id(), user_id: userId, name, token_hash: sha256(plaintext), prefix, created_at: Date.now() };
const machine = kind === "machine";
const row = {
id: id(),
user_id: userId,
name,
token_hash: sha256(plaintext),
prefix,
created_at: Date.now(),
kind,
team_id: machine ? opts.teamId ?? null : null,
vault_scope: machine && Array.isArray(opts.vaultScope) && opts.vaultScope.length ? JSON.stringify(opts.vaultScope) : null,
read_only: machine ? (opts.readOnly === false ? 0 : 1) : 0,
expires_at: opts.expiresAt ?? null
};
await run(
`INSERT INTO api_keys (id, user_id, name, token_hash, prefix, created_at) VALUES (?,?,?,?,?,?)`,
[row.id, row.user_id, row.name, row.token_hash, row.prefix, row.created_at]
`INSERT INTO api_keys (id, user_id, name, token_hash, prefix, created_at, kind, team_id, vault_scope, read_only, expires_at) VALUES (?,?,?,?,?,?,?,?,?,?,?)`,
[row.id, row.user_id, row.name, row.token_hash, row.prefix, row.created_at, row.kind, row.team_id, row.vault_scope, row.read_only, row.expires_at]
);
return { plaintext, row };
}
// Resolve a Bearer token to its owning user (or null). Updates last_used_at.
export async function userForApiKey(bearer) {
if (!bearer) return null;
const key = await get(`SELECT * FROM api_keys WHERE token_hash = ?`, [sha256(bearer)]);
if (!key) return null;
await run(`UPDATE api_keys SET last_used_at = ? WHERE id = ?`, [Date.now(), key.id]);
return get(`SELECT * FROM users WHERE id = ?`, [key.user_id]);
/** A key row is usable when it exists and has not expired. Revoked keys are deleted rows. */
export function keyIsLive(key, now = Date.now()) {
if (!key) return false;
const exp = key.expires_at == null ? null : Number(key.expires_at);
return exp == null || exp > now;
}
export const listApiKeys = (userId) =>
all(`SELECT id, name, prefix, created_at, last_used_at FROM api_keys WHERE user_id = ? ORDER BY created_at DESC`, [userId]);
/**
* Resolve a Bearer token to { key, user } (or null). Expired keys resolve to
* null, which every caller answers with a 401. Updates last_used_at.
*/
export async function keyForBearer(bearerToken) {
if (!bearerToken || !bearerToken.startsWith("lsk_")) return null;
const key = await get(`SELECT * FROM api_keys WHERE token_hash = ?`, [sha256(bearerToken)]);
if (!keyIsLive(key)) return null;
const user = await get(`SELECT * FROM users WHERE id = ?`, [key.user_id]);
if (!user) return null;
await run(`UPDATE api_keys SET last_used_at = ? WHERE id = ?`, [Date.now(), key.id]);
return { key: normalizeKey(key), user };
}
export const revokeApiKey = (userId, keyId) =>
run(`DELETE FROM api_keys WHERE id = ? AND user_id = ?`, [keyId, userId]);
/**
* Resolve a Bearer token to its owning user, for routes that act AS the person
* (the personal vault, /api/me). Machine keys are refused here: a deploy box
* reads the team vaults it was granted and nothing of the person's own.
*/
export async function userForApiKey(bearerToken) {
const found = await keyForBearer(bearerToken);
if (!found || found.key.kind === "machine") return null;
return found.user;
}
/** Parse the stored columns into the shape the routes use. */
export function normalizeKey(key) {
let scope = null;
if (key.vault_scope) {
try {
const parsed = JSON.parse(key.vault_scope);
if (Array.isArray(parsed)) scope = parsed.filter((v) => typeof v === "string");
} catch { scope = null; }
}
return {
...key,
kind: key.kind === "machine" ? "machine" : "user",
vaultScope: scope,
readOnly: Number(key.read_only) === 1,
expiresAt: key.expires_at == null ? null : Number(key.expires_at)
};
}
/** Is `vaultName` inside this key's scope? User keys and unscoped machine keys see every vault. */
export function keyCoversVault(key, vaultName) {
if (!key || key.kind !== "machine") return true;
return !key.vaultScope || key.vaultScope.includes(vaultName);
}
export const listApiKeys = async (userId) =>
(await all(
`SELECT k.id, k.name, k.prefix, k.created_at, k.last_used_at, k.kind, k.team_id, k.vault_scope, k.read_only, k.expires_at, k.public_key, t.slug AS team_slug
FROM api_keys k LEFT JOIN credshare_teams t ON t.id = k.team_id
WHERE k.user_id = ? ORDER BY k.created_at DESC`,
[userId]
)).map(normalizeKey);
/** Public view of a key row (never the hash). */
export function keyJson(k) {
return {
id: k.id,
name: k.name,
prefix: k.prefix,
kind: k.kind,
team: k.team_slug ?? null,
vaults: k.vaultScope ?? null,
readOnly: k.kind === "machine" ? k.readOnly : false,
expiresAt: k.expiresAt ?? null,
expired: !keyIsLive(k),
publicKey: k.public_key ?? null,
createdAt: Number(k.created_at),
lastUsedAt: k.last_used_at == null ? null : Number(k.last_used_at)
};
}
/** Revoke = delete. The key's vault grants go with it (explicitly; SQLite FKs are off by default). */
export async function revokeApiKey(userId, keyId) {
const owned = await get(`SELECT id FROM api_keys WHERE id = ? AND user_id = ?`, [keyId, userId]);
if (!owned) return false;
await run(`DELETE FROM credshare_key_grants WHERE api_key_id = ?`, [keyId]);
await run(`DELETE FROM api_keys WHERE id = ? AND user_id = ?`, [keyId, userId]);
return true;
}
/**
* Validate a machine-key request from the API or the settings form and turn it
* into createApiKey options. Throws ApiKeyError with a status to answer with.
*
* `expires` accepts a ms epoch, an ISO date, or a duration like 30d / 12h / 90m.
*/
export async function machineKeyOptions(userId, { team, vaults, readOnly, expires }) {
const slug = String(team || "").trim().toLowerCase();
if (!slug) throw new ApiKeyError(422, "A machine key needs a team.");
const teamRow = await get(`SELECT * FROM credshare_teams WHERE slug = ?`, [slug]);
if (!teamRow) throw new ApiKeyError(404, `Unknown team: ${slug}`);
const member = await get(`SELECT * FROM credshare_members WHERE team_id = ? AND user_id = ? AND status = 'active'`, [teamRow.id, userId]);
if (!member) throw new ApiKeyError(403, "You are not a member of this team.");
const list = (Array.isArray(vaults) ? vaults : typeof vaults === "string" ? vaults.split(/[\s,]+/) : [])
.map((v) => String(v).trim().toLowerCase())
.filter(Boolean);
for (const v of list) {
if (!VAULT_NAME.test(v)) throw new ApiKeyError(422, `"${v}" is not a vault name (lowercase letters, numbers, dashes; e.g. web--prod).`);
}
const expiresAt = parseExpiry(expires);
if (expiresAt !== null && expiresAt <= Date.now()) throw new ApiKeyError(422, "That expiry is already in the past.");
return {
kind: "machine",
teamId: teamRow.id,
vaultScope: [...new Set(list)],
readOnly: readOnly === false || readOnly === "false" || readOnly === 0 || readOnly === "0" ? false : true,
expiresAt
};
}
export function parseExpiry(value, now = Date.now()) {
if (value === undefined || value === null || value === "" || value === "never") return null;
if (typeof value === "number" && Number.isFinite(value)) return value;
const s = String(value).trim();
const dur = /^(\d+)\s*(m|h|d|w|y)$/i.exec(s);
if (dur) {
const unit = { m: 60e3, h: 3600e3, d: 86400e3, w: 7 * 86400e3, y: 365 * 86400e3 }[dur[2].toLowerCase()];
return now + Number(dur[1]) * unit;
}
if (/^\d{12,}$/.test(s)) return Number(s);
const t = Date.parse(s);
if (Number.isNaN(t)) throw new ApiKeyError(422, `Cannot read expiry "${s}". Use 30d, 12h, or a date like 2027-01-01.`);
return t;
}
// Pull the Bearer token off a request.
export function bearer(req) {

View file

@ -74,7 +74,31 @@ function keyCard({ publicKey, hasGrant, grantCommand }) {
* The page body below the app bar. `secrets` are rows of credshare_secrets
* (name, version, updated_at only — ciphertext is fetched by vault.js).
*/
export function vaultPageBody({ team, vault, secrets, hasGrant, publicKey, email }) {
/**
* The caller's machine keys for this vault's team. Granting one seals the
* vault key to the machine's own public key, in the browser, after unlock --
* the same crypto_box_seal the CLI's `teams grant --key` does.
*/
function machineKeysCard({ machineKeys, team, parts }) {
if (!machineKeys || machineKeys.length === 0) return "";
const grantCmd = (name) => `logicsrc teams grant ${team.slug} ${parts ? `${parts.project} ${parts.env}` : "<project> <env>"} --key ${name}`;
const rows = machineKeys.map((k) => {
const state = k.granted
? `<span class="pill on">granted</span> <button class="btn compact danger" type="button" data-action="revoke-key" data-key-id="${esc(k.id)}">Revoke</button>`
: k.publicKey
? `<button class="btn compact" type="button" data-action="grant-key" data-key-id="${esc(k.id)}" data-key-public="${esc(k.publicKey)}" data-key-name="${esc(k.name)}" disabled title="Unlock with your key first">Grant</button>`
: `<span class="pill warn">not used yet</span> <span class="faint" style="font-size:.74rem">run one command with the key on the box first</span>`;
return `<tr><td><code>${esc(k.name)}</code> <span class="faint">${esc(k.prefix)}…</span></td><td>${k.readOnly ? "read-only" : "read-write"}</td><td><div class="member-actions">${state}</div></td></tr>`;
}).join("");
return `<div class="card" id="machine-keys" style="margin-bottom:18px"><div class="card-head"><span class="h">Machine keys</span></div>
<div class="card-body">
<p class="dim" style="margin-top:0;font-size:.85rem">Your machine API keys scoped to this vault. Unlock above, then grant: the vault key is sealed to the machine's own key in this browser. Or from a terminal: <code>${esc(grantCmd(machineKeys[0].name))}</code></p>
<div class="table-scroll"><table><thead><tr><th>Key</th><th>Access</th><th></th></tr></thead><tbody>${rows}</tbody></table></div>
<p data-role="key-status" class="mono" style="font-size:.8rem;margin-bottom:0"></p>
</div></div>`;
}
export function vaultPageBody({ team, vault, secrets, hasGrant, publicKey, email, machineKeys = [] }) {
const parts = splitVaultName(vault.name);
const grantCommand = `logicsrc teams grant ${team.slug} ${parts ? `${parts.project} ${parts.env}` : "<project> <env>"} ${email || "<your email>"}`;
const rows = secrets.map((s) => `<tr data-key-name="${esc(s.name)}">
@ -89,6 +113,7 @@ export function vaultPageBody({ team, vault, secrets, hasGrant, publicKey, email
<p class="faint mono" style="font-size:.8rem;margin:0 0 6px"><a href="/dashboard">teams</a> / ${esc(team.slug)} / vaults</p>
<div class="section-title"><h1 style="font-size:1.5rem"><code>${esc(vault.name)}</code></h1><span class="count">${secrets.length}</span></div>
${keyCard({ publicKey, hasGrant, grantCommand })}
${machineKeysCard({ machineKeys, team, parts })}
<div class="card"><div class="card-body">
${secrets.length
? `<div class="table-scroll"><table><thead><tr><th>Name</th><th>Value</th><th>v</th><th>Updated (UTC)</th></tr></thead><tbody>${rows}</tbody></table></div>`

View file

@ -0,0 +1,29 @@
-- Machine API keys: headless credentials for deploy boxes and CI.
--
-- A 'user' key is what `logicsrc login` mints: it acts as the person, with the
-- person's identity key. A 'machine' key is created on purpose, is scoped to
-- one team (and optionally a list of vault names), is read-only unless asked
-- otherwise, may expire, and carries its OWN identity public key, registered by
-- the machine on first use. Vault keys are sealed to that public key in
-- credshare_key_grants, so a machine never holds a person's secret key and a
-- revoked machine key reads nothing.
--
-- read_only defaults to 0 so every existing (person) key keeps writing; the
-- app sets it to 1 for a machine key unless --read-write is asked for.
ALTER TABLE api_keys ADD COLUMN kind TEXT NOT NULL DEFAULT 'user';
ALTER TABLE api_keys ADD COLUMN team_id TEXT;
ALTER TABLE api_keys ADD COLUMN vault_scope TEXT;
ALTER TABLE api_keys ADD COLUMN read_only bigint NOT NULL DEFAULT 0;
ALTER TABLE api_keys ADD COLUMN expires_at bigint;
ALTER TABLE api_keys ADD COLUMN public_key TEXT;
ALTER TABLE credshare_audit ADD COLUMN actor_key_id TEXT;
CREATE TABLE IF NOT EXISTS credshare_key_grants (
vault_id TEXT NOT NULL REFERENCES credshare_vaults(id) ON DELETE CASCADE,
api_key_id TEXT NOT NULL REFERENCES api_keys(id) ON DELETE CASCADE,
wrapped_dek TEXT NOT NULL,
granted_by TEXT NOT NULL REFERENCES users(id),
created_at bigint NOT NULL,
PRIMARY KEY (vault_id, api_key_id)
);
CREATE INDEX IF NOT EXISTS idx_key_grants_key ON credshare_key_grants(api_key_id);

View file

@ -0,0 +1,29 @@
-- Machine API keys: headless credentials for deploy boxes and CI.
--
-- A 'user' key is what `logicsrc login` mints: it acts as the person, with the
-- person's identity key. A 'machine' key is created on purpose, is scoped to
-- one team (and optionally a list of vault names), is read-only unless asked
-- otherwise, may expire, and carries its OWN identity public key, registered by
-- the machine on first use. Vault keys are sealed to that public key in
-- credshare_key_grants, so a machine never holds a person's secret key and a
-- revoked machine key reads nothing.
--
-- read_only defaults to 0 so every existing (person) key keeps writing; the
-- app sets it to 1 for a machine key unless --read-write is asked for.
ALTER TABLE api_keys ADD COLUMN kind TEXT NOT NULL DEFAULT 'user';
ALTER TABLE api_keys ADD COLUMN team_id TEXT;
ALTER TABLE api_keys ADD COLUMN vault_scope TEXT;
ALTER TABLE api_keys ADD COLUMN read_only INTEGER NOT NULL DEFAULT 0;
ALTER TABLE api_keys ADD COLUMN expires_at INTEGER;
ALTER TABLE api_keys ADD COLUMN public_key TEXT;
ALTER TABLE credshare_audit ADD COLUMN actor_key_id TEXT;
CREATE TABLE IF NOT EXISTS credshare_key_grants (
vault_id TEXT NOT NULL REFERENCES credshare_vaults(id) ON DELETE CASCADE,
api_key_id TEXT NOT NULL REFERENCES api_keys(id) ON DELETE CASCADE,
wrapped_dek TEXT NOT NULL,
granted_by TEXT NOT NULL REFERENCES users(id),
created_at INTEGER NOT NULL,
PRIMARY KEY (vault_id, api_key_id)
);
CREATE INDEX IF NOT EXISTS idx_key_grants_key ON credshare_key_grants(api_key_id);

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) => {

View file

@ -10,6 +10,7 @@ import { authRouter } from "./routes/auth.mjs";
import { passkeyRouter } from "./routes/passkey.mjs";
import { coinpayRouter } from "./routes/coinpay.mjs";
import { credshareRouter } from "./routes/credshare.mjs";
import { apiKeysRouter } from "./routes/apikeys.mjs";
import { opencredsRouter } from "./routes/opencreds.mjs";
import { cliRouter } from "./routes/cli.mjs";
import { pagesRouter } from "./routes/pages.mjs";
@ -50,6 +51,7 @@ app.use(authRouter); // GET / (+ /auth/login|register|logout)
app.use(passkeyRouter);
app.use(coinpayRouter);
app.use(credshareRouter); // /api/credshare/* (session or lsk_ Bearer)
app.use(apiKeysRouter); // /api/keys (session or a person's lsk_ key; never a machine key)
app.use(opencredsRouter); // /api/opencreds/* — personal vault sync (session or lsk_ Bearer)
app.use(cliRouter); // /cli/authorize, /cli/token, /api/me
app.use(pagesRouter); // /dashboard, /teams/*, /settings

View file

@ -28,7 +28,7 @@ async function migrate() {
await db.execute("DROP SCHEMA public CASCADE");
await db.execute("CREATE SCHEMA public");
}
for (const file of ["001_auth.sql", "002_credshare.sql"]) {
for (const file of ["001_auth.sql", "002_credshare.sql", "005_machine_keys.sql"]) {
const sql = readFileSync(join(here, "..", "src", isPostgres ? "migrations-pg" : "migrations", file), "utf8");
for (const statement of sql.split(/;\s*$/m).map((s) => s.trim()).filter(Boolean)) {
await db.execute(statement);

View file

@ -33,7 +33,7 @@ async function migrate() {
await db.execute("DROP SCHEMA public CASCADE");
await db.execute("CREATE SCHEMA public");
}
for (const file of ["001_auth.sql", "002_credshare.sql"]) {
for (const file of ["001_auth.sql", "002_credshare.sql", "005_machine_keys.sql"]) {
const sql = readFileSync(join(here, "..", "src", isPostgres ? "migrations-pg" : "migrations", file), "utf8");
for (const statement of sql.split(/;\s*$/m).map((s) => s.trim()).filter(Boolean)) {
await db.execute(statement);

View file

@ -0,0 +1,330 @@
// Machine API keys: a credential for a deploy box or CI that is narrower than
// the person who made it.
//
// What these pin: the key is stored hashed and shown once; a machine key sees
// one team and only its scoped vaults; it opens a vault only through a grant
// sealed to ITS OWN public key (never the person's); a read-only key is refused
// every write; it cannot mint keys, read /api/me or the personal vault; expired
// and revoked keys are 401; and a person's key behaves exactly as before.
process.env.DATABASE_URL = process.env.PWA_TEST_DATABASE_URL || ":memory:";
import test from "node:test";
import assert from "node:assert/strict";
import { readFileSync } from "node:fs";
import { fileURLToPath } from "node:url";
import { dirname, join } from "node:path";
import express from "express";
const here = dirname(fileURLToPath(import.meta.url));
const { db, run, get, all, isPostgres } = await import("../src/db.mjs");
const { credshareRouter } = await import("../src/routes/credshare.mjs");
const { apiKeysRouter } = await import("../src/routes/apikeys.mjs");
const { cliRouter } = await import("../src/routes/cli.mjs");
const { opencredsRouter } = await import("../src/routes/opencreds.mjs");
const { createApiKey, keyForBearer, userForApiKey, parseExpiry } = await import("../src/lib/apikey.mjs");
const { sha256 } = await import("../src/lib/crypto.mjs");
async function migrate() {
if (isPostgres) {
await db.execute("DROP SCHEMA public CASCADE");
await db.execute("CREATE SCHEMA public");
}
for (const file of ["001_auth.sql", "002_credshare.sql", "005_machine_keys.sql"]) {
const sql = readFileSync(join(here, "..", "src", isPostgres ? "migrations-pg" : "migrations", file), "utf8");
for (const statement of sql.split(/;\s*$/m).map((s) => s.trim()).filter(Boolean)) {
await db.execute(statement);
}
}
}
/** The app as production mounts it, minus sessions: every request is Bearer-authed. */
async function serve() {
const app = express();
app.use(express.json());
app.use(credshareRouter);
app.use(apiKeysRouter);
app.use(opencredsRouter);
app.use(cliRouter);
const server = app.listen(0);
await new Promise((resolve) => server.once("listening", resolve));
const base = `http://127.0.0.1:${server.address().port}`;
const call = async (method, path, token, body) => {
const headers = { accept: "application/json" };
if (token) headers.authorization = `Bearer ${token}`;
if (body !== undefined) headers["content-type"] = "application/json";
const res = await fetch(`${base}${path}`, { method, headers, body: body === undefined ? undefined : JSON.stringify(body) });
const text = await res.text();
return { status: res.status, body: text ? JSON.parse(text) : null };
};
return {
get: (path, token) => call("GET", path, token),
post: (path, token, body) => call("POST", path, token, body ?? {}),
put: (path, token, body) => call("PUT", path, token, body ?? {}),
del: (path, token) => call("DELETE", path, token),
close: () => new Promise((resolve) => server.close(resolve))
};
}
const now = Date.now();
/** Ann owns team acme (vaults web--prod, api--prod) and is in team other (vault x--prod). */
async function seed() {
await run(`INSERT INTO users (id, email, created_at) VALUES (?,?,?)`, ["u_ann", "ann@example.com", now]);
await run(`INSERT INTO credshare_keys (user_id, public_key, updated_at) VALUES (?,?,?)`, ["u_ann", "pk-ann", now]);
for (const [tid, slug] of [["t_acme", "acme"], ["t_other", "other"]]) {
await run(`INSERT INTO credshare_teams (id, slug, name, created_by, created_at) VALUES (?,?,?,?,?)`, [tid, slug, slug, "u_ann", now]);
await run(`INSERT INTO credshare_members (id, team_id, user_id, email, role, status, created_at) VALUES (?,?,?,?,?,?,?)`,
[`m_${slug}`, tid, "u_ann", "ann@example.com", "owner", "active", now]);
}
for (const [vid, tid, name] of [["v_web", "t_acme", "web--prod"], ["v_api", "t_acme", "api--prod"], ["v_x", "t_other", "x--prod"]]) {
await run(`INSERT INTO credshare_vaults (id, team_id, name, created_by, created_at) VALUES (?,?,?,?,?)`, [vid, tid, name, "u_ann", now]);
await run(`INSERT INTO credshare_vault_grants (vault_id, user_id, wrapped_dek, granted_by, created_at) VALUES (?,?,?,?,?)`, [vid, "u_ann", `dek-ann-${vid}`, "u_ann", now]);
await run(`INSERT INTO credshare_secrets (vault_id, name, nonce, ciphertext, fingerprint, version, updated_by, updated_at) VALUES (?,?,?,?,?,?,?,?)`,
[vid, "API_KEY", "n", "c", "fp", 1, "u_ann", now]);
}
}
await migrate();
await seed();
const http = await serve();
test.after(() => http.close());
// Ann's person key, minted the way `logicsrc login` mints it.
const { plaintext: annKey } = await createApiKey("u_ann", "laptop");
test("a key is stored as sha256 with a display prefix, and the plaintext only resolves while live", async () => {
const { plaintext, row } = await createApiKey("u_ann", "hash-check");
assert.match(plaintext, /^lsk_/);
const stored = await get(`SELECT * FROM api_keys WHERE id = ?`, [row.id]);
assert.equal(stored.token_hash, sha256(plaintext));
assert.notEqual(stored.token_hash, plaintext);
assert.equal(stored.prefix, plaintext.slice(0, 12));
assert.equal(stored.kind, "user");
assert.equal(Number(stored.read_only), 0, "person keys are never read-only");
assert.equal((await keyForBearer(plaintext)).user.id, "u_ann");
assert.equal(await keyForBearer(plaintext + "x"), null);
assert.equal(await keyForBearer("not-a-key"), null);
});
test("expiry durations parse, and a past date is refused", () => {
assert.equal(parseExpiry("30d", 0), 30 * 86400e3);
assert.equal(parseExpiry("12h", 0), 12 * 3600e3);
assert.equal(parseExpiry(null), null);
assert.equal(parseExpiry("2027-01-01T00:00:00Z"), Date.parse("2027-01-01T00:00:00Z"));
assert.throws(() => parseExpiry("soonish"));
});
test("a person mints a machine key over the API; the secret is in that response only", async () => {
const made = await http.post("/api/keys", annKey, { name: "dev2-deploy", kind: "machine", team: "acme", vaults: ["web--prod"], readOnly: true, expiresAt: "90d" });
assert.equal(made.status, 201);
assert.match(made.body.secret, /^lsk_/);
assert.equal(made.body.key.kind, "machine");
assert.equal(made.body.key.team, "acme");
assert.deepEqual(made.body.key.vaults, ["web--prod"]);
assert.equal(made.body.key.readOnly, true);
assert.ok(made.body.key.expiresAt > Date.now());
const listed = await http.get("/api/keys", annKey);
assert.equal(listed.status, 200);
const row = listed.body.keys.find((k) => k.name === "dev2-deploy");
assert.ok(row);
assert.equal(JSON.stringify(listed.body).includes(made.body.secret), false, "the list never carries a secret");
assert.equal("token_hash" in row, false);
});
test("machine key requests are validated: team required, membership required, vault names checked", async () => {
assert.equal((await http.post("/api/keys", annKey, { name: "m", kind: "machine" })).status, 422);
assert.equal((await http.post("/api/keys", annKey, { name: "m", kind: "machine", team: "nope" })).status, 404);
assert.equal((await http.post("/api/keys", annKey, { name: "m", kind: "machine", team: "acme", vaults: ["Bad Name"] })).status, 422);
assert.equal((await http.post("/api/keys", annKey, { name: "m", kind: "machine", team: "acme", expiresAt: "2001-01-01" })).status, 422);
assert.equal((await http.post("/api/keys", null, { name: "m" })).status, 401);
});
async function machineKey(opts = {}) {
const { plaintext, row } = await createApiKey("u_ann", opts.name || `m-${Math.random().toString(36).slice(2, 8)}`, {
kind: "machine",
teamId: "t_acme",
vaultScope: opts.vaults ?? ["web--prod"],
readOnly: opts.readOnly ?? true,
expiresAt: opts.expiresAt ?? null
});
return { token: plaintext, id: row.id, name: row.name };
}
test("a machine key cannot mint, list or revoke keys", async () => {
const m = await machineKey();
assert.equal((await http.post("/api/keys", m.token, { name: "escalate", kind: "user" })).status, 403);
assert.equal((await http.post("/api/keys", m.token, { name: "escalate", kind: "machine", team: "acme" })).status, 403);
assert.equal((await http.get("/api/keys", m.token)).status, 403);
assert.equal((await http.del(`/api/keys/${m.id}`, m.token)).status, 403);
});
test("a machine key cannot read /api/me or the personal vault; a person key still can read /api/me", async () => {
const m = await machineKey();
assert.equal((await http.get("/api/me", m.token)).status, 403);
assert.equal((await http.get("/api/opencreds/vault", m.token)).status, 403);
assert.equal(await userForApiKey(m.token), null);
const me = await http.get("/api/me", annKey);
assert.equal(me.status, 200);
assert.equal(me.body.email, "ann@example.com");
});
test("a machine key registers its OWN public key, leaving the person's untouched", async () => {
const m = await machineKey();
const reg = await http.post("/api/credshare/keys", m.token, { publicKey: "pk-machine-1" });
assert.equal(reg.status, 200, "registering is allowed even for a read-only key");
assert.equal((await get(`SELECT public_key FROM api_keys WHERE id = ?`, [m.id])).public_key, "pk-machine-1");
assert.equal((await get(`SELECT public_key FROM credshare_keys WHERE user_id = ?`, ["u_ann"])).public_key, "pk-ann");
const me = await http.get("/api/credshare/me", m.token);
assert.equal(me.status, 200);
assert.equal(me.body.user.publicKey, "pk-machine-1");
assert.deepEqual(me.body.teams.map((t) => t.slug), ["acme"]);
assert.equal(me.body.key.kind, "machine");
assert.equal(me.body.key.team, "acme");
assert.deepEqual(me.body.key.vaults, ["web--prod"]);
assert.equal(me.body.key.readOnly, true);
});
test("a machine key sees one team and only its scoped vaults", async () => {
const m = await machineKey({ vaults: ["web--prod"] });
const teams = await http.get("/api/credshare/teams", m.token);
assert.deepEqual(teams.body.teams.map((t) => t.slug), ["acme"]);
const vaults = await http.get("/api/credshare/teams/acme/vaults", m.token);
assert.equal(vaults.status, 200);
assert.deepEqual(vaults.body.vaults.map((v) => v.name), ["web--prod"]);
assert.equal(vaults.body.vaults[0].hasAccess, false, "access means a grant to the KEY, not to Ann");
assert.equal((await http.get("/api/credshare/teams/other/vaults", m.token)).status, 403);
assert.equal((await http.get("/api/credshare/vaults/v_api/secrets", m.token)).status, 403);
assert.equal((await http.get("/api/credshare/vaults/v_x/secrets", m.token)).status, 403);
assert.equal((await http.get("/api/credshare/vaults/v_web/secrets", m.token)).status, 200);
// An unscoped machine key sees every vault in its team, and still no other team.
const all = await machineKey({ vaults: [] });
const allVaults = await http.get("/api/credshare/teams/acme/vaults", all.token);
assert.deepEqual(allVaults.body.vaults.map((v) => v.name).sort(), ["api--prod", "web--prod"]);
});
test("the vault key reaches a machine only through a grant sealed to its own key", async () => {
const m = await machineKey({ name: "grant-me" });
// Not registered yet: a grant is refused with the instruction to use the key once.
const early = await http.post("/api/credshare/vaults/v_web/key-grants", annKey, { keyId: m.id, wrappedDek: "sealed-to-machine" });
assert.equal(early.status, 409);
assert.equal(early.body.code, "no_public_key");
await http.post("/api/credshare/keys", m.token, { publicKey: "pk-grant-me" });
const before = await http.get("/api/credshare/vaults/v_web/grant", m.token);
assert.equal(before.status, 403);
assert.equal(before.body.code, "no_key_grant");
// Out-of-scope vault: refused even for the owner.
assert.equal((await http.post("/api/credshare/vaults/v_api/key-grants", annKey, { keyId: m.id, wrappedDek: "x" })).status, 409);
// A machine key cannot grant itself (or anything).
assert.equal((await http.post("/api/credshare/vaults/v_web/key-grants", m.token, { keyId: m.id, wrappedDek: "x" })).status, 403);
const granted = await http.post("/api/credshare/vaults/v_web/key-grants", annKey, { keyId: m.id, wrappedDek: "sealed-to-machine" });
assert.equal(granted.status, 201);
const after = await http.get("/api/credshare/vaults/v_web/grant", m.token);
assert.equal(after.status, 200);
assert.equal(after.body.wrappedDek, "sealed-to-machine", "never Ann's wrapped key");
const listed = await http.get("/api/credshare/teams/acme/vaults", m.token);
assert.equal(listed.body.vaults.find((v) => v.name === "web--prod").hasAccess, true);
// The read is in the vault's audit trail, attributed to the key.
const reads = await all(`SELECT * FROM credshare_audit WHERE vault_id = ? AND action = 'vault:read' AND actor_key_id = ?`, ["v_web", m.id]);
assert.equal(reads.length, 1);
assert.equal(reads[0].actor_user_id, "u_ann");
// Ann's own grant is untouched.
assert.equal((await http.get("/api/credshare/vaults/v_web/grant", annKey)).body.wrappedDek, "dek-ann-v_web");
});
test("a read-only machine key is refused every write; a read-write one may write a granted vault", async () => {
const ro = await machineKey({ readOnly: true });
const upsert = { upserts: [{ name: "NEW", nonce: "n", ciphertext: "c", fingerprint: "f" }], deletes: [] };
const roPut = await http.put("/api/credshare/vaults/v_web/secrets", ro.token, upsert);
assert.equal(roPut.status, 403);
assert.equal(roPut.body.code, "read_only_key");
assert.equal((await http.post("/api/credshare/teams/acme/vaults", ro.token, { name: "new--prod" })).status, 403);
assert.equal((await http.post("/api/credshare/teams", ro.token, { slug: "evil" })).status, 403);
assert.equal((await http.post("/api/credshare/teams/acme/invites", ro.token, { email: "x@example.com" })).status, 403);
assert.equal((await http.post("/api/credshare/vaults/v_web/grants", ro.token, { email: "ann@example.com", wrappedDek: "x" })).status, 403);
assert.equal((await http.get("/api/credshare/users?email=ann@example.com", ro.token)).status, 403);
const rw = await machineKey({ readOnly: false });
await http.post("/api/credshare/keys", rw.token, { publicKey: "pk-rw" });
// Write needs a grant first, so a key cannot plant values in a vault it cannot read.
assert.equal((await http.put("/api/credshare/vaults/v_web/secrets", rw.token, upsert)).status, 403);
await http.post("/api/credshare/vaults/v_web/key-grants", annKey, { keyId: rw.id, wrappedDek: "sealed-rw" });
const ok = await http.put("/api/credshare/vaults/v_web/secrets", rw.token, upsert);
assert.equal(ok.status, 200);
const row = await get(`SELECT * FROM credshare_audit WHERE vault_id = ? AND key_name = 'NEW' AND action = 'secret:add'`, ["v_web"]);
assert.equal(row.actor_key_id, rw.id);
// Team admin stays people-only for a read-write key too.
assert.equal((await http.post("/api/credshare/teams", rw.token, { slug: "evil" })).status, 403);
await run(`DELETE FROM credshare_secrets WHERE vault_id = ? AND name = 'NEW'`, ["v_web"]);
});
test("expired and revoked keys are 401, and revoking drops the key's grants", async () => {
const expired = await machineKey({ expiresAt: Date.now() - 1000 });
assert.equal((await http.get("/api/credshare/me", expired.token)).status, 401);
const m = await machineKey();
await http.post("/api/credshare/keys", m.token, { publicKey: "pk-revoke" });
await http.post("/api/credshare/vaults/v_web/key-grants", annKey, { keyId: m.id, wrappedDek: "sealed" });
assert.equal((await http.get("/api/credshare/vaults/v_web/grant", m.token)).status, 200);
assert.equal((await http.del(`/api/keys/${m.id}`, annKey)).status, 200);
assert.equal((await http.get("/api/credshare/vaults/v_web/grant", m.token)).status, 401);
assert.equal((await all(`SELECT * FROM credshare_key_grants WHERE api_key_id = ?`, [m.id])).length, 0);
assert.equal((await http.del(`/api/keys/${m.id}`, annKey)).status, 404);
});
test("re-registering a different public key drops the grants sealed to the old one", async () => {
const m = await machineKey();
await http.post("/api/credshare/keys", m.token, { publicKey: "pk-old" });
await http.post("/api/credshare/vaults/v_web/key-grants", annKey, { keyId: m.id, wrappedDek: "sealed-old" });
const again = await http.post("/api/credshare/keys", m.token, { publicKey: "pk-new" });
assert.equal(again.body.droppedGrants, 1);
assert.equal((await http.get("/api/credshare/vaults/v_web/grant", m.token)).status, 403);
});
test("a re-key re-seals the machine grants it is given and drops the rest", async () => {
const keep = await machineKey({ name: "keep" });
const drop = await machineKey({ name: "drop" });
for (const k of [keep, drop]) {
await http.post("/api/credshare/keys", k.token, { publicKey: `pk-${k.name}` });
await http.post("/api/credshare/vaults/v_web/key-grants", annKey, { keyId: k.id, wrappedDek: `old-${k.name}` });
}
const listed = await http.get("/api/credshare/vaults/v_web/key-grants", annKey);
assert.deepEqual(listed.body.keyGrants.map((g) => g.name).filter((n) => n === "keep" || n === "drop").sort(), ["drop", "keep"]);
assert.equal(listed.body.keyGrants.find((g) => g.name === "keep").publicKey, "pk-keep");
const secrets = (await all(`SELECT name, fingerprint FROM credshare_secrets WHERE vault_id = ?`, ["v_web"]))
.map((s) => ({ name: s.name, nonce: "n2", ciphertext: "c2", fingerprint: s.fingerprint }));
const rekey = await http.post("/api/credshare/vaults/v_web/rekey", annKey, {
grants: [{ email: "ann@example.com", wrappedDek: "dek-ann-v_web" }],
secrets,
keyGrants: [{ keyId: keep.id, wrappedDek: "new-keep" }]
});
assert.equal(rekey.status, 200, JSON.stringify(rekey.body));
assert.deepEqual(rekey.body.keysResealed, ["keep"]);
assert.ok(rekey.body.keysDropped.includes("drop"));
assert.equal((await http.get("/api/credshare/vaults/v_web/grant", keep.token)).body.wrappedDek, "new-keep");
assert.equal((await http.get("/api/credshare/vaults/v_web/grant", drop.token)).status, 403);
});
test("a person's key still registers the person's identity key, as before", async () => {
const { plaintext } = await createApiKey("u_ann", "ci-person");
const reg = await http.post("/api/credshare/keys", plaintext, { publicKey: "pk-ann" });
assert.equal(reg.status, 200);
assert.equal((await get(`SELECT public_key FROM credshare_keys WHERE user_id = ?`, ["u_ann"])).public_key, "pk-ann");
const me = await http.get("/api/credshare/me", plaintext);
assert.deepEqual(me.body.teams.map((t) => t.slug).sort(), ["acme", "other"]);
assert.equal(me.body.key.kind, "user");
});

View file

@ -21,7 +21,7 @@ if (isPostgres) {
await db.execute("DROP SCHEMA public CASCADE");
await db.execute("CREATE SCHEMA public");
}
for (const file of ["001_auth.sql", "002_credshare.sql"]) {
for (const file of ["001_auth.sql", "002_credshare.sql", "005_machine_keys.sql"]) {
const sql = readFileSync(join(here, "..", "src", isPostgres ? "migrations-pg" : "migrations", file), "utf8");
for (const statement of sql.split(/;\s*$/m).map((s) => s.trim()).filter(Boolean)) await db.execute(statement);
}

View file

@ -23,7 +23,7 @@ async function migrate() {
await db.execute("DROP SCHEMA public CASCADE");
await db.execute("CREATE SCHEMA public");
}
for (const file of ["001_auth.sql", "002_credshare.sql"]) {
for (const file of ["001_auth.sql", "002_credshare.sql", "005_machine_keys.sql"]) {
const sql = readFileSync(join(here, "..", "src", isPostgres ? "migrations-pg" : "migrations", file), "utf8");
for (const statement of sql.split(/;\s*$/m).map((s) => s.trim()).filter(Boolean)) {
await db.execute(statement);

View file

@ -144,7 +144,7 @@
},
"packages/cli": {
"name": "@logicsrc/cli",
"version": "0.7.0",
"version": "0.8.0",
"bin": {
"logicsrc": "dist/index.js",
},

View file

@ -362,6 +362,54 @@ Safety properties, all enforced rather than documented:
- A rotation that would leave the caller ungranted, grant nobody, or cover the
wrong number of secrets is rejected before anything is written.
A machine API key holding the vault (see below) is re-sealed to the new key too,
unless its owner is revoked in the same rotation; a key that is not re-sealed
loses access, never keeps a stale grant.
### Machine API keys (deploy boxes and CI)
A person's key (what `logicsrc login` stores) acts as that person, with their
identity key. Logging a fresh box in with one used to upload the box's new
keypair as the person's identity, replacing the real one. A **machine key** is
the credential for a box instead:
- scoped to **one team**, and optionally to named vaults (`<project>--<env>`);
- **read-only** unless created with `--read-write` (then it may write only
vaults it was granted), and never able to manage teams, members or grants;
- optionally **expiring**; revoked or expired keys get a 401;
- unable to mint, list or revoke keys, to read `/api/me`, or to touch the
personal vault;
- holding its **own identity key**, generated on the box the first time a
command runs with it and registered on the key, never on the person. The
vault key reaches it as a grant sealed to that public key
(`credshare_key_grants`), and every read is in the vault's audit trail
with the key's id.
```bash
# On your machine: make the key (the secret is shown once; --out writes it 0600)
logicsrc keys create dev2-deploy --team acme --vault web--prod --expires 90d --out deploy.key
# On the box, once: creates ~/.config/logicsrc/keys/<prefix>.json (0600) and registers its public key
LOGICSRC_API_KEY=$(cat deploy.key) logicsrc whoami
# On your machine: seal the vault key to the box's key
logicsrc teams grant acme web prod --key dev2-deploy
# On the box, from then on (or store the key with: logicsrc login --api-key <key>)
LOGICSRC_API_KEY=$(cat deploy.key) logicsrc teams pull acme web prod --env .env
logicsrc keys list # scope, expiry, whether the box registered yet
logicsrc keys revoke dev2-deploy # 401 from now on; its grants are deleted
```
The same keys are in the web app (**Settings ▸ API keys**: kind, team, vaults,
read-only, expiry; a vault page grants a machine key in the browser after
unlock), in the API (`GET|POST /api/keys`, `DELETE /api/keys/:id`,
`GET|POST /api/credshare/vaults/:id/key-grants`,
`DELETE /api/credshare/vaults/:id/key-grants/:keyId`), and in the MCP server
(`list_api_keys`, `create_api_key`, `revoke_api_key`, authenticated with
`LOGICSRC_API_KEY`, which must be a person's key).
`logicsrc login` picks its flow from the machine it runs on:
- **Has its own browser** → loopback OAuth-PKCE: a `127.0.0.1` listener catches
@ -370,7 +418,9 @@ Safety properties, all enforced rather than documented:
prints a short code, you approve it from a browser on any other machine.
Force it with `--device`. A loopback redirect would be useless here — the
browser's `127.0.0.1` is not the CLI's machine.
- **Unattended** → `--token lsk_…` from **Settings ▸ API keys**.
- **Unattended** → `--api-key lsk_…` with a machine key (its own identity; see
above), or `--token lsk_…` with a person's key from **Settings ▸ API keys**.
`--token` given a machine key takes the `--api-key` path.
It talks to the hosted credentials app by default. Point it elsewhere (local dev,
self-hosted) with `LOGICSRC_API=http://localhost:8080 logicsrc login` or

View file

@ -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",

View file

@ -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
View 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));
}

View 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/);
});
});

View file

@ -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;

View file

@ -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}`);

View 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();
});
});

View 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)}`))
);
}

View file

@ -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;
}

View file

@ -63,6 +63,62 @@ export interface RekeyResult {
rekeyed: number;
granted: string[];
revoked: string[];
/** Machine keys re-sealed to the new DEK, and the ones dropped (servers before machine keys omit these). */
keysResealed?: string[];
keysDropped?: string[];
}
/** The credential a request was made with, as /api/credshare/me describes it. Null for a browser session. */
export interface RemoteKeyInfo {
id: string;
name: string;
prefix: string;
kind: "user" | "machine";
/** Machine keys only: the one team the key may see. */
team: string | null;
/** Machine keys only: the vault names it may see, or null for every vault in the team. */
vaults: string[] | null;
readOnly: boolean;
expiresAt: number | null;
}
/** One of the caller's API keys, as GET /api/keys lists it. Never carries a secret. */
export interface RemoteApiKey {
id: string;
name: string;
prefix: string;
kind: "user" | "machine";
team: string | null;
vaults: string[] | null;
readOnly: boolean;
expiresAt: number | null;
expired: boolean;
/** The machine's own identity public key, once it has run one command. */
publicKey: string | null;
createdAt: number;
lastUsedAt: number | null;
}
export interface CreateApiKeyInput {
name: string;
kind?: "user" | "machine";
team?: string;
vaults?: string[];
readOnly?: boolean;
/** ms epoch, an ISO date, or a duration such as 30d / 12h. */
expiresAt?: number | string;
}
/** A machine key holding a vault, with its public key so a re-key can re-seal to it. */
export interface RemoteKeyGrant {
keyId: string;
name: string;
prefix: string;
owner: string | null;
publicKey: string | null;
readOnly: boolean;
expiresAt: number | null;
grantedAt: number;
}
export class TeamApiError extends Error {
@ -88,11 +144,15 @@ export class TeamClient {
this.token = token;
}
private async request<T>(method: string, path: string, body?: unknown): Promise<T> {
private request<T>(method: string, path: string, body?: unknown): Promise<T> {
return this.requestAt<T>(`/api/credshare${path}`, method, body);
}
private async requestAt<T>(fullPath: string, method: string, body?: unknown): Promise<T> {
const headers: Record<string, string> = { accept: "application/json" };
if (body !== undefined) headers["content-type"] = "application/json";
if (this.token) headers["authorization"] = `Bearer ${this.token}`;
const response = await fetch(`${this.apiUrl}/api/credshare${path}`, {
const response = await fetch(`${this.apiUrl}${fullPath}`, {
method,
headers,
body: body === undefined ? undefined : JSON.stringify(body)
@ -117,7 +177,7 @@ export class TeamClient {
return this.request<{ email: string; publicKey: string }>("POST", "/keys", { publicKey });
}
me() {
return this.request<{ user: RemoteUser; teams: RemoteTeam[] }>("GET", "/me");
return this.request<{ user: RemoteUser; teams: RemoteTeam[]; key?: RemoteKeyInfo | null }>("GET", "/me");
}
logout() {
return this.request<{ ok: boolean }>("POST", "/logout");
@ -193,10 +253,33 @@ export class TeamClient {
grants: Array<{ email: string; wrappedDek: string }>;
secrets: Array<{ name: string; nonce: string; ciphertext: string; fingerprint: string }>;
revoke: string[];
keyGrants?: Array<{ keyId: string; wrappedDek: string }>;
}
) {
return this.request<RekeyResult>("POST", `/vaults/${encodeURIComponent(vaultId)}/rekey`, body);
}
// ---- machine-key grants (the vault key sealed to a machine key's own public key) ----
listKeyGrants(vaultId: string) {
return this.request<{ keyGrants: RemoteKeyGrant[] }>("GET", `/vaults/${encodeURIComponent(vaultId)}/key-grants`);
}
putKeyGrant(vaultId: string, keyId: string, wrappedDek: string) {
return this.request<{ ok: boolean; keyId: string; name: string }>("POST", `/vaults/${encodeURIComponent(vaultId)}/key-grants`, { keyId, wrappedDek });
}
deleteKeyGrant(vaultId: string, keyId: string) {
return this.request<{ ok: boolean; revoked: string }>("DELETE", `/vaults/${encodeURIComponent(vaultId)}/key-grants/${encodeURIComponent(keyId)}`);
}
// ---- API keys (/api/keys; a person's credential only, never a machine key) ----
listApiKeys() {
return this.requestAt<{ keys: RemoteApiKey[] }>("/api/keys", "GET");
}
createApiKey(input: CreateApiKeyInput) {
return this.requestAt<{ key: RemoteApiKey; secret: string }>("/api/keys", "POST", input);
}
revokeApiKey(keyId: string) {
return this.requestAt<{ ok: boolean; revoked: string }>(`/api/keys/${encodeURIComponent(keyId)}`, "DELETE");
}
listAudit(vaultId: string) {
return this.request<{ audit: Array<Record<string, unknown>> }>("GET", `/vaults/${encodeURIComponent(vaultId)}/audit`);
}

View file

@ -23,6 +23,18 @@ export interface LocalIdentity {
keys: IdentityKeyPair;
createdAt: string;
updatedAt: string;
/**
* Set on an API-key identity (keys/<prefix>.json): what kind of key it is.
* A "machine" identity holds the machine's OWN keypair, registered on the
* key; a "user" one holds no keypair and borrows this machine's identity.json.
*/
keyKind?: "user" | "machine";
keyId?: string;
keyName?: string;
/** Machine keys: the one team the key is scoped to. */
team?: string;
/** The public key is on the server, so no command needs to register it again. */
registered?: boolean;
}
/**
@ -178,8 +190,84 @@ export async function updateIdentity(
return next;
}
/** Require a logged-in identity (token present), or throw with guidance. */
/** `LOGICSRC_API_KEY`, the headless credential for deploy boxes and CI. */
export function envApiKey(): string | undefined {
const value = process.env.LOGICSRC_API_KEY?.trim();
return value ? value : undefined;
}
/** The display prefix the server stores for a key (and names its identity file after). */
export function apiKeyPrefix(token: string): string {
return token.slice(0, 12);
}
/** Where an API key's own identity lives: `<home>/keys/<prefix>.json`, mode 0600. */
export function keyIdentityPath(token: string): string {
const prefix = apiKeyPrefix(token).replace(/[^A-Za-z0-9_-]/g, "_");
return join(logicsrcHome(), "keys", `${prefix}.json`);
}
/** Set by `logicsrc login --api-key`: which key identity commands use when no env key is set. */
export function activeKeyPath(): string {
return join(logicsrcHome(), "active-key.json");
}
export function readActiveKeyIdentity(): LocalIdentity | undefined {
const pointer = activeKeyPath();
if (!existsSync(pointer)) return undefined;
try {
const { file } = JSON.parse(readFileSync(pointer, "utf8")) as { file?: string };
return file ? readIdentity(file) : undefined;
} catch {
return undefined;
}
}
export function writeKeyIdentity(identity: LocalIdentity, file: string): void {
writeSecure(file, { ...identity, updatedAt: new Date().toISOString() });
}
export function setActiveKey(file: string): void {
writeSecure(activeKeyPath(), { file });
}
/**
* Turn an API-key identity file into what commands authenticate with.
* A user key borrows this machine's identity.json keypair (it acts as the
* person); a machine key carries its own.
*/
function fromKeyIdentity(stored: LocalIdentity, token: string): LocalIdentity & { apiToken: string; email: string } {
if (stored.keyKind === "user") {
const own = readIdentity();
if (!own?.keys?.secretKey) {
throw new Error("This API key acts as a person, and this machine has no identity key. Run: logicsrc login");
}
return { ...own, apiUrl: stored.apiUrl, apiToken: token, email: stored.email ?? own.email ?? "" };
}
return { ...stored, apiToken: token, email: stored.email ?? "" };
}
/**
* Require a logged-in identity (token present), or throw with guidance.
*
* Precedence: `LOGICSRC_API_KEY` (headless), then a key chosen with
* `logicsrc login --api-key`, then the person's own `logicsrc login`. The CLI
* prepares an API-key identity before any command runs (ensureApiKeyIdentity),
* so reading it here stays synchronous.
*/
export function requireAuth(file = identityPath()): LocalIdentity & { apiToken: string; email: string } {
const token = file === identityPath() ? envApiKey() : undefined;
if (token) {
const stored = readIdentity(keyIdentityPath(token));
if (!stored) {
throw new Error("LOGICSRC_API_KEY is set but its identity is not prepared yet. Run any logicsrc command with it once (e.g. logicsrc whoami).");
}
return fromKeyIdentity(stored, token);
}
if (file === identityPath()) {
const active = readActiveKeyIdentity();
if (active?.apiToken) return fromKeyIdentity(active, active.apiToken);
}
const identity = readIdentity(file);
if (!identity?.apiToken || !identity.email) {
throw new Error('Not logged in. Run "logicsrc login" first.');

View file

@ -78,8 +78,18 @@ export {
type RemoteMember,
type RemoteVault,
type RemoteSecret,
type RemoteGrantRow
type RemoteGrantRow,
type RemoteKeyInfo,
type RemoteApiKey,
type RemoteKeyGrant,
type CreateApiKeyInput
} from "./client.js";
export {
ensureApiKeyIdentity,
ApiKeyAuthError,
type EnsureApiKeyOptions,
type EnsuredApiKey
} from "./machine-key.js";
export {
generateIdentityKeyPair,
generateVaultKey,
@ -103,6 +113,12 @@ export {
defaultApiUrl,
envApiUrl,
resolveApiUrl,
envApiKey,
apiKeyPrefix,
keyIdentityPath,
activeKeyPath,
readActiveKeyIdentity,
setActiveKey,
DEFAULT_API_URL,
type LocalIdentity
} from "./identity.js";

View file

@ -0,0 +1,129 @@
import { TeamClient, TeamApiError } from "./client.js";
import { generateIdentityKeyPair, publicKeyForSecret } from "./crypto.js";
import { keyIdentityPath, readIdentity, writeKeyIdentity, type LocalIdentity } from "./identity.js";
/**
* Headless auth with an API key (`LOGICSRC_API_KEY`, or `logicsrc login --api-key`).
*
* A MACHINE key gets its own X25519 identity on first use: generated here,
* kept at `<home>/keys/<prefix>.json` (0600), and its public half registered on
* the key row server-side. A person grants the key a vault by sealing the vault
* key to that public key (`logicsrc teams grant … --key <name>`), so the box
* never holds, or replaces, the person's own identity key. That replacement is
* what `login --token` did on a fresh box, and why this exists.
*
* A person's (`user`) key passed the same way is recorded as such and borrows
* this machine's identity.json; nothing is uploaded for it.
*/
export interface EnsureApiKeyOptions {
apiUrl: string;
/** Write the token into the identity file (login --api-key). Env-var use leaves it out. */
persistToken?: boolean;
/**
* The key already registered a DIFFERENT public key (another box, or a lost
* identity file). Replacing it drops every grant sealed to the old one, so it
* only happens when asked.
*/
reregister?: boolean;
/** Identity file to use; defaults to keys/<prefix>.json. */
file?: string;
}
export interface EnsuredApiKey {
identity: LocalIdentity;
file: string;
/** True when this call registered the public key (first use). */
registeredNow: boolean;
}
export class ApiKeyAuthError extends Error {
constructor(message: string) {
super(message);
this.name = "ApiKeyAuthError";
}
}
export async function ensureApiKeyIdentity(token: string, options: EnsureApiKeyOptions): Promise<EnsuredApiKey> {
if (!token.startsWith("lsk_")) {
throw new ApiKeyAuthError("That is not a LogicSRC API key (they start with lsk_).");
}
const file = options.file ?? keyIdentityPath(token);
const existing = readIdentity(file);
const apiUrl = options.apiUrl.replace(/\/+$/, "");
// Already set up against this server: no network round trip per command.
if (
existing?.registered &&
existing.apiUrl === apiUrl &&
!options.reregister &&
(existing.keyKind === "user" || (existing.keys?.secretKey && (await publicKeyForSecret(existing.keys.secretKey)) === existing.keys.publicKey))
) {
if (options.persistToken && existing.apiToken !== token) {
const next = { ...existing, apiToken: token };
writeKeyIdentity(next, file);
return { identity: next, file, registeredNow: false };
}
return { identity: existing, file, registeredNow: false };
}
const client = new TeamClient({ apiUrl, token });
let me: Awaited<ReturnType<TeamClient["me"]>>;
try {
me = await client.me();
} catch (error) {
if (error instanceof TeamApiError && error.status === 401) {
throw new ApiKeyAuthError(`The API key ${token.slice(0, 12)}… was refused by ${apiUrl}: it is invalid, revoked, or expired.`);
}
throw error;
}
const now = new Date().toISOString();
const base = {
apiUrl,
email: me.user.email ?? undefined,
userId: me.user.id,
keyId: me.key?.id,
keyName: me.key?.name,
createdAt: existing?.createdAt ?? now,
updatedAt: now,
...(options.persistToken ? { apiToken: token } : {})
};
// A person's key (or a server from before machine keys, which reports no kind).
if (me.key?.kind !== "machine") {
const identity: LocalIdentity = {
...base,
keyKind: "user",
// Placeholder only: a user-kind key identity borrows identity.json's keypair.
keys: { publicKey: "", secretKey: "" },
registered: true
};
writeKeyIdentity(identity, file);
return { identity, file, registeredNow: false };
}
const keys = existing?.keys?.secretKey ? existing.keys : await generateIdentityKeyPair();
const serverKey = me.user.publicKey;
let registeredNow = false;
if (serverKey !== keys.publicKey) {
if (serverKey && !options.reregister) {
throw new ApiKeyAuthError(
`The machine key "${me.key.name}" already registered an identity from another machine (or a lost ${file}). ` +
"Its vault grants are sealed to that identity. To move the key here, run: " +
"logicsrc login --api-key <key> --reregister (this drops its grants; grant it again afterwards)."
);
}
await client.uploadPublicKey(keys.publicKey);
registeredNow = true;
}
const identity: LocalIdentity = {
...base,
keyKind: "machine",
team: me.key.team ?? undefined,
keys,
registered: true
};
writeKeyIdentity(identity, file);
return { identity, file, registeredNow };
}

View file

@ -57,6 +57,16 @@ async function acquireDek(ctx: TeamContext, slug: string, vault: string, vaultId
return unwrapVaultKey(wrappedDek, ctx.identity.keys);
} catch (error) {
if (!(error instanceof TeamApiError) || error.status !== 403) throw error;
if (ctx.identity.keyKind === "machine") {
// A machine key opens vaults only through a grant sealed to its own key,
// and never mints a vault key: a person grants it, from their machine.
const at = vault.indexOf("--");
const where = at > 0 ? `${vault.slice(0, at)} ${vault.slice(at + 2)}` : `<project> <env>`;
throw new Error(
`This machine key${ctx.identity.keyName ? ` (${ctx.identity.keyName})` : ""} has no grant for team:${slug}/${vault}. ` +
`A member with access runs:\n logicsrc teams grant ${slug} ${where} --key ${ctx.identity.keyName ?? "<key name>"}`
);
}
// No grant yet. If nobody holds the DEK, this is a fresh vault we can own.
const { grants } = await ctx.client.listGrants(vaultId);
const someoneHasAccess = grants.some((g) => g.hasAccess);
@ -77,7 +87,10 @@ export const teamProvider: CredentialProvider = {
name: "LogicSRC Team Vault",
description: "End-to-end-encrypted team credential vault. Share secrets with teammates by email — the server never sees plaintext.",
status: "available",
authRequirements: ["logicsrc login (identity at ~/.config/logicsrc/identity.json)"],
authRequirements: [
"logicsrc login (identity at ~/.config/logicsrc/identity.json)",
"or LOGICSRC_API_KEY=<machine key> (identity at ~/.config/logicsrc/keys/<prefix>.json)"
],
capabilities: { readValues: true, readNames: true, write: true, delete: true, rollback: true, audit: true },
async inspect(endpoint: CredentialEndpoint): Promise<CredentialSnapshot> {

View file

@ -167,4 +167,28 @@ describe("planVaultRekey", () => {
expect(plan.secrets).toEqual([]);
expect(plan.grants).toHaveLength(1);
});
it("re-seals machine keys to the new key, dropping ones whose owner is revoked or that have no key", async () => {
const me = await generateIdentityKeyPair();
const box = await generateIdentityKeyPair();
const gone = await generateIdentityKeyPair();
const { secrets, wrapped } = await makeVault({ TOKEN: "hunter2" }, [me]);
const plan = await planVaultRekey({
myWrappedDek: wrapped[0],
identity: me,
secrets,
members: [member("me@example.com", me), member("left@example.com", gone, { status: "invited" })],
machineKeys: [
{ keyId: "k_box", name: "dev2-deploy", owner: "me@example.com", publicKey: box.publicKey },
{ keyId: "k_left", name: "their-ci", owner: "left@example.com", publicKey: gone.publicKey },
{ keyId: "k_new", name: "never-used", owner: "me@example.com", publicKey: null }
]
});
expect(plan.keyGrants.map((g) => g.keyId)).toEqual(["k_box"]);
expect(plan.keysDropped.sort()).toEqual(["never-used", "their-ci"]);
// The box opens the NEW key, which decrypts the rotated ciphertext.
const boxDek = await unwrapVaultKey(plan.keyGrants[0].wrappedDek, box);
expect(await decryptValue({ nonce: plan.secrets[0].nonce, ciphertext: plan.secrets[0].ciphertext }, boxDek)).toBe("hunter2");
});
});

View file

@ -59,6 +59,12 @@ export interface RekeyPlanInput {
* crypto hygiene -- re-key without revoking anyone.
*/
scope?: "active" | "all";
/**
* Machine API keys holding this vault today. Each is re-sealed to the new DEK
* unless its owner loses access in this same rotation; the server drops any
* key grant a re-key does not re-seal, so leaving one out revokes it.
*/
machineKeys?: Array<{ keyId: string; name: string; owner: string | null; publicKey: string | null }>;
}
export interface RekeyPlan {
@ -70,6 +76,10 @@ export interface RekeyPlan {
revoked: string[];
/** Members skipped because they have no public key to seal to. */
skipped: Array<{ email: string; reason: string }>;
/** New sealed DEKs for the machine keys that keep access. */
keyGrants: Array<{ keyId: string; wrappedDek: string }>;
/** Machine keys this rotation drops (owner revoked, or no public key). */
keysDropped: string[];
}
/** Members who have no key yet cannot be sealed to, whatever the scope. */
@ -151,5 +161,16 @@ export async function planVaultRekey(input: RekeyPlanInput): Promise<RekeyPlan>
);
}
return { secrets, grants, revoked, skipped };
const keyGrants: Array<{ keyId: string; wrappedDek: string }> = [];
const keysDropped: string[] = [];
const revokedOwners = new Set(revoked.map((e) => e.toLowerCase()));
for (const key of input.machineKeys ?? []) {
if (!key.publicKey || (key.owner && revokedOwners.has(key.owner.toLowerCase()))) {
keysDropped.push(key.name);
continue;
}
keyGrants.push({ keyId: key.keyId, wrappedDek: await wrapVaultKey(newDek, key.publicKey) });
}
return { secrets, grants, revoked, skipped, keyGrants, keysDropped };
}