@1st-flock/donations-embed-node 1.0.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.
@@ -0,0 +1,438 @@
1
+ /**
2
+ * Internal constants shared across the SDK.
3
+ *
4
+ * Kept in a tiny module so internal modules (HTTP transport, webhook
5
+ * verifier) can import without dragging in the public surface.
6
+ */
7
+ /**
8
+ * Single source of truth for the SDK's marketed version. Every outbound
9
+ * request advertises this in the User-Agent header so the platform can
10
+ * attribute traffic and warn customers running EOL versions.
11
+ */
12
+ declare const SDK_VERSION = "1.0.0";
13
+ /**
14
+ * Webhook timestamp tolerance in seconds — per spec §6.7.
15
+ *
16
+ * The verifier rejects deliveries whose timestamp falls outside this
17
+ * window even if the HMAC matches. Customers should not need to override
18
+ * this in production; the parameter exists so unit tests can simulate
19
+ * clock drift.
20
+ */
21
+ declare const DEFAULT_WEBHOOK_TOLERANCE_SECONDS = 300;
22
+
23
+ /**
24
+ * Donation domain models — TypeScript mirror of OpenAPI `Donation`,
25
+ * `RefundRequest`, and friends. The OpenAPI spec at
26
+ * `donations-embed/openapi.yaml` is the single source of truth for shapes;
27
+ * any drift here is a bug.
28
+ */
29
+ /** Lifecycle state of a donation. Matches OpenAPI `Donation.status`. */
30
+ type DonationStatus = "pending" | "completed" | "failed" | "refunded" | "partial_refund";
31
+ /** Payment instrument used for the donation. */
32
+ type PaymentMethodType = "card" | "ach";
33
+ /** One row of a donation's per-fund allocation. */
34
+ interface FundAllocation {
35
+ /** Fund identifier (UUID). */
36
+ fund_id: string;
37
+ /** Human-readable fund label. */
38
+ fund_name: string;
39
+ /** Allocated portion of the donation, in cents (>= 0). */
40
+ amount_cents: number;
41
+ }
42
+ /** A processed donation row, returned by `GET /v1/embed/donations`. */
43
+ interface Donation {
44
+ /** Server-issued donation ID (UUID). */
45
+ id: string;
46
+ /** Human-readable receipt ID (e.g. `don_8a1b9c4d`). */
47
+ confirmation_id: string;
48
+ donor_name: string;
49
+ donor_email: string;
50
+ /** Total charged including any cover-fees uplift, in cents. */
51
+ gross_amount_cents: number;
52
+ /** Processing fee component of `gross_amount_cents`, in cents. */
53
+ fee_amount_cents: number;
54
+ /** Amount the organization received after fees, in cents. */
55
+ net_amount_cents: number;
56
+ payment_method_type: PaymentMethodType;
57
+ /** Last 4 digits of the card / bank account. */
58
+ payment_method_last4: string;
59
+ /** Card brand (e.g. `visa`); null for ACH. */
60
+ payment_method_brand?: string | null;
61
+ /** Per-fund allocations. */
62
+ funds: FundAllocation[];
63
+ /**
64
+ * Identifier of the recurring schedule that generated this charge,
65
+ * if any (UUID). Null for one-time donations.
66
+ */
67
+ recurring_id?: string | null;
68
+ /**
69
+ * Cumulative refunded amount; equals `gross_amount_cents` for a full
70
+ * refund. Defaults to 0 when there has been no refund.
71
+ */
72
+ refunded_amount_cents: number;
73
+ status: DonationStatus;
74
+ /** ISO-8601 timestamp at which the donation was created. */
75
+ created_at: string;
76
+ }
77
+ /** Paginated response from `GET /v1/embed/donations`. */
78
+ interface DonationListResponse {
79
+ donations: Donation[];
80
+ /**
81
+ * Cursor for the next page; pass back as `cursor` query param. Null on
82
+ * the last page.
83
+ */
84
+ next_cursor?: string | null;
85
+ }
86
+ /** Body of `POST /v1/embed/donations/{donation_id}/refund`. */
87
+ interface RefundRequest {
88
+ /**
89
+ * Refund amount in cents. Omit (or pass `null` / `undefined`) to
90
+ * refund the full donation. When supplied, must be >= 1.
91
+ */
92
+ amount_cents?: number | null;
93
+ /**
94
+ * Optional internal note attached to the refund record (max 500 chars).
95
+ */
96
+ reason?: string | null;
97
+ }
98
+ /** Successful refund result. */
99
+ interface RefundResponse {
100
+ donation_id: string;
101
+ refund_amount_cents: number;
102
+ /** ISO-8601 timestamp at which the refund was issued. */
103
+ refunded_at: string;
104
+ /** Vendor-neutral refund identifier from the payment processor. */
105
+ processor_refund_id: string;
106
+ }
107
+
108
+ /**
109
+ * Recurring donation domain models — mirror of OpenAPI `Recurring` schemas.
110
+ */
111
+ /** Cadence between charges. Matches OpenAPI `Recurring.interval`. */
112
+ type RecurringInterval = "weekly" | "monthly" | "annual";
113
+ /** Lifecycle state of a recurring schedule. */
114
+ type RecurringStatus = "active" | "paused" | "cancelled";
115
+ /** A single recurring donation schedule. */
116
+ interface Recurring {
117
+ id: string;
118
+ donor_name: string;
119
+ donor_email: string;
120
+ /** Per-cycle charge amount, in cents (>= 0). */
121
+ amount_cents: number;
122
+ interval: RecurringInterval;
123
+ /** Number of intervals between charges (e.g. 1 = every month). */
124
+ interval_count: number;
125
+ status: RecurringStatus;
126
+ /**
127
+ * ISO-8601 date (YYYY-MM-DD) of the next scheduled charge; null when
128
+ * status is not `active`.
129
+ */
130
+ next_charge_date?: string | null;
131
+ /** ISO-8601 timestamp at which the schedule was created. */
132
+ created_at: string;
133
+ }
134
+ /** Paginated response from `GET /v1/embed/recurring`. */
135
+ interface RecurringListResponse {
136
+ recurring: Recurring[];
137
+ /** Cursor for the next page; null on the last page. */
138
+ next_cursor?: string | null;
139
+ }
140
+ /**
141
+ * Result of `POST /v1/embed/recurring/{recurring_id}/cancel`.
142
+ *
143
+ * The `already_cancelled` field is `true` when an idempotent replay
144
+ * against an already-cancelled schedule short-circuits without contacting
145
+ * the gateway again.
146
+ */
147
+ interface RecurringCancelResponse {
148
+ id: string;
149
+ status: "cancelled";
150
+ already_cancelled: boolean;
151
+ }
152
+
153
+ /**
154
+ * Webhook event payload models — discriminated union over `type`.
155
+ *
156
+ * Each concrete event extends {@link WebhookEnvelopeBase} (the canonical
157
+ * envelope) and adds a `data` field whose shape varies per event type.
158
+ * {@link WebhookEvent} is the discriminated union of every concrete event,
159
+ * so a `switch (event.type)` block narrows `event.data.object` to the
160
+ * right shape automatically.
161
+ *
162
+ * Example:
163
+ * ```ts
164
+ * import { verifyWebhook } from "@1st-flock/donations-embed-node";
165
+ *
166
+ * const event = verifyWebhook(rawBody, signatureHeader, secret);
167
+ * switch (event.type) {
168
+ * case "donation.completed":
169
+ * // event.data.object is DonationEventObject — typed.
170
+ * enqueueReceipt(event.data.object);
171
+ * break;
172
+ * case "donation.refunded":
173
+ * // event.data.object includes refund_amount_cents.
174
+ * reverseReceipt(event.data.object);
175
+ * break;
176
+ * }
177
+ * ```
178
+ */
179
+
180
+ /** Stable union of every event type emitted by the platform. */
181
+ type WebhookEventType = "donation.created" | "donation.completed" | "donation.failed" | "donation.refunded" | "recurring.activated" | "recurring.payment_succeeded" | "recurring.payment_failed" | "recurring.cancelled" | "key.frozen";
182
+ /** Reason a key pair was automatically frozen by abuse-detection. */
183
+ type KeyFrozenReason = "card_testing_detected";
184
+ /**
185
+ * Donor identity carried inside donation event payloads.
186
+ *
187
+ * Inline subset of the donor model; does not include the address since
188
+ * webhook payloads omit it for compactness.
189
+ */
190
+ interface DonationEventDonor {
191
+ name: string;
192
+ email: string;
193
+ }
194
+ /** Payment-method snapshot inside a donation event payload. */
195
+ interface EventPaymentMethod {
196
+ type: PaymentMethodType;
197
+ last4: string;
198
+ /** Card brand; null for ACH. */
199
+ brand?: string | null;
200
+ }
201
+ /** Per-fund allocation inside a donation event payload (no fund name). */
202
+ interface DonationEventFundAllocation {
203
+ fund_id: string;
204
+ amount_cents: number;
205
+ }
206
+ /** Donation-shaped payload — used by completed / failed events. */
207
+ interface DonationEventObject {
208
+ id: string;
209
+ confirmation_id: string;
210
+ donor: DonationEventDonor;
211
+ gross_amount_cents: number;
212
+ fee_amount_cents: number;
213
+ net_amount_cents: number;
214
+ payment_method: EventPaymentMethod;
215
+ processor_transaction_id?: string | null;
216
+ status: DonationStatus;
217
+ created_at?: string | null;
218
+ funds?: DonationEventFundAllocation[];
219
+ }
220
+ /** Refund variant — extends donation payload with refund metadata. */
221
+ interface DonationRefundedEventObject extends DonationEventObject {
222
+ refund_amount_cents: number;
223
+ /** Vendor-neutral refund identifier. */
224
+ refund_transaction_id?: string | null;
225
+ }
226
+ /**
227
+ * Session-shaped payload for the `donation.created` event.
228
+ *
229
+ * Note: at this point there is no donation row yet — the embed has only
230
+ * just opened a session. Correlate to the eventual donation via the
231
+ * `donation_id` returned by `/v1/embed/sessions/{id}/confirm`.
232
+ */
233
+ interface DonationCreatedEventObject {
234
+ session_id: string;
235
+ organization_id: string;
236
+ amount_cents?: number | null;
237
+ fund_ids?: string[];
238
+ }
239
+ /**
240
+ * Recurring-schedule payload — used by `recurring.activated`,
241
+ * `recurring.payment_succeeded`, `recurring.payment_failed`.
242
+ */
243
+ interface RecurringEventObject {
244
+ id: string;
245
+ donor: DonationEventDonor;
246
+ amount_cents: number;
247
+ interval: RecurringInterval;
248
+ interval_count: number;
249
+ status: RecurringStatus;
250
+ processor_subscription_id?: string | null;
251
+ created_at?: string | null;
252
+ }
253
+ /** Minimal payload for `recurring.cancelled`. */
254
+ interface RecurringCancelledEventObject {
255
+ recurring_id: string;
256
+ processor_subscription_id?: string | null;
257
+ }
258
+ /** Payload for `key.frozen` — emitted by automatic protection. */
259
+ interface KeyFrozenEventObject {
260
+ key_pair_id: string;
261
+ /** Truncated prefix of the publishable key (safe to log). */
262
+ pk_prefix: string;
263
+ reason: KeyFrozenReason;
264
+ decline_count_window?: number | null;
265
+ window_seconds?: number | null;
266
+ frozen_at: string;
267
+ }
268
+ /**
269
+ * Fields shared by every webhook event envelope. Mirrors OpenAPI
270
+ * `WebhookEnvelope`; concrete subclasses pin `type` to a literal so the
271
+ * discriminator can route correctly.
272
+ */
273
+ interface WebhookEnvelopeBase {
274
+ /** Globally unique event ID. Echoed in `Flock-Event-Id` for dedup. */
275
+ id: string;
276
+ /** Unix epoch seconds at event creation. */
277
+ created: number;
278
+ /** True for live-mode events; false for test-mode. */
279
+ live_mode: boolean;
280
+ }
281
+ /** Donor opened the embed and a session was created (no donation row yet). */
282
+ interface DonationCreatedEvent extends WebhookEnvelopeBase {
283
+ type: "donation.created";
284
+ data: {
285
+ object: DonationCreatedEventObject;
286
+ };
287
+ }
288
+ /** Donation succeeded. */
289
+ interface DonationCompletedEvent extends WebhookEnvelopeBase {
290
+ type: "donation.completed";
291
+ data: {
292
+ object: DonationEventObject;
293
+ };
294
+ }
295
+ /** Donation declined or terminated before completion. */
296
+ interface DonationFailedEvent extends WebhookEnvelopeBase {
297
+ type: "donation.failed";
298
+ data: {
299
+ object: DonationEventObject;
300
+ };
301
+ }
302
+ /** Refund (full or partial) succeeded. */
303
+ interface DonationRefundedEvent extends WebhookEnvelopeBase {
304
+ type: "donation.refunded";
305
+ data: {
306
+ object: DonationRefundedEventObject;
307
+ };
308
+ }
309
+ /** Recurring schedule created and the first charge succeeded. */
310
+ interface RecurringActivatedEvent extends WebhookEnvelopeBase {
311
+ type: "recurring.activated";
312
+ data: {
313
+ object: RecurringEventObject;
314
+ /** The first underlying charge that activated this schedule. */
315
+ donation?: DonationEventObject | null;
316
+ };
317
+ }
318
+ /** Per-cycle charge against a recurring schedule succeeded. */
319
+ interface RecurringPaymentSucceededEvent extends WebhookEnvelopeBase {
320
+ type: "recurring.payment_succeeded";
321
+ data: {
322
+ object: RecurringEventObject;
323
+ /** The successful per-cycle charge. */
324
+ donation?: DonationEventObject | null;
325
+ };
326
+ }
327
+ /** Per-cycle charge against a recurring schedule failed. */
328
+ interface RecurringPaymentFailedEvent extends WebhookEnvelopeBase {
329
+ type: "recurring.payment_failed";
330
+ data: {
331
+ object: RecurringEventObject;
332
+ /** The failed per-cycle charge attempt, if available. */
333
+ donation?: DonationEventObject | null;
334
+ };
335
+ }
336
+ /** Recurring schedule was cancelled (by customer, donor, or platform). */
337
+ interface RecurringCancelledEvent extends WebhookEnvelopeBase {
338
+ type: "recurring.cancelled";
339
+ data: {
340
+ object: RecurringCancelledEventObject;
341
+ };
342
+ }
343
+ /** Key pair was automatically frozen by abuse-detection. */
344
+ interface KeyFrozenEvent extends WebhookEnvelopeBase {
345
+ type: "key.frozen";
346
+ data: {
347
+ object: KeyFrozenEventObject;
348
+ };
349
+ }
350
+ /**
351
+ * Discriminated union of every concrete webhook event type.
352
+ *
353
+ * The `type` field acts as a discriminator. A `switch` block on
354
+ * `event.type` narrows `event.data.object` to the correct shape for the
355
+ * branch.
356
+ */
357
+ type WebhookEvent = DonationCreatedEvent | DonationCompletedEvent | DonationFailedEvent | DonationRefundedEvent | RecurringActivatedEvent | RecurringPaymentSucceededEvent | RecurringPaymentFailedEvent | RecurringCancelledEvent | KeyFrozenEvent;
358
+ /** Alias for {@link WebhookEvent} matching the OpenAPI `WebhookEnvelope` name. */
359
+ type WebhookEnvelope = WebhookEvent;
360
+ /**
361
+ * The set of recognized event-type discriminator strings, exposed for
362
+ * runtime checks (e.g. logging unknown types). Kept in sync with
363
+ * {@link WebhookEventType} by construction.
364
+ */
365
+ declare const WEBHOOK_EVENT_TYPES: readonly WebhookEventType[];
366
+ /**
367
+ * Type guard: returns `true` when `value` is structurally a
368
+ * {@link WebhookEvent} (has the required envelope fields plus a known
369
+ * discriminator and a `data.object` payload).
370
+ *
371
+ * This is intentionally a *shape* check and not a deep schema validation —
372
+ * the discriminated union does not exist at runtime, and we keep the SDK
373
+ * dependency-free (no Zod). Callers that need exhaustive validation can
374
+ * pivot on `event.type` after the guard returns true.
375
+ */
376
+ declare function isWebhookEvent(value: unknown): value is WebhookEvent;
377
+
378
+ /**
379
+ * HMAC-SHA256 webhook signature verification.
380
+ *
381
+ * Wire format on the `Flock-Signature` header (per spec §6.7):
382
+ * ```
383
+ * t=<unix_ts>,v1=<hmac_sha256_hex>[,v1=<hmac_sha256_hex>]
384
+ * ```
385
+ *
386
+ * A second `v1=` segment is present during a key-rotation grace window so
387
+ * verifiers MAY check either signature without coordinating with the
388
+ * platform. A 5-minute timestamp tolerance prevents replay; payloads
389
+ * outside that window are rejected even when the HMAC matches.
390
+ *
391
+ * This module is byte-compatible with the platform-side signer at
392
+ * `app/services/finance/embed/webhook_signer.py` — any drift is a bug,
393
+ * and the cross-SDK fixtures in `tests/fixtures/webhook-events.ts` mirror
394
+ * the equivalent fixtures in the Python and Go SDKs to guarantee a
395
+ * signature produced by one SDK verifies correctly under the others.
396
+ */
397
+
398
+ /** Optional knobs accepted by {@link verifyWebhook}; useful for tests. */
399
+ interface VerifyWebhookOptions {
400
+ /**
401
+ * Maximum allowed clock skew between the platform and the receiver,
402
+ * in seconds. Defaults to 5 minutes (per spec §6.7); only override
403
+ * for unit tests.
404
+ */
405
+ toleranceSeconds?: number;
406
+ /**
407
+ * Wall-clock seconds-since-epoch to compare against. Defaults to the
408
+ * current time (`Date.now() / 1000`); override in tests for
409
+ * determinism.
410
+ */
411
+ now?: number;
412
+ }
413
+ /**
414
+ * Verify a webhook delivery and return the parsed event.
415
+ *
416
+ * @param body - The raw request body as received off the wire. **Do not
417
+ * re-serialize** the JSON before passing it in — even a single
418
+ * whitespace difference will invalidate the signature. Frameworks that
419
+ * buffer the body (Express with `express.raw()`, Fastify
420
+ * `request.rawBody`) provide the bytes directly.
421
+ * @param signature - Value of the `Flock-Signature` request header.
422
+ * @param secret - The HMAC signing secret returned by the platform when
423
+ * the webhook endpoint was created or its URL was last changed.
424
+ * @param options - Optional tolerance / clock overrides for tests.
425
+ * @returns The parsed {@link WebhookEvent} (a discriminated union member
426
+ * selected by the `type` discriminator).
427
+ * @throws {@link WebhookFormatError} The signature header does not parse,
428
+ * or the body is not UTF-8 JSON matching a known event shape.
429
+ * @throws {@link WebhookTimestampError} The timestamp falls outside the
430
+ * tolerance window. Reject as a replay attempt.
431
+ * @throws {@link WebhookSignatureError} No `v1=` digest matched under
432
+ * the supplied secret. The body may have been tampered with, the
433
+ * secret may be wrong, or the request did not originate from
434
+ * 1st Flock.
435
+ */
436
+ declare function verifyWebhook(body: string | Uint8Array, signature: string, secret: string, options?: VerifyWebhookOptions): WebhookEvent;
437
+
438
+ export { type WebhookEnvelope as A, type WebhookEnvelopeBase as B, type WebhookEvent as C, type DonationListResponse as D, type EventPaymentMethod as E, type FundAllocation as F, type WebhookEventType as G, isWebhookEvent as H, verifyWebhook as I, type KeyFrozenEvent as K, type PaymentMethodType as P, type RefundResponse as R, SDK_VERSION as S, type VerifyWebhookOptions as V, WEBHOOK_EVENT_TYPES as W, type Donation as a, type RecurringStatus as b, type RecurringListResponse as c, type RecurringCancelResponse as d, DEFAULT_WEBHOOK_TOLERANCE_SECONDS as e, type DonationCompletedEvent as f, type DonationCreatedEvent as g, type DonationCreatedEventObject as h, type DonationEventDonor as i, type DonationEventFundAllocation as j, type DonationEventObject as k, type DonationFailedEvent as l, type DonationRefundedEvent as m, type DonationRefundedEventObject as n, type DonationStatus as o, type KeyFrozenEventObject as p, type KeyFrozenReason as q, type Recurring as r, type RecurringActivatedEvent as s, type RecurringCancelledEvent as t, type RecurringCancelledEventObject as u, type RecurringEventObject as v, type RecurringInterval as w, type RecurringPaymentFailedEvent as x, type RecurringPaymentSucceededEvent as y, type RefundRequest as z };
@@ -0,0 +1,181 @@
1
+ 'use strict';
2
+
3
+ var buffer = require('buffer');
4
+ var crypto = require('crypto');
5
+
6
+ // src/webhooks.ts
7
+
8
+ // src/errors.ts
9
+ var DonationsEmbedError = class extends Error {
10
+ constructor(message) {
11
+ super(message);
12
+ this.name = "DonationsEmbedError";
13
+ Object.setPrototypeOf(this, new.target.prototype);
14
+ }
15
+ };
16
+ var WebhookError = class extends DonationsEmbedError {
17
+ constructor(message) {
18
+ super(message);
19
+ this.name = "WebhookError";
20
+ Object.setPrototypeOf(this, new.target.prototype);
21
+ }
22
+ };
23
+ var WebhookSignatureError = class extends WebhookError {
24
+ constructor(message) {
25
+ super(message);
26
+ this.name = "WebhookSignatureError";
27
+ Object.setPrototypeOf(this, new.target.prototype);
28
+ }
29
+ };
30
+ var WebhookTimestampError = class extends WebhookError {
31
+ constructor(message) {
32
+ super(message);
33
+ this.name = "WebhookTimestampError";
34
+ Object.setPrototypeOf(this, new.target.prototype);
35
+ }
36
+ };
37
+ var WebhookFormatError = class extends WebhookError {
38
+ constructor(message) {
39
+ super(message);
40
+ this.name = "WebhookFormatError";
41
+ Object.setPrototypeOf(this, new.target.prototype);
42
+ }
43
+ };
44
+
45
+ // src/models/events.ts
46
+ var WEBHOOK_EVENT_TYPES = [
47
+ "donation.created",
48
+ "donation.completed",
49
+ "donation.failed",
50
+ "donation.refunded",
51
+ "recurring.activated",
52
+ "recurring.payment_succeeded",
53
+ "recurring.payment_failed",
54
+ "recurring.cancelled",
55
+ "key.frozen"
56
+ ];
57
+ function isWebhookEvent(value) {
58
+ if (typeof value !== "object" || value === null) return false;
59
+ const v = value;
60
+ if (typeof v.id !== "string") return false;
61
+ if (typeof v.created !== "number") return false;
62
+ if (typeof v.live_mode !== "boolean") return false;
63
+ if (typeof v.type !== "string") return false;
64
+ if (!WEBHOOK_EVENT_TYPES.includes(v.type)) return false;
65
+ if (typeof v.data !== "object" || v.data === null) return false;
66
+ const data = v.data;
67
+ if (typeof data.object !== "object" || data.object === null) return false;
68
+ return true;
69
+ }
70
+
71
+ // src/_const.ts
72
+ var DEFAULT_WEBHOOK_TOLERANCE_SECONDS = 300;
73
+
74
+ // src/webhooks.ts
75
+ function parseSignatureHeader(header) {
76
+ if (!header) {
77
+ throw new WebhookFormatError("Flock-Signature header is missing or empty");
78
+ }
79
+ let timestamp = null;
80
+ const digests = [];
81
+ for (const raw of header.split(",")) {
82
+ const part = raw.trim();
83
+ if (part.startsWith("t=")) {
84
+ const tsRaw = part.slice(2);
85
+ if (!/^\d+$/.test(tsRaw)) {
86
+ throw new WebhookFormatError(
87
+ `timestamp segment in Flock-Signature is not an integer: ${JSON.stringify(part)}`
88
+ );
89
+ }
90
+ timestamp = Number.parseInt(tsRaw, 10);
91
+ } else if (part.startsWith("v1=")) {
92
+ const digest = part.slice(3);
93
+ if (!/^[0-9a-f]{64}$/.test(digest)) {
94
+ throw new WebhookFormatError(
95
+ `v1 signature segment is not a 64-char hex digest: ${JSON.stringify(part)}`
96
+ );
97
+ }
98
+ digests.push(digest);
99
+ }
100
+ }
101
+ if (timestamp === null) {
102
+ throw new WebhookFormatError(
103
+ "Flock-Signature is missing the required t=<unix_ts> segment"
104
+ );
105
+ }
106
+ if (digests.length === 0) {
107
+ throw new WebhookFormatError("Flock-Signature has no v1=<hex> segments");
108
+ }
109
+ return { timestamp, digests };
110
+ }
111
+ function computeExpected(secret, timestamp, body) {
112
+ const hmac = crypto.createHmac("sha256", secret);
113
+ hmac.update(`${timestamp}.`, "utf8");
114
+ hmac.update(body);
115
+ return hmac.digest("hex");
116
+ }
117
+ function constantTimeEqualHex(a, b) {
118
+ if (a.length !== b.length) return false;
119
+ const aBuf = buffer.Buffer.from(a, "utf8");
120
+ const bBuf = buffer.Buffer.from(b, "utf8");
121
+ return crypto.timingSafeEqual(aBuf, bBuf);
122
+ }
123
+ function coerceBody(body) {
124
+ if (typeof body === "string") {
125
+ return buffer.Buffer.from(body, "utf8");
126
+ }
127
+ return body;
128
+ }
129
+ function verifyWebhook(body, signature, secret, options = {}) {
130
+ const tolerance = options.toleranceSeconds ?? DEFAULT_WEBHOOK_TOLERANCE_SECONDS;
131
+ if (typeof secret !== "string" || secret.length === 0) {
132
+ throw new WebhookFormatError("secret must be a non-empty string");
133
+ }
134
+ const { timestamp, digests } = parseSignatureHeader(signature);
135
+ const current = options.now ?? Date.now() / 1e3;
136
+ if (Math.abs(current - timestamp) > tolerance) {
137
+ throw new WebhookTimestampError(
138
+ `webhook timestamp ${timestamp} is outside the ${tolerance}s tolerance (current=${Math.floor(current)})`
139
+ );
140
+ }
141
+ const bodyBytes = coerceBody(body);
142
+ const expected = computeExpected(secret, timestamp, bodyBytes);
143
+ let matched = false;
144
+ for (const d of digests) {
145
+ if (constantTimeEqualHex(expected, d)) {
146
+ matched = true;
147
+ }
148
+ }
149
+ if (!matched) {
150
+ throw new WebhookSignatureError(
151
+ "webhook signature did not match \u2014 wrong secret or tampered body"
152
+ );
153
+ }
154
+ let decoded;
155
+ try {
156
+ decoded = buffer.Buffer.from(bodyBytes).toString("utf8");
157
+ } catch (err) {
158
+ throw new WebhookFormatError(
159
+ `webhook body is not valid UTF-8: ${err.message}`
160
+ );
161
+ }
162
+ let payload;
163
+ try {
164
+ payload = JSON.parse(decoded);
165
+ } catch (err) {
166
+ throw new WebhookFormatError(
167
+ `webhook body did not parse as JSON: ${err.message}`
168
+ );
169
+ }
170
+ if (!isWebhookEvent(payload)) {
171
+ throw new WebhookFormatError(
172
+ "webhook body did not match any known event schema"
173
+ );
174
+ }
175
+ return payload;
176
+ }
177
+
178
+ exports.DEFAULT_WEBHOOK_TOLERANCE_SECONDS = DEFAULT_WEBHOOK_TOLERANCE_SECONDS;
179
+ exports.verifyWebhook = verifyWebhook;
180
+ //# sourceMappingURL=webhooks.cjs.map
181
+ //# sourceMappingURL=webhooks.cjs.map