@fantastic.dev/better-stripe 0.86.0 → 0.88.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 (133) hide show
  1. package/CHANGELOG.md +12 -0
  2. package/README.md +1 -1
  3. package/dist/client/billing/renewalObservation/active-scheduled.d.ts +6 -0
  4. package/dist/client/billing/renewalObservation/active-scheduled.d.ts.map +1 -0
  5. package/dist/client/billing/renewalObservation/active-scheduled.js +37 -0
  6. package/dist/client/billing/renewalObservation/active-scheduled.js.map +1 -0
  7. package/dist/client/billing/renewalObservation/common.d.ts +47 -0
  8. package/dist/client/billing/renewalObservation/common.d.ts.map +1 -0
  9. package/dist/client/billing/renewalObservation/common.js +39 -0
  10. package/dist/client/billing/renewalObservation/common.js.map +1 -0
  11. package/dist/client/billing/renewalObservation/configured-baseline.d.ts +76 -0
  12. package/dist/client/billing/renewalObservation/configured-baseline.d.ts.map +1 -0
  13. package/dist/client/billing/renewalObservation/configured-baseline.js +26 -0
  14. package/dist/client/billing/renewalObservation/configured-baseline.js.map +1 -0
  15. package/dist/client/billing/renewalObservation/coupon-discount-joins.d.ts +53 -0
  16. package/dist/client/billing/renewalObservation/coupon-discount-joins.d.ts.map +1 -0
  17. package/dist/client/billing/renewalObservation/coupon-discount-joins.js +103 -0
  18. package/dist/client/billing/renewalObservation/coupon-discount-joins.js.map +1 -0
  19. package/dist/client/billing/renewalObservation/invoice-tax-identity.d.ts +52 -0
  20. package/dist/client/billing/renewalObservation/invoice-tax-identity.d.ts.map +1 -0
  21. package/dist/client/billing/renewalObservation/invoice-tax-identity.js +49 -0
  22. package/dist/client/billing/renewalObservation/invoice-tax-identity.js.map +1 -0
  23. package/dist/client/billing/renewalObservation/pending-and-stage.d.ts +76 -0
  24. package/dist/client/billing/renewalObservation/pending-and-stage.d.ts.map +1 -0
  25. package/dist/client/billing/renewalObservation/pending-and-stage.js +36 -0
  26. package/dist/client/billing/renewalObservation/pending-and-stage.js.map +1 -0
  27. package/dist/client/billing/renewalObservation/phase-price-normalization.d.ts +57 -0
  28. package/dist/client/billing/renewalObservation/phase-price-normalization.d.ts.map +1 -0
  29. package/dist/client/billing/renewalObservation/phase-price-normalization.js +70 -0
  30. package/dist/client/billing/renewalObservation/phase-price-normalization.js.map +1 -0
  31. package/dist/client/billing/renewalObservation/planProjection.d.ts +8 -0
  32. package/dist/client/billing/renewalObservation/planProjection.d.ts.map +1 -0
  33. package/dist/client/billing/renewalObservation/planProjection.js +150 -0
  34. package/dist/client/billing/renewalObservation/planProjection.js.map +1 -0
  35. package/dist/client/billing/renewalObservation/reference-catalog.d.ts +37 -0
  36. package/dist/client/billing/renewalObservation/reference-catalog.d.ts.map +1 -0
  37. package/dist/client/billing/renewalObservation/reference-catalog.js +109 -0
  38. package/dist/client/billing/renewalObservation/reference-catalog.js.map +1 -0
  39. package/dist/client/billing/renewalObservation/schedule-templates.d.ts +74 -0
  40. package/dist/client/billing/renewalObservation/schedule-templates.d.ts.map +1 -0
  41. package/dist/client/billing/renewalObservation/schedule-templates.js +72 -0
  42. package/dist/client/billing/renewalObservation/schedule-templates.js.map +1 -0
  43. package/dist/client/billing/renewalObservation/scheduled-context.d.ts +44 -0
  44. package/dist/client/billing/renewalObservation/scheduled-context.d.ts.map +1 -0
  45. package/dist/client/billing/renewalObservation/scheduled-context.js +64 -0
  46. package/dist/client/billing/renewalObservation/scheduled-context.js.map +1 -0
  47. package/dist/client/billing/renewalObservation/scheduled-identity.d.ts +53 -0
  48. package/dist/client/billing/renewalObservation/scheduled-identity.d.ts.map +1 -0
  49. package/dist/client/billing/renewalObservation/scheduled-identity.js +95 -0
  50. package/dist/client/billing/renewalObservation/scheduled-identity.js.map +1 -0
  51. package/dist/client/billing/renewalObservation/scheduled-normalization.d.ts +59 -0
  52. package/dist/client/billing/renewalObservation/scheduled-normalization.d.ts.map +1 -0
  53. package/dist/client/billing/renewalObservation/scheduled-normalization.js +29 -0
  54. package/dist/client/billing/renewalObservation/scheduled-normalization.js.map +1 -0
  55. package/dist/client/billing/renewalObservation/settings-normalization.d.ts +54 -0
  56. package/dist/client/billing/renewalObservation/settings-normalization.d.ts.map +1 -0
  57. package/dist/client/billing/renewalObservation/settings-normalization.js +53 -0
  58. package/dist/client/billing/renewalObservation/settings-normalization.js.map +1 -0
  59. package/dist/client/billing/renewalObservation/stage-runner.d.ts +4 -0
  60. package/dist/client/billing/renewalObservation/stage-runner.d.ts.map +1 -0
  61. package/dist/client/billing/renewalObservation/stage-runner.js +34 -0
  62. package/dist/client/billing/renewalObservation/stage-runner.js.map +1 -0
  63. package/dist/client/billing/renewalObservation/weeklyPending.d.ts +13 -0
  64. package/dist/client/billing/renewalObservation/weeklyPending.d.ts.map +1 -0
  65. package/dist/client/billing/renewalObservation/weeklyPending.js +55 -0
  66. package/dist/client/billing/renewalObservation/weeklyPending.js.map +1 -0
  67. package/dist/client/billing/renewalV2/binding.d.ts +1 -1
  68. package/dist/client/billing/renewalV2/binding.d.ts.map +1 -1
  69. package/dist/client/billing/renewalV2/binding.js.map +1 -1
  70. package/dist/client/billing/renewalV2/configureInput.d.ts +1 -0
  71. package/dist/client/billing/renewalV2/configureInput.d.ts.map +1 -1
  72. package/dist/client/billing/renewalV2/configureInput.js +3 -3
  73. package/dist/client/billing/renewalV2/configureInput.js.map +1 -1
  74. package/dist/client/billing/renewalV2/configureReceipt.d.ts +19 -0
  75. package/dist/client/billing/renewalV2/configureReceipt.d.ts.map +1 -0
  76. package/dist/client/billing/renewalV2/configureReceipt.js +91 -0
  77. package/dist/client/billing/renewalV2/configureReceipt.js.map +1 -0
  78. package/dist/client/billing/renewalV2/index.d.ts +417 -0
  79. package/dist/client/billing/renewalV2/index.d.ts.map +1 -1
  80. package/dist/client/billing/renewalV2/index.js +73 -3
  81. package/dist/client/billing/renewalV2/index.js.map +1 -1
  82. package/dist/client/billing/renewalV2/observation.d.ts +19 -0
  83. package/dist/client/billing/renewalV2/observation.d.ts.map +1 -0
  84. package/dist/client/billing/renewalV2/observation.js +95 -0
  85. package/dist/client/billing/renewalV2/observation.js.map +1 -0
  86. package/dist/client/billing/renewalV2/observationInput.d.ts +77 -0
  87. package/dist/client/billing/renewalV2/observationInput.d.ts.map +1 -0
  88. package/dist/client/billing/renewalV2/observationInput.js +140 -0
  89. package/dist/client/billing/renewalV2/observationInput.js.map +1 -0
  90. package/dist/client/connect/payoutAdoptionTestHelpers.d.ts +32 -32
  91. package/dist/client/connect/payoutExecutionTestHelpers.d.ts +16 -16
  92. package/dist/client/renewal.d.ts +4 -2
  93. package/dist/client/renewal.d.ts.map +1 -1
  94. package/dist/client/renewal.js +2 -1
  95. package/dist/client/renewal.js.map +1 -1
  96. package/dist/client/usage/observationClient.d.ts +2 -2
  97. package/dist/client/usage/observationClient.d.ts.map +1 -1
  98. package/dist/component/balanceFunding/internal/actions.d.ts +11 -11
  99. package/dist/component/balanceFunding/mutations.d.ts +16 -16
  100. package/dist/component/balanceFunding/preparationHandlers.d.ts +8 -8
  101. package/dist/component/usage/allowance.fixtures.d.ts +16 -16
  102. package/docs/client-api.md +26 -0
  103. package/docs/renewal-context-reads.md +5 -1
  104. package/docs/renewal-material-observation.md +124 -0
  105. package/docs/renewal-phase-assembly.md +68 -0
  106. package/docs/renewal-price-replacements.md +3 -0
  107. package/package.json +1 -1
  108. package/src/client/billing/renewalObservation/active-scheduled.ts +67 -0
  109. package/src/client/billing/renewalObservation/common.ts +83 -0
  110. package/src/client/billing/renewalObservation/configured-baseline.ts +55 -0
  111. package/src/client/billing/renewalObservation/coupon-discount-joins.ts +163 -0
  112. package/src/client/billing/renewalObservation/invoice-tax-identity.ts +65 -0
  113. package/src/client/billing/renewalObservation/pending-and-stage.ts +89 -0
  114. package/src/client/billing/renewalObservation/phase-price-normalization.ts +106 -0
  115. package/src/client/billing/renewalObservation/planProjection.ts +177 -0
  116. package/src/client/billing/renewalObservation/reference-catalog.ts +150 -0
  117. package/src/client/billing/renewalObservation/schedule-templates.ts +118 -0
  118. package/src/client/billing/renewalObservation/scheduled-context.ts +98 -0
  119. package/src/client/billing/renewalObservation/scheduled-identity.ts +175 -0
  120. package/src/client/billing/renewalObservation/scheduled-normalization.ts +49 -0
  121. package/src/client/billing/renewalObservation/settings-normalization.ts +60 -0
  122. package/src/client/billing/renewalObservation/stage-runner.ts +30 -0
  123. package/src/client/billing/renewalObservation/weeklyPending.ts +81 -0
  124. package/src/client/billing/renewalV2/binding.ts +4 -1
  125. package/src/client/billing/renewalV2/configureInput.ts +3 -3
  126. package/src/client/billing/renewalV2/configureReceipt.test.ts +558 -0
  127. package/src/client/billing/renewalV2/configureReceipt.ts +96 -0
  128. package/src/client/billing/renewalV2/index.ts +131 -6
  129. package/src/client/billing/renewalV2/observation.boundary-review.test.ts +49 -0
  130. package/src/client/billing/renewalV2/observation.test.ts +334 -0
  131. package/src/client/billing/renewalV2/observation.ts +149 -0
  132. package/src/client/billing/renewalV2/observationInput.ts +167 -0
  133. package/src/client/renewal.ts +10 -0
@@ -0,0 +1,81 @@
1
+ import { object, get, array, need, type O } from "./common.js";
2
+ function noReset(sub: O) {
3
+ return (
4
+ sub.billing_cycle_anchor_config === null &&
5
+ sub.trial_start === null &&
6
+ sub.trial_end === null &&
7
+ sub.billing_thresholds === null &&
8
+ sub.cancel_at === null &&
9
+ sub.canceled_at === null &&
10
+ sub.cancel_at_period_end === false &&
11
+ sub.pending_update === null &&
12
+ sub.pause_collection === null &&
13
+ array(get(sub, "items").data).every((x) => {
14
+ const i = object(x);
15
+ return (
16
+ i.billing_thresholds === null &&
17
+ (i.current_trial === null ||
18
+ !Object.prototype.hasOwnProperty.call(i, "current_trial"))
19
+ );
20
+ })
21
+ );
22
+ }
23
+ /** Narrow UTC-week inference. Never takes an expected end or caller evidence. */
24
+ export function weeklyPending(state: {
25
+ desired: O;
26
+ originalSub: O;
27
+ sub: O;
28
+ expected: O;
29
+ target: O;
30
+ targetPhase: O;
31
+ schedule: O;
32
+ phases: unknown[];
33
+ }) {
34
+ const profile = get(state.desired, "profile"),
35
+ target = get(state.target, "recurring");
36
+ if (
37
+ profile.billingMode !== "classic" ||
38
+ profile.cadence !== "changed" ||
39
+ profile.anchor !== "ordinary" ||
40
+ target.interval !== "week" ||
41
+ target.interval_count !== 1 ||
42
+ target.usage_type !== "licensed" ||
43
+ state.schedule.end_behavior !== "release" ||
44
+ !noReset(state.originalSub) ||
45
+ !noReset(state.sub)
46
+ )
47
+ return false;
48
+ const phases = array(get(state.desired, "payload").phases),
49
+ desired = object(phases[1]),
50
+ duration = get(desired, "duration");
51
+ if (
52
+ duration.interval !== "week" ||
53
+ duration.interval_count !== 1 ||
54
+ desired.billing_cycle_anchor !== "phase_start" ||
55
+ state.targetPhase.billing_cycle_anchor !== "phase_start" ||
56
+ !state.phases.every((p) => {
57
+ const phase = object(p);
58
+ return (
59
+ phase.trial === false &&
60
+ phase.trial_end === null &&
61
+ phase.billing_thresholds === null
62
+ );
63
+ })
64
+ )
65
+ return false;
66
+ const start = state.expected.periodEnd;
67
+ if (
68
+ !Number.isSafeInteger(start) ||
69
+ typeof start !== "number" ||
70
+ start < 0 ||
71
+ !Number.isSafeInteger(start + 604800)
72
+ )
73
+ return false;
74
+ const expectedEnd = start + 604800;
75
+ need(
76
+ state.targetPhase.start_date === start &&
77
+ state.targetPhase.end_date === expectedEnd,
78
+ "target_phase_duration_mismatch",
79
+ );
80
+ return true;
81
+ }
@@ -8,7 +8,10 @@ export async function renewalBindingV2(
8
8
  | "renewal-attach-receipt"
9
9
  | "renewal-baseline"
10
10
  | "renewal-defaults"
11
- | "renewal-configure",
11
+ | "renewal-configure"
12
+ | "renewal-configured-baseline"
13
+ | "renewal-configured-defaults"
14
+ | "renewal-configure-receipt",
12
15
  preimage: unknown,
13
16
  ): Promise<string> {
14
17
  // Finish all input capture and canonical bytes before the first await.
@@ -26,7 +26,7 @@ function ownData(raw: unknown, required: string[], optional: string[] = []) {
26
26
  }
27
27
  return fields;
28
28
  }
29
- function closed(raw: unknown) {
29
+ export function validateConfigurationFields(raw: unknown) {
30
30
  const root = ownData(
31
31
  raw,
32
32
  [
@@ -73,9 +73,9 @@ const input = z
73
73
  })
74
74
  .strict();
75
75
  export function captureConfiguration(raw: unknown) {
76
- closed(raw);
76
+ validateConfigurationFields(raw);
77
77
  const captured = renewalSnapshot(raw);
78
- closed(captured);
78
+ validateConfigurationFields(captured);
79
79
  const args = input.parse(captured);
80
80
  return {
81
81
  ...args,
@@ -0,0 +1,558 @@
1
+ import { afterEach, expect, it, vi } from "vitest";
2
+ import { createHash, webcrypto } from "node:crypto";
3
+ import * as sdk from "./index.js";
4
+ import { renewalSnapshot } from "../renewalReplacementSnapshot.js";
5
+ import { fixture } from "../../../../tests/renewalAggregate/fixtures.js";
6
+
7
+ const construct = (raw: any) => sdk.constructRenewalConfigurationReceiptV2(raw);
8
+ async function input() {
9
+ const f = fixture(),
10
+ preparation = {
11
+ subscription: f.subscription,
12
+ targetPrice: f.targetPrice,
13
+ billingCustomer: f.billingCustomer,
14
+ expected: f.prepared.expected,
15
+ key: f.prepared.requestIdentity.key,
16
+ };
17
+ const configuration = {
18
+ preparation,
19
+ attachReceipt: {
20
+ attachRequest: {
21
+ preparation: structuredClone(preparation),
22
+ apiVersion: f.attachRequest.apiVersion,
23
+ attachKey: f.attachRequest.key,
24
+ firstDispatchedAt: f.attachRequest.firstDispatchedAt,
25
+ },
26
+ actualDispatch: {
27
+ scope: "platform" as const,
28
+ apiVersion: f.attachRequest.apiVersion,
29
+ method: "POST" as const,
30
+ path: "/v1/subscription_schedules" as const,
31
+ payload: f.attachRequest.payload,
32
+ key: f.attachRequest.key,
33
+ firstDispatchedAt: f.attachRequest.firstDispatchedAt,
34
+ },
35
+ providerSnapshot: structuredClone(f.schedule),
36
+ },
37
+ freshSubscription: f.configureInput.freshSubscription,
38
+ targetPrice: f.targetPrice,
39
+ billingCustomer: f.billingCustomer,
40
+ schedule: structuredClone(f.schedule),
41
+ apiVersion: f.configureInput.apiVersion,
42
+ observedAt: f.configureInput.observedAt,
43
+ firstDispatchedAt: f.configureInput.firstDispatchedAt,
44
+ configureKey: f.configureInput.configureKey,
45
+ };
46
+ const request = await sdk.projectRenewalConfigurationV2(configuration);
47
+ if (request.status !== "projected_configure_request") throw Error("fixture");
48
+ const { scope, apiVersion, method, path, payload, key, firstDispatchedAt } =
49
+ request;
50
+ return {
51
+ configuration,
52
+ actualDispatch: {
53
+ scope,
54
+ apiVersion,
55
+ method,
56
+ path,
57
+ payload,
58
+ key,
59
+ firstDispatchedAt,
60
+ },
61
+ providerSnapshot: structuredClone(f.schedule),
62
+ transport: { status: 200 } as { status: number; requestId?: string },
63
+ };
64
+ }
65
+ const digest = (family: string, value: unknown) =>
66
+ `${family}:v2:sha256:${createHash("sha256")
67
+ .update(
68
+ JSON.stringify(
69
+ renewalSnapshot(["betterstripe-renewal-binding", 2, family, value]),
70
+ ),
71
+ "utf8",
72
+ )
73
+ .digest("hex")}`;
74
+ afterEach(() => vi.unstubAllGlobals());
75
+ it("constructs the complete unsigned C9 record with independent C7/C8/C9 hashes", async () => {
76
+ expect(sdk.constructRenewalConfigurationReceiptV2).toBeTypeOf("function");
77
+ const raw = await input(),
78
+ before = structuredClone(raw);
79
+ const options: sdk.ConstructRenewalConfigurationReceiptV2Options = raw;
80
+ const result: sdk.RenewalConfigurationReceiptV2 =
81
+ await sdk.constructRenewalConfigurationReceiptV2(options);
82
+ expect(result).toMatchObject({
83
+ version: 2,
84
+ stage: "configure_acknowledged",
85
+ scope: "platform",
86
+ verification: "owned_response_only",
87
+ scheduleId: "sub_sched_owned",
88
+ subscriptionId: "sub_original",
89
+ customerAccountId: "acct_buyer",
90
+ billingCustomerId: "cus_buyer",
91
+ livemode: false,
92
+ });
93
+ expect(result.request).toEqual(
94
+ await sdk.projectRenewalConfigurationV2(raw.configuration),
95
+ );
96
+ expect(result.providerSnapshot).toEqual(raw.providerSnapshot);
97
+ expect(result.transport).toEqual(raw.transport);
98
+ expect(result.providerSnapshotBinding).toBe(
99
+ digest("renewal-configured-baseline", raw.providerSnapshot),
100
+ );
101
+ expect(result.defaultSettingsBinding).toBe(
102
+ digest(
103
+ "renewal-configured-defaults",
104
+ raw.providerSnapshot.default_settings,
105
+ ),
106
+ );
107
+ const { binding, ...unsigned } = result;
108
+ expect(binding).toBe(digest("renewal-configure-receipt", unsigned));
109
+ expect(raw).toEqual(before);
110
+ expect(JSON.stringify(result).length).toBeLessThan(500000);
111
+ });
112
+ it.each([
113
+ "scope",
114
+ "apiVersion",
115
+ "method",
116
+ "path",
117
+ "payload",
118
+ "key",
119
+ "firstDispatchedAt",
120
+ ])("compares complete actual configure dispatch %s", async (field) => {
121
+ const raw: any = await input();
122
+ raw.actualDispatch[field] =
123
+ field === "payload"
124
+ ? { ...raw.actualDispatch.payload, extra: true }
125
+ : field === "firstDispatchedAt"
126
+ ? raw.actualDispatch[field] + 1
127
+ : "changed";
128
+ await expect(construct(raw)).rejects.toThrow();
129
+ });
130
+ it.each([199, 300, 200.5, NaN])(
131
+ "rejects invalid transport status %s before hashing",
132
+ async (status) => {
133
+ const raw = await input();
134
+ raw.transport.status = status;
135
+ const digest = vi.fn();
136
+ vi.stubGlobal("crypto", { subtle: { digest } });
137
+ await expect(construct(raw)).rejects.toThrow();
138
+ expect(digest).not.toHaveBeenCalled();
139
+ },
140
+ );
141
+ it.each([200, 299])(
142
+ "retains actual transport status %s and optional request ID",
143
+ async (status) => {
144
+ const raw = await input();
145
+ raw.transport = { status, requestId: "r".repeat(status === 200 ? 1 : 255) };
146
+ expect((await construct(raw)).transport).toEqual(raw.transport);
147
+ },
148
+ );
149
+ it.each(["", "r".repeat(256), 0, null, undefined])(
150
+ "rejects present invalid requestId %s",
151
+ async (requestId) => {
152
+ const raw: any = await input();
153
+ raw.transport.requestId = requestId;
154
+ await expect(construct(raw)).rejects.toThrow();
155
+ },
156
+ );
157
+ it.each(["absent", "null", "object"])(
158
+ "preserves configured defaults presence %s without inventing application facts",
159
+ async (kind) => {
160
+ const raw: any = await input();
161
+ if (kind === "absent") delete raw.providerSnapshot.default_settings;
162
+ else
163
+ raw.providerSnapshot.default_settings =
164
+ kind === "null" ? null : { future_field: ["retained"] };
165
+ const result = await construct(raw);
166
+ expect(result.providerSnapshot).toEqual(raw.providerSnapshot);
167
+ expect(
168
+ Object.prototype.hasOwnProperty.call(result, "defaultSettingsBinding"),
169
+ ).toBe(kind !== "absent");
170
+ if (kind !== "absent")
171
+ expect(result.defaultSettingsBinding).toBe(
172
+ digest(
173
+ "renewal-configured-defaults",
174
+ raw.providerSnapshot.default_settings,
175
+ ),
176
+ );
177
+ const { binding, ...unsigned } = result;
178
+ expect(binding).toBe(digest("renewal-configure-receipt", unsigned));
179
+ },
180
+ );
181
+ it("preserves special own JSON keys throughout response, defaults and hashes", async () => {
182
+ const raw: any = await input();
183
+ for (const body of [
184
+ raw.providerSnapshot,
185
+ raw.providerSnapshot.default_settings,
186
+ ])
187
+ Object.defineProperty(body, "__proto__", {
188
+ enumerable: true,
189
+ value: { retained: true },
190
+ });
191
+ const result = await construct(raw);
192
+ expect(result.providerSnapshot).toEqual(
193
+ JSON.parse(JSON.stringify(raw.providerSnapshot)),
194
+ );
195
+ expect(
196
+ Object.prototype.hasOwnProperty.call(result.providerSnapshot, "__proto__"),
197
+ ).toBe(true);
198
+ expect(result.providerSnapshotBinding).toBe(
199
+ digest("renewal-configured-baseline", raw.providerSnapshot),
200
+ );
201
+ expect(result.defaultSettingsBinding).toBe(
202
+ digest(
203
+ "renewal-configured-defaults",
204
+ raw.providerSnapshot.default_settings,
205
+ ),
206
+ );
207
+ });
208
+ it.each([
209
+ "schedule",
210
+ "customer",
211
+ "subscription",
212
+ "account",
213
+ "mode",
214
+ "deleted",
215
+ "expanded",
216
+ ])("rejects incompatible available response identity %s", async (kind) => {
217
+ const raw: any = await input(),
218
+ b = raw.providerSnapshot;
219
+ if (kind === "schedule") b.id = "sub_sched_foreign";
220
+ else if (kind === "account") b.customer_account = "acct_other";
221
+ else if (kind === "mode") b.livemode = true;
222
+ else if (kind === "deleted") b.deleted = true;
223
+ else if (kind === "expanded")
224
+ b.subscription = {
225
+ id: "sub_original",
226
+ object: "subscription",
227
+ schedule: {
228
+ id: b.id,
229
+ object: "subscription_schedule",
230
+ customer: "cus_foreign",
231
+ },
232
+ };
233
+ else b[kind] = kind === "customer" ? "cus_foreign" : "sub_foreign";
234
+ await expect(construct(raw)).rejects.toThrow();
235
+ });
236
+ it("records operation-only consistency without requiring phases/defaults to match the request", async () => {
237
+ const raw: any = await input();
238
+ raw.providerSnapshot.phases = [{ observed: "different" }];
239
+ raw.providerSnapshot.default_settings = null;
240
+ const result = await construct(raw);
241
+ expect(result.request.payload.phases).toHaveLength(2);
242
+ expect(result.providerSnapshot.phases).toEqual([{ observed: "different" }]);
243
+ expect(result).not.toHaveProperty("nativeQualificationAccepted");
244
+ });
245
+ it.each([true, false])(
246
+ "rejects own lastResponse even when enumerable=%s",
247
+ async (enumerable) => {
248
+ const raw = await input();
249
+ Object.defineProperty(raw.providerSnapshot, "lastResponse", {
250
+ enumerable,
251
+ value: null,
252
+ });
253
+ await expect(construct(raw)).rejects.toThrow();
254
+ },
255
+ );
256
+ it.each(["root", "configuration", "actualDispatch", "transport"])(
257
+ "rejects unknown %s names before inspecting values",
258
+ async (where) => {
259
+ const raw: any = await input(),
260
+ target = where === "root" ? raw : raw[where];
261
+ const read = vi.fn();
262
+ Object.defineProperty(target, "unexpected", {
263
+ enumerable: true,
264
+ get: read,
265
+ });
266
+ await expect(construct(raw)).rejects.toThrow();
267
+ expect(read).not.toHaveBeenCalled();
268
+ },
269
+ );
270
+ it("rechecks required nested configuration fields after capture before hashing", async () => {
271
+ const raw: any = await input(),
272
+ target = raw.configuration;
273
+ raw.configuration = new Proxy(target, {
274
+ getPrototypeOf(t) {
275
+ delete t.observedAt;
276
+ return Object.prototype;
277
+ },
278
+ });
279
+ const digest = vi.fn();
280
+ vi.stubGlobal("crypto", { subtle: { digest } });
281
+ await expect(construct(raw)).rejects.toThrow();
282
+ expect(digest).not.toHaveBeenCalled();
283
+ });
284
+ it("rejects C6 Failure with a fixed error while C6 itself retains Failure data", async () => {
285
+ const raw = await input();
286
+ raw.configuration.configureKey =
287
+ raw.configuration.attachReceipt.actualDispatch.key;
288
+ expect(
289
+ await sdk.projectRenewalConfigurationV2(raw.configuration),
290
+ ).toMatchObject({
291
+ status: "attached_unconfigured",
292
+ reason: "configure_key_must_be_distinct",
293
+ });
294
+ await expect(construct(raw)).rejects.toThrow(
295
+ "Invalid renewal configuration receipt input.",
296
+ );
297
+ });
298
+ it("captures response/transport/default presence before its first await", async () => {
299
+ const raw: any = await input(),
300
+ before = structuredClone(raw);
301
+ let release!: () => void;
302
+ const held = new Promise<void>((r) => {
303
+ release = r;
304
+ });
305
+ let calls = 0;
306
+ vi.stubGlobal("crypto", {
307
+ subtle: {
308
+ async digest(
309
+ algorithm: string,
310
+ bytes: Parameters<typeof webcrypto.subtle.digest>[1],
311
+ ) {
312
+ if (++calls === 1) await held;
313
+ return webcrypto.subtle.digest(algorithm, bytes);
314
+ },
315
+ },
316
+ });
317
+ const pending = construct(raw);
318
+ raw.providerSnapshot.customer = "cus_changed";
319
+ delete raw.providerSnapshot.default_settings;
320
+ raw.transport.requestId = "changed";
321
+ release();
322
+ const result = await pending;
323
+ expect(result.providerSnapshot).toEqual(before.providerSnapshot);
324
+ expect(result.transport).toEqual(before.transport);
325
+ });
326
+ it.each(["reject", "invalid"])(
327
+ "rejects %s crypto responses without fallback",
328
+ async (kind) => {
329
+ const raw = await input();
330
+ vi.stubGlobal("crypto", {
331
+ subtle: {
332
+ digest: () =>
333
+ kind === "reject"
334
+ ? Promise.reject(Error("private"))
335
+ : Promise.resolve(new ArrayBuffer(1)),
336
+ },
337
+ });
338
+ await expect(construct(raw)).rejects.toThrow(
339
+ "Invalid renewal configuration receipt input.",
340
+ );
341
+ },
342
+ );
343
+ it("enforces UTF-8 preimage and complete input budgets", async () => {
344
+ const raw: any = await input();
345
+ raw.providerSnapshot.unicode = "\u0800".repeat(170000);
346
+ await expect(construct(raw)).rejects.toThrow();
347
+ raw.providerSnapshot.unicode = "x".repeat(500000);
348
+ await expect(construct(raw)).rejects.toThrow();
349
+ });
350
+ it("rejects excessive input depth before hashing", async () => {
351
+ const raw: any = await input();
352
+ let nested: unknown = null;
353
+ for (let i = 0; i < 41; i++) nested = { next: nested };
354
+ raw.providerSnapshot.deep = nested;
355
+ const digest = vi.fn();
356
+ vi.stubGlobal("crypto", { subtle: { digest } });
357
+ await expect(construct(raw)).rejects.toThrow();
358
+ expect(digest).not.toHaveBeenCalled();
359
+ });
360
+ it("fits near-limit complete input and retains bounded output without truncation", async () => {
361
+ const raw: any = await input();
362
+ raw.providerSnapshot.padding = "";
363
+ raw.providerSnapshot.padding = "x".repeat(
364
+ 500000 - JSON.stringify(raw).length - 256,
365
+ );
366
+ const inputBytes = Buffer.byteLength(JSON.stringify(raw), "utf8"),
367
+ result = await construct(raw);
368
+ const outputBytes = Buffer.byteLength(JSON.stringify(result), "utf8");
369
+ expect(inputBytes).toBe(499744);
370
+ expect(outputBytes).toBeLessThanOrEqual(500000);
371
+ expect(result.providerSnapshot.padding).toBe(raw.providerSnapshot.padding);
372
+ raw.providerSnapshot.padding += "x".repeat(512);
373
+ await expect(construct(raw)).rejects.toThrow();
374
+ });
375
+ it.each([
376
+ "renewal-configured-baseline",
377
+ "renewal-configured-defaults",
378
+ "renewal-configure-receipt",
379
+ ])("rejects late errors and invalid digests for %s", async (family) => {
380
+ for (const kind of ["reject", "invalid"]) {
381
+ const raw = await input();
382
+ let reached = false;
383
+ vi.stubGlobal("crypto", {
384
+ subtle: {
385
+ async digest(
386
+ algorithm: string,
387
+ bytes: Parameters<typeof webcrypto.subtle.digest>[1],
388
+ ) {
389
+ const encoded = JSON.parse(
390
+ Buffer.from(bytes as Uint8Array).toString("utf8"),
391
+ );
392
+ if (encoded[2] === family) {
393
+ reached = true;
394
+ if (kind === "reject") throw Error("private");
395
+ return new ArrayBuffer(1);
396
+ }
397
+ return webcrypto.subtle.digest(algorithm, bytes);
398
+ },
399
+ },
400
+ });
401
+ await expect(construct(raw)).rejects.toThrow(
402
+ "Invalid renewal configuration receipt input.",
403
+ );
404
+ expect(reached).toBe(true);
405
+ vi.unstubAllGlobals();
406
+ }
407
+ });
408
+ it("accepts complete matching expanded response identities", async () => {
409
+ const raw: any = await input();
410
+ raw.providerSnapshot.customer = {
411
+ id: "cus_buyer",
412
+ object: "customer",
413
+ livemode: false,
414
+ customer_account: "acct_buyer",
415
+ unknown_field: true,
416
+ };
417
+ raw.providerSnapshot.subscription = {
418
+ id: "sub_original",
419
+ object: "subscription",
420
+ deleted: false,
421
+ customer: structuredClone(raw.providerSnapshot.customer),
422
+ schedule: {
423
+ id: raw.providerSnapshot.id,
424
+ object: "subscription_schedule",
425
+ subscription: "sub_original",
426
+ },
427
+ };
428
+ expect((await construct(raw)).providerSnapshot).toEqual(raw.providerSnapshot);
429
+ });
430
+ it("does not accept an incoming C6 output as raw configuration", async () => {
431
+ const raw: any = await input();
432
+ raw.configuration = await sdk.projectRenewalConfigurationV2(
433
+ raw.configuration,
434
+ );
435
+ await expect(construct(raw)).rejects.toThrow();
436
+ });
437
+ it("rejects hidden response metadata introduced by reflection during capture", async () => {
438
+ const raw: any = await input(),
439
+ body = raw.providerSnapshot;
440
+ raw.providerSnapshot = new Proxy(body, {
441
+ getPrototypeOf(target) {
442
+ Object.defineProperty(target, "lastResponse", {
443
+ enumerable: false,
444
+ value: null,
445
+ });
446
+ return Object.prototype;
447
+ },
448
+ });
449
+ const digest = vi.fn();
450
+ vi.stubGlobal("crypto", { subtle: { digest } });
451
+ await expect(construct(raw)).rejects.toThrow();
452
+ expect(digest).not.toHaveBeenCalled();
453
+ });
454
+ it("validates the raw prototype before selecting a body swapped by reflection", async () => {
455
+ const raw: any = await input(),
456
+ replacement = structuredClone(raw.providerSnapshot),
457
+ metadataRead = vi.fn();
458
+ Object.defineProperty(replacement, "lastResponse", {
459
+ enumerable: false,
460
+ get: metadataRead,
461
+ });
462
+ let swaps = 0;
463
+ const wrapped = new Proxy(raw, {
464
+ getPrototypeOf(target) {
465
+ swaps++;
466
+ target.providerSnapshot = replacement;
467
+ return Object.prototype;
468
+ },
469
+ });
470
+ const digest = vi.fn(
471
+ (algorithm: string, bytes: Parameters<typeof webcrypto.subtle.digest>[1]) =>
472
+ webcrypto.subtle.digest(algorithm, bytes),
473
+ );
474
+ vi.stubGlobal("crypto", { subtle: { digest } });
475
+ await expect(construct(wrapped)).rejects.toThrow(
476
+ "Invalid renewal configuration receipt input.",
477
+ );
478
+ expect(swaps).toBe(1);
479
+ expect(digest).not.toHaveBeenCalled();
480
+ expect(metadataRead).not.toHaveBeenCalled();
481
+ });
482
+ it.each(["class", "custom"])(
483
+ "rejects a %s raw-root prototype before hashing",
484
+ async (kind) => {
485
+ const raw = await input();
486
+ class Wrapper {}
487
+ const wrapped = Object.assign(
488
+ kind === "class" ? new Wrapper() : Object.create({ inherited: true }),
489
+ raw,
490
+ );
491
+ const digest = vi.fn(
492
+ (
493
+ algorithm: string,
494
+ bytes: Parameters<typeof webcrypto.subtle.digest>[1],
495
+ ) => webcrypto.subtle.digest(algorithm, bytes),
496
+ );
497
+ vi.stubGlobal("crypto", { subtle: { digest } });
498
+ await expect(construct(wrapped)).rejects.toThrow(
499
+ "Invalid renewal configuration receipt input.",
500
+ );
501
+ expect(digest).not.toHaveBeenCalled();
502
+ },
503
+ );
504
+ it("retains null-prototype raw own-data roots", async () => {
505
+ const raw = await input(),
506
+ wrapped = Object.assign(Object.create(null), raw),
507
+ result = await construct(wrapped);
508
+ expect(result.providerSnapshot).toEqual(raw.providerSnapshot);
509
+ expect(result.stage).toBe("configure_acknowledged");
510
+ });
511
+ it("accepts a benign Proxy while querying its plain prototype only once", async () => {
512
+ const raw = await input();
513
+ let checks = 0;
514
+ const wrapped = new Proxy(raw, {
515
+ getPrototypeOf() {
516
+ checks++;
517
+ return Object.prototype;
518
+ },
519
+ });
520
+ const result = await construct(wrapped);
521
+ expect(checks).toBe(1);
522
+ expect(result.providerSnapshot).toEqual(raw.providerSnapshot);
523
+ });
524
+ it.each(["symbol", "nonEnumerable", "accessor", "cycle", "sparse"])(
525
+ "rejects invalid raw %s before hashing",
526
+ async (kind) => {
527
+ const raw: any = await input(),
528
+ read = vi.fn();
529
+ if (kind === "symbol") raw[Symbol("unexpected")] = true;
530
+ else if (kind === "nonEnumerable")
531
+ Object.defineProperty(raw.transport, "status", {
532
+ value: 200,
533
+ enumerable: false,
534
+ });
535
+ else if (kind === "accessor")
536
+ Object.defineProperty(raw, "providerSnapshot", {
537
+ enumerable: true,
538
+ get: read,
539
+ });
540
+ else if (kind === "cycle")
541
+ raw.providerSnapshot.circular = raw.providerSnapshot;
542
+ else raw.providerSnapshot.future = new Array(1);
543
+ const digest = vi.fn();
544
+ vi.stubGlobal("crypto", { subtle: { digest } });
545
+ await expect(construct(raw)).rejects.toThrow();
546
+ expect(read).not.toHaveBeenCalled();
547
+ expect(digest).not.toHaveBeenCalled();
548
+ },
549
+ );
550
+ it("exports only the named public constructor and types", async () => {
551
+ const root = await import("../../index.js");
552
+ expect(root).toHaveProperty(
553
+ "constructRenewalConfigurationReceiptV2",
554
+ sdk.constructRenewalConfigurationReceiptV2,
555
+ );
556
+ expect(root).not.toHaveProperty("captureConfigurationReceipt");
557
+ expect(root).not.toHaveProperty("renewalBindingV2");
558
+ });