All files / src/lib pid-fingerprint.ts

100% Statements 14/14
100% Branches 12/12
100% Functions 3/3
100% Lines 11/11

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47                                  6x     127x 127x 121x 121x 119x         65x               62x 62x 56x         56x    
/**
 * The secure hash that links a PID to an account (ADR-067, #708).
 *
 * `HMAC-SHA256(key, given name | family name | birth date)`, prefixed with
 * the key id so a rotation is visible. The hub stores this value on the
 * Keycloak account and nothing else of the PID: the name and the birth date
 * exist only in memory while it is computed. Without the key the value can
 * be neither computed nor checked against a guess; the key lives in Key
 * Vault (`pid-fingerprint-key`), apart from Keycloak.
 *
 * Under the GDPR the value is pseudonymised personal data (Art. 4(5),
 * Recital 26): it recognises one person, but reveals nothing about them.
 */
import { createHmac } from "crypto";
import { normalise, type VerifiedPid } from "@/lib/eudi-patient-map";
 
/** At least 256 bits, base64. Without it the link is switched off. */
const MIN_KEY_BYTES = 32;
 
function key(): { id: string; bytes: Buffer } | null {
  const raw = process.env.PID_FINGERPRINT_KEY;
  if (!raw) return null;
  const bytes = Buffer.from(raw, "base64");
  if (bytes.length < MIN_KEY_BYTES) return null;
  return { id: process.env.PID_FINGERPRINT_KEY_ID || "k1", bytes };
}
 
/** Whether this deployment can link a PID to an account at all. */
export function pidLinkEnabled(): boolean {
  return key() !== null;
}
 
/**
 * The secure hash of a PID, `<key id>:<64 hex>`, or null when the PID lacks
 * a name or a birth date, or the deployment has no key.
 */
export function pidFingerprint(pid: VerifiedPid): string | null {
  const k = key();
  if (!k || !pid.givenName || !pid.familyName || !pid.birthDate) return null;
  const input = [
    normalise(pid.givenName),
    normalise(pid.familyName),
    pid.birthDate.trim(),
  ].join("|");
  return `${k.id}:${createHmac("sha256", k.bytes).update(input).digest("hex")}`;
}