@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.
Files changed (57) hide show
  1. package/CHANGELOG.md +13 -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/billing/invoicePaymentPages.d.ts +28 -0
  8. package/dist/client/billing/invoicePaymentPages.d.ts.map +1 -0
  9. package/dist/client/billing/invoicePaymentPages.js +124 -0
  10. package/dist/client/billing/invoicePaymentPages.js.map +1 -0
  11. package/dist/client/connect/refundContext.d.ts +6 -0
  12. package/dist/client/connect/refundContext.d.ts.map +1 -0
  13. package/dist/client/connect/refundContext.js +109 -0
  14. package/dist/client/connect/refundContext.js.map +1 -0
  15. package/dist/client/connect/refundContextHistory.d.ts +20 -0
  16. package/dist/client/connect/refundContextHistory.d.ts.map +1 -0
  17. package/dist/client/connect/refundContextHistory.js +55 -0
  18. package/dist/client/connect/refundContextHistory.js.map +1 -0
  19. package/dist/client/connect/refundContextTypes.d.ts +39 -0
  20. package/dist/client/connect/refundContextTypes.d.ts.map +1 -0
  21. package/dist/client/connect/refundContextTypes.js +15 -0
  22. package/dist/client/connect/refundContextTypes.js.map +1 -0
  23. package/dist/client/connect/refundTarget.d.ts +14 -0
  24. package/dist/client/connect/refundTarget.d.ts.map +1 -0
  25. package/dist/client/connect/refundTarget.js +17 -0
  26. package/dist/client/connect/refundTarget.js.map +1 -0
  27. package/dist/client/connect/refunds.d.ts +17 -1
  28. package/dist/client/connect/refunds.d.ts.map +1 -1
  29. package/dist/client/connect/refunds.js +7 -17
  30. package/dist/client/connect/refunds.js.map +1 -1
  31. package/dist/client/index.d.ts +6 -6
  32. package/dist/client/index.d.ts.map +1 -1
  33. package/dist/client/index.js +2 -7
  34. package/dist/client/index.js.map +1 -1
  35. package/dist/client/invoiceReads.d.ts +20 -0
  36. package/dist/client/invoiceReads.d.ts.map +1 -0
  37. package/dist/client/invoiceReads.js +25 -0
  38. package/dist/client/invoiceReads.js.map +1 -0
  39. package/docs/checkout-session-pages.md +71 -0
  40. package/docs/invoice-payment-pages.md +43 -0
  41. package/docs/read-contracts.md +44 -0
  42. package/docs/refund-context.md +84 -0
  43. package/package.json +5 -2
  44. package/src/client/billing/checkoutPages.test.ts +251 -0
  45. package/src/client/billing/checkoutPages.ts +135 -0
  46. package/src/client/billing/invoicePaymentPages.test.ts +354 -0
  47. package/src/client/billing/invoicePaymentPages.ts +165 -0
  48. package/src/client/connect/refundContext.ts +140 -0
  49. package/src/client/connect/refundContextHistory.ts +84 -0
  50. package/src/client/connect/refundContextTypes.ts +56 -0
  51. package/src/client/connect/refundTarget.ts +39 -0
  52. package/src/client/connect/refunds.test.ts +72 -0
  53. package/src/client/connect/refunds.ts +8 -22
  54. package/src/client/index.ts +16 -12
  55. package/src/client/invoiceReads.ts +45 -0
  56. package/src/client/refund-context-shapes.test.ts +127 -0
  57. package/src/client/refund-context.test.ts +404 -0
@@ -0,0 +1,354 @@
1
+ import { afterEach, expect, it, vi } from "vitest";
2
+
3
+ import { getStripeClient } from "../helpers.js";
4
+ import { BetterStripe } from "../index.js";
5
+
6
+ afterEach(() => vi.restoreAllMocks());
7
+ function fixture() {
8
+ const key = `sk_test_invoice_payments_${crypto.randomUUID()}`;
9
+ const stripe = getStripeClient(key);
10
+ const client = new BetterStripe({} as never, { STRIPE_SECRET_KEY: key });
11
+ const ctx = { runQuery: vi.fn() };
12
+ const invoice = {
13
+ id: "in_buyer",
14
+ customer_account: "acct_buyer",
15
+ currency: "jpy",
16
+ parent: {
17
+ type: "subscription_details",
18
+ subscription_details: { subscription: "sub_buyer" },
19
+ },
20
+ payments: { data: [{ id: "inpay_truncated" }], has_more: true },
21
+ };
22
+ const retrieve = vi
23
+ .spyOn(stripe.invoices, "retrieve")
24
+ .mockResolvedValue(invoice as never);
25
+ const list = vi.spyOn(stripe.invoicePayments, "list");
26
+ const payment = (
27
+ id = "inpay_first",
28
+ type = "payment_intent",
29
+ reference: string | null = "pi_paid",
30
+ ) => ({
31
+ id,
32
+ object: "invoice_payment",
33
+ invoice: "in_buyer",
34
+ amount_paid: 1234,
35
+ amount_requested: 1234,
36
+ currency: "jpy",
37
+ status: "paid",
38
+ payment: { type, ...(reference ? { [type]: reference } : {}) },
39
+ });
40
+ const opts = {
41
+ stripeInvoiceId: "in_buyer",
42
+ customerAccount: "acct_buyer",
43
+ stripeSubscriptionId: "sub_buyer",
44
+ };
45
+ return { stripe, client, ctx, invoice, retrieve, list, payment, opts };
46
+ }
47
+ it("verifies invoice scope before enumerating canonical payment references, ignoring truncated previews", async () => {
48
+ const f = fixture();
49
+ const row = f.payment();
50
+ f.list.mockResolvedValue({ data: [row], has_more: false } as never);
51
+ const result = await f.client.getInvoicePaymentPageFromStripe(f.ctx, f.opts);
52
+ expect(f.retrieve).toHaveBeenCalledExactlyOnceWith("in_buyer");
53
+ expect(f.list).toHaveBeenCalledExactlyOnceWith({
54
+ invoice: "in_buyer",
55
+ limit: 25,
56
+ });
57
+ expect(result).toEqual({
58
+ scope: f.opts,
59
+ page: [
60
+ {
61
+ invoicePayment: row,
62
+ paymentIntentId: "pi_paid",
63
+ referenceStatus: "payment_intent",
64
+ },
65
+ ],
66
+ hasMore: false,
67
+ continueCursor: null,
68
+ });
69
+ });
70
+ it("resumes all invoice payments and preserves unsupported and unavailable references", async () => {
71
+ const f = fixture();
72
+ f.list
73
+ .mockResolvedValueOnce({ data: [f.payment()], has_more: true } as never)
74
+ .mockResolvedValueOnce({
75
+ data: [
76
+ f.payment("inpay_charge", "charge", "ch_old"),
77
+ f.payment("inpay_missing", "payment_intent", null),
78
+ ],
79
+ has_more: false,
80
+ } as never);
81
+ const first = await f.client.getInvoicePaymentPageFromStripe(f.ctx, f.opts);
82
+ const second = await f.client.getInvoicePaymentPageFromStripe(f.ctx, {
83
+ ...f.opts,
84
+ cursor: first.continueCursor,
85
+ });
86
+ expect(f.retrieve).toHaveBeenCalledTimes(2);
87
+ expect(f.list).toHaveBeenLastCalledWith({
88
+ invoice: "in_buyer",
89
+ limit: 25,
90
+ starting_after: "inpay_first",
91
+ });
92
+ expect(second.page.map((row) => row.referenceStatus)).toEqual([
93
+ "unsupported",
94
+ "unavailable",
95
+ ]);
96
+ expect(second.page.map((row) => row.paymentIntentId)).toEqual([null, null]);
97
+ });
98
+ it.each([
99
+ { id: "in_foreign" },
100
+ { customer_account: "acct_foreign" },
101
+ {
102
+ parent: {
103
+ type: "subscription_details",
104
+ subscription_details: { subscription: "sub_foreign" },
105
+ },
106
+ },
107
+ { parent: null },
108
+ ])(
109
+ "rejects foreign or missing invoice bindings before payment enumeration %#",
110
+ async (change) => {
111
+ const f = fixture();
112
+ f.retrieve.mockResolvedValue({ ...f.invoice, ...change } as never);
113
+ await expect(
114
+ f.client.getInvoicePaymentPageFromStripe(f.ctx, f.opts),
115
+ ).rejects.toThrow();
116
+ expect(f.list).not.toHaveBeenCalled();
117
+ },
118
+ );
119
+ it.each([
120
+ { stripeInvoiceId: "bad" },
121
+ { customerAccount: "cus_wrong" },
122
+ { stripeSubscriptionId: "bad" },
123
+ { limit: 0 },
124
+ { limit: 101 },
125
+ { limit: 1.5 },
126
+ { cursor: "invalid" },
127
+ ])("rejects invalid selectors before provider reads %#", async (change) => {
128
+ const f = fixture();
129
+ await expect(
130
+ f.client.getInvoicePaymentPageFromStripe(f.ctx, { ...f.opts, ...change }),
131
+ ).rejects.toThrow();
132
+ expect(f.retrieve).not.toHaveBeenCalled();
133
+ expect(f.list).not.toHaveBeenCalled();
134
+ });
135
+ it("binds continuation to invoice, buyer and subscription selectors", async () => {
136
+ const f = fixture();
137
+ f.list.mockResolvedValue({ data: [f.payment()], has_more: true } as never);
138
+ const first = await f.client.getInvoicePaymentPageFromStripe(f.ctx, f.opts);
139
+ for (const change of [
140
+ { stripeInvoiceId: "in_other" },
141
+ { customerAccount: "acct_other" },
142
+ { stripeSubscriptionId: "sub_other" },
143
+ ])
144
+ await expect(
145
+ f.client.getInvoicePaymentPageFromStripe(f.ctx, {
146
+ ...f.opts,
147
+ ...change,
148
+ cursor: first.continueCursor,
149
+ }),
150
+ ).rejects.toThrow();
151
+ expect(f.retrieve).toHaveBeenCalledTimes(1);
152
+ expect(f.list).toHaveBeenCalledTimes(1);
153
+ });
154
+ it("propagates provider failure without an empty success page", async () => {
155
+ const f = fixture();
156
+ f.retrieve.mockRejectedValue(new Error("Provider unavailable"));
157
+ await expect(
158
+ f.client.getInvoicePaymentPageFromStripe(f.ctx, f.opts),
159
+ ).rejects.toThrow("Provider unavailable");
160
+ expect(f.list).not.toHaveBeenCalled();
161
+ });
162
+
163
+ it("preserves open and canceled rows, null and zero paid amounts and original currency units", async () => {
164
+ const f = fixture();
165
+ const open = {
166
+ ...f.payment("inpay_open"),
167
+ status: "open",
168
+ amount_paid: null,
169
+ currency: "isk",
170
+ };
171
+ const canceled = {
172
+ ...f.payment("inpay_canceled"),
173
+ status: "canceled",
174
+ amount_paid: 0,
175
+ currency: "huf",
176
+ };
177
+ f.list.mockResolvedValue({
178
+ data: [open, canceled],
179
+ has_more: false,
180
+ } as never);
181
+ const result = await f.client.getInvoicePaymentPageFromStripe(f.ctx, f.opts);
182
+ expect(result.page.map((row) => row.invoicePayment)).toEqual([
183
+ open,
184
+ canceled,
185
+ ]);
186
+ expect(result).not.toHaveProperty("eligible");
187
+ expect(result).not.toHaveProperty("refundableAmount");
188
+ });
189
+ it("resolves expanded canonical references without using metadata or invoice previews", async () => {
190
+ const f = fixture();
191
+ const row = {
192
+ ...f.payment(),
193
+ invoice: { id: "in_buyer" },
194
+ payment: { type: "payment_intent", payment_intent: { id: "pi_expanded" } },
195
+ };
196
+ f.retrieve.mockResolvedValue({
197
+ ...f.invoice,
198
+ parent: {
199
+ type: "subscription_details",
200
+ subscription_details: { subscription: { id: "sub_buyer" } },
201
+ },
202
+ } as never);
203
+ f.list.mockResolvedValue({ data: [row], has_more: false } as never);
204
+ expect(
205
+ (await f.client.getInvoicePaymentPageFromStripe(f.ctx, f.opts)).page[0]
206
+ ?.paymentIntentId,
207
+ ).toBe("pi_expanded");
208
+ });
209
+ it("retains unknown payment types and malformed PaymentIntent identifiers as unsupported or unavailable", async () => {
210
+ const f = fixture();
211
+ f.list.mockResolvedValue({
212
+ data: [
213
+ f.payment("inpay_future", "future_type", "anything"),
214
+ f.payment("inpay_bad", "payment_intent", "ch_wrong"),
215
+ ],
216
+ has_more: false,
217
+ } as never);
218
+ const result = await f.client.getInvoicePaymentPageFromStripe(f.ctx, f.opts);
219
+ expect(result.page.map((row) => row.referenceStatus)).toEqual([
220
+ "unsupported",
221
+ "unavailable",
222
+ ]);
223
+ expect(result.page.every((row) => row.paymentIntentId === null)).toBe(true);
224
+ });
225
+ it.each([
226
+ { data: [], has_more: true },
227
+ { data: [{ id: "inpay_foreign", invoice: "in_foreign" }], has_more: false },
228
+ { data: [{ id: "bad", invoice: "in_buyer" }], has_more: false },
229
+ ])(
230
+ "rejects malformed provider pages instead of inventing completion %#",
231
+ async (response) => {
232
+ const f = fixture();
233
+ f.list.mockResolvedValue(response as never);
234
+ await expect(
235
+ f.client.getInvoicePaymentPageFromStripe(f.ctx, f.opts),
236
+ ).rejects.toThrow();
237
+ },
238
+ );
239
+ it("allows a terminal empty page", async () => {
240
+ const f = fixture();
241
+ f.list.mockResolvedValue({ data: [], has_more: false } as never);
242
+ expect(await f.client.getInvoicePaymentPageFromStripe(f.ctx, f.opts)).toEqual(
243
+ {
244
+ scope: f.opts,
245
+ page: [],
246
+ hasMore: false,
247
+ continueCursor: null,
248
+ },
249
+ );
250
+ });
251
+ it("rejects a provider page exceeding the requested bound", async () => {
252
+ const f = fixture();
253
+ f.list.mockResolvedValue({
254
+ data: [f.payment(), f.payment("inpay_second")],
255
+ has_more: false,
256
+ } as never);
257
+ await expect(
258
+ f.client.getInvoicePaymentPageFromStripe(f.ctx, { ...f.opts, limit: 1 }),
259
+ ).rejects.toThrow();
260
+ });
261
+ it("propagates payment-list failure after verified invoice scope", async () => {
262
+ const f = fixture();
263
+ f.list.mockRejectedValue(new Error("Payment list unavailable"));
264
+ await expect(
265
+ f.client.getInvoicePaymentPageFromStripe(f.ctx, f.opts),
266
+ ).rejects.toThrow("Payment list unavailable");
267
+ });
268
+ it("rejects nonadvancing continuation instead of repeating indefinitely", async () => {
269
+ const f = fixture();
270
+ f.list.mockResolvedValue({ data: [f.payment()], has_more: true } as never);
271
+ const first = await f.client.getInvoicePaymentPageFromStripe(f.ctx, f.opts);
272
+ await expect(
273
+ f.client.getInvoicePaymentPageFromStripe(f.ctx, {
274
+ ...f.opts,
275
+ cursor: first.continueCursor,
276
+ }),
277
+ ).rejects.toThrow(/continuation/);
278
+ });
279
+
280
+ it("rejects duplicate and repeated boundary payment rows", async () => {
281
+ const f = fixture();
282
+ f.list.mockResolvedValueOnce({
283
+ data: [f.payment()],
284
+ has_more: true,
285
+ } as never);
286
+ const first = await f.client.getInvoicePaymentPageFromStripe(f.ctx, f.opts);
287
+ f.list.mockResolvedValueOnce({
288
+ data: [f.payment(), f.payment("inpay_second")],
289
+ has_more: false,
290
+ } as never);
291
+ await expect(
292
+ f.client.getInvoicePaymentPageFromStripe(f.ctx, {
293
+ ...f.opts,
294
+ cursor: first.continueCursor,
295
+ }),
296
+ ).rejects.toThrow();
297
+ f.list.mockResolvedValueOnce({
298
+ data: [f.payment("inpay_second"), f.payment("inpay_second")],
299
+ has_more: false,
300
+ } as never);
301
+ await expect(
302
+ f.client.getInvoicePaymentPageFromStripe(f.ctx, f.opts),
303
+ ).rejects.toThrow();
304
+ });
305
+
306
+ it.each([
307
+ { amount_paid: Number.MAX_SAFE_INTEGER + 1 },
308
+ { amount_paid: -1 },
309
+ { amount_requested: 1.5 },
310
+ { amount_requested: Number.NaN },
311
+ { currency: "" },
312
+ ])(
313
+ "rejects unrepresentable original payment units instead of returning rounded evidence %#",
314
+ async (change) => {
315
+ const f = fixture();
316
+ f.list.mockResolvedValue({
317
+ data: [{ ...f.payment(), ...change }],
318
+ has_more: false,
319
+ } as never);
320
+ await expect(
321
+ f.client.getInvoicePaymentPageFromStripe(f.ctx, f.opts),
322
+ ).rejects.toThrow(/units|currency/);
323
+ },
324
+ );
325
+
326
+ it("rejects noncanonical and invalid-schema cursor payloads before provider reads", async () => {
327
+ const f = fixture();
328
+ const payload = btoa(
329
+ JSON.stringify({ version: 2, scope: f.opts, after: "inpay_previous" }),
330
+ );
331
+ for (const cursor of ["%%%", payload, `${payload}=`]) {
332
+ await expect(
333
+ f.client.getInvoicePaymentPageFromStripe(f.ctx, { ...f.opts, cursor }),
334
+ ).rejects.toThrow(/cursor/);
335
+ }
336
+ expect(f.retrieve).not.toHaveBeenCalled();
337
+ expect(f.list).not.toHaveBeenCalled();
338
+ });
339
+ it("revalidates invoice ownership on continuation instead of trusting a previous successful page", async () => {
340
+ const f = fixture();
341
+ f.list.mockResolvedValue({ data: [f.payment()], has_more: true } as never);
342
+ const first = await f.client.getInvoicePaymentPageFromStripe(f.ctx, f.opts);
343
+ f.retrieve.mockResolvedValue({
344
+ ...f.invoice,
345
+ customer_account: "acct_foreign",
346
+ } as never);
347
+ await expect(
348
+ f.client.getInvoicePaymentPageFromStripe(f.ctx, {
349
+ ...f.opts,
350
+ cursor: first.continueCursor,
351
+ }),
352
+ ).rejects.toThrow(/scope/);
353
+ expect(f.list).toHaveBeenCalledTimes(1);
354
+ });
@@ -0,0 +1,165 @@
1
+ import type Stripe from "stripe";
2
+ import { z } from "zod";
3
+
4
+ const scopeSchema = z
5
+ .object({
6
+ stripeInvoiceId: z
7
+ .string()
8
+ .max(128)
9
+ .regex(/^in_[A-Za-z0-9_]+$/),
10
+ customerAccount: z
11
+ .string()
12
+ .max(128)
13
+ .regex(/^acct_[A-Za-z0-9_]+$/),
14
+ stripeSubscriptionId: z
15
+ .string()
16
+ .max(128)
17
+ .regex(/^sub_[A-Za-z0-9_]+$/),
18
+ })
19
+ .strict();
20
+ const optionsSchema = scopeSchema
21
+ .extend({
22
+ limit: z.number().int().min(1).max(100).default(25),
23
+ cursor: z.string().min(1).max(2048).nullable().optional(),
24
+ })
25
+ .strict();
26
+ const cursorSchema = z
27
+ .object({
28
+ version: z.literal(1),
29
+ scope: scopeSchema,
30
+ after: z
31
+ .string()
32
+ .max(128)
33
+ .regex(/^inpay_[A-Za-z0-9_]+$/),
34
+ })
35
+ .strict();
36
+ export type InvoicePaymentPageOptions = z.input<typeof optionsSchema>;
37
+ export type ProviderInvoicePaymentPage = {
38
+ scope: {
39
+ stripeInvoiceId: string;
40
+ customerAccount: string;
41
+ stripeSubscriptionId: string;
42
+ };
43
+ page: {
44
+ invoicePayment: Stripe.InvoicePayment;
45
+ paymentIntentId: string | null;
46
+ referenceStatus: "payment_intent" | "unsupported" | "unavailable";
47
+ }[];
48
+ hasMore: boolean;
49
+ continueCursor: string | null;
50
+ };
51
+ /** Bind a continuation to the verified invoice, buyer and subscription selectors. */
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
+ /** Reject malformed continuations and accidental cross-scope reuse before provider reads. */
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 value = cursorSchema.parse(
63
+ JSON.parse(atob(cursor.replaceAll("-", "+").replaceAll("_", "/"))),
64
+ );
65
+ if (
66
+ JSON.stringify(value.scope) !== JSON.stringify(scope) ||
67
+ encodeCursor(value.scope, value.after) !== cursor
68
+ )
69
+ throw new Error();
70
+ return value.after;
71
+ } catch {
72
+ throw new Error("Invalid invoice payment page cursor or scope");
73
+ }
74
+ }
75
+ /** Normalize provider references without inferring missing identifiers. */
76
+ function referenceId(value: string | { id: string } | null | undefined) {
77
+ return typeof value === "string" ? value : value?.id;
78
+ }
79
+ /** Keep financial evidence exact; reject units that JavaScript cannot safely represent. */
80
+ function assertRepresentableUnits(row: Stripe.InvoicePayment) {
81
+ const amounts = [
82
+ row.amount_requested,
83
+ ...(row.amount_paid === null ? [] : [row.amount_paid]),
84
+ ];
85
+ if (
86
+ amounts.some((amount) => !Number.isSafeInteger(amount) || amount < 0) ||
87
+ !/^[a-z]{3}$/.test(row.currency)
88
+ ) {
89
+ throw new Error("Invalid provider invoice payment units or currency");
90
+ }
91
+ }
92
+ /** Retain unsupported rows while distinguishing canonical and unavailable references. */
93
+ function paymentReference(
94
+ invoicePayment: Stripe.InvoicePayment,
95
+ ): ProviderInvoicePaymentPage["page"][number] {
96
+ assertRepresentableUnits(invoicePayment);
97
+ const type = invoicePayment.payment.type;
98
+ const id =
99
+ type === "payment_intent"
100
+ ? referenceId(invoicePayment.payment.payment_intent)
101
+ : undefined;
102
+ const paymentIntentId = id && /^pi_[A-Za-z0-9_]+$/.test(id) ? id : null;
103
+ return {
104
+ invoicePayment,
105
+ paymentIntentId,
106
+ referenceStatus:
107
+ type !== "payment_intent"
108
+ ? "unsupported"
109
+ : paymentIntentId
110
+ ? "payment_intent"
111
+ : "unavailable",
112
+ };
113
+ }
114
+
115
+ /** Canonical provider references only. The host authorizes scope and separately verifies refund eligibility. */
116
+ export async function getInvoicePaymentPageFromStripe(
117
+ stripe: Stripe,
118
+ input: InvoicePaymentPageOptions,
119
+ ): Promise<ProviderInvoicePaymentPage> {
120
+ const { limit, cursor, ...scope } = optionsSchema.parse(input);
121
+ const after = cursor ? decodeCursor(cursor, scope) : undefined;
122
+ const invoice = await stripe.invoices.retrieve(scope.stripeInvoiceId);
123
+ const parent = invoice.parent;
124
+ if (
125
+ invoice.id !== scope.stripeInvoiceId ||
126
+ invoice.customer_account !== scope.customerAccount ||
127
+ parent?.type !== "subscription_details" ||
128
+ referenceId(parent.subscription_details?.subscription) !==
129
+ scope.stripeSubscriptionId
130
+ ) {
131
+ throw new Error(
132
+ "Invalid provider invoice payment buyer or subscription scope",
133
+ );
134
+ }
135
+ const response = await stripe.invoicePayments.list({
136
+ invoice: scope.stripeInvoiceId,
137
+ limit,
138
+ ...(after ? { starting_after: after } : {}),
139
+ });
140
+ if (
141
+ response.data.length > limit ||
142
+ new Set(response.data.map((row) => row.id)).size !== response.data.length ||
143
+ response.data.some(
144
+ (row) =>
145
+ row.id === after ||
146
+ referenceId(row.invoice) !== scope.stripeInvoiceId ||
147
+ !/^inpay_[A-Za-z0-9_]+$/.test(row.id),
148
+ )
149
+ ) {
150
+ throw new Error(
151
+ "Invalid provider invoice payment page scope or continuation",
152
+ );
153
+ }
154
+ const last = response.data[response.data.length - 1]?.id;
155
+ if (response.has_more && (!last || last === after))
156
+ throw new Error(
157
+ "Provider invoice payment page has no advancing continuation",
158
+ );
159
+ return {
160
+ scope,
161
+ page: response.data.map(paymentReference),
162
+ hasMore: response.has_more,
163
+ continueCursor: response.has_more ? encodeCursor(scope, last!) : null,
164
+ };
165
+ }
@@ -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
+ }