@fantastic.dev/better-stripe 0.31.0 → 0.33.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 +13 -0
- package/README.md +7 -1
- package/dist/client/billing/checkoutPages.d.ts +26 -0
- package/dist/client/billing/checkoutPages.d.ts.map +1 -0
- package/dist/client/billing/checkoutPages.js +111 -0
- package/dist/client/billing/checkoutPages.js.map +1 -0
- package/dist/client/billing/invoicePaymentPages.d.ts +28 -0
- package/dist/client/billing/invoicePaymentPages.d.ts.map +1 -0
- package/dist/client/billing/invoicePaymentPages.js +124 -0
- package/dist/client/billing/invoicePaymentPages.js.map +1 -0
- package/dist/client/connect/refundContext.d.ts +6 -0
- package/dist/client/connect/refundContext.d.ts.map +1 -0
- package/dist/client/connect/refundContext.js +109 -0
- package/dist/client/connect/refundContext.js.map +1 -0
- package/dist/client/connect/refundContextHistory.d.ts +20 -0
- package/dist/client/connect/refundContextHistory.d.ts.map +1 -0
- package/dist/client/connect/refundContextHistory.js +55 -0
- package/dist/client/connect/refundContextHistory.js.map +1 -0
- package/dist/client/connect/refundContextTypes.d.ts +39 -0
- package/dist/client/connect/refundContextTypes.d.ts.map +1 -0
- package/dist/client/connect/refundContextTypes.js +15 -0
- package/dist/client/connect/refundContextTypes.js.map +1 -0
- package/dist/client/connect/refundTarget.d.ts +14 -0
- package/dist/client/connect/refundTarget.d.ts.map +1 -0
- package/dist/client/connect/refundTarget.js +17 -0
- package/dist/client/connect/refundTarget.js.map +1 -0
- package/dist/client/connect/refunds.d.ts +17 -1
- package/dist/client/connect/refunds.d.ts.map +1 -1
- package/dist/client/connect/refunds.js +7 -17
- package/dist/client/connect/refunds.js.map +1 -1
- package/dist/client/index.d.ts +6 -6
- package/dist/client/index.d.ts.map +1 -1
- package/dist/client/index.js +2 -7
- package/dist/client/index.js.map +1 -1
- package/dist/client/invoiceReads.d.ts +20 -0
- package/dist/client/invoiceReads.d.ts.map +1 -0
- package/dist/client/invoiceReads.js +25 -0
- package/dist/client/invoiceReads.js.map +1 -0
- package/docs/checkout-session-pages.md +71 -0
- package/docs/invoice-payment-pages.md +43 -0
- package/docs/read-contracts.md +44 -0
- package/docs/refund-context.md +84 -0
- package/package.json +5 -2
- package/src/client/billing/checkoutPages.test.ts +251 -0
- package/src/client/billing/checkoutPages.ts +135 -0
- package/src/client/billing/invoicePaymentPages.test.ts +354 -0
- package/src/client/billing/invoicePaymentPages.ts +165 -0
- package/src/client/connect/refundContext.ts +140 -0
- package/src/client/connect/refundContextHistory.ts +84 -0
- package/src/client/connect/refundContextTypes.ts +56 -0
- package/src/client/connect/refundTarget.ts +39 -0
- package/src/client/connect/refunds.test.ts +72 -0
- package/src/client/connect/refunds.ts +8 -22
- package/src/client/index.ts +16 -12
- package/src/client/invoiceReads.ts +45 -0
- package/src/client/refund-context-shapes.test.ts +127 -0
- package/src/client/refund-context.test.ts +404 -0
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
# Buyer Checkout-session provider pages
|
|
2
|
+
|
|
3
|
+
`BetterStripe.getCheckoutSessionPageFromStripe` discovers one bounded page of
|
|
4
|
+
actual provider Checkout sessions for a V2 buyer account. It complements invoice
|
|
5
|
+
pages: an open or asynchronous Checkout can exist before any invoice exists.
|
|
6
|
+
This reader performs no provider write, component synchronization, commission
|
|
7
|
+
award or settlement operation.
|
|
8
|
+
|
|
9
|
+
```ts
|
|
10
|
+
import type {
|
|
11
|
+
CheckoutSessionPageOptions,
|
|
12
|
+
ProviderCheckoutSessionPage,
|
|
13
|
+
} from "@fantastic.dev/better-stripe";
|
|
14
|
+
|
|
15
|
+
// Obtain the personal buyer account from authenticated host-owned mapping.
|
|
16
|
+
const options: CheckoutSessionPageOptions = {
|
|
17
|
+
customerAccount: authorizedBuyerAccount,
|
|
18
|
+
limit: 25,
|
|
19
|
+
cursor: previousPage?.continueCursor,
|
|
20
|
+
};
|
|
21
|
+
const result: ProviderCheckoutSessionPage =
|
|
22
|
+
await stripe.getCheckoutSessionPageFromStripe(ctx, options);
|
|
23
|
+
```
|
|
24
|
+
|
|
25
|
+
The server-only Vite reference is
|
|
26
|
+
`example/convex/billing/checkoutHistory.ts`. Its buyer identity must come from
|
|
27
|
+
host authentication. The demonstration's browser personas are not production
|
|
28
|
+
authorization. It obtains the personal account from the component, rejects
|
|
29
|
+
missing, foreign or organization mappings, and overrides any browser-supplied
|
|
30
|
+
account selector. Existing React `Checkout` workflows remain responsible for
|
|
31
|
+
checkout presentation; hosts such as Dojo retain their own styles and routing.
|
|
32
|
+
|
|
33
|
+
## Selectors and results
|
|
34
|
+
|
|
35
|
+
- `customerAccount` must be a V2 `acct_…` identifier. Legacy customer selectors
|
|
36
|
+
and arbitrary provider parameters are rejected.
|
|
37
|
+
- Optional `status` is `open`, `complete` or `expired`. Omit it when discovering
|
|
38
|
+
all lifecycle states. Paid-only invoice discovery cannot find unresolved
|
|
39
|
+
Checkouts with no invoice.
|
|
40
|
+
- Optional `created.gte` and `created.lte` are inclusive integer Unix seconds.
|
|
41
|
+
An empty range object is normalized away. Creation time is not payment time;
|
|
42
|
+
an older session can complete or become paid during a later membership episode.
|
|
43
|
+
- `limit` defaults to 25 and must be an integer from 1 to 100. It may change
|
|
44
|
+
between pages. `cursor` is opaque and bound to buyer, status and creation range.
|
|
45
|
+
It is a continuation selector, not a signed authorization token.
|
|
46
|
+
- Results contain `page`, `hasMore` and `continueCursor`. Raw lifecycle values,
|
|
47
|
+
metadata, original currency/amount units and expanded subscription/payment
|
|
48
|
+
references are preserved. A complete session, payment reference or amount is
|
|
49
|
+
not independently proof of payment, refundable proceeds or affiliate credit.
|
|
50
|
+
|
|
51
|
+
The reader validates buyer/resource identity and selected status/time filters.
|
|
52
|
+
It rejects oversized pages, duplicate IDs within a page, a repeated immediately
|
|
53
|
+
preceding continuation ID, and empty nonterminal pages. Provider failures
|
|
54
|
+
propagate instead of becoming empty successful history.
|
|
55
|
+
|
|
56
|
+
## Host reconciliation
|
|
57
|
+
|
|
58
|
+
These are mutable provider pages, not an atomic snapshot or a complete-history
|
|
59
|
+
attestation. A stateless cursor cannot remember every earlier page. Hosts must
|
|
60
|
+
retain bounded durable checkpoints and seen IDs, detect cross-page overlap,
|
|
61
|
+
cycles and reordered/new records, and revalidate canonical buyer, community,
|
|
62
|
+
episode and registered request lineage before making a business decision.
|
|
63
|
+
|
|
64
|
+
An exhausted page alone does not prove absence. Missing/unregistered provenance,
|
|
65
|
+
unmapped references, incomplete scans, truncated related-resource previews,
|
|
66
|
+
unsupported lifecycle states and unresolved asynchronous attempts remain
|
|
67
|
+
unknown. Provider retention does not prove historical absence. Reconcile
|
|
68
|
+
actual supported session, subscription and invoice reads with immutable trusted
|
|
69
|
+
paid facts. Guard provider-read/database races and same-second ordering; do not
|
|
70
|
+
replace historical payment time with event arrival or deployment dates. This
|
|
71
|
+
reader does not fill referral locks or change already settled awards.
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
# Invoice payment references
|
|
2
|
+
|
|
3
|
+
`getInvoicePaymentPageFromStripe` enumerates a known subscription invoice's provider payment records. The host supplies the authorized invoice ID, canonical V2 customer account and expected Stripe subscription ID. BetterStripe retrieves the invoice and verifies all three bindings before requesting any invoice payments, including on continuation pages.
|
|
4
|
+
|
|
5
|
+
The method returns bounded pages with `hasMore` and a scope-bound `continueCursor`. Stripe's embedded invoice `payments` property contains only a preview. The reader uses the dedicated [invoice payment list endpoint](https://docs.stripe.com/api/invoice-payment/list) instead. A nonterminal empty or nonadvancing provider response fails rather than inventing a cursor or claiming completion. A terminal empty page is valid. Provider failures propagate.
|
|
6
|
+
|
|
7
|
+
Unsafe, fractional or negative provider amounts and malformed currency identifiers fail rather than returning rounded money evidence. No unit conversion or summation runs in the reader.
|
|
8
|
+
|
|
9
|
+
Each row retains the provider invoice-payment record's exact currency, requested amount, allocated paid amount and actual status. A canonical PaymentIntent reference has `referenceStatus: "payment_intent"`. Missing or malformed PaymentIntent references are `"unavailable"`; charge-only, payment-record and future payment types are `"unsupported"`. Those rows remain in the page. No records are silently filtered to make a page look complete.
|
|
10
|
+
|
|
11
|
+
This is a reference reader, not an authorization or refund-eligibility decision. The host must derive its enabled authenticated actor and community permissions, verify original merchant routing against BetterStripe's payment records, and project safe fields before returning data to browsers. A payment reference does not authorize an affiliate or collaborator to refund the merchant's sale. Ownership transfer does not establish historical merchant authority.
|
|
12
|
+
|
|
13
|
+
Invoice payment `amount_paid` is the amount credited to this invoice. It may be less than the underlying PaymentIntent's received amount if the PaymentIntent pays multiple invoices. It is not the underlying payment's remaining refundable amount. The host must verify that issuing a refund cannot reach money outside the authorized sale, and revalidate eligibility at refund creation. Do not add unlike currencies or treat synchronized refund balances as provider-live balances.
|
|
14
|
+
|
|
15
|
+
Pending/open and canceled invoice payments, including null or zero paid amounts, retain their actual provider state. Ending enumeration only exhausts that current invoice-payment scope. It does not prove settlement, a complete customer history, an immutable snapshot, a business-history verdict or entitlement cancellation. Provider records can change between requests. Cursor scope binding detects accidental selector changes; the cursor is not an authorization credential.
|
|
16
|
+
|
|
17
|
+
The method performs no provider writes or local financial mutations. It does not create refunds, reverse transfers, update access or cancel subscriptions. Ordinary refund financial reversals and actor validation remain in the existing refund APIs.
|
|
18
|
+
|
|
19
|
+
```ts
|
|
20
|
+
import {
|
|
21
|
+
BetterStripe,
|
|
22
|
+
type InvoicePaymentPageOptions,
|
|
23
|
+
} from "@fantastic.dev/better-stripe";
|
|
24
|
+
|
|
25
|
+
// Derive these selectors from an authorized server-owned subscription/invoice.
|
|
26
|
+
const options: InvoicePaymentPageOptions = {
|
|
27
|
+
stripeInvoiceId,
|
|
28
|
+
customerAccount,
|
|
29
|
+
stripeSubscriptionId,
|
|
30
|
+
limit: 25,
|
|
31
|
+
};
|
|
32
|
+
const result = await stripe.getInvoicePaymentPageFromStripe(ctx, options);
|
|
33
|
+
// result.scope retains the verified invoice, buyer and subscription selectors.
|
|
34
|
+
// Continue with result.continueCursor and the same authorized selectors.
|
|
35
|
+
```
|
|
36
|
+
|
|
37
|
+
Public exports include `InvoicePaymentPageOptions` and
|
|
38
|
+
`ProviderInvoicePaymentPage`. The Vite server-only binding is
|
|
39
|
+
`example/convex/billing/invoicePayments.ts`; the presentation reference is
|
|
40
|
+
`example/src/components/invoice-payment-selector.tsx`. Project only the fields
|
|
41
|
+
needed by that UI after host authorization, rather than returning raw provider
|
|
42
|
+
objects to a browser. Source merge requires a verified published artifact and
|
|
43
|
+
explicit Dojo adoption before its refund workflow can consume this API.
|
package/docs/read-contracts.md
CHANGED
|
@@ -278,3 +278,47 @@ The Vite server-only reference `example/convex/billing/invoiceHistory.ts` derive
|
|
|
278
278
|
V2 account from a retained personal buyer mapping after its caller authorizes
|
|
279
279
|
the buyer. It accepts no account selector from the caller. Production hosts need
|
|
280
280
|
real session authorization; selecting a demo persona does not provide it.
|
|
281
|
+
|
|
282
|
+
## Provider invoice payment references
|
|
283
|
+
|
|
284
|
+
`getInvoicePaymentPageFromStripe(ctx, { stripeInvoiceId, customerAccount,
|
|
285
|
+
stripeSubscriptionId, limit, cursor })` verifies the known invoice's canonical
|
|
286
|
+
V2 buyer and subscription on every request, then enumerates the dedicated
|
|
287
|
+
invoice-payments endpoint. Its bounded `{ scope, page, hasMore, continueCursor }`
|
|
288
|
+
result preserves original provider rows and canonical PaymentIntent references;
|
|
289
|
+
unsupported or unavailable references remain visible. Embedded invoice payment
|
|
290
|
+
previews are not complete lists. See [invoice payment references](./invoice-payment-pages.md)
|
|
291
|
+
for the public contract, pagination failures and host obligations.
|
|
292
|
+
|
|
293
|
+
Invoice allocations are not the PaymentIntent's remaining refundable balance.
|
|
294
|
+
The host authorizes the actual session, verifies original merchant and sale scope,
|
|
295
|
+
and revalidates creation-time eligibility through the existing refund APIs. This
|
|
296
|
+
reader writes no financial records and changes no access or subscription state.
|
|
297
|
+
|
|
298
|
+
## Provider Checkout-session pages
|
|
299
|
+
|
|
300
|
+
`getCheckoutSessionPageFromStripe(ctx, { customerAccount, status?, created?,
|
|
301
|
+
limit?, cursor? })` discovers actual V2 buyer Checkout sessions, including open
|
|
302
|
+
or asynchronous sessions that have no invoice yet. It preserves raw lifecycle,
|
|
303
|
+
metadata and payment/subscription references and performs no synchronization or
|
|
304
|
+
financial write. The server-only Vite adapter derives its account from the
|
|
305
|
+
host-authorized personal buyer mapping.
|
|
306
|
+
|
|
307
|
+
See [Checkout-session discovery](./checkout-session-pages.md) for public types,
|
|
308
|
+
scope-bound continuation, response validation and host obligations. Within-page
|
|
309
|
+
duplicates and immediately repeated continuation IDs reject; cross-page overlap
|
|
310
|
+
requires host checkpoints and seen-ID reconciliation. Neither an exhausted page
|
|
311
|
+
nor a complete Checkout status proves historical absence or payment. Unknown
|
|
312
|
+
provenance, mutable provider states and provider-read/database races remain host
|
|
313
|
+
responsibilities before any referral qualification or award.
|
|
314
|
+
|
|
315
|
+
## Refund context
|
|
316
|
+
|
|
317
|
+
`getRefundContext(ctx, { stripePaymentIntentId, actor, maxRefundPages?,
|
|
318
|
+
stripeAccountId? })` observes the authorized original captured charge and complete
|
|
319
|
+
bounded refund history. It returns a ready original-currency remainder or an
|
|
320
|
+
explicit unavailable reason, and propagates provider failures. Required actors,
|
|
321
|
+
partial-capture units, history budgets and creation-time host obligations are
|
|
322
|
+
specified in [refund context](./refund-context.md). Invoice allocations and
|
|
323
|
+
authorized gross amounts are not remaining refundable principal. No access,
|
|
324
|
+
subscription or financial state is changed by this reader.
|
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
# Refund context observation
|
|
2
|
+
|
|
3
|
+
`BetterStripe.getRefundContext(ctx, options)` reads one original PaymentIntent,
|
|
4
|
+
its captured charge and a bounded refund history after actor authorization. It
|
|
5
|
+
performs no provider write, component synchronization, transfer reversal or
|
|
6
|
+
access/subscription change. It complements the existing public React `Refunds`
|
|
7
|
+
review workflow; no additional renderer is required.
|
|
8
|
+
|
|
9
|
+
```ts
|
|
10
|
+
const context = await stripe.getRefundContext(ctx, {
|
|
11
|
+
stripePaymentIntentId: originalPayment.stripePaymentIntentId,
|
|
12
|
+
actor: { type: "seller", accountId: originalMerchantAccount },
|
|
13
|
+
maxRefundPages: 5,
|
|
14
|
+
});
|
|
15
|
+
if (context.status === "ready") {
|
|
16
|
+
// Original currency minor units; revalidate before creating the refund.
|
|
17
|
+
const remaining = context.remainingRefundableAmount;
|
|
18
|
+
}
|
|
19
|
+
```
|
|
20
|
+
|
|
21
|
+
## Authority and original scope
|
|
22
|
+
|
|
23
|
+
The required `actor` is either `{ type: "seller", accountId }` or
|
|
24
|
+
`{ type: "admin" }`. Runtime validation rejects missing or malformed actors and
|
|
25
|
+
noncanonical `pi_`/`acct_` selectors before component or provider reads. Sellers
|
|
26
|
+
must own the original destination or `store` split leg; affiliate and collaborator
|
|
27
|
+
legs do not confer refund authority. Admin authority must be established by the
|
|
28
|
+
host. The legacy optional actor on `createRefund` is not inherited by this reader.
|
|
29
|
+
|
|
30
|
+
The original synchronized payment must exist. Its V2 buyer account is correlated
|
|
31
|
+
with the live PaymentIntent; the original currency, PaymentIntent, latest charge
|
|
32
|
+
and charge's PaymentIntent reference must agree. Nullable legacy customer
|
|
33
|
+
references must also be canonical and agree; they do not replace the V2 buyer.
|
|
34
|
+
Malformed provider objects or contradictory lifecycle flags cannot produce a
|
|
35
|
+
ready result. A disputed, uncaptured or zero-captured charge is unavailable.
|
|
36
|
+
|
|
37
|
+
`stripeAccountId`, when supplied, is a **server-owned provider request scope**,
|
|
38
|
+
not the buyer account or merchant identity. Derive it from the original payment's
|
|
39
|
+
known charge context. Never accept it or the actor from browser input. The Vite
|
|
40
|
+
server-only `example/convex/connect/refundContext.ts` reference intentionally
|
|
41
|
+
supports platform charges only, derives the personal seller mapping and verifies
|
|
42
|
+
original merchant ownership. Demo personas still require real authentication in
|
|
43
|
+
a production host; the helper registers no public endpoint.
|
|
44
|
+
|
|
45
|
+
## Result and units
|
|
46
|
+
|
|
47
|
+
Public types are `RefundContextOptions`, `RefundContext` and
|
|
48
|
+
`RefundContextUnavailableReason`. A ready result contains `stripePaymentIntentId`,
|
|
49
|
+
`stripeChargeId`, `customerAccount`, `currency`, `capturedAmount`, `refundedAmount`,
|
|
50
|
+
`remainingRefundableAmount` and `observedAt` (milliseconds).
|
|
51
|
+
|
|
52
|
+
Amounts remain safe integer minor units in the original currency; no conversion
|
|
53
|
+
or fixed two-decimal assumption is applied. `capturedAmount` comes from
|
|
54
|
+
`charge.amount_captured`, checked against `paymentIntent.amount_received`.
|
|
55
|
+
Authorized `paymentIntent.amount`, `charge.amount` and synchronized payment
|
|
56
|
+
amount can exceed a partial capture and are not refund limits. `refundedAmount`
|
|
57
|
+
is the complete succeeded-refund total, reconciled with `charge.amount_refunded`.
|
|
58
|
+
The full-refund flag must agree in both directions with whether that total equals
|
|
59
|
+
captured principal. The remaining amount is captured principal minus that total. Dispute principal,
|
|
60
|
+
processing fees, balance transactions and invoice allocations are not subtracted
|
|
61
|
+
or substituted into this calculation.
|
|
62
|
+
|
|
63
|
+
An unavailable result has only `{ status: "unavailable", reason }`, with no
|
|
64
|
+
invented zero balance. Provider failures reject with their original identity so
|
|
65
|
+
callers can retry rather than present a completed observation.
|
|
66
|
+
|
|
67
|
+
## Bounded completeness and host obligations
|
|
68
|
+
|
|
69
|
+
Each refund page is requested explicitly with limit 100. `maxRefundPages` defaults
|
|
70
|
+
to 5 and accepts integers 1–10. Every observed row must have a canonical refund
|
|
71
|
+
identity, matching charge, PaymentIntent and currency, and a known lifecycle.
|
|
72
|
+
Pending or requires-action refunds block ready; failed/canceled refunds do not
|
|
73
|
+
count as returned principal. Unknown states, malformed or oversized envelopes,
|
|
74
|
+
duplicate IDs anywhere in the bounded traversal, exhausted nonterminal pages,
|
|
75
|
+
unsafe amounts and counter disagreements return unavailable.
|
|
76
|
+
|
|
77
|
+
`observedAt` is an observation, not a reservation or immutable snapshot. Hosts
|
|
78
|
+
must authenticate the actual session, authorize tenant/community and original
|
|
79
|
+
merchant scope, and revalidate immediately before `createRefund`. Invoice
|
|
80
|
+
`amount_paid` is allocated principal for that invoice, not the whole
|
|
81
|
+
PaymentIntent's refund authority. Deny ambiguous cross-invoice/community scopes
|
|
82
|
+
until a safe original-payment binding is established. A ready zero remainder
|
|
83
|
+
must not enable another refund. This reader does not grant authority to remove
|
|
84
|
+
access, cancel a subscription or change the original financial recipients.
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@fantastic.dev/better-stripe",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.33.0",
|
|
4
4
|
"description": "A Convex component for Stripe V2 Accounts API integration.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"stripe",
|
|
@@ -64,7 +64,10 @@
|
|
|
64
64
|
"docs/react-workflows-audit.md",
|
|
65
65
|
"CHANGELOG.md",
|
|
66
66
|
"MIGRATION.md",
|
|
67
|
-
"docs/read-contracts.md"
|
|
67
|
+
"docs/read-contracts.md",
|
|
68
|
+
"docs/invoice-payment-pages.md",
|
|
69
|
+
"docs/checkout-session-pages.md",
|
|
70
|
+
"docs/refund-context.md"
|
|
68
71
|
],
|
|
69
72
|
"scripts": {
|
|
70
73
|
"build": "tsc --project ./tsconfig.build.json",
|
|
@@ -0,0 +1,251 @@
|
|
|
1
|
+
import { afterEach, expect, it, vi } from "vitest";
|
|
2
|
+
import { BetterStripe } from "../index.js";
|
|
3
|
+
import { getStripeClient } from "../helpers.js";
|
|
4
|
+
|
|
5
|
+
afterEach(() => vi.restoreAllMocks());
|
|
6
|
+
|
|
7
|
+
function fixture() {
|
|
8
|
+
const key = `sk_test_checkout_page_${crypto.randomUUID()}`;
|
|
9
|
+
const client = new BetterStripe({} as never, { STRIPE_SECRET_KEY: key });
|
|
10
|
+
const list = vi.spyOn(getStripeClient(key).checkout.sessions, "list");
|
|
11
|
+
const ctx = { runQuery: vi.fn(), runMutation: vi.fn() };
|
|
12
|
+
const session = (id: string, customerAccount = "acct_buyer") => ({
|
|
13
|
+
id,
|
|
14
|
+
object: "checkout.session",
|
|
15
|
+
customer_account: customerAccount,
|
|
16
|
+
customer: null,
|
|
17
|
+
status: "open",
|
|
18
|
+
payment_status: "unpaid",
|
|
19
|
+
mode: "subscription",
|
|
20
|
+
created: 100,
|
|
21
|
+
metadata: { dojoPurchaseIntentId: "intent_original" },
|
|
22
|
+
subscription: null,
|
|
23
|
+
payment_intent: null,
|
|
24
|
+
});
|
|
25
|
+
return {
|
|
26
|
+
client,
|
|
27
|
+
list,
|
|
28
|
+
ctx,
|
|
29
|
+
session,
|
|
30
|
+
opts: { customerAccount: "acct_buyer" },
|
|
31
|
+
};
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
it("reads a bounded public V2 buyer Checkout page without syncing or claiming completeness", async () => {
|
|
35
|
+
const f = fixture();
|
|
36
|
+
const row = f.session("cs_test_original");
|
|
37
|
+
f.list.mockResolvedValue({ data: [row], has_more: false } as never);
|
|
38
|
+
expect(f.client.getCheckoutSessionPageFromStripe).toEqual(
|
|
39
|
+
expect.any(Function),
|
|
40
|
+
);
|
|
41
|
+
const result = await f.client.getCheckoutSessionPageFromStripe(f.ctx, f.opts);
|
|
42
|
+
expect(f.list).toHaveBeenCalledExactlyOnceWith({
|
|
43
|
+
customer_account: "acct_buyer",
|
|
44
|
+
limit: 25,
|
|
45
|
+
});
|
|
46
|
+
expect(result).toEqual({ page: [row], hasMore: false, continueCursor: null });
|
|
47
|
+
expect(result.page[0]).toBe(row);
|
|
48
|
+
expect(f.ctx.runQuery).not.toHaveBeenCalled();
|
|
49
|
+
expect(f.ctx.runMutation).not.toHaveBeenCalled();
|
|
50
|
+
});
|
|
51
|
+
|
|
52
|
+
it("resumes with canonical filters while allowing a different bounded page size", async () => {
|
|
53
|
+
const f = fixture();
|
|
54
|
+
f.list
|
|
55
|
+
.mockResolvedValueOnce({
|
|
56
|
+
data: [f.session("cs_newer")],
|
|
57
|
+
has_more: true,
|
|
58
|
+
} as never)
|
|
59
|
+
.mockResolvedValueOnce({
|
|
60
|
+
data: [f.session("cs_older")],
|
|
61
|
+
has_more: false,
|
|
62
|
+
} as never);
|
|
63
|
+
const first = await f.client.getCheckoutSessionPageFromStripe(f.ctx, {
|
|
64
|
+
...f.opts,
|
|
65
|
+
status: "open",
|
|
66
|
+
created: { lte: 200, gte: 0 },
|
|
67
|
+
limit: 1,
|
|
68
|
+
});
|
|
69
|
+
expect(first.continueCursor).toEqual(expect.any(String));
|
|
70
|
+
const next = await f.client.getCheckoutSessionPageFromStripe(f.ctx, {
|
|
71
|
+
...f.opts,
|
|
72
|
+
status: "open",
|
|
73
|
+
created: { gte: 0, lte: 200 },
|
|
74
|
+
limit: 2,
|
|
75
|
+
cursor: first.continueCursor,
|
|
76
|
+
});
|
|
77
|
+
expect(f.list).toHaveBeenLastCalledWith({
|
|
78
|
+
customer_account: "acct_buyer",
|
|
79
|
+
status: "open",
|
|
80
|
+
created: { gte: 0, lte: 200 },
|
|
81
|
+
limit: 2,
|
|
82
|
+
starting_after: "cs_newer",
|
|
83
|
+
});
|
|
84
|
+
expect(next).toEqual({
|
|
85
|
+
page: [f.session("cs_older")],
|
|
86
|
+
hasMore: false,
|
|
87
|
+
continueCursor: null,
|
|
88
|
+
});
|
|
89
|
+
});
|
|
90
|
+
|
|
91
|
+
it.each([
|
|
92
|
+
{ customerAccount: "acct_foreign" },
|
|
93
|
+
{ status: "expired" as const },
|
|
94
|
+
{ created: { lte: 201 } },
|
|
95
|
+
{ created: undefined },
|
|
96
|
+
])(
|
|
97
|
+
"rejects continuation filter mutation before provider I/O %#",
|
|
98
|
+
async (change) => {
|
|
99
|
+
const f = fixture();
|
|
100
|
+
f.list.mockResolvedValue({
|
|
101
|
+
data: [f.session("cs_original")],
|
|
102
|
+
has_more: true,
|
|
103
|
+
} as never);
|
|
104
|
+
const opts = { ...f.opts, status: "open" as const, created: { lte: 200 } };
|
|
105
|
+
const first = await f.client.getCheckoutSessionPageFromStripe(f.ctx, opts);
|
|
106
|
+
f.list.mockClear();
|
|
107
|
+
await expect(
|
|
108
|
+
f.client.getCheckoutSessionPageFromStripe(f.ctx, {
|
|
109
|
+
...opts,
|
|
110
|
+
...change,
|
|
111
|
+
cursor: first.continueCursor,
|
|
112
|
+
}),
|
|
113
|
+
).rejects.toThrow(/cursor|scope/i);
|
|
114
|
+
expect(f.list).not.toHaveBeenCalled();
|
|
115
|
+
},
|
|
116
|
+
);
|
|
117
|
+
|
|
118
|
+
it.each([
|
|
119
|
+
{ customerAccount: "cus_legacy" },
|
|
120
|
+
{ customerAccount: "acct_" },
|
|
121
|
+
{ limit: 0 },
|
|
122
|
+
{ limit: 101 },
|
|
123
|
+
{ limit: 1.5 },
|
|
124
|
+
{ status: "paid" },
|
|
125
|
+
{ created: { gte: 2, lte: 1 } },
|
|
126
|
+
{ created: { gte: -1 } },
|
|
127
|
+
{ customer: "cus_legacy" },
|
|
128
|
+
{ cursor: "" },
|
|
129
|
+
{ cursor: "not a cursor" },
|
|
130
|
+
])(
|
|
131
|
+
"rejects invalid public selectors before provider I/O %#",
|
|
132
|
+
async (change) => {
|
|
133
|
+
const f = fixture();
|
|
134
|
+
await expect(
|
|
135
|
+
f.client.getCheckoutSessionPageFromStripe(f.ctx, {
|
|
136
|
+
...f.opts,
|
|
137
|
+
...change,
|
|
138
|
+
} as never),
|
|
139
|
+
).rejects.toThrow();
|
|
140
|
+
expect(f.list).not.toHaveBeenCalled();
|
|
141
|
+
},
|
|
142
|
+
);
|
|
143
|
+
|
|
144
|
+
it.each([
|
|
145
|
+
{ customer_account: "acct_foreign" },
|
|
146
|
+
{ customer_account: undefined },
|
|
147
|
+
{ customer: "cus_legacy" },
|
|
148
|
+
{ id: "in_wrong_resource" },
|
|
149
|
+
{ object: "invoice" },
|
|
150
|
+
{ created: -1 },
|
|
151
|
+
])("rejects invalid provider buyer/resource identity %#", async (change) => {
|
|
152
|
+
const f = fixture();
|
|
153
|
+
f.list.mockResolvedValue({
|
|
154
|
+
data: [{ ...f.session("cs_original"), ...change }],
|
|
155
|
+
has_more: false,
|
|
156
|
+
} as never);
|
|
157
|
+
await expect(
|
|
158
|
+
f.client.getCheckoutSessionPageFromStripe(f.ctx, f.opts),
|
|
159
|
+
).rejects.toThrow(/scope|identity/i);
|
|
160
|
+
});
|
|
161
|
+
|
|
162
|
+
it.each([{ status: "expired" }, { created: 99 }, { created: 201 }])(
|
|
163
|
+
"rejects a provider response outside the selected filters %#",
|
|
164
|
+
async (change) => {
|
|
165
|
+
const f = fixture();
|
|
166
|
+
f.list.mockResolvedValue({
|
|
167
|
+
data: [{ ...f.session("cs_original"), ...change }],
|
|
168
|
+
has_more: false,
|
|
169
|
+
} as never);
|
|
170
|
+
await expect(
|
|
171
|
+
f.client.getCheckoutSessionPageFromStripe(f.ctx, {
|
|
172
|
+
...f.opts,
|
|
173
|
+
status: "open",
|
|
174
|
+
created: { gte: 100, lte: 200 },
|
|
175
|
+
}),
|
|
176
|
+
).rejects.toThrow(/scope|identity/i);
|
|
177
|
+
},
|
|
178
|
+
);
|
|
179
|
+
|
|
180
|
+
it("preserves unknown lifecycle and raw expanded references without treating them as payment proof", async () => {
|
|
181
|
+
const f = fixture();
|
|
182
|
+
const row = {
|
|
183
|
+
...f.session("cs_async"),
|
|
184
|
+
status: "future_provider_state",
|
|
185
|
+
payment_status: "unpaid",
|
|
186
|
+
currency: "kwd",
|
|
187
|
+
amount_total: 1234,
|
|
188
|
+
subscription: { id: "sub_original", status: "incomplete" },
|
|
189
|
+
payment_intent: { id: "pi_original", status: "processing" },
|
|
190
|
+
invoice: null,
|
|
191
|
+
metadata: { communityId: "community_original" },
|
|
192
|
+
};
|
|
193
|
+
f.list.mockResolvedValue({ data: [row], has_more: false } as never);
|
|
194
|
+
const result = await f.client.getCheckoutSessionPageFromStripe(f.ctx, f.opts);
|
|
195
|
+
expect(result.page[0]).toBe(row);
|
|
196
|
+
expect(result).not.toHaveProperty("completeHistory");
|
|
197
|
+
});
|
|
198
|
+
|
|
199
|
+
it("rejects oversized, duplicate and nonadvancing provider pages", async () => {
|
|
200
|
+
const f = fixture();
|
|
201
|
+
const row = f.session("cs_original");
|
|
202
|
+
f.list.mockResolvedValueOnce({
|
|
203
|
+
data: [row, f.session("cs_second")],
|
|
204
|
+
has_more: false,
|
|
205
|
+
} as never);
|
|
206
|
+
await expect(
|
|
207
|
+
f.client.getCheckoutSessionPageFromStripe(f.ctx, { ...f.opts, limit: 1 }),
|
|
208
|
+
).rejects.toThrow(/page/i);
|
|
209
|
+
f.list.mockResolvedValueOnce({ data: [row, row], has_more: false } as never);
|
|
210
|
+
await expect(
|
|
211
|
+
f.client.getCheckoutSessionPageFromStripe(f.ctx, f.opts),
|
|
212
|
+
).rejects.toThrow(/duplicate|page/i);
|
|
213
|
+
f.list.mockResolvedValueOnce({ data: [], has_more: true } as never);
|
|
214
|
+
await expect(
|
|
215
|
+
f.client.getCheckoutSessionPageFromStripe(f.ctx, f.opts),
|
|
216
|
+
).rejects.toThrow(/continuation/i);
|
|
217
|
+
f.list.mockResolvedValueOnce({ data: [row], has_more: true } as never);
|
|
218
|
+
const first = await f.client.getCheckoutSessionPageFromStripe(f.ctx, f.opts);
|
|
219
|
+
f.list.mockResolvedValueOnce({ data: [row], has_more: false } as never);
|
|
220
|
+
await expect(
|
|
221
|
+
f.client.getCheckoutSessionPageFromStripe(f.ctx, {
|
|
222
|
+
...f.opts,
|
|
223
|
+
cursor: first.continueCursor,
|
|
224
|
+
}),
|
|
225
|
+
).rejects.toThrow(/continuation/i);
|
|
226
|
+
});
|
|
227
|
+
|
|
228
|
+
it("normalizes an empty filter and returns an exhausted empty page", async () => {
|
|
229
|
+
const f = fixture();
|
|
230
|
+
f.list.mockResolvedValue({ data: [], has_more: false } as never);
|
|
231
|
+
await expect(
|
|
232
|
+
f.client.getCheckoutSessionPageFromStripe(f.ctx, {
|
|
233
|
+
...f.opts,
|
|
234
|
+
created: {},
|
|
235
|
+
cursor: null,
|
|
236
|
+
}),
|
|
237
|
+
).resolves.toEqual({ page: [], hasMore: false, continueCursor: null });
|
|
238
|
+
expect(f.list).toHaveBeenCalledExactlyOnceWith({
|
|
239
|
+
customer_account: "acct_buyer",
|
|
240
|
+
limit: 25,
|
|
241
|
+
});
|
|
242
|
+
});
|
|
243
|
+
|
|
244
|
+
it("propagates provider failure rather than turning it into empty history", async () => {
|
|
245
|
+
const f = fixture();
|
|
246
|
+
const failure = new Error("provider unavailable");
|
|
247
|
+
f.list.mockRejectedValue(failure);
|
|
248
|
+
await expect(
|
|
249
|
+
f.client.getCheckoutSessionPageFromStripe(f.ctx, f.opts),
|
|
250
|
+
).rejects.toBe(failure);
|
|
251
|
+
});
|
|
@@ -0,0 +1,135 @@
|
|
|
1
|
+
import type Stripe from "stripe";
|
|
2
|
+
import { z } from "zod";
|
|
3
|
+
|
|
4
|
+
const time = z.number().int().nonnegative().safe();
|
|
5
|
+
const scopeSchema = z
|
|
6
|
+
.object({
|
|
7
|
+
customerAccount: z
|
|
8
|
+
.string()
|
|
9
|
+
.max(128)
|
|
10
|
+
.regex(/^acct_[A-Za-z0-9_]+$/),
|
|
11
|
+
status: z.enum(["open", "complete", "expired"]).optional(),
|
|
12
|
+
created: z
|
|
13
|
+
.object({ gte: time.optional(), lte: time.optional() })
|
|
14
|
+
.strict()
|
|
15
|
+
.optional(),
|
|
16
|
+
})
|
|
17
|
+
.strict();
|
|
18
|
+
const optionsSchema = scopeSchema
|
|
19
|
+
.extend({
|
|
20
|
+
limit: z.number().int().min(1).max(100).default(25),
|
|
21
|
+
cursor: z.string().min(1).max(2048).nullable().optional(),
|
|
22
|
+
})
|
|
23
|
+
.strict();
|
|
24
|
+
const sessionId = z
|
|
25
|
+
.string()
|
|
26
|
+
.max(128)
|
|
27
|
+
.regex(/^cs_[A-Za-z0-9_]+$/);
|
|
28
|
+
const cursorSchema = z
|
|
29
|
+
.object({
|
|
30
|
+
version: z.literal(1),
|
|
31
|
+
scope: scopeSchema,
|
|
32
|
+
after: sessionId,
|
|
33
|
+
})
|
|
34
|
+
.strict();
|
|
35
|
+
const identitySchema = z
|
|
36
|
+
.object({
|
|
37
|
+
id: sessionId,
|
|
38
|
+
object: z.literal("checkout.session"),
|
|
39
|
+
customer_account: z.string(),
|
|
40
|
+
customer: z.null().optional(),
|
|
41
|
+
created: time,
|
|
42
|
+
})
|
|
43
|
+
.passthrough();
|
|
44
|
+
|
|
45
|
+
export type CheckoutSessionPageOptions = z.input<typeof optionsSchema>;
|
|
46
|
+
export type ProviderCheckoutSessionPage = {
|
|
47
|
+
page: Stripe.Checkout.Session[];
|
|
48
|
+
hasMore: boolean;
|
|
49
|
+
continueCursor: string | null;
|
|
50
|
+
};
|
|
51
|
+
|
|
52
|
+
function encodeCursor(scope: z.infer<typeof scopeSchema>, after: string) {
|
|
53
|
+
return btoa(JSON.stringify({ version: 1, scope, after }))
|
|
54
|
+
.replaceAll("+", "-")
|
|
55
|
+
.replaceAll("/", "_")
|
|
56
|
+
.replace(/=+$/, "");
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
function decodeCursor(cursor: string, scope: z.infer<typeof scopeSchema>) {
|
|
60
|
+
try {
|
|
61
|
+
if (!/^[A-Za-z0-9_-]+$/.test(cursor)) throw new Error();
|
|
62
|
+
const parsed = cursorSchema.parse(
|
|
63
|
+
JSON.parse(atob(cursor.replaceAll("-", "+").replaceAll("_", "/"))),
|
|
64
|
+
);
|
|
65
|
+
if (
|
|
66
|
+
JSON.stringify(parsed.scope) !== JSON.stringify(scope) ||
|
|
67
|
+
encodeCursor(parsed.scope, parsed.after) !== cursor
|
|
68
|
+
)
|
|
69
|
+
throw new Error();
|
|
70
|
+
return parsed.after;
|
|
71
|
+
} catch {
|
|
72
|
+
throw new Error("Invalid Checkout page cursor or scope");
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/** Provider discovery only. Hosts authorize buyers and reconcile mutable history and gaps. */
|
|
77
|
+
export async function getCheckoutSessionPageFromStripe(
|
|
78
|
+
stripe: Stripe,
|
|
79
|
+
input: CheckoutSessionPageOptions,
|
|
80
|
+
): Promise<ProviderCheckoutSessionPage> {
|
|
81
|
+
const { limit, cursor, ...scope } = optionsSchema.parse(input);
|
|
82
|
+
if (
|
|
83
|
+
scope.created?.gte !== undefined &&
|
|
84
|
+
scope.created.lte !== undefined &&
|
|
85
|
+
scope.created.gte > scope.created.lte
|
|
86
|
+
)
|
|
87
|
+
throw new Error("Invalid Checkout page time window");
|
|
88
|
+
if (
|
|
89
|
+
scope.created &&
|
|
90
|
+
scope.created.gte === undefined &&
|
|
91
|
+
scope.created.lte === undefined
|
|
92
|
+
)
|
|
93
|
+
delete scope.created;
|
|
94
|
+
const after = cursor ? decodeCursor(cursor, scope) : undefined;
|
|
95
|
+
const response = await stripe.checkout.sessions.list({
|
|
96
|
+
customer_account: scope.customerAccount,
|
|
97
|
+
limit,
|
|
98
|
+
...(scope.status ? { status: scope.status } : {}),
|
|
99
|
+
...(scope.created ? { created: scope.created } : {}),
|
|
100
|
+
...(after ? { starting_after: after } : {}),
|
|
101
|
+
});
|
|
102
|
+
if (
|
|
103
|
+
!Array.isArray(response.data) ||
|
|
104
|
+
typeof response.has_more !== "boolean" ||
|
|
105
|
+
response.data.length > limit
|
|
106
|
+
)
|
|
107
|
+
throw new Error("Invalid provider Checkout page");
|
|
108
|
+
const seen = new Set<string>();
|
|
109
|
+
for (const row of response.data) {
|
|
110
|
+
const parsed = identitySchema.safeParse(row);
|
|
111
|
+
if (
|
|
112
|
+
!parsed.success ||
|
|
113
|
+
parsed.data.customer_account !== scope.customerAccount ||
|
|
114
|
+
(scope.status !== undefined && row.status !== scope.status) ||
|
|
115
|
+
(scope.created?.gte !== undefined &&
|
|
116
|
+
parsed.data.created < scope.created.gte) ||
|
|
117
|
+
(scope.created?.lte !== undefined &&
|
|
118
|
+
parsed.data.created > scope.created.lte)
|
|
119
|
+
)
|
|
120
|
+
throw new Error("Invalid provider Checkout page buyer scope or identity");
|
|
121
|
+
if (seen.has(row.id))
|
|
122
|
+
throw new Error("Duplicate provider Checkout page entry");
|
|
123
|
+
if (row.id === after)
|
|
124
|
+
throw new Error("Provider Checkout page has no advancing continuation");
|
|
125
|
+
seen.add(row.id);
|
|
126
|
+
}
|
|
127
|
+
const last = response.data[response.data.length - 1]?.id;
|
|
128
|
+
if (response.has_more && !last)
|
|
129
|
+
throw new Error("Provider Checkout page has no advancing continuation");
|
|
130
|
+
return {
|
|
131
|
+
page: response.data,
|
|
132
|
+
hasMore: response.has_more,
|
|
133
|
+
continueCursor: response.has_more ? encodeCursor(scope, last!) : null,
|
|
134
|
+
};
|
|
135
|
+
}
|