diff --git a/INTEGRATION.md b/INTEGRATION.md index 31bf2ae..1ae4ddf 100644 --- a/INTEGRATION.md +++ b/INTEGRATION.md @@ -13,7 +13,18 @@ blob = encrypt(kr, ctx, b"ada@example.com") assert decrypt(kr, ctx, blob) == b"ada@example.com" ``` -`api/eg_crypto` is the Python package. `crates/encryptoglyph` is the Rust source of truth. Both check `testvectors/envelope.json`. +`api/eg_crypto` is the Python package. `crates/encryptoglyph` is the Rust source of truth. `@godesk/encryptoglyph` (`sdk/js`) is the Node.js 24 package. All three check `testvectors/envelope.json`. + +```js +import { Keyring, encrypt, decrypt } from "@godesk/encryptoglyph"; + +const kr = new Keyring(kid, key); +const ctx = { tenant: "acme", purpose: "field", table: "customers", recordId: "42", field: "email" }; +const blob = encrypt(kr, ctx, "ada@example.com"); +if (Buffer.from(decrypt(kr, ctx, blob)).toString() !== "ada@example.com") throw new Error("round trip"); +``` + +Install with `npm install ./sdk/js`, `npm install ./sdk/js/godesk-encryptoglyph-0.2.0.tgz`, or `npm install github:GoDeskio/Encryptoglyph#`. No `wasm-pack` step. ## Sidecar diff --git a/README.md b/README.md index c7ad0e0..d98b462 100644 --- a/README.md +++ b/README.md @@ -22,7 +22,7 @@ Encryptoglyph is an open-source encryption-at-rest library and self-hosted servi | --- | --- | | Rust envelope, HKDF, Argon2id, key rotation | Implemented and tested | | Python module, wire-compatible with Rust | Implemented and tested | -| TypeScript wrapper over the WASM build | Source in `bindings/ts`; `wasm-pack` output is not committed | +| Node.js package `@godesk/encryptoglyph` | `sdk/js` and `bindings/ts`. Pure JS, Node >= 24, no `wasm-pack` step | | `eg-api` container | `/healthz`, the `/v1` sidecar, and the console. Swagger, ReDoc, and `/openapi.json` are not served | | OpenBao, Postgres 16, restic rest-server | Images and config in `deploy/docker-compose.yml`. The console reports them as not connected | | Console | `console/`, served by the API. See [INTEGRATION.md](INTEGRATION.md) | @@ -47,7 +47,7 @@ flowchart TB subgraph crypto [shared XChaCha20-Poly1305 envelope] rust[Rust crate] python[Python eg_crypto] - ts[TypeScript WASM] + ts[Node.js envelope] end operator --> traefik traefik --> console @@ -62,7 +62,7 @@ flowchart TB The lines from `eg-api` to OpenBao, Postgres, and rest-server are placement in the compose file, not live calls from the health handler. -![Architecture diagram: Traefik on proxy-net in front of the MSP console and API; OpenBao, Postgres, and restic rest-server on an internal network; Rust, Python, and TypeScript sharing one envelope](docs/img/architecture.svg) +![Architecture diagram: Traefik on proxy-net in front of the MSP console and API; OpenBao, Postgres, and restic rest-server on an internal network; Rust, Python, and Node.js sharing one envelope](docs/img/architecture.svg) The SVG is the same layout: [docs/img/architecture.svg](docs/img/architecture.svg). @@ -189,37 +189,51 @@ python -m pip install -r requirements-dev.txt pytest ``` -### TypeScript +### Node.js -`bindings/ts` is a thin wrapper around the WASM build of the Rust crate. Crypto stays in Rust. Build the package with wasm-pack, then compile the wrapper: +`@godesk/encryptoglyph` is plain ECMAScript in `sdk/js` (and the same envelope file in `bindings/ts`). It runs on Node.js 24 or newer and does not run `wasm-pack`. XChaCha20-Poly1305 uses HChaCha20 plus Node's ChaCha20-Poly1305. HKDF-SHA256 and Argon2id use `node:crypto`. The package decrypts `testvectors/envelope.json`. + +From a checkout: + +```bash +npm install ./sdk/js +node --test sdk/js/test/vectors.test.js +``` + +The Rust `wasm` feature still builds for `wasm32-unknown-unknown`. `fpe` and `blahaj` stay in the crate's main dependency table, and the wasm32 graph enables `getrandom` `js` plus `getrandom` 0.4 `wasm_js`. `bindings/ts` can still pack that feature when a browser build is needed: ```bash cd bindings/ts npm run build:wasm -npm run build -# Node services use the CommonJS package instead of the bundler target: npm run build:wasm:node node vector-test.cjs pkg-node ``` -```ts -import { Keyring } from "@godesk/encryptoglyph"; +Git installs use the repository root `package.json`, which points at the same files: + +```bash +npm install github:GoDeskio/Encryptoglyph# +``` + +A packed tarball is `sdk/js/godesk-encryptoglyph-0.2.0.tgz`. + +```js +import { Keyring, encrypt, decrypt } from "@godesk/encryptoglyph"; const key = crypto.getRandomValues(new Uint8Array(32)); const kr = new Keyring("k1", key); -const blob = kr.encrypt( - { tenant: "acme", purpose: "field", table: "customers", recordId: "42", field: "email" }, - new TextEncoder().encode("ada@example.com"), -); +const ctx = { tenant: "acme", purpose: "field", table: "customers", recordId: "42", field: "email" }; +const blob = encrypt(kr, ctx, "ada@example.com"); +const plain = decrypt(kr, ctx, blob); ``` -The package is `private` and is not published to npm from this repository. `bindings/ts/pkg` is gitignored. +The browser sidecar client remains `sdk/js/encryptoglyph.js`. It calls `/v1` and does not seal locally. The envelope module is for Node, where `node:crypto` provides the primitives. ## Security model - **Authenticated encryption.** Version 2 is XChaCha20-Poly1305-IETF. The header (magic, version, algorithm, key id, nonce) is part of the additional data, together with the canonical record context. Flipping the version or moving the blob between records fails authentication. - **Key separation.** A root key never encrypts plaintext directly. HKDF-SHA256 derives a data key from the root key, the purpose, the tenant, and the algorithm. Password root keys use Argon2id with a 16-byte salt. -- **Rotation.** A `Keyring` encrypts with the current key id and can decrypt older ids. `rewrap` writes a fresh version-2 blob. The current key cannot be retired. +- **Rotation.** A `Keyring` encrypts with the current key id and can decrypt older ids. `rewrap` writes a fresh version-3 blob. The current key cannot be retired. - **Uniform failures.** Decrypt errors do not distinguish a bad tag from a malformed header. - **No backdoor in the library.** There is no escrow or override key in the Rust or Python code. Custody of root keys is an OpenBao operation. This console keeps session keys in process memory and says so. - **Network.** Compose does not publish host ports. OpenBao's own UI is disabled. Postgres passwords come from the gitignored env file. diff --git a/bindings/ts/README.md b/bindings/ts/README.md new file mode 100644 index 0000000..37cc1ef --- /dev/null +++ b/bindings/ts/README.md @@ -0,0 +1,18 @@ +# bindings/ts + +TypeScript source for `@godesk/encryptoglyph`. The runtime is `js/envelope.js`, a byte-for-byte copy of `sdk/js/envelope.js`. Installing this directory does not run `wasm-pack` or `tsc`. + +Node.js 24 or newer: + +```bash +npm install ./bindings/ts +node --experimental-strip-types -e "import { Keyring } from '@godesk/encryptoglyph'" +``` + +From git: + +```bash +npm install github:GoDeskio/Encryptoglyph#:bindings/ts +``` + +The repository-root package and `sdk/js` publish the same name and the same envelope. Use whichever path your installer accepts. Konektor (Node) should depend on the root package or `sdk/js`. diff --git a/bindings/ts/index.d.ts b/bindings/ts/index.d.ts new file mode 100644 index 0000000..d874497 --- /dev/null +++ b/bindings/ts/index.d.ts @@ -0,0 +1,103 @@ +export const VERSION_LEGACY: 1; +export const VERSION_V2: 2; +export const VERSION_V3: 3; +export const ALG_AES256GCM: 1; +export const ALG_XCHACHA20POLY1305: 2; +export const ALG_XCHACHA20POLY1305_COMMIT: 3; +export const KEY_LEN: 32; +export const ARGON2_TIME: 3; +export const ARGON2_MEMORY_KIB: 262144; +export const ARGON2_PARALLELISM: 1; + +export class DecryptError extends Error {} +export class DowngradeError extends DecryptError {} + +export type Bytes = Uint8Array; + +export interface RecordContextInit { + tenant: string; + purpose: string; + table: string; + recordId?: string; + record_id?: string; + field?: string; + schemaVersion?: number; + schema_version?: number; +} + +export class RecordContext { + constructor( + tenant: string, + purpose: string, + table: string, + recordId: string, + field?: string, + schemaVersion?: number, + ); + tenant: string; + purpose: string; + table: string; + recordId: string; + field: string; + schemaVersion: number; + aad(): Uint8Array; +} + +export class Keyring { + constructor(kid: string, key: Bytes); + constructor(keys: Record, current: string); + static generateKey(): Uint8Array; + readonly current: string; + add(kid: string, key: Bytes, makeCurrent?: boolean): void; + retire(kid: string): void; + has(kid: string): boolean; + derive(kid: string, purpose: string, tenant: string, alg: number): Uint8Array; + encrypt(ctx: RecordContext | RecordContextInit | unknown[], plaintext: Bytes | string): Uint8Array; + decrypt(ctx: RecordContext | RecordContextInit | unknown[], blob: Bytes, minVersion?: number): Uint8Array; + rewrap(ctx: RecordContext | RecordContextInit | unknown[], blob: Bytes): Uint8Array; + needsRewrap(blob: Bytes): boolean; +} + +export interface ParsedHeader { + version: number; + alg: number; + kid: string; + nonce: Uint8Array; + header: Uint8Array; + body: Uint8Array; +} + +export function parseHeader(blob: Bytes): ParsedHeader; +export function encrypt(keyring: Keyring, ctx: RecordContext | RecordContextInit | unknown[], plaintext: Bytes | string): Uint8Array; +export function encryptWithNonce( + keyring: Keyring, + ctx: RecordContext | RecordContextInit | unknown[], + plaintext: Bytes | string, + nonce: Bytes, +): Uint8Array; +export function encryptV2(keyring: Keyring, ctx: RecordContext | RecordContextInit | unknown[], plaintext: Bytes | string): Uint8Array; +export function encryptLegacyV1( + keyring: Keyring, + ctx: RecordContext | RecordContextInit | unknown[], + plaintext: Bytes | string, +): Uint8Array; +export function decrypt( + keyring: Keyring, + ctx: RecordContext | RecordContextInit | unknown[], + blob: Bytes, + minVersion?: number, +): Uint8Array; +export function needsRewrap(keyring: Keyring, blob: Bytes): boolean; +export function rewrap(keyring: Keyring, ctx: RecordContext | RecordContextInit | unknown[], blob: Bytes): Uint8Array; +export function blindIndex(key: Bytes, tenant: string, field: string, value: string, length?: number): Uint8Array; +export function verifyBlindIndex(key: Bytes, tenant: string, field: string, value: string, expected: Bytes): boolean; +export function fingerprint(key: Bytes): string; +export function deriveRootKeyFromPassword(password: string | Bytes, salt: Bytes): Uint8Array; +export function deriveRootKeyWithParams( + password: string | Bytes, + salt: Bytes, + params?: { time?: number; memoryKiB?: number; parallelism?: number }, +): Uint8Array; +export function hchacha20(key: Bytes, nonce16: Bytes): Uint8Array; +export function asContext(ctx: RecordContext | RecordContextInit | unknown[]): RecordContext; +export function normalizeBlindIndex(value: string): string; diff --git a/bindings/ts/js/envelope.js b/bindings/ts/js/envelope.js new file mode 100644 index 0000000..29b71d9 --- /dev/null +++ b/bindings/ts/js/envelope.js @@ -0,0 +1,450 @@ +// Encryptoglyph envelope for Node.js >= 24. No wasm-pack and no extra crypto dependency. +// +// Wire format (see docs/SPEC-ENVELOPE.md and testvectors/envelope.json): +// "EG" | version u8 | alg u8 | kid_len u8 | kid | nonce | body +// v3 body = 32-byte key commitment || ciphertext || 16-byte tag (default writer) +// v2 body = ciphertext || tag, XChaCha20-Poly1305 (decrypt and upgrade) +// v1 body = ciphertext || tag, AES-256-GCM (decrypt only) +// +// XChaCha20-Poly1305 is HChaCha20 (draft-irtf-cfrg-xchacha) plus Node's OpenSSL +// ChaCha20-Poly1305. HKDF-SHA256 and Argon2id come from node:crypto. + +import crypto from "node:crypto"; + +export const VERSION_LEGACY = 1; +export const VERSION_V2 = 2; +export const VERSION_V3 = 3; +export const ALG_AES256GCM = 1; +export const ALG_XCHACHA20POLY1305 = 2; +export const ALG_XCHACHA20POLY1305_COMMIT = 3; +export const KEY_LEN = 32; +export const ARGON2_TIME = 3; +export const ARGON2_MEMORY_KIB = 262144; +export const ARGON2_PARALLELISM = 1; + +const COMMIT_LEN = 32; +const TAG_LEN = 16; +const HKDF_SALT = Buffer.from("encryptoglyph/hkdf-salt/v2"); +const NONCE_LEN = { + [ALG_AES256GCM]: 12, + [ALG_XCHACHA20POLY1305]: 24, + [ALG_XCHACHA20POLY1305_COMMIT]: 24, +}; +const VERSION_ALG = { + [VERSION_LEGACY]: ALG_AES256GCM, + [VERSION_V2]: ALG_XCHACHA20POLY1305, + [VERSION_V3]: ALG_XCHACHA20POLY1305_COMMIT, +}; + +export class DecryptError extends Error { + constructor(message = "decryption failed") { + super(message); + this.name = "DecryptError"; + } +} + +export class DowngradeError extends DecryptError { + constructor(message = "envelope version below minimum") { + super(message); + this.name = "DowngradeError"; + } +} + +function toBuf(value, encoding) { + if (Buffer.isBuffer(value)) return value; + if (value instanceof Uint8Array) return Buffer.from(value); + if (typeof value === "string") return Buffer.from(value, encoding); + throw new TypeError("expected bytes or a string"); +} + +function lp(bytes) { + const len = Buffer.alloc(4); + len.writeUInt32BE(bytes.length); + return Buffer.concat([len, bytes]); +} + +function rotl(v, n) { + return ((v << n) | (v >>> (32 - n))) >>> 0; +} + +function quarterRound(s, a, b, c, d) { + s[a] = (s[a] + s[b]) >>> 0; + s[d] = rotl(s[d] ^ s[a], 16); + s[c] = (s[c] + s[d]) >>> 0; + s[b] = rotl(s[b] ^ s[c], 12); + s[a] = (s[a] + s[b]) >>> 0; + s[d] = rotl(s[d] ^ s[a], 8); + s[c] = (s[c] + s[d]) >>> 0; + s[b] = rotl(s[b] ^ s[c], 7); +} + +/** HChaCha20 from draft-irtf-cfrg-xchacha. Output is raw state words 0-3 and 12-15. */ +export function hchacha20(key, nonce16) { + const k = toBuf(key); + const n = toBuf(nonce16); + if (k.length !== 32 || n.length !== 16) throw new Error("invalid HChaCha20 input"); + const s = new Uint32Array(16); + s[0] = 0x61707865; + s[1] = 0x3320646e; + s[2] = 0x79622d32; + s[3] = 0x6b206574; + for (let i = 0; i < 8; i++) s[4 + i] = k.readUInt32LE(i * 4); + for (let i = 0; i < 4; i++) s[12 + i] = n.readUInt32LE(i * 4); + for (let i = 0; i < 10; i++) { + quarterRound(s, 0, 4, 8, 12); + quarterRound(s, 1, 5, 9, 13); + quarterRound(s, 2, 6, 10, 14); + quarterRound(s, 3, 7, 11, 15); + quarterRound(s, 0, 5, 10, 15); + quarterRound(s, 1, 6, 11, 12); + quarterRound(s, 2, 7, 8, 13); + quarterRound(s, 3, 4, 9, 14); + } + const out = Buffer.alloc(32); + for (let i = 0; i < 4; i++) out.writeUInt32LE(s[i], i * 4); + for (let i = 0; i < 4; i++) out.writeUInt32LE(s[12 + i], 16 + i * 4); + return out; +} + +function hkdf32(ikm, salt, info) { + return Buffer.from(crypto.hkdfSync("sha256", ikm, salt, info, KEY_LEN)); +} + +function xchachaEncrypt(key, nonce24, aad, plaintext) { + const sub = hchacha20(key, nonce24.subarray(0, 16)); + const iv = Buffer.concat([Buffer.alloc(4), nonce24.subarray(16, 24)]); + const cipher = crypto.createCipheriv("chacha20-poly1305", sub, iv, { authTagLength: TAG_LEN }); + cipher.setAAD(aad); + return Buffer.concat([cipher.update(plaintext), cipher.final(), cipher.getAuthTag()]); +} + +function xchachaDecrypt(key, nonce24, aad, body) { + const sub = hchacha20(key, nonce24.subarray(0, 16)); + const iv = Buffer.concat([Buffer.alloc(4), nonce24.subarray(16, 24)]); + const ct = body.subarray(0, body.length - TAG_LEN); + const tag = body.subarray(body.length - TAG_LEN); + const decipher = crypto.createDecipheriv("chacha20-poly1305", sub, iv, { authTagLength: TAG_LEN }); + decipher.setAAD(aad); + decipher.setAuthTag(tag); + return Buffer.concat([decipher.update(ct), decipher.final()]); +} + +function aesGcmEncrypt(key, nonce, aad, plaintext) { + const cipher = crypto.createCipheriv("aes-256-gcm", key, nonce); + cipher.setAAD(aad); + return Buffer.concat([cipher.update(plaintext), cipher.final(), cipher.getAuthTag()]); +} + +function aesGcmDecrypt(key, nonce, aad, body) { + const ct = body.subarray(0, body.length - TAG_LEN); + const tag = body.subarray(body.length - TAG_LEN); + const decipher = crypto.createDecipheriv("aes-256-gcm", key, nonce); + decipher.setAAD(aad); + decipher.setAuthTag(tag); + return Buffer.concat([decipher.update(ct), decipher.final()]); +} + +export class RecordContext { + constructor(tenant, purpose, table, recordId, field = "", schemaVersion = 1) { + this.tenant = String(tenant); + this.purpose = String(purpose); + this.table = String(table); + this.recordId = String(recordId); + this.field = String(field ?? ""); + this.schemaVersion = schemaVersion; + } + + aad() { + const parts = [this.tenant, this.purpose, this.table, this.recordId, this.field, String(this.schemaVersion)]; + return Buffer.concat([Buffer.from("EGAAD1"), ...parts.map((part) => lp(Buffer.from(part)))]); + } +} + +export function asContext(ctx) { + if (ctx instanceof RecordContext) return ctx; + if (Array.isArray(ctx)) { + const [tenant, purpose, table, recordId, field = "", schemaVersion = 1] = ctx; + return new RecordContext(tenant, purpose, table, recordId, field, schemaVersion); + } + if (ctx && typeof ctx === "object") { + return new RecordContext( + ctx.tenant, + ctx.purpose, + ctx.table, + ctx.recordId ?? ctx.record_id, + ctx.field ?? "", + ctx.schemaVersion ?? ctx.schema_version ?? 1, + ); + } + throw new TypeError("invalid record context"); +} + +function copyKey(key) { + const buf = toBuf(key); + if (buf.length !== KEY_LEN) throw new Error("root keys must be 32 bytes"); + return Buffer.from(buf); +} + +function checkKid(kid) { + const bytes = Buffer.from(String(kid), "utf8"); + if (bytes.length < 1 || bytes.length > 255) throw new Error("bad key id"); + return String(kid); +} + +export class Keyring { + constructor(kidOrKeys, keyOrCurrent) { + this._keys = new Map(); + this._current = ""; + if (typeof kidOrKeys === "string") { + this.add(kidOrKeys, keyOrCurrent, true); + return; + } + if (kidOrKeys && typeof kidOrKeys === "object" && !ArrayBuffer.isView(kidOrKeys)) { + for (const [kid, key] of Object.entries(kidOrKeys)) this.add(kid, key, false); + if (typeof keyOrCurrent !== "string" || !this._keys.has(keyOrCurrent)) { + throw new Error("current key id not in keyring"); + } + this._current = keyOrCurrent; + return; + } + throw new TypeError("invalid keyring"); + } + + static generateKey() { + return crypto.randomBytes(KEY_LEN); + } + + get current() { + return this._current; + } + + add(kid, key, makeCurrent = true) { + const id = checkKid(kid); + this._keys.set(id, copyKey(key)); + if (makeCurrent) this._current = id; + } + + retire(kid) { + if (kid === this._current) throw new Error("cannot retire current key"); + const prev = this._keys.get(kid); + if (prev) prev.fill(0); + this._keys.delete(kid); + } + + has(kid) { + return this._keys.has(kid); + } + + derive(kid, purpose, tenant, alg) { + const root = this._keys.get(kid); + if (!root) throw new DecryptError(); + const info = Buffer.concat([ + Buffer.from("encryptoglyph/dek/v2"), + lp(Buffer.from(purpose)), + lp(Buffer.from(tenant)), + Buffer.from([alg]), + ]); + return hkdf32(root, HKDF_SALT, info); + } + + encrypt(ctx, plaintext) { + return encrypt(this, ctx, plaintext); + } + + decrypt(ctx, blob, minVersion = VERSION_LEGACY) { + return decrypt(this, ctx, blob, minVersion); + } + + rewrap(ctx, blob) { + return rewrap(this, ctx, blob); + } + + needsRewrap(blob) { + return needsRewrap(this, blob); + } +} + +function header(version, alg, kid, nonce) { + const kidBytes = Buffer.from(checkKid(kid), "utf8"); + return Buffer.concat([Buffer.from("EG"), Buffer.from([version, alg, kidBytes.length]), kidBytes, nonce]); +} + +export function parseHeader(blob) { + const buf = toBuf(blob); + try { + if (buf.length < 5 || buf[0] !== 0x45 || buf[1] !== 0x47) throw new Error("magic"); + const version = buf[2]; + const alg = buf[3]; + const klen = buf[4]; + if (VERSION_ALG[version] !== alg) throw new Error("pair"); + const off = 5 + klen; + const n = NONCE_LEN[alg]; + const extra = alg === ALG_XCHACHA20POLY1305_COMMIT ? COMMIT_LEN : 0; + if (buf.length < off + n + extra + TAG_LEN) throw new Error("short"); + const kid = new TextDecoder("utf-8", { fatal: true }).decode(buf.subarray(5, off)); + const nonce = buf.subarray(off, off + n); + return { + version, + alg, + kid, + nonce, + header: buf.subarray(0, off + n), + body: buf.subarray(off + n), + }; + } catch (err) { + if (err instanceof DecryptError) throw err; + throw new DecryptError(); + } +} + +function commitKeys(dek, nonce) { + return { + enc: hkdf32(dek, nonce, Buffer.from("encryptoglyph/v3/enc")), + commit: hkdf32(dek, nonce, Buffer.from("encryptoglyph/v3/commit")), + }; +} + +function commitment(commitKey, aad) { + return crypto.createHmac("sha256", commitKey).update(Buffer.from("EGCMT1")).update(aad).digest(); +} + +function plaintextBytes(plaintext) { + return typeof plaintext === "string" ? Buffer.from(plaintext) : toBuf(plaintext); +} + +export function encryptWithNonce(keyring, ctx, plaintext, nonce) { + const n = toBuf(nonce); + if (n.length !== 24) throw new Error("nonce must be 24 bytes"); + const record = asContext(ctx); + const alg = ALG_XCHACHA20POLY1305_COMMIT; + const dek = keyring.derive(keyring.current, record.purpose, record.tenant, alg); + const hdr = header(VERSION_V3, alg, keyring.current, n); + const aad = Buffer.concat([hdr, record.aad()]); + const { enc, commit } = commitKeys(dek, n); + const ct = xchachaEncrypt(enc, n, aad, plaintextBytes(plaintext)); + return Buffer.concat([hdr, commitment(commit, aad), ct]); +} + +export function encrypt(keyring, ctx, plaintext) { + return encryptWithNonce(keyring, ctx, plaintext, crypto.randomBytes(24)); +} + +export function encryptV2(keyring, ctx, plaintext) { + const record = asContext(ctx); + const alg = ALG_XCHACHA20POLY1305; + const key = keyring.derive(keyring.current, record.purpose, record.tenant, alg); + const nonce = crypto.randomBytes(24); + const hdr = header(VERSION_V2, alg, keyring.current, nonce); + const ct = xchachaEncrypt(key, nonce, Buffer.concat([hdr, record.aad()]), plaintextBytes(plaintext)); + return Buffer.concat([hdr, ct]); +} + +export function encryptLegacyV1(keyring, ctx, plaintext) { + const record = asContext(ctx); + const alg = ALG_AES256GCM; + const key = keyring.derive(keyring.current, record.purpose, record.tenant, alg); + const nonce = crypto.randomBytes(12); + const hdr = header(VERSION_LEGACY, alg, keyring.current, nonce); + const ct = aesGcmEncrypt(key, nonce, Buffer.concat([hdr, record.aad()]), plaintextBytes(plaintext)); + return Buffer.concat([hdr, ct]); +} + +export function decrypt(keyring, ctx, blob, minVersion = VERSION_LEGACY) { + const parsed = parseHeader(blob); + if (parsed.version < minVersion) throw new DowngradeError(); + const record = asContext(ctx); + const key = keyring.derive(parsed.kid, record.purpose, record.tenant, parsed.alg); + const aad = Buffer.concat([parsed.header, record.aad()]); + try { + if (parsed.alg === ALG_XCHACHA20POLY1305_COMMIT) { + const { enc, commit } = commitKeys(key, parsed.nonce); + const expect = commitment(commit, aad); + const tag = parsed.body.subarray(0, COMMIT_LEN); + let opened = null; + let aeadOk = true; + try { + opened = xchachaDecrypt(enc, parsed.nonce, aad, parsed.body.subarray(COMMIT_LEN)); + } catch { + aeadOk = false; + } + const commitOk = crypto.timingSafeEqual(tag, expect); + if (!aeadOk || !commitOk || opened === null) throw new DecryptError(); + return opened; + } + if (parsed.alg === ALG_XCHACHA20POLY1305) { + return xchachaDecrypt(key, parsed.nonce, aad, parsed.body); + } + return aesGcmDecrypt(key, parsed.nonce, aad, parsed.body); + } catch (err) { + if (err instanceof DowngradeError) throw err; + throw new DecryptError(); + } +} + +export function needsRewrap(keyring, blob) { + const parsed = parseHeader(blob); + return parsed.version < VERSION_V3 || parsed.kid !== keyring.current; +} + +export function rewrap(keyring, ctx, blob) { + return encrypt(keyring, ctx, decrypt(keyring, ctx, blob)); +} + +export function normalizeBlindIndex(value) { + return String(value).trim().toLowerCase().split(/\s+/).filter((part) => part.length > 0).join(" "); +} + +export function blindIndex(key, tenant, field, value, length = 16) { + const n = Math.min(length, 32); + const msg = Buffer.concat([ + Buffer.from("EGBI1"), + lp(Buffer.from(tenant)), + lp(Buffer.from(field)), + Buffer.from(normalizeBlindIndex(value)), + ]); + return crypto.createHmac("sha256", toBuf(key)).update(msg).digest().subarray(0, n); +} + +export function verifyBlindIndex(key, tenant, field, value, expected) { + const exp = toBuf(expected); + const got = blindIndex(key, tenant, field, value, exp.length); + if (got.length !== exp.length) return false; + return crypto.timingSafeEqual(got, exp); +} + +export function fingerprint(key) { + return crypto + .createHash("sha256") + .update(Buffer.from("encryptoglyph/key-fingerprint/v1")) + .update(toBuf(key)) + .digest("hex") + .slice(0, 32); +} + +export function deriveRootKeyWithParams(password, salt, params = {}) { + if (typeof crypto.argon2Sync !== "function") { + throw new Error("Argon2id requires Node.js >= 24 (crypto.argon2Sync)"); + } + const s = toBuf(salt); + if (s.length !== 16) throw new Error("salt must be 16 bytes"); + const time = params.time ?? ARGON2_TIME; + const memoryKiB = params.memoryKiB ?? ARGON2_MEMORY_KIB; + const parallelism = params.parallelism ?? ARGON2_PARALLELISM; + const out = crypto.argon2Sync("argon2id", { + message: typeof password === "string" ? Buffer.from(password) : toBuf(password), + nonce: s, + parallelism, + tagLength: KEY_LEN, + memory: memoryKiB, + passes: time, + }); + return Buffer.from(out); +} + +export function deriveRootKeyFromPassword(password, salt) { + return deriveRootKeyWithParams(password, salt, { + time: ARGON2_TIME, + memoryKiB: ARGON2_MEMORY_KIB, + parallelism: ARGON2_PARALLELISM, + }); +} diff --git a/bindings/ts/package.json b/bindings/ts/package.json index 7a7fa01..540c7e2 100644 --- a/bindings/ts/package.json +++ b/bindings/ts/package.json @@ -1,14 +1,37 @@ { "name": "@godesk/encryptoglyph", - "version": "0.1.0", - "private": true, + "version": "0.2.0", + "description": "TypeScript entry for the Encryptoglyph Node.js envelope. Same bytes as sdk/js/envelope.js. No wasm-pack step.", "license": "Apache-2.0", "type": "module", - "main": "dist/index.js", - "types": "dist/index.d.ts", + "engines": { + "node": ">=24" + }, + "main": "./js/envelope.js", + "types": "./index.d.ts", + "exports": { + ".": { + "types": "./index.d.ts", + "import": "./js/envelope.js" + } + }, + "files": [ + "js/envelope.js", + "index.d.ts", + "src/index.ts", + "README.md", + "vector-test.cjs" + ], "scripts": { "build:wasm": "wasm-pack build ../../crates/encryptoglyph --target bundler --out-dir ../../bindings/ts/pkg -- --features wasm", "build:wasm:node": "wasm-pack build ../../crates/encryptoglyph --target nodejs --out-dir ../../bindings/ts/pkg-node -- --features wasm", - "build": "tsc -p ." + "build": "tsc -p .", + "test": "node --test vector-test.mjs", + "typecheck": "tsc -p . --noEmit" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/GoDeskio/Encryptoglyph.git", + "directory": "bindings/ts" } } diff --git a/bindings/ts/src/index.ts b/bindings/ts/src/index.ts index 5d15296..0bc8fb7 100644 --- a/bindings/ts/src/index.ts +++ b/bindings/ts/src/index.ts @@ -1,39 +1,33 @@ -// Thin typed wrapper over the Rust/WASM core. All crypto happens in Rust; nothing here -// touches key material beyond passing bytes through. -import { WasmKeyring, deriveRootKeyFromPassword as wasmDerive } from "../pkg/encryptoglyph.js"; +// Typed re-export of the pure-JS envelope. Crypto runs in js/envelope.js, which is +// the same file as sdk/js/envelope.js. Consumers do not run wasm-pack. +export { + ALG_AES256GCM, + ALG_XCHACHA20POLY1305, + ALG_XCHACHA20POLY1305_COMMIT, + ARGON2_MEMORY_KIB, + ARGON2_PARALLELISM, + ARGON2_TIME, + DecryptError, + DowngradeError, + KEY_LEN, + Keyring, + RecordContext, + VERSION_LEGACY, + VERSION_V2, + VERSION_V3, + blindIndex, + decrypt, + deriveRootKeyFromPassword, + deriveRootKeyWithParams, + encrypt, + encryptLegacyV1, + encryptV2, + encryptWithNonce, + fingerprint, + needsRewrap, + parseHeader, + rewrap, + verifyBlindIndex, +} from "../js/envelope.js"; -export const VERSION_LEGACY = 1; -export const VERSION_V2 = 2; - -export interface RecordContext { - tenant: string; - purpose: string; - table: string; - recordId: string; - field?: string; - schemaVersion?: number; -} - -export class Keyring { - private readonly inner: WasmKeyring; - constructor(kid: string, key: Uint8Array) { this.inner = new WasmKeyring(kid, key); } - add(kid: string, key: Uint8Array, makeCurrent = true): void { this.inner.add(kid, key, makeCurrent); } - retire(kid: string): void { this.inner.retire(kid); } - get current(): string { return this.inner.current(); } - - encrypt(c: RecordContext, plaintext: Uint8Array): Uint8Array { - return this.inner.encrypt(c.tenant, c.purpose, c.table, c.recordId, c.field ?? "", c.schemaVersion ?? 1, plaintext); - } - decrypt(c: RecordContext, blob: Uint8Array, minVersion = VERSION_LEGACY): Uint8Array { - return this.inner.decrypt(c.tenant, c.purpose, c.table, c.recordId, c.field ?? "", c.schemaVersion ?? 1, blob, minVersion); - } - rewrap(c: RecordContext, blob: Uint8Array): Uint8Array { - return this.inner.rewrap(c.tenant, c.purpose, c.table, c.recordId, c.field ?? "", c.schemaVersion ?? 1, blob); - } - needsRewrap(blob: Uint8Array): boolean { return this.inner.needsRewrap(blob); } -} - -/** Argon2id (m=256 MiB, t=3, p=1). salt: 16 random bytes stored with the account. */ -export function deriveRootKeyFromPassword(password: string, salt: Uint8Array): Uint8Array { - return wasmDerive(new TextEncoder().encode(password), salt); -} +export type { Bytes, ParsedHeader, RecordContextInit } from "../index.d.ts"; diff --git a/bindings/ts/tsconfig.json b/bindings/ts/tsconfig.json index 67ea677..bf45a24 100644 --- a/bindings/ts/tsconfig.json +++ b/bindings/ts/tsconfig.json @@ -1 +1,13 @@ -{ "compilerOptions": { "target": "ES2022", "module": "ES2022", "moduleResolution": "bundler", "strict": true, "declaration": true, "outDir": "dist", "skipLibCheck": true }, "include": ["src"] } +{ + "compilerOptions": { + "target": "ES2022", + "module": "ES2022", + "moduleResolution": "bundler", + "strict": true, + "declaration": true, + "noEmit": true, + "skipLibCheck": true, + "allowJs": true + }, + "include": ["src", "index.d.ts"] +} diff --git a/bindings/ts/vector-test.mjs b/bindings/ts/vector-test.mjs new file mode 100644 index 0000000..b757295 --- /dev/null +++ b/bindings/ts/vector-test.mjs @@ -0,0 +1,31 @@ +// Node >= 24. Decrypts testvectors/envelope.json with the pure-JS envelope. +import { readFileSync } from "node:fs"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; +import { Keyring, decrypt } from "./js/envelope.js"; + +const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "../.."); +const vectors = JSON.parse(readFileSync(path.join(root, "testvectors/envelope.json"), "utf8")); +const key = Buffer.from(vectors.key_hex, "hex"); +const kr = new Keyring(vectors.kid, key); +for (const field of ["v3_hex", "v2_hex", "v1_hex"]) { + const opened = Buffer.from(decrypt(kr, vectors.ctx, Buffer.from(vectors[field], "hex"))).toString(); + if (opened !== vectors.plaintext) throw new Error("vector " + field); +} +const blob = Buffer.from(kr.encrypt(vectors.ctx, "x")); +blob[blob.length - 1] ^= 1; +let threw = false; +try { + kr.decrypt(vectors.ctx, blob, 1); +} catch { + threw = true; +} +if (!threw) throw new Error("tamper not detected"); +let downgraded = false; +try { + kr.decrypt(vectors.ctx, Buffer.from(vectors.v1_hex, "hex"), 2); +} catch { + downgraded = true; +} +if (!downgraded) throw new Error("downgrade not blocked"); +console.log("js vectors OK"); diff --git a/docs/SECURITY-HARDENING.md b/docs/SECURITY-HARDENING.md index 9cea932..68461aa 100644 --- a/docs/SECURITY-HARDENING.md +++ b/docs/SECURITY-HARDENING.md @@ -7,7 +7,7 @@ Bitwarden SDK, so it uses real **XChaCha20-Poly1305** (libsodium) instead of XAE ## Library shape Encryptoglyph is the single shared GoDesk crypto library (no separate SDK fork): - `crates/encryptoglyph` — Rust core (RustCrypto `chacha20poly1305`, `aes-gcm`, `hkdf`, `argon2`, `subtle`, `zeroize`; `#![forbid(unsafe_code)]`). Source of truth. -- `wasm` feature + `bindings/ts` — WASM build and TypeScript wrapper for web vaults, extensions, desktop, and Node. +- `sdk/js` and `bindings/ts` — Node.js >= 24 package `@godesk/encryptoglyph`. Pure JS over `node:crypto` (no wasm-pack). The Rust `wasm` feature still builds for wasm32; it is not what Node installs. - `api/eg_crypto` — Python implementation, wire-compatible (to become a PyO3 binding of the core). - `testvectors/envelope.json` — shared vectors. Rust and Python check them in this tree. Go and Node check them in their packages (see [ADOPTION.md](../ADOPTION.md)). - Komboe adoption plan: `docs/design/komboe-integration.md`. @@ -35,7 +35,7 @@ Tests: `api/tests/test_crypto.py` (round-trip, nonce uniqueness, tamper every he 3. **Post-quantum hybrid:** for key exchange/transport (agent enrolment, escrow bundles) use X25519 + ML-KEM-768 hybrid (FIPS 203) once a vetted library is available in our stacks (liboqs / OpenSSL 3.5+ / age PQ plugin). Symmetric XChaCha20-Poly1305 with 256-bit keys is already PQ-adequate. 4. **Key commitment:** shipped as envelope v3 (see the table above). Do not add a second commitment. v2 and v1 stay readable until rewrap. 5. **Memory hygiene:** the Rust core zeroises keys; replace the pure-Python path with a PyO3 binding of the core. -6. **Bindings:** publish the WASM/TS package to the internal registry with a CI wasm-pack build + TS vector test; add UniFFI (mobile) and a Go binding if needed. +6. **Bindings:** `@godesk/encryptoglyph` (`sdk/js`, Node >= 24) is the install path and checks `testvectors/envelope.json` locally. The Rust `wasm` feature still builds (`getrandom` `js`, and `getrandom` 0.4 `wasm_js` on wasm32). Go is `bindings/go`. UniFFI (mobile) is still open. 7. **Ittia and other GoDesk projects:** adopt the v3 envelope. Paths and rewrap steps are in [ADOPTION.md](../ADOPTION.md). 8. **Audit:** third-party crypto review of this design + the M6 pentest; fuzz `parse_header`; add CI dependency/license scan. 9. **CI:** `.github/workflows/ci.yml` runs lint (ruff), pytest, compose config, gitleaks, the exposure probe, `rust-core` (`cargo test --locked`, clippy, `cargo deny`), license metadata, and the console e2e job. It does not run `cargo fmt` or a wasm-pack build. Node and Go vector tests are local until that workflow grows jobs for them. GitHub Actions budget failures are not product failures. diff --git a/docs/img/architecture.svg b/docs/img/architecture.svg index a83ea9f..f8cf5d1 100644 --- a/docs/img/architecture.svg +++ b/docs/img/architecture.svg @@ -1,6 +1,6 @@ Encryptoglyph architecture - External Traefik on proxy-net routes to the MSP console and the API. OpenBao, Postgres, and the restic rest-server stay on an internal network with no host ports. The Rust crate, Python module, and TypeScript wrapper share one XChaCha20-Poly1305 envelope. + External Traefik on proxy-net routes to the MSP console and the API. OpenBao, Postgres, and the restic rest-server stay on an internal network with no host ports. The Rust crate, Python module, and Node.js package share one XChaCha20-Poly1305 envelope. Encryptoglyph deployment Compose skeleton in deploy/docker-compose.yml. Data services are not published on the host. @@ -67,6 +67,6 @@ api/eg_crypto - TypeScript - bindings/ts WASM + Node.js + sdk/js pure JS diff --git a/package.json b/package.json new file mode 100644 index 0000000..e60407d --- /dev/null +++ b/package.json @@ -0,0 +1,38 @@ +{ + "name": "@godesk/encryptoglyph", + "version": "0.2.0", + "description": "Encryptoglyph envelope encryption for Node.js. XChaCha20-Poly1305, HKDF-SHA256, and Argon2id, with no wasm-pack step.", + "license": "Apache-2.0", + "type": "module", + "engines": { + "node": ">=24" + }, + "main": "./sdk/js/index.js", + "types": "./sdk/js/index.d.ts", + "exports": { + ".": { + "types": "./sdk/js/index.d.ts", + "import": "./sdk/js/index.js" + }, + "./client": { + "import": "./sdk/js/encryptoglyph.js", + "default": "./sdk/js/encryptoglyph.js" + } + }, + "files": [ + "sdk/js/index.js", + "sdk/js/index.d.ts", + "sdk/js/envelope.js", + "sdk/js/encryptoglyph.js", + "sdk/js/README.md", + "LICENSE", + "NOTICE" + ], + "scripts": { + "test": "node --test sdk/js/test/vectors.test.js" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/GoDeskio/Encryptoglyph.git" + } +} diff --git a/sdk/js/README.md b/sdk/js/README.md new file mode 100644 index 0000000..8286756 --- /dev/null +++ b/sdk/js/README.md @@ -0,0 +1,77 @@ +# @godesk/encryptoglyph + +Node.js envelope encryption for Encryptoglyph. The package is plain ECMAScript modules. Installing it does not run `wasm-pack`. + +Requires Node.js 24 or newer. `crypto.argon2Sync`, HKDF, AES-256-GCM, and ChaCha20-Poly1305 come from `node:crypto`. XChaCha20-Poly1305 is HChaCha20 (draft-irtf-cfrg-xchacha) plus that ChaCha20-Poly1305. The default writer is envelope version 3 (XChaCha20-Poly1305 with a 32-byte key commitment). Version 2 and legacy AES-256-GCM version 1 still decrypt. `rewrap` writes a fresh version-3 blob. + +## Install + +From a checkout of this repository: + +```bash +npm install ./sdk/js +``` + +The packed tarball in this directory installs the same files: + +```bash +npm install ./sdk/js/godesk-encryptoglyph-0.2.0.tgz +``` + +From git, after this package is on the ref you name: + +```bash +npm install github:GoDeskio/Encryptoglyph# +npm install github:GoDeskio/Encryptoglyph#:sdk/js +``` + +The repository root `package.json` and `sdk/js/package.json` both publish `@godesk/encryptoglyph`. `bindings/ts` is the same runtime with the TypeScript wrapper source. + +## Seal a credential + +Keep the 32-byte root key outside the repo (environment, secret store, or a password-derived key). The record context is authenticated, so a ciphertext cannot be moved to another row or field. + +```js +import { Keyring, encrypt, decrypt } from "@godesk/encryptoglyph"; + +const key = Buffer.from(process.env.EG_ROOT_KEY, "hex"); +const kr = new Keyring("k1", key); +const ctx = { + tenant: "konektor", + purpose: "credential", + table: "connections", + recordId: "conn-42", + field: "secret", +}; +const blob = encrypt(kr, ctx, "super-secret"); +const opened = decrypt(kr, ctx, blob); +``` + +`new Keyring("k1", key)` matches the TypeScript wrapper. `new Keyring({ k1: key }, "k1")` matches the Python keyring. + +Password roots use Argon2id (m = 256 MiB, t = 3, p = 1, 16-byte salt), same as the Rust and Python libraries: + +```js +import { deriveRootKeyFromPassword } from "@godesk/encryptoglyph"; + +const root = deriveRootKeyFromPassword(password, salt16); +``` + +## Sidecar client + +`encryptoglyph.js` is the browser and Node client for the `/v1` HTTP sidecar. It does not encrypt locally. + +```js +import { Encryptoglyph } from "@godesk/encryptoglyph"; + +const eg = new Encryptoglyph(process.env.EG_URL); +await eg.session(); +``` + +## Tests + +```bash +node --test sdk/js/test/vectors.test.js +``` + +The tests check `testvectors/envelope.json` (v1, v2, v3, and the blind index) and the draft HChaCha20 vector. diff --git a/sdk/js/envelope.js b/sdk/js/envelope.js new file mode 100644 index 0000000..29b71d9 --- /dev/null +++ b/sdk/js/envelope.js @@ -0,0 +1,450 @@ +// Encryptoglyph envelope for Node.js >= 24. No wasm-pack and no extra crypto dependency. +// +// Wire format (see docs/SPEC-ENVELOPE.md and testvectors/envelope.json): +// "EG" | version u8 | alg u8 | kid_len u8 | kid | nonce | body +// v3 body = 32-byte key commitment || ciphertext || 16-byte tag (default writer) +// v2 body = ciphertext || tag, XChaCha20-Poly1305 (decrypt and upgrade) +// v1 body = ciphertext || tag, AES-256-GCM (decrypt only) +// +// XChaCha20-Poly1305 is HChaCha20 (draft-irtf-cfrg-xchacha) plus Node's OpenSSL +// ChaCha20-Poly1305. HKDF-SHA256 and Argon2id come from node:crypto. + +import crypto from "node:crypto"; + +export const VERSION_LEGACY = 1; +export const VERSION_V2 = 2; +export const VERSION_V3 = 3; +export const ALG_AES256GCM = 1; +export const ALG_XCHACHA20POLY1305 = 2; +export const ALG_XCHACHA20POLY1305_COMMIT = 3; +export const KEY_LEN = 32; +export const ARGON2_TIME = 3; +export const ARGON2_MEMORY_KIB = 262144; +export const ARGON2_PARALLELISM = 1; + +const COMMIT_LEN = 32; +const TAG_LEN = 16; +const HKDF_SALT = Buffer.from("encryptoglyph/hkdf-salt/v2"); +const NONCE_LEN = { + [ALG_AES256GCM]: 12, + [ALG_XCHACHA20POLY1305]: 24, + [ALG_XCHACHA20POLY1305_COMMIT]: 24, +}; +const VERSION_ALG = { + [VERSION_LEGACY]: ALG_AES256GCM, + [VERSION_V2]: ALG_XCHACHA20POLY1305, + [VERSION_V3]: ALG_XCHACHA20POLY1305_COMMIT, +}; + +export class DecryptError extends Error { + constructor(message = "decryption failed") { + super(message); + this.name = "DecryptError"; + } +} + +export class DowngradeError extends DecryptError { + constructor(message = "envelope version below minimum") { + super(message); + this.name = "DowngradeError"; + } +} + +function toBuf(value, encoding) { + if (Buffer.isBuffer(value)) return value; + if (value instanceof Uint8Array) return Buffer.from(value); + if (typeof value === "string") return Buffer.from(value, encoding); + throw new TypeError("expected bytes or a string"); +} + +function lp(bytes) { + const len = Buffer.alloc(4); + len.writeUInt32BE(bytes.length); + return Buffer.concat([len, bytes]); +} + +function rotl(v, n) { + return ((v << n) | (v >>> (32 - n))) >>> 0; +} + +function quarterRound(s, a, b, c, d) { + s[a] = (s[a] + s[b]) >>> 0; + s[d] = rotl(s[d] ^ s[a], 16); + s[c] = (s[c] + s[d]) >>> 0; + s[b] = rotl(s[b] ^ s[c], 12); + s[a] = (s[a] + s[b]) >>> 0; + s[d] = rotl(s[d] ^ s[a], 8); + s[c] = (s[c] + s[d]) >>> 0; + s[b] = rotl(s[b] ^ s[c], 7); +} + +/** HChaCha20 from draft-irtf-cfrg-xchacha. Output is raw state words 0-3 and 12-15. */ +export function hchacha20(key, nonce16) { + const k = toBuf(key); + const n = toBuf(nonce16); + if (k.length !== 32 || n.length !== 16) throw new Error("invalid HChaCha20 input"); + const s = new Uint32Array(16); + s[0] = 0x61707865; + s[1] = 0x3320646e; + s[2] = 0x79622d32; + s[3] = 0x6b206574; + for (let i = 0; i < 8; i++) s[4 + i] = k.readUInt32LE(i * 4); + for (let i = 0; i < 4; i++) s[12 + i] = n.readUInt32LE(i * 4); + for (let i = 0; i < 10; i++) { + quarterRound(s, 0, 4, 8, 12); + quarterRound(s, 1, 5, 9, 13); + quarterRound(s, 2, 6, 10, 14); + quarterRound(s, 3, 7, 11, 15); + quarterRound(s, 0, 5, 10, 15); + quarterRound(s, 1, 6, 11, 12); + quarterRound(s, 2, 7, 8, 13); + quarterRound(s, 3, 4, 9, 14); + } + const out = Buffer.alloc(32); + for (let i = 0; i < 4; i++) out.writeUInt32LE(s[i], i * 4); + for (let i = 0; i < 4; i++) out.writeUInt32LE(s[12 + i], 16 + i * 4); + return out; +} + +function hkdf32(ikm, salt, info) { + return Buffer.from(crypto.hkdfSync("sha256", ikm, salt, info, KEY_LEN)); +} + +function xchachaEncrypt(key, nonce24, aad, plaintext) { + const sub = hchacha20(key, nonce24.subarray(0, 16)); + const iv = Buffer.concat([Buffer.alloc(4), nonce24.subarray(16, 24)]); + const cipher = crypto.createCipheriv("chacha20-poly1305", sub, iv, { authTagLength: TAG_LEN }); + cipher.setAAD(aad); + return Buffer.concat([cipher.update(plaintext), cipher.final(), cipher.getAuthTag()]); +} + +function xchachaDecrypt(key, nonce24, aad, body) { + const sub = hchacha20(key, nonce24.subarray(0, 16)); + const iv = Buffer.concat([Buffer.alloc(4), nonce24.subarray(16, 24)]); + const ct = body.subarray(0, body.length - TAG_LEN); + const tag = body.subarray(body.length - TAG_LEN); + const decipher = crypto.createDecipheriv("chacha20-poly1305", sub, iv, { authTagLength: TAG_LEN }); + decipher.setAAD(aad); + decipher.setAuthTag(tag); + return Buffer.concat([decipher.update(ct), decipher.final()]); +} + +function aesGcmEncrypt(key, nonce, aad, plaintext) { + const cipher = crypto.createCipheriv("aes-256-gcm", key, nonce); + cipher.setAAD(aad); + return Buffer.concat([cipher.update(plaintext), cipher.final(), cipher.getAuthTag()]); +} + +function aesGcmDecrypt(key, nonce, aad, body) { + const ct = body.subarray(0, body.length - TAG_LEN); + const tag = body.subarray(body.length - TAG_LEN); + const decipher = crypto.createDecipheriv("aes-256-gcm", key, nonce); + decipher.setAAD(aad); + decipher.setAuthTag(tag); + return Buffer.concat([decipher.update(ct), decipher.final()]); +} + +export class RecordContext { + constructor(tenant, purpose, table, recordId, field = "", schemaVersion = 1) { + this.tenant = String(tenant); + this.purpose = String(purpose); + this.table = String(table); + this.recordId = String(recordId); + this.field = String(field ?? ""); + this.schemaVersion = schemaVersion; + } + + aad() { + const parts = [this.tenant, this.purpose, this.table, this.recordId, this.field, String(this.schemaVersion)]; + return Buffer.concat([Buffer.from("EGAAD1"), ...parts.map((part) => lp(Buffer.from(part)))]); + } +} + +export function asContext(ctx) { + if (ctx instanceof RecordContext) return ctx; + if (Array.isArray(ctx)) { + const [tenant, purpose, table, recordId, field = "", schemaVersion = 1] = ctx; + return new RecordContext(tenant, purpose, table, recordId, field, schemaVersion); + } + if (ctx && typeof ctx === "object") { + return new RecordContext( + ctx.tenant, + ctx.purpose, + ctx.table, + ctx.recordId ?? ctx.record_id, + ctx.field ?? "", + ctx.schemaVersion ?? ctx.schema_version ?? 1, + ); + } + throw new TypeError("invalid record context"); +} + +function copyKey(key) { + const buf = toBuf(key); + if (buf.length !== KEY_LEN) throw new Error("root keys must be 32 bytes"); + return Buffer.from(buf); +} + +function checkKid(kid) { + const bytes = Buffer.from(String(kid), "utf8"); + if (bytes.length < 1 || bytes.length > 255) throw new Error("bad key id"); + return String(kid); +} + +export class Keyring { + constructor(kidOrKeys, keyOrCurrent) { + this._keys = new Map(); + this._current = ""; + if (typeof kidOrKeys === "string") { + this.add(kidOrKeys, keyOrCurrent, true); + return; + } + if (kidOrKeys && typeof kidOrKeys === "object" && !ArrayBuffer.isView(kidOrKeys)) { + for (const [kid, key] of Object.entries(kidOrKeys)) this.add(kid, key, false); + if (typeof keyOrCurrent !== "string" || !this._keys.has(keyOrCurrent)) { + throw new Error("current key id not in keyring"); + } + this._current = keyOrCurrent; + return; + } + throw new TypeError("invalid keyring"); + } + + static generateKey() { + return crypto.randomBytes(KEY_LEN); + } + + get current() { + return this._current; + } + + add(kid, key, makeCurrent = true) { + const id = checkKid(kid); + this._keys.set(id, copyKey(key)); + if (makeCurrent) this._current = id; + } + + retire(kid) { + if (kid === this._current) throw new Error("cannot retire current key"); + const prev = this._keys.get(kid); + if (prev) prev.fill(0); + this._keys.delete(kid); + } + + has(kid) { + return this._keys.has(kid); + } + + derive(kid, purpose, tenant, alg) { + const root = this._keys.get(kid); + if (!root) throw new DecryptError(); + const info = Buffer.concat([ + Buffer.from("encryptoglyph/dek/v2"), + lp(Buffer.from(purpose)), + lp(Buffer.from(tenant)), + Buffer.from([alg]), + ]); + return hkdf32(root, HKDF_SALT, info); + } + + encrypt(ctx, plaintext) { + return encrypt(this, ctx, plaintext); + } + + decrypt(ctx, blob, minVersion = VERSION_LEGACY) { + return decrypt(this, ctx, blob, minVersion); + } + + rewrap(ctx, blob) { + return rewrap(this, ctx, blob); + } + + needsRewrap(blob) { + return needsRewrap(this, blob); + } +} + +function header(version, alg, kid, nonce) { + const kidBytes = Buffer.from(checkKid(kid), "utf8"); + return Buffer.concat([Buffer.from("EG"), Buffer.from([version, alg, kidBytes.length]), kidBytes, nonce]); +} + +export function parseHeader(blob) { + const buf = toBuf(blob); + try { + if (buf.length < 5 || buf[0] !== 0x45 || buf[1] !== 0x47) throw new Error("magic"); + const version = buf[2]; + const alg = buf[3]; + const klen = buf[4]; + if (VERSION_ALG[version] !== alg) throw new Error("pair"); + const off = 5 + klen; + const n = NONCE_LEN[alg]; + const extra = alg === ALG_XCHACHA20POLY1305_COMMIT ? COMMIT_LEN : 0; + if (buf.length < off + n + extra + TAG_LEN) throw new Error("short"); + const kid = new TextDecoder("utf-8", { fatal: true }).decode(buf.subarray(5, off)); + const nonce = buf.subarray(off, off + n); + return { + version, + alg, + kid, + nonce, + header: buf.subarray(0, off + n), + body: buf.subarray(off + n), + }; + } catch (err) { + if (err instanceof DecryptError) throw err; + throw new DecryptError(); + } +} + +function commitKeys(dek, nonce) { + return { + enc: hkdf32(dek, nonce, Buffer.from("encryptoglyph/v3/enc")), + commit: hkdf32(dek, nonce, Buffer.from("encryptoglyph/v3/commit")), + }; +} + +function commitment(commitKey, aad) { + return crypto.createHmac("sha256", commitKey).update(Buffer.from("EGCMT1")).update(aad).digest(); +} + +function plaintextBytes(plaintext) { + return typeof plaintext === "string" ? Buffer.from(plaintext) : toBuf(plaintext); +} + +export function encryptWithNonce(keyring, ctx, plaintext, nonce) { + const n = toBuf(nonce); + if (n.length !== 24) throw new Error("nonce must be 24 bytes"); + const record = asContext(ctx); + const alg = ALG_XCHACHA20POLY1305_COMMIT; + const dek = keyring.derive(keyring.current, record.purpose, record.tenant, alg); + const hdr = header(VERSION_V3, alg, keyring.current, n); + const aad = Buffer.concat([hdr, record.aad()]); + const { enc, commit } = commitKeys(dek, n); + const ct = xchachaEncrypt(enc, n, aad, plaintextBytes(plaintext)); + return Buffer.concat([hdr, commitment(commit, aad), ct]); +} + +export function encrypt(keyring, ctx, plaintext) { + return encryptWithNonce(keyring, ctx, plaintext, crypto.randomBytes(24)); +} + +export function encryptV2(keyring, ctx, plaintext) { + const record = asContext(ctx); + const alg = ALG_XCHACHA20POLY1305; + const key = keyring.derive(keyring.current, record.purpose, record.tenant, alg); + const nonce = crypto.randomBytes(24); + const hdr = header(VERSION_V2, alg, keyring.current, nonce); + const ct = xchachaEncrypt(key, nonce, Buffer.concat([hdr, record.aad()]), plaintextBytes(plaintext)); + return Buffer.concat([hdr, ct]); +} + +export function encryptLegacyV1(keyring, ctx, plaintext) { + const record = asContext(ctx); + const alg = ALG_AES256GCM; + const key = keyring.derive(keyring.current, record.purpose, record.tenant, alg); + const nonce = crypto.randomBytes(12); + const hdr = header(VERSION_LEGACY, alg, keyring.current, nonce); + const ct = aesGcmEncrypt(key, nonce, Buffer.concat([hdr, record.aad()]), plaintextBytes(plaintext)); + return Buffer.concat([hdr, ct]); +} + +export function decrypt(keyring, ctx, blob, minVersion = VERSION_LEGACY) { + const parsed = parseHeader(blob); + if (parsed.version < minVersion) throw new DowngradeError(); + const record = asContext(ctx); + const key = keyring.derive(parsed.kid, record.purpose, record.tenant, parsed.alg); + const aad = Buffer.concat([parsed.header, record.aad()]); + try { + if (parsed.alg === ALG_XCHACHA20POLY1305_COMMIT) { + const { enc, commit } = commitKeys(key, parsed.nonce); + const expect = commitment(commit, aad); + const tag = parsed.body.subarray(0, COMMIT_LEN); + let opened = null; + let aeadOk = true; + try { + opened = xchachaDecrypt(enc, parsed.nonce, aad, parsed.body.subarray(COMMIT_LEN)); + } catch { + aeadOk = false; + } + const commitOk = crypto.timingSafeEqual(tag, expect); + if (!aeadOk || !commitOk || opened === null) throw new DecryptError(); + return opened; + } + if (parsed.alg === ALG_XCHACHA20POLY1305) { + return xchachaDecrypt(key, parsed.nonce, aad, parsed.body); + } + return aesGcmDecrypt(key, parsed.nonce, aad, parsed.body); + } catch (err) { + if (err instanceof DowngradeError) throw err; + throw new DecryptError(); + } +} + +export function needsRewrap(keyring, blob) { + const parsed = parseHeader(blob); + return parsed.version < VERSION_V3 || parsed.kid !== keyring.current; +} + +export function rewrap(keyring, ctx, blob) { + return encrypt(keyring, ctx, decrypt(keyring, ctx, blob)); +} + +export function normalizeBlindIndex(value) { + return String(value).trim().toLowerCase().split(/\s+/).filter((part) => part.length > 0).join(" "); +} + +export function blindIndex(key, tenant, field, value, length = 16) { + const n = Math.min(length, 32); + const msg = Buffer.concat([ + Buffer.from("EGBI1"), + lp(Buffer.from(tenant)), + lp(Buffer.from(field)), + Buffer.from(normalizeBlindIndex(value)), + ]); + return crypto.createHmac("sha256", toBuf(key)).update(msg).digest().subarray(0, n); +} + +export function verifyBlindIndex(key, tenant, field, value, expected) { + const exp = toBuf(expected); + const got = blindIndex(key, tenant, field, value, exp.length); + if (got.length !== exp.length) return false; + return crypto.timingSafeEqual(got, exp); +} + +export function fingerprint(key) { + return crypto + .createHash("sha256") + .update(Buffer.from("encryptoglyph/key-fingerprint/v1")) + .update(toBuf(key)) + .digest("hex") + .slice(0, 32); +} + +export function deriveRootKeyWithParams(password, salt, params = {}) { + if (typeof crypto.argon2Sync !== "function") { + throw new Error("Argon2id requires Node.js >= 24 (crypto.argon2Sync)"); + } + const s = toBuf(salt); + if (s.length !== 16) throw new Error("salt must be 16 bytes"); + const time = params.time ?? ARGON2_TIME; + const memoryKiB = params.memoryKiB ?? ARGON2_MEMORY_KIB; + const parallelism = params.parallelism ?? ARGON2_PARALLELISM; + const out = crypto.argon2Sync("argon2id", { + message: typeof password === "string" ? Buffer.from(password) : toBuf(password), + nonce: s, + parallelism, + tagLength: KEY_LEN, + memory: memoryKiB, + passes: time, + }); + return Buffer.from(out); +} + +export function deriveRootKeyFromPassword(password, salt) { + return deriveRootKeyWithParams(password, salt, { + time: ARGON2_TIME, + memoryKiB: ARGON2_MEMORY_KIB, + parallelism: ARGON2_PARALLELISM, + }); +} diff --git a/sdk/js/godesk-encryptoglyph-0.2.0.tgz b/sdk/js/godesk-encryptoglyph-0.2.0.tgz new file mode 100644 index 0000000..df573c5 Binary files /dev/null and b/sdk/js/godesk-encryptoglyph-0.2.0.tgz differ diff --git a/sdk/js/index.d.ts b/sdk/js/index.d.ts new file mode 100644 index 0000000..24e810f --- /dev/null +++ b/sdk/js/index.d.ts @@ -0,0 +1,110 @@ +export const VERSION_LEGACY: 1; +export const VERSION_V2: 2; +export const VERSION_V3: 3; +export const ALG_AES256GCM: 1; +export const ALG_XCHACHA20POLY1305: 2; +export const ALG_XCHACHA20POLY1305_COMMIT: 3; +export const KEY_LEN: 32; +export const ARGON2_TIME: 3; +export const ARGON2_MEMORY_KIB: 262144; +export const ARGON2_PARALLELISM: 1; + +export class DecryptError extends Error {} +export class DowngradeError extends DecryptError {} + +export type Bytes = Uint8Array; + +export interface RecordContextInit { + tenant: string; + purpose: string; + table: string; + recordId?: string; + record_id?: string; + field?: string; + schemaVersion?: number; + schema_version?: number; +} + +export class RecordContext { + constructor( + tenant: string, + purpose: string, + table: string, + recordId: string, + field?: string, + schemaVersion?: number, + ); + tenant: string; + purpose: string; + table: string; + recordId: string; + field: string; + schemaVersion: number; + aad(): Uint8Array; +} + +export class Keyring { + constructor(kid: string, key: Bytes); + constructor(keys: Record, current: string); + static generateKey(): Uint8Array; + readonly current: string; + add(kid: string, key: Bytes, makeCurrent?: boolean): void; + retire(kid: string): void; + has(kid: string): boolean; + derive(kid: string, purpose: string, tenant: string, alg: number): Uint8Array; + encrypt(ctx: RecordContext | RecordContextInit | unknown[], plaintext: Bytes | string): Uint8Array; + decrypt(ctx: RecordContext | RecordContextInit | unknown[], blob: Bytes, minVersion?: number): Uint8Array; + rewrap(ctx: RecordContext | RecordContextInit | unknown[], blob: Bytes): Uint8Array; + needsRewrap(blob: Bytes): boolean; +} + +export interface ParsedHeader { + version: number; + alg: number; + kid: string; + nonce: Uint8Array; + header: Uint8Array; + body: Uint8Array; +} + +export function parseHeader(blob: Bytes): ParsedHeader; +export function encrypt(keyring: Keyring, ctx: RecordContext | RecordContextInit | unknown[], plaintext: Bytes | string): Uint8Array; +export function encryptWithNonce( + keyring: Keyring, + ctx: RecordContext | RecordContextInit | unknown[], + plaintext: Bytes | string, + nonce: Bytes, +): Uint8Array; +export function encryptV2(keyring: Keyring, ctx: RecordContext | RecordContextInit | unknown[], plaintext: Bytes | string): Uint8Array; +export function encryptLegacyV1( + keyring: Keyring, + ctx: RecordContext | RecordContextInit | unknown[], + plaintext: Bytes | string, +): Uint8Array; +export function decrypt( + keyring: Keyring, + ctx: RecordContext | RecordContextInit | unknown[], + blob: Bytes, + minVersion?: number, +): Uint8Array; +export function needsRewrap(keyring: Keyring, blob: Bytes): boolean; +export function rewrap(keyring: Keyring, ctx: RecordContext | RecordContextInit | unknown[], blob: Bytes): Uint8Array; +export function blindIndex(key: Bytes, tenant: string, field: string, value: string, length?: number): Uint8Array; +export function verifyBlindIndex(key: Bytes, tenant: string, field: string, value: string, expected: Bytes): boolean; +export function fingerprint(key: Bytes): string; +export function deriveRootKeyFromPassword(password: string | Bytes, salt: Bytes): Uint8Array; +export function deriveRootKeyWithParams( + password: string | Bytes, + salt: Bytes, + params?: { time?: number; memoryKiB?: number; parallelism?: number }, +): Uint8Array; +export function hchacha20(key: Bytes, nonce16: Bytes): Uint8Array; +export function asContext(ctx: RecordContext | RecordContextInit | unknown[]): RecordContext; +export function normalizeBlindIndex(value: string): string; + +export class Encryptoglyph { + constructor(baseUrl: string); + sessionId: string; + session(): Promise; + seal(ctx: Record, plaintext: Bytes | string): Promise; +} diff --git a/sdk/js/index.js b/sdk/js/index.js new file mode 100644 index 0000000..eb75f22 --- /dev/null +++ b/sdk/js/index.js @@ -0,0 +1,34 @@ +export { + ALG_AES256GCM, + ALG_XCHACHA20POLY1305, + ALG_XCHACHA20POLY1305_COMMIT, + ARGON2_MEMORY_KIB, + ARGON2_PARALLELISM, + ARGON2_TIME, + DecryptError, + DowngradeError, + KEY_LEN, + Keyring, + RecordContext, + VERSION_LEGACY, + VERSION_V2, + VERSION_V3, + asContext, + blindIndex, + decrypt, + deriveRootKeyFromPassword, + deriveRootKeyWithParams, + encrypt, + encryptLegacyV1, + encryptV2, + encryptWithNonce, + fingerprint, + hchacha20, + needsRewrap, + normalizeBlindIndex, + parseHeader, + rewrap, + verifyBlindIndex, +} from "./envelope.js"; + +export { Encryptoglyph } from "./encryptoglyph.js"; diff --git a/sdk/js/package.json b/sdk/js/package.json new file mode 100644 index 0000000..d8c611c --- /dev/null +++ b/sdk/js/package.json @@ -0,0 +1,42 @@ +{ + "name": "@godesk/encryptoglyph", + "version": "0.2.0", + "description": "Encryptoglyph envelope encryption for Node.js. XChaCha20-Poly1305, HKDF-SHA256, and Argon2id, with no wasm-pack step.", + "license": "Apache-2.0", + "type": "module", + "engines": { + "node": ">=24" + }, + "main": "./index.js", + "types": "./index.d.ts", + "exports": { + ".": { + "types": "./index.d.ts", + "import": "./index.js" + }, + "./envelope": { + "types": "./index.d.ts", + "import": "./envelope.js" + }, + "./client": { + "import": "./encryptoglyph.js", + "default": "./encryptoglyph.js" + } + }, + "files": [ + "index.js", + "index.d.ts", + "envelope.js", + "encryptoglyph.js", + "README.md" + ], + "scripts": { + "test": "node --test test/vectors.test.js", + "pack": "npm pack" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/GoDeskio/Encryptoglyph.git", + "directory": "sdk/js" + } +} diff --git a/sdk/js/test/vectors.test.js b/sdk/js/test/vectors.test.js new file mode 100644 index 0000000..4f0fb47 --- /dev/null +++ b/sdk/js/test/vectors.test.js @@ -0,0 +1,191 @@ +import assert from "node:assert/strict"; +import crypto from "node:crypto"; +import { execFileSync } from "node:child_process"; +import { readFileSync } from "node:fs"; +import path from "node:path"; +import test from "node:test"; +import { fileURLToPath } from "node:url"; + +import { + ARGON2_MEMORY_KIB, + ARGON2_PARALLELISM, + ARGON2_TIME, + DecryptError, + DowngradeError, + Keyring, + VERSION_V2, + VERSION_V3, + blindIndex, + decrypt, + deriveRootKeyWithParams, + encrypt, + encryptLegacyV1, + encryptV2, + encryptWithNonce, + hchacha20, + needsRewrap, + parseHeader, + rewrap, +} from "../envelope.js"; + +const here = path.dirname(fileURLToPath(import.meta.url)); + +function loadVectors() { + const candidates = [ + path.resolve(here, "../../../testvectors/envelope.json"), + path.resolve(here, "../../testvectors/envelope.json"), + ]; + for (const candidate of candidates) { + try { + return JSON.parse(readFileSync(candidate, "utf8")); + } catch { + // try the next location + } + } + throw new Error("testvectors/envelope.json not found"); +} + +const vectors = loadVectors(); +const key = Buffer.from(vectors.key_hex, "hex"); +const ctx = vectors.ctx; + +function keyring() { + return new Keyring(vectors.kid, key); +} + +test("node is 24 or newer", () => { + const major = Number(process.versions.node.split(".")[0]); + assert.ok(major >= 24, `Node ${process.versions.node} is below 24`); +}); + +test("HChaCha20 matches the CFRG draft vector", () => { + const draftKey = Buffer.from("000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f", "hex"); + const nonce = Buffer.from("000000090000004a0000000031415927", "hex"); + const expect = "82413b4227b27bfed30e42508a877d73a0f9e4d58a74a853c12ec41326d3ecdc"; + assert.equal(hchacha20(draftKey, nonce).toString("hex"), expect); +}); + +test("shared vectors decrypt v1, v2, and v3", () => { + const kr = keyring(); + for (const field of ["v3_hex", "v2_hex", "v1_hex"]) { + const opened = decrypt(kr, ctx, Buffer.from(vectors[field], "hex")); + assert.equal(Buffer.from(opened).toString(), vectors.plaintext); + } +}); + +test("v3 known answer reseals with the vector nonce", () => { + const kr = keyring(); + const blob = Buffer.from(vectors.v3_hex, "hex"); + const header = parseHeader(blob); + assert.equal(header.version, VERSION_V3); + assert.equal(header.kid, vectors.kid); + assert.equal(header.nonce.length, 24); + const again = encryptWithNonce(kr, ctx, vectors.plaintext, header.nonce); + assert.equal(Buffer.from(again).toString("hex"), vectors.v3_hex); +}); + +test("blind index matches the shared vector", () => { + const tag = blindIndex(key, "tenant-a", "email", "Foo@Example.com", 16); + assert.equal(Buffer.from(tag).toString("hex"), vectors.blind_index_hex); +}); + +test("packed tarball contains the same envelope.js", () => { + const packed = execFileSync("tar", ["-xOf", path.resolve(here, "../godesk-encryptoglyph-0.2.0.tgz"), "package/envelope.js"]); + const source = readFileSync(path.resolve(here, "../envelope.js")); + assert.equal(crypto.createHash("sha256").update(packed).digest("hex"), crypto.createHash("sha256").update(source).digest("hex")); +}); + +test("bindings/ts ships the same envelope.js", () => { + const canonical = readFileSync(path.resolve(here, "../envelope.js")); + const wrapper = readFileSync(path.resolve(here, "../../../bindings/ts/js/envelope.js")); + assert.equal( + crypto.createHash("sha256").update(canonical).digest("hex"), + crypto.createHash("sha256").update(wrapper).digest("hex"), + ); +}); + +test("round trip, unique nonces, and rewrap of legacy blobs", () => { + const kr = new Keyring("k1", Keyring.generateKey()); + const record = { tenant: "acme", purpose: "credential", table: "connections", recordId: "42", field: "secret" }; + const first = encrypt(kr, record, "super-secret"); + const second = encrypt(kr, record, "super-secret"); + assert.equal(parseHeader(first).version, VERSION_V3); + assert.notEqual(Buffer.from(first).toString("hex"), Buffer.from(second).toString("hex")); + assert.equal(Buffer.from(decrypt(kr, record, first)).toString(), "super-secret"); + assert.equal(needsRewrap(kr, first), false); + + const legacy = encryptLegacyV1(kr, record, "legacy"); + assert.equal(needsRewrap(kr, legacy), true); + assert.equal(Buffer.from(decrypt(kr, record, legacy)).toString(), "legacy"); + const upgraded = rewrap(kr, record, legacy); + assert.equal(parseHeader(upgraded).version, VERSION_V3); + assert.equal(needsRewrap(kr, upgraded), false); + assert.throws(() => decrypt(kr, record, legacy, VERSION_V2), DowngradeError); + + const v2 = encryptV2(kr, record, "v2 data"); + assert.equal(parseHeader(v2).version, VERSION_V2); + const fromV2 = rewrap(kr, record, v2); + assert.equal(parseHeader(fromV2).version, VERSION_V3); + assert.equal(Buffer.from(decrypt(kr, record, fromV2)).toString(), "v2 data"); +}); + +test("tamper, wrong context, and wrong key fail closed", () => { + const kr = new Keyring("k1", Keyring.generateKey()); + const record = { tenant: "acme", purpose: "field", table: "users", recordId: "1", field: "email" }; + const blob = Buffer.from(encrypt(kr, record, "secret")); + blob[blob.length - 1] ^= 0x01; + assert.throws(() => decrypt(kr, record, blob), DecryptError); + assert.throws( + () => decrypt(kr, { ...record, field: "other" }, encrypt(kr, record, "secret")), + DecryptError, + ); + const other = new Keyring("k1", Keyring.generateKey()); + assert.throws(() => decrypt(other, record, encrypt(kr, record, "secret")), DecryptError); +}); + +test("rotation rewraps under the new key id", () => { + const kr = new Keyring("k1", Keyring.generateKey()); + const record = { tenant: "acme", purpose: "tool-result", table: "calls", recordId: "9", field: "body" }; + const old = encrypt(kr, record, "rotate me"); + kr.add("k2", Keyring.generateKey()); + assert.equal(kr.current, "k2"); + assert.equal(needsRewrap(kr, old), true); + assert.equal(Buffer.from(kr.decrypt(record, old)).toString(), "rotate me"); + const next = kr.rewrap(record, old); + assert.equal(parseHeader(next).kid, "k2"); + kr.retire("k1"); + assert.equal(Buffer.from(decrypt(kr, record, next)).toString(), "rotate me"); + assert.throws(() => decrypt(kr, record, old), DecryptError); + assert.throws(() => kr.retire("k2"), /current key/); +}); + +test("Argon2id matches golang.org/x/crypto on reduced parameters", () => { + assert.equal(ARGON2_TIME, 3); + assert.equal(ARGON2_MEMORY_KIB, 262144); + assert.equal(ARGON2_PARALLELISM, 1); + const pw = Buffer.alloc(32, 1); + const salt = Buffer.alloc(16, 2); + const got = deriveRootKeyWithParams(pw, salt, { time: 3, memoryKiB: 32, parallelism: 1 }); + assert.equal(Buffer.from(got).toString("hex"), "30e0b44b7e23423b7282859ea36f02825b5828dde3c25f124d59d42d7235e132"); + const horse = deriveRootKeyWithParams("correct horse", Buffer.from("0123456789abcdef"), { + time: 2, + memoryKiB: 64, + parallelism: 1, + }); + assert.equal( + Buffer.from(horse).toString("hex"), + "74fb6b1d311ac0bb4c891f7efd79680245d9f84b72ad8f9bbe61c86e2b9f864d", + ); + assert.throws(() => deriveRootKeyWithParams("x", Buffer.from("short")), /16 bytes/); +}); + +test("HKDF separates purpose and tenant", () => { + const kr = new Keyring("k1", key); + const derived = new Set(); + for (const purpose of ["a", "b"]) { + for (const tenant of ["t1", "t2"]) { + derived.add(Buffer.from(kr.derive("k1", purpose, tenant, 2)).toString("hex")); + } + } + assert.equal(derived.size, 4); +});