@referalli/sdk 0.0.0-stage → 0.3.20
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/CHANGELOG.md +128 -0
- package/LICENSE +21 -0
- package/README.md +236 -2
- package/dist/cjs/attribution.d.ts +105 -0
- package/dist/cjs/attribution.js +200 -0
- package/dist/cjs/browser.d.ts +41 -0
- package/dist/cjs/browser.js +88 -0
- package/dist/cjs/client.d.ts +97 -0
- package/dist/cjs/client.js +301 -0
- package/dist/cjs/consent/adapters/cookiebot.d.ts +7 -0
- package/dist/cjs/consent/adapters/cookiebot.js +49 -0
- package/dist/cjs/consent/adapters/cookiemunch.d.ts +8 -0
- package/dist/cjs/consent/adapters/cookiemunch.js +56 -0
- package/dist/cjs/consent/adapters/custom.d.ts +8 -0
- package/dist/cjs/consent/adapters/custom.js +39 -0
- package/dist/cjs/consent/adapters/didomi.d.ts +9 -0
- package/dist/cjs/consent/adapters/didomi.js +67 -0
- package/dist/cjs/consent/adapters/gcm.d.ts +10 -0
- package/dist/cjs/consent/adapters/gcm.js +78 -0
- package/dist/cjs/consent/adapters/gpp.d.ts +9 -0
- package/dist/cjs/consent/adapters/gpp.js +92 -0
- package/dist/cjs/consent/adapters/none.d.ts +3 -0
- package/dist/cjs/consent/adapters/none.js +30 -0
- package/dist/cjs/consent/adapters/onetrust.d.ts +8 -0
- package/dist/cjs/consent/adapters/onetrust.js +71 -0
- package/dist/cjs/consent/adapters/osano.d.ts +9 -0
- package/dist/cjs/consent/adapters/osano.js +71 -0
- package/dist/cjs/consent/adapters/tcf.d.ts +8 -0
- package/dist/cjs/consent/adapters/tcf.js +79 -0
- package/dist/cjs/consent/adapters/termly.d.ts +10 -0
- package/dist/cjs/consent/adapters/termly.js +61 -0
- package/dist/cjs/consent/adapters/usercentrics.d.ts +9 -0
- package/dist/cjs/consent/adapters/usercentrics.js +106 -0
- package/dist/cjs/consent/conformance.d.ts +22 -0
- package/dist/cjs/consent/conformance.js +33 -0
- package/dist/cjs/consent/gate.d.ts +23 -0
- package/dist/cjs/consent/gate.js +220 -0
- package/dist/cjs/consent/port.d.ts +105 -0
- package/dist/cjs/consent/port.js +72 -0
- package/dist/cjs/consent/registry.d.ts +17 -0
- package/dist/cjs/consent/registry.js +61 -0
- package/dist/cjs/consent/served.d.ts +15 -0
- package/dist/cjs/consent/served.js +26 -0
- package/dist/cjs/core.d.ts +77 -0
- package/dist/cjs/core.js +64 -0
- package/dist/cjs/errors.d.ts +42 -0
- package/dist/cjs/errors.generated.d.ts +183 -0
- package/dist/cjs/errors.generated.js +279 -0
- package/dist/cjs/errors.js +47 -0
- package/dist/cjs/generated.d.ts +15146 -0
- package/dist/cjs/generated.js +625 -0
- package/dist/cjs/index.d.ts +22 -0
- package/dist/cjs/index.js +93 -0
- package/dist/cjs/mobile.d.ts +66 -0
- package/dist/cjs/mobile.js +69 -0
- package/dist/cjs/node.d.ts +209 -0
- package/dist/cjs/node.js +140 -0
- package/dist/cjs/outbox.d.ts +186 -0
- package/dist/cjs/outbox.js +324 -0
- package/dist/cjs/package.json +3 -0
- package/dist/cjs/resources.generated.d.ts +6002 -0
- package/dist/cjs/resources.generated.js +2090 -0
- package/dist/cjs/served.d.ts +25 -0
- package/dist/cjs/served.js +214 -0
- package/dist/cjs/sha256.d.ts +2 -0
- package/dist/cjs/sha256.js +86 -0
- package/dist/cjs/snippet.d.ts +99 -0
- package/dist/cjs/snippet.js +213 -0
- package/dist/cjs/stripe-events.d.ts +25 -0
- package/dist/cjs/stripe-events.js +117 -0
- package/dist/cjs/version.d.ts +2 -0
- package/dist/cjs/version.js +5 -0
- package/dist/cjs/webhooks.d.ts +76 -0
- package/dist/cjs/webhooks.js +159 -0
- package/dist/esm/attribution.d.ts +105 -0
- package/dist/esm/attribution.js +186 -0
- package/dist/esm/browser.d.ts +41 -0
- package/dist/esm/browser.js +68 -0
- package/dist/esm/client.d.ts +97 -0
- package/dist/esm/client.js +297 -0
- package/dist/esm/consent/adapters/cookiebot.d.ts +7 -0
- package/dist/esm/consent/adapters/cookiebot.js +46 -0
- package/dist/esm/consent/adapters/cookiemunch.d.ts +8 -0
- package/dist/esm/consent/adapters/cookiemunch.js +53 -0
- package/dist/esm/consent/adapters/custom.d.ts +8 -0
- package/dist/esm/consent/adapters/custom.js +36 -0
- package/dist/esm/consent/adapters/didomi.d.ts +9 -0
- package/dist/esm/consent/adapters/didomi.js +64 -0
- package/dist/esm/consent/adapters/gcm.d.ts +10 -0
- package/dist/esm/consent/adapters/gcm.js +75 -0
- package/dist/esm/consent/adapters/gpp.d.ts +9 -0
- package/dist/esm/consent/adapters/gpp.js +89 -0
- package/dist/esm/consent/adapters/none.d.ts +3 -0
- package/dist/esm/consent/adapters/none.js +27 -0
- package/dist/esm/consent/adapters/onetrust.d.ts +8 -0
- package/dist/esm/consent/adapters/onetrust.js +68 -0
- package/dist/esm/consent/adapters/osano.d.ts +9 -0
- package/dist/esm/consent/adapters/osano.js +68 -0
- package/dist/esm/consent/adapters/tcf.d.ts +8 -0
- package/dist/esm/consent/adapters/tcf.js +76 -0
- package/dist/esm/consent/adapters/termly.d.ts +10 -0
- package/dist/esm/consent/adapters/termly.js +58 -0
- package/dist/esm/consent/adapters/usercentrics.d.ts +9 -0
- package/dist/esm/consent/adapters/usercentrics.js +103 -0
- package/dist/esm/consent/conformance.d.ts +22 -0
- package/dist/esm/consent/conformance.js +30 -0
- package/dist/esm/consent/gate.d.ts +23 -0
- package/dist/esm/consent/gate.js +217 -0
- package/dist/esm/consent/port.d.ts +105 -0
- package/dist/esm/consent/port.js +67 -0
- package/dist/esm/consent/registry.d.ts +17 -0
- package/dist/esm/consent/registry.js +55 -0
- package/dist/esm/consent/served.d.ts +15 -0
- package/dist/esm/consent/served.js +22 -0
- package/dist/esm/core.d.ts +77 -0
- package/dist/esm/core.js +60 -0
- package/dist/esm/errors.d.ts +42 -0
- package/dist/esm/errors.generated.d.ts +183 -0
- package/dist/esm/errors.generated.js +231 -0
- package/dist/esm/errors.js +40 -0
- package/dist/esm/generated.d.ts +15146 -0
- package/dist/esm/generated.js +622 -0
- package/dist/esm/index.d.ts +22 -0
- package/dist/esm/index.js +22 -0
- package/dist/esm/mobile.d.ts +66 -0
- package/dist/esm/mobile.js +64 -0
- package/dist/esm/node.d.ts +209 -0
- package/dist/esm/node.js +135 -0
- package/dist/esm/outbox.d.ts +186 -0
- package/dist/esm/outbox.js +316 -0
- package/dist/esm/package.json +3 -0
- package/dist/esm/resources.generated.d.ts +6002 -0
- package/dist/esm/resources.generated.js +2086 -0
- package/dist/esm/served.d.ts +25 -0
- package/dist/esm/served.js +207 -0
- package/dist/esm/sha256.d.ts +2 -0
- package/dist/esm/sha256.js +82 -0
- package/dist/esm/snippet.d.ts +99 -0
- package/dist/esm/snippet.js +210 -0
- package/dist/esm/stripe-events.d.ts +25 -0
- package/dist/esm/stripe-events.js +114 -0
- package/dist/esm/version.d.ts +2 -0
- package/dist/esm/version.js +2 -0
- package/dist/esm/webhooks.d.ts +76 -0
- package/dist/esm/webhooks.js +153 -0
- package/dist/tsconfig.build.tsbuildinfo +1 -0
- package/dist/tsconfig.cjs.tsbuildinfo +1 -0
- package/package.json +105 -4
- package/src/attribution.ts +216 -0
- package/src/browser.ts +107 -0
- package/src/client.ts +351 -0
- package/src/codegen.ts +130 -0
- package/src/consent/adapters/cookiebot.ts +42 -0
- package/src/consent/adapters/cookiemunch.ts +49 -0
- package/src/consent/adapters/custom.ts +37 -0
- package/src/consent/adapters/didomi.ts +59 -0
- package/src/consent/adapters/gcm.ts +68 -0
- package/src/consent/adapters/gpp.ts +81 -0
- package/src/consent/adapters/none.ts +28 -0
- package/src/consent/adapters/onetrust.ts +64 -0
- package/src/consent/adapters/osano.ts +63 -0
- package/src/consent/adapters/tcf.ts +67 -0
- package/src/consent/adapters/termly.ts +54 -0
- package/src/consent/adapters/usercentrics.ts +97 -0
- package/src/consent/conformance.ts +47 -0
- package/src/consent/gate.ts +216 -0
- package/src/consent/port.ts +148 -0
- package/src/consent/registry.ts +60 -0
- package/src/consent/served.ts +24 -0
- package/src/core.ts +127 -0
- package/src/errors.generated.ts +277 -0
- package/src/errors.ts +57 -0
- package/src/generated.ts +14540 -0
- package/src/index.ts +100 -0
- package/src/mobile.ts +96 -0
- package/src/node.ts +291 -0
- package/src/outbox.ts +452 -0
- package/src/resources.generated.ts +2097 -0
- package/src/served.ts +229 -0
- package/src/sha256.ts +82 -0
- package/src/snippet.ts +305 -0
- package/src/stripe-events.ts +130 -0
- package/src/version.ts +2 -0
- package/src/webhooks.ts +207 -0
|
@@ -0,0 +1,130 @@
|
|
|
1
|
+
import type { GenericBillingEvent } from './outbox.js';
|
|
2
|
+
|
|
3
|
+
/** The part of a Stripe event the mapper reads. A `Stripe.Event` fits. */
|
|
4
|
+
export interface StripeEventLike {
|
|
5
|
+
id: string;
|
|
6
|
+
type: string;
|
|
7
|
+
created: number;
|
|
8
|
+
data: { object: object };
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
export interface StripeEventMapOptions {
|
|
12
|
+
/** Your user id for a Stripe customer id, or null when you have none. */
|
|
13
|
+
customerRef: (stripeCustomerId: string) => string | null | undefined | Promise<string | null | undefined>;
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
const idOf = (ref: unknown): string | undefined => (typeof ref === 'string' ? ref : (ref as { id?: string } | null | undefined)?.id) || undefined;
|
|
17
|
+
const unique = (ids: unknown[]) => [...new Set(ids.filter((id): id is string => typeof id === 'string' && id !== ''))];
|
|
18
|
+
|
|
19
|
+
// The address check the API applies: it refuses the whole event on an address it doesn't accept.
|
|
20
|
+
const API_EMAIL = /^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9-]*\.)+[A-Za-z]{2,}$/;
|
|
21
|
+
|
|
22
|
+
/** What each mapped Stripe type becomes, besides the fields they all share. */
|
|
23
|
+
function fieldsOf(type: string, obj: any): Partial<GenericBillingEvent> | null {
|
|
24
|
+
const items: any[] = [...(obj.lines?.data ?? []), ...(obj.items?.data ?? [])];
|
|
25
|
+
const prices: any[] = items.map((l) => l?.price ?? l?.pricing?.price_details ?? l?.plan);
|
|
26
|
+
const catalog = {
|
|
27
|
+
productRef: idOf(prices[0]?.product),
|
|
28
|
+
// So a connection's product filter can match.
|
|
29
|
+
productIds: unique(prices.map((p) => idOf(p?.product))),
|
|
30
|
+
priceIds: unique(prices.map((p) => (typeof p === 'string' ? p : (p?.id ?? p?.price)))),
|
|
31
|
+
};
|
|
32
|
+
switch (type) {
|
|
33
|
+
case 'invoice.paid': {
|
|
34
|
+
// basil moved subscription_details under parent; read both (and the first line's subscription metadata).
|
|
35
|
+
const subscription = obj.parent?.subscription_details ?? obj.subscription_details;
|
|
36
|
+
// The charge behind the invoice, so a later refund or dispute that names only the charge finds it.
|
|
37
|
+
const chargeRef = idOf(obj.charge) ?? idOf(obj.payments?.data?.[0]?.payment?.charge);
|
|
38
|
+
return {
|
|
39
|
+
type: 'invoice_paid',
|
|
40
|
+
subscriptionRef: idOf(obj.subscription) ?? idOf(subscription?.subscription),
|
|
41
|
+
invoiceRef: obj.id,
|
|
42
|
+
amountGross: obj.amount_paid ?? 0,
|
|
43
|
+
tax: obj.tax ?? 0,
|
|
44
|
+
...catalog,
|
|
45
|
+
...(API_EMAIL.test(obj.customer_email ?? '') ? { customerEmail: obj.customer_email } : {}),
|
|
46
|
+
metadata: {
|
|
47
|
+
...obj.lines?.data?.[0]?.metadata,
|
|
48
|
+
...obj.parent?.subscription_details?.metadata,
|
|
49
|
+
...obj.subscription_details?.metadata,
|
|
50
|
+
...obj.metadata,
|
|
51
|
+
expansion: obj.metadata?.expansion === 'true',
|
|
52
|
+
...(chargeRef ? { chargeRef } : {}),
|
|
53
|
+
},
|
|
54
|
+
};
|
|
55
|
+
}
|
|
56
|
+
case 'charge.refunded':
|
|
57
|
+
return {
|
|
58
|
+
type: 'refund',
|
|
59
|
+
// Without an invoice: the payment intent, a one-time Checkout payment's ref.
|
|
60
|
+
invoiceRef: idOf(obj.invoice) ?? idOf(obj.payment_intent),
|
|
61
|
+
// amount_refunded is the charge's running total. The flag makes Referalli reverse only what earlier refunds haven't.
|
|
62
|
+
amountGross: obj.amount_refunded ?? 0,
|
|
63
|
+
metadata: { ...obj.metadata, chargeRef: obj.id, refundCumulative: true },
|
|
64
|
+
};
|
|
65
|
+
case 'charge.dispute.created': {
|
|
66
|
+
const chargeRef = idOf(obj.charge);
|
|
67
|
+
return { type: 'dispute', invoiceRef: idOf(obj.invoice) ?? idOf(obj.payment_intent), amountGross: obj.amount ?? 0, metadata: { ...obj.metadata, ...(chargeRef ? { chargeRef } : {}) } };
|
|
68
|
+
}
|
|
69
|
+
// A one-time Checkout payment with no invoice (`invoice_creation` off): it earns here, never also on invoice.paid.
|
|
70
|
+
case 'checkout.session.completed':
|
|
71
|
+
case 'checkout.session.async_payment_succeeded': {
|
|
72
|
+
if (obj.mode !== 'payment' || obj.payment_status !== 'paid' || obj.invoice) return null;
|
|
73
|
+
// Refunds and disputes name the payment intent, so it is the payment's ref.
|
|
74
|
+
const ref = idOf(obj.payment_intent) ?? obj.id;
|
|
75
|
+
const email = obj.customer_details?.email ?? obj.customer_email;
|
|
76
|
+
return {
|
|
77
|
+
type: 'invoice_paid',
|
|
78
|
+
invoiceRef: ref,
|
|
79
|
+
amountGross: obj.amount_total ?? 0,
|
|
80
|
+
tax: obj.total_details?.amount_tax ?? 0,
|
|
81
|
+
// A guest has no Stripe customer: the app's own id (client_reference_id), else the payment (linked by metadata).
|
|
82
|
+
customerRef: obj.client_reference_id || ref,
|
|
83
|
+
...(API_EMAIL.test(email ?? '') ? { customerEmail: email } : {}),
|
|
84
|
+
metadata: { ...obj.metadata, checkoutSessionRef: obj.id },
|
|
85
|
+
};
|
|
86
|
+
}
|
|
87
|
+
case 'customer.subscription.created':
|
|
88
|
+
return {
|
|
89
|
+
type: 'sub_created',
|
|
90
|
+
subscriptionRef: obj.id,
|
|
91
|
+
mrrDelta: items[0]?.price?.unit_amount ?? 0,
|
|
92
|
+
...catalog,
|
|
93
|
+
// trial is what records a trial conversion and pays a trial bounty.
|
|
94
|
+
metadata: { ...obj.metadata, trial: obj.status === 'trialing' },
|
|
95
|
+
};
|
|
96
|
+
case 'customer.subscription.deleted':
|
|
97
|
+
return { type: 'sub_canceled', subscriptionRef: obj.id, mrrDelta: -(items[0]?.price?.unit_amount ?? 0), ...catalog, metadata: { ...obj.metadata } };
|
|
98
|
+
default:
|
|
99
|
+
return null;
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/**
|
|
104
|
+
* Turn a Stripe event you already received (and verified) into events for a
|
|
105
|
+
* `generic` billing connection. Queue each with `createOutbox`. Other Stripe
|
|
106
|
+
* types return `[]`.
|
|
107
|
+
*
|
|
108
|
+
* A customer `customerRef` has no id for is still sent, under the Stripe id and
|
|
109
|
+
* with `metadata.stripeCustomerUnmapped: true`: the payment is on record and
|
|
110
|
+
* replays once the id is linked, where throwing would lose it after Stripe's
|
|
111
|
+
* retries end.
|
|
112
|
+
*/
|
|
113
|
+
export async function stripeEventToBillingEvents(event: StripeEventLike, options: StripeEventMapOptions): Promise<GenericBillingEvent[]> {
|
|
114
|
+
const obj = event.data.object as any;
|
|
115
|
+
const fields = fieldsOf(event.type, obj);
|
|
116
|
+
if (!fields) return [];
|
|
117
|
+
const stripeCustomer = idOf(obj.customer);
|
|
118
|
+
// A dispute names no customer: Referalli finds it by the charge.
|
|
119
|
+
const mapped = stripeCustomer ? await options.customerRef(stripeCustomer) : undefined;
|
|
120
|
+
return [
|
|
121
|
+
{
|
|
122
|
+
...(fields as Pick<GenericBillingEvent, 'type'>),
|
|
123
|
+
providerEventId: `stripe:${event.id}`,
|
|
124
|
+
customerRef: mapped || stripeCustomer || fields.customerRef,
|
|
125
|
+
currency: obj.currency?.toLowerCase(),
|
|
126
|
+
occurredAt: new Date(event.created * 1000).toISOString(),
|
|
127
|
+
metadata: { ...fields.metadata, ...(stripeCustomer && !mapped ? { stripeCustomerUnmapped: true } : {}) },
|
|
128
|
+
},
|
|
129
|
+
];
|
|
130
|
+
}
|
package/src/version.ts
ADDED
package/src/webhooks.ts
ADDED
|
@@ -0,0 +1,207 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Verify Referalli webhook deliveries (Standard Webhooks: `webhook-id`,
|
|
3
|
+
* `webhook-timestamp`, `webhook-signature: v1,<base64 HMAC-SHA256>`). Use the
|
|
4
|
+
* raw request body exactly as received: re-serialized JSON won't match.
|
|
5
|
+
*
|
|
6
|
+
* `verifyWebhook` / `constructWebhookEvent` are synchronous (plain-JS HMAC, so
|
|
7
|
+
* they run anywhere). `webhooks.verify` / `webhooks.constructEvent` are async
|
|
8
|
+
* and use WebCrypto (falling back to `node:crypto` on Node 18).
|
|
9
|
+
*/
|
|
10
|
+
import { ReferalliError } from './errors.js';
|
|
11
|
+
import type { WebhookPayloads } from './generated.js';
|
|
12
|
+
import { hmacSha256 } from './sha256.js';
|
|
13
|
+
|
|
14
|
+
/** Deliveries signed more than this long ago (or ahead) are rejected. */
|
|
15
|
+
export const WEBHOOK_TOLERANCE_SEC = 300;
|
|
16
|
+
|
|
17
|
+
/** A plain header object (Node, Express) or a fetch `Headers` (Next.js, edge, Deno, Bun). */
|
|
18
|
+
export type WebhookHeaders = Record<string, string | string[] | undefined> | { get(name: string): string | null };
|
|
19
|
+
|
|
20
|
+
export interface VerifyOptions {
|
|
21
|
+
/** Defaults to the current time. */
|
|
22
|
+
now?: Date | number;
|
|
23
|
+
/** Seconds; default 300. */
|
|
24
|
+
toleranceSec?: number;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
export type WebhookFailure = 'missing_headers' | 'timestamp' | 'signature';
|
|
28
|
+
|
|
29
|
+
export class WebhookVerificationError extends ReferalliError {
|
|
30
|
+
override readonly name: string = 'WebhookVerificationError';
|
|
31
|
+
|
|
32
|
+
constructor(
|
|
33
|
+
message: string,
|
|
34
|
+
readonly reason: WebhookFailure = 'signature',
|
|
35
|
+
) {
|
|
36
|
+
super(message);
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/** Every delivery's envelope. `data` is the topic's payload. */
|
|
41
|
+
export interface WebhookEnvelope<Topic extends string = string, Data = Record<string, unknown>> {
|
|
42
|
+
id: string;
|
|
43
|
+
topic: Topic;
|
|
44
|
+
orgId: string;
|
|
45
|
+
livemode?: boolean;
|
|
46
|
+
createdAt: string;
|
|
47
|
+
data: Data;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
type Topics = Extract<keyof WebhookPayloads, string>;
|
|
51
|
+
type EventFor<K extends Topics> = WebhookPayloads[K] extends { topic: unknown; data: unknown } ? WebhookPayloads[K] : WebhookEnvelope<K, WebhookPayloads[K]>;
|
|
52
|
+
|
|
53
|
+
/** A webhook topic (`referral.created`, …), from the OpenAPI document's `webhooks`. */
|
|
54
|
+
export type WebhookTopic = [Topics] extends [never] ? string : Topics;
|
|
55
|
+
/** Any delivery: a union discriminated by `topic`, so `switch (event.topic)` narrows `data`. */
|
|
56
|
+
export type WebhookEvent = [Topics] extends [never] ? WebhookEnvelope : { [K in Topics]: EventFor<K> }[Topics];
|
|
57
|
+
/** The delivery for one topic. */
|
|
58
|
+
export type WebhookEventOf<K extends WebhookTopic> = [Topics] extends [never] ? WebhookEnvelope<K> : Extract<WebhookEvent, { topic: K }>;
|
|
59
|
+
|
|
60
|
+
type RawBody = string | Uint8Array;
|
|
61
|
+
|
|
62
|
+
const enc = new TextEncoder();
|
|
63
|
+
|
|
64
|
+
function header(headers: WebhookHeaders, name: string): string | undefined {
|
|
65
|
+
if (typeof (headers as { get?: unknown }).get === 'function') return (headers as { get(n: string): string | null }).get(name) ?? undefined;
|
|
66
|
+
const h = headers as Record<string, string | string[] | undefined>;
|
|
67
|
+
const v = h[name] ?? h[name.toLowerCase()] ?? Object.entries(h).find(([k]) => k.toLowerCase() === name)?.[1];
|
|
68
|
+
return Array.isArray(v) ? v[0] : v;
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
function fromBase64(s: string): Uint8Array {
|
|
72
|
+
const bin = atob(s);
|
|
73
|
+
const out = new Uint8Array(bin.length);
|
|
74
|
+
for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i);
|
|
75
|
+
return out;
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
function toBase64(bytes: Uint8Array): string {
|
|
79
|
+
let bin = '';
|
|
80
|
+
for (const b of bytes) bin += String.fromCharCode(b);
|
|
81
|
+
return btoa(bin);
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/** The HMAC key a secret stands for: the base64 after `whsec_`, else the raw string. */
|
|
85
|
+
const keyOf = (secret: string): Uint8Array => (secret.startsWith('whsec_') ? fromBase64(secret.slice('whsec_'.length)) : enc.encode(secret));
|
|
86
|
+
|
|
87
|
+
function signedContent(id: string, ts: string, body: RawBody): Uint8Array {
|
|
88
|
+
const prefix = enc.encode(`${id}.${ts}.`);
|
|
89
|
+
const raw = typeof body === 'string' ? enc.encode(body) : body;
|
|
90
|
+
const out = new Uint8Array(prefix.length + raw.length);
|
|
91
|
+
out.set(prefix);
|
|
92
|
+
out.set(raw, prefix.length);
|
|
93
|
+
return out;
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
/** Constant-time string equality (length is not secret). */
|
|
97
|
+
function safeEqual(a: string, b: string): boolean {
|
|
98
|
+
if (a.length !== b.length) return false;
|
|
99
|
+
let diff = 0;
|
|
100
|
+
for (let i = 0; i < a.length; i++) diff |= a.charCodeAt(i) ^ b.charCodeAt(i);
|
|
101
|
+
return diff === 0;
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
interface Parsed {
|
|
105
|
+
id: string;
|
|
106
|
+
ts: string;
|
|
107
|
+
provided: string[];
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
function parse(headers: WebhookHeaders, opts: VerifyOptions): Parsed | WebhookFailure {
|
|
111
|
+
const id = header(headers, 'webhook-id');
|
|
112
|
+
const ts = header(headers, 'webhook-timestamp');
|
|
113
|
+
const sig = header(headers, 'webhook-signature');
|
|
114
|
+
if (!id || !ts || !sig) return 'missing_headers';
|
|
115
|
+
if (!/^\d+$/.test(ts)) return 'timestamp';
|
|
116
|
+
const nowMs = opts.now === undefined ? Date.now() : typeof opts.now === 'number' ? opts.now : opts.now.getTime();
|
|
117
|
+
if (Math.abs(nowMs / 1000 - Number(ts)) > (opts.toleranceSec ?? WEBHOOK_TOLERANCE_SEC)) return 'timestamp';
|
|
118
|
+
return { id, ts, provided: sig.split(' ').filter((p) => p.startsWith('v1,')) };
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
const secretList = (secrets: string | string[]) => (Array.isArray(secrets) ? secrets : [secrets]);
|
|
122
|
+
const text = (body: RawBody) => (typeof body === 'string' ? body : new TextDecoder().decode(body));
|
|
123
|
+
|
|
124
|
+
const failureMessage: Record<WebhookFailure, string> = {
|
|
125
|
+
missing_headers: 'missing webhook-id, webhook-timestamp or webhook-signature header',
|
|
126
|
+
timestamp: 'webhook timestamp is outside the tolerance (replayed or clock skew)',
|
|
127
|
+
signature: 'no webhook signature matches the secret',
|
|
128
|
+
};
|
|
129
|
+
|
|
130
|
+
function checkSync(rawBody: RawBody, headers: WebhookHeaders, secrets: string | string[], opts: VerifyOptions): WebhookFailure | null {
|
|
131
|
+
const p = parse(headers, opts);
|
|
132
|
+
if (typeof p === 'string') return p;
|
|
133
|
+
const content = signedContent(p.id, p.ts, rawBody);
|
|
134
|
+
const ok = secretList(secrets).some((secret) => {
|
|
135
|
+
const expected = `v1,${toBase64(hmacSha256(keyOf(secret), content))}`;
|
|
136
|
+
return p.provided.some((s) => safeEqual(s, expected));
|
|
137
|
+
});
|
|
138
|
+
return ok ? null : 'signature';
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
/**
|
|
142
|
+
* True when `rawBody` was signed by Referalli with one of `secrets` within the
|
|
143
|
+
* tolerance. Pass two secrets while you rotate one. Synchronous; runs anywhere.
|
|
144
|
+
*/
|
|
145
|
+
export function verifyWebhook(rawBody: RawBody, headers: WebhookHeaders, secrets: string | string[], opts: VerifyOptions = {}): boolean {
|
|
146
|
+
return checkSync(rawBody, headers, secrets, opts) === null;
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
/** Verify, then parse the event. Throws `WebhookVerificationError` when the signature or timestamp is wrong. */
|
|
150
|
+
export function constructWebhookEvent<T = WebhookEvent>(rawBody: RawBody, headers: WebhookHeaders, secrets: string | string[], opts: VerifyOptions = {}): T {
|
|
151
|
+
const failure = checkSync(rawBody, headers, secrets, opts);
|
|
152
|
+
if (failure) throw new WebhookVerificationError(failureMessage[failure], failure);
|
|
153
|
+
return JSON.parse(text(rawBody)) as T;
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
// Typed off the global so this compiles with DOM or Node typings.
|
|
157
|
+
type Subtle = typeof globalThis.crypto.subtle;
|
|
158
|
+
type Bytes = Parameters<Subtle['sign']>[2];
|
|
159
|
+
|
|
160
|
+
let subtlePromise: Promise<Subtle> | null = null;
|
|
161
|
+
/** WebCrypto: global on Node 19+, Bun, Deno, edge and browsers; `node:crypto` on Node 18. */
|
|
162
|
+
function subtle(): Promise<Subtle> {
|
|
163
|
+
subtlePromise ??= (async () => {
|
|
164
|
+
const c = (globalThis as { crypto?: { subtle?: Subtle } }).crypto;
|
|
165
|
+
if (c?.subtle) return c.subtle;
|
|
166
|
+
const mod = 'node:crypto';
|
|
167
|
+
const nodeCrypto = (await import(/* webpackIgnore: true */ /* @vite-ignore */ mod)) as { webcrypto: { subtle: Subtle } };
|
|
168
|
+
return nodeCrypto.webcrypto.subtle;
|
|
169
|
+
})();
|
|
170
|
+
return subtlePromise;
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
async function checkAsync(rawBody: RawBody, headers: WebhookHeaders, secrets: string | string[], opts: VerifyOptions): Promise<WebhookFailure | null> {
|
|
174
|
+
const p = parse(headers, opts);
|
|
175
|
+
if (typeof p === 'string') return p;
|
|
176
|
+
const s = await subtle();
|
|
177
|
+
const content = signedContent(p.id, p.ts, rawBody);
|
|
178
|
+
for (const secret of secretList(secrets)) {
|
|
179
|
+
const key = await s.importKey('raw', keyOf(secret) as Bytes, { name: 'HMAC', hash: 'SHA-256' }, false, ['sign']);
|
|
180
|
+
const expected = `v1,${toBase64(new Uint8Array(await s.sign('HMAC', key, content as Bytes)))}`;
|
|
181
|
+
if (p.provided.some((x) => safeEqual(x, expected))) return null;
|
|
182
|
+
}
|
|
183
|
+
return 'signature';
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
/** Async verification and typed event parsing (WebCrypto). Also available as `referalli.webhooks`. */
|
|
187
|
+
export const webhooks = {
|
|
188
|
+
/** True when the delivery is authentic and fresh. */
|
|
189
|
+
async verify(rawBody: RawBody, headers: WebhookHeaders, secrets: string | string[], opts: VerifyOptions = {}): Promise<boolean> {
|
|
190
|
+
return (await checkAsync(rawBody, headers, secrets, opts)) === null;
|
|
191
|
+
},
|
|
192
|
+
|
|
193
|
+
/**
|
|
194
|
+
* Verify the delivery and return the typed event; throws
|
|
195
|
+
* `WebhookVerificationError` (with a `reason`) when it isn't authentic.
|
|
196
|
+
*
|
|
197
|
+
* const event = await webhooks.constructEvent(await req.text(), req.headers, process.env.REFERALLI_WEBHOOK_SECRET!);
|
|
198
|
+
* if (event.topic === 'referral.created') event.data;
|
|
199
|
+
*/
|
|
200
|
+
async constructEvent<T = WebhookEvent>(rawBody: RawBody, headers: WebhookHeaders, secrets: string | string[], opts: VerifyOptions = {}): Promise<T> {
|
|
201
|
+
const failure = await checkAsync(rawBody, headers, secrets, opts);
|
|
202
|
+
if (failure) throw new WebhookVerificationError(failureMessage[failure], failure);
|
|
203
|
+
return JSON.parse(text(rawBody)) as T;
|
|
204
|
+
},
|
|
205
|
+
};
|
|
206
|
+
|
|
207
|
+
export type Webhooks = typeof webhooks;
|