Why this matters
Every merchant who connects Meta, Google, Shopify, or a payment account to this product hands over live credentials that can spend advertising money or read customer orders. If a database backup leaks, a web query has a bug, or a developer prints an error object to logs, those credentials become an instant takeover of every connected shop. You cannot solve that risk with database passwords or disk encryption alone, because a running application reads an encrypted disk in plain text. During Wave 45, a review of the API server caught a real bug that illustrates how unforgiving secret management is: the server read an optional vault master key and quietly fell back to generating a brand-new random key on every restart, which meant every OAuth token stored before a restart became permanently unreadable the second the server rebooted. Cryptography only protects a business when the right primitive is picked for each job, keys stay separated from the data they guard, and failure modes fail closed instead of silently losing or leaking secrets.
The ideas
Cryptography feels complex mostly because five different tools get lumped under one word. Nearly every server-side decision in this repository comes down to picking the right primitive from this table:
| Tool | Key needed? | Reversible? | What it proves | Analogy |
|---|---|---|---|---|
| Hash (SHA-256) | No | No | Exact content fingerprint | Tamper-evident wax seal |
| HMAC (HMAC-SHA-256) | Shared secret | No | Sender and unaltered body | Private family signet |
| Authenticated encryption (AES-256-GCM) | Shared secret | Yes | Secrecy plus tamper detection | Locked steel box with latch |
| Digital signature (ES256, EdDSA) | Private signs, public checks | No | Authorship without sharing secret | Publicly verifiable signature |
| HKDF | Root secret + label | No | Isolated child keys per purpose | Separate door keys from one master |
One-way hashing and why hashing is not anonymisation
A cryptographic hash turns any bytes into a fixed-length digest, 32 bytes (64 hex characters) for SHA-256. It is one-way, and changing a single bit scrambles the whole output (the avalanche effect).
Two practical traps matter immediately:
- Same object, different bytes. In JSON,
{"b":2,"a":1}and{"a":1,"b":2}mean the same thing yet hash to unrelated digests. Whenever two programs must compute the same hash independently, they convert objects to canonical JSON first: sorted keys, fixed spacing, and non-finite numbers refused. - Plain hashes of personal data are not anonymous. Because SHA-256 is fast and unkeyed, an attacker with hashed Turkish mobile numbers or e-mails can run a dictionary attack: hash all 100 million
+905xxxxxxxxxnumbers or a leaked e-mail list in seconds and match them. Under KVKK, hashed identifiers remain personal data.
In plain words
Keyed hashes (HMAC), raw bodies, and constant-time checks
Anyone on the internet can POST fake JSON to a public webhook URL. Plain SHA-256 cannot stop forgery because the attacker can compute SHA-256 on fake payloads too.
An HMAC mixes a shared secret into SHA-256 (RFC 2104) so only someone holding that secret can produce the valid tag. Four rules separate safe HMAC checks from broken ones:
- Verify the raw body. Parsing JSON and calling
JSON.stringifycan shift whitespace or escaping by one byte and break valid webhooks. - Check a timestamp window. Signing
<timestampSec>.<rawBody>and rejecting skew beyond 300 seconds stops attackers from replaying old captured requests. - Use constant-time comparison. Plain
===stops at the first differing byte;crypto.timingSafeEqualchecks every byte in fixed time so timing leaks nothing. - Support dual-key rotation. Accepting both
currentandprevioussecrets during cutover avoids dropping in-flight webhooks.
Authenticated encryption: AES-256-GCM, nonces, tags, and AAD
When the API must later recover a secret, such as an OAuth refresh token to call Meta or Google, hashing fails because it is one-way. You need reversible authenticated encryption.
AES-256-GCM hides plaintext and detects any modification in one step, producing ciphertext, a fresh 12-byte random nonce (IV), and a 16-byte authentication tag. Three rules are non-negotiable:
- Never reuse a nonce under one key. GCM encrypts by applying XOR with a keystream derived from the key and nonce. Reusing a nonce cancels the keystream between two ciphertexts, exposing plaintext differences and enabling forged tags.
- Bind context with additional authenticated data (AAD). Without AAD, an attacker with database write access could perform a ciphertext transplant, copying Workspace A's valid ciphertext into Workspace B's row. Folding
workspaceId:connectionId:provider:kekVersioninto the authentication tag makes transplanted rows fail decryption immediately. - Prevent delimiter injection. Joining AAD parts with colons fails if any part itself contains a colon (
"a:b"+"c"collides with"a"+"b:c"). Validating every segment against a strict colon-free allowlist and prefixing versioned domain separation labels (gd-dek-v1:,oauth:) guarantees distinct contexts never collide.
Public-key signatures and HKDF in brief
Passkey sign-in (covered in L04) uses public-key signatures (ES256, EdDSA) so the user's private key never leaves their device. Stored OAuth tokens use symmetric AES-256-GCM because the server both encrypts and later reads them. Whenever one root secret must yield separate symmetric keys for distinct features, HKDF (RFC 5869) derives independent child keys bound to purpose labels.
Envelope encryption, rotation, sealing, and zeroisation
Encrypting 50,000 OAuth tokens directly with one master key makes master-key rotation slow and per-customer erasure messy. Envelope encryption uses two key layers:
[ Master KEK (32 bytes, process config ONLY, never in PostgreSQL) ]
| wraps / unwraps (AES-256-GCM + AAD "gd-dek-v1:<ws>:<kekVer>")
v
[ Workspace DEK (32 bytes, stored as 63-byte wrapped_dek in vault.workspace_deks) ]
| encrypts / decrypts (AES-256-GCM + AAD "<ws>:<conn>:<provider>:<kekVer>")
v
[ OAuth Tokens / Credentials (ciphertext + 12B IV + 16B auth_tag) ]Each workspace has its own 256-bit data encryption key (DEK). The master key encryption key (KEK) performs only key wrapping on those small 32-byte DEKs. During key rotation, KEK rotation simply rewraps each 32-byte DEK under KEK v2 with zero token ciphertexts re-encrypted, whereas DEK rotation generates a new workspace DEK and re-encrypts only that workspace's rows.
For short-lived standalone items such as pending OAuth states or authenticator secrets, sealing generates a fresh per-item 256-bit DEK, wraps it under the KEK, and packs the wrapped DEK, IV, tag, and ciphertext with strict flow AAD. After any unwrap, zeroisation (buf.fill(0) in finally) wipes mutable key buffers, though JavaScript strings are immutable and remain until garbage collection.
Vault isolation, crypto-shredding, and hash-chained audit logs
Encryption sits behind database isolation: encrypted secrets live inside a separate vault schema reachable only through the vault executor role, while normal screens list connection metadata from a safe view (oauth_connections_safe) with zero crypto columns.
On revocation or tenant erasure, crypto-shredding destroys key material (and overwrites revoked row columns) so live ciphertext can no longer decrypt, optionally recording a PII-free erasure certificate. Meanwhile, the append-only audit log links every row into an audit chain from a 64-zero genesis hash, summarised by an audit chain checkpoint and exportable as an audit bundle for offline verification without trusting the server.
How this repository does it
Every cryptographic mechanism described above maps directly to live files in this repository. Notice the careful status distinctions: the core cryptographic primitives, database schema, triggers, scrubbers, and offline verifiers are built and verified by automated tests, while production key custody, runtime multi-version KEK rotation, and live deployment are not built yet.
| Capability | Live repository files | Verified detail | Status |
|---|---|---|---|
| Envelope encryption & AAD | | AES-256-GCM, 12B random IV, 16B tag, 63B wrapped DEK, SAFE_AAD_SEGMENT_RE, validateKey256, zeroizeBuffer | Verified |
| KEK rewrap & DEK rotation library | | rewrapWorkspaceDek, rotateKekBatch (ciphertextsReencrypted: 0), rotateWorkspaceDek | Verified (library) |
| Crypto-shredding & erasure certificates | | shredTenantDek, buildErasureCertificate (domain-separated SHA-256 commitments, hashed not signed), verifyCryptoShredProof | Verified |
| OAuth standalone sealing | | Fresh 256-bit DEK per blob, [0x01][63B wrapped DEK][12B IV][16B tag][ciphertext], oauth:... AAD | Verified |
| Raw-body HMAC & dual-key rotation | , | <timestampSec>.<rawBody>, 300s skew window, MAX_HMAC_ROTATION_SECRETS = 2, timingSafeEqual | Verified |
| Vault schema, safe view & roles | , | vault.workspace_deks, vault.oauth_connections, vault.sub_merchants, vault.audit_chain_head, oauth_connections_safe, vault_executor | Verified |
| Least-privilege vault runtime config | , | Fails closed in production if VAULT_MASTER_KEK_BASE64 missing/zero; only API and dispatch hold VAULT_DATABASE_URL + KEK | Verified |
| Hash-chained audit log & checkpoint | , , | GENESIS_PREV_HASH_HEX, canonicalJsonStringify, FOR UPDATE lock on vault.audit_chain_head, 16-char checkpoint prefix | Verified |
| Offline audit bundle verifier | , , | Verifies pg_preimage_v1 rows offline in Node.js CLI or browser Web Crypto | Verified |
| Log redaction & secret scanning | , , | FORBIDDEN_SECRET_KEY_SET, value-level detectSecrets, assertNoSecrets, scrubOpaque, Gitleaks rules | Verified |
Inside the 63-byte wrapped DEK
Open and you will see an exact binary layout (packages/vault/src/envelope.tsWRAPPED_DEK_TOTAL_BYTES = 63) that makes key wrapping self-describing and tamper-evident:
Byte offset Length Meaning
0 1 byte Envelope format version (0x01)
1..2 2 bytes kekVersion (unsigned 16-bit big-endian integer)
3..14 12 bytes Random AES-256-GCM IV (nonce)
15..30 16 bytes AES-256-GCM authentication tag
31..62 32 bytes Encrypted 256-bit workspace DEK ciphertextWhen unwrapDek opens that 63-byte buffer, it reads kekVersion from bytes 1–2, looks up that exact master key inside KekKeyring, rebuilds gd-dek-v1:${workspaceId}:${kekVersion} as AAD, and decrypts. If anyone edits byte 2 to claim a different key version, or copies the 63 bytes to another workspace row, the 16-byte tag check fails before a single key byte is returned. Furthermore, validateKey256 explicitly rejects an all-zero 32-byte buffer (WEAK_ZERO_KEY) so a broken configuration script cannot accidentally encrypt production data with zeros.
Process separation and secret hygiene
Notice how least privilege spans both PostgreSQL and operating-system processes:
Web / API process --> holds DATABASE_URL + VAULT_DATABASE_URL + VAULT_MASTER_KEK_BASE64
Dispatch process --> holds DATABASE_URL + VAULT_DATABASE_URL + VAULT_MASTER_KEK_BASE64
General background job --> holds DATABASE_URL ONLY (lint refuses any VAULT_* env var)
SEO crawler worker --> holds ZERO database or vault credentials (enforced at startup)Even inside the API process, redaction works as a second net. maintains both a key allowlist/denylist (packages/vault/src/log-scrubber.tsFORBIDDEN_SECRET_KEY_SET alongside SAFE_SHA256_HASH_KEY_SET so legitimate audit digests do not false-positive) and value-level pattern detectors (detectSecrets) that catch OAuth tokens, JWTs (eyJ...), raw IBANs, tax IDs, and base64/hex keys even when tucked under an innocent field name. Startup configuration failures in throw apps/api/src/platform/runtime-config.tsApiRuntimeConfigError carrying machine-readable error codes only — never echoing back the malformed secret value.
Not built yet
What went wrong once
Real cryptographic failures rarely come from breaking AES-256 mathematically; they come from wiring, lifecycle, and process-boundary mistakes around the cipher. Four real incidents from Waves 45 through 48 show how those bugs happen and how they were fixed.
1. The master key that regenerated on every boot (Wave 45, finding P-2)
During an early review, the API factory initialised the vault key with deps.vaultKek ?? generateKek(), and the production bootstrap never passed deps.vaultKek in. Everything looked green in single-process tests. The moment two API instances ran or one process restarted, however, the new process generated a brand-new ephemeral key and could not decrypt a single OAuth token stored minutes earlier.
Fix: now loads apps/api/src/platform/runtime-config.tsVAULT_MASTER_KEK_BASE64, verifies it decodes to exactly 32 non-zero bytes, and refuses to boot in production if it is missing or malformed. Outside production, an ephemeral fallback remains allowed for local convenience, but logs an explicit api.vault_kek_ephemeral warning so no developer mistakes it for durable storage.
2. Connections stored in memory, and what deleting a token really requires (Wave 47, finding P-10)
While tracing the vault key fix, a reviewer discovered that POST /connections encrypted incoming OAuth tokens properly and then saved the encrypted row inside an in-memory JavaScript Map even when PostgreSQL was configured. Restarting the server wiped every connection, and there was no real revoke path.
When Wave 47 wired persistence into vault.oauth_connections over the separate vault database pool (failing closed with 503 VAULT_STORE_NOT_CONFIGURED before spending a single-use step-up token if the vault pool or KEK is missing), the implementing engineer caught a subtle crypto-shredding trap on revoke. Because every connection inside a workspace shares that workspace's DEK, overwriting only a revoked connection row's wrapped_dek column would leave its ciphertext still decryptable with the active workspace DEK.
Fix: Revocation now calls the upstream provider and always overwrites all four cryptographic columns (wrapped_dek, ciphertext, iv, auth_tag), verified by a mutation check that confirms skipping ciphertext causes the revoke test to fail. The engineering report also states the honest database boundary: overwriting live columns destroys the live copy only; PostgreSQL MVCC retains old row versions on disk until VACUUM runs, and older database backups retain whatever ciphertext and wrapped keys were present when the backup was taken until those backups expire.
3. Sample workspaces whose placeholder DEKs refused real connections (Wave 47)
Static SQL seed files for local demo workspaces cannot wrap a workspace DEK under a master key that only exists at runtime, so the seed inserted opaque placeholder bytes into vault.workspace_deks. When developers tried connecting a real test account to a seeded workspace, the vault rejected the row as corrupted (503 VAULT_WORKSPACE_KEY_UNAVAILABLE).
Fix: First, the team locked down an unbreakable safety rule: the API must never silently overwrite an undecryptable workspace DEK, because silently generating a replacement key when a real KEK is merely misconfigured would permanently orphan every existing connection in that workspace. Only a narrow local dev-stack bootstrap path performs a strict compare-and-set matching the exact known seed placeholder bytes, guaranteeing a real workspace key is never overwritten.
4. Moving OAuth token refresh out of the general worker (Wave 48)
OAuth access tokens expire and must be refreshed in the background, which requires both VAULT_DATABASE_URL and VAULT_MASTER_KEK_BASE64. An initial draft placed token refresh inside the general background worker — and immediately collided with a deployment lint test that deliberately forbids any VAULT_* environment variable in the general worker unit.
Rather than relaxing the security rule to give a broad worker access to every customer's vault keys, Wave 48 moved token refresh into a tiny dedicated process, , running under its own dedicated operating-system user so the general worker cannot even read its environment file. The lesson is foundational: when a job needs a secret, move the job to the smallest process allowed to hold that secret; never widen the secret boundary to match a convenient process.apps/api/src/dispatch-main.ts
Try it yourself
Every step below is read-only and safe to run from the repository root in PowerShell or Git Bash. None of these commands touch ports 3000, 4000, or 5432, require PostgreSQL, or contact any external provider.
Step 1: See SHA-256 avalanche and why canonical JSON matters
Run this short Node.js one-liner to compare two objects with identical keys in different orders and watch one changed character scramble a SHA-256 digest:
node -e "const c=require('node:crypto'); const h=(s)=>c.createHash('sha256').update(s).digest('hex'); console.log('a-first:', h('{\"a\":1,\"b\":2}')); console.log('b-first:', h('{\"b\":2,\"a\":1}')); console.log('1-bit: ', h('{\"a\":1,\"b\":3}'));"Notice that a-first and b-first produce completely unrelated 64-character hex hashes even though they mean the same thing. That is why sorts keys before hashing.packages/approvals/src/canonical-hash.ts
Step 2: Run the vault envelope, rotation, and log-scrubber test suite
Execute the self-contained vault unit tests to watch AES-256-GCM round-trips, 1-byte tamper rejection, cross-workspace AAD swap blocking, zero-reencryption KEK rotation, and secret-scrubber assertions run live:
node --test packages/vault/test/vault.test.mjsLook for suites 3, 4, and 5 in the output: suite 3 flips single bytes in ciphertext, IV, tag, and AAD; suite 4 rotates KEK v1 to v2 with zero ciphertexts re-encrypted; and suite 5 checks that tokens, base64 keys, IBANs, and tax numbers never escape into logs or oauth_connections_safe.
Step 3: Run the crypto-shredding and offline audit-bundle verifier tests
Verify that destroying a workspace DEK renders its ciphertexts unreadable, erasure certificates detect tampering, and offline audit bundle verification catches modified or missing rows:
node --test packages/vault/test/crypto-shred.test.mjs packages/vault/test/audit-bundle-verifier.test.mjsBoth suites run purely in memory with zero database setup and prove the mathematical checks behind and tools/verify-audit-bundle.mjs.apps/web/src/app/trust/bundle-verify-browser.ts
Step 4: Inspect the 63-byte wrapped DEK layout and startup KEK validation
Open and find packages/vault/src/envelope.tsWRAPPED_DEK_TOTAL_BYTES, SAFE_AAD_SEGMENT_RE, and validateKey256, then open and find apps/api/src/platform/runtime-config.tsVAULT_MASTER_KEK_BASE64. Trace how the runtime refuses all-zero keys and missing production keys without ever printing the secret value in the thrown error.
Check yourself
0 / 7Why is hashing customer e-mails with plain SHA-256 not enough to call a dataset anonymous?
Why must webhook HMAC checks run on the raw HTTP body instead of JSON.stringify(req.body)?
What attack does binding workspaceId:connectionId:provider:kekVersion as AAD in AES-256-GCM stop?
Why does rotating the master KEK under envelope encryption avoid re-encrypting stored OAuth tokens?
On per-connection revoke in Wave 47, why was wiping only wrapped_dek insufficient?
Why did Wave 48 move OAuth token refresh to apps/api/src/dispatch-main.ts instead of giving the general worker the vault key?
Why does an exported audit bundle support offline verification?
Words to know
36Go deeper
ADR 0004: Zero-password vault and FORCE RLS— design decision behind the isolatedvaultschema, envelope encryption, andoauth_connections_safe.ADR 0005: Expiring SHA-256 approval ledger— how canonical JSON hashing binds approval previews to executed actions.Threat model— specifically assets A1–A2, threat T2 (vault credential theft), and gate G2.Archived lesson 14: Cryptography, vault DEK/KEK and audit chains— earlier wave notes replaced by this lesson.Archived lesson 26: Audit retention and assurance— earlier notes on audit retention and bundle verification.Archived lesson 31: Audit chain checkpoints— earlier notes on workspace audit checkpoints.- NIST SP 800-38D: Recommendation for Galois/Counter Mode (GCM) — authoritative standard on AES-GCM nonces, tags, and AAD.
- NIST FIPS 180-4: Secure Hash Standard (SHA-256) — official specification of SHA-256.
- RFC 2104: HMAC — Keyed-Hashing for Message Authentication — why HMAC uses a two-pass keyed hash construction.
- RFC 5869: HKDF — HMAC-based Key Derivation Function — deriving domain-separated keys safely.
- RFC 8785: JSON Canonicalization Scheme (JCS) — deterministic JSON serialisation for cryptographic hashing.
- Node.js
node:cryptodocumentation — official reference forcreateCipheriv,createHmac,timingSafeEqual, andrandomBytes. - MDN Web Crypto API — browser-native
crypto.subtleused by the offline audit verifier.