@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.
@@ -1,11 +1,33 @@
1
- import type { AccountId, BillingEvent } from '../domain/types.js';
1
+ import type { AccountId, BillingEvent, LedgerEntry } from '../domain/types.js';
2
2
  import type { LedgerOps } from '../ledger/ledger.js';
3
3
  import type { NormalizedEvent, PurchaseChangedEvent, PurchaseCompletedEvent, VerifiedDelivery } from '../providers/port.js';
4
4
  import type { IngestTx } from './ports.js';
5
5
  export type ApplyStatus = 'applied' | 'ignored' | 'needs_review';
6
+ /**
7
+ * A credit this apply posted, reported so `afterCredited` can fire once the
8
+ * transaction has committed. A host handler sets it on its result when it
9
+ * credits an account itself (Lohi's SePay / Apple / Google top-ups).
10
+ */
11
+ export interface HandlerCredited {
12
+ accountId: AccountId;
13
+ /** The crediting ledger entry (`delta > 0`); a zero or negative entry never fires the hook. */
14
+ entry: LedgerEntry;
15
+ /** `completed`: the credit of a capture. `reinstated`: credit a provider reinstatement gave back or released (a capture parked under a reversal). */
16
+ kind: 'completed' | 'reinstated';
17
+ /** The provider's purchase id, when the handler knows it. */
18
+ externalId?: string | null;
19
+ /** The checkout session the credit settles, when there is one. */
20
+ sessionId?: string | null;
21
+ }
6
22
  export interface ApplyResult {
7
23
  status: ApplyStatus;
8
24
  reason?: string;
25
+ /**
26
+ * An account this apply credited. Fires `afterCredited` after commit,
27
+ * whatever the `status` (a credit that committed is announced), but not when
28
+ * the entry is empty. Absent on a duplicate, replay, ignore or reversal.
29
+ */
30
+ credited?: HandlerCredited;
9
31
  /** No session or purchase on this host owns the event (the `onUnmatched` hook may forward it). */
10
32
  unmatched?: boolean;
11
33
  /** Ledger events to emit after commit. */
@@ -28,8 +50,14 @@ export interface ApplyContext<TTx = unknown> {
28
50
  ledger: LedgerOps;
29
51
  delivery: VerifiedDelivery;
30
52
  now: Date;
53
+ /** The ingest store bound to `tx`: what `defaultEventHandlers` apply through. Valid only inside the handler's transaction. */
54
+ store: IngestTx;
55
+ /** The ingest's id generator, for rows a delegated library applier inserts. */
56
+ newId: () => string;
31
57
  }
32
58
  export type EventHandler<TTx = unknown> = (event: NormalizedEvent, ctx: ApplyContext<TTx>) => Promise<ApplyResult>;
59
+ /** What an {@link EventHandler} returns. */
60
+ export type HandlerResult = ApplyResult;
33
61
  interface Deps {
34
62
  tx: IngestTx;
35
63
  ledger: LedgerOps;
@@ -45,4 +73,22 @@ export declare function applyPurchaseCompleted(event: PurchaseCompletedEvent, d:
45
73
  * arrive in, the purchase ends where the newest event puts it.
46
74
  */
47
75
  export declare function applyPurchaseChanged(event: PurchaseChangedEvent, d: Deps): Promise<ApplyResult>;
76
+ /**
77
+ * The library's own appliers, keyed by the event kind they handle. A host
78
+ * that overrides one kind (Lohi's `purchase.completed` over its own top-up
79
+ * table) hands the deliveries it does not own back to these, per provider:
80
+ *
81
+ * ```ts
82
+ * handlers: { 'purchase.completed': (e, ctx) =>
83
+ * ctx.delivery.provider === 'polar' ? defaultEventHandlers['purchase.completed'](e, ctx) : lohiTopup(e, ctx) }
84
+ * ```
85
+ *
86
+ * They apply through `ctx.store` inside the handler's transaction and report
87
+ * the credit they post in `credited`.
88
+ */
89
+ export declare const defaultEventHandlers: {
90
+ readonly 'purchase.completed': EventHandler<unknown>;
91
+ readonly 'purchase.reversed': EventHandler<unknown>;
92
+ readonly 'purchase.reinstated': EventHandler<unknown>;
93
+ };
48
94
  export {};
@@ -11,6 +11,10 @@
11
11
  */
12
12
  import { isBillingError } from '../domain/errors.js';
13
13
  import { isNewer } from './watermark.js';
14
+ /** The `credited` field for a fresh entry: a keyed replay posted nothing new. */
15
+ const creditedOf = (posted, kind, ref) => !posted.replayed
16
+ ? { credited: { accountId: posted.entry.accountId, entry: posted.entry, kind, externalId: ref.externalId, sessionId: ref.sessionId } }
17
+ : {};
14
18
  const sameMoney = (a, b) => a.currency === b.currency && a.amountMinor === b.amountMinor;
15
19
  /** The one ledger key of a checkout's credit: whichever path pays it, it is paid once. */
16
20
  const topupKey = (sessionId) => `topup:${sessionId}`;
@@ -117,6 +121,7 @@ export async function applyPurchaseCompleted(event, d) {
117
121
  status: 'applied',
118
122
  ...(session.status === 'pending' ? {} : { reason: `late_${session.status}` }),
119
123
  events: posted.events,
124
+ ...creditedOf(posted, 'completed', { externalId: event.externalId, sessionId: session.id }),
120
125
  };
121
126
  }
122
127
  /**
@@ -225,6 +230,7 @@ async function reinstate(purchase, mark, d) {
225
230
  return { status: 'ignored', reason: 'not_reversed' };
226
231
  }
227
232
  let events = [];
233
+ let credited = {};
228
234
  const patch = {
229
235
  status: 'reinstated',
230
236
  clawedBack: 0,
@@ -245,6 +251,7 @@ async function reinstate(purchase, mark, d) {
245
251
  meta: { provider: purchase.provider, externalId: purchase.externalId, amount: purchase.amount },
246
252
  });
247
253
  events = posted.events;
254
+ credited = creditedOf(posted, 'reinstated', { externalId: purchase.externalId, sessionId: pending.sessionId });
248
255
  Object.assign(patch, { credits: pending.credits, creditEntryId: posted.entry.id, meta: withoutPending(purchase.meta) });
249
256
  // The session is paid now: a second capture of it is money for a human.
250
257
  await d.tx.updateSession(pending.sessionId, { status: 'completed', externalId: purchase.externalId, completedAt: d.now });
@@ -260,11 +267,35 @@ async function reinstate(purchase, mark, d) {
260
267
  source: { type: 'purchase', id: purchase.id },
261
268
  });
262
269
  events = posted.events;
270
+ credited = creditedOf(posted, 'reinstated', { externalId: purchase.externalId, sessionId: purchase.checkoutSessionId });
263
271
  patch.creditEntryId = posted.entry.id;
264
272
  }
265
273
  await d.tx.updatePurchase(purchase.id, patch);
266
- return { status: 'applied', events };
274
+ return { status: 'applied', events, ...credited };
267
275
  }
276
+ /**
277
+ * The library's own appliers, keyed by the event kind they handle. A host
278
+ * that overrides one kind (Lohi's `purchase.completed` over its own top-up
279
+ * table) hands the deliveries it does not own back to these, per provider:
280
+ *
281
+ * ```ts
282
+ * handlers: { 'purchase.completed': (e, ctx) =>
283
+ * ctx.delivery.provider === 'polar' ? defaultEventHandlers['purchase.completed'](e, ctx) : lohiTopup(e, ctx) }
284
+ * ```
285
+ *
286
+ * They apply through `ctx.store` inside the handler's transaction and report
287
+ * the credit they post in `credited`.
288
+ */
289
+ export const defaultEventHandlers = Object.freeze({
290
+ 'purchase.completed': handlerFor('purchase.completed', (event, d) => applyPurchaseCompleted(event, d)),
291
+ 'purchase.reversed': handlerFor('purchase.reversed', (event, d) => applyPurchaseChanged(event, d)),
292
+ 'purchase.reinstated': handlerFor('purchase.reinstated', (event, d) => applyPurchaseChanged(event, d)),
293
+ });
294
+ /** An event of another kind than the one a default handler is for is refused, not misapplied. */
295
+ function handlerFor(kind, apply) {
296
+ return async (event, ctx) => event.kind === kind ? apply(event, depsOf(ctx)) : { status: 'ignored', reason: `no_handler:${event.kind}` };
297
+ }
298
+ const depsOf = (ctx) => ({ tx: ctx.store, ledger: ctx.ledger, delivery: ctx.delivery, now: ctx.now, newId: ctx.newId });
268
299
  /**
269
300
  * Counter the purchase's crediting entry by what the balance still holds;
270
301
  * the rest of the purchase's credits is the shortfall (design §4.11 — the
@@ -1,8 +1,8 @@
1
- import type { AccountId, BillingEvent, Money } from '../domain/types.js';
1
+ import type { AccountId, BillingEvent, LedgerEntry, Money } from '../domain/types.js';
2
2
  import type { Ledger } from '../ledger/ledger.js';
3
3
  import type { Clock, IdGenerator } from '../ports/runtime.js';
4
4
  import { type CheckoutRedirect, type InboundRequest, type IngestOutcome, type NormalizedEvent, type ProviderAdapter, type ProviderId, type ProviderResponse, type VerifiedDelivery } from '../providers/port.js';
5
- import { type EventHandler, type PurchaseReversed } from './apply.js';
5
+ import { type EventHandler, type HandlerCredited, type PurchaseReversed } from './apply.js';
6
6
  import { type CheckoutSession, type IngestReader, type IngestStore } from './ports.js';
7
7
  /** Structured events for the host's metrics, alerts and bus (design §13). */
8
8
  export type IngestEvent = {
@@ -46,6 +46,30 @@ export type UnmatchedHook = (input: {
46
46
  request: InboundRequest;
47
47
  delivery: VerifiedDelivery;
48
48
  }) => Promise<ProviderResponse | void>;
49
+ /** An account the ingest credited, handed to `afterCredited` once the credit has committed. */
50
+ export interface CreditedPurchase {
51
+ provider: ProviderId;
52
+ accountId: AccountId;
53
+ /** `completed`: the credit of a capture. `reinstated`: credit a provider reinstatement gave back or released (a capture parked under a reversal). */
54
+ kind: HandlerCredited['kind'];
55
+ /** The crediting ledger entry (`delta > 0`). */
56
+ entry: LedgerEntry;
57
+ /** The provider's purchase id, when the applier knows it. */
58
+ externalId: string | null;
59
+ /** The checkout session the credit settles, when there is one. */
60
+ sessionId: string | null;
61
+ }
62
+ /**
63
+ * Runs after the inbox transaction commits, at most once per credit, for the
64
+ * library's own appliers and for host handlers that return `credited`. Never
65
+ * for a duplicate, a replay of a settled row, an ignored delivery or an empty
66
+ * entry. A throw (or a rejection) goes to `onHookError` and changes nothing:
67
+ * the delivery stays `applied`. A process crash between the commit and the
68
+ * hook loses the call, so the host keeps a periodic backstop (Lohi: the
69
+ * renewal tick). The hook is awaited before the provider is answered, so keep
70
+ * it short: hand slow work to a queue.
71
+ */
72
+ export type AfterCreditedHook = (credited: CreditedPurchase) => void | Promise<void>;
49
73
  export interface IngestOptions<TTx> {
50
74
  adapters: readonly ProviderAdapter[];
51
75
  /** Must share its transactions with the ledger's store. */
@@ -56,8 +80,12 @@ export interface IngestOptions<TTx> {
56
80
  policy?: IngestPolicy;
57
81
  events?: IngestEventSink;
58
82
  onUnmatched?: UnmatchedHook;
59
- /** Appliers for event kinds the library does not apply itself (P1: `subscription.snapshot`). */
83
+ /** Appliers for event kinds the library does not apply itself (P1: `subscription.snapshot`). A host may also override `purchase.*` and delegate back through `defaultEventHandlers`. */
60
84
  handlers?: Partial<Record<NormalizedEvent['kind'], EventHandler<TTx>>>;
85
+ /** Called after commit when a delivery credited an account; see {@link AfterCreditedHook}. */
86
+ afterCredited?: AfterCreditedHook;
87
+ /** Receives what `afterCredited` threw. A throw or rejection here is swallowed too. */
88
+ onHookError?: (error: unknown, credited: CreditedPurchase) => void | Promise<void>;
61
89
  }
62
90
  export interface IngestResult extends IngestOutcome {
63
91
  response: ProviderResponse;
@@ -74,6 +102,8 @@ export interface CreateCheckoutInput {
74
102
  successUrl: string;
75
103
  errorUrl: string;
76
104
  cancelUrl: string;
105
+ /** The buyer's IP, forwarded to adapters that use it (Polar picks the tax country from it). Empty or blank means unknown. */
106
+ customerIpAddress?: string | null;
77
107
  /** Session lifetime. Default 30 min. A payment after it still credits. */
78
108
  ttlMs?: number;
79
109
  meta?: Record<string, unknown> | null;
@@ -102,10 +102,11 @@ export function createIngest(options) {
102
102
  });
103
103
  async function applyEvent(event, tx, delivery, now) {
104
104
  const ops = ledger.in(tx);
105
+ const bound = store.bind(tx);
105
106
  const handler = options.handlers?.[event.kind];
106
107
  if (handler)
107
- return handler(event, { tx, ledger: ops, delivery, now });
108
- const deps = { tx: store.bind(tx), ledger: ops, delivery, now, newId: ids };
108
+ return handler(event, { tx, ledger: ops, delivery, now, store: bound, newId: ids });
109
+ const deps = { tx: bound, ledger: ops, delivery, now, newId: ids };
109
110
  switch (event.kind) {
110
111
  case 'purchase.completed':
111
112
  return applyPurchaseCompleted(event, deps);
@@ -123,10 +124,12 @@ export function createIngest(options) {
123
124
  return { status: 'ignored', reason: `no_handler:${event.kind}` };
124
125
  }
125
126
  }
126
- /** Worst status wins: needs_review > applied > ignored. */
127
+ /** Worst status wins: needs_review > applied > ignored. Every credit is kept: it committed with its siblings. */
127
128
  function combine(results) {
129
+ // One credit is announced once, even if two events of a delivery report the same entry.
130
+ const credits = results.flatMap((r) => (r.credited ? [r.credited] : [])).filter((c, i, all) => all.findIndex((o) => o.entry?.id === c.entry?.id) === i);
128
131
  if (results.length === 0)
129
- return { status: 'ignored', reason: 'no_events' };
132
+ return { status: 'ignored', reason: 'no_events', credits };
130
133
  const pick = results.find((r) => r.status === 'needs_review') ?? results.find((r) => r.status === 'applied') ?? results[0];
131
134
  const reason = pick.reason ?? results.find((r) => r.reason)?.reason;
132
135
  const reversal = results.find((r) => r.reversal)?.reversal;
@@ -136,8 +139,40 @@ export function createIngest(options) {
136
139
  unmatched: results.every((r) => r.unmatched === true),
137
140
  events: results.flatMap((r) => r.events ?? []),
138
141
  ...(reversal ? { reversal } : {}),
142
+ credits,
139
143
  };
140
144
  }
145
+ const creditedPurchase = (provider, credited) => ({
146
+ provider,
147
+ accountId: credited.accountId,
148
+ kind: credited.kind,
149
+ entry: credited.entry,
150
+ externalId: credited.externalId ?? null,
151
+ sessionId: credited.sessionId ?? null,
152
+ });
153
+ /** After commit. A hook failure is the host's to hear about, never the delivery's. */
154
+ async function announce(provider, credits) {
155
+ const hook = options.afterCredited;
156
+ if (!hook)
157
+ return;
158
+ for (const reported of credits) {
159
+ // A malformed `credited` from a host handler (no entry …) is the hook's problem, not the delivery's.
160
+ if (!(reported?.entry?.delta > 0))
161
+ continue;
162
+ const credited = creditedPurchase(provider, reported);
163
+ try {
164
+ await hook(credited);
165
+ }
166
+ catch (error) {
167
+ try {
168
+ await options.onHookError?.(error, credited);
169
+ }
170
+ catch {
171
+ // A broken error sink must not turn a committed credit into a retry.
172
+ }
173
+ }
174
+ }
175
+ }
141
176
  /**
142
177
  * Normalize and apply one stored row. `manual` (replay) re-opens a final
143
178
  * `needs_review`/`dead` row with a fresh retry budget.
@@ -155,7 +190,7 @@ export function createIngest(options) {
155
190
  return null;
156
191
  const reopen = manual && (locked.status === 'needs_review' || locked.status === 'dead');
157
192
  if (FINAL_INBOX_STATUSES.has(locked.status) && !reopen)
158
- return { status: 'ignored', skipped: locked };
193
+ return { status: 'ignored', skipped: locked, credits: [] };
159
194
  const applied = combine(await sequential(events, (event) => applyEvent(event, tx, delivery, now)));
160
195
  await itx.updateInbox(locked.id, {
161
196
  status: applied.status,
@@ -180,6 +215,7 @@ export function createIngest(options) {
180
215
  after.push({ type: 'billing.alert', alert: 'inbox_needs_review', provider: row.provider, eventId: row.eventId, reason: result.reason ?? null });
181
216
  }
182
217
  await emit(after);
218
+ await announce(row.provider, result.credits);
183
219
  return {
184
220
  status: result.status,
185
221
  eventId: row.eventId,
@@ -377,6 +413,7 @@ export function createIngest(options) {
377
413
  errorUrl: input.errorUrl,
378
414
  cancelUrl: input.cancelUrl,
379
415
  productRef: session.productRef,
416
+ ...(input.customerIpAddress?.trim() ? { customerIpAddress: input.customerIpAddress.trim() } : {}),
380
417
  });
381
418
  await store.transaction((tx) => store.bind(tx).insertSession(session));
382
419
  return { session, redirect };
package/dist/index.d.ts CHANGED
@@ -12,8 +12,8 @@ export type { BillingEventSink, Clock, EntryListOptions, IdGenerator, LedgerRead
12
12
  export { createMemoryLedgerStore, type MemoryLedgerStore, type MemoryTx } from './stores/memory.js';
13
13
  export { createWaterfall, creditsStep, freeStep, quotaStep, type QuotaPool, type SettleContext, type SettleOptions, type Settled, type StepContext, type StepPlan, type Waterfall, type WaterfallConfig, type WaterfallStep, } from './quote/index.js';
14
14
  export * from './providers/port.js';
15
- export { createIngest, type CreateCheckoutInput, type Ingest, type IngestEvent, type IngestEventSink, type IngestOptions, type IngestPolicy, type IngestResult, type SweepResult, type UnmatchedHook, } from './inbox/ingest.js';
16
- export type { ApplyContext, ApplyResult, ApplyStatus, EventHandler, PurchaseReversed } from './inbox/apply.js';
15
+ export { createIngest, type AfterCreditedHook, type CreateCheckoutInput, type CreditedPurchase, type Ingest, type IngestEvent, type IngestEventSink, type IngestOptions, type IngestPolicy, type IngestResult, type SweepResult, type UnmatchedHook, } from './inbox/ingest.js';
16
+ export { defaultEventHandlers, type ApplyContext, type ApplyResult, type ApplyStatus, type EventHandler, type HandlerCredited, type HandlerResult, type PurchaseReversed, } from './inbox/apply.js';
17
17
  export { FINAL_INBOX_STATUSES, type CheckoutSession, type CheckoutSessionPatch, type CheckoutSessionStatus, type InboxListOptions, type InboxPatch, type InboxRow, type InboxStatus, type IngestReader, type IngestStore, type IngestTx, type Purchase, type PurchasePatch, type PurchaseStatus, } from './inbox/ports.js';
18
18
  export { createMemoryIngestStore, type MemoryIngestStore } from './inbox/memory.js';
19
19
  export { isSensitiveKey, redactPayload } from './inbox/redact.js';
package/dist/index.js CHANGED
@@ -12,6 +12,7 @@ export { createMemoryLedgerStore } from './stores/memory.js';
12
12
  export { createWaterfall, creditsStep, freeStep, quotaStep, } from './quote/index.js';
13
13
  export * from './providers/port.js';
14
14
  export { createIngest, } from './inbox/ingest.js';
15
+ export { defaultEventHandlers, } from './inbox/apply.js';
15
16
  export { FINAL_INBOX_STATUSES, } from './inbox/ports.js';
16
17
  export { createMemoryIngestStore } from './inbox/memory.js';
17
18
  export { isSensitiveKey, redactPayload } from './inbox/redact.js';
@@ -0,0 +1,24 @@
1
+ import type { Money } from '../../domain/types.js';
2
+ import type { NormalizedEvent } from '../port.js';
3
+ /** What an App Store product id means to this host. */
4
+ export interface AppleProduct {
5
+ /** Catalog productRef (a pack, or a plan for an auto-renewable product). */
6
+ productRef: string;
7
+ /** What one unit costs in the catalog. Required for one-time products. */
8
+ amount?: Money;
9
+ }
10
+ export interface AppleNormalizeOptions {
11
+ products: Readonly<Record<string, AppleProduct>>;
12
+ checkoutPattern: RegExp;
13
+ }
14
+ /** Event type of a client-posted StoreKit transaction (not a notification type). */
15
+ export declare const APPLE_TRANSACTION_EVENT = "TRANSACTION";
16
+ export declare const rec: (value: unknown) => Record<string, unknown> | null;
17
+ /** Apple timestamps are epoch milliseconds. */
18
+ export declare function msDate(value: unknown): Date | null;
19
+ /**
20
+ * Normalize one stored App Store delivery. `payload` is what the adapter
21
+ * stored: a decoded notification (`data.transaction`, `data.renewal`) or,
22
+ * for a client proof, `{ transaction, checkoutRef? }`.
23
+ */
24
+ export declare function normalizeAppleEvent(eventType: string, payload: unknown, subjectRef: string | null, occurredAt: Date, options: AppleNormalizeOptions): NormalizedEvent;
@@ -0,0 +1,232 @@
1
+ /**
2
+ * App Store event → normalized events, the pure half of the adapter.
3
+ * Deterministic over the stored (decoded, redacted) payload, the delivery's
4
+ * `subjectRef` and the adapter's product map, so a replay normalizes like the
5
+ * first run.
6
+ *
7
+ * - One-time products (consumable, non-consumable) are purchases keyed by
8
+ * `transactionId`: `ONE_TIME_CHARGE` or a client-posted transaction
9
+ * completes one, `REFUND` / `REVOKE` reverse it and `REFUND_REVERSED`
10
+ * reinstates it. Their `signedDate` is the watermark, so the newest word
11
+ * wins whatever order they arrive in (design §6).
12
+ * - Auto-renewable subscriptions become `subscription.snapshot`s keyed by
13
+ * `originalTransactionId`; the notification's `status` decides the term
14
+ * status, a refund or revoke ends access now (design §4.6).
15
+ * - A purchase names our checkout session either through the host's client
16
+ * proof or because its `appAccountToken` is a session id (`checkoutPattern`);
17
+ * the library credits checkout-bound purchases only.
18
+ * - Store prices vary per storefront and are not ours to check: the product
19
+ * id is the price authority, and the amount reported is the configured
20
+ * product amount × quantity, which is what the host's session holds.
21
+ */
22
+ import { CURRENCY_EXPONENT } from '../../domain/money.js';
23
+ /** Event type of a client-posted StoreKit transaction (not a notification type). */
24
+ export const APPLE_TRANSACTION_EVENT = 'TRANSACTION';
25
+ export const rec = (value) => value && typeof value === 'object' && !Array.isArray(value) ? value : null;
26
+ const str = (value) => (typeof value === 'string' && value.length > 0 ? value : null);
27
+ /** Apple timestamps are epoch milliseconds. */
28
+ export function msDate(value) {
29
+ if (typeof value !== 'number' || !Number.isSafeInteger(value) || value <= 0)
30
+ return null;
31
+ return new Date(value);
32
+ }
33
+ const own = (map, key) => (key !== null && Object.hasOwn(map, key) ? map[key] : undefined);
34
+ const ONE_TIME_TYPES = new Set(['Consumable', 'Non-Consumable']);
35
+ const SUBSCRIPTION_TYPE = 'Auto-Renewable Subscription';
36
+ /** Notification types that describe an auto-renewable subscription's state. */
37
+ const SUBSCRIPTION_NOTIFICATIONS = new Set([
38
+ 'SUBSCRIBED',
39
+ 'DID_RENEW',
40
+ 'DID_FAIL_TO_RENEW',
41
+ 'GRACE_PERIOD_EXPIRED',
42
+ 'EXPIRED',
43
+ 'DID_CHANGE_RENEWAL_STATUS',
44
+ 'DID_CHANGE_RENEWAL_PREF',
45
+ 'RENEWAL_EXTENDED',
46
+ 'OFFER_REDEEMED',
47
+ 'REFUND',
48
+ 'REFUND_REVERSED',
49
+ 'REVOKE',
50
+ ]);
51
+ /** Two snapshots signed the same millisecond: the later lifecycle state wins. */
52
+ const TIE_ORDER = ['active', 'grace', 'past_due', 'expired', 'revoked'];
53
+ /** `data.status` of a subscription notification. */
54
+ const STATUS = { 1: 'active', 2: 'expired', 3: 'past_due', 4: 'grace', 5: 'revoked' };
55
+ /** A price in Apple's milliunits as minor units, when it is one exactly. */
56
+ function priceOf(txn) {
57
+ const currency = str(txn['currency'])?.toUpperCase();
58
+ const price = txn['price'];
59
+ if (!currency || !Object.hasOwn(CURRENCY_EXPONENT, currency) || typeof price !== 'number' || !Number.isSafeInteger(price) || price < 0)
60
+ return undefined;
61
+ const divisor = 10 ** (3 - CURRENCY_EXPONENT[currency]);
62
+ return price % divisor === 0 ? { currency, amountMinor: price / divisor } : undefined;
63
+ }
64
+ function bindingOf(token, hostCheckoutRef, options) {
65
+ const checkoutRef = hostCheckoutRef ?? (token && options.checkoutPattern.test(token) ? token : null);
66
+ const account = token
67
+ ? { kind: 'apple_app_account_token', value: token }
68
+ : checkoutRef
69
+ ? { kind: 'checkout', value: checkoutRef }
70
+ : null;
71
+ return { account, checkoutRef };
72
+ }
73
+ function completed(txn, binding, occurredAt, proof, options) {
74
+ const transactionId = str(txn['transactionId']);
75
+ if (!transactionId)
76
+ return { kind: 'needs_review', reason: 'missing_transaction_id' };
77
+ // A notification that names no checkout of ours is settled by the host's
78
+ // client proof; parking every such purchase for a human would only be noise.
79
+ if (!proof && !binding.checkoutRef)
80
+ return { kind: 'ignored', reason: 'unbound_purchase' };
81
+ if (!binding.account)
82
+ return { kind: 'needs_review', reason: 'unbound_purchase' };
83
+ const productId = str(txn['productId']);
84
+ const product = own(options.products, productId);
85
+ if (!product)
86
+ return { kind: 'needs_review', reason: 'unknown_product', detail: { productId } };
87
+ if (!product.amount)
88
+ return { kind: 'needs_review', reason: 'product_amount_missing', detail: { productId } };
89
+ const quantity = txn['quantity'] === undefined ? 1 : txn['quantity'];
90
+ const total = typeof quantity === 'number' ? product.amount.amountMinor * quantity : NaN;
91
+ if (!Number.isSafeInteger(quantity) || quantity < 1 || !Number.isSafeInteger(total)) {
92
+ return { kind: 'needs_review', reason: 'invalid_quantity', detail: { quantity: quantity ?? null } };
93
+ }
94
+ return {
95
+ kind: 'purchase.completed',
96
+ account: binding.account,
97
+ externalId: transactionId,
98
+ productRef: product.productRef,
99
+ quantity: quantity,
100
+ amount: { currency: product.amount.currency, amountMinor: total },
101
+ ...(binding.checkoutRef ? { checkoutRef: binding.checkoutRef } : {}),
102
+ occurredAt,
103
+ };
104
+ }
105
+ function changed(kind, txn, binding, occurredAt, reason) {
106
+ const transactionId = str(txn['transactionId']);
107
+ if (!transactionId)
108
+ return { kind: 'needs_review', reason: 'missing_transaction_id' };
109
+ return {
110
+ kind,
111
+ externalId: transactionId,
112
+ ...(reason ? { reason } : {}),
113
+ ...(binding.checkoutRef ? { checkoutRef: binding.checkoutRef } : {}),
114
+ occurredAt,
115
+ };
116
+ }
117
+ function snapshot(type, data, txn, renewal, token, occurredAt, options) {
118
+ if (!token)
119
+ return { kind: 'ignored', reason: 'no_account_token' };
120
+ const externalId = str(txn['originalTransactionId']);
121
+ if (!externalId)
122
+ return { kind: 'needs_review', reason: 'missing_original_transaction_id' };
123
+ const product = own(options.products, str(txn['productId']));
124
+ if (!product)
125
+ return { kind: 'ignored', reason: 'unknown_product' };
126
+ const subtype = str(data['subtype']);
127
+ const revokedAt = msDate(txn['revocationDate']);
128
+ let status;
129
+ if (type === 'REFUND' || type === 'REVOKE' || revokedAt)
130
+ status = 'revoked';
131
+ else if (typeof data['status'] === 'number' && Object.hasOwn(STATUS, data['status']))
132
+ status = STATUS[data['status']];
133
+ else if (type === 'EXPIRED')
134
+ status = 'expired';
135
+ else if (type === 'GRACE_PERIOD_EXPIRED')
136
+ status = 'past_due';
137
+ else if (type === 'DID_FAIL_TO_RENEW')
138
+ status = subtype === 'GRACE_PERIOD' ? 'grace' : 'past_due';
139
+ else
140
+ status = 'active';
141
+ const periodStart = msDate(txn['purchaseDate']);
142
+ const expires = msDate(txn['expiresDate']);
143
+ // A revocation ends access when it happened, not when the period would have.
144
+ const endedAt = status === 'revoked' ? (revokedAt ?? occurredAt) : null;
145
+ const periodEnd = expires && endedAt ? (endedAt < expires ? endedAt : expires) : (expires ?? endedAt);
146
+ if (!periodStart || !periodEnd)
147
+ return { kind: 'needs_review', reason: 'missing_period' };
148
+ const live = status === 'active' || status === 'grace' || status === 'past_due';
149
+ const renewing = renewal?.['autoRenewStatus'] === 1;
150
+ const graceUntil = status === 'grace' ? msDate(renewal?.['gracePeriodExpiresDate']) : null;
151
+ const nextProductId = str(renewal?.['autoRenewProductId']);
152
+ const next = nextProductId && nextProductId !== str(txn['productId']) ? own(options.products, nextProductId) : undefined;
153
+ const price = priceOf(txn);
154
+ return {
155
+ kind: 'subscription.snapshot',
156
+ account: { kind: 'apple_app_account_token', value: token },
157
+ externalId,
158
+ planRef: product.productRef,
159
+ status,
160
+ periodStart,
161
+ periodEnd,
162
+ autoRenew: live && renewing,
163
+ cancelAtPeriodEnd: live && renewal !== null && !renewing,
164
+ ...(graceUntil ? { graceUntil } : {}),
165
+ ...(next ? { nextPlanRef: next.productRef } : {}),
166
+ ...(price ? { price } : {}),
167
+ occurredAt,
168
+ tieBreak: String(TIE_ORDER.indexOf(status) + 1),
169
+ };
170
+ }
171
+ /**
172
+ * Normalize one stored App Store delivery. `payload` is what the adapter
173
+ * stored: a decoded notification (`data.transaction`, `data.renewal`) or,
174
+ * for a client proof, `{ transaction, checkoutRef? }`.
175
+ */
176
+ export function normalizeAppleEvent(eventType, payload, subjectRef, occurredAt, options) {
177
+ const body = rec(payload) ?? {};
178
+ if (eventType === APPLE_TRANSACTION_EVENT) {
179
+ const txn = rec(body['transaction']);
180
+ if (!txn)
181
+ return { kind: 'needs_review', reason: 'missing_transaction' };
182
+ const binding = bindingOf(subjectRef, str(body['checkoutRef']), options);
183
+ const type = str(txn['type']);
184
+ if (type === SUBSCRIPTION_TYPE)
185
+ return { kind: 'ignored', reason: 'subscription_transaction' };
186
+ if (!type || !ONE_TIME_TYPES.has(type))
187
+ return { kind: 'ignored', reason: `unsupported_type:${type ?? 'none'}` };
188
+ // Refunded before it reached us: record the reversal so it never credits.
189
+ if (msDate(txn['revocationDate']))
190
+ return changed('purchase.reversed', txn, binding, occurredAt, 'refund');
191
+ return completed(txn, binding, occurredAt, true, options);
192
+ }
193
+ const data = rec(body['data']) ?? {};
194
+ const txn = rec(data['transaction']);
195
+ const renewal = rec(data['renewal']);
196
+ const view = { ...data, subtype: body['subtype'] };
197
+ if (eventType === 'TEST')
198
+ return { kind: 'ignored', reason: 'test_notification' };
199
+ if (!txn)
200
+ return { kind: 'ignored', reason: `no_transaction:${eventType}` };
201
+ const type = str(txn['type']);
202
+ if (type === SUBSCRIPTION_TYPE) {
203
+ if (eventType === 'CONSUMPTION_REQUEST')
204
+ return consumption(txn, occurredAt);
205
+ if (!SUBSCRIPTION_NOTIFICATIONS.has(eventType))
206
+ return { kind: 'ignored', reason: `unhandled_type:${eventType}` };
207
+ return snapshot(eventType, view, txn, renewal, subjectRef, occurredAt, options);
208
+ }
209
+ if (!type || !ONE_TIME_TYPES.has(type))
210
+ return { kind: 'ignored', reason: `unsupported_type:${type ?? 'none'}` };
211
+ const binding = bindingOf(subjectRef, null, options);
212
+ switch (eventType) {
213
+ case 'ONE_TIME_CHARGE':
214
+ return completed(txn, binding, occurredAt, false, options);
215
+ case 'REFUND':
216
+ return changed('purchase.reversed', txn, binding, occurredAt, 'refund');
217
+ case 'REVOKE':
218
+ return changed('purchase.reversed', txn, binding, occurredAt, 'revoke');
219
+ case 'REFUND_REVERSED':
220
+ return changed('purchase.reinstated', txn, binding, occurredAt);
221
+ case 'CONSUMPTION_REQUEST':
222
+ return consumption(txn, occurredAt);
223
+ default:
224
+ return { kind: 'ignored', reason: `unhandled_type:${eventType}` };
225
+ }
226
+ }
227
+ function consumption(txn, occurredAt) {
228
+ const transactionId = str(txn['transactionId']);
229
+ if (!transactionId)
230
+ return { kind: 'needs_review', reason: 'missing_transaction_id' };
231
+ return { kind: 'consumption.requested', externalId: transactionId, occurredAt };
232
+ }
@@ -0,0 +1,54 @@
1
+ import { type ConsumptionReporter, type IngestOutcome, type ProviderAdapter, type ProviderEnvironment, type ProviderResponse, type PurchaseVerifier } from '../port.js';
2
+ import { type AppleProduct } from './events.js';
3
+ export { APPLE_RECEIPT_SIGNING_OID, APPLE_ROOT_CA_G3_PEM, APPLE_ROOT_CA_G3_SHA256, APPLE_WWDR_INTERMEDIATE_OID, } from './jws.js';
4
+ export { APPLE_TRANSACTION_EVENT, type AppleProduct } from './events.js';
5
+ /** App Store Server API credentials (an In-App Purchase key from App Store Connect). */
6
+ export interface AppleServerApiCredentials {
7
+ issuerId: string;
8
+ keyId: string;
9
+ /** The `.p8` key, PEM. */
10
+ privateKey: string;
11
+ }
12
+ export interface AppleAdapterOptions {
13
+ /** Required. `production` accepts only Production payloads, `sandbox` only Sandbox. */
14
+ environment: ProviderEnvironment;
15
+ /** This app's bundle id: a payload signed for any other app is refused. */
16
+ bundleId: string;
17
+ /** This app's Apple id; checked when the notification carries one. Production only. */
18
+ appAppleId?: number;
19
+ /** App Store product id → what it means here. */
20
+ products: Readonly<Record<string, AppleProduct>>;
21
+ /** Our checkout session ids as carried in `appAccountToken`. Default: UUID. */
22
+ checkoutPattern?: RegExp;
23
+ /**
24
+ * Trusted roots (PEM). **Tests only** — production leaves it unset and
25
+ * trusts the pinned Apple Root CA G3 alone.
26
+ */
27
+ trustedRoots?: readonly string[];
28
+ /** Needed only for `reportConsumption`. */
29
+ serverApi?: AppleServerApiCredentials;
30
+ /** Wall clock for certificate validity and API tokens. Default `new Date()`. */
31
+ clock?: () => Date;
32
+ fetch?: typeof fetch;
33
+ /** API timeout. Default 10 s. */
34
+ timeoutMs?: number;
35
+ }
36
+ /** A StoreKit 2 transaction posted by the app, bound to the host's checkout session. */
37
+ export interface AppleTransactionProof {
38
+ signedTransaction: string;
39
+ /** The checkout session the host created for this purchase (server-priced). */
40
+ checkoutRef?: string;
41
+ }
42
+ export interface AppleAdapter extends ProviderAdapter, PurchaseVerifier<AppleTransactionProof>, ConsumptionReporter {
43
+ readonly id: 'apple';
44
+ }
45
+ /** An App Store Server API call failed. Never carries the token or the response body. */
46
+ export declare class AppleApiError extends Error {
47
+ readonly name = "AppleApiError";
48
+ readonly code: 'apple_unreachable' | 'apple_error';
49
+ readonly status: number | null;
50
+ constructor(code: AppleApiError['code'], message: string, status?: number | null);
51
+ }
52
+ export declare function createAppleAdapter(options: AppleAdapterOptions): AppleAdapter;
53
+ /** Apple retries any non-2xx for days; acknowledge everything a retry cannot change. */
54
+ export declare function respondApple(outcome: IngestOutcome): ProviderResponse;