@fantastic.dev/better-stripe 0.45.2 → 0.47.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 +36 -0
- package/README.md +1 -1
- package/dist/client/connect/payoutAdoptionTestHelpers.d.ts +46 -0
- package/dist/client/connect/payoutAdoptionTestHelpers.d.ts.map +1 -1
- package/dist/client/connect/payoutExecutionTestHelpers.d.ts +39 -16
- package/dist/client/connect/payoutExecutionTestHelpers.d.ts.map +1 -1
- package/dist/client/connect/payoutLargeAdoptionTestHelpers.d.ts +78 -32
- package/dist/client/connect/payoutLargeAdoptionTestHelpers.d.ts.map +1 -1
- package/dist/client/connect/payoutSyncTestHelpers.d.ts +23 -0
- package/dist/client/connect/payoutSyncTestHelpers.d.ts.map +1 -1
- package/dist/client/connect/refundSync.d.ts +32 -0
- package/dist/client/connect/refundSync.d.ts.map +1 -0
- package/dist/client/connect/refundSync.js +61 -0
- package/dist/client/connect/refundSync.js.map +1 -0
- package/dist/client/connect/refundSyncValidation.d.ts +16 -0
- package/dist/client/connect/refundSyncValidation.d.ts.map +1 -0
- package/dist/client/connect/refundSyncValidation.js +87 -0
- package/dist/client/connect/refundSyncValidation.js.map +1 -0
- package/dist/client/index.d.ts +54 -1
- package/dist/client/index.d.ts.map +1 -1
- package/dist/client/index.js +10 -3
- package/dist/client/index.js.map +1 -1
- package/dist/client/types/triggers.d.ts +3 -2
- package/dist/client/types/triggers.d.ts.map +1 -1
- package/dist/client/webhooks/helpers.d.ts.map +1 -1
- package/dist/client/webhooks/helpers.js +1 -0
- package/dist/client/webhooks/helpers.js.map +1 -1
- package/dist/client/webhooks/refundReconciliation.d.ts +10 -0
- package/dist/client/webhooks/refundReconciliation.d.ts.map +1 -0
- package/dist/client/webhooks/refundReconciliation.js +41 -0
- package/dist/client/webhooks/refundReconciliation.js.map +1 -0
- package/dist/client/webhooks/refundReconciliationValidators.d.ts +68 -0
- package/dist/client/webhooks/refundReconciliationValidators.d.ts.map +1 -0
- package/dist/client/webhooks/refundReconciliationValidators.js +11 -0
- package/dist/client/webhooks/refundReconciliationValidators.js.map +1 -0
- package/dist/component/_generated/api.d.ts +12 -0
- package/dist/component/_generated/api.d.ts.map +1 -1
- package/dist/component/_generated/api.js.map +1 -1
- package/dist/component/_generated/component.d.ts +67 -0
- package/dist/component/_generated/component.d.ts.map +1 -1
- package/dist/component/balanceFunding/mutations.d.ts +27 -27
- package/dist/component/balanceFunding/workflowValidators.d.ts +16 -16
- package/dist/component/connect/mutations.d.ts.map +1 -1
- package/dist/component/connect/mutations.js +2 -53
- package/dist/component/connect/mutations.js.map +1 -1
- package/dist/component/connect/refundWrites.d.ts +6 -0
- package/dist/component/connect/refundWrites.d.ts.map +1 -0
- package/dist/component/connect/refundWrites.js +56 -0
- package/dist/component/connect/refundWrites.js.map +1 -0
- package/dist/component/earnings/triggers.d.ts +46 -0
- package/dist/component/earnings/triggers.d.ts.map +1 -1
- package/dist/component/processingCostReconciliation/rollback.d.ts +1 -1
- package/dist/component/refundHistory/originalSeller.d.ts +1 -1
- package/dist/component/refundHistory/originalSeller.d.ts.map +1 -1
- package/dist/component/refundHistory/originalSeller.js.map +1 -1
- package/dist/component/refundSync/helpers.d.ts +43 -0
- package/dist/component/refundSync/helpers.d.ts.map +1 -0
- package/dist/component/refundSync/helpers.js +71 -0
- package/dist/component/refundSync/helpers.js.map +1 -0
- package/dist/component/refundSync/mutations.d.ts +56 -0
- package/dist/component/refundSync/mutations.d.ts.map +1 -0
- package/dist/component/refundSync/mutations.js +113 -0
- package/dist/component/refundSync/mutations.js.map +1 -0
- package/dist/component/refundSync/queries.d.ts +12 -0
- package/dist/component/refundSync/queries.d.ts.map +1 -0
- package/dist/component/refundSync/queries.js +10 -0
- package/dist/component/refundSync/queries.js.map +1 -0
- package/dist/component/refundSync/routing.d.ts +8 -0
- package/dist/component/refundSync/routing.d.ts.map +1 -0
- package/dist/component/refundSync/routing.js +42 -0
- package/dist/component/refundSync/routing.js.map +1 -0
- package/dist/component/refundSync/schema.d.ts +25 -0
- package/dist/component/refundSync/schema.d.ts.map +1 -0
- package/dist/component/refundSync/schema.js +15 -0
- package/dist/component/refundSync/schema.js.map +1 -0
- package/dist/component/refundSync/validators.d.ts +164 -0
- package/dist/component/refundSync/validators.d.ts.map +1 -0
- package/dist/component/refundSync/validators.js +32 -0
- package/dist/component/refundSync/validators.js.map +1 -0
- package/dist/component/schema.d.ts +23 -0
- package/dist/component/schema.js +2 -0
- package/dist/component/schema.js.map +1 -1
- package/docs/refund-context.md +82 -0
- package/package.json +1 -1
- package/src/client/connect/refundSync.test.ts +239 -0
- package/src/client/connect/refundSync.transport.test.ts +396 -0
- package/src/client/connect/refundSync.ts +125 -0
- package/src/client/connect/refundSyncValidation.ts +120 -0
- package/src/client/index.ts +34 -6
- package/src/client/types/triggers.ts +3 -1
- package/src/client/webhooks/helpers.ts +1 -0
- package/src/client/webhooks/refund-reconciliation.test.ts +320 -0
- package/src/client/webhooks/refundReconciliation.ts +80 -0
- package/src/client/webhooks/refundReconciliationValidators.ts +15 -0
- package/src/component/_generated/api.ts +12 -0
- package/src/component/_generated/component.ts +100 -0
- package/src/component/connect/mutations.ts +2 -67
- package/src/component/connect/refundWrites.ts +76 -0
- package/src/component/refundHistory/originalSeller.ts +4 -1
- package/src/component/refundSync/helpers.ts +99 -0
- package/src/component/refundSync/mutations.ts +131 -0
- package/src/component/refundSync/queries.ts +10 -0
- package/src/component/refundSync/refund-sync.test.ts +255 -0
- package/src/component/refundSync/routing.ts +55 -0
- package/src/component/refundSync/schema.ts +19 -0
- package/src/component/refundSync/validators.ts +35 -0
- package/src/component/schema.ts +2 -0
|
@@ -0,0 +1,396 @@
|
|
|
1
|
+
// @vitest-environment edge-runtime
|
|
2
|
+
import Stripe from "stripe";
|
|
3
|
+
import { convexTest } from "convex-test";
|
|
4
|
+
import { componentsGeneric, defineSchema } from "convex/server";
|
|
5
|
+
import { expect, it } from "vitest";
|
|
6
|
+
import schema from "../../component/schema.js";
|
|
7
|
+
import { BetterStripe } from "../index.js";
|
|
8
|
+
import { prepareRefundSync } from "./refundSync.js";
|
|
9
|
+
import { componentRef } from "../webhooks/helpers.js";
|
|
10
|
+
import { getStripeClient, type Component, type RunCtx } from "../helpers.js";
|
|
11
|
+
|
|
12
|
+
const modules = import.meta.glob("../../component/**/*.*s");
|
|
13
|
+
const component = componentsGeneric().betterStripe as unknown as Component;
|
|
14
|
+
const options = {
|
|
15
|
+
stripeRefundId: "re_original",
|
|
16
|
+
scope: { type: "platform" as const },
|
|
17
|
+
};
|
|
18
|
+
function refund() {
|
|
19
|
+
return {
|
|
20
|
+
id: "re_original",
|
|
21
|
+
object: "refund",
|
|
22
|
+
amount: 250,
|
|
23
|
+
currency: "usd",
|
|
24
|
+
payment_intent: "pi_original",
|
|
25
|
+
charge: "ch_original",
|
|
26
|
+
status: "succeeded",
|
|
27
|
+
reason: null,
|
|
28
|
+
metadata: { betterStripeRefundCommand: "original-command" },
|
|
29
|
+
};
|
|
30
|
+
}
|
|
31
|
+
function fixture() {
|
|
32
|
+
const t = convexTest(defineSchema({}), {
|
|
33
|
+
"./_generated/server.ts": () =>
|
|
34
|
+
import("../../component/_generated/server.js"),
|
|
35
|
+
});
|
|
36
|
+
t.registerComponent("betterStripe", schema, modules);
|
|
37
|
+
const key = `sk_test_refund_sync_transport_${crypto.randomUUID()}`;
|
|
38
|
+
const sdk = new BetterStripe(component, { STRIPE_SECRET_KEY: key });
|
|
39
|
+
const stripe = getStripeClient(key, sdk.stripeApiVersion);
|
|
40
|
+
const calls: {
|
|
41
|
+
path: string;
|
|
42
|
+
method: string;
|
|
43
|
+
account: string | undefined;
|
|
44
|
+
version: string;
|
|
45
|
+
body: string;
|
|
46
|
+
}[] = [];
|
|
47
|
+
let response: object = refund();
|
|
48
|
+
let code = 200;
|
|
49
|
+
let charge = {
|
|
50
|
+
id: "ch_original",
|
|
51
|
+
object: "charge",
|
|
52
|
+
payment_intent: "pi_original",
|
|
53
|
+
currency: "usd",
|
|
54
|
+
amount: 1000,
|
|
55
|
+
amount_captured: 1000,
|
|
56
|
+
transfer_data: { destination: "acct_original" },
|
|
57
|
+
};
|
|
58
|
+
// Replace only the SDK HTTP slot: actual Stripe request paths, headers and parsing execute.
|
|
59
|
+
const slot = stripe as unknown as {
|
|
60
|
+
_setApiField: (key: string, value: unknown) => void;
|
|
61
|
+
};
|
|
62
|
+
slot._setApiField("maxNetworkRetries", 0);
|
|
63
|
+
slot._setApiField("httpClient", {
|
|
64
|
+
getClientName: () => "refund-sync-test",
|
|
65
|
+
makeRequest: async (
|
|
66
|
+
...[, , path, method, headers, body]: Parameters<
|
|
67
|
+
ReturnType<typeof Stripe.createNodeHttpClient>["makeRequest"]
|
|
68
|
+
>
|
|
69
|
+
) => {
|
|
70
|
+
calls.push({
|
|
71
|
+
path,
|
|
72
|
+
method,
|
|
73
|
+
account: headers["Stripe-Account"] as string | undefined,
|
|
74
|
+
version: String(headers["Stripe-Version"]),
|
|
75
|
+
body: String(body),
|
|
76
|
+
});
|
|
77
|
+
return {
|
|
78
|
+
getStatusCode: () => code,
|
|
79
|
+
getHeaders: () => ({}),
|
|
80
|
+
getRawResponse: () => ({}),
|
|
81
|
+
toJSON: async () =>
|
|
82
|
+
structuredClone(path.startsWith("/v1/charges/") ? charge : response),
|
|
83
|
+
toStream: () => {
|
|
84
|
+
throw new Error("Unexpected stream");
|
|
85
|
+
},
|
|
86
|
+
};
|
|
87
|
+
},
|
|
88
|
+
});
|
|
89
|
+
const ctx = { runQuery: t.query, runMutation: t.mutation } as RunCtx;
|
|
90
|
+
return {
|
|
91
|
+
t,
|
|
92
|
+
sdk,
|
|
93
|
+
stripe,
|
|
94
|
+
ctx,
|
|
95
|
+
calls,
|
|
96
|
+
set: (value: object, status = 200) => {
|
|
97
|
+
response = value;
|
|
98
|
+
code = status;
|
|
99
|
+
},
|
|
100
|
+
setCharge: (value: typeof charge) => {
|
|
101
|
+
charge = value;
|
|
102
|
+
},
|
|
103
|
+
run: () => sdk.syncRefundFromStripe(ctx, options),
|
|
104
|
+
row: () => sdk.getRefundByStripeId(ctx, { stripeRefundId: "re_original" }),
|
|
105
|
+
};
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
it.each(["platform", "connected"] as const)(
|
|
109
|
+
"serializes explicit %s API scope without treating it as merchant authority",
|
|
110
|
+
async (type) => {
|
|
111
|
+
const f = fixture();
|
|
112
|
+
f.set({ ...refund(), metadata: { accountId: "acct_metadata_guessed" } });
|
|
113
|
+
const scope =
|
|
114
|
+
type === "platform" ? { type } : { type, accountId: "acct_api_realm" };
|
|
115
|
+
expect(
|
|
116
|
+
await f.sdk.syncRefundFromStripe(f.ctx, { ...options, scope }),
|
|
117
|
+
).toMatchObject({ status: "accepted", changed: true });
|
|
118
|
+
expect(f.calls).toEqual([
|
|
119
|
+
{
|
|
120
|
+
path: "/v1/refunds/re_original",
|
|
121
|
+
method: "GET",
|
|
122
|
+
account: type === "platform" ? undefined : "acct_api_realm",
|
|
123
|
+
version: f.sdk.stripeApiVersion,
|
|
124
|
+
body: "",
|
|
125
|
+
},
|
|
126
|
+
]);
|
|
127
|
+
expect((await f.row())?.accountId).toBeUndefined();
|
|
128
|
+
},
|
|
129
|
+
);
|
|
130
|
+
|
|
131
|
+
it("validates expanded original references returned through the actual HTTP parser", async () => {
|
|
132
|
+
const f = fixture();
|
|
133
|
+
f.set({
|
|
134
|
+
...refund(),
|
|
135
|
+
payment_intent: { id: "pi_original", object: "payment_intent" },
|
|
136
|
+
charge: { id: "ch_original", object: "charge" },
|
|
137
|
+
});
|
|
138
|
+
expect(await f.run()).toMatchObject({
|
|
139
|
+
status: "accepted",
|
|
140
|
+
refund: {
|
|
141
|
+
stripePaymentIntentId: "pi_original",
|
|
142
|
+
stripeChargeId: "ch_original",
|
|
143
|
+
},
|
|
144
|
+
});
|
|
145
|
+
});
|
|
146
|
+
|
|
147
|
+
it.each([
|
|
148
|
+
{ object: "charge" },
|
|
149
|
+
{ id: "re_foreign" },
|
|
150
|
+
{ amount: Number.MAX_SAFE_INTEGER + 1 },
|
|
151
|
+
{ currency: "USD" },
|
|
152
|
+
{ status: "invented" },
|
|
153
|
+
{ reason: "invented" },
|
|
154
|
+
{ metadata: { private: 123 } },
|
|
155
|
+
{ payment_intent: { id: "pi_original" } },
|
|
156
|
+
{ charge: { id: "ch_original", object: "payment_intent" } },
|
|
157
|
+
])(
|
|
158
|
+
"holds malformed current HTTP observation %j without accepting a financial row",
|
|
159
|
+
async (patch) => {
|
|
160
|
+
const f = fixture();
|
|
161
|
+
f.set({ ...refund(), ...patch });
|
|
162
|
+
await expect(f.run()).rejects.toThrow();
|
|
163
|
+
expect(await f.row()).toBeNull();
|
|
164
|
+
expect(f.calls).toHaveLength(1);
|
|
165
|
+
},
|
|
166
|
+
);
|
|
167
|
+
|
|
168
|
+
it("propagates provider HTTP failure with no snapshot fallback and permits a later fresh read", async () => {
|
|
169
|
+
const f = fixture();
|
|
170
|
+
f.set(
|
|
171
|
+
{ error: { type: "api_error", message: "Current refund unavailable" } },
|
|
172
|
+
503,
|
|
173
|
+
);
|
|
174
|
+
await expect(f.run()).rejects.toThrow("Current refund unavailable");
|
|
175
|
+
expect(await f.row()).toBeNull();
|
|
176
|
+
f.set(refund());
|
|
177
|
+
expect(await f.run()).toMatchObject({ status: "accepted", generation: 2 });
|
|
178
|
+
expect(f.calls.every((call) => call.method === "GET")).toBe(true);
|
|
179
|
+
});
|
|
180
|
+
|
|
181
|
+
it("uses original charge destination proof instead of a mutable payment destination", async () => {
|
|
182
|
+
const f = fixture();
|
|
183
|
+
await f.t.mutation(component.connect.mutations.upsertPayment, {
|
|
184
|
+
stripePaymentIntentId: "pi_original",
|
|
185
|
+
userId: "original-buyer",
|
|
186
|
+
amount: 1000,
|
|
187
|
+
currency: "usd",
|
|
188
|
+
status: "succeeded",
|
|
189
|
+
destinationAccountId: "acct_replacement",
|
|
190
|
+
});
|
|
191
|
+
expect(await f.run()).toMatchObject({
|
|
192
|
+
status: "accepted",
|
|
193
|
+
refund: { accountId: "acct_original" },
|
|
194
|
+
});
|
|
195
|
+
expect(f.calls.map((call) => call.path)).toEqual([
|
|
196
|
+
"/v1/refunds/re_original",
|
|
197
|
+
"/v1/charges/ch_original",
|
|
198
|
+
]);
|
|
199
|
+
expect(
|
|
200
|
+
f.calls.every(
|
|
201
|
+
(call) => call.account === undefined && call.method === "GET",
|
|
202
|
+
),
|
|
203
|
+
).toBe(true);
|
|
204
|
+
});
|
|
205
|
+
|
|
206
|
+
it("holds explicit original merchant disagreement instead of remapping an old refund", async () => {
|
|
207
|
+
const f = fixture();
|
|
208
|
+
await f.t.mutation(component.connect.mutations.upsertRefund, {
|
|
209
|
+
stripeRefundId: "re_original",
|
|
210
|
+
stripePaymentIntentId: "pi_original",
|
|
211
|
+
stripeChargeId: "ch_original",
|
|
212
|
+
accountId: "acct_other_original",
|
|
213
|
+
amount: 250,
|
|
214
|
+
currency: "usd",
|
|
215
|
+
status: "pending",
|
|
216
|
+
});
|
|
217
|
+
await expect(f.run()).rejects.toThrow("Original refund identity");
|
|
218
|
+
expect(await f.row()).toMatchObject({
|
|
219
|
+
status: "pending",
|
|
220
|
+
accountId: "acct_other_original",
|
|
221
|
+
});
|
|
222
|
+
});
|
|
223
|
+
|
|
224
|
+
it("uses the existing immutable allocation seller proof without requiring an unrelated charge GET", async () => {
|
|
225
|
+
const f = fixture();
|
|
226
|
+
await f.t.mutation(
|
|
227
|
+
component.settlement.mutations.reserveSettlementAllocation,
|
|
228
|
+
{
|
|
229
|
+
sourceChargeId: "ch_original",
|
|
230
|
+
paymentIntentId: "pi_original",
|
|
231
|
+
gross: 1000,
|
|
232
|
+
currency: "usd",
|
|
233
|
+
processingFee: 0,
|
|
234
|
+
platformNet: 100,
|
|
235
|
+
transfers: [
|
|
236
|
+
{ destinationAccountId: "acct_original", role: "store", amount: 800 },
|
|
237
|
+
{
|
|
238
|
+
destinationAccountId: "acct_affiliate",
|
|
239
|
+
role: "affiliate",
|
|
240
|
+
amount: 100,
|
|
241
|
+
},
|
|
242
|
+
],
|
|
243
|
+
},
|
|
244
|
+
);
|
|
245
|
+
expect(await f.run()).toMatchObject({
|
|
246
|
+
status: "accepted",
|
|
247
|
+
refund: { accountId: "acct_original" },
|
|
248
|
+
});
|
|
249
|
+
expect(f.calls.map((call) => call.path)).toEqual(["/v1/refunds/re_original"]);
|
|
250
|
+
});
|
|
251
|
+
|
|
252
|
+
it("preserves an accepted commit when only its response is lost, then observes it without a refund write request", async () => {
|
|
253
|
+
const f = fixture();
|
|
254
|
+
let isLost = false;
|
|
255
|
+
const context: RunCtx = {
|
|
256
|
+
runQuery: f.ctx.runQuery,
|
|
257
|
+
runMutation: async (ref, ...args) => {
|
|
258
|
+
const result = await f.ctx.runMutation!(ref, ...args);
|
|
259
|
+
const path = (ref as Record<symbol, string>)[
|
|
260
|
+
Symbol.for("toReferencePath")
|
|
261
|
+
];
|
|
262
|
+
if (!isLost && path.endsWith("refundSync/mutations/finish")) {
|
|
263
|
+
isLost = true;
|
|
264
|
+
throw new Error("Commit response lost");
|
|
265
|
+
}
|
|
266
|
+
return result;
|
|
267
|
+
},
|
|
268
|
+
};
|
|
269
|
+
await expect(f.sdk.syncRefundFromStripe(context, options)).rejects.toThrow(
|
|
270
|
+
"Commit response lost",
|
|
271
|
+
);
|
|
272
|
+
expect(await f.row()).toMatchObject({ status: "succeeded", amount: 250 });
|
|
273
|
+
expect(await f.run()).toMatchObject({
|
|
274
|
+
status: "accepted",
|
|
275
|
+
changed: false,
|
|
276
|
+
generation: 2,
|
|
277
|
+
});
|
|
278
|
+
expect(f.calls).toHaveLength(2);
|
|
279
|
+
expect(f.calls.every((call) => call.method === "GET")).toBe(true);
|
|
280
|
+
});
|
|
281
|
+
|
|
282
|
+
it("observes an expired uncaptured authorization release without importing captured-funds eligibility", async () => {
|
|
283
|
+
const f = fixture();
|
|
284
|
+
await f.t.mutation(component.connect.mutations.upsertPayment, {
|
|
285
|
+
stripePaymentIntentId: "pi_original",
|
|
286
|
+
userId: "buyer",
|
|
287
|
+
amount: 1000,
|
|
288
|
+
currency: "usd",
|
|
289
|
+
status: "succeeded",
|
|
290
|
+
destinationAccountId: "acct_original",
|
|
291
|
+
});
|
|
292
|
+
f.set({ ...refund(), reason: "expired_uncaptured_charge" });
|
|
293
|
+
f.setCharge({
|
|
294
|
+
id: "ch_original",
|
|
295
|
+
object: "charge",
|
|
296
|
+
payment_intent: "pi_original",
|
|
297
|
+
currency: "usd",
|
|
298
|
+
amount: 1000,
|
|
299
|
+
amount_captured: 0,
|
|
300
|
+
transfer_data: { destination: "acct_original" },
|
|
301
|
+
});
|
|
302
|
+
expect(await f.run()).toMatchObject({
|
|
303
|
+
status: "accepted",
|
|
304
|
+
refund: { reason: "expired_uncaptured_charge" },
|
|
305
|
+
});
|
|
306
|
+
});
|
|
307
|
+
|
|
308
|
+
it("rechecks original seller routing inside the accepting transaction after the provider read", async () => {
|
|
309
|
+
const f = fixture();
|
|
310
|
+
const observation = await prepareRefundSync(
|
|
311
|
+
f.stripe,
|
|
312
|
+
component,
|
|
313
|
+
f.ctx,
|
|
314
|
+
options,
|
|
315
|
+
);
|
|
316
|
+
await f.t.mutation(
|
|
317
|
+
component.settlement.mutations.reserveSettlementAllocation,
|
|
318
|
+
{
|
|
319
|
+
sourceChargeId: "ch_original",
|
|
320
|
+
paymentIntentId: "pi_original",
|
|
321
|
+
gross: 1000,
|
|
322
|
+
currency: "usd",
|
|
323
|
+
processingFee: 0,
|
|
324
|
+
platformNet: 100,
|
|
325
|
+
transfers: [
|
|
326
|
+
{
|
|
327
|
+
destinationAccountId: "acct_different_original",
|
|
328
|
+
role: "store",
|
|
329
|
+
amount: 900,
|
|
330
|
+
},
|
|
331
|
+
],
|
|
332
|
+
},
|
|
333
|
+
);
|
|
334
|
+
await expect(
|
|
335
|
+
f.t.mutation(
|
|
336
|
+
componentRef(component, "refundSync/mutations/finish"),
|
|
337
|
+
observation,
|
|
338
|
+
),
|
|
339
|
+
).rejects.toThrow("Original refund merchant");
|
|
340
|
+
expect(await f.row()).toBeNull();
|
|
341
|
+
expect(f.calls.map((call) => call.method)).toEqual(["GET"]);
|
|
342
|
+
});
|
|
343
|
+
|
|
344
|
+
it("rolls back the accepting claim, refund and cumulative payment together if the host transaction aborts", async () => {
|
|
345
|
+
const f = fixture();
|
|
346
|
+
await f.t.mutation(component.connect.mutations.upsertPayment, {
|
|
347
|
+
stripePaymentIntentId: "pi_original",
|
|
348
|
+
userId: "buyer",
|
|
349
|
+
amount: 1000,
|
|
350
|
+
currency: "usd",
|
|
351
|
+
status: "succeeded",
|
|
352
|
+
});
|
|
353
|
+
await f.t.mutation(component.connect.mutations.upsertRefund, {
|
|
354
|
+
stripeRefundId: "re_original",
|
|
355
|
+
stripePaymentIntentId: "pi_original",
|
|
356
|
+
stripeChargeId: "ch_original",
|
|
357
|
+
amount: 250,
|
|
358
|
+
currency: "usd",
|
|
359
|
+
status: "failed",
|
|
360
|
+
});
|
|
361
|
+
const observation = await prepareRefundSync(
|
|
362
|
+
f.stripe,
|
|
363
|
+
component,
|
|
364
|
+
f.ctx,
|
|
365
|
+
options,
|
|
366
|
+
);
|
|
367
|
+
await expect(
|
|
368
|
+
f.t.mutation(async (ctx) => {
|
|
369
|
+
const accepted: unknown = await ctx.runMutation(
|
|
370
|
+
componentRef(component, "refundSync/mutations/finish"),
|
|
371
|
+
observation,
|
|
372
|
+
);
|
|
373
|
+
expect(accepted).toMatchObject({ status: "accepted", changed: true });
|
|
374
|
+
throw new Error("Injected host transaction abort after acceptance");
|
|
375
|
+
}),
|
|
376
|
+
).rejects.toThrow("Injected host transaction abort");
|
|
377
|
+
expect(await f.row()).toMatchObject({ status: "failed" });
|
|
378
|
+
expect(
|
|
379
|
+
await f.t.query(component.connect.queries.getPaymentByStripeId, {
|
|
380
|
+
stripePaymentIntentId: "pi_original",
|
|
381
|
+
}),
|
|
382
|
+
).toMatchObject({ refundedAmount: 0 });
|
|
383
|
+
// Reusing the same prepared generation is still a first acceptance after rollback.
|
|
384
|
+
expect(
|
|
385
|
+
await f.t.mutation(
|
|
386
|
+
componentRef(component, "refundSync/mutations/finish"),
|
|
387
|
+
observation,
|
|
388
|
+
),
|
|
389
|
+
).toMatchObject({ status: "accepted", changed: true });
|
|
390
|
+
expect(
|
|
391
|
+
await f.t.query(component.connect.queries.getPaymentByStripeId, {
|
|
392
|
+
stripePaymentIntentId: "pi_original",
|
|
393
|
+
}),
|
|
394
|
+
).toMatchObject({ refundedAmount: 250 });
|
|
395
|
+
expect(f.calls.map((call) => call.method)).toEqual(["GET"]);
|
|
396
|
+
});
|
|
@@ -0,0 +1,125 @@
|
|
|
1
|
+
import type Stripe from "stripe";
|
|
2
|
+
import type { Infer } from "convex/values";
|
|
3
|
+
import type { Component, RunCtx } from "../helpers.js";
|
|
4
|
+
import { runMutationOrThrow } from "../helpers.js";
|
|
5
|
+
import { componentRef } from "../webhooks/helpers.js";
|
|
6
|
+
import { validateIdentity } from "../../component/refundSync/helpers.js";
|
|
7
|
+
import type {
|
|
8
|
+
result,
|
|
9
|
+
routingResult,
|
|
10
|
+
} from "../../component/refundSync/validators.js";
|
|
11
|
+
import {
|
|
12
|
+
refundApiContext,
|
|
13
|
+
refundSnapshot,
|
|
14
|
+
refundChargeMerchant,
|
|
15
|
+
type RefundSyncScope,
|
|
16
|
+
} from "./refundSyncValidation.js";
|
|
17
|
+
|
|
18
|
+
export type RefundSyncOptions = {
|
|
19
|
+
stripeRefundId: string;
|
|
20
|
+
scope: RefundSyncScope;
|
|
21
|
+
};
|
|
22
|
+
export type RefundSyncResult = Infer<typeof result>;
|
|
23
|
+
export type PreparedRefundSync = Awaited<ReturnType<typeof prepareRefundSync>>;
|
|
24
|
+
|
|
25
|
+
async function markUnknown(
|
|
26
|
+
component: Component,
|
|
27
|
+
ctx: RunCtx,
|
|
28
|
+
observation: {
|
|
29
|
+
stripeRefundId: string;
|
|
30
|
+
apiContext: string;
|
|
31
|
+
generation: number;
|
|
32
|
+
},
|
|
33
|
+
) {
|
|
34
|
+
await runMutationOrThrow(
|
|
35
|
+
ctx,
|
|
36
|
+
componentRef(component, "refundSync/mutations/markUnknown"),
|
|
37
|
+
observation,
|
|
38
|
+
);
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/** Internal preparation for a future transactional host callback; no refund write yet. */
|
|
42
|
+
export async function prepareRefundSync(
|
|
43
|
+
stripe: Stripe,
|
|
44
|
+
component: Component,
|
|
45
|
+
ctx: RunCtx,
|
|
46
|
+
opts: RefundSyncOptions,
|
|
47
|
+
) {
|
|
48
|
+
const identity = {
|
|
49
|
+
stripeRefundId: opts?.stripeRefundId,
|
|
50
|
+
apiContext: refundApiContext(opts?.scope),
|
|
51
|
+
};
|
|
52
|
+
validateIdentity(identity);
|
|
53
|
+
if (!ctx.runMutation || !ctx.runQuery)
|
|
54
|
+
throw new Error(
|
|
55
|
+
"Refund synchronization requires runMutation and runQuery.",
|
|
56
|
+
);
|
|
57
|
+
const generation = (await runMutationOrThrow(
|
|
58
|
+
ctx,
|
|
59
|
+
componentRef(component, "refundSync/mutations/begin"),
|
|
60
|
+
identity,
|
|
61
|
+
)) as number;
|
|
62
|
+
try {
|
|
63
|
+
const request =
|
|
64
|
+
identity.apiContext === "platform"
|
|
65
|
+
? {}
|
|
66
|
+
: { stripeAccount: identity.apiContext };
|
|
67
|
+
const refund = refundSnapshot(
|
|
68
|
+
await stripe.refunds.retrieve(identity.stripeRefundId, {}, request),
|
|
69
|
+
identity.stripeRefundId,
|
|
70
|
+
);
|
|
71
|
+
const routing = (await ctx.runQuery(
|
|
72
|
+
componentRef(component, "refundSync/queries/routing"),
|
|
73
|
+
{
|
|
74
|
+
stripeRefundId: refund.stripeRefundId,
|
|
75
|
+
stripePaymentIntentId: refund.stripePaymentIntentId,
|
|
76
|
+
stripeChargeId: refund.stripeChargeId,
|
|
77
|
+
currency: refund.currency,
|
|
78
|
+
},
|
|
79
|
+
)) as Infer<typeof routingResult>;
|
|
80
|
+
if (routing.status === "held")
|
|
81
|
+
throw new Error(
|
|
82
|
+
"Original refund merchant proof is ambiguous or contradictory.",
|
|
83
|
+
);
|
|
84
|
+
const accountId =
|
|
85
|
+
routing.merchantAccount ??
|
|
86
|
+
(routing.requiresChargeProof
|
|
87
|
+
? refundChargeMerchant(
|
|
88
|
+
await stripe.charges.retrieve(refund.stripeChargeId, {}, request),
|
|
89
|
+
refund,
|
|
90
|
+
)
|
|
91
|
+
: undefined);
|
|
92
|
+
return {
|
|
93
|
+
...identity,
|
|
94
|
+
generation,
|
|
95
|
+
refund: { ...refund, ...(accountId === undefined ? {} : { accountId }) },
|
|
96
|
+
};
|
|
97
|
+
} catch (error) {
|
|
98
|
+
await markUnknown(component, ctx, { ...identity, generation });
|
|
99
|
+
throw error;
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/** Host-authorized provider read plus generation-qualified, atomic existing refund synchronization. */
|
|
104
|
+
export async function syncRefundFromStripe(
|
|
105
|
+
stripe: Stripe,
|
|
106
|
+
component: Component,
|
|
107
|
+
ctx: RunCtx,
|
|
108
|
+
opts: RefundSyncOptions,
|
|
109
|
+
): Promise<RefundSyncResult> {
|
|
110
|
+
const observation = await prepareRefundSync(stripe, component, ctx, opts);
|
|
111
|
+
try {
|
|
112
|
+
return (await runMutationOrThrow(
|
|
113
|
+
ctx,
|
|
114
|
+
componentRef(component, "refundSync/mutations/finish"),
|
|
115
|
+
observation,
|
|
116
|
+
)) as RefundSyncResult;
|
|
117
|
+
} catch (error) {
|
|
118
|
+
await markUnknown(component, ctx, {
|
|
119
|
+
stripeRefundId: observation.stripeRefundId,
|
|
120
|
+
apiContext: observation.apiContext,
|
|
121
|
+
generation: observation.generation,
|
|
122
|
+
});
|
|
123
|
+
throw error;
|
|
124
|
+
}
|
|
125
|
+
}
|
|
@@ -0,0 +1,120 @@
|
|
|
1
|
+
import type Stripe from "stripe";
|
|
2
|
+
import type { Infer } from "convex/values";
|
|
3
|
+
import type { snapshot } from "../../component/refundSync/validators.js";
|
|
4
|
+
import { validateSnapshot } from "../../component/refundSync/helpers.js";
|
|
5
|
+
|
|
6
|
+
export type RefundSyncScope =
|
|
7
|
+
{ type: "platform" } | { type: "connected"; accountId: string };
|
|
8
|
+
|
|
9
|
+
/** The host authorizes this API namespace; metadata never selects it. */
|
|
10
|
+
export function refundApiContext(scope: RefundSyncScope) {
|
|
11
|
+
if (scope?.type === "platform" && Object.keys(scope).length === 1)
|
|
12
|
+
return "platform";
|
|
13
|
+
if (
|
|
14
|
+
scope?.type === "connected" &&
|
|
15
|
+
Object.keys(scope).length === 2 &&
|
|
16
|
+
typeof scope.accountId === "string" &&
|
|
17
|
+
/^acct_[A-Za-z0-9_]{1,250}$/.test(scope.accountId)
|
|
18
|
+
)
|
|
19
|
+
return scope.accountId;
|
|
20
|
+
throw new Error("Refund synchronization scope must be explicit.");
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
function originalId(
|
|
24
|
+
value: string | { id: string; object: string } | null,
|
|
25
|
+
kind: "charge" | "payment_intent",
|
|
26
|
+
) {
|
|
27
|
+
if (typeof value === "string") return value;
|
|
28
|
+
if (value && value.object === kind && typeof value.id === "string")
|
|
29
|
+
return value.id;
|
|
30
|
+
throw new Error("Provider refund original payment identity is unavailable.");
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
function refundReason(
|
|
34
|
+
value: Stripe.Refund.Reason | null,
|
|
35
|
+
): Infer<typeof snapshot>["reason"] {
|
|
36
|
+
switch (value) {
|
|
37
|
+
case null:
|
|
38
|
+
return undefined;
|
|
39
|
+
case "duplicate":
|
|
40
|
+
return "duplicate";
|
|
41
|
+
case "fraudulent":
|
|
42
|
+
return "fraudulent";
|
|
43
|
+
case "requested_by_customer":
|
|
44
|
+
return "requested_by_customer";
|
|
45
|
+
case "expired_uncaptured_charge":
|
|
46
|
+
return "expired_uncaptured_charge";
|
|
47
|
+
default:
|
|
48
|
+
throw new Error("Provider refund reason is invalid.");
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/** A current provider observation can legitimately move back to requires_action. */
|
|
53
|
+
export function refundSnapshot(
|
|
54
|
+
r: Stripe.Refund,
|
|
55
|
+
stripeRefundId: string,
|
|
56
|
+
): Infer<typeof snapshot> {
|
|
57
|
+
if (!r || r.object !== "refund" || r.id !== stripeRefundId)
|
|
58
|
+
throw new Error("Provider refund identity does not match.");
|
|
59
|
+
if (
|
|
60
|
+
!["pending", "requires_action", "succeeded", "failed", "canceled"].includes(
|
|
61
|
+
r.status ?? "",
|
|
62
|
+
)
|
|
63
|
+
)
|
|
64
|
+
throw new Error("Provider refund status is unavailable.");
|
|
65
|
+
const reason = refundReason(r.reason);
|
|
66
|
+
if (r.failure_reason != null && typeof r.failure_reason !== "string")
|
|
67
|
+
throw new Error("Provider refund failure detail is invalid.");
|
|
68
|
+
const metadata = r.metadata === null ? {} : r.metadata;
|
|
69
|
+
if (
|
|
70
|
+
!metadata ||
|
|
71
|
+
typeof metadata !== "object" ||
|
|
72
|
+
Array.isArray(metadata) ||
|
|
73
|
+
Object.values(metadata).some((value) => typeof value !== "string")
|
|
74
|
+
)
|
|
75
|
+
throw new Error("Provider refund metadata is invalid.");
|
|
76
|
+
const row: Infer<typeof snapshot> = {
|
|
77
|
+
stripeRefundId: r.id,
|
|
78
|
+
stripePaymentIntentId: originalId(r.payment_intent, "payment_intent"),
|
|
79
|
+
stripeChargeId: originalId(r.charge, "charge"),
|
|
80
|
+
amount: r.amount,
|
|
81
|
+
currency: r.currency,
|
|
82
|
+
status: r.status as Infer<typeof snapshot>["status"],
|
|
83
|
+
...(reason === undefined ? {} : { reason }),
|
|
84
|
+
...(r.failure_reason == null ? {} : { failureReason: r.failure_reason }),
|
|
85
|
+
metadata,
|
|
86
|
+
};
|
|
87
|
+
validateSnapshot(row);
|
|
88
|
+
return row;
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
/** The charge's original destination is independent of the caller's API namespace. */
|
|
92
|
+
export function refundChargeMerchant(
|
|
93
|
+
charge: Stripe.Charge,
|
|
94
|
+
row: Infer<typeof snapshot>,
|
|
95
|
+
) {
|
|
96
|
+
if (
|
|
97
|
+
!charge ||
|
|
98
|
+
charge.object !== "charge" ||
|
|
99
|
+
charge.id !== row.stripeChargeId ||
|
|
100
|
+
originalId(charge.payment_intent, "payment_intent") !==
|
|
101
|
+
row.stripePaymentIntentId ||
|
|
102
|
+
charge.currency !== row.currency ||
|
|
103
|
+
!Number.isSafeInteger(charge.amount) ||
|
|
104
|
+
charge.amount < row.amount
|
|
105
|
+
)
|
|
106
|
+
throw new Error("Original refund charge proof does not match.");
|
|
107
|
+
const destination = charge.transfer_data?.destination;
|
|
108
|
+
const account =
|
|
109
|
+
typeof destination === "string"
|
|
110
|
+
? destination
|
|
111
|
+
: destination?.object === "account"
|
|
112
|
+
? destination.id
|
|
113
|
+
: undefined;
|
|
114
|
+
if (
|
|
115
|
+
typeof account !== "string" ||
|
|
116
|
+
!/^acct_[A-Za-z0-9_]{1,250}$/.test(account)
|
|
117
|
+
)
|
|
118
|
+
throw new Error("Original refund merchant cannot be qualified.");
|
|
119
|
+
return account;
|
|
120
|
+
}
|