Files
keep/src/cli/commands/vault.ts

117 lines
6.1 KiB
TypeScript
Raw Normal View History

Implement keep: self-hosted E2E encrypted secrets sync Server: Express + better-sqlite3 (WAL), multi-recipient key-wrapping per IMPLEMENTATION.md's design — vaults/recipients/vault_grants/ access_log. Two auth paths: ADMIN_PASSWORD header for recipient management and revoke (pure metadata operations), signed-request auth (Ed25519 signature over method+path+timestamp+body-hash) for push/pull/grant, mirroring the spirit of this project family's other signed-handshake patterns without naming them. CLI: identity init/show/set-id, push/pull/grant/log, admin recipient add/list/remove and revoke. Grant is a client-side crypto operation (the granter unwraps the vault's current key locally and reseals it for the new recipient) rather than a server-side operation, since the server never holds an unwrapped key to grant with. Verified end-to-end with two independent local identities against a live server and separately against the built Docker image: register, push, pull (granted and ungranted), grant without re-pushing, admin revoke, a subsequent rotation confirming the revoked recipient stays excluded, and rejection of missing/malformed signed-request auth. Two real bugs caught during verification, not just written up: - libsodium-wrappers' published ESM build does a relative import only resolvable under bundler-style resolution — broken under plain Node ESM. Fixed via createRequire to force the CJS build. - Express's req.path inside a sub-router is relative to the mount point, which would have silently mismatched a client signing the full request path. Fixed by verifying against req.originalUrl. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-07-12 19:38:24 +02:00
import fs from 'node:fs';
import { requireIdentityAndRecipientId } from '../identityStore.js';
import { signedFetch, adminFetch, expectOk } from '../signedFetch.js';
import { parseEnv, serializeEnv } from '../envFormat.js';
import {
ready,
Identity,
generateSymmetricKey,
secretboxEncrypt,
secretboxDecrypt,
enc,
} from '../../shared/crypto.js';
Resolve open design questions: write-scoped grants, rollback, purge Per-question resolution, per best practice rather than deferral: - Push authorization: closed the least-privilege gap where read implied write. vault_grants gained can_write (default true, so nothing existing changes); enforced on push and grant (granting others is itself a mutation of vault membership, so it needs write too, not just read). 'keep grant --read-only' creates a read-only grant. - Version history: not full history (conflates "undo a typo'd push" with "this leaked, stop retaining it" into one mechanism). Retains exactly one previous version as a rollback safety net (vaults.prev_ciphertext/prev_nonce + a vault_grants_previous mirror table so recipients can unwrap it), plus 'keep push --purge' for compromise-driven rotations that explicitly skips retention and wipes any existing previous version too. - Per-secret-key granularity: resolved by NOT building it — documented the escape hatch (split into more vaults) instead of adding partial- decrypt complexity for a problem the existing primitive solves. One more real bug caught during verification: the CLI's --previous flag initially signed a path including its query string, but the server verifies against req.originalUrl with the query stripped — a mismatch that would have made every --previous request fail signature verification. Fixed by splitting the signed path from the request URL in signedFetch, signing only the former. Verified end-to-end with three independent identities: read-only grant correctly blocked from push and from granting others, write access and read-only status both preserved correctly across a rotation, previous- version pull working for a routine push and correctly unavailable to every recipient after a purge push. Also re-verified against a fresh Docker build. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-07-12 19:50:08 +02:00
export async function vaultPush(vaultKey: string, file: string, purge: boolean): Promise<void> {
Implement keep: self-hosted E2E encrypted secrets sync Server: Express + better-sqlite3 (WAL), multi-recipient key-wrapping per IMPLEMENTATION.md's design — vaults/recipients/vault_grants/ access_log. Two auth paths: ADMIN_PASSWORD header for recipient management and revoke (pure metadata operations), signed-request auth (Ed25519 signature over method+path+timestamp+body-hash) for push/pull/grant, mirroring the spirit of this project family's other signed-handshake patterns without naming them. CLI: identity init/show/set-id, push/pull/grant/log, admin recipient add/list/remove and revoke. Grant is a client-side crypto operation (the granter unwraps the vault's current key locally and reseals it for the new recipient) rather than a server-side operation, since the server never holds an unwrapped key to grant with. Verified end-to-end with two independent local identities against a live server and separately against the built Docker image: register, push, pull (granted and ungranted), grant without re-pushing, admin revoke, a subsequent rotation confirming the revoked recipient stays excluded, and rejection of missing/malformed signed-request auth. Two real bugs caught during verification, not just written up: - libsodium-wrappers' published ESM build does a relative import only resolvable under bundler-style resolution — broken under plain Node ESM. Fixed via createRequire to force the CJS build. - Express's req.path inside a sub-router is relative to the mount point, which would have silently mismatched a client signing the full request path. Fixed by verifying against req.originalUrl. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-07-12 19:38:24 +02:00
await ready();
const { identity, recipientId } = await requireIdentityAndRecipientId();
if (!fs.existsSync(file)) throw new Error(`file not found: ${file}`);
const values = parseEnv(fs.readFileSync(file, 'utf8'));
const payload = enc.fromUtf8(JSON.stringify(values));
const existsRes = await expectOk(await signedFetch(identity, recipientId, 'GET', `/api/vaults/${encodeURIComponent(vaultKey)}/exists`));
Resolve open design questions: write-scoped grants, rollback, purge Per-question resolution, per best practice rather than deferral: - Push authorization: closed the least-privilege gap where read implied write. vault_grants gained can_write (default true, so nothing existing changes); enforced on push and grant (granting others is itself a mutation of vault membership, so it needs write too, not just read). 'keep grant --read-only' creates a read-only grant. - Version history: not full history (conflates "undo a typo'd push" with "this leaked, stop retaining it" into one mechanism). Retains exactly one previous version as a rollback safety net (vaults.prev_ciphertext/prev_nonce + a vault_grants_previous mirror table so recipients can unwrap it), plus 'keep push --purge' for compromise-driven rotations that explicitly skips retention and wipes any existing previous version too. - Per-secret-key granularity: resolved by NOT building it — documented the escape hatch (split into more vaults) instead of adding partial- decrypt complexity for a problem the existing primitive solves. One more real bug caught during verification: the CLI's --previous flag initially signed a path including its query string, but the server verifies against req.originalUrl with the query stripped — a mismatch that would have made every --previous request fail signature verification. Fixed by splitting the signed path from the request URL in signedFetch, signing only the former. Verified end-to-end with three independent identities: read-only grant correctly blocked from push and from granting others, write access and read-only status both preserved correctly across a rotation, previous- version pull working for a routine push and correctly unavailable to every recipient after a purge push. Also re-verified against a fresh Docker build. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-07-12 19:50:08 +02:00
// recipientId -> { publicKey, canWrite } — canWrite is preserved across
// a rotation, not reset, so pushing an update never silently changes
// who else can write vs. only read.
const wrapFor = new Map<string, { publicKey: string; canWrite: boolean }>();
wrapFor.set(recipientId, { publicKey: identity.id, canWrite: true });
Implement keep: self-hosted E2E encrypted secrets sync Server: Express + better-sqlite3 (WAL), multi-recipient key-wrapping per IMPLEMENTATION.md's design — vaults/recipients/vault_grants/ access_log. Two auth paths: ADMIN_PASSWORD header for recipient management and revoke (pure metadata operations), signed-request auth (Ed25519 signature over method+path+timestamp+body-hash) for push/pull/grant, mirroring the spirit of this project family's other signed-handshake patterns without naming them. CLI: identity init/show/set-id, push/pull/grant/log, admin recipient add/list/remove and revoke. Grant is a client-side crypto operation (the granter unwraps the vault's current key locally and reseals it for the new recipient) rather than a server-side operation, since the server never holds an unwrapped key to grant with. Verified end-to-end with two independent local identities against a live server and separately against the built Docker image: register, push, pull (granted and ungranted), grant without re-pushing, admin revoke, a subsequent rotation confirming the revoked recipient stays excluded, and rejection of missing/malformed signed-request auth. Two real bugs caught during verification, not just written up: - libsodium-wrappers' published ESM build does a relative import only resolvable under bundler-style resolution — broken under plain Node ESM. Fixed via createRequire to force the CJS build. - Express's req.path inside a sub-router is relative to the mount point, which would have silently mismatched a client signing the full request path. Fixed by verifying against req.originalUrl. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-07-12 19:38:24 +02:00
if (existsRes.exists) {
const recipientsRes = await signedFetch(identity, recipientId, 'GET', `/api/vaults/${encodeURIComponent(vaultKey)}/recipients`);
if (!recipientsRes.ok) {
const body = await recipientsRes.json().catch(() => ({}));
throw new Error(body.error ?? `no access to vault '${vaultKey}' — ask an existing grantee to run 'keep grant ${vaultKey} ${recipientId}'`);
}
Resolve open design questions: write-scoped grants, rollback, purge Per-question resolution, per best practice rather than deferral: - Push authorization: closed the least-privilege gap where read implied write. vault_grants gained can_write (default true, so nothing existing changes); enforced on push and grant (granting others is itself a mutation of vault membership, so it needs write too, not just read). 'keep grant --read-only' creates a read-only grant. - Version history: not full history (conflates "undo a typo'd push" with "this leaked, stop retaining it" into one mechanism). Retains exactly one previous version as a rollback safety net (vaults.prev_ciphertext/prev_nonce + a vault_grants_previous mirror table so recipients can unwrap it), plus 'keep push --purge' for compromise-driven rotations that explicitly skips retention and wipes any existing previous version too. - Per-secret-key granularity: resolved by NOT building it — documented the escape hatch (split into more vaults) instead of adding partial- decrypt complexity for a problem the existing primitive solves. One more real bug caught during verification: the CLI's --previous flag initially signed a path including its query string, but the server verifies against req.originalUrl with the query stripped — a mismatch that would have made every --previous request fail signature verification. Fixed by splitting the signed path from the request URL in signedFetch, signing only the former. Verified end-to-end with three independent identities: read-only grant correctly blocked from push and from granting others, write access and read-only status both preserved correctly across a rotation, previous- version pull working for a routine push and correctly unavailable to every recipient after a purge push. Also re-verified against a fresh Docker build. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-07-12 19:50:08 +02:00
const current = await recipientsRes.json() as { recipientId: string; publicKey: string; canWrite: boolean }[];
for (const r of current) if (r.publicKey) wrapFor.set(r.recipientId, { publicKey: r.publicKey, canWrite: r.canWrite });
Implement keep: self-hosted E2E encrypted secrets sync Server: Express + better-sqlite3 (WAL), multi-recipient key-wrapping per IMPLEMENTATION.md's design — vaults/recipients/vault_grants/ access_log. Two auth paths: ADMIN_PASSWORD header for recipient management and revoke (pure metadata operations), signed-request auth (Ed25519 signature over method+path+timestamp+body-hash) for push/pull/grant, mirroring the spirit of this project family's other signed-handshake patterns without naming them. CLI: identity init/show/set-id, push/pull/grant/log, admin recipient add/list/remove and revoke. Grant is a client-side crypto operation (the granter unwraps the vault's current key locally and reseals it for the new recipient) rather than a server-side operation, since the server never holds an unwrapped key to grant with. Verified end-to-end with two independent local identities against a live server and separately against the built Docker image: register, push, pull (granted and ungranted), grant without re-pushing, admin revoke, a subsequent rotation confirming the revoked recipient stays excluded, and rejection of missing/malformed signed-request auth. Two real bugs caught during verification, not just written up: - libsodium-wrappers' published ESM build does a relative import only resolvable under bundler-style resolution — broken under plain Node ESM. Fixed via createRequire to force the CJS build. - Express's req.path inside a sub-router is relative to the mount point, which would have silently mismatched a client signing the full request path. Fixed by verifying against req.originalUrl. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-07-12 19:38:24 +02:00
}
const symmetricKey = generateSymmetricKey();
const { nonce, ciphertext } = secretboxEncrypt(symmetricKey, payload);
Resolve open design questions: write-scoped grants, rollback, purge Per-question resolution, per best practice rather than deferral: - Push authorization: closed the least-privilege gap where read implied write. vault_grants gained can_write (default true, so nothing existing changes); enforced on push and grant (granting others is itself a mutation of vault membership, so it needs write too, not just read). 'keep grant --read-only' creates a read-only grant. - Version history: not full history (conflates "undo a typo'd push" with "this leaked, stop retaining it" into one mechanism). Retains exactly one previous version as a rollback safety net (vaults.prev_ciphertext/prev_nonce + a vault_grants_previous mirror table so recipients can unwrap it), plus 'keep push --purge' for compromise-driven rotations that explicitly skips retention and wipes any existing previous version too. - Per-secret-key granularity: resolved by NOT building it — documented the escape hatch (split into more vaults) instead of adding partial- decrypt complexity for a problem the existing primitive solves. One more real bug caught during verification: the CLI's --previous flag initially signed a path including its query string, but the server verifies against req.originalUrl with the query stripped — a mismatch that would have made every --previous request fail signature verification. Fixed by splitting the signed path from the request URL in signedFetch, signing only the former. Verified end-to-end with three independent identities: read-only grant correctly blocked from push and from granting others, write access and read-only status both preserved correctly across a rotation, previous- version pull working for a routine push and correctly unavailable to every recipient after a purge push. Also re-verified against a fresh Docker build. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-07-12 19:50:08 +02:00
const wrappedKeys: Record<string, { wrappedKey: string; canWrite: boolean }> = {};
for (const [rid, { publicKey, canWrite }] of wrapFor) {
wrappedKeys[rid] = { wrappedKey: enc.toBase64(Identity.sealFor(publicKey, symmetricKey)), canWrite };
Implement keep: self-hosted E2E encrypted secrets sync Server: Express + better-sqlite3 (WAL), multi-recipient key-wrapping per IMPLEMENTATION.md's design — vaults/recipients/vault_grants/ access_log. Two auth paths: ADMIN_PASSWORD header for recipient management and revoke (pure metadata operations), signed-request auth (Ed25519 signature over method+path+timestamp+body-hash) for push/pull/grant, mirroring the spirit of this project family's other signed-handshake patterns without naming them. CLI: identity init/show/set-id, push/pull/grant/log, admin recipient add/list/remove and revoke. Grant is a client-side crypto operation (the granter unwraps the vault's current key locally and reseals it for the new recipient) rather than a server-side operation, since the server never holds an unwrapped key to grant with. Verified end-to-end with two independent local identities against a live server and separately against the built Docker image: register, push, pull (granted and ungranted), grant without re-pushing, admin revoke, a subsequent rotation confirming the revoked recipient stays excluded, and rejection of missing/malformed signed-request auth. Two real bugs caught during verification, not just written up: - libsodium-wrappers' published ESM build does a relative import only resolvable under bundler-style resolution — broken under plain Node ESM. Fixed via createRequire to force the CJS build. - Express's req.path inside a sub-router is relative to the mount point, which would have silently mismatched a client signing the full request path. Fixed by verifying against req.originalUrl. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-07-12 19:38:24 +02:00
}
await expectOk(await signedFetch(identity, recipientId, 'POST', `/api/vaults/${encodeURIComponent(vaultKey)}/push`, {
ciphertext: enc.toBase64(ciphertext),
nonce: enc.toBase64(nonce),
wrappedKeys,
Resolve open design questions: write-scoped grants, rollback, purge Per-question resolution, per best practice rather than deferral: - Push authorization: closed the least-privilege gap where read implied write. vault_grants gained can_write (default true, so nothing existing changes); enforced on push and grant (granting others is itself a mutation of vault membership, so it needs write too, not just read). 'keep grant --read-only' creates a read-only grant. - Version history: not full history (conflates "undo a typo'd push" with "this leaked, stop retaining it" into one mechanism). Retains exactly one previous version as a rollback safety net (vaults.prev_ciphertext/prev_nonce + a vault_grants_previous mirror table so recipients can unwrap it), plus 'keep push --purge' for compromise-driven rotations that explicitly skips retention and wipes any existing previous version too. - Per-secret-key granularity: resolved by NOT building it — documented the escape hatch (split into more vaults) instead of adding partial- decrypt complexity for a problem the existing primitive solves. One more real bug caught during verification: the CLI's --previous flag initially signed a path including its query string, but the server verifies against req.originalUrl with the query stripped — a mismatch that would have made every --previous request fail signature verification. Fixed by splitting the signed path from the request URL in signedFetch, signing only the former. Verified end-to-end with three independent identities: read-only grant correctly blocked from push and from granting others, write access and read-only status both preserved correctly across a rotation, previous- version pull working for a routine push and correctly unavailable to every recipient after a purge push. Also re-verified against a fresh Docker build. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-07-12 19:50:08 +02:00
purge,
Implement keep: self-hosted E2E encrypted secrets sync Server: Express + better-sqlite3 (WAL), multi-recipient key-wrapping per IMPLEMENTATION.md's design — vaults/recipients/vault_grants/ access_log. Two auth paths: ADMIN_PASSWORD header for recipient management and revoke (pure metadata operations), signed-request auth (Ed25519 signature over method+path+timestamp+body-hash) for push/pull/grant, mirroring the spirit of this project family's other signed-handshake patterns without naming them. CLI: identity init/show/set-id, push/pull/grant/log, admin recipient add/list/remove and revoke. Grant is a client-side crypto operation (the granter unwraps the vault's current key locally and reseals it for the new recipient) rather than a server-side operation, since the server never holds an unwrapped key to grant with. Verified end-to-end with two independent local identities against a live server and separately against the built Docker image: register, push, pull (granted and ungranted), grant without re-pushing, admin revoke, a subsequent rotation confirming the revoked recipient stays excluded, and rejection of missing/malformed signed-request auth. Two real bugs caught during verification, not just written up: - libsodium-wrappers' published ESM build does a relative import only resolvable under bundler-style resolution — broken under plain Node ESM. Fixed via createRequire to force the CJS build. - Express's req.path inside a sub-router is relative to the mount point, which would have silently mismatched a client signing the full request path. Fixed by verifying against req.originalUrl. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-07-12 19:38:24 +02:00
}));
Resolve open design questions: write-scoped grants, rollback, purge Per-question resolution, per best practice rather than deferral: - Push authorization: closed the least-privilege gap where read implied write. vault_grants gained can_write (default true, so nothing existing changes); enforced on push and grant (granting others is itself a mutation of vault membership, so it needs write too, not just read). 'keep grant --read-only' creates a read-only grant. - Version history: not full history (conflates "undo a typo'd push" with "this leaked, stop retaining it" into one mechanism). Retains exactly one previous version as a rollback safety net (vaults.prev_ciphertext/prev_nonce + a vault_grants_previous mirror table so recipients can unwrap it), plus 'keep push --purge' for compromise-driven rotations that explicitly skips retention and wipes any existing previous version too. - Per-secret-key granularity: resolved by NOT building it — documented the escape hatch (split into more vaults) instead of adding partial- decrypt complexity for a problem the existing primitive solves. One more real bug caught during verification: the CLI's --previous flag initially signed a path including its query string, but the server verifies against req.originalUrl with the query stripped — a mismatch that would have made every --previous request fail signature verification. Fixed by splitting the signed path from the request URL in signedFetch, signing only the former. Verified end-to-end with three independent identities: read-only grant correctly blocked from push and from granting others, write access and read-only status both preserved correctly across a rotation, previous- version pull working for a routine push and correctly unavailable to every recipient after a purge push. Also re-verified against a fresh Docker build. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-07-12 19:50:08 +02:00
console.log(`pushed '${vaultKey}' — ${Object.keys(values).length} key${Object.keys(values).length === 1 ? '' : 's'}, wrapped for ${wrapFor.size} recipient${wrapFor.size === 1 ? '' : 's'}${purge ? ' (purged previous version)' : ''}.`);
Implement keep: self-hosted E2E encrypted secrets sync Server: Express + better-sqlite3 (WAL), multi-recipient key-wrapping per IMPLEMENTATION.md's design — vaults/recipients/vault_grants/ access_log. Two auth paths: ADMIN_PASSWORD header for recipient management and revoke (pure metadata operations), signed-request auth (Ed25519 signature over method+path+timestamp+body-hash) for push/pull/grant, mirroring the spirit of this project family's other signed-handshake patterns without naming them. CLI: identity init/show/set-id, push/pull/grant/log, admin recipient add/list/remove and revoke. Grant is a client-side crypto operation (the granter unwraps the vault's current key locally and reseals it for the new recipient) rather than a server-side operation, since the server never holds an unwrapped key to grant with. Verified end-to-end with two independent local identities against a live server and separately against the built Docker image: register, push, pull (granted and ungranted), grant without re-pushing, admin revoke, a subsequent rotation confirming the revoked recipient stays excluded, and rejection of missing/malformed signed-request auth. Two real bugs caught during verification, not just written up: - libsodium-wrappers' published ESM build does a relative import only resolvable under bundler-style resolution — broken under plain Node ESM. Fixed via createRequire to force the CJS build. - Express's req.path inside a sub-router is relative to the mount point, which would have silently mismatched a client signing the full request path. Fixed by verifying against req.originalUrl. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-07-12 19:38:24 +02:00
}
Resolve open design questions: write-scoped grants, rollback, purge Per-question resolution, per best practice rather than deferral: - Push authorization: closed the least-privilege gap where read implied write. vault_grants gained can_write (default true, so nothing existing changes); enforced on push and grant (granting others is itself a mutation of vault membership, so it needs write too, not just read). 'keep grant --read-only' creates a read-only grant. - Version history: not full history (conflates "undo a typo'd push" with "this leaked, stop retaining it" into one mechanism). Retains exactly one previous version as a rollback safety net (vaults.prev_ciphertext/prev_nonce + a vault_grants_previous mirror table so recipients can unwrap it), plus 'keep push --purge' for compromise-driven rotations that explicitly skips retention and wipes any existing previous version too. - Per-secret-key granularity: resolved by NOT building it — documented the escape hatch (split into more vaults) instead of adding partial- decrypt complexity for a problem the existing primitive solves. One more real bug caught during verification: the CLI's --previous flag initially signed a path including its query string, but the server verifies against req.originalUrl with the query stripped — a mismatch that would have made every --previous request fail signature verification. Fixed by splitting the signed path from the request URL in signedFetch, signing only the former. Verified end-to-end with three independent identities: read-only grant correctly blocked from push and from granting others, write access and read-only status both preserved correctly across a rotation, previous- version pull working for a routine push and correctly unavailable to every recipient after a purge push. Also re-verified against a fresh Docker build. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-07-12 19:50:08 +02:00
export async function vaultPull(vaultKey: string, format: 'env' | 'json', outFile: string | undefined, previous: boolean): Promise<void> {
Implement keep: self-hosted E2E encrypted secrets sync Server: Express + better-sqlite3 (WAL), multi-recipient key-wrapping per IMPLEMENTATION.md's design — vaults/recipients/vault_grants/ access_log. Two auth paths: ADMIN_PASSWORD header for recipient management and revoke (pure metadata operations), signed-request auth (Ed25519 signature over method+path+timestamp+body-hash) for push/pull/grant, mirroring the spirit of this project family's other signed-handshake patterns without naming them. CLI: identity init/show/set-id, push/pull/grant/log, admin recipient add/list/remove and revoke. Grant is a client-side crypto operation (the granter unwraps the vault's current key locally and reseals it for the new recipient) rather than a server-side operation, since the server never holds an unwrapped key to grant with. Verified end-to-end with two independent local identities against a live server and separately against the built Docker image: register, push, pull (granted and ungranted), grant without re-pushing, admin revoke, a subsequent rotation confirming the revoked recipient stays excluded, and rejection of missing/malformed signed-request auth. Two real bugs caught during verification, not just written up: - libsodium-wrappers' published ESM build does a relative import only resolvable under bundler-style resolution — broken under plain Node ESM. Fixed via createRequire to force the CJS build. - Express's req.path inside a sub-router is relative to the mount point, which would have silently mismatched a client signing the full request path. Fixed by verifying against req.originalUrl. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-07-12 19:38:24 +02:00
await ready();
const { identity, recipientId } = await requireIdentityAndRecipientId();
Resolve open design questions: write-scoped grants, rollback, purge Per-question resolution, per best practice rather than deferral: - Push authorization: closed the least-privilege gap where read implied write. vault_grants gained can_write (default true, so nothing existing changes); enforced on push and grant (granting others is itself a mutation of vault membership, so it needs write too, not just read). 'keep grant --read-only' creates a read-only grant. - Version history: not full history (conflates "undo a typo'd push" with "this leaked, stop retaining it" into one mechanism). Retains exactly one previous version as a rollback safety net (vaults.prev_ciphertext/prev_nonce + a vault_grants_previous mirror table so recipients can unwrap it), plus 'keep push --purge' for compromise-driven rotations that explicitly skips retention and wipes any existing previous version too. - Per-secret-key granularity: resolved by NOT building it — documented the escape hatch (split into more vaults) instead of adding partial- decrypt complexity for a problem the existing primitive solves. One more real bug caught during verification: the CLI's --previous flag initially signed a path including its query string, but the server verifies against req.originalUrl with the query stripped — a mismatch that would have made every --previous request fail signature verification. Fixed by splitting the signed path from the request URL in signedFetch, signing only the former. Verified end-to-end with three independent identities: read-only grant correctly blocked from push and from granting others, write access and read-only status both preserved correctly across a rotation, previous- version pull working for a routine push and correctly unavailable to every recipient after a purge push. Also re-verified against a fresh Docker build. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-07-12 19:50:08 +02:00
const query = previous ? '?previous=1' : '';
const data = await expectOk(await signedFetch(identity, recipientId, 'GET', `/api/vaults/${encodeURIComponent(vaultKey)}/pull${query}`));
Implement keep: self-hosted E2E encrypted secrets sync Server: Express + better-sqlite3 (WAL), multi-recipient key-wrapping per IMPLEMENTATION.md's design — vaults/recipients/vault_grants/ access_log. Two auth paths: ADMIN_PASSWORD header for recipient management and revoke (pure metadata operations), signed-request auth (Ed25519 signature over method+path+timestamp+body-hash) for push/pull/grant, mirroring the spirit of this project family's other signed-handshake patterns without naming them. CLI: identity init/show/set-id, push/pull/grant/log, admin recipient add/list/remove and revoke. Grant is a client-side crypto operation (the granter unwraps the vault's current key locally and reseals it for the new recipient) rather than a server-side operation, since the server never holds an unwrapped key to grant with. Verified end-to-end with two independent local identities against a live server and separately against the built Docker image: register, push, pull (granted and ungranted), grant without re-pushing, admin revoke, a subsequent rotation confirming the revoked recipient stays excluded, and rejection of missing/malformed signed-request auth. Two real bugs caught during verification, not just written up: - libsodium-wrappers' published ESM build does a relative import only resolvable under bundler-style resolution — broken under plain Node ESM. Fixed via createRequire to force the CJS build. - Express's req.path inside a sub-router is relative to the mount point, which would have silently mismatched a client signing the full request path. Fixed by verifying against req.originalUrl. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-07-12 19:38:24 +02:00
const symmetricKey = identity.openSealed(enc.fromBase64(data.wrappedKey));
if (!symmetricKey) throw new Error('failed to unwrap this vault\'s key — wrong identity, or the grant is stale');
const plaintext = secretboxDecrypt(symmetricKey, enc.fromBase64(data.nonce), enc.fromBase64(data.ciphertext));
const values = JSON.parse(enc.toUtf8(plaintext)) as Record<string, string>;
const out = format === 'json' ? JSON.stringify(values, null, 2) : serializeEnv(values);
if (outFile) {
fs.writeFileSync(outFile, out);
Resolve open design questions: write-scoped grants, rollback, purge Per-question resolution, per best practice rather than deferral: - Push authorization: closed the least-privilege gap where read implied write. vault_grants gained can_write (default true, so nothing existing changes); enforced on push and grant (granting others is itself a mutation of vault membership, so it needs write too, not just read). 'keep grant --read-only' creates a read-only grant. - Version history: not full history (conflates "undo a typo'd push" with "this leaked, stop retaining it" into one mechanism). Retains exactly one previous version as a rollback safety net (vaults.prev_ciphertext/prev_nonce + a vault_grants_previous mirror table so recipients can unwrap it), plus 'keep push --purge' for compromise-driven rotations that explicitly skips retention and wipes any existing previous version too. - Per-secret-key granularity: resolved by NOT building it — documented the escape hatch (split into more vaults) instead of adding partial- decrypt complexity for a problem the existing primitive solves. One more real bug caught during verification: the CLI's --previous flag initially signed a path including its query string, but the server verifies against req.originalUrl with the query stripped — a mismatch that would have made every --previous request fail signature verification. Fixed by splitting the signed path from the request URL in signedFetch, signing only the former. Verified end-to-end with three independent identities: read-only grant correctly blocked from push and from granting others, write access and read-only status both preserved correctly across a rotation, previous- version pull working for a routine push and correctly unavailable to every recipient after a purge push. Also re-verified against a fresh Docker build. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-07-12 19:50:08 +02:00
console.error(`wrote ${Object.keys(values).length} key(s) to ${outFile}${previous ? ' (previous version)' : ''}`);
Implement keep: self-hosted E2E encrypted secrets sync Server: Express + better-sqlite3 (WAL), multi-recipient key-wrapping per IMPLEMENTATION.md's design — vaults/recipients/vault_grants/ access_log. Two auth paths: ADMIN_PASSWORD header for recipient management and revoke (pure metadata operations), signed-request auth (Ed25519 signature over method+path+timestamp+body-hash) for push/pull/grant, mirroring the spirit of this project family's other signed-handshake patterns without naming them. CLI: identity init/show/set-id, push/pull/grant/log, admin recipient add/list/remove and revoke. Grant is a client-side crypto operation (the granter unwraps the vault's current key locally and reseals it for the new recipient) rather than a server-side operation, since the server never holds an unwrapped key to grant with. Verified end-to-end with two independent local identities against a live server and separately against the built Docker image: register, push, pull (granted and ungranted), grant without re-pushing, admin revoke, a subsequent rotation confirming the revoked recipient stays excluded, and rejection of missing/malformed signed-request auth. Two real bugs caught during verification, not just written up: - libsodium-wrappers' published ESM build does a relative import only resolvable under bundler-style resolution — broken under plain Node ESM. Fixed via createRequire to force the CJS build. - Express's req.path inside a sub-router is relative to the mount point, which would have silently mismatched a client signing the full request path. Fixed by verifying against req.originalUrl. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-07-12 19:38:24 +02:00
} else {
process.stdout.write(out);
}
}
Resolve open design questions: write-scoped grants, rollback, purge Per-question resolution, per best practice rather than deferral: - Push authorization: closed the least-privilege gap where read implied write. vault_grants gained can_write (default true, so nothing existing changes); enforced on push and grant (granting others is itself a mutation of vault membership, so it needs write too, not just read). 'keep grant --read-only' creates a read-only grant. - Version history: not full history (conflates "undo a typo'd push" with "this leaked, stop retaining it" into one mechanism). Retains exactly one previous version as a rollback safety net (vaults.prev_ciphertext/prev_nonce + a vault_grants_previous mirror table so recipients can unwrap it), plus 'keep push --purge' for compromise-driven rotations that explicitly skips retention and wipes any existing previous version too. - Per-secret-key granularity: resolved by NOT building it — documented the escape hatch (split into more vaults) instead of adding partial- decrypt complexity for a problem the existing primitive solves. One more real bug caught during verification: the CLI's --previous flag initially signed a path including its query string, but the server verifies against req.originalUrl with the query stripped — a mismatch that would have made every --previous request fail signature verification. Fixed by splitting the signed path from the request URL in signedFetch, signing only the former. Verified end-to-end with three independent identities: read-only grant correctly blocked from push and from granting others, write access and read-only status both preserved correctly across a rotation, previous- version pull working for a routine push and correctly unavailable to every recipient after a purge push. Also re-verified against a fresh Docker build. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-07-12 19:50:08 +02:00
export async function vaultGrant(vaultKey: string, targetRecipientId: string, readOnly: boolean): Promise<void> {
Implement keep: self-hosted E2E encrypted secrets sync Server: Express + better-sqlite3 (WAL), multi-recipient key-wrapping per IMPLEMENTATION.md's design — vaults/recipients/vault_grants/ access_log. Two auth paths: ADMIN_PASSWORD header for recipient management and revoke (pure metadata operations), signed-request auth (Ed25519 signature over method+path+timestamp+body-hash) for push/pull/grant, mirroring the spirit of this project family's other signed-handshake patterns without naming them. CLI: identity init/show/set-id, push/pull/grant/log, admin recipient add/list/remove and revoke. Grant is a client-side crypto operation (the granter unwraps the vault's current key locally and reseals it for the new recipient) rather than a server-side operation, since the server never holds an unwrapped key to grant with. Verified end-to-end with two independent local identities against a live server and separately against the built Docker image: register, push, pull (granted and ungranted), grant without re-pushing, admin revoke, a subsequent rotation confirming the revoked recipient stays excluded, and rejection of missing/malformed signed-request auth. Two real bugs caught during verification, not just written up: - libsodium-wrappers' published ESM build does a relative import only resolvable under bundler-style resolution — broken under plain Node ESM. Fixed via createRequire to force the CJS build. - Express's req.path inside a sub-router is relative to the mount point, which would have silently mismatched a client signing the full request path. Fixed by verifying against req.originalUrl. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-07-12 19:38:24 +02:00
await ready();
const { identity, recipientId } = await requireIdentityAndRecipientId();
const pullRes = await expectOk(await signedFetch(identity, recipientId, 'GET', `/api/vaults/${encodeURIComponent(vaultKey)}/pull`));
const symmetricKey = identity.openSealed(enc.fromBase64(pullRes.wrappedKey));
if (!symmetricKey) throw new Error("failed to unwrap this vault's key — can't grant access to someone else without it");
const recipientsRes = await expectOk(await signedFetch(identity, recipientId, 'GET', '/api/recipients'));
const target = (recipientsRes as { recipientId: string; publicKey: string }[]).find(r => r.recipientId === targetRecipientId);
if (!target) throw new Error(`unknown recipient id: ${targetRecipientId} (ask an admin to 'keep recipient add' them first)`);
const wrappedKey = enc.toBase64(Identity.sealFor(target.publicKey, symmetricKey));
await expectOk(await signedFetch(identity, recipientId, 'POST', `/api/vaults/${encodeURIComponent(vaultKey)}/grant`, {
recipientId: targetRecipientId,
wrappedKey,
Resolve open design questions: write-scoped grants, rollback, purge Per-question resolution, per best practice rather than deferral: - Push authorization: closed the least-privilege gap where read implied write. vault_grants gained can_write (default true, so nothing existing changes); enforced on push and grant (granting others is itself a mutation of vault membership, so it needs write too, not just read). 'keep grant --read-only' creates a read-only grant. - Version history: not full history (conflates "undo a typo'd push" with "this leaked, stop retaining it" into one mechanism). Retains exactly one previous version as a rollback safety net (vaults.prev_ciphertext/prev_nonce + a vault_grants_previous mirror table so recipients can unwrap it), plus 'keep push --purge' for compromise-driven rotations that explicitly skips retention and wipes any existing previous version too. - Per-secret-key granularity: resolved by NOT building it — documented the escape hatch (split into more vaults) instead of adding partial- decrypt complexity for a problem the existing primitive solves. One more real bug caught during verification: the CLI's --previous flag initially signed a path including its query string, but the server verifies against req.originalUrl with the query stripped — a mismatch that would have made every --previous request fail signature verification. Fixed by splitting the signed path from the request URL in signedFetch, signing only the former. Verified end-to-end with three independent identities: read-only grant correctly blocked from push and from granting others, write access and read-only status both preserved correctly across a rotation, previous- version pull working for a routine push and correctly unavailable to every recipient after a purge push. Also re-verified against a fresh Docker build. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-07-12 19:50:08 +02:00
canWrite: !readOnly,
Implement keep: self-hosted E2E encrypted secrets sync Server: Express + better-sqlite3 (WAL), multi-recipient key-wrapping per IMPLEMENTATION.md's design — vaults/recipients/vault_grants/ access_log. Two auth paths: ADMIN_PASSWORD header for recipient management and revoke (pure metadata operations), signed-request auth (Ed25519 signature over method+path+timestamp+body-hash) for push/pull/grant, mirroring the spirit of this project family's other signed-handshake patterns without naming them. CLI: identity init/show/set-id, push/pull/grant/log, admin recipient add/list/remove and revoke. Grant is a client-side crypto operation (the granter unwraps the vault's current key locally and reseals it for the new recipient) rather than a server-side operation, since the server never holds an unwrapped key to grant with. Verified end-to-end with two independent local identities against a live server and separately against the built Docker image: register, push, pull (granted and ungranted), grant without re-pushing, admin revoke, a subsequent rotation confirming the revoked recipient stays excluded, and rejection of missing/malformed signed-request auth. Two real bugs caught during verification, not just written up: - libsodium-wrappers' published ESM build does a relative import only resolvable under bundler-style resolution — broken under plain Node ESM. Fixed via createRequire to force the CJS build. - Express's req.path inside a sub-router is relative to the mount point, which would have silently mismatched a client signing the full request path. Fixed by verifying against req.originalUrl. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-07-12 19:38:24 +02:00
}));
Resolve open design questions: write-scoped grants, rollback, purge Per-question resolution, per best practice rather than deferral: - Push authorization: closed the least-privilege gap where read implied write. vault_grants gained can_write (default true, so nothing existing changes); enforced on push and grant (granting others is itself a mutation of vault membership, so it needs write too, not just read). 'keep grant --read-only' creates a read-only grant. - Version history: not full history (conflates "undo a typo'd push" with "this leaked, stop retaining it" into one mechanism). Retains exactly one previous version as a rollback safety net (vaults.prev_ciphertext/prev_nonce + a vault_grants_previous mirror table so recipients can unwrap it), plus 'keep push --purge' for compromise-driven rotations that explicitly skips retention and wipes any existing previous version too. - Per-secret-key granularity: resolved by NOT building it — documented the escape hatch (split into more vaults) instead of adding partial- decrypt complexity for a problem the existing primitive solves. One more real bug caught during verification: the CLI's --previous flag initially signed a path including its query string, but the server verifies against req.originalUrl with the query stripped — a mismatch that would have made every --previous request fail signature verification. Fixed by splitting the signed path from the request URL in signedFetch, signing only the former. Verified end-to-end with three independent identities: read-only grant correctly blocked from push and from granting others, write access and read-only status both preserved correctly across a rotation, previous- version pull working for a routine push and correctly unavailable to every recipient after a purge push. Also re-verified against a fresh Docker build. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-07-12 19:50:08 +02:00
console.log(`granted ${readOnly ? 'read-only ' : ''}'${vaultKey}' access to ${targetRecipientId}.`);
Implement keep: self-hosted E2E encrypted secrets sync Server: Express + better-sqlite3 (WAL), multi-recipient key-wrapping per IMPLEMENTATION.md's design — vaults/recipients/vault_grants/ access_log. Two auth paths: ADMIN_PASSWORD header for recipient management and revoke (pure metadata operations), signed-request auth (Ed25519 signature over method+path+timestamp+body-hash) for push/pull/grant, mirroring the spirit of this project family's other signed-handshake patterns without naming them. CLI: identity init/show/set-id, push/pull/grant/log, admin recipient add/list/remove and revoke. Grant is a client-side crypto operation (the granter unwraps the vault's current key locally and reseals it for the new recipient) rather than a server-side operation, since the server never holds an unwrapped key to grant with. Verified end-to-end with two independent local identities against a live server and separately against the built Docker image: register, push, pull (granted and ungranted), grant without re-pushing, admin revoke, a subsequent rotation confirming the revoked recipient stays excluded, and rejection of missing/malformed signed-request auth. Two real bugs caught during verification, not just written up: - libsodium-wrappers' published ESM build does a relative import only resolvable under bundler-style resolution — broken under plain Node ESM. Fixed via createRequire to force the CJS build. - Express's req.path inside a sub-router is relative to the mount point, which would have silently mismatched a client signing the full request path. Fixed by verifying against req.originalUrl. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-07-12 19:38:24 +02:00
}
export async function vaultRevoke(vaultKey: string, targetRecipientId: string): Promise<void> {
await expectOk(await adminFetch('DELETE', `/api/admin/vaults/${encodeURIComponent(vaultKey)}/grants/${encodeURIComponent(targetRecipientId)}`));
console.log(`revoked ${targetRecipientId}'s access to '${vaultKey}'.`);
Resolve open design questions: write-scoped grants, rollback, purge Per-question resolution, per best practice rather than deferral: - Push authorization: closed the least-privilege gap where read implied write. vault_grants gained can_write (default true, so nothing existing changes); enforced on push and grant (granting others is itself a mutation of vault membership, so it needs write too, not just read). 'keep grant --read-only' creates a read-only grant. - Version history: not full history (conflates "undo a typo'd push" with "this leaked, stop retaining it" into one mechanism). Retains exactly one previous version as a rollback safety net (vaults.prev_ciphertext/prev_nonce + a vault_grants_previous mirror table so recipients can unwrap it), plus 'keep push --purge' for compromise-driven rotations that explicitly skips retention and wipes any existing previous version too. - Per-secret-key granularity: resolved by NOT building it — documented the escape hatch (split into more vaults) instead of adding partial- decrypt complexity for a problem the existing primitive solves. One more real bug caught during verification: the CLI's --previous flag initially signed a path including its query string, but the server verifies against req.originalUrl with the query stripped — a mismatch that would have made every --previous request fail signature verification. Fixed by splitting the signed path from the request URL in signedFetch, signing only the former. Verified end-to-end with three independent identities: read-only grant correctly blocked from push and from granting others, write access and read-only status both preserved correctly across a rotation, previous- version pull working for a routine push and correctly unavailable to every recipient after a purge push. Also re-verified against a fresh Docker build. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-07-12 19:50:08 +02:00
console.log(`Note: this stops future pulls only. If this was a compromise response, also run 'keep push ${vaultKey} --purge' with rotated values.`);
Implement keep: self-hosted E2E encrypted secrets sync Server: Express + better-sqlite3 (WAL), multi-recipient key-wrapping per IMPLEMENTATION.md's design — vaults/recipients/vault_grants/ access_log. Two auth paths: ADMIN_PASSWORD header for recipient management and revoke (pure metadata operations), signed-request auth (Ed25519 signature over method+path+timestamp+body-hash) for push/pull/grant, mirroring the spirit of this project family's other signed-handshake patterns without naming them. CLI: identity init/show/set-id, push/pull/grant/log, admin recipient add/list/remove and revoke. Grant is a client-side crypto operation (the granter unwraps the vault's current key locally and reseals it for the new recipient) rather than a server-side operation, since the server never holds an unwrapped key to grant with. Verified end-to-end with two independent local identities against a live server and separately against the built Docker image: register, push, pull (granted and ungranted), grant without re-pushing, admin revoke, a subsequent rotation confirming the revoked recipient stays excluded, and rejection of missing/malformed signed-request auth. Two real bugs caught during verification, not just written up: - libsodium-wrappers' published ESM build does a relative import only resolvable under bundler-style resolution — broken under plain Node ESM. Fixed via createRequire to force the CJS build. - Express's req.path inside a sub-router is relative to the mount point, which would have silently mismatched a client signing the full request path. Fixed by verifying against req.originalUrl. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-07-12 19:38:24 +02:00
}
export async function vaultLog(vaultKey: string): Promise<void> {
await ready();
const { identity, recipientId } = await requireIdentityAndRecipientId();
const entries = await expectOk(await signedFetch(identity, recipientId, 'GET', `/api/vaults/${encodeURIComponent(vaultKey)}/log`));
if (!entries.length) { console.log('no access log entries yet.'); return; }
for (const e of entries as { recipient_id: string; action: string; accessed_at: number }[]) {
console.log(`${new Date(e.accessed_at * 1000).toISOString()} ${e.action.padEnd(6)} ${e.recipient_id}`);
}
}