31 lines
884 B
TypeScript
31 lines
884 B
TypeScript
import { createHash, timingSafeEqual } from "node:crypto";
|
|
|
|
export const MIN_PROVISIONING_SECRET_LENGTH = 32;
|
|
|
|
export function parseProvisioningBearerSecret(
|
|
header: string | null | undefined
|
|
) {
|
|
const match = /^Bearer\s+([^\s]+)$/i.exec(String(header || "").trim());
|
|
return match?.[1] || null;
|
|
}
|
|
|
|
function digest(value: string) {
|
|
return createHash("sha256").update(value).digest();
|
|
}
|
|
|
|
export function verifyProvisioningSecret(
|
|
candidate: string | null | undefined,
|
|
expected: string | null | undefined
|
|
) {
|
|
const normalizedCandidate = String(candidate || "");
|
|
const normalizedExpected = String(expected || "").trim();
|
|
if (
|
|
normalizedCandidate.length < MIN_PROVISIONING_SECRET_LENGTH ||
|
|
normalizedExpected.length < MIN_PROVISIONING_SECRET_LENGTH
|
|
) {
|
|
return false;
|
|
}
|
|
|
|
return timingSafeEqual(digest(normalizedCandidate), digest(normalizedExpected));
|
|
}
|