@fantastic.dev/better-stripe 0.110.0 → 0.112.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 (134) hide show
  1. package/CHANGELOG.md +12 -0
  2. package/README.md +1 -1
  3. package/dist/client/billing/renewalAttach/internal/observation/freshActor.d.ts +564 -0
  4. package/dist/client/billing/renewalAttach/internal/observation/freshActor.d.ts.map +1 -1
  5. package/dist/client/billing/renewalAttach/internal/observation/freshActor.js +103 -21
  6. package/dist/client/billing/renewalAttach/internal/observation/freshActor.js.map +1 -1
  7. package/dist/client/billing/renewalAttach/internal/observation/freshTransport.d.ts +18 -1
  8. package/dist/client/billing/renewalAttach/internal/observation/freshTransport.d.ts.map +1 -1
  9. package/dist/client/billing/renewalAttach/internal/observation/freshTransport.js +54 -1
  10. package/dist/client/billing/renewalAttach/internal/observation/freshTransport.js.map +1 -1
  11. package/dist/client/billing/renewalAttach/internal/observation/invocation.d.ts +4 -0
  12. package/dist/client/billing/renewalAttach/internal/observation/invocation.d.ts.map +1 -1
  13. package/dist/client/billing/renewalAttach/internal/observation/invocation.js +1 -0
  14. package/dist/client/billing/renewalAttach/internal/observation/invocation.js.map +1 -1
  15. package/dist/client/billing/renewalAttach/internal/observation/readerAuthorization.d.ts +4 -0
  16. package/dist/client/billing/renewalAttach/internal/observation/readerAuthorization.d.ts.map +1 -1
  17. package/dist/client/billing/renewalAttach/internal/observation/readerAuthorization.js +6 -1
  18. package/dist/client/billing/renewalAttach/internal/observation/readerAuthorization.js.map +1 -1
  19. package/dist/client/billing/renewalAttach/internal/observation/witnessAuthorization.d.ts +38 -0
  20. package/dist/client/billing/renewalAttach/internal/observation/witnessAuthorization.d.ts.map +1 -0
  21. package/dist/client/billing/renewalAttach/internal/observation/witnessAuthorization.js +172 -0
  22. package/dist/client/billing/renewalAttach/internal/observation/witnessAuthorization.js.map +1 -0
  23. package/dist/client/billing/renewalAttach/internal/observation/witnessData.d.ts +135 -0
  24. package/dist/client/billing/renewalAttach/internal/observation/witnessData.d.ts.map +1 -0
  25. package/dist/client/billing/renewalAttach/internal/observation/witnessData.js +143 -0
  26. package/dist/client/billing/renewalAttach/internal/observation/witnessData.js.map +1 -0
  27. package/dist/client/billing/renewalAttach/internal/observation/witnessOperation.d.ts +85 -0
  28. package/dist/client/billing/renewalAttach/internal/observation/witnessOperation.d.ts.map +1 -0
  29. package/dist/client/billing/renewalAttach/internal/observation/witnessOperation.js +121 -0
  30. package/dist/client/billing/renewalAttach/internal/observation/witnessOperation.js.map +1 -0
  31. package/dist/client/billing/renewalAttach/internal/operations/witnessProfiles.d.ts +44 -0
  32. package/dist/client/billing/renewalAttach/internal/operations/witnessProfiles.d.ts.map +1 -0
  33. package/dist/client/billing/renewalAttach/internal/operations/witnessProfiles.js +4 -0
  34. package/dist/client/billing/renewalAttach/internal/operations/witnessProfiles.js.map +1 -0
  35. package/dist/client/billing/renewalAttach/internal/producer/configureJournalWork.d.ts +1 -1
  36. package/dist/client/billing/renewalAttach/internal/producer/configureLineage.d.ts +21 -21
  37. package/dist/client/billing/renewalAttach/internal/producer/journalWorkFactory.d.ts +3 -3
  38. package/dist/client/billing/renewalAttach/internal/producer/operationFactory.d.ts +1 -1
  39. package/dist/client/connect/payoutAdoptionTestHelpers.d.ts +84 -32
  40. package/dist/client/connect/payoutAdoptionTestHelpers.d.ts.map +1 -1
  41. package/dist/client/connect/payoutExecutionTestHelpers.d.ts +26 -0
  42. package/dist/client/connect/payoutExecutionTestHelpers.d.ts.map +1 -1
  43. package/dist/client/connect/payoutLargeAdoptionTestHelpers.d.ts +84 -32
  44. package/dist/client/connect/payoutLargeAdoptionTestHelpers.d.ts.map +1 -1
  45. package/dist/client/connect/payoutSyncTestHelpers.d.ts +26 -0
  46. package/dist/client/connect/payoutSyncTestHelpers.d.ts.map +1 -1
  47. package/dist/component/_generated/api.d.ts +24 -0
  48. package/dist/component/_generated/api.d.ts.map +1 -1
  49. package/dist/component/_generated/api.js.map +1 -1
  50. package/dist/component/_generated/component.d.ts +94 -10
  51. package/dist/component/_generated/component.d.ts.map +1 -1
  52. package/dist/component/balanceFunding/internal/actions.d.ts +11 -11
  53. package/dist/component/balanceFunding/mutations.d.ts +16 -16
  54. package/dist/component/balanceFunding/preparationHandlers.d.ts +8 -8
  55. package/dist/component/balanceFunding/queries.d.ts +1 -1
  56. package/dist/component/balanceFunding/workflowValidators.d.ts +16 -16
  57. package/dist/component/earnings/triggers.d.ts +44 -0
  58. package/dist/component/earnings/triggers.d.ts.map +1 -1
  59. package/dist/component/financialObservations/settlementHelpers.d.ts +3 -3
  60. package/dist/component/renewalWitnesses/eligibility.d.ts +36 -0
  61. package/dist/component/renewalWitnesses/eligibility.d.ts.map +1 -0
  62. package/dist/component/renewalWitnesses/eligibility.js +60 -0
  63. package/dist/component/renewalWitnesses/eligibility.js.map +1 -0
  64. package/dist/component/renewalWitnesses/mutations.d.ts +45 -0
  65. package/dist/component/renewalWitnesses/mutations.d.ts.map +1 -0
  66. package/dist/component/renewalWitnesses/mutations.js +14 -0
  67. package/dist/component/renewalWitnesses/mutations.js.map +1 -0
  68. package/dist/component/renewalWitnesses/protocol.d.ts +75 -0
  69. package/dist/component/renewalWitnesses/protocol.d.ts.map +1 -0
  70. package/dist/component/renewalWitnesses/protocol.js +82 -0
  71. package/dist/component/renewalWitnesses/protocol.js.map +1 -0
  72. package/dist/component/renewalWitnesses/queries.d.ts +39 -0
  73. package/dist/component/renewalWitnesses/queries.d.ts.map +1 -0
  74. package/dist/component/renewalWitnesses/queries.js +11 -0
  75. package/dist/component/renewalWitnesses/queries.js.map +1 -0
  76. package/dist/component/renewalWitnesses/schema.d.ts +99 -0
  77. package/dist/component/renewalWitnesses/schema.d.ts.map +1 -0
  78. package/dist/component/renewalWitnesses/schema.js +36 -0
  79. package/dist/component/renewalWitnesses/schema.js.map +1 -0
  80. package/dist/component/renewalWitnesses/source.d.ts +22 -0
  81. package/dist/component/renewalWitnesses/source.d.ts.map +1 -0
  82. package/dist/component/renewalWitnesses/source.js +108 -0
  83. package/dist/component/renewalWitnesses/source.js.map +1 -0
  84. package/dist/component/schema.d.ts +42 -16
  85. package/dist/component/schema.js +2 -0
  86. package/dist/component/schema.js.map +1 -1
  87. package/dist/component/usage/allowance.fixtures.d.ts +42 -16
  88. package/dist/component/usage/allowance.fixtures.d.ts.map +1 -1
  89. package/dist/component/usageCredits/accounting.fixtures.d.ts +26 -0
  90. package/dist/component/usageCredits/accounting.fixtures.d.ts.map +1 -1
  91. package/dist/shared/renewalWitness.d.ts +51 -0
  92. package/dist/shared/renewalWitness.d.ts.map +1 -0
  93. package/dist/shared/renewalWitness.js +127 -0
  94. package/dist/shared/renewalWitness.js.map +1 -0
  95. package/docs/renewal-witness-protocol.md +139 -0
  96. package/package.json +1 -1
  97. package/src/client/billing/renewalAttach/internal/observation/freshActor.ts +142 -19
  98. package/src/client/billing/renewalAttach/internal/observation/freshTransport.ts +90 -1
  99. package/src/client/billing/renewalAttach/internal/observation/invocation.ts +2 -0
  100. package/src/client/billing/renewalAttach/internal/observation/readerAuthorization.ts +6 -1
  101. package/src/client/billing/renewalAttach/internal/observation/witnessAcquisition.integration.test.ts +348 -0
  102. package/src/client/billing/renewalAttach/internal/observation/witnessActor.integration.test.ts +204 -0
  103. package/src/client/billing/renewalAttach/internal/observation/witnessAuthorization.ts +239 -0
  104. package/src/client/billing/renewalAttach/internal/observation/witnessCapabilities.integration.test.ts +231 -0
  105. package/src/client/billing/renewalAttach/internal/observation/witnessData.ts +189 -0
  106. package/src/client/billing/renewalAttach/internal/observation/witnessHistorical.integration.test.ts +98 -0
  107. package/src/client/billing/renewalAttach/internal/observation/witnessImmutable.integration.test.ts +78 -0
  108. package/src/client/billing/renewalAttach/internal/observation/witnessInvoice.integration.test.ts +85 -0
  109. package/src/client/billing/renewalAttach/internal/observation/witnessLifecycle.integration.test.ts +264 -0
  110. package/src/client/billing/renewalAttach/internal/observation/witnessOperation.ts +205 -0
  111. package/src/client/billing/renewalAttach/internal/observation/witnessProfile.integration.test.ts +93 -0
  112. package/src/client/billing/renewalAttach/internal/observation/witnessRPCControls.integration.test.ts +256 -0
  113. package/src/client/billing/renewalAttach/internal/operations/witnessProfiles.ts +58 -0
  114. package/src/client/billing/renewalAttach/internal/test-fixtures/invoiceObservation.ts +3 -1
  115. package/src/client/billing/renewalAttach/internal/test-fixtures/producerConfigureAdmission.ts +8 -0
  116. package/src/client/billing/renewalAttach/internal/test-fixtures/producerInitialOperation.ts +18 -7
  117. package/src/client/billing/renewalAttach/internal/test-fixtures/witnessHistory.ts +70 -0
  118. package/src/client/billing/renewalAttach/internal/test-fixtures/witnessObservation.ts +353 -0
  119. package/src/component/_generated/api.ts +24 -0
  120. package/src/component/_generated/component.ts +98 -10
  121. package/src/component/renewalOperations/configureJournal.fixtures.ts +25 -3
  122. package/src/component/renewalWitnesses/bounds.test.ts +204 -0
  123. package/src/component/renewalWitnesses/codec.test.ts +84 -0
  124. package/src/component/renewalWitnesses/controls.test.ts +250 -0
  125. package/src/component/renewalWitnesses/eligibility.ts +78 -0
  126. package/src/component/renewalWitnesses/mutations.ts +17 -0
  127. package/src/component/renewalWitnesses/protocol.test.ts +63 -0
  128. package/src/component/renewalWitnesses/protocol.ts +103 -0
  129. package/src/component/renewalWitnesses/queries.ts +11 -0
  130. package/src/component/renewalWitnesses/routes.test.ts +154 -0
  131. package/src/component/renewalWitnesses/schema.ts +36 -0
  132. package/src/component/renewalWitnesses/source.ts +157 -0
  133. package/src/component/schema.ts +2 -0
  134. package/src/shared/renewalWitness.ts +179 -0
@@ -0,0 +1,204 @@
1
+ import { afterEach, expect, it, vi } from "vitest";
2
+ import {
3
+ witnessFixture,
4
+ addWitnessInvoices,
5
+ } from "../../../tests/renewalObservation/witnessFixtures.js";
6
+ import { canonicalConfigure } from "../renewalOperations/configureJournal.fixtures.js";
7
+ import { canonicalWitnessJSON } from "../../shared/renewalWitness.js";
8
+ import { validateWitness } from "./eligibility.js";
9
+ import { retainWitness, readWitness } from "./protocol.js";
10
+ import { inspectRenewalEvidenceV1 } from "../../client/billing/renewalObservation/evidence-v1.js";
11
+
12
+ afterEach(() => vi.unstubAllGlobals());
13
+ const argsFor = (h: Awaited<ReturnType<typeof witnessFixture>>) => ({
14
+ identity: h.identity,
15
+ payloadJSON: canonicalConfigure(h.payload),
16
+ });
17
+
18
+ for (const retained of [false, true])
19
+ it(
20
+ "stored native target material remains independent of later live drift, C9=" +
21
+ retained,
22
+ async () => {
23
+ const h = await witnessFixture(retained);
24
+ const original = argsFor(h).payloadJSON;
25
+ await h.t.run((ctx) => retainWitness(ctx, argsFor(h)));
26
+ h.payload.reads.schedule.status = "canceled";
27
+ h.payload.reads.schedule.canceled_at =
28
+ h.payload.acquisition.observedAtMs / 1000;
29
+ h.payload.reads.subscription.description = "LATER_LIVE_DRIFT";
30
+ const stored = await h.t.run((ctx) => readWitness(ctx, h.identity));
31
+ expect(stored?.payloadJSON).toBe(original);
32
+ const snapshot = JSON.parse(stored!.payloadJSON);
33
+ const result = await inspectRenewalEvidenceV1({
34
+ version: 1,
35
+ apiVersion: "2026-09-30.endive",
36
+ configuration: h.configuration,
37
+ configureReceipt: h.rawConfigureReceipt,
38
+ reads: h.payload.reads,
39
+ invoiceContext: null,
40
+ historicalSnapshot: {
41
+ reads: snapshot.reads,
42
+ invoiceContext: snapshot.invoiceContext,
43
+ },
44
+ });
45
+ expect(result.historicalMaterial.predicate).toBe(
46
+ "snapshot_target_material_match",
47
+ );
48
+ expect(result.currentMaterial.predicate).not.toBe(
49
+ "current_target_material_match",
50
+ );
51
+ expect(result.operationalAuthority).toBe(false);
52
+ },
53
+ );
54
+ for (const retained of [false, true])
55
+ it(
56
+ "retains exact full invoice context with optional C9=" + retained,
57
+ async () => {
58
+ const h = await witnessFixture(retained);
59
+ addWitnessInvoices(h);
60
+ const args = argsFor(h);
61
+ const result = await h.t.run((ctx) => retainWitness(ctx, args));
62
+ expect(result.status).toBe("retained");
63
+ const read = await h.t.run((ctx) => readWitness(ctx, h.identity));
64
+ expect(read?.payloadJSON).toBe(args.payloadJSON);
65
+ const stored = JSON.parse(read!.payloadJSON);
66
+ expect(
67
+ stored.invoiceContext.current.linePages[0].data[0].pricing
68
+ .unit_amount_decimal,
69
+ ).toBe("2000.000000000000");
70
+ expect(stored.invoiceContext.original.invoice.futureInvoice).toEqual({
71
+ preserved: null,
72
+ });
73
+ expect(
74
+ stored.invoiceContext.current.linePages[0].data[0].futureLine,
75
+ ).toEqual([null, "retained"]);
76
+ },
77
+ );
78
+
79
+ it("a valid response2 without retained C9 does not fabricate receipt retention", async () => {
80
+ const h = await witnessFixture();
81
+ await h.retainConfigure(false);
82
+ const result = await h.t.run((ctx) => retainWitness(ctx, argsFor(h)));
83
+ expect(result.status).toBe("retained");
84
+ const read = await h.t.run((ctx) => readWitness(ctx, h.identity));
85
+ expect(
86
+ JSON.parse(read!.payloadJSON).source.configure.acknowledgement,
87
+ ).toBeNull();
88
+ });
89
+
90
+ for (const bytes of [480000, 499900])
91
+ it(
92
+ "bounds the complete payload and descriptor before insertion near " +
93
+ bytes +
94
+ " bytes",
95
+ async () => {
96
+ const base = await witnessFixture(false, { sourcePadding: "" });
97
+ const overhead = new TextEncoder().encode(
98
+ canonicalConfigure(base.payload),
99
+ ).length;
100
+ const padding = "x".repeat(Math.floor((bytes - overhead) / 2));
101
+ const h = await witnessFixture(false, { sourcePadding: padding });
102
+ const args = argsFor(h);
103
+ const actual = new TextEncoder().encode(args.payloadJSON).length;
104
+ expect(actual).toBeGreaterThanOrEqual(bytes - 1);
105
+ expect(actual).toBeLessThanOrEqual(bytes);
106
+ expect(canonicalWitnessJSON(args.payloadJSON).json).toBe(
107
+ args.payloadJSON,
108
+ );
109
+ expect(
110
+ await h.t.run(
111
+ async (ctx) =>
112
+ (await validateWitness(ctx, args.payloadJSON)).fields
113
+ .observedItemId,
114
+ ),
115
+ ).toBe("si_successor");
116
+ if (bytes === 499900) {
117
+ await expect(
118
+ h.t.run((ctx) => retainWitness(ctx, args)),
119
+ ).rejects.toThrow();
120
+ expect(
121
+ await h.t.run((ctx) =>
122
+ ctx.db.query("renewalObservationWitnesses").take(1),
123
+ ),
124
+ ).toEqual([]);
125
+ } else {
126
+ expect((await h.t.run((ctx) => retainWitness(ctx, args))).status).toBe(
127
+ "retained",
128
+ );
129
+ const read = await h.t.run((ctx) => readWitness(ctx, h.identity));
130
+ expect(read?.payloadJSON).toBe(args.payloadJSON);
131
+ expect(
132
+ JSON.parse(read!.payloadJSON).source.parent.record.originalBundle
133
+ .witnessPadding,
134
+ ).toBe(padding);
135
+ }
136
+ },
137
+ );
138
+
139
+ it("an existing witness identity cannot adopt a different otherwise valid configure operation", async () => {
140
+ const h = await witnessFixture();
141
+ const originalIdentity = { ...h.identity },
142
+ originalJSON = argsFor(h).payloadJSON;
143
+ const first = await h.t.run((ctx) => retainWitness(ctx, argsFor(h)));
144
+ const record = structuredClone(h.record);
145
+ record.logicalOperationId += ":fork";
146
+ const createArgs = {
147
+ ...h.createArgs,
148
+ logicalOperationId: record.logicalOperationId,
149
+ recordJSON: canonicalConfigure(record),
150
+ };
151
+ const next = await h.t.mutation(h.create, createArgs);
152
+ await h.t.mutation(h.reserve, {
153
+ operationId: next.operationId,
154
+ expectedRevision: 0,
155
+ stage: "configure",
156
+ expectedRequestBinding: h.request.requestIdentity.binding,
157
+ recordJSON: createArgs.recordJSON,
158
+ });
159
+ const loaded = await h.t.query(h.load, { operationId: next.operationId });
160
+ h.identity.operationId = next.operationId;
161
+ h.payload.source.configure.record = JSON.parse(loaded.recordJSON);
162
+ h.payload.source.configure.reservation = loaded.activeAttempt;
163
+ expect(
164
+ await h.t.run(
165
+ async (ctx) =>
166
+ (await validateWitness(ctx, argsFor(h).payloadJSON)).fields
167
+ .observedItemId,
168
+ ),
169
+ ).toBe("si_successor");
170
+ expect(await h.t.run((ctx) => retainWitness(ctx, argsFor(h)))).toEqual({
171
+ status: "conflict",
172
+ reason: "identity_changed",
173
+ });
174
+ expect(await h.t.run((ctx) => readWitness(ctx, originalIdentity))).toEqual({
175
+ descriptor: Reflect.get(first, "descriptor"),
176
+ payloadJSON: originalJSON,
177
+ });
178
+ });
179
+
180
+ it("a recomputed payload hash cannot hide material corruption", async () => {
181
+ const h = await witnessFixture();
182
+ const result = await h.t.run((ctx) => retainWitness(ctx, argsFor(h)));
183
+ if (result.status !== "retained") throw Error("EXPECTED_RETENTION");
184
+ h.payload.reads.subscription.description = "ALTERED_AFTER_CAPTURE";
185
+ const raw = canonicalConfigure(h.payload);
186
+ const digest = await crypto.subtle.digest(
187
+ "SHA-256",
188
+ new TextEncoder().encode("renewal-witness:v1\u0000" + raw),
189
+ );
190
+ const binding =
191
+ "renewal-witness:v1:sha256:" +
192
+ [...new Uint8Array(digest)]
193
+ .map((n) => n.toString(16).padStart(2, "0"))
194
+ .join("");
195
+ await h.t.run((ctx) =>
196
+ ctx.db.patch(result.descriptor.witnessRowId, {
197
+ payloadJSON: raw,
198
+ payloadBinding: binding,
199
+ }),
200
+ );
201
+ await expect(
202
+ h.t.run((ctx) => readWitness(ctx, h.identity)),
203
+ ).rejects.toThrow();
204
+ });
@@ -0,0 +1,84 @@
1
+ import { afterEach, expect, it, vi } from "vitest";
2
+ import { canonicalWitnessJSON } from "../../shared/renewalWitness.js";
3
+ import { witnessFixture } from "../../../tests/renewalObservation/witnessFixtures.js";
4
+ import { canonicalConfigure } from "../renewalOperations/configureJournal.fixtures.js";
5
+
6
+ afterEach(() => vi.unstubAllGlobals());
7
+ const controls = [
8
+ "unknown-root",
9
+ "subject-empty",
10
+ "negative-time",
11
+ "wall-budget",
12
+ "ns-budget",
13
+ "ns-leading-zero",
14
+ "negative-derived-start",
15
+ "api-version",
16
+ "base-profile",
17
+ "invoice-profile",
18
+ "nodes",
19
+ "depth",
20
+ "aggregate-bytes",
21
+ ] as const;
22
+ it.each(controls)("complete witness codec refuses %s", async (control) => {
23
+ const h = await witnessFixture();
24
+ const value = h.payload;
25
+ if (control === "unknown-root")
26
+ Reflect.set(value, "operationalAuthority", true);
27
+ if (control === "subject-empty") value.capturedSubject = "";
28
+ if (control === "negative-time") value.acquisition.observedAtMs = -1;
29
+ if (control === "wall-budget") value.acquisition.elapsedWallMs = 30000;
30
+ if (control === "ns-budget")
31
+ value.acquisition.elapsedNsDecimal = "30000000000";
32
+ if (control === "ns-leading-zero") value.acquisition.elapsedNsDecimal = "01";
33
+ if (control === "negative-derived-start") {
34
+ value.acquisition.observedAtMs = 1;
35
+ value.acquisition.elapsedWallMs = 2;
36
+ }
37
+ if (control === "api-version") value.acquisition.apiVersion = "other";
38
+ if (control === "base-profile") value.acquisition.baseReadProfile = "other";
39
+ if (control === "invoice-profile")
40
+ Reflect.set(
41
+ value.acquisition,
42
+ "invoiceReadProfile",
43
+ "endive-pinned-invoices-fence-7-v1",
44
+ );
45
+ if (control === "nodes")
46
+ value.reads.schedule.extra = Array.from({ length: 10000 }, () => null);
47
+ if (control === "depth") {
48
+ let nested: unknown = null;
49
+ for (let i = 0; i < 41; i++) nested = { nested };
50
+ value.reads.schedule.extra = nested;
51
+ }
52
+ if (control === "aggregate-bytes") {
53
+ for (const body of [
54
+ value.reads.schedule,
55
+ value.reads.subscription,
56
+ value.reads.targetPrice,
57
+ value.reads.billingCustomer,
58
+ ])
59
+ body.extra = "\u0800".repeat(45000);
60
+ }
61
+ // JSON.stringify intentionally skips the canonical fixture helper so the
62
+ // target, rather than fixture construction, must reject excessive budgets.
63
+ const raw =
64
+ control === "nodes" || control === "depth" || control === "aggregate-bytes"
65
+ ? JSON.stringify(value)
66
+ : canonicalConfigure(value);
67
+ expect(() => canonicalWitnessJSON(raw)).toThrow();
68
+ });
69
+
70
+ it("keeps exact decimal text, unknown nested fields and own null values", async () => {
71
+ const h = await witnessFixture();
72
+ h.payload.reads.targetPrice.extra = {
73
+ amount: "9007199254740991.000000000001",
74
+ nullValue: null,
75
+ list: [null, "retained"],
76
+ };
77
+ const raw = canonicalConfigure(h.payload);
78
+ const captured = canonicalWitnessJSON(raw);
79
+ expect(captured.json).toBe(raw);
80
+ expect(captured.value).toEqual(h.payload);
81
+ expect(
82
+ Reflect.get(captured.value.reads.targetPrice as object, "extra"),
83
+ ).toEqual(h.payload.reads.targetPrice.extra);
84
+ });
@@ -0,0 +1,250 @@
1
+ import { afterEach, expect, it, vi } from "vitest";
2
+ import { witnessFixture } from "../../../tests/renewalObservation/witnessFixtures.js";
3
+ import { canonicalConfigure } from "../renewalOperations/configureJournal.fixtures.js";
4
+ import { canonicalJournalEvent } from "../../shared/renewalOperationJournal.js";
5
+ import { retainWitness, readWitness } from "./protocol.js";
6
+
7
+ afterEach(() => {
8
+ vi.unstubAllGlobals();
9
+ vi.restoreAllMocks();
10
+ });
11
+ const argsFor = (h: Awaited<ReturnType<typeof witnessFixture>>) => ({
12
+ identity: h.identity,
13
+ payloadJSON: canonicalConfigure(h.payload),
14
+ });
15
+ async function count(h: Awaited<ReturnType<typeof witnessFixture>>) {
16
+ return h.t.run(
17
+ async (ctx) =>
18
+ (await ctx.db.query("renewalObservationWitnesses").take(3)).length,
19
+ );
20
+ }
21
+
22
+ it("rejects an opaque configure event even when its stored hash and ownership are valid", async () => {
23
+ const h = await witnessFixture();
24
+ await h.t.mutation(h.bind, {
25
+ operationId: h.created.operationId,
26
+ attemptId: h.reserved.reservation.attemptId,
27
+ policyJSON: canonicalConfigure(h.record.timingPolicy),
28
+ basisJSON: canonicalConfigure(h.basis),
29
+ });
30
+ const event = await canonicalJournalEvent(
31
+ 1,
32
+ canonicalConfigure({ opaque: "unbound configure event" }),
33
+ );
34
+ await h.t.mutation(h.append, {
35
+ reservation: h.reserved.reservation,
36
+ expectedSequence: 0,
37
+ event: { sequence: 1, binding: event.binding, dataJSON: event.json },
38
+ });
39
+ await expect(
40
+ h.t.run((ctx) => retainWitness(ctx, argsFor(h))),
41
+ ).rejects.toThrow();
42
+ expect(await count(h)).toBe(0);
43
+ });
44
+
45
+ for (const retained of [false, true])
46
+ it("preserves complete witness with captured C9=" + retained, async () => {
47
+ const h = await witnessFixture(retained);
48
+ const result = await h.t.run((ctx) => retainWitness(ctx, argsFor(h)));
49
+ expect(result.status).toBe("retained");
50
+ if (result.status !== "retained") throw Error("EXPECTED_RETENTION");
51
+ expect(result.descriptor.observedItemId).toBe("si_successor");
52
+ expect(result.descriptor.providerQualificationRequired).toBe(true);
53
+ const read = await h.t.run((ctx) => readWitness(ctx, h.identity));
54
+ expect(read?.descriptor).toEqual(result.descriptor);
55
+ expect(JSON.parse(read!.payloadJSON)).toEqual(h.payload);
56
+ expect(read?.descriptor.authenticationEstablished).toBe(false);
57
+ });
58
+
59
+ it("captured-null C9 remains null after a later valid retained C9", async () => {
60
+ const h = await witnessFixture();
61
+ const original = await h.t.run((ctx) => retainWitness(ctx, argsFor(h)));
62
+ await h.retainConfigure();
63
+ const later = await h.t.run((ctx) => readWitness(ctx, h.identity));
64
+ expect(original.status).toBe("retained");
65
+ if (original.status !== "retained") throw Error("EXPECTED_RETENTION");
66
+ expect(later?.descriptor).toEqual(original.descriptor);
67
+ expect(
68
+ JSON.parse(later!.payloadJSON).source.configure.acknowledgement,
69
+ ).toBeNull();
70
+ });
71
+
72
+ it("concurrent duplicate transactions retain one complete immutable row", async () => {
73
+ const h = await witnessFixture();
74
+ const results = await Promise.all([
75
+ h.t.run((ctx) => retainWitness(ctx, argsFor(h))),
76
+ h.t.run((ctx) => retainWitness(ctx, argsFor(h))),
77
+ ]);
78
+ expect(results[0]).toEqual(results[1]);
79
+ expect(await count(h)).toBe(1);
80
+ });
81
+
82
+ it("changed valid payload conflicts and cannot overwrite the original", async () => {
83
+ const h = await witnessFixture();
84
+ const args = argsFor(h);
85
+ const first = await h.t.run((ctx) => retainWitness(ctx, args));
86
+ h.payload.capturedSubject = "https://host.test|different-capture";
87
+ expect(await h.t.run((ctx) => retainWitness(ctx, argsFor(h)))).toEqual({
88
+ status: "conflict",
89
+ reason: "identity_changed",
90
+ });
91
+ expect(await h.t.run((ctx) => readWitness(ctx, h.identity))).toEqual({
92
+ descriptor: Reflect.get(first, "descriptor"),
93
+ payloadJSON: args.payloadJSON,
94
+ });
95
+ expect(await count(h)).toBe(1);
96
+ });
97
+
98
+ for (const field of ["componentScope", "witnessId", "operations"] as const)
99
+ it(
100
+ "wrong read identity refuses without exposing payload: " + field,
101
+ async () => {
102
+ const h = await witnessFixture();
103
+ await h.t.run((ctx) => retainWitness(ctx, argsFor(h)));
104
+ const identity = { ...h.identity };
105
+ if (field === "operations") {
106
+ identity.parentOperationId = h.identity.operationId;
107
+ identity.operationId = h.identity.parentOperationId;
108
+ } else identity[field] = "foreign";
109
+ expect(await h.t.run((ctx) => readWitness(ctx, identity))).toBeNull();
110
+ },
111
+ );
112
+
113
+ for (const control of [
114
+ "C1",
115
+ "C7",
116
+ "C3",
117
+ "basis",
118
+ "reservation",
119
+ "unretained-C9",
120
+ "material",
121
+ "target-item",
122
+ "invoice-context",
123
+ ] as const)
124
+ it("refuses altered source/material before storage: " + control, async () => {
125
+ const h = await witnessFixture();
126
+ if (control === "C1")
127
+ Reflect.set(h.payload.source.parent.record, "profile", "ALTERED");
128
+ if (control === "C7")
129
+ Reflect.set(
130
+ h.payload.source.configure.record,
131
+ "logicalOperationId",
132
+ "ALTERED",
133
+ );
134
+ if (control === "C3")
135
+ Reflect.set(
136
+ h.payload.source.parent.acknowledgement!.receipt,
137
+ "binding",
138
+ "ALTERED",
139
+ );
140
+ if (control === "basis")
141
+ Reflect.set(h.payload.source.parent.initialBasis, "basisJSON", "{}");
142
+ if (control === "reservation")
143
+ Reflect.set(
144
+ h.payload.source.configure.reservation,
145
+ "requestBinding",
146
+ "ALTERED",
147
+ );
148
+ if (control === "unretained-C9")
149
+ h.payload.source.configure.acknowledgement = structuredClone(
150
+ h.payload.source.parent.acknowledgement,
151
+ );
152
+ if (control === "material")
153
+ h.payload.reads.subscription.description = "ALTERED";
154
+ if (control === "target-item")
155
+ h.payload.reads.subscription.items.data.push(
156
+ structuredClone(h.payload.reads.subscription.items.data[0]),
157
+ );
158
+ if (control === "invoice-context")
159
+ Reflect.set(h.payload, "invoiceContext", {
160
+ original: null,
161
+ current: null,
162
+ });
163
+ await expect(
164
+ h.t.run((ctx) => retainWitness(ctx, argsFor(h))),
165
+ ).rejects.toThrow();
166
+ expect(await count(h)).toBe(0);
167
+ });
168
+
169
+ for (const control of [
170
+ "binding",
171
+ "payload",
172
+ "duplicate",
173
+ "parent-owner",
174
+ "configure-owner",
175
+ "missing-C3",
176
+ ] as const)
177
+ it(
178
+ "rechecks stored rows and source integrity on reads: " + control,
179
+ async () => {
180
+ const h = await witnessFixture();
181
+ const result = await h.t.run((ctx) => retainWitness(ctx, argsFor(h)));
182
+ if (result.status !== "retained") throw Error("EXPECTED_RETENTION");
183
+ await h.t.run(async (ctx) => {
184
+ const row = await ctx.db.get(
185
+ "renewalObservationWitnesses",
186
+ result.descriptor.witnessRowId,
187
+ );
188
+ if (!row) throw Error("MISSING_ROW");
189
+ if (control === "binding")
190
+ await ctx.db.patch(row._id, { payloadBinding: "ALTERED" });
191
+ if (control === "payload") {
192
+ const value = JSON.parse(row.payloadJSON);
193
+ value.capturedSubject = "ALTERED";
194
+ await ctx.db.patch(row._id, {
195
+ payloadJSON: canonicalConfigure(value),
196
+ });
197
+ }
198
+ if (control === "duplicate")
199
+ await ctx.db.insert("renewalObservationWitnesses", {
200
+ identity: row.identity,
201
+ payloadJSON: row.payloadJSON,
202
+ payloadBinding: row.payloadBinding,
203
+ });
204
+ if (control === "parent-owner" || control === "configure-owner") {
205
+ const operationId =
206
+ control === "parent-owner"
207
+ ? h.identity.parentOperationId
208
+ : h.identity.operationId;
209
+ const operation = await ctx.db.get("renewalOperations", operationId);
210
+ if (!operation) throw Error("MISSING_OPERATION");
211
+ await ctx.db.patch(operation.payloadId, {
212
+ owner: {
213
+ kind: "operation",
214
+ operationId:
215
+ control === "parent-owner"
216
+ ? h.identity.operationId
217
+ : h.identity.parentOperationId,
218
+ },
219
+ });
220
+ }
221
+ if (control === "missing-C3") {
222
+ const operation = await ctx.db.get(
223
+ "renewalOperations",
224
+ h.identity.parentOperationId,
225
+ );
226
+ if (!operation?.knownAcknowledgement) throw Error("MISSING_ACK");
227
+ await ctx.db.delete(operation.knownAcknowledgement.receiptPayloadId);
228
+ }
229
+ });
230
+ await expect(
231
+ h.t.run((ctx) => readWitness(ctx, h.identity)),
232
+ ).rejects.toThrow();
233
+ },
234
+ );
235
+
236
+ it("a lost caller response leaves one row but does not establish public ACK delivery", async () => {
237
+ const h = await witnessFixture();
238
+ let committed: Awaited<ReturnType<typeof retainWitness>> | null = null;
239
+ await expect(
240
+ (async () => {
241
+ committed = await h.t.run((ctx) => retainWitness(ctx, argsFor(h)));
242
+ throw Error("CONTROLLED_LOST_REPLY");
243
+ })(),
244
+ ).rejects.toThrow("CONTROLLED_LOST_REPLY");
245
+ expect(await count(h)).toBe(1);
246
+ const duplicate = await h.t.run((ctx) => retainWitness(ctx, argsFor(h)));
247
+ expect(duplicate).toEqual(committed);
248
+ if (duplicate.status !== "retained") throw Error("EXPECTED_RETENTION");
249
+ expect(duplicate.descriptor.publicDeliveryEstablished).toBe(false);
250
+ });
@@ -0,0 +1,78 @@
1
+ import type { QueryCtx } from "../_generated/server.js";
2
+ import { inspectRenewalEvidenceV1 } from "../../client/billing/renewalObservation/evidence-v1.js";
3
+ import {
4
+ canonicalWitnessJSON,
5
+ witnessNeed as need,
6
+ type WitnessPayload,
7
+ } from "../../shared/renewalWitness.js";
8
+ import { validateWitnessSource } from "./source.js";
9
+
10
+ function configureInput(
11
+ value: WitnessPayload,
12
+ configuration: unknown,
13
+ dispatch: unknown,
14
+ ) {
15
+ const known = value.source.configure.acknowledgement;
16
+ return known === null
17
+ ? null
18
+ : {
19
+ configuration,
20
+ actualDispatch: dispatch,
21
+ providerSnapshot: known.receipt.providerSnapshot,
22
+ transport: known.receipt.transport,
23
+ };
24
+ }
25
+ /** Full material and exact source qualify unsigned storage DATA, not provider provenance. */
26
+ export async function validateWitness(ctx: Pick<QueryCtx, "db">, raw: string) {
27
+ const payload = canonicalWitnessJSON(raw);
28
+ const source = await validateWitnessSource(ctx, payload.value);
29
+ const evidence = await inspectRenewalEvidenceV1({
30
+ version: 1,
31
+ apiVersion: "2026-09-30.endive",
32
+ configuration: source.configuration,
33
+ configureReceipt: configureInput(
34
+ payload.value,
35
+ source.configuration,
36
+ source.dispatch,
37
+ ),
38
+ reads: payload.value.reads,
39
+ invoiceContext: payload.value.invoiceContext,
40
+ historicalSnapshot: null,
41
+ });
42
+ need(
43
+ evidence.identity &&
44
+ evidence.currentMaterial.predicate === "current_target_material_match",
45
+ );
46
+ if (payload.value.invoiceContext !== null)
47
+ need(evidence.invoiceEvidence.predicate === "invoice_lines_correlated");
48
+ const { identity } = evidence;
49
+ const fields = {
50
+ version: 1 as const,
51
+ identity: source.identity,
52
+ capturedSubject: payload.value.capturedSubject,
53
+ observedAtMs: payload.value.acquisition.observedAtMs,
54
+ customerAccountId: identity.customerAccountId,
55
+ customerId: identity.customerId,
56
+ livemode: identity.livemode,
57
+ subscriptionId: identity.subscriptionId,
58
+ scheduleId: identity.scheduleId,
59
+ observedItemId: evidence.currentMaterial.observedItemId,
60
+ nativePeriod: evidence.currentMaterial.nativePeriod,
61
+ operationalAuthority: false as const,
62
+ authenticationEstablished: false as const,
63
+ publicDeliveryEstablished: false as const,
64
+ providerQualificationRequired: true as const,
65
+ };
66
+ const digest = await crypto.subtle.digest(
67
+ "SHA-256",
68
+ new TextEncoder().encode("renewal-witness:v1\u0000" + payload.json),
69
+ );
70
+ const hex = [...new Uint8Array(digest)]
71
+ .map((n) => n.toString(16).padStart(2, "0"))
72
+ .join("");
73
+ return {
74
+ payload,
75
+ fields,
76
+ payloadBinding: "renewal-witness:v1:sha256:" + hex,
77
+ };
78
+ }
@@ -0,0 +1,17 @@
1
+ import { v } from "convex/values";
2
+ import { mutation } from "../_generated/server.js";
3
+ import { descriptor, identity } from "./schema.js";
4
+ import { retainWitness } from "./protocol.js";
5
+
6
+ /** Trusted host component API. Host authorization and live capture remain separate requirements. */
7
+ export const retainAuthorizedWitness = mutation({
8
+ args: { identity, payloadJSON: v.string() },
9
+ returns: v.union(
10
+ v.object({ status: v.literal("retained"), descriptor }),
11
+ v.object({
12
+ status: v.literal("conflict"),
13
+ reason: v.literal("identity_changed"),
14
+ }),
15
+ ),
16
+ handler: retainWitness,
17
+ });