logicsrc/plugins/credential-sharing/src/rekey.ts
Anthony Ettinger ade33efd17
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>
2026-10-05 23:08:32 -07:00

176 lines
7.3 KiB
TypeScript

/**
* Vault re-keying (rotation) for LogicSRC team vaults.
*
* Re-keying replaces a vault's data-encryption key. Every secret is decrypted
* with the old DEK and re-encrypted under a new one, and the new DEK is sealed
* afresh to each member who should keep access. Secret VALUES never change --
* that is the whole point. Nothing downstream breaks; what changes is that
* every previously-issued wrapped DEK becomes useless, so anyone dropped from
* the grant list can no longer read the vault even if they kept a copy of their
* old grant.
*
* This module is deliberately pure: it takes the current sealed state plus the
* caller's identity and returns the complete next state. All of it runs on the
* member's machine -- the server receives ciphertext and sealed keys only, and
* never sees either DEK.
*
* Ordering matters and is NOT this module's problem: a half-applied rotation
* (new grants, old ciphertext, or the reverse) locks everyone out permanently,
* because the DEK is recoverable only through the grants. The server applies
* the result of `planVaultRekey` in a single transaction; see the
* /vaults/:id/rekey endpoint.
*/
import { decryptValue, encryptValue, generateVaultKey, unwrapVaultKey, wrapVaultKey, type IdentityKeyPair } from "./crypto.js";
import { fingerprintValue, fingerprintsEqual } from "./fingerprint.js";
/** A secret as the server stores it. */
export interface SealedSecret {
name: string;
nonce: string;
ciphertext: string;
fingerprint: string;
}
/** A member who is a candidate to receive the new DEK. */
export interface RekeyMember {
email: string;
/** X25519 public key, or null if they have never uploaded one. */
publicKey: string | null;
/** Team membership status. Only "active" members are kept by default. */
status: "active" | "invited";
/** Whether they hold a grant on this vault today. */
hasAccess: boolean;
}
export interface RekeyPlanInput {
/** The caller's own wrapped DEK, which bootstraps the whole operation. */
myWrappedDek: string;
/** The caller's identity keypair. */
identity: IdentityKeyPair;
/** Every secret currently in the vault. */
secrets: SealedSecret[];
/** Every team member, with their current access. */
members: RekeyMember[];
/**
* Who keeps access.
* - "active" (default): only members whose team status is "active" AND who
* hold a grant today. This is the "someone left the team" rotation.
* - "all": everyone holding a grant today, whatever their status. Pure
* 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 {
/** Re-encrypted secrets, ready to write. Values are identical to the input. */
secrets: SealedSecret[];
/** New sealed DEKs, one per retained member. */
grants: Array<{ email: string; wrappedDek: string }>;
/** Members whose access this rotation removes. */
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. */
function sealable(member: RekeyMember): boolean {
return typeof member.publicKey === "string" && member.publicKey.length > 0;
}
/**
* Build the complete next state of a vault under a fresh DEK.
*
* Throws rather than returning a partial plan: a rotation that silently dropped
* a secret it could not decrypt would destroy it on write.
*/
export async function planVaultRekey(input: RekeyPlanInput): Promise<RekeyPlan> {
const scope = input.scope ?? "active";
const oldDek = await unwrapVaultKey(input.myWrappedDek, input.identity);
const newDek = await generateVaultKey();
// Decrypt everything BEFORE encrypting anything. If one secret fails to open
// we abort with the vault untouched, rather than writing a half-rotated set.
const plaintext = new Map<string, string>();
for (const secret of input.secrets) {
let value: string;
try {
value = await decryptValue({ nonce: secret.nonce, ciphertext: secret.ciphertext }, oldDek);
} catch {
throw new Error(
`Cannot rotate: "${secret.name}" did not decrypt with your vault key. The vault may already be mid-rotation, or your grant is stale — re-run after a member with access re-grants you.`
);
}
// The fingerprint is a deterministic hash of the value, so a mismatch here
// means the stored row was already inconsistent. Refuse to propagate it.
if (!fingerprintsEqual(secret.fingerprint, fingerprintValue(value))) {
throw new Error(
`Cannot rotate: "${secret.name}" has a fingerprint that does not match its ciphertext. Refusing to re-encrypt a record that is already inconsistent.`
);
}
plaintext.set(secret.name, value);
}
const secrets: SealedSecret[] = [];
for (const secret of input.secrets) {
const value = plaintext.get(secret.name) as string;
const sealed = await encryptValue(value, newDek);
secrets.push({
name: secret.name,
nonce: sealed.nonce,
ciphertext: sealed.ciphertext,
// Unchanged by construction -- the value did not change. Recomputed
// rather than copied so a bug here surfaces as a server-side rejection.
fingerprint: fingerprintValue(value)
});
}
const grants: Array<{ email: string; wrappedDek: string }> = [];
const revoked: string[] = [];
const skipped: Array<{ email: string; reason: string }> = [];
for (const member of input.members) {
const keep = member.hasAccess && (scope === "all" || member.status === "active");
if (!keep) {
if (member.hasAccess) revoked.push(member.email);
continue;
}
if (!sealable(member)) {
// Holds access today but has no key to re-seal to. Rotating would cut
// them off silently, so surface it instead of burying it.
skipped.push({ email: member.email, reason: "no public key on file" });
revoked.push(member.email);
continue;
}
grants.push({ email: member.email, wrappedDek: await wrapVaultKey(newDek, member.publicKey as string) });
}
if (grants.length === 0) {
throw new Error(
"Cannot rotate: no member would keep access, which would make the vault permanently unreadable. Grant at least one active member with a registered key first."
);
}
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 };
}