@fantastic.dev/better-stripe 0.111.0 → 0.113.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 (87) 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 +32 -32
  40. package/dist/client/connect/payoutExecutionTestHelpers.d.ts +16 -16
  41. package/dist/component/_generated/api.d.ts +24 -0
  42. package/dist/component/_generated/api.d.ts.map +1 -1
  43. package/dist/component/_generated/api.js.map +1 -1
  44. package/dist/component/_generated/component.d.ts +94 -10
  45. package/dist/component/_generated/component.d.ts.map +1 -1
  46. package/dist/component/balanceFunding/preparationHandlers.d.ts +8 -8
  47. package/dist/component/balanceFunding/queries.d.ts +1 -1
  48. package/dist/component/financialObservations/settlementHelpers.d.ts +3 -3
  49. package/dist/component/renewalWitnesses/mutations.d.ts +45 -0
  50. package/dist/component/renewalWitnesses/mutations.d.ts.map +1 -0
  51. package/dist/component/renewalWitnesses/mutations.js +14 -0
  52. package/dist/component/renewalWitnesses/mutations.js.map +1 -0
  53. package/dist/component/renewalWitnesses/queries.d.ts +39 -0
  54. package/dist/component/renewalWitnesses/queries.d.ts.map +1 -0
  55. package/dist/component/renewalWitnesses/queries.js +11 -0
  56. package/dist/component/renewalWitnesses/queries.js.map +1 -0
  57. package/dist/component/usage/allowance.fixtures.d.ts +16 -16
  58. package/docs/renewal-example-authorization.md +74 -0
  59. package/docs/renewal-witness-protocol.md +61 -10
  60. package/package.json +1 -1
  61. package/src/client/billing/renewalAttach/internal/observation/freshActor.ts +142 -19
  62. package/src/client/billing/renewalAttach/internal/observation/freshTransport.ts +90 -1
  63. package/src/client/billing/renewalAttach/internal/observation/invocation.ts +2 -0
  64. package/src/client/billing/renewalAttach/internal/observation/readerAuthorization.ts +6 -1
  65. package/src/client/billing/renewalAttach/internal/observation/witnessAcquisition.integration.test.ts +348 -0
  66. package/src/client/billing/renewalAttach/internal/observation/witnessActor.integration.test.ts +204 -0
  67. package/src/client/billing/renewalAttach/internal/observation/witnessAuthorization.ts +239 -0
  68. package/src/client/billing/renewalAttach/internal/observation/witnessCapabilities.integration.test.ts +231 -0
  69. package/src/client/billing/renewalAttach/internal/observation/witnessData.ts +189 -0
  70. package/src/client/billing/renewalAttach/internal/observation/witnessHistorical.integration.test.ts +98 -0
  71. package/src/client/billing/renewalAttach/internal/observation/witnessImmutable.integration.test.ts +78 -0
  72. package/src/client/billing/renewalAttach/internal/observation/witnessInvoice.integration.test.ts +85 -0
  73. package/src/client/billing/renewalAttach/internal/observation/witnessLifecycle.integration.test.ts +264 -0
  74. package/src/client/billing/renewalAttach/internal/observation/witnessOperation.ts +205 -0
  75. package/src/client/billing/renewalAttach/internal/observation/witnessProfile.integration.test.ts +93 -0
  76. package/src/client/billing/renewalAttach/internal/observation/witnessRPCControls.integration.test.ts +256 -0
  77. package/src/client/billing/renewalAttach/internal/operations/witnessProfiles.ts +58 -0
  78. package/src/client/billing/renewalAttach/internal/test-fixtures/invoiceObservation.ts +3 -1
  79. package/src/client/billing/renewalAttach/internal/test-fixtures/producerConfigureAdmission.ts +8 -0
  80. package/src/client/billing/renewalAttach/internal/test-fixtures/producerInitialOperation.ts +28 -11
  81. package/src/client/billing/renewalAttach/internal/test-fixtures/witnessHistory.ts +70 -0
  82. package/src/client/billing/renewalAttach/internal/test-fixtures/witnessObservation.ts +353 -0
  83. package/src/component/_generated/api.ts +24 -0
  84. package/src/component/_generated/component.ts +98 -10
  85. package/src/component/renewalWitnesses/mutations.ts +17 -0
  86. package/src/component/renewalWitnesses/queries.ts +11 -0
  87. package/src/component/renewalWitnesses/routes.test.ts +154 -0
@@ -0,0 +1,239 @@
1
+ import { types } from "node:util";
2
+ import { getFunctionAddress } from "convex/server";
3
+ import {
4
+ COMPILED_WITNESS_CAPTURE_ENTRIES,
5
+ COMPILED_WITNESS_READ_ENTRIES,
6
+ type WitnessCaptureProfile,
7
+ type WitnessReadProfile,
8
+ type WitnessScope,
9
+ } from "../operations/witnessProfiles.js";
10
+ import {
11
+ COMPILED_FRESH_OBSERVATION_ENTRIES,
12
+ COMPILED_OBSERVATION_HISTORY_ENTRIES,
13
+ } from "../operations/sourceOperations.js";
14
+ import {
15
+ readMaintainedRootComponent,
16
+ readCheckedJournalActionRPC,
17
+ } from "../producer/classOwnedActionRoot.js";
18
+ import { invoiceProfileGuard } from "./invoiceAuthorization.js";
19
+ import { closed, freeze } from "../c10/ownData.js";
20
+ import { matchConfigureDATA } from "../producer/configureJournalData.js";
21
+ import {
22
+ captureReaderQueryDATA,
23
+ readerText as text,
24
+ } from "./readerAuthorization.js";
25
+ import type { ObservationInvocationState } from "./invocation.js";
26
+ import {
27
+ witnessIdentity,
28
+ witnessNeed as need,
29
+ type WitnessIdentity,
30
+ } from "../../../../../shared/renewalWitness.js";
31
+
32
+ export type WitnessMode = "retain" | "read";
33
+ export type WitnessProfile = WitnessCaptureProfile | WitnessReadProfile;
34
+ const nativeThen = Promise.prototype.then;
35
+ export const witnessAddress = (ref: Parameters<typeof getFunctionAddress>[0]) =>
36
+ JSON.stringify(getFunctionAddress(ref));
37
+ export function witnessProfileGuard(
38
+ profile: WitnessProfile,
39
+ mode: WitnessMode,
40
+ ) {
41
+ const entries: readonly WitnessProfile[] =
42
+ mode === "retain"
43
+ ? COMPILED_WITNESS_CAPTURE_ENTRIES
44
+ : COMPILED_WITNESS_READ_ENTRIES;
45
+ need(!types.isProxy(profile));
46
+ closed(profile, ["freshProfile", "invoiceProfile", "authorizationQuery"]);
47
+ need(Object.isFrozen(profile) && entries.includes(profile));
48
+ const fresh = profile.freshProfile;
49
+ need(
50
+ COMPILED_FRESH_OBSERVATION_ENTRIES.includes(fresh) &&
51
+ COMPILED_OBSERVATION_HISTORY_ENTRIES.includes(fresh.historyEntry),
52
+ );
53
+ need(
54
+ entries.filter(
55
+ (entry) =>
56
+ entry.freshProfile.historyEntry.component ===
57
+ fresh.historyEntry.component,
58
+ ).length === 1,
59
+ );
60
+ if (profile.invoiceProfile !== null) {
61
+ invoiceProfileGuard(profile.invoiceProfile);
62
+ need(profile.invoiceProfile.freshProfile === fresh);
63
+ }
64
+ }
65
+ /** The EMPTY check precedes root/input reflection, clocks and SDK selection. */
66
+ export function captureWitnessProfile(
67
+ root: object,
68
+ mode: WitnessMode,
69
+ ): WitnessProfile {
70
+ const entries: readonly WitnessProfile[] =
71
+ mode === "retain"
72
+ ? COMPILED_WITNESS_CAPTURE_ENTRIES
73
+ : COMPILED_WITNESS_READ_ENTRIES;
74
+ if (entries.length === 0) throw Error("RENEWAL_WITNESS_UNBOUND");
75
+ const component = readMaintainedRootComponent(root);
76
+ const matches = entries.filter((profile) => {
77
+ need(!types.isProxy(profile));
78
+ closed(profile, ["freshProfile", "invoiceProfile", "authorizationQuery"]);
79
+ return profile.freshProfile.historyEntry.component === component;
80
+ });
81
+ need(matches.length === 1);
82
+ witnessProfileGuard(matches[0], mode);
83
+ return matches[0];
84
+ }
85
+ /** Brand and settle the original RPC Promise without adopting a public .then substitute. */
86
+ export function witnessRPC<T>(
87
+ state: ObservationInvocationState,
88
+ work: () => Promise<T>,
89
+ guard: () => void,
90
+ ): Promise<T> {
91
+ return state.owned(() => {
92
+ const pending = work();
93
+ need(types.isPromise(pending));
94
+ return new Promise<T>((resolve, reject) => {
95
+ Reflect.apply(nativeThen, pending, [resolve, reject]);
96
+ });
97
+ }, guard);
98
+ }
99
+ function checkedScope(raw: unknown): WitnessScope {
100
+ const scope = closed(raw, [
101
+ "identity",
102
+ "providerScope",
103
+ "configureRequestBinding",
104
+ "observedItemId",
105
+ "nativePeriod",
106
+ ]);
107
+ const provider = closed(scope.providerScope, [
108
+ "mode",
109
+ "stripeAccount",
110
+ "livemode",
111
+ "customerAccountId",
112
+ "customerId",
113
+ "subscriptionId",
114
+ "scheduleId",
115
+ ]);
116
+ need(
117
+ provider.mode === "platform" &&
118
+ provider.stripeAccount === null &&
119
+ typeof provider.livemode === "boolean",
120
+ );
121
+ const period = closed(scope.nativePeriod, ["start", "end"]);
122
+ need(
123
+ typeof period.start === "number" &&
124
+ Number.isSafeInteger(period.start) &&
125
+ period.start >= 0 &&
126
+ typeof period.end === "number" &&
127
+ Number.isSafeInteger(period.end) &&
128
+ period.end > period.start,
129
+ );
130
+ return freeze({
131
+ identity: witnessIdentity(scope.identity),
132
+ providerScope: {
133
+ mode: "platform",
134
+ stripeAccount: null,
135
+ livemode: provider.livemode,
136
+ customerAccountId: text(provider.customerAccountId),
137
+ customerId: text(provider.customerId),
138
+ subscriptionId: text(provider.subscriptionId),
139
+ scheduleId: text(provider.scheduleId),
140
+ },
141
+ configureRequestBinding: text(scope.configureRequestBinding),
142
+ observedItemId: text(scope.observedItemId),
143
+ nativePeriod: { start: period.start, end: period.end },
144
+ });
145
+ }
146
+ export function createWitnessAuthorization(
147
+ state: ObservationInvocationState,
148
+ profile: WitnessProfile,
149
+ mode: WitnessMode,
150
+ identity: WitnessIdentity,
151
+ expectedScope: WitnessScope | null,
152
+ ) {
153
+ const rpc = readCheckedJournalActionRPC(state.binding),
154
+ query = profile.authorizationQuery;
155
+ const address = witnessAddress(query),
156
+ base = state.readCaptured().authorization;
157
+ const args =
158
+ mode === "retain"
159
+ ? {
160
+ capability: "renewal_witness_retain_v1" as const,
161
+ scope: expectedScope!,
162
+ }
163
+ : { capability: "renewal_witness_read_v1" as const, identity };
164
+ need(mode !== "retain" || expectedScope);
165
+ let grant: Record<string, unknown> | null = null;
166
+ let expiry: number | null = null;
167
+ function guard() {
168
+ state.guard();
169
+ witnessProfileGuard(profile, mode);
170
+ need(
171
+ profile.authorizationQuery === query &&
172
+ witnessAddress(query) === address &&
173
+ profile.freshProfile.historyEntry === state.historyEntry &&
174
+ readCheckedJournalActionRPC(state.binding) === rpc,
175
+ );
176
+ if (expiry !== null) need(state.check().wallMs < expiry);
177
+ }
178
+ return Object.freeze({
179
+ guard,
180
+ async authorize() {
181
+ guard();
182
+ await state.authorizeUnchanged();
183
+ guard();
184
+ const raw: unknown = await witnessRPC(
185
+ state,
186
+ () => rpc.runQuery.call(rpc.receiver, query, args),
187
+ guard,
188
+ );
189
+ const reply = captureReaderQueryDATA(raw);
190
+ need(new TextEncoder().encode(JSON.stringify(reply)).length <= 8192);
191
+ const data = closed(reply, [
192
+ "capability",
193
+ "scope",
194
+ "tokenIdentifier",
195
+ "authorizationId",
196
+ "authorizationRevision",
197
+ "expiresAtMs",
198
+ ...(mode === "read" ? ["witnessRowId", "payloadBinding"] : []),
199
+ ]);
200
+ const scope = checkedScope(data.scope);
201
+ need(
202
+ data.capability === args.capability &&
203
+ data.tokenIdentifier === base.tokenIdentifier,
204
+ );
205
+ matchConfigureDATA(scope.identity, identity);
206
+ if (expectedScope) matchConfigureDATA(scope, expectedScope);
207
+ text(data.authorizationId);
208
+ need(
209
+ typeof data.authorizationRevision === "number" &&
210
+ Number.isSafeInteger(data.authorizationRevision) &&
211
+ data.authorizationRevision > 0,
212
+ );
213
+ need(
214
+ typeof data.expiresAtMs === "number" &&
215
+ Number.isSafeInteger(data.expiresAtMs) &&
216
+ data.expiresAtMs > state.check().wallMs,
217
+ );
218
+ if (mode === "read") {
219
+ text(data.witnessRowId);
220
+ need(
221
+ /^renewal-witness:v1:sha256:[0-9a-f]{64}$/.test(
222
+ text(data.payloadBinding),
223
+ ),
224
+ );
225
+ }
226
+ if (grant) matchConfigureDATA(data, grant);
227
+ else {
228
+ grant = freeze(data);
229
+ expiry = data.expiresAtMs;
230
+ }
231
+ guard();
232
+ return freeze({
233
+ scope,
234
+ witnessRowId: mode === "read" ? text(data.witnessRowId) : null,
235
+ payloadBinding: mode === "read" ? text(data.payloadBinding) : null,
236
+ });
237
+ },
238
+ });
239
+ }
@@ -0,0 +1,231 @@
1
+ import {
2
+ witnessControls,
3
+ prepareWitnessObservation,
4
+ invokeWitnessCapture,
5
+ invokeWitnessRead,
6
+ readStoredWitness,
7
+ witnessFixtureOptions,
8
+ } from "../test-fixtures/witnessObservation.js";
9
+ import { configureAdmissionCase } from "../test-fixtures/producerConfigureAdmission.js";
10
+ import { expect } from "vitest";
11
+ import assert from "node:assert/strict";
12
+ function data(raw: unknown) {
13
+ assert(raw !== null && typeof raw === "object");
14
+ return raw;
15
+ }
16
+
17
+ configureAdmissionCase(
18
+ "a separately authorized later subject reads immutable capture without becoming its captured subject",
19
+ prepareWitnessObservation,
20
+ async (h, state) => {
21
+ await invokeWitnessCapture(h, state);
22
+ const original = await readStoredWitness(h, state);
23
+ assert(original);
24
+ const reader = {
25
+ subject: "historical-reader",
26
+ issuer: "https://host.test",
27
+ tokenIdentifier: "https://host.test|historical-reader",
28
+ };
29
+ witnessControls.allowedReaders.push(reader.tokenIdentifier);
30
+ const output = await invokeWitnessRead(h, state, { identity: reader });
31
+ assert("witness" in output && output.evidence);
32
+ expect(output.authorization.tokenIdentifier).toBe(reader.tokenIdentifier);
33
+ expect(output.witness.descriptor.capturedSubject).toBe(
34
+ witnessFixtureOptions.identity.tokenIdentifier,
35
+ );
36
+ expect(output.evidence.historicalMaterial.predicate).toBe(
37
+ "snapshot_target_material_match",
38
+ );
39
+ expect((await readStoredWitness(h, state))?.payloadJSON).toBe(
40
+ original.payloadJSON,
41
+ );
42
+ const before = h.calls.length;
43
+ await expect(
44
+ invokeWitnessRead(h, state, {
45
+ identity: {
46
+ ...reader,
47
+ subject: "unauthorized",
48
+ tokenIdentifier: "https://host.test|unauthorized",
49
+ },
50
+ }),
51
+ ).rejects.toThrow();
52
+ expect(h.calls).toHaveLength(before);
53
+ },
54
+ witnessFixtureOptions,
55
+ );
56
+
57
+ for (const path of [
58
+ ["identity", "componentScope"],
59
+ ["identity", "parentOperationId"],
60
+ ["identity", "operationId"],
61
+ ["identity", "witnessId"],
62
+ ["providerScope", "customerId"],
63
+ ["providerScope", "customerAccountId"],
64
+ ["providerScope", "subscriptionId"],
65
+ ["providerScope", "scheduleId"],
66
+ ["configureRequestBinding"],
67
+ ["observedItemId"],
68
+ ] as const) {
69
+ configureAdmissionCase(
70
+ "retention refuses a host grant with foreign " + path.join("."),
71
+ prepareWitnessObservation,
72
+ async (h, state) => {
73
+ witnessControls.onRetainGrant = (grant) => {
74
+ const scope = data(Reflect.get(grant, "scope"));
75
+ const target =
76
+ path.length === 1 ? scope : data(Reflect.get(scope, path[0]));
77
+ Reflect.set(target, path[path.length - 1], "controlled-foreign-value");
78
+ };
79
+ await expect(invokeWitnessCapture(h, state)).rejects.toThrow();
80
+ expect(witnessControls.retainQueries).toBe(1);
81
+ expect(await readStoredWitness(h, state)).toBeNull();
82
+ },
83
+ witnessFixtureOptions,
84
+ );
85
+ }
86
+ for (const change of [
87
+ "livemode",
88
+ "mode",
89
+ "account",
90
+ "period",
91
+ "subject",
92
+ "extra",
93
+ ] as const) {
94
+ configureAdmissionCase(
95
+ "retention refuses host grant control " + change,
96
+ prepareWitnessObservation,
97
+ async (h, state) => {
98
+ witnessControls.onRetainGrant = (grant) => {
99
+ const scope = data(Reflect.get(grant, "scope")),
100
+ provider = data(Reflect.get(scope, "providerScope"));
101
+ if (change === "livemode") Reflect.set(provider, "livemode", true);
102
+ if (change === "mode") Reflect.set(provider, "mode", "connected");
103
+ if (change === "account")
104
+ Reflect.set(provider, "stripeAccount", "acct_foreign");
105
+ if (change === "period")
106
+ Reflect.set(
107
+ data(Reflect.get(scope, "nativePeriod")),
108
+ "end",
109
+ state.scope.nativePeriod.end + 1,
110
+ );
111
+ if (change === "subject")
112
+ Reflect.set(grant, "tokenIdentifier", "https://host.test|foreign");
113
+ if (change === "extra") Reflect.set(grant, "extra", true);
114
+ };
115
+ await expect(invokeWitnessCapture(h, state)).rejects.toThrow();
116
+ expect(await readStoredWitness(h, state)).toBeNull();
117
+ },
118
+ witnessFixtureOptions,
119
+ );
120
+ }
121
+ configureAdmissionCase(
122
+ "base observation permission cannot substitute for independent retention or later read permission",
123
+ prepareWitnessObservation,
124
+ async (h, state) => {
125
+ witnessControls.denyRetain = true;
126
+ await expect(invokeWitnessCapture(h, state)).rejects.toThrow();
127
+ expect(await readStoredWitness(h, state)).toBeNull();
128
+ witnessControls.denyRetain = false;
129
+ await invokeWitnessCapture(h, state);
130
+ const stored = await readStoredWitness(h, state);
131
+ witnessControls.denyRead = true;
132
+ const before = h.calls.length;
133
+ await expect(invokeWitnessRead(h, state)).rejects.toThrow();
134
+ expect(h.calls).toHaveLength(before);
135
+ expect(await readStoredWitness(h, state)).toEqual(stored);
136
+ },
137
+ witnessFixtureOptions,
138
+ );
139
+
140
+ for (const path of [
141
+ ["identity", "componentScope"],
142
+ ["identity", "parentOperationId"],
143
+ ["identity", "operationId"],
144
+ ["identity", "witnessId"],
145
+ ["providerScope", "customerId"],
146
+ ["providerScope", "customerAccountId"],
147
+ ["providerScope", "subscriptionId"],
148
+ ["providerScope", "scheduleId"],
149
+ ["configureRequestBinding"],
150
+ ["observedItemId"],
151
+ ] as const)
152
+ configureAdmissionCase(
153
+ "later read refuses a grant with foreign " + path.join("."),
154
+ prepareWitnessObservation,
155
+ async (h, state) => {
156
+ await invokeWitnessCapture(h, state);
157
+ const stored = await readStoredWitness(h, state),
158
+ before = h.calls.length;
159
+ witnessControls.onReadGrant = (grant) => {
160
+ const scope = data(Reflect.get(grant, "scope"));
161
+ const target =
162
+ path.length === 1 ? scope : data(Reflect.get(scope, path[0]));
163
+ Reflect.set(target, path[path.length - 1], "controlled-foreign-value");
164
+ };
165
+ await expect(invokeWitnessRead(h, state)).rejects.toThrow();
166
+ expect(witnessControls.readQueries).toBe(1);
167
+ expect(h.calls).toHaveLength(before);
168
+ expect(await readStoredWitness(h, state)).toEqual(stored);
169
+ },
170
+ witnessFixtureOptions,
171
+ );
172
+
173
+ for (const field of [
174
+ "witnessRowId",
175
+ "payloadBinding",
176
+ "tokenIdentifier",
177
+ ] as const)
178
+ configureAdmissionCase(
179
+ "later read binds the exact granted " + field,
180
+ prepareWitnessObservation,
181
+ async (h, state) => {
182
+ await invokeWitnessCapture(h, state);
183
+ const stored = await readStoredWitness(h, state),
184
+ before = h.calls.length;
185
+ witnessControls.onReadGrant = (grant) =>
186
+ Reflect.set(
187
+ grant,
188
+ field,
189
+ field === "payloadBinding"
190
+ ? "renewal-witness:v1:sha256:" + "0".repeat(64)
191
+ : "controlled-foreign-value",
192
+ );
193
+ await expect(invokeWitnessRead(h, state)).rejects.toThrow();
194
+ expect(h.calls).toHaveLength(before);
195
+ expect(await readStoredWitness(h, state)).toEqual(stored);
196
+ },
197
+ witnessFixtureOptions,
198
+ );
199
+
200
+ for (const mode of [
201
+ "expired-before-retain",
202
+ "changed-retention-revision",
203
+ "changed-read-revision",
204
+ ] as const)
205
+ configureAdmissionCase(
206
+ "witness capability control " + mode,
207
+ prepareWitnessObservation,
208
+ async (h, state) => {
209
+ if (mode === "expired-before-retain") {
210
+ witnessControls.onRetainGrant = (grant) =>
211
+ Reflect.set(grant, "expiresAtMs", Date.now());
212
+ await expect(invokeWitnessCapture(h, state)).rejects.toThrow();
213
+ expect(await readStoredWitness(h, state)).toBeNull();
214
+ } else if (mode === "changed-retention-revision") {
215
+ witnessControls.onRetainGrant = (grant, count) => {
216
+ if (count === 2) Reflect.set(grant, "authorizationRevision", 2);
217
+ };
218
+ await expect(invokeWitnessCapture(h, state)).rejects.toThrow();
219
+ expect(await readStoredWitness(h, state)).not.toBeNull();
220
+ } else {
221
+ await invokeWitnessCapture(h, state);
222
+ const stored = await readStoredWitness(h, state);
223
+ witnessControls.onReadGrant = (grant, count) => {
224
+ if (count === 2) Reflect.set(grant, "authorizationRevision", 2);
225
+ };
226
+ await expect(invokeWitnessRead(h, state)).rejects.toThrow();
227
+ expect(await readStoredWitness(h, state)).toEqual(stored);
228
+ }
229
+ },
230
+ witnessFixtureOptions,
231
+ );
@@ -0,0 +1,189 @@
1
+ import {
2
+ canonicalWitnessJSON,
3
+ witnessNeed as need,
4
+ witnessObject as object,
5
+ witnessText as text,
6
+ type WitnessIdentity,
7
+ type WitnessPayload,
8
+ } from "../../../../../shared/renewalWitness.js";
9
+ import { renewalSnapshot } from "../../../renewalReplacementSnapshot.js";
10
+ import { inspectRenewalEvidenceV1 } from "../../../renewalObservation/evidence-v1.js";
11
+ import type { WitnessScope } from "../operations/witnessProfiles.js";
12
+ import { closed, freeze } from "../c10/ownData.js";
13
+ import { matchConfigureDATA } from "../producer/configureJournalData.js";
14
+ import type { ObservationInvocationState } from "./invocation.js";
15
+ import type { ObservationReads } from "./types.js";
16
+ import type { InvoiceContextV1 } from "../../../renewalObservation/evidence-v1-types.js";
17
+
18
+ function capturedStage(raw: unknown, parent: boolean) {
19
+ const stage = object(raw),
20
+ load = object(stage.operation);
21
+ const reservation = object(object(stage.attempt).reservation);
22
+ const { recordJSON: _recordJSON, ...summary } = reservation;
23
+ void _recordJSON;
24
+ const known = stage.acknowledgement;
25
+ return {
26
+ record: object(JSON.parse(text(load.recordJSON, 500000))),
27
+ reservation: summary,
28
+ acknowledgement:
29
+ known === null
30
+ ? null
31
+ : {
32
+ retention: object(object(known).retention),
33
+ receipt: object(
34
+ JSON.parse(text(object(known).receiptJSON, 500000)),
35
+ ),
36
+ },
37
+ ...(parent ? { initialBasis: object(load.initialBasis) } : {}),
38
+ };
39
+ }
40
+
41
+ /** Called only inside the actual fresh actor, before its original lifetime closes. */
42
+ export function captureWitnessPayload(
43
+ state: ObservationInvocationState,
44
+ identity: WitnessIdentity,
45
+ reads: ObservationReads,
46
+ invoiceContext: InvoiceContextV1 | null,
47
+ ) {
48
+ const captured = state.readCaptured(),
49
+ sample = state.check();
50
+ const snapshot = captured.history.snapshot;
51
+ const payload = renewalSnapshot({
52
+ version: 1,
53
+ kind: "renewal_witness_payload",
54
+ identity,
55
+ capturedSubject: captured.authorization.tokenIdentifier,
56
+ acquisition: {
57
+ observedAtMs: sample.wallMs,
58
+ elapsedWallMs: sample.wallMs - state.startedAt.wallMs,
59
+ elapsedNsDecimal: (sample.ns - state.startedAt.ns).toString(),
60
+ apiVersion: "2026-09-30.endive",
61
+ baseReadProfile: "endive-schedule-first-44-v1",
62
+ invoiceReadProfile:
63
+ invoiceContext === null ? null : "endive-pinned-invoices-fence-7-v1",
64
+ },
65
+ source: {
66
+ parent: capturedStage(snapshot.parent, true),
67
+ configure: capturedStage(snapshot.configure, false),
68
+ },
69
+ reads,
70
+ invoiceContext,
71
+ });
72
+ return canonicalWitnessJSON(JSON.stringify(payload)).json;
73
+ }
74
+
75
+ /** Recompute complete unsigned material and digest; a stored hash is not its own proof. */
76
+ export async function inspectWitnessPayload(raw: string) {
77
+ const canonical = canonicalWitnessJSON(raw),
78
+ payload = canonical.value;
79
+ const record = object(payload.source.configure.record.configureRecord);
80
+ const known = payload.source.configure.acknowledgement;
81
+ const configureReceipt =
82
+ known === null
83
+ ? null
84
+ : {
85
+ configuration: record.configuration,
86
+ actualDispatch: payload.source.configure.record.dispatch,
87
+ providerSnapshot: known.receipt.providerSnapshot,
88
+ transport: known.receipt.transport,
89
+ };
90
+ const evidence = await inspectRenewalEvidenceV1({
91
+ version: 1,
92
+ apiVersion: "2026-09-30.endive",
93
+ configuration: record.configuration,
94
+ configureReceipt,
95
+ reads: payload.reads,
96
+ invoiceContext: payload.invoiceContext,
97
+ historicalSnapshot: null,
98
+ });
99
+ need(
100
+ evidence.identity &&
101
+ evidence.currentMaterial.predicate === "current_target_material_match",
102
+ );
103
+ if (payload.invoiceContext !== null)
104
+ need(evidence.invoiceEvidence.predicate === "invoice_lines_correlated");
105
+ const { identity } = evidence,
106
+ material = evidence.currentMaterial;
107
+ const scope: WitnessScope = freeze({
108
+ identity: payload.identity,
109
+ providerScope: {
110
+ mode: "platform",
111
+ stripeAccount: null,
112
+ livemode: identity.livemode,
113
+ customerAccountId: identity.customerAccountId,
114
+ customerId: identity.customerId,
115
+ subscriptionId: identity.subscriptionId,
116
+ scheduleId: identity.scheduleId,
117
+ },
118
+ configureRequestBinding: text(
119
+ object(object(record.request).requestIdentity).binding,
120
+ ),
121
+ observedItemId: material.observedItemId,
122
+ nativePeriod: material.nativePeriod,
123
+ });
124
+ const digest = await crypto.subtle.digest(
125
+ "SHA-256",
126
+ new TextEncoder().encode("renewal-witness:v1\u0000" + canonical.json),
127
+ );
128
+ const hex = [...new Uint8Array(digest)]
129
+ .map((n) => n.toString(16).padStart(2, "0"))
130
+ .join("");
131
+ const payloadBinding = "renewal-witness:v1:sha256:" + hex;
132
+ const fields = freeze({
133
+ version: 1,
134
+ identity: payload.identity,
135
+ payloadBinding,
136
+ capturedSubject: payload.capturedSubject,
137
+ observedAtMs: payload.acquisition.observedAtMs,
138
+ customerAccountId: identity.customerAccountId,
139
+ customerId: identity.customerId,
140
+ livemode: identity.livemode,
141
+ subscriptionId: identity.subscriptionId,
142
+ scheduleId: identity.scheduleId,
143
+ observedItemId: material.observedItemId,
144
+ nativePeriod: material.nativePeriod,
145
+ operationalAuthority: false,
146
+ authenticationEstablished: false,
147
+ publicDeliveryEstablished: false,
148
+ providerQualificationRequired: true,
149
+ });
150
+ return {
151
+ identity: freeze(evidence.identity),
152
+ payload,
153
+ payloadJSON: canonical.json,
154
+ scope,
155
+ fields,
156
+ historicalInput: {
157
+ configuration: record.configuration,
158
+ configureReceipt,
159
+ historicalSnapshot: {
160
+ reads: payload.reads,
161
+ invoiceContext: payload.invoiceContext,
162
+ },
163
+ },
164
+ };
165
+ }
166
+ export type InspectedWitness = Awaited<
167
+ ReturnType<typeof inspectWitnessPayload>
168
+ >;
169
+ export function checkedWitnessDescriptor(
170
+ raw: unknown,
171
+ admitted: InspectedWitness,
172
+ ) {
173
+ const descriptor = closed(raw, [
174
+ ...Object.keys(admitted.fields),
175
+ "witnessRowId",
176
+ ]);
177
+ const witnessRowId = text(descriptor.witnessRowId);
178
+ matchConfigureDATA(descriptor, { ...admitted.fields, witnessRowId });
179
+ return freeze({ ...admitted.fields, witnessRowId });
180
+ }
181
+ export function checkWitnessC7(
182
+ payload: WitnessPayload,
183
+ state: ObservationInvocationState,
184
+ ) {
185
+ matchConfigureDATA(
186
+ payload.source.configure.record.configureRecord,
187
+ state.readCaptured().history.record,
188
+ );
189
+ }