@tofound/billing 1.0.0 → 1.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -4,6 +4,67 @@ All notable changes to `@tofound/billing`. Versions follow semver; 0.x minors
4
4
  were additive. From 1.0.0 the public API is frozen: removing or narrowing
5
5
  anything in the declaration snapshot is a major version.
6
6
 
7
+ ## 1.2.0 — 2026-10-25
8
+
9
+ Additive to 1.1: every 1.1 export is unchanged (the public-api declaration
10
+ snapshot only grows). No schema change. Without `app`, the Polar adapter's
11
+ behavior and checkout request bodies are exactly 1.1.0's.
12
+
13
+ To adopt: pin `@tofound/billing@1.2.0`.
14
+
15
+ - **Polar app tag for a shared Polar org.** `PolarAdapterOptions.app` is this
16
+ host's tag, stamped as `metadata.app` next to `metadata.checkout_id` on every
17
+ checkout. With it set, the normalizer classifies every `order.*`,
18
+ `subscription.*` and `checkout.*` event by `data.metadata.app` of the object
19
+ the event is about: equal → processed as before; present and different (or
20
+ unreadable) → `ignored` with reason `foreign_app`; absent → governed by the new
21
+ `unlabeled?: 'accept' | 'ignore'` (default `'accept'`; `'ignore'` →
22
+ `ignored`, reason `unlabeled_app`). Foreign wins over every other rule, so a
23
+ foreign partial refund is `ignored`, not `needs_review`. A foreign or ignored
24
+ unlabeled event leaves one `ignored` inbox row and nothing else: no ledger
25
+ entry, term, snapshot, alert or `onUnmatched` relay, and a redelivery or
26
+ `replay` stays `ignored`. New type `PolarUnlabeledPolicy`; new config errors
27
+ `polar_invalid_app`, `polar_invalid_unlabeled`, `polar_unlabeled_requires_app`.
28
+ - **Checkout metadata and customer seam.** `CheckoutRequest` (and
29
+ `CreateCheckoutInput`, forwarded by `ingest.createCheckout`) gain optional
30
+ `customerEmail`, `externalCustomerId` and `metadata`. Polar sends them as
31
+ `customer_email`, `external_customer_id` (default `accountId`) and extra
32
+ `metadata` keys. `checkout_id` and `app` are reserved and cannot be set by the
33
+ host (`polar_reserved_metadata_key`, before any call); a non-primitive value
34
+ is `polar_invalid_metadata`. Other adapters ignore the three fields.
35
+ - **Docs:** API.md (options, outcomes, seam), a *Shared Polar org* section in
36
+ MIGRATION-LOHI.md.
37
+
38
+ ## 1.1.0 — 2026-10-24
39
+
40
+ Additive to 1.0: every 1.0 export is unchanged (the public-api declaration
41
+ snapshot only grows). No schema change.
42
+
43
+ To adopt: pin `@tofound/billing@1.1.0`.
44
+
45
+ - **`afterCredited` / `onHookError`** on `createIngest`: a hook called after
46
+ the delivery's transaction commits, at most once per credit, with a
47
+ `CreditedPurchase` (`provider`, `accountId`, `kind`, `entry`, `externalId`,
48
+ `sessionId`). It fires for the library's own appliers and for a host handler
49
+ that returns the new optional `credited` field on its result
50
+ (`HandlerResult`, an alias of `ApplyResult`). It never fires for a duplicate,
51
+ a replay of a settled row, an ignored delivery, a reversal, a rolled-back
52
+ attempt or an empty entry. A hook that throws goes to `onHookError` and never
53
+ changes the delivery outcome.
54
+ - **`defaultEventHandlers`** exported: the library's `purchase.completed`,
55
+ `purchase.reversed` and `purchase.reinstated` appliers, so a host that
56
+ overrides a kind for one provider can delegate the others back. `ApplyContext`
57
+ gains `store` (the ingest store bound to the handler's transaction) and
58
+ `newId`; handlers only read them, so existing handlers compile unchanged
59
+ (a test that builds an `ApplyContext` by hand adds the two fields).
60
+ - **`ingest.createCheckout` forwards `customerIpAddress`** to the adapter
61
+ (`CheckoutRequest.customerIpAddress`, optional). Polar uses it to pick the tax
62
+ country; before, only a direct `polar.createCheckout` sent it.
63
+ - **`docs/GUIDE.md`**, a task guide shipped in the package: credit packs, a
64
+ monthly plan end to end, a provider subscription and supersede, failed
65
+ renewals per source, refunds with shortfall, arming a provider, migrating a
66
+ legacy term table, and that Google Play subscriptions are not supported.
67
+
7
68
  ## 1.0.0 — 2026-10-24
8
69
 
9
70
  The 1.0 API freeze. Every 0.2 export is unchanged (changes since 0.2.0 are
package/README.md CHANGED
@@ -4,7 +4,7 @@
4
4
  products (2Novel first, the Lohi reader api last). Each host API embeds it on
5
5
  its own database; there is no billing service.
6
6
 
7
- 1.0 ships (the public API is frozen from 1.0.0 on):
7
+ 1.2 ships (the public API is frozen from 1.0.0 on; 1.1 and 1.2 only add):
8
8
 
9
9
  - **The money core** (since 0.1): an idempotent, no-overdraft credit ledger
10
10
  behind store ports, memory and Drizzle/Postgres stores, a Drizzle schema
@@ -23,7 +23,7 @@ its own database; there is no billing service.
23
23
  (`@tofound/billing/providers/google`) adapters.
24
24
 
25
25
  ```sh
26
- bun add @tofound/billing@1.0.0 --exact # peer: drizzle-orm ^0.45 for /drizzle
26
+ bun add @tofound/billing@1.2.0 --exact # peer: drizzle-orm ^0.45 for /drizzle
27
27
  ```
28
28
 
29
29
  ```ts
@@ -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,14 @@ 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;
107
+ /** The buyer's email, forwarded to adapters that use it (Polar prefills the pay page). Blank means unknown. */
108
+ customerEmail?: string | null;
109
+ /** The provider's customer id when it is not `accountId` (Polar `external_customer_id`). Blank means `accountId`. */
110
+ externalCustomerId?: string | null;
111
+ /** Host metadata forwarded to adapters that carry it (Polar: onto the order and subscription). Empty means none. */
112
+ metadata?: Readonly<Record<string, string | number | boolean>> | null;
77
113
  /** Session lifetime. Default 30 min. A payment after it still credits. */
78
114
  ttlMs?: number;
79
115
  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,10 @@ 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() } : {}),
417
+ ...(input.customerEmail?.trim() ? { customerEmail: input.customerEmail.trim() } : {}),
418
+ ...(input.externalCustomerId?.trim() ? { externalCustomerId: input.externalCustomerId.trim() } : {}),
419
+ ...(input.metadata && Object.keys(input.metadata).length > 0 ? { metadata: input.metadata } : {}),
380
420
  });
381
421
  await store.transaction((tx) => store.bind(tx).insertSession(session));
382
422
  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';
@@ -9,7 +9,13 @@ export interface NormalizeOptions {
9
9
  products: Readonly<Record<string, string>>;
10
10
  /** Our checkout session ids, as carried in `metadata.checkout_id`. */
11
11
  checkoutPattern: RegExp;
12
+ /** The host's app tag; unset = no ownership check (a single-tenant org). */
13
+ app?: string;
14
+ /** What an event without `metadata.app` is. Only read when `app` is set. */
15
+ unlabeled?: PolarUnlabeledPolicy;
12
16
  }
17
+ /** Events without `metadata.app` (orders created before the tag existed): process them, or leave them to the other host. */
18
+ export type PolarUnlabeledPolicy = 'accept' | 'ignore';
13
19
  /** The provider's watermark: when Polar last changed the object, else when it was created or sent. */
14
20
  export declare function occurredAtOf(envelope: PolarEnvelope, fallback: Date): Date;
15
21
  /** The server-issued external customer id (design §4.1). */
@@ -29,6 +29,26 @@ function checkoutRefOf(data, options) {
29
29
  const ref = str(rec(data['metadata'])?.['checkout_id']);
30
30
  return ref && options.checkoutPattern.test(ref) ? ref : null;
31
31
  }
32
+ /**
33
+ * The ignore verdict for an event this adapter does not own, or null to process
34
+ * it. Ownership is the `metadata.app` Polar copied from our checkout onto the
35
+ * order / subscription (and left on the checkout itself). Present and not
36
+ * exactly our tag — another host's, empty, not a string, or `metadata` not an
37
+ * object at all — is foreign: a label we cannot read is never credited. Absent
38
+ * is `unlabeled`, governed by the host's policy.
39
+ */
40
+ function notOurs(data, options) {
41
+ if (options.app === undefined)
42
+ return null;
43
+ const metadata = data['metadata'];
44
+ if (metadata !== undefined && metadata !== null && !rec(metadata))
45
+ return { kind: 'ignored', reason: 'foreign_app' };
46
+ const label = rec(metadata)?.['app'];
47
+ if (label === undefined || label === null) {
48
+ return options.unlabeled === 'ignore' ? { kind: 'ignored', reason: 'unlabeled_app' } : null;
49
+ }
50
+ return label === options.app ? null : { kind: 'ignored', reason: 'foreign_app' };
51
+ }
32
52
  function moneyOf(currencyRaw, amountMinor, rawAmount) {
33
53
  const currency = own(CURRENCIES, (str(currencyRaw) ?? '').toUpperCase());
34
54
  if (!currency)
@@ -203,11 +223,16 @@ function checkoutEvent(envelope, options) {
203
223
  }
204
224
  export function normalizePolarEvent(envelope, occurredAt, options) {
205
225
  const { type } = envelope;
206
- if (type.startsWith('subscription.'))
207
- return subscriptionEvent(envelope, occurredAt, options);
208
- if (type.startsWith('order.'))
209
- return orderEvent(envelope, occurredAt, options);
210
- if (type.startsWith('checkout.'))
211
- return checkoutEvent(envelope, options);
212
- return { kind: 'ignored', reason: `unhandled_type:${type}` };
226
+ const family = type.startsWith('subscription.')
227
+ ? subscriptionEvent
228
+ : type.startsWith('order.')
229
+ ? orderEvent
230
+ : type.startsWith('checkout.')
231
+ ? (e, _at, o) => checkoutEvent(e, o)
232
+ : null;
233
+ if (!family)
234
+ return { kind: 'ignored', reason: `unhandled_type:${type}` };
235
+ // Ownership first: a foreign event must not reach a rule that could park it
236
+ // for review (partial refund, unknown product, unbound order …).
237
+ return notOurs(envelope.data, options) ?? family(envelope, occurredAt, options);
213
238
  }
@@ -1,4 +1,6 @@
1
1
  import { type CheckoutCapable, type CheckoutRedirect, type CheckoutRequest, type IngestOutcome, type PortalCapable, type ProviderAdapter, type ProviderEnvironment, type ProviderResponse } from '../port.js';
2
+ import { type PolarUnlabeledPolicy } from './events.js';
3
+ export type { PolarUnlabeledPolicy } from './events.js';
2
4
  export { POLAR_WEBHOOK_ID_HEADER, POLAR_WEBHOOK_SIGNATURE_HEADER, POLAR_WEBHOOK_TIMESTAMP_HEADER, POLAR_WEBHOOK_TOLERANCE_SECONDS, signPolarWebhook, type PolarKeyDerivation, } from './signature.js';
3
5
  /**
4
6
  * 2Novel's two-switch arming, made explicit: production needs both the
@@ -21,6 +23,19 @@ export interface PolarAdapterOptions {
21
23
  accessToken?: string;
22
24
  /** Our checkout session ids as carried in `metadata.checkout_id`. Default: UUID. */
23
25
  checkoutPattern?: RegExp;
26
+ /**
27
+ * This host's tag in a Polar org shared with other hosts. Stamped on every
28
+ * checkout as `metadata.app`; an event whose object carries a different
29
+ * `metadata.app` is ignored (`foreign_app`) — never credited, reversed,
30
+ * snapshotted or parked for review. Unset: no tagging, no ownership check.
31
+ */
32
+ app?: string;
33
+ /**
34
+ * An event with no `metadata.app` (an order made before the tag existed):
35
+ * `'accept'` processes it as before (default), `'ignore'` leaves it to the
36
+ * other host (`unlabeled_app`). Needs `app`.
37
+ */
38
+ unlabeled?: PolarUnlabeledPolicy;
24
39
  /** Replay window in seconds. Default 300. */
25
40
  toleranceSec?: number;
26
41
  /** Wall clock for the replay window. Default `new Date()`. */
@@ -29,7 +44,7 @@ export interface PolarAdapterOptions {
29
44
  /** API timeout. Default 10 s. */
30
45
  timeoutMs?: number;
31
46
  }
32
- /** A checkout request; Polar uses the buyer's IP for tax country when the host has it. */
47
+ /** A checkout request; Polar uses the buyer's IP (`customerIpAddress`) for the tax country when the host has it. */
33
48
  export interface PolarCheckoutRequest extends CheckoutRequest {
34
49
  customerIpAddress?: string | null;
35
50
  }
@@ -25,6 +25,9 @@ const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/
25
25
  /** Header and body bounds; past them the delivery is refused, not stored. */
26
26
  const MAX_WEBHOOK_ID = 128;
27
27
  const MAX_EVENT_TYPE = 64;
28
+ /** Keys the adapter writes into checkout metadata; a host cannot set them. */
29
+ const RESERVED_METADATA_KEYS = new Set(['checkout_id', 'app']);
30
+ const MAX_APP_LENGTH = 128;
28
31
  const stateless = (pattern) => new RegExp(pattern.source, pattern.flags.replace(/[gy]/g, ''));
29
32
  /**
30
33
  * 2Novel's two-switch arming, made explicit: production needs both the
@@ -101,8 +104,23 @@ export function createPolarAdapter(options) {
101
104
  const tolerance = options.toleranceSec ?? POLAR_WEBHOOK_TOLERANCE_SECONDS;
102
105
  if (!Number.isFinite(tolerance) || tolerance <= 0)
103
106
  throw new ProviderConfigError('polar_invalid_tolerance', 'toleranceSec must be positive');
107
+ const app = options.app;
108
+ if (app !== undefined && (typeof app !== 'string' || app.trim().length === 0 || app !== app.trim() || app.length > MAX_APP_LENGTH)) {
109
+ throw new ProviderConfigError('polar_invalid_app', 'app must be a non-blank string without surrounding whitespace, at most 128 characters');
110
+ }
111
+ const unlabeled = options.unlabeled;
112
+ if (unlabeled !== undefined && unlabeled !== 'accept' && unlabeled !== 'ignore') {
113
+ throw new ProviderConfigError('polar_invalid_unlabeled', "unlabeled must be 'accept' or 'ignore'");
114
+ }
115
+ if (unlabeled !== undefined && app === undefined) {
116
+ throw new ProviderConfigError('polar_unlabeled_requires_app', 'unlabeled has no meaning without an app tag');
117
+ }
104
118
  const products = { ...options.products };
105
- const normalizeOptions = { products, checkoutPattern: stateless(options.checkoutPattern ?? UUID_RE) };
119
+ const normalizeOptions = {
120
+ products,
121
+ checkoutPattern: stateless(options.checkoutPattern ?? UUID_RE),
122
+ ...(app !== undefined ? { app, ...(unlabeled ? { unlabeled } : {}) } : {}),
123
+ };
106
124
  const clock = options.clock ?? (() => new Date());
107
125
  const fetchImpl = options.fetch ?? globalThis.fetch;
108
126
  const timeoutMs = options.timeoutMs ?? 10_000;
@@ -112,6 +130,26 @@ export function createPolarAdapter(options) {
112
130
  const matches = Object.keys(products).filter((id) => products[id] === productRef);
113
131
  return matches.length === 1 ? matches[0] : null;
114
132
  }
133
+ /** Host metadata for the checkout; the adapter's own keys are not the host's to set. */
134
+ function checkoutMetadata(input) {
135
+ if (input === undefined || input === null)
136
+ return {};
137
+ if (typeof input !== 'object' || Array.isArray(input))
138
+ throw new ProviderConfigError('polar_invalid_metadata', 'checkout metadata must be a flat object');
139
+ const out = {};
140
+ for (const [key, value] of Object.entries(input)) {
141
+ if (key === '__proto__')
142
+ throw new ProviderConfigError('polar_invalid_metadata', 'checkout metadata key "__proto__" is not allowed');
143
+ if (RESERVED_METADATA_KEYS.has(key)) {
144
+ throw new ProviderConfigError('polar_reserved_metadata_key', `checkout metadata key "${key}" is reserved by the adapter`);
145
+ }
146
+ if (typeof value !== 'string' && typeof value !== 'boolean' && !(typeof value === 'number' && Number.isFinite(value))) {
147
+ throw new ProviderConfigError('polar_invalid_metadata', `checkout metadata "${key}" must be a string, number or boolean`);
148
+ }
149
+ out[key] = value;
150
+ }
151
+ return out;
152
+ }
115
153
  async function call(path, body) {
116
154
  if (!options.accessToken) {
117
155
  throw new ProviderConfigError('polar_not_configured', 'a Polar access token is required for checkout and portal sessions');
@@ -208,12 +246,15 @@ export function createPolarAdapter(options) {
208
246
  if (!normalizeOptions.checkoutPattern.test(req.sessionId)) {
209
247
  throw new ProviderConfigError('polar_invalid_checkout_id', 'checkout session id does not match the adapter checkoutPattern');
210
248
  }
249
+ const metadata = checkoutMetadata(req.metadata);
250
+ const customerEmail = req.customerEmail?.trim();
211
251
  const raw = await call('/checkouts/', {
212
252
  products: [productId],
213
- external_customer_id: req.accountId,
253
+ external_customer_id: req.externalCustomerId?.trim() || req.accountId,
214
254
  ...(req.customerIpAddress ? { customer_ip_address: req.customerIpAddress } : {}),
215
- // Polar copies metadata onto the resulting order.
216
- metadata: { checkout_id: req.sessionId },
255
+ ...(customerEmail ? { customer_email: customerEmail } : {}),
256
+ // Polar copies metadata onto the resulting order and subscription.
257
+ metadata: { checkout_id: req.sessionId, ...(app !== undefined ? { app } : {}), ...metadata },
217
258
  // A discount code would make the order's amount differ from the
218
259
  // session's catalog amount: the buyer pays and the purchase is parked
219
260
  // for review. Discounts belong in the catalog, not on the pay page.
@@ -151,6 +151,14 @@ export interface CheckoutRequest {
151
151
  errorUrl: string;
152
152
  cancelUrl: string;
153
153
  productRef?: string | null;
154
+ /** The buyer's IP when the host has it; adapters that cannot use it ignore it (Polar: tax country). */
155
+ customerIpAddress?: string | null;
156
+ /** The buyer's email, to prefill the pay page when the host has it; adapters that cannot use it ignore it (Polar: `customer_email`). */
157
+ customerEmail?: string | null;
158
+ /** The provider-side customer id when it is not `accountId` (Polar: `external_customer_id`, e.g. a host-namespaced `lohi:<uid>`); adapters that cannot use it ignore it. */
159
+ externalCustomerId?: string | null;
160
+ /** Host keys the provider carries onto the resulting purchase (Polar: checkout `metadata`). The adapter's own keys are reserved; adapters that cannot use it ignore it. */
161
+ metadata?: Readonly<Record<string, string | number | boolean>> | null;
154
162
  }
155
163
  export type CheckoutRedirect = {
156
164
  kind: 'redirect';
package/docs/API.md CHANGED
@@ -1,14 +1,15 @@
1
- # @tofound/billing — API (1.0)
1
+ # @tofound/billing — API (1.2)
2
2
 
3
3
  Part of the `billing.public-api` contract with `src/index.ts` and
4
- `src/domain/types.ts`. 0.x minors were additive. From 1.0.0 the API is
4
+ `src/domain/types.ts`. 0.x minors were additive; 1.1.0 and 1.2.0 are additive to 1.0.0. From 1.0.0 the API is
5
5
  frozen: the declaration snapshot in `test/contract/public-api.test.ts` fails
6
6
  on any change to these exports, and removing or narrowing one is a major
7
- version.
7
+ version. For task-oriented walkthroughs (packs, plans, failed renewals,
8
+ refunds, arming a provider) see [GUIDE.md](GUIDE.md).
8
9
 
9
10
  | Entry | Contents |
10
11
  |---|---|
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` | domain types, money helpers, `BillingError`, `createLedger`, ports, `createMemoryLedgerStore`, waterfall + steps, provider port, `createIngest`, `defaultEventHandlers`, `createMemoryIngestStore`, `defineCatalog`, terms, `resolveEntitlement`, `createPlans`, `createRenewal`, `createSnapshotHandler`, `createMemoryTermStore` |
12
13
  | `@tofound/billing/drizzle` | `createBillingTables`, `billingTableBuilder`, `checkAdditiveDdl`, `createDrizzleLedgerStore`, `createIngestTables`, `createDrizzleIngestStore`, `createTermTables`, `createDrizzleTermStore`, `termTableNames` (peer `drizzle-orm ^0.45`) |
13
14
  | `@tofound/billing/providers/sepay` | `createSepayAdapter`, `respondSepay`, `signCheckoutFields`, `parseSepayOrder` |
14
15
  | `@tofound/billing/providers/polar` | `createPolarAdapter`, `resolvePolarEnvironment`, `respondPolar`, `redactPolarPayload`, `signPolarWebhook`, `PolarApiError`, `POLAR_WEBHOOK_*` header names and tolerance; types `PolarAdapter`, `PolarAdapterOptions`, `PolarCheckoutRequest`, `PolarKeyDerivation` |
@@ -161,9 +162,9 @@ await w.settle(tx, lockedState, { accountId, idempotencyKey }) // same steps, co
161
162
 
162
163
  ```ts
163
164
  const sepay = createSepayAdapter({ environment: 'production', webhookKeys: [current, next?], merchantId, secretKey })
164
- const ingest = createIngest({ adapters: [sepay], store, ledger, events?, policy?, onUnmatched? })
165
+ const ingest = createIngest({ adapters: [sepay], store, ledger, events?, policy?, onUnmatched?, handlers?, afterCredited?, onHookError? })
165
166
 
166
- const { session, redirect } = await ingest.createCheckout({ provider: 'sepay', accountId, amount, credits, productRef, description, successUrl, errorUrl, cancelUrl })
167
+ const { session, redirect } = await ingest.createCheckout({ provider: 'sepay', accountId, amount, credits, productRef, description, successUrl, errorUrl, cancelUrl, customerIpAddress? })
167
168
  const r = await ingest.handle('sepay', { headers, rawBody, url, receivedAt }) // → reply with r.response
168
169
  await ingest.confirm('sepay', { invoice: session.id }) // poll; same event id as the IPN
169
170
  await ingest.closeCheckout(session.id, 'expired') // a later capture still credits
@@ -191,6 +192,34 @@ await ingest.sweep()
191
192
  - `confirm` credits the session's own account, whoever asks; a host route
192
193
  that forwards a client's invoice still checks the caller owns that session
193
194
  before it spends a provider API call on it.
195
+ - **`afterCredited(c: CreditedPurchase)`** (1.1) runs after the delivery's
196
+ transaction commits, at most once per credit: `{ provider, accountId, kind:
197
+ 'completed' | 'reinstated', entry, externalId, sessionId }`. It fires for the
198
+ library's own appliers and for a host handler whose `ApplyResult`
199
+ (`HandlerResult`) carries `credited: { accountId, entry, kind, externalId?,
200
+ sessionId? }`. It never fires for `duplicate`, `ignored`, a replay of a
201
+ settled row, a reversal, a rolled-back attempt or an entry with `delta ≤ 0`,
202
+ and it fires whatever the delivery's status when a credit committed (a
203
+ sibling event that needs review does not unsend it). A throw or rejection
204
+ goes to `onHookError(error, c)` (itself guarded) and never changes the
205
+ outcome; a crash between commit and hook loses the call, so keep a periodic
206
+ backstop.
207
+ - `afterCredited` announces **purchase credits** (capture, reinstatement) and
208
+ what a host handler reports in `credited`. Other credits the ingest posts,
209
+ such as the `plan_refund` of a superseded term from `createSnapshotHandler`,
210
+ are not announced. The hook is awaited before the provider is answered: keep
211
+ it short and hand slow work to a queue.
212
+ - **`defaultEventHandlers`** (1.1) are the library's `purchase.completed` /
213
+ `purchase.reversed` / `purchase.reinstated` appliers as `EventHandler`s, so a
214
+ host that overrides one kind for a provider can hand the others back per
215
+ delivery. They apply through `ctx.store` (the ingest store bound to the
216
+ handler's transaction; with `ctx.newId`, new on `ApplyContext` in 1.1) and
217
+ return `credited`. A handler given an event of another kind answers
218
+ `ignored` (`no_handler:<kind>`).
219
+ - **`createCheckout({ customerIpAddress })`** (1.1) is forwarded to the adapter's
220
+ `CheckoutRequest` when non-empty; an adapter that cannot use it ignores it.
221
+ `customerEmail`, `externalCustomerId` and `metadata` (1.2) travel the same
222
+ way, each only when non-blank / non-empty (see Polar → *Shared Polar org*).
194
223
  - `sweep` lists only rows of the providers this ingest has adapters for, and
195
224
  a row it cannot even record stays due without stopping the rows behind it.
196
225
  - `onUnmatched` receives deliveries no session matches (e.g. another product's
@@ -241,7 +270,9 @@ const { url } = await polar.createPortalSession({ kind: 'account_id', value: acc
241
270
  no default either, and it picks the API host:
242
271
  `api.polar.sh` or `sandbox-api.polar.sh`. Sandbox and production products
243
272
  have different ids, so pass the `products` map for the environment you run.
244
- Other config errors: `polar_webhook_secrets_required`, `polar_invalid_tolerance`.
273
+ Other config errors: `polar_webhook_secrets_required`, `polar_invalid_tolerance`,
274
+ and, from 1.2, `polar_invalid_app`, `polar_invalid_unlabeled`,
275
+ `polar_unlabeled_requires_app`.
245
276
  - **Standard Webhooks verification** runs on the raw body before any parse.
246
277
  The signed content is `${webhook-id}.${webhook-timestamp}.${rawBody}`, HMAC-SHA256, and any
247
278
  `v1,` entry of `webhook-signature` may match any secret in
@@ -253,13 +284,70 @@ const { url } = await polar.createPortalSession({ kind: 'account_id', value: acc
253
284
  `malformed` (400). Nothing is stored in either case. The event id is
254
285
  `polar:<webhook-id>`, so a retry of a message whose row is final is
255
286
  `duplicate`; a `failed` row is processed again.
287
+ - **Shared Polar org (1.2).** Two hosts can run on one Polar organization
288
+ (Lohi and 2Novel do). Every webhook of the org reaches both, so each host
289
+ tags its checkouts and the adapter keeps only its own events.
290
+
291
+ | Option | |
292
+ |---|---|
293
+ | `app?: string` | This host's tag (non-blank, no surrounding whitespace, at most 128 characters; else `ProviderConfigError('polar_invalid_app')`). Stamped as `metadata.app` next to `metadata.checkout_id` on every checkout. Unset: no tag, no ownership check, behavior and request bodies exactly as 1.1.0 |
294
+ | `unlabeled?: 'accept' \| 'ignore'` | What an event with no `metadata.app` is. `'accept'` (default) processes it as before, for orders made before the tag existed; `'ignore'` leaves it to the other host. Needs `app` (`polar_unlabeled_requires_app`; anything else `polar_invalid_unlabeled`). Type `PolarUnlabeledPolicy` |
295
+
296
+ Ownership is read from `data.metadata.app` of the object the event is about,
297
+ before any other rule: `order.*` from the order, `subscription.*` from the
298
+ subscription, `checkout.*` from the checkout (Polar copies the checkout's
299
+ metadata onto the order and the subscription it creates). Other event types
300
+ are not classified (`unhandled_type:<type>`).
301
+
302
+ | `metadata.app` | `unlabeled` | normalized as |
303
+ |---|---|---|
304
+ | equal to `app` | any | processed as without a tag |
305
+ | present and anything else (another host's tag, empty, not a string, other case) | any | `ignored`, reason `foreign_app` |
306
+ | absent (no `metadata`, no key, or `null`) | `'accept'` | processed as without a tag |
307
+ | absent | `'ignore'` | `ignored`, reason `unlabeled_app` |
308
+
309
+ Foreign wins over every other rule, so a foreign partial refund, unknown
310
+ product, bad amount or unbound order is `ignored`, never `needs_review`.
311
+ What the host sees from `ingest.handle`: `{ status: 'ignored', reason:
312
+ 'foreign_app' }` (or `unlabeled_app`), answered 200 by `respondPolar`
313
+ (`{received, outcome: 'ignored', reason}`), one inbox row in `ignored`, one
314
+ `billing.webhook` event with outcome `ignored`. No ledger entry, purchase,
315
+ term, `subscription.snapshot` handler call, `billing.alert`, `afterCredited`
316
+ or `onUnmatched` relay; a redelivery and `replay` answer `duplicate` with the
317
+ same reason and run nothing. The row is the delivery's redacted payload, kept
318
+ like any ignored delivery, so every foreign event of the org costs this host
319
+ one inbox row: plan the inbox's retention for `foreign_app` rows. Ownership
320
+ runs before the subscription-receipt rule, so with an `app` a renewal order
321
+ without our tag reads `foreign_app` / `unlabeled_app` rather than
322
+ `subscription_order`; nothing is credited either way. `metadata` that is
323
+ present but not an object counts as a foreign (unreadable) label.
324
+
325
+ `createCheckout` (and `ingest.createCheckout`, since the fields are on
326
+ `CheckoutRequest` / `CreateCheckoutInput`) also takes:
327
+
328
+ | Field | Polar request |
329
+ |---|---|
330
+ | `externalCustomerId?: string \| null` | `external_customer_id`; default `accountId`. Lohi: `lohi:<uid>` |
331
+ | `customerEmail?: string \| null` | `customer_email`, trimmed; omitted when blank |
332
+ | `metadata?: Record<string, string \| number \| boolean> \| null` | merged into `metadata` after `checkout_id` and `app` (e.g. `lohi_account`) |
333
+
334
+ `checkout_id` and `app` are reserved, whether or not the adapter has an
335
+ `app`: a host key with either name is refused before any call
336
+ (`polar_reserved_metadata_key`), and a value that is not a string, finite
337
+ number or boolean is `polar_invalid_metadata` (`__proto__` is refused too). Metadata values are
338
+ stored in the inbox with the payload and redacted by key name only: keep
339
+ personal data out of them. Polar's own limits on keys
340
+ and values, and a rejected `customer_email`, come back as a `PolarApiError`
341
+ (`polar_error`, with `status`). With no `app` and none of the new fields the
342
+ request body is byte-identical to 1.1.0. SePay, Apple and Google ignore the
343
+ three fields.
256
344
  - **Credit packs.** `createCheckout` refuses an unmapped `productRef`
257
345
  (exactly one Polar product per ref), a non-positive amount, or a session id
258
346
  that is not `checkoutPattern` before any call (`ProviderConfigError` codes
259
347
  `polar_unknown_product`, `polar_invalid_amount`, `polar_invalid_checkout_id`,
260
348
  and `polar_not_configured` without a token). A failed call is `PolarApiError`
261
349
  (`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`
350
+ with `external_customer_id = accountId` (or `externalCustomerId`), `metadata.checkout_id = sessionId`
263
351
  and `allow_discount_codes: false`. A response whose currency or `amount`
264
352
  (the product price before discount and tax) differs from the catalog amount,
265
353
  or that carries a `discount_amount`, is refused as `polar_price_mismatch`.
@@ -268,9 +356,9 @@ const { url } = await polar.createPortalSession({ kind: 'account_id', value: acc
268
356
  The Polar checkout already exists by then; it is never handed to the buyer.
269
357
  The session id comes from the ingest's `ids` (default `randomUUID`), so a custom
270
358
  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.
359
+ `polar_invalid_checkout_id`. `customerIpAddress` (sent for the tax country) is forwarded by
360
+ `ingest.createCheckout` since 1.1 and accepted by a direct
361
+ `polar.createCheckout` call.
274
362
  `order.paid` for a one-time order becomes `purchase.completed`, bound to the
275
363
  session by `metadata.checkout_id` and credited once (`topup:<sessionId>`).
276
364
  Its amount is the catalog price, `subtotal_amount − discount_amount`, which
package/docs/GUIDE.md ADDED
@@ -0,0 +1,255 @@
1
+ # @tofound/billing — task guide (1.2)
2
+
3
+ How to do the common jobs with the library. [API.md](API.md) is the
4
+ reference for every export; this page walks the order of the calls and what
5
+ to do when something fails. Examples use `LT`-style credits and a Postgres
6
+ host, but nothing here depends on a product.
7
+
8
+ Imports: the main entry `@tofound/billing` has the ledger, ingest, catalog,
9
+ plans, renewal and entitlement; the Drizzle stores and tables are in
10
+ `/drizzle`, `createPolarAdapter` and `resolvePolarEnvironment` in
11
+ `/providers/polar`, and `createAdminAdjustments` in `/hostkit`.
12
+
13
+ Every example assumes the pieces a host builds once:
14
+
15
+ ```ts
16
+ const ledger = createLedger({ store: createDrizzleLedgerStore({ db, tables }) })
17
+ const terms = createDrizzleTermStore({ db, tables: termTables }) // plans only
18
+ const catalog = defineCatalog({ … }) // your config, no literals in the library
19
+ const plans = createPlans({ ledger, terms, catalog })
20
+ const renewal = createRenewal({ ledger, terms, catalog })
21
+ const ingest = createIngest({ adapters, store: createDrizzleIngestStore({ db, tables: ingestTables }), ledger, handlers, afterCredited, onHookError })
22
+ ```
23
+
24
+ Two rules hold throughout. **Prices come from your catalog and your
25
+ server, never from a client.** **Every money effect is keyed**, so a retry,
26
+ a redelivery and a replay each post once.
27
+
28
+ ## 1. Sell credit packs
29
+
30
+ A pack is a server-priced checkout session; the provider's payment credits
31
+ the session once.
32
+
33
+ 1. Declare packs in the catalog: `creditPacks: [{ key, market, provider, price, credits, bonusCredits?, productRef? }]`.
34
+ 2. Start the checkout from the pack, never from a client amount:
35
+
36
+ ```ts
37
+ const pack = catalog.pack(key) // undefined for a key the client invented: answer 404 before going on
38
+ if (!pack) throw new NotFound()
39
+ const { session, redirect } = await ingest.createCheckout({
40
+ provider: pack.provider, accountId, amount: pack.price,
41
+ credits: pack.credits + pack.bonusCredits, productRef: pack.productRef,
42
+ description, successUrl, errorUrl, cancelUrl,
43
+ customerIpAddress, // 1.1: Polar uses it for the tax country; others ignore it
44
+ // 1.2, Polar only (others ignore them): customerEmail, externalCustomerId, metadata — see API.md → Shared Polar org
45
+ })
46
+ // send the buyer to `redirect` (SePay: `kind: 'form'`; Polar: `kind: 'redirect'`)
47
+ ```
48
+
49
+ 3. Mount one raw-body route per provider that calls
50
+ `ingest.handle(provider, { headers, rawBody, url, receivedAt })` and
51
+ replies with `result.response`. The credit posts under `topup:<sessionId>`
52
+ once, however many times the provider repeats itself, and a payment that
53
+ lands after the session expired still credits.
54
+ 4. For a client-return page, poll with `ingest.confirm(provider, proof)`; it
55
+ shares the webhook's event id, so the two cannot double-credit. Check the
56
+ caller owns the session before you call it.
57
+ 5. Run `ingest.sweep()` on a timer: it retries `failed` rows with backoff and
58
+ re-enters rows a crash left `received`.
59
+ 6. React to the credit with `afterCredited` (§ 2), not by polling the ledger.
60
+
61
+ **When it fails:** a wrong amount, a foreign currency or a second capture of
62
+ a paid session goes to `needs_review` with a `billing.alert` and credits
63
+ nothing; fix it by hand and `ingest.replay(provider, eventId)`.
64
+
65
+ ## 2. React to a credit: `afterCredited`
66
+
67
+ ```ts
68
+ createIngest({
69
+ …,
70
+ afterCredited: async (c) => { // c: CreditedPurchase
71
+ // c.provider, c.accountId, c.kind ('completed' | 'reinstated'),
72
+ // c.entry (the ledger entry, delta > 0), c.externalId, c.sessionId
73
+ await renewal.retryPastDue(c.accountId)
74
+ },
75
+ onHookError: (error, c) => report(error, c.accountId),
76
+ })
77
+ ```
78
+
79
+ - It runs **after the delivery's transaction committed**, never inside it. The
80
+ crediting transaction already holds the account lock, which must come last,
81
+ so a hook that opens its own transaction (renewal does) cannot deadlock it.
82
+ - It runs **at most once per credit**. It does not run for a `duplicate`, a
83
+ replay of a settled row, an `ignored` or `needs_review` delivery, a
84
+ reversal, or an empty entry, and not for a delivery that credited nothing
85
+ (an `ignored` or `needs_review` outcome). A delivery with several events
86
+ announces each credit that committed, whatever its sibling's status. A
87
+ transaction that rolled back never ran it; the retry that finally commits
88
+ does.
89
+ - **A throwing hook changes nothing.** The error goes to `onHookError` (whose
90
+ own throw is swallowed) and the delivery stays `applied`, so the provider
91
+ is not asked to redeliver.
92
+ - It announces purchase credits (capture, reinstatement) and what a host
93
+ handler reports in `credited`; the refund a superseded term receives (§ 4)
94
+ is not announced. The hook is awaited before the provider is answered, so
95
+ keep it short.
96
+ - A crash between commit and hook loses the call. Keep a periodic backstop:
97
+ `renewal.renewDue()` retries past-due terms on its next run.
98
+ - It also fires for **host handlers**: a handler you supply for
99
+ `purchase.completed` that credits an account itself returns the credit, and
100
+ the library announces it:
101
+
102
+ ```ts
103
+ handlers: {
104
+ 'purchase.completed': async (event, ctx) => {
105
+ const posted = await ctx.ledger.credit({ … })
106
+ return { status: 'applied', events: posted.events, credited: { accountId, entry: posted.entry, kind: 'completed', sessionId, externalId: event.externalId } }
107
+ },
108
+ }
109
+ ```
110
+
111
+ ### Hand one provider back to the library
112
+
113
+ A host that overrides `purchase.*` for its own top-up table still wants the
114
+ library's appliers for a provider whose sessions live in the library tables
115
+ (Polar). Delegate per provider with `defaultEventHandlers`:
116
+
117
+ ```ts
118
+ const purchase: EventHandler<Tx> = (event, ctx) =>
119
+ ctx.delivery.provider === 'polar'
120
+ ? defaultEventHandlers['purchase.completed'](event, ctx) // or 'purchase.reversed' / 'purchase.reinstated'
121
+ : hostTopup(event, ctx)
122
+ handlers: { 'purchase.completed': purchase, 'purchase.reversed': …, 'purchase.reinstated': … }
123
+ ```
124
+
125
+ `ctx.store` is the ingest store bound to the handler's transaction; the
126
+ default handlers apply through it and report the credit they post.
127
+
128
+ ## 3. Sell a monthly plan end to end
129
+
130
+ 1. **Catalog.** Plans with strict `rank` (one `free`), credit offers per
131
+ `market × months`, and `policies` (`graceDays`, `renewalLeadSec`,
132
+ `upgradeProration`).
133
+ 2. **Quote.** `plans.quote({ accountId, plan, months, market })` returns the
134
+ kind (`new`, `extend`, `upgrade`, `renew`, `downgrade`, `blocked`), the
135
+ price and the funding lines. Render those lines; do not recompute them.
136
+ `market` is set by the host, never taken from the client.
137
+ 3. **Purchase.** `plans.purchase({ …, idempotencyKey })`, inside the host
138
+ transaction when it also writes host rows (`plans.in(tx)`; a throw must
139
+ roll that transaction back). Mint the key once per confirm: a retry with it
140
+ buys once.
141
+ 4. **Entitlement.** `resolveEntitlement(await terms.reader().listTerms(accountId), now, catalog, { balance })`
142
+ answers the plan, status (`active`, `grace`, `free`), warnings and quotas.
143
+ 5. **Renewal.** `renewal.renewDue({ limit })` on a timer (every 15 minutes is
144
+ fine) under the host's own advisory lock, so two instances do not both
145
+ run. It charges the live catalog price, keyed by term and period end, so a
146
+ double run debits once.
147
+ 6. **Retry on top-up.** `afterCredited` (§ 2) calls
148
+ `renewal.retryPastDue(accountId)`; the term continues from its old end.
149
+ The timer is the backstop.
150
+
151
+ ## 4. Sell a provider subscription, and supersede a credit term
152
+
153
+ 1. Add a provider offer to the plan: `{ source: 'polar', productRef, market, interval, price }`,
154
+ and map the provider's product ids to those refs in the adapter's
155
+ `products`.
156
+ 2. Create the checkout **outside the ingest**: `polar.createCheckout({ sessionId: randomUUID(), accountId, amount: offer.price, productRef, … })`
157
+ with the catalog price (the adapter refuses a product priced differently).
158
+ No session row is written.
159
+ 3. Wire the snapshot handler:
160
+ `handlers: { 'subscription.snapshot': createSnapshotHandler({ terms, catalog, resolveAccount }) }`.
161
+ `resolveAccount` maps the provider's external customer id to your account
162
+ and returns `null` for another host's customer.
163
+ 4. **Supersede (S4).** When an entitled provider subscription of the same or
164
+ higher rank arrives, the snapshot handler closes the open credit term
165
+ (`superseded`) and refunds its unused share as a `plan_refund` credit
166
+ keyed `supersede:<termId>`. Before that, `plans.quote` answers `blocked`
167
+ (`covered_by_subscription`) for a plan the subscription already covers,
168
+ so the buyer is not charged twice.
169
+ 5. Give the buyer the provider's portal for card and cancel:
170
+ `polar.createPortalSession({ kind: 'account_id', value: accountId }, returnUrl)`.
171
+
172
+ ## 5. Handle a failed renewal, per source
173
+
174
+ | Source | What fails | What the library does | What the host does |
175
+ |---|---|---|---|
176
+ | **Credit renewal** | Balance below the live price at `periodEnd − renewalLeadSec` | An early failure emits `renewal_failed` and leaves the term `active`. At the period end the term becomes `past_due` with `graceUntil = periodEnd + graceDays`, still entitled. After the grace it is `expired`. | Show the shortfall from the `renewal_failed` event (`required`, `balance`, `shortfall`). A top-up fires `afterCredited`, which calls `retryPastDue`; the renewal timer retries too. |
177
+ | **Polar subscription** | The card is declined; Polar retries | The snapshot goes `past_due` and the term gets a grace window. `revoked`, or `canceled` once ended, ends access. Snapshots are ordered by Polar's `modified_at`, so an old one cannot undo a new one. | Show "update your card" with the portal link. A card fix arrives as an `active` snapshot; nothing else to do. |
178
+ | **Apple** | Billing retry or grace period (App Store) | Auto-renewable notifications become snapshots with `past_due` / `grace`. One-time (consumable) purchases are keyed by transaction; a refund reverses once. | Treat Apple's own retry and grace as the source of truth; do not charge credits for an Apple term. Selling Apple subscriptions is the host's decision; the adapter handles the notifications. |
179
+ | **Any webhook** | The handler throws | The row is `failed`, answered 5xx so the provider redelivers, retried by `sweep` with backoff, then `dead` with a `billing.alert`. | Alert on `billing.alert`; fix the cause and `ingest.replay(provider, eventId)`. |
180
+
181
+ A failed **pack** payment creates no order and no credit; the session simply
182
+ expires, and a late payment still credits once.
183
+
184
+ ## 6. Refunds and reversals, and the shortfall
185
+
186
+ - A provider refund, chargeback or void becomes a reversal. The library
187
+ claws back through `ledger.reverse` (`reversal:<provider>:<externalId>:<n>`)
188
+ what the balance still holds; the part the buyer already spent is recorded
189
+ as the purchase's **`shortfall`** and reported in a `refund_applied` event
190
+ (`clawedBack`, `shortfall`).
191
+ - The reversal is ordered by the provider's own timestamp, so a refund that
192
+ arrives before its payment parks the payment and never credits it; a
193
+ reinstatement restores exactly what was taken back.
194
+ - **A shortfall is policy, and the host applies it.** The catalog carries the
195
+ choice (`policies.reversalShortfall`: `record` or `lapse_credit_terms`), but
196
+ the library only reports the numbers: it records the shortfall on the
197
+ purchase and emits `refund_applied`. Read the policy there and either record
198
+ it for support or close the credit terms the credits had bought yourself.
199
+ The library never takes a balance below zero to cover it.
200
+ - A **partial** refund is never guessed: it goes to `needs_review`.
201
+ Settle it by hand with an `adjustment` (`createAdminAdjustments`, which
202
+ can `clamp` to the balance and reports the shortfall).
203
+
204
+ ## 7. Arm a provider in production (two switches)
205
+
206
+ A provider in production needs two independent switches, so a half-finished
207
+ deploy cannot take real money.
208
+
209
+ 1. **The environment is explicit.** The adapter has no default.
210
+ `resolvePolarEnvironment({ environment: env.POLAR_ENV, productionEnabled: env.POLAR_PRODUCTION_ENABLED === 'true' })`
211
+ returns `production` only when **both** `POLAR_ENV=production` **and**
212
+ `productionEnabled` hold; `production` without the flag throws
213
+ `polar_production_disabled`, and an unset or misspelled value throws
214
+ `polar_environment_required`.
215
+ 2. **The credentials match the environment.** Production secrets, the
216
+ production product ids in `products`, and a webhook secret for the
217
+ production endpoint. SePay refuses test credentials in production (and
218
+ live ones in sandbox).
219
+
220
+ Rehearse the switch in sandbox first, keep the routes returning 503 until
221
+ both switches are on, and disarm by clearing the second switch. Hosts
222
+ rotate secrets by listing the new one beside the old (`webhookSecrets`,
223
+ `webhookKeys`) and removing the old one after a day.
224
+
225
+ ## 8. Migrate a legacy term table
226
+
227
+ The recipe Lohi follows for its subscription table, generic for any host
228
+ that already has one row per subscription.
229
+
230
+ 1. **Add the library tables** (`createTermTables`) as new tables only; run
231
+ your own `db:generate` and `checkAdditiveDdl` on the SQL. Never alter the
232
+ legacy table.
233
+ 2. **Copy with deterministic ids** (`legacy_<id>`), in batches of a few hundred
234
+ rows, one transaction each, `ON CONFLICT DO NOTHING`, key order, with a
235
+ `--dry-run`. Map: live row → an open `active` credit term; every other
236
+ row → `expired` (keep the original status in `meta`); a second live row →
237
+ a `scheduled` term, or list it for a human.
238
+ 3. **Run modes, flipped by config only:** `legacy` (read and write the old
239
+ table) → `dual` (still the old table, mirror each write into terms in the
240
+ same transaction, run the library resolver in shadow and log mismatches)
241
+ → `library_read` (read terms) → `library` (write through `createPlans` /
242
+ `createRenewal`, and project back to the legacy row in the same
243
+ transaction so a rollback is a config flip).
244
+ 4. **Check parity both ways** before each step: every legacy row has its
245
+ term and the reverse; per account the resolved plan, end date, auto-renew
246
+ and status class match; the ledger history is untouched.
247
+ 5. **Never drop the legacy table** in the same project.
248
+
249
+ ## 9. Google Play subscriptions are not supported
250
+
251
+ The Google adapter handles **one-time products** only: a purchase is trusted
252
+ only as Play's own `products.get` answer, and a voided purchase is clawed
253
+ back once. Google Play **subscriptions are not supported yet**: subscription
254
+ notifications are acknowledged and `ignored`, no term is created and no
255
+ credit is granted. Do not sell a Google subscription through this library.
@@ -220,6 +220,61 @@ Ask the catalog for tiers (`SUBSCRIPTION_TIERS`,
220
220
  `tiersWithPermission(…)`). Never retype a tier list: the library carries no
221
221
  tier literals.
222
222
 
223
+ ## Shared Polar org (1.2.0)
224
+
225
+ Lohi and 2Novel use one Polar organization, so every Polar webhook reaches
226
+ both hosts. Without a tag, a Lohi order refunded partially lands in
227
+ 2Novel's `needs_review` queue and the other way round. 1.2.0 gives the Polar
228
+ adapter an `app` tag. Adopt it when Lohi moves its Polar checkout onto the
229
+ library; it replaces the private fetch decorator Lohi uses to stamp checkouts.
230
+
231
+ ```ts
232
+ const polar = createPolarAdapter({
233
+ environment, webhookSecrets, products, accessToken,
234
+ app: 'lohi', // 2Novel: '2novel'
235
+ unlabeled: 'accept', // switch Lohi to 'ignore' only after the checks below; 2Novel keeps 'accept'
236
+ })
237
+
238
+ // Per checkout; ingest.createCheckout takes the same three fields.
239
+ await polar.createCheckout({
240
+ ...request,
241
+ externalCustomerId: `lohi:${user.id}`,
242
+ customerEmail: user.email,
243
+ metadata: { lohi_account: user.id }, // `checkout_id` and `app` are reserved
244
+ })
245
+ ```
246
+
247
+ - **Events:** `metadata.app === 'lohi'` is processed as before. Another tag is
248
+ `ignored` (`foreign_app`) and an event without the tag is `ignored`
249
+ (`unlabeled_app`) under `'ignore'`. Neither is credited, reversed,
250
+ snapshotted, alerted or relayed through `onUnmatched`, and a redelivery or
251
+ `replay` stays `ignored`. `respondPolar` acknowledges them with 200.
252
+ - **Account ids:** the library does not read `lohi_account`. With
253
+ `externalCustomerId: 'lohi:<uid>'`, subscription events arrive with
254
+ `account = { kind: 'polar_customer_external_id', value: 'lohi:<uid>' }`, and
255
+ `resolveAccount` strips the prefix. Reject an unprefixed id.
256
+ - **Account ids and the portal:** a portal for a namespaced customer takes the
257
+ `polar_customer_external_id` kind with the prefixed value
258
+ (`{ kind: 'polar_customer_external_id', value: 'lohi:<uid>' }`); an
259
+ `account_id` ref is sent as is, without the prefix.
260
+ - **Before turning on `'ignore'`:** an event is Lohi's only if its object
261
+ carries `metadata.app`. Both hosts stamp UUID `checkout_id`s, so an event
262
+ with only a `checkout_id` cannot be told apart and is ignored
263
+ (`unlabeled_app`) under `'ignore'`: no credit, no reversal, no alert. That
264
+ covers a checkout created before the tag shipped and paid later (a payment
265
+ after the 30-minute session still credits), and the refund of any order made
266
+ before the tag. Keep `'accept'` until the pre-tag sessions have settled, and
267
+ deal with pre-tag refunds by hand. Subscription events are classified by the
268
+ subscription's own `metadata.app`, which relies on Polar copying the
269
+ checkout's metadata onto the subscription (it does for orders): check one
270
+ sandbox subscription end to end first, or its access is never granted.
271
+ - **Personal data:** the inbox redacts by key name only, so a PII value under a
272
+ neutral metadata key (`note: 'John Doe'`) is stored. Put ids in `metadata`,
273
+ never names, emails or phone numbers.
274
+ - **Both hosts:** deploy the tag on the checkout side before turning on `ignore`
275
+ on the receiving side, and keep the webhook subscription of each host
276
+ pointed at its own URL; the tag only decides whose event a delivery is.
277
+
223
278
  ## Quotes
224
279
 
225
280
  Lohi keeps `planFunding()` and `GATES`, and `/pricing/quote` stays byte
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tofound/billing",
3
- "version": "1.0.0",
3
+ "version": "1.2.0",
4
4
  "description": "Shared subscription and credit library by 2found: credit ledger, quote/charge waterfall, Drizzle schema factory.",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -52,6 +52,7 @@
52
52
  "files": [
53
53
  "dist",
54
54
  "docs/API.md",
55
+ "docs/GUIDE.md",
55
56
  "docs/MIGRATION-LOHI.md",
56
57
  "docs/SCHEMA.md",
57
58
  "README.md",