@fantastic.dev/better-stripe 0.32.0 → 0.34.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 +14 -0
- package/README.md +36 -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/connect/payoutAdoptionTestHelpers.d.ts +36 -0
- package/dist/client/connect/payoutAdoptionTestHelpers.d.ts.map +1 -1
- package/dist/client/connect/payoutExecutionTestHelpers.d.ts +18 -0
- package/dist/client/connect/payoutExecutionTestHelpers.d.ts.map +1 -1
- package/dist/client/connect/payoutLargeAdoptionTestHelpers.d.ts +36 -0
- package/dist/client/connect/payoutLargeAdoptionTestHelpers.d.ts.map +1 -1
- package/dist/client/connect/payoutSyncTestHelpers.d.ts +18 -0
- package/dist/client/connect/payoutSyncTestHelpers.d.ts.map +1 -1
- 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/core/accountClosures.d.ts +15 -0
- package/dist/client/core/accountClosures.d.ts.map +1 -0
- package/dist/client/core/accountClosures.js +10 -0
- package/dist/client/core/accountClosures.js.map +1 -0
- package/dist/client/core/accounts.d.ts.map +1 -1
- package/dist/client/core/accounts.js +15 -23
- package/dist/client/core/accounts.js.map +1 -1
- package/dist/client/core/personalAccountMapping.d.ts +8 -0
- package/dist/client/core/personalAccountMapping.d.ts.map +1 -0
- package/dist/client/core/personalAccountMapping.js +11 -0
- package/dist/client/core/personalAccountMapping.js.map +1 -0
- package/dist/client/index.d.ts +57 -2
- package/dist/client/index.d.ts.map +1 -1
- package/dist/client/index.js +13 -0
- package/dist/client/index.js.map +1 -1
- package/dist/client/invoiceReads.d.ts +7 -1
- package/dist/client/invoiceReads.d.ts.map +1 -1
- package/dist/client/invoiceReads.js +11 -1
- package/dist/client/invoiceReads.js.map +1 -1
- package/dist/client/publicTypes.d.ts +5 -0
- package/dist/client/publicTypes.d.ts.map +1 -0
- package/dist/client/publicTypes.js +2 -0
- package/dist/client/publicTypes.js.map +1 -0
- package/dist/component/_generated/component.d.ts +88 -0
- package/dist/component/_generated/component.d.ts.map +1 -1
- package/dist/component/accountClosure/helpers.d.ts +18 -0
- package/dist/component/accountClosure/helpers.d.ts.map +1 -0
- package/dist/component/accountClosure/helpers.js +18 -0
- package/dist/component/accountClosure/helpers.js.map +1 -0
- package/dist/component/accountClosure/mutations.d.ts +20 -0
- package/dist/component/accountClosure/mutations.d.ts.map +1 -0
- package/dist/component/accountClosure/mutations.js +55 -0
- package/dist/component/accountClosure/mutations.js.map +1 -0
- package/dist/component/accountClosure/queries.d.ts +34 -0
- package/dist/component/accountClosure/queries.d.ts.map +1 -0
- package/dist/component/accountClosure/queries.js +36 -0
- package/dist/component/accountClosure/queries.js.map +1 -0
- package/dist/component/accountClosure/schema.d.ts +46 -0
- package/dist/component/accountClosure/schema.d.ts.map +1 -0
- package/dist/component/accountClosure/schema.js +20 -0
- package/dist/component/accountClosure/schema.js.map +1 -0
- package/dist/component/core/mutations.d.ts.map +1 -1
- package/dist/component/core/mutations.js +5 -0
- package/dist/component/core/mutations.js.map +1 -1
- package/dist/component/core/personalAccountMapping.d.ts +95 -0
- package/dist/component/core/personalAccountMapping.d.ts.map +1 -0
- package/dist/component/core/personalAccountMapping.js +54 -0
- package/dist/component/core/personalAccountMapping.js.map +1 -0
- package/dist/component/core/queries.d.ts +27 -0
- package/dist/component/core/queries.d.ts.map +1 -1
- package/dist/component/core/queries.js +7 -0
- package/dist/component/core/queries.js.map +1 -1
- package/dist/component/earnings/triggers.d.ts +42 -0
- package/dist/component/earnings/triggers.d.ts.map +1 -1
- package/dist/component/payoutRelease/queries.d.ts +2 -2
- package/dist/component/payoutRelease/queries.d.ts.map +1 -1
- package/dist/component/schema.d.ts +18 -0
- package/dist/component/schema.js +2 -0
- package/dist/component/schema.js.map +1 -1
- package/docs/checkout-session-pages.md +71 -0
- package/docs/personal-account-mapping.md +54 -0
- package/docs/read-contracts.md +28 -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/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/core/account-close-orchestration.test.ts +131 -0
- package/src/client/core/account-closure.test.ts +317 -0
- package/src/client/core/accountClosures.ts +37 -0
- package/src/client/core/accounts.test.ts +0 -111
- package/src/client/core/accounts.ts +24 -29
- package/src/client/core/personal-account-mapping.test.ts +71 -0
- package/src/client/core/personalAccountMapping.ts +23 -0
- package/src/client/index.ts +45 -33
- package/src/client/invoiceReads.ts +17 -1
- package/src/client/publicTypes.ts +35 -0
- package/src/client/refund-context-shapes.test.ts +127 -0
- package/src/client/refund-context.test.ts +404 -0
- package/src/component/_generated/api.ts +8 -0
- package/src/component/_generated/component.ts +126 -0
- package/src/component/accountClosure/helpers.ts +21 -0
- package/src/component/accountClosure/mutations.ts +56 -0
- package/src/component/accountClosure/queries.ts +43 -0
- package/src/component/accountClosure/schema.ts +20 -0
- package/src/component/core/mutations.ts +3 -0
- package/src/component/core/personal-account-mapping.test.ts +173 -0
- package/src/component/core/personalAccountMapping.ts +81 -0
- package/src/component/core/queries.ts +11 -0
- package/src/component/schema.ts +2 -0
|
@@ -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
|
+
};
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
import type Stripe from "stripe";
|
|
2
|
+
|
|
3
|
+
export function refundObjectId(
|
|
4
|
+
value: string | { id: string } | null | undefined,
|
|
5
|
+
) {
|
|
6
|
+
return typeof value === "string" ? value : value?.id;
|
|
7
|
+
}
|
|
8
|
+
export type RefundTargetOptions = {
|
|
9
|
+
stripePaymentIntentId?: string;
|
|
10
|
+
stripeChargeId?: string;
|
|
11
|
+
stripeAccountId?: string;
|
|
12
|
+
};
|
|
13
|
+
/** Shared target resolution; caller authorization and observation validation remain separate. */
|
|
14
|
+
export async function readRefundPayment(
|
|
15
|
+
stripe: Stripe,
|
|
16
|
+
opts: RefundTargetOptions,
|
|
17
|
+
) {
|
|
18
|
+
if (!opts.stripePaymentIntentId) return null;
|
|
19
|
+
return stripe.paymentIntents.retrieve(
|
|
20
|
+
opts.stripePaymentIntentId,
|
|
21
|
+
undefined,
|
|
22
|
+
opts.stripeAccountId ? { stripeAccount: opts.stripeAccountId } : undefined,
|
|
23
|
+
);
|
|
24
|
+
}
|
|
25
|
+
/** Resolve only the selected original charge; does not create refunds or inspect fees. */
|
|
26
|
+
export async function readRefundCharge(
|
|
27
|
+
stripe: Stripe,
|
|
28
|
+
opts: RefundTargetOptions,
|
|
29
|
+
payment: Stripe.PaymentIntent | null,
|
|
30
|
+
) {
|
|
31
|
+
const chargeId =
|
|
32
|
+
opts.stripeChargeId ?? refundObjectId(payment?.latest_charge);
|
|
33
|
+
if (!chargeId) return null;
|
|
34
|
+
return stripe.charges.retrieve(
|
|
35
|
+
chargeId,
|
|
36
|
+
undefined,
|
|
37
|
+
opts.stripeAccountId ? { stripeAccount: opts.stripeAccountId } : undefined,
|
|
38
|
+
);
|
|
39
|
+
}
|
|
@@ -362,5 +362,77 @@ describe("createRefund — actor scoping (BTS-35)", () => {
|
|
|
362
362
|
stripePaymentIntentId: "pi_1",
|
|
363
363
|
});
|
|
364
364
|
expect(stripe.refunds.create).toHaveBeenCalledTimes(1);
|
|
365
|
+
expect(stripe.paymentIntents.retrieve).not.toHaveBeenCalled();
|
|
366
|
+
expect(stripe.charges.retrieve).toHaveBeenCalledTimes(2);
|
|
367
|
+
expect(stripe.refunds.create).toHaveBeenCalledWith(
|
|
368
|
+
{ charge: "ch_1", reverse_transfer: true },
|
|
369
|
+
undefined,
|
|
370
|
+
);
|
|
371
|
+
});
|
|
372
|
+
});
|
|
373
|
+
|
|
374
|
+
it("keeps explicit charge-first lookup and original request/idempotency flags", async () => {
|
|
375
|
+
const stripe = makeStripe({ transfer: "tr_one", application_fee: "fee_one" });
|
|
376
|
+
await createRefund(asStripe(stripe), makeComponent(), noCtx, {
|
|
377
|
+
stripeChargeId: "ch_1",
|
|
378
|
+
stripeAccountId: "acct_request_scope",
|
|
379
|
+
idempotencyKey: "refund_same_intent",
|
|
380
|
+
amount: 123,
|
|
381
|
+
});
|
|
382
|
+
expect(stripe.paymentIntents.retrieve).not.toHaveBeenCalled();
|
|
383
|
+
expect(stripe.charges.retrieve).toHaveBeenCalledTimes(1);
|
|
384
|
+
expect(stripe.refunds.create).toHaveBeenCalledWith(
|
|
385
|
+
{
|
|
386
|
+
charge: "ch_1",
|
|
387
|
+
amount: 123,
|
|
388
|
+
refund_application_fee: true,
|
|
389
|
+
reverse_transfer: true,
|
|
390
|
+
},
|
|
391
|
+
{
|
|
392
|
+
stripeAccount: "acct_request_scope",
|
|
393
|
+
idempotencyKey: "refund_same_intent",
|
|
394
|
+
},
|
|
395
|
+
);
|
|
396
|
+
});
|
|
397
|
+
|
|
398
|
+
it("rejects both target selectors before authorization, lookup or money movement", async () => {
|
|
399
|
+
const stripe = makeStripe({});
|
|
400
|
+
const ctx = makeCtx();
|
|
401
|
+
await expect(
|
|
402
|
+
createRefund(asStripe(stripe), makeComponent(), ctx, {
|
|
403
|
+
stripePaymentIntentId: "pi_1",
|
|
404
|
+
stripeChargeId: "ch_1",
|
|
405
|
+
actor: { type: "seller", accountId: "acct_store" },
|
|
406
|
+
}),
|
|
407
|
+
).rejects.toMatchObject({ data: { code: "REFUND_CREATE_FAILED" } });
|
|
408
|
+
expect(ctx.runQuery).not.toHaveBeenCalled();
|
|
409
|
+
expect(stripe.paymentIntents.retrieve).not.toHaveBeenCalled();
|
|
410
|
+
expect(stripe.charges.retrieve).not.toHaveBeenCalled();
|
|
411
|
+
expect(stripe.refunds.create).not.toHaveBeenCalled();
|
|
412
|
+
});
|
|
413
|
+
|
|
414
|
+
it("preserves structured createRefund error wrapping on charge-only lookup failure", async () => {
|
|
415
|
+
const stripe = makeStripe({});
|
|
416
|
+
const failure = Object.assign(new Error("Fixture provider failure"), {
|
|
417
|
+
type: "StripeAPIError",
|
|
418
|
+
code: "api_error",
|
|
419
|
+
});
|
|
420
|
+
stripe.charges.retrieve.mockRejectedValue(failure);
|
|
421
|
+
await expect(
|
|
422
|
+
createRefund(asStripe(stripe), makeComponent(), noCtx, {
|
|
423
|
+
stripeChargeId: "ch_1",
|
|
424
|
+
}),
|
|
425
|
+
).rejects.toMatchObject({
|
|
426
|
+
data: {
|
|
427
|
+
code: "REFUND_CREATE_FAILED",
|
|
428
|
+
message: "Failed to create refund",
|
|
429
|
+
stripeError: {
|
|
430
|
+
type: "StripeAPIError",
|
|
431
|
+
code: "api_error",
|
|
432
|
+
message: "Fixture provider failure",
|
|
433
|
+
},
|
|
434
|
+
},
|
|
365
435
|
});
|
|
436
|
+
expect(stripe.paymentIntents.retrieve).not.toHaveBeenCalled();
|
|
437
|
+
expect(stripe.refunds.create).not.toHaveBeenCalled();
|
|
366
438
|
});
|
|
@@ -10,6 +10,7 @@ import type {
|
|
|
10
10
|
} from "../types.js";
|
|
11
11
|
import { componentRef } from "../webhooks/helpers.js";
|
|
12
12
|
import { type RefundActor, isRefundAuthorized } from "./refundActor.js";
|
|
13
|
+
import { readRefundPayment, readRefundCharge } from "./refundTarget.js";
|
|
13
14
|
|
|
14
15
|
export type { RefundActor } from "./refundActor.js";
|
|
15
16
|
|
|
@@ -126,9 +127,6 @@ export async function createRefund(
|
|
|
126
127
|
await assertRefundAuthorized(stripe, component, ctx, opts);
|
|
127
128
|
|
|
128
129
|
try {
|
|
129
|
-
const accountRequestOpts = opts.stripeAccountId
|
|
130
|
-
? { stripeAccount: opts.stripeAccountId }
|
|
131
|
-
: undefined;
|
|
132
130
|
const createRequestOpts =
|
|
133
131
|
opts.stripeAccountId !== undefined || opts.idempotencyKey !== undefined
|
|
134
132
|
? {
|
|
@@ -141,22 +139,9 @@ export async function createRefund(
|
|
|
141
139
|
}
|
|
142
140
|
: undefined;
|
|
143
141
|
|
|
144
|
-
//
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
const pi = await stripe.paymentIntents.retrieve(
|
|
148
|
-
opts.stripePaymentIntentId,
|
|
149
|
-
undefined,
|
|
150
|
-
accountRequestOpts,
|
|
151
|
-
);
|
|
152
|
-
chargeId =
|
|
153
|
-
typeof pi.latest_charge === "string"
|
|
154
|
-
? pi.latest_charge
|
|
155
|
-
: (pi.latest_charge?.id ?? undefined);
|
|
156
|
-
}
|
|
157
|
-
const charge = chargeId
|
|
158
|
-
? await stripe.charges.retrieve(chargeId, undefined, accountRequestOpts)
|
|
159
|
-
: undefined;
|
|
142
|
+
// Preserve the original target and marketplace flags through shared read-only resolution.
|
|
143
|
+
const payment = await readRefundPayment(stripe, opts);
|
|
144
|
+
const charge = await readRefundCharge(stripe, opts, payment);
|
|
160
145
|
|
|
161
146
|
const refundApplicationFee =
|
|
162
147
|
(opts.refundApplicationFee ?? true) && Boolean(charge?.application_fee);
|
|
@@ -193,7 +178,7 @@ export async function createRefund(
|
|
|
193
178
|
* no ledger row), a seller is denied rather than allowed. No-ops for admin /
|
|
194
179
|
* omitted actors.
|
|
195
180
|
*/
|
|
196
|
-
async function assertRefundAuthorized(
|
|
181
|
+
export async function assertRefundAuthorized(
|
|
197
182
|
stripe: Stripe,
|
|
198
183
|
component: Component,
|
|
199
184
|
ctx: RunCtx,
|
|
@@ -203,9 +188,9 @@ async function assertRefundAuthorized(
|
|
|
203
188
|
stripeAccountId?: string;
|
|
204
189
|
actor?: RefundActor;
|
|
205
190
|
},
|
|
206
|
-
): Promise<
|
|
191
|
+
): Promise<StripeComponentPayment | null> {
|
|
207
192
|
const { actor } = opts;
|
|
208
|
-
if (!actor || actor.type === "admin") return; // unrestricted
|
|
193
|
+
if (!actor || actor.type === "admin") return null; // legacy createRefund remains unrestricted
|
|
209
194
|
|
|
210
195
|
// Resolve the PaymentIntent id that keys the payments ledger. A charge-only
|
|
211
196
|
// refund resolves through the charge's `payment_intent`.
|
|
@@ -253,6 +238,7 @@ async function assertRefundAuthorized(
|
|
|
253
238
|
`Refund not authorized: seller ${actor.accountId} may not refund a sale routed to another account`,
|
|
254
239
|
);
|
|
255
240
|
}
|
|
241
|
+
return payment;
|
|
256
242
|
}
|
|
257
243
|
|
|
258
244
|
export async function getRefundByStripeId(
|