@fantastic.dev/better-stripe 0.32.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.
Files changed (51) hide show
  1. package/CHANGELOG.md +7 -0
  2. package/README.md +7 -1
  3. package/dist/client/billing/checkoutPages.d.ts +26 -0
  4. package/dist/client/billing/checkoutPages.d.ts.map +1 -0
  5. package/dist/client/billing/checkoutPages.js +111 -0
  6. package/dist/client/billing/checkoutPages.js.map +1 -0
  7. package/dist/client/connect/refundContext.d.ts +6 -0
  8. package/dist/client/connect/refundContext.d.ts.map +1 -0
  9. package/dist/client/connect/refundContext.js +109 -0
  10. package/dist/client/connect/refundContext.js.map +1 -0
  11. package/dist/client/connect/refundContextHistory.d.ts +20 -0
  12. package/dist/client/connect/refundContextHistory.d.ts.map +1 -0
  13. package/dist/client/connect/refundContextHistory.js +55 -0
  14. package/dist/client/connect/refundContextHistory.js.map +1 -0
  15. package/dist/client/connect/refundContextTypes.d.ts +39 -0
  16. package/dist/client/connect/refundContextTypes.d.ts.map +1 -0
  17. package/dist/client/connect/refundContextTypes.js +15 -0
  18. package/dist/client/connect/refundContextTypes.js.map +1 -0
  19. package/dist/client/connect/refundTarget.d.ts +14 -0
  20. package/dist/client/connect/refundTarget.d.ts.map +1 -0
  21. package/dist/client/connect/refundTarget.js +17 -0
  22. package/dist/client/connect/refundTarget.js.map +1 -0
  23. package/dist/client/connect/refunds.d.ts +17 -1
  24. package/dist/client/connect/refunds.d.ts.map +1 -1
  25. package/dist/client/connect/refunds.js +7 -17
  26. package/dist/client/connect/refunds.js.map +1 -1
  27. package/dist/client/index.d.ts +2 -0
  28. package/dist/client/index.d.ts.map +1 -1
  29. package/dist/client/index.js.map +1 -1
  30. package/dist/client/invoiceReads.d.ts +7 -1
  31. package/dist/client/invoiceReads.d.ts.map +1 -1
  32. package/dist/client/invoiceReads.js +11 -1
  33. package/dist/client/invoiceReads.js.map +1 -1
  34. package/dist/component/payoutRelease/queries.d.ts +2 -2
  35. package/dist/component/payoutRelease/queries.d.ts.map +1 -1
  36. package/docs/checkout-session-pages.md +71 -0
  37. package/docs/read-contracts.md +28 -0
  38. package/docs/refund-context.md +84 -0
  39. package/package.json +4 -2
  40. package/src/client/billing/checkoutPages.test.ts +251 -0
  41. package/src/client/billing/checkoutPages.ts +135 -0
  42. package/src/client/connect/refundContext.ts +140 -0
  43. package/src/client/connect/refundContextHistory.ts +84 -0
  44. package/src/client/connect/refundContextTypes.ts +56 -0
  45. package/src/client/connect/refundTarget.ts +39 -0
  46. package/src/client/connect/refunds.test.ts +72 -0
  47. package/src/client/connect/refunds.ts +8 -22
  48. package/src/client/index.ts +9 -0
  49. package/src/client/invoiceReads.ts +17 -1
  50. package/src/client/refund-context-shapes.test.ts +127 -0
  51. package/src/client/refund-context.test.ts +404 -0
@@ -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
+ }
@@ -0,0 +1,140 @@
1
+ import type Stripe from "stripe";
2
+ import type { Component, RunCtx } from "../helpers.js";
3
+ import type { StripeComponentPayment } from "../types.js";
4
+ import { componentRef } from "../webhooks/helpers.js";
5
+ import { assertRefundAuthorized } from "./refunds.js";
6
+ import {
7
+ readRefundPayment,
8
+ readRefundCharge,
9
+ refundObjectId,
10
+ } from "./refundTarget.js";
11
+ import { readRefundHistory } from "./refundContextHistory.js";
12
+ import {
13
+ refundContextOptionsSchema,
14
+ type RefundContextOptions,
15
+ type RefundContext,
16
+ type RefundContextUnavailableReason,
17
+ } from "./refundContextTypes.js";
18
+
19
+ const unavailable = (
20
+ reason: RefundContextUnavailableReason,
21
+ ): RefundContext => ({ status: "unavailable", reason });
22
+ function amountsAgree(payment: Stripe.PaymentIntent, charge: Stripe.Charge) {
23
+ const amounts = [
24
+ payment.amount,
25
+ payment.amount_received,
26
+ charge.amount,
27
+ charge.amount_captured,
28
+ charge.amount_refunded,
29
+ ];
30
+ return (
31
+ amounts.every((n) => Number.isSafeInteger(n) && n >= 0) &&
32
+ charge.amount_captured === payment.amount_received &&
33
+ charge.amount_captured <= charge.amount &&
34
+ charge.amount_captured <= payment.amount &&
35
+ charge.amount_refunded <= charge.amount_captured
36
+ );
37
+ }
38
+
39
+ function canonicalCustomer(value: Stripe.PaymentIntent["customer"]) {
40
+ if (value === null) return true;
41
+ if (typeof value === "string") return /^cus_[A-Za-z0-9_]+$/.test(value);
42
+ return Boolean(
43
+ value &&
44
+ value.object === "customer" &&
45
+ typeof value.id === "string" &&
46
+ /^cus_[A-Za-z0-9_]+$/.test(value.id),
47
+ );
48
+ }
49
+
50
+ /** Observes one authorized original payment; hosts still own community scope and creation-time revalidation. */
51
+ export async function getRefundContext(
52
+ stripe: Stripe,
53
+ component: Component,
54
+ ctx: RunCtx,
55
+ input: RefundContextOptions,
56
+ ): Promise<RefundContext> {
57
+ const opts = refundContextOptionsSchema.parse(input);
58
+ const original =
59
+ (await assertRefundAuthorized(stripe, component, ctx, opts)) ??
60
+ ((await ctx.runQuery(
61
+ componentRef(component, "connect/queries/getPaymentByStripeId"),
62
+ { stripePaymentIntentId: opts.stripePaymentIntentId },
63
+ )) as StripeComponentPayment | null);
64
+ if (!original) return unavailable("payment_unavailable");
65
+ if (original.stripePaymentIntentId !== opts.stripePaymentIntentId)
66
+ return unavailable("payment_scope_mismatch");
67
+ const buyer = original.accountId;
68
+ if (!buyer || !/^acct_[A-Za-z0-9_]+$/.test(buyer))
69
+ return unavailable("buyer_unavailable");
70
+ const payment = await readRefundPayment(stripe, opts);
71
+ if (
72
+ !payment ||
73
+ payment.object !== "payment_intent" ||
74
+ payment.id !== opts.stripePaymentIntentId
75
+ )
76
+ return unavailable("payment_scope_mismatch");
77
+ if (!canonicalCustomer(payment.customer))
78
+ return unavailable("buyer_mismatch");
79
+ if (payment.customer_account !== buyer) return unavailable("buyer_mismatch");
80
+ if (payment.status !== "succeeded")
81
+ return unavailable("payment_not_succeeded");
82
+ if (
83
+ !/^[a-z]{3}$/.test(payment.currency) ||
84
+ payment.currency !== original.currency
85
+ )
86
+ return unavailable("currency_mismatch");
87
+ const chargeId = refundObjectId(payment.latest_charge);
88
+ if (!chargeId || !/^ch_[A-Za-z0-9_]+$/.test(chargeId))
89
+ return unavailable("charge_unavailable");
90
+ const charge = await readRefundCharge(stripe, opts, payment);
91
+ if (
92
+ !charge ||
93
+ charge.id !== chargeId ||
94
+ refundObjectId(charge.payment_intent) !== payment.id
95
+ )
96
+ return unavailable("charge_scope_mismatch");
97
+ if (
98
+ charge.object !== "charge" ||
99
+ charge.status !== "succeeded" ||
100
+ typeof charge.paid !== "boolean" ||
101
+ typeof charge.captured !== "boolean" ||
102
+ typeof charge.disputed !== "boolean" ||
103
+ typeof charge.refunded !== "boolean"
104
+ )
105
+ return unavailable("charge_scope_mismatch");
106
+ if (!canonicalCustomer(charge.customer)) return unavailable("buyer_mismatch");
107
+ if (refundObjectId(charge.customer) !== refundObjectId(payment.customer))
108
+ return unavailable("buyer_mismatch");
109
+ if (charge.currency !== payment.currency)
110
+ return unavailable("currency_mismatch");
111
+ if (!amountsAgree(payment, charge)) return unavailable("amount_unavailable");
112
+ if (!charge.paid || !charge.captured || charge.amount_captured === 0)
113
+ return unavailable("charge_not_captured");
114
+ if (charge.disputed) return unavailable("charge_disputed");
115
+ const history = await readRefundHistory(stripe, {
116
+ paymentIntentId: payment.id,
117
+ chargeId: charge.id,
118
+ currency: payment.currency,
119
+ capturedAmount: charge.amount_captured,
120
+ maxRefundPages: opts.maxRefundPages,
121
+ stripeAccountId: opts.stripeAccountId,
122
+ });
123
+ if (history.status !== "complete") return history;
124
+ if (
125
+ history.refundedAmount !== charge.amount_refunded ||
126
+ charge.refunded !== (history.refundedAmount === charge.amount_captured)
127
+ )
128
+ return unavailable("refund_counter_mismatch");
129
+ return {
130
+ status: "ready",
131
+ stripePaymentIntentId: payment.id,
132
+ stripeChargeId: charge.id,
133
+ customerAccount: buyer,
134
+ currency: payment.currency,
135
+ capturedAmount: charge.amount_captured,
136
+ refundedAmount: history.refundedAmount,
137
+ remainingRefundableAmount: charge.amount_captured - history.refundedAmount,
138
+ observedAt: Date.now(),
139
+ };
140
+ }
@@ -0,0 +1,84 @@
1
+ import type Stripe from "stripe";
2
+ import { refundObjectId } from "./refundTarget.js";
3
+ import type { RefundContextUnavailableReason } from "./refundContextTypes.js";
4
+
5
+ type HistoryResult =
6
+ | { status: "complete"; refundedAmount: number }
7
+ | { status: "unavailable"; reason: RefundContextUnavailableReason };
8
+ const unavailable = (
9
+ reason: RefundContextUnavailableReason,
10
+ ): HistoryResult => ({ status: "unavailable", reason });
11
+
12
+ /** All bounded pages must agree with the captured charge; loaded previews cannot establish a remainder. */
13
+ export async function readRefundHistory(
14
+ stripe: Stripe,
15
+ opts: {
16
+ paymentIntentId: string;
17
+ chargeId: string;
18
+ currency: string;
19
+ capturedAmount: number;
20
+ maxRefundPages: number;
21
+ stripeAccountId?: string;
22
+ },
23
+ ): Promise<HistoryResult> {
24
+ let refundedAmount = 0;
25
+ let cursor: string | undefined;
26
+ const seen = new Set<string>();
27
+ for (let count = 0; count < opts.maxRefundPages; count++) {
28
+ const page = await stripe.refunds.list(
29
+ {
30
+ payment_intent: opts.paymentIntentId,
31
+ limit: 100,
32
+ ...(cursor ? { starting_after: cursor } : {}),
33
+ },
34
+ opts.stripeAccountId
35
+ ? { stripeAccount: opts.stripeAccountId }
36
+ : undefined,
37
+ );
38
+ if (
39
+ !page ||
40
+ page.object !== "list" ||
41
+ !Array.isArray(page.data) ||
42
+ page.data.length > 100 ||
43
+ typeof page.has_more !== "boolean" ||
44
+ (page.has_more && !page.data.length)
45
+ )
46
+ return unavailable("refund_history_incomplete");
47
+ for (const refund of page.data) {
48
+ if (
49
+ !refund ||
50
+ refund.object !== "refund" ||
51
+ typeof refund.id !== "string" ||
52
+ !/^re_[A-Za-z0-9_]+$/.test(refund.id) ||
53
+ seen.has(refund.id)
54
+ )
55
+ return unavailable("refund_history_incomplete");
56
+ seen.add(refund.id);
57
+ if (
58
+ refundObjectId(refund.charge) !== opts.chargeId ||
59
+ refundObjectId(refund.payment_intent) !== opts.paymentIntentId ||
60
+ refund.currency !== opts.currency ||
61
+ !Number.isSafeInteger(refund.amount) ||
62
+ refund.amount < 0
63
+ )
64
+ return unavailable("refund_scope_mismatch");
65
+ if (refund.status === "pending" || refund.status === "requires_action")
66
+ return unavailable("refund_pending");
67
+ if (
68
+ refund.status !== "succeeded" &&
69
+ refund.status !== "failed" &&
70
+ refund.status !== "canceled"
71
+ )
72
+ return unavailable("refund_state_unknown");
73
+ if (refund.status === "succeeded") refundedAmount += refund.amount;
74
+ if (
75
+ !Number.isSafeInteger(refundedAmount) ||
76
+ refundedAmount > opts.capturedAmount
77
+ )
78
+ return unavailable("refund_counter_mismatch");
79
+ }
80
+ if (!page.has_more) return { status: "complete", refundedAmount };
81
+ cursor = page.data[page.data.length - 1]!.id;
82
+ }
83
+ return unavailable("refund_history_incomplete");
84
+ }
@@ -0,0 +1,56 @@
1
+ import { z } from "zod";
2
+ import type { RefundActor } from "./refundActor.js";
3
+
4
+ const accountId = z.string().regex(/^acct_[A-Za-z0-9_]+$/);
5
+ /** New observations require an explicit actor; legacy createRefund omission is not inherited. */
6
+ export const refundContextOptionsSchema = z
7
+ .object({
8
+ stripePaymentIntentId: z.string().regex(/^pi_[A-Za-z0-9_]+$/),
9
+ actor: z.discriminatedUnion("type", [
10
+ z.object({ type: z.literal("admin") }).strict(),
11
+ z.object({ type: z.literal("seller"), accountId }).strict(),
12
+ ]),
13
+ stripeAccountId: accountId.optional(),
14
+ maxRefundPages: z.number().int().min(1).max(10).default(5),
15
+ })
16
+ .strict();
17
+
18
+ export type RefundContextOptions = {
19
+ stripePaymentIntentId: string;
20
+ actor: RefundActor;
21
+ /** Server-owned provider request scope, distinct from the buyer and merchant accounts. */
22
+ stripeAccountId?: string;
23
+ /** Complete bounded history or unavailable, never a partial refund balance. Default 5, maximum 10. */
24
+ maxRefundPages?: number;
25
+ };
26
+ export type RefundContextUnavailableReason =
27
+ | "payment_unavailable"
28
+ | "buyer_unavailable"
29
+ | "payment_scope_mismatch"
30
+ | "payment_not_succeeded"
31
+ | "charge_unavailable"
32
+ | "charge_scope_mismatch"
33
+ | "buyer_mismatch"
34
+ | "currency_mismatch"
35
+ | "amount_unavailable"
36
+ | "charge_not_captured"
37
+ | "charge_disputed"
38
+ | "refund_pending"
39
+ | "refund_state_unknown"
40
+ | "refund_history_incomplete"
41
+ | "refund_scope_mismatch"
42
+ | "refund_counter_mismatch";
43
+ export type RefundContext =
44
+ | { status: "unavailable"; reason: RefundContextUnavailableReason }
45
+ | {
46
+ status: "ready";
47
+ stripePaymentIntentId: string;
48
+ stripeChargeId: string;
49
+ customerAccount: string;
50
+ currency: string;
51
+ capturedAmount: number;
52
+ refundedAmount: number;
53
+ remainingRefundableAmount: number;
54
+ /** Milliseconds; an observation, not a reservation or immutable snapshot. */
55
+ observedAt: number;
56
+ };