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'; export async function vaultPush(vaultKey: string, file: string, purge: boolean): Promise { 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`)); // 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(); wrapFor.set(recipientId, { publicKey: identity.id, canWrite: true }); 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}'`); } 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 }); } const symmetricKey = generateSymmetricKey(); const { nonce, ciphertext } = secretboxEncrypt(symmetricKey, payload); const wrappedKeys: Record = {}; for (const [rid, { publicKey, canWrite }] of wrapFor) { wrappedKeys[rid] = { wrappedKey: enc.toBase64(Identity.sealFor(publicKey, symmetricKey)), canWrite }; } await expectOk(await signedFetch(identity, recipientId, 'POST', `/api/vaults/${encodeURIComponent(vaultKey)}/push`, { ciphertext: enc.toBase64(ciphertext), nonce: enc.toBase64(nonce), wrappedKeys, purge, })); 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)' : ''}.`); } export async function vaultPull(vaultKey: string, format: 'env' | 'json', outFile: string | undefined, previous: boolean): Promise { await ready(); const { identity, recipientId } = await requireIdentityAndRecipientId(); const query = previous ? '?previous=1' : ''; const data = await expectOk(await signedFetch(identity, recipientId, 'GET', `/api/vaults/${encodeURIComponent(vaultKey)}/pull${query}`)); 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; const out = format === 'json' ? JSON.stringify(values, null, 2) : serializeEnv(values); if (outFile) { fs.writeFileSync(outFile, out); console.error(`wrote ${Object.keys(values).length} key(s) to ${outFile}${previous ? ' (previous version)' : ''}`); } else { process.stdout.write(out); } } export async function vaultGrant(vaultKey: string, targetRecipientId: string, readOnly: boolean): Promise { 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, canWrite: !readOnly, })); console.log(`granted ${readOnly ? 'read-only ' : ''}'${vaultKey}' access to ${targetRecipientId}.`); } export async function vaultRevoke(vaultKey: string, targetRecipientId: string): Promise { await expectOk(await adminFetch('DELETE', `/api/admin/vaults/${encodeURIComponent(vaultKey)}/grants/${encodeURIComponent(targetRecipientId)}`)); console.log(`revoked ${targetRecipientId}'s access to '${vaultKey}'.`); console.log(`Note: this stops future pulls only. If this was a compromise response, also run 'keep push ${vaultKey} --purge' with rotated values.`); } export async function vaultLog(vaultKey: string): Promise { 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}`); } }