@cosmicdrift/kumiko-samples 0.414.0 → 0.416.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 (142) hide show
  1. package/package.json +1 -1
  2. package/packages/bundled-features/package.json +21 -1
  3. package/packages/bundled-features/src/agent-tools/changes.json +6 -0
  4. package/packages/bundled-features/src/agent-tools/tool-catalog.ts +20 -1
  5. package/packages/bundled-features/src/agent-tools/tool-dispatch.ts +19 -5
  6. package/packages/bundled-features/src/auth-email-password/signup-token-store.ts +2 -3
  7. package/packages/bundled-features/src/auth-email-password/web/session.tsx +2 -1
  8. package/packages/bundled-features/src/auth-mfa/changes.json +6 -0
  9. package/packages/bundled-features/src/billing-foundation/changes.json +24 -0
  10. package/packages/bundled-features/src/billing-foundation/checkout-core.ts +11 -0
  11. package/packages/bundled-features/src/billing-foundation/checkout-ledger.ts +8 -0
  12. package/packages/bundled-features/src/billing-foundation/events.ts +7 -5
  13. package/packages/bundled-features/src/billing-foundation/handlers/create-checkout-session.write.ts +2 -0
  14. package/packages/bundled-features/src/billing-foundation/handlers/process-event.write.ts +76 -24
  15. package/packages/bundled-features/src/billing-foundation/handlers/process-payment-event.write.ts +5 -4
  16. package/packages/bundled-features/src/billing-foundation/handlers/start-plan-checkout.write.ts +2 -0
  17. package/packages/bundled-features/src/billing-foundation/webhook-handler.ts +2 -2
  18. package/packages/bundled-features/src/channel-whatsapp/changes.json +30 -0
  19. package/packages/bundled-features/src/channel-whatsapp/constants.ts +1 -0
  20. package/packages/bundled-features/src/channel-whatsapp/events.ts +4 -3
  21. package/packages/bundled-features/src/channel-whatsapp/graph-client.ts +37 -1
  22. package/packages/bundled-features/src/channel-whatsapp/inbound-handlers.ts +23 -2
  23. package/packages/bundled-features/src/channel-whatsapp/webhook-normalize.ts +27 -6
  24. package/packages/bundled-features/src/compliance-profiles/changes.json +5 -0
  25. package/packages/bundled-features/src/compliance-profiles/handlers/set-profile.write.ts +2 -0
  26. package/packages/bundled-features/src/data-retention/feature.ts +1 -0
  27. package/packages/bundled-features/src/delivery/changes.json +6 -0
  28. package/packages/bundled-features/src/delivery/handlers/opted-in-user-ids.query.ts +12 -3
  29. package/packages/bundled-features/src/document-ingest-foundation/changes.json +6 -0
  30. package/packages/bundled-features/src/document-ingest-foundation/feature.ts +1 -0
  31. package/packages/bundled-features/src/document-ingest-foundation/report-ingest-progress.ts +3 -1
  32. package/packages/bundled-features/src/documents/changes.json +6 -0
  33. package/packages/bundled-features/src/documents/feature.ts +10 -5
  34. package/packages/bundled-features/src/form-draft/feature.ts +1 -0
  35. package/packages/bundled-features/src/handbook-knowledge/README.md +64 -0
  36. package/packages/bundled-features/src/handbook-knowledge/changes.json +8 -0
  37. package/packages/bundled-features/src/handbook-knowledge/constants.ts +8 -0
  38. package/packages/bundled-features/src/handbook-knowledge/feature.ts +34 -0
  39. package/packages/bundled-features/src/handbook-knowledge/handbook-index.ts +66 -0
  40. package/packages/bundled-features/src/handbook-knowledge/handlers.ts +77 -0
  41. package/packages/bundled-features/src/handbook-knowledge/index.ts +10 -0
  42. package/packages/bundled-features/src/helpdesk/changes.json +6 -0
  43. package/packages/bundled-features/src/helpdesk/feature.ts +1 -0
  44. package/packages/bundled-features/src/helpdesk/handlers/reply.write.ts +3 -3
  45. package/packages/bundled-features/src/helpdesk/handlers/report.write.ts +3 -2
  46. package/packages/bundled-features/src/helpdesk/handlers/submit.write.ts +3 -2
  47. package/packages/bundled-features/src/helpdesk/legacy-contact-streams.ts +3 -1
  48. package/packages/bundled-features/src/helpdesk/lib.ts +9 -4
  49. package/packages/bundled-features/src/inbound-mail-foundation/account-poll.ts +4 -1
  50. package/packages/bundled-features/src/inbound-mail-foundation/changes.json +6 -0
  51. package/packages/bundled-features/src/inbound-mail-foundation/content-refetch.ts +11 -4
  52. package/packages/bundled-features/src/inbound-mail-foundation/entities.ts +18 -9
  53. package/packages/bundled-features/src/inbound-mail-foundation/events.ts +18 -9
  54. package/packages/bundled-features/src/inbound-mail-foundation/handlers/connect-account.write.ts +2 -1
  55. package/packages/bundled-features/src/inbound-mail-foundation/handlers/forget-message.write.ts +6 -0
  56. package/packages/bundled-features/src/inbound-mail-foundation/handlers/ingest-message-schema.ts +18 -5
  57. package/packages/bundled-features/src/inbound-mail-foundation/normalize-inbound-message.ts +22 -8
  58. package/packages/bundled-features/src/inbound-mail-foundation/sanitize-inbound-html.ts +2 -5
  59. package/packages/bundled-features/src/managed-pages/web/page-edit-screen.tsx +11 -5
  60. package/packages/bundled-features/src/shared/changes.json +6 -0
  61. package/packages/bundled-features/src/shared/hmac-signature.ts +4 -2
  62. package/packages/bundled-features/src/shared/index.ts +2 -1
  63. package/packages/bundled-features/src/shared/normalize-email.ts +3 -0
  64. package/packages/bundled-features/src/shared/send-best-effort.ts +16 -6
  65. package/packages/bundled-features/src/signature/README.md +59 -0
  66. package/packages/bundled-features/src/signature/changes.json +15 -0
  67. package/packages/bundled-features/src/signature/entity.ts +192 -0
  68. package/packages/bundled-features/src/signature/feature.ts +125 -0
  69. package/packages/bundled-features/src/signature/files.ts +107 -0
  70. package/packages/bundled-features/src/signature/grant.ts +79 -0
  71. package/packages/bundled-features/src/signature/handlers/anonymous.write.ts +88 -0
  72. package/packages/bundled-features/src/signature/handlers/cancel.write.ts +40 -0
  73. package/packages/bundled-features/src/signature/handlers/issue-link.write.ts +72 -0
  74. package/packages/bundled-features/src/signature/handlers/lifecycle.write.ts +99 -0
  75. package/packages/bundled-features/src/signature/handlers/link-internal.write.ts +261 -0
  76. package/packages/bundled-features/src/signature/handlers/request.write.ts +86 -0
  77. package/packages/bundled-features/src/signature/handlers/revoke-link.write.ts +23 -0
  78. package/packages/bundled-features/src/signature/handlers/sign-in-person.write.ts +69 -0
  79. package/packages/bundled-features/src/signature/i18n.ts +52 -0
  80. package/packages/bundled-features/src/signature/index.ts +33 -0
  81. package/packages/bundled-features/src/signature/lib.ts +125 -0
  82. package/packages/bundled-features/src/signature/options.ts +49 -0
  83. package/packages/bundled-features/src/signature/payloads.ts +71 -0
  84. package/packages/bundled-features/src/signature/png.ts +169 -0
  85. package/packages/bundled-features/src/signature/screens.ts +115 -0
  86. package/packages/bundled-features/src/signature/signature-page.ts +93 -0
  87. package/packages/bundled-features/src/signature/signing.ts +77 -0
  88. package/packages/bundled-features/src/signature/static-sign.ts +98 -0
  89. package/packages/bundled-features/src/signature/sweep.ts +161 -0
  90. package/packages/bundled-features/src/signature/user-data.ts +159 -0
  91. package/packages/bundled-features/src/signature/web/constants.ts +92 -0
  92. package/packages/bundled-features/src/signature/web/index.ts +31 -0
  93. package/packages/bundled-features/src/signature/web/pad.ts +147 -0
  94. package/packages/bundled-features/src/signature/web/signature-pad.tsx +82 -0
  95. package/packages/bundled-features/src/step-dispatcher/changes.json +6 -0
  96. package/packages/bundled-features/src/step-dispatcher/deliver-dispatch-request.ts +5 -2
  97. package/packages/bundled-features/src/step-dispatcher/feature.ts +14 -0
  98. package/packages/bundled-features/src/step-dispatcher/sweep-abandoned.ts +4 -0
  99. package/packages/bundled-features/src/subscription-paddle/backfill-checkout-ledger.ts +2 -0
  100. package/packages/bundled-features/src/subscription-paddle/changes.json +6 -0
  101. package/packages/bundled-features/src/subscription-paddle/redeliver-legacy-checkout.ts +23 -2
  102. package/packages/bundled-features/src/subscription-stripe/changes.json +12 -0
  103. package/packages/bundled-features/src/subscription-stripe/feature.ts +9 -0
  104. package/packages/bundled-features/src/subscription-stripe/plugin-methods.ts +7 -1
  105. package/packages/bundled-features/src/subscription-stripe/verify-webhook.ts +19 -5
  106. package/packages/bundled-features/src/template-resolver/changes.json +12 -0
  107. package/packages/bundled-features/src/template-resolver/seeding.ts +37 -7
  108. package/packages/bundled-features/src/template-resolver/web/web-preview-renderer.tsx +7 -1
  109. package/packages/bundled-features/src/tenant-inactivity/changes.json +6 -0
  110. package/packages/bundled-features/src/tenant-inactivity/check-inactive-tenants.ts +34 -16
  111. package/packages/bundled-features/src/tenant-inactivity/handlers/keep-account.write.ts +6 -0
  112. package/packages/bundled-features/src/tenant-inactivity/state-store.ts +12 -1
  113. package/packages/bundled-features/src/tenant-lifecycle/changes.json +6 -0
  114. package/packages/bundled-features/src/tenant-lifecycle/feature.ts +1 -0
  115. package/packages/bundled-features/src/user/resolve-verified-user-email.ts +3 -3
  116. package/packages/bundled-features/src/user-data-rights/feature.ts +1 -0
  117. package/packages/bundled-features/src/waitlist/handlers/reject.write.ts +1 -1
  118. package/packages/bundled-features/src/waitlist/handlers/submit.write.ts +2 -2
  119. package/packages/bundled-features/src/waitlist/import.ts +2 -1
  120. package/packages/bundled-features/src/waitlist/lib.ts +1 -5
  121. package/packages/bundled-features/src/waitlist/link-on-signup.ts +2 -2
  122. package/packages/bundled-features/src/workflow-runner/changes.json +6 -0
  123. package/packages/bundled-features/src/workflow-runner/handlers/resume-run.write.ts +4 -2
  124. package/samples/apps/admin-console/src/app/shell.tsx +1 -0
  125. package/samples/apps/use-all-bundled/feature-manifest.json +63 -1
  126. package/samples/apps/use-all-bundled/kumiko/migrations/0068_signature.rebuild.json +4 -0
  127. package/samples/apps/use-all-bundled/src/run-config.ts +35 -1
  128. package/samples/recipes/crypto-shredding-hr/README.md +11 -0
  129. package/samples/recipes/crypto-shredding-hr/src/feature.ts +27 -0
  130. package/samples/recipes/embedded/README.md +4 -0
  131. package/samples/recipes/embedded/src/entities/invoice.ts +6 -0
  132. package/samples/recipes/embedded/src/feature.ts +7 -1
  133. package/samples/recipes/embedded/src/handlers/invoice-receive.write.ts +1 -0
  134. package/samples/recipes/embedded/src/screens/invoice-receive.screen.ts +2 -0
  135. package/samples/recipes/handbook-knowledge/README.md +22 -0
  136. package/samples/recipes/handbook-knowledge/package.json +12 -0
  137. package/samples/recipes/handbook-knowledge/src/feature.ts +42 -0
  138. package/samples/recipes/record-detail-layout/src/feature.ts +36 -5
  139. package/samples/recipes/record-detail-layout/src/order-board.ts +10 -2
  140. package/samples/recipes/signature/README.md +21 -0
  141. package/samples/recipes/signature/package.json +13 -0
  142. package/samples/recipes/signature/src/feature.ts +26 -0
@@ -5,7 +5,10 @@
5
5
 
6
6
  import type { SignatureExtraRouteDeps } from "@cosmicdrift/kumiko-framework/api";
7
7
  import { SYSTEM_TENANT_ID } from "@cosmicdrift/kumiko-framework/engine";
8
+ import type { FrameworkErrorCode } from "@cosmicdrift/kumiko-framework/errors";
9
+ import { createFallbackLogger } from "@cosmicdrift/kumiko-framework/logging";
8
10
  import { Temporal } from "@cosmicdrift/kumiko-types/temporal";
11
+ import { isOneOf } from "@cosmicdrift/kumiko-types/type-guards";
9
12
  import { isTakeoverWindowOver } from "./backfill-checkout-ledger.ts";
10
13
  import {
11
14
  LEDGER_BACKFILL_MARKER_HANDLER_QN,
@@ -13,6 +16,15 @@ import {
13
16
  } from "./ledger-backfill-marker.ts";
14
17
  import { hasLegacyTenantBinding } from "./webhook-events.ts";
15
18
 
19
+ const log = createFallbackLogger("subscription-paddle");
20
+
21
+ // A retry cannot fix these: the marker handler is missing, disabled or not permitted.
22
+ const MARKER_CONFIGURATION_ERROR_CODES = [
23
+ "access_denied",
24
+ "not_found",
25
+ "feature_disabled",
26
+ ] as const satisfies readonly FrameworkErrorCode[];
27
+
16
28
  type IgnoredEvent = Parameters<typeof hasLegacyTenantBinding>[0];
17
29
 
18
30
  export async function shouldRedeliverLegacyCheckout(args: {
@@ -28,8 +40,17 @@ export async function shouldRedeliverLegacyCheckout(args: {
28
40
  roles: [],
29
41
  payload: { markCompleted: false },
30
42
  });
31
- // Cannot tell whether the sweep is still open: err towards redelivery, Paddle retries a bounded number of times.
32
- if (!marker.isSuccess) return true;
43
+ if (!marker.isSuccess) {
44
+ // tenantBinding is client-settable, so a permanent failure must not turn into endless 503s.
45
+ if (isOneOf(MARKER_CONFIGURATION_ERROR_CODES, marker.error.code)) {
46
+ log.warn("ledger backfill marker not readable, not redelivering", {
47
+ errorCode: marker.error.code,
48
+ });
49
+ return false;
50
+ }
51
+ // Transient or internal: Paddle redelivers only a bounded number of times, so retrying is safe.
52
+ return true;
53
+ }
33
54
  const { completedAt } = marker.data as LedgerBackfillMarkerResult; // @cast-boundary engine-payload
34
55
  if (completedAt === null) return true;
35
56
  return !isTakeoverWindowOver(completedAt, (args.now ?? Temporal.Now.instant)());
@@ -1,4 +1,16 @@
1
1
  [
2
+ {
3
+ "version": "0.416.0",
4
+ "type": "improvement",
5
+ "title": "Stripe checkout can accept promotion codes",
6
+ "detail": "The new option `allowPromotionCodes` sets `allow_promotion_codes` on every Checkout Session of the app, in subscription and payment mode. Coupons and promotion codes are created in the Stripe dashboard. Default false, so existing checkouts show no code field. The consumer-protection confirmation mail still shows the catalog price captured at consent, not the discounted amount."
7
+ },
8
+ {
9
+ "version": "0.415.0",
10
+ "type": "fix",
11
+ "title": "customer.subscription.created without a linked checkout session is redelivered while young",
12
+ "detail": "An empty checkout session list for a created event younger than ten minutes answers 503 so Stripe redelivers, instead of dropping the subscription as not in the ledger."
13
+ },
2
14
  {
3
15
  "version": "0.414.0",
4
16
  "type": "breaking",
@@ -132,6 +132,12 @@ export type SubscriptionStripeOptions = {
132
132
  * mode:"subscription" — Stripe rejects invoice_creation there; the
133
133
  * subscription's own invoicing covers it. */
134
134
  readonly paymentInvoiceCreation?: boolean;
135
+ /** Shows Stripe's promotion-code field in every checkout of this app.
136
+ * Default false, because the field shows even when no code exists. Codes
137
+ * and coupons are created in the Stripe dashboard, not in the app. The
138
+ * consumer-protection confirmation mail shows the catalog price captured
139
+ * at consent, not the discounted amount. */
140
+ readonly allowPromotionCodes?: boolean;
135
141
  /** Allowlist of Stripe price-ids a mode:"payment" (one-off) checkout may
136
142
  * target — checkout-core's `openCheckout` rejects any other priceId as
137
143
  * `unknown_price`. App-specific and empty by default: without an
@@ -241,6 +247,9 @@ export function createSubscriptionStripeFeature(
241
247
  ...(options.paymentInvoiceCreation !== undefined && {
242
248
  paymentInvoiceCreation: options.paymentInvoiceCreation,
243
249
  }),
250
+ ...(options.allowPromotionCodes !== undefined && {
251
+ allowPromotionCodes: options.allowPromotionCodes,
252
+ }),
244
253
  }),
245
254
  createPortalSession: createStripePortalSession(runtimes.ctx),
246
255
  cancelSubscription: createStripeCancelSubscription(runtimes.ctx),
@@ -45,6 +45,8 @@ export type StripeCheckoutSessionRuntimeOptions = {
45
45
  /** Whether a mode:"payment" checkout gets a Stripe invoice. Default true.
46
46
  * Never applied in mode:"subscription" — Stripe rejects invoice_creation there. */
47
47
  readonly paymentInvoiceCreation?: boolean;
48
+ /** Shows Stripe's promotion-code field in checkout. Default false. */
49
+ readonly allowPromotionCodes?: boolean;
48
50
  };
49
51
 
50
52
  // Stripe's own Locale union also accepts arbitrary strings, so the known set
@@ -114,7 +116,10 @@ function isUnknownCustomerStripeError(
114
116
 
115
117
  export function createStripeCheckoutSession(
116
118
  runtime: StripeCtxRuntime,
117
- { paymentInvoiceCreation = true }: StripeCheckoutSessionRuntimeOptions = {},
119
+ {
120
+ paymentInvoiceCreation = true,
121
+ allowPromotionCodes = false,
122
+ }: StripeCheckoutSessionRuntimeOptions = {},
118
123
  ) {
119
124
  return async (
120
125
  ctx: HandlerContext,
@@ -138,6 +143,7 @@ export function createStripeCheckoutSession(
138
143
  success_url: options.successUrl,
139
144
  cancel_url: options.cancelUrl,
140
145
  submit_type: "pay",
146
+ ...(allowPromotionCodes && { allow_promotion_codes: true }),
141
147
  ...(options.locale && { locale: mapAppLocaleToStripeLocale(options.locale) }),
142
148
  ...(options.submitMessage && {
143
149
  custom_text: {
@@ -167,7 +167,7 @@ export function verifyAndParseStripeWebhook(
167
167
  // Only the checkout ledger can vouch for a new subscription, so `created` must name its session.
168
168
  const providerCheckoutId =
169
169
  normalizedType === SubscriptionEventTypes.created
170
- ? await findCheckoutSessionId(stripe, sub.id)
170
+ ? await findCheckoutSessionId(stripe, sub.id, event.created)
171
171
  : undefined;
172
172
  return {
173
173
  providerEventId: event.id,
@@ -183,22 +183,36 @@ export function verifyAndParseStripeWebhook(
183
183
  };
184
184
  }
185
185
 
186
- // Only a failing Stripe API call is answered with 503 so Stripe redelivers. A successful empty
187
- // list means the subscription has no checkout session: the created event then carries no
188
- // checkout id and the foundation ignores it as not in the ledger.
186
+ // Stripe may emit `customer.subscription.created` before the session is linked to the subscription.
187
+ const SESSION_LINK_GRACE_SECONDS = 600;
188
+
189
+ // A failing Stripe API call, or an empty list for a young event, is answered with 503 so Stripe
190
+ // redelivers. An empty list for an older event means the subscription has no checkout session: the
191
+ // created event then carries no checkout id and the foundation ignores it as not in the ledger.
189
192
  async function findCheckoutSessionId(
190
193
  stripe: Stripe,
191
194
  subscriptionId: string,
195
+ eventCreatedSeconds: number,
192
196
  ): Promise<string | undefined> {
197
+ let sessionId: string | undefined;
193
198
  try {
194
199
  const sessions = await stripe.checkout.sessions.list({
195
200
  subscription: subscriptionId,
196
201
  limit: 1,
197
202
  });
198
- return sessions.data[0]?.id;
203
+ sessionId = sessions.data[0]?.id;
199
204
  } catch (error) {
200
205
  throw transientProviderRejection(error);
201
206
  }
207
+ if (sessionId === undefined) {
208
+ const ageSeconds = Temporal.Now.instant().epochMilliseconds / 1000 - eventCreatedSeconds;
209
+ if (ageSeconds < SESSION_LINK_GRACE_SECONDS) {
210
+ throw transientProviderRejection(
211
+ new Error(`no checkout session linked to ${subscriptionId} yet`),
212
+ );
213
+ }
214
+ }
215
+ return sessionId;
202
216
  }
203
217
 
204
218
  // =============================================================================
@@ -1,4 +1,16 @@
1
1
  [
2
+ {
3
+ "version": "0.415.0",
4
+ "type": "fix",
5
+ "title": "Orphan cleanup keeps edited system templates of notifications unknown to the booting registry",
6
+ "detail": "A system mail template of a mounted feature whose notification this boot does not register (conditional registration, older pod during a rolling deploy) is deleted only while the system user alone ever wrote it; an edited row is kept and logged with slug and locale. Rows of notifications renamed away through `renamedFrom` are still deleted."
7
+ },
8
+ {
9
+ "version": "0.415.0",
10
+ "type": "fix",
11
+ "title": "Web preview of document bodies fills the example values",
12
+ "detail": "The web preview target sent document bodies with unfilled variable chips. It now fills them with the example values like the snippet preview does."
13
+ },
2
14
  {
3
15
  "version": "0.414.0",
4
16
  "type": "improvement",
@@ -32,6 +32,7 @@ import {
32
32
  import { createFallbackLogger } from "@cosmicdrift/kumiko-framework/logging";
33
33
  import type { Dispatcher } from "@cosmicdrift/kumiko-framework/pipeline";
34
34
  import { runEventStoreSeed, type SeedIfExists } from "@cosmicdrift/kumiko-framework/seeding";
35
+ import { SYSTEM_USER_ID } from "@cosmicdrift/kumiko-types/identifiers";
35
36
  import { isPlainObject, propertyOf } from "@cosmicdrift/kumiko-types/type-guards";
36
37
  import { executor } from "./handlers/shared.ts";
37
38
  import { evaluateTemplateWrite } from "./handlers/template-gates.ts";
@@ -407,20 +408,33 @@ const ALREADY_REMOVED_ERROR_CODES: ReadonlySet<string> = new Set([
407
408
 
408
409
  const NOTIFICATION_SLUG_PATTERN = /^([^:]+):notify:[^:]+$/;
409
410
 
410
- function isOrphanedNotificationSlug(registry: Registry, slug: string): boolean {
411
+ type OrphanVerdict = "renamed-away" | "unknown-to-registry" | "not-orphaned";
412
+
413
+ function orphanVerdictOf(registry: Registry, slug: string): OrphanVerdict {
411
414
  const feature = NOTIFICATION_SLUG_PATTERN.exec(slug)?.[1];
412
- if (feature === undefined) return false;
415
+ if (feature === undefined) return "not-orphaned";
413
416
  const notifications = registry.getAllNotifications();
414
- if (notifications.has(slug)) return false;
417
+ if (notifications.has(slug)) return "not-orphaned";
415
418
  const renamedAway = Array.from(notifications.values()).some((notification) =>
416
419
  notification.renamedFrom?.includes(slug),
417
420
  );
418
- return renamedAway || registry.getFeature(feature) !== undefined;
421
+ if (renamedAway) return "renamed-away";
422
+ return registry.getFeature(feature) !== undefined ? "unknown-to-registry" : "not-orphaned";
423
+ }
424
+
425
+ // Seeds write as the system user; a row only the system user ever touched still holds seed text.
426
+ function isUneditedSeedRow(row: TemplateResourceRow): boolean {
427
+ return (
428
+ row.insertedById === SYSTEM_USER_ID &&
429
+ (row.modifiedById === null || row.modifiedById === SYSTEM_USER_ID)
430
+ );
419
431
  }
420
432
 
421
433
  // A removed or renamed notification leaves its seeded system rows behind; they would keep
422
- // showing up in the template overview. Tenant overrides may hold customer text, so they stay
423
- // and are only reported. Slugs of unmounted features are not ours to judge.
434
+ // showing up in the template overview. A notification that is merely unknown to this boot
435
+ // (conditional registration, older pod during a rolling deploy) only loses rows nobody edited.
436
+ // Tenant overrides may hold customer text, so they stay and are only reported. Slugs of
437
+ // unmounted features are not ours to judge.
424
438
  async function removeOrphanedNotificationTemplates(
425
439
  db: DbConnection,
426
440
  registry: Registry,
@@ -428,7 +442,23 @@ async function removeOrphanedNotificationTemplates(
428
442
  const rows = await selectMany<TemplateResourceRow>(db, templateResourcesTable, {
429
443
  kind: "mail",
430
444
  });
431
- const orphans = rows.filter((row) => isOrphanedNotificationSlug(registry, row.slug));
445
+ const orphans: TemplateResourceRow[] = [];
446
+ for (const row of rows) {
447
+ const verdict = orphanVerdictOf(registry, row.slug);
448
+ if (verdict === "not-orphaned") continue;
449
+ if (
450
+ verdict === "unknown-to-registry" &&
451
+ row.tenantId === SYSTEM_TENANT_ID &&
452
+ !isUneditedSeedRow(row)
453
+ ) {
454
+ log.warn("edited system template of a notification unknown to this boot is kept", {
455
+ slug: row.slug,
456
+ locale: row.locale,
457
+ });
458
+ continue;
459
+ }
460
+ orphans.push(row);
461
+ }
432
462
  // skip: nothing orphaned
433
463
  if (orphans.length === 0) return;
434
464
 
@@ -17,6 +17,7 @@ import {
17
17
  } from "@cosmicdrift/kumiko-renderer/web";
18
18
  import { isPlainObject } from "@cosmicdrift/kumiko-types/type-guards";
19
19
  import { type ReactNode, useState } from "react";
20
+ import { fillDocumentVariables } from "./fill-document-variables.ts";
20
21
  import { TemplateResolverQueries } from "./qualified-names.ts";
21
22
  import { stringValuesOf } from "./string-values.ts";
22
23
 
@@ -117,9 +118,14 @@ export const WebPreviewRenderer: PreviewRenderer = ({
117
118
  variables,
118
119
  }: PreviewRendererProps): ReactNode => {
119
120
  const isDocument = editFormat === "document";
121
+ const examples = stringValuesOf(variables);
120
122
  return (
121
123
  <BodyPreviewFrame
122
- body={isDocument ? content : substituteVariables(content, stringValuesOf(variables))}
124
+ body={
125
+ isDocument
126
+ ? fillDocumentVariables(content, examples)
127
+ : substituteVariables(content, examples)
128
+ }
123
129
  bodyFormat={isDocument ? "document" : "markdown"}
124
130
  />
125
131
  );
@@ -1,4 +1,10 @@
1
1
  [
2
+ {
3
+ "version": "0.415.0",
4
+ "type": "fix",
5
+ "title": "Keep-link redemption and the destruction request are serialized",
6
+ "detail": "The inactivity job checks the cycle and files the destruction request in one transaction under an advisory lock that the keep-account handler also takes. If the redemption wins, the job skips the request. If the request wins, the link is rejected as invalid instead of reporting a kept account for a tenant that is already in destroyRequested."
7
+ },
2
8
  {
3
9
  "version": "0.411.0",
4
10
  "type": "improvement",
@@ -1,5 +1,5 @@
1
- import { fetchOne, type TenantDb } from "@cosmicdrift/kumiko-framework/db";
2
- import type { JobContext, TenantId } from "@cosmicdrift/kumiko-framework/engine";
1
+ import { fetchOne, runInOwnTransaction, type TenantDb } from "@cosmicdrift/kumiko-framework/db";
2
+ import type { JobContext, Registry, TenantId } from "@cosmicdrift/kumiko-framework/engine";
3
3
  import { hasMailTranslations, mailT } from "@cosmicdrift/kumiko-framework/i18n";
4
4
  import { parseRoles } from "@cosmicdrift/kumiko-framework/utils";
5
5
  import { Temporal } from "@cosmicdrift/kumiko-types/temporal";
@@ -30,6 +30,7 @@ import {
30
30
  isInactivityCycleCurrent,
31
31
  loadInactivityState,
32
32
  loadNewestSessionActivity,
33
+ lockInactivityCycle,
33
34
  type StoredInactivityState,
34
35
  saveInactivityState,
35
36
  } from "./state-store.ts";
@@ -179,6 +180,35 @@ async function sendWarningMails(args: {
179
180
  return delivered;
180
181
  }
181
182
 
183
+ // The probes and mails before this are slow; a keep link redeemed meanwhile must not end in a
184
+ // deletion request. Check and request share one transaction under the lock the redemption takes.
185
+ async function requestDestructionUnlessKept(
186
+ ctx: JobContext,
187
+ registry: Registry,
188
+ tenantId: TenantId,
189
+ stored: StoredInactivityState | null,
190
+ now: Temporal.Instant,
191
+ ): Promise<boolean> {
192
+ return runInOwnTransaction(ctx.db, async (txDb) => {
193
+ const runner = txDb.unsafeRaw();
194
+ await lockInactivityCycle(runner, tenantId);
195
+ if (stored !== null && !(await isInactivityCycleCurrent(txDb, stored.cycleId))) return false;
196
+ const result = await requestTenantDestruction({
197
+ tenantId,
198
+ actor: ctx.systemUser,
199
+ now,
200
+ db: txDb,
201
+ runner,
202
+ registry,
203
+ revokeSessions: true,
204
+ });
205
+ if (!result.isSuccess) {
206
+ throw new Error(`tenant-inactivity: destruction request for ${tenantId} failed`);
207
+ }
208
+ return true;
209
+ });
210
+ }
211
+
182
212
  async function evaluate(
183
213
  ctx: JobContext,
184
214
  options: TenantInactivityOptions,
@@ -220,20 +250,8 @@ async function evaluate(
220
250
  }
221
251
 
222
252
  if (!ctx.registry) throw new Error("tenant-inactivity: ctx.registry required");
223
- // The probes and mails above are slow; a keep link redeemed meanwhile must not end in a deletion request.
224
- if (stored !== null && !(await isInactivityCycleCurrent(ctx.db, stored.cycleId))) return state;
225
- const result = await requestTenantDestruction({
226
- tenantId,
227
- actor: ctx.systemUser,
228
- now,
229
- db: ctx.db,
230
- runner: ctx.db.unsafeRaw(),
231
- registry: ctx.registry,
232
- revokeSessions: true,
233
- });
234
- if (!result.isSuccess) {
235
- throw new Error(`tenant-inactivity: destruction request for ${tenantId} failed`);
236
- }
253
+ const requested = await requestDestructionUnlessKept(ctx, ctx.registry, tenantId, stored, now);
254
+ if (!requested) return state;
237
255
  // If the owner cancels the request, a fresh cycle starts instead of an instant second request.
238
256
  return startNewCycle({ ...state, lastActivityAt: now });
239
257
  }
@@ -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.ts";
5
6
  import { redeemKeepAccountToken } from "../keep-token.ts";
7
+ import { lockInactivityCycle } from "../state-store.ts";
6
8
  import { tenantInactivityStateTable } from "../state-table.ts";
7
9
 
8
10
  const KEEP_ACCOUNT_ESCAPE_HATCH_REASON =
@@ -37,6 +39,10 @@ export function createKeepAccountHandler(opts: { readonly keepAccountTokenSecret
37
39
  return row?.cycleId ?? null;
38
40
  },
39
41
  commitKeep: async (tenantId, cycleId) => {
42
+ await lockInactivityCycle(runner, tenantId);
43
+ // A destruction request that won the lock owns the tenant now; reporting "kept" would be a lie.
44
+ const tenant = await fetchOne<{ status: string }>(runner, tenantTable, { id: tenantId });
45
+ if (tenant?.status !== "active") return false;
40
46
  const updated = await updateMany(
41
47
  runner,
42
48
  tenantInactivityStateTable,
@@ -1,4 +1,8 @@
1
- import type { TenantDb } from "@cosmicdrift/kumiko-framework/db";
1
+ import {
2
+ acquireNamespacedAdvisoryLock,
3
+ type DbRunner,
4
+ type TenantDb,
5
+ } from "@cosmicdrift/kumiko-framework/db";
2
6
  import { Temporal } from "@cosmicdrift/kumiko-types/temporal";
3
7
  import { userSessionTable } from "../sessions/index.ts";
4
8
  import type { InactivityState } from "./inactivity-plan.ts";
@@ -8,6 +12,7 @@ export type StoredInactivityState = InactivityState & { readonly cycleId: string
8
12
 
9
13
  type StateRow = StoredInactivityState & { readonly id: string };
10
14
 
15
+ const CYCLE_LOCK_NAMESPACE = 0x696e6163; // 'inac'
11
16
  const EPOCH = Temporal.Instant.fromEpochMilliseconds(0);
12
17
 
13
18
  export async function loadInactivityState(db: TenantDb): Promise<StoredInactivityState | null> {
@@ -64,6 +69,12 @@ export async function saveInactivityState(
64
69
  }
65
70
  }
66
71
 
72
+ // Serializes the destruction request against keep-link redemption: both hold this lock while they
73
+ // decide, so exactly one of them wins and the other sees the result.
74
+ export async function lockInactivityCycle(runner: DbRunner, tenantId: string): Promise<void> {
75
+ await acquireNamespacedAdvisoryLock(runner, CYCLE_LOCK_NAMESPACE, tenantId);
76
+ }
77
+
67
78
  export async function isInactivityCycleCurrent(db: TenantDb, cycleId: string): Promise<boolean> {
68
79
  const row = await db.fetchOne<StateRow>(tenantInactivityStateTable, { tenantId: db.tenantId });
69
80
  return !row || row.cycleId === cycleId;
@@ -1,4 +1,10 @@
1
1
  [
2
+ {
3
+ "version": "0.415.0",
4
+ "type": "fix",
5
+ "title": "Held-tenant destruction test tolerates the scheduled sweep finishing first",
6
+ "detail": "After the retention job releases a destroyHeld tenant, the scheduled sweep may already have moved it on to destroyed. The test now accepts destroying or destroyed and only asserts the retention override while the status is still destroying, reading the overrides first so the check stays meaningful."
7
+ },
2
8
  {
3
9
  "version": "0.414.0",
4
10
  "type": "fix",
@@ -157,6 +157,7 @@ export function createTenantLifecycleFeature(): FeatureDefinition {
157
157
  r.job({
158
158
  name: "run-tenant-destruction",
159
159
  trigger: { cron: "0 * * * * *", wakesSleepingApp: false },
160
+ irreversibleWithoutEntryHandler: "high-risk-or-cron-pipeline",
160
161
  concurrency: "skip",
161
162
  escapeHatch: { reason: RUN_TENANT_DESTRUCTION_REASON },
162
163
  handler: async (_payload, ctx) => {
@@ -1,5 +1,5 @@
1
1
  import type { UserDataHookCtx } from "@cosmicdrift/kumiko-framework/engine";
2
- import { decryptStoredPii } from "../shared/index.ts";
2
+ import { decryptStoredPii, normalizeEmail } from "../shared/index.ts";
3
3
  import { userTable } from "./schema/user.ts";
4
4
 
5
5
  // Only a verified owner may see or erase rows matched by email. Forget keeps emailVerified but has
@@ -12,6 +12,6 @@ export async function resolveVerifiedUserEmail(
12
12
  id: ctx.userId,
13
13
  });
14
14
  if (row?.emailVerified !== true) return null;
15
- if (ctx.userEmailBeforeDelete) return ctx.userEmailBeforeDelete.toLowerCase();
16
- return (await decryptStoredPii(row.email, "email", piiDecryptReason)).toLowerCase();
15
+ if (ctx.userEmailBeforeDelete) return normalizeEmail(ctx.userEmailBeforeDelete);
16
+ return normalizeEmail(await decryptStoredPii(row.email, "email", piiDecryptReason));
17
17
  }
@@ -708,6 +708,7 @@ export function createUserDataRightsFeature(opts: UserDataRightsOptions = {}): F
708
708
  r.job({
709
709
  name: "run-forget-cleanup",
710
710
  trigger: { maintenance: true },
711
+ irreversibleWithoutEntryHandler: "high-risk-or-cron-pipeline",
711
712
  concurrency: "skip",
712
713
  escapeHatch: { reason: RUN_FORGET_CLEANUP_REASON },
713
714
  handler: async (_payload, ctx) => {
@@ -12,6 +12,7 @@ import {
12
12
  type WriteFailure,
13
13
  writeFailure,
14
14
  } from "@cosmicdrift/kumiko-framework/errors";
15
+ import { normalizeEmail } from "../../shared/index.ts";
15
16
  import {
16
17
  cancelPendingInvitation,
17
18
  INVITATION_STATUS,
@@ -21,7 +22,6 @@ import { isOpenWaitlistStatus } from "../entity.ts";
21
22
  import {
22
23
  adminAccess,
23
24
  isTenantMember,
24
- normalizeEmail,
25
25
  platformActor,
26
26
  waitlistDb,
27
27
  waitlistExecutor,
@@ -12,8 +12,8 @@ import {
12
12
  } from "@cosmicdrift/kumiko-framework/engine";
13
13
  import { InternalError } from "@cosmicdrift/kumiko-framework/errors";
14
14
  import { Temporal } from "@cosmicdrift/kumiko-types/temporal";
15
- import { sendBestEffort } from "../../shared/index.ts";
16
- import { normalizeEmail, platformActor, waitlistDb, waitlistExecutor } from "../lib.ts";
15
+ import { normalizeEmail, sendBestEffort } from "../../shared/index.ts";
16
+ import { platformActor, waitlistDb, waitlistExecutor } from "../lib.ts";
17
17
  import {
18
18
  resolveWaitlistMailLocale,
19
19
  waitlistAdminNoticeVariables,
@@ -2,7 +2,8 @@ import { createHash } from "node:crypto";
2
2
  import type { TenantDb } from "@cosmicdrift/kumiko-framework/db";
3
3
  import { InternalError } from "@cosmicdrift/kumiko-framework/errors";
4
4
  import type { Temporal } from "@cosmicdrift/kumiko-types/temporal";
5
- import { normalizeEmail, platformActor, waitlistExecutor } from "./lib.ts";
5
+ import { normalizeEmail } from "../shared/index.ts";
6
+ import { platformActor, waitlistExecutor } from "./lib.ts";
6
7
  import { WAITLIST_FIELD_LIMITS, type WaitlistStatus } from "./web/constants.ts";
7
8
 
8
9
  export type WaitlistImportEntry = {
@@ -11,7 +11,7 @@ import {
11
11
  SYSTEM_TENANT_ID,
12
12
  type TenantId,
13
13
  } from "@cosmicdrift/kumiko-framework/engine";
14
- import { acknowledgedSystemDb } from "../shared/index.ts";
14
+ import { acknowledgedSystemDb, normalizeEmail } from "../shared/index.ts";
15
15
  import { tenantMembershipsTable } from "../tenant/index.ts";
16
16
  import { userTable } from "../user/index.ts";
17
17
  import { waitlistEntryEntity, waitlistEntryTable } from "./entity.ts";
@@ -24,10 +24,6 @@ export const waitlistExecutor = createEventStoreExecutor(waitlistEntryTable, wai
24
24
  entityName: "waitlistEntry",
25
25
  });
26
26
 
27
- export function normalizeEmail(email: string): string {
28
- return email.toLowerCase();
29
- }
30
-
31
27
  export function waitlistDb(ctx: Pick<AppContext, "systemDb">): TenantDb {
32
28
  return acknowledgedSystemDb(ctx, "waitlist", WAITLIST_CROSS_TENANT_REASON);
33
29
  }
@@ -7,10 +7,10 @@ import {
7
7
  import { type MultiStreamApplyFn, SYSTEM_TENANT_ID } from "@cosmicdrift/kumiko-framework/engine";
8
8
  import { parseRoles } from "@cosmicdrift/kumiko-framework/utils";
9
9
  import { Temporal } from "@cosmicdrift/kumiko-types/temporal";
10
- import { decryptStoredPii } from "../shared/index.ts";
10
+ import { decryptStoredPii, normalizeEmail } from "../shared/index.ts";
11
11
  import { tenantMembershipsTable } from "../tenant/index.ts";
12
12
  import { userTable } from "../user/index.ts";
13
- import { normalizeEmail, platformActor, waitlistExecutor } from "./lib.ts";
13
+ import { platformActor, waitlistExecutor } from "./lib.ts";
14
14
  import { DEFAULT_OWN_TENANT_INVITE_ROLE, WAITLIST_STATUS } from "./web/constants.ts";
15
15
 
16
16
  const PII_DECRYPT_REASON = "waitlist:link-on-signup";
@@ -1,4 +1,10 @@
1
1
  [
2
+ {
3
+ "version": "0.415.0",
4
+ "type": "fix",
5
+ "title": "Resumed steps receive a registered TenantDb",
6
+ "detail": "The resume-run handler handed steps a spread copy of the tenant db. Framework helpers that look a TenantDb up by identity (executors, runInOwnTransaction) rejected that copy with \"TenantDb not built by createTenantDb\". The steps now get the same db with outsideTransaction dropped in place."
7
+ },
2
8
  {
3
9
  "version": "0.391.1",
4
10
  "type": "improvement",
@@ -32,6 +32,7 @@
32
32
 
33
33
  import { fetchOne, type TenantDb } from "@cosmicdrift/kumiko-framework/db";
34
34
  import {
35
+ attachOutsideTransaction,
35
36
  buildPipelineSteps,
36
37
  computeDefinitionFingerprint,
37
38
  describeWorkflowStepError,
@@ -362,11 +363,12 @@ async function runResumedPipeline(ctx: HandlerContext, db: TenantDb, input: Resu
362
363
  stepIndex,
363
364
  );
364
365
 
365
- // The handler is system-scoped, so ctx.db is unusable; the steps still read the database clock.
366
+ // The handler is system-scoped, so ctx.db is unusable; the steps get the tenant db without
367
+ // outsideTransaction. Dropped in place: a copy would fall out of the identity-keyed TenantDb registries.
366
368
  const outcome = await runStepList(
367
369
  steps,
368
370
  triggerEvent,
369
- { ...ctx, db: { ...db, outsideTransaction: undefined } },
371
+ { ...ctx, db: attachOutsideTransaction(db, undefined) },
370
372
  stepsAcc,
371
373
  {},
372
374
  workflowCtx,
@@ -34,6 +34,7 @@ export function AppShell({
34
34
  <WorkspaceShell
35
35
  brand={<Brand />}
36
36
  schema={schema}
37
+ navStyle="plain"
37
38
  topbarActions={
38
39
  <DefaultTopbarActions
39
40
  lightIcon={<Sun className="h-4 w-4" />}