@fantastic.dev/better-stripe 0.107.0 → 0.108.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 (40) hide show
  1. package/CHANGELOG.md +6 -0
  2. package/README.md +1 -1
  3. package/dist/client/billing/renewalAttach/internal/observation/reader.d.ts +64 -0
  4. package/dist/client/billing/renewalAttach/internal/observation/reader.d.ts.map +1 -0
  5. package/dist/client/billing/renewalAttach/internal/observation/reader.js +170 -0
  6. package/dist/client/billing/renewalAttach/internal/observation/reader.js.map +1 -0
  7. package/dist/client/billing/renewalAttach/internal/observation/readerAuthorization.d.ts +44 -0
  8. package/dist/client/billing/renewalAttach/internal/observation/readerAuthorization.d.ts.map +1 -0
  9. package/dist/client/billing/renewalAttach/internal/observation/readerAuthorization.js +145 -0
  10. package/dist/client/billing/renewalAttach/internal/observation/readerAuthorization.js.map +1 -0
  11. package/dist/client/billing/renewalAttach/internal/operations/sourceOperations.d.ts +2 -0
  12. package/dist/client/billing/renewalAttach/internal/operations/sourceOperations.d.ts.map +1 -1
  13. package/dist/client/billing/renewalAttach/internal/operations/sourceOperations.js +1 -0
  14. package/dist/client/billing/renewalAttach/internal/operations/sourceOperations.js.map +1 -1
  15. package/dist/client/billing/renewalAttach/internal/producer/classOwnedActionRoot.d.ts +2 -0
  16. package/dist/client/billing/renewalAttach/internal/producer/classOwnedActionRoot.d.ts.map +1 -1
  17. package/dist/client/billing/renewalAttach/internal/producer/classOwnedActionRoot.js +9 -0
  18. package/dist/client/billing/renewalAttach/internal/producer/classOwnedActionRoot.js.map +1 -1
  19. package/dist/client/connect/payoutExecutionTestHelpers.d.ts +16 -16
  20. package/dist/client/connect/payoutSyncTestHelpers.d.ts +16 -16
  21. package/dist/component/balanceFunding/internal/actions.d.ts +11 -11
  22. package/dist/component/balanceFunding/mutations.d.ts +27 -27
  23. package/dist/component/balanceFunding/stateHandlers.d.ts +8 -8
  24. package/dist/component/earnings/triggers.d.ts +16 -16
  25. package/dist/component/financialObservations/settlementHelpers.d.ts +3 -3
  26. package/dist/component/payoutRelease/queries.d.ts +2 -2
  27. package/dist/component/payoutRelease/queries.d.ts.map +1 -1
  28. package/dist/component/processingCostReconciliation/rollback.d.ts +1 -1
  29. package/dist/component/usage/allowance.fixtures.d.ts +16 -16
  30. package/docs/renewal-context-reads.md +52 -0
  31. package/package.json +1 -1
  32. package/src/client/billing/renewalAttach/internal/observation/reader.integration.test.ts +93 -0
  33. package/src/client/billing/renewalAttach/internal/observation/reader.ts +241 -0
  34. package/src/client/billing/renewalAttach/internal/observation/readerAuthorization.ts +179 -0
  35. package/src/client/billing/renewalAttach/internal/observation/readerControls.integration.test.ts +553 -0
  36. package/src/client/billing/renewalAttach/internal/operations/sourceOperations.ts +3 -0
  37. package/src/client/billing/renewalAttach/internal/producer/classOwnedActionRoot.ts +12 -0
  38. package/src/client/billing/renewalAttach/internal/test-fixtures/observationReader.ts +100 -0
  39. package/src/client/billing/renewalAttach/internal/test-fixtures/producerConfigureAdmission.ts +9 -0
  40. package/src/client/billing/renewalAttach/internal/test-fixtures/producerInitialOperation.ts +5 -1
@@ -0,0 +1,241 @@
1
+ import { types } from "node:util";
2
+ import {
3
+ getFunctionAddress,
4
+ type GenericActionCtx,
5
+ type GenericDataModel,
6
+ } from "convex/server";
7
+ import { COMPILED_OBSERVATION_HISTORY_ENTRIES } from "../operations/sourceOperations.js";
8
+ import {
9
+ readMaintainedRootComponent,
10
+ captureMaintainedJournalBinding,
11
+ readCheckedJournalActionRPC,
12
+ } from "../producer/classOwnedActionRoot.js";
13
+ import { closed, freeze } from "../c10/ownData.js";
14
+ import {
15
+ object,
16
+ matchConfigureDATA,
17
+ } from "../producer/configureJournalData.js";
18
+ import { captureRetainedObservationHistory } from "./history.js";
19
+ import {
20
+ readerNeed as need,
21
+ readerText as text,
22
+ readerStop,
23
+ captureReaderAuthorization,
24
+ createObservationReaderLifetime,
25
+ captureReaderQueryDATA,
26
+ } from "./readerAuthorization.js";
27
+
28
+ /** Fresh host authorization for four fixed DATA queries. No client or write authority. */
29
+ export async function captureAuthorizedObservationHistoryReader(
30
+ actualRoot: object,
31
+ raw: unknown,
32
+ ) {
33
+ need(arguments.length === 2);
34
+ if (COMPILED_OBSERVATION_HISTORY_ENTRIES.length === 0) readerStop();
35
+ const component = readMaintainedRootComponent(actualRoot);
36
+ const matches = COMPILED_OBSERVATION_HISTORY_ENTRIES.filter(
37
+ (e) => e.component === component,
38
+ );
39
+ need(matches.length === 1);
40
+ const entry = matches[0];
41
+ closed(entry, ["component", "componentScope", "authorizationQuery"]);
42
+ need(Object.isFrozen(entry));
43
+ need(!types.isProxy(raw));
44
+ const input = closed(raw, [
45
+ "actualActionCtx",
46
+ "operationId",
47
+ "parentOperationId",
48
+ ]);
49
+ const args = freeze({
50
+ componentScope: text(entry.componentScope),
51
+ operationId: text(input.operationId),
52
+ parentOperationId: text(input.parentOperationId),
53
+ });
54
+ need(args.operationId !== args.parentOperationId);
55
+ need(
56
+ input.actualActionCtx &&
57
+ typeof input.actualActionCtx === "object" &&
58
+ !types.isProxy(input.actualActionCtx),
59
+ );
60
+ const ctx = input.actualActionCtx as GenericActionCtx<GenericDataModel>;
61
+ const auth = ctx.auth,
62
+ getIdentity = auth?.getUserIdentity;
63
+ need(
64
+ auth &&
65
+ !types.isProxy(auth) &&
66
+ typeof getIdentity === "function" &&
67
+ !types.isProxy(getIdentity),
68
+ );
69
+ const captured = {
70
+ query: ctx.runQuery,
71
+ mutation: ctx.runMutation,
72
+ meta: ctx.meta,
73
+ metadata: ctx.meta?.getFunctionMetadata,
74
+ };
75
+ const q = component.renewalOperations.queries;
76
+ const references = () => {
77
+ const current = component.renewalOperations.queries;
78
+ return [
79
+ current.loadAuthorizedOperation,
80
+ current.readAttempt,
81
+ current.readStageEvent,
82
+ current.readProviderAcknowledgement,
83
+ ];
84
+ };
85
+ const refs = {
86
+ load: q.loadAuthorizedOperation,
87
+ attempt: q.readAttempt,
88
+ event: q.readStageEvent,
89
+ acknowledgement: q.readProviderAcknowledgement,
90
+ };
91
+ const addresses = references().map((ref) =>
92
+ JSON.stringify(getFunctionAddress(ref)),
93
+ );
94
+ const authAddress = JSON.stringify(
95
+ getFunctionAddress(entry.authorizationQuery),
96
+ );
97
+ const lifetime = createObservationReaderLifetime();
98
+ let binding: object | null = null;
99
+ let authorizedUntil: number | null = null;
100
+ function guard() {
101
+ if (authorizedUntil !== null)
102
+ need(lifetime.check().wallMs < authorizedUntil);
103
+ need(readMaintainedRootComponent(actualRoot) === component);
104
+ need(
105
+ COMPILED_OBSERVATION_HISTORY_ENTRIES.filter(
106
+ (e) => e.component === component,
107
+ ).length === 1 && COMPILED_OBSERVATION_HISTORY_ENTRIES.includes(entry),
108
+ );
109
+ need(
110
+ ctx.auth === auth &&
111
+ auth.getUserIdentity === getIdentity &&
112
+ ctx.runQuery === captured.query &&
113
+ ctx.runMutation === captured.mutation &&
114
+ ctx.meta === captured.meta &&
115
+ ctx.meta.getFunctionMetadata === captured.metadata,
116
+ );
117
+ need(
118
+ JSON.stringify(getFunctionAddress(entry.authorizationQuery)) ===
119
+ authAddress,
120
+ );
121
+ references().forEach((ref, index) =>
122
+ need(JSON.stringify(getFunctionAddress(ref)) === addresses[index]),
123
+ );
124
+ if (binding) {
125
+ const rpc = readCheckedJournalActionRPC(binding);
126
+ need(
127
+ rpc.receiver === ctx &&
128
+ rpc.component === component &&
129
+ rpc.operationId === args.operationId &&
130
+ rpc.runQuery === captured.query &&
131
+ rpc.runMutation === captured.mutation,
132
+ );
133
+ }
134
+ }
135
+ const owned = <T>(work: () => T | PromiseLike<T>) =>
136
+ lifetime.owned(work, guard);
137
+ try {
138
+ binding = await owned(() =>
139
+ captureMaintainedJournalBinding(actualRoot, {
140
+ actualActionCtx: ctx,
141
+ operationId: args.operationId,
142
+ }),
143
+ );
144
+ guard();
145
+ } catch (error) {
146
+ lifetime.close();
147
+ throw error;
148
+ }
149
+ async function authorize() {
150
+ const who = await owned(() => getIdentity.call(auth));
151
+ need(who && !types.isProxy(who));
152
+ const token = Object.getOwnPropertyDescriptor(who, "tokenIdentifier");
153
+ need(token && token.enumerable && "value" in token);
154
+ const tokenIdentifier = text(token.value, 2048);
155
+ const reply: unknown = await owned(() =>
156
+ captured.query.call(ctx, entry.authorizationQuery, args),
157
+ );
158
+ return captureReaderAuthorization(
159
+ reply,
160
+ args,
161
+ tokenIdentifier,
162
+ lifetime.check().wallMs,
163
+ );
164
+ }
165
+ async function stage(operationId: string) {
166
+ const operation: unknown = captureReaderQueryDATA(
167
+ await owned(() => captured.query.call(ctx, refs.load, { operationId })),
168
+ );
169
+ const load = object(operation),
170
+ active = object(load.activeAttempt);
171
+ const attemptId = text(active.attemptId);
172
+ const attempt: unknown = captureReaderQueryDATA(
173
+ await owned(() =>
174
+ captured.query.call(ctx, refs.attempt, { operationId, attemptId }),
175
+ ),
176
+ );
177
+ const manifest = closed(attempt, ["reservation", "events"]);
178
+ need(Array.isArray(manifest.events) && manifest.events.length <= 3);
179
+ const count = manifest.events.length;
180
+ const events = [];
181
+ for (let index = 0; index < count; index++) {
182
+ const sequence: 1 | 2 | 3 = index === 0 ? 1 : index === 1 ? 2 : 3;
183
+ events.push(
184
+ captureReaderQueryDATA(
185
+ await owned(() =>
186
+ captured.query.call(ctx, refs.event, {
187
+ operationId,
188
+ attemptId,
189
+ sequence,
190
+ }),
191
+ ),
192
+ ),
193
+ );
194
+ }
195
+ const acknowledgement: unknown = captureReaderQueryDATA(
196
+ await owned(() =>
197
+ captured.query.call(ctx, refs.acknowledgement, { operationId }),
198
+ ),
199
+ );
200
+ return { operation, attempt, events, acknowledgement };
201
+ }
202
+ let used = false;
203
+ return Object.freeze({
204
+ async read() {
205
+ need(arguments.length === 0 && !used);
206
+ used = true;
207
+ try {
208
+ lifetime.check();
209
+ guard();
210
+ const authorization = await authorize();
211
+ authorizedUntil = authorization.expiresAtMs;
212
+ const parent = await stage(args.parentOperationId),
213
+ configure = await stage(args.operationId);
214
+ const history = await owned(() =>
215
+ captureRetainedObservationHistory({ parent, configure }),
216
+ );
217
+ const receipt = history.attachmentReceipt;
218
+ matchConfigureDATA(authorization.providerScope, {
219
+ mode: "platform",
220
+ stripeAccount: null,
221
+ livemode: receipt.livemode,
222
+ customerAccountId: receipt.customerAccountId,
223
+ subscriptionId: receipt.subscriptionId,
224
+ scheduleId: receipt.scheduleId,
225
+ });
226
+ const final = await authorize();
227
+ matchConfigureDATA(final, authorization);
228
+ need(lifetime.check().wallMs < authorization.expiresAtMs);
229
+ guard();
230
+ return freeze({
231
+ status: "authorized_observation_history_data" as const,
232
+ history,
233
+ authorization,
234
+ operationalAuthority: false as const,
235
+ });
236
+ } finally {
237
+ lifetime.close();
238
+ }
239
+ },
240
+ });
241
+ }
@@ -0,0 +1,179 @@
1
+ import { closed, freeze } from "../c10/ownData.js";
2
+ import { rejectProxyJSON } from "../acquisition/rawWireSource.js";
3
+ import { renewalSnapshot } from "../../../renewalReplacementSnapshot.js";
4
+ import { matchConfigureDATA } from "../producer/configureJournalData.js";
5
+ import type { FunctionReference } from "convex/server";
6
+ import type { Component } from "../../../../helpers.js";
7
+ export const readerStop = (): never => {
8
+ throw Error("OBSERVATION_HISTORY_READER_UNBOUND");
9
+ };
10
+ export function readerNeed(value: unknown): asserts value {
11
+ if (!value) readerStop();
12
+ }
13
+ export function readerText(value: unknown, max = 255): string {
14
+ readerNeed(
15
+ typeof value === "string" && value.length > 0 && value.length <= max,
16
+ );
17
+ return value;
18
+ }
19
+ export type AuthorizationArgs = {
20
+ componentScope: string;
21
+ parentOperationId: string;
22
+ operationId: string;
23
+ };
24
+ export type ObservationHistorySourceEntry = Readonly<{
25
+ component: Component;
26
+ componentScope: string;
27
+ authorizationQuery: FunctionReference<
28
+ "query",
29
+ "public" | "internal",
30
+ AuthorizationArgs,
31
+ unknown
32
+ >;
33
+ }>;
34
+ /** Detached bounded own DATA before another query or await can observe it. */
35
+ export function captureReaderQueryDATA<T>(raw: T): T {
36
+ rejectProxyJSON(raw);
37
+ const copy = renewalSnapshot(raw);
38
+ readerNeed(new TextEncoder().encode(JSON.stringify(copy)).length <= 500000);
39
+ matchConfigureDATA(raw, copy);
40
+ return freeze(copy);
41
+ }
42
+ export function captureReaderAuthorization(
43
+ raw: unknown,
44
+ args: AuthorizationArgs,
45
+ tokenIdentifier: string,
46
+ now: number,
47
+ ) {
48
+ rejectProxyJSON(raw);
49
+ const copy = renewalSnapshot(raw);
50
+ readerNeed(new TextEncoder().encode(JSON.stringify(copy)).length <= 8192);
51
+ matchConfigureDATA(raw, copy);
52
+ const x = closed(copy, [
53
+ "tokenIdentifier",
54
+ "componentScope",
55
+ "parentOperationId",
56
+ "operationId",
57
+ "providerScope",
58
+ "authorizationId",
59
+ "authorizationRevision",
60
+ "expiresAtMs",
61
+ ]);
62
+ const p = closed(x.providerScope, [
63
+ "mode",
64
+ "stripeAccount",
65
+ "livemode",
66
+ "customerAccountId",
67
+ "subscriptionId",
68
+ "scheduleId",
69
+ ]);
70
+ readerNeed(
71
+ x.tokenIdentifier === tokenIdentifier &&
72
+ x.componentScope === args.componentScope &&
73
+ x.parentOperationId === args.parentOperationId &&
74
+ x.operationId === args.operationId,
75
+ );
76
+ readerNeed(
77
+ p.mode === "platform" &&
78
+ p.stripeAccount === null &&
79
+ typeof p.livemode === "boolean",
80
+ );
81
+ readerNeed(
82
+ typeof x.authorizationRevision === "number" &&
83
+ Number.isSafeInteger(x.authorizationRevision) &&
84
+ x.authorizationRevision > 0,
85
+ );
86
+ readerNeed(
87
+ typeof x.expiresAtMs === "number" &&
88
+ Number.isSafeInteger(x.expiresAtMs) &&
89
+ x.expiresAtMs > now,
90
+ );
91
+ return freeze({
92
+ ...args,
93
+ tokenIdentifier: readerText(tokenIdentifier, 2048),
94
+ providerScope: {
95
+ mode: "platform" as const,
96
+ stripeAccount: null,
97
+ livemode: p.livemode,
98
+ customerAccountId: readerText(p.customerAccountId),
99
+ subscriptionId: readerText(p.subscriptionId),
100
+ scheduleId: readerText(p.scheduleId),
101
+ },
102
+ authorizationId: readerText(x.authorizationId),
103
+ authorizationRevision: x.authorizationRevision,
104
+ expiresAtMs: x.expiresAtMs,
105
+ });
106
+ }
107
+
108
+ /** Fresh query-only budget, including capture and idle time. Never an old write Owner. */
109
+ export function createObservationReaderLifetime() {
110
+ let state: "running" | "closed" | "expired" = "running";
111
+ const initial = { wallMs: Date.now(), ns: process.hrtime.bigint() };
112
+ let last = initial;
113
+ const valid = (s: typeof initial) =>
114
+ Number.isSafeInteger(s.wallMs) &&
115
+ s.wallMs >= 0 &&
116
+ s.ns >= 0n &&
117
+ s.ns <= 18446744073709551615n;
118
+ readerNeed(valid(initial));
119
+ let rejectExpiry!: (error: Error) => void;
120
+ const expiry = new Promise<never>((_resolve, reject) => {
121
+ rejectExpiry = reject;
122
+ });
123
+ void expiry.catch(() => {});
124
+ function expire(): never {
125
+ state = "expired";
126
+ clearTimeout(timer);
127
+ const error = Error("OBSERVATION_HISTORY_READER_EXPIRED");
128
+ rejectExpiry(error);
129
+ throw error;
130
+ }
131
+ const timer = setTimeout(() => {
132
+ if (state === "running") {
133
+ state = "expired";
134
+ rejectExpiry(Error("OBSERVATION_HISTORY_READER_EXPIRED"));
135
+ }
136
+ }, 30000);
137
+ timer.unref?.();
138
+ function check() {
139
+ if (state === "expired") throw Error("OBSERVATION_HISTORY_READER_EXPIRED");
140
+ readerNeed(state === "running");
141
+ const sample = { wallMs: Date.now(), ns: process.hrtime.bigint() };
142
+ if (
143
+ !valid(sample) ||
144
+ sample.wallMs < last.wallMs ||
145
+ sample.ns < last.ns ||
146
+ sample.wallMs - initial.wallMs >= 30000 ||
147
+ sample.ns - initial.ns >= 30000000000n
148
+ )
149
+ expire();
150
+ last = sample;
151
+ return sample;
152
+ }
153
+ function close() {
154
+ if (state === "running") state = "closed";
155
+ clearTimeout(timer);
156
+ }
157
+ async function owned<T>(
158
+ work: () => T | PromiseLike<T>,
159
+ guard: () => void,
160
+ ): Promise<T> {
161
+ check();
162
+ guard();
163
+ try {
164
+ const pending = Promise.resolve().then(() => {
165
+ check();
166
+ guard();
167
+ return work();
168
+ });
169
+ const result = await Promise.race([pending, expiry]);
170
+ check();
171
+ guard();
172
+ return result;
173
+ } catch (error) {
174
+ close();
175
+ throw error;
176
+ }
177
+ }
178
+ return Object.freeze({ check, close, owned });
179
+ }