@tofound/billing 1.1.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,37 @@ 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
+
7
38
  ## 1.1.0 — 2026-10-24
8
39
 
9
40
  Additive to 1.0: every 1.0 export is unchanged (the public-api declaration
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.1 ships (the public API is frozen from 1.0.0 on; 1.1 only adds):
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.1.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
@@ -104,6 +104,12 @@ export interface CreateCheckoutInput {
104
104
  cancelUrl: string;
105
105
  /** The buyer's IP, forwarded to adapters that use it (Polar picks the tax country from it). Empty or blank means unknown. */
106
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;
107
113
  /** Session lifetime. Default 30 min. A payment after it still credits. */
108
114
  ttlMs?: number;
109
115
  meta?: Record<string, unknown> | null;
@@ -414,6 +414,9 @@ export function createIngest(options) {
414
414
  cancelUrl: input.cancelUrl,
415
415
  productRef: session.productRef,
416
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 } : {}),
417
420
  });
418
421
  await store.transaction((tx) => store.bind(tx).insertSession(session));
419
422
  return { session, redirect };
@@ -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()`. */
@@ -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.
@@ -153,6 +153,12 @@ export interface CheckoutRequest {
153
153
  productRef?: string | null;
154
154
  /** The buyer's IP when the host has it; adapters that cannot use it ignore it (Polar: tax country). */
155
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;
156
162
  }
157
163
  export type CheckoutRedirect = {
158
164
  kind: 'redirect';
package/docs/API.md CHANGED
@@ -1,7 +1,7 @@
1
- # @tofound/billing — API (1.1)
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; 1.1.0 is additive to 1.0.0. 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
7
  version. For task-oriented walkthroughs (packs, plans, failed renewals,
@@ -218,6 +218,8 @@ await ingest.sweep()
218
218
  `ignored` (`no_handler:<kind>`).
219
219
  - **`createCheckout({ customerIpAddress })`** (1.1) is forwarded to the adapter's
220
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*).
221
223
  - `sweep` lists only rows of the providers this ingest has adapters for, and
222
224
  a row it cannot even record stays due without stopping the rows behind it.
223
225
  - `onUnmatched` receives deliveries no session matches (e.g. another product's
@@ -268,7 +270,9 @@ const { url } = await polar.createPortalSession({ kind: 'account_id', value: acc
268
270
  no default either, and it picks the API host:
269
271
  `api.polar.sh` or `sandbox-api.polar.sh`. Sandbox and production products
270
272
  have different ids, so pass the `products` map for the environment you run.
271
- 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`.
272
276
  - **Standard Webhooks verification** runs on the raw body before any parse.
273
277
  The signed content is `${webhook-id}.${webhook-timestamp}.${rawBody}`, HMAC-SHA256, and any
274
278
  `v1,` entry of `webhook-signature` may match any secret in
@@ -280,13 +284,70 @@ const { url } = await polar.createPortalSession({ kind: 'account_id', value: acc
280
284
  `malformed` (400). Nothing is stored in either case. The event id is
281
285
  `polar:<webhook-id>`, so a retry of a message whose row is final is
282
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.
283
344
  - **Credit packs.** `createCheckout` refuses an unmapped `productRef`
284
345
  (exactly one Polar product per ref), a non-positive amount, or a session id
285
346
  that is not `checkoutPattern` before any call (`ProviderConfigError` codes
286
347
  `polar_unknown_product`, `polar_invalid_amount`, `polar_invalid_checkout_id`,
287
348
  and `polar_not_configured` without a token). A failed call is `PolarApiError`
288
349
  (`polar_unreachable`, `polar_error` with `status`, `polar_bad_response`). It then creates a Polar checkout
289
- with `external_customer_id = accountId`, `metadata.checkout_id = sessionId`
350
+ with `external_customer_id = accountId` (or `externalCustomerId`), `metadata.checkout_id = sessionId`
290
351
  and `allow_discount_codes: false`. A response whose currency or `amount`
291
352
  (the product price before discount and tax) differs from the catalog amount,
292
353
  or that carries a `discount_amount`, is refused as `polar_price_mismatch`.
package/docs/GUIDE.md CHANGED
@@ -1,4 +1,4 @@
1
- # @tofound/billing — task guide (1.1)
1
+ # @tofound/billing — task guide (1.2)
2
2
 
3
3
  How to do the common jobs with the library. [API.md](API.md) is the
4
4
  reference for every export; this page walks the order of the calls and what
@@ -41,6 +41,7 @@ the session once.
41
41
  credits: pack.credits + pack.bonusCredits, productRef: pack.productRef,
42
42
  description, successUrl, errorUrl, cancelUrl,
43
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
44
45
  })
45
46
  // send the buyer to `redirect` (SePay: `kind: 'form'`; Polar: `kind: 'redirect'`)
46
47
  ```
@@ -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.1.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",