@fantastic.dev/better-stripe 0.100.0 → 0.101.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 (80) hide show
  1. package/CHANGELOG.md +6 -0
  2. package/README.md +1 -1
  3. package/dist/client/connect/payoutAdoptionTestHelpers.d.ts +18 -18
  4. package/dist/client/connect/payoutExecutionTestHelpers.d.ts +9 -9
  5. package/dist/client/connect/payoutLargeAdoptionTestHelpers.d.ts +18 -18
  6. package/dist/client/connect/payoutSyncTestHelpers.d.ts +9 -9
  7. package/dist/component/balanceFunding/mutations.d.ts +43 -43
  8. package/dist/component/earnings/triggers.d.ts +6 -6
  9. package/dist/component/renewalOperations/attachValidation.d.ts +19 -0
  10. package/dist/component/renewalOperations/attachValidation.d.ts.map +1 -0
  11. package/dist/component/renewalOperations/attachValidation.js +167 -0
  12. package/dist/component/renewalOperations/attachValidation.js.map +1 -0
  13. package/dist/component/renewalOperations/configureAcknowledgement.d.ts +13 -0
  14. package/dist/component/renewalOperations/configureAcknowledgement.d.ts.map +1 -0
  15. package/dist/component/renewalOperations/configureAcknowledgement.js +108 -0
  16. package/dist/component/renewalOperations/configureAcknowledgement.js.map +1 -0
  17. package/dist/component/renewalOperations/configureParent.d.ts +10 -0
  18. package/dist/component/renewalOperations/configureParent.d.ts.map +1 -0
  19. package/dist/component/renewalOperations/configureParent.js +62 -0
  20. package/dist/component/renewalOperations/configureParent.js.map +1 -0
  21. package/dist/component/renewalOperations/configureValidation.d.ts +12 -0
  22. package/dist/component/renewalOperations/configureValidation.d.ts.map +1 -0
  23. package/dist/component/renewalOperations/configureValidation.js +64 -0
  24. package/dist/component/renewalOperations/configureValidation.js.map +1 -0
  25. package/dist/component/renewalOperations/helpers.d.ts +16 -21
  26. package/dist/component/renewalOperations/helpers.d.ts.map +1 -1
  27. package/dist/component/renewalOperations/helpers.js +13 -169
  28. package/dist/component/renewalOperations/helpers.js.map +1 -1
  29. package/dist/component/renewalOperations/mutations.d.ts +6 -6
  30. package/dist/component/renewalOperations/mutations.d.ts.map +1 -1
  31. package/dist/component/renewalOperations/mutations.js +14 -7
  32. package/dist/component/renewalOperations/mutations.js.map +1 -1
  33. package/dist/component/renewalOperations/operationContext.d.ts +12 -0
  34. package/dist/component/renewalOperations/operationContext.d.ts.map +1 -0
  35. package/dist/component/renewalOperations/operationContext.js +14 -0
  36. package/dist/component/renewalOperations/operationContext.js.map +1 -0
  37. package/dist/component/renewalOperations/queries.d.ts +4 -4
  38. package/dist/component/renewalOperations/queries.js +2 -1
  39. package/dist/component/renewalOperations/queries.js.map +1 -1
  40. package/dist/component/renewalOperations/schema.d.ts +59 -59
  41. package/dist/component/renewalOperations/schema.js +3 -3
  42. package/dist/component/renewalOperations/schema.js.map +1 -1
  43. package/dist/component/renewalOperations/stageAcknowledgement.d.ts +15 -0
  44. package/dist/component/renewalOperations/stageAcknowledgement.d.ts.map +1 -0
  45. package/dist/component/renewalOperations/stageAcknowledgement.js +20 -0
  46. package/dist/component/renewalOperations/stageAcknowledgement.js.map +1 -0
  47. package/dist/component/renewalOperations/validationTypes.d.ts +9 -0
  48. package/dist/component/renewalOperations/validationTypes.d.ts.map +1 -0
  49. package/dist/component/renewalOperations/validationTypes.js +2 -0
  50. package/dist/component/renewalOperations/validationTypes.js.map +1 -0
  51. package/dist/component/schema.d.ts +9 -9
  52. package/dist/component/usage/allowance.fixtures.d.ts +9 -9
  53. package/dist/component/usageCredits/accounting.fixtures.d.ts +9 -9
  54. package/dist/shared/renewalOperationJournal.d.ts +1 -1
  55. package/dist/shared/renewalOperationJournal.d.ts.map +1 -1
  56. package/dist/shared/renewalOperationJournal.js +41 -9
  57. package/dist/shared/renewalOperationJournal.js.map +1 -1
  58. package/docs/renewal-context-reads.md +36 -8
  59. package/package.json +1 -1
  60. package/src/component/renewalOperations/attachValidation.ts +203 -0
  61. package/src/component/renewalOperations/configureAcknowledgement.test.ts +30 -0
  62. package/src/component/renewalOperations/configureAcknowledgement.ts +182 -0
  63. package/src/component/renewalOperations/configureAcknowledgementControls.test.ts +96 -0
  64. package/src/component/renewalOperations/configureBasis.test.ts +77 -0
  65. package/src/component/renewalOperations/configureCreation.test.ts +75 -0
  66. package/src/component/renewalOperations/configureJournal.fixtures.ts +385 -0
  67. package/src/component/renewalOperations/configureParent.ts +71 -0
  68. package/src/component/renewalOperations/configurePolicy.test.ts +105 -0
  69. package/src/component/renewalOperations/configurePublication.test.ts +85 -0
  70. package/src/component/renewalOperations/configureReceiptBounds.test.ts +39 -0
  71. package/src/component/renewalOperations/configureSourceControls.test.ts +65 -0
  72. package/src/component/renewalOperations/configureValidation.ts +70 -0
  73. package/src/component/renewalOperations/helpers.ts +21 -204
  74. package/src/component/renewalOperations/mutations.ts +16 -7
  75. package/src/component/renewalOperations/operationContext.ts +21 -0
  76. package/src/component/renewalOperations/queries.ts +1 -1
  77. package/src/component/renewalOperations/schema.ts +3 -3
  78. package/src/component/renewalOperations/stageAcknowledgement.ts +45 -0
  79. package/src/component/renewalOperations/validationTypes.ts +9 -0
  80. package/src/shared/renewalOperationJournal.ts +49 -8
@@ -0,0 +1,65 @@
1
+ import { afterEach, expect, it, vi } from "vitest";
2
+ import {
3
+ canonicalConfigure,
4
+ configureComponentFixture,
5
+ } from "./configureJournal.fixtures.js";
6
+
7
+ afterEach(() => vi.unstubAllGlobals());
8
+ it.each([
9
+ "request-payload",
10
+ "C3-body",
11
+ "C6-input",
12
+ "credential-value",
13
+ "credential-name",
14
+ "credential-key",
15
+ ])(
16
+ "refuses contradictory or private configure %s source without inserting DATA",
17
+ async (scenario) => {
18
+ const h = await configureComponentFixture();
19
+ const raw = JSON.parse(h.createArgs.recordJSON);
20
+ const source = raw.configureRecord;
21
+ if (scenario === "request-payload") source.request.payload.future = true;
22
+ if (scenario === "C3-body")
23
+ source.attachReceipt.providerSnapshot.future = true;
24
+ if (scenario === "C6-input")
25
+ source.configuration.configureKey += ":changed";
26
+ if (scenario === "credential-value")
27
+ source.configuration.freshSubscription.future =
28
+ "Bearer synthetic-journal-token";
29
+ if (scenario === "credential-name")
30
+ source.configuration.freshSubscription.access_token =
31
+ "synthetic-journal-token";
32
+ if (scenario === "credential-key") {
33
+ const { projectRenewalConfigurationV2 } =
34
+ await import("../../client/billing/renewalV2/index.js");
35
+ source.configuration.configureKey = "sk_test_SYNTHETIC_PRIVACY_CONTROL";
36
+ const request = await projectRenewalConfigurationV2(source.configuration);
37
+ if (!("requestIdentity" in request))
38
+ throw Error("INVALID_FIXTURE_REQUEST");
39
+ source.request = request;
40
+ raw.requestBinding = request.requestIdentity.binding;
41
+ raw.dispatch = {
42
+ scope: request.scope,
43
+ apiVersion: request.apiVersion,
44
+ method: request.method,
45
+ path: request.path,
46
+ payload: request.payload,
47
+ key: request.key,
48
+ firstDispatchedAt: request.firstDispatchedAt,
49
+ };
50
+ }
51
+ const before = await h.t.run((ctx) =>
52
+ ctx.db.query("renewalOperations").take(3),
53
+ );
54
+ await expect(
55
+ h.t.mutation(h.create, {
56
+ ...h.createArgs,
57
+ recordJSON: canonicalConfigure(raw),
58
+ }),
59
+ ).rejects.toThrow("RENEWAL_JOURNAL_CONFLICT");
60
+ expect(
61
+ await h.t.run((ctx) => ctx.db.query("renewalOperations").take(3)),
62
+ ).toEqual(before);
63
+ expect(h.fetches()).toBe(0);
64
+ },
65
+ );
@@ -0,0 +1,70 @@
1
+ import { canonicalJournalRecord } from "../../shared/renewalOperationJournal.js";
2
+ import { captureConfigureSource } from "../../client/billing/renewalAttach/internal/c10/eventCapture.js";
3
+ import { reconstructConfigurationV2 } from "../../client/billing/renewalV2/index.js";
4
+ import { equal } from "../../client/billing/renewalAggregate/shared.js";
5
+
6
+ export function configureConflict(): never {
7
+ throw Error("RENEWAL_JOURNAL_CONFLICT");
8
+ }
9
+ export function jsonObject(value: unknown): Record<string, unknown> {
10
+ if (!value || typeof value !== "object" || Array.isArray(value))
11
+ configureConflict();
12
+ return value as Record<string, unknown>;
13
+ }
14
+ /** Complete C3/C6/C7 reconstruction of unsigned configure DATA. */
15
+ export async function validateOperationalConfigureSource(
16
+ full: ReturnType<typeof canonicalJournalRecord>,
17
+ ) {
18
+ try {
19
+ const original = jsonObject(JSON.parse(full.json));
20
+ const source = jsonObject(original.configureRecord);
21
+ const keys = [
22
+ "configuration",
23
+ "request",
24
+ "attachReceipt",
25
+ "originalBundle",
26
+ ];
27
+ if (
28
+ Object.keys(source).length !== keys.length ||
29
+ Object.keys(source).some((key) => !keys.includes(key))
30
+ )
31
+ configureConflict();
32
+ const configuration = captureConfigureSource(source.configuration);
33
+ // The constructor revalidates all semantic fields of this captured JSON DATA.
34
+ const rebuilt = await reconstructConfigurationV2(configuration);
35
+ if (!rebuilt.material || !("requestIdentity" in rebuilt.result))
36
+ configureConflict();
37
+ const { prepared, receipt } = rebuilt.material;
38
+ const request = rebuilt.result;
39
+ const account = jsonObject(original.account);
40
+ const policy = jsonObject(original.timingPolicy);
41
+ const seven = {
42
+ scope: request.scope,
43
+ apiVersion: request.apiVersion,
44
+ method: request.method,
45
+ path: request.path,
46
+ payload: request.payload,
47
+ key: request.key,
48
+ firstDispatchedAt: request.firstDispatchedAt,
49
+ };
50
+ if (
51
+ original.stage !== "configure" ||
52
+ original.apiVersion !== request.apiVersion ||
53
+ !equal(source.configuration, configuration) ||
54
+ !equal(source.request, request) ||
55
+ !equal(source.attachReceipt, receipt) ||
56
+ !equal(original.dispatch, seven) ||
57
+ full.requestBinding !== request.requestIdentity.binding ||
58
+ account.mode !== "platform" ||
59
+ account.stripeAccount !== null ||
60
+ account.livemode !== prepared.expected.livemode ||
61
+ policy.firstDispatchedAt !== request.firstDispatchedAt ||
62
+ policy.periodStart !== prepared.expected.periodStart ||
63
+ policy.periodEnd !== prepared.expected.periodEnd
64
+ )
65
+ configureConflict();
66
+ return { original, source, configuration, request, receipt };
67
+ } catch {
68
+ return configureConflict();
69
+ }
70
+ }
@@ -1,17 +1,21 @@
1
- import { renewalSnapshot } from "../../client/billing/renewalReplacementSnapshot.js";
1
+ import { validateStageAcknowledgement } from "./stageAcknowledgement.js";
2
+ import {
3
+ acknowledgementConflict,
4
+ jsonObject,
5
+ sameJSON,
6
+ validateAttachAcknowledgement,
7
+ } from "./attachValidation.js";
8
+ export {
9
+ validateAttachAcknowledgement,
10
+ validateAttachReceiptEventDATA,
11
+ admitAttachReceiptOutputDATA,
12
+ } from "./attachValidation.js";
13
+ import { validateOperationalConfigureSource } from "./configureValidation.js";
2
14
  import {
3
- constructRenewalScheduleAttachmentReceiptV2,
4
15
  prepareRenewalPriceReplacementV2,
5
16
  prepareRenewalScheduleAttachmentV2,
6
17
  } from "../../client/billing/renewalV2/index.js";
7
- import { captureAttachmentReceipt } from "../../client/billing/renewalV2/receipt.js";
8
- import {
9
- captureAttachSource,
10
- captureAttachDispatch,
11
- captureAttachResponse,
12
- captureAttachReceipt,
13
- } from "../../client/billing/renewalAttach/internal/c10/eventCapture.js";
14
- import { requiredJSONSnapshot } from "../../client/billing/renewalAttach/internal/material/requiredJson.js";
18
+ import { captureAttachSource } from "../../client/billing/renewalAttach/internal/c10/eventCapture.js";
15
19
  import type { Doc } from "../_generated/dataModel.js";
16
20
  import type { QueryCtx } from "../_generated/server.js";
17
21
  import {
@@ -71,6 +75,10 @@ export async function validateOperationalAttachSource(
71
75
  full: ReturnType<typeof canonicalJournalRecord>,
72
76
  ): Promise<void> {
73
77
  if (!("recordVersion" in full)) return;
78
+ if (JSON.parse(full.json).stage === "configure") {
79
+ await validateOperationalConfigureSource(full);
80
+ return;
81
+ }
74
82
  try {
75
83
  const parsed: unknown = JSON.parse(full.json);
76
84
  const original = jsonObject(parsed);
@@ -316,197 +324,6 @@ export async function eventChain(ctx: Reader, reservation: Reservation) {
316
324
  return events;
317
325
  }
318
326
 
319
- function acknowledgementConflict(): never {
320
- throw Error("RENEWAL_JOURNAL_CONFLICT");
321
- }
322
- function isJSONObject(value: unknown): value is Record<string, unknown> {
323
- return value !== null && typeof value === "object" && !Array.isArray(value);
324
- }
325
- function jsonObject(value: unknown) {
326
- if (!isJSONObject(value)) acknowledgementConflict();
327
- return value;
328
- }
329
- function sameJSON(left: unknown, right: unknown) {
330
- return (
331
- JSON.stringify(renewalSnapshot(left)) ===
332
- JSON.stringify(renewalSnapshot(right))
333
- );
334
- }
335
- type AttachReceipt = Awaited<
336
- ReturnType<typeof constructRenewalScheduleAttachmentReceiptV2>
337
- >;
338
-
339
- /** Parsed JSON DATA admission only; no caller-object or provider provenance. */
340
- export function admitAttachReceiptOutputDATA(
341
- receiptJSON: string,
342
- rebuilt: AttachReceipt,
343
- ) {
344
- if (
345
- typeof receiptJSON !== "string" ||
346
- receiptJSON.length > 500000 ||
347
- new TextEncoder().encode(receiptJSON).length > 500000
348
- )
349
- acknowledgementConflict();
350
- const parsed: unknown = JSON.parse(receiptJSON);
351
- if (!sameJSON(parsed, rebuilt)) acknowledgementConflict();
352
- const output = renewalSnapshot({
353
- status: "attach_acknowledged",
354
- operationalAuthority: false,
355
- receipt: parsed,
356
- });
357
- const slots = new Map<string, { expected: string; family: string }>([
358
- [
359
- JSON.stringify(["receipt", "logicalBinding"]),
360
- { expected: rebuilt.logicalBinding, family: "renewal" },
361
- ],
362
- [
363
- JSON.stringify(["receipt", "request", "logicalBinding"]),
364
- { expected: rebuilt.request.logicalBinding, family: "renewal" },
365
- ],
366
- [
367
- JSON.stringify(["receipt", "request", "requestIdentity", "binding"]),
368
- {
369
- expected: rebuilt.request.requestIdentity.binding,
370
- family: "renewal-attach",
371
- },
372
- ],
373
- [
374
- JSON.stringify(["receipt", "binding"]),
375
- { expected: rebuilt.binding, family: "renewal-attach-receipt" },
376
- ],
377
- ]);
378
- const found = new Set<string>();
379
- function walk(value: unknown, path: string[]) {
380
- const key = JSON.stringify(path);
381
- const slot = slots.get(key);
382
- if (slot) {
383
- if (
384
- value !== slot.expected ||
385
- typeof value !== "string" ||
386
- !new RegExp("^" + slot.family + ":v2:sha256:[0-9a-f]{64}$").test(value)
387
- )
388
- acknowledgementConflict();
389
- found.add(key);
390
- return;
391
- }
392
- if (value === null || typeof value !== "object") {
393
- requiredJSONSnapshot(value);
394
- return;
395
- }
396
- for (const [name, child] of Object.entries(value)) {
397
- requiredJSONSnapshot(name);
398
- requiredJSONSnapshot({ [name]: child === null ? null : true });
399
- walk(child, [...path, name]);
400
- }
401
- }
402
- walk(output, []);
403
- if (
404
- found.size !== 4 ||
405
- new TextEncoder().encode(JSON.stringify(output)).length > 500000
406
- )
407
- acknowledgementConflict();
408
- return JSON.stringify(output.receipt);
409
- }
410
-
411
- /** Full stored-source/event/C3 consistency; these are unsigned DATA checks. */
412
- export async function validateAttachAcknowledgement(
413
- full: ReturnType<typeof canonicalJournalRecord>,
414
- reservation: Reservation,
415
- events: Awaited<ReturnType<typeof eventChain>>,
416
- receiptJSON: string,
417
- ) {
418
- if (
419
- reservation.stage !== "attach" ||
420
- (events.length !== 2 && events.length !== 3) ||
421
- events[0].sequence !== 1 ||
422
- events[1].sequence !== 2
423
- )
424
- acknowledgementConflict();
425
- const parsedOriginal: unknown = JSON.parse(full.json);
426
- const original = jsonObject(parsedOriginal);
427
- const account = jsonObject(original.account);
428
- const source = captureAttachSource(original.attachRequest);
429
- if (!sameJSON(original.attachRequest, source)) acknowledgementConflict();
430
- const parsedDispatch: unknown = JSON.parse(events[0].dataJSON);
431
- const parsedResponse: unknown = JSON.parse(events[1].dataJSON);
432
- captureAttachDispatch(parsedDispatch);
433
- captureAttachResponse(parsedResponse);
434
- const dispatch = jsonObject(parsedDispatch);
435
- const response = jsonObject(parsedResponse);
436
- const raw = captureAttachmentReceipt({
437
- attachRequest: source,
438
- actualDispatch: original.dispatch,
439
- providerSnapshot: response.body,
440
- });
441
- // C3 internally rebuilds C1/C2 and compares the entire closed seven-wire input.
442
- const rebuilt = await constructRenewalScheduleAttachmentReceiptV2({
443
- attachRequest: source,
444
- actualDispatch: raw.actualDispatch,
445
- providerSnapshot: raw.providerSnapshot,
446
- });
447
- const request = rebuilt.request;
448
- const seven = {
449
- scope: request.scope,
450
- apiVersion: request.apiVersion,
451
- method: request.method,
452
- path: request.path,
453
- payload: request.payload,
454
- key: request.key,
455
- firstDispatchedAt: request.firstDispatchedAt,
456
- };
457
- if (
458
- !sameJSON(original.dispatch, seven) ||
459
- !sameJSON(dispatch.request, request) ||
460
- !sameJSON(response.request, request) ||
461
- original.stage !== "attach" ||
462
- original.apiVersion !== request.apiVersion ||
463
- full.requestBinding !== request.requestIdentity.binding ||
464
- reservation.key !== request.key ||
465
- reservation.apiVersion !== request.apiVersion ||
466
- reservation.firstDispatchedAt !== request.firstDispatchedAt ||
467
- account.mode !== "platform" ||
468
- account.stripeAccount !== null ||
469
- account.livemode !== rebuilt.livemode ||
470
- !sameJSON(JSON.parse(reservation.accountJSON), account)
471
- )
472
- acknowledgementConflict();
473
- if ("recordVersion" in reservation) {
474
- if (
475
- !sameJSON(JSON.parse(reservation.timingPolicyJSON), original.timingPolicy)
476
- )
477
- acknowledgementConflict();
478
- } else if (!sameJSON(JSON.parse(reservation.basisJSON), original.basis))
479
- acknowledgementConflict();
480
- const admittedJSON = admitAttachReceiptOutputDATA(receiptJSON, rebuilt);
481
- // Only ACTUAL published event3 is checked. A head2 retention does not model
482
- // or require a prospective receipt-event envelope to pass another cap.
483
- if (events.length === 3)
484
- validateAttachReceiptEventDATA(events[2].dataJSON, rebuilt);
485
- return {
486
- receiptJSON: admittedJSON,
487
- receiptBinding: rebuilt.binding,
488
- receipt: rebuilt,
489
- };
490
- }
491
-
492
- /** Whole typed C10 DATA and full request/receipt equality, never ACK authority. */
493
- export function validateAttachReceiptEventDATA(
494
- raw: string,
495
- receipt: AttachReceipt,
496
- ) {
497
- const parsed: unknown = JSON.parse(raw);
498
- captureAttachReceipt(parsed);
499
- if (
500
- !sameJSON(parsed, {
501
- event: "receipt",
502
- stage: "attach",
503
- request: receipt.request,
504
- receipt,
505
- })
506
- )
507
- acknowledgementConflict();
508
- }
509
-
510
327
  /** Optional stored known DATA; every reference, owner and full JSON is checked. */
511
328
  export async function validateKnownAcknowledgement(
512
329
  ctx: Reader,
@@ -523,7 +340,7 @@ export async function validateKnownAcknowledgement(
523
340
  if (
524
341
  events.length < 2 ||
525
342
  retained.schemaVersion !== 1 ||
526
- retained.stage !== "attach" ||
343
+ retained.stage !== reservation.stage ||
527
344
  retained.attemptId !== reservation.attemptId ||
528
345
  retained.sourcePayloadId !== reservation.payloadId ||
529
346
  retained.dispatchEventId !== events[0].eventId ||
@@ -546,7 +363,7 @@ export async function validateKnownAcknowledgement(
546
363
  owner.kind !== "receipt" ||
547
364
  owner.operationId !== row._id ||
548
365
  owner.attemptId !== reservation.attemptId ||
549
- owner.stage !== "attach"
366
+ owner.stage !== reservation.stage
550
367
  )
551
368
  acknowledgementConflict();
552
369
  return retained;
@@ -571,7 +388,7 @@ export async function validateV2KnownAcknowledgement(
571
388
  row.knownAcknowledgement.receiptPayloadId,
572
389
  );
573
390
  if (!payload) acknowledgementConflict();
574
- const admitted = await validateAttachAcknowledgement(
391
+ const admitted = await validateStageAcknowledgement(
575
392
  full,
576
393
  reservation,
577
394
  events,
@@ -1,3 +1,9 @@
1
+ import {
2
+ validateStageAcknowledgement,
3
+ validateStageReceiptEventDATA,
4
+ } from "./stageAcknowledgement.js";
5
+ import { validateConfigureParent } from "./configureParent.js";
6
+ import { readCheckedOperation as originalRecord } from "./operationContext.js";
1
7
  import type { Infer } from "convex/values";
2
8
  import { mutation } from "../_generated/server.js";
3
9
  import {
@@ -10,7 +16,6 @@ import {
10
16
  import {
11
17
  findOperation,
12
18
  validateOperationalAttachSource,
13
- originalRecord,
14
19
  currentReservation,
15
20
  checkedInitialBasis,
16
21
  reservationFields,
@@ -59,6 +64,7 @@ export const createAuthorizedOperation = mutation({
59
64
  )
60
65
  return conflict;
61
66
  await validateOperationalAttachSource(full);
67
+ await validateConfigureParent(ctx, full);
62
68
  const existing = await findOperation(
63
69
  ctx,
64
70
  args.authorizationScope,
@@ -206,7 +212,7 @@ export const appendStageEvent = mutation({
206
212
  : null;
207
213
  if (known !== null && incoming.sequence === 3) {
208
214
  try {
209
- validateAttachReceiptEventDATA(incoming.json, known.admitted.receipt);
215
+ validateStageReceiptEventDATA(incoming.json, known.admitted);
210
216
  } catch {
211
217
  throw Error("RENEWAL_JOURNAL_CONFLICT");
212
218
  }
@@ -298,7 +304,7 @@ export const retainProviderAcknowledgement = mutation({
298
304
  if (
299
305
  !reservation ||
300
306
  reservation.attemptId !== args.attemptId ||
301
- reservation.stage !== "attach"
307
+ (reservation.stage !== "attach" && !("recordVersion" in reservation))
302
308
  )
303
309
  throw Error("RENEWAL_JOURNAL_CONFLICT");
304
310
  if (
@@ -315,7 +321,7 @@ export const retainProviderAcknowledgement = mutation({
315
321
  args.expectedSequence !== head)
316
322
  )
317
323
  throw Error("RENEWAL_JOURNAL_CONFLICT");
318
- const admitted = await validateAttachAcknowledgement(
324
+ const admitted = await validateStageAcknowledgement(
319
325
  full,
320
326
  reservation,
321
327
  events,
@@ -361,12 +367,12 @@ export const retainProviderAcknowledgement = mutation({
361
367
  kind: "receipt",
362
368
  operationId: row._id,
363
369
  attemptId: reservation.attemptId,
364
- stage: "attach",
370
+ stage: reservation.stage,
365
371
  },
366
372
  });
367
373
  const known: Infer<typeof knownAcknowledgement> = {
368
374
  schemaVersion: 1,
369
- stage: "attach",
375
+ stage: reservation.stage,
370
376
  attemptId: reservation.attemptId,
371
377
  sourcePayloadId: reservation.payloadId,
372
378
  dispatchEventId: events[0].eventId,
@@ -412,6 +418,9 @@ export const bindInitialBasis = mutation({
412
418
  const normalized = canonicalInitialBasis(args.policyJSON, args.basisJSON);
413
419
  if (normalized.policyJSON !== reservation.timingPolicyJSON)
414
420
  throw Error("RENEWAL_JOURNAL_CONFLICT");
421
+ const parent = await validateConfigureParent(ctx, full);
422
+ if (parent && parent.basisJSON !== normalized.basisJSON)
423
+ throw Error("RENEWAL_JOURNAL_CONFLICT");
415
424
  const existing = checkedInitialBasis(
416
425
  row,
417
426
  reservation.attemptId,
@@ -421,7 +430,7 @@ export const bindInitialBasis = mutation({
421
430
  version: 1,
422
431
  attemptId: reservation.attemptId,
423
432
  sourcePayloadId: reservation.payloadId,
424
- stage: "attach",
433
+ stage: reservation.stage,
425
434
  policyJSON: normalized.policyJSON,
426
435
  basisJSON: normalized.basisJSON,
427
436
  };
@@ -0,0 +1,21 @@
1
+ import type { Doc } from "../_generated/dataModel.js";
2
+ import type { QueryCtx } from "../_generated/server.js";
3
+ import { originalRecord } from "./helpers.js";
4
+ import { configureConflict } from "./configureValidation.js";
5
+ import { validateConfigureParent } from "./configureParent.js";
6
+
7
+ /** Full source and parent checks for every stored operation API boundary. */
8
+ export async function readCheckedOperation(
9
+ ctx: Pick<QueryCtx, "db">,
10
+ row: Doc<"renewalOperations">,
11
+ ) {
12
+ const full = await originalRecord(ctx, row);
13
+ const parent = await validateConfigureParent(ctx, full);
14
+ if (
15
+ parent &&
16
+ row.initialBasis &&
17
+ row.initialBasis.basisJSON !== parent.basisJSON
18
+ )
19
+ configureConflict();
20
+ return full;
21
+ }
@@ -1,7 +1,7 @@
1
+ import { readCheckedOperation as originalRecord } from "./operationContext.js";
1
2
  import { v } from "convex/values";
2
3
  import { query } from "../_generated/server.js";
3
4
  import {
4
- originalRecord,
5
5
  currentReservation,
6
6
  eventChain,
7
7
  validateAttachAcknowledgement,
@@ -32,7 +32,7 @@ export const payloadsTable = defineTable({
32
32
  });
33
33
  const knownAcknowledgementFields = {
34
34
  schemaVersion: v.literal(1),
35
- stage: v.literal("attach"),
35
+ stage,
36
36
  attemptId: v.id("renewalOperationAttempts"),
37
37
  sourcePayloadId: v.id("renewalOperationPayloads"),
38
38
  dispatchEventId: v.id("renewalOperationEvents"),
@@ -64,7 +64,7 @@ export const initialBasisDescriptor = v.object({
64
64
  version: v.literal(1),
65
65
  attemptId: v.id("renewalOperationAttempts"),
66
66
  sourcePayloadId: v.id("renewalOperationPayloads"),
67
- stage: v.literal("attach"),
67
+ stage,
68
68
  policyJSON: v.string(),
69
69
  basisJSON: v.string(),
70
70
  });
@@ -130,7 +130,7 @@ const legacyAttemptFields = {
130
130
  const operationalAttemptFields = {
131
131
  ...attemptFields,
132
132
  recordVersion: v.literal(2),
133
- stage: v.literal("attach"),
133
+ stage,
134
134
  timingPolicyJSON: v.string(),
135
135
  };
136
136
  export const attemptsTable = defineTable(
@@ -0,0 +1,45 @@
1
+ import type { canonicalJournalRecord } from "../../shared/renewalOperationJournal.js";
2
+ import type { Reservation, CheckedEvents } from "./validationTypes.js";
3
+ import {
4
+ validateAttachAcknowledgement,
5
+ validateAttachReceiptEventDATA,
6
+ } from "./attachValidation.js";
7
+ import {
8
+ validateConfigureAcknowledgement,
9
+ validateConfigureReceiptEventDATA,
10
+ } from "./configureAcknowledgement.js";
11
+
12
+ export async function validateStageAcknowledgement(
13
+ full: ReturnType<typeof canonicalJournalRecord>,
14
+ reservation: Reservation,
15
+ events: CheckedEvents,
16
+ receiptJSON: string,
17
+ ) {
18
+ if (reservation.stage === "configure" && "recordVersion" in reservation)
19
+ return {
20
+ ...(await validateConfigureAcknowledgement(
21
+ full,
22
+ reservation,
23
+ events,
24
+ receiptJSON,
25
+ )),
26
+ stage: "configure" as const,
27
+ };
28
+ return {
29
+ ...(await validateAttachAcknowledgement(
30
+ full,
31
+ reservation,
32
+ events,
33
+ receiptJSON,
34
+ )),
35
+ stage: "attach" as const,
36
+ };
37
+ }
38
+ export function validateStageReceiptEventDATA(
39
+ raw: string,
40
+ admitted: Awaited<ReturnType<typeof validateStageAcknowledgement>>,
41
+ ) {
42
+ if (admitted.stage === "configure")
43
+ validateConfigureReceiptEventDATA(raw, admitted.receipt);
44
+ else validateAttachReceiptEventDATA(raw, admitted.receipt);
45
+ }
@@ -0,0 +1,9 @@
1
+ import type { Infer } from "convex/values";
2
+ import type { QueryCtx } from "../_generated/server.js";
3
+ import type { reservationData, eventDescriptor } from "./schema.js";
4
+
5
+ export type JournalReader = Pick<QueryCtx, "db">;
6
+ export type Reservation = Infer<typeof reservationData>;
7
+ export type CheckedEvents = readonly (Infer<typeof eventDescriptor> & {
8
+ dataJSON: string;
9
+ })[];
@@ -16,13 +16,19 @@ function record(value: unknown): value is Record<string, unknown> {
16
16
  function text(value: unknown): value is string {
17
17
  return typeof value === "string" && value.length > 0;
18
18
  }
19
- /** Intrinsic V2 policy DATA only; full C1/C2 validation is an async boundary. */
20
- function validateAttachTimingPolicy(value: Record<string, unknown>): void {
19
+ /** Intrinsic V2 policy DATA only; complete stage reconstruction is async. */
20
+ function validateStageTimingPolicy(value: Record<string, unknown>): void {
21
21
  const policy = value.timingPolicy;
22
22
  const dispatch = value.dispatch;
23
- const source = value.attachRequest;
23
+ const configure = value.configureRecord;
24
+ const source =
25
+ value.stage === "attach"
26
+ ? value.attachRequest
27
+ : record(configure)
28
+ ? configure.configuration
29
+ : null;
24
30
  if (
25
- value.stage !== "attach" ||
31
+ (value.stage !== "attach" && value.stage !== "configure") ||
26
32
  Object.prototype.hasOwnProperty.call(value, "basis") ||
27
33
  !Object.prototype.hasOwnProperty.call(value, "timingPolicy") ||
28
34
  !record(policy) ||
@@ -32,6 +38,43 @@ function validateAttachTimingPolicy(value: Record<string, unknown>): void {
32
38
  !record(source.preparation.expected)
33
39
  )
34
40
  stop();
41
+ if (value.stage === "configure") {
42
+ const parent = value.parentAttachment;
43
+ if (
44
+ !record(parent) ||
45
+ !record(configure) ||
46
+ !record(configure.attachReceipt) ||
47
+ !record(configure.request) ||
48
+ !record(configure.request.requestIdentity)
49
+ )
50
+ stop();
51
+ const parentKeys = [
52
+ "operationId",
53
+ "attemptId",
54
+ "sourcePayloadId",
55
+ "receiptBinding",
56
+ ];
57
+ if (
58
+ Object.keys(parent).length !== parentKeys.length ||
59
+ Object.keys(parent).some((key) => !parentKeys.includes(key))
60
+ )
61
+ stop();
62
+ for (const key of parentKeys) {
63
+ const field = parent[key];
64
+ if (!text(field) || field.length > 255) stop();
65
+ }
66
+ if (
67
+ typeof parent.receiptBinding !== "string" ||
68
+ !/^renewal-attach-receipt:v2:sha256:[0-9a-f]{64}$/.test(
69
+ parent.receiptBinding,
70
+ ) ||
71
+ parent.receiptBinding !== configure.attachReceipt.binding ||
72
+ configure.request.stage !== "configure" ||
73
+ configure.request.requestIdentity.binding !== value.requestBinding ||
74
+ configure.request.firstDispatchedAt !== source.firstDispatchedAt
75
+ )
76
+ stop();
77
+ }
35
78
  const fields = [
36
79
  "version",
37
80
  "firstDispatchedAt",
@@ -85,7 +128,7 @@ export function canonicalJournalRecord(raw: string) {
85
128
  (value.schemaVersion !== 1 && value.schemaVersion !== 2)
86
129
  )
87
130
  stop();
88
- if (value.schemaVersion === 2) validateAttachTimingPolicy(value);
131
+ if (value.schemaVersion === 2) validateStageTimingPolicy(value);
89
132
  const authorization = value.authorization;
90
133
  if (
91
134
  !record(authorization) ||
@@ -157,11 +200,9 @@ export function journalReservationMaterial(
157
200
  accountJSON: JSON.stringify(renewalSnapshot(account)),
158
201
  });
159
202
  if (value.schemaVersion === 2) {
160
- if (value.stage !== "attach") stop();
161
- validateAttachTimingPolicy(value);
203
+ validateStageTimingPolicy(value);
162
204
  return Object.freeze({
163
205
  ...common,
164
- stage: "attach" as const,
165
206
  recordVersion: 2 as const,
166
207
  timingPolicyJSON: JSON.stringify(renewalSnapshot(value.timingPolicy)),
167
208
  });