@deliverd/sdk 0.9.0 → 0.11.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/webhooks.ts CHANGED
@@ -1,117 +1,117 @@
1
- import { createHmac, timingSafeEqual } from "node:crypto";
2
- import { DeliverdError } from "./errors.js";
3
- import type { CallbackEnvelope, WebhookEvent } from "./types.js";
4
-
5
- /**
6
- * Verifying what Deliverd sends you.
7
- *
8
- * The scheme is Stripe's — a timestamp and a signature in one header, the
9
- * timestamp inside the signed material — so this is the verification everyone
10
- * has written before. It is here anyway because a receiver that skips it is
11
- * accepting anything anyone posts at the URL, and "write your own HMAC check"
12
- * is the step every integration guide shows and half of them get wrong.
13
- *
14
- * Kept byte-for-byte with the server's own `lib/webhooks/signature.ts`;
15
- * `sdk-parity.test.ts` on the server holds the two together.
16
- */
17
-
18
- export const SIGNATURE_HEADER = "deliverd-signature";
19
- export const EVENT_HEADER = "deliverd-event";
20
- export const DELIVERY_HEADER = "deliverd-delivery";
21
-
22
- /** How old a signature may be. Five minutes, as the server sends. */
23
- export const TOLERANCE_SECONDS = 300;
24
-
25
- export function signedPayload(timestamp: number, body: string): string {
26
- return `${timestamp}.${body}`;
27
- }
28
-
29
- /**
30
- * Whether the header is this secret's signature over this body, recently.
31
- *
32
- * `body` must be the raw request body, before any JSON parsing — a re-encoded
33
- * object is a different string and will never verify. In Express that means
34
- * `express.raw({ type: "application/json" })`; in Next.js `await request.text()`.
35
- */
36
- export function verifySignature(
37
- secret: string,
38
- body: string,
39
- header: string | null | undefined,
40
- options: { now?: number; toleranceSeconds?: number } = {}
41
- ): boolean {
42
- if (!header) return false;
43
- const now = options.now ?? Math.floor(Date.now() / 1000);
44
- const tolerance = options.toleranceSeconds ?? TOLERANCE_SECONDS;
45
-
46
- const parts = new Map(
47
- header.split(",").map((p) => {
48
- const at = p.indexOf("=");
49
- return [p.slice(0, at).trim(), p.slice(at + 1).trim()] as const;
50
- })
51
- );
52
- const t = Number(parts.get("t"));
53
- const v1 = parts.get("v1");
54
- if (!Number.isFinite(t) || !v1) return false;
55
- if (Math.abs(now - t) > tolerance) return false;
56
-
57
- const expected = createHmac("sha256", secret).update(signedPayload(t, body)).digest("hex");
58
- const a = Buffer.from(expected, "utf8");
59
- const b = Buffer.from(v1, "utf8");
60
- // Length first: timingSafeEqual throws on a mismatch, which leaks length.
61
- if (a.length !== b.length) return false;
62
- return timingSafeEqual(a, b);
63
- }
64
-
65
- /**
66
- * Verify and parse in one step, the way a handler wants it.
67
- *
68
- * Throws rather than returning null, because a webhook route that treats an
69
- * unverifiable body as "no event" answers 200 and tells the sender everything
70
- * is fine.
71
- */
72
- export function constructEvent(
73
- secret: string,
74
- body: string,
75
- header: string | null | undefined,
76
- options: { now?: number; toleranceSeconds?: number } = {}
77
- ): WebhookEvent {
78
- if (!verifySignature(secret, body, header, options)) {
79
- throw new DeliverdError(
80
- 400,
81
- "invalid_signature",
82
- "The signature did not verify. Check the endpoint's secret, and that you passed the raw request body rather than a re-encoded object."
83
- );
84
- }
85
- try {
86
- return JSON.parse(body) as WebhookEvent;
87
- } catch (cause) {
88
- throw new DeliverdError(400, "invalid_json", "The body verified but is not JSON.", undefined, { cause });
89
- }
90
- }
91
-
92
- /**
93
- * Verify and parse a per-request callback: what Deliverd POSTs to the
94
- * `callbackUrl` you gave when you asked, when a person answers.
95
- *
96
- * Signed exactly as a webhook is, with the request's own `callbackSecret`
97
- * (returned once, by the call that made the request) in place of an
98
- * endpoint's. Throws on a body that does not verify, for the same reason
99
- * `constructEvent` does.
100
- */
101
- export function constructCallback(
102
- callbackSecret: string,
103
- body: string,
104
- header: string | null | undefined,
105
- options: { now?: number; toleranceSeconds?: number } = {}
106
- ): CallbackEnvelope {
107
- return constructEvent(callbackSecret, body, header, options) as unknown as CallbackEnvelope;
108
- }
109
-
110
- export class Webhooks {
111
- verifySignature = verifySignature;
112
- constructEvent = constructEvent;
113
- constructCallback = constructCallback;
114
- readonly signatureHeader = SIGNATURE_HEADER;
115
- readonly eventHeader = EVENT_HEADER;
116
- readonly deliveryHeader = DELIVERY_HEADER;
117
- }
1
+ import { createHmac, timingSafeEqual } from "node:crypto";
2
+ import { DeliverdError } from "./errors.js";
3
+ import type { CallbackEnvelope, WebhookEvent } from "./types.js";
4
+
5
+ /**
6
+ * Verifying what Deliverd sends you.
7
+ *
8
+ * The scheme is Stripe's — a timestamp and a signature in one header, the
9
+ * timestamp inside the signed material — so this is the verification everyone
10
+ * has written before. It is here anyway because a receiver that skips it is
11
+ * accepting anything anyone posts at the URL, and "write your own HMAC check"
12
+ * is the step every integration guide shows and half of them get wrong.
13
+ *
14
+ * Kept byte-for-byte with the server's own `lib/webhooks/signature.ts`;
15
+ * `sdk-parity.test.ts` on the server holds the two together.
16
+ */
17
+
18
+ export const SIGNATURE_HEADER = "deliverd-signature";
19
+ export const EVENT_HEADER = "deliverd-event";
20
+ export const DELIVERY_HEADER = "deliverd-delivery";
21
+
22
+ /** How old a signature may be. Five minutes, as the server sends. */
23
+ export const TOLERANCE_SECONDS = 300;
24
+
25
+ export function signedPayload(timestamp: number, body: string): string {
26
+ return `${timestamp}.${body}`;
27
+ }
28
+
29
+ /**
30
+ * Whether the header is this secret's signature over this body, recently.
31
+ *
32
+ * `body` must be the raw request body, before any JSON parsing — a re-encoded
33
+ * object is a different string and will never verify. In Express that means
34
+ * `express.raw({ type: "application/json" })`; in Next.js `await request.text()`.
35
+ */
36
+ export function verifySignature(
37
+ secret: string,
38
+ body: string,
39
+ header: string | null | undefined,
40
+ options: { now?: number; toleranceSeconds?: number } = {}
41
+ ): boolean {
42
+ if (!header) return false;
43
+ const now = options.now ?? Math.floor(Date.now() / 1000);
44
+ const tolerance = options.toleranceSeconds ?? TOLERANCE_SECONDS;
45
+
46
+ const parts = new Map(
47
+ header.split(",").map((p) => {
48
+ const at = p.indexOf("=");
49
+ return [p.slice(0, at).trim(), p.slice(at + 1).trim()] as const;
50
+ })
51
+ );
52
+ const t = Number(parts.get("t"));
53
+ const v1 = parts.get("v1");
54
+ if (!Number.isFinite(t) || !v1) return false;
55
+ if (Math.abs(now - t) > tolerance) return false;
56
+
57
+ const expected = createHmac("sha256", secret).update(signedPayload(t, body)).digest("hex");
58
+ const a = Buffer.from(expected, "utf8");
59
+ const b = Buffer.from(v1, "utf8");
60
+ // Length first: timingSafeEqual throws on a mismatch, which leaks length.
61
+ if (a.length !== b.length) return false;
62
+ return timingSafeEqual(a, b);
63
+ }
64
+
65
+ /**
66
+ * Verify and parse in one step, the way a handler wants it.
67
+ *
68
+ * Throws rather than returning null, because a webhook route that treats an
69
+ * unverifiable body as "no event" answers 200 and tells the sender everything
70
+ * is fine.
71
+ */
72
+ export function constructEvent(
73
+ secret: string,
74
+ body: string,
75
+ header: string | null | undefined,
76
+ options: { now?: number; toleranceSeconds?: number } = {}
77
+ ): WebhookEvent {
78
+ if (!verifySignature(secret, body, header, options)) {
79
+ throw new DeliverdError(
80
+ 400,
81
+ "invalid_signature",
82
+ "The signature did not verify. Check the endpoint's secret, and that you passed the raw request body rather than a re-encoded object."
83
+ );
84
+ }
85
+ try {
86
+ return JSON.parse(body) as WebhookEvent;
87
+ } catch (cause) {
88
+ throw new DeliverdError(400, "invalid_json", "The body verified but is not JSON.", undefined, { cause });
89
+ }
90
+ }
91
+
92
+ /**
93
+ * Verify and parse a per-request callback: what Deliverd POSTs to the
94
+ * `callbackUrl` you gave when you asked, when a person answers.
95
+ *
96
+ * Signed exactly as a webhook is, with the request's own `callbackSecret`
97
+ * (returned once, by the call that made the request) in place of an
98
+ * endpoint's. Throws on a body that does not verify, for the same reason
99
+ * `constructEvent` does.
100
+ */
101
+ export function constructCallback(
102
+ callbackSecret: string,
103
+ body: string,
104
+ header: string | null | undefined,
105
+ options: { now?: number; toleranceSeconds?: number } = {}
106
+ ): CallbackEnvelope {
107
+ return constructEvent(callbackSecret, body, header, options) as unknown as CallbackEnvelope;
108
+ }
109
+
110
+ export class Webhooks {
111
+ verifySignature = verifySignature;
112
+ constructEvent = constructEvent;
113
+ constructCallback = constructCallback;
114
+ readonly signatureHeader = SIGNATURE_HEADER;
115
+ readonly eventHeader = EVENT_HEADER;
116
+ readonly deliveryHeader = DELIVERY_HEADER;
117
+ }