@tofound/billing 0.2.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.
@@ -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
+ }
@@ -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,8 +1,10 @@
1
- # @tofound/billing — API (0.2)
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
  |---|---|
@@ -10,6 +12,9 @@ Part of the `billing.public-api` contract with `src/index.ts` and
10
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
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` |
13
18
  | `@tofound/billing/testing` | `ledgerConformanceCases`, `assertLedgerInvariants`, `assertQuoteMatchesSettlement`, `ingestConformanceCases`, `termConformanceCases`, memory stores |
14
19
 
15
20
  The library reads no env, logs nothing and has no runtime dependencies. Every
@@ -340,6 +345,129 @@ const { url } = await polar.createPortalSession({ kind: 'account_id', value: acc
340
345
  carries the token or Polar's response body. A portal for any other
341
346
  account kind is refused (`ProviderConfigError('polar_unsupported_account')`).
342
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
+
343
471
  ## Catalog, terms and entitlement (0.2)
344
472
 
345
473
  ```ts
@@ -415,3 +543,65 @@ createIngest({ …, handlers: { 'subscription.snapshot': createSnapshotHandler({
415
543
  See [SCHEMA.md](SCHEMA.md). `createDrizzleLedgerStore({ db, tables })` works
416
544
  with any Drizzle Postgres driver; `ledger.in(tx)` takes the host's Drizzle
417
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.