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

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