@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,37 @@
|
|
|
1
|
+
import { type IngestOutcome, type ProviderAdapter, type ProviderEnvironment, type ProviderResponse, type PurchaseVerifier, type Reconcilable } from '../port.js';
|
|
2
|
+
import { type PubSubAuth, type ServiceAccount } from './api.js';
|
|
3
|
+
import { type GoogleProduct } from './events.js';
|
|
4
|
+
export { GooglePlayApiError, type PubSubAuth, type ServiceAccount } from './api.js';
|
|
5
|
+
export { GOOGLE_PURCHASE_EVENT, GOOGLE_RTDN_EVENT, GOOGLE_VOIDED_EVENT, type GoogleProduct } from './events.js';
|
|
6
|
+
export interface GoogleAdapterOptions {
|
|
7
|
+
/** Required. `production` ignores license testers' purchases; `sandbox` credits them. */
|
|
8
|
+
environment: ProviderEnvironment;
|
|
9
|
+
/** This app's package name: a notification for any other package is refused. */
|
|
10
|
+
packageName: string;
|
|
11
|
+
/** Play product id → what it means here. */
|
|
12
|
+
products: Readonly<Record<string, GoogleProduct>>;
|
|
13
|
+
/** Who signs the Pub/Sub push: the subscription's audience and service account. */
|
|
14
|
+
pubsub: PubSubAuth;
|
|
15
|
+
/** Service account with Play Console access, for the Play Developer API. */
|
|
16
|
+
serviceAccount: ServiceAccount;
|
|
17
|
+
/** Our checkout session ids as carried in `obfuscatedExternalAccountId`. Default: UUID. */
|
|
18
|
+
checkoutPattern?: RegExp;
|
|
19
|
+
/** Wall clock for token lifetimes and the reconcile window. Default `new Date()`. */
|
|
20
|
+
clock?: () => Date;
|
|
21
|
+
fetch?: typeof fetch;
|
|
22
|
+
/** API timeout. Default 10 s. */
|
|
23
|
+
timeoutMs?: number;
|
|
24
|
+
}
|
|
25
|
+
/** A purchase the app reports from Play Billing, bound to the host's checkout session. */
|
|
26
|
+
export interface GooglePurchaseProof {
|
|
27
|
+
productId: string;
|
|
28
|
+
purchaseToken: string;
|
|
29
|
+
/** The checkout session the host created for this purchase (server-priced). */
|
|
30
|
+
checkoutRef?: string;
|
|
31
|
+
}
|
|
32
|
+
export interface GoogleAdapter extends ProviderAdapter, PurchaseVerifier<GooglePurchaseProof>, Reconcilable {
|
|
33
|
+
readonly id: 'google';
|
|
34
|
+
}
|
|
35
|
+
export declare function createGoogleAdapter(options: GoogleAdapterOptions): GoogleAdapter;
|
|
36
|
+
/** Pub/Sub redelivers any non-2xx with backoff; acknowledge everything a retry cannot change. */
|
|
37
|
+
export declare function respondGoogle(outcome: IngestOutcome): ProviderResponse;
|
|
@@ -0,0 +1,228 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Google Play adapter (`@tofound/billing/providers/google`), ported from Lohi
|
|
3
|
+
* `lib/google-play-iap.ts`:
|
|
4
|
+
* - Real-time Developer Notifications arrive by Pub/Sub push; the push's
|
|
5
|
+
* OIDC token must be Google's, for our audience and service account, and
|
|
6
|
+
* the notification must name our package — nothing is stored otherwise;
|
|
7
|
+
* - a purchase is never taken from the notification or the app: verify asks
|
|
8
|
+
* `purchases.products.get` and stores Play's answer, so a replay normalizes
|
|
9
|
+
* from the same evidence without calling Google again;
|
|
10
|
+
* - voided purchases (RTDN and `voidedpurchases.list` via `Reconcilable`)
|
|
11
|
+
* reverse by `orderId`, so both paths claw back once;
|
|
12
|
+
* - purchase tokens are dropped by the inbox redaction and never put in an
|
|
13
|
+
* event id.
|
|
14
|
+
* No SDK, no env reads, no logging. Play has one rail for real and test
|
|
15
|
+
* money, so the environment decides what a license tester's purchase is: a
|
|
16
|
+
* `production` adapter acknowledges it as ignored, a `sandbox` one credits it.
|
|
17
|
+
* Subscriptions are not handled here (their notifications are ignored).
|
|
18
|
+
*/
|
|
19
|
+
import { createHash } from 'node:crypto';
|
|
20
|
+
import { ProviderConfigError, VerifyError, } from '../port.js';
|
|
21
|
+
import { GooglePlayApiError, createGoogleKeyCache, createPlayApi, verifyPubSubToken } from './api.js';
|
|
22
|
+
import { GOOGLE_PURCHASE_EVENT, GOOGLE_RTDN_EVENT, GOOGLE_VOIDED_EVENT, ONE_TIME_PRODUCT_PURCHASED, millisDate, normalizeGoogleEvent, rec, } from './events.js';
|
|
23
|
+
export { GooglePlayApiError } from './api.js';
|
|
24
|
+
export { GOOGLE_PURCHASE_EVENT, GOOGLE_RTDN_EVENT, GOOGLE_VOIDED_EVENT } from './events.js';
|
|
25
|
+
const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
|
26
|
+
const MAX_BODY = 64 * 1024;
|
|
27
|
+
const MAX_ID = 128;
|
|
28
|
+
const MAX_PURCHASE_TOKEN = 4096;
|
|
29
|
+
/** `voidedpurchases.list` looks back at most 30 days. */
|
|
30
|
+
const VOIDED_LOOKBACK_MS = 30 * 24 * 3600 * 1000;
|
|
31
|
+
const MAX_VOIDED_PAGE = 1000;
|
|
32
|
+
/** A page cursor older than the lookback by more than this restarts the list. */
|
|
33
|
+
const STALE_PAGE_MS = 24 * 3600 * 1000;
|
|
34
|
+
/** A purchase notification Play does not know yet is retried for this long (replication lag). */
|
|
35
|
+
const LOOKUP_GRACE_MS = 10 * 60 * 1000;
|
|
36
|
+
const stateless = (pattern) => new RegExp(pattern.source, pattern.flags.replace(/[gy]/g, ''));
|
|
37
|
+
const boundedId = (value, max = MAX_ID) => (typeof value === 'string' && value.length > 0 && value.length <= max ? value : null);
|
|
38
|
+
/** Stands in for an order id Play did not issue (test purchases), without exposing the token. */
|
|
39
|
+
const tokenRef = (purchaseToken) => `token-${createHash('sha256').update(purchaseToken).digest('hex').slice(0, 32)}`;
|
|
40
|
+
/** A client proof's event id: the purchase, plus what could change its outcome. */
|
|
41
|
+
function proofEventId(base, checkoutRef, reversed) {
|
|
42
|
+
const session = checkoutRef ? `:c${createHash('sha256').update(checkoutRef).digest('hex').slice(0, 16)}` : '';
|
|
43
|
+
return `${base}${session}${reversed ? ':reversed' : ''}`;
|
|
44
|
+
}
|
|
45
|
+
export function createGoogleAdapter(options) {
|
|
46
|
+
const { environment } = options;
|
|
47
|
+
if (environment !== 'production' && environment !== 'sandbox') {
|
|
48
|
+
throw new ProviderConfigError('google_environment_required', 'Google Play environment must be passed explicitly: production | sandbox');
|
|
49
|
+
}
|
|
50
|
+
if (!options.packageName)
|
|
51
|
+
throw new ProviderConfigError('google_package_name_required', 'the app package name is required');
|
|
52
|
+
if (!options.pubsub?.audience || !options.pubsub.serviceAccountEmail) {
|
|
53
|
+
throw new ProviderConfigError('google_pubsub_auth_required', 'the Pub/Sub push audience and service account are required');
|
|
54
|
+
}
|
|
55
|
+
if (!options.serviceAccount?.clientEmail || !options.serviceAccount.privateKey) {
|
|
56
|
+
throw new ProviderConfigError('google_service_account_required', 'a service account is required for the Play Developer API');
|
|
57
|
+
}
|
|
58
|
+
const normalizeOptions = { products: { ...options.products }, checkoutPattern: stateless(options.checkoutPattern ?? UUID_RE) };
|
|
59
|
+
const pubsub = { ...options.pubsub };
|
|
60
|
+
const transport = {
|
|
61
|
+
fetch: options.fetch ?? globalThis.fetch,
|
|
62
|
+
timeoutMs: options.timeoutMs ?? 10_000,
|
|
63
|
+
clock: options.clock ?? (() => new Date()),
|
|
64
|
+
};
|
|
65
|
+
const keyFor = createGoogleKeyCache(transport);
|
|
66
|
+
const play = createPlayApi(transport, options.packageName, { ...options.serviceAccount });
|
|
67
|
+
/**
|
|
68
|
+
* Play's answer for a notified purchase. Right after the purchase Play may
|
|
69
|
+
* not serve it yet: a young notification fails so Pub/Sub redelivers it; an
|
|
70
|
+
* old one is stored with a not-found marker for a human.
|
|
71
|
+
*/
|
|
72
|
+
async function lookup(productId, purchaseToken, occurredAt) {
|
|
73
|
+
const purchase = await play.getProductPurchase(productId, purchaseToken);
|
|
74
|
+
if (purchase)
|
|
75
|
+
return purchase;
|
|
76
|
+
if (transport.clock().getTime() - occurredAt.getTime() < LOOKUP_GRACE_MS) {
|
|
77
|
+
throw new GooglePlayApiError('google_not_found', 'Play does not know the notified purchase yet');
|
|
78
|
+
}
|
|
79
|
+
return { notFound: true };
|
|
80
|
+
}
|
|
81
|
+
function parseCursor(cursor) {
|
|
82
|
+
const floor = transport.clock().getTime() - VOIDED_LOOKBACK_MS;
|
|
83
|
+
if (cursor === null)
|
|
84
|
+
return { startTime: floor };
|
|
85
|
+
const match = /^(\d{1,16})(?::(.+))?$/.exec(cursor);
|
|
86
|
+
if (!match)
|
|
87
|
+
throw new ProviderConfigError('google_invalid_cursor', 'reconcile cursor is not one this adapter issued');
|
|
88
|
+
const startTime = Number(match[1]);
|
|
89
|
+
// A page token belongs to the query that issued it: resume with that exact
|
|
90
|
+
// startTime, unless the cursor sat so long that Play no longer serves it.
|
|
91
|
+
if (match[2] && startTime >= floor - STALE_PAGE_MS)
|
|
92
|
+
return { startTime, pageToken: match[2] };
|
|
93
|
+
return { startTime: Math.max(startTime, floor) };
|
|
94
|
+
}
|
|
95
|
+
const adapter = {
|
|
96
|
+
id: 'google',
|
|
97
|
+
environment,
|
|
98
|
+
async verify(req) {
|
|
99
|
+
await verifyPubSubToken(req.headers.get('authorization'), pubsub, keyFor, transport.clock());
|
|
100
|
+
if (req.rawBody.length > MAX_BODY)
|
|
101
|
+
throw new VerifyError('malformed', 'Pub/Sub push body oversized');
|
|
102
|
+
let message;
|
|
103
|
+
let rtdn;
|
|
104
|
+
try {
|
|
105
|
+
message = rec(rec(JSON.parse(req.rawBody))?.['message']);
|
|
106
|
+
const data = message?.['data'];
|
|
107
|
+
rtdn = typeof data === 'string' ? rec(JSON.parse(Buffer.from(data, 'base64').toString('utf8'))) : null;
|
|
108
|
+
}
|
|
109
|
+
catch {
|
|
110
|
+
throw new VerifyError('malformed', 'Pub/Sub push body is not a JSON notification');
|
|
111
|
+
}
|
|
112
|
+
const messageId = boundedId(message?.['messageId'] ?? message?.['message_id']);
|
|
113
|
+
if (!message || !rtdn || !messageId)
|
|
114
|
+
throw new VerifyError('malformed', 'Pub/Sub push carries no notification or message id');
|
|
115
|
+
if (rtdn['packageName'] !== options.packageName)
|
|
116
|
+
throw new VerifyError('unauthorized', 'Play notification is for another package');
|
|
117
|
+
const occurredAt = millisDate(rtdn['eventTimeMillis']);
|
|
118
|
+
if (!occurredAt)
|
|
119
|
+
throw new VerifyError('malformed', 'Play notification lacks eventTimeMillis');
|
|
120
|
+
const stored = { ...rtdn, messageId };
|
|
121
|
+
let subjectRef = null;
|
|
122
|
+
const oneTime = rec(rtdn['oneTimeProductNotification']);
|
|
123
|
+
if (oneTime && oneTime['notificationType'] === ONE_TIME_PRODUCT_PURCHASED) {
|
|
124
|
+
const sku = boundedId(oneTime['sku']);
|
|
125
|
+
const purchaseToken = boundedId(oneTime['purchaseToken'], MAX_PURCHASE_TOKEN);
|
|
126
|
+
if (!sku || !purchaseToken)
|
|
127
|
+
throw new VerifyError('malformed', 'Play purchase notification lacks its sku or purchase token');
|
|
128
|
+
// A lookup failure is not the sender's fault: it throws past the
|
|
129
|
+
// VerifyError path, the delivery fails and Pub/Sub redelivers it.
|
|
130
|
+
const purchase = await lookup(sku, purchaseToken, occurredAt);
|
|
131
|
+
subjectRef = boundedId(purchase['obfuscatedExternalAccountId']);
|
|
132
|
+
stored['purchase'] = purchase;
|
|
133
|
+
}
|
|
134
|
+
return {
|
|
135
|
+
provider: 'google',
|
|
136
|
+
environment,
|
|
137
|
+
eventId: `google:${messageId}`,
|
|
138
|
+
eventType: GOOGLE_RTDN_EVENT,
|
|
139
|
+
occurredAt,
|
|
140
|
+
payload: stored,
|
|
141
|
+
...(subjectRef ? { subjectRef } : {}),
|
|
142
|
+
};
|
|
143
|
+
},
|
|
144
|
+
async normalize(delivery) {
|
|
145
|
+
return [normalizeGoogleEvent(delivery.eventType, delivery.payload, delivery.occurredAt, delivery.environment, normalizeOptions)];
|
|
146
|
+
},
|
|
147
|
+
respond: respondGoogle,
|
|
148
|
+
// No `redact`: the inbox's generic rules already drop `purchaseToken`.
|
|
149
|
+
async verifyPurchase(proof) {
|
|
150
|
+
if (proof.checkoutRef !== undefined && !normalizeOptions.checkoutPattern.test(proof.checkoutRef)) {
|
|
151
|
+
throw new ProviderConfigError('google_invalid_checkout_id', 'checkoutRef does not match the adapter checkoutPattern');
|
|
152
|
+
}
|
|
153
|
+
const productId = boundedId(proof.productId);
|
|
154
|
+
const purchaseToken = boundedId(proof.purchaseToken, MAX_PURCHASE_TOKEN);
|
|
155
|
+
if (!productId || !purchaseToken)
|
|
156
|
+
throw new VerifyError('malformed', 'Play purchase proof lacks its product id or purchase token');
|
|
157
|
+
const purchase = await play.getProductPurchase(productId, purchaseToken);
|
|
158
|
+
// Unknown to Play, or not paid yet: nothing to apply.
|
|
159
|
+
if (!purchase || purchase['purchaseState'] === 2)
|
|
160
|
+
return null;
|
|
161
|
+
const orderId = boundedId(purchase['orderId']);
|
|
162
|
+
const subjectRef = boundedId(purchase['obfuscatedExternalAccountId']);
|
|
163
|
+
return {
|
|
164
|
+
provider: 'google',
|
|
165
|
+
environment,
|
|
166
|
+
// The same id whoever posts it, so the app's retry is a duplicate; a
|
|
167
|
+
// proof that can end differently (another session, now canceled) is new.
|
|
168
|
+
eventId: proofEventId(`google:order:${orderId ?? tokenRef(purchaseToken)}`, proof.checkoutRef, purchase['purchaseState'] === 1),
|
|
169
|
+
eventType: GOOGLE_PURCHASE_EVENT,
|
|
170
|
+
occurredAt: millisDate(purchase['purchaseTimeMillis']) ?? transport.clock(),
|
|
171
|
+
payload: { purchase, productId, ...(proof.checkoutRef ? { checkoutRef: proof.checkoutRef } : {}) },
|
|
172
|
+
...(subjectRef ? { subjectRef } : {}),
|
|
173
|
+
};
|
|
174
|
+
},
|
|
175
|
+
/**
|
|
176
|
+
* Voided one-time purchases since `cursor` (null: the last 30 days), as
|
|
177
|
+
* deliveries that dedup with each other across sweeps. `next` resumes
|
|
178
|
+
* the list; it is null once a page comes back empty, so keep the last
|
|
179
|
+
* non-null cursor for the next sweep.
|
|
180
|
+
*/
|
|
181
|
+
async listChangesSince(cursor, limit) {
|
|
182
|
+
const { startTime, pageToken } = parseCursor(cursor);
|
|
183
|
+
const page = await play.listVoided({ startTime, maxResults: Math.max(1, Math.min(MAX_VOIDED_PAGE, Math.floor(limit))), ...(pageToken ? { pageToken } : {}) });
|
|
184
|
+
const deliveries = [];
|
|
185
|
+
let highWater = startTime;
|
|
186
|
+
for (const entry of page.voided) {
|
|
187
|
+
const occurredAt = millisDate(entry['voidedTimeMillis']);
|
|
188
|
+
const orderId = boundedId(entry['orderId']);
|
|
189
|
+
const purchaseToken = boundedId(entry['purchaseToken'], MAX_PURCHASE_TOKEN);
|
|
190
|
+
if (!occurredAt || (!orderId && !purchaseToken))
|
|
191
|
+
continue;
|
|
192
|
+
highWater = Math.max(highWater, occurredAt.getTime());
|
|
193
|
+
deliveries.push({
|
|
194
|
+
provider: 'google',
|
|
195
|
+
environment,
|
|
196
|
+
eventId: `google:void:${orderId ?? tokenRef(purchaseToken)}`,
|
|
197
|
+
eventType: GOOGLE_VOIDED_EVENT,
|
|
198
|
+
occurredAt,
|
|
199
|
+
payload: { voided: entry },
|
|
200
|
+
});
|
|
201
|
+
}
|
|
202
|
+
if (page.nextPageToken)
|
|
203
|
+
return { deliveries, next: `${startTime}:${page.nextPageToken}` };
|
|
204
|
+
return { deliveries, next: page.voided.length > 0 ? String(highWater + 1) : null };
|
|
205
|
+
},
|
|
206
|
+
};
|
|
207
|
+
return adapter;
|
|
208
|
+
}
|
|
209
|
+
const json = (status, body) => ({
|
|
210
|
+
status,
|
|
211
|
+
headers: { 'content-type': 'application/json' },
|
|
212
|
+
body: JSON.stringify(body),
|
|
213
|
+
});
|
|
214
|
+
/** Pub/Sub redelivers any non-2xx with backoff; acknowledge everything a retry cannot change. */
|
|
215
|
+
export function respondGoogle(outcome) {
|
|
216
|
+
if (outcome.relay)
|
|
217
|
+
return outcome.relay;
|
|
218
|
+
switch (outcome.status) {
|
|
219
|
+
case 'unauthorized':
|
|
220
|
+
return json(401, { error: 'Unauthorized' });
|
|
221
|
+
case 'malformed':
|
|
222
|
+
return json(400, { error: 'Invalid payload' });
|
|
223
|
+
case 'failed':
|
|
224
|
+
return json(500, { error: 'Internal error' });
|
|
225
|
+
default:
|
|
226
|
+
return json(200, { received: true, outcome: outcome.status, ...(outcome.reason ? { reason: outcome.reason } : {}) });
|
|
227
|
+
}
|
|
228
|
+
}
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import type { NormalizedEvent } from '../port.js';
|
|
2
|
+
export interface PolarEnvelope {
|
|
3
|
+
type: string;
|
|
4
|
+
timestamp?: unknown;
|
|
5
|
+
data: Record<string, unknown>;
|
|
6
|
+
}
|
|
7
|
+
export interface NormalizeOptions {
|
|
8
|
+
/** Polar product id → catalog productRef. */
|
|
9
|
+
products: Readonly<Record<string, string>>;
|
|
10
|
+
/** Our checkout session ids, as carried in `metadata.checkout_id`. */
|
|
11
|
+
checkoutPattern: RegExp;
|
|
12
|
+
}
|
|
13
|
+
/** The provider's watermark: when Polar last changed the object, else when it was created or sent. */
|
|
14
|
+
export declare function occurredAtOf(envelope: PolarEnvelope, fallback: Date): Date;
|
|
15
|
+
/** The server-issued external customer id (design §4.1). */
|
|
16
|
+
export declare function externalCustomerOf(data: Record<string, unknown>): string | null;
|
|
17
|
+
export declare function normalizePolarEvent(envelope: PolarEnvelope, occurredAt: Date, options: NormalizeOptions): NormalizedEvent;
|
|
@@ -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;
|