All files / src/lib/patient member-reference.ts

100% Statements 16/16
100% Branches 4/4
100% Functions 1/1
100% Lines 15/15

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                                  4x 4x     13x     13x 13x 13x 13x 104x 104x 104x 156x 156x   104x 104x   13x    
import { createHash } from "node:crypto";
 
/**
 * The reference a bonus program's answer is tied to (#934 step 8, ADR-091).
 *
 * The hub sends an insurer neither a name nor an insurance number. Each
 * consent to a program has a reference instead: the member reads it here and
 * gives it to the insurer, and the answer the insurer collects carries the
 * same one. It is derived from the consent id, so a new join after a
 * withdrawal has a new reference, and nothing is stored for it.
 *
 * The neo4j-proxy sends what this computes:
 * services/neo4j-proxy/src/member-reference.ts is the second copy, and both
 * run services/neo4j-proxy/__tests__/fixtures/member-reference-vectors.json.
 */
 
/** Crockford base32: no I, L, O or U, so a reference survives being read out. */
const ALPHABET = "0123456789ABCDEFGHJKMNPQRSTVWXYZ";
const LENGTH = 12;
 
export function memberReference(consentId: string): string {
  const digest = createHash("sha256")
    .update(`mvhd:programme-reference:${consentId}`)
    .digest();
  let out = "";
  let acc = 0;
  let bits = 0;
  for (const byte of digest) {
    acc = (acc << 8) | byte;
    bits += 8;
    while (bits >= 5 && out.length < LENGTH) {
      out += ALPHABET[(acc >>> (bits - 5)) & 31];
      bits -= 5;
    }
    acc &= (1 << bits) - 1;
    if (out.length === LENGTH) break;
  }
  return `${out.slice(0, 4)}-${out.slice(4, 8)}-${out.slice(8)}`;
}