-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhmac.ts
More file actions
27 lines (23 loc) · 808 Bytes
/
Copy pathhmac.ts
File metadata and controls
27 lines (23 loc) · 808 Bytes
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
import { createHmac, timingSafeEqual } from 'node:crypto';
export const DEMO_PARTNER_SECRET = 'demo-partner-secret';
export function partnerSecret(): string {
return process.env.PARTNER_HMAC_SECRET || DEMO_PARTNER_SECRET;
}
export function signBody(body: string, secret: string = partnerSecret()): string {
const digest = createHmac('sha256', secret).update(body).digest('hex');
return `sha256=${digest}`;
}
export function verifySignature(
body: string,
signature: string | null | undefined,
secret: string = partnerSecret(),
): boolean {
if (!signature) return false;
const expected = signBody(body, secret);
if (signature.length !== expected.length) return false;
try {
return timingSafeEqual(Buffer.from(signature), Buffer.from(expected));
} catch {
return false;
}
}