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>
This commit is contained in:
Fredrik Johansson
2026-07-12 19:38:24 +02:00
parent 2c34562c7f
commit 67000b66ee
27 changed files with 3343 additions and 106 deletions

View File

@@ -0,0 +1,21 @@
import { loadOrCreateIdentity, setRecipientId } from '../identityStore.js';
export async function identityInit(): Promise<void> {
const { identity, created } = await loadOrCreateIdentity();
console.log(created ? 'identity created.' : 'identity already exists.');
console.log(`public key: ${identity.id}`);
console.log(`\nSend this public key to whoever runs 'keep recipient add' for this vault server.`);
console.log(`They'll give you back a recipient id — set it locally with:`);
console.log(` keep identity set-id <recipient-id>`);
}
export async function identityShow(): Promise<void> {
const { identity, recipientId } = await loadOrCreateIdentity();
console.log(`public key: ${identity.id}`);
console.log(`recipient id: ${recipientId ?? '(not set — see: keep identity set-id)'}`);
}
export function identitySetId(recipientId: string): void {
setRecipientId(recipientId);
console.log(`recipient id set to: ${recipientId}`);
}

View File

@@ -0,0 +1,20 @@
import { adminFetch, expectOk } from '../signedFetch.js';
export async function recipientAdd(label: string, publicKey: string): Promise<void> {
const data = await expectOk(await adminFetch('POST', '/api/admin/recipients', { label, publicKey }));
console.log(`recipient created: ${data.recipientId}`);
console.log(`Give this id back to whoever owns this identity — they set it with 'keep identity set-id ${data.recipientId}'.`);
}
export async function recipientList(): Promise<void> {
const data = await expectOk(await adminFetch('GET', '/api/admin/recipients'));
if (!data.length) { console.log('no recipients yet.'); return; }
for (const r of data) {
console.log(`${r.recipientId} ${r.label} ${r.publicKey.slice(0, 16)}`);
}
}
export async function recipientRemove(recipientId: string): Promise<void> {
await expectOk(await adminFetch('DELETE', `/api/admin/recipients/${encodeURIComponent(recipientId)}`));
console.log(`recipient removed: ${recipientId} (and all their vault grants)`);
}

110
src/cli/commands/vault.ts Normal file
View File

@@ -0,0 +1,110 @@
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): Promise<void> {
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`));
const wrapFor = new Map<string, string>(); // recipientId -> publicKey
wrapFor.set(recipientId, identity.id);
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 }[];
for (const r of current) if (r.publicKey) wrapFor.set(r.recipientId, r.publicKey);
}
const symmetricKey = generateSymmetricKey();
const { nonce, ciphertext } = secretboxEncrypt(symmetricKey, payload);
const wrappedKeys: Record<string, string> = {};
for (const [rid, pubHex] of wrapFor) {
wrappedKeys[rid] = enc.toBase64(Identity.sealFor(pubHex, symmetricKey));
}
await expectOk(await signedFetch(identity, recipientId, 'POST', `/api/vaults/${encodeURIComponent(vaultKey)}/push`, {
ciphertext: enc.toBase64(ciphertext),
nonce: enc.toBase64(nonce),
wrappedKeys,
}));
console.log(`pushed '${vaultKey}' — ${Object.keys(values).length} key${Object.keys(values).length === 1 ? '' : 's'}, wrapped for ${wrapFor.size} recipient${wrapFor.size === 1 ? '' : 's'}.`);
}
export async function vaultPull(vaultKey: string, format: 'env' | 'json', outFile?: string): Promise<void> {
await ready();
const { identity, recipientId } = await requireIdentityAndRecipientId();
const data = await expectOk(await signedFetch(identity, recipientId, 'GET', `/api/vaults/${encodeURIComponent(vaultKey)}/pull`));
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);
console.error(`wrote ${Object.keys(values).length} key(s) to ${outFile}`);
} else {
process.stdout.write(out);
}
}
export async function vaultGrant(vaultKey: string, targetRecipientId: string): Promise<void> {
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,
}));
console.log(`granted '${vaultKey}' to ${targetRecipientId}.`);
}
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}'.`);
console.log(`Note: this stops future pulls only. If this was a compromise response, also run 'keep push ${vaultKey}' with rotated values.`);
}
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}`);
}
}

22
src/cli/envFormat.ts Normal file
View File

@@ -0,0 +1,22 @@
export function parseEnv(text: string): Record<string, string> {
const out: Record<string, string> = {};
for (const rawLine of text.split('\n')) {
const line = rawLine.trim();
if (!line || line.startsWith('#')) continue;
const eq = line.indexOf('=');
if (eq === -1) continue;
const key = line.slice(0, eq).trim();
let value = line.slice(eq + 1).trim();
if ((value.startsWith('"') && value.endsWith('"')) || (value.startsWith("'") && value.endsWith("'"))) {
value = value.slice(1, -1);
}
out[key] = value;
}
return out;
}
export function serializeEnv(values: Record<string, string>): string {
return Object.entries(values)
.map(([k, v]) => `${k}=${/[\s#"']/.test(v) ? JSON.stringify(v) : v}`)
.join('\n') + '\n';
}

53
src/cli/identityStore.ts Normal file
View File

@@ -0,0 +1,53 @@
import fs from 'node:fs';
import path from 'node:path';
import os from 'node:os';
import { Identity } from '../shared/crypto.js';
const DIR = path.join(os.homedir(), '.keep');
const FILE = path.join(DIR, 'identity.json');
interface StoredIdentity {
seedHex: string;
// Assigned by whoever runs `keep recipient add` after registering this
// identity's public key — not derivable from the keypair itself, so it
// has to be stored once known via `keep identity set-id`.
recipientId?: string;
}
function readStored(): StoredIdentity | null {
if (!fs.existsSync(FILE)) return null;
return JSON.parse(fs.readFileSync(FILE, 'utf8')) as StoredIdentity;
}
function writeStored(data: StoredIdentity): void {
fs.mkdirSync(DIR, { recursive: true, mode: 0o700 });
fs.writeFileSync(FILE, JSON.stringify(data, null, 2), { mode: 0o600 });
}
export async function loadOrCreateIdentity(): Promise<{ identity: Identity; recipientId: string | null; created: boolean }> {
const stored = readStored();
if (stored) {
return { identity: await Identity.fromSeedHex(stored.seedHex), recipientId: stored.recipientId ?? null, created: false };
}
const identity = await Identity.generate();
writeStored({ seedHex: identity.seedHex });
return { identity, recipientId: null, created: true };
}
export function setRecipientId(recipientId: string): void {
const stored = readStored();
if (!stored) throw new Error("no local identity — run 'keep identity init' first");
writeStored({ ...stored, recipientId });
}
export async function requireIdentityAndRecipientId(): Promise<{ identity: Identity; recipientId: string }> {
const stored = readStored();
if (!stored) throw new Error("no local identity — run 'keep identity init' first");
if (!stored.recipientId) {
throw new Error(
"this identity has no recipient id set yet — after an admin registers your public key " +
"('keep identity show' to get it), run 'keep identity set-id <recipient-id>' with the id they give you back",
);
}
return { identity: await Identity.fromSeedHex(stored.seedHex), recipientId: stored.recipientId };
}

61
src/cli/index.ts Normal file
View File

@@ -0,0 +1,61 @@
#!/usr/bin/env node
import { identityInit, identityShow, identitySetId } from './commands/identity.js';
import { recipientAdd, recipientList, recipientRemove } from './commands/recipient.js';
import { vaultPush, vaultPull, vaultGrant, vaultRevoke, vaultLog } from './commands/vault.js';
function flag(args: string[], name: string, fallback?: string): string | undefined {
const i = args.indexOf(`--${name}`);
return i !== -1 ? args[i + 1] : fallback;
}
async function main(): Promise<void> {
const [, , cmd, sub, ...rest] = process.argv;
try {
if (cmd === 'identity') {
if (sub === 'init') return await identityInit();
if (sub === 'show') return await identityShow();
if (sub === 'set-id') return identitySetId(rest[0]);
}
if (cmd === 'recipient') {
if (sub === 'add') return await recipientAdd(flag(rest, 'label')!, flag(rest, 'pubkey')!);
if (sub === 'list') return await recipientList();
if (sub === 'remove') return await recipientRemove(rest[0]);
}
if (cmd === 'push') return await vaultPush(sub, flag(rest, 'file', '.env')!);
if (cmd === 'pull') return await vaultPull(sub, (flag(rest, 'format', 'env') as 'env' | 'json'), flag(rest, 'out'));
if (cmd === 'grant') return await vaultGrant(sub, rest[0]);
if (cmd === 'revoke') return await vaultRevoke(sub, rest[0]);
if (cmd === 'log') return await vaultLog(sub);
printUsage();
process.exitCode = cmd ? 1 : 0;
} catch (err) {
console.error(`error: ${err instanceof Error ? err.message : err}`);
process.exitCode = 1;
}
}
function printUsage(): void {
console.log(`keep — self-hosted, end-to-end encrypted secrets sync
keep identity init
keep identity show
keep identity set-id <recipient-id>
keep push <vault> [--file .env]
keep pull <vault> [--format env|json] [--out <path>]
keep grant <vault> <recipient-id>
keep revoke <vault> <recipient-id> (admin — needs KEEP_ADMIN_PASSWORD)
keep log <vault>
keep recipient add --label <label> --pubkey <hex> (admin)
keep recipient list (admin)
keep recipient remove <recipient-id> (admin)
Env: KEEP_SERVER_URL (default http://localhost:3050), KEEP_ADMIN_PASSWORD (for admin commands)`);
}
main();

48
src/cli/signedFetch.ts Normal file
View File

@@ -0,0 +1,48 @@
import { Identity, signingString, enc } from '../shared/crypto.js';
export function serverUrl(): string {
return process.env.KEEP_SERVER_URL ?? 'http://localhost:3050';
}
export async function signedFetch(
identity: Identity,
recipientId: string,
method: string,
path: string,
body?: unknown,
): Promise<Response> {
const bodyBytes = body !== undefined ? enc.fromUtf8(JSON.stringify(body)) : new Uint8Array();
const timestamp = Math.floor(Date.now() / 1000);
const toSign = signingString(method, path, timestamp, bodyBytes);
const signature = enc.toHex(identity.sign(enc.fromUtf8(toSign)));
return fetch(`${serverUrl()}${path}`, {
method,
headers: {
'Content-Type': 'application/json',
'X-Recipient-Id': recipientId,
'X-Signature': signature,
'X-Timestamp': String(timestamp),
},
body: body !== undefined ? JSON.stringify(body) : undefined,
});
}
export async function adminFetch(method: string, path: string, body?: unknown): Promise<Response> {
const password = process.env.KEEP_ADMIN_PASSWORD;
if (!password) throw new Error('KEEP_ADMIN_PASSWORD is not set');
return fetch(`${serverUrl()}${path}`, {
method,
headers: {
'Content-Type': 'application/json',
'X-Admin-Password': password,
},
body: body !== undefined ? JSON.stringify(body) : undefined,
});
}
export async function expectOk(res: Response): Promise<any> {
const data = await res.json().catch(() => ({}));
if (!res.ok) throw new Error(data.error ?? `request failed: ${res.status}`);
return data;
}

47
src/server/adminRoutes.ts Normal file
View File

@@ -0,0 +1,47 @@
import { Router } from 'express';
import { randomBytes } from 'node:crypto';
import { listRecipients, createRecipient, deleteRecipient, deleteGrant, getAccessLog, logAccess } from './db.js';
import { requireAdminAuth } from './auth.js';
export const router = Router();
router.use(requireAdminAuth);
function newRecipientId(label: string): string {
const slug = label.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '').slice(0, 24);
const suffix = randomBytes(3).toString('hex');
return slug ? `${slug}-${suffix}` : suffix;
}
router.get('/recipients', (_req, res) => {
res.json(listRecipients().map(r => ({ recipientId: r.recipient_id, label: r.label, publicKey: r.public_key, createdAt: r.created_at })));
});
router.post('/recipients', (req, res) => {
const body = req.body as { label?: string; publicKey?: string };
if (!body.label || !body.publicKey) {
res.status(400).json({ error: 'label and publicKey are required' });
return;
}
const recipientId = newRecipientId(body.label);
createRecipient(recipientId, body.label, body.publicKey);
res.json({ recipientId });
});
router.delete('/recipients/:id', (req, res) => {
deleteRecipient(req.params.id);
res.json({ ok: true });
});
// Revocation is pure metadata deletion — no crypto material is touched,
// which is exactly why admin alone (no vault access of their own
// required) can perform it, unlike `grant`.
router.delete('/vaults/:key/grants/:recipientId', (req, res) => {
deleteGrant(req.params.key, req.params.recipientId);
logAccess(req.params.key, req.params.recipientId, 'revoke');
res.json({ ok: true });
});
router.get('/vaults/:key/log', (req, res) => {
res.json(getAccessLog(req.params.key));
});

77
src/server/auth.ts Normal file
View File

@@ -0,0 +1,77 @@
// Signed-request authentication for recipient-facing endpoints
// (push/pull/grant/log) — distinct from the ADMIN_PASSWORD header used by
// admin-only routes (recipient add/remove, revoke). A recipient proves
// their identity by signing a canonical string derived from the request
// itself; no session, no cookie, stateless like every other password/
// signature check in this project family.
import type { Request, Response, NextFunction } from 'express';
import { getRecipient } from './db.js';
import { Identity, signingString } from '../shared/crypto.js';
import { config } from './config.js';
export interface AuthedRequest extends Request {
recipientId?: string;
rawBody?: Buffer;
}
export async function requireRecipientAuth(req: AuthedRequest, res: Response, next: NextFunction): Promise<void> {
const recipientId = req.get('X-Recipient-Id');
const signature = req.get('X-Signature');
const timestampHeader = req.get('X-Timestamp');
if (!recipientId || !signature || !timestampHeader) {
res.status(401).json({ error: 'missing auth headers' });
return;
}
const timestamp = Number(timestampHeader);
if (!Number.isFinite(timestamp) || Math.abs(Date.now() / 1000 - timestamp) > config.requestMaxSkewSeconds) {
res.status(401).json({ error: 'timestamp out of range' });
return;
}
const recipient = getRecipient(recipientId);
if (!recipient) {
res.status(401).json({ error: 'unknown recipient' });
return;
}
// req.path is relative to whichever router mounted this middleware
// (e.g. "/vaults/x/pull" inside a router mounted at "/api"), which would
// silently disagree with a client that signs the full request path.
// req.originalUrl is always the full path as actually requested,
// regardless of router nesting — strip the query string, since the
// client doesn't sign one.
const fullPath = req.originalUrl.split('?')[0];
const body = req.rawBody ?? Buffer.alloc(0);
const expected = signingString(req.method, fullPath, timestamp, body);
let sigBytes: Uint8Array;
try {
sigBytes = Buffer.from(signature, 'hex');
} catch {
res.status(401).json({ error: 'bad signature encoding' });
return;
}
const ok = Identity.verify(recipient.public_key, Buffer.from(expected, 'utf8'), sigBytes);
if (!ok) {
res.status(401).json({ error: 'signature verification failed' });
return;
}
req.recipientId = recipientId;
next();
}
export function requireAdminAuth(req: Request, res: Response, next: NextFunction): void {
if (!config.adminPassword) {
res.status(503).json({ error: 'admin disabled — ADMIN_PASSWORD not set' });
return;
}
if (req.get('X-Admin-Password') !== config.adminPassword) {
res.status(401).json({ error: 'bad password' });
return;
}
next();
}

12
src/server/config.ts Normal file
View File

@@ -0,0 +1,12 @@
import path from 'node:path';
export const config = {
port: parseInt(process.env.PORT ?? '3050', 10),
dataDir: process.env.DATA_DIR ?? path.resolve('data'),
// Gates recipient management + revoke. Unset disables admin routes
// entirely (503) rather than refusing to start — push/pull/grant for
// already-registered recipients keep working regardless.
adminPassword: process.env.ADMIN_PASSWORD || null,
// Replay-protection window for signed requests.
requestMaxSkewSeconds: parseInt(process.env.REQUEST_MAX_SKEW_SECONDS ?? '300', 10),
};

159
src/server/db.ts Normal file
View File

@@ -0,0 +1,159 @@
import Database from 'better-sqlite3';
import fs from 'node:fs';
import path from 'node:path';
import { config } from './config.js';
fs.mkdirSync(config.dataDir, { recursive: true });
export const db = new Database(path.join(config.dataDir, 'keep.db'));
db.pragma('journal_mode = WAL');
db.exec(`
CREATE TABLE IF NOT EXISTS vaults (
vault_key TEXT PRIMARY KEY,
ciphertext BLOB NOT NULL,
nonce BLOB NOT NULL,
updated_at INTEGER NOT NULL,
updated_by TEXT NOT NULL
);
CREATE TABLE IF NOT EXISTS recipients (
recipient_id TEXT PRIMARY KEY,
label TEXT NOT NULL,
public_key TEXT NOT NULL,
created_at INTEGER NOT NULL
);
-- Deleting a row IS the revocation for that (vault, recipient) pair.
CREATE TABLE IF NOT EXISTS vault_grants (
vault_key TEXT NOT NULL,
recipient_id TEXT NOT NULL,
wrapped_key TEXT NOT NULL, -- base64 crypto_box_seal(vault_symmetric_key, recipient_pubkey)
granted_at INTEGER NOT NULL,
PRIMARY KEY (vault_key, recipient_id)
);
CREATE TABLE IF NOT EXISTS access_log (
id INTEGER PRIMARY KEY AUTOINCREMENT,
vault_key TEXT NOT NULL,
recipient_id TEXT NOT NULL,
action TEXT NOT NULL,
accessed_at INTEGER NOT NULL
);
`);
export interface VaultRow {
vault_key: string;
ciphertext: Buffer;
nonce: Buffer;
updated_at: number;
updated_by: string;
}
export interface RecipientRow {
recipient_id: string;
label: string;
public_key: string;
created_at: number;
}
export interface GrantRow {
vault_key: string;
recipient_id: string;
wrapped_key: string;
granted_at: number;
}
export function getVault(vaultKey: string): VaultRow | undefined {
return db.prepare(`SELECT * FROM vaults WHERE vault_key = ?`).get(vaultKey) as VaultRow | undefined;
}
export function upsertVault(vaultKey: string, ciphertext: Buffer, nonce: Buffer, updatedBy: string): void {
db.prepare(
`INSERT INTO vaults (vault_key, ciphertext, nonce, updated_at, updated_by)
VALUES (?, ?, ?, ?, ?)
ON CONFLICT(vault_key) DO UPDATE SET
ciphertext = excluded.ciphertext, nonce = excluded.nonce,
updated_at = excluded.updated_at, updated_by = excluded.updated_by`,
).run(vaultKey, ciphertext, nonce, Math.floor(Date.now() / 1000), updatedBy);
}
export function getRecipient(recipientId: string): RecipientRow | undefined {
return db.prepare(`SELECT * FROM recipients WHERE recipient_id = ?`).get(recipientId) as RecipientRow | undefined;
}
export function listRecipients(): RecipientRow[] {
return db.prepare(`SELECT * FROM recipients ORDER BY created_at ASC`).all() as RecipientRow[];
}
export function createRecipient(recipientId: string, label: string, publicKey: string): void {
db.prepare(
`INSERT INTO recipients (recipient_id, label, public_key, created_at) VALUES (?, ?, ?, ?)`,
).run(recipientId, label, publicKey, Math.floor(Date.now() / 1000));
}
export function deleteRecipient(recipientId: string): void {
const tx = db.transaction(() => {
db.prepare(`DELETE FROM recipients WHERE recipient_id = ?`).run(recipientId);
db.prepare(`DELETE FROM vault_grants WHERE recipient_id = ?`).run(recipientId);
});
tx();
}
export function hasGrant(vaultKey: string, recipientId: string): boolean {
const row = db.prepare(
`SELECT 1 FROM vault_grants WHERE vault_key = ? AND recipient_id = ?`,
).get(vaultKey, recipientId);
return row != null;
}
export function getGrant(vaultKey: string, recipientId: string): GrantRow | undefined {
return db.prepare(
`SELECT * FROM vault_grants WHERE vault_key = ? AND recipient_id = ?`,
).get(vaultKey, recipientId) as GrantRow | undefined;
}
export function listGrantsForVault(vaultKey: string): GrantRow[] {
return db.prepare(`SELECT * FROM vault_grants WHERE vault_key = ?`).all(vaultKey) as GrantRow[];
}
export function setGrant(vaultKey: string, recipientId: string, wrappedKeyB64: string): void {
db.prepare(
`INSERT INTO vault_grants (vault_key, recipient_id, wrapped_key, granted_at)
VALUES (?, ?, ?, ?)
ON CONFLICT(vault_key, recipient_id) DO UPDATE SET wrapped_key = excluded.wrapped_key, granted_at = excluded.granted_at`,
).run(vaultKey, recipientId, wrappedKeyB64, Math.floor(Date.now() / 1000));
}
// Used by `push` (rotation): replaces every wrapped-key row for a vault
// in one transaction, so a concurrent grant/revoke can't interleave with
// a partial rewrap and leave the vault in a mixed old/new-key state.
export function replaceAllGrantsForVault(vaultKey: string, wrappedByRecipientId: Map<string, string>): void {
const tx = db.transaction(() => {
db.prepare(`DELETE FROM vault_grants WHERE vault_key = ?`).run(vaultKey);
const insert = db.prepare(
`INSERT INTO vault_grants (vault_key, recipient_id, wrapped_key, granted_at) VALUES (?, ?, ?, ?)`,
);
const now = Math.floor(Date.now() / 1000);
for (const [recipientId, wrappedKeyB64] of wrappedByRecipientId) {
insert.run(vaultKey, recipientId, wrappedKeyB64, now);
}
});
tx();
}
export function deleteGrant(vaultKey: string, recipientId: string): void {
db.prepare(`DELETE FROM vault_grants WHERE vault_key = ? AND recipient_id = ?`).run(vaultKey, recipientId);
}
export function logAccess(vaultKey: string, recipientId: string, action: 'pull' | 'push' | 'grant' | 'revoke'): void {
db.prepare(
`INSERT INTO access_log (vault_key, recipient_id, action, accessed_at) VALUES (?, ?, ?, ?)`,
).run(vaultKey, recipientId, action, Math.floor(Date.now() / 1000));
}
export function getAccessLog(vaultKey: string, limit = 50): { recipient_id: string; action: string; accessed_at: number }[] {
return db.prepare(
`SELECT recipient_id, action, accessed_at FROM access_log WHERE vault_key = ? ORDER BY accessed_at DESC LIMIT ?`,
).all(vaultKey, limit) as { recipient_id: string; action: string; accessed_at: number }[];
}

34
src/server/index.ts Normal file
View File

@@ -0,0 +1,34 @@
import express from 'express';
import { config } from './config.js';
import { router as apiRouter } from './routes.js';
import { router as adminRouter } from './adminRoutes.js';
import type { AuthedRequest } from './auth.js';
const app = express();
// Capture the raw body bytes alongside the parsed JSON — signature
// verification needs to hash exactly what was sent, not a re-serialized
// version of the parsed object (which could differ in key order/spacing
// and produce a different hash than what the client signed).
app.use(express.json({
verify: (req, _res, buf) => {
(req as AuthedRequest).rawBody = Buffer.from(buf);
},
}));
// Must be registered before apiRouter — that router applies
// requireRecipientAuth to every path under /api via router.use(), which
// would otherwise swallow this unauthenticated health check too, since
// Express matches route registration order and app.use('/api', ...)
// matches /api/health as a prefix.
app.get('/api/health', (_req, res) => res.json({ ok: true }));
app.use('/api/admin', adminRouter);
app.use('/api', apiRouter);
app.listen(config.port, () => {
console.log(`[keep] listening on :${config.port}`);
if (!config.adminPassword) {
console.log('[keep] ADMIN_PASSWORD not set — /api/admin is disabled');
}
});

135
src/server/routes.ts Normal file
View File

@@ -0,0 +1,135 @@
import { Router } from 'express';
import {
getVault,
upsertVault,
hasGrant,
getGrant,
listGrantsForVault,
setGrant,
replaceAllGrantsForVault,
logAccess,
getAccessLog,
listRecipients,
} from './db.js';
import { requireRecipientAuth, type AuthedRequest } from './auth.js';
export const router = Router();
router.use(requireRecipientAuth);
// Recipient public keys aren't secret — knowing one doesn't grant access
// to anything — so this is recipient-authenticated (proves you're a
// registered identity) rather than admin-gated. Needed so a recipient can
// look up who else exists before granting them access to a vault.
router.get('/recipients', (_req, res) => {
res.json(listRecipients().map(r => ({ recipientId: r.recipient_id, label: r.label, publicKey: r.public_key })));
});
// Existence isn't secret — lets `keep push` distinguish "vault doesn't
// exist yet, fine to self-bootstrap" from "vault exists but I have no
// grant," which a bare 403 on /recipients can't tell apart.
router.get('/vaults/:key/exists', (req, res) => {
res.json({ exists: getVault(req.params.key) != null });
});
// Only current grantees of a vault can see who else has access to it —
// needed by `keep push` to know who to re-wrap the rotated key for.
router.get('/vaults/:key/recipients', (req: AuthedRequest, res) => {
const vaultKey = req.params.key;
if (!hasGrant(vaultKey, req.recipientId!)) {
res.status(403).json({ error: 'no access to this vault' });
return;
}
const grants = listGrantsForVault(vaultKey);
const byId = new Map(listRecipients().map(r => [r.recipient_id, r]));
res.json(grants.map(g => {
const r = byId.get(g.recipient_id);
return { recipientId: g.recipient_id, label: r?.label ?? null, publicKey: r?.public_key ?? null };
}));
});
router.get('/vaults/:key/pull', (req: AuthedRequest, res) => {
const vaultKey = req.params.key;
const recipientId = req.recipientId!;
const grant = getGrant(vaultKey, recipientId);
const vault = getVault(vaultKey);
if (!grant || !vault) {
logAccess(vaultKey, recipientId, 'pull'); // logged even on failure — a spike of failed pulls from an unexpected identity is exactly the signal this exists to surface
res.status(404).json({ error: 'no vault or no access' });
return;
}
logAccess(vaultKey, recipientId, 'pull');
res.json({
ciphertext: vault.ciphertext.toString('base64'),
nonce: vault.nonce.toString('base64'),
wrappedKey: grant.wrapped_key,
updatedAt: vault.updated_at,
updatedBy: vault.updated_by,
});
});
// Rotation: replaces the vault's ciphertext AND every recipient's wrapped
// key in one call — the client has already generated a fresh symmetric
// key and re-wrapped it for every currently-granted recipient (fetched
// via GET /vaults/:key/recipients first). Existing vaults require the
// pusher to already be a grantee (read implies write, v1 decision from
// IMPLEMENTATION.md); a brand-new vault key may be created by any
// registered recipient, who becomes its first grantee.
router.post('/vaults/:key/push', (req: AuthedRequest, res) => {
const vaultKey = req.params.key;
const recipientId = req.recipientId!;
const existing = getVault(vaultKey);
if (existing && !hasGrant(vaultKey, recipientId)) {
res.status(403).json({ error: 'no access to this vault' });
return;
}
const body = req.body as { ciphertext?: string; nonce?: string; wrappedKeys?: Record<string, string> };
if (!body.ciphertext || !body.nonce || !body.wrappedKeys || Object.keys(body.wrappedKeys).length === 0) {
res.status(400).json({ error: 'ciphertext, nonce, and at least one wrapped key are required' });
return;
}
upsertVault(vaultKey, Buffer.from(body.ciphertext, 'base64'), Buffer.from(body.nonce, 'base64'), recipientId);
replaceAllGrantsForVault(vaultKey, new Map(Object.entries(body.wrappedKeys)));
logAccess(vaultKey, recipientId, 'push');
res.json({ ok: true });
});
// Adds ONE new recipient to an existing vault using the CURRENT
// (unrotated) symmetric key — the granter must already hold a grant
// (meaning they can unwrap the current key locally) and supplies a fresh
// seal of that same key for the new recipient's public key. Does not
// touch the ciphertext or any other recipient's wrapped key.
router.post('/vaults/:key/grant', (req: AuthedRequest, res) => {
const vaultKey = req.params.key;
const granterId = req.recipientId!;
if (!hasGrant(vaultKey, granterId)) {
res.status(403).json({ error: 'no access to this vault' });
return;
}
const body = req.body as { recipientId?: string; wrappedKey?: string };
if (!body.recipientId || !body.wrappedKey) {
res.status(400).json({ error: 'recipientId and wrappedKey are required' });
return;
}
setGrant(vaultKey, body.recipientId, body.wrappedKey);
logAccess(vaultKey, granterId, 'grant');
res.json({ ok: true });
});
router.get('/vaults/:key/log', (req: AuthedRequest, res) => {
const vaultKey = req.params.key;
if (!hasGrant(vaultKey, req.recipientId!)) {
res.status(403).json({ error: 'no access to this vault' });
return;
}
res.json(getAccessLog(vaultKey));
});

127
src/shared/crypto.ts Normal file
View File

@@ -0,0 +1,127 @@
// Identity and sealing primitives — standard libsodium Ed25519/X25519
// primitives and sign-to-curve derivation, for Node rather than a browser
// client.
//
// libsodium-wrappers' published ESM build does a relative import
// ("./libsodium.mjs") that only resolves under bundler-style resolution
// (Vite, webpack) — it's broken under plain Node ESM, where "libsodium"
// is a separate node_modules package, not a sibling file. A purely
// browser-bundled use of the same package would never hit this. Forcing
// the CJS build via createRequire sidesteps the bug: CJS
// require('libsodium') resolves as a normal node_modules lookup instead
// of a broken relative path.
import { createRequire } from 'node:module';
import { createHash } from 'node:crypto';
const require = createRequire(import.meta.url);
const sodium = require('libsodium-wrappers') as typeof import('libsodium-wrappers');
export interface KeyPair {
publicKey: Uint8Array;
privateKey: Uint8Array;
}
export class Identity {
pub: Uint8Array;
priv: Uint8Array;
id: string; // hex Ed25519 pubkey
curvePriv: Uint8Array;
curvePub: Uint8Array;
constructor(kp: KeyPair) {
this.pub = kp.publicKey;
this.priv = kp.privateKey;
this.id = sodium.to_hex(this.pub);
this.curvePriv = sodium.crypto_sign_ed25519_sk_to_curve25519(this.priv);
this.curvePub = sodium.crypto_sign_ed25519_pk_to_curve25519(this.pub);
}
static async generate(): Promise<Identity> {
await sodium.ready;
return new Identity(sodium.crypto_sign_keypair());
}
static async fromSeedHex(seedHex: string): Promise<Identity> {
await sodium.ready;
return new Identity(sodium.crypto_sign_seed_keypair(sodium.from_hex(seedHex)));
}
// First 32 bytes of the Ed25519 private key are the seed — the usual
// compact persistence convention for this kind of identity.
get seedHex(): string {
return sodium.to_hex(this.priv.slice(0, 32));
}
sign(data: Uint8Array): Uint8Array {
return sodium.crypto_sign_detached(data, this.priv);
}
static verify(pubHex: string, data: Uint8Array, sig: Uint8Array): boolean {
try {
return sodium.crypto_sign_verify_detached(sig, data, sodium.from_hex(pubHex));
} catch {
return false;
}
}
// Anonymous sealing (crypto_box_seal): the server never needs to know
// *who* wrapped a key for a recipient, only that it was wrapped
// correctly for them. Used to wrap a vault's symmetric key per
// recipient.
static sealFor(recipientPubHex: string, plaintext: Uint8Array): Uint8Array {
const recipientCurvePub = sodium.crypto_sign_ed25519_pk_to_curve25519(sodium.from_hex(recipientPubHex));
return sodium.crypto_box_seal(plaintext, recipientCurvePub);
}
openSealed(sealed: Uint8Array): Uint8Array | null {
try {
return sodium.crypto_box_seal_open(sealed, this.curvePub, this.curvePriv);
} catch {
return null;
}
}
}
export async function ready(): Promise<void> {
await sodium.ready;
}
// Symmetric payload encryption for a vault's contents.
export function generateSymmetricKey(): Uint8Array {
return sodium.crypto_secretbox_keygen();
}
export function secretboxEncrypt(key: Uint8Array, plaintext: Uint8Array): { nonce: Uint8Array; ciphertext: Uint8Array } {
const nonce = sodium.randombytes_buf(sodium.crypto_secretbox_NONCEBYTES);
const ciphertext = sodium.crypto_secretbox_easy(plaintext, nonce, key);
return { nonce, ciphertext };
}
export function secretboxDecrypt(key: Uint8Array, nonce: Uint8Array, ciphertext: Uint8Array): Uint8Array {
return sodium.crypto_secretbox_open_easy(ciphertext, nonce, key);
}
export const enc = {
toHex: (b: Uint8Array) => sodium.to_hex(b),
fromHex: (s: string) => sodium.from_hex(s),
toBase64: (b: Uint8Array) => sodium.to_base64(b, sodium.base64_variants.ORIGINAL),
fromBase64: (s: string) => sodium.from_base64(s, sodium.base64_variants.ORIGINAL),
toUtf8: (b: Uint8Array) => sodium.to_string(b),
fromUtf8: (s: string) => sodium.from_string(s),
};
function sha256Hex(bytes: Uint8Array): string {
return createHash('sha256').update(bytes).digest('hex');
}
// Canonical string a signed request's signature covers: binds method,
// path, a body hash, and a timestamp (replay window) together so a
// captured signature can't be replayed against a different request or
// after the timestamp window expires — a fixed, explicit byte layout
// rather than "sign whatever the body happens to be." Uses Node's built-in
// hash rather than libsodium's crypto_hash (which is SHA-512, not
// SHA-256, and not what's wanted here) — no reason to route a plain
// content hash through libsodium.
export function signingString(method: string, path: string, timestamp: number, body: Uint8Array): string {
const bodyHash = sha256Hex(body);
return `${method.toUpperCase()}\n${path}\n${timestamp}\n${bodyHash}`;
}