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:
127
src/shared/crypto.ts
Normal file
127
src/shared/crypto.ts
Normal 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}`;
|
||||
}
|
||||
Reference in New Issue
Block a user