@tofound/billing 0.1.0 → 1.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +136 -1
- package/README.md +73 -13
- package/dist/catalog/catalog.d.ts +115 -0
- package/dist/catalog/catalog.js +201 -0
- package/dist/domain/types.d.ts +3 -1
- package/dist/drizzle/index.d.ts +2 -0
- package/dist/drizzle/index.js +2 -0
- package/dist/entitlement/resolve.d.ts +76 -0
- package/dist/entitlement/resolve.js +122 -0
- package/dist/hostkit/adjustments.d.ts +65 -0
- package/dist/hostkit/adjustments.js +84 -0
- package/dist/hostkit/index.d.ts +9 -0
- package/dist/hostkit/index.js +9 -0
- package/dist/hostkit/legacy-ledger.d.ts +87 -0
- package/dist/hostkit/legacy-ledger.js +111 -0
- package/dist/hostkit/quote-wire.d.ts +73 -0
- package/dist/hostkit/quote-wire.js +50 -0
- package/dist/index.d.ts +10 -0
- package/dist/index.js +9 -0
- package/dist/providers/apple/events.d.ts +24 -0
- package/dist/providers/apple/events.js +232 -0
- package/dist/providers/apple/index.d.ts +54 -0
- package/dist/providers/apple/index.js +231 -0
- package/dist/providers/apple/jws.d.ts +50 -0
- package/dist/providers/apple/jws.js +206 -0
- package/dist/providers/google/api.d.ts +57 -0
- package/dist/providers/google/api.js +226 -0
- package/dist/providers/google/events.d.ts +46 -0
- package/dist/providers/google/events.js +135 -0
- package/dist/providers/google/index.d.ts +37 -0
- package/dist/providers/google/index.js +228 -0
- package/dist/providers/polar/events.d.ts +17 -0
- package/dist/providers/polar/events.js +213 -0
- package/dist/providers/polar/index.d.ts +50 -0
- package/dist/providers/polar/index.js +271 -0
- package/dist/providers/polar/signature.d.ts +23 -0
- package/dist/providers/polar/signature.js +52 -0
- package/dist/providers/port.d.ts +6 -0
- package/dist/providers/sepay/index.js +29 -0
- package/dist/renewal/renewal.d.ts +69 -0
- package/dist/renewal/renewal.js +198 -0
- package/dist/stores/testing.d.ts +4 -2
- package/dist/stores/testing.js +4 -2
- package/dist/terms/conformance.d.ts +17 -0
- package/dist/terms/conformance.js +198 -0
- package/dist/terms/decide.d.ts +97 -0
- package/dist/terms/decide.js +176 -0
- package/dist/terms/drizzle.d.ts +12 -0
- package/dist/terms/drizzle.js +131 -0
- package/dist/terms/memory.d.ts +23 -0
- package/dist/terms/memory.js +126 -0
- package/dist/terms/plans.d.ts +85 -0
- package/dist/terms/plans.js +331 -0
- package/dist/terms/ports.d.ts +55 -0
- package/dist/terms/ports.js +1 -0
- package/dist/terms/rules.d.ts +11 -0
- package/dist/terms/rules.js +36 -0
- package/dist/terms/schema.d.ts +711 -0
- package/dist/terms/schema.js +70 -0
- package/dist/terms/snapshot.d.ts +20 -0
- package/dist/terms/snapshot.js +134 -0
- package/dist/terms/types.d.ts +85 -0
- package/dist/terms/types.js +4 -0
- package/docs/API.md +415 -6
- package/docs/MIGRATION-LOHI.md +237 -0
- package/docs/SCHEMA.md +57 -2
- package/package.json +22 -1
|
@@ -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
|
+
}
|
package/dist/providers/port.d.ts
CHANGED
|
@@ -54,6 +54,12 @@ export interface SubscriptionSnapshotEvent {
|
|
|
54
54
|
nextPlanRef?: string;
|
|
55
55
|
price?: Money;
|
|
56
56
|
occurredAt: Date;
|
|
57
|
+
/**
|
|
58
|
+
* Orders snapshots stamped with the same `occurredAt` (one provider change
|
|
59
|
+
* sent as several events): the greater key wins, the event id settles the
|
|
60
|
+
* rest. Compared as strings; an adapter keeps its keys one width.
|
|
61
|
+
*/
|
|
62
|
+
tieBreak?: string;
|
|
57
63
|
}
|
|
58
64
|
export interface PurchaseCompletedEvent {
|
|
59
65
|
kind: 'purchase.completed';
|
|
@@ -13,6 +13,7 @@
|
|
|
13
13
|
* byte-compatible with `sepay-pg-node@1.0.0`.
|
|
14
14
|
*/
|
|
15
15
|
import { createHash } from 'node:crypto';
|
|
16
|
+
import { redactPayload } from '../../inbox/redact.js';
|
|
16
17
|
import { ProviderConfigError, VerifyError, } from '../port.js';
|
|
17
18
|
import { createSepayOrderClient, parseVnd } from './order.js';
|
|
18
19
|
import { signCheckoutFields, webhookKeyMatches } from './signature.js';
|
|
@@ -110,6 +111,7 @@ export function createSepayAdapter(options) {
|
|
|
110
111
|
return [normalizeIpn(delivery.payload, delivery.occurredAt, invoicePattern)];
|
|
111
112
|
},
|
|
112
113
|
respond: respondSepay,
|
|
114
|
+
redact: redactSepayPayload,
|
|
113
115
|
async createCheckout(req) {
|
|
114
116
|
const credentials = merchant();
|
|
115
117
|
if (req.amount.currency !== 'VND' || !Number.isSafeInteger(req.amount.amountMinor) || req.amount.amountMinor <= 0) {
|
|
@@ -157,6 +159,20 @@ export function createSepayAdapter(options) {
|
|
|
157
159
|
};
|
|
158
160
|
return adapter;
|
|
159
161
|
}
|
|
162
|
+
/** SePay's buyer browser fingerprint; not personal data by key name, so the generic redaction keeps it. */
|
|
163
|
+
const USER_AGENT_KEY = /^user_?agent$/i;
|
|
164
|
+
/** The generic inbox redaction, minus `user_agent` (on `order` today) at any depth. */
|
|
165
|
+
function redactSepayPayload(payload) {
|
|
166
|
+
return dropUserAgent(redactPayload(payload));
|
|
167
|
+
}
|
|
168
|
+
function dropUserAgent(value) {
|
|
169
|
+
if (Array.isArray(value))
|
|
170
|
+
return value.map(dropUserAgent);
|
|
171
|
+
if (value && typeof value === 'object') {
|
|
172
|
+
return Object.fromEntries(Object.entries(value).filter(([key]) => !USER_AGENT_KEY.test(key)).map(([key, inner]) => [key, dropUserAgent(inner)]));
|
|
173
|
+
}
|
|
174
|
+
return value;
|
|
175
|
+
}
|
|
160
176
|
/** `TRANSACTION_VOID` wins over capture fields; an untyped body counts as paid only when CAPTURED (Lohi). */
|
|
161
177
|
function eventTypeOf(body) {
|
|
162
178
|
const type = typeof body.notification_type === 'string' ? body.notification_type : '';
|
|
@@ -193,6 +209,13 @@ function normalizeIpn(body, occurredAt, invoicePattern) {
|
|
|
193
209
|
const amount = parseVnd(order.order_amount);
|
|
194
210
|
if (amount === null)
|
|
195
211
|
return { kind: 'needs_review', reason: 'invalid_amount', detail: { amount: order.order_amount ?? null } };
|
|
212
|
+
// The money that moved must be the order's: a transaction amount that
|
|
213
|
+
// disagrees is never settled (or reversed) on either figure. Only a void may
|
|
214
|
+
// report its movement as negative.
|
|
215
|
+
const paid = body.transaction?.transaction_amount;
|
|
216
|
+
if (paid !== undefined && paid !== null && (isVoid ? magnitudeVnd(paid) : parseVnd(paid)) !== amount) {
|
|
217
|
+
return { kind: 'needs_review', reason: 'amount_mismatch', detail: { orderAmount: order.order_amount ?? null, transactionAmount: paid } };
|
|
218
|
+
}
|
|
196
219
|
const orderId = typeof order.order_id === 'string' && order.order_id ? order.order_id : null;
|
|
197
220
|
if (isVoid) {
|
|
198
221
|
// A void must name the captured order it reverses (Lohi `dispatchSepayVoid`).
|
|
@@ -219,6 +242,12 @@ function normalizeIpn(body, occurredAt, invoicePattern) {
|
|
|
219
242
|
occurredAt,
|
|
220
243
|
};
|
|
221
244
|
}
|
|
245
|
+
/** `parseVnd` of the amount's magnitude, so a void reported as a negative movement still matches. */
|
|
246
|
+
function magnitudeVnd(raw) {
|
|
247
|
+
if (typeof raw === 'number')
|
|
248
|
+
return parseVnd(Math.abs(raw));
|
|
249
|
+
return typeof raw === 'string' ? parseVnd(raw.trim().replace(/^-/, '')) : null;
|
|
250
|
+
}
|
|
222
251
|
const json = (status, body) => ({
|
|
223
252
|
status,
|
|
224
253
|
headers: { 'content-type': 'application/json' },
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Renewal of credit-bought months (design §4.9, §4.10, D9). The trigger is
|
|
3
|
+
* the host's (2Novel: an interval under `pg_try_advisory_lock`; Lohi: the
|
|
4
|
+
* admin `renew-due`); this module is what each run does:
|
|
5
|
+
*
|
|
6
|
+
* - an auto-renewing term at its period end is charged the **live** catalog
|
|
7
|
+
* price of `nextPlanKey ?? planKey` for `intervalMonths`, keyed
|
|
8
|
+
* `renew:<termId>:<previous periodEnd ISO>` — a double run debits once;
|
|
9
|
+
* - a short balance (or a plan no longer sold for credits) makes it
|
|
10
|
+
* `past_due` with `graceUntil = periodEnd + graceDays`; it stays entitled
|
|
11
|
+
* until then, and a paid retry continues the period from the old end. An
|
|
12
|
+
* early attempt (`renewalLeadSec`) that fails leaves the paid period
|
|
13
|
+
* `active` and is tried again by the next run;
|
|
14
|
+
* - grace passed, or a non-renewing term ended → `expired`, and the
|
|
15
|
+
* entitlement falls to the next term or the free plan;
|
|
16
|
+
* - a scheduled term (S3b) is charged and activated when it starts.
|
|
17
|
+
*
|
|
18
|
+
* Each term runs in its own transaction: term rows (oldest first), then the
|
|
19
|
+
* ledger account. `retryPastDue` is what a host calls once a top-up has
|
|
20
|
+
* committed — in its own transaction, never inside the crediting one, which
|
|
21
|
+
* already holds the account lock that must come last.
|
|
22
|
+
*/
|
|
23
|
+
import type { Catalog } from '../catalog/catalog.js';
|
|
24
|
+
import type { AccountId, BillingEvent, LedgerEntry } from '../domain/types.js';
|
|
25
|
+
import type { Ledger } from '../ledger/ledger.js';
|
|
26
|
+
import type { Clock } from '../ports/runtime.js';
|
|
27
|
+
import type { TermStore } from '../terms/ports.js';
|
|
28
|
+
import type { Term, TermEvent } from '../terms/types.js';
|
|
29
|
+
export type RenewalEvent = TermEvent | BillingEvent;
|
|
30
|
+
export interface RenewalOptions<TTx> {
|
|
31
|
+
ledger: Ledger<TTx>;
|
|
32
|
+
terms: TermStore<TTx>;
|
|
33
|
+
catalog: Catalog;
|
|
34
|
+
clock?: Clock;
|
|
35
|
+
/** The account's market now, for the live price; `null`/absent → the term's own market. */
|
|
36
|
+
marketOf?: (accountId: AccountId) => string | null | Promise<string | null>;
|
|
37
|
+
/** At-most-once, after commit, for transactions the service opened. */
|
|
38
|
+
events?: (event: RenewalEvent) => void | Promise<void>;
|
|
39
|
+
onEventError?: (error: unknown, event: RenewalEvent) => void;
|
|
40
|
+
}
|
|
41
|
+
export type RenewalOutcome = 'renewed' | 'activated' | 'past_due' | 'expired' | 'skipped' | 'error';
|
|
42
|
+
export interface RenewalResult {
|
|
43
|
+
termId: string;
|
|
44
|
+
accountId: AccountId;
|
|
45
|
+
outcome: RenewalOutcome;
|
|
46
|
+
/** Why a renewal failed (`insufficient_credits`, `offer_not_found`) or was skipped, or the error message. */
|
|
47
|
+
reason?: string;
|
|
48
|
+
entry?: LedgerEntry | null;
|
|
49
|
+
term?: Term;
|
|
50
|
+
}
|
|
51
|
+
export interface RenewalRun {
|
|
52
|
+
results: RenewalResult[];
|
|
53
|
+
events: RenewalEvent[];
|
|
54
|
+
}
|
|
55
|
+
export interface RenewalOps {
|
|
56
|
+
/** Process one term if it is due at `now`. */
|
|
57
|
+
renewTerm(termId: string, now?: Date): Promise<RenewalRun>;
|
|
58
|
+
/** Charge the account's past_due credit terms again (or expire them once grace has passed). */
|
|
59
|
+
retryPastDue(accountId: AccountId, now?: Date): Promise<RenewalRun>;
|
|
60
|
+
}
|
|
61
|
+
export interface RenewalService<TTx = unknown> extends RenewalOps {
|
|
62
|
+
/** Every due term, each in its own transaction; one term's error does not stop the batch. */
|
|
63
|
+
renewDue(input?: {
|
|
64
|
+
now?: Date;
|
|
65
|
+
limit?: number;
|
|
66
|
+
}): Promise<RenewalRun>;
|
|
67
|
+
in(tx: TTx): RenewalOps;
|
|
68
|
+
}
|
|
69
|
+
export declare function createRenewal<TTx>(options: RenewalOptions<TTx>): RenewalService<TTx>;
|