@fantastic.dev/better-stripe 0.110.0 → 0.112.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (134) hide show
  1. package/CHANGELOG.md +12 -0
  2. package/README.md +1 -1
  3. package/dist/client/billing/renewalAttach/internal/observation/freshActor.d.ts +564 -0
  4. package/dist/client/billing/renewalAttach/internal/observation/freshActor.d.ts.map +1 -1
  5. package/dist/client/billing/renewalAttach/internal/observation/freshActor.js +103 -21
  6. package/dist/client/billing/renewalAttach/internal/observation/freshActor.js.map +1 -1
  7. package/dist/client/billing/renewalAttach/internal/observation/freshTransport.d.ts +18 -1
  8. package/dist/client/billing/renewalAttach/internal/observation/freshTransport.d.ts.map +1 -1
  9. package/dist/client/billing/renewalAttach/internal/observation/freshTransport.js +54 -1
  10. package/dist/client/billing/renewalAttach/internal/observation/freshTransport.js.map +1 -1
  11. package/dist/client/billing/renewalAttach/internal/observation/invocation.d.ts +4 -0
  12. package/dist/client/billing/renewalAttach/internal/observation/invocation.d.ts.map +1 -1
  13. package/dist/client/billing/renewalAttach/internal/observation/invocation.js +1 -0
  14. package/dist/client/billing/renewalAttach/internal/observation/invocation.js.map +1 -1
  15. package/dist/client/billing/renewalAttach/internal/observation/readerAuthorization.d.ts +4 -0
  16. package/dist/client/billing/renewalAttach/internal/observation/readerAuthorization.d.ts.map +1 -1
  17. package/dist/client/billing/renewalAttach/internal/observation/readerAuthorization.js +6 -1
  18. package/dist/client/billing/renewalAttach/internal/observation/readerAuthorization.js.map +1 -1
  19. package/dist/client/billing/renewalAttach/internal/observation/witnessAuthorization.d.ts +38 -0
  20. package/dist/client/billing/renewalAttach/internal/observation/witnessAuthorization.d.ts.map +1 -0
  21. package/dist/client/billing/renewalAttach/internal/observation/witnessAuthorization.js +172 -0
  22. package/dist/client/billing/renewalAttach/internal/observation/witnessAuthorization.js.map +1 -0
  23. package/dist/client/billing/renewalAttach/internal/observation/witnessData.d.ts +135 -0
  24. package/dist/client/billing/renewalAttach/internal/observation/witnessData.d.ts.map +1 -0
  25. package/dist/client/billing/renewalAttach/internal/observation/witnessData.js +143 -0
  26. package/dist/client/billing/renewalAttach/internal/observation/witnessData.js.map +1 -0
  27. package/dist/client/billing/renewalAttach/internal/observation/witnessOperation.d.ts +85 -0
  28. package/dist/client/billing/renewalAttach/internal/observation/witnessOperation.d.ts.map +1 -0
  29. package/dist/client/billing/renewalAttach/internal/observation/witnessOperation.js +121 -0
  30. package/dist/client/billing/renewalAttach/internal/observation/witnessOperation.js.map +1 -0
  31. package/dist/client/billing/renewalAttach/internal/operations/witnessProfiles.d.ts +44 -0
  32. package/dist/client/billing/renewalAttach/internal/operations/witnessProfiles.d.ts.map +1 -0
  33. package/dist/client/billing/renewalAttach/internal/operations/witnessProfiles.js +4 -0
  34. package/dist/client/billing/renewalAttach/internal/operations/witnessProfiles.js.map +1 -0
  35. package/dist/client/billing/renewalAttach/internal/producer/configureJournalWork.d.ts +1 -1
  36. package/dist/client/billing/renewalAttach/internal/producer/configureLineage.d.ts +21 -21
  37. package/dist/client/billing/renewalAttach/internal/producer/journalWorkFactory.d.ts +3 -3
  38. package/dist/client/billing/renewalAttach/internal/producer/operationFactory.d.ts +1 -1
  39. package/dist/client/connect/payoutAdoptionTestHelpers.d.ts +84 -32
  40. package/dist/client/connect/payoutAdoptionTestHelpers.d.ts.map +1 -1
  41. package/dist/client/connect/payoutExecutionTestHelpers.d.ts +26 -0
  42. package/dist/client/connect/payoutExecutionTestHelpers.d.ts.map +1 -1
  43. package/dist/client/connect/payoutLargeAdoptionTestHelpers.d.ts +84 -32
  44. package/dist/client/connect/payoutLargeAdoptionTestHelpers.d.ts.map +1 -1
  45. package/dist/client/connect/payoutSyncTestHelpers.d.ts +26 -0
  46. package/dist/client/connect/payoutSyncTestHelpers.d.ts.map +1 -1
  47. package/dist/component/_generated/api.d.ts +24 -0
  48. package/dist/component/_generated/api.d.ts.map +1 -1
  49. package/dist/component/_generated/api.js.map +1 -1
  50. package/dist/component/_generated/component.d.ts +94 -10
  51. package/dist/component/_generated/component.d.ts.map +1 -1
  52. package/dist/component/balanceFunding/internal/actions.d.ts +11 -11
  53. package/dist/component/balanceFunding/mutations.d.ts +16 -16
  54. package/dist/component/balanceFunding/preparationHandlers.d.ts +8 -8
  55. package/dist/component/balanceFunding/queries.d.ts +1 -1
  56. package/dist/component/balanceFunding/workflowValidators.d.ts +16 -16
  57. package/dist/component/earnings/triggers.d.ts +44 -0
  58. package/dist/component/earnings/triggers.d.ts.map +1 -1
  59. package/dist/component/financialObservations/settlementHelpers.d.ts +3 -3
  60. package/dist/component/renewalWitnesses/eligibility.d.ts +36 -0
  61. package/dist/component/renewalWitnesses/eligibility.d.ts.map +1 -0
  62. package/dist/component/renewalWitnesses/eligibility.js +60 -0
  63. package/dist/component/renewalWitnesses/eligibility.js.map +1 -0
  64. package/dist/component/renewalWitnesses/mutations.d.ts +45 -0
  65. package/dist/component/renewalWitnesses/mutations.d.ts.map +1 -0
  66. package/dist/component/renewalWitnesses/mutations.js +14 -0
  67. package/dist/component/renewalWitnesses/mutations.js.map +1 -0
  68. package/dist/component/renewalWitnesses/protocol.d.ts +75 -0
  69. package/dist/component/renewalWitnesses/protocol.d.ts.map +1 -0
  70. package/dist/component/renewalWitnesses/protocol.js +82 -0
  71. package/dist/component/renewalWitnesses/protocol.js.map +1 -0
  72. package/dist/component/renewalWitnesses/queries.d.ts +39 -0
  73. package/dist/component/renewalWitnesses/queries.d.ts.map +1 -0
  74. package/dist/component/renewalWitnesses/queries.js +11 -0
  75. package/dist/component/renewalWitnesses/queries.js.map +1 -0
  76. package/dist/component/renewalWitnesses/schema.d.ts +99 -0
  77. package/dist/component/renewalWitnesses/schema.d.ts.map +1 -0
  78. package/dist/component/renewalWitnesses/schema.js +36 -0
  79. package/dist/component/renewalWitnesses/schema.js.map +1 -0
  80. package/dist/component/renewalWitnesses/source.d.ts +22 -0
  81. package/dist/component/renewalWitnesses/source.d.ts.map +1 -0
  82. package/dist/component/renewalWitnesses/source.js +108 -0
  83. package/dist/component/renewalWitnesses/source.js.map +1 -0
  84. package/dist/component/schema.d.ts +42 -16
  85. package/dist/component/schema.js +2 -0
  86. package/dist/component/schema.js.map +1 -1
  87. package/dist/component/usage/allowance.fixtures.d.ts +42 -16
  88. package/dist/component/usage/allowance.fixtures.d.ts.map +1 -1
  89. package/dist/component/usageCredits/accounting.fixtures.d.ts +26 -0
  90. package/dist/component/usageCredits/accounting.fixtures.d.ts.map +1 -1
  91. package/dist/shared/renewalWitness.d.ts +51 -0
  92. package/dist/shared/renewalWitness.d.ts.map +1 -0
  93. package/dist/shared/renewalWitness.js +127 -0
  94. package/dist/shared/renewalWitness.js.map +1 -0
  95. package/docs/renewal-witness-protocol.md +139 -0
  96. package/package.json +1 -1
  97. package/src/client/billing/renewalAttach/internal/observation/freshActor.ts +142 -19
  98. package/src/client/billing/renewalAttach/internal/observation/freshTransport.ts +90 -1
  99. package/src/client/billing/renewalAttach/internal/observation/invocation.ts +2 -0
  100. package/src/client/billing/renewalAttach/internal/observation/readerAuthorization.ts +6 -1
  101. package/src/client/billing/renewalAttach/internal/observation/witnessAcquisition.integration.test.ts +348 -0
  102. package/src/client/billing/renewalAttach/internal/observation/witnessActor.integration.test.ts +204 -0
  103. package/src/client/billing/renewalAttach/internal/observation/witnessAuthorization.ts +239 -0
  104. package/src/client/billing/renewalAttach/internal/observation/witnessCapabilities.integration.test.ts +231 -0
  105. package/src/client/billing/renewalAttach/internal/observation/witnessData.ts +189 -0
  106. package/src/client/billing/renewalAttach/internal/observation/witnessHistorical.integration.test.ts +98 -0
  107. package/src/client/billing/renewalAttach/internal/observation/witnessImmutable.integration.test.ts +78 -0
  108. package/src/client/billing/renewalAttach/internal/observation/witnessInvoice.integration.test.ts +85 -0
  109. package/src/client/billing/renewalAttach/internal/observation/witnessLifecycle.integration.test.ts +264 -0
  110. package/src/client/billing/renewalAttach/internal/observation/witnessOperation.ts +205 -0
  111. package/src/client/billing/renewalAttach/internal/observation/witnessProfile.integration.test.ts +93 -0
  112. package/src/client/billing/renewalAttach/internal/observation/witnessRPCControls.integration.test.ts +256 -0
  113. package/src/client/billing/renewalAttach/internal/operations/witnessProfiles.ts +58 -0
  114. package/src/client/billing/renewalAttach/internal/test-fixtures/invoiceObservation.ts +3 -1
  115. package/src/client/billing/renewalAttach/internal/test-fixtures/producerConfigureAdmission.ts +8 -0
  116. package/src/client/billing/renewalAttach/internal/test-fixtures/producerInitialOperation.ts +18 -7
  117. package/src/client/billing/renewalAttach/internal/test-fixtures/witnessHistory.ts +70 -0
  118. package/src/client/billing/renewalAttach/internal/test-fixtures/witnessObservation.ts +353 -0
  119. package/src/component/_generated/api.ts +24 -0
  120. package/src/component/_generated/component.ts +98 -10
  121. package/src/component/renewalOperations/configureJournal.fixtures.ts +25 -3
  122. package/src/component/renewalWitnesses/bounds.test.ts +204 -0
  123. package/src/component/renewalWitnesses/codec.test.ts +84 -0
  124. package/src/component/renewalWitnesses/controls.test.ts +250 -0
  125. package/src/component/renewalWitnesses/eligibility.ts +78 -0
  126. package/src/component/renewalWitnesses/mutations.ts +17 -0
  127. package/src/component/renewalWitnesses/protocol.test.ts +63 -0
  128. package/src/component/renewalWitnesses/protocol.ts +103 -0
  129. package/src/component/renewalWitnesses/queries.ts +11 -0
  130. package/src/component/renewalWitnesses/routes.test.ts +154 -0
  131. package/src/component/renewalWitnesses/schema.ts +36 -0
  132. package/src/component/renewalWitnesses/source.ts +157 -0
  133. package/src/component/schema.ts +2 -0
  134. package/src/shared/renewalWitness.ts +179 -0
@@ -0,0 +1,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,11 @@
1
+ import { v } from "convex/values";
2
+ import { query } from "../_generated/server.js";
3
+ import { descriptor, identity } from "./schema.js";
4
+ import { readWitness } from "./protocol.js";
5
+
6
+ /** Trusted host component API. A fresh host read grant must precede any external release. */
7
+ export const readAuthorizedWitness = query({
8
+ args: { identity },
9
+ returns: v.union(v.null(), v.object({ descriptor, payloadJSON: v.string() })),
10
+ handler: (ctx, args) => readWitness(ctx, args.identity),
11
+ });
@@ -0,0 +1,154 @@
1
+ import { makeFunctionReference } from "convex/server";
2
+ import { describe, expect, it } from "vitest";
3
+ import { witnessFixture } from "../../../tests/renewalObservation/witnessFixtures.js";
4
+ import { canonicalConfigure } from "../renewalOperations/configureJournal.fixtures.js";
5
+
6
+ // Test-only routing names do not stand in for genuine generated production references.
7
+ const retain = makeFunctionReference<"mutation">(
8
+ "renewalWitnesses/mutations:retainAuthorizedWitness",
9
+ );
10
+ const read = makeFunctionReference<"query">(
11
+ "renewalWitnesses/queries:readAuthorizedWitness",
12
+ );
13
+
14
+ describe("registered renewal witness component boundaries", () => {
15
+ it.each([false, true])(
16
+ "retains and reads complete immutable material with captured C9 %s",
17
+ async (retained) => {
18
+ const h = await witnessFixture(retained);
19
+ const payloadJSON = canonicalConfigure(h.payload);
20
+ const args = { identity: h.identity, payloadJSON };
21
+ const first = await h.t.mutation(retain, args);
22
+ expect(first.status).toBe("retained");
23
+ expect(first.descriptor.identity).toEqual(h.identity);
24
+ expect(first.descriptor.publicDeliveryEstablished).toBe(false);
25
+ expect(await h.t.mutation(retain, args)).toEqual(first);
26
+ expect(await h.t.query(read, { identity: h.identity })).toEqual({
27
+ descriptor: first.descriptor,
28
+ payloadJSON,
29
+ });
30
+ const altered = structuredClone(h.payload);
31
+ altered.capturedSubject = "another-captured-subject";
32
+ expect(
33
+ await h.t.mutation(retain, {
34
+ identity: h.identity,
35
+ payloadJSON: canonicalConfigure(altered),
36
+ }),
37
+ ).toEqual({ status: "conflict", reason: "identity_changed" });
38
+ expect(await h.t.query(read, { identity: h.identity })).toEqual({
39
+ descriptor: first.descriptor,
40
+ payloadJSON,
41
+ });
42
+ expect(h.fetches()).toBe(0);
43
+ },
44
+ );
45
+
46
+ it("rejects unknown identity fields and malformed operation IDs before storage", async () => {
47
+ const h = await witnessFixture();
48
+ const payloadJSON = canonicalConfigure(h.payload);
49
+ await expect(
50
+ h.t.mutation(retain, {
51
+ identity: { ...h.identity, extra: "not-admitted" },
52
+ payloadJSON,
53
+ }),
54
+ ).rejects.toThrow(/Validator error/);
55
+ await expect(
56
+ h.t.mutation(retain, {
57
+ identity: { ...h.identity, operationId: "not-a-convex-id" },
58
+ payloadJSON,
59
+ }),
60
+ ).rejects.toThrow(/Validator error/);
61
+ expect(
62
+ await h.t.run((ctx) =>
63
+ ctx.db.query("renewalObservationWitnesses").take(2),
64
+ ),
65
+ ).toEqual([]);
66
+ });
67
+
68
+ it("rejects unknown outer arguments and noncanonical payloads without inserting", async () => {
69
+ const h = await witnessFixture();
70
+ const args = {
71
+ identity: h.identity,
72
+ payloadJSON: canonicalConfigure(h.payload),
73
+ };
74
+ await expect(
75
+ h.t.mutation(retain, { ...args, extra: true }),
76
+ ).rejects.toThrow(/Validator error/);
77
+ await expect(
78
+ h.t.mutation(retain, {
79
+ ...args,
80
+ payloadJSON: JSON.stringify(h.payload, null, 2),
81
+ }),
82
+ ).rejects.toThrow("RENEWAL_WITNESS_INVALID");
83
+ expect(
84
+ await h.t.run((ctx) =>
85
+ ctx.db.query("renewalObservationWitnesses").take(2),
86
+ ),
87
+ ).toEqual([]);
88
+ });
89
+
90
+ it("releases no payload for another installation or operation identity", async () => {
91
+ const h = await witnessFixture();
92
+ await h.t.mutation(retain, {
93
+ identity: h.identity,
94
+ payloadJSON: canonicalConfigure(h.payload),
95
+ });
96
+ for (const identity of [
97
+ { ...h.identity, componentScope: "another-installation" },
98
+ {
99
+ ...h.identity,
100
+ operationId: h.identity.parentOperationId,
101
+ parentOperationId: h.identity.operationId,
102
+ },
103
+ { ...h.identity, witnessId: "another-witness" },
104
+ ]) {
105
+ expect(await h.t.query(read, { identity })).toBeNull();
106
+ }
107
+ await expect(
108
+ h.t.query(read, { identity: { ...h.identity, extra: true } }),
109
+ ).rejects.toThrow(/Validator error/);
110
+ await expect(
111
+ h.t.query(read, { identity: h.identity, extra: true }),
112
+ ).rejects.toThrow(/Validator error/);
113
+ expect(h.fetches()).toBe(0);
114
+ });
115
+
116
+ it("revalidates material behind a rehashed corrupt row without repairing it", async () => {
117
+ const h = await witnessFixture();
118
+ const args = {
119
+ identity: h.identity,
120
+ payloadJSON: canonicalConfigure(h.payload),
121
+ };
122
+ const first = await h.t.mutation(retain, args);
123
+ const changed = structuredClone(h.payload);
124
+ Object.assign(changed.reads.subscription, { cancel_at_period_end: true });
125
+ const payloadJSON = canonicalConfigure(changed);
126
+ const hash = await crypto.subtle.digest(
127
+ "SHA-256",
128
+ new TextEncoder().encode("renewal-witness:v1\u0000" + payloadJSON),
129
+ );
130
+ const hex = [...new Uint8Array(hash)]
131
+ .map((n) => n.toString(16).padStart(2, "0"))
132
+ .join("");
133
+ const payloadBinding = "renewal-witness:v1:sha256:" + hex;
134
+ await h.t.run((ctx) =>
135
+ ctx.db.patch(
136
+ "renewalObservationWitnesses",
137
+ first.descriptor.witnessRowId,
138
+ { payloadJSON, payloadBinding },
139
+ ),
140
+ );
141
+ await expect(h.t.query(read, { identity: h.identity })).rejects.toThrow(
142
+ "RENEWAL_WITNESS_INVALID",
143
+ );
144
+ await expect(h.t.mutation(retain, args)).rejects.toThrow(
145
+ "RENEWAL_WITNESS_INVALID",
146
+ );
147
+ const row = await h.t.run((ctx) =>
148
+ ctx.db.get("renewalObservationWitnesses", first.descriptor.witnessRowId),
149
+ );
150
+ expect(row?.payloadJSON).toBe(payloadJSON);
151
+ expect(row?.payloadBinding).toBe(payloadBinding);
152
+ expect(h.fetches()).toBe(0);
153
+ });
154
+ });
@@ -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,