@cosmicdrift/kumiko-bundled-features 0.414.0 → 0.415.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 (95) hide show
  1. package/dist/auth-email-password/signup-token-store.d.ts +2 -2
  2. package/dist/auth-email-password/signup-token-store.js +2 -4
  3. package/dist/auth-email-password/web/session.js +2 -1
  4. package/dist/billing-foundation/checkout-core.d.ts +2 -0
  5. package/dist/billing-foundation/checkout-core.js +9 -0
  6. package/dist/billing-foundation/checkout-ledger.d.ts +7 -0
  7. package/dist/billing-foundation/checkout-ledger.js +6 -0
  8. package/dist/billing-foundation/events.d.ts +1 -0
  9. package/dist/billing-foundation/events.js +6 -5
  10. package/dist/billing-foundation/handlers/create-checkout-session.write.js +2 -1
  11. package/dist/billing-foundation/handlers/process-event.write.d.ts +3 -1
  12. package/dist/billing-foundation/handlers/process-event.write.js +57 -32
  13. package/dist/billing-foundation/handlers/process-payment-event.write.js +5 -5
  14. package/dist/billing-foundation/handlers/start-plan-checkout.write.js +2 -1
  15. package/dist/billing-foundation/webhook-handler.js +2 -2
  16. package/dist/channel-whatsapp/events.d.ts +3 -0
  17. package/dist/channel-whatsapp/events.js +4 -3
  18. package/dist/channel-whatsapp/inbound-handlers.js +24 -3
  19. package/dist/channel-whatsapp/webhook-normalize.js +21 -6
  20. package/dist/compliance-profiles/handlers/set-profile.write.js +2 -0
  21. package/dist/data-retention/feature.js +1 -0
  22. package/dist/delivery/handlers/opted-in-user-ids.query.js +12 -3
  23. package/dist/document-ingest-foundation/feature.js +1 -0
  24. package/dist/document-ingest-foundation/report-ingest-progress.js +4 -1
  25. package/dist/documents/feature.d.ts +2 -2
  26. package/dist/documents/feature.js +7 -2
  27. package/dist/form-draft/feature.js +1 -0
  28. package/dist/helpdesk/feature.js +1 -0
  29. package/dist/helpdesk/handlers/reply.write.js +3 -3
  30. package/dist/helpdesk/handlers/report.write.js +3 -2
  31. package/dist/helpdesk/handlers/submit.write.js +3 -2
  32. package/dist/helpdesk/legacy-contact-streams.js +5 -2
  33. package/dist/helpdesk/lib.d.ts +1 -1
  34. package/dist/helpdesk/lib.js +4 -4
  35. package/dist/inbound-mail-foundation/account-poll.js +2 -0
  36. package/dist/inbound-mail-foundation/content-refetch.d.ts +3 -0
  37. package/dist/inbound-mail-foundation/content-refetch.js +2 -6
  38. package/dist/inbound-mail-foundation/entities.js +10 -9
  39. package/dist/inbound-mail-foundation/events.js +10 -9
  40. package/dist/inbound-mail-foundation/handlers/connect-account.write.js +2 -1
  41. package/dist/inbound-mail-foundation/handlers/forget-message.write.js +4 -0
  42. package/dist/inbound-mail-foundation/handlers/ingest-message-schema.js +12 -5
  43. package/dist/inbound-mail-foundation/normalize-inbound-message.d.ts +6 -0
  44. package/dist/inbound-mail-foundation/normalize-inbound-message.js +21 -8
  45. package/dist/inbound-mail-foundation/sanitize-inbound-html.d.ts +0 -1
  46. package/dist/inbound-mail-foundation/sanitize-inbound-html.js +2 -4
  47. package/dist/managed-pages/web/page-edit-screen.js +12 -5
  48. package/dist/shared/hmac-signature.js +4 -2
  49. package/dist/shared/index.d.ts +2 -1
  50. package/dist/shared/index.js +2 -1
  51. package/dist/shared/normalize-email.d.ts +1 -0
  52. package/dist/shared/normalize-email.js +3 -0
  53. package/dist/shared/send-best-effort.d.ts +1 -0
  54. package/dist/shared/send-best-effort.js +10 -5
  55. package/dist/step-dispatcher/deliver-dispatch-request.js +5 -3
  56. package/dist/step-dispatcher/feature.js +11 -0
  57. package/dist/step-dispatcher/sweep-abandoned.d.ts +1 -0
  58. package/dist/step-dispatcher/sweep-abandoned.js +3 -0
  59. package/dist/subscription-paddle/backfill-checkout-ledger.js +2 -0
  60. package/dist/subscription-paddle/redeliver-legacy-checkout.js +19 -2
  61. package/dist/subscription-stripe/verify-webhook.js +16 -6
  62. package/dist/template-resolver/seeding.js +32 -7
  63. package/dist/template-resolver/web/web-preview-renderer.js +5 -1
  64. package/dist/tenant-inactivity/check-inactive-tenants.js +27 -16
  65. package/dist/tenant-inactivity/handlers/keep-account.write.js +7 -0
  66. package/dist/tenant-inactivity/state-store.d.ts +2 -1
  67. package/dist/tenant-inactivity/state-store.js +7 -0
  68. package/dist/tenant-lifecycle/feature.js +1 -0
  69. package/dist/user/resolve-verified-user-email.js +3 -3
  70. package/dist/user-data-rights/feature.js +1 -0
  71. package/dist/waitlist/handlers/reject.write.js +2 -1
  72. package/dist/waitlist/handlers/submit.write.js +2 -2
  73. package/dist/waitlist/import.js +2 -1
  74. package/dist/waitlist/lib.d.ts +0 -1
  75. package/dist/waitlist/lib.js +1 -4
  76. package/dist/waitlist/link-on-signup.js +2 -2
  77. package/dist/workflow-runner/handlers/resume-run.write.js +4 -3
  78. package/package.json +11 -11
  79. package/src/auth-mfa/changes.json +6 -0
  80. package/src/billing-foundation/changes.json +24 -0
  81. package/src/channel-whatsapp/changes.json +24 -0
  82. package/src/compliance-profiles/changes.json +5 -0
  83. package/src/delivery/changes.json +6 -0
  84. package/src/document-ingest-foundation/changes.json +6 -0
  85. package/src/documents/changes.json +6 -0
  86. package/src/helpdesk/changes.json +6 -0
  87. package/src/inbound-mail-foundation/changes.json +6 -0
  88. package/src/shared/changes.json +6 -0
  89. package/src/step-dispatcher/changes.json +6 -0
  90. package/src/subscription-paddle/changes.json +6 -0
  91. package/src/subscription-stripe/changes.json +6 -0
  92. package/src/template-resolver/changes.json +12 -0
  93. package/src/tenant-inactivity/changes.json +6 -0
  94. package/src/tenant-lifecycle/changes.json +6 -0
  95. package/src/workflow-runner/changes.json +6 -0
@@ -1,7 +1,7 @@
1
1
  import { jsx as _jsx } from "react/jsx-runtime";
2
2
  import { dispatcherErrorTextWithFieldIssues, PreviewPane, useMutation, useNav, usePrimitives, useQuery, useTranslation, useUnsavedInputSource, } from "@cosmicdrift/kumiko-renderer";
3
3
  import { EditorWorkbench, LoadingState, StatusBadge } from "@cosmicdrift/kumiko-renderer/web";
4
- import { useState } from "react";
4
+ import { useRef, useState } from "react";
5
5
  import { DocumentContentEditor } from "../../template-resolver/web/index.js";
6
6
  import { PAGE_CREATE_HANDLER, PAGE_DETAIL_QUERY, PAGE_EDIT_SCREEN_ID, PAGE_LIST_SCREEN_ID, PAGE_UPDATE_HANDLER, } from "./constants.js";
7
7
  import { changesOf, createdIdOf, createPayloadOf, draftOfRecord, EMPTY_PAGE_DRAFT, isDraftDirty, lossyFeaturesOfRecord, } from "./page-edit-draft.js";
@@ -17,8 +17,10 @@ const TEST_ID = "page-workbench";
17
17
  function PageEditor({ record, onSaved, }) {
18
18
  const t = useTranslation();
19
19
  const { Banner } = usePrimitives();
20
- const initial = record === null ? EMPTY_PAGE_DRAFT : draftOfRecord(record);
21
- const lossyOnOpen = record === null ? [] : lossyFeaturesOfRecord(record);
20
+ // Computed once: the editor is remounted per record version, and every keystroke re-renders it.
21
+ const [initial] = useState(() => (record === null ? EMPTY_PAGE_DRAFT : draftOfRecord(record)));
22
+ const [lossyOnOpen] = useState(() => (record === null ? [] : lossyFeaturesOfRecord(record)));
23
+ const savedRef = useRef(false);
22
24
  const [draft, setDraft] = useState(initial);
23
25
  const [bodyEdited, setBodyEdited] = useState(false);
24
26
  const [resetCount, setResetCount] = useState(0);
@@ -26,8 +28,12 @@ function PageEditor({ record, onSaved, }) {
26
28
  const create = useMutation(PAGE_CREATE_HANDLER);
27
29
  const update = useMutation(PAGE_UPDATE_HANDLER);
28
30
  const dirty = isDraftDirty(draft, initial);
29
- useUnsavedInputSource(() => dirty);
30
- const patch = (changes) => setDraft((current) => ({ ...current, ...changes }));
31
+ // The leave guard runs synchronously after save, before React re-renders with the saved state.
32
+ useUnsavedInputSource(() => dirty && !savedRef.current);
33
+ const patch = (changes) => {
34
+ savedRef.current = false;
35
+ setDraft((current) => ({ ...current, ...changes }));
36
+ };
31
37
  const canSave = dirty && draft.slug !== "" && draft.title !== "";
32
38
  const save = async () => {
33
39
  setSaveError(null);
@@ -42,6 +48,7 @@ function PageEditor({ record, onSaved, }) {
42
48
  setSaveError(dispatcherErrorTextWithFieldIssues(result.error, t));
43
49
  return;
44
50
  }
51
+ savedRef.current = true;
45
52
  onSaved(record === null ? createdIdOf(result.data) : record.id);
46
53
  };
47
54
  const discard = () => {
@@ -3,8 +3,10 @@ export function signHmacSha256Base64Url(input, secret) {
3
3
  return createHmac("sha256", secret).update(input).digest("base64url");
4
4
  }
5
5
  export function hmacSignatureMatches(expectedBase64Url, providedBase64Url) {
6
- const expectedBuf = Buffer.from(expectedBase64Url, "base64url");
7
- const providedBuf = Buffer.from(providedBase64Url, "base64url");
6
+ // The text is compared, not the decoded bytes: decoding ignores the unused trailing bits of the
7
+ // last character, so one signature would have several accepted spellings.
8
+ const expectedBuf = Buffer.from(expectedBase64Url);
9
+ const providedBuf = Buffer.from(providedBase64Url);
8
10
  // timingSafeEqual throws on a length mismatch, and the throw itself is a timing signal.
9
11
  return expectedBuf.length === providedBuf.length && timingSafeEqual(expectedBuf, providedBuf);
10
12
  }
@@ -19,6 +19,7 @@ export { createLockoutCounter, type LockoutCounterState } from "./lockout-counte
19
19
  export { createMailLocaleTemplates } from "./mail-locale-templates.ts";
20
20
  export { mailHeading, mailParagraph, mailParagraphWithLink, mailRepeatedRows, } from "./mail-template-body.ts";
21
21
  export { mapWithConcurrency } from "./map-with-concurrency.ts";
22
+ export { normalizeEmail } from "./normalize-email.ts";
22
23
  export { denyUnlessJoinRowParentVisible, hostRowIsGone, joinRowParentIsVisible, parentRowIsVisible, visibleParentRowIds, } from "./parent-visibility.ts";
23
24
  export { hashPassword, verifyDummyPassword, verifyPassword } from "./password-hashing.ts";
24
25
  export { type PriceEnvProvider, type PriceEnvShape, priceEnvSchema, priceEnvShape, } from "./price-env-shape.ts";
@@ -35,7 +36,7 @@ export { resolveFeatureAccess } from "./resolve-feature-access.ts";
35
36
  export { extensionForResourceContentType, isResourceImageContentType, isResourceImageFormat, RESOURCE_IMAGE_FORMATS, type ResourceImageContentType, type ResourceImageFormat, } from "./resource-image-formats.ts";
36
37
  export { type RowBoundGrantResult, redeemRowBoundGrant, signRowBoundGrant, } from "./row-bound-grant.ts";
37
38
  export { runInSubTransaction } from "./run-in-sub-transaction.ts";
38
- export { sendBestEffort } from "./send-best-effort.ts";
39
+ export { runBestEffort, sendBestEffort } from "./send-best-effort.ts";
39
40
  export { registrationLocaleFromRequest, sessionLocaleField } from "./session-locale-field.ts";
40
41
  export { sessionTimezoneField } from "./session-timezone-field.ts";
41
42
  export { assertNotSvg, MAX_INPUT_PIXELS, SHARP_INPUT_OPTIONS } from "./sharp-input-limits.ts";
@@ -19,6 +19,7 @@ export { createLockoutCounter } from "./lockout-counter.js";
19
19
  export { createMailLocaleTemplates } from "./mail-locale-templates.js";
20
20
  export { mailHeading, mailParagraph, mailParagraphWithLink, mailRepeatedRows, } from "./mail-template-body.js";
21
21
  export { mapWithConcurrency } from "./map-with-concurrency.js";
22
+ export { normalizeEmail } from "./normalize-email.js";
22
23
  export { denyUnlessJoinRowParentVisible, hostRowIsGone, joinRowParentIsVisible, parentRowIsVisible, visibleParentRowIds, } from "./parent-visibility.js";
23
24
  export { hashPassword, verifyDummyPassword, verifyPassword } from "./password-hashing.js";
24
25
  export { priceEnvSchema, priceEnvShape, } from "./price-env-shape.js";
@@ -35,7 +36,7 @@ export { resolveFeatureAccess } from "./resolve-feature-access.js";
35
36
  export { extensionForResourceContentType, isResourceImageContentType, isResourceImageFormat, RESOURCE_IMAGE_FORMATS, } from "./resource-image-formats.js";
36
37
  export { redeemRowBoundGrant, signRowBoundGrant, } from "./row-bound-grant.js";
37
38
  export { runInSubTransaction } from "./run-in-sub-transaction.js";
38
- export { sendBestEffort } from "./send-best-effort.js";
39
+ export { runBestEffort, sendBestEffort } from "./send-best-effort.js";
39
40
  export { registrationLocaleFromRequest, sessionLocaleField } from "./session-locale-field.js";
40
41
  export { sessionTimezoneField } from "./session-timezone-field.js";
41
42
  export { assertNotSvg, MAX_INPUT_PIXELS, SHARP_INPUT_OPTIONS } from "./sharp-input-limits.js";
@@ -0,0 +1 @@
1
+ export declare function normalizeEmail(email: string): string;
@@ -0,0 +1,3 @@
1
+ export function normalizeEmail(email) {
2
+ return email.toLowerCase();
3
+ }
@@ -1,2 +1,3 @@
1
1
  import type { HandlerContext } from "@cosmicdrift/kumiko-framework/engine";
2
+ export declare function runBestEffort(ctx: Pick<HandlerContext, "obs">, logMessage: string, run: () => Promise<unknown>): Promise<void>;
2
3
  export declare function sendBestEffort(ctx: Pick<HandlerContext, "notify" | "obs">, logMessage: string, send: (notify: NonNullable<HandlerContext["notify"]>) => Promise<unknown>): Promise<void>;
@@ -1,10 +1,7 @@
1
1
  import { InternalError } from "@cosmicdrift/kumiko-framework/errors";
2
- export async function sendBestEffort(ctx, logMessage, send) {
2
+ export async function runBestEffort(ctx, logMessage, run) {
3
3
  try {
4
- if (!ctx.notify) {
5
- throw new InternalError({ message: "ctx.notify unavailable — mount the delivery feature" });
6
- }
7
- await send(ctx.notify);
4
+ await run();
8
5
  }
9
6
  catch (err) {
10
7
  ctx.obs.log?.warn(logMessage, {
@@ -12,3 +9,11 @@ export async function sendBestEffort(ctx, logMessage, send) {
12
9
  });
13
10
  }
14
11
  }
12
+ export async function sendBestEffort(ctx, logMessage, send) {
13
+ await runBestEffort(ctx, logMessage, async () => {
14
+ if (!ctx.notify) {
15
+ throw new InternalError({ message: "ctx.notify unavailable — mount the delivery feature" });
16
+ }
17
+ await send(ctx.notify);
18
+ });
19
+ }
@@ -90,13 +90,14 @@ export async function deliverDispatchRequest(args) {
90
90
  await abortOnFinalAttempt(err, ctx, recorder, aggregateId, requested.payload);
91
91
  }
92
92
  }
93
- function createOutcomeRecorder(ctx, aggregateId, attempt) {
93
+ function createOutcomeRecorder(ctx, aggregateId, attempt, expectedVersion) {
94
94
  const record = async (type, payload) => {
95
95
  await ctx.unsafeAppendEvent({
96
96
  aggregateId,
97
97
  aggregateType: STEP_DISPATCH_AGGREGATE_TYPE,
98
98
  type,
99
99
  payload,
100
+ ...(expectedVersion !== undefined && { expectedVersion }),
100
101
  });
101
102
  await eraseDispatchKey(aggregateId);
102
103
  };
@@ -107,7 +108,8 @@ function createOutcomeRecorder(ctx, aggregateId, attempt) {
107
108
  }
108
109
  // For a deliver job that ended terminally without an outcome (BullMQ stall, lost job): the
109
110
  // request is closed as failed and its key erased. A stream that already has an outcome only
110
- // repeats the erase.
111
+ // repeats the erase. The failure is pinned to the loaded version: a delivery that records its
112
+ // outcome in between makes the append throw VersionConflictError and the key stays.
111
113
  export async function closeAbandonedDispatch(ctx, aggregateId) {
112
114
  const stream = await ctx.loadAggregate(aggregateId);
113
115
  if (stream.some(isDispatchOutcome)) {
@@ -115,7 +117,7 @@ export async function closeAbandonedDispatch(ctx, aggregateId) {
115
117
  return "already-closed";
116
118
  }
117
119
  const requested = stream.find((e) => e.type === STEP_DISPATCH_REQUESTED_TYPE);
118
- await createOutcomeRecorder(ctx, aggregateId, 0).recordFailure(rawStepKindOf(requested?.payload), DISPATCH_ABANDONED_ERROR);
120
+ await createOutcomeRecorder(ctx, aggregateId, 0, stream.at(-1)?.version).recordFailure(rawStepKindOf(requested?.payload), DISPATCH_ABANDONED_ERROR);
119
121
  return "closed";
120
122
  }
121
123
  async function deliverRequested(args, requested, ctx, recorder) {
@@ -41,6 +41,7 @@ export function createStepDispatcherFeature() {
41
41
  // StepDispatcherJobNames.deliver mirrors it; feature.boot.test.ts pins the two together.
42
42
  r.job("deliver", {
43
43
  trigger: { manual: true },
44
+ irreversibleWithoutEntryHandler: "per-dispatch-record-key",
44
45
  retries: DELIVER_RETRIES,
45
46
  backoff: "exponential",
46
47
  maxPerTenant: { limit: DELIVER_MAX_PER_TENANT, onLimit: "defer" },
@@ -68,12 +69,21 @@ export function createStepDispatcherFeature() {
68
69
  // Literal name, mirrored by StepDispatcherJobNames.sweepAbandoned (pinned in feature.boot.test.ts).
69
70
  r.job("sweep-abandoned", {
70
71
  trigger: { cron: "17 3 * * *", wakesSleepingApp: false },
72
+ irreversibleWithoutEntryHandler: "per-dispatch-record-key",
71
73
  concurrency: "skip",
72
74
  escapeHatch: { reason: SWEEP_ESCAPE_HATCH_REASON },
73
75
  }, async (_payload, ctx) => {
76
+ const runner = ctx.services.jobRunner;
77
+ const isJobPending = runner?.isJobPending?.bind(runner);
78
+ if (!isJobPending) {
79
+ // Fail closed: closing would erase the PII key of a delivery that may still run.
80
+ ctx.obs.log.warn("job runner cannot report job state, abandoned dispatches are not swept");
81
+ return;
82
+ }
74
83
  await sweepAbandonedDispatches({
75
84
  db: ctx.db.unsafeRaw(),
76
85
  registry: ctx.registry,
86
+ isDeliverJobPending: (aggregateId) => isJobPending(StepDispatcherJobs.deliver, deliverJobId(aggregateId)),
77
87
  startedBeforeIso: ctx.tz
78
88
  .now()
79
89
  .subtract({ hours: ABANDON_DISPATCH_AFTER_HOURS })
@@ -83,6 +93,7 @@ export function createStepDispatcherFeature() {
83
93
  });
84
94
  r.multiStreamProjection({
85
95
  name: "step-dispatcher",
96
+ irreversibleWithoutEntryHandler: "per-dispatch-record-key",
86
97
  apply: {
87
98
  [STEP_DISPATCH_REQUESTED_TYPE]: async (event, _tx, ctx) => {
88
99
  const stream = await ctx.loadAggregate(event.aggregateId);
@@ -4,6 +4,7 @@ export type SweepAbandonedArgs = {
4
4
  readonly db: DbRunner;
5
5
  readonly registry: Registry;
6
6
  readonly startedBeforeIso: string;
7
+ readonly isDeliverJobPending: (aggregateId: string) => Promise<boolean>;
7
8
  readonly onCloseFailure: (aggregateId: string, errorName: string) => void;
8
9
  readonly batchSize?: number;
9
10
  };
@@ -27,6 +27,9 @@ export async function sweepAbandonedDispatches(args) {
27
27
  callerFeature: STEP_DISPATCHER_FEATURE,
28
28
  });
29
29
  try {
30
+ // skip: the next run checks the stream again
31
+ if (await args.isDeliverJobPending(aggregateId))
32
+ continue;
30
33
  await closeAbandonedDispatch(applyContext, aggregateId);
31
34
  }
32
35
  catch (err) {
@@ -2,6 +2,8 @@
2
2
  // existed: their custom_data still carries the old tenantBinding. Once the
3
3
  // first sweep is done the job keeps sweeping for an hour (checkouts opened by
4
4
  // the previous release can still be paid), then does nothing.
5
+ // The tenant in custom_data is unverified: the key that signed the binding no longer exists.
6
+ // Only origin "api" and the one hour window bound that; losing a paid checkout would be worse.
5
7
  import { parseProviderConsentId, SubscriptionFoundationHandlers, } from "@cosmicdrift/kumiko-bundled-features/billing-foundation";
6
8
  import { createSystemUser, parseTenantId, } from "@cosmicdrift/kumiko-framework/engine";
7
9
  import { Temporal } from "@cosmicdrift/kumiko-types/temporal";
@@ -3,10 +3,19 @@
3
3
  // "not in the ledger" may only be waiting for the next sweep. Answering it with a retryable
4
4
  // 5xx makes Paddle deliver it again once the sweep has ledgered the checkout.
5
5
  import { SYSTEM_TENANT_ID } from "@cosmicdrift/kumiko-framework/engine";
6
+ import { createFallbackLogger } from "@cosmicdrift/kumiko-framework/logging";
6
7
  import { Temporal } from "@cosmicdrift/kumiko-types/temporal";
8
+ import { isOneOf } from "@cosmicdrift/kumiko-types/type-guards";
7
9
  import { isTakeoverWindowOver } from "./backfill-checkout-ledger.js";
8
10
  import { LEDGER_BACKFILL_MARKER_HANDLER_QN, } from "./ledger-backfill-marker.js";
9
11
  import { hasLegacyTenantBinding } from "./webhook-events.js";
12
+ const log = createFallbackLogger("subscription-paddle");
13
+ // A retry cannot fix these: the marker handler is missing, disabled or not permitted.
14
+ const MARKER_CONFIGURATION_ERROR_CODES = [
15
+ "access_denied",
16
+ "not_found",
17
+ "feature_disabled",
18
+ ];
10
19
  export async function shouldRedeliverLegacyCheckout(args) {
11
20
  if (!hasLegacyTenantBinding(args.event))
12
21
  return false;
@@ -16,9 +25,17 @@ export async function shouldRedeliverLegacyCheckout(args) {
16
25
  roles: [],
17
26
  payload: { markCompleted: false },
18
27
  });
19
- // Cannot tell whether the sweep is still open: err towards redelivery, Paddle retries a bounded number of times.
20
- if (!marker.isSuccess)
28
+ if (!marker.isSuccess) {
29
+ // tenantBinding is client-settable, so a permanent failure must not turn into endless 503s.
30
+ if (isOneOf(MARKER_CONFIGURATION_ERROR_CODES, marker.error.code)) {
31
+ log.warn("ledger backfill marker not readable, not redelivering", {
32
+ errorCode: marker.error.code,
33
+ });
34
+ return false;
35
+ }
36
+ // Transient or internal: Paddle redelivers only a bounded number of times, so retrying is safe.
21
37
  return true;
38
+ }
22
39
  const { completedAt } = marker.data; // @cast-boundary engine-payload
23
40
  if (completedAt === null)
24
41
  return true;
@@ -116,7 +116,7 @@ export function verifyAndParseStripeWebhook(runtime, options) {
116
116
  }
117
117
  // Only the checkout ledger can vouch for a new subscription, so `created` must name its session.
118
118
  const providerCheckoutId = normalizedType === SubscriptionEventTypes.created
119
- ? await findCheckoutSessionId(stripe, sub.id)
119
+ ? await findCheckoutSessionId(stripe, sub.id, event.created)
120
120
  : undefined;
121
121
  return {
122
122
  providerEventId: event.id,
@@ -131,20 +131,30 @@ export function verifyAndParseStripeWebhook(runtime, options) {
131
131
  };
132
132
  };
133
133
  }
134
- // Only a failing Stripe API call is answered with 503 so Stripe redelivers. A successful empty
135
- // list means the subscription has no checkout session: the created event then carries no
136
- // checkout id and the foundation ignores it as not in the ledger.
137
- async function findCheckoutSessionId(stripe, subscriptionId) {
134
+ // Stripe may emit `customer.subscription.created` before the session is linked to the subscription.
135
+ const SESSION_LINK_GRACE_SECONDS = 600;
136
+ // A failing Stripe API call, or an empty list for a young event, is answered with 503 so Stripe
137
+ // redelivers. An empty list for an older event means the subscription has no checkout session: the
138
+ // created event then carries no checkout id and the foundation ignores it as not in the ledger.
139
+ async function findCheckoutSessionId(stripe, subscriptionId, eventCreatedSeconds) {
140
+ let sessionId;
138
141
  try {
139
142
  const sessions = await stripe.checkout.sessions.list({
140
143
  subscription: subscriptionId,
141
144
  limit: 1,
142
145
  });
143
- return sessions.data[0]?.id;
146
+ sessionId = sessions.data[0]?.id;
144
147
  }
145
148
  catch (error) {
146
149
  throw transientProviderRejection(error);
147
150
  }
151
+ if (sessionId === undefined) {
152
+ const ageSeconds = Temporal.Now.instant().epochMilliseconds / 1000 - eventCreatedSeconds;
153
+ if (ageSeconds < SESSION_LINK_GRACE_SECONDS) {
154
+ throw transientProviderRejection(new Error(`no checkout session linked to ${subscriptionId} yet`));
155
+ }
156
+ }
157
+ return sessionId;
148
158
  }
149
159
  /** Maps a Stripe subscription's price/status/period-end/cancel_at onto the
150
160
  * foundation's normalized shape. Null when the subscription's price isn't
@@ -14,6 +14,7 @@ import { NotFoundError, VersionConflictError } from "@cosmicdrift/kumiko-framewo
14
14
  import { deleteRowsWithoutReplayableStream, getStreamVersion, getUnscopedStreamMaxVersionForSeed, } from "@cosmicdrift/kumiko-framework/event-store";
15
15
  import { createFallbackLogger } from "@cosmicdrift/kumiko-framework/logging";
16
16
  import { runEventStoreSeed } from "@cosmicdrift/kumiko-framework/seeding";
17
+ import { SYSTEM_USER_ID } from "@cosmicdrift/kumiko-types/identifiers";
17
18
  import { isPlainObject, propertyOf } from "@cosmicdrift/kumiko-types/type-guards";
18
19
  import { executor } from "./handlers/shared.js";
19
20
  import { evaluateTemplateWrite } from "./handlers/template-gates.js";
@@ -285,24 +286,48 @@ const ALREADY_REMOVED_ERROR_CODES = new Set([
285
286
  new VersionConflictError({ entityId: "", expectedVersion: 0, currentVersion: 0 }).code,
286
287
  ]);
287
288
  const NOTIFICATION_SLUG_PATTERN = /^([^:]+):notify:[^:]+$/;
288
- function isOrphanedNotificationSlug(registry, slug) {
289
+ function orphanVerdictOf(registry, slug) {
289
290
  const feature = NOTIFICATION_SLUG_PATTERN.exec(slug)?.[1];
290
291
  if (feature === undefined)
291
- return false;
292
+ return "not-orphaned";
292
293
  const notifications = registry.getAllNotifications();
293
294
  if (notifications.has(slug))
294
- return false;
295
+ return "not-orphaned";
295
296
  const renamedAway = Array.from(notifications.values()).some((notification) => notification.renamedFrom?.includes(slug));
296
- return renamedAway || registry.getFeature(feature) !== undefined;
297
+ if (renamedAway)
298
+ return "renamed-away";
299
+ return registry.getFeature(feature) !== undefined ? "unknown-to-registry" : "not-orphaned";
300
+ }
301
+ // Seeds write as the system user; a row only the system user ever touched still holds seed text.
302
+ function isUneditedSeedRow(row) {
303
+ return (row.insertedById === SYSTEM_USER_ID &&
304
+ (row.modifiedById === null || row.modifiedById === SYSTEM_USER_ID));
297
305
  }
298
306
  // A removed or renamed notification leaves its seeded system rows behind; they would keep
299
- // showing up in the template overview. Tenant overrides may hold customer text, so they stay
300
- // and are only reported. Slugs of unmounted features are not ours to judge.
307
+ // showing up in the template overview. A notification that is merely unknown to this boot
308
+ // (conditional registration, older pod during a rolling deploy) only loses rows nobody edited.
309
+ // Tenant overrides may hold customer text, so they stay and are only reported. Slugs of
310
+ // unmounted features are not ours to judge.
301
311
  async function removeOrphanedNotificationTemplates(db, registry) {
302
312
  const rows = await selectMany(db, templateResourcesTable, {
303
313
  kind: "mail",
304
314
  });
305
- const orphans = rows.filter((row) => isOrphanedNotificationSlug(registry, row.slug));
315
+ const orphans = [];
316
+ for (const row of rows) {
317
+ const verdict = orphanVerdictOf(registry, row.slug);
318
+ if (verdict === "not-orphaned")
319
+ continue;
320
+ if (verdict === "unknown-to-registry" &&
321
+ row.tenantId === SYSTEM_TENANT_ID &&
322
+ !isUneditedSeedRow(row)) {
323
+ log.warn("edited system template of a notification unknown to this boot is kept", {
324
+ slug: row.slug,
325
+ locale: row.locale,
326
+ });
327
+ continue;
328
+ }
329
+ orphans.push(row);
330
+ }
306
331
  // skip: nothing orphaned
307
332
  if (orphans.length === 0)
308
333
  return;
@@ -3,6 +3,7 @@ import { dispatcherErrorText, substituteVariables, useDebouncedValue, usePrimiti
3
3
  import { HtmlMailFrame, LoadingState, ModeSwitch, PreviewWidthFrame, } from "@cosmicdrift/kumiko-renderer/web";
4
4
  import { isPlainObject } from "@cosmicdrift/kumiko-types/type-guards";
5
5
  import { useState } from "react";
6
+ import { fillDocumentVariables } from "./fill-document-variables.js";
6
7
  import { TemplateResolverQueries } from "./qualified-names.js";
7
8
  import { stringValuesOf } from "./string-values.js";
8
9
  const PREVIEW_DEBOUNCE_MS = 300;
@@ -37,5 +38,8 @@ export function BodyPreviewFrame({ body, bodyFormat, }) {
37
38
  // Markdown with the example values filled in.
38
39
  export const WebPreviewRenderer = ({ content, editFormat, variables, }) => {
39
40
  const isDocument = editFormat === "document";
40
- return (_jsx(BodyPreviewFrame, { body: isDocument ? content : substituteVariables(content, stringValuesOf(variables)), bodyFormat: isDocument ? "document" : "markdown" }));
41
+ const examples = stringValuesOf(variables);
42
+ return (_jsx(BodyPreviewFrame, { body: isDocument
43
+ ? fillDocumentVariables(content, examples)
44
+ : substituteVariables(content, examples), bodyFormat: isDocument ? "document" : "markdown" }));
41
45
  };
@@ -1,4 +1,4 @@
1
- import { fetchOne } from "@cosmicdrift/kumiko-framework/db";
1
+ import { fetchOne, runInOwnTransaction } from "@cosmicdrift/kumiko-framework/db";
2
2
  import { hasMailTranslations, mailT } from "@cosmicdrift/kumiko-framework/i18n";
3
3
  import { parseRoles } from "@cosmicdrift/kumiko-framework/utils";
4
4
  import { Temporal } from "@cosmicdrift/kumiko-types/temporal";
@@ -11,7 +11,7 @@ import { activityBase, decideInactivityAction, foldActivity, resetWarnings, } fr
11
11
  import { signKeepAccountToken } from "./keep-token.js";
12
12
  import { InactivityWarningNotificationType, inactivityMailTemplateLocale, } from "./mail-notifications.js";
13
13
  import { resolveInactivityRule } from "./options.js";
14
- import { isInactivityCycleCurrent, loadInactivityState, loadNewestSessionActivity, saveInactivityState, } from "./state-store.js";
14
+ import { isInactivityCycleCurrent, loadInactivityState, loadNewestSessionActivity, lockInactivityCycle, saveInactivityState, } from "./state-store.js";
15
15
  // Links outlive the deadline a little so a late click still counts as a reaction.
16
16
  const KEEP_LINK_GRACE_MINUTES = 14 * 24 * 60;
17
17
  const MS_PER_MINUTE = 60_000;
@@ -118,6 +118,29 @@ async function sendWarningMails(args) {
118
118
  }
119
119
  return delivered;
120
120
  }
121
+ // The probes and mails before this are slow; a keep link redeemed meanwhile must not end in a
122
+ // deletion request. Check and request share one transaction under the lock the redemption takes.
123
+ async function requestDestructionUnlessKept(ctx, registry, tenantId, stored, now) {
124
+ return runInOwnTransaction(ctx.db, async (txDb) => {
125
+ const runner = txDb.unsafeRaw();
126
+ await lockInactivityCycle(runner, tenantId);
127
+ if (stored !== null && !(await isInactivityCycleCurrent(txDb, stored.cycleId)))
128
+ return false;
129
+ const result = await requestTenantDestruction({
130
+ tenantId,
131
+ actor: ctx.systemUser,
132
+ now,
133
+ db: txDb,
134
+ runner,
135
+ registry,
136
+ revokeSessions: true,
137
+ });
138
+ if (!result.isSuccess) {
139
+ throw new Error(`tenant-inactivity: destruction request for ${tenantId} failed`);
140
+ }
141
+ return true;
142
+ });
143
+ }
121
144
  async function evaluate(ctx, options, tenantId, rule, stored, now) {
122
145
  const initial = stored ?? emptyState(now);
123
146
  const folded = foldActivity(initial, await loadNewestSessionActivity(ctx.db));
@@ -151,21 +174,9 @@ async function evaluate(ctx, options, tenantId, rule, stored, now) {
151
174
  }
152
175
  if (!ctx.registry)
153
176
  throw new Error("tenant-inactivity: ctx.registry required");
154
- // The probes and mails above are slow; a keep link redeemed meanwhile must not end in a deletion request.
155
- if (stored !== null && !(await isInactivityCycleCurrent(ctx.db, stored.cycleId)))
177
+ const requested = await requestDestructionUnlessKept(ctx, ctx.registry, tenantId, stored, now);
178
+ if (!requested)
156
179
  return state;
157
- const result = await requestTenantDestruction({
158
- tenantId,
159
- actor: ctx.systemUser,
160
- now,
161
- db: ctx.db,
162
- runner: ctx.db.unsafeRaw(),
163
- registry: ctx.registry,
164
- revokeSessions: true,
165
- });
166
- if (!result.isSuccess) {
167
- throw new Error(`tenant-inactivity: destruction request for ${tenantId} failed`);
168
- }
169
180
  // If the owner cancels the request, a fresh cycle starts instead of an instant second request.
170
181
  return startNewCycle({ ...state, lastActivityAt: now });
171
182
  }
@@ -2,7 +2,9 @@ import { fetchOne, updateMany } from "@cosmicdrift/kumiko-framework/db";
2
2
  import { defineWriteHandler } from "@cosmicdrift/kumiko-framework/engine";
3
3
  import { UnprocessableError, writeFailure } from "@cosmicdrift/kumiko-framework/errors";
4
4
  import * as z from "zod";
5
+ import { tenantTable } from "../../tenant/index.js";
5
6
  import { redeemKeepAccountToken } from "../keep-token.js";
7
+ import { lockInactivityCycle } from "../state-store.js";
6
8
  import { tenantInactivityStateTable } from "../state-table.js";
7
9
  const KEEP_ACCOUNT_ESCAPE_HATCH_REASON = "the anonymous link holder has no tenant scope; the tenant comes from the signed token and every statement filters by that tenantId";
8
10
  export function createKeepAccountHandler(opts) {
@@ -33,6 +35,11 @@ export function createKeepAccountHandler(opts) {
33
35
  return row?.cycleId ?? null;
34
36
  },
35
37
  commitKeep: async (tenantId, cycleId) => {
38
+ await lockInactivityCycle(runner, tenantId);
39
+ // A destruction request that won the lock owns the tenant now; reporting "kept" would be a lie.
40
+ const tenant = await fetchOne(runner, tenantTable, { id: tenantId });
41
+ if (tenant?.status !== "active")
42
+ return false;
36
43
  const updated = await updateMany(runner, tenantInactivityStateTable, {
37
44
  lastActivityAt: now,
38
45
  warningsSent: 0,
@@ -1,4 +1,4 @@
1
- import type { TenantDb } from "@cosmicdrift/kumiko-framework/db";
1
+ import { type DbRunner, type TenantDb } from "@cosmicdrift/kumiko-framework/db";
2
2
  import { Temporal } from "@cosmicdrift/kumiko-types/temporal";
3
3
  import type { InactivityState } from "./inactivity-plan.ts";
4
4
  export type StoredInactivityState = InactivityState & {
@@ -7,5 +7,6 @@ export type StoredInactivityState = InactivityState & {
7
7
  export declare function loadInactivityState(db: TenantDb): Promise<StoredInactivityState | null>;
8
8
  export declare function isSameInactivityState(a: StoredInactivityState | null, b: StoredInactivityState): boolean;
9
9
  export declare function saveInactivityState(db: TenantDb, previous: StoredInactivityState | null, next: StoredInactivityState): Promise<void>;
10
+ export declare function lockInactivityCycle(runner: DbRunner, tenantId: string): Promise<void>;
10
11
  export declare function isInactivityCycleCurrent(db: TenantDb, cycleId: string): Promise<boolean>;
11
12
  export declare function loadNewestSessionActivity(db: TenantDb): Promise<Temporal.Instant | null>;
@@ -1,6 +1,8 @@
1
+ import { acquireNamespacedAdvisoryLock, } from "@cosmicdrift/kumiko-framework/db";
1
2
  import { Temporal } from "@cosmicdrift/kumiko-types/temporal";
2
3
  import { userSessionTable } from "../sessions/index.js";
3
4
  import { tenantInactivityStateTable } from "./state-table.js";
5
+ const CYCLE_LOCK_NAMESPACE = 0x696e6163; // 'inac'
4
6
  const EPOCH = Temporal.Instant.fromEpochMilliseconds(0);
5
7
  export async function loadInactivityState(db) {
6
8
  const row = await db.fetchOne(tenantInactivityStateTable, { tenantId: db.tenantId });
@@ -47,6 +49,11 @@ export async function saveInactivityState(db, previous, next) {
47
49
  });
48
50
  }
49
51
  }
52
+ // Serializes the destruction request against keep-link redemption: both hold this lock while they
53
+ // decide, so exactly one of them wins and the other sees the result.
54
+ export async function lockInactivityCycle(runner, tenantId) {
55
+ await acquireNamespacedAdvisoryLock(runner, CYCLE_LOCK_NAMESPACE, tenantId);
56
+ }
50
57
  export async function isInactivityCycleCurrent(db, cycleId) {
51
58
  const row = await db.fetchOne(tenantInactivityStateTable, { tenantId: db.tenantId });
52
59
  return !row || row.cycleId === cycleId;
@@ -83,6 +83,7 @@ export function createTenantLifecycleFeature() {
83
83
  r.job({
84
84
  name: "run-tenant-destruction",
85
85
  trigger: { cron: "0 * * * * *", wakesSleepingApp: false },
86
+ irreversibleWithoutEntryHandler: "high-risk-or-cron-pipeline",
86
87
  concurrency: "skip",
87
88
  escapeHatch: { reason: RUN_TENANT_DESTRUCTION_REASON },
88
89
  handler: async (_payload, ctx) => {
@@ -1,4 +1,4 @@
1
- import { decryptStoredPii } from "../shared/index.js";
1
+ import { decryptStoredPii, normalizeEmail } from "../shared/index.js";
2
2
  import { userTable } from "./schema/user.js";
3
3
  // Only a verified owner may see or erase rows matched by email. Forget keeps emailVerified but has
4
4
  // already rewritten the email, hence the pre-tx copy.
@@ -9,6 +9,6 @@ export async function resolveVerifiedUserEmail(ctx, piiDecryptReason) {
9
9
  if (row?.emailVerified !== true)
10
10
  return null;
11
11
  if (ctx.userEmailBeforeDelete)
12
- return ctx.userEmailBeforeDelete.toLowerCase();
13
- return (await decryptStoredPii(row.email, "email", piiDecryptReason)).toLowerCase();
12
+ return normalizeEmail(ctx.userEmailBeforeDelete);
13
+ return normalizeEmail(await decryptStoredPii(row.email, "email", piiDecryptReason));
14
14
  }
@@ -512,6 +512,7 @@ export function createUserDataRightsFeature(opts = {}) {
512
512
  r.job({
513
513
  name: "run-forget-cleanup",
514
514
  trigger: { maintenance: true },
515
+ irreversibleWithoutEntryHandler: "high-risk-or-cron-pipeline",
515
516
  concurrency: "skip",
516
517
  escapeHatch: { reason: RUN_FORGET_CLEANUP_REASON },
517
518
  handler: async (_payload, ctx) => {
@@ -1,9 +1,10 @@
1
1
  import { selectMany } from "@cosmicdrift/kumiko-framework/db";
2
2
  import { createSystemUser, defineWriteHandler, parseTenantId, } from "@cosmicdrift/kumiko-framework/engine";
3
3
  import { InternalError, NotFoundError, UnprocessableError, writeFailure, } from "@cosmicdrift/kumiko-framework/errors";
4
+ import { normalizeEmail } from "../../shared/index.js";
4
5
  import { cancelPendingInvitation, INVITATION_STATUS, tenantInvitationsTable, } from "../../tenant/index.js";
5
6
  import { isOpenWaitlistStatus } from "../entity.js";
6
- import { adminAccess, isTenantMember, normalizeEmail, platformActor, waitlistDb, waitlistExecutor, } from "../lib.js";
7
+ import { adminAccess, isTenantMember, platformActor, waitlistDb, waitlistExecutor, } from "../lib.js";
7
8
  import { WaitlistIdSchema } from "../payloads.js";
8
9
  import { WAITLIST_STATUS, WaitlistErrors } from "../web/constants.js";
9
10
  // An invited entry already has a live invitation link; rejecting must kill it,
@@ -2,8 +2,8 @@ import { acquireNamespacedAdvisoryLock, createSystemDbView, createTenantDb, runI
2
2
  import { defineWriteHandler, } from "@cosmicdrift/kumiko-framework/engine";
3
3
  import { InternalError } from "@cosmicdrift/kumiko-framework/errors";
4
4
  import { Temporal } from "@cosmicdrift/kumiko-types/temporal";
5
- import { sendBestEffort } from "../../shared/index.js";
6
- import { normalizeEmail, platformActor, waitlistDb, waitlistExecutor } from "../lib.js";
5
+ import { normalizeEmail, sendBestEffort } from "../../shared/index.js";
6
+ import { platformActor, waitlistDb, waitlistExecutor } from "../lib.js";
7
7
  import { resolveWaitlistMailLocale, waitlistAdminNoticeVariables, waitlistConfirmationVariables, } from "../mail.js";
8
8
  import { DEFAULT_SUBMIT_EMAIL_RATE_LIMITS, DEFAULT_SUBMIT_RATE_LIMIT, } from "../options.js";
9
9
  import { WaitlistSubmitSchema } from "../payloads.js";
@@ -1,6 +1,7 @@
1
1
  import { createHash } from "node:crypto";
2
2
  import { InternalError } from "@cosmicdrift/kumiko-framework/errors";
3
- import { normalizeEmail, platformActor, waitlistExecutor } from "./lib.js";
3
+ import { normalizeEmail } from "../shared/index.js";
4
+ import { platformActor, waitlistExecutor } from "./lib.js";
4
5
  import { WAITLIST_FIELD_LIMITS } from "./web/constants.js";
5
6
  // RFC 4122 name-based UUID (v5 layout, fixed namespace) so a re-run finds the entry
6
7
  // it created before without matching on encrypted personal data.
@@ -28,7 +28,6 @@ export declare const waitlistExecutor: import("@cosmicdrift/kumiko-types/event-s
28
28
  readonly status: string;
29
29
  readonly submittedAt: Temporal.Instant;
30
30
  }>;
31
- export declare function normalizeEmail(email: string): string;
32
31
  export declare function waitlistDb(ctx: Pick<AppContext, "systemDb">): TenantDb;
33
32
  export declare function platformActor(): SessionUser;
34
33
  export declare function isTenantMember(db: TenantDb, email: string, tenantId: TenantId): Promise<boolean>;