Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

refactor(security): compare secrets with one constant-time helper

Yudhi Armyndharisf40f66a241e9
diff --git a/src/modules/integration/ingress-signature.ts b/src/modules/integration/ingress-signature.ts
index f62dd8acc..baa5988ba 100644
--- a/src/modules/integration/ingress-signature.ts
+++ b/src/modules/integration/ingress-signature.ts
@@ -49,7 +49,7 @@ function parseWebhookSecret(secret: string): string | undefined {
* header/contentTemplate/encoding/prefix/timestampHeader are ignored. The
* signature header may carry multiple space-separated `v1,` candidates (key rotation); any match passes.
* Pure and total: never throws. Ported from supabase-otp-hook/verify.ts; idiomatic changes: reuse the
- * existing safeEqualStr (identical to the reference's safeEqual) and the lowercasing `header()` helper
+ * existing constantTimeEqual (identical to the reference's safeEqual) and the lowercasing `header()` helper
* (the reference lowercases separately — OpenWA already delivers lowercased keys).
*/
function verifyStandardWebhooks(spec: IngressSignatureSpec, input: VerifyInput): { ok: boolean; reason?: string } {
@@ -82,7 +82,7 @@ function verifyStandardWebhooks(spec: IngressSignatureSpec, input: VerifyInput):
const comma = candidate.indexOf(',');
if (comma < 0) continue;
if (candidate.slice(0, comma) !== 'v1') continue;
- if (safeEqualStr(candidate.slice(comma + 1), expected)) return { ok: true };
+ if (constantTimeEqual(candidate.slice(comma + 1), expected)) return { ok: true };
}
return { ok: false, reason: 'webhook-signature mismatch' };
}
@@ -121,7 +121,7 @@ export function verifyIngressSignature(
if (!provided) return { ok: false, reason: 'missing signature header' };
if (spec.scheme === 'shared-secret') {
- return safeEqualStr(provided, input.secret) ? { ok: true } : { ok: false, reason: 'shared-secret mismatch' };
+ return constantTimeEqual(provided, input.secret) ? { ok: true } : { ok: false, reason: 'shared-secret mismatch' };
}
// hmac-sha256. Substitute the template tokens in a SINGLE pass with a function replacer: a string
@@ -140,14 +140,5 @@ export function verifyIngressSignature(
.update(signedContent)
.digest(spec.encoding ?? 'hex');
const expected = (spec.prefix ?? '') + digest;
- return safeEqualStr(provided, expected) ? { ok: true } : { ok: false, reason: 'hmac mismatch' };
-}
-
-/**
- * Constant-time string equality that does not leak the expected value's length.
- * Kept as a named export for the ingress call sites; delegates to the shared helper so the metrics
- * token compare and the ingress signature compares stay in lockstep.
- */
-export function safeEqualStr(a: string, b: string): boolean {
- return constantTimeEqual(a, b);
+ return constantTimeEqual(provided, expected) ? { ok: true } : { ok: false, reason: 'hmac mismatch' };
}
diff --git a/src/modules/integration/ingress.service.ts b/src/modules/integration/ingress.service.ts
index 124235fff..bb28ff1b5 100644
--- a/src/modules/integration/ingress.service.ts
+++ b/src/modules/integration/ingress.service.ts
@@ -1,6 +1,7 @@
import { createHash } from 'node:crypto';
import { throttlerMessage } from '@nestjs/throttler';
-import { safeEqualStr, verifyIngressSignature } from './ingress-signature';
+import { verifyIngressSignature } from './ingress-signature';
+import { constantTimeEqual } from '../../common/security/constantTimeEqual';
import { PluginIngressRoute } from '../../core/plugins/plugin.interfaces';
import { IngressJobData } from '../queue/processors/ingress.processor';
import type { EngineStatus } from '../../engine/interfaces/whatsapp-engine.interface';
@@ -119,7 +120,7 @@ export class IngressService {
const token = req.query[route.challenge.tokenParam];
const echo = req.query[route.challenge.echoParam];
// Constant-time compare (mirrors the signature path) so the verify token can't be probed by timing.
- if (token && instance.verifyToken && safeEqualStr(token, instance.verifyToken)) {
+ if (token && instance.verifyToken && constantTimeEqual(token, instance.verifyToken)) {
return { status: 200, body: echo ?? '' };
}
return { status: 403, body: 'challenge failed' };
diff --git a/src/modules/metrics/metrics.service.ts b/src/modules/metrics/metrics.service.ts
index 148dde049..292be7820 100644
--- a/src/modules/metrics/metrics.service.ts
+++ b/src/modules/metrics/metrics.service.ts
@@ -117,19 +117,14 @@ export class MetricsService implements OnModuleDestroy {
throw new HttpException('Too many failed metrics token attempts', HttpStatus.TOO_MANY_REQUESTS);
}
const provided = (authorizationHeader ?? '').replace(/^Bearer\s+/i, '').trim();
- if (!provided || !this.safeEqual(provided, expected)) {
+ // Length-hiding constant-time compare, so the expected token's byte-length is not leaked through a fast
+ // length-mismatch return: this `/api/metrics` endpoint is @Public and timed by callers.
+ if (!provided || !constantTimeEqual(provided, expected)) {
throw new UnauthorizedException('Invalid metrics token');
}
this.failedScrapeLimiter.refund(subject);
}
- private safeEqual(a: string, b: string): boolean {
- // Length-hiding constant-time compare: hash both inputs with a per-process key (fixed-length
- // digests) then timingSafeEqual, so the expected token's byte-length is not leaked through a
- // fast length-mismatch return. This `/api/metrics` endpoint is @Public and timed by callers.
- return constantTimeEqual(a, b);
- }
-
/** Render the current metrics in Prometheus text exposition format (memoized for a short TTL). */
async render(): Promise<string> {
const now = Date.now();