@fantastic.dev/better-stripe 0.109.1 → 0.111.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 (100) 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 +41 -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 +40 -3
  6. package/dist/client/billing/renewalAttach/internal/observation/freshActor.js.map +1 -1
  7. package/dist/client/billing/renewalAttach/internal/observation/freshTransport.d.ts +10 -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 +162 -57
  10. package/dist/client/billing/renewalAttach/internal/observation/freshTransport.js.map +1 -1
  11. package/dist/client/billing/renewalAttach/internal/observation/invoiceAuthorization.d.ts +14 -0
  12. package/dist/client/billing/renewalAttach/internal/observation/invoiceAuthorization.d.ts.map +1 -0
  13. package/dist/client/billing/renewalAttach/internal/observation/invoiceAuthorization.js +109 -0
  14. package/dist/client/billing/renewalAttach/internal/observation/invoiceAuthorization.js.map +1 -0
  15. package/dist/client/billing/renewalAttach/internal/observation/invoicePlan.d.ts +20 -0
  16. package/dist/client/billing/renewalAttach/internal/observation/invoicePlan.d.ts.map +1 -0
  17. package/dist/client/billing/renewalAttach/internal/observation/invoicePlan.js +176 -0
  18. package/dist/client/billing/renewalAttach/internal/observation/invoicePlan.js.map +1 -0
  19. package/dist/client/billing/renewalAttach/internal/observation/profile.js.map +1 -1
  20. package/dist/client/billing/renewalAttach/internal/observation/types.d.ts +1 -1
  21. package/dist/client/billing/renewalAttach/internal/observation/types.d.ts.map +1 -1
  22. package/dist/client/billing/renewalAttach/internal/observation/types.js.map +1 -1
  23. package/dist/client/billing/renewalAttach/internal/operations/sourceOperations.d.ts +24 -0
  24. package/dist/client/billing/renewalAttach/internal/operations/sourceOperations.d.ts.map +1 -1
  25. package/dist/client/billing/renewalAttach/internal/operations/sourceOperations.js +1 -0
  26. package/dist/client/billing/renewalAttach/internal/operations/sourceOperations.js.map +1 -1
  27. package/dist/client/billing/renewalObservation/evidence-invoice.d.ts.map +1 -1
  28. package/dist/client/billing/renewalObservation/evidence-invoice.js +3 -0
  29. package/dist/client/billing/renewalObservation/evidence-invoice.js.map +1 -1
  30. package/dist/client/connect/payoutAdoptionTestHelpers.d.ts +84 -32
  31. package/dist/client/connect/payoutAdoptionTestHelpers.d.ts.map +1 -1
  32. package/dist/client/connect/payoutExecutionTestHelpers.d.ts +42 -16
  33. package/dist/client/connect/payoutExecutionTestHelpers.d.ts.map +1 -1
  34. package/dist/client/connect/payoutLargeAdoptionTestHelpers.d.ts +52 -0
  35. package/dist/client/connect/payoutLargeAdoptionTestHelpers.d.ts.map +1 -1
  36. package/dist/client/connect/payoutSyncTestHelpers.d.ts +26 -0
  37. package/dist/client/connect/payoutSyncTestHelpers.d.ts.map +1 -1
  38. package/dist/component/balanceFunding/internal/actions.d.ts +11 -11
  39. package/dist/component/balanceFunding/mutations.d.ts +27 -27
  40. package/dist/component/balanceFunding/preparationHandlers.d.ts +8 -8
  41. package/dist/component/balanceFunding/queries.d.ts +1 -1
  42. package/dist/component/balanceFunding/workflowValidators.d.ts +16 -16
  43. package/dist/component/earnings/triggers.d.ts +44 -0
  44. package/dist/component/earnings/triggers.d.ts.map +1 -1
  45. package/dist/component/renewalWitnesses/eligibility.d.ts +36 -0
  46. package/dist/component/renewalWitnesses/eligibility.d.ts.map +1 -0
  47. package/dist/component/renewalWitnesses/eligibility.js +60 -0
  48. package/dist/component/renewalWitnesses/eligibility.js.map +1 -0
  49. package/dist/component/renewalWitnesses/protocol.d.ts +75 -0
  50. package/dist/component/renewalWitnesses/protocol.d.ts.map +1 -0
  51. package/dist/component/renewalWitnesses/protocol.js +82 -0
  52. package/dist/component/renewalWitnesses/protocol.js.map +1 -0
  53. package/dist/component/renewalWitnesses/schema.d.ts +99 -0
  54. package/dist/component/renewalWitnesses/schema.d.ts.map +1 -0
  55. package/dist/component/renewalWitnesses/schema.js +36 -0
  56. package/dist/component/renewalWitnesses/schema.js.map +1 -0
  57. package/dist/component/renewalWitnesses/source.d.ts +22 -0
  58. package/dist/component/renewalWitnesses/source.d.ts.map +1 -0
  59. package/dist/component/renewalWitnesses/source.js +108 -0
  60. package/dist/component/renewalWitnesses/source.js.map +1 -0
  61. package/dist/component/schema.d.ts +42 -16
  62. package/dist/component/schema.js +2 -0
  63. package/dist/component/schema.js.map +1 -1
  64. package/dist/component/usage/allowance.fixtures.d.ts +26 -0
  65. package/dist/component/usage/allowance.fixtures.d.ts.map +1 -1
  66. package/dist/component/usageCredits/accounting.fixtures.d.ts +42 -16
  67. package/dist/component/usageCredits/accounting.fixtures.d.ts.map +1 -1
  68. package/dist/shared/renewalWitness.d.ts +51 -0
  69. package/dist/shared/renewalWitness.d.ts.map +1 -0
  70. package/dist/shared/renewalWitness.js +127 -0
  71. package/dist/shared/renewalWitness.js.map +1 -0
  72. package/docs/renewal-invoice-reads.md +85 -0
  73. package/docs/renewal-witness-protocol.md +88 -0
  74. package/package.json +1 -1
  75. package/src/client/billing/renewalAttach/internal/observation/freshActor.ts +69 -3
  76. package/src/client/billing/renewalAttach/internal/observation/freshTransport.ts +189 -59
  77. package/src/client/billing/renewalAttach/internal/observation/invoiceActor.integration.test.ts +142 -0
  78. package/src/client/billing/renewalAttach/internal/observation/invoiceActorControls.integration.test.ts +495 -0
  79. package/src/client/billing/renewalAttach/internal/observation/invoiceAuthorization.ts +145 -0
  80. package/src/client/billing/renewalAttach/internal/observation/invoicePlan.ts +284 -0
  81. package/src/client/billing/renewalAttach/internal/observation/profile.ts +1 -1
  82. package/src/client/billing/renewalAttach/internal/observation/types.ts +7 -1
  83. package/src/client/billing/renewalAttach/internal/operations/sourceOperations.ts +30 -0
  84. package/src/client/billing/renewalAttach/internal/producer/producerConfigureWriteControls.integration.test.ts +74 -62
  85. package/src/client/billing/renewalAttach/internal/test-fixtures/invoiceObservation.ts +158 -0
  86. package/src/client/billing/renewalAttach/internal/test-fixtures/producerConfigureAdmission.ts +11 -1
  87. package/src/client/billing/renewalAttach/internal/test-fixtures/producerInitialOperation.ts +4 -0
  88. package/src/client/billing/renewalObservation/evidence-invoice-identity.test.ts +13 -0
  89. package/src/client/billing/renewalObservation/evidence-invoice.ts +8 -0
  90. package/src/component/renewalOperations/configureJournal.fixtures.ts +25 -3
  91. package/src/component/renewalWitnesses/bounds.test.ts +204 -0
  92. package/src/component/renewalWitnesses/codec.test.ts +84 -0
  93. package/src/component/renewalWitnesses/controls.test.ts +250 -0
  94. package/src/component/renewalWitnesses/eligibility.ts +78 -0
  95. package/src/component/renewalWitnesses/protocol.test.ts +63 -0
  96. package/src/component/renewalWitnesses/protocol.ts +103 -0
  97. package/src/component/renewalWitnesses/schema.ts +36 -0
  98. package/src/component/renewalWitnesses/source.ts +157 -0
  99. package/src/component/schema.ts +2 -0
  100. package/src/shared/renewalWitness.ts +179 -0
@@ -32,6 +32,7 @@ const controls = vi.hoisted(() => ({
32
32
  selectors: 0,
33
33
  history: [] as unknown[],
34
34
  observation: [] as unknown[],
35
+ invoices: [] as unknown[],
35
36
  onSelect: null as null | ((client: object) => void),
36
37
  }));
37
38
  vi.mock("../operations/sourceOperations.js", () => {
@@ -46,6 +47,7 @@ vi.mock("../operations/sourceOperations.js", () => {
46
47
  COMPILED_CONFIGURE_WRITE_ENTRIES: controls.write,
47
48
  COMPILED_OBSERVATION_HISTORY_ENTRIES: controls.history,
48
49
  COMPILED_FRESH_OBSERVATION_ENTRIES: controls.observation,
50
+ COMPILED_INVOICE_OBSERVATION_ENTRIES: controls.invoices,
49
51
  loadConfigureWriteTransportSource: poison,
50
52
  loadConfigureReplayTransportSource: poison,
51
53
  loadFixedConfigureWriteOperation: poison,
@@ -112,6 +114,7 @@ beforeEach(() => {
112
114
  controls.selectors = 0;
113
115
  controls.history.splice(0);
114
116
  controls.observation.splice(0);
117
+ controls.invoices.splice(0);
115
118
  controls.onSelect = null;
116
119
  controls.entries.splice(0, controls.entries.length, {
117
120
  coversRetained: () => true,
@@ -181,7 +184,10 @@ async function setup(
181
184
  if (completion.mode === "replay" && completion.posts === 1)
182
185
  throw Error("CONTROLLED_LOST_RESPONSE");
183
186
  }
184
- const body = method === "POST" ? baseline.schedule : routes.get(path);
187
+ const body =
188
+ method === "POST"
189
+ ? baseline.schedule
190
+ : (routes.get(path + parsed.search) ?? routes.get(path));
185
191
  assert(body);
186
192
  assert(
187
193
  method === "GET" ||
@@ -404,6 +410,9 @@ export async function configureAdmissionFixture(
404
410
  hostQuery?: NonNullable<
405
411
  Parameters<typeof initialOperations>[2]
406
412
  >["hostQuery"];
413
+ hostInvoiceQuery?: NonNullable<
414
+ Parameters<typeof initialOperations>[2]
415
+ >["hostQuery"];
407
416
  count?: number;
408
417
  keys?: readonly string[];
409
418
  afterBind?: (reply: unknown) => Promise<void>;
@@ -434,6 +443,7 @@ export async function configureAdmissionFixture(
434
443
  keys: options.keys,
435
444
  identity: options.identity,
436
445
  hostQuery: options.hostQuery,
446
+ hostInvoiceQuery: options.hostInvoiceQuery,
437
447
  source: captureRetainedInput(baseline.original),
438
448
  afterBind: options.afterBind,
439
449
  afterQuery: options.afterQuery,
@@ -41,6 +41,7 @@ export async function initialOperations(
41
41
  options: {
42
42
  identity?: { subject: string; issuer: string; tokenIdentifier: string };
43
43
  hostQuery?: ReturnType<typeof queryGeneric>;
44
+ hostInvoiceQuery?: ReturnType<typeof queryGeneric>;
44
45
  epochMs?: number;
45
46
  workEndWallMs?: number;
46
47
  endWallMs?: number;
@@ -180,6 +181,9 @@ export async function initialOperations(
180
181
  let secondaryId = 0;
181
182
  const host = {
182
183
  ...(options.hostQuery ? { authorize: options.hostQuery } : {}),
184
+ ...(options.hostInvoiceQuery
185
+ ? { authorizeInvoices: options.hostInvoiceQuery }
186
+ : {}),
183
187
  secondary: actionGeneric({
184
188
  args: { id: v.string() },
185
189
  handler: async (ctx, args): Promise<null> => {
@@ -46,3 +46,16 @@ it.each(["string", "minimal-expanded", "full-expanded"] as const)(
46
46
  expect(f.h.input).toEqual(before);
47
47
  },
48
48
  );
49
+
50
+ it("distinct invoices cannot reuse one line ID for incompatible period inventories", async () => {
51
+ const f = invoiceRecipe("subscription_cycle", "open");
52
+ await prerequisites(f.h);
53
+ set(f.currentLine, "id", f.originalLine.id);
54
+ const result = await inspectRenewalEvidenceV1(f.h.input);
55
+ expect(result.invoiceEvidence).toEqual({
56
+ predicate: "conflict",
57
+ original: null,
58
+ current: null,
59
+ reason: "invoice_relation_mismatch",
60
+ });
61
+ });
@@ -251,6 +251,14 @@ export async function inspectInvoiceEvidenceV1(
251
251
  };
252
252
  const original = examine("original"),
253
253
  current = examine("current");
254
+ const lineIds = (role: "original" | "current") =>
255
+ array(invoiceRecordV1(inventory[role]).linePages).flatMap((page) =>
256
+ array(invoiceRecordV1(page).data).map(
257
+ (line) => invoiceRecordV1(line).id,
258
+ ),
259
+ );
260
+ const originalIds = new Set(lineIds("original"));
261
+ relation(lineIds("current").every((id) => !originalIds.has(id)));
254
262
  return {
255
263
  predicate: "invoice_lines_correlated",
256
264
  original,
@@ -25,13 +25,32 @@ export function sevenConfigure(request: {
25
25
  return { scope, apiVersion, method, path, payload, key, firstDispatchedAt };
26
26
  }
27
27
  /** Complete synthetic constructor DATA only, without an Owner or provider call. */
28
- export async function configureJournalFixture() {
28
+ export async function configureJournalFixture(
29
+ options: { targetInterval?: "week"; sourcePadding?: string } = {},
30
+ ) {
29
31
  let fetches = 0;
30
32
  vi.stubGlobal("fetch", () => {
31
33
  fetches++;
32
34
  throw Error("UNEXPECTED_PROVIDER_CALL");
33
35
  });
34
36
  const baseline = makeConfigureReadNativeBaseline();
37
+ if (options.sourcePadding !== undefined)
38
+ Object.assign(baseline.original.originalBundle, {
39
+ witnessPadding: options.sourcePadding,
40
+ });
41
+ if (options.targetInterval) {
42
+ const prep = baseline.original.attachRequest.preparation;
43
+ Object.assign(prep.targetPrice.recurring, {
44
+ interval: options.targetInterval,
45
+ });
46
+ Object.assign(prep.subscription, { trial_start: null, trial_end: null });
47
+ baseline.original.originalBundle.wireTargetPrice = structuredClone(
48
+ prep.targetPrice,
49
+ );
50
+ baseline.original.originalBundle.wireSubscription = structuredClone(
51
+ prep.subscription,
52
+ );
53
+ }
35
54
  const attachRequest = structuredClone(baseline.original.attachRequest);
36
55
  const prepared = await c1(attachRequest.preparation);
37
56
  const attach = await c2({
@@ -126,8 +145,11 @@ export async function configureJournalFixture() {
126
145
  };
127
146
  }
128
147
 
129
- export async function configureComponentFixture(publishParent = true) {
130
- const h = await configureJournalFixture();
148
+ export async function configureComponentFixture(
149
+ publishParent = true,
150
+ options: { targetInterval?: "week"; sourcePadding?: string } = {},
151
+ ) {
152
+ const h = await configureJournalFixture(options);
131
153
  const { convexTest } = await import("convex-test");
132
154
  const { schema, modules } = await import("../../test.js");
133
155
  const { makeFunctionReference } = await import("convex/server");
@@ -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
+ });