@fantastic.dev/better-stripe 0.64.1 → 0.65.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 (45) hide show
  1. package/CHANGELOG.md +10 -0
  2. package/README.md +1 -1
  3. package/dist/client/connect/payoutLargeAdoptionTestHelpers.d.ts +32 -32
  4. package/dist/client/connect/payoutSyncTestHelpers.d.ts +16 -16
  5. package/dist/client/index.d.ts +1 -0
  6. package/dist/client/index.d.ts.map +1 -1
  7. package/dist/client/index.js.map +1 -1
  8. package/dist/client/recoveryWorkflow/provider.d.ts +3 -0
  9. package/dist/client/recoveryWorkflow/provider.d.ts.map +1 -1
  10. package/dist/client/recoveryWorkflow/provider.js +1 -1
  11. package/dist/client/recoveryWorkflow/provider.js.map +1 -1
  12. package/dist/client/settlement/authorization.d.ts +19 -0
  13. package/dist/client/settlement/authorization.d.ts.map +1 -0
  14. package/dist/client/settlement/authorization.fixture.d.ts +112 -0
  15. package/dist/client/settlement/authorization.fixture.d.ts.map +1 -0
  16. package/dist/client/settlement/authorization.fixture.js +178 -0
  17. package/dist/client/settlement/authorization.fixture.js.map +1 -0
  18. package/dist/client/settlement/authorization.js +28 -0
  19. package/dist/client/settlement/authorization.js.map +1 -0
  20. package/dist/client/settlement/execution.d.ts +2 -1
  21. package/dist/client/settlement/execution.d.ts.map +1 -1
  22. package/dist/client/settlement/execution.js +8 -4
  23. package/dist/client/settlement/execution.js.map +1 -1
  24. package/dist/client/settlement/settleSale.d.ts +3 -0
  25. package/dist/client/settlement/settleSale.d.ts.map +1 -1
  26. package/dist/client/settlement/settleSale.js +5 -2
  27. package/dist/client/settlement/settleSale.js.map +1 -1
  28. package/dist/client/usage/observationClient.d.ts +2 -2
  29. package/dist/client/usage/observationClient.d.ts.map +1 -1
  30. package/dist/component/balanceFunding/mutations.d.ts +27 -27
  31. package/dist/component/balanceFunding/queries.d.ts +1 -1
  32. package/dist/component/balanceFunding/stateHandlers.d.ts +8 -8
  33. package/dist/component/earnings/triggers.d.ts +16 -16
  34. package/dist/component/processingCostReconciliation/rollback.d.ts +1 -1
  35. package/dist/component/usage/allowance.fixtures.d.ts +16 -16
  36. package/docs/settlement.md +56 -0
  37. package/package.json +1 -1
  38. package/src/client/index.ts +4 -0
  39. package/src/client/recoveryWorkflow/provider.test.ts +149 -7
  40. package/src/client/recoveryWorkflow/provider.ts +10 -1
  41. package/src/client/settlement/authorization.fixture.ts +199 -0
  42. package/src/client/settlement/authorization.test.ts +160 -0
  43. package/src/client/settlement/authorization.ts +53 -0
  44. package/src/client/settlement/execution.ts +11 -4
  45. package/src/client/settlement/settleSale.ts +16 -2
@@ -0,0 +1,160 @@
1
+ // @vitest-environment edge-runtime
2
+ import { afterEach, expect, it, vi } from "vitest";
3
+ import { authorizationFixture } from "./authorization.fixture.js";
4
+ import type { SettlementAuthorizationContext } from "./authorization.js";
5
+
6
+ afterEach(() => vi.restoreAllMocks());
7
+
8
+ it("retains the public no-hook settlement and registered component ledger", async () => {
9
+ const f = await authorizationFixture();
10
+ expect(await f.settle()).toMatchObject({
11
+ status: "settled",
12
+ executedTransfers: [{ amount: 940 }],
13
+ });
14
+ expect(f.transfers).toHaveLength(1);
15
+ expect(await f.allocation()).toMatchObject({
16
+ sourceChargeId: "ch_authorize",
17
+ gross: 1000,
18
+ });
19
+ });
20
+
21
+ it("denies admission before an allocation or transfer when the host hook rejects", async () => {
22
+ const f = await authorizationFixture();
23
+ f.revoke();
24
+ await expect(
25
+ f.settle({ ...f.options, authorize: async () => f.authorize() }),
26
+ ).rejects.toThrow("Host settlement authorization denied");
27
+ expect(await f.allocation()).toBeNull();
28
+ expect(f.transfers).toHaveLength(0);
29
+ });
30
+
31
+ it("reauthorizes after provider source reads before admitting allocation", async () => {
32
+ const f = await authorizationFixture();
33
+ f.pauseRead("payment");
34
+ const pending = f.settle({
35
+ ...f.options,
36
+ authorize: async () => f.authorize(),
37
+ });
38
+ await f.reachedRead;
39
+ f.revoke();
40
+ f.release();
41
+ await expect(pending).rejects.toThrow("Host settlement authorization denied");
42
+ expect(await f.allocation()).toBeNull();
43
+ expect(f.transfers).toHaveLength(0);
44
+ });
45
+
46
+ it("reauthorizes after transfer reconciliation immediately before new money dispatch", async () => {
47
+ const f = await authorizationFixture();
48
+ f.pauseRead("history");
49
+ const pending = f.settle({
50
+ ...f.options,
51
+ authorize: async () => f.authorize(),
52
+ });
53
+ await f.reachedRead;
54
+ f.revoke();
55
+ f.release();
56
+ await expect(pending).rejects.toThrow("Host settlement authorization denied");
57
+ expect(f.transfers).toHaveLength(0);
58
+ expect(await f.allocation()).toMatchObject({ gross: 1000 });
59
+ });
60
+
61
+ it("stops later legs on denial and retries only missing legs under the frozen allocation", async () => {
62
+ const f = await authorizationFixture(true);
63
+ f.stopAfterFirst();
64
+ const contexts: SettlementAuthorizationContext[] = [];
65
+ const authorize = async (context: SettlementAuthorizationContext) => {
66
+ contexts.push(context);
67
+ f.authorize();
68
+ };
69
+ await expect(f.settle({ ...f.options, authorize })).rejects.toThrow(
70
+ "Host settlement authorization denied",
71
+ );
72
+ expect(f.transfers).toHaveLength(1);
73
+ f.allow();
74
+ await f.settle({
75
+ ...f.options,
76
+ allocation: {
77
+ ...f.options.allocation,
78
+ platformNet: 100,
79
+ transfers: [
80
+ { destinationAccountId: "acct_changed", role: "store", amount: 840 },
81
+ ],
82
+ },
83
+ authorize,
84
+ });
85
+ expect(f.transfers).toHaveLength(2);
86
+ expect(f.transfers.map((t) => t.destination)).toEqual([
87
+ "acct_creator",
88
+ "acct_other",
89
+ ]);
90
+ expect(
91
+ contexts
92
+ .filter((c) => c.phase === "transfer")
93
+ .map((c) => c.transfer.destinationAccountId),
94
+ ).toEqual(["acct_creator", "acct_other", "acct_other"]);
95
+ expect(
96
+ contexts
97
+ .filter((c) => c.phase === "reserve")
98
+ .map((c) => c.settlement.platformNet),
99
+ ).toEqual([0, 0]);
100
+ });
101
+
102
+ it("checks the actual saved foreign leg when another reservation wins after admission", async () => {
103
+ const f = await authorizationFixture();
104
+ const authorize = async (context: SettlementAuthorizationContext) => {
105
+ if (context.phase === "reserve") {
106
+ await f.reserve({
107
+ ...f.options.allocation,
108
+ transfers: [
109
+ { destinationAccountId: "acct_foreign", role: "store", amount: 940 },
110
+ ],
111
+ });
112
+ } else if (context.transfer.destinationAccountId !== "acct_creator") {
113
+ throw new Error("Host rejected actual foreign recipient");
114
+ }
115
+ };
116
+ await expect(f.settle({ ...f.options, authorize })).rejects.toThrow(
117
+ "Host rejected actual foreign recipient",
118
+ );
119
+ expect(f.transfers).toHaveLength(0);
120
+ expect(await f.allocation()).toMatchObject({
121
+ transfers: [{ destinationAccountId: "acct_foreign" }],
122
+ });
123
+ });
124
+
125
+ it("recovers known provider success without invoking another new-money hook or POST", async () => {
126
+ const f = await authorizationFixture();
127
+ f.failLedger();
128
+ const authorize = vi.fn(async () => {});
129
+ await expect(f.settle({ ...f.options, authorize })).rejects.toThrow(
130
+ "Synthetic ledger write failure",
131
+ );
132
+ expect(f.transfers).toHaveLength(1);
133
+ authorize.mockClear();
134
+ expect(await f.settle({ ...f.options, authorize })).toMatchObject({
135
+ status: "settled",
136
+ });
137
+ expect(f.transfers).toHaveLength(1);
138
+ expect(authorize.mock.calls).toHaveLength(1);
139
+ expect(authorize).toHaveBeenCalledWith(
140
+ expect.objectContaining({ phase: "reserve" }),
141
+ );
142
+ });
143
+
144
+ it("detaches authorization snapshots so callback mutation cannot change financial inputs", async () => {
145
+ const f = await authorizationFixture();
146
+ const authorize = async (context: SettlementAuthorizationContext) => {
147
+ Object.assign(context.settlement, { platformNet: 500 });
148
+ if (context.phase === "reserve")
149
+ Object.assign(context.settlement.transfers[0], { amount: 1 });
150
+ else
151
+ Object.assign(context.transfer, {
152
+ amount: 1,
153
+ destinationAccountId: "acct_foreign",
154
+ });
155
+ };
156
+ expect(await f.settle({ ...f.options, authorize })).toMatchObject({
157
+ platformNet: 0,
158
+ executedTransfers: [{ amount: 940, destinationAccountId: "acct_creator" }],
159
+ });
160
+ });
@@ -0,0 +1,53 @@
1
+ import type { SplitTransfer } from "../core/fees.js";
2
+ import type { ResolvedSettlement } from "./execution.js";
3
+
4
+ type Source = Readonly<Omit<ResolvedSettlement, "transfers">>;
5
+ export type SettlementAuthorizationContext =
6
+ | {
7
+ phase: "reserve";
8
+ settlement: Source & {
9
+ readonly transfers: readonly Readonly<SplitTransfer>[];
10
+ };
11
+ }
12
+ | {
13
+ phase: "transfer";
14
+ settlement: Source;
15
+ transfer: Readonly<SplitTransfer>;
16
+ };
17
+ /** Server-only check. Throw to deny; returning never changes the allocation. */
18
+ export type SettlementAuthorization = (
19
+ context: SettlementAuthorizationContext,
20
+ ) => Promise<void>;
21
+
22
+ /** Detached snapshots prevent host callbacks from modifying claimed economics. */
23
+ export async function authorizeSettlement(
24
+ authorize: SettlementAuthorization | undefined,
25
+ settlement: ResolvedSettlement,
26
+ transfer?: SplitTransfer,
27
+ ) {
28
+ if (!authorize) return;
29
+ const source = structuredClone({
30
+ sourceChargeId: settlement.sourceChargeId,
31
+ paymentIntentId: settlement.paymentIntentId,
32
+ sourceInvoiceId: settlement.sourceInvoiceId,
33
+ usageSource: settlement.usageSource,
34
+ creditSource: settlement.creditSource,
35
+ gross: settlement.gross,
36
+ currency: settlement.currency,
37
+ processingFee: settlement.processingFee,
38
+ platformNet: settlement.platformNet,
39
+ adjustmentAmount: settlement.adjustmentAmount,
40
+ paymentId: settlement.paymentId,
41
+ });
42
+ await authorize(
43
+ transfer
44
+ ? { phase: "transfer", settlement: source, transfer: { ...transfer } }
45
+ : {
46
+ phase: "reserve",
47
+ settlement: {
48
+ ...source,
49
+ transfers: structuredClone(settlement.transfers),
50
+ },
51
+ },
52
+ );
53
+ }
@@ -9,6 +9,10 @@ import type { SplitTransfer } from "../core/fees.js";
9
9
  import type { Component, RunCtx } from "../helpers.js";
10
10
  import { runMutationOrThrow } from "../helpers.js";
11
11
  import { componentRef } from "../webhooks/helpers.js";
12
+ import {
13
+ authorizeSettlement,
14
+ type SettlementAuthorization,
15
+ } from "./authorization.js";
12
16
  export type ResolvedSettlement = {
13
17
  sourceChargeId: string;
14
18
  paymentIntentId?: string;
@@ -65,6 +69,7 @@ export async function executeResolvedTransfers(
65
69
  component: Component,
66
70
  ctx: RunCtx,
67
71
  opts: ResolvedSettlement,
72
+ authorize?: SettlementAuthorization,
68
73
  ): Promise<SettlementResult> {
69
74
  const saved = (await runMutationOrThrow(
70
75
  ctx,
@@ -160,9 +165,10 @@ export async function executeResolvedTransfers(
160
165
  let transferId = recorded?.stripeTransferId;
161
166
  if (!transferId) {
162
167
  const recovered = matchingTransfer(provider, claim, leg);
163
- const transfer =
164
- recovered ??
165
- (await stripe.transfers.create(
168
+ let transfer = recovered;
169
+ if (!transfer) {
170
+ await authorizeSettlement(authorize, claim, leg);
171
+ transfer = await stripe.transfers.create(
166
172
  {
167
173
  amount: leg.amount,
168
174
  currency: claim.currency,
@@ -177,7 +183,8 @@ export async function executeResolvedTransfers(
177
183
  {
178
184
  idempotencyKey: `bs_split_${claim.sourceChargeId}_${leg.destinationAccountId}_${leg.role}`,
179
185
  },
180
- ));
186
+ );
187
+ }
181
188
  transferId = transfer.id;
182
189
  await recordSettlementTransfer(component, ctx, claim, leg, transfer);
183
190
  }
@@ -4,6 +4,10 @@ import type { Component, RunCtx } from "../helpers.js";
4
4
  import { componentRef } from "../webhooks/helpers.js";
5
5
  import { throwStripeError } from "../errors.js";
6
6
  import { getVerifiedSale, type VerifiedSaleOptions } from "./verifiedSale.js";
7
+ import {
8
+ authorizeSettlement,
9
+ type SettlementAuthorization,
10
+ } from "./authorization.js";
7
11
  import {
8
12
  executeResolvedTransfers,
9
13
  type SettlementResult,
@@ -19,6 +23,8 @@ export type SettleSaleOptions = VerifiedSaleOptions & {
19
23
  };
20
24
  paymentId?: string;
21
25
  onSettled?: (result: SettlementResult) => Promise<void>;
26
+ /** Reauthorize after source reads and immediately before each new transfer. */
27
+ authorize?: SettlementAuthorization;
22
28
  };
23
29
  export async function settleSale(
24
30
  stripe: Stripe,
@@ -47,13 +53,21 @@ export async function settleSale(
47
53
  "INVALID_CONFIGURATION",
48
54
  "Allocation must use verified payment currency, gross and actual processing cost.",
49
55
  );
50
- const result = await executeResolvedTransfers(stripe, component, ctx, {
56
+ const request = {
51
57
  ...opts.allocation,
52
58
  sourceChargeId: sale.chargeId,
53
59
  paymentIntentId: sale.paymentIntentId,
54
60
  sourceInvoiceId: sale.invoiceId,
55
61
  paymentId: opts.paymentId,
56
- });
62
+ };
63
+ await authorizeSettlement(opts.authorize, prior ?? request);
64
+ const result = await executeResolvedTransfers(
65
+ stripe,
66
+ component,
67
+ ctx,
68
+ request,
69
+ opts.authorize,
70
+ );
57
71
  await opts.onSettled?.(result);
58
72
  return result;
59
73
  }