All files / src/lib proxy.ts

100% Statements 10/10
100% Branches 10/10
100% Functions 3/3
100% Lines 9/9

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                29x   29x                 30x 30x         91x 91x                     70x 70x 68x              
import { createHash } from "node:crypto";
 
/**
 * Base URL of services/neo4j-proxy (FHIR, OMOP, NLQ, federated, TCK).
 * The compose stack and ACA set NEO4J_PROXY_URL; the default is a proxy
 * started locally with `npm run dev` in services/neo4j-proxy.
 */
export const NEO4J_PROXY_URL =
  process.env.NEO4J_PROXY_URL ?? "http://localhost:9090";
 
const LOAD_TEST_ID = /^[A-Za-z0-9._-]{1,64}$/;
 
/**
 * Headers that carry a load test's run id on to the proxy (#519). k6 sends
 * X-Load-Test on every request; the proxy logs it as `load_test`, so a run's
 * server-side latency and errors can be read later next to its k6 metrics.
 * Empty for any other request.
 */
export function loadTestHeaders(req?: Request): Record<string, string> {
  const id = loadTestId(req);
  return id ? { "X-Load-Test": id } : {};
}
 
/** The load test run a request belongs to (its valid X-Load-Test), if any. */
export function loadTestId(req?: Request): string | undefined {
  const id = req?.headers?.get("x-load-test");
  return id && LOAD_TEST_ID.test(id) ? id : undefined;
}
 
/**
 * Names the person behind a proxy call, so the proxy's rate limit counts per
 * user and not per organisation (#519): a SHA-256 of the session's user id,
 * shortened, never the id, the name or the email. Empty without a session.
 */
export function callerHeaders(session?: {
  user?: { id?: string | null };
}): Record<string, string> {
  const id = session?.user?.id;
  if (!id) return {};
  return {
    "X-Caller": createHash("sha256")
      .update(id, "utf8")
      .digest("hex")
      .slice(0, 32),
  };
}