104 lines
3.9 KiB
TypeScript
104 lines
3.9 KiB
TypeScript
// R-P5 (P5) — master-key wrapping for the per-tenant DEK (AD-8, pure server-only).
|
|
//
|
|
// A KeyWrapper encrypts ("wraps") and decrypts ("unwraps") a tenant DEK with the
|
|
// APP MASTER KEY. The DEK itself never leaves the DB unwrapped. Swapping the
|
|
// wrapper (e.g. to a self-hosted Vault/OpenBao Transit engine later) re-wraps the
|
|
// DEKs but does NOT require re-encrypting any field ciphertext — that is the whole
|
|
// point of the envelope indirection.
|
|
//
|
|
// Today: EnvKeyWrapper, AES-256-GCM under CRYPTO_SECRET (EXT-06 app master key).
|
|
//
|
|
// Exported via the `@hivegrid/foundation/crypto` SUBPATH only.
|
|
|
|
import { createCipheriv, createDecipheriv, createHash, randomBytes } from "node:crypto";
|
|
|
|
const ALGORITHM = "aes-256-gcm";
|
|
const IV_BYTES = 12;
|
|
|
|
/**
|
|
* Wraps/unwraps a tenant DEK with the app master key. Implementations must be
|
|
* deterministic in their unwrap and authenticated (GCM tag), so a tampered or
|
|
* foreign blob fails closed.
|
|
*/
|
|
export interface KeyWrapper {
|
|
/** Encrypt the plaintext DEK with the master key → opaque blob for storage. */
|
|
wrap(dek: Buffer): Promise<Buffer>;
|
|
/** Decrypt a blob produced by {@link wrap} back into the plaintext DEK. */
|
|
unwrap(blob: Buffer): Promise<Buffer>;
|
|
}
|
|
|
|
/**
|
|
* Master-key wrapper backed by the app secret `CRYPTO_SECRET` (EXT-06). The
|
|
* 256-bit wrapping key is derived as SHA-256(CRYPTO_SECRET) — same derivation as
|
|
* the legacy CryptoApi, so the master secret is a single source of truth. The
|
|
* stored blob is `iv(12) | tag(16) | ciphertext`.
|
|
*
|
|
* The secret is read LAZILY (per call), never at import time, so importing this
|
|
* module has no env requirement and stays test-friendly.
|
|
*/
|
|
export class EnvKeyWrapper implements KeyWrapper {
|
|
private readonly envVar: string;
|
|
|
|
constructor(envVar = "CRYPTO_SECRET") {
|
|
this.envVar = envVar;
|
|
}
|
|
|
|
private masterKey(): Buffer {
|
|
const secret = process.env[this.envVar];
|
|
if (!secret) {
|
|
// Klartext-mappable upstream; here a plain Error is fine (server boot/config).
|
|
throw new Error(`EnvKeyWrapper: ${this.envVar} env variable not set`);
|
|
}
|
|
return createHash("sha256").update(secret).digest();
|
|
}
|
|
|
|
// Bodies are sync but wrapped so EVERY failure (missing secret, auth-tag
|
|
// mismatch on a foreign/tampered blob) surfaces as a REJECTION, matching the
|
|
// async KeyWrapper contract a future network-backed wrapper will satisfy.
|
|
wrap(dek: Buffer): Promise<Buffer> {
|
|
try {
|
|
const iv = randomBytes(IV_BYTES);
|
|
const cipher = createCipheriv(ALGORITHM, this.masterKey(), iv);
|
|
const ciphertext = Buffer.concat([cipher.update(dek), cipher.final()]);
|
|
const tag = cipher.getAuthTag();
|
|
return Promise.resolve(Buffer.concat([iv, tag, ciphertext]));
|
|
} catch (error) {
|
|
return Promise.reject(error instanceof Error ? error : new Error(String(error)));
|
|
}
|
|
}
|
|
|
|
unwrap(blob: Buffer): Promise<Buffer> {
|
|
try {
|
|
if (blob.length < IV_BYTES + 16) {
|
|
throw new Error("EnvKeyWrapper: wrapped DEK blob too short");
|
|
}
|
|
const iv = blob.subarray(0, IV_BYTES);
|
|
const tag = blob.subarray(IV_BYTES, IV_BYTES + 16);
|
|
const ciphertext = blob.subarray(IV_BYTES + 16);
|
|
const decipher = createDecipheriv(ALGORITHM, this.masterKey(), iv);
|
|
decipher.setAuthTag(tag);
|
|
return Promise.resolve(Buffer.concat([decipher.update(ciphertext), decipher.final()]));
|
|
} catch (error) {
|
|
return Promise.reject(error instanceof Error ? error : new Error(String(error)));
|
|
}
|
|
}
|
|
}
|
|
|
|
let defaultWrapper: KeyWrapper | null = null;
|
|
|
|
/**
|
|
* The process-wide default wrapper (EnvKeyWrapper). A future self-hosted-KMS
|
|
* binding swaps this once; callers never construct a wrapper directly.
|
|
*/
|
|
export function getKeyWrapper(): KeyWrapper {
|
|
if (!defaultWrapper) {
|
|
defaultWrapper = new EnvKeyWrapper();
|
|
}
|
|
return defaultWrapper;
|
|
}
|
|
|
|
/** Override the default wrapper (tests, or the future Vault/OpenBao binding). */
|
|
export function setKeyWrapper(wrapper: KeyWrapper | null): void {
|
|
defaultWrapper = wrapper;
|
|
}
|