Encryption Integration Guide

Technology: encryption · Category: tooling · Last reviewed: 2026-10-20

Source: https://tech-stack.codeamanilabs.org/guide/encryption

Insight:

Encryption is not one primitive but four categories, and the fatal mistake is reaching for the wrong one — hashing data you must read back, or "encrypting" a password you should never recover. Get the category right first (AES-256-GCM for data you decrypt, Argon2id for passwords you never can, HPKE or a libsodium sealed box to encrypt to a public key, envelope encryption with a real KMS for keys at scale), then let an audited library do the math. Two things moved in 2026: Node 24 LTS ships ML-KEM, Argon2 and ChaCha20-Poly1305 in core crypto (OpenSSL 3.5), so post-quantum hybrid HPKE runs today; and "Vercel KMS" is a signing service, not an encryption KMS — envelope encryption still means AWS or GCP KMS reached through Vercel OIDC. For codeAmani the load-bearing case is field-level AES-256-GCM over DoseVault PHI and all customer PII, so the database only ever holds ciphertext, plus masking and blind indexes in every log and lookup.

███████╗███╗   ██╗ ██████╗██████╗ ██╗   ██╗██████╗ ████████╗██╗ ██████╗ ███╗   ██╗
██╔════╝████╗  ██║██╔════╝██╔══██╗╚██╗ ██╔╝██╔══██╗╚══██╔══╝██║██╔═══██╗████╗  ██║
█████╗  ██╔██╗ ██║██║     ██████╔╝ ╚████╔╝ ██████╔╝   ██║   ██║██║   ██║██╔██╗ ██║
██╔══╝  ██║╚██╗██║██║     ██╔══██╗  ╚██╔╝  ██╔═══╝    ██║   ██║██║   ██║██║╚██╗██║
███████╗██║ ╚████║╚██████╗██║  ██║   ██║   ██║        ██║   ██║╚██████╔╝██║ ╚████║
╚══════╝╚═╝  ╚═══╝ ╚═════╝╚═╝  ╚═╝   ╚═╝   ╚═╝        ╚═╝   ╚═╝ ╚═════╝ ╚═╝  ╚═══╝

Encryption Integration Guide

Focus: pick the right primitive for the job and let an audited library do the math. Symmetric (AES-256-GCM) for data you can decrypt, hashing (Argon2id) for passwords you never can, HPKE or sealed boxes for "encrypt to a public key", and envelope encryption with a KMS for keys at scale. For codeAmani the load-bearing case is protecting PHI (DoseVault, HIPAA) and customer PII — field-level encryption, masking and blind indexes on top of these primitives.

Overview

Encryption is not one thing. The most common mistake is reaching for the wrong tool: hashing a value you need to read back later, "encrypting" a password you should never be able to recover, or hand-rolling AES with a static IV. Get the category right first; the implementation is then almost mechanical.

Four categories cover almost everything you'll touch:

  1. Symmetric encryption — one secret key encrypts and decrypts. Fast, used for bulk data. Default: AES-256-GCM (or ChaCha20-Poly1305 / XChaCha20-Poly1305). Reversible.
  2. Asymmetric (public-key) encryption — a public key encrypts, a separate private key decrypts. OWASP now recommends a hybrid public-key encryption scheme — HPKE (RFC 9180) — rather than raw RSA or a hand-built ECDH+AES combination. libsodium sealed boxes remain a fine, simple choice.
  3. Hashing — a one-way function. Not encryption: no key, no way back. Argon2id for passwords, SHA-256 for integrity, HMAC-SHA-256 when a secret key is involved.
  4. E2EE — end-to-end: only the endpoints hold keys; the server relays ciphertext it cannot read. Built from the above.

Layered on where the data lives: in transit (TLS — the platform's job, you just enforce HTTPS) vs at rest (provider disk encryption is on by default; field-level encryption and key management are your job).

Golden rule, straight from OWASP: don't roll your own crypto. Use Node's node:crypto / Web Crypto (built in), libsodium, @noble/*, hpke, jose or Google Tink.

What changed in 2026 (read this if you used an older version of this guide)

Was Now (verified 2026-10-20)
"Web Crypto in Node 20+" Node 20 is EOL (2026-04-30); Vercel deprecated it on 2026-10-01. Target Node 24 LTS "Krypton" (Vercel default; maintenance LTS from 2026-10-20) or 22 "Jod". Node 26 becomes LTS on 2026-10-28.
Argon2 needs the native argon2 addon Node 24.7+ has crypto.argon2() / argon2Sync() built in (and Web Crypto Argon2id under "Modern Algorithms"). It's a raw KDF — keep the argon2 package for PHC-string password storage.
Post-quantum is a "watch" item Node 24.7+ (OpenSSL 3.5) ships ML-KEM-512/768/1024 (crypto.encapsulate / decapsulate), ML-DSA and SLH-DSA keys. hpke@1.1.7 runs MLKEM768-X25519 hybrid HPKE on Node today.
"Encrypt to a public key: X25519 / RSA-OAEP" OWASP Cryptographic Storage now says: use HPKE; X25519 is key agreement, not encryption on its own.
"KMS: AWS, GCP, Cloudflare, Vercel" Vercel KMS (Beta) only signs JWTs/messages (RS/PS/ES keys); it has no encrypt/decrypt. Envelope encryption = AWS KMS or GCP Cloud KMS, authenticated from Vercel with OIDC federation.
Supabase pgsodium for column encryption Supabase marks pgsodium pending deprecation and recommends against its Transparent Column Encryption; use Supabase Vault for DB-side secrets and app-layer encryption for PHI.
@noble/ciphers 2.3 2.4.0 (ESM-only, .js subpath imports).

Official Documentation

Source URL What it covers
Node.js 24 crypto https://nodejs.org/docs/latest-v24.x/api/crypto.html createCipheriv GCM/ChaCha20-Poly1305, argon2, encapsulate/decapsulate, ML-KEM/ML-DSA keys, hkdf, timingSafeEqual
Node.js 24 Web Crypto https://nodejs.org/docs/latest-v24.x/api/webcrypto.html crypto.subtle; "Modern Algorithms" (ML-KEM, ML-DSA, Argon2, ChaCha20-Poly1305, AES-OCB) — Stability 1.1
MDN — SubtleCrypto.encrypt https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto/encrypt AES-GCM in browsers/Edge, IV rules
OWASP Cryptographic Storage https://cheatsheetseries.owasp.org/cheatsheets/Cryptographic_Storage_Cheat_Sheet.html Algorithms, modes, HPKE, envelope encryption, key separation
OWASP Password Storage https://cheatsheetseries.owasp.org/cheatsheets/Password_Storage_Cheat_Sheet.html Argon2id / scrypt / bcrypt / PBKDF2 parameters, peppering
OWASP Post-Quantum Cryptography https://cheatsheetseries.owasp.org/cheatsheets/Post_Quantum_Cryptography_Cheat_Sheet.html ML-KEM, hybrid TLS (X25519MLKEM768), ML-DSA migration
NIST FIPS 203 / 204 / 205 https://csrc.nist.gov/pubs/fips/203/final ML-KEM, ML-DSA, SLH-DSA (final, Aug 2024)
libsodium sealed boxes https://doc.libsodium.org/public-key_cryptography/sealed_boxes Anonymous public-key encryption
hpke (panva) https://github.com/panva/hpke RFC 9180 HPKE incl. ML-KEM and hybrid KEMs
AWS KMS https://docs.aws.amazon.com/kms/latest/developerguide/overview.html GenerateDataKey, Decrypt, encryption context
Google Cloud KMS envelope encryption https://cloud.google.com/kms/docs/envelope-encryption DEK/KEK model, encrypt/decrypt
Vercel KMS https://vercel.com/docs/kms Managed signing keys (Beta)

The taxonomy at a glance

Category Reversible? Key model Reach for codeAmani example
Symmetric Yes one shared key AES-256-GCM Encrypt a PHI column at rest
Public-key Yes public + private HPKE (RFC 9180), libsodium sealed box Encrypt to a clinician's device key
Hashing No none (HMAC: secret key) Argon2id (passwords), SHA-256 (integrity), HMAC-SHA-256 (blind index, webhooks) Store a PIN; look up a patient by phone
E2EE Yes (endpoints only) per-party keys HPKE / sealed box / libsignal Patient-to-clinician message

Encryption vs hashing — never blur them: encryption is reversible with the key; hashing is one-way with no key. Passwords get hashed; values you must display later get encrypted. "Decrypt the password to email it to the user" is a design bug.


Runtime matrix (what runs where)

Primitive Node 22 LTS Node 24 LTS (Vercel default) Edge / Workers / browser
AES-256-GCM node:crypto + crypto.subtle same crypto.subtle
ChaCha20-Poly1305 node:crypto node:crypto + crypto.subtle (Modern Algos) @noble/ciphers
Argon2id npm argon2 (native addon) npm argon2, or built-in crypto.argon2() (v24.7+) not for password storage — hash on a Node function
ML-KEM / ML-DSA / SLH-DSA no node:crypto (v24.7+, OpenSSL 3.5) @noble/post-quantum
HPKE hpke (classic KEMs) hpke incl. KEM_MLKEM768_X25519 hpke (classic KEMs; Workers: no ML-KEM per its matrix)
Sealed box libsodium-wrappers same same (WASM)

Check the OpenSSL your function actually runs with process.versions.openssl (Node 24.22.0 bundles 3.5.8).


Symmetric: AES-256-GCM

AES-256-GCM is OWASP's preferred default (GCM/CCM first preference). It is authenticated — tampering, a wrong key, or wrong AAD makes decryption throw.

Non-negotiable rules:

Node runtime (examples/aead.ts, wire format v1.iv.tag.ct, base64url):

import { createCipheriv, randomBytes } from "node:crypto";

export function encrypt(plaintext: string, key: Buffer, aad?: Buffer): string {
  const iv = randomBytes(12);
  const cipher = createCipheriv("aes-256-gcm", key, iv, { authTagLength: 16 });
  if (aad) cipher.setAAD(aad);
  const ct = Buffer.concat([cipher.update(plaintext, "utf8"), cipher.final()]);
  const tag = cipher.getAuthTag(); // only valid AFTER final()
  return ["v1", iv.toString("base64url"), tag.toString("base64url"), ct.toString("base64url")].join(".");
}

Edge / Workers / browser — Web Crypto (examples/webcrypto-aes-gcm.ts):

// lib/crypto/aes-gcm.ts — AES-256-GCM via Web Crypto (Node 22+/24 LTS, Edge, Workers, browser).
const IV_BYTES = 12; // GCM standard; MUST be unique per message under one key

const b64 = (u: Uint8Array): string => btoa(String.fromCharCode(...u));
const unb64 = (s: string): Uint8Array<ArrayBuffer> => Uint8Array.from(atob(s), (c) => c.charCodeAt(0));

/** Import a 32-byte (256-bit) raw key as a non-extractable AES-GCM CryptoKey. */
export async function importKey(raw: Uint8Array<ArrayBuffer>): Promise<CryptoKey> {
  if (raw.byteLength !== 32) throw new Error("AES-256 key must be 32 bytes");
  return crypto.subtle.importKey("raw", raw, { name: "AES-GCM" }, false, ["encrypt", "decrypt"]);
}

/** Encrypt UTF-8 text → { iv, ciphertext } (base64). The 16-byte GCM tag is appended to ciphertext. */
export async function encrypt(plaintext: string, key: CryptoKey, aad?: Uint8Array<ArrayBuffer>) {
  const iv = crypto.getRandomValues(new Uint8Array(IV_BYTES)); // fresh every call
  const params: AesGcmParams = aad ? { name: "AES-GCM", iv, additionalData: aad } : { name: "AES-GCM", iv };
  const ct = await crypto.subtle.encrypt(params, key, new TextEncoder().encode(plaintext));
  return { iv: b64(iv), ciphertext: b64(new Uint8Array(ct)) };
}

/** Decrypt; rejects (OperationError) if the tag fails — tampered data, wrong key or wrong AAD. */
export async function decrypt(
  payload: { iv: string; ciphertext: string },
  key: CryptoKey,
  aad?: Uint8Array<ArrayBuffer>,
): Promise<string> {
  const iv = unb64(payload.iv);
  const params: AesGcmParams = aad ? { name: "AES-GCM", iv, additionalData: aad } : { name: "AES-GCM", iv };
  const pt = await crypto.subtle.decrypt(params, key, unb64(payload.ciphertext));
  return new TextDecoder().decode(pt);
}

AAD binds context. Pass table:rowId as AAD so a ciphertext copied to another row fails to decrypt. Cheap, strong defence against ciphertext swapping.

TypeScript ≥ 5.7 note: Web Crypto's BufferSource now wants Uint8Array<ArrayBuffer>; a bare Uint8Array (which may be backed by SharedArrayBuffer) is a type error under --strict. The snippet above is typed accordingly (checked with TS 5.9.3 and 7.0.2).


HPKE (RFC 9180) combines a KEM, a KDF and an AEAD into one vetted construction — OWASP's current recommendation. The zero-dependency hpke package (by panva, the jose author) runs on Node, Deno, Bun, Workers and browsers, and on Node 24 supports the post-quantum hybrid KEM_MLKEM768_X25519. Base mode doesn't authenticate the sender; use an auth/PSK mode if you need that.

// examples/hpke-pq.mts — hpke@1.1.7, Node 24 LTS (verified running on Node 24.15.0)
import * as HPKE from "hpke";

const suite = new HPKE.CipherSuite(HPKE.KEM_MLKEM768_X25519, HPKE.KDF_HKDF_SHA256, HPKE.AEAD_AES_256_GCM);

const recipient = await suite.GenerateKeyPair();
const publicKeyBytes = await suite.SerializePublicKey(recipient.publicKey); // publish these

const info = new TextEncoder().encode("codeamani/dosevault/message/v1");
const pub = await suite.DeserializePublicKey(publicKeyBytes);
const { encapsulatedSecret, ciphertext } = await suite.Seal(pub, new TextEncoder().encode("BP 120/80"), { info });

const plaintext = await suite.Open(recipient, encapsulatedSecret, ciphertext, { info });

The full example falls back to KEM_DHKEM_X25519_HKDF_SHA256 where ML-KEM isn't available (browsers, Workers). Store encapsulatedSecret (1,120 bytes for the hybrid KEM) next to the ciphertext.

libsodium sealed boxes (X25519 + XSalsa20-Poly1305) are still a simple, safe "encrypt to a public key" — anonymous sender, classical only:

// lib/crypto/sealed-box.ts — anonymous public-key encryption with libsodium (libsodium-wrappers 0.8.4)
import sodium from "libsodium-wrappers";

/** Recipient generates a keypair once; publishes publicKey, keeps privateKey secret. */
export async function newKeypair() {
  await sodium.ready;
  const { publicKey, privateKey } = sodium.crypto_box_keypair();
  return { publicKey, privateKey }; // Uint8Array, 32 bytes each (X25519)
}

/** Anyone with the recipient's public key can seal a message to them. */
export async function seal(message: string, recipientPublicKey: Uint8Array): Promise<Uint8Array> {
  await sodium.ready;
  // ephemeral keypair is generated + erased internally; sender stays anonymous
  return sodium.crypto_box_seal(sodium.from_string(message), recipientPublicKey);
}

/** Only the recipient (holding both keys) can open it; throws on tampering. */
export async function open(
  sealed: Uint8Array,
  recipientPublicKey: Uint8Array,
  recipientPrivateKey: Uint8Array,
): Promise<string> {
  await sodium.ready;
  const opened = sodium.crypto_box_seal_open(sealed, recipientPublicKey, recipientPrivateKey);
  return sodium.to_string(opened);
}

Always await sodium.ready before any sodium.* call (WASM loads async). libsodium-wrappers 0.8.x ships its own types — don't install @types/libsodium-wrappers (now a deprecated stub).

RSA only for interop: RSA-OAEP, ≥ 2048-bit keys; never PKCS#1 v1.5 encryption.


Post-quantum: what to do now

Raw ML-KEM in Node 24.7+ (examples/ml-kem-node.mts) — it only agrees a 32-byte secret; derive an AES key with HKDF:

import { decapsulate, encapsulate, generateKeyPairSync, hkdfSync } from "node:crypto";

const { publicKey, privateKey } = generateKeyPairSync("ml-kem-768");
const { sharedKey, ciphertext } = encapsulate(publicKey);            // sender
const recovered = decapsulate(privateKey, ciphertext);                // recipient
const aesKey = Buffer.from(hkdfSync("sha256", recovered, Buffer.alloc(0), "app/v1/aes-256-gcm", 32));

Hashing: passwords and integrity (not encryption)

// lib/crypto/password.ts — server-side ONLY (argon2@0.45.1, native N-API addon)
import * as argon2 from "argon2";

const ARGON2_OPTIONS = { type: argon2.argon2id, memoryCost: 19456, timeCost: 2, parallelism: 1 } as const;

export const hashPassword = (plain: string) => argon2.hash(plain, ARGON2_OPTIONS); // PHC string, 16-byte random salt
export const verifyPassword = (hash: string, plain: string) => argon2.verify(hash, plain); // false on mismatch, throws on bad hash
export const needsRehash = (hash: string) => argon2.needsRehash(hash, ARGON2_OPTIONS); // pass the SAME options

Node 24.7+ built-in crypto.argon2() returns raw key bytes (no PHC string, no needsRehash). Use it to derive a key from a passphrase (examples/node-argon2-kdf.mts); keep the argon2 package for password storage. argon2@1.0.0-alpha.1 sits on the next tag — don't adopt until it's latest.

With Clerk as the auth provider we don't store passwords at all. Hash yourself only for systems Clerk doesn't cover.


In transit vs at rest

In transit At rest (disk) At rest (field-level)
Threat Eavesdropper / MITM Stolen disk / backup Leaked dump, SQL injection, over-broad RLS, curious operator
Mechanism TLS 1.2+/1.3 Provider AES-256 App-layer AES-256-GCM + envelope keys
Who Platform (Vercel, Cloudflare, Neon/Supabase enforce TLS) Provider, on by default You

Envelope encryption & KMS

You don't encrypt millions of rows with one key in an env var. Envelope encryption (OWASP):

flowchart LR
    PT["Plaintext PHI"] -->|"AES-256-GCM"| CT["Ciphertext"]
    DEK["Data key (DEK)"] -->|encrypts| CT
    KMS["AWS / GCP KMS holds KEK"] -->|"wraps DEK"| WDEK["Wrapped DEK"]
    CT --> DB[("Database row")]
    WDEK --> DB
    OIDC["Vercel OIDC token"] -.->|"federated, no static keys"| KMS

Which KMS

KMS Envelope encryption? Pricing (verified 2026-10-20) Notes
AWS KMS Yes — GenerateDataKey + Decrypt $1/key/month (rotations add $1 for the first two, then capped); symmetric requests $0.03 per 10,000; free tier 20,000 requests/month (asymmetric excluded) EncryptionContext = AAD, logged in CloudTrail. ML-DSA signing keys GA.
GCP Cloud KMS Yes — generate DEK locally, wrap with encrypt Software key version $0.06/month, HSM $1.00/month; crypto ops $0.03 per 10,000 (some HSM ops $0.15) additionalAuthenticatedData = AAD. ML-KEM-768/1024 supported.
Vercel KMS (Beta) No — signing only (RS*/PS*/ES*, default RS512; no HS*) Beta, all plans; no price published @vercel/kms signJWT / signMessage; JWKS at https://kms.vercel.com/<issuerId>/jwks.json. FIPS 140-3 L1 OpenSSL provider. Use it to sign tokens without a private key in env — not to encrypt data.

AWS KMS from a Vercel Function (OIDC, no long-lived AWS keys)

Non-secret configuration (put these in Vercel project settings as plain env, not secrets):

Setting Example Secret?
AWS_REGION us-east-1 No
AWS_ROLE_ARN arn:aws:iam::<account>:role/<app>-kms No
KMS_KEY_ID alias/dosevault-phi No
// examples/envelope-aws-kms.ts (excerpt) — @aws-sdk/client-kms 3.1153.0 + @vercel/oidc-aws-credentials-provider 3.3.13
import { DecryptCommand, GenerateDataKeyCommand, KMSClient } from "@aws-sdk/client-kms";
import { awsCredentialsProvider } from "@vercel/oidc-aws-credentials-provider";
import { encrypt } from "./aead.js";

const kms = new KMSClient({
  region: process.env.AWS_REGION,
  credentials: awsCredentialsProvider({ roleArn: process.env.AWS_ROLE_ARN ?? "" }),
});

export async function sealField(plaintext: string, ctx: { table: string; rowId: string }) {
  const { Plaintext, CiphertextBlob } = await kms.send(
    new GenerateDataKeyCommand({ KeyId: process.env.KMS_KEY_ID, KeySpec: "AES_256", EncryptionContext: ctx }),
  );
  if (!Plaintext || !CiphertextBlob) throw new Error("KMS returned no data key");
  const dek = Buffer.from(Plaintext);
  try {
    return {
      wrappedDek: Buffer.from(CiphertextBlob).toString("base64"),
      payload: encrypt(plaintext, dek, Buffer.from(`${ctx.table}:${ctx.rowId}`)),
    };
  } finally {
    dek.fill(0); // drop the plaintext DEK
  }
}
// openField(): DecryptCommand({ KeyId, CiphertextBlob, EncryptionContext: ctx }) → decrypt(payload, dek, aad)

GCP equivalent: examples/envelope-gcp-kms.ts (KeyManagementServiceClient.encrypt/decrypt with additionalAuthenticatedData). For very high volume, cache DEKs briefly or use the AWS Encryption SDK (@aws-crypto/client-node 5.0.2) with its caching materials manager — KMS calls cost money and add latency.

Rotation triggers (OWASP): suspected compromise, end of cryptoperiod, or usage limits (e.g. AES-GCM random-IV message count). Turn on automatic KEK rotation in AWS/GCP.


PII / PHI: field-level encryption, masking, blind indexes, tokenization

DoseVault handles PHI under HIPAA; every codeAmani product handles customer PII (US-first; KDPA 2019 also applies to Kenya-targeted projects). Disk encryption alone isn't enough.

1. Field-level (application-layer) encryption

Encrypt sensitive columns before they reach Postgres; decrypt in the app. The DB only ever sees ciphertext.

// Storing a PHI field — envelope-encrypt at the app boundary, store only ciphertext columns.
import { sealField } from "./envelope-aws-kms.js";
import { blindIndex } from "./mask.js";

interface RecordsTable {
  insert(row: {
    id: string;
    patient_phone_bidx: string; // blind index for lookups — never the phone itself
    diagnosis_dek: string;      // wrapped DEK (KMS CiphertextBlob, base64)
    diagnosis_ct: string;       // "v1.iv.tag.ct"
  }): Promise<void>;
}

export async function storeDiagnosis(
  db: RecordsTable,
  rec: { id: string; phone: string; diagnosis: string },
  bidxKey: Buffer,
): Promise<void> {
  const { wrappedDek, payload } = await sealField(rec.diagnosis, { table: "records", rowId: rec.id });
  await db.insert({
    id: rec.id,
    patient_phone_bidx: blindIndex(rec.phone, bidxKey),
    diagnosis_dek: wrappedDek,
    diagnosis_ct: payload,
  });
}

2. Blind indexes (search without plaintext)

Encrypted columns can't be WHEREd. Store a keyed HMAC-SHA-256 of the normalised value next to it and query on that. Use a separate HMAC key from the encryption key. Leaks equality (same input → same index), so only index what you must look up.

3. Masking (display / logs)

// Mask an M-Pesa phone (always 254XXXXXXXXX) and an ID for UI / logs
export const maskPhone = (p: string): string => p.replace(/^(\d{3})\d{6}(\d{3})$/, "$1******$2"); // 254******149
export const maskId = (id: string): string => (id.length <= 4 ? "****" : "****" + id.slice(-4));

// Blind index: deterministic, keyed lookup token for an encrypted column (e.g. find a
// patient by phone without storing the phone in plaintext). HMAC key ≠ encryption key.
import { createHmac } from "node:crypto";
export const blindIndex = (value: string, hmacKey: Buffer): string =>
  createHmac("sha256", hmacKey).update(value.normalize("NFKC").toLowerCase()).digest("base64url");

Never log raw PII/PHI. Mask emails, phone numbers, patient ids — and, on Kenya-targeted projects, M-Pesa phones and CheckoutRequestIDs — before they reach Sentry or logs. Structured logging only.

4. Tokenization

Replace a sensitive value with a meaningless token; keep the real value in one locked-down vault. For card data, Stripe already tokenizes — never store PANs; that keeps us out of most PCI DSS scope.

flowchart LR
    U["Patient submits PHI"] -->|TLS in transit| API["API route (Node runtime)"]
    API -->|"AES-256-GCM + KMS-wrapped DEK"| ENC["Encrypt PHI columns"]
    ENC --> DB[("DB: ciphertext + blind index")]
    API -->|"mask for logs"| LOG["Sentry / logs see masked only"]
    DB -->|"decrypt in app on read"| VIEW["Authorised clinician view"]

Tokens and cookies: jose

For an encrypted, tamper-proof token or cookie, don't invent a format — use JWE via jose@6.2.13 (dir + A256GCM). For signed tokens issued from Vercel without holding a private key, Vercel KMS signJWT is the managed option.

import { CompactEncrypt, compactDecrypt } from "jose";

const key = crypto.getRandomValues(new Uint8Array(32)); // in prod: 32 bytes from env/KMS
const jwe = await new CompactEncrypt(new TextEncoder().encode(JSON.stringify({ sub: "user_123" })))
  .setProtectedHeader({ alg: "dir", enc: "A256GCM" })
  .encrypt(key);
const { plaintext } = await compactDecrypt(jwe, key);

Secrets

Only real secrets go in the vault. Generate each with a CSPRNG (openssl rand -base64 32) per environment, store in Vercel env (Sensitive) / the codeAmani secrets vault, never in the repo:

ENCRYPTION_KEY_B64=base64-32-random-bytes-placeholder
BLIND_INDEX_KEY_B64=base64-32-random-bytes-placeholder

With envelope encryption in production, ENCRYPTION_KEY_B64 is only a dev/local fallback; the KEK lives in KMS and needs no env secret (OIDC federation).


E2EE in one paragraph

End-to-end encryption means the server only ever holds ciphertext. For one-shot messages, HPKE (or a sealed box) is genuine E2EE: encrypt client-side to the recipient's public key, store opaque bytes, only the recipient's private key opens it. For live conversations, Signal's double ratchet adds forward secrecy and post-compromise security — don't implement it yourself; use libsignal or a vetted SDK. Key distribution and device verification are the hard part, not the cipher.


Security checklist


codeAmani notes

Official docs: