103 lines
3.6 KiB
TypeScript
103 lines
3.6 KiB
TypeScript
export type MetricsTokenAuthResult =
|
|
| { ok: true }
|
|
| { ok: false; status: 401; code: "missing_token" | "invalid_token" }
|
|
| { ok: false; status: 403; code: "metrics_disabled" }
|
|
| { ok: false; status: 500; code: "token_misconfigured" };
|
|
|
|
export type MetricsTokenAuthOptions = {
|
|
/** The raw value of the `Authorization` header, if any. */
|
|
authorizationHeader?: string | null | undefined;
|
|
/** The configured metrics token. When empty + enabled => 500 (operator must configure). */
|
|
configuredToken?: string | null | undefined;
|
|
/** Master switch; mirrors `METRICS_ENABLED=true`. */
|
|
metricsEnabled: boolean;
|
|
};
|
|
|
|
const MIN_METRICS_TOKEN_BYTES = 32;
|
|
const MAX_METRICS_TOKEN_BYTES = 512;
|
|
|
|
/**
|
|
* Reads `METRICS_ENABLED` from a plain env record. Mirrors the existing
|
|
* project convention of treating the literal string "true" as enabled.
|
|
*/
|
|
export function isMetricsEnabled(env: Record<string, string | undefined>): boolean {
|
|
return env.METRICS_ENABLED === "true";
|
|
}
|
|
|
|
/**
|
|
* Constant-time check that the inbound bearer token matches the configured
|
|
* token. Returns a discriminated result that callers map onto framework-
|
|
* specific responses (Hono context, React Router Response).
|
|
*
|
|
* Security notes:
|
|
* - Empty / whitespace tokens are rejected.
|
|
* - The comparison performs a fixed amount of byte work for every validly
|
|
* sized token instead of returning early on length mismatches.
|
|
* - The token MUST NEVER be logged. See `redactMetricsToken` for the
|
|
* audit-safe representation.
|
|
*/
|
|
export function validateMetricsTokenAuth(options: MetricsTokenAuthOptions): MetricsTokenAuthResult {
|
|
if (!options.metricsEnabled) {
|
|
return { ok: false, status: 403, code: "metrics_disabled" };
|
|
}
|
|
|
|
const configured = options.configuredToken?.trim() ?? "";
|
|
const configuredBytes = new TextEncoder().encode(configured);
|
|
if (configuredBytes.length < MIN_METRICS_TOKEN_BYTES || configuredBytes.length > MAX_METRICS_TOKEN_BYTES) {
|
|
return { ok: false, status: 500, code: "token_misconfigured" };
|
|
}
|
|
|
|
const presented = extractBearerToken(options.authorizationHeader);
|
|
if (!presented) {
|
|
return { ok: false, status: 401, code: "missing_token" };
|
|
}
|
|
|
|
if (!timingSafeEqualStrings(presented, configured)) {
|
|
return { ok: false, status: 401, code: "invalid_token" };
|
|
}
|
|
|
|
return { ok: true };
|
|
}
|
|
|
|
/**
|
|
* Returns an audit-safe, non-reversible representation of a metrics token for
|
|
* logging. Empty / missing tokens render as `"<unset>"`.
|
|
*/
|
|
export function redactMetricsToken(token: string | undefined | null): string {
|
|
if (!token) {
|
|
return "<unset>";
|
|
}
|
|
const trimmed = token.trim();
|
|
if (trimmed.length === 0) {
|
|
return "<unset>";
|
|
}
|
|
if (trimmed.length <= 8) {
|
|
return "***";
|
|
}
|
|
return `${trimmed.slice(0, 4)}…${trimmed.slice(-2)}`;
|
|
}
|
|
|
|
function extractBearerToken(header: string | null | undefined): string | undefined {
|
|
if (!header) {
|
|
return undefined;
|
|
}
|
|
const match = /^Bearer\s+(\S+)\s*$/i.exec(header.trim());
|
|
if (!match) {
|
|
return undefined;
|
|
}
|
|
const candidate = match[1]?.trim() ?? "";
|
|
return candidate.length > 0 && new TextEncoder().encode(candidate).length <= MAX_METRICS_TOKEN_BYTES ? candidate : undefined;
|
|
}
|
|
|
|
function timingSafeEqualStrings(a: string, b: string): boolean {
|
|
// Compare a fixed amount of work so mismatched character or byte lengths do
|
|
// not reveal the configured token length through an early return.
|
|
const aBytes = new TextEncoder().encode(a);
|
|
const bBytes = new TextEncoder().encode(b);
|
|
let diff = aBytes.length ^ bBytes.length;
|
|
for (let i = 0; i < MAX_METRICS_TOKEN_BYTES; i += 1) {
|
|
diff |= (aBytes[i] ?? 0) ^ (bBytes[i] ?? 0);
|
|
}
|
|
return diff === 0;
|
|
}
|