@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,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,63 @@
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 { canonicalWitnessJSON } from "../../shared/renewalWitness.js";
5
+ import { retainWitness, readWitness } from "./protocol.js";
6
+ import { inspectRenewalEvidenceV1 } from "../../client/billing/renewalObservation/evidence-v1.js";
7
+
8
+ afterEach(() => {
9
+ vi.unstubAllGlobals();
10
+ vi.restoreAllMocks();
11
+ });
12
+ it("admits a complete canonical snapshot after checking its independent material prerequisite", async () => {
13
+ const h = await witnessFixture();
14
+ const result = await inspectRenewalEvidenceV1({
15
+ version: 1,
16
+ apiVersion: "2026-09-30.endive",
17
+ configuration: h.configuration,
18
+ configureReceipt: null,
19
+ reads: h.payload.reads,
20
+ invoiceContext: null,
21
+ historicalSnapshot: null,
22
+ });
23
+ expect(result.currentMaterial.predicate).toBe(
24
+ "current_target_material_match",
25
+ );
26
+ const raw = canonicalConfigure(h.payload);
27
+ expect(canonicalWitnessJSON(raw)).toEqual({ json: raw, value: h.payload });
28
+ expect(h.fetches()).toBe(0);
29
+ });
30
+ it("retains and reads the complete immutable payload with a stable duplicate descriptor", async () => {
31
+ const h = await witnessFixture();
32
+ const args = {
33
+ identity: h.identity,
34
+ payloadJSON: canonicalConfigure(h.payload),
35
+ };
36
+ const first = await h.t.run((ctx) => retainWitness(ctx, args));
37
+ expect(first).toMatchObject({
38
+ status: "retained",
39
+ descriptor: {
40
+ identity: h.identity,
41
+ operationalAuthority: false,
42
+ publicDeliveryEstablished: false,
43
+ },
44
+ });
45
+ expect(await h.t.run((ctx) => retainWitness(ctx, args))).toEqual(first);
46
+ expect(await h.t.run((ctx) => readWitness(ctx, h.identity))).toEqual({
47
+ descriptor: Reflect.get(first as object, "descriptor"),
48
+ payloadJSON: args.payloadJSON,
49
+ });
50
+ });
51
+ it.each(["noncanonical", "duplicate-key", "utf8-overflow"] as const)(
52
+ "rejects %s before any storage",
53
+ async (mode) => {
54
+ const h = await witnessFixture();
55
+ const raw =
56
+ mode === "noncanonical"
57
+ ? JSON.stringify(h.payload, null, 2)
58
+ : mode === "duplicate-key"
59
+ ? '{"version":1,"version":2}'
60
+ : JSON.stringify({ padding: "\u0800".repeat(170000) });
61
+ expect(() => canonicalWitnessJSON(raw)).toThrow();
62
+ },
63
+ );
@@ -0,0 +1,103 @@
1
+ import { getConvexSize } from "convex/values";
2
+ import type { MutationCtx, QueryCtx } from "../_generated/server.js";
3
+ import { sameJSON } from "../renewalOperations/attachValidation.js";
4
+ import {
5
+ witnessNeed as need,
6
+ witnessIdentity,
7
+ type WitnessIdentity,
8
+ } from "../../shared/renewalWitness.js";
9
+ import { normalizedWitnessIdentity } from "./source.js";
10
+ import { validateWitness } from "./eligibility.js";
11
+
12
+ type Reader = Pick<QueryCtx, "db">;
13
+ async function find(ctx: Reader, identity: WitnessIdentity) {
14
+ const rows = await ctx.db
15
+ .query("renewalObservationWitnesses")
16
+ .withIndex("by_componentScope_and_witnessId", (q) =>
17
+ q
18
+ .eq("identity.componentScope", identity.componentScope)
19
+ .eq("identity.witnessId", identity.witnessId),
20
+ )
21
+ .take(2);
22
+ need(rows.length <= 1);
23
+ return rows[0] ?? null;
24
+ }
25
+ function budget(admitted: Awaited<ReturnType<typeof validateWitness>>) {
26
+ const { payload, fields, payloadBinding } = admitted;
27
+ need(
28
+ getConvexSize({
29
+ identity: fields.identity,
30
+ payloadJSON: payload.json,
31
+ payloadBinding,
32
+ }) <= 500000,
33
+ );
34
+ // Reserve the maximum admitted opaque ID length before making any insert.
35
+ need(
36
+ getConvexSize({
37
+ descriptor: { ...fields, payloadBinding, witnessRowId: "x".repeat(255) },
38
+ payloadJSON: payload.json,
39
+ }) <= 500000,
40
+ );
41
+ }
42
+ async function checked(
43
+ ctx: Reader,
44
+ row: NonNullable<Awaited<ReturnType<typeof find>>>,
45
+ ) {
46
+ const admitted = await validateWitness(ctx, row.payloadJSON);
47
+ budget(admitted);
48
+ need(
49
+ sameJSON(admitted.fields.identity, row.identity) &&
50
+ admitted.payloadBinding === row.payloadBinding,
51
+ );
52
+ return {
53
+ descriptor: {
54
+ ...admitted.fields,
55
+ payloadBinding: admitted.payloadBinding,
56
+ witnessRowId: row._id,
57
+ },
58
+ payloadJSON: admitted.payload.json,
59
+ };
60
+ }
61
+ /** Trusted component helper only. A host retention capability and live capture remain required. */
62
+ export async function retainWitness(
63
+ ctx: Pick<MutationCtx, "db">,
64
+ args: { identity: WitnessIdentity; payloadJSON: string },
65
+ ) {
66
+ const identity = normalizedWitnessIdentity(ctx, args.identity);
67
+ const admitted = await validateWitness(ctx, args.payloadJSON);
68
+ need(sameJSON(admitted.fields.identity, identity));
69
+ budget(admitted);
70
+ const existing = await find(ctx, identity);
71
+ if (existing) {
72
+ const original = await checked(ctx, existing);
73
+ if (
74
+ existing.payloadJSON !== admitted.payload.json ||
75
+ !sameJSON(existing.identity, identity)
76
+ )
77
+ return {
78
+ status: "conflict" as const,
79
+ reason: "identity_changed" as const,
80
+ };
81
+ return { status: "retained" as const, descriptor: original.descriptor };
82
+ }
83
+ const witnessRowId = await ctx.db.insert("renewalObservationWitnesses", {
84
+ identity,
85
+ payloadJSON: admitted.payload.json,
86
+ payloadBinding: admitted.payloadBinding,
87
+ });
88
+ return {
89
+ status: "retained" as const,
90
+ descriptor: {
91
+ ...admitted.fields,
92
+ payloadBinding: admitted.payloadBinding,
93
+ witnessRowId,
94
+ },
95
+ };
96
+ }
97
+ /** Fresh host read authorization belongs to the caller; this cannot establish public ACK delivery. */
98
+ export async function readWitness(ctx: Reader, raw: WitnessIdentity) {
99
+ const identity = witnessIdentity(raw);
100
+ const row = await find(ctx, identity);
101
+ if (!row || !sameJSON(row.identity, identity)) return null;
102
+ return checked(ctx, row);
103
+ }
@@ -0,0 +1,36 @@
1
+ import { defineTable } from "convex/server";
2
+ import { v } from "convex/values";
3
+
4
+ export const identity = v.object({
5
+ componentScope: v.string(),
6
+ witnessId: v.string(),
7
+ parentOperationId: v.id("renewalOperations"),
8
+ operationId: v.id("renewalOperations"),
9
+ });
10
+ export const descriptor = v.object({
11
+ version: v.literal(1),
12
+ witnessRowId: v.id("renewalObservationWitnesses"),
13
+ identity,
14
+ payloadBinding: v.string(),
15
+ capturedSubject: v.string(),
16
+ observedAtMs: v.number(),
17
+ customerAccountId: v.string(),
18
+ customerId: v.string(),
19
+ livemode: v.boolean(),
20
+ subscriptionId: v.string(),
21
+ scheduleId: v.string(),
22
+ observedItemId: v.string(),
23
+ nativePeriod: v.object({ start: v.number(), end: v.number() }),
24
+ operationalAuthority: v.literal(false),
25
+ authenticationEstablished: v.literal(false),
26
+ publicDeliveryEstablished: v.literal(false),
27
+ providerQualificationRequired: v.literal(true),
28
+ });
29
+ export const witnessesTable = defineTable({
30
+ identity,
31
+ payloadJSON: v.string(),
32
+ payloadBinding: v.string(),
33
+ }).index("by_componentScope_and_witnessId", [
34
+ "identity.componentScope",
35
+ "identity.witnessId",
36
+ ]);
@@ -0,0 +1,157 @@
1
+ import type { QueryCtx } from "../_generated/server.js";
2
+ import type { Id } from "../_generated/dataModel.js";
3
+ import { readCheckedOperation } from "../renewalOperations/operationContext.js";
4
+ import {
5
+ currentReservation,
6
+ eventChain,
7
+ validateV2KnownAcknowledgement,
8
+ } from "../renewalOperations/helpers.js";
9
+ import { sameJSON } from "../renewalOperations/attachValidation.js";
10
+ import { validateConfigureAcknowledgement } from "../renewalOperations/configureAcknowledgement.js";
11
+ import { constructRenewalConfigurationReceiptV2 } from "../../client/billing/renewalV2/index.js";
12
+ import {
13
+ witnessIdentity,
14
+ witnessNeed as need,
15
+ witnessObject as object,
16
+ witnessClosed as closed,
17
+ type WitnessIdentity,
18
+ type WitnessPayload,
19
+ } from "../../shared/renewalWitness.js";
20
+
21
+ type Reader = Pick<QueryCtx, "db">;
22
+ export function normalizedWitnessIdentity(ctx: Reader, raw: WitnessIdentity) {
23
+ const value = witnessIdentity(raw);
24
+ const parentOperationId = ctx.db.normalizeId(
25
+ "renewalOperations",
26
+ value.parentOperationId,
27
+ );
28
+ const operationId = ctx.db.normalizeId(
29
+ "renewalOperations",
30
+ value.operationId,
31
+ );
32
+ need(parentOperationId && operationId);
33
+ return { ...value, parentOperationId, operationId };
34
+ }
35
+ async function checkedStage(
36
+ ctx: Reader,
37
+ operationId: Id<"renewalOperations">,
38
+ stage: "attach" | "configure",
39
+ ) {
40
+ const row = await ctx.db.get("renewalOperations", operationId);
41
+ need(row && row.recordVersion === 2);
42
+ const full = await readCheckedOperation(ctx, row);
43
+ const reservation = await currentReservation(ctx, row, full);
44
+ need(
45
+ reservation &&
46
+ "recordVersion" in reservation &&
47
+ reservation.stage === stage,
48
+ );
49
+ const events = await eventChain(ctx, reservation);
50
+ const known = await validateV2KnownAcknowledgement(
51
+ ctx,
52
+ row,
53
+ full,
54
+ reservation,
55
+ events,
56
+ );
57
+ if (stage === "configure" && events.length > 0) {
58
+ const original = object(JSON.parse(full.json));
59
+ const request = object(original.configureRecord).request;
60
+ need(
61
+ sameJSON(JSON.parse(events[0].dataJSON), {
62
+ event: "dispatch",
63
+ stage: "configure",
64
+ request,
65
+ }),
66
+ );
67
+ if (events.length === 3) need(known);
68
+ if (events.length >= 2 && !known) {
69
+ const response = closed(JSON.parse(events[1].dataJSON), [
70
+ "event",
71
+ "stage",
72
+ "request",
73
+ "body",
74
+ "transport",
75
+ ]);
76
+ need(
77
+ response.event === "response" &&
78
+ response.stage === "configure" &&
79
+ sameJSON(response.request, request),
80
+ );
81
+ type Input = Parameters<typeof constructRenewalConfigurationReceiptV2>[0];
82
+ const receipt = await constructRenewalConfigurationReceiptV2({
83
+ configuration: object(original.configureRecord)
84
+ .configuration as Input["configuration"],
85
+ actualDispatch: original.dispatch as Input["actualDispatch"],
86
+ providerSnapshot: object(response.body),
87
+ transport: object(response.transport) as Input["transport"],
88
+ });
89
+ await validateConfigureAcknowledgement(
90
+ full,
91
+ reservation,
92
+ events,
93
+ JSON.stringify(receipt),
94
+ );
95
+ }
96
+ }
97
+ if (stage === "attach")
98
+ need(events.length === 3 && known && row.initialBasis);
99
+ const { recordJSON: _recordJSON, ...summary } = reservation;
100
+ void _recordJSON;
101
+ const acknowledgement =
102
+ known === null
103
+ ? null
104
+ : {
105
+ retention: {
106
+ status: "retained" as const,
107
+ operationId,
108
+ ...known.retained,
109
+ },
110
+ receipt: JSON.parse(known.admitted.receiptJSON) as Record<
111
+ string,
112
+ unknown
113
+ >,
114
+ };
115
+ return {
116
+ record: JSON.parse(full.json) as Record<string, unknown>,
117
+ reservation: summary,
118
+ acknowledgement,
119
+ initialBasis: row.initialBasis,
120
+ };
121
+ }
122
+ /** Reload complete actual chains/owners on every boundary; never trust stored flags. */
123
+ export async function validateWitnessSource(
124
+ ctx: Reader,
125
+ value: WitnessPayload,
126
+ ) {
127
+ const identity = normalizedWitnessIdentity(ctx, value.identity);
128
+ const parent = await checkedStage(ctx, identity.parentOperationId, "attach");
129
+ const child = await checkedStage(ctx, identity.operationId, "configure");
130
+ need(
131
+ object(child.record.parentAttachment).operationId ===
132
+ identity.parentOperationId,
133
+ );
134
+ need(parent.initialBasis && parent.acknowledgement);
135
+ const includeC9 = value.source.configure.acknowledgement !== null;
136
+ if (includeC9) need(child.acknowledgement);
137
+ const expected = {
138
+ parent: {
139
+ record: parent.record,
140
+ reservation: parent.reservation,
141
+ initialBasis: parent.initialBasis,
142
+ acknowledgement: parent.acknowledgement,
143
+ },
144
+ configure: {
145
+ record: child.record,
146
+ reservation: child.reservation,
147
+ acknowledgement: includeC9 ? child.acknowledgement : null,
148
+ },
149
+ };
150
+ need(sameJSON(value.source, expected));
151
+ // A later valid C9 is checked above but cannot be injected into captured-null DATA.
152
+ return {
153
+ identity,
154
+ configuration: object(child.record.configureRecord).configuration,
155
+ dispatch: child.record.dispatch,
156
+ };
157
+ }
@@ -141,8 +141,10 @@ import {
141
141
  operationsTable as renewalOperations,
142
142
  payloadsTable as renewalOperationPayloads,
143
143
  } from "./renewalOperations/schema.js";
144
+ import { witnessesTable as renewalObservationWitnesses } from "./renewalWitnesses/schema.js";
144
145
 
145
146
  export default defineSchema({
147
+ renewalObservationWitnesses,
146
148
  renewalOperations,
147
149
  renewalOperationAttempts,
148
150
  renewalOperationEvents,
@@ -0,0 +1,179 @@
1
+ import { renewalSnapshot } from "../client/billing/renewalReplacementSnapshot.js";
2
+ import type { ObservationReads } from "../client/billing/renewalAttach/internal/observation/types.js";
3
+ import type { InvoiceContextV1 } from "../client/billing/renewalObservation/evidence-v1-types.js";
4
+
5
+ export function witnessStop(): never {
6
+ throw Error("RENEWAL_WITNESS_INVALID");
7
+ }
8
+ export function witnessNeed(value: unknown): asserts value {
9
+ if (!value) witnessStop();
10
+ }
11
+ export function witnessObject(raw: unknown): Record<string, unknown> {
12
+ witnessNeed(raw !== null && typeof raw === "object" && !Array.isArray(raw));
13
+ return raw as Record<string, unknown>;
14
+ }
15
+ export function witnessClosed(raw: unknown, keys: readonly string[]) {
16
+ const value = witnessObject(raw),
17
+ actual = Object.keys(value);
18
+ witnessNeed(
19
+ actual.length === keys.length && actual.every((key) => keys.includes(key)),
20
+ );
21
+ return value;
22
+ }
23
+ export function witnessText(raw: unknown, max = 255): string {
24
+ witnessNeed(typeof raw === "string" && raw.length > 0 && raw.length <= max);
25
+ return raw;
26
+ }
27
+ export type WitnessIdentity = Readonly<{
28
+ componentScope: string;
29
+ witnessId: string;
30
+ parentOperationId: string;
31
+ operationId: string;
32
+ }>;
33
+ export function witnessIdentity(raw: unknown): WitnessIdentity {
34
+ const value = witnessClosed(raw, [
35
+ "componentScope",
36
+ "witnessId",
37
+ "parentOperationId",
38
+ "operationId",
39
+ ]);
40
+ const identity = {
41
+ componentScope: witnessText(value.componentScope),
42
+ witnessId: witnessText(value.witnessId),
43
+ parentOperationId: witnessText(value.parentOperationId),
44
+ operationId: witnessText(value.operationId),
45
+ };
46
+ witnessNeed(identity.operationId !== identity.parentOperationId);
47
+ return identity;
48
+ }
49
+ export type WitnessAcknowledgement = Readonly<{
50
+ retention: Record<string, unknown>;
51
+ receipt: Record<string, unknown>;
52
+ }>;
53
+ export type WitnessStage = Readonly<{
54
+ record: Record<string, unknown>;
55
+ reservation: Record<string, unknown>;
56
+ acknowledgement: WitnessAcknowledgement | null;
57
+ }>;
58
+ export type WitnessPayload = Readonly<{
59
+ version: 1;
60
+ kind: "renewal_witness_payload";
61
+ identity: WitnessIdentity;
62
+ capturedSubject: string;
63
+ acquisition: Readonly<{
64
+ observedAtMs: number;
65
+ elapsedWallMs: number;
66
+ elapsedNsDecimal: string;
67
+ apiVersion: "2026-09-30.endive";
68
+ baseReadProfile: "endive-schedule-first-44-v1";
69
+ invoiceReadProfile: "endive-pinned-invoices-fence-7-v1" | null;
70
+ }>;
71
+ source: Readonly<{
72
+ parent: WitnessStage & Readonly<{ initialBasis: Record<string, unknown> }>;
73
+ configure: WitnessStage;
74
+ }>;
75
+ reads: ObservationReads;
76
+ invoiceContext: InvoiceContextV1 | null;
77
+ }>;
78
+ function acknowledgement(raw: unknown): WitnessAcknowledgement | null {
79
+ if (raw === null) return null;
80
+ const value = witnessClosed(raw, ["retention", "receipt"]);
81
+ return {
82
+ retention: witnessObject(value.retention),
83
+ receipt: witnessObject(value.receipt),
84
+ };
85
+ }
86
+ function stage(raw: unknown, parent: boolean) {
87
+ const value = witnessClosed(raw, [
88
+ "record",
89
+ "reservation",
90
+ "acknowledgement",
91
+ ...(parent ? ["initialBasis"] : []),
92
+ ]);
93
+ return {
94
+ record: witnessObject(value.record),
95
+ reservation: witnessObject(value.reservation),
96
+ acknowledgement: acknowledgement(value.acknowledgement),
97
+ ...(parent ? { initialBasis: witnessObject(value.initialBasis) } : {}),
98
+ };
99
+ }
100
+ /** Complete canonical JSON only. This admits DATA, not capture/authentication authority. */
101
+ export function canonicalWitnessJSON(
102
+ raw: string,
103
+ ): Readonly<{ json: string; value: WitnessPayload }> {
104
+ witnessNeed(
105
+ typeof raw === "string" &&
106
+ raw.length <= 500000 &&
107
+ new TextEncoder().encode(raw).length <= 500000,
108
+ );
109
+ const copy: unknown = renewalSnapshot(JSON.parse(raw));
110
+ witnessNeed(JSON.stringify(copy) === raw);
111
+ const value = witnessClosed(copy, [
112
+ "version",
113
+ "kind",
114
+ "identity",
115
+ "capturedSubject",
116
+ "acquisition",
117
+ "source",
118
+ "reads",
119
+ "invoiceContext",
120
+ ]);
121
+ witnessNeed(value.version === 1 && value.kind === "renewal_witness_payload");
122
+ witnessIdentity(value.identity);
123
+ witnessText(value.capturedSubject, 2048);
124
+ const acquired = witnessClosed(value.acquisition, [
125
+ "observedAtMs",
126
+ "elapsedWallMs",
127
+ "elapsedNsDecimal",
128
+ "apiVersion",
129
+ "baseReadProfile",
130
+ "invoiceReadProfile",
131
+ ]);
132
+ witnessNeed(
133
+ typeof acquired.observedAtMs === "number" &&
134
+ Number.isSafeInteger(acquired.observedAtMs) &&
135
+ acquired.observedAtMs >= 0,
136
+ );
137
+ witnessNeed(
138
+ typeof acquired.elapsedWallMs === "number" &&
139
+ Number.isSafeInteger(acquired.elapsedWallMs) &&
140
+ acquired.elapsedWallMs >= 0 &&
141
+ acquired.elapsedWallMs < 30000 &&
142
+ acquired.observedAtMs - acquired.elapsedWallMs >= 0,
143
+ );
144
+ witnessNeed(
145
+ typeof acquired.elapsedNsDecimal === "string" &&
146
+ /^(0|[1-9][0-9]{0,10})$/.test(acquired.elapsedNsDecimal) &&
147
+ BigInt(acquired.elapsedNsDecimal) < 30000000000n,
148
+ );
149
+ witnessNeed(
150
+ acquired.apiVersion === "2026-09-30.endive" &&
151
+ acquired.baseReadProfile === "endive-schedule-first-44-v1",
152
+ );
153
+ witnessNeed(
154
+ value.invoiceContext === null
155
+ ? acquired.invoiceReadProfile === null
156
+ : acquired.invoiceReadProfile === "endive-pinned-invoices-fence-7-v1",
157
+ );
158
+ const source = witnessClosed(value.source, ["parent", "configure"]);
159
+ witnessNeed(stage(source.parent, true).acknowledgement !== null);
160
+ stage(source.configure, false);
161
+ const reads = witnessClosed(value.reads, [
162
+ "schedule",
163
+ "subscription",
164
+ "targetPrice",
165
+ "billingCustomer",
166
+ "coupons",
167
+ ]);
168
+ for (const name of [
169
+ "schedule",
170
+ "subscription",
171
+ "targetPrice",
172
+ "billingCustomer",
173
+ ])
174
+ witnessObject(reads[name]);
175
+ witnessNeed(Array.isArray(reads.coupons));
176
+ if (value.invoiceContext !== null)
177
+ witnessClosed(value.invoiceContext, ["original", "current"]);
178
+ return Object.freeze({ json: raw, value: copy as WitnessPayload });
179
+ }