All files / src/lib service-token.ts

100% Statements 14/14
100% Branches 6/6
100% Functions 2/2
100% Lines 14/14

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 191x     76x 76x 76x   1x 40x 2x 2x   38x 38x 40x 1x 1x 40x  
import { createHash, timingSafeEqual } from "node:crypto";
import { AppError } from "@ontrack/backend-common";
 
function digestToken(value: string): Buffer {
  return createHash("sha256").update(value, "utf8").digest();
}
 
export function assertServiceToken(headerValue: string | undefined, expected: string): void {
  if (!headerValue || !expected) {
    throw new AppError(401, "UNAUTHORIZED", "Missing or invalid service token");
  }
 
  const a = digestToken(headerValue);
  const b = digestToken(expected);
  if (a.length !== b.length || !timingSafeEqual(a, b)) {
    throw new AppError(401, "UNAUTHORIZED", "Missing or invalid service token");
  }
}