@cosmicdrift/kumiko-bundled-features 0.404.0 → 0.405.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 (131) hide show
  1. package/dist/auth-email-password/mail-notifications.d.ts +3 -3
  2. package/dist/auth-email-password/mail-notifications.js +10 -34
  3. package/dist/auth-email-password/web/auth-gate.js +4 -0
  4. package/dist/auth-email-password/web/default-topbar-actions.d.ts +6 -1
  5. package/dist/auth-email-password/web/default-topbar-actions.js +2 -2
  6. package/dist/auth-email-password/web/index.d.ts +2 -0
  7. package/dist/auth-email-password/web/index.js +1 -0
  8. package/dist/auth-email-password/web/invite-accept-screen.js +6 -41
  9. package/dist/auth-email-password/web/tenant-label.d.ts +2 -0
  10. package/dist/auth-email-password/web/tenant-label.js +10 -0
  11. package/dist/auth-email-password/web/tenant-menu-items.js +2 -7
  12. package/dist/auth-email-password/web/tenant-switcher.js +5 -12
  13. package/dist/auth-email-password/web/use-redirect-authed-from-login.d.ts +7 -0
  14. package/dist/auth-email-password/web/use-redirect-authed-from-login.js +30 -0
  15. package/dist/auth-foundation/feature.js +8 -21
  16. package/dist/auth-mfa/handlers/reencrypt.job.js +7 -15
  17. package/dist/auth-mfa/hmac-token-codec.d.ts +6 -1
  18. package/dist/auth-mfa/hmac-token-codec.js +8 -10
  19. package/dist/auth-mfa/mfa-challenge-token.js +2 -8
  20. package/dist/auth-mfa/mfa-preauth-setup-token.js +2 -8
  21. package/dist/auth-mfa/mfa-setup-token.d.ts +2 -8
  22. package/dist/auth-mfa/mfa-setup-token.js +8 -45
  23. package/dist/billing-foundation/consumer-protection/termination-revoke.js +3 -11
  24. package/dist/billing-foundation/feature.js +1 -5
  25. package/dist/billing-foundation/handlers/process-event.write.js +2 -6
  26. package/dist/billing-foundation/handlers/process-payment-event.write.js +2 -6
  27. package/dist/billing-foundation/index.d.ts +2 -0
  28. package/dist/billing-foundation/index.js +2 -0
  29. package/dist/billing-foundation/projection.js +12 -21
  30. package/dist/billing-foundation/provider-event-seen.d.ts +5 -0
  31. package/dist/billing-foundation/provider-event-seen.js +7 -0
  32. package/dist/billing-foundation/provider-shared.d.ts +11 -0
  33. package/dist/billing-foundation/provider-shared.js +44 -0
  34. package/dist/billing-foundation/tenant-destroy-hook.js +5 -4
  35. package/dist/channel-email/feature.js +1 -1
  36. package/dist/config/handlers/reencrypt.job.js +7 -15
  37. package/dist/delivery/delivery-service.js +2 -8
  38. package/dist/file-derivatives/feature.js +9 -21
  39. package/dist/file-foundation/feature.js +2 -6
  40. package/dist/files-tenant-data/hooks.js +1 -6
  41. package/dist/folders/feature.js +2 -9
  42. package/dist/folders/web/folder-manager.js +7 -26
  43. package/dist/folders/web/folder-section.js +5 -24
  44. package/dist/form-draft/handlers/save.write.d.ts +9 -0
  45. package/dist/form-draft/handlers/save.write.js +3 -7
  46. package/dist/inbound-mail-foundation/feature.js +2 -6
  47. package/dist/inbound-mail-foundation/handlers/thread-rollup.js +1 -0
  48. package/dist/inbound-mail-foundation/oauth-state.js +5 -13
  49. package/dist/inbound-mail-foundation/tenant-destroy-hook.d.ts +1 -1
  50. package/dist/inbound-mail-foundation/tenant-destroy-hook.js +3 -18
  51. package/dist/jobs/handlers/tenant-failures.query.js +1 -15
  52. package/dist/jobs/handlers/tenant-runs.query.js +1 -14
  53. package/dist/jobs/job-run-logger.js +19 -23
  54. package/dist/jobs/parse-subject.d.ts +1 -0
  55. package/dist/jobs/parse-subject.js +15 -0
  56. package/dist/ledger/feature.js +2 -8
  57. package/dist/mail-foundation/feature.js +3 -7
  58. package/dist/managed-pages/render-page-body.js +4 -12
  59. package/dist/notes-history/feature.js +2 -9
  60. package/dist/personal-access-tokens/handlers/list.query.js +1 -9
  61. package/dist/personal-access-tokens/hash.js +2 -2
  62. package/dist/personal-access-tokens/parse-scope-names.d.ts +1 -0
  63. package/dist/personal-access-tokens/parse-scope-names.js +10 -0
  64. package/dist/personal-access-tokens/resolver.js +1 -9
  65. package/dist/renderer-foundation/feature.js +3 -14
  66. package/dist/secrets/handlers/rotate.job.js +7 -18
  67. package/dist/shared/collect-extension-options.d.ts +4 -0
  68. package/dist/shared/collect-extension-options.js +8 -0
  69. package/dist/shared/hmac-signature.d.ts +2 -0
  70. package/dist/shared/hmac-signature.js +10 -0
  71. package/dist/shared/index.d.ts +6 -0
  72. package/dist/shared/index.js +6 -0
  73. package/dist/shared/is-unique-constraint-failure.d.ts +2 -0
  74. package/dist/shared/is-unique-constraint-failure.js +7 -0
  75. package/dist/shared/mail-locale-templates.d.ts +12 -0
  76. package/dist/shared/mail-locale-templates.js +36 -0
  77. package/dist/shared/resolve-feature-access.d.ts +7 -0
  78. package/dist/shared/resolve-feature-access.js +8 -0
  79. package/dist/shared/signed-token.js +4 -14
  80. package/dist/shared/single-use-token-store.js +2 -2
  81. package/dist/shared/stream-tenant-derived-state.js +1 -5
  82. package/dist/shared/tenant-db-cache.d.ts +3 -0
  83. package/dist/shared/tenant-db-cache.js +14 -0
  84. package/dist/shared/web/status-banner.d.ts +15 -0
  85. package/dist/shared/web/status-banner.js +13 -0
  86. package/dist/shared/web/use-dispatched-writes.d.ts +8 -0
  87. package/dist/shared/web/use-dispatched-writes.js +29 -0
  88. package/dist/subscription-paddle/feature.js +2 -15
  89. package/dist/subscription-paddle/price-methods.d.ts +2 -5
  90. package/dist/subscription-paddle/price-methods.js +5 -26
  91. package/dist/subscription-paddle/runtime.d.ts +1 -1
  92. package/dist/subscription-paddle/runtime.js +3 -16
  93. package/dist/subscription-stripe/feature.js +2 -17
  94. package/dist/subscription-stripe/plugin-methods.d.ts +2 -5
  95. package/dist/subscription-stripe/plugin-methods.js +3 -18
  96. package/dist/subscription-stripe/runtime.js +3 -19
  97. package/dist/tags/feature.js +2 -9
  98. package/dist/tags/web/tag-manager.js +5 -24
  99. package/dist/tags/web/tag-section.js +3 -12
  100. package/dist/template-resolver/document-sanitizer.js +3 -2
  101. package/dist/template-resolver/handlers/tenant-overrides.query.js +3 -9
  102. package/dist/template-resolver/web/collection-entry-create-form.js +1 -0
  103. package/dist/tenant/handlers/decrypt-member-users.d.ts +10 -0
  104. package/dist/tenant/handlers/decrypt-member-users.js +17 -0
  105. package/dist/tenant/handlers/members.query.js +2 -17
  106. package/dist/tenant/handlers/team-list.query.js +4 -17
  107. package/dist/tenant-lifecycle/archive-and-delete-tenant-rows.d.ts +5 -0
  108. package/dist/tenant-lifecycle/archive-and-delete-tenant-rows.js +20 -0
  109. package/dist/tenant-lifecycle/index.d.ts +1 -0
  110. package/dist/tenant-lifecycle/index.js +1 -0
  111. package/dist/tier-engine/feature.js +1 -1
  112. package/dist/user-data-rights/build-hook-db.d.ts +11 -0
  113. package/dist/user-data-rights/build-hook-db.js +22 -0
  114. package/dist/user-data-rights/handlers/request-export.write.js +2 -12
  115. package/dist/user-data-rights/mail-notifications.d.ts +3 -3
  116. package/dist/user-data-rights/mail-notifications.js +10 -34
  117. package/dist/user-data-rights/run-forget-cleanup.d.ts +1 -1
  118. package/dist/user-data-rights/run-forget-cleanup.js +2 -21
  119. package/dist/user-data-rights/run-user-export.d.ts +1 -1
  120. package/dist/user-data-rights/run-user-export.js +2 -21
  121. package/dist/user-data-rights/token-helpers.js +2 -14
  122. package/dist/user-data-rights/web/privacy-center-screen.js +1 -11
  123. package/dist/user-data-rights/web/public-deletion-gate.js +1 -0
  124. package/dist/user-profile/web/profile-screen.js +1 -11
  125. package/package.json +35 -35
  126. package/src/auth-email-password/changes.json +6 -0
  127. package/src/auth-mfa/changes.json +6 -0
  128. package/src/billing-foundation/changes.json +6 -0
  129. package/src/documents/changes.json +8 -0
  130. package/src/shared/changes.json +6 -0
  131. package/src/tenant-lifecycle/changes.json +6 -0
@@ -2,7 +2,7 @@
2
2
  // matched public declaration takes the cancellation back until it takes effect.
3
3
  // The anonymous handler only routes to the declaration's tenant; the system
4
4
  // handler checks the token and does the work.
5
- import { createHash, timingSafeEqual } from "node:crypto";
5
+ import { hashOpaqueTokenSync, opaqueTokenHashMatches } from "@cosmicdrift/kumiko-framework/crypto";
6
6
  import { access, createSystemUser, } from "@cosmicdrift/kumiko-framework/engine";
7
7
  import { Temporal } from "@cosmicdrift/kumiko-types/temporal";
8
8
  import * as z from "zod";
@@ -21,15 +21,7 @@ export const REVOCATION_PATHS = {
21
21
  const TOKEN_BYTES = 32;
22
22
  export function createRevocationToken() {
23
23
  const token = Buffer.from(crypto.getRandomValues(new Uint8Array(TOKEN_BYTES))).toString("base64url");
24
- return { token, tokenHash: hashRevocationToken(token) };
25
- }
26
- function hashRevocationToken(token) {
27
- return createHash("sha256").update(token).digest("hex");
28
- }
29
- function tokenMatchesHash(token, expectedHash) {
30
- const actual = Buffer.from(hashRevocationToken(token));
31
- const expected = Buffer.from(expectedHash);
32
- return actual.length === expected.length && timingSafeEqual(actual, expected);
24
+ return { token, tokenHash: hashOpaqueTokenSync(token) };
33
25
  }
34
26
  export function revocationUrl(args) {
35
27
  // Origin only: a baseUrl path prefix would not match the routes mounted at the root.
@@ -101,7 +93,7 @@ export function createRecordContractTerminationRevocationHandler(options, consum
101
93
  .map((e) => contractTerminationDeclaredPayloadSchema.safeParse(e.payload).data)
102
94
  .find((candidate) => candidate?.requestId === payload.requestId);
103
95
  if (declared?.revocationTokenHash === undefined ||
104
- !tokenMatchesHash(payload.token, declared.revocationTokenHash)) {
96
+ !opaqueTokenHashMatches(payload.token, declared.revocationTokenHash)) {
105
97
  return outcome("invalid");
106
98
  }
107
99
  if (hasRevocation(stream.events, payload.requestId))
@@ -148,11 +148,7 @@ export function createBillingFoundationFeature(options = {}) {
148
148
  },
149
149
  });
150
150
  // Plugin extension point. Provider plugins register here.
151
- r.extendsRegistrar(SUBSCRIPTION_PROVIDER_EXTENSION, {
152
- onRegister: () => {
153
- // No side-effects at register-time.
154
- },
155
- });
151
+ r.extendsRegistrar(SUBSCRIPTION_PROVIDER_EXTENSION, {});
156
152
  // Custom write handlers:
157
153
  // - process-event: programmatic entry point called by the webhook
158
154
  // handler; dispatches to the type-matched appendEvent
@@ -19,6 +19,7 @@ import { subscriptionAggregateId } from "../aggregate-id.js";
19
19
  import { SUBSCRIPTION_PII_FIELDS, subscriptionEntity } from "../entities.js";
20
20
  import { INVOICE_PAID_EVENT_QN, INVOICE_PAYMENT_FAILED_EVENT_QN, SUBSCRIPTION_AGGREGATE_TYPE, SUBSCRIPTION_CANCELED_EVENT_QN, SUBSCRIPTION_CREATED_EVENT_QN, SUBSCRIPTION_UPDATED_EVENT_QN, } from "../events.js";
21
21
  import { getSubscriptionForTenant } from "../get-subscription-for-tenant.js";
22
+ import { hasSeenProviderEvent } from "../provider-event-seen.js";
22
23
  import { BILLING_SUBSCRIPTION_LOCK_NAMESPACE, isSubscriptionBlockingCheckout, isSwitchableSubscriptionStatus, SubscriptionEventTypes, SubscriptionStatuses, } from "../web/constants.js";
23
24
  // =============================================================================
24
25
  // Input schema = the normalized SubscriptionEvent (without tenantId, which
@@ -127,12 +128,7 @@ export async function appendSubscriptionEvent(ctx, tenantId, rawPayload, now = T
127
128
  // idempotency anchor (like cap-counter).
128
129
  // ---------------------------------------------------------------
129
130
  const existingEvents = await ctx.events.load(aggId);
130
- const alreadySeen = existingEvents.some((e) => {
131
- const headers = e.metadata.headers ?? {};
132
- return (headers["providerEventId"] === payload.providerEventId &&
133
- headers["providerName"] === payload.providerName);
134
- });
135
- if (alreadySeen) {
131
+ if (hasSeenProviderEvent(existingEvents, payload)) {
136
132
  return { duplicate: true, subscriptionAggregateId: aggId };
137
133
  }
138
134
  // A state event the provider emitted before the newest one already stored is a
@@ -14,6 +14,7 @@ import * as z from "zod";
14
14
  import { paymentAggregateId } from "../aggregate-id.js";
15
15
  import { PAYMENT_PII_FIELDS, paymentEntity } from "../entities.js";
16
16
  import { PAYMENT_AGGREGATE_TYPE, PAYMENT_RECEIVED_EVENT_QN, } from "../events.js";
17
+ import { hasSeenProviderEvent } from "../provider-event-seen.js";
17
18
  export const processPaymentEventSchema = z.object({
18
19
  providerEventId: z.string().min(1).max(200),
19
20
  providerName: z.string().min(1).max(50),
@@ -43,12 +44,7 @@ export const processPaymentEventHandler = {
43
44
  // optimize via a per-tenant providerEventId-index if that bites).
44
45
  // ---------------------------------------------------------------
45
46
  const existingEvents = await ctx.events.load(aggId);
46
- const alreadySeen = existingEvents.some((e) => {
47
- const headers = e.metadata.headers ?? {};
48
- return (headers["providerEventId"] === payload.providerEventId &&
49
- headers["providerName"] === payload.providerName);
50
- });
51
- if (alreadySeen) {
47
+ if (hasSeenProviderEvent(existingEvents, payload)) {
52
48
  return {
53
49
  isSuccess: true,
54
50
  data: { duplicate: true, paymentAggregateId: aggId },
@@ -8,6 +8,8 @@ export { INVOICE_PAID_EVENT_QN, INVOICE_PAID_EVENT_SHORT, INVOICE_PAYMENT_FAILED
8
8
  export { createBillingFoundationFeature } from "./feature.ts";
9
9
  export { getSubscriptionForTenant, type SubscriptionView } from "./get-subscription-for-tenant.ts";
10
10
  export { paymentsProjectionTable, subscriptionsProjectionTable } from "./projection.ts";
11
+ export { hasSeenProviderEvent } from "./provider-event-seen.ts";
12
+ export { createTtlPriceCache, parseStoredSecret, type TtlPriceCache, type TtlPriceCacheOptions, validateOneOffPriceIds, } from "./provider-shared.ts";
11
13
  export { billingPlansPanel, createBillingPlansScreen } from "./screens.ts";
12
14
  export { createSubscriptionTierSync, effectiveTierFromSubscription, SUBSCRIPTION_WEBHOOK_PATH, type SubscriptionTierSyncDeps, type TierSyncResult, } from "./subscription-tier-sync.ts";
13
15
  export { type BillingFoundationOptions, type BillingPlanBenefit, type BillingPlanCatalog, type BillingPlanContactCard, type BillingPlanPrice, type BillingPlansResult, type BillingPlanView, type BillingProviderView, type ConsumerProtectionOptions, KNOWN_RECURRING_INTERVALS, type LegalLinkSet, type OneOffCheckoutRequest, type OneOffCheckoutVerdict, type PaymentEvent, type PlanSwitchPreview, type ProviderPrice, type ProviderSubscriptionSnapshot, type RecurringInterval, type SubscriptionEvent, type SubscriptionProviderPlugin, } from "./types.ts";
@@ -9,6 +9,8 @@ export { INVOICE_PAID_EVENT_QN, INVOICE_PAID_EVENT_SHORT, INVOICE_PAYMENT_FAILED
9
9
  export { createBillingFoundationFeature } from "./feature.js";
10
10
  export { getSubscriptionForTenant } from "./get-subscription-for-tenant.js";
11
11
  export { paymentsProjectionTable, subscriptionsProjectionTable } from "./projection.js";
12
+ export { hasSeenProviderEvent } from "./provider-event-seen.js";
13
+ export { createTtlPriceCache, parseStoredSecret, validateOneOffPriceIds, } from "./provider-shared.js";
12
14
  export { billingPlansPanel, createBillingPlansScreen } from "./screens.js";
13
15
  export { createSubscriptionTierSync, effectiveTierFromSubscription, SUBSCRIPTION_WEBHOOK_PATH, } from "./subscription-tier-sync.js";
14
16
  export { KNOWN_RECURRING_INTERVALS, } from "./types.js";
@@ -92,21 +92,11 @@ async function upsert(tx, event, set, fullPayload) {
92
92
  // example, during a rebuild-from-events) can arrive in any order and still
93
93
  // materialize the row correctly.
94
94
  // =============================================================================
95
- /** subscription-created → UPSERT with all fields. PK = aggregateId =
96
- * subscriptionAggregateId(tenantId), with one row per tenant. UPSERT allows
97
- * the Disney+-change pattern (a second provider sends create for the same
98
- * tenant) to overwrite the existing row instead of causing a PK conflict. */
99
- export const applySubscriptionCreated = defineApply(async (event, tx) => {
100
- const full = fullSetFromPayload(event.payload);
101
- await upsert(tx, event, { ...full, ...cancelAtSetFromPayload(event.payload) }, event.payload);
102
- });
103
- /** subscription-updated → UPSERT with all fields. */
104
- export const applySubscriptionUpdated = defineApply(async (event, tx) => {
95
+ const applyFullSubscriptionState = defineApply(async (event, tx) => {
105
96
  const full = fullSetFromPayload(event.payload);
106
97
  await upsert(tx, event, { ...full, ...cancelAtSetFromPayload(event.payload) }, event.payload);
107
98
  });
108
- /** subscription-canceled → status/tier/currentPeriodEnd patchen. */
109
- export const applySubscriptionCanceled = defineApply(async (event, tx) => {
99
+ const applyStatusTierPeriodPatch = defineApply(async (event, tx) => {
110
100
  const p = event.payload;
111
101
  await upsert(tx, event, {
112
102
  status: p.status,
@@ -115,18 +105,19 @@ export const applySubscriptionCanceled = defineApply(async (event, tx) => {
115
105
  ...cancelAtSetFromPayload(p),
116
106
  }, p);
117
107
  });
108
+ /** subscription-created → UPSERT with all fields. PK = aggregateId =
109
+ * subscriptionAggregateId(tenantId), with one row per tenant. UPSERT allows
110
+ * the Disney+-change pattern (a second provider sends create for the same
111
+ * tenant) to overwrite the existing row instead of causing a PK conflict. */
112
+ export const applySubscriptionCreated = applyFullSubscriptionState;
113
+ /** subscription-updated → UPSERT with all fields. */
114
+ export const applySubscriptionUpdated = applyFullSubscriptionState;
115
+ /** subscription-canceled → status/tier/currentPeriodEnd patchen. */
116
+ export const applySubscriptionCanceled = applyStatusTierPeriodPatch;
118
117
  /** invoice-paid → state update (status, tier, currentPeriodEnd).
119
118
  * The invoice history itself lives in the event store, so it remains
120
119
  * replayable. */
121
- export const applyInvoicePaid = defineApply(async (event, tx) => {
122
- const p = event.payload;
123
- await upsert(tx, event, {
124
- status: p.status,
125
- tier: p.tier,
126
- currentPeriodEnd: p.currentPeriodEndIso,
127
- ...cancelAtSetFromPayload(p),
128
- }, p);
129
- });
120
+ export const applyInvoicePaid = applyStatusTierPeriodPatch;
130
121
  /** invoice-payment-failed → status (typically past_due) + tier. The tier
131
122
  * engine reads the row and decides whether to downgrade. currentPeriodEnd is
132
123
  * intentionally unchanged: the period has not "ended"; payment simply
@@ -0,0 +1,5 @@
1
+ import type { StoredEvent } from "@cosmicdrift/kumiko-framework/event-store";
2
+ export declare function hasSeenProviderEvent(existingEvents: readonly Pick<StoredEvent, "metadata">[], providerEvent: {
3
+ readonly providerEventId: string;
4
+ readonly providerName: string;
5
+ }): boolean;
@@ -0,0 +1,7 @@
1
+ export function hasSeenProviderEvent(existingEvents, providerEvent) {
2
+ return existingEvents.some((e) => {
3
+ const headers = e.metadata.headers ?? {};
4
+ return (headers["providerEventId"] === providerEvent.providerEventId &&
5
+ headers["providerName"] === providerEvent.providerName);
6
+ });
7
+ }
@@ -0,0 +1,11 @@
1
+ export declare function validateOneOffPriceIds(providerLabel: string, priceIds: readonly string[]): void;
2
+ export declare function parseStoredSecret(providerLabel: string, raw: string | undefined): string | undefined;
3
+ export type TtlPriceCache<TPrice> = {
4
+ readonly get: (priceId: string) => TPrice | undefined;
5
+ readonly set: (priceId: string, price: TPrice) => void;
6
+ };
7
+ export type TtlPriceCacheOptions = {
8
+ readonly ttlMs?: number;
9
+ readonly now: () => number;
10
+ };
11
+ export declare function createTtlPriceCache<TPrice>({ ttlMs, now, }: TtlPriceCacheOptions): TtlPriceCache<TPrice>;
@@ -0,0 +1,44 @@
1
+ import { parseJsonSafe } from "@cosmicdrift/kumiko-framework/utils";
2
+ export function validateOneOffPriceIds(providerLabel, priceIds) {
3
+ const seen = new Set();
4
+ for (const priceId of priceIds) {
5
+ if (priceId.length === 0) {
6
+ throw new Error(`${providerLabel}: oneOffPriceIds must not contain an empty string`);
7
+ }
8
+ if (seen.has(priceId)) {
9
+ throw new Error(`${providerLabel}: duplicate oneOffPriceIds entry "${priceId}"`);
10
+ }
11
+ seen.add(priceId);
12
+ }
13
+ }
14
+ // backing:"secrets" values are stored JSON-serialized, so the store read has to
15
+ // be parsed back; the env fallback is a plain string and stays raw. The error
16
+ // must not carry the input: the JSON parser's own message would repeat the
17
+ // credential into logs and, for webhooks, into the 401 body.
18
+ export function parseStoredSecret(providerLabel, raw) {
19
+ if (raw === undefined || raw.length === 0)
20
+ return undefined;
21
+ const parsed = parseJsonSafe(raw, undefined);
22
+ if (parsed === undefined) {
23
+ throw new Error(`${providerLabel} credential (backing:secrets) is not valid JSON`);
24
+ }
25
+ return typeof parsed === "string" && parsed.length > 0 ? parsed : undefined;
26
+ }
27
+ export function createTtlPriceCache({ ttlMs = 600_000, now, }) {
28
+ const store = new Map();
29
+ return {
30
+ get: (priceId) => {
31
+ const entry = store.get(priceId);
32
+ if (!entry)
33
+ return undefined;
34
+ if (entry.expiresAt <= now()) {
35
+ store.delete(priceId);
36
+ return undefined;
37
+ }
38
+ return entry.price;
39
+ },
40
+ set: (priceId, price) => {
41
+ store.set(priceId, { price, expiresAt: now() + ttlMs });
42
+ },
43
+ };
44
+ }
@@ -1,6 +1,7 @@
1
1
  import { declareEscapeHatch } from "@cosmicdrift/kumiko-framework/engine";
2
2
  import { archiveStream } from "@cosmicdrift/kumiko-framework/event-store";
3
3
  import { resolveProfileForTenant } from "../compliance-profiles/index.js";
4
+ import { TENANT_DESTROY_ARCHIVE_REASON, TENANT_DESTROY_ARCHIVED_BY, } from "../tenant-lifecycle/index.js";
4
5
  import { paymentAggregateId, subscriptionAggregateId } from "./aggregate-id.js";
5
6
  import { PAYMENT_AGGREGATE_TYPE, SUBSCRIPTION_AGGREGATE_TYPE } from "./events.js";
6
7
  import { paymentsProjectionMeta, subscriptionsProjectionMeta } from "./projection.js";
@@ -34,8 +35,8 @@ export async function subscriptionTenantDestroyHook(ctx) {
34
35
  tenantId: ctx.tenantId,
35
36
  aggregateId,
36
37
  aggregateType: SUBSCRIPTION_AGGREGATE_TYPE,
37
- archivedBy: "tenant-lifecycle:destroy",
38
- reason: "tenant_destroy",
38
+ archivedBy: TENANT_DESTROY_ARCHIVED_BY,
39
+ reason: TENANT_DESTROY_ARCHIVE_REASON,
39
40
  });
40
41
  }
41
42
  /** Tenant-destroy hook for payment PII. Unlike subscriptionTenantDestroyHook
@@ -62,7 +63,7 @@ export async function paymentTenantDestroyHook(ctx) {
62
63
  tenantId: ctx.tenantId,
63
64
  aggregateId,
64
65
  aggregateType: PAYMENT_AGGREGATE_TYPE,
65
- archivedBy: "tenant-lifecycle:destroy",
66
- reason: "tenant_destroy",
66
+ archivedBy: TENANT_DESTROY_ARCHIVED_BY,
67
+ reason: TENANT_DESTROY_ARCHIVE_REASON,
67
68
  });
68
69
  }
@@ -17,7 +17,7 @@ export function createChannelEmailFeature(options) {
17
17
  r.requires({ features: ["delivery"] });
18
18
  r.envSchema(smtpEnvSchema);
19
19
  r.translations({ keys: { "delivery.channel.email": { en: "Email" } } });
20
- r.extendsRegistrar(EMAIL_APP_TRANSPORT_EXTENSION, { onRegister: () => { } });
20
+ r.extendsRegistrar(EMAIL_APP_TRANSPORT_EXTENSION, {});
21
21
  r.useExtension(EMAIL_APP_TRANSPORT_EXTENSION, EMAIL_APP_TRANSPORT_USAGE, {
22
22
  transport: appTransport,
23
23
  });
@@ -26,7 +26,7 @@ import { createEventStoreExecutor, createSystemDbView, createTenantDb, } from "@
26
26
  import { SYSTEM_TENANT_ID, } from "@cosmicdrift/kumiko-framework/engine";
27
27
  import { InternalError } from "@cosmicdrift/kumiko-framework/errors";
28
28
  import { createEscapeHatchReporter } from "@cosmicdrift/kumiko-framework/pipeline";
29
- import { classifyStoredEnvelope, runChunkedMigration, } from "../../shared/index.js";
29
+ import { classifyStoredEnvelope, createTenantDbCache, runChunkedMigration, } from "../../shared/index.js";
30
30
  import { configValueEntity, configValuesTable } from "../table.js";
31
31
  const DEFAULT_MAX_FAILURES = 10;
32
32
  const SCAN_SLICE_SIZE = 100;
@@ -80,20 +80,12 @@ export const reencryptJob = async (rawPayload, ctx) => {
80
80
  log: ctx.obs.log,
81
81
  });
82
82
  }
83
- const tdbCache = new Map();
84
- function tdbFor(tenantId) {
85
- let existing = tdbCache.get(tenantId);
86
- if (!existing) {
87
- existing = createTenantDb({
88
- db,
89
- tenantId,
90
- mode: "system",
91
- reason: "KEK rotation job re-encrypts config values of every tenant",
92
- });
93
- tdbCache.set(tenantId, existing);
94
- }
95
- return existing;
96
- }
83
+ const tdbFor = createTenantDbCache((tenantId) => createTenantDb({
84
+ db,
85
+ tenantId,
86
+ mode: "system",
87
+ reason: "KEK rotation job re-encrypts config values of every tenant",
88
+ }));
97
89
  const sdbCache = new Map();
98
90
  function sdbFor(tenantId) {
99
91
  let existing = sdbCache.get(tenantId);
@@ -4,7 +4,7 @@ import { createFallbackLogger, scrubLogText, } from "@cosmicdrift/kumiko-framewo
4
4
  import { assertNotifyTargetsOwnTenant, createEscapeHatchReporter, } from "@cosmicdrift/kumiko-framework/pipeline";
5
5
  import { generateId } from "@cosmicdrift/kumiko-framework/utils";
6
6
  import { fileContextFromResolver } from "../file-foundation/index.js";
7
- import { redactErrorText } from "../shared/index.js";
7
+ import { collectExtensionOptions, redactErrorText } from "../shared/index.js";
8
8
  import { hashUnsubscribeAddress } from "./address-opt-out.js";
9
9
  import { appendAttemptEvent, logAttempt } from "./attempt-log.js";
10
10
  import { buildChannelContext } from "./channel-context.js";
@@ -20,13 +20,7 @@ export function redactedMessageOf(err) {
20
20
  }
21
21
  // Build channel list from registry extension usages
22
22
  export function collectChannels(registry) {
23
- const usages = registry.getExtensionUsages(DELIVERY_CHANNEL_EXTENSION);
24
- return usages.map((usage) => {
25
- if (!isDeliveryChannelPlugin(usage.options)) {
26
- throw new Error(`${DELIVERY_CHANNEL_EXTENSION} registration for "${usage.entityName}" has invalid options`);
27
- }
28
- return { name: usage.entityName, ...usage.options };
29
- });
23
+ return collectExtensionOptions(registry, DELIVERY_CHANNEL_EXTENSION, isDeliveryChannelPlugin);
30
24
  }
31
25
  export function createDeliveryService(options) {
32
26
  const { db, registry, sseBroker, channels, tenantUserIdsQuery, rateLimit, isChannelKilled, idempotencyRedis, jobRunner, secrets, addressCipher, filesForTenant, tenantConfigFor, escapeHatchAuditSink, log, unsubscribeLinks, } = options;
@@ -59,27 +59,15 @@ export function createFileDerivativesFeature(opts = {}) {
59
59
  // alone boots fine but fails at request-time with a SQL error the first
60
60
  // time variant() runs.
61
61
  r.requires({ features: ["files"] });
62
- r.extendsRegistrar(EXT_DERIVATIVE_RENDERER, {
63
- onRegister: () => {
64
- // No side-effects at register-time — resolution (exact MIME match,
65
- // then `<type>/*` wildcard) happens at request-time in
66
- // resolveRenderer, mirrors file-foundation's fileProvider point.
67
- },
68
- });
69
- r.extendsRegistrar(EXT_DERIVATIVE_PUBLIC_PREDICATE, {
70
- onRegister: () => {
71
- // No side-effects at register-time — resolution happens at
72
- // request-time in publicVariantQuery, keyed by the FileRef's
73
- // entityType.
74
- },
75
- });
76
- r.extendsRegistrar(EXT_DERIVATIVE_OVERLAY_RESOLVER, {
77
- onRegister: () => {
78
- // No side-effects at register-time — resolution happens in
79
- // variant(), keyed by the FileRef's entityType, before the spec
80
- // hash is computed.
81
- },
82
- });
62
+ // Resolution (exact MIME match, then `<type>/*` wildcard) happens at request-time in
63
+ // resolveRenderer, mirrors file-foundation's fileProvider point.
64
+ r.extendsRegistrar(EXT_DERIVATIVE_RENDERER, {});
65
+ // Resolution happens at request-time in publicVariantQuery, keyed by the FileRef's
66
+ // entityType.
67
+ r.extendsRegistrar(EXT_DERIVATIVE_PUBLIC_PREDICATE, {});
68
+ // Resolution happens in variant(), keyed by the FileRef's entityType, before the spec
69
+ // hash is computed.
70
+ r.extendsRegistrar(EXT_DERIVATIVE_OVERLAY_RESOLVER, {});
83
71
  // Registered ONLY when resolveApexTenant is supplied — r.queryHandler
84
72
  // registers publicVariantQuery into the feature's dispatch table as a
85
73
  // side effect of being called, independent of what's done with its
@@ -31,12 +31,8 @@ export function createFileFoundationFeature() {
31
31
  recommended: false,
32
32
  });
33
33
  r.requires({ features: ["config"] });
34
- r.extendsRegistrar(EXT_FILE_PROVIDER, {
35
- onRegister: () => {
36
- // No side-effects at register-time — registry stores the usage,
37
- // factory looks it up at request-time.
38
- },
39
- });
34
+ // Registry stores the usage, factory looks it up at request-time.
35
+ r.extendsRegistrar(EXT_FILE_PROVIDER, {});
40
36
  const providerConfigKey = r.config("provider", createTenantConfig("text", {
41
37
  default: "",
42
38
  env: FILE_STORAGE_PROVIDER_ENV,
@@ -46,6 +46,7 @@
46
46
  import { createEventStoreExecutor, selectMany } from "@cosmicdrift/kumiko-framework/db";
47
47
  import { createSystemUser, parseTenantId, } from "@cosmicdrift/kumiko-framework/engine";
48
48
  import { assertSafeStorageKey, fileRefEntity, fileRefsTable, storageKeyStemPrefix, tenantStoragePrefixes, } from "@cosmicdrift/kumiko-framework/files";
49
+ import { chunk } from "@cosmicdrift/kumiko-framework/utils";
49
50
  import { runChunkedMigration } from "../shared/index.js";
50
51
  const crud = createEventStoreExecutor(fileRefsTable, fileRefEntity, { entityName: "fileRef" });
51
52
  // Existence-check batch size for fileRefStorageDestroyHook's survivor lookup
@@ -53,12 +54,6 @@ const crud = createEventStoreExecutor(fileRefsTable, fileRefEntity, { entityName
53
54
  // or a single unbounded array for a tenant with a huge prefix.
54
55
  const SURVIVOR_CHECK_BATCH_SIZE = 500;
55
56
  const DESTROY_CHUNK_SIZE = 500;
56
- function chunk(items, size) {
57
- const chunks = [];
58
- for (let i = 0; i < items.length; i += size)
59
- chunks.push(items.slice(i, i + size));
60
- return chunks;
61
- }
62
57
  function isUnderOwnPrefix(storageKey, prefixes) {
63
58
  return prefixes.some((prefix) => storageKey.startsWith(prefix));
64
59
  }
@@ -15,7 +15,7 @@
15
15
  // Deferred: reparenting with cycle-check (folder:update CAN change parentId, but
16
16
  // no UI exposes it in v1 — folders-view guards cycles defensively).
17
17
  import { defineEntityCreateHandler, defineEntityDetailHandler, defineEntityListHandler, defineEntityUpdateHandler, defineFeature, } from "@cosmicdrift/kumiko-framework/engine";
18
- import { assertNoWhereRuleInOwnershipWrite } from "../shared/index.js";
18
+ import { assertNoWhereRuleInOwnershipWrite, resolveFeatureAccess } from "../shared/index.js";
19
19
  import { createFolderAssignmentEntity, folderEntity } from "./entity.js";
20
20
  import { createClearFolderHandler } from "./handlers/clear-folder.write.js";
21
21
  import { createDeleteFolderHandler } from "./handlers/delete-folder.write.js";
@@ -63,13 +63,6 @@ function registerFolders(r, access, toggleable, ownership, parents) {
63
63
  }));
64
64
  }
65
65
  const defaultFoldersFeature = defineFeature(FOLDERS_FEATURE_NAME, (r) => registerFolders(r, DEFAULT_FOLDER_ACCESS, undefined, undefined, undefined));
66
- function resolveAccess(opts) {
67
- if (opts.access !== undefined)
68
- return opts.access;
69
- if (opts.roles !== undefined)
70
- return { roles: opts.roles };
71
- return DEFAULT_FOLDER_ACCESS;
72
- }
73
66
  // Options wrapper. Without options returns the module-level singleton (no
74
67
  // rebuild). access/roles/toggleable build a fresh feature-definition.
75
68
  export function createFoldersFeature(opts = {}) {
@@ -87,6 +80,6 @@ export function createFoldersFeature(opts = {}) {
87
80
  "assignment row. Omit `parents` to keep every registered entity " +
88
81
  "admissible as a host instead.");
89
82
  }
90
- const access = resolveAccess(opts);
83
+ const access = resolveFeatureAccess(opts, DEFAULT_FOLDER_ACCESS);
91
84
  return defineFeature(FOLDERS_FEATURE_NAME, (r) => registerFolders(r, access, opts.toggleable, opts.ownership, opts.parents));
92
85
  }
@@ -26,9 +26,10 @@ import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
26
26
  // NOTE on Tailwind: a host's Tailwind v4 build must `@source`-scan this package's
27
27
  // src (node_modules is ignored by default) or these classes never compile. money-
28
28
  // horse already does; that scan is a real shipping requirement for any host.
29
- import { useDispatcher, usePrimitives, useQuery, useTranslation, } from "@cosmicdrift/kumiko-renderer";
29
+ import { usePrimitives, useQuery, useTranslation } from "@cosmicdrift/kumiko-renderer";
30
30
  import { ChevronRight, File, Folder, Pencil, Plus, Trash2 } from "lucide-react";
31
31
  import { useEffect, useState } from "react";
32
+ import { useDispatchedWrites } from "../../shared/web/use-dispatched-writes.js";
32
33
  import { FoldersHandlers, FoldersQueries } from "./constants.js";
33
34
  import { buildFolderTree } from "./tree.js";
34
35
  const UNFILED = "__unfiled__";
@@ -51,13 +52,15 @@ const loadCollapsed = () => {
51
52
  export function FolderManager({ renderMeta, filing, }) {
52
53
  const { Banner, Button, Dialog, Input, Text } = usePrimitives();
53
54
  const t = useTranslation();
54
- const dispatcher = useDispatcher();
55
55
  const catalog = useQuery(FoldersQueries.folderList, {});
56
56
  const [pending, setPending] = useState(null);
57
57
  const [draftName, setDraftName] = useState("");
58
58
  const [collapsed, setCollapsed] = useState(loadCollapsed);
59
- const [busy, setBusy] = useState(false);
60
- const [errorKey, setErrorKey] = useState(null);
59
+ const { busy, setBusy, errorKey, setErrorKey, writeOk, apply } = useDispatchedWrites(async () => {
60
+ setPending(null);
61
+ await catalog.refetch();
62
+ await filing?.onReassigned();
63
+ });
61
64
  const [dragOverKey, setDragOverKey] = useState(null);
62
65
  const [pendingDelete, setPendingDelete] = useState(null);
63
66
  // Persist expand/collapse so a reload (F5) doesn't re-expand everything.
@@ -116,28 +119,6 @@ export function FolderManager({ renderMeta, filing, }) {
116
119
  setDraftName(folder.name);
117
120
  setPending({ mode: "rename", id: folder.id, version: folder.version });
118
121
  };
119
- const apply = async (write) => {
120
- setBusy(true);
121
- setErrorKey(null);
122
- try {
123
- if (await write()) {
124
- setPending(null);
125
- await catalog.refetch();
126
- await filing?.onReassigned();
127
- }
128
- }
129
- finally {
130
- setBusy(false);
131
- }
132
- };
133
- const writeOk = async (type, payload) => {
134
- const result = await dispatcher.write(type, payload);
135
- if (!result.isSuccess) {
136
- setErrorKey(result.error.i18nKey);
137
- return false;
138
- }
139
- return true;
140
- };
141
122
  const saveDraft = () => {
142
123
  const name = draftName.trim();
143
124
  if (name === "" || pending === null)
@@ -13,6 +13,7 @@ import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
13
13
  // (RenderEdit passes { entityName, entityId }).
14
14
  import { useDispatcher, usePrimitives, useQuery, useTranslation, } from "@cosmicdrift/kumiko-renderer";
15
15
  import { useState } from "react";
16
+ import { useDispatchedWrites } from "../../shared/web/use-dispatched-writes.js";
16
17
  import { FoldersHandlers, FoldersQueries } from "./constants.js";
17
18
  import { folderPath } from "./tree.js";
18
19
  // Sentinel for the "no folder" combobox option — selecting it clears the
@@ -33,8 +34,10 @@ export function FolderSection({ entityName, entityId, }) {
33
34
  ],
34
35
  }, { enabled });
35
36
  const [newName, setNewName] = useState("");
36
- const [busy, setBusy] = useState(false);
37
- const [errorKey, setErrorKey] = useState(null);
37
+ const refetch = async () => {
38
+ await Promise.all([catalog.refetch(), assignments.refetch()]);
39
+ };
40
+ const { busy, errorKey, setErrorKey, writeOk, apply } = useDispatchedWrites(refetch);
38
41
  if (entityId === null) {
39
42
  return (_jsx(Banner, { variant: "info", testId: "folder-section-create-mode", children: _jsx(Text, { children: t("folders.section.createMode") }) }));
40
43
  }
@@ -52,28 +55,6 @@ export function FolderSection({ entityName, entityId, }) {
52
55
  { value: NO_FOLDER, label: t("folders.section.none") },
53
56
  ...folders.map((f) => ({ value: f.id, label: folderPath(folders, f.id) })),
54
57
  ];
55
- const refetch = async () => {
56
- await Promise.all([catalog.refetch(), assignments.refetch()]);
57
- };
58
- const apply = async (write) => {
59
- setBusy(true);
60
- setErrorKey(null);
61
- try {
62
- if (await write())
63
- await refetch();
64
- }
65
- finally {
66
- setBusy(false);
67
- }
68
- };
69
- const writeOk = async (type, payload) => {
70
- const result = await dispatcher.write(type, payload);
71
- if (!result.isSuccess) {
72
- setErrorKey(result.error.i18nKey);
73
- return false;
74
- }
75
- return true;
76
- };
77
58
  const onSelect = (next) => {
78
59
  if (next === currentFolderId)
79
60
  return;
@@ -1,3 +1,12 @@
1
+ /**
2
+ * save is an upsert keyed on (tenantId, ownerId, draftKey) — same
3
+ * lookup-then-create|update-with-race-retry idiom as
4
+ * delivery/upsert-preference.ts, because createEventStoreExecutor has no
5
+ * built-in upsert. Two racing saves for the same draftKey: the loser hits
6
+ * the unique index (FORM_DRAFT_UNIQUE_KEY_CONSTRAINT), re-looks-up the
7
+ * winner's row, and updates it (with the winner's version) instead of
8
+ * erroring.
9
+ */
1
10
  export declare const saveDraftWrite: import("@cosmicdrift/kumiko-types/define-handler").WriteHandlerDefinition<"save", import("zod").ZodObject<{
2
11
  draftKey: import("zod").ZodString;
3
12
  values: import("zod").ZodRecord<import("zod").ZodString, import("zod").ZodUnknown>;
@@ -1,11 +1,13 @@
1
1
  import { defineWriteHandler } from "@cosmicdrift/kumiko-framework/engine";
2
2
  import { failUnprocessable } from "@cosmicdrift/kumiko-framework/errors";
3
3
  import { getTemporal } from "@cosmicdrift/kumiko-framework/time";
4
+ import { isUniqueConstraintFailure } from "../../shared/index.js";
4
5
  import { countDraftsByOwner } from "../db/queries/draft-count.js";
5
6
  import { formDraftExecutor } from "../executor.js";
6
7
  import { lookupDraft } from "../lookup.js";
7
8
  import { saveDraftPayloadSchema } from "../schemas.js";
8
9
  import { FORM_DRAFT_ACCESS, FORM_DRAFT_MAX_PER_OWNER, FORM_DRAFT_UNIQUE_KEY_CONSTRAINT, } from "../web/constants.js";
10
+ const SAVE_DRAFT_COUNT_REASON = "COUNT(*) of the caller's own drafts without loading 64KB value blobs";
9
11
  /**
10
12
  * save is an upsert keyed on (tenantId, ownerId, draftKey) — same
11
13
  * lookup-then-create|update-with-race-retry idiom as
@@ -15,12 +17,6 @@ import { FORM_DRAFT_ACCESS, FORM_DRAFT_MAX_PER_OWNER, FORM_DRAFT_UNIQUE_KEY_CONS
15
17
  * winner's row, and updates it (with the winner's version) instead of
16
18
  * erroring.
17
19
  */
18
- function isDraftKeyConflict(failure) {
19
- const error = failure.error; // @cast-boundary error-details
20
- return (error.code === "unique_violation" &&
21
- error.details?.constraintName === FORM_DRAFT_UNIQUE_KEY_CONSTRAINT);
22
- }
23
- const SAVE_DRAFT_COUNT_REASON = "COUNT(*) of the caller's own drafts without loading 64KB value blobs";
24
20
  export const saveDraftWrite = defineWriteHandler({
25
21
  name: "save",
26
22
  schema: saveDraftPayloadSchema,
@@ -49,7 +45,7 @@ export const saveDraftWrite = defineWriteHandler({
49
45
  const result = await formDraftExecutor.create({ ownerId, draftKey, draft }, event.user, ctx.db);
50
46
  if (result.isSuccess)
51
47
  return result;
52
- if (!isDraftKeyConflict(result))
48
+ if (!isUniqueConstraintFailure(result, FORM_DRAFT_UNIQUE_KEY_CONSTRAINT))
53
49
  return result;
54
50
  const winner = await lookupDraft(ctx.db, event.user.tenantId, ownerId, draftKey);
55
51
  if (!winner)
@@ -169,12 +169,8 @@ export function createInboundMailFoundationFeature(options = {}) {
169
169
  registerMailAccountWakeConsumer(r);
170
170
  // Plugin extension point — providers register via
171
171
  // r.useExtension("inboundMailProvider", "<key>", plugin).
172
- r.extendsRegistrar(INBOUND_MAIL_PROVIDER_EXTENSION, {
173
- onRegister: () => {
174
- // No side-effects at register-time — lookup happens at runtime
175
- // via resolveInboundProviderForKey/-Account.
176
- },
177
- });
172
+ // Lookup happens at runtime via resolveInboundProviderForKey/-Account.
173
+ r.extendsRegistrar(INBOUND_MAIL_PROVIDER_EXTENSION, {});
178
174
  // Sync machinery: high-frequency tick state, deliberately NOT
179
175
  // event-sourced — r.storeTable keeps the migration DDL but excludes the
180
176
  // tables from the projection rebuild.
@@ -70,6 +70,7 @@ export async function appendThreadRollup(ctx, input) {
70
70
  // @cast-boundary engine-payload — eigene events, shape via defineEvent
71
71
  const previousThread = lastThreadEvent?.payload;
72
72
  const previousLastAt = previousThread?.lastMessageAtIso ?? "";
73
+ // biome-ignore lint/complexity/useMathMinMax: ISO strings compare lexicographically; Math.max would coerce them to NaN
73
74
  const newLastAt = receivedAtIso > previousLastAt ? receivedAtIso : previousLastAt;
74
75
  const messageCount = await countWhere(threadRollupRunner, inboundMessagesProjectionTable, {
75
76
  tenantId,