Machine API keys: headless teams pull for deploy boxes and CI (#230)

A person's lsk_ key acts as the person, with one identity key per user. Logging
a fresh box in with `login --token` uploaded the box's new keypair as the
person's identity and replaced the real one. Machine keys fix that: a key made
for a box, scoped to one team (and optionally named vaults), read-only unless
--read-write, optionally expiring, with its OWN identity key registered on the
key row. A vault key reaches it as a grant sealed to that public key
(credshare_key_grants), never through the person.

Schema (005_machine_keys, SQLite + Postgres): api_keys gains kind, team_id,
vault_scope, read_only (default 0, so existing person keys keep writing),
expires_at, public_key; new credshare_key_grants; credshare_audit.actor_key_id.

Server: each credshare route declares what a machine key may do (read / write /
register); the rest are people-only. Machine keys see only their team and
scoped vaults, read their grant from credshare_key_grants (audited as
vault:read with the key id), are refused every write when read-only, and cannot
mint/list/revoke keys, read /api/me or touch the personal vault. Expired and
revoked keys are 401. New GET|POST /api/keys, DELETE /api/keys/:id, and
GET|POST|DELETE /api/credshare/vaults/:id/key-grants. A re-key re-seals the
machine grants it is given and drops the rest.

CLI 0.8.0: `logicsrc keys create|list|revoke` (--team, --vault, --read-only /
--read-write, --expires, --out 0600); LOGICSRC_API_KEY and
`login --api-key` with a per-key identity in keys/<prefix>.json (0600),
generated and registered on first use; `login --token` with a machine key takes
that path instead of replacing the person's key; `teams grant … --key <name>`;
`credentials rotate` re-seals machine keys.

PWA: settings creates machine keys (team, vaults, read-only, expiry); a vault
page grants or revokes a machine key in the browser after unlock.

MCP: list_api_keys / create_api_key / revoke_api_key over /api/keys with a
Bearer LOGICSRC_API_KEY.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Anthony Ettinger 2026-10-05 23:08:32 -07:00 • committed by GitHub
parent 4df342a064
commit ade33efd17
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
35 changed files with 2220 additions and 106 deletions

View file

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