@tofound/billing 1.3.0 → 1.4.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,31 @@ 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.4.0 — 2026-10-29
8
+
9
+ Additive to 1.3: every 1.3 export is unchanged (the public-api declaration
10
+ snapshot only grows). No schema change. `readOrder`, `verifyPurchase`,
11
+ `cancelOrder` and `confirm` behave exactly as in 1.3.0.
12
+
13
+ To adopt: pin `@tofound/billing@1.4.0`.
14
+
15
+ - **Read-only purchase lookup.** A new provider port, `PurchaseLookup<TProof>`
16
+ (`lookupPurchase(proof): Promise<PurchaseLookupResult>`). It reports what the
17
+ provider says about one purchase: `paid` (with `externalId`, `amount` and
18
+ `occurredAt`), `pending`, `cancelled`, `not_found`, or `unavailable` with a
19
+ short reason. It never applies anything and never throws. The guard
20
+ `isPurchaseLookup` is exported from the root entry.
21
+ - **SePay `lookupPurchase({ invoice })`.** One order-detail GET. `CAPTURED`
22
+ maps to `paid` (`externalId` = order id, else the invoice; `occurredAt` = the
23
+ lookup time), `AUTHENTICATION_NOT_NEEDED` to `pending` and `CANCELLED` to
24
+ `cancelled`. HTTP 404 or no data for the invoice is `not_found`. A timeout,
25
+ network error, other non-2xx or unparseable order is `unavailable` with the
26
+ reason `timeout`, `network`, `http_<n>` or `malformed`; missing merchant
27
+ credentials give `not_configured`. The new option
28
+ `SepayAdapterOptions.lookupTimeoutMs` sets the timeout (default 8 s);
29
+ `timeoutMs` still governs `readOrder`.
30
+ - **Docs:** README (SePay section).
31
+
7
32
  ## 1.3.0 — 2026-10-28
8
33
 
9
34
  Additive to 1.2: every 1.2 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.3 ships (the public API is frozen from 1.0.0 on; 1.1, 1.2 and 1.3 only add):
7
+ 1.4 ships (the public API is frozen from 1.0.0 on; 1.1 to 1.4 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.3.0 --exact # peer: drizzle-orm ^0.45 for /drizzle
26
+ bun add @tofound/billing@1.4.0 --exact # peer: drizzle-orm ^0.45 for /drizzle
27
27
  ```
28
28
 
29
29
  ```ts
@@ -64,6 +64,32 @@ It also opens checkouts (`createCheckout`) and customer portal sessions.
64
64
  switches into one required value. `signPolarWebhook` signs test deliveries.
65
65
  The full entry is in `docs/API.md`.
66
66
 
67
+ ## SePay
68
+
69
+ `@tofound/billing/providers/sepay` verifies and normalizes SePay IPNs, signs
70
+ checkout forms and reads orders. `createSepayAdapter({ environment,
71
+ webhookKeys, merchantId, secretKey })` needs the environment passed explicitly
72
+ and refuses credentials of the other rail.
73
+
74
+ `lookupPurchase({ invoice })` (new in 1.4, the `PurchaseLookup` port) is a
75
+ read-only answer about one invoice. It makes one order-detail request, applies
76
+ nothing and never throws; `isPurchaseLookup(adapter)` tells whether an adapter
77
+ has it. It maps the order like this:
78
+
79
+ | SePay answers | Result |
80
+ |---|---|
81
+ | `CAPTURED` | `paid`: `externalId` = order id (else the invoice), `amount` in VND, `occurredAt` = the lookup time (the order body carries no paid time) |
82
+ | `AUTHENTICATION_NOT_NEEDED` | `pending` |
83
+ | `CANCELLED` | `cancelled` |
84
+ | HTTP 404, or no `data` for this invoice | `not_found` |
85
+ | timeout (`lookupTimeoutMs`, default 8 s), network error | `unavailable`, reason `timeout` / `network` |
86
+ | any other non-2xx (5xx, 401, 403 …) | `unavailable`, reason `http_<status>` |
87
+ | an unparseable body, or this invoice in another currency, amount or status | `unavailable`, reason `malformed` |
88
+ | no merchant credentials configured | `unavailable`, reason `not_configured` |
89
+
90
+ To credit a paid invoice, the host still goes through `verifyPurchase` or its
91
+ own apply path. `readOrder` and `verifyPurchase` are unchanged.
92
+
67
93
  ## Host kit
68
94
 
69
95
  `@tofound/billing/hostkit` (new in 1.0) is for hosts that keep their own
@@ -186,6 +186,27 @@ export interface PortalCapable {
186
186
  export interface PurchaseVerifier<TProof = unknown> {
187
187
  verifyPurchase(proof: TProof): Promise<VerifiedDelivery | null>;
188
188
  }
189
+ /**
190
+ * What the provider says about one purchase right now. `paid.occurredAt` is
191
+ * the adapter's best time for the capture (SePay: the lookup time, since its
192
+ * order body carries none); `unavailable` is any answer the adapter could not
193
+ * vouch for, with a short code (`timeout`, `network`, `http_<n>`, `malformed` …).
194
+ */
195
+ export type PurchaseLookupResult = {
196
+ state: 'paid';
197
+ externalId: string;
198
+ amount: Money;
199
+ occurredAt: Date;
200
+ } | {
201
+ state: 'pending' | 'cancelled' | 'not_found';
202
+ } | {
203
+ state: 'unavailable';
204
+ reason: string;
205
+ };
206
+ /** Read-only: what the provider says about one purchase. Never applies anything and never throws. */
207
+ export interface PurchaseLookup<TProof = unknown> {
208
+ lookupPurchase(proof: TProof): Promise<PurchaseLookupResult>;
209
+ }
189
210
  export interface Reconcilable {
190
211
  listChangesSince(cursor: string | null, limit: number): Promise<{
191
212
  deliveries: VerifiedDelivery[];
@@ -200,6 +221,7 @@ export interface ConsumptionReporter {
200
221
  }
201
222
  export declare function isCheckoutCapable<T extends object>(adapter: T): adapter is T & CheckoutCapable;
202
223
  export declare function isPurchaseVerifier<T extends object>(adapter: T): adapter is T & PurchaseVerifier;
224
+ export declare function isPurchaseLookup(adapter: unknown): adapter is PurchaseLookup;
203
225
  /** `verify` refused a delivery: `unauthorized` → 401, `malformed` → 400. Nothing is stored. */
204
226
  export declare class VerifyError extends Error {
205
227
  readonly name = "VerifyError";
@@ -4,6 +4,9 @@ export function isCheckoutCapable(adapter) {
4
4
  export function isPurchaseVerifier(adapter) {
5
5
  return typeof adapter.verifyPurchase === 'function';
6
6
  }
7
+ export function isPurchaseLookup(adapter) {
8
+ return typeof adapter === 'object' && adapter !== null && typeof adapter.lookupPurchase === 'function';
9
+ }
7
10
  // ---------------------------------------------------------------------------
8
11
  // Errors
9
12
  // ---------------------------------------------------------------------------
@@ -1,4 +1,4 @@
1
- import { type CheckoutCapable, type IngestOutcome, type ProviderAdapter, type ProviderEnvironment, type ProviderResponse, type PurchaseVerifier } from '../port.js';
1
+ import { type CheckoutCapable, type IngestOutcome, type ProviderAdapter, type ProviderEnvironment, type ProviderResponse, type PurchaseLookup, type PurchaseVerifier } from '../port.js';
2
2
  import { type SepayOrderState } from './order.js';
3
3
  export { parseSepayOrder, parseVnd, type SepayOrderState } from './order.js';
4
4
  export { signCheckoutFields } from './signature.js';
@@ -17,12 +17,14 @@ export interface SepayAdapterOptions {
17
17
  fetch?: typeof fetch;
18
18
  /** Order API timeout. Default 10 s. */
19
19
  timeoutMs?: number;
20
+ /** `lookupPurchase` timeout per call; past it the answer is `unavailable/timeout`. Default 8 s. */
21
+ lookupTimeoutMs?: number;
20
22
  }
21
23
  /** Poll proof: the checkout session id used as the SePay invoice. */
22
24
  export interface SepayPurchaseProof {
23
25
  invoice: string;
24
26
  }
25
- export interface SepayAdapter extends ProviderAdapter, CheckoutCapable, PurchaseVerifier<SepayPurchaseProof> {
27
+ export interface SepayAdapter extends ProviderAdapter, CheckoutCapable, PurchaseVerifier<SepayPurchaseProof>, PurchaseLookup<SepayPurchaseProof> {
26
28
  readonly id: 'sepay';
27
29
  /** Current order state; `unknown` on any lookup failure. */
28
30
  readOrder(invoice: string): Promise<SepayOrderState>;
@@ -154,6 +154,15 @@ export function createSepayAdapter(options) {
154
154
  const now = new Date();
155
155
  return deliveryOf(body, now, JSON.stringify(body));
156
156
  },
157
+ async lookupPurchase(proof) {
158
+ // Read-only and never throws: missing merchant credentials are an answer too.
159
+ if (!merchantId || !secretKey)
160
+ return { state: 'unavailable', reason: 'not_configured' };
161
+ // No invoice names no order; a typed caller cannot pass one, an untyped one gets an answer, not a throw.
162
+ if (typeof proof?.invoice !== 'string' || proof.invoice === '')
163
+ return { state: 'not_found' };
164
+ return orderClient().lookup(proof.invoice, options.lookupTimeoutMs ?? 8_000);
165
+ },
157
166
  readOrder: async (invoice) => orderClient().read(invoice),
158
167
  cancelOrder: async (invoice) => orderClient().cancel(invoice),
159
168
  };
@@ -4,6 +4,7 @@
4
4
  * cancellation, and another invoice or currency is never accepted as this
5
5
  * purchase.
6
6
  */
7
+ import type { PurchaseLookupResult } from '../port.js';
7
8
  export type SepayOrderState = {
8
9
  state: 'unknown';
9
10
  } | {
@@ -24,6 +25,12 @@ export interface SepayOrderClientOptions {
24
25
  }
25
26
  export declare function createSepayOrderClient(options: SepayOrderClientOptions): {
26
27
  read: (invoice: string) => Promise<SepayOrderState>;
28
+ /**
29
+ * The read-only lookup over the same order-detail request: a missing
30
+ * order is `not_found`, anything the client cannot vouch for is
31
+ * `unavailable` with a short code, and it never throws.
32
+ */
33
+ lookup(invoice: string, timeoutMs: number): Promise<PurchaseLookupResult>;
27
34
  /**
28
35
  * A 200 cancellation answer is not a state snapshot: re-read the order,
29
36
  * so a capture racing the cancellation wins and is still settled.
@@ -1,9 +1,3 @@
1
- /**
2
- * SePay order API (read, cancel), ported from Lohi `api/src/lib/sepay.ts` —
3
- * the stricter of the two host copies: a lookup failure is never proof of
4
- * cancellation, and another invoice or currency is never accepted as this
5
- * purchase.
6
- */
7
1
  /** Parse SePay's order body (`{data: {...}}`) for `invoice`. Anything off is `unknown`. */
8
2
  export function parseSepayOrder(body, invoice) {
9
3
  const data = body?.data;
@@ -31,20 +25,31 @@ export function parseVnd(raw) {
31
25
  }
32
26
  export function createSepayOrderClient(options) {
33
27
  const authorization = `Basic ${Buffer.from(`${options.merchantId}:${options.secretKey}`).toString('base64')}`;
34
- async function request(path, body) {
35
- const response = await options.fetch(`${options.apiBase}/${path}`, {
28
+ function call(path, signal, body) {
29
+ return options.fetch(`${options.apiBase}/${path}`, {
36
30
  method: body ? 'POST' : 'GET',
37
31
  headers: { Authorization: authorization, 'Content-Type': 'application/json' },
38
32
  ...(body ? { body: JSON.stringify(body) } : {}),
39
- signal: AbortSignal.timeout(options.timeoutMs),
33
+ signal,
40
34
  });
35
+ }
36
+ /** Network errors and the timeout throw; everything the server answered is returned. */
37
+ async function detail(invoice, signal) {
38
+ const response = await call(`order/detail/${encodeURIComponent(invoice)}`, signal);
41
39
  if (!response.ok)
42
- return null;
43
- return response.json();
40
+ return { status: response.status, json: false };
41
+ const text = await response.text();
42
+ try {
43
+ return { status: response.status, json: true, body: JSON.parse(text) };
44
+ }
45
+ catch {
46
+ return { status: response.status, json: false };
47
+ }
44
48
  }
45
49
  async function read(invoice) {
46
50
  try {
47
- return parseSepayOrder(await request(`order/detail/${encodeURIComponent(invoice)}`), invoice);
51
+ const answer = await detail(invoice, AbortSignal.timeout(options.timeoutMs));
52
+ return answer.json ? parseSepayOrder(answer.body, invoice) : { state: 'unknown' };
48
53
  }
49
54
  catch {
50
55
  return { state: 'unknown' };
@@ -52,13 +57,35 @@ export function createSepayOrderClient(options) {
52
57
  }
53
58
  return {
54
59
  read,
60
+ /**
61
+ * The read-only lookup over the same order-detail request: a missing
62
+ * order is `not_found`, anything the client cannot vouch for is
63
+ * `unavailable` with a short code, and it never throws.
64
+ */
65
+ async lookup(invoice, timeoutMs) {
66
+ const signal = AbortSignal.timeout(timeoutMs);
67
+ let answer;
68
+ try {
69
+ answer = await detail(invoice, signal);
70
+ }
71
+ catch {
72
+ return { state: 'unavailable', reason: signal.aborted ? 'timeout' : 'network' };
73
+ }
74
+ if (answer.status === 404)
75
+ return { state: 'not_found' };
76
+ if (answer.status < 200 || answer.status > 299)
77
+ return { state: 'unavailable', reason: `http_${answer.status}` };
78
+ if (!answer.json)
79
+ return { state: 'unavailable', reason: 'malformed' };
80
+ return lookupResultOf(answer.body, invoice, new Date());
81
+ },
55
82
  /**
56
83
  * A 200 cancellation answer is not a state snapshot: re-read the order,
57
84
  * so a capture racing the cancellation wins and is still settled.
58
85
  */
59
86
  async cancel(invoice) {
60
87
  try {
61
- await request('order/cancel', { order_invoice_number: invoice });
88
+ await call('order/cancel', AbortSignal.timeout(options.timeoutMs), { order_invoice_number: invoice });
62
89
  }
63
90
  catch {
64
91
  // The re-read below is the answer either way.
@@ -67,3 +94,25 @@ export function createSepayOrderClient(options) {
67
94
  },
68
95
  };
69
96
  }
97
+ /**
98
+ * A 2xx order body as a lookup result. No `data` for this invoice is
99
+ * `not_found`; data for it that `parseSepayOrder` refuses (another currency,
100
+ * an unreadable amount or status) is `malformed`, never a guess. `paid` carries
101
+ * the lookup time: SePay's order body has no capture time.
102
+ */
103
+ function lookupResultOf(body, invoice, now) {
104
+ const data = body?.data;
105
+ if (!data || typeof data !== 'object' || data['order_invoice_number'] !== invoice) {
106
+ return { state: 'not_found' };
107
+ }
108
+ const order = parseSepayOrder(body, invoice);
109
+ switch (order.state) {
110
+ case 'paid':
111
+ return { state: 'paid', externalId: order.orderId ?? invoice, amount: { currency: 'VND', amountMinor: order.amountVnd }, occurredAt: now };
112
+ case 'pending':
113
+ case 'cancelled':
114
+ return { state: order.state };
115
+ default:
116
+ return { state: 'unavailable', reason: 'malformed' };
117
+ }
118
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tofound/billing",
3
- "version": "1.3.0",
3
+ "version": "1.4.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",