@fantastic.dev/better-stripe 0.60.0 → 0.60.1
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 +6 -0
- package/README.md +3 -1
- package/dist/client/connect/payoutAdoptionTestHelpers.d.ts +26 -6
- package/dist/client/connect/payoutAdoptionTestHelpers.d.ts.map +1 -1
- package/dist/client/connect/payoutExecutionTestHelpers.d.ts +13 -3
- package/dist/client/connect/payoutExecutionTestHelpers.d.ts.map +1 -1
- package/dist/client/connect/payoutLargeAdoptionTestHelpers.d.ts +26 -6
- package/dist/client/connect/payoutLargeAdoptionTestHelpers.d.ts.map +1 -1
- package/dist/client/connect/payoutSyncTestHelpers.d.ts +13 -3
- package/dist/client/connect/payoutSyncTestHelpers.d.ts.map +1 -1
- package/dist/client/usage/creditCapacity.d.ts.map +1 -1
- package/dist/client/usage/creditCapacity.js +7 -1
- package/dist/client/usage/creditCapacity.js.map +1 -1
- package/dist/client/usage/creditClient.d.ts +3 -0
- package/dist/client/usage/creditClient.d.ts.map +1 -1
- package/dist/client/usage/creditDelivery.d.ts.map +1 -1
- package/dist/client/usage/creditDelivery.js +4 -1
- package/dist/client/usage/creditDelivery.js.map +1 -1
- package/dist/client/usage/creditLifecycle.d.ts.map +1 -1
- package/dist/client/usage/creditLifecycle.js +2 -1
- package/dist/client/usage/creditLifecycle.js.map +1 -1
- package/dist/client/usage/creditNative.d.ts +3 -0
- package/dist/client/usage/creditNative.d.ts.map +1 -1
- package/dist/client/usage/creditNative.js +3 -0
- package/dist/client/usage/creditNative.js.map +1 -1
- package/dist/client/usage/creditProvider.d.ts.map +1 -1
- package/dist/client/usage/creditProvider.js +2 -1
- package/dist/client/usage/creditProvider.js.map +1 -1
- package/dist/client/usage/creditRead.d.ts +1 -0
- package/dist/client/usage/creditRead.d.ts.map +1 -1
- package/dist/client/usage/creditReconciliation.d.ts.map +1 -1
- package/dist/client/usage/creditReconciliation.js +11 -3
- package/dist/client/usage/creditReconciliation.js.map +1 -1
- package/dist/client/usage/creditSettlement.fixtures.d.ts +1 -0
- package/dist/client/usage/creditSettlement.fixtures.d.ts.map +1 -1
- package/dist/client/usage/creditTransport.fixtures.d.ts +1 -0
- package/dist/client/usage/creditTransport.fixtures.d.ts.map +1 -1
- package/dist/client/usage/creditTransport.fixtures.js +2 -1
- package/dist/client/usage/creditTransport.fixtures.js.map +1 -1
- package/dist/client/usage/subscriptionCancellation.d.ts.map +1 -1
- package/dist/client/usage/subscriptionCancellation.js +3 -2
- package/dist/client/usage/subscriptionCancellation.js.map +1 -1
- package/dist/client/usage/subscriptionCheckout.d.ts.map +1 -1
- package/dist/client/usage/subscriptionCheckout.js +3 -2
- package/dist/client/usage/subscriptionCheckout.js.map +1 -1
- package/dist/client/usage/subscriptionLifecycle.d.ts +1 -0
- package/dist/client/usage/subscriptionLifecycle.d.ts.map +1 -1
- package/dist/client/usage/subscriptionLifecycle.js +3 -2
- package/dist/client/usage/subscriptionLifecycle.js.map +1 -1
- package/dist/client/usage/subscriptionProvider.d.ts +2 -0
- package/dist/client/usage/subscriptionProvider.d.ts.map +1 -1
- package/dist/client/usage/subscriptionProvider.js +9 -2
- package/dist/client/usage/subscriptionProvider.js.map +1 -1
- package/dist/component/_generated/component.d.ts +21 -0
- package/dist/component/_generated/component.d.ts.map +1 -1
- package/dist/component/earnings/triggers.d.ts +16 -6
- package/dist/component/earnings/triggers.d.ts.map +1 -1
- package/dist/component/schema.d.ts +13 -3
- package/dist/component/usage/allowance.fixtures.d.ts +4212 -0
- package/dist/component/usage/allowance.fixtures.d.ts.map +1 -0
- package/dist/component/usage/allowance.fixtures.js +67 -0
- package/dist/component/usage/allowance.fixtures.js.map +1 -0
- package/dist/component/usageCredits/accounting.fixtures.d.ts +4235 -0
- package/dist/component/usageCredits/accounting.fixtures.d.ts.map +1 -0
- package/dist/component/usageCredits/accounting.fixtures.js +89 -0
- package/dist/component/usageCredits/accounting.fixtures.js.map +1 -0
- package/dist/component/usageCredits/helpers.d.ts +7 -0
- package/dist/component/usageCredits/helpers.d.ts.map +1 -1
- package/dist/component/usageCredits/helpers.js +5 -0
- package/dist/component/usageCredits/helpers.js.map +1 -1
- package/dist/component/usageCredits/mutations.d.ts +6 -0
- package/dist/component/usageCredits/mutations.d.ts.map +1 -1
- package/dist/component/usageCredits/mutations.js +70 -7
- package/dist/component/usageCredits/mutations.js.map +1 -1
- package/dist/component/usageCredits/purchase.d.ts +1 -0
- package/dist/component/usageCredits/purchase.d.ts.map +1 -1
- package/dist/component/usageCredits/queries.d.ts +10 -0
- package/dist/component/usageCredits/queries.d.ts.map +1 -1
- package/dist/component/usageCredits/schema.d.ts +24 -4
- package/dist/component/usageCredits/schema.d.ts.map +1 -1
- package/dist/component/usageCredits/schema.js +4 -0
- package/dist/component/usageCredits/schema.js.map +1 -1
- package/dist/component/usageSubscriptions/history.d.ts.map +1 -1
- package/dist/component/usageSubscriptions/history.js +3 -1
- package/dist/component/usageSubscriptions/history.js.map +1 -1
- package/dist/component/usageSubscriptions/mutations.d.ts +5 -0
- package/dist/component/usageSubscriptions/mutations.d.ts.map +1 -1
- package/dist/component/usageSubscriptions/mutations.js +19 -0
- package/dist/component/usageSubscriptions/mutations.js.map +1 -1
- package/dist/component/usageSubscriptions/queries.d.ts +2 -0
- package/dist/component/usageSubscriptions/queries.d.ts.map +1 -1
- package/dist/component/usageSubscriptions/schema.d.ts +7 -2
- package/dist/component/usageSubscriptions/schema.d.ts.map +1 -1
- package/dist/component/usageSubscriptions/schema.js +1 -0
- package/dist/component/usageSubscriptions/schema.js.map +1 -1
- package/docs/README.md +2 -0
- package/docs/usage-credits.md +6 -1
- package/docs/usage-security.md +130 -0
- package/package.json +2 -1
- package/src/client/usage/creditBackingIsolation.test.ts +110 -0
- package/src/client/usage/creditCapacity.test.ts +80 -1
- package/src/client/usage/creditCapacity.ts +10 -1
- package/src/client/usage/creditDelivery.ts +4 -0
- package/src/client/usage/creditLifecycle.ts +2 -0
- package/src/client/usage/creditNative.ts +5 -0
- package/src/client/usage/creditProofBounds.test.ts +187 -0
- package/src/client/usage/creditProvider.test.ts +74 -0
- package/src/client/usage/creditProvider.ts +2 -0
- package/src/client/usage/creditReconciliation.ts +18 -3
- package/src/client/usage/creditTransport.fixtures.ts +2 -1
- package/src/client/usage/subscriptionCancellation.ts +3 -2
- package/src/client/usage/subscriptionCheckout.ts +7 -2
- package/src/client/usage/subscriptionClient.test.ts +60 -1
- package/src/client/usage/subscriptionLifecycle.ts +3 -2
- package/src/client/usage/subscriptionProvider.ts +27 -3
- package/src/component/_generated/component.ts +40 -1
- package/src/component/usage/allowance.fixtures.ts +77 -0
- package/src/component/usage/allowance.test.ts +3 -66
- package/src/component/usage/allowanceBounds.test.ts +79 -0
- package/src/component/usage/historyIsolation.test.ts +124 -0
- package/src/component/usageCredits/accounting.fixtures.ts +96 -0
- package/src/component/usageCredits/accounting.test.ts +176 -82
- package/src/component/usageCredits/freshness.test.ts +33 -0
- package/src/component/usageCredits/helpers.ts +8 -0
- package/src/component/usageCredits/mutations.ts +83 -5
- package/src/component/usageCredits/quotas.test.ts +63 -0
- package/src/component/usageCredits/schema.ts +10 -0
- package/src/component/usageSubscriptions/history.test.ts +57 -0
- package/src/component/usageSubscriptions/history.ts +3 -1
- package/src/component/usageSubscriptions/mutations.ts +23 -0
- package/src/component/usageSubscriptions/schema.ts +1 -0
|
@@ -0,0 +1,110 @@
|
|
|
1
|
+
import { afterEach, expect, it, vi } from "vitest";
|
|
2
|
+
import { BetterStripe } from "../index.js";
|
|
3
|
+
import type { RunCtx } from "../helpers.js";
|
|
4
|
+
import { componentRef } from "../webhooks/helpers.js";
|
|
5
|
+
import { creditFixture } from "./creditTransport.fixtures.js";
|
|
6
|
+
import { verifyCreditDelivery } from "./creditDelivery.js";
|
|
7
|
+
import type { Doc } from "../../component/_generated/dataModel.js";
|
|
8
|
+
import type { PreparedUsageRecord } from "./records.js";
|
|
9
|
+
afterEach(() => vi.useRealTimers());
|
|
10
|
+
it("rejects a foreign mapped Customer on native grant or summary during reconciliation and delivery", async () => {
|
|
11
|
+
for (const condition of ["grant", "summary"]) {
|
|
12
|
+
const f = creditFixture(),
|
|
13
|
+
client = new BetterStripe(f.component),
|
|
14
|
+
options = { stripeSecretKey: "sk_test_credit", httpClient: f.httpClient };
|
|
15
|
+
const view = await f.ready();
|
|
16
|
+
await f.t.action((ctx) =>
|
|
17
|
+
client.usage.purchaseCredits(ctx as RunCtx, f.purchase, options),
|
|
18
|
+
);
|
|
19
|
+
f.state.paid = true;
|
|
20
|
+
await f.t.action((ctx) =>
|
|
21
|
+
client.usage.observeCreditPurchase(ctx as RunCtx, f.purchase, options),
|
|
22
|
+
);
|
|
23
|
+
const event = {
|
|
24
|
+
scope: f.purchase.scope,
|
|
25
|
+
binding: f.purchase.binding,
|
|
26
|
+
sourceEventId: "work1",
|
|
27
|
+
quantity: "6",
|
|
28
|
+
occurredAt: 700,
|
|
29
|
+
},
|
|
30
|
+
subscription = view.bindings[0].subscription;
|
|
31
|
+
const reservation = await f.t.action((ctx) =>
|
|
32
|
+
client.usage.reserveCredits(ctx as RunCtx, { event, subscription }),
|
|
33
|
+
);
|
|
34
|
+
const receipt = await f.t.action((ctx) =>
|
|
35
|
+
client.usage.record(ctx as RunCtx, {
|
|
36
|
+
event,
|
|
37
|
+
subscription,
|
|
38
|
+
reservationId: reservation.reservationId,
|
|
39
|
+
}),
|
|
40
|
+
);
|
|
41
|
+
if (condition === "grant") f.state.grant!.customer = "cus_other";
|
|
42
|
+
else f.state.summaryCustomer = "cus_other";
|
|
43
|
+
await expect(
|
|
44
|
+
f.t.action(async (ctx) => {
|
|
45
|
+
const saved = (await ctx.runQuery(
|
|
46
|
+
componentRef(f.component, "usageDelivery/queries/snapshot"),
|
|
47
|
+
{ scope: event.scope, eventId: receipt.eventId },
|
|
48
|
+
)) as { event: Doc<"usageEvents"> };
|
|
49
|
+
await verifyCreditDelivery(
|
|
50
|
+
f.stripe,
|
|
51
|
+
f.component,
|
|
52
|
+
ctx as RunCtx,
|
|
53
|
+
saved.event,
|
|
54
|
+
JSON.parse(saved.event.recordJson) as PreparedUsageRecord,
|
|
55
|
+
);
|
|
56
|
+
}),
|
|
57
|
+
).rejects.toThrow(/scope|identity|reconciliation/i);
|
|
58
|
+
await expect(
|
|
59
|
+
f.t.action((ctx) =>
|
|
60
|
+
client.usage.reconcileCreditPurchase(
|
|
61
|
+
ctx as RunCtx,
|
|
62
|
+
f.purchase,
|
|
63
|
+
options,
|
|
64
|
+
),
|
|
65
|
+
),
|
|
66
|
+
).rejects.toThrow(/identity|scope|mismatch/i);
|
|
67
|
+
}
|
|
68
|
+
});
|
|
69
|
+
|
|
70
|
+
it("rechecks the original mapped Customer immediately before native grant expiration", async () => {
|
|
71
|
+
let checking = false,
|
|
72
|
+
reads = 0,
|
|
73
|
+
expirations = 0;
|
|
74
|
+
const f = creditFixture(async (input, init) => {
|
|
75
|
+
const path = new URL(input).pathname;
|
|
76
|
+
if (path.endsWith("/expire") && init?.method === "POST") expirations++;
|
|
77
|
+
if (
|
|
78
|
+
checking &&
|
|
79
|
+
path === "/v1/billing/credit_grants/credgr_topup1" &&
|
|
80
|
+
++reads === 2
|
|
81
|
+
)
|
|
82
|
+
return new Response(
|
|
83
|
+
JSON.stringify({ ...f.state.grant, customer: "cus_other" }),
|
|
84
|
+
{ headers: { "content-type": "application/json" } },
|
|
85
|
+
);
|
|
86
|
+
});
|
|
87
|
+
const client = new BetterStripe(f.component),
|
|
88
|
+
provider = { stripeSecretKey: "sk_test_credit", httpClient: f.httpClient };
|
|
89
|
+
await f.ready();
|
|
90
|
+
await f.t.action((ctx) =>
|
|
91
|
+
client.usage.purchaseCredits(ctx as RunCtx, f.purchase, provider),
|
|
92
|
+
);
|
|
93
|
+
f.state.paid = true;
|
|
94
|
+
await f.t.action((ctx) =>
|
|
95
|
+
client.usage.observeCreditPurchase(ctx as RunCtx, f.purchase, provider),
|
|
96
|
+
);
|
|
97
|
+
checking = true;
|
|
98
|
+
await expect(
|
|
99
|
+
f.t.action((ctx) =>
|
|
100
|
+
client.usage.prepareCreditRefund(ctx as RunCtx, f.purchase, provider),
|
|
101
|
+
),
|
|
102
|
+
).rejects.toThrow(/identity/i);
|
|
103
|
+
expect(reads).toBe(2);
|
|
104
|
+
expect(expirations).toBe(0);
|
|
105
|
+
expect(
|
|
106
|
+
await f.t.action((ctx) =>
|
|
107
|
+
client.usage.getCreditBalance(ctx as RunCtx, f.purchase),
|
|
108
|
+
),
|
|
109
|
+
).toMatchObject({ availableQuantity: "0", frozenQuantity: "10" });
|
|
110
|
+
});
|
|
@@ -27,7 +27,12 @@ const terms = creditPurchaseTerms({
|
|
|
27
27
|
ownership: "issuer",
|
|
28
28
|
rollover: "retain_original_terms",
|
|
29
29
|
});
|
|
30
|
-
function fixture(
|
|
30
|
+
function fixture(
|
|
31
|
+
ledger: number,
|
|
32
|
+
more = false,
|
|
33
|
+
foreign = false,
|
|
34
|
+
mapped = false,
|
|
35
|
+
) {
|
|
31
36
|
const methods: string[] = [];
|
|
32
37
|
const stripe = new Stripe("sk_test_credit_capacity", {
|
|
33
38
|
httpClient: Stripe.createFetchHttpClient(async (input, init) => {
|
|
@@ -39,6 +44,7 @@ function fixture(ledger: number, more = false, foreign = false) {
|
|
|
39
44
|
: [
|
|
40
45
|
{
|
|
41
46
|
id: "credgr_existing",
|
|
47
|
+
customer: mapped ? "cus_other" : "cus_buyer",
|
|
42
48
|
customer_account: foreign ? "acct_other" : "acct_buyer",
|
|
43
49
|
livemode: false,
|
|
44
50
|
expires_at: null,
|
|
@@ -48,6 +54,7 @@ function fixture(ledger: number, more = false, foreign = false) {
|
|
|
48
54
|
has_more: more,
|
|
49
55
|
}
|
|
50
56
|
: {
|
|
57
|
+
customer: mapped ? "cus_other" : "cus_buyer",
|
|
51
58
|
customer_account: "acct_buyer",
|
|
52
59
|
livemode: false,
|
|
53
60
|
balances: [
|
|
@@ -81,3 +88,75 @@ it("permits verified depleted grants but holds incomplete or foreign native inve
|
|
|
81
88
|
verifyNativeCreditCapacity(fixture(0, false, true).stripe, terms, 1),
|
|
82
89
|
).rejects.toThrow(/scope/i);
|
|
83
90
|
});
|
|
91
|
+
|
|
92
|
+
it("rejects foreign mapped Customer inventory even when its Accounts v2 payer matches", async () => {
|
|
93
|
+
await expect(
|
|
94
|
+
verifyNativeCreditCapacity(fixture(0, false, false, true).stripe, terms, 1),
|
|
95
|
+
).rejects.toThrow(/scope|customer/i);
|
|
96
|
+
});
|
|
97
|
+
|
|
98
|
+
function inventory(total: number, unexpired: number, size = 100) {
|
|
99
|
+
let lists = 0,
|
|
100
|
+
balances = 0;
|
|
101
|
+
const stripe = new Stripe("sk_test_inventory_bounds", {
|
|
102
|
+
maxNetworkRetries: 0,
|
|
103
|
+
httpClient: Stripe.createFetchHttpClient(async (input) => {
|
|
104
|
+
const url = new URL(String(input));
|
|
105
|
+
let value: unknown;
|
|
106
|
+
if (url.pathname.endsWith("/credit_grants")) {
|
|
107
|
+
lists++;
|
|
108
|
+
const cursor = url.searchParams.get("starting_after");
|
|
109
|
+
const start = cursor
|
|
110
|
+
? Number(cursor.slice(cursor.lastIndexOf("_") + 1)) + 1
|
|
111
|
+
: 0;
|
|
112
|
+
const count = Math.min(size, total - start);
|
|
113
|
+
value = {
|
|
114
|
+
data: Array.from({ length: count }, (_, offset) => ({
|
|
115
|
+
id: `credgr_${start + offset}`,
|
|
116
|
+
customer_account: "acct_buyer",
|
|
117
|
+
customer: "cus_buyer",
|
|
118
|
+
livemode: false,
|
|
119
|
+
voided_at: start + offset < unexpired ? null : 1,
|
|
120
|
+
expires_at: null,
|
|
121
|
+
})),
|
|
122
|
+
has_more: start + count < total,
|
|
123
|
+
};
|
|
124
|
+
} else {
|
|
125
|
+
balances++;
|
|
126
|
+
value = {
|
|
127
|
+
customer_account: "acct_buyer",
|
|
128
|
+
customer: "cus_buyer",
|
|
129
|
+
livemode: false,
|
|
130
|
+
balances: [{ ledger_balance: { monetary: { value: 0 } } }],
|
|
131
|
+
};
|
|
132
|
+
}
|
|
133
|
+
return new Response(JSON.stringify(value), {
|
|
134
|
+
headers: { "content-type": "application/json" },
|
|
135
|
+
});
|
|
136
|
+
}),
|
|
137
|
+
});
|
|
138
|
+
return { stripe, counts: () => ({ lists, balances }) };
|
|
139
|
+
}
|
|
140
|
+
it("accepts exact native inventory and balance-read bounds and holds one-over proofs", async () => {
|
|
141
|
+
const exact = inventory(1000, 0);
|
|
142
|
+
await verifyNativeCreditCapacity(exact.stripe, terms, 1);
|
|
143
|
+
expect(exact.counts()).toEqual({ lists: 10, balances: 0 });
|
|
144
|
+
const overflow = inventory(1001, 0);
|
|
145
|
+
await expect(
|
|
146
|
+
verifyNativeCreditCapacity(overflow.stripe, terms, 1),
|
|
147
|
+
).rejects.toThrow(/incomplete/i);
|
|
148
|
+
expect(overflow.counts()).toEqual({ lists: 10, balances: 0 });
|
|
149
|
+
const balances = inventory(100, 100);
|
|
150
|
+
await verifyNativeCreditCapacity(balances.stripe, terms, 1);
|
|
151
|
+
expect(balances.counts()).toEqual({ lists: 1, balances: 100 });
|
|
152
|
+
const excessive = inventory(101, 101);
|
|
153
|
+
await expect(
|
|
154
|
+
verifyNativeCreditCapacity(excessive.stripe, terms, 1),
|
|
155
|
+
).rejects.toThrow(/budget/i);
|
|
156
|
+
expect(excessive.counts()).toEqual({ lists: 2, balances: 0 });
|
|
157
|
+
});
|
|
158
|
+
it("rejects native inventory pages exceeding the requested proof size", async () => {
|
|
159
|
+
await expect(
|
|
160
|
+
verifyNativeCreditCapacity(inventory(101, 0, 101).stripe, terms, 1),
|
|
161
|
+
).rejects.toThrow(/budget|page|inventory/i);
|
|
162
|
+
});
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import type Stripe from "stripe";
|
|
2
|
-
import { creditRequire } from "./creditNative.js";
|
|
2
|
+
import { creditRequire, nativeCustomerId } from "./creditNative.js";
|
|
3
3
|
import type { UsageCreditPurchaseTerms } from "./creditTerms.js";
|
|
4
4
|
/** Read-only, bounded prepayment guard. Pending component intents reserve slots separately. */
|
|
5
5
|
export async function verifyNativeCreditCapacity(
|
|
@@ -16,9 +16,16 @@ export async function verifyNativeCreditCapacity(
|
|
|
16
16
|
limit: 100,
|
|
17
17
|
...(cursor ? { starting_after: cursor } : {}),
|
|
18
18
|
});
|
|
19
|
+
creditRequire(
|
|
20
|
+
Array.isArray(result.data) &&
|
|
21
|
+
result.data.length <= 100 &&
|
|
22
|
+
typeof result.has_more === "boolean",
|
|
23
|
+
"Native credit inventory page exceeds proof budget",
|
|
24
|
+
);
|
|
19
25
|
for (const grant of result.data) {
|
|
20
26
|
creditRequire(
|
|
21
27
|
grant.customer_account === terms.scope.customerAccount &&
|
|
28
|
+
nativeCustomerId(grant.customer) === terms.binding.stripeCustomerId &&
|
|
22
29
|
grant.livemode === terms.scope.livemode,
|
|
23
30
|
"Native credit inventory scope mismatch",
|
|
24
31
|
);
|
|
@@ -58,6 +65,8 @@ export async function verifyNativeCreditCapacity(
|
|
|
58
65
|
creditRequire(
|
|
59
66
|
balance.livemode === terms.scope.livemode &&
|
|
60
67
|
balance.customer_account === terms.scope.customerAccount &&
|
|
68
|
+
nativeCustomerId(balance.customer) ===
|
|
69
|
+
terms.binding.stripeCustomerId &&
|
|
61
70
|
balance.balances.length === 1,
|
|
62
71
|
"Native credit capacity balance unavailable",
|
|
63
72
|
);
|
|
@@ -8,6 +8,7 @@ import type { PreparedUsageRecord } from "./records.js";
|
|
|
8
8
|
import { creditNativeObservation } from "./creditProofs.js";
|
|
9
9
|
import { creditPurchaseTerms } from "./creditTerms.js";
|
|
10
10
|
import {
|
|
11
|
+
nativeCustomerId,
|
|
11
12
|
creditRequire,
|
|
12
13
|
paymentIdentity,
|
|
13
14
|
verifiedCreditPayment,
|
|
@@ -84,6 +85,7 @@ export async function verifyCreditDelivery(
|
|
|
84
85
|
grant.id === local.creditGrantId &&
|
|
85
86
|
!grant.voided_at &&
|
|
86
87
|
grant.customer_account === record.scope.customerAccount &&
|
|
88
|
+
nativeCustomerId(grant.customer) === record.binding.stripeCustomerId &&
|
|
87
89
|
grant.livemode === record.scope.livemode &&
|
|
88
90
|
grant.metadata?.bsUsageCredit === purchase.key &&
|
|
89
91
|
(grant.expires_at === null ||
|
|
@@ -94,6 +96,8 @@ export async function verifyCreditDelivery(
|
|
|
94
96
|
record.binding.stripePriceId &&
|
|
95
97
|
summary.livemode === record.scope.livemode &&
|
|
96
98
|
summary.customer_account === record.scope.customerAccount &&
|
|
99
|
+
nativeCustomerId(summary.customer) ===
|
|
100
|
+
record.binding.stripeCustomerId &&
|
|
97
101
|
summary.balances.length === 1 &&
|
|
98
102
|
native?.currency === terms.binding.plan.rate.currency &&
|
|
99
103
|
native.value === expected &&
|
|
@@ -10,6 +10,7 @@ import {
|
|
|
10
10
|
} from "./creditTerms.js";
|
|
11
11
|
import {
|
|
12
12
|
creditCall,
|
|
13
|
+
nativeCustomerId,
|
|
13
14
|
creditRequire,
|
|
14
15
|
verifyCreditRealm,
|
|
15
16
|
discoverCredit,
|
|
@@ -140,6 +141,7 @@ export async function prepareCreditRefund(
|
|
|
140
141
|
creditRequire(
|
|
141
142
|
grant.id === row.creditGrantId &&
|
|
142
143
|
grant.customer_account === terms.scope.customerAccount &&
|
|
144
|
+
nativeCustomerId(grant.customer) === terms.binding.stripeCustomerId &&
|
|
143
145
|
grant.livemode === terms.scope.livemode &&
|
|
144
146
|
grant.metadata?.bsUsageCredit === row.key,
|
|
145
147
|
"Original credit grant identity mismatch",
|
|
@@ -4,6 +4,9 @@ import { UsageCreditError, UsageCreditRecoveryError } from "./creditTerms.js";
|
|
|
4
4
|
import { verifyRealm } from "./catalogTypes.js";
|
|
5
5
|
import { verifyPinnedUsagePrice } from "./catalogPrices.js";
|
|
6
6
|
import { paymentCreditProof } from "./creditProofs.js";
|
|
7
|
+
export const nativeCustomerId = (
|
|
8
|
+
value: string | { id: string } | null | undefined,
|
|
9
|
+
) => (typeof value === "string" ? value : value?.id);
|
|
7
10
|
export async function creditCall<T>(call: () => Promise<T>): Promise<T> {
|
|
8
11
|
try {
|
|
9
12
|
return await call();
|
|
@@ -60,6 +63,7 @@ export function paymentIdentity(
|
|
|
60
63
|
payment.object === "payment_intent" &&
|
|
61
64
|
(!pinned || payment.id === pinned) &&
|
|
62
65
|
payment.customer_account === terms.scope.customerAccount &&
|
|
66
|
+
nativeCustomerId(payment.customer) === terms.binding.stripeCustomerId &&
|
|
63
67
|
payment.livemode === terms.scope.livemode &&
|
|
64
68
|
payment.currency === terms.binding.plan.rate.currency &&
|
|
65
69
|
payment.amount === terms.amount &&
|
|
@@ -82,6 +86,7 @@ export function verifiedCreditPayment(
|
|
|
82
86
|
typeof charge !== "string" &&
|
|
83
87
|
charge.object === "charge" &&
|
|
84
88
|
charge.payment_intent === payment.id &&
|
|
89
|
+
nativeCustomerId(charge.customer) === terms.binding.stripeCustomerId &&
|
|
85
90
|
charge.paid &&
|
|
86
91
|
charge.captured &&
|
|
87
92
|
charge.status === "succeeded" &&
|
|
@@ -0,0 +1,187 @@
|
|
|
1
|
+
import { afterEach, expect, it, vi } from "vitest";
|
|
2
|
+
import { schema, modules } from "../../test.js";
|
|
3
|
+
import { mutation } from "../../component/_generated/server.js";
|
|
4
|
+
import { v } from "convex/values";
|
|
5
|
+
import { componentRef } from "../webhooks/helpers.js";
|
|
6
|
+
import { BetterStripe } from "../index.js";
|
|
7
|
+
import type { RunCtx } from "../helpers.js";
|
|
8
|
+
import { creditFixture } from "./creditTransport.fixtures.js";
|
|
9
|
+
afterEach(() => vi.useRealTimers());
|
|
10
|
+
function response(value: unknown) {
|
|
11
|
+
return new Response(JSON.stringify(value), {
|
|
12
|
+
headers: { "content-type": "application/json" },
|
|
13
|
+
});
|
|
14
|
+
}
|
|
15
|
+
async function setup(count: number, applications = false) {
|
|
16
|
+
let invoiceReads = 0;
|
|
17
|
+
const entries = Array.from({ length: count }, (_, i) => ({
|
|
18
|
+
id: `cbtxn_${i}`,
|
|
19
|
+
object: "billing.credit_balance_transaction",
|
|
20
|
+
credit_grant: "credgr_topup1",
|
|
21
|
+
livemode: false,
|
|
22
|
+
type: applications && i > 0 ? "debit" : "credit",
|
|
23
|
+
credit:
|
|
24
|
+
applications && i > 0
|
|
25
|
+
? null
|
|
26
|
+
: {
|
|
27
|
+
type: "credits_granted",
|
|
28
|
+
amount: {
|
|
29
|
+
type: "monetary",
|
|
30
|
+
monetary: { currency: "usd", value: i === 0 ? 20 : 0 },
|
|
31
|
+
},
|
|
32
|
+
},
|
|
33
|
+
debit:
|
|
34
|
+
applications && i > 0
|
|
35
|
+
? {
|
|
36
|
+
type: "credits_applied",
|
|
37
|
+
amount: {
|
|
38
|
+
type: "monetary",
|
|
39
|
+
monetary: { currency: "usd", value: i <= 10 ? 2 : 0 },
|
|
40
|
+
},
|
|
41
|
+
credits_applied: {
|
|
42
|
+
invoice: "in_usage",
|
|
43
|
+
invoice_line_item: "il_usage",
|
|
44
|
+
},
|
|
45
|
+
}
|
|
46
|
+
: null,
|
|
47
|
+
}));
|
|
48
|
+
const f = creditFixture(async (input) => {
|
|
49
|
+
const path = new URL(input).pathname;
|
|
50
|
+
if (path === "/v1/billing/credit_balance_transactions")
|
|
51
|
+
return response({ object: "list", data: entries, has_more: false });
|
|
52
|
+
if (path === "/v1/invoices/in_usage") {
|
|
53
|
+
invoiceReads++;
|
|
54
|
+
return response({
|
|
55
|
+
id: "in_usage",
|
|
56
|
+
livemode: false,
|
|
57
|
+
customer_account: "acct_buyer",
|
|
58
|
+
customer: "cus_buyer",
|
|
59
|
+
currency: "usd",
|
|
60
|
+
status: "paid",
|
|
61
|
+
amount_paid: 0,
|
|
62
|
+
status_transitions: { finalized_at: 1300 },
|
|
63
|
+
parent: { subscription_details: { subscription: "sub_calls" } },
|
|
64
|
+
lines: {
|
|
65
|
+
has_more: false,
|
|
66
|
+
data: [
|
|
67
|
+
{
|
|
68
|
+
id: "il_usage",
|
|
69
|
+
amount: 20,
|
|
70
|
+
currency: "usd",
|
|
71
|
+
quantity_decimal: "10",
|
|
72
|
+
period: { start: 600, end: 1200 },
|
|
73
|
+
pricing: {
|
|
74
|
+
price_details: { price: "price_calls" },
|
|
75
|
+
unit_amount_decimal: "2",
|
|
76
|
+
},
|
|
77
|
+
parent: {
|
|
78
|
+
subscription_item_details: {
|
|
79
|
+
subscription: "sub_calls",
|
|
80
|
+
subscription_item: "si_calls",
|
|
81
|
+
proration: false,
|
|
82
|
+
},
|
|
83
|
+
},
|
|
84
|
+
pretax_credit_amounts: entries.slice(1).map((tx, index) => ({
|
|
85
|
+
type: "credit_balance_transaction",
|
|
86
|
+
credit_balance_transaction: tx.id,
|
|
87
|
+
amount: index < 10 ? 2 : 0,
|
|
88
|
+
})),
|
|
89
|
+
},
|
|
90
|
+
],
|
|
91
|
+
},
|
|
92
|
+
});
|
|
93
|
+
}
|
|
94
|
+
});
|
|
95
|
+
f.t.registerComponent("betterStripe", schema, {
|
|
96
|
+
...modules,
|
|
97
|
+
"./component/proofBoundsFixture.ts": async () => ({
|
|
98
|
+
pinProvider: mutation({
|
|
99
|
+
args: {},
|
|
100
|
+
returns: v.null(),
|
|
101
|
+
handler: async (ctx) => {
|
|
102
|
+
const outbox = (await ctx.db.query("usageOutbox").first())!;
|
|
103
|
+
await ctx.db.patch(outbox._id, {
|
|
104
|
+
provider: "function://test-provider",
|
|
105
|
+
definitionVersion: 1,
|
|
106
|
+
});
|
|
107
|
+
return null;
|
|
108
|
+
},
|
|
109
|
+
}),
|
|
110
|
+
}),
|
|
111
|
+
});
|
|
112
|
+
const client = new BetterStripe(f.component),
|
|
113
|
+
provider = { stripeSecretKey: "sk_test_credit", httpClient: f.httpClient };
|
|
114
|
+
const view = await f.ready();
|
|
115
|
+
await f.t.action((ctx) =>
|
|
116
|
+
client.usage.purchaseCredits(ctx as RunCtx, f.purchase, provider),
|
|
117
|
+
);
|
|
118
|
+
f.state.paid = true;
|
|
119
|
+
await f.t.action((ctx) =>
|
|
120
|
+
client.usage.observeCreditPurchase(ctx as RunCtx, f.purchase, provider),
|
|
121
|
+
);
|
|
122
|
+
if (applications) {
|
|
123
|
+
const event = {
|
|
124
|
+
scope: f.purchase.scope,
|
|
125
|
+
binding: f.purchase.binding,
|
|
126
|
+
sourceEventId: "all_units",
|
|
127
|
+
quantity: "10",
|
|
128
|
+
occurredAt: 700,
|
|
129
|
+
},
|
|
130
|
+
subscription = view.bindings[0].subscription;
|
|
131
|
+
const reservation = await f.t.action((ctx) =>
|
|
132
|
+
client.usage.reserveCredits(ctx as RunCtx, { event, subscription }),
|
|
133
|
+
);
|
|
134
|
+
const receipt = await f.t.action((ctx) =>
|
|
135
|
+
client.usage.record(ctx as RunCtx, {
|
|
136
|
+
event,
|
|
137
|
+
subscription,
|
|
138
|
+
reservationId: reservation.reservationId,
|
|
139
|
+
}),
|
|
140
|
+
);
|
|
141
|
+
await f.t.action(async (ctx) => {
|
|
142
|
+
await ctx.runMutation(
|
|
143
|
+
componentRef(f.component, "proofBoundsFixture/pinProvider"),
|
|
144
|
+
{},
|
|
145
|
+
);
|
|
146
|
+
const claimed = (await ctx.runMutation(
|
|
147
|
+
componentRef(f.component, "usageDelivery/steps/claim"),
|
|
148
|
+
{ scope: event.scope, eventId: receipt.eventId },
|
|
149
|
+
)) as { kind: string; request: Record<string, unknown> };
|
|
150
|
+
expect(claimed.kind).toBe("ready");
|
|
151
|
+
await ctx.runMutation(
|
|
152
|
+
componentRef(f.component, "usageDelivery/steps/save"),
|
|
153
|
+
{ ...claimed.request, outcome: { status: "accepted", created: 700 } },
|
|
154
|
+
);
|
|
155
|
+
});
|
|
156
|
+
f.state.nativeApplied = 20;
|
|
157
|
+
}
|
|
158
|
+
const reconcile = () =>
|
|
159
|
+
f.t.action((ctx) =>
|
|
160
|
+
client.usage.reconcileCreditPurchase(ctx as RunCtx, f.purchase, provider),
|
|
161
|
+
);
|
|
162
|
+
return { f, reconcile, invoiceReads: () => invoiceReads };
|
|
163
|
+
}
|
|
164
|
+
it("accepts exactly 100 native credit transactions and rejects an oversized transaction proof", async () => {
|
|
165
|
+
expect(await (await setup(100)).reconcile()).toMatchObject({
|
|
166
|
+
status: "available",
|
|
167
|
+
value: { backing: "sufficient" },
|
|
168
|
+
});
|
|
169
|
+
await expect((await setup(101)).reconcile()).rejects.toThrow(
|
|
170
|
+
/budget|limit|unavailable/i,
|
|
171
|
+
);
|
|
172
|
+
});
|
|
173
|
+
it("proves ten original credit-funded invoice applications and holds an eleventh without guessing", async () => {
|
|
174
|
+
const exact = await setup(11, true);
|
|
175
|
+
const observed = await exact.reconcile();
|
|
176
|
+
expect(observed).toMatchObject({
|
|
177
|
+
status: "available",
|
|
178
|
+
value: { reason: null, backing: "sufficient", applied: 20 },
|
|
179
|
+
});
|
|
180
|
+
expect(exact.invoiceReads()).toBe(10);
|
|
181
|
+
const overflow = await setup(12, true);
|
|
182
|
+
expect(await overflow.reconcile()).toMatchObject({
|
|
183
|
+
status: "available",
|
|
184
|
+
value: { backing: "held", reason: "invoice_provenance_unavailable" },
|
|
185
|
+
});
|
|
186
|
+
expect(overflow.invoiceReads()).toBe(0);
|
|
187
|
+
});
|
|
@@ -200,3 +200,77 @@ it("cancels an unpaid original purchase and never recreates its payment intent",
|
|
|
200
200
|
),
|
|
201
201
|
).toHaveLength(1);
|
|
202
202
|
});
|
|
203
|
+
|
|
204
|
+
it("rejects captured credit purchases whose payment or charge uses a foreign mapped Customer", async () => {
|
|
205
|
+
for (const field of ["paymentCustomer", "chargeCustomer"] as const) {
|
|
206
|
+
const f = creditFixture();
|
|
207
|
+
await f.ready();
|
|
208
|
+
await f.t.action((ctx) =>
|
|
209
|
+
ensureCreditPurchase(f.stripe, f.component, ctx as RunCtx, f.purchase),
|
|
210
|
+
);
|
|
211
|
+
f.state.paid = true;
|
|
212
|
+
f.state[field] = "cus_other";
|
|
213
|
+
await expect(
|
|
214
|
+
f.t.action((ctx) =>
|
|
215
|
+
observeCreditPurchase(f.stripe, f.component, ctx as RunCtx, f.purchase),
|
|
216
|
+
),
|
|
217
|
+
).rejects.toThrow(/scope|identity|verified/i);
|
|
218
|
+
expect(
|
|
219
|
+
f.calls.filter(
|
|
220
|
+
(c) => c.path === "/v1/billing/credit_grants" && c.method === "POST",
|
|
221
|
+
),
|
|
222
|
+
).toHaveLength(0);
|
|
223
|
+
}
|
|
224
|
+
});
|
|
225
|
+
|
|
226
|
+
it("rejects adoption of a paid grant whose mapped Customer differs from its original payer binding", async () => {
|
|
227
|
+
const f = creditFixture();
|
|
228
|
+
await f.ready();
|
|
229
|
+
await f.t.action((ctx) =>
|
|
230
|
+
ensureCreditPurchase(f.stripe, f.component, ctx as RunCtx, f.purchase),
|
|
231
|
+
);
|
|
232
|
+
f.state.paid = true;
|
|
233
|
+
let failed = false;
|
|
234
|
+
await expect(
|
|
235
|
+
f.t.action((ctx) =>
|
|
236
|
+
observeCreditPurchase(
|
|
237
|
+
f.stripe,
|
|
238
|
+
f.component,
|
|
239
|
+
{
|
|
240
|
+
runQuery: ctx.runQuery,
|
|
241
|
+
runAction: ctx.runAction,
|
|
242
|
+
runMutation: async (
|
|
243
|
+
reference: Parameters<NonNullable<RunCtx["runMutation"]>>[0],
|
|
244
|
+
args: Record<string, unknown>,
|
|
245
|
+
) => {
|
|
246
|
+
if (
|
|
247
|
+
String(
|
|
248
|
+
(reference as unknown as Record<symbol, string>)[
|
|
249
|
+
Symbol.for("toReferencePath")
|
|
250
|
+
],
|
|
251
|
+
).endsWith("/usageCredits/mutations/pinGrant") &&
|
|
252
|
+
!failed
|
|
253
|
+
) {
|
|
254
|
+
failed = true;
|
|
255
|
+
throw new Error("simulated persistence failure");
|
|
256
|
+
}
|
|
257
|
+
return ctx.runMutation(reference, args);
|
|
258
|
+
},
|
|
259
|
+
} as RunCtx,
|
|
260
|
+
f.purchase,
|
|
261
|
+
),
|
|
262
|
+
),
|
|
263
|
+
).rejects.toThrow();
|
|
264
|
+
expect(f.state.grant).toBeDefined();
|
|
265
|
+
f.state.grant!.customer = "cus_other";
|
|
266
|
+
await expect(
|
|
267
|
+
f.t.action((ctx) =>
|
|
268
|
+
observeCreditPurchase(f.stripe, f.component, ctx as RunCtx, f.purchase),
|
|
269
|
+
),
|
|
270
|
+
).rejects.toThrow(/grant|identity/i);
|
|
271
|
+
expect(
|
|
272
|
+
f.calls.filter(
|
|
273
|
+
(c) => c.path === "/v1/billing/credit_grants" && c.method === "POST",
|
|
274
|
+
),
|
|
275
|
+
).toHaveLength(1);
|
|
276
|
+
});
|
|
@@ -15,6 +15,7 @@ import { grantCreditProof } from "./creditProofs.js";
|
|
|
15
15
|
import {
|
|
16
16
|
creditCall,
|
|
17
17
|
creditCreateWindow,
|
|
18
|
+
nativeCustomerId,
|
|
18
19
|
creditRequire,
|
|
19
20
|
discoverCredit,
|
|
20
21
|
paymentIdentity,
|
|
@@ -191,6 +192,7 @@ function grantProof(
|
|
|
191
192
|
creditRequire(
|
|
192
193
|
grant.object === "billing.credit_grant" &&
|
|
193
194
|
grant.customer_account === terms.scope.customerAccount &&
|
|
195
|
+
nativeCustomerId(grant.customer) === terms.binding.stripeCustomerId &&
|
|
194
196
|
grant.livemode === terms.scope.livemode &&
|
|
195
197
|
grant.metadata?.bsUsageCredit === key &&
|
|
196
198
|
grant.category === "paid" &&
|
|
@@ -11,6 +11,7 @@ import {
|
|
|
11
11
|
} from "./creditTerms.js";
|
|
12
12
|
import {
|
|
13
13
|
creditCall,
|
|
14
|
+
nativeCustomerId,
|
|
14
15
|
creditRequire,
|
|
15
16
|
verifyCreditRealm,
|
|
16
17
|
paymentIdentity,
|
|
@@ -29,8 +30,7 @@ export async function reconcileCreditPurchase(
|
|
|
29
30
|
input: UsageCreditPurchaseOptions,
|
|
30
31
|
) {
|
|
31
32
|
return creditCall(async () => {
|
|
32
|
-
const terms = creditPurchaseTerms(input)
|
|
33
|
-
startedAt = Date.now();
|
|
33
|
+
const terms = creditPurchaseTerms(input);
|
|
34
34
|
let source = await findCreditPurchase(component, ctx, input);
|
|
35
35
|
if (!source.row.creditGrantId) {
|
|
36
36
|
await observeCreditPurchase(stripe, component, ctx, input);
|
|
@@ -43,6 +43,12 @@ export async function reconcileCreditPurchase(
|
|
|
43
43
|
reason: "credit_purchase_not_ready",
|
|
44
44
|
retryable: true,
|
|
45
45
|
};
|
|
46
|
+
const proofStartedAt = Date.now();
|
|
47
|
+
const startedAt = (await runMutationOrThrow(
|
|
48
|
+
ctx,
|
|
49
|
+
componentRef(component, "usageCredits/mutations/beginObservation"),
|
|
50
|
+
{ inputJson: JSON.stringify(input) },
|
|
51
|
+
)) as number;
|
|
46
52
|
await verifyCreditRealm(stripe, terms, false);
|
|
47
53
|
const payment = await stripe.paymentIntents.retrieve(
|
|
48
54
|
purchase.paymentIntentId,
|
|
@@ -76,6 +82,8 @@ export async function reconcileCreditPurchase(
|
|
|
76
82
|
creditRequire(
|
|
77
83
|
nativeGrant.id === purchase.creditGrantId &&
|
|
78
84
|
nativeGrant.customer_account === terms.scope.customerAccount &&
|
|
85
|
+
nativeCustomerId(nativeGrant.customer) ===
|
|
86
|
+
terms.binding.stripeCustomerId &&
|
|
79
87
|
nativeGrant.livemode === terms.scope.livemode &&
|
|
80
88
|
nativeGrant.metadata?.bsUsageCredit === purchase.key &&
|
|
81
89
|
nativeGrant.amount.monetary?.value === terms.amount &&
|
|
@@ -114,6 +122,12 @@ export async function reconcileCreditPurchase(
|
|
|
114
122
|
available.currency === ledger.currency,
|
|
115
123
|
"Native credit summary currency mismatch",
|
|
116
124
|
);
|
|
125
|
+
creditRequire(
|
|
126
|
+
Array.isArray(transactions.data) &&
|
|
127
|
+
transactions.data.length <= 100 &&
|
|
128
|
+
typeof transactions.has_more === "boolean",
|
|
129
|
+
"Native credit transaction proof budget exceeded",
|
|
130
|
+
);
|
|
117
131
|
let granted = 0,
|
|
118
132
|
applied = 0,
|
|
119
133
|
expired = 0,
|
|
@@ -200,12 +214,13 @@ export async function reconcileCreditPurchase(
|
|
|
200
214
|
inputJson: JSON.stringify(input),
|
|
201
215
|
proofJson: JSON.stringify(proof),
|
|
202
216
|
startedAt,
|
|
217
|
+
proofStartedAt,
|
|
203
218
|
},
|
|
204
219
|
)) as string;
|
|
205
220
|
const result = JSON.parse(resultJson) as UsageCreditReconciliation;
|
|
206
221
|
return {
|
|
207
222
|
status: "available" as const,
|
|
208
|
-
observedAt: Math.floor(
|
|
223
|
+
observedAt: Math.floor(proofStartedAt / 1000),
|
|
209
224
|
value: result,
|
|
210
225
|
};
|
|
211
226
|
});
|
|
@@ -36,6 +36,7 @@ export function creditFixture(
|
|
|
36
36
|
processingFee: 1,
|
|
37
37
|
paymentCustomer: "cus_buyer",
|
|
38
38
|
chargeCustomer: "cus_buyer",
|
|
39
|
+
summaryCustomer: "cus_buyer",
|
|
39
40
|
failGrant: false,
|
|
40
41
|
wrongPayer: false,
|
|
41
42
|
paymentId: "pi_topup1",
|
|
@@ -81,7 +82,7 @@ export function creditFixture(
|
|
|
81
82
|
});
|
|
82
83
|
if (path === "/v1/billing/credit_balance_summary")
|
|
83
84
|
return response({
|
|
84
|
-
customer:
|
|
85
|
+
customer: state.summaryCustomer,
|
|
85
86
|
customer_account: "acct_buyer",
|
|
86
87
|
livemode: false,
|
|
87
88
|
balances: [
|