@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.
Files changed (67) hide show
  1. package/CHANGELOG.md +136 -1
  2. package/README.md +73 -13
  3. package/dist/catalog/catalog.d.ts +115 -0
  4. package/dist/catalog/catalog.js +201 -0
  5. package/dist/domain/types.d.ts +3 -1
  6. package/dist/drizzle/index.d.ts +2 -0
  7. package/dist/drizzle/index.js +2 -0
  8. package/dist/entitlement/resolve.d.ts +76 -0
  9. package/dist/entitlement/resolve.js +122 -0
  10. package/dist/hostkit/adjustments.d.ts +65 -0
  11. package/dist/hostkit/adjustments.js +84 -0
  12. package/dist/hostkit/index.d.ts +9 -0
  13. package/dist/hostkit/index.js +9 -0
  14. package/dist/hostkit/legacy-ledger.d.ts +87 -0
  15. package/dist/hostkit/legacy-ledger.js +111 -0
  16. package/dist/hostkit/quote-wire.d.ts +73 -0
  17. package/dist/hostkit/quote-wire.js +50 -0
  18. package/dist/index.d.ts +10 -0
  19. package/dist/index.js +9 -0
  20. package/dist/providers/apple/events.d.ts +24 -0
  21. package/dist/providers/apple/events.js +232 -0
  22. package/dist/providers/apple/index.d.ts +54 -0
  23. package/dist/providers/apple/index.js +231 -0
  24. package/dist/providers/apple/jws.d.ts +50 -0
  25. package/dist/providers/apple/jws.js +206 -0
  26. package/dist/providers/google/api.d.ts +57 -0
  27. package/dist/providers/google/api.js +226 -0
  28. package/dist/providers/google/events.d.ts +46 -0
  29. package/dist/providers/google/events.js +135 -0
  30. package/dist/providers/google/index.d.ts +37 -0
  31. package/dist/providers/google/index.js +228 -0
  32. package/dist/providers/polar/events.d.ts +17 -0
  33. package/dist/providers/polar/events.js +213 -0
  34. package/dist/providers/polar/index.d.ts +50 -0
  35. package/dist/providers/polar/index.js +271 -0
  36. package/dist/providers/polar/signature.d.ts +23 -0
  37. package/dist/providers/polar/signature.js +52 -0
  38. package/dist/providers/port.d.ts +6 -0
  39. package/dist/providers/sepay/index.js +29 -0
  40. package/dist/renewal/renewal.d.ts +69 -0
  41. package/dist/renewal/renewal.js +198 -0
  42. package/dist/stores/testing.d.ts +4 -2
  43. package/dist/stores/testing.js +4 -2
  44. package/dist/terms/conformance.d.ts +17 -0
  45. package/dist/terms/conformance.js +198 -0
  46. package/dist/terms/decide.d.ts +97 -0
  47. package/dist/terms/decide.js +176 -0
  48. package/dist/terms/drizzle.d.ts +12 -0
  49. package/dist/terms/drizzle.js +131 -0
  50. package/dist/terms/memory.d.ts +23 -0
  51. package/dist/terms/memory.js +126 -0
  52. package/dist/terms/plans.d.ts +85 -0
  53. package/dist/terms/plans.js +331 -0
  54. package/dist/terms/ports.d.ts +55 -0
  55. package/dist/terms/ports.js +1 -0
  56. package/dist/terms/rules.d.ts +11 -0
  57. package/dist/terms/rules.js +36 -0
  58. package/dist/terms/schema.d.ts +711 -0
  59. package/dist/terms/schema.js +70 -0
  60. package/dist/terms/snapshot.d.ts +20 -0
  61. package/dist/terms/snapshot.js +134 -0
  62. package/dist/terms/types.d.ts +85 -0
  63. package/dist/terms/types.js +4 -0
  64. package/docs/API.md +415 -6
  65. package/docs/MIGRATION-LOHI.md +237 -0
  66. package/docs/SCHEMA.md +57 -2
  67. package/package.json +22 -1
package/docs/API.md CHANGED
@@ -1,15 +1,21 @@
1
- # @tofound/billing — API (0.1)
1
+ # @tofound/billing — API (1.0)
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. 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.
6
8
 
7
9
  | Entry | Contents |
8
10
  |---|---|
9
- | `@tofound/billing` | domain types, money helpers, `BillingError`, `createLedger`, ports, `createMemoryLedgerStore`, waterfall + steps, provider port, `createIngest`, `createMemoryIngestStore` |
10
- | `@tofound/billing/drizzle` | `createBillingTables`, `billingTableBuilder`, `checkAdditiveDdl`, `createDrizzleLedgerStore`, `createIngestTables`, `createDrizzleIngestStore` (peer `drizzle-orm ^0.45`) |
11
+ | `@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/drizzle` | `createBillingTables`, `billingTableBuilder`, `checkAdditiveDdl`, `createDrizzleLedgerStore`, `createIngestTables`, `createDrizzleIngestStore`, `createTermTables`, `createDrizzleTermStore`, `termTableNames` (peer `drizzle-orm ^0.45`) |
11
13
  | `@tofound/billing/providers/sepay` | `createSepayAdapter`, `respondSepay`, `signCheckoutFields`, `parseSepayOrder` |
12
- | `@tofound/billing/testing` | `ledgerConformanceCases`, `assertLedgerInvariants`, `assertQuoteMatchesSettlement`, `ingestConformanceCases`, memory stores |
14
+ | `@tofound/billing/providers/polar` | `createPolarAdapter`, `resolvePolarEnvironment`, `respondPolar`, `redactPolarPayload`, `signPolarWebhook`, `PolarApiError`, `POLAR_WEBHOOK_*` header names and tolerance; types `PolarAdapter`, `PolarAdapterOptions`, `PolarCheckoutRequest`, `PolarKeyDerivation` |
15
+ | `@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` |
16
+ | `@tofound/billing/providers/google` | `createGoogleAdapter`, `respondGoogle`, `GooglePlayApiError`, `GOOGLE_RTDN_EVENT`, `GOOGLE_PURCHASE_EVENT`, `GOOGLE_VOIDED_EVENT`; types `GoogleAdapter`, `GoogleAdapterOptions`, `GoogleProduct`, `GooglePurchaseProof`, `PubSubAuth`, `ServiceAccount` |
17
+ | `@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` |
18
+ | `@tofound/billing/testing` | `ledgerConformanceCases`, `assertLedgerInvariants`, `assertQuoteMatchesSettlement`, `ingestConformanceCases`, `termConformanceCases`, memory stores |
13
19
 
14
20
  The library reads no env, logs nothing and has no runtime dependencies. Every
15
21
  amount is an integer in minor units — a safe-integer `number` in TS, `bigint`
@@ -84,6 +90,11 @@ Invariants every store upholds (design §4.3):
84
90
  | `reversal_exceeds_original` | `reverse` amount > \|original delta\| | `{entryId, amount, original}` |
85
91
  | `already_reversed` | the entry already has its reversal | `{entryId, reversalId?}` |
86
92
  | `balance_overflow` | a result leaves the safe-integer range | — |
93
+ | `invalid_catalog` | `defineCatalog` refuses the host's catalog | the offending key |
94
+ | `plan_not_found` | a plan key the catalog does not have | `{plan}` |
95
+ | `offer_not_found` | the plan is not sold for these months in this market | `{plan, months, market}` |
96
+ | `term_not_found` | auto-renew / cancel with no open credit term | `{accountId}` |
97
+ | `plan_blocked` | a plan purchase the quote refuses | `{reason}` (`covered_by_subscription`) |
87
98
 
88
99
  A plain `Error` (not `BillingError`) signals a broken store or host setup,
89
100
  e.g. a repeating `IdGenerator`; it is never an expected outcome.
@@ -142,6 +153,9 @@ await w.settle(tx, lockedState, { accountId, idempotencyKey }) // same steps, co
142
153
  emit after its commit (the sink is not called inside a host transaction).
143
154
  - `assertQuoteMatchesSettlement(quote, {settled, walletDelta, meterDeltas})`
144
155
  is the conformance check every host runs against real charges.
156
+ `walletDelta` is **balance after − balance before**, so a charge is
157
+ negative: a settled quote must show `walletDelta === -quote.price`, a
158
+ blocked one `0`. `meterDeltas` are the units each pool consumed (positive).
145
159
 
146
160
  ## Provider ingest (`billing.provider-port`)
147
161
 
@@ -191,8 +205,403 @@ await ingest.sweep()
191
205
  plus the ledger's `credited` / `debited` — all after commit; a throwing sink
192
206
  never fails the delivery.
193
207
 
208
+ ## Polar (`@tofound/billing/providers/polar`)
209
+
210
+ ```ts
211
+ const environment = resolvePolarEnvironment({ environment: env.POLAR_ENV, productionEnabled: env.POLAR_PRODUCTION_ENABLED === 'true' })
212
+ const polar = createPolarAdapter({
213
+ environment, // required: 'production' | 'sandbox'
214
+ webhookSecrets: [current, next?], // `whsec_…`; two only while rotating
215
+ products: { [polarProductId]: productRef }, // this environment's Polar products → catalog productRefs
216
+ accessToken?, // organization token: checkout + portal only
217
+ checkoutPattern?, toleranceSec?, clock?, fetch?, timeoutMs?,
218
+ })
219
+ const ingest = createIngest({
220
+ adapters: [polar], store, ledger,
221
+ handlers: { 'subscription.snapshot': createSnapshotHandler({ terms, catalog, resolveAccount }) },
222
+ })
223
+
224
+ const { redirect } = await ingest.createCheckout({ provider: 'polar', accountId, amount, credits, productRef, … }) // a credit pack
225
+ const r = await ingest.handle('polar', { headers, rawBody, url, receivedAt }) // → reply with r.response
226
+ const { url } = await polar.createPortalSession({ kind: 'account_id', value: accountId }, returnUrl) // or kind 'polar_customer_external_id'
227
+ ```
228
+
229
+ | Export | Signature |
230
+ |---|---|
231
+ | `resolvePolarEnvironment` | `({ environment: string \| null \| undefined, productionEnabled: boolean }) → 'production' \| 'sandbox'` |
232
+ | `createPolarAdapter` | `(PolarAdapterOptions) → PolarAdapter` (`ProviderAdapter` + `createCheckout` + `createPortalSession`) |
233
+ | `respondPolar` | `(IngestOutcome) → ProviderResponse`: the adapter's `respond` |
234
+ | `redactPolarPayload` | `(payload) → payload`: the adapter's `redact` (`redactPayload` plus `tax_id`, `custom_field_data`, `avatar_url`, `customer_ip_address`, and any Polar secret inside a value, e.g. the `polar_c_…` client secret in a checkout `url` → `polar_c_[redacted]`) |
235
+ | `signPolarWebhook` | `(secret, id, timestamp, rawBody, derivation = 'standard') → 'v1,<base64>'`: for host tests and fixtures |
236
+
237
+ - **Environment, never inferred.** `resolvePolarEnvironment` turns the host's
238
+ two switches into one value: `sandbox` → sandbox; `production` only with
239
+ `productionEnabled: true`, else `ProviderConfigError('polar_production_disabled')`;
240
+ anything else (unset, typo) → `polar_environment_required`. The adapter has
241
+ no default either, and it picks the API host:
242
+ `api.polar.sh` or `sandbox-api.polar.sh`. Sandbox and production products
243
+ have different ids, so pass the `products` map for the environment you run.
244
+ Other config errors: `polar_webhook_secrets_required`, `polar_invalid_tolerance`.
245
+ - **Standard Webhooks verification** runs on the raw body before any parse.
246
+ The signed content is `${webhook-id}.${webhook-timestamp}.${rawBody}`, HMAC-SHA256, and any
247
+ `v1,` entry of `webhook-signature` may match any secret in
248
+ `webhookSecrets`. Both key derivations are accepted: base64 after `whsec_` (standard) and the whole
249
+ string's UTF-8 (legacy). Comparison is constant-time. A missing header, a
250
+ `webhook-id` over 128 characters, a non-numeric timestamp, a timestamp
251
+ outside ±`toleranceSec` (300 s) or no matching signature → `unauthorized`
252
+ (401). Non-JSON, no `type` / `data`, or a `type` over 64 characters →
253
+ `malformed` (400). Nothing is stored in either case. The event id is
254
+ `polar:<webhook-id>`, so a retry of a message whose row is final is
255
+ `duplicate`; a `failed` row is processed again.
256
+ - **Credit packs.** `createCheckout` refuses an unmapped `productRef`
257
+ (exactly one Polar product per ref), a non-positive amount, or a session id
258
+ that is not `checkoutPattern` before any call (`ProviderConfigError` codes
259
+ `polar_unknown_product`, `polar_invalid_amount`, `polar_invalid_checkout_id`,
260
+ and `polar_not_configured` without a token). A failed call is `PolarApiError`
261
+ (`polar_unreachable`, `polar_error` with `status`, `polar_bad_response`). It then creates a Polar checkout
262
+ with `external_customer_id = accountId`, `metadata.checkout_id = sessionId`
263
+ and `allow_discount_codes: false`. A response whose currency or `amount`
264
+ (the product price before discount and tax) differs from the catalog amount,
265
+ or that carries a `discount_amount`, is refused as `polar_price_mismatch`.
266
+ The checkout's `net_amount` is not compared: it drops by the tax once a
267
+ tax-inclusive country is known.
268
+ The Polar checkout already exists by then; it is never handed to the buyer.
269
+ The session id comes from the ingest's `ids` (default `randomUUID`), so a custom
270
+ generator must match `checkoutPattern`, or every checkout throws
271
+ `polar_invalid_checkout_id`. `PolarCheckoutRequest.customerIpAddress` (sent for tax
272
+ country) is only accepted by a direct `polar.createCheckout` call;
273
+ `ingest.createCheckout` does not forward it.
274
+ `order.paid` for a one-time order becomes `purchase.completed`, bound to the
275
+ session by `metadata.checkout_id` and credited once (`topup:<sessionId>`).
276
+ Its amount is the catalog price, `subtotal_amount − discount_amount`, which
277
+ reads the same whatever the organization's tax behaviour: a tax-inclusive
278
+ $5.00 order (a DE buyer under `location`) has `net_amount` 420 and
279
+ `tax_amount` 80, a tax-exclusive one `total_amount` 540, and both are 500
280
+ here. `net_amount` and `total_amount` are never used; an order without a
281
+ readable subtotal is `needs_review` (`invalid_amount`). If the amount differs
282
+ from the session (a discount), the order goes to `needs_review`
283
+ (`amount_mismatch`) and nothing is credited. `order.created` / `order.updated` move no money, and a
284
+ subscription's own orders are receipts (`ignored`).
285
+ - **Refunds.** `order.refunded` with status `refunded` becomes
286
+ `purchase.reversed`, its amount on the same basis as the order's
287
+ (`refunded_amount` is not compared: it excludes a tax-inclusive order's tax). The reversal claws back once, in any order relative to
288
+ `order.paid`: a refund delivered first, carrying our `metadata.checkout_id`,
289
+ voids the session, and the late paid order never credits (a refund matching
290
+ neither a session nor a purchase is `ignored`, `no_match`). A partial refund is `needs_review` (`partial_refund`)
291
+ and is never guessed into a clawback.
292
+ - **Subscriptions.** `subscription.*` events become `subscription.snapshot` with
293
+ `account = { kind: 'polar_customer_external_id', value: external_customer_id }`.
294
+ The status maps as follows:
295
+ - `active` / `trialing` → `active`
296
+ - `past_due` / `unpaid` → `past_due`
297
+ - `canceled` → `active` (ends at period end), or `expired` when `ended_at` is at
298
+ or before the event's own `modified_at`
299
+ - revoked or paused → `revoked`
300
+
301
+ Statuses Polar sets before any payment (`incomplete`…) are `ignored`. Each
302
+ snapshot is watermarked by Polar's `modified_at`. Polar sends one change as
303
+ several events with the same `modified_at` (a revoke is `updated`,
304
+ `canceled` and `revoked`), so the event type breaks the tie (`tieBreak`):
305
+ `revoked` > `paused` > `canceled` > `uncanceled` > `past_due` > `active` >
306
+ `updated` > `created`. A revoke therefore ends `revoked` in any arrival
307
+ order; the outranked copies are `ignored` (`stale`). The period ends at
308
+ `ended_at` when that is before `current_period_end`. A product not in `products`
309
+ is `ignored` (`unknown_product`). Without a `subscription.snapshot` handler,
310
+ a snapshot is `needs_review` (`no_handler:…`).
311
+ - **Subscription checkouts** do not go through the ingest:
312
+ `ingest.createCheckout` sells credit packs (a session, credits on
313
+ `order.paid`). For a plan, call `polar.createCheckout` directly with a fresh
314
+ UUID `sessionId` (it is only carried in `metadata`), the plan offer's
315
+ `productRef` and its catalog price (the price guard applies). No session row
316
+ is written: the subscription reaches the terms through `subscription.*`
317
+ events bound by `external_customer_id = accountId`, and its orders are
318
+ receipts.
319
+ - **Webhook events to subscribe:** `order.paid`, `order.refunded`,
320
+ `subscription.created` / `.updated` / `.active` / `.canceled` /
321
+ `.uncanceled` / `.revoked` (and `.past_due` where offered). `checkout.*`
322
+ is not needed: the ingest has no `checkout.status` handler, so those
323
+ deliveries are verified, stored and `ignored` (`no_handler:checkout.status`),
324
+ which is harmless but fills the inbox (about half of the rows in a sandbox
325
+ run). The order carries everything a credit needs.
326
+ - **What the host wires:**
327
+ - **Environment and secrets:** resolve the environment once at boot, keep
328
+ the secrets server-side and pass the access token only where checkout or
329
+ the portal runs.
330
+ - **Webhook route:** a raw-body route that answers with `r.response`.
331
+ `respondPolar` acknowledges every outcome a retry cannot change with 200
332
+ and answers 5xx only on `failed`. A relayed delivery returns the
333
+ `onUnmatched` response as is.
334
+ - **`resolveAccount`:** maps the external customer id back to your account.
335
+ It returns `null` for another host's customers on a shared organization.
336
+ Only a subscription whose product is in `products` reaches it; that
337
+ `null` is relayed through `onUnmatched`. A subscription on an unmapped
338
+ product is `ignored` (`unknown_product`) and is not relayed. Another
339
+ host's one-time order goes to `needs_review` (`unsupported_account_ref`
340
+ or `unbound_order`, alerted), unless its `metadata.checkout_id` is a
341
+ session id this host's pattern accepts that matches none of its sessions;
342
+ that order is relayed as unmatched.
343
+ - **Catalog:** one Polar `productRef` per offer.
344
+ - **Monitoring:** watch the `billing.alert` events. `PolarApiError` never
345
+ carries the token or Polar's response body. A portal for any other
346
+ account kind is refused (`ProviderConfigError('polar_unsupported_account')`).
347
+
348
+ ## App Store (`@tofound/billing/providers/apple`, 1.0)
349
+
350
+ ```ts
351
+ const apple = createAppleAdapter({
352
+ environment, // required: 'production' | 'sandbox'
353
+ bundleId, // a payload for any other app is refused
354
+ products: { [appStoreProductId]: { productRef, amount? } }, // amount required for one-time products
355
+ appAppleId?, // checked when the notification carries one
356
+ serverApi?: { issuerId, keyId, privateKey }, // the .p8 key; only for reportConsumption
357
+ checkoutPattern?, clock?, fetch?, timeoutMs?,
358
+ // trustedRoots?: tests only — production trusts the pinned Apple Root CA G3 alone
359
+ })
360
+ const ingest = createIngest({ adapters: [apple], store, ledger, handlers: { 'subscription.snapshot': … } })
361
+
362
+ const r = await ingest.handle('apple', { headers, rawBody, url, receivedAt }) // App Store Server Notifications v2
363
+ const outcome = await ingest.confirm('apple', { signedTransaction, checkoutRef }) // StoreKit 2 client proof → IngestOutcome
364
+ await apple.reportConsumption(transactionId, info) // App Store Server API
365
+ ```
366
+
367
+ - **Verification.** Every JWS (`signedPayload`, `signedTransactionInfo`,
368
+ `signedRenewalInfo`, a client's `signedTransaction`) is ES256 over its
369
+ `x5c` chain. The chain must end at the pinned Apple Root CA G3
370
+ (`APPLE_ROOT_CA_G3_SHA256`). The leaf must carry the receipt-signing marker
371
+ OID and the intermediate the WWDR OID, and every certificate must be valid
372
+ at `clock()`. A payload for another `bundleId`, another `appAppleId` or the
373
+ other environment is `unauthorized` (401): a production adapter refuses
374
+ Sandbox payloads. Non-JSON, no `signedPayload`, or a notification without
375
+ its type, `notificationUUID` or `signedDate` is `malformed` (400). The event
376
+ id is `apple:<notificationUUID>`; a client proof's is
377
+ `apple:txn:<transactionId>`, plus the checkout session and the revoked
378
+ state when present. So the app's retry is a `duplicate`, and a proof that
379
+ can end differently is a new event.
380
+ - **One-time products** are purchases keyed by `transactionId`.
381
+ `ONE_TIME_CHARGE` or a client proof completes one. The amount is the
382
+ configured product `amount` × quantity, because the product id is the price
383
+ authority. `REFUND` and `REVOKE` reverse it, and `REFUND_REVERSED`
384
+ reinstates it. Each carries its `signedDate` as a watermark, so a stale
385
+ notification is ignored whatever order they arrive in.
386
+ - **Only checkout-bound purchases credit.** A purchase names the session
387
+ through the proof's `checkoutRef`, or because its `appAccountToken`
388
+ matches `checkoutPattern` (UUID by default). A notification naming no
389
+ session is `ignored` (`unbound_purchase`), and the app's proof settles it.
390
+ Other reasons for a one-time purchase: `unknown_product`,
391
+ `product_amount_missing` and `invalid_quantity` go to `needs_review`.
392
+ `TEST` notifications are ignored (`test_notification`).
393
+ - **Auto-renewable subscriptions** become `subscription.snapshot` keyed by
394
+ `originalTransactionId`, with a deterministic `tieBreak`. A refund or
395
+ revoke ends access now. A subscription without an `appAccountToken` is
396
+ `ignored` (`no_account_token`), and one whose product is not in
397
+ `products` is `ignored` (`unknown_product`). Neither alerts, so every
398
+ subscription product must be listed and every purchase must carry the
399
+ account token.
400
+ - **Errors.** Config: `ProviderConfigError` `apple_environment_required`,
401
+ `apple_bundle_id_required`, `apple_invalid_root`,
402
+ `apple_invalid_checkout_id`, `apple_server_api_not_configured`,
403
+ `apple_server_api_invalid_key`. A Server API failure is `AppleApiError`
404
+ (`apple_unreachable`, `apple_error` with `status`). It never carries the
405
+ token or the response body.
406
+ - **`respondApple`**: 401 / 400 / 500 for `unauthorized` / `malformed` /
407
+ `failed`, and 200 for everything else, because Apple retries any non-2xx
408
+ for days. The stored payload keeps the decoded transaction, not the JWS,
409
+ and the generic redaction drops `appAccountToken`.
410
+
411
+ ## Google Play (`@tofound/billing/providers/google`, 1.0)
412
+
413
+ ```ts
414
+ const google = createGoogleAdapter({
415
+ environment, // required: 'production' | 'sandbox'
416
+ packageName, // a notification for any other package is refused
417
+ products: { [playProductId]: { productRef, amount } },
418
+ pubsub: { audience, serviceAccountEmail }, // who signs the Pub/Sub push
419
+ serviceAccount: { clientEmail, privateKey }, // Play Developer API access
420
+ checkoutPattern?, clock?, fetch?, timeoutMs?,
421
+ })
422
+
423
+ const r = await ingest.handle('google', { headers, rawBody, url, receivedAt }) // RTDN via Pub/Sub push
424
+ const outcome = await ingest.confirm('google', { productId, purchaseToken, checkoutRef }) // → IngestOutcome
425
+ const { deliveries, next } = await google.listChangesSince(cursor, limit) // voidedpurchases.list; see Voids
426
+ ```
427
+
428
+ - **Push verification.** The `Authorization` bearer is Google's OIDC token:
429
+ RS256 against Google's JWKS, with `iss`, `aud` = `pubsub.audience`, the
430
+ signing `email` (verified), `exp` and `iat` all checked. Keys are cached,
431
+ and an unknown `kid` refetches them at most once a minute. A missing or
432
+ forged token, or a notification for another package, is `unauthorized`
433
+ (401), and Play is never called. The event id is `google:<messageId>`.
434
+ - **A purchase is trusted only as Play's answer.** The notification only
435
+ says where to look. The adapter fetches `purchases.products.get` with a
436
+ service-account token (cached; concurrent requests share one fetch) and
437
+ stores that answer. If Play does not know a purchase younger than 10
438
+ minutes, the delivery fails and Pub/Sub redelivers it; an older one goes
439
+ to `needs_review` (`purchase_not_found`). A Play failure is
440
+ `GooglePlayApiError` (`google_unreachable`, `google_error`,
441
+ `google_bad_response`, `google_auth_failed`, `google_not_found`) and is
442
+ transient for the inbox. Purchases are keyed by `orderId`, and the amount
443
+ is the configured product `amount` × quantity. A production adapter
444
+ ignores license testers' purchases (`test_purchase`); pending purchases
445
+ are `ignored` (`purchase_pending`). `product_mismatch` and
446
+ `partial_refund` go to `needs_review`.
447
+ - **Client proofs** share the apply path. Their event id is
448
+ `google:order:<orderId>`, plus the checkout session and the canceled
449
+ state. An unknown or unpaid purchase returns no delivery.
450
+ - **Voids.** An RTDN `voidedPurchaseNotification` and an entry from
451
+ `listChangesSince` both name the order by `orderId`, so either claws back
452
+ once. `listChangesSince(null, limit)` starts 30 days back. `next` resumes
453
+ the list (the next page, or just past the newest void seen) and is null
454
+ only when Play returned no entries at all, so keep the last non-null
455
+ cursor for the next sweep. A page with entries but no deliveries is not
456
+ empty. A cursor this adapter did not issue is
457
+ `ProviderConfigError('google_invalid_cursor')`. `createIngest` has no entry
458
+ for these deliveries yet: `ingest.confirm('google', delivery)` throws
459
+ `VerifyError('malformed')`. Until it does, wrap the adapter's
460
+ `verifyPurchase` so a delivery (an object with `eventId`) passes through
461
+ unchanged. RTDN voids need no shim.
462
+ - **Subscriptions** are out of scope: their notifications are acknowledged
463
+ as `ignored`.
464
+ - **Config errors:** `google_environment_required`,
465
+ `google_package_name_required`, `google_pubsub_auth_required`,
466
+ `google_service_account_required`, `google_invalid_key`,
467
+ `google_invalid_checkout_id`.
468
+ - **`respondGoogle`** maps outcomes like `respondApple`: 2xx for everything
469
+ a redelivery cannot change. The generic redaction drops `purchaseToken`.
470
+
471
+ ## Catalog, terms and entitlement (0.2)
472
+
473
+ ```ts
474
+ const catalog = defineCatalog({ version, creditUnit, markets: [{ key: 'vn', currency: 'VND' }], plans, creditPacks?, policies? })
475
+ const terms = createDrizzleTermStore({ db, tables: { billingTerms, billingTermAccounts } }) // memory: createMemoryTermStore(ledgerStore)
476
+ const plans = createPlans({ ledger, terms, catalog, events? })
477
+ const renewal = createRenewal({ ledger, terms, catalog, marketOf?, events? })
478
+
479
+ const quote = await plans.quote({ accountId, plan: 'pro', months: 3, market }) // market set by the host, never the client
480
+ const bought = await plans.purchase({ accountId, plan: 'pro', months: 3, market, idempotencyKey })
481
+ const ent = resolveEntitlement(await terms.reader().listTerms(accountId), new Date(), catalog, { balance })
482
+ await renewal.renewDue() // host cron, under its own advisory lock
483
+ await renewal.retryPastDue(accountId) // after a top-up commits, in its own transaction
484
+ createIngest({ …, handlers: { 'subscription.snapshot': createSnapshotHandler({ terms, catalog, resolveAccount }) } })
485
+ ```
486
+
487
+ - **The catalog is the host's config**: plans (strict `rank`, exactly one
488
+ `free`), credit offers per `market` × `months`, provider offers by
489
+ `productRef`, packs and `policies` (`termDays` 30, `upgradeProration`
490
+ `remaining_time` | `none`, `graceDays` 3, `renewalLeadSec`). The library has
491
+ no plan or price literal.
492
+ - **Terms** (`billing_terms`) are one shape for credit, Polar, Apple and Google.
493
+ Credit terms are written only by plans and renewal; provider terms only by
494
+ the snapshot handler, under a watermark (an older snapshot is `ignored`).
495
+ At most one open (`active` | `grace` | `past_due`) credit term and one
496
+ `scheduled` term per account. Every writer locks the account's terms
497
+ first (`lockAccountTerms`, through the `term_accounts` guard row), then
498
+ the ledger account last.
499
+ - **Entitlement** (S1): the highest-rank entitled term wins, then the later
500
+ end, then the older term; quotas and permissions never sum; nothing entitled
501
+ → the free plan. A `past_due` term is entitled (`status: 'grace'`) until
502
+ `graceUntil`. `includedCredits` comes only from provider-funded terms.
503
+ Warnings: `two_subscriptions` (S5), `past_due`, `renewal_shortfall` (pass
504
+ `balance`), `scheduled_downgrade`.
505
+ - **Plan quotes** walk one waterfall (covered → credits) for both the quote
506
+ and the purchase, so `assertQuoteMatchesSettlement` holds. `kind`:
507
+ `new`; `extend` (S2, same plan, months appended, charged in full);
508
+ `upgrade` (end date kept; `remaining_time` charges
509
+ ceil(remaining/total × (offerNew − paid)), `originalPrice` is the unprorated
510
+ difference); `renew` (paying a past_due term, from its old end);
511
+ `downgrade` (S3b, no money now: the renewal switches plan under auto-renew,
512
+ otherwise a `scheduled` term charged when it starts; also after a
513
+ non-renewing subscription of ≥ rank, reason `scheduled_after_subscription`);
514
+ `blocked` (S3, a renewing subscription of ≥ rank, reason
515
+ `covered_by_subscription`). A new term supersedes a `scheduled` one that
516
+ would start inside it. The purchase writes term rows before the debit, so
517
+ a throw relies on the rollback: under `plans.in(tx)` the host must roll its
518
+ transaction back. A repeated `idempotencyKey` replays — from its ledger
519
+ entry, or for a purchase that charged nothing from the term that recorded
520
+ the key (the last 20 per term), whatever the term's status since.
521
+ - **Renewal** (D9) charges the **live** catalog price of
522
+ `nextPlanKey ?? planKey` (`plan_renewal`, key
523
+ `renew:<termId>:<periodEnd ISO>`, so a double run debits once). A short
524
+ balance makes the term `past_due` with `graceUntil = periodEnd + graceDays`
525
+ and emits `renewal_failed {required, balance, shortfall}`; grace passed →
526
+ `expired`. An early attempt inside `renewalLeadSec` that fails emits
527
+ `renewal_failed` but leaves the paid period `active` (outcome `skipped`);
528
+ the next run tries again.
529
+ - **S4 supersede**: an entitled provider subscription of ≥ rank closes the
530
+ credit term (`superseded`) and refunds its unused share,
531
+ ceil(remaining/total × paid), as `plan_refund` keyed `supersede:<termId>`.
532
+ A snapshot whose account `resolveAccount` does not know is `ignored`
533
+ (`no_match`) and relayed through `onUnmatched`, before its product is
534
+ checked (another host's subscription on a shared provider account); a
535
+ subscription already bound to another account is `needs_review`
536
+ (`account_mismatch`).
537
+ - Events after commit: `term_changed {change, term}`, `renewal_failed`, plus
538
+ the ledger's `credited` / `debited`; under `.in(tx)` they come back in the
539
+ result.
540
+
194
541
  ## Drizzle
195
542
 
196
543
  See [SCHEMA.md](SCHEMA.md). `createDrizzleLedgerStore({ db, tables })` works
197
544
  with any Drizzle Postgres driver; `ledger.in(tx)` takes the host's Drizzle
198
545
  transaction.
546
+
547
+ ## Host kit (`@tofound/billing/hostkit`, 1.0)
548
+
549
+ For hosts that keep their own tables and wire. A worked migration is in
550
+ `docs/MIGRATION-LOHI.md`.
551
+
552
+ **`createLegacyLedgerStore(driver, codec?)`** returns a `LedgerStore` over a
553
+ host's wallet tables. The host's `LegacyWalletDriver<TTx>` does row I/O only:
554
+ - `transaction`;
555
+ - `lockWallet` (insert-or-lock) and `setBalance`;
556
+ - `insertRow` (`ON CONFLICT DO NOTHING` on the key, and on the reversed entry
557
+ id);
558
+ - `getBalance`, `getRow`, `findRowByKey`, `findReversalOf`;
559
+ - `countRows` (optionally only rows before a given row) and `listRows`
560
+ (newest first, limit/offset).
561
+
562
+ All of these work in `(createdAt, id)` order.
563
+
564
+ The kit adds:
565
+ - **seq:** a row's 1-based position in that order. A new row's `createdAt`
566
+ moves to 1 ms after the account's newest row when the clock has not passed
567
+ it.
568
+ - **Old rows:** a key-less pre-adapter row reads as `legacy:<id>`, and its
569
+ kind comes from `codec.kindOf(row)` (default: `topup` for a credit, `spend`
570
+ otherwise).
571
+ - **Reason:** the host reason column is written from `codec.reasonOf(entry)`
572
+ (default `entry.reason ?? entry.kind`).
573
+ - **Library fields** (`kind`, `reversesId`, `sourceType`, `sourceId`,
574
+ `meta`) travel in `LegacyEntryRow.ledger`, which the driver persists, for
575
+ example in one nullable `jsonb`.
576
+
577
+ Acceptance for a driver is `ledgerConformanceCases` on the host's database.
578
+
579
+ **`createAdminAdjustments({ store, overdraft?, keyPrefix?, clock?, ids?, events? })`**
580
+ returns an object whose `adjust(input, tx?)` posts one `adjustment` entry
581
+ under key `<keyPrefix><requestId>` (default prefix `admin:`).
582
+ - The account lock is taken first.
583
+ - A retried request id answers `replayed`.
584
+ - A stale `expectedBalance` answers `{status:'balance_changed', balance}`
585
+ and posts nothing.
586
+ - `overdraft` is `reject` (default; a short debit throws
587
+ `insufficient_credits`) or `clamp` (posts `−min(balance, amount)` and
588
+ reports `shortfall`).
589
+ - `meta.adjustment` records `{actorId, note, requestId}`.
590
+ - The result carries `balanceBefore` and `balanceAfter`.
591
+ - Events go to `events` after the kit's own commit. Under a host `tx` they
592
+ are returned for the host to emit.
593
+
594
+ **`serializeQuote(quote, { labels?, coveredSources? })`** returns the served
595
+ quote:
596
+ - keys in the order `originalPrice, price, currency, reason, funding,
597
+ settlement, canSettle, shortfall?, balance, upsell?, expiresInSec,
598
+ subscriptionCovered?`;
599
+ - unset optionals left out, never `null`;
600
+ - `labels.reason/line/upsell` supply host copy (returning `undefined` keeps
601
+ the step's label);
602
+ - `coveredSources` adds `subscriptionCovered`, which is true when the quote
603
+ settles and only those sources fund it (a pool that funds part of the
604
+ price, with the wallet paying the rest, is not covered).
605
+
606
+ **`serializePlanQuote`** puts `kind, plan, months, market` first and
607
+ `periodStart, periodEnd` (ISO strings or `null`) and `scheduled` last.