@tofound/billing 0.0.0-stage → 0.2.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.
Files changed (100) hide show
  1. package/CHANGELOG.md +122 -0
  2. package/LICENSE +3 -0
  3. package/README.md +79 -2
  4. package/dist/catalog/catalog.d.ts +115 -0
  5. package/dist/catalog/catalog.js +201 -0
  6. package/dist/domain/errors.d.ts +14 -0
  7. package/dist/domain/errors.js +21 -0
  8. package/dist/domain/money.d.ts +21 -0
  9. package/dist/domain/money.js +77 -0
  10. package/dist/domain/types.d.ts +167 -0
  11. package/dist/domain/types.js +18 -0
  12. package/dist/drizzle/index.d.ts +5 -0
  13. package/dist/drizzle/index.js +5 -0
  14. package/dist/drizzle/schema-factory.d.ts +586 -0
  15. package/dist/drizzle/schema-factory.js +206 -0
  16. package/dist/drizzle/store.d.ts +20 -0
  17. package/dist/drizzle/store.js +124 -0
  18. package/dist/entitlement/resolve.d.ts +76 -0
  19. package/dist/entitlement/resolve.js +122 -0
  20. package/dist/inbox/apply.d.ts +48 -0
  21. package/dist/inbox/apply.js +299 -0
  22. package/dist/inbox/conformance.d.ts +20 -0
  23. package/dist/inbox/conformance.js +254 -0
  24. package/dist/inbox/drizzle.d.ts +14 -0
  25. package/dist/inbox/drizzle.js +203 -0
  26. package/dist/inbox/ingest.d.ts +108 -0
  27. package/dist/inbox/ingest.js +404 -0
  28. package/dist/inbox/memory.d.ts +13 -0
  29. package/dist/inbox/memory.js +172 -0
  30. package/dist/inbox/ports.d.ts +150 -0
  31. package/dist/inbox/ports.js +1 -0
  32. package/dist/inbox/redact.d.ts +2 -0
  33. package/dist/inbox/redact.js +47 -0
  34. package/dist/inbox/schema.d.ts +1158 -0
  35. package/dist/inbox/schema.js +90 -0
  36. package/dist/inbox/watermark.d.ts +13 -0
  37. package/dist/inbox/watermark.js +6 -0
  38. package/dist/index.d.ts +30 -0
  39. package/dist/index.js +27 -0
  40. package/dist/ledger/ledger.d.ts +47 -0
  41. package/dist/ledger/ledger.js +224 -0
  42. package/dist/ports/index.d.ts +2 -0
  43. package/dist/ports/index.js +1 -0
  44. package/dist/ports/ledger-store.d.ts +53 -0
  45. package/dist/ports/ledger-store.js +1 -0
  46. package/dist/ports/runtime.d.ts +9 -0
  47. package/dist/ports/runtime.js +1 -0
  48. package/dist/providers/polar/events.d.ts +17 -0
  49. package/dist/providers/polar/events.js +213 -0
  50. package/dist/providers/polar/index.d.ts +50 -0
  51. package/dist/providers/polar/index.js +271 -0
  52. package/dist/providers/polar/signature.d.ts +23 -0
  53. package/dist/providers/polar/signature.js +52 -0
  54. package/dist/providers/port.d.ts +207 -0
  55. package/dist/providers/port.js +30 -0
  56. package/dist/providers/sepay/index.d.ts +34 -0
  57. package/dist/providers/sepay/index.js +241 -0
  58. package/dist/providers/sepay/order.d.ts +32 -0
  59. package/dist/providers/sepay/order.js +69 -0
  60. package/dist/providers/sepay/signature.d.ts +8 -0
  61. package/dist/providers/sepay/signature.js +51 -0
  62. package/dist/quote/conformance.d.ts +16 -0
  63. package/dist/quote/conformance.js +39 -0
  64. package/dist/quote/index.d.ts +3 -0
  65. package/dist/quote/index.js +3 -0
  66. package/dist/quote/steps.d.ts +54 -0
  67. package/dist/quote/steps.js +103 -0
  68. package/dist/quote/waterfall.d.ts +98 -0
  69. package/dist/quote/waterfall.js +82 -0
  70. package/dist/renewal/renewal.d.ts +69 -0
  71. package/dist/renewal/renewal.js +198 -0
  72. package/dist/stores/conformance.d.ts +22 -0
  73. package/dist/stores/conformance.js +269 -0
  74. package/dist/stores/memory.d.ts +19 -0
  75. package/dist/stores/memory.js +137 -0
  76. package/dist/stores/testing.d.ts +13 -0
  77. package/dist/stores/testing.js +13 -0
  78. package/dist/terms/conformance.d.ts +17 -0
  79. package/dist/terms/conformance.js +198 -0
  80. package/dist/terms/decide.d.ts +97 -0
  81. package/dist/terms/decide.js +176 -0
  82. package/dist/terms/drizzle.d.ts +12 -0
  83. package/dist/terms/drizzle.js +131 -0
  84. package/dist/terms/memory.d.ts +23 -0
  85. package/dist/terms/memory.js +126 -0
  86. package/dist/terms/plans.d.ts +85 -0
  87. package/dist/terms/plans.js +331 -0
  88. package/dist/terms/ports.d.ts +55 -0
  89. package/dist/terms/ports.js +1 -0
  90. package/dist/terms/rules.d.ts +11 -0
  91. package/dist/terms/rules.js +36 -0
  92. package/dist/terms/schema.d.ts +711 -0
  93. package/dist/terms/schema.js +70 -0
  94. package/dist/terms/snapshot.d.ts +20 -0
  95. package/dist/terms/snapshot.js +134 -0
  96. package/dist/terms/types.d.ts +85 -0
  97. package/dist/terms/types.js +4 -0
  98. package/docs/API.md +417 -0
  99. package/docs/SCHEMA.md +163 -0
  100. package/package.json +80 -4
@@ -0,0 +1,213 @@
1
+ const rec = (value) => value && typeof value === 'object' && !Array.isArray(value) ? value : null;
2
+ const str = (value) => (typeof value === 'string' && value.length > 0 ? value : null);
3
+ /** A non-negative safe-integer minor amount from a number or digit string. */
4
+ function minor(value) {
5
+ const n = typeof value === 'number' ? value : typeof value === 'string' && /^\d+$/.test(value) ? Number(value) : NaN;
6
+ return Number.isSafeInteger(n) && n >= 0 ? n : null;
7
+ }
8
+ function date(value) {
9
+ const raw = str(value);
10
+ if (!raw)
11
+ return null;
12
+ const parsed = new Date(raw);
13
+ return Number.isNaN(parsed.getTime()) ? null : parsed;
14
+ }
15
+ /** Payload values are keys here: never let `constructor` or `__proto__` resolve an inherited member. */
16
+ const own = (map, key) => (Object.hasOwn(map, key) ? map[key] : undefined);
17
+ const CURRENCIES = { USD: 'USD', VND: 'VND' };
18
+ /** The provider's watermark: when Polar last changed the object, else when it was created or sent. */
19
+ export function occurredAtOf(envelope, fallback) {
20
+ const { data } = envelope;
21
+ return date(data['modified_at']) ?? date(data['created_at']) ?? date(envelope.timestamp) ?? fallback;
22
+ }
23
+ /** The server-issued external customer id (design §4.1). */
24
+ export function externalCustomerOf(data) {
25
+ return str(rec(data['customer'])?.['external_id']) ?? str(data['external_customer_id']);
26
+ }
27
+ const productIdOf = (data) => str(rec(data['product'])?.['id']) ?? str(data['product_id']);
28
+ function checkoutRefOf(data, options) {
29
+ const ref = str(rec(data['metadata'])?.['checkout_id']);
30
+ return ref && options.checkoutPattern.test(ref) ? ref : null;
31
+ }
32
+ function moneyOf(currencyRaw, amountMinor, rawAmount) {
33
+ const currency = own(CURRENCIES, (str(currencyRaw) ?? '').toUpperCase());
34
+ if (!currency)
35
+ return { ok: false, event: { kind: 'needs_review', reason: 'invalid_currency', detail: { currency: currencyRaw ?? null } } };
36
+ if (amountMinor === null)
37
+ return { ok: false, event: { kind: 'needs_review', reason: 'invalid_amount', detail: { amount: rawAmount ?? null } } };
38
+ return { ok: true, money: { currency, amountMinor } };
39
+ }
40
+ /**
41
+ * What the merchant charged for the product: the price the catalog defines,
42
+ * after discounts, before tax — `subtotal_amount − discount_amount`, the one
43
+ * basis that reads the same whatever the tax behaviour. `net_amount` and
44
+ * `total_amount` move with it: a tax-inclusive order of a 500 pack has
45
+ * `net_amount` 420 and `tax_amount` 80, a tax-exclusive one `total_amount`
46
+ * 540. A discounted or re-priced order still fails the inbox's exact-amount
47
+ * guard instead of crediting a full pack.
48
+ */
49
+ function orderAmount(data) {
50
+ const subtotal = minor(data['subtotal_amount']);
51
+ const discount = data['discount_amount'] == null ? 0 : minor(data['discount_amount']);
52
+ // An unreadable discount must not fall through to the gross amount.
53
+ const amount = subtotal !== null && discount !== null && subtotal >= discount ? subtotal - discount : null;
54
+ return moneyOf(data['currency'], amount, data['subtotal_amount']);
55
+ }
56
+ const isSubscriptionOrder = (data) => {
57
+ const reason = str(data['billing_reason']);
58
+ return str(data['subscription_id']) !== null || (reason !== null && reason !== 'purchase');
59
+ };
60
+ function orderEvent(envelope, occurredAt, options) {
61
+ const { type, data } = envelope;
62
+ if (type === 'order.created' || type === 'order.updated')
63
+ return { kind: 'ignored', reason: 'no_money_moved' };
64
+ if (type !== 'order.paid' && type !== 'order.refunded')
65
+ return { kind: 'ignored', reason: `unhandled_type:${type}` };
66
+ if (isSubscriptionOrder(data)) {
67
+ // Receipts of a subscription; access comes and goes with `subscription.*`.
68
+ return { kind: 'ignored', reason: type === 'order.paid' ? 'subscription_order' : 'subscription_order_refund' };
69
+ }
70
+ const orderId = str(data['id']);
71
+ if (!orderId)
72
+ return { kind: 'needs_review', reason: 'missing_order_id' };
73
+ const amount = orderAmount(data);
74
+ if (!amount.ok)
75
+ return amount.event;
76
+ const checkoutRef = checkoutRefOf(data, options);
77
+ if (type === 'order.refunded') {
78
+ const status = str(data['status']);
79
+ if (status !== 'refunded') {
80
+ // `refunded_amount` is a running total; a partial refund against a pack
81
+ // has no agreed credit amount to take back.
82
+ return {
83
+ kind: 'needs_review',
84
+ reason: status === 'partially_refunded' ? 'partial_refund' : `refund_status:${status ?? 'none'}`,
85
+ detail: { refundedAmount: data['refunded_amount'] ?? null },
86
+ };
87
+ }
88
+ return {
89
+ kind: 'purchase.reversed',
90
+ externalId: orderId,
91
+ reason: 'refund',
92
+ ...(checkoutRef ? { checkoutRef } : {}),
93
+ amount: amount.money,
94
+ occurredAt,
95
+ };
96
+ }
97
+ const customer = externalCustomerOf(data);
98
+ const account = customer
99
+ ? { kind: 'polar_customer_external_id', value: customer }
100
+ : checkoutRef
101
+ ? { kind: 'checkout', value: checkoutRef }
102
+ : null;
103
+ if (!account)
104
+ return { kind: 'needs_review', reason: 'unbound_order' };
105
+ const productId = productIdOf(data);
106
+ return {
107
+ kind: 'purchase.completed',
108
+ account,
109
+ externalId: orderId,
110
+ productRef: (productId && own(options.products, productId)) ?? null,
111
+ quantity: 1,
112
+ amount: amount.money,
113
+ ...(checkoutRef ? { checkoutRef } : {}),
114
+ occurredAt,
115
+ };
116
+ }
117
+ /**
118
+ * Same-instant precedence, lowest first: the later a type stands here, the
119
+ * more it says about the one change they share (a revoke outranks the
120
+ * `updated` that carries the same state). Unknown types rank lowest.
121
+ */
122
+ const TIE_ORDER = [
123
+ 'subscription.created',
124
+ 'subscription.updated',
125
+ 'subscription.active',
126
+ 'subscription.past_due',
127
+ 'subscription.uncanceled',
128
+ 'subscription.canceled',
129
+ 'subscription.paused',
130
+ 'subscription.revoked',
131
+ ];
132
+ const GRANTING = new Set(['active', 'trialing']);
133
+ const DUNNING = new Set(['past_due', 'unpaid']);
134
+ function subscriptionEvent(envelope, occurredAt, options) {
135
+ const { type, data } = envelope;
136
+ const customer = externalCustomerOf(data);
137
+ if (!customer)
138
+ return { kind: 'ignored', reason: 'no_external_customer' };
139
+ const externalId = str(data['id']);
140
+ if (!externalId)
141
+ return { kind: 'needs_review', reason: 'missing_subscription_id' };
142
+ const productId = productIdOf(data);
143
+ const planRef = productId ? own(options.products, productId) : undefined;
144
+ if (!planRef)
145
+ return { kind: 'ignored', reason: 'unknown_product' };
146
+ const providerStatus = str(data['status'])?.toLowerCase() ?? null;
147
+ const endedAt = date(data['ended_at']);
148
+ let status;
149
+ if (type === 'subscription.revoked' || type === 'subscription.paused' || providerStatus === 'paused')
150
+ status = 'revoked';
151
+ else if (!providerStatus)
152
+ return { kind: 'ignored', reason: 'missing_status' };
153
+ else if (GRANTING.has(providerStatus))
154
+ status = 'active';
155
+ else if (DUNNING.has(providerStatus))
156
+ status = 'past_due';
157
+ else if (providerStatus === 'canceled')
158
+ status = endedAt && endedAt.getTime() <= occurredAt.getTime() ? 'expired' : 'active';
159
+ else
160
+ return { kind: 'ignored', reason: `unhandled_status:${providerStatus}` };
161
+ // A revocation ends access whatever the payload says about periods.
162
+ const revokedAt = status === 'revoked' ? occurredAt : null;
163
+ const periodStart = date(data['current_period_start']) ?? date(data['started_at']) ?? revokedAt;
164
+ const currentEnd = date(data['current_period_end']);
165
+ // An ended subscription's period stops when it ended, not when it would have renewed.
166
+ const periodEnd = currentEnd && endedAt ? (endedAt < currentEnd ? endedAt : currentEnd) : (currentEnd ?? endedAt ?? revokedAt);
167
+ if (!periodStart || !periodEnd)
168
+ return { kind: 'needs_review', reason: 'missing_period' };
169
+ const cancelAtPeriodEnd = type !== 'subscription.uncanceled' &&
170
+ (type === 'subscription.canceled' || providerStatus === 'canceled' || data['cancel_at_period_end'] === true);
171
+ const live = status === 'active' || status === 'past_due';
172
+ let price;
173
+ if (data['amount'] != null || data['currency'] != null) {
174
+ const amount = moneyOf(data['currency'], minor(data['amount']), data['amount']);
175
+ if (!amount.ok)
176
+ return amount.event;
177
+ price = amount.money;
178
+ }
179
+ return {
180
+ kind: 'subscription.snapshot',
181
+ account: { kind: 'polar_customer_external_id', value: customer },
182
+ externalId,
183
+ planRef,
184
+ status,
185
+ periodStart,
186
+ periodEnd,
187
+ autoRenew: live && !cancelAtPeriodEnd,
188
+ cancelAtPeriodEnd: live && cancelAtPeriodEnd,
189
+ ...(price ? { price } : {}),
190
+ occurredAt,
191
+ tieBreak: String(TIE_ORDER.indexOf(type) + 1),
192
+ };
193
+ }
194
+ function checkoutEvent(envelope, options) {
195
+ // Only sessions we created carry our id; anything else is not ours to track.
196
+ const checkoutRef = checkoutRefOf(envelope.data, options);
197
+ if (!checkoutRef)
198
+ return { kind: 'ignored', reason: 'foreign_checkout' };
199
+ const status = str(envelope.data['status']);
200
+ if (!status)
201
+ return { kind: 'ignored', reason: 'missing_status' };
202
+ return { kind: 'checkout.status', checkoutRef, status };
203
+ }
204
+ export function normalizePolarEvent(envelope, occurredAt, options) {
205
+ const { type } = envelope;
206
+ if (type.startsWith('subscription.'))
207
+ return subscriptionEvent(envelope, occurredAt, options);
208
+ if (type.startsWith('order.'))
209
+ return orderEvent(envelope, occurredAt, options);
210
+ if (type.startsWith('checkout.'))
211
+ return checkoutEvent(envelope, options);
212
+ return { kind: 'ignored', reason: `unhandled_type:${type}` };
213
+ }
@@ -0,0 +1,50 @@
1
+ import { type CheckoutCapable, type CheckoutRedirect, type CheckoutRequest, type IngestOutcome, type PortalCapable, type ProviderAdapter, type ProviderEnvironment, type ProviderResponse } from '../port.js';
2
+ export { POLAR_WEBHOOK_ID_HEADER, POLAR_WEBHOOK_SIGNATURE_HEADER, POLAR_WEBHOOK_TIMESTAMP_HEADER, POLAR_WEBHOOK_TOLERANCE_SECONDS, signPolarWebhook, type PolarKeyDerivation, } from './signature.js';
3
+ /**
4
+ * 2Novel's two-switch arming, made explicit: production needs both the
5
+ * requested environment and the arming flag. Unlike the host copy, an unset
6
+ * or unknown environment is refused rather than defaulted to sandbox, and an
7
+ * unarmed production refuses here instead of on the first charge.
8
+ */
9
+ export declare function resolvePolarEnvironment(input: {
10
+ environment: string | null | undefined;
11
+ productionEnabled: boolean;
12
+ }): ProviderEnvironment;
13
+ export interface PolarAdapterOptions {
14
+ /** Required. Resolve the host's switches with `resolvePolarEnvironment`. */
15
+ environment: ProviderEnvironment;
16
+ /** Accepted webhook secrets (`whsec_…`); more than one only while rotating. */
17
+ webhookSecrets: readonly string[];
18
+ /** Polar product id → catalog productRef, for this environment's products. */
19
+ products: Readonly<Record<string, string>>;
20
+ /** Organization access token; needed for checkout and portal, not for webhooks. */
21
+ accessToken?: string;
22
+ /** Our checkout session ids as carried in `metadata.checkout_id`. Default: UUID. */
23
+ checkoutPattern?: RegExp;
24
+ /** Replay window in seconds. Default 300. */
25
+ toleranceSec?: number;
26
+ /** Wall clock for the replay window. Default `new Date()`. */
27
+ clock?: () => Date;
28
+ fetch?: typeof fetch;
29
+ /** API timeout. Default 10 s. */
30
+ timeoutMs?: number;
31
+ }
32
+ /** A checkout request; Polar uses the buyer's IP for tax country when the host has it. */
33
+ export interface PolarCheckoutRequest extends CheckoutRequest {
34
+ customerIpAddress?: string | null;
35
+ }
36
+ export interface PolarAdapter extends ProviderAdapter, CheckoutCapable, PortalCapable {
37
+ readonly id: 'polar';
38
+ createCheckout(req: PolarCheckoutRequest): Promise<CheckoutRedirect>;
39
+ }
40
+ /** A Polar API call failed. Never carries the token or the response body. */
41
+ export declare class PolarApiError extends Error {
42
+ readonly name = "PolarApiError";
43
+ readonly code: 'polar_unreachable' | 'polar_error' | 'polar_bad_response' | 'polar_price_mismatch';
44
+ readonly status: number | null;
45
+ constructor(code: PolarApiError['code'], message: string, status?: number | null);
46
+ }
47
+ export declare function redactPolarPayload(payload: unknown): unknown;
48
+ export declare function createPolarAdapter(options: PolarAdapterOptions): PolarAdapter;
49
+ /** Polar retries any non-2xx; acknowledge everything a retry cannot change. */
50
+ export declare function respondPolar(outcome: IngestOutcome): ProviderResponse;
@@ -0,0 +1,271 @@
1
+ /**
2
+ * Polar adapter (`@tofound/billing/providers/polar`), ported from 2Novel
3
+ * `lib/polar.ts` and `billing/polar-{signature,events}.ts`:
4
+ * - the environment is required — no sandbox default, no inference; 2Novel's
5
+ * two switches (`POLAR_ENV` + `POLAR_PRODUCTION_ENABLED`) become one value
6
+ * through `resolvePolarEnvironment`, which refuses an unarmed production;
7
+ * - Standard Webhooks verification before any parse, both secret
8
+ * derivations, a rotation list and a 300 s replay window;
9
+ * - subscription events → `subscription.snapshot` (the terms layer maps and
10
+ * price-checks them), one-time orders → `purchase.completed` bound to our
11
+ * checkout session, full refunds → `purchase.reversed`.
12
+ * No SDK, no env reads, no logging; errors never carry the token or a
13
+ * provider response body.
14
+ */
15
+ import { redactPayload } from '../../inbox/redact.js';
16
+ import { ProviderConfigError, VerifyError, } from '../port.js';
17
+ import { externalCustomerOf, normalizePolarEvent, occurredAtOf } from './events.js';
18
+ import { POLAR_WEBHOOK_ID_HEADER, POLAR_WEBHOOK_SIGNATURE_HEADER, POLAR_WEBHOOK_TIMESTAMP_HEADER, POLAR_WEBHOOK_TOLERANCE_SECONDS, polarSignatureMatches, } from './signature.js';
19
+ export { POLAR_WEBHOOK_ID_HEADER, POLAR_WEBHOOK_SIGNATURE_HEADER, POLAR_WEBHOOK_TIMESTAMP_HEADER, POLAR_WEBHOOK_TOLERANCE_SECONDS, signPolarWebhook, } from './signature.js';
20
+ const API_BASE = {
21
+ production: 'https://api.polar.sh/v1',
22
+ sandbox: 'https://sandbox-api.polar.sh/v1',
23
+ };
24
+ const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
25
+ /** Header and body bounds; past them the delivery is refused, not stored. */
26
+ const MAX_WEBHOOK_ID = 128;
27
+ const MAX_EVENT_TYPE = 64;
28
+ const stateless = (pattern) => new RegExp(pattern.source, pattern.flags.replace(/[gy]/g, ''));
29
+ /**
30
+ * 2Novel's two-switch arming, made explicit: production needs both the
31
+ * requested environment and the arming flag. Unlike the host copy, an unset
32
+ * or unknown environment is refused rather than defaulted to sandbox, and an
33
+ * unarmed production refuses here instead of on the first charge.
34
+ */
35
+ export function resolvePolarEnvironment(input) {
36
+ const requested = input.environment?.trim().toLowerCase();
37
+ if (requested === 'sandbox')
38
+ return 'sandbox';
39
+ if (requested === 'production') {
40
+ if (input.productionEnabled !== true) {
41
+ throw new ProviderConfigError('polar_production_disabled', 'Polar production requested but not armed (productionEnabled)');
42
+ }
43
+ return 'production';
44
+ }
45
+ throw new ProviderConfigError('polar_environment_required', 'Polar environment must be passed explicitly: production | sandbox');
46
+ }
47
+ /** A Polar API call failed. Never carries the token or the response body. */
48
+ export class PolarApiError extends Error {
49
+ name = 'PolarApiError';
50
+ code;
51
+ status;
52
+ constructor(code, message, status = null) {
53
+ super(message);
54
+ this.code = code;
55
+ this.status = status;
56
+ }
57
+ }
58
+ /** Polar-specific personal data the generic redaction does not name. */
59
+ const POLAR_SENSITIVE_KEYS = new Set(['tax_id', 'custom_field_data', 'avatar_url', 'customer_ip_address']);
60
+ /**
61
+ * A Polar credential inside a value: a checkout's `url` embeds its client
62
+ * secret (`…/checkout/polar_c_…`); the same shape covers the other prefixed
63
+ * secrets (`polar_cst_`, `polar_oat_` …).
64
+ */
65
+ const POLAR_SECRET_RE = /\bpolar_([a-z]{1,4})_[A-Za-z0-9]{16,}/g;
66
+ function dropPolarSensitive(value) {
67
+ if (Array.isArray(value))
68
+ return value.map(dropPolarSensitive);
69
+ if (value && typeof value === 'object') {
70
+ const out = {};
71
+ for (const [key, inner] of Object.entries(value))
72
+ if (!POLAR_SENSITIVE_KEYS.has(key))
73
+ out[key] = dropPolarSensitive(inner);
74
+ return out;
75
+ }
76
+ if (typeof value === 'string')
77
+ return value.replace(POLAR_SECRET_RE, 'polar_$1_[redacted]');
78
+ return value;
79
+ }
80
+ export function redactPolarPayload(payload) {
81
+ return dropPolarSensitive(redactPayload(payload));
82
+ }
83
+ const httpsUrl = (value) => {
84
+ if (typeof value !== 'string')
85
+ return null;
86
+ try {
87
+ return new URL(value).protocol === 'https:' ? value : null;
88
+ }
89
+ catch {
90
+ return null;
91
+ }
92
+ };
93
+ export function createPolarAdapter(options) {
94
+ const { environment } = options;
95
+ if (environment !== 'production' && environment !== 'sandbox') {
96
+ throw new ProviderConfigError('polar_environment_required', 'Polar environment must be passed explicitly: production | sandbox');
97
+ }
98
+ const secrets = options.webhookSecrets.filter((secret) => secret.length > 0);
99
+ if (secrets.length === 0)
100
+ throw new ProviderConfigError('polar_webhook_secrets_required', 'at least one Polar webhook secret is required');
101
+ const tolerance = options.toleranceSec ?? POLAR_WEBHOOK_TOLERANCE_SECONDS;
102
+ if (!Number.isFinite(tolerance) || tolerance <= 0)
103
+ throw new ProviderConfigError('polar_invalid_tolerance', 'toleranceSec must be positive');
104
+ const products = { ...options.products };
105
+ const normalizeOptions = { products, checkoutPattern: stateless(options.checkoutPattern ?? UUID_RE) };
106
+ const clock = options.clock ?? (() => new Date());
107
+ const fetchImpl = options.fetch ?? globalThis.fetch;
108
+ const timeoutMs = options.timeoutMs ?? 10_000;
109
+ function productIdFor(productRef) {
110
+ if (!productRef)
111
+ return null;
112
+ const matches = Object.keys(products).filter((id) => products[id] === productRef);
113
+ return matches.length === 1 ? matches[0] : null;
114
+ }
115
+ async function call(path, body) {
116
+ if (!options.accessToken) {
117
+ throw new ProviderConfigError('polar_not_configured', 'a Polar access token is required for checkout and portal sessions');
118
+ }
119
+ let response;
120
+ try {
121
+ response = await fetchImpl(`${API_BASE[environment]}${path}`, {
122
+ method: 'POST',
123
+ headers: { Authorization: `Bearer ${options.accessToken}`, 'Content-Type': 'application/json' },
124
+ body: JSON.stringify(body),
125
+ signal: AbortSignal.timeout(timeoutMs),
126
+ });
127
+ }
128
+ catch {
129
+ throw new PolarApiError('polar_unreachable', 'Polar API unreachable');
130
+ }
131
+ if (!response.ok)
132
+ throw new PolarApiError('polar_error', `Polar API answered ${response.status}`, response.status);
133
+ let parsed;
134
+ try {
135
+ parsed = await response.json();
136
+ }
137
+ catch {
138
+ throw new PolarApiError('polar_bad_response', 'Polar API answered non-JSON', response.status);
139
+ }
140
+ if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {
141
+ throw new PolarApiError('polar_bad_response', 'Polar API answered an unexpected body', response.status);
142
+ }
143
+ return parsed;
144
+ }
145
+ const adapter = {
146
+ id: 'polar',
147
+ environment,
148
+ async verify(req) {
149
+ const id = req.headers.get(POLAR_WEBHOOK_ID_HEADER);
150
+ const timestamp = req.headers.get(POLAR_WEBHOOK_TIMESTAMP_HEADER);
151
+ const signature = req.headers.get(POLAR_WEBHOOK_SIGNATURE_HEADER);
152
+ if (!id || !timestamp || !signature)
153
+ throw new VerifyError('unauthorized', 'Polar webhook headers missing');
154
+ if (id.length > MAX_WEBHOOK_ID || !/^\d{1,12}$/.test(timestamp))
155
+ throw new VerifyError('unauthorized', 'Polar webhook headers invalid');
156
+ if (Math.abs(clock().getTime() / 1000 - Number(timestamp)) > tolerance) {
157
+ throw new VerifyError('unauthorized', 'Polar webhook timestamp outside the replay window');
158
+ }
159
+ if (!polarSignatureMatches(signature, secrets, id, timestamp, req.rawBody)) {
160
+ throw new VerifyError('unauthorized', 'Polar webhook signature mismatch');
161
+ }
162
+ let body;
163
+ try {
164
+ body = JSON.parse(req.rawBody);
165
+ }
166
+ catch {
167
+ throw new VerifyError('malformed', 'Polar webhook body is not JSON');
168
+ }
169
+ const envelope = body;
170
+ if (!envelope ||
171
+ typeof envelope !== 'object' ||
172
+ Array.isArray(envelope) ||
173
+ typeof envelope.type !== 'string' ||
174
+ envelope.type.length === 0 ||
175
+ envelope.type.length > MAX_EVENT_TYPE ||
176
+ !envelope.data ||
177
+ typeof envelope.data !== 'object' ||
178
+ Array.isArray(envelope.data)) {
179
+ throw new VerifyError('malformed', 'Polar webhook body is not an event envelope');
180
+ }
181
+ const customer = externalCustomerOf(envelope.data);
182
+ return {
183
+ provider: 'polar',
184
+ environment,
185
+ // The webhook id is stable across Polar's retries of one message.
186
+ eventId: `polar:${id}`,
187
+ eventType: envelope.type,
188
+ occurredAt: occurredAtOf(envelope, req.receivedAt),
189
+ payload: body,
190
+ ...(customer ? { subjectRef: customer } : {}),
191
+ };
192
+ },
193
+ async normalize(delivery) {
194
+ const envelope = delivery.payload;
195
+ return [normalizePolarEvent({ ...envelope, type: delivery.eventType, data: envelope.data ?? {} }, delivery.occurredAt, normalizeOptions)];
196
+ },
197
+ respond: respondPolar,
198
+ redact: redactPolarPayload,
199
+ async createCheckout(req) {
200
+ const productId = productIdFor(req.productRef);
201
+ if (!productId)
202
+ throw new ProviderConfigError('polar_unknown_product', 'checkout productRef maps to no single Polar product');
203
+ if (!Number.isSafeInteger(req.amount.amountMinor) || req.amount.amountMinor <= 0) {
204
+ throw new ProviderConfigError('polar_invalid_amount', 'Polar charges a positive whole minor amount');
205
+ }
206
+ // The session id is how the order finds its way back: one the webhook
207
+ // would not recognise must never be charged.
208
+ if (!normalizeOptions.checkoutPattern.test(req.sessionId)) {
209
+ throw new ProviderConfigError('polar_invalid_checkout_id', 'checkout session id does not match the adapter checkoutPattern');
210
+ }
211
+ const raw = await call('/checkouts/', {
212
+ products: [productId],
213
+ external_customer_id: req.accountId,
214
+ ...(req.customerIpAddress ? { customer_ip_address: req.customerIpAddress } : {}),
215
+ // Polar copies metadata onto the resulting order.
216
+ metadata: { checkout_id: req.sessionId },
217
+ // A discount code would make the order's amount differ from the
218
+ // session's catalog amount: the buyer pays and the purchase is parked
219
+ // for review. Discounts belong in the catalog, not on the pay page.
220
+ allow_discount_codes: false,
221
+ success_url: req.successUrl,
222
+ return_url: req.cancelUrl,
223
+ });
224
+ const url = httpsUrl(raw['url']);
225
+ if (typeof raw['id'] !== 'string' || !url)
226
+ throw new PolarApiError('polar_bad_response', 'Polar returned no checkout url');
227
+ // The catalog is the price authority: a dashboard product priced
228
+ // differently is refused before anyone can pay it. A checkout's
229
+ // `amount` is the product price before discount and tax; its
230
+ // `net_amount` drops by the tax once a tax-inclusive country is known,
231
+ // so it is no price signal.
232
+ const currency = typeof raw['currency'] === 'string' ? raw['currency'].toUpperCase() : '';
233
+ const discount = raw['discount_amount'] ?? 0;
234
+ if (currency !== req.amount.currency || raw['amount'] !== req.amount.amountMinor || discount !== 0) {
235
+ throw new PolarApiError('polar_price_mismatch', 'Polar product price differs from the catalog amount');
236
+ }
237
+ return { kind: 'redirect', url };
238
+ },
239
+ async createPortalSession(account, returnUrl) {
240
+ if (account.kind !== 'polar_customer_external_id' && account.kind !== 'account_id') {
241
+ throw new ProviderConfigError('polar_unsupported_account', 'a Polar portal needs the external customer id');
242
+ }
243
+ const raw = await call('/customer-sessions/', { external_customer_id: account.value, return_url: returnUrl });
244
+ const url = httpsUrl(raw['customer_portal_url']);
245
+ if (!url)
246
+ throw new PolarApiError('polar_bad_response', 'Polar returned no customer portal url');
247
+ return { url };
248
+ },
249
+ };
250
+ return adapter;
251
+ }
252
+ const json = (status, body) => ({
253
+ status,
254
+ headers: { 'content-type': 'application/json' },
255
+ body: JSON.stringify(body),
256
+ });
257
+ /** Polar retries any non-2xx; acknowledge everything a retry cannot change. */
258
+ export function respondPolar(outcome) {
259
+ if (outcome.relay)
260
+ return outcome.relay;
261
+ switch (outcome.status) {
262
+ case 'unauthorized':
263
+ return json(401, { error: 'Unauthorized' });
264
+ case 'malformed':
265
+ return json(400, { error: 'Invalid payload' });
266
+ case 'failed':
267
+ return json(500, { error: 'Internal error' });
268
+ default:
269
+ return json(200, { received: true, outcome: outcome.status, ...(outcome.reason ? { reason: outcome.reason } : {}) });
270
+ }
271
+ }
@@ -0,0 +1,23 @@
1
+ /**
2
+ * Standard Webhooks, as Polar signs its deliveries (ported from 2Novel
3
+ * `billing/polar-signature.ts`). Signed content is
4
+ * `${webhook-id}.${webhook-timestamp}.${rawBody}`; the signature header is a
5
+ * space-delimited list of `v1,<base64 HMAC-SHA256>` entries. The raw body is
6
+ * what was signed, so verification runs before any JSON parse.
7
+ */
8
+ export declare const POLAR_WEBHOOK_ID_HEADER = "webhook-id";
9
+ export declare const POLAR_WEBHOOK_TIMESTAMP_HEADER = "webhook-timestamp";
10
+ export declare const POLAR_WEBHOOK_SIGNATURE_HEADER = "webhook-signature";
11
+ /** Standard Webhooks' replay window; dedup on the webhook id makes a late retry harmless. */
12
+ export declare const POLAR_WEBHOOK_TOLERANCE_SECONDS = 300;
13
+ /**
14
+ * `standard` is the base64 payload after `whsec_` (Standard Webhooks; Polar
15
+ * secrets since its 2026-09-08 cutover); `legacy` is the UTF-8 bytes of the
16
+ * whole secret string (older Polar secrets). Both are accepted, so a rotation
17
+ * across the cutover never silently drops deliveries.
18
+ */
19
+ export type PolarKeyDerivation = 'standard' | 'legacy';
20
+ /** The `v1,<base64>` entry Polar would send — for host tests and fixtures. */
21
+ export declare function signPolarWebhook(secret: string, id: string, timestamp: string, rawBody: string, derivation?: PolarKeyDerivation): string;
22
+ /** Constant-time match of any presented `v1` signature against any accepted secret and derivation. */
23
+ export declare function polarSignatureMatches(header: string, secrets: readonly string[], id: string, timestamp: string, rawBody: string): boolean;
@@ -0,0 +1,52 @@
1
+ import { createHmac, timingSafeEqual } from 'node:crypto';
2
+ /**
3
+ * Standard Webhooks, as Polar signs its deliveries (ported from 2Novel
4
+ * `billing/polar-signature.ts`). Signed content is
5
+ * `${webhook-id}.${webhook-timestamp}.${rawBody}`; the signature header is a
6
+ * space-delimited list of `v1,<base64 HMAC-SHA256>` entries. The raw body is
7
+ * what was signed, so verification runs before any JSON parse.
8
+ */
9
+ export const POLAR_WEBHOOK_ID_HEADER = 'webhook-id';
10
+ export const POLAR_WEBHOOK_TIMESTAMP_HEADER = 'webhook-timestamp';
11
+ export const POLAR_WEBHOOK_SIGNATURE_HEADER = 'webhook-signature';
12
+ /** Standard Webhooks' replay window; dedup on the webhook id makes a late retry harmless. */
13
+ export const POLAR_WEBHOOK_TOLERANCE_SECONDS = 300;
14
+ const PREFIX = 'whsec_';
15
+ function deriveKey(secret, derivation) {
16
+ if (derivation === 'legacy')
17
+ return Buffer.from(secret, 'utf8');
18
+ if (!secret.startsWith(PREFIX))
19
+ return null;
20
+ const decoded = Buffer.from(secret.slice(PREFIX.length), 'base64');
21
+ return decoded.length > 0 ? decoded : null;
22
+ }
23
+ /** Every key a secret may sign with: its UTF-8 bytes, and its decoded payload when it has the prefix. */
24
+ const signingKeys = (secret) => ['legacy', 'standard'].map((d) => deriveKey(secret, d)).filter((key) => key !== null);
25
+ const hmac = (key, content) => createHmac('sha256', key).update(content).digest();
26
+ /** The `v1,<base64>` entry Polar would send — for host tests and fixtures. */
27
+ export function signPolarWebhook(secret, id, timestamp, rawBody, derivation = 'standard') {
28
+ const key = deriveKey(secret, derivation) ?? Buffer.from(secret, 'utf8');
29
+ return `v1,${hmac(key, `${id}.${timestamp}.${rawBody}`).toString('base64')}`;
30
+ }
31
+ /** Constant-time match of any presented `v1` signature against any accepted secret and derivation. */
32
+ export function polarSignatureMatches(header, secrets, id, timestamp, rawBody) {
33
+ const presented = header
34
+ .split(' ')
35
+ .map((entry) => entry.trim())
36
+ .filter((entry) => entry.startsWith('v1,'))
37
+ .map((entry) => Buffer.from(entry.slice(3), 'base64'))
38
+ .filter((sig) => sig.length > 0);
39
+ if (presented.length === 0)
40
+ return false;
41
+ const content = `${id}.${timestamp}.${rawBody}`;
42
+ let ok = false;
43
+ for (const secret of secrets) {
44
+ for (const key of signingKeys(secret)) {
45
+ const want = hmac(key, content);
46
+ for (const sig of presented)
47
+ if (sig.length === want.length && timingSafeEqual(sig, want))
48
+ ok = true;
49
+ }
50
+ }
51
+ return ok;
52
+ }