mirror of
https://github.com/profullstack/logicsrc.git
synced 2026-12-01 09:24:46 +00:00
Machine API keys: headless teams pull for deploy boxes and CI (#230)
A person's lsk_ key acts as the person, with one identity key per user. Logging a fresh box in with `login --token` uploaded the box's new keypair as the person's identity and replaced the real one. Machine keys fix that: a key made for a box, scoped to one team (and optionally named vaults), read-only unless --read-write, optionally expiring, with its OWN identity key registered on the key row. A vault key reaches it as a grant sealed to that public key (credshare_key_grants), never through the person. Schema (005_machine_keys, SQLite + Postgres): api_keys gains kind, team_id, vault_scope, read_only (default 0, so existing person keys keep writing), expires_at, public_key; new credshare_key_grants; credshare_audit.actor_key_id. Server: each credshare route declares what a machine key may do (read / write / register); the rest are people-only. Machine keys see only their team and scoped vaults, read their grant from credshare_key_grants (audited as vault:read with the key id), are refused every write when read-only, and cannot mint/list/revoke keys, read /api/me or touch the personal vault. Expired and revoked keys are 401. New GET|POST /api/keys, DELETE /api/keys/:id, and GET|POST|DELETE /api/credshare/vaults/:id/key-grants. A re-key re-seals the machine grants it is given and drops the rest. CLI 0.8.0: `logicsrc keys create|list|revoke` (--team, --vault, --read-only / --read-write, --expires, --out 0600); LOGICSRC_API_KEY and `login --api-key` with a per-key identity in keys/<prefix>.json (0600), generated and registered on first use; `login --token` with a machine key takes that path instead of replacing the person's key; `teams grant … --key <name>`; `credentials rotate` re-seals machine keys. PWA: settings creates machine keys (team, vaults, read-only, expiry); a vault page grants or revokes a machine key in the browser after unlock. MCP: list_api_keys / create_api_key / revoke_api_key over /api/keys with a Bearer LOGICSRC_API_KEY. Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
4df342a064
commit
ade33efd17
35 changed files with 2220 additions and 106 deletions
|
|
@ -1,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) {
|
||||
|
|
|
|||
|
|
@ -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>`
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue