@fantastic.dev/better-stripe 0.110.0 → 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 (55) hide show
  1. package/CHANGELOG.md +6 -0
  2. package/README.md +1 -1
  3. package/dist/client/connect/payoutAdoptionTestHelpers.d.ts +52 -0
  4. package/dist/client/connect/payoutAdoptionTestHelpers.d.ts.map +1 -1
  5. package/dist/client/connect/payoutExecutionTestHelpers.d.ts +42 -16
  6. package/dist/client/connect/payoutExecutionTestHelpers.d.ts.map +1 -1
  7. package/dist/client/connect/payoutLargeAdoptionTestHelpers.d.ts +84 -32
  8. package/dist/client/connect/payoutLargeAdoptionTestHelpers.d.ts.map +1 -1
  9. package/dist/client/connect/payoutSyncTestHelpers.d.ts +26 -0
  10. package/dist/client/connect/payoutSyncTestHelpers.d.ts.map +1 -1
  11. package/dist/component/balanceFunding/internal/actions.d.ts +11 -11
  12. package/dist/component/balanceFunding/mutations.d.ts +16 -16
  13. package/dist/component/balanceFunding/workflowValidators.d.ts +16 -16
  14. package/dist/component/earnings/triggers.d.ts +44 -0
  15. package/dist/component/earnings/triggers.d.ts.map +1 -1
  16. package/dist/component/renewalWitnesses/eligibility.d.ts +36 -0
  17. package/dist/component/renewalWitnesses/eligibility.d.ts.map +1 -0
  18. package/dist/component/renewalWitnesses/eligibility.js +60 -0
  19. package/dist/component/renewalWitnesses/eligibility.js.map +1 -0
  20. package/dist/component/renewalWitnesses/protocol.d.ts +75 -0
  21. package/dist/component/renewalWitnesses/protocol.d.ts.map +1 -0
  22. package/dist/component/renewalWitnesses/protocol.js +82 -0
  23. package/dist/component/renewalWitnesses/protocol.js.map +1 -0
  24. package/dist/component/renewalWitnesses/schema.d.ts +99 -0
  25. package/dist/component/renewalWitnesses/schema.d.ts.map +1 -0
  26. package/dist/component/renewalWitnesses/schema.js +36 -0
  27. package/dist/component/renewalWitnesses/schema.js.map +1 -0
  28. package/dist/component/renewalWitnesses/source.d.ts +22 -0
  29. package/dist/component/renewalWitnesses/source.d.ts.map +1 -0
  30. package/dist/component/renewalWitnesses/source.js +108 -0
  31. package/dist/component/renewalWitnesses/source.js.map +1 -0
  32. package/dist/component/schema.d.ts +42 -16
  33. package/dist/component/schema.js +2 -0
  34. package/dist/component/schema.js.map +1 -1
  35. package/dist/component/usage/allowance.fixtures.d.ts +26 -0
  36. package/dist/component/usage/allowance.fixtures.d.ts.map +1 -1
  37. package/dist/component/usageCredits/accounting.fixtures.d.ts +26 -0
  38. package/dist/component/usageCredits/accounting.fixtures.d.ts.map +1 -1
  39. package/dist/shared/renewalWitness.d.ts +51 -0
  40. package/dist/shared/renewalWitness.d.ts.map +1 -0
  41. package/dist/shared/renewalWitness.js +127 -0
  42. package/dist/shared/renewalWitness.js.map +1 -0
  43. package/docs/renewal-witness-protocol.md +88 -0
  44. package/package.json +1 -1
  45. package/src/component/renewalOperations/configureJournal.fixtures.ts +25 -3
  46. package/src/component/renewalWitnesses/bounds.test.ts +204 -0
  47. package/src/component/renewalWitnesses/codec.test.ts +84 -0
  48. package/src/component/renewalWitnesses/controls.test.ts +250 -0
  49. package/src/component/renewalWitnesses/eligibility.ts +78 -0
  50. package/src/component/renewalWitnesses/protocol.test.ts +63 -0
  51. package/src/component/renewalWitnesses/protocol.ts +103 -0
  52. package/src/component/renewalWitnesses/schema.ts +36 -0
  53. package/src/component/renewalWitnesses/source.ts +157 -0
  54. package/src/component/schema.ts +2 -0
  55. package/src/shared/renewalWitness.ts +179 -0
@@ -0,0 +1,88 @@
1
+ # Immutable renewal witness protocol
2
+
3
+ This component protocol stores complete unsigned renewal snapshot DATA. It is
4
+ the persistence prerequisite for historical acquisition, not an activated
5
+ capture or authorization API. It adds a table and ordinary transactional helpers,
6
+ with no registered production query or mutation. Live capture, separate host
7
+ retain/read capabilities, actual returned acknowledgement custody and genuine
8
+ generated routes remain required before runtime activation.
9
+
10
+ ## Payload and source checks
11
+
12
+ The canonical envelope contains exact installation/witness/parent/configure
13
+ identity, captured subject, bounded acquisition metadata, complete source records
14
+ and reservations, retained attachment receipt, optional retained configure
15
+ receipt, full raw reads and optional complete invoice context. Unknown resource
16
+ fields, own null values and wire decimal strings remain intact.
17
+
18
+ Acquisition metadata names the base 44-read profile and a separate nullable
19
+ seven-extra-read invoice profile. Wall and canonical decimal nanosecond durations
20
+ must fit the original 30-second profile; the derived wall start is nonnegative.
21
+ These are unsigned metadata checks. They establish neither an actual invocation
22
+ nor provider historical time.
23
+
24
+ At both retain and read boundaries, validation reloads the actual original
25
+ component records, payload owners, active reservations, parent basis, complete
26
+ event chains and retained acknowledgements. It checks the parent link and full
27
+ stored source against those records. Configure events must match the complete
28
+ C7 request; response2 is reconstructed even without retained C9. Opaque generic
29
+ journal events do not qualify this protocol. Full stage events need not be
30
+ duplicated in each witness because their actual immutable records are checked.
31
+
32
+ Configuration comes from the complete C7 record. Captured-present C9 must match
33
+ its full retained counterpart; raw constructor input is reconstructed from exact
34
+ dispatch, provider snapshot and transport. Captured-null C9 remains null even if
35
+ a valid C9 is retained later. Later journal integrity is checked without
36
+ injecting the newer receipt into the stored snapshot.
37
+
38
+ The existing evidence analyzer must recompute `current_target_material_match`.
39
+ If invoice context is included, it must also supply complete paired correlation.
40
+ Stored analysis flags and hashes alone do not qualify material. Descriptor
41
+ scope, successor item and native period derive from the complete admitted
42
+ evidence. No live provider resource is fetched during persistence or retrieval.
43
+
44
+ ## Immutable transactions and bounds
45
+
46
+ The logical uniqueness key is installation `componentScope` plus `witnessId`.
47
+ The complete identity additionally binds parent and configure operation IDs.
48
+ Indexed lookups use `take(2)` to detect duplicate rows. First identity wins:
49
+ identical canonical payloads return the same descriptor, while a changed payload
50
+ or operation under that key conflicts. The protocol never overwrites, repairs
51
+ or chooses a new identity automatically.
52
+
53
+ A read checks the full requested identity before releasing content. Wrong
54
+ installation, witness or operation returns no payload. The stored payload is
55
+ revalidated against original component context and its full digest; corrupted,
56
+ missing or duplicate source/storage rows refuse. Later live resource drift does
57
+ not replace the earlier snapshot.
58
+
59
+ The complete canonical envelope keeps the existing 500,000-byte, 10,000-node and
60
+ 40-depth bounds. Before insertion, the protocol also charges the complete stored
61
+ value and full read reply, reserving the admitted maximum opaque ID length for
62
+ its future descriptor. It never crops resources to fit. Transactional helpers
63
+ are intended for one retain operation per registered transaction; normal Convex
64
+ transaction concurrency provides the first-wins behavior across calls.
65
+
66
+ ## Retention and historical meaning
67
+
68
+ A successful transaction returns a row descriptor and full payload binding. It
69
+ does not prove that an external caller received that result. A lost response can
70
+ leave a durable row with no returned public acknowledgement. An explicit later
71
+ identical request can recover the same descriptor, subject to the separate host
72
+ policy and runtime custody checks required for historical acquisition.
73
+
74
+ Descriptors always report false authentication, operational authority and public
75
+ delivery, with provider qualification still required. The captured subject is
76
+ immutable DATA, not permission for a later reader. A later host authorization
77
+ may permit a different subject without rewriting the capture.
78
+
79
+ Stored raw material may supply `{reads, invoiceContext}` to the historical
80
+ evidence axis, independently of later live settings or terminal drift. It does
81
+ not revive a write Owner, manufacture a native past observation, prove atomic
82
+ acquisition or establish exclusive causality. Fetching an old invoice later is
83
+ not a substitute for the complete active snapshot.
84
+
85
+ The controlled tests exercise real component transaction helpers and journal
86
+ records. Production route generation, deployment, native/provider qualification,
87
+ actual capture/read integration, release acceptance and Dojo adoption remain
88
+ separate requirements. Existing execution holds remain in force.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@fantastic.dev/better-stripe",
3
- "version": "0.110.0",
3
+ "version": "0.111.0",
4
4
  "description": "Convex component for Stripe Accounts v2, subscriptions, metered billing and Connect marketplaces, with React workflows.",
5
5
  "keywords": [
6
6
  "stripe",
@@ -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
+ });