@cosmicdrift/kumiko-bundled-features 0.404.1 → 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.
- package/dist/auth-email-password/mail-notifications.d.ts +3 -3
- package/dist/auth-email-password/mail-notifications.js +10 -34
- package/dist/auth-email-password/web/default-topbar-actions.d.ts +6 -1
- package/dist/auth-email-password/web/default-topbar-actions.js +2 -2
- package/dist/auth-email-password/web/index.d.ts +2 -0
- package/dist/auth-email-password/web/index.js +1 -0
- package/dist/auth-email-password/web/invite-accept-screen.js +6 -41
- package/dist/auth-email-password/web/tenant-label.d.ts +2 -0
- package/dist/auth-email-password/web/tenant-label.js +10 -0
- package/dist/auth-email-password/web/tenant-menu-items.js +2 -7
- package/dist/auth-email-password/web/tenant-switcher.js +5 -12
- package/dist/auth-email-password/web/use-redirect-authed-from-login.d.ts +7 -0
- package/dist/auth-email-password/web/use-redirect-authed-from-login.js +30 -0
- package/dist/auth-foundation/feature.js +8 -21
- package/dist/auth-mfa/handlers/reencrypt.job.js +7 -15
- package/dist/auth-mfa/hmac-token-codec.d.ts +6 -1
- package/dist/auth-mfa/hmac-token-codec.js +8 -10
- package/dist/auth-mfa/mfa-challenge-token.js +2 -8
- package/dist/auth-mfa/mfa-preauth-setup-token.js +2 -8
- package/dist/auth-mfa/mfa-setup-token.d.ts +2 -8
- package/dist/auth-mfa/mfa-setup-token.js +8 -45
- package/dist/billing-foundation/consumer-protection/termination-revoke.js +3 -11
- package/dist/billing-foundation/feature.js +1 -5
- package/dist/billing-foundation/handlers/process-event.write.js +2 -6
- package/dist/billing-foundation/handlers/process-payment-event.write.js +2 -6
- package/dist/billing-foundation/index.d.ts +2 -0
- package/dist/billing-foundation/index.js +2 -0
- package/dist/billing-foundation/projection.js +12 -21
- package/dist/billing-foundation/provider-event-seen.d.ts +5 -0
- package/dist/billing-foundation/provider-event-seen.js +7 -0
- package/dist/billing-foundation/provider-shared.d.ts +11 -0
- package/dist/billing-foundation/provider-shared.js +44 -0
- package/dist/billing-foundation/tenant-destroy-hook.js +5 -4
- package/dist/channel-email/feature.js +1 -1
- package/dist/config/handlers/reencrypt.job.js +7 -15
- package/dist/delivery/delivery-service.js +2 -8
- package/dist/file-derivatives/feature.js +9 -21
- package/dist/file-foundation/feature.js +2 -6
- package/dist/files-tenant-data/hooks.js +1 -6
- package/dist/folders/feature.js +2 -9
- package/dist/folders/web/folder-manager.js +7 -26
- package/dist/folders/web/folder-section.js +5 -24
- package/dist/form-draft/handlers/save.write.d.ts +9 -0
- package/dist/form-draft/handlers/save.write.js +3 -7
- package/dist/inbound-mail-foundation/feature.js +2 -6
- package/dist/inbound-mail-foundation/oauth-state.js +5 -13
- package/dist/inbound-mail-foundation/tenant-destroy-hook.d.ts +1 -1
- package/dist/inbound-mail-foundation/tenant-destroy-hook.js +3 -18
- package/dist/jobs/handlers/tenant-failures.query.js +1 -15
- package/dist/jobs/handlers/tenant-runs.query.js +1 -14
- package/dist/jobs/job-run-logger.js +19 -23
- package/dist/jobs/parse-subject.d.ts +1 -0
- package/dist/jobs/parse-subject.js +15 -0
- package/dist/ledger/feature.js +2 -8
- package/dist/mail-foundation/feature.js +3 -7
- package/dist/managed-pages/render-page-body.js +4 -12
- package/dist/notes-history/feature.js +2 -9
- package/dist/personal-access-tokens/handlers/list.query.js +1 -9
- package/dist/personal-access-tokens/hash.js +2 -2
- package/dist/personal-access-tokens/parse-scope-names.d.ts +1 -0
- package/dist/personal-access-tokens/parse-scope-names.js +10 -0
- package/dist/personal-access-tokens/resolver.js +1 -9
- package/dist/renderer-foundation/feature.js +3 -14
- package/dist/secrets/handlers/rotate.job.js +7 -18
- package/dist/shared/collect-extension-options.d.ts +4 -0
- package/dist/shared/collect-extension-options.js +8 -0
- package/dist/shared/hmac-signature.d.ts +2 -0
- package/dist/shared/hmac-signature.js +10 -0
- package/dist/shared/index.d.ts +6 -0
- package/dist/shared/index.js +6 -0
- package/dist/shared/is-unique-constraint-failure.d.ts +2 -0
- package/dist/shared/is-unique-constraint-failure.js +7 -0
- package/dist/shared/mail-locale-templates.d.ts +12 -0
- package/dist/shared/mail-locale-templates.js +36 -0
- package/dist/shared/resolve-feature-access.d.ts +7 -0
- package/dist/shared/resolve-feature-access.js +8 -0
- package/dist/shared/signed-token.js +4 -14
- package/dist/shared/single-use-token-store.js +2 -2
- package/dist/shared/stream-tenant-derived-state.js +1 -5
- package/dist/shared/tenant-db-cache.d.ts +3 -0
- package/dist/shared/tenant-db-cache.js +14 -0
- package/dist/shared/web/status-banner.d.ts +15 -0
- package/dist/shared/web/status-banner.js +13 -0
- package/dist/shared/web/use-dispatched-writes.d.ts +8 -0
- package/dist/shared/web/use-dispatched-writes.js +29 -0
- package/dist/subscription-paddle/feature.js +2 -15
- package/dist/subscription-paddle/price-methods.d.ts +2 -5
- package/dist/subscription-paddle/price-methods.js +5 -26
- package/dist/subscription-paddle/runtime.d.ts +1 -1
- package/dist/subscription-paddle/runtime.js +3 -16
- package/dist/subscription-stripe/feature.js +2 -17
- package/dist/subscription-stripe/plugin-methods.d.ts +2 -5
- package/dist/subscription-stripe/plugin-methods.js +3 -18
- package/dist/subscription-stripe/runtime.js +3 -19
- package/dist/tags/feature.js +2 -9
- package/dist/tags/web/tag-manager.js +5 -24
- package/dist/tags/web/tag-section.js +3 -12
- package/dist/template-resolver/handlers/tenant-overrides.query.js +3 -9
- package/dist/tenant/handlers/decrypt-member-users.d.ts +10 -0
- package/dist/tenant/handlers/decrypt-member-users.js +17 -0
- package/dist/tenant/handlers/members.query.js +2 -17
- package/dist/tenant/handlers/team-list.query.js +4 -17
- package/dist/tenant-lifecycle/archive-and-delete-tenant-rows.d.ts +5 -0
- package/dist/tenant-lifecycle/archive-and-delete-tenant-rows.js +20 -0
- package/dist/tenant-lifecycle/index.d.ts +1 -0
- package/dist/tenant-lifecycle/index.js +1 -0
- package/dist/tier-engine/feature.js +1 -1
- package/dist/user-data-rights/build-hook-db.d.ts +11 -0
- package/dist/user-data-rights/build-hook-db.js +22 -0
- package/dist/user-data-rights/handlers/request-export.write.js +2 -12
- package/dist/user-data-rights/mail-notifications.d.ts +3 -3
- package/dist/user-data-rights/mail-notifications.js +10 -34
- package/dist/user-data-rights/run-forget-cleanup.d.ts +1 -1
- package/dist/user-data-rights/run-forget-cleanup.js +2 -21
- package/dist/user-data-rights/run-user-export.d.ts +1 -1
- package/dist/user-data-rights/run-user-export.js +2 -21
- package/dist/user-data-rights/token-helpers.js +2 -14
- package/dist/user-data-rights/web/privacy-center-screen.js +1 -11
- package/dist/user-profile/web/profile-screen.js +1 -11
- package/package.json +20 -20
- package/src/auth-email-password/changes.json +6 -0
- package/src/auth-mfa/changes.json +6 -0
- package/src/billing-foundation/changes.json +6 -0
- package/src/shared/changes.json +6 -0
- package/src/tenant-lifecycle/changes.json +6 -0
|
@@ -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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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 =
|
|
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:
|
|
38
|
-
reason:
|
|
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:
|
|
66
|
-
reason:
|
|
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, {
|
|
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
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
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
|
-
|
|
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
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
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
|
-
|
|
35
|
-
|
|
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
|
}
|
package/dist/folders/feature.js
CHANGED
|
@@ -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 =
|
|
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 {
|
|
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
|
|
60
|
-
|
|
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
|
|
37
|
-
|
|
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 (!
|
|
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
|
-
|
|
173
|
-
|
|
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.
|
|
@@ -10,13 +10,11 @@
|
|
|
10
10
|
// Patterned after auth-email-password/signed-token.ts (HMAC-SHA256, purpose
|
|
11
11
|
// in the HMAC input, timing-safe comparison, expiry in the clear-text
|
|
12
12
|
// segment).
|
|
13
|
-
import {
|
|
13
|
+
import { randomUUID } from "node:crypto";
|
|
14
14
|
import { Temporal } from "@cosmicdrift/kumiko-types/temporal";
|
|
15
15
|
import { isPlainObject } from "@cosmicdrift/kumiko-types/type-guards";
|
|
16
|
+
import { hmacSignatureMatches, signHmacSha256Base64Url } from "../shared/index.js";
|
|
16
17
|
const STATE_PURPOSE = "inbound-mail-oauth-connect";
|
|
17
|
-
function sign(input, secret) {
|
|
18
|
-
return createHmac("sha256", secret).update(input).digest("base64url");
|
|
19
|
-
}
|
|
20
18
|
function hmacInput(payloadB64, expiresAtMs) {
|
|
21
19
|
return `${STATE_PURPOSE}:${payloadB64}.${expiresAtMs}`;
|
|
22
20
|
}
|
|
@@ -24,7 +22,7 @@ export function signOAuthState(payload, ttlMinutes, secret, now = Temporal.Now.i
|
|
|
24
22
|
const full = { ...payload, nonce: randomUUID() };
|
|
25
23
|
const payloadB64 = Buffer.from(JSON.stringify(full), "utf8").toString("base64url");
|
|
26
24
|
const expiresAtMs = now.add({ minutes: ttlMinutes }).epochMilliseconds;
|
|
27
|
-
const signature =
|
|
25
|
+
const signature = signHmacSha256Base64Url(hmacInput(payloadB64, expiresAtMs), secret);
|
|
28
26
|
return `${payloadB64}.${expiresAtMs}.${signature}`;
|
|
29
27
|
}
|
|
30
28
|
export function verifyOAuthState(state, secret, now = Temporal.Now.instant()) {
|
|
@@ -38,14 +36,8 @@ export function verifyOAuthState(state, secret, now = Temporal.Now.instant()) {
|
|
|
38
36
|
if (!Number.isFinite(expiresAtMs) || String(expiresAtMs) !== expiresAtRaw) {
|
|
39
37
|
return { ok: false, reason: "malformed" };
|
|
40
38
|
}
|
|
41
|
-
const expected =
|
|
42
|
-
|
|
43
|
-
const providedBuf = Buffer.from(providedSig, "base64url");
|
|
44
|
-
// Check the length before timingSafeEqual: it throws on a length mismatch,
|
|
45
|
-
// and the throw itself leaks information through timing.
|
|
46
|
-
if (expectedBuf.length !== providedBuf.length)
|
|
47
|
-
return { ok: false, reason: "bad_signature" };
|
|
48
|
-
if (!timingSafeEqual(expectedBuf, providedBuf))
|
|
39
|
+
const expected = signHmacSha256Base64Url(hmacInput(payloadB64, expiresAtMs), secret);
|
|
40
|
+
if (!hmacSignatureMatches(expected, providedSig))
|
|
49
41
|
return { ok: false, reason: "bad_signature" };
|
|
50
42
|
if (Temporal.Instant.compare(now, Temporal.Instant.fromEpochMilliseconds(expiresAtMs)) > 0) {
|
|
51
43
|
return { ok: false, reason: "expired" };
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import type { TenantDataHookCtx } from "@cosmicdrift/kumiko-framework/engine";
|
|
2
2
|
export declare const INBOUND_MAIL_TENANT_DESTROY_ARCHIVE_REASON = "tenant-destroy archives each inbound-mail entity's event-streams before the projection rows are deleted";
|
|
3
3
|
export declare function mailAccountTenantDestroyHook(ctx: TenantDataHookCtx): Promise<void>;
|
|
4
4
|
export declare function inboundMessageTenantDestroyHook(ctx: TenantDataHookCtx): Promise<void>;
|