@fantastic.dev/better-stripe 0.84.0 → 0.85.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 (33) hide show
  1. package/CHANGELOG.md +6 -0
  2. package/README.md +1 -1
  3. package/dist/client/billing/renewalV2/binding.d.ts +1 -1
  4. package/dist/client/billing/renewalV2/binding.d.ts.map +1 -1
  5. package/dist/client/billing/renewalV2/binding.js.map +1 -1
  6. package/dist/client/billing/renewalV2/index.d.ts +25 -0
  7. package/dist/client/billing/renewalV2/index.d.ts.map +1 -1
  8. package/dist/client/billing/renewalV2/index.js +55 -1
  9. package/dist/client/billing/renewalV2/index.js.map +1 -1
  10. package/dist/client/billing/renewalV2/receipt.d.ts +36 -0
  11. package/dist/client/billing/renewalV2/receipt.d.ts.map +1 -0
  12. package/dist/client/billing/renewalV2/receipt.js +131 -0
  13. package/dist/client/billing/renewalV2/receipt.js.map +1 -0
  14. package/dist/client/connect/payoutAdoptionTestHelpers.d.ts +32 -32
  15. package/dist/client/connect/payoutSyncTestHelpers.d.ts +16 -16
  16. package/dist/client/renewal.d.ts +2 -2
  17. package/dist/client/renewal.d.ts.map +1 -1
  18. package/dist/client/renewal.js +1 -1
  19. package/dist/client/renewal.js.map +1 -1
  20. package/dist/client/usage/observationClient.d.ts +2 -2
  21. package/dist/client/usage/observationClient.d.ts.map +1 -1
  22. package/dist/component/balanceFunding/mutations.d.ts +16 -16
  23. package/dist/component/balanceFunding/preparationHandlers.d.ts +8 -8
  24. package/dist/component/balanceFunding/stateHandlers.d.ts +8 -8
  25. package/dist/component/earnings/triggers.d.ts +16 -16
  26. package/docs/renewal-context-reads.md +69 -3
  27. package/docs/renewal-phase-assembly.md +5 -0
  28. package/package.json +1 -1
  29. package/src/client/billing/renewalV2/binding.ts +1 -1
  30. package/src/client/billing/renewalV2/index.ts +104 -1
  31. package/src/client/billing/renewalV2/receipt.test.ts +289 -0
  32. package/src/client/billing/renewalV2/receipt.ts +163 -0
  33. package/src/client/renewal.ts +3 -0
@@ -0,0 +1,289 @@
1
+ import { afterEach, expect, it, vi } from "vitest";
2
+ import { createHash, webcrypto } from "node:crypto";
3
+ import * as v2 from "./index.js";
4
+ import { renewalSnapshot } from "../renewalReplacementSnapshot.js";
5
+ import { fixture } from "../../../../tests/renewalAggregate/fixtures.js";
6
+
7
+ const construct = (raw: any) =>
8
+ v2.constructRenewalScheduleAttachmentReceiptV2(raw);
9
+ function input() {
10
+ const f = fixture();
11
+ const preparation = {
12
+ subscription: f.subscription,
13
+ targetPrice: f.targetPrice,
14
+ billingCustomer: f.billingCustomer,
15
+ expected: f.prepared.expected,
16
+ key: f.prepared.requestIdentity.key,
17
+ };
18
+ return {
19
+ attachRequest: {
20
+ preparation,
21
+ apiVersion: f.attachRequest.apiVersion,
22
+ attachKey: f.attachRequest.key,
23
+ firstDispatchedAt: f.attachRequest.firstDispatchedAt,
24
+ },
25
+ actualDispatch: {
26
+ scope: "platform" as const,
27
+ apiVersion: f.attachRequest.apiVersion,
28
+ method: "POST" as const,
29
+ path: "/v1/subscription_schedules" as const,
30
+ payload: { from_subscription: preparation.expected.subscriptionId },
31
+ key: f.attachRequest.key,
32
+ firstDispatchedAt: f.attachRequest.firstDispatchedAt,
33
+ },
34
+ providerSnapshot: f.schedule,
35
+ };
36
+ }
37
+ afterEach(() => vi.unstubAllGlobals());
38
+ it("constructs the complete unsigned C3 receipt through the public barrel", async () => {
39
+ expect(v2.constructRenewalScheduleAttachmentReceiptV2).toBeTypeOf("function");
40
+ const raw = input();
41
+ const options: v2.ConstructRenewalScheduleAttachmentReceiptV2Options = raw;
42
+ const receipt = await v2.constructRenewalScheduleAttachmentReceiptV2(options);
43
+ const typed: v2.RenewalScheduleAttachmentReceiptV2 = receipt;
44
+ expect(typed.version).toBe(2);
45
+ const prepared = await v2.prepareRenewalPriceReplacementV2(
46
+ raw.attachRequest.preparation,
47
+ );
48
+ const { preparation: _preparation, ...requestOptions } = raw.attachRequest;
49
+ const request = await v2.prepareRenewalScheduleAttachmentV2({
50
+ ...requestOptions,
51
+ prepared,
52
+ });
53
+ const unsigned = {
54
+ version: 2,
55
+ stage: "attached_unconfigured",
56
+ scope: "platform",
57
+ logicalBinding: prepared.requestIdentity.binding,
58
+ request,
59
+ scheduleId: raw.providerSnapshot.id,
60
+ subscriptionId: prepared.expected.subscriptionId,
61
+ customerAccountId: prepared.expected.customerAccountId,
62
+ livemode: prepared.expected.livemode,
63
+ providerSnapshot: raw.providerSnapshot,
64
+ };
65
+ const bytes = JSON.stringify(
66
+ renewalSnapshot([
67
+ "betterstripe-renewal-binding",
68
+ 2,
69
+ "renewal-attach-receipt",
70
+ unsigned,
71
+ ]),
72
+ );
73
+ expect(receipt).toEqual({
74
+ ...unsigned,
75
+ binding: `renewal-attach-receipt:v2:sha256:${createHash("sha256").update(bytes, "utf8").digest("hex")}`,
76
+ });
77
+ const sdk = await import("../../index.js");
78
+ expect(sdk).toHaveProperty(
79
+ "constructRenewalScheduleAttachmentReceiptV2",
80
+ v2.constructRenewalScheduleAttachmentReceiptV2,
81
+ );
82
+ expect(receipt).not.toHaveProperty("transport");
83
+ expect(receipt).not.toHaveProperty("observedAt");
84
+ });
85
+
86
+ it.each([
87
+ "scope",
88
+ "apiVersion",
89
+ "method",
90
+ "path",
91
+ "payload",
92
+ "key",
93
+ "firstDispatchedAt",
94
+ ])("rejects changed actual dispatch %s", async (field) => {
95
+ const raw: any = input();
96
+ raw.actualDispatch[field] =
97
+ field === "payload"
98
+ ? { from_subscription: "sub_foreign" }
99
+ : field === "firstDispatchedAt"
100
+ ? raw.actualDispatch[field] + 1
101
+ : "changed";
102
+ await expect(construct(raw)).rejects.toThrow();
103
+ });
104
+ it("binds complete unknown provider material without claiming response authority", async () => {
105
+ const a: any = input(),
106
+ b: any = input();
107
+ b.providerSnapshot.future_native_field = { untouched: [null, "safe"] };
108
+ const first = await construct(a),
109
+ second = await construct(b);
110
+ expect(second.providerSnapshot).toEqual(b.providerSnapshot);
111
+ expect(second.binding).not.toBe(first.binding);
112
+ expect(second).not.toHaveProperty("authenticationEstablished");
113
+ expect(second).not.toHaveProperty("providerQualification");
114
+ });
115
+ it("preserves own JSON keys that record parsers may otherwise discard", async () => {
116
+ const raw: any = input();
117
+ Object.defineProperty(raw.providerSnapshot, "__proto__", {
118
+ value: { retained: true },
119
+ enumerable: true,
120
+ });
121
+ const result = await construct(raw);
122
+ expect(
123
+ Object.prototype.hasOwnProperty.call(result.providerSnapshot, "__proto__"),
124
+ ).toBe(true);
125
+ expect(result.providerSnapshot).toEqual(
126
+ JSON.parse(JSON.stringify(raw.providerSnapshot)),
127
+ );
128
+ });
129
+ it("accepts matching expanded identity relations without dropping fields", async () => {
130
+ const raw: any = input();
131
+ raw.providerSnapshot.customer = {
132
+ id: "cus_buyer",
133
+ object: "customer",
134
+ livemode: false,
135
+ customer_account: "acct_buyer",
136
+ future_field: "preserve",
137
+ };
138
+ raw.providerSnapshot.subscription = {
139
+ id: "sub_original",
140
+ object: "subscription",
141
+ deleted: false,
142
+ customer: structuredClone(raw.providerSnapshot.customer),
143
+ schedule: {
144
+ id: raw.providerSnapshot.id,
145
+ object: "subscription_schedule",
146
+ subscription: "sub_original",
147
+ },
148
+ };
149
+ const result = await construct(raw);
150
+ expect(result.providerSnapshot).toEqual(raw.providerSnapshot);
151
+ });
152
+ it("rejects stored preparations and does not convert V1 receipt records", async () => {
153
+ const raw: any = input();
154
+ raw.attachRequest.preparation = fixture().prepared;
155
+ await expect(construct(raw)).rejects.toThrow();
156
+ await expect(construct(fixture().attachReceipt)).rejects.toThrow();
157
+ });
158
+ it("rejects extra payload fields and required accessors before digest", async () => {
159
+ const digest = vi.fn();
160
+ vi.stubGlobal("crypto", { subtle: { digest } });
161
+ const raw: any = input();
162
+ raw.actualDispatch.payload.extra = "unexpected";
163
+ await expect(construct(raw)).rejects.toThrow();
164
+ delete raw.actualDispatch.payload.extra;
165
+ const read = vi.fn();
166
+ Object.defineProperty(raw, "providerSnapshot", {
167
+ enumerable: true,
168
+ get: read,
169
+ });
170
+ await expect(construct(raw)).rejects.toThrow();
171
+ expect(read).not.toHaveBeenCalled();
172
+ expect(digest).not.toHaveBeenCalled();
173
+ });
174
+ it.each([
175
+ "customer",
176
+ "subscription",
177
+ "mode",
178
+ "account",
179
+ "deleted",
180
+ "missingBillingCustomer",
181
+ ])("rejects wrong or missing identity %s", async (field) => {
182
+ const raw: any = input();
183
+ if (field === "mode") raw.providerSnapshot.livemode = true;
184
+ else if (field === "account")
185
+ raw.providerSnapshot.customer_account = "acct_other";
186
+ else if (field === "deleted") raw.providerSnapshot.deleted = true;
187
+ else if (field === "missingBillingCustomer")
188
+ delete raw.attachRequest.preparation.billingCustomer;
189
+ else
190
+ raw.providerSnapshot[field] =
191
+ field === "customer" ? "cus_foreign" : "sub_foreign";
192
+ await expect(construct(raw)).rejects.toThrow();
193
+ });
194
+ it("checks expanded identity relations and preserves opaque fields", async () => {
195
+ const raw: any = input();
196
+ raw.providerSnapshot.subscription = {
197
+ id: "sub_original",
198
+ object: "subscription",
199
+ schedule: {
200
+ id: raw.providerSnapshot.id,
201
+ object: "subscription_schedule",
202
+ customer: "cus_foreign",
203
+ },
204
+ };
205
+ await expect(construct(raw)).rejects.toThrow();
206
+ });
207
+ it.each(["root", "attachRequest", "preparation", "actualDispatch"])(
208
+ "rejects unknown %s names before reading them",
209
+ async (field) => {
210
+ const raw: any = input(),
211
+ target =
212
+ field === "root"
213
+ ? raw
214
+ : field === "preparation"
215
+ ? raw.attachRequest.preparation
216
+ : raw[field];
217
+ const read = vi.fn(() => "ignored");
218
+ Object.defineProperty(target, "unexpected", {
219
+ enumerable: true,
220
+ get: read,
221
+ });
222
+ await expect(construct(raw)).rejects.toThrow();
223
+ expect(read).not.toHaveBeenCalled();
224
+ },
225
+ );
226
+ it("rechecks captured required fields before digest after a Proxy mutation", async () => {
227
+ const raw: any = input(),
228
+ request = raw.attachRequest;
229
+ raw.attachRequest = new Proxy(request, {
230
+ getPrototypeOf(target) {
231
+ delete target.apiVersion;
232
+ return Object.prototype;
233
+ },
234
+ });
235
+ const digest = vi.fn();
236
+ vi.stubGlobal("crypto", { subtle: { digest } });
237
+ await expect(construct(raw)).rejects.toThrow();
238
+ expect(digest).not.toHaveBeenCalled();
239
+ });
240
+ it("captures the whole raw leaf before awaiting digest", async () => {
241
+ const raw: any = input();
242
+ const original = structuredClone(raw.providerSnapshot);
243
+ let release!: () => void;
244
+ const held = new Promise<void>((r) => {
245
+ release = r;
246
+ });
247
+ let calls = 0;
248
+ vi.stubGlobal("crypto", {
249
+ subtle: {
250
+ async digest(
251
+ algorithm: string,
252
+ bytes: Parameters<typeof webcrypto.subtle.digest>[1],
253
+ ) {
254
+ if (++calls === 1) await held;
255
+ return webcrypto.subtle.digest(algorithm, bytes);
256
+ },
257
+ },
258
+ });
259
+ const pending = construct(raw);
260
+ raw.providerSnapshot.customer = "cus_changed";
261
+ raw.actualDispatch.key = "changed";
262
+ release();
263
+ const result = await pending;
264
+ expect(result.providerSnapshot).toEqual(original);
265
+ });
266
+ it.each(["unavailable", "rejected", "invalid"])(
267
+ "fails when digest is %s without fallback",
268
+ async (kind) => {
269
+ vi.stubGlobal(
270
+ "crypto",
271
+ kind === "unavailable"
272
+ ? {}
273
+ : {
274
+ subtle: {
275
+ digest:
276
+ kind === "rejected"
277
+ ? () => Promise.reject(Error("failed"))
278
+ : () => Promise.resolve(new ArrayBuffer(1)),
279
+ },
280
+ },
281
+ );
282
+ await expect(construct(input())).rejects.toThrow();
283
+ },
284
+ );
285
+ it("enforces the whole UTF-8 receipt preimage budget", async () => {
286
+ const raw: any = input();
287
+ raw.providerSnapshot.large_unknown = "\u0800".repeat(180000);
288
+ await expect(construct(raw)).rejects.toThrow();
289
+ });
@@ -0,0 +1,163 @@
1
+ import { z } from "zod";
2
+ import { renewalSnapshot } from "../renewalReplacementSnapshot.js";
3
+ import {
4
+ referenceId,
5
+ timestamp,
6
+ type ObjectData,
7
+ } from "../renewalAggregate/shared.js";
8
+
9
+ const preparation = z
10
+ .object({
11
+ subscription: z.unknown(),
12
+ targetPrice: z.unknown(),
13
+ billingCustomer: z.unknown().optional(),
14
+ expected: z.unknown(),
15
+ key: z.string(),
16
+ })
17
+ .strict();
18
+ const attachRequest = z
19
+ .object({
20
+ preparation,
21
+ apiVersion: z.string(),
22
+ attachKey: z.string(),
23
+ firstDispatchedAt: timestamp,
24
+ })
25
+ .strict();
26
+ const dispatch = z
27
+ .object({
28
+ scope: z.literal("platform"),
29
+ apiVersion: z.string(),
30
+ method: z.literal("POST"),
31
+ path: z.literal("/v1/subscription_schedules"),
32
+ payload: z.object({ from_subscription: z.string() }).strict(),
33
+ key: z.string(),
34
+ firstDispatchedAt: timestamp,
35
+ })
36
+ .strict();
37
+ const input = z
38
+ .object({
39
+ attachRequest,
40
+ actualDispatch: dispatch,
41
+ // The bounded JSON capture already owns this plain object. A record parser
42
+ // can discard special own keys such as __proto__, changing the bound body.
43
+ providerSnapshot: z.custom<ObjectData>(
44
+ (v) => v !== null && typeof v === "object" && !Array.isArray(v),
45
+ ),
46
+ })
47
+ .strict();
48
+
49
+ function ownData(raw: unknown, required: string[], optional: string[] = []) {
50
+ if (!raw || typeof raw !== "object" || Array.isArray(raw))
51
+ throw Error("Invalid renewal receipt input.");
52
+ const keys = Reflect.ownKeys(raw);
53
+ if (
54
+ keys.some(
55
+ (k) => typeof k !== "string" || ![...required, ...optional].includes(k),
56
+ ) ||
57
+ required.some((k) => !keys.includes(k))
58
+ )
59
+ throw Error("Invalid renewal receipt fields.");
60
+ const result: ObjectData = {};
61
+ for (const key of keys) {
62
+ const d = Object.getOwnPropertyDescriptor(raw, key)!;
63
+ if (!d || !d.enumerable || !("value" in d))
64
+ throw Error("Renewal receipt requires own JSON data.");
65
+ result[key as string] = d.value;
66
+ }
67
+ return result;
68
+ }
69
+ function closed(raw: unknown) {
70
+ const root = ownData(raw, [
71
+ "attachRequest",
72
+ "actualDispatch",
73
+ "providerSnapshot",
74
+ ]);
75
+ const request = ownData(root.attachRequest, [
76
+ "preparation",
77
+ "apiVersion",
78
+ "attachKey",
79
+ "firstDispatchedAt",
80
+ ]);
81
+ ownData(
82
+ request.preparation,
83
+ ["subscription", "targetPrice", "expected", "key"],
84
+ ["billingCustomer"],
85
+ );
86
+ const wire = ownData(root.actualDispatch, [
87
+ "scope",
88
+ "apiVersion",
89
+ "method",
90
+ "path",
91
+ "payload",
92
+ "key",
93
+ "firstDispatchedAt",
94
+ ]);
95
+ ownData(wire.payload, ["from_subscription"]);
96
+ }
97
+ export function captureAttachmentReceipt(raw: unknown) {
98
+ closed(raw);
99
+ const captured = renewalSnapshot(raw);
100
+ // Recheck the detached object: hostile reflection can mutate the live source.
101
+ closed(captured);
102
+ return input.parse(captured);
103
+ }
104
+
105
+ /** Available identity facts only, never response provenance or financial proof. */
106
+ export function assertAttachmentIdentity(
107
+ body: ObjectData,
108
+ operation: {
109
+ scheduleId: string;
110
+ subscriptionId: string;
111
+ billingCustomerId: string;
112
+ customerAccountId: string;
113
+ livemode: boolean;
114
+ },
115
+ ) {
116
+ const need = (v: boolean) => {
117
+ if (!v) throw Error("Unverified renewal attachment identity.");
118
+ };
119
+ const context = {
120
+ customerAccountId: operation.customerAccountId,
121
+ livemode: operation.livemode,
122
+ };
123
+ const check = (
124
+ value: unknown,
125
+ kind: "customer" | "subscription" | "subscription_schedule",
126
+ depth: number,
127
+ ): void => {
128
+ need(depth <= 40);
129
+ const prefix =
130
+ kind === "customer"
131
+ ? "cus"
132
+ : kind === "subscription"
133
+ ? "sub"
134
+ : "sub_sched";
135
+ const expected =
136
+ kind === "customer"
137
+ ? operation.billingCustomerId
138
+ : kind === "subscription"
139
+ ? operation.subscriptionId
140
+ : operation.scheduleId;
141
+ need(referenceId(value, prefix, kind, context) === expected);
142
+ if (typeof value === "string") return;
143
+ const expanded = value as ObjectData;
144
+ need(expanded.deleted === undefined || expanded.deleted === false);
145
+ const owns = (key: string) =>
146
+ Object.prototype.hasOwnProperty.call(expanded, key);
147
+ if (kind !== "customer" && owns("customer"))
148
+ check(expanded.customer, "customer", depth + 1);
149
+ if (kind === "subscription" && owns("schedule"))
150
+ check(expanded.schedule, "subscription_schedule", depth + 1);
151
+ if (kind === "subscription_schedule" && owns("subscription"))
152
+ check(expanded.subscription, "subscription", depth + 1);
153
+ };
154
+ need(
155
+ body.object === "subscription_schedule" &&
156
+ body.id === operation.scheduleId &&
157
+ (body.deleted === undefined || body.deleted === false) &&
158
+ body.customer_account === operation.customerAccountId &&
159
+ body.livemode === operation.livemode,
160
+ );
161
+ check(body.customer, "customer", 0);
162
+ check(body.subscription, "subscription", 0);
163
+ }
@@ -14,10 +14,13 @@ export type { ReadRenewalPriceReplacementContextOptions } from "./billing/renewa
14
14
  export {
15
15
  prepareRenewalPriceReplacementV2,
16
16
  prepareRenewalScheduleAttachmentV2,
17
+ constructRenewalScheduleAttachmentReceiptV2,
17
18
  } from "./billing/renewalV2/index.js";
18
19
  export type {
19
20
  PrepareRenewalPriceReplacementV2Options,
20
21
  PreparedRenewalPriceReplacementV2,
21
22
  PrepareRenewalScheduleAttachmentV2Options,
22
23
  PreparedRenewalScheduleAttachmentV2,
24
+ ConstructRenewalScheduleAttachmentReceiptV2Options,
25
+ RenewalScheduleAttachmentReceiptV2,
23
26
  } from "./billing/renewalV2/index.js";