@referalli/sdk 0.0.0-stage → 0.3.21

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.
Files changed (184) hide show
  1. package/CHANGELOG.md +132 -0
  2. package/LICENSE +21 -0
  3. package/README.md +236 -2
  4. package/dist/cjs/attribution.d.ts +105 -0
  5. package/dist/cjs/attribution.js +200 -0
  6. package/dist/cjs/browser.d.ts +41 -0
  7. package/dist/cjs/browser.js +88 -0
  8. package/dist/cjs/client.d.ts +97 -0
  9. package/dist/cjs/client.js +301 -0
  10. package/dist/cjs/consent/adapters/cookiebot.d.ts +7 -0
  11. package/dist/cjs/consent/adapters/cookiebot.js +49 -0
  12. package/dist/cjs/consent/adapters/cookiemunch.d.ts +8 -0
  13. package/dist/cjs/consent/adapters/cookiemunch.js +56 -0
  14. package/dist/cjs/consent/adapters/custom.d.ts +8 -0
  15. package/dist/cjs/consent/adapters/custom.js +39 -0
  16. package/dist/cjs/consent/adapters/didomi.d.ts +9 -0
  17. package/dist/cjs/consent/adapters/didomi.js +67 -0
  18. package/dist/cjs/consent/adapters/gcm.d.ts +10 -0
  19. package/dist/cjs/consent/adapters/gcm.js +78 -0
  20. package/dist/cjs/consent/adapters/gpp.d.ts +9 -0
  21. package/dist/cjs/consent/adapters/gpp.js +92 -0
  22. package/dist/cjs/consent/adapters/none.d.ts +3 -0
  23. package/dist/cjs/consent/adapters/none.js +30 -0
  24. package/dist/cjs/consent/adapters/onetrust.d.ts +8 -0
  25. package/dist/cjs/consent/adapters/onetrust.js +71 -0
  26. package/dist/cjs/consent/adapters/osano.d.ts +9 -0
  27. package/dist/cjs/consent/adapters/osano.js +71 -0
  28. package/dist/cjs/consent/adapters/tcf.d.ts +8 -0
  29. package/dist/cjs/consent/adapters/tcf.js +79 -0
  30. package/dist/cjs/consent/adapters/termly.d.ts +10 -0
  31. package/dist/cjs/consent/adapters/termly.js +61 -0
  32. package/dist/cjs/consent/adapters/usercentrics.d.ts +9 -0
  33. package/dist/cjs/consent/adapters/usercentrics.js +106 -0
  34. package/dist/cjs/consent/conformance.d.ts +22 -0
  35. package/dist/cjs/consent/conformance.js +33 -0
  36. package/dist/cjs/consent/gate.d.ts +23 -0
  37. package/dist/cjs/consent/gate.js +220 -0
  38. package/dist/cjs/consent/port.d.ts +105 -0
  39. package/dist/cjs/consent/port.js +72 -0
  40. package/dist/cjs/consent/registry.d.ts +17 -0
  41. package/dist/cjs/consent/registry.js +61 -0
  42. package/dist/cjs/consent/served.d.ts +15 -0
  43. package/dist/cjs/consent/served.js +26 -0
  44. package/dist/cjs/core.d.ts +77 -0
  45. package/dist/cjs/core.js +64 -0
  46. package/dist/cjs/errors.d.ts +42 -0
  47. package/dist/cjs/errors.generated.d.ts +183 -0
  48. package/dist/cjs/errors.generated.js +279 -0
  49. package/dist/cjs/errors.js +47 -0
  50. package/dist/cjs/generated.d.ts +15151 -0
  51. package/dist/cjs/generated.js +625 -0
  52. package/dist/cjs/index.d.ts +22 -0
  53. package/dist/cjs/index.js +93 -0
  54. package/dist/cjs/mobile.d.ts +66 -0
  55. package/dist/cjs/mobile.js +69 -0
  56. package/dist/cjs/node.d.ts +209 -0
  57. package/dist/cjs/node.js +140 -0
  58. package/dist/cjs/outbox.d.ts +186 -0
  59. package/dist/cjs/outbox.js +324 -0
  60. package/dist/cjs/package.json +3 -0
  61. package/dist/cjs/resources.generated.d.ts +6002 -0
  62. package/dist/cjs/resources.generated.js +2090 -0
  63. package/dist/cjs/served.d.ts +25 -0
  64. package/dist/cjs/served.js +214 -0
  65. package/dist/cjs/sha256.d.ts +2 -0
  66. package/dist/cjs/sha256.js +86 -0
  67. package/dist/cjs/snippet.d.ts +99 -0
  68. package/dist/cjs/snippet.js +213 -0
  69. package/dist/cjs/stripe-events.d.ts +25 -0
  70. package/dist/cjs/stripe-events.js +117 -0
  71. package/dist/cjs/version.d.ts +2 -0
  72. package/dist/cjs/version.js +5 -0
  73. package/dist/cjs/webhooks.d.ts +76 -0
  74. package/dist/cjs/webhooks.js +159 -0
  75. package/dist/esm/attribution.d.ts +105 -0
  76. package/dist/esm/attribution.js +186 -0
  77. package/dist/esm/browser.d.ts +41 -0
  78. package/dist/esm/browser.js +68 -0
  79. package/dist/esm/client.d.ts +97 -0
  80. package/dist/esm/client.js +297 -0
  81. package/dist/esm/consent/adapters/cookiebot.d.ts +7 -0
  82. package/dist/esm/consent/adapters/cookiebot.js +46 -0
  83. package/dist/esm/consent/adapters/cookiemunch.d.ts +8 -0
  84. package/dist/esm/consent/adapters/cookiemunch.js +53 -0
  85. package/dist/esm/consent/adapters/custom.d.ts +8 -0
  86. package/dist/esm/consent/adapters/custom.js +36 -0
  87. package/dist/esm/consent/adapters/didomi.d.ts +9 -0
  88. package/dist/esm/consent/adapters/didomi.js +64 -0
  89. package/dist/esm/consent/adapters/gcm.d.ts +10 -0
  90. package/dist/esm/consent/adapters/gcm.js +75 -0
  91. package/dist/esm/consent/adapters/gpp.d.ts +9 -0
  92. package/dist/esm/consent/adapters/gpp.js +89 -0
  93. package/dist/esm/consent/adapters/none.d.ts +3 -0
  94. package/dist/esm/consent/adapters/none.js +27 -0
  95. package/dist/esm/consent/adapters/onetrust.d.ts +8 -0
  96. package/dist/esm/consent/adapters/onetrust.js +68 -0
  97. package/dist/esm/consent/adapters/osano.d.ts +9 -0
  98. package/dist/esm/consent/adapters/osano.js +68 -0
  99. package/dist/esm/consent/adapters/tcf.d.ts +8 -0
  100. package/dist/esm/consent/adapters/tcf.js +76 -0
  101. package/dist/esm/consent/adapters/termly.d.ts +10 -0
  102. package/dist/esm/consent/adapters/termly.js +58 -0
  103. package/dist/esm/consent/adapters/usercentrics.d.ts +9 -0
  104. package/dist/esm/consent/adapters/usercentrics.js +103 -0
  105. package/dist/esm/consent/conformance.d.ts +22 -0
  106. package/dist/esm/consent/conformance.js +30 -0
  107. package/dist/esm/consent/gate.d.ts +23 -0
  108. package/dist/esm/consent/gate.js +217 -0
  109. package/dist/esm/consent/port.d.ts +105 -0
  110. package/dist/esm/consent/port.js +67 -0
  111. package/dist/esm/consent/registry.d.ts +17 -0
  112. package/dist/esm/consent/registry.js +55 -0
  113. package/dist/esm/consent/served.d.ts +15 -0
  114. package/dist/esm/consent/served.js +22 -0
  115. package/dist/esm/core.d.ts +77 -0
  116. package/dist/esm/core.js +60 -0
  117. package/dist/esm/errors.d.ts +42 -0
  118. package/dist/esm/errors.generated.d.ts +183 -0
  119. package/dist/esm/errors.generated.js +231 -0
  120. package/dist/esm/errors.js +40 -0
  121. package/dist/esm/generated.d.ts +15151 -0
  122. package/dist/esm/generated.js +622 -0
  123. package/dist/esm/index.d.ts +22 -0
  124. package/dist/esm/index.js +22 -0
  125. package/dist/esm/mobile.d.ts +66 -0
  126. package/dist/esm/mobile.js +64 -0
  127. package/dist/esm/node.d.ts +209 -0
  128. package/dist/esm/node.js +135 -0
  129. package/dist/esm/outbox.d.ts +186 -0
  130. package/dist/esm/outbox.js +316 -0
  131. package/dist/esm/package.json +3 -0
  132. package/dist/esm/resources.generated.d.ts +6002 -0
  133. package/dist/esm/resources.generated.js +2086 -0
  134. package/dist/esm/served.d.ts +25 -0
  135. package/dist/esm/served.js +207 -0
  136. package/dist/esm/sha256.d.ts +2 -0
  137. package/dist/esm/sha256.js +82 -0
  138. package/dist/esm/snippet.d.ts +99 -0
  139. package/dist/esm/snippet.js +210 -0
  140. package/dist/esm/stripe-events.d.ts +25 -0
  141. package/dist/esm/stripe-events.js +114 -0
  142. package/dist/esm/version.d.ts +2 -0
  143. package/dist/esm/version.js +2 -0
  144. package/dist/esm/webhooks.d.ts +76 -0
  145. package/dist/esm/webhooks.js +153 -0
  146. package/dist/tsconfig.build.tsbuildinfo +1 -0
  147. package/dist/tsconfig.cjs.tsbuildinfo +1 -0
  148. package/package.json +105 -4
  149. package/src/attribution.ts +216 -0
  150. package/src/browser.ts +107 -0
  151. package/src/client.ts +351 -0
  152. package/src/codegen.ts +130 -0
  153. package/src/consent/adapters/cookiebot.ts +42 -0
  154. package/src/consent/adapters/cookiemunch.ts +49 -0
  155. package/src/consent/adapters/custom.ts +37 -0
  156. package/src/consent/adapters/didomi.ts +59 -0
  157. package/src/consent/adapters/gcm.ts +68 -0
  158. package/src/consent/adapters/gpp.ts +81 -0
  159. package/src/consent/adapters/none.ts +28 -0
  160. package/src/consent/adapters/onetrust.ts +64 -0
  161. package/src/consent/adapters/osano.ts +63 -0
  162. package/src/consent/adapters/tcf.ts +67 -0
  163. package/src/consent/adapters/termly.ts +54 -0
  164. package/src/consent/adapters/usercentrics.ts +97 -0
  165. package/src/consent/conformance.ts +47 -0
  166. package/src/consent/gate.ts +216 -0
  167. package/src/consent/port.ts +148 -0
  168. package/src/consent/registry.ts +60 -0
  169. package/src/consent/served.ts +24 -0
  170. package/src/core.ts +127 -0
  171. package/src/errors.generated.ts +277 -0
  172. package/src/errors.ts +57 -0
  173. package/src/generated.ts +14545 -0
  174. package/src/index.ts +100 -0
  175. package/src/mobile.ts +96 -0
  176. package/src/node.ts +291 -0
  177. package/src/outbox.ts +452 -0
  178. package/src/resources.generated.ts +2097 -0
  179. package/src/served.ts +229 -0
  180. package/src/sha256.ts +82 -0
  181. package/src/snippet.ts +305 -0
  182. package/src/stripe-events.ts +130 -0
  183. package/src/version.ts +2 -0
  184. package/src/webhooks.ts +207 -0
@@ -0,0 +1,25 @@
1
+ import type { GenericBillingEvent } from './outbox.js';
2
+ /** The part of a Stripe event the mapper reads. A `Stripe.Event` fits. */
3
+ export interface StripeEventLike {
4
+ id: string;
5
+ type: string;
6
+ created: number;
7
+ data: {
8
+ 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
+ * Turn a Stripe event you already received (and verified) into events for a
17
+ * `generic` billing connection. Queue each with `createOutbox`. Other Stripe
18
+ * types return `[]`.
19
+ *
20
+ * A customer `customerRef` has no id for is still sent, under the Stripe id and
21
+ * with `metadata.stripeCustomerUnmapped: true`: the payment is on record and
22
+ * replays once the id is linked, where throwing would lose it after Stripe's
23
+ * retries end.
24
+ */
25
+ export declare function stripeEventToBillingEvents(event: StripeEventLike, options: StripeEventMapOptions): Promise<GenericBillingEvent[]>;
@@ -0,0 +1,117 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.stripeEventToBillingEvents = stripeEventToBillingEvents;
4
+ const idOf = (ref) => (typeof ref === 'string' ? ref : ref?.id) || undefined;
5
+ const unique = (ids) => [...new Set(ids.filter((id) => typeof id === 'string' && id !== ''))];
6
+ // The address check the API applies: it refuses the whole event on an address it doesn't accept.
7
+ const API_EMAIL = /^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9-]*\.)+[A-Za-z]{2,}$/;
8
+ /** What each mapped Stripe type becomes, besides the fields they all share. */
9
+ function fieldsOf(type, obj) {
10
+ const items = [...(obj.lines?.data ?? []), ...(obj.items?.data ?? [])];
11
+ const prices = items.map((l) => l?.price ?? l?.pricing?.price_details ?? l?.plan);
12
+ const catalog = {
13
+ productRef: idOf(prices[0]?.product),
14
+ // So a connection's product filter can match.
15
+ productIds: unique(prices.map((p) => idOf(p?.product))),
16
+ priceIds: unique(prices.map((p) => (typeof p === 'string' ? p : (p?.id ?? p?.price)))),
17
+ };
18
+ switch (type) {
19
+ case 'invoice.paid': {
20
+ // basil moved subscription_details under parent; read both (and the first line's subscription metadata).
21
+ const subscription = obj.parent?.subscription_details ?? obj.subscription_details;
22
+ // The charge behind the invoice, so a later refund or dispute that names only the charge finds it.
23
+ const chargeRef = idOf(obj.charge) ?? idOf(obj.payments?.data?.[0]?.payment?.charge);
24
+ return {
25
+ type: 'invoice_paid',
26
+ subscriptionRef: idOf(obj.subscription) ?? idOf(subscription?.subscription),
27
+ invoiceRef: obj.id,
28
+ amountGross: obj.amount_paid ?? 0,
29
+ tax: obj.tax ?? 0,
30
+ ...catalog,
31
+ ...(API_EMAIL.test(obj.customer_email ?? '') ? { customerEmail: obj.customer_email } : {}),
32
+ metadata: {
33
+ ...obj.lines?.data?.[0]?.metadata,
34
+ ...obj.parent?.subscription_details?.metadata,
35
+ ...obj.subscription_details?.metadata,
36
+ ...obj.metadata,
37
+ expansion: obj.metadata?.expansion === 'true',
38
+ ...(chargeRef ? { chargeRef } : {}),
39
+ },
40
+ };
41
+ }
42
+ case 'charge.refunded':
43
+ return {
44
+ type: 'refund',
45
+ // Without an invoice: the payment intent, a one-time Checkout payment's ref.
46
+ invoiceRef: idOf(obj.invoice) ?? idOf(obj.payment_intent),
47
+ // amount_refunded is the charge's running total. The flag makes Referalli reverse only what earlier refunds haven't.
48
+ amountGross: obj.amount_refunded ?? 0,
49
+ metadata: { ...obj.metadata, chargeRef: obj.id, refundCumulative: true },
50
+ };
51
+ case 'charge.dispute.created': {
52
+ const chargeRef = idOf(obj.charge);
53
+ return { type: 'dispute', invoiceRef: idOf(obj.invoice) ?? idOf(obj.payment_intent), amountGross: obj.amount ?? 0, metadata: { ...obj.metadata, ...(chargeRef ? { chargeRef } : {}) } };
54
+ }
55
+ // A one-time Checkout payment with no invoice (`invoice_creation` off): it earns here, never also on invoice.paid.
56
+ case 'checkout.session.completed':
57
+ case 'checkout.session.async_payment_succeeded': {
58
+ if (obj.mode !== 'payment' || obj.payment_status !== 'paid' || obj.invoice)
59
+ return null;
60
+ // Refunds and disputes name the payment intent, so it is the payment's ref.
61
+ const ref = idOf(obj.payment_intent) ?? obj.id;
62
+ const email = obj.customer_details?.email ?? obj.customer_email;
63
+ return {
64
+ type: 'invoice_paid',
65
+ invoiceRef: ref,
66
+ amountGross: obj.amount_total ?? 0,
67
+ tax: obj.total_details?.amount_tax ?? 0,
68
+ // A guest has no Stripe customer: the app's own id (client_reference_id), else the payment (linked by metadata).
69
+ customerRef: obj.client_reference_id || ref,
70
+ ...(API_EMAIL.test(email ?? '') ? { customerEmail: email } : {}),
71
+ metadata: { ...obj.metadata, checkoutSessionRef: obj.id },
72
+ };
73
+ }
74
+ case 'customer.subscription.created':
75
+ return {
76
+ type: 'sub_created',
77
+ subscriptionRef: obj.id,
78
+ mrrDelta: items[0]?.price?.unit_amount ?? 0,
79
+ ...catalog,
80
+ // trial is what records a trial conversion and pays a trial bounty.
81
+ metadata: { ...obj.metadata, trial: obj.status === 'trialing' },
82
+ };
83
+ case 'customer.subscription.deleted':
84
+ return { type: 'sub_canceled', subscriptionRef: obj.id, mrrDelta: -(items[0]?.price?.unit_amount ?? 0), ...catalog, metadata: { ...obj.metadata } };
85
+ default:
86
+ return null;
87
+ }
88
+ }
89
+ /**
90
+ * Turn a Stripe event you already received (and verified) into events for a
91
+ * `generic` billing connection. Queue each with `createOutbox`. Other Stripe
92
+ * types return `[]`.
93
+ *
94
+ * A customer `customerRef` has no id for is still sent, under the Stripe id and
95
+ * with `metadata.stripeCustomerUnmapped: true`: the payment is on record and
96
+ * replays once the id is linked, where throwing would lose it after Stripe's
97
+ * retries end.
98
+ */
99
+ async function stripeEventToBillingEvents(event, options) {
100
+ const obj = event.data.object;
101
+ const fields = fieldsOf(event.type, obj);
102
+ if (!fields)
103
+ return [];
104
+ const stripeCustomer = idOf(obj.customer);
105
+ // A dispute names no customer: Referalli finds it by the charge.
106
+ const mapped = stripeCustomer ? await options.customerRef(stripeCustomer) : undefined;
107
+ return [
108
+ {
109
+ ...fields,
110
+ providerEventId: `stripe:${event.id}`,
111
+ customerRef: mapped || stripeCustomer || fields.customerRef,
112
+ currency: obj.currency?.toLowerCase(),
113
+ occurredAt: new Date(event.created * 1000).toISOString(),
114
+ metadata: { ...fields.metadata, ...(stripeCustomer && !mapped ? { stripeCustomerUnmapped: true } : {}) },
115
+ },
116
+ ];
117
+ }
@@ -0,0 +1,2 @@
1
+ /** This package's version (sent in the user agent). */
2
+ export declare const SDK_VERSION = "0.3.21";
@@ -0,0 +1,5 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.SDK_VERSION = void 0;
4
+ /** This package's version (sent in the user agent). */
5
+ exports.SDK_VERSION = '0.3.21';
@@ -0,0 +1,76 @@
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
+ /** Deliveries signed more than this long ago (or ahead) are rejected. */
13
+ export declare const WEBHOOK_TOLERANCE_SEC = 300;
14
+ /** A plain header object (Node, Express) or a fetch `Headers` (Next.js, edge, Deno, Bun). */
15
+ export type WebhookHeaders = Record<string, string | string[] | undefined> | {
16
+ get(name: string): string | null;
17
+ };
18
+ export interface VerifyOptions {
19
+ /** Defaults to the current time. */
20
+ now?: Date | number;
21
+ /** Seconds; default 300. */
22
+ toleranceSec?: number;
23
+ }
24
+ export type WebhookFailure = 'missing_headers' | 'timestamp' | 'signature';
25
+ export declare class WebhookVerificationError extends ReferalliError {
26
+ readonly reason: WebhookFailure;
27
+ readonly name: string;
28
+ constructor(message: string, reason?: WebhookFailure);
29
+ }
30
+ /** Every delivery's envelope. `data` is the topic's payload. */
31
+ export interface WebhookEnvelope<Topic extends string = string, Data = Record<string, unknown>> {
32
+ id: string;
33
+ topic: Topic;
34
+ orgId: string;
35
+ livemode?: boolean;
36
+ createdAt: string;
37
+ data: Data;
38
+ }
39
+ type Topics = Extract<keyof WebhookPayloads, string>;
40
+ type EventFor<K extends Topics> = WebhookPayloads[K] extends {
41
+ topic: unknown;
42
+ data: unknown;
43
+ } ? WebhookPayloads[K] : WebhookEnvelope<K, WebhookPayloads[K]>;
44
+ /** A webhook topic (`referral.created`, …), from the OpenAPI document's `webhooks`. */
45
+ export type WebhookTopic = [Topics] extends [never] ? string : Topics;
46
+ /** Any delivery: a union discriminated by `topic`, so `switch (event.topic)` narrows `data`. */
47
+ export type WebhookEvent = [Topics] extends [never] ? WebhookEnvelope : {
48
+ [K in Topics]: EventFor<K>;
49
+ }[Topics];
50
+ /** The delivery for one topic. */
51
+ export type WebhookEventOf<K extends WebhookTopic> = [Topics] extends [never] ? WebhookEnvelope<K> : Extract<WebhookEvent, {
52
+ topic: K;
53
+ }>;
54
+ type RawBody = string | Uint8Array;
55
+ /**
56
+ * True when `rawBody` was signed by Referalli with one of `secrets` within the
57
+ * tolerance. Pass two secrets while you rotate one. Synchronous; runs anywhere.
58
+ */
59
+ export declare function verifyWebhook(rawBody: RawBody, headers: WebhookHeaders, secrets: string | string[], opts?: VerifyOptions): boolean;
60
+ /** Verify, then parse the event. Throws `WebhookVerificationError` when the signature or timestamp is wrong. */
61
+ export declare function constructWebhookEvent<T = WebhookEvent>(rawBody: RawBody, headers: WebhookHeaders, secrets: string | string[], opts?: VerifyOptions): T;
62
+ /** Async verification and typed event parsing (WebCrypto). Also available as `referalli.webhooks`. */
63
+ export declare const webhooks: {
64
+ /** True when the delivery is authentic and fresh. */
65
+ verify(rawBody: RawBody, headers: WebhookHeaders, secrets: string | string[], opts?: VerifyOptions): Promise<boolean>;
66
+ /**
67
+ * Verify the delivery and return the typed event; throws
68
+ * `WebhookVerificationError` (with a `reason`) when it isn't authentic.
69
+ *
70
+ * const event = await webhooks.constructEvent(await req.text(), req.headers, process.env.REFERALLI_WEBHOOK_SECRET!);
71
+ * if (event.topic === 'referral.created') event.data;
72
+ */
73
+ constructEvent<T = import("./generated.js").ClickRecordedEvent | import("./generated.js").ReferralCreatedEvent | import("./generated.js").ReferralHeldEvent | import("./generated.js").ReferralApprovedEvent | import("./generated.js").ReferralVoidedEvent | import("./generated.js").ReferralPausedEvent | import("./generated.js").ReferralResumedEvent | import("./generated.js").ReferralReassignedEvent | import("./generated.js").ReferralRejectedEvent | import("./generated.js").CustomerAliasedEvent | import("./generated.js").BillingAccountOwnerChangedEvent | import("./generated.js").CommissionEarnedEvent | import("./generated.js").CommissionReversedEvent | import("./generated.js").CommissionApprovedEvent | import("./generated.js").CommissionSettledEvent | import("./generated.js").PartnerAppliedEvent | import("./generated.js").PartnerEnrolledEvent | import("./generated.js").PartnerApprovedEvent | import("./generated.js").PartnerLevelUpEvent | import("./generated.js").PayoutScheduledEvent | import("./generated.js").PayoutSubmittedEvent | import("./generated.js").PayoutSentEvent | import("./generated.js").PayoutFailedEvent | import("./generated.js").PayoutCancelledEvent | import("./generated.js").TaxFormDeliveredEvent | import("./generated.js").RefereeRewardEarnedEvent | import("./generated.js").RefereeRewardReversedEvent | import("./generated.js").CouponCreatedEvent | import("./generated.js").CreditRedeemedEvent | import("./generated.js").BillingEventRecordedEvent | import("./generated.js").BillingEventHeldEvent | import("./generated.js").BillingEventExpiredEvent | import("./generated.js").RoiPaybackReachedEvent | import("./generated.js").RoiPatternDetectedEvent | import("./generated.js").FraudCaseOpenedEvent | import("./generated.js").DealSubmittedEvent | import("./generated.js").DisputeResolvedEvent | import("./generated.js").PrivacyRequestCompletedEvent | import("./generated.js").ApiKeyExpiringEvent | import("./generated.js").FxRatesUpdatedEvent | import("./generated.js").WebhookEndpointDisabledEvent | import("./generated.js").WebhookEndpointFailingEvent | import("./generated.js").StripeCreditAppliedEvent | import("./generated.js").StripeCreditFailedEvent | import("./generated.js").AccountCreditAppliedEvent | import("./generated.js").AccountCreditReversedEvent | import("./generated.js").AccountCreditFailedEvent | import("./generated.js").WebhookEndpointRecoveredEvent>(rawBody: RawBody, headers: WebhookHeaders, secrets: string | string[], opts?: VerifyOptions): Promise<T>;
74
+ };
75
+ export type Webhooks = typeof webhooks;
76
+ export {};
@@ -0,0 +1,159 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.webhooks = exports.WebhookVerificationError = exports.WEBHOOK_TOLERANCE_SEC = void 0;
4
+ exports.verifyWebhook = verifyWebhook;
5
+ exports.constructWebhookEvent = constructWebhookEvent;
6
+ /**
7
+ * Verify Referalli webhook deliveries (Standard Webhooks: `webhook-id`,
8
+ * `webhook-timestamp`, `webhook-signature: v1,<base64 HMAC-SHA256>`). Use the
9
+ * raw request body exactly as received: re-serialized JSON won't match.
10
+ *
11
+ * `verifyWebhook` / `constructWebhookEvent` are synchronous (plain-JS HMAC, so
12
+ * they run anywhere). `webhooks.verify` / `webhooks.constructEvent` are async
13
+ * and use WebCrypto (falling back to `node:crypto` on Node 18).
14
+ */
15
+ const errors_js_1 = require("./errors.js");
16
+ const sha256_js_1 = require("./sha256.js");
17
+ /** Deliveries signed more than this long ago (or ahead) are rejected. */
18
+ exports.WEBHOOK_TOLERANCE_SEC = 300;
19
+ class WebhookVerificationError extends errors_js_1.ReferalliError {
20
+ reason;
21
+ name = 'WebhookVerificationError';
22
+ constructor(message, reason = 'signature') {
23
+ super(message);
24
+ this.reason = reason;
25
+ }
26
+ }
27
+ exports.WebhookVerificationError = WebhookVerificationError;
28
+ const enc = new TextEncoder();
29
+ function header(headers, name) {
30
+ if (typeof headers.get === 'function')
31
+ return headers.get(name) ?? undefined;
32
+ const h = headers;
33
+ const v = h[name] ?? h[name.toLowerCase()] ?? Object.entries(h).find(([k]) => k.toLowerCase() === name)?.[1];
34
+ return Array.isArray(v) ? v[0] : v;
35
+ }
36
+ function fromBase64(s) {
37
+ const bin = atob(s);
38
+ const out = new Uint8Array(bin.length);
39
+ for (let i = 0; i < bin.length; i++)
40
+ out[i] = bin.charCodeAt(i);
41
+ return out;
42
+ }
43
+ function toBase64(bytes) {
44
+ let bin = '';
45
+ for (const b of bytes)
46
+ bin += String.fromCharCode(b);
47
+ return btoa(bin);
48
+ }
49
+ /** The HMAC key a secret stands for: the base64 after `whsec_`, else the raw string. */
50
+ const keyOf = (secret) => (secret.startsWith('whsec_') ? fromBase64(secret.slice('whsec_'.length)) : enc.encode(secret));
51
+ function signedContent(id, ts, body) {
52
+ const prefix = enc.encode(`${id}.${ts}.`);
53
+ const raw = typeof body === 'string' ? enc.encode(body) : body;
54
+ const out = new Uint8Array(prefix.length + raw.length);
55
+ out.set(prefix);
56
+ out.set(raw, prefix.length);
57
+ return out;
58
+ }
59
+ /** Constant-time string equality (length is not secret). */
60
+ function safeEqual(a, b) {
61
+ if (a.length !== b.length)
62
+ return false;
63
+ let diff = 0;
64
+ for (let i = 0; i < a.length; i++)
65
+ diff |= a.charCodeAt(i) ^ b.charCodeAt(i);
66
+ return diff === 0;
67
+ }
68
+ function parse(headers, opts) {
69
+ const id = header(headers, 'webhook-id');
70
+ const ts = header(headers, 'webhook-timestamp');
71
+ const sig = header(headers, 'webhook-signature');
72
+ if (!id || !ts || !sig)
73
+ return 'missing_headers';
74
+ if (!/^\d+$/.test(ts))
75
+ return 'timestamp';
76
+ const nowMs = opts.now === undefined ? Date.now() : typeof opts.now === 'number' ? opts.now : opts.now.getTime();
77
+ if (Math.abs(nowMs / 1000 - Number(ts)) > (opts.toleranceSec ?? exports.WEBHOOK_TOLERANCE_SEC))
78
+ return 'timestamp';
79
+ return { id, ts, provided: sig.split(' ').filter((p) => p.startsWith('v1,')) };
80
+ }
81
+ const secretList = (secrets) => (Array.isArray(secrets) ? secrets : [secrets]);
82
+ const text = (body) => (typeof body === 'string' ? body : new TextDecoder().decode(body));
83
+ const failureMessage = {
84
+ missing_headers: 'missing webhook-id, webhook-timestamp or webhook-signature header',
85
+ timestamp: 'webhook timestamp is outside the tolerance (replayed or clock skew)',
86
+ signature: 'no webhook signature matches the secret',
87
+ };
88
+ function checkSync(rawBody, headers, secrets, opts) {
89
+ const p = parse(headers, opts);
90
+ if (typeof p === 'string')
91
+ return p;
92
+ const content = signedContent(p.id, p.ts, rawBody);
93
+ const ok = secretList(secrets).some((secret) => {
94
+ const expected = `v1,${toBase64((0, sha256_js_1.hmacSha256)(keyOf(secret), content))}`;
95
+ return p.provided.some((s) => safeEqual(s, expected));
96
+ });
97
+ return ok ? null : 'signature';
98
+ }
99
+ /**
100
+ * True when `rawBody` was signed by Referalli with one of `secrets` within the
101
+ * tolerance. Pass two secrets while you rotate one. Synchronous; runs anywhere.
102
+ */
103
+ function verifyWebhook(rawBody, headers, secrets, opts = {}) {
104
+ return checkSync(rawBody, headers, secrets, opts) === null;
105
+ }
106
+ /** Verify, then parse the event. Throws `WebhookVerificationError` when the signature or timestamp is wrong. */
107
+ function constructWebhookEvent(rawBody, headers, secrets, opts = {}) {
108
+ const failure = checkSync(rawBody, headers, secrets, opts);
109
+ if (failure)
110
+ throw new WebhookVerificationError(failureMessage[failure], failure);
111
+ return JSON.parse(text(rawBody));
112
+ }
113
+ let subtlePromise = null;
114
+ /** WebCrypto: global on Node 19+, Bun, Deno, edge and browsers; `node:crypto` on Node 18. */
115
+ function subtle() {
116
+ subtlePromise ??= (async () => {
117
+ const c = globalThis.crypto;
118
+ if (c?.subtle)
119
+ return c.subtle;
120
+ const mod = 'node:crypto';
121
+ const nodeCrypto = (await Promise.resolve(`${mod}`).then(s => require(s)));
122
+ return nodeCrypto.webcrypto.subtle;
123
+ })();
124
+ return subtlePromise;
125
+ }
126
+ async function checkAsync(rawBody, headers, secrets, opts) {
127
+ const p = parse(headers, opts);
128
+ if (typeof p === 'string')
129
+ return p;
130
+ const s = await subtle();
131
+ const content = signedContent(p.id, p.ts, rawBody);
132
+ for (const secret of secretList(secrets)) {
133
+ const key = await s.importKey('raw', keyOf(secret), { name: 'HMAC', hash: 'SHA-256' }, false, ['sign']);
134
+ const expected = `v1,${toBase64(new Uint8Array(await s.sign('HMAC', key, content)))}`;
135
+ if (p.provided.some((x) => safeEqual(x, expected)))
136
+ return null;
137
+ }
138
+ return 'signature';
139
+ }
140
+ /** Async verification and typed event parsing (WebCrypto). Also available as `referalli.webhooks`. */
141
+ exports.webhooks = {
142
+ /** True when the delivery is authentic and fresh. */
143
+ async verify(rawBody, headers, secrets, opts = {}) {
144
+ return (await checkAsync(rawBody, headers, secrets, opts)) === null;
145
+ },
146
+ /**
147
+ * Verify the delivery and return the typed event; throws
148
+ * `WebhookVerificationError` (with a `reason`) when it isn't authentic.
149
+ *
150
+ * const event = await webhooks.constructEvent(await req.text(), req.headers, process.env.REFERALLI_WEBHOOK_SECRET!);
151
+ * if (event.topic === 'referral.created') event.data;
152
+ */
153
+ async constructEvent(rawBody, headers, secrets, opts = {}) {
154
+ const failure = await checkAsync(rawBody, headers, secrets, opts);
155
+ if (failure)
156
+ throw new WebhookVerificationError(failureMessage[failure], failure);
157
+ return JSON.parse(text(rawBody));
158
+ },
159
+ };
@@ -0,0 +1,105 @@
1
+ /**
2
+ * The first-party referral context, shared by the browser tracker (`aff.js`,
3
+ * `referalli/browser`) and the server kits (`@referalli/next`,
4
+ * `@referalli/express`): what it is, how a landing URL updates it, and how it
5
+ * is stored in a cookie on the merchant's own domain. Isomorphic and
6
+ * dependency-free.
7
+ */
8
+ /** Cookie (and localStorage key) holding the context. A wire name shared with every `aff.js` install; don't change it. */
9
+ export declare const REFERRAL_COOKIE = "referalli_ctx";
10
+ /**
11
+ * The pre-rename name of the same context. The browser tracker (`aff.js`,
12
+ * `referalli/browser`) writes the context under BOTH names, with the same
13
+ * value, attributes and expiry, and reads either.
14
+ *
15
+ * Why: integrations that read the cookie themselves may still read the pre-rename
16
+ * name. Atlas's connector and Cookie Munch's preset both read `referalli_ctx` now.
17
+ * The twin is written until 2027-01-31, announced in the changelog and on
18
+ * /docs/renamed-from-referally, then dropped (reading stays tolerant).
19
+ *
20
+ * TODO(legacy-ctx, 2027-01-31): stop writing the legacy name; keep reading it for
21
+ * one more cookie window after that.
22
+ */
23
+ export declare const LEGACY_REFERRAL_COOKIE = "referally_ctx";
24
+ /** Every name the context is written and read under, current first. */
25
+ export declare const REFERRAL_COOKIE_NAMES: readonly string[];
26
+ /** Query parameters that carry a partner's referral code, in priority order. */
27
+ export declare const REFERRAL_PARAMS: readonly string[];
28
+ /** Query parameter carrying a click id from a Referalli redirect link (`/go/...`). */
29
+ export declare const CLICK_ID_PARAM = "ref_click_id";
30
+ export declare const DEFAULT_COOKIE_DAYS = 60;
31
+ export interface ReferralContext {
32
+ /** This browser's anonymous id (`a_…`). */
33
+ anonId: string;
34
+ /** The partner's referral code from `?via=` / `?ref=` / `?aff=`. */
35
+ code: string | null;
36
+ /** The click id from a redirect link. */
37
+ clickId: string | null;
38
+ /** When the context was first created (epoch ms). */
39
+ ts: number;
40
+ }
41
+ /** The stored shape: the context plus when it expires (epoch ms). */
42
+ export type StoredReferral = ReferralContext & {
43
+ exp?: number;
44
+ };
45
+ export interface MergeOptions {
46
+ now?: number;
47
+ /** Lifetime, 1–400 days. Default 60. */
48
+ cookieDays?: number;
49
+ /** Keep an unexpired first referral instead of replacing it. */
50
+ firstTouch?: boolean;
51
+ randomId?: () => string;
52
+ }
53
+ export declare const clampDays: (days: number | undefined) => number;
54
+ /** A fresh anonymous id: `a_` + 20 random base-36 characters. */
55
+ export declare function newAnonId(): string;
56
+ /** The referral a URL carries: the first of `params` that is set, and `ref_click_id`. */
57
+ export declare function referralFromUrl(url: string | URL, params?: readonly string[]): {
58
+ code: string | null;
59
+ clickId: string | null;
60
+ };
61
+ /** Parse a stored context (the cookie's or localStorage's value, URI-encoded or not). Expired or malformed → null. */
62
+ export declare function parseReferral(raw: string | null | undefined, now?: number): StoredReferral | null;
63
+ /**
64
+ * The context from a `Cookie` request header. `names` are tried in order
65
+ * (default: `REFERRAL_COOKIE_NAMES`, the current name then the legacy one);
66
+ * add an older cookie name to keep reading contexts saved under it.
67
+ */
68
+ export declare function referralFromCookieHeader(cookieHeader: string | null | undefined, now?: number, names?: readonly string[]): StoredReferral | null;
69
+ /**
70
+ * The context after a page view: a new referral in the URL replaces the
71
+ * stored one (unless `firstTouch` keeps an unexpired one), and a referral
72
+ * restarts the expiry window. Same rules as `aff.js`.
73
+ */
74
+ export declare function mergeReferral(stored: StoredReferral | null, fromUrl: {
75
+ code: string | null;
76
+ clickId: string | null;
77
+ }, opts?: MergeOptions): StoredReferral;
78
+ export interface CookieOptions {
79
+ cookieDays?: number;
80
+ /** Share with subdomains, e.g. `.example.com`. */
81
+ domain?: string;
82
+ /** Default true. Turn off only for plain-http local development. */
83
+ secure?: boolean;
84
+ }
85
+ /**
86
+ * A `Set-Cookie` header value for the context. Not HttpOnly on purpose: the
87
+ * browser tracker reads the same cookie.
88
+ */
89
+ export declare function serializeReferralCookie(ctx: StoredReferral, opts?: CookieOptions): string;
90
+ /**
91
+ * `Set-Cookie` values for the context under every name: `referalli_ctx` and
92
+ * its legacy twin `referally_ctx`, same value, attributes and expiry (see
93
+ * LEGACY_REFERRAL_COOKIE). Server kits append each one.
94
+ */
95
+ export declare function serializeReferralCookies(ctx: StoredReferral, opts?: CookieOptions): string[];
96
+ /** `Set-Cookie` values that delete the context under every name (consent denied or withdrawn). */
97
+ export declare function clearReferralCookies(opts?: Pick<CookieOptions, 'domain' | 'secure'>): string[];
98
+ /** Fields for `associate` (server-side attribution at signup) from a context. */
99
+ export declare function associateFields(ctx: ReferralContext | null | undefined): {
100
+ anonId?: string;
101
+ referralToken?: string;
102
+ couponCode?: string;
103
+ };
104
+ /** SHA-256 hex of a normalised (trimmed, lower-cased) email, for `emailHash` (WebCrypto). */
105
+ export declare function hashEmail(email: string): Promise<string>;