@tofound/billing 0.2.0 → 1.1.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.
@@ -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
+ }
@@ -29,7 +29,7 @@ export interface PolarAdapterOptions {
29
29
  /** API timeout. Default 10 s. */
30
30
  timeoutMs?: number;
31
31
  }
32
- /** A checkout request; Polar uses the buyer's IP for tax country when the host has it. */
32
+ /** A checkout request; Polar uses the buyer's IP (`customerIpAddress`) for the tax country when the host has it. */
33
33
  export interface PolarCheckoutRequest extends CheckoutRequest {
34
34
  customerIpAddress?: string | null;
35
35
  }
@@ -151,6 +151,8 @@ export interface CheckoutRequest {
151
151
  errorUrl: string;
152
152
  cancelUrl: string;
153
153
  productRef?: string | null;
154
+ /** The buyer's IP when the host has it; adapters that cannot use it ignore it (Polar: tax country). */
155
+ customerIpAddress?: string | null;
154
156
  }
155
157
  export type CheckoutRedirect = {
156
158
  kind: 'redirect';
@@ -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' },
package/docs/API.md CHANGED
@@ -1,15 +1,21 @@
1
- # @tofound/billing — API (0.2)
1
+ # @tofound/billing — API (1.1)
2
2
 
3
3
  Part of the `billing.public-api` contract with `src/index.ts` and
4
- `src/domain/types.ts`. 0.x minors are additive; the declaration snapshot in
5
- `test/contract/public-api.test.ts` fails on any change to these exports.
4
+ `src/domain/types.ts`. 0.x minors were additive; 1.1.0 is additive to 1.0.0. From 1.0.0 the API is
5
+ frozen: the declaration snapshot in `test/contract/public-api.test.ts` fails
6
+ on any change to these exports, and removing or narrowing one is a major
7
+ version. For task-oriented walkthroughs (packs, plans, failed renewals,
8
+ refunds, arming a provider) see [GUIDE.md](GUIDE.md).
6
9
 
7
10
  | Entry | Contents |
8
11
  |---|---|
9
- | `@tofound/billing` | domain types, money helpers, `BillingError`, `createLedger`, ports, `createMemoryLedgerStore`, waterfall + steps, provider port, `createIngest`, `createMemoryIngestStore`, `defineCatalog`, terms, `resolveEntitlement`, `createPlans`, `createRenewal`, `createSnapshotHandler`, `createMemoryTermStore` |
12
+ | `@tofound/billing` | domain types, money helpers, `BillingError`, `createLedger`, ports, `createMemoryLedgerStore`, waterfall + steps, provider port, `createIngest`, `defaultEventHandlers`, `createMemoryIngestStore`, `defineCatalog`, terms, `resolveEntitlement`, `createPlans`, `createRenewal`, `createSnapshotHandler`, `createMemoryTermStore` |
10
13
  | `@tofound/billing/drizzle` | `createBillingTables`, `billingTableBuilder`, `checkAdditiveDdl`, `createDrizzleLedgerStore`, `createIngestTables`, `createDrizzleIngestStore`, `createTermTables`, `createDrizzleTermStore`, `termTableNames` (peer `drizzle-orm ^0.45`) |
11
14
  | `@tofound/billing/providers/sepay` | `createSepayAdapter`, `respondSepay`, `signCheckoutFields`, `parseSepayOrder` |
12
15
  | `@tofound/billing/providers/polar` | `createPolarAdapter`, `resolvePolarEnvironment`, `respondPolar`, `redactPolarPayload`, `signPolarWebhook`, `PolarApiError`, `POLAR_WEBHOOK_*` header names and tolerance; types `PolarAdapter`, `PolarAdapterOptions`, `PolarCheckoutRequest`, `PolarKeyDerivation` |
16
+ | `@tofound/billing/providers/apple` | `createAppleAdapter`, `respondApple`, `AppleApiError`, `APPLE_TRANSACTION_EVENT`, `APPLE_ROOT_CA_G3_PEM` / `_SHA256`, `APPLE_RECEIPT_SIGNING_OID`, `APPLE_WWDR_INTERMEDIATE_OID`; types `AppleAdapter`, `AppleAdapterOptions`, `AppleProduct`, `AppleServerApiCredentials`, `AppleTransactionProof` |
17
+ | `@tofound/billing/providers/google` | `createGoogleAdapter`, `respondGoogle`, `GooglePlayApiError`, `GOOGLE_RTDN_EVENT`, `GOOGLE_PURCHASE_EVENT`, `GOOGLE_VOIDED_EVENT`; types `GoogleAdapter`, `GoogleAdapterOptions`, `GoogleProduct`, `GooglePurchaseProof`, `PubSubAuth`, `ServiceAccount` |
18
+ | `@tofound/billing/hostkit` | `createLegacyLedgerStore`, `LEGACY_KEY_PREFIX`, `createAdminAdjustments`, `serializeQuote`, `serializePlanQuote`; types `LegacyWalletDriver`, `LegacyEntryRow`, `LegacyLedgerFields`, `LegacyLedgerCodec`, `AdjustmentInput`, `AdjustmentResult`, `AdjustmentOverdraft`, `AdminAdjustments`, `AdminAdjustmentsOptions`, `QuoteWire`, `PlanQuoteWire`, `FundingLineWire`, `QuoteLabeler`, `QuoteWireOptions` |
13
19
  | `@tofound/billing/testing` | `ledgerConformanceCases`, `assertLedgerInvariants`, `assertQuoteMatchesSettlement`, `ingestConformanceCases`, `termConformanceCases`, memory stores |
14
20
 
15
21
  The library reads no env, logs nothing and has no runtime dependencies. Every
@@ -156,9 +162,9 @@ await w.settle(tx, lockedState, { accountId, idempotencyKey }) // same steps, co
156
162
 
157
163
  ```ts
158
164
  const sepay = createSepayAdapter({ environment: 'production', webhookKeys: [current, next?], merchantId, secretKey })
159
- const ingest = createIngest({ adapters: [sepay], store, ledger, events?, policy?, onUnmatched? })
165
+ const ingest = createIngest({ adapters: [sepay], store, ledger, events?, policy?, onUnmatched?, handlers?, afterCredited?, onHookError? })
160
166
 
161
- const { session, redirect } = await ingest.createCheckout({ provider: 'sepay', accountId, amount, credits, productRef, description, successUrl, errorUrl, cancelUrl })
167
+ const { session, redirect } = await ingest.createCheckout({ provider: 'sepay', accountId, amount, credits, productRef, description, successUrl, errorUrl, cancelUrl, customerIpAddress? })
162
168
  const r = await ingest.handle('sepay', { headers, rawBody, url, receivedAt }) // → reply with r.response
163
169
  await ingest.confirm('sepay', { invoice: session.id }) // poll; same event id as the IPN
164
170
  await ingest.closeCheckout(session.id, 'expired') // a later capture still credits
@@ -186,6 +192,32 @@ await ingest.sweep()
186
192
  - `confirm` credits the session's own account, whoever asks; a host route
187
193
  that forwards a client's invoice still checks the caller owns that session
188
194
  before it spends a provider API call on it.
195
+ - **`afterCredited(c: CreditedPurchase)`** (1.1) runs after the delivery's
196
+ transaction commits, at most once per credit: `{ provider, accountId, kind:
197
+ 'completed' | 'reinstated', entry, externalId, sessionId }`. It fires for the
198
+ library's own appliers and for a host handler whose `ApplyResult`
199
+ (`HandlerResult`) carries `credited: { accountId, entry, kind, externalId?,
200
+ sessionId? }`. It never fires for `duplicate`, `ignored`, a replay of a
201
+ settled row, a reversal, a rolled-back attempt or an entry with `delta ≤ 0`,
202
+ and it fires whatever the delivery's status when a credit committed (a
203
+ sibling event that needs review does not unsend it). A throw or rejection
204
+ goes to `onHookError(error, c)` (itself guarded) and never changes the
205
+ outcome; a crash between commit and hook loses the call, so keep a periodic
206
+ backstop.
207
+ - `afterCredited` announces **purchase credits** (capture, reinstatement) and
208
+ what a host handler reports in `credited`. Other credits the ingest posts,
209
+ such as the `plan_refund` of a superseded term from `createSnapshotHandler`,
210
+ are not announced. The hook is awaited before the provider is answered: keep
211
+ it short and hand slow work to a queue.
212
+ - **`defaultEventHandlers`** (1.1) are the library's `purchase.completed` /
213
+ `purchase.reversed` / `purchase.reinstated` appliers as `EventHandler`s, so a
214
+ host that overrides one kind for a provider can hand the others back per
215
+ delivery. They apply through `ctx.store` (the ingest store bound to the
216
+ handler's transaction; with `ctx.newId`, new on `ApplyContext` in 1.1) and
217
+ return `credited`. A handler given an event of another kind answers
218
+ `ignored` (`no_handler:<kind>`).
219
+ - **`createCheckout({ customerIpAddress })`** (1.1) is forwarded to the adapter's
220
+ `CheckoutRequest` when non-empty; an adapter that cannot use it ignores it.
189
221
  - `sweep` lists only rows of the providers this ingest has adapters for, and
190
222
  a row it cannot even record stays due without stopping the rows behind it.
191
223
  - `onUnmatched` receives deliveries no session matches (e.g. another product's
@@ -263,9 +295,9 @@ const { url } = await polar.createPortalSession({ kind: 'account_id', value: acc
263
295
  The Polar checkout already exists by then; it is never handed to the buyer.
264
296
  The session id comes from the ingest's `ids` (default `randomUUID`), so a custom
265
297
  generator must match `checkoutPattern`, or every checkout throws
266
- `polar_invalid_checkout_id`. `PolarCheckoutRequest.customerIpAddress` (sent for tax
267
- country) is only accepted by a direct `polar.createCheckout` call;
268
- `ingest.createCheckout` does not forward it.
298
+ `polar_invalid_checkout_id`. `customerIpAddress` (sent for the tax country) is forwarded by
299
+ `ingest.createCheckout` since 1.1 and accepted by a direct
300
+ `polar.createCheckout` call.
269
301
  `order.paid` for a one-time order becomes `purchase.completed`, bound to the
270
302
  session by `metadata.checkout_id` and credited once (`topup:<sessionId>`).
271
303
  Its amount is the catalog price, `subtotal_amount − discount_amount`, which
@@ -340,6 +372,129 @@ const { url } = await polar.createPortalSession({ kind: 'account_id', value: acc
340
372
  carries the token or Polar's response body. A portal for any other
341
373
  account kind is refused (`ProviderConfigError('polar_unsupported_account')`).
342
374
 
375
+ ## App Store (`@tofound/billing/providers/apple`, 1.0)
376
+
377
+ ```ts
378
+ const apple = createAppleAdapter({
379
+ environment, // required: 'production' | 'sandbox'
380
+ bundleId, // a payload for any other app is refused
381
+ products: { [appStoreProductId]: { productRef, amount? } }, // amount required for one-time products
382
+ appAppleId?, // checked when the notification carries one
383
+ serverApi?: { issuerId, keyId, privateKey }, // the .p8 key; only for reportConsumption
384
+ checkoutPattern?, clock?, fetch?, timeoutMs?,
385
+ // trustedRoots?: tests only — production trusts the pinned Apple Root CA G3 alone
386
+ })
387
+ const ingest = createIngest({ adapters: [apple], store, ledger, handlers: { 'subscription.snapshot': … } })
388
+
389
+ const r = await ingest.handle('apple', { headers, rawBody, url, receivedAt }) // App Store Server Notifications v2
390
+ const outcome = await ingest.confirm('apple', { signedTransaction, checkoutRef }) // StoreKit 2 client proof → IngestOutcome
391
+ await apple.reportConsumption(transactionId, info) // App Store Server API
392
+ ```
393
+
394
+ - **Verification.** Every JWS (`signedPayload`, `signedTransactionInfo`,
395
+ `signedRenewalInfo`, a client's `signedTransaction`) is ES256 over its
396
+ `x5c` chain. The chain must end at the pinned Apple Root CA G3
397
+ (`APPLE_ROOT_CA_G3_SHA256`). The leaf must carry the receipt-signing marker
398
+ OID and the intermediate the WWDR OID, and every certificate must be valid
399
+ at `clock()`. A payload for another `bundleId`, another `appAppleId` or the
400
+ other environment is `unauthorized` (401): a production adapter refuses
401
+ Sandbox payloads. Non-JSON, no `signedPayload`, or a notification without
402
+ its type, `notificationUUID` or `signedDate` is `malformed` (400). The event
403
+ id is `apple:<notificationUUID>`; a client proof's is
404
+ `apple:txn:<transactionId>`, plus the checkout session and the revoked
405
+ state when present. So the app's retry is a `duplicate`, and a proof that
406
+ can end differently is a new event.
407
+ - **One-time products** are purchases keyed by `transactionId`.
408
+ `ONE_TIME_CHARGE` or a client proof completes one. The amount is the
409
+ configured product `amount` × quantity, because the product id is the price
410
+ authority. `REFUND` and `REVOKE` reverse it, and `REFUND_REVERSED`
411
+ reinstates it. Each carries its `signedDate` as a watermark, so a stale
412
+ notification is ignored whatever order they arrive in.
413
+ - **Only checkout-bound purchases credit.** A purchase names the session
414
+ through the proof's `checkoutRef`, or because its `appAccountToken`
415
+ matches `checkoutPattern` (UUID by default). A notification naming no
416
+ session is `ignored` (`unbound_purchase`), and the app's proof settles it.
417
+ Other reasons for a one-time purchase: `unknown_product`,
418
+ `product_amount_missing` and `invalid_quantity` go to `needs_review`.
419
+ `TEST` notifications are ignored (`test_notification`).
420
+ - **Auto-renewable subscriptions** become `subscription.snapshot` keyed by
421
+ `originalTransactionId`, with a deterministic `tieBreak`. A refund or
422
+ revoke ends access now. A subscription without an `appAccountToken` is
423
+ `ignored` (`no_account_token`), and one whose product is not in
424
+ `products` is `ignored` (`unknown_product`). Neither alerts, so every
425
+ subscription product must be listed and every purchase must carry the
426
+ account token.
427
+ - **Errors.** Config: `ProviderConfigError` `apple_environment_required`,
428
+ `apple_bundle_id_required`, `apple_invalid_root`,
429
+ `apple_invalid_checkout_id`, `apple_server_api_not_configured`,
430
+ `apple_server_api_invalid_key`. A Server API failure is `AppleApiError`
431
+ (`apple_unreachable`, `apple_error` with `status`). It never carries the
432
+ token or the response body.
433
+ - **`respondApple`**: 401 / 400 / 500 for `unauthorized` / `malformed` /
434
+ `failed`, and 200 for everything else, because Apple retries any non-2xx
435
+ for days. The stored payload keeps the decoded transaction, not the JWS,
436
+ and the generic redaction drops `appAccountToken`.
437
+
438
+ ## Google Play (`@tofound/billing/providers/google`, 1.0)
439
+
440
+ ```ts
441
+ const google = createGoogleAdapter({
442
+ environment, // required: 'production' | 'sandbox'
443
+ packageName, // a notification for any other package is refused
444
+ products: { [playProductId]: { productRef, amount } },
445
+ pubsub: { audience, serviceAccountEmail }, // who signs the Pub/Sub push
446
+ serviceAccount: { clientEmail, privateKey }, // Play Developer API access
447
+ checkoutPattern?, clock?, fetch?, timeoutMs?,
448
+ })
449
+
450
+ const r = await ingest.handle('google', { headers, rawBody, url, receivedAt }) // RTDN via Pub/Sub push
451
+ const outcome = await ingest.confirm('google', { productId, purchaseToken, checkoutRef }) // → IngestOutcome
452
+ const { deliveries, next } = await google.listChangesSince(cursor, limit) // voidedpurchases.list; see Voids
453
+ ```
454
+
455
+ - **Push verification.** The `Authorization` bearer is Google's OIDC token:
456
+ RS256 against Google's JWKS, with `iss`, `aud` = `pubsub.audience`, the
457
+ signing `email` (verified), `exp` and `iat` all checked. Keys are cached,
458
+ and an unknown `kid` refetches them at most once a minute. A missing or
459
+ forged token, or a notification for another package, is `unauthorized`
460
+ (401), and Play is never called. The event id is `google:<messageId>`.
461
+ - **A purchase is trusted only as Play's answer.** The notification only
462
+ says where to look. The adapter fetches `purchases.products.get` with a
463
+ service-account token (cached; concurrent requests share one fetch) and
464
+ stores that answer. If Play does not know a purchase younger than 10
465
+ minutes, the delivery fails and Pub/Sub redelivers it; an older one goes
466
+ to `needs_review` (`purchase_not_found`). A Play failure is
467
+ `GooglePlayApiError` (`google_unreachable`, `google_error`,
468
+ `google_bad_response`, `google_auth_failed`, `google_not_found`) and is
469
+ transient for the inbox. Purchases are keyed by `orderId`, and the amount
470
+ is the configured product `amount` × quantity. A production adapter
471
+ ignores license testers' purchases (`test_purchase`); pending purchases
472
+ are `ignored` (`purchase_pending`). `product_mismatch` and
473
+ `partial_refund` go to `needs_review`.
474
+ - **Client proofs** share the apply path. Their event id is
475
+ `google:order:<orderId>`, plus the checkout session and the canceled
476
+ state. An unknown or unpaid purchase returns no delivery.
477
+ - **Voids.** An RTDN `voidedPurchaseNotification` and an entry from
478
+ `listChangesSince` both name the order by `orderId`, so either claws back
479
+ once. `listChangesSince(null, limit)` starts 30 days back. `next` resumes
480
+ the list (the next page, or just past the newest void seen) and is null
481
+ only when Play returned no entries at all, so keep the last non-null
482
+ cursor for the next sweep. A page with entries but no deliveries is not
483
+ empty. A cursor this adapter did not issue is
484
+ `ProviderConfigError('google_invalid_cursor')`. `createIngest` has no entry
485
+ for these deliveries yet: `ingest.confirm('google', delivery)` throws
486
+ `VerifyError('malformed')`. Until it does, wrap the adapter's
487
+ `verifyPurchase` so a delivery (an object with `eventId`) passes through
488
+ unchanged. RTDN voids need no shim.
489
+ - **Subscriptions** are out of scope: their notifications are acknowledged
490
+ as `ignored`.
491
+ - **Config errors:** `google_environment_required`,
492
+ `google_package_name_required`, `google_pubsub_auth_required`,
493
+ `google_service_account_required`, `google_invalid_key`,
494
+ `google_invalid_checkout_id`.
495
+ - **`respondGoogle`** maps outcomes like `respondApple`: 2xx for everything
496
+ a redelivery cannot change. The generic redaction drops `purchaseToken`.
497
+
343
498
  ## Catalog, terms and entitlement (0.2)
344
499
 
345
500
  ```ts
@@ -415,3 +570,65 @@ createIngest({ …, handlers: { 'subscription.snapshot': createSnapshotHandler({
415
570
  See [SCHEMA.md](SCHEMA.md). `createDrizzleLedgerStore({ db, tables })` works
416
571
  with any Drizzle Postgres driver; `ledger.in(tx)` takes the host's Drizzle
417
572
  transaction.
573
+
574
+ ## Host kit (`@tofound/billing/hostkit`, 1.0)
575
+
576
+ For hosts that keep their own tables and wire. A worked migration is in
577
+ `docs/MIGRATION-LOHI.md`.
578
+
579
+ **`createLegacyLedgerStore(driver, codec?)`** returns a `LedgerStore` over a
580
+ host's wallet tables. The host's `LegacyWalletDriver<TTx>` does row I/O only:
581
+ - `transaction`;
582
+ - `lockWallet` (insert-or-lock) and `setBalance`;
583
+ - `insertRow` (`ON CONFLICT DO NOTHING` on the key, and on the reversed entry
584
+ id);
585
+ - `getBalance`, `getRow`, `findRowByKey`, `findReversalOf`;
586
+ - `countRows` (optionally only rows before a given row) and `listRows`
587
+ (newest first, limit/offset).
588
+
589
+ All of these work in `(createdAt, id)` order.
590
+
591
+ The kit adds:
592
+ - **seq:** a row's 1-based position in that order. A new row's `createdAt`
593
+ moves to 1 ms after the account's newest row when the clock has not passed
594
+ it.
595
+ - **Old rows:** a key-less pre-adapter row reads as `legacy:<id>`, and its
596
+ kind comes from `codec.kindOf(row)` (default: `topup` for a credit, `spend`
597
+ otherwise).
598
+ - **Reason:** the host reason column is written from `codec.reasonOf(entry)`
599
+ (default `entry.reason ?? entry.kind`).
600
+ - **Library fields** (`kind`, `reversesId`, `sourceType`, `sourceId`,
601
+ `meta`) travel in `LegacyEntryRow.ledger`, which the driver persists, for
602
+ example in one nullable `jsonb`.
603
+
604
+ Acceptance for a driver is `ledgerConformanceCases` on the host's database.
605
+
606
+ **`createAdminAdjustments({ store, overdraft?, keyPrefix?, clock?, ids?, events? })`**
607
+ returns an object whose `adjust(input, tx?)` posts one `adjustment` entry
608
+ under key `<keyPrefix><requestId>` (default prefix `admin:`).
609
+ - The account lock is taken first.
610
+ - A retried request id answers `replayed`.
611
+ - A stale `expectedBalance` answers `{status:'balance_changed', balance}`
612
+ and posts nothing.
613
+ - `overdraft` is `reject` (default; a short debit throws
614
+ `insufficient_credits`) or `clamp` (posts `−min(balance, amount)` and
615
+ reports `shortfall`).
616
+ - `meta.adjustment` records `{actorId, note, requestId}`.
617
+ - The result carries `balanceBefore` and `balanceAfter`.
618
+ - Events go to `events` after the kit's own commit. Under a host `tx` they
619
+ are returned for the host to emit.
620
+
621
+ **`serializeQuote(quote, { labels?, coveredSources? })`** returns the served
622
+ quote:
623
+ - keys in the order `originalPrice, price, currency, reason, funding,
624
+ settlement, canSettle, shortfall?, balance, upsell?, expiresInSec,
625
+ subscriptionCovered?`;
626
+ - unset optionals left out, never `null`;
627
+ - `labels.reason/line/upsell` supply host copy (returning `undefined` keeps
628
+ the step's label);
629
+ - `coveredSources` adds `subscriptionCovered`, which is true when the quote
630
+ settles and only those sources fund it (a pool that funds part of the
631
+ price, with the wallet paying the rest, is not covered).
632
+
633
+ **`serializePlanQuote`** puts `kind, plan, months, market` first and
634
+ `periodStart, periodEnd` (ISO strings or `null`) and `scheduled` last.