@cosmicdrift/kumiko-bundled-features 0.414.0 → 0.415.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/auth-email-password/signup-token-store.d.ts +2 -2
- package/dist/auth-email-password/signup-token-store.js +2 -4
- package/dist/auth-email-password/web/session.js +2 -1
- package/dist/billing-foundation/checkout-core.d.ts +2 -0
- package/dist/billing-foundation/checkout-core.js +9 -0
- package/dist/billing-foundation/checkout-ledger.d.ts +7 -0
- package/dist/billing-foundation/checkout-ledger.js +6 -0
- package/dist/billing-foundation/events.d.ts +1 -0
- package/dist/billing-foundation/events.js +6 -5
- package/dist/billing-foundation/handlers/create-checkout-session.write.js +2 -1
- package/dist/billing-foundation/handlers/process-event.write.d.ts +3 -1
- package/dist/billing-foundation/handlers/process-event.write.js +57 -32
- package/dist/billing-foundation/handlers/process-payment-event.write.js +5 -5
- package/dist/billing-foundation/handlers/start-plan-checkout.write.js +2 -1
- package/dist/billing-foundation/webhook-handler.js +2 -2
- package/dist/channel-whatsapp/events.d.ts +3 -0
- package/dist/channel-whatsapp/events.js +4 -3
- package/dist/channel-whatsapp/inbound-handlers.js +24 -3
- package/dist/channel-whatsapp/webhook-normalize.js +21 -6
- package/dist/compliance-profiles/handlers/set-profile.write.js +2 -0
- package/dist/data-retention/feature.js +1 -0
- package/dist/delivery/handlers/opted-in-user-ids.query.js +12 -3
- package/dist/document-ingest-foundation/feature.js +1 -0
- package/dist/document-ingest-foundation/report-ingest-progress.js +4 -1
- package/dist/documents/feature.d.ts +2 -2
- package/dist/documents/feature.js +7 -2
- package/dist/form-draft/feature.js +1 -0
- package/dist/helpdesk/feature.js +1 -0
- package/dist/helpdesk/handlers/reply.write.js +3 -3
- package/dist/helpdesk/handlers/report.write.js +3 -2
- package/dist/helpdesk/handlers/submit.write.js +3 -2
- package/dist/helpdesk/legacy-contact-streams.js +5 -2
- package/dist/helpdesk/lib.d.ts +1 -1
- package/dist/helpdesk/lib.js +4 -4
- package/dist/inbound-mail-foundation/account-poll.js +2 -0
- package/dist/inbound-mail-foundation/content-refetch.d.ts +3 -0
- package/dist/inbound-mail-foundation/content-refetch.js +2 -6
- package/dist/inbound-mail-foundation/entities.js +10 -9
- package/dist/inbound-mail-foundation/events.js +10 -9
- package/dist/inbound-mail-foundation/handlers/connect-account.write.js +2 -1
- package/dist/inbound-mail-foundation/handlers/forget-message.write.js +4 -0
- package/dist/inbound-mail-foundation/handlers/ingest-message-schema.js +12 -5
- package/dist/inbound-mail-foundation/normalize-inbound-message.d.ts +6 -0
- package/dist/inbound-mail-foundation/normalize-inbound-message.js +21 -8
- package/dist/inbound-mail-foundation/sanitize-inbound-html.d.ts +0 -1
- package/dist/inbound-mail-foundation/sanitize-inbound-html.js +2 -4
- package/dist/managed-pages/web/page-edit-screen.js +12 -5
- package/dist/shared/hmac-signature.js +4 -2
- package/dist/shared/index.d.ts +2 -1
- package/dist/shared/index.js +2 -1
- package/dist/shared/normalize-email.d.ts +1 -0
- package/dist/shared/normalize-email.js +3 -0
- package/dist/shared/send-best-effort.d.ts +1 -0
- package/dist/shared/send-best-effort.js +10 -5
- package/dist/step-dispatcher/deliver-dispatch-request.js +5 -3
- package/dist/step-dispatcher/feature.js +11 -0
- package/dist/step-dispatcher/sweep-abandoned.d.ts +1 -0
- package/dist/step-dispatcher/sweep-abandoned.js +3 -0
- package/dist/subscription-paddle/backfill-checkout-ledger.js +2 -0
- package/dist/subscription-paddle/redeliver-legacy-checkout.js +19 -2
- package/dist/subscription-stripe/verify-webhook.js +16 -6
- package/dist/template-resolver/seeding.js +32 -7
- package/dist/template-resolver/web/web-preview-renderer.js +5 -1
- package/dist/tenant-inactivity/check-inactive-tenants.js +27 -16
- package/dist/tenant-inactivity/handlers/keep-account.write.js +7 -0
- package/dist/tenant-inactivity/state-store.d.ts +2 -1
- package/dist/tenant-inactivity/state-store.js +7 -0
- package/dist/tenant-lifecycle/feature.js +1 -0
- package/dist/user/resolve-verified-user-email.js +3 -3
- package/dist/user-data-rights/feature.js +1 -0
- package/dist/waitlist/handlers/reject.write.js +2 -1
- package/dist/waitlist/handlers/submit.write.js +2 -2
- package/dist/waitlist/import.js +2 -1
- package/dist/waitlist/lib.d.ts +0 -1
- package/dist/waitlist/lib.js +1 -4
- package/dist/waitlist/link-on-signup.js +2 -2
- package/dist/workflow-runner/handlers/resume-run.write.js +4 -3
- package/package.json +11 -11
- package/src/auth-mfa/changes.json +6 -0
- package/src/billing-foundation/changes.json +24 -0
- package/src/channel-whatsapp/changes.json +24 -0
- package/src/compliance-profiles/changes.json +5 -0
- package/src/delivery/changes.json +6 -0
- package/src/document-ingest-foundation/changes.json +6 -0
- package/src/documents/changes.json +6 -0
- package/src/helpdesk/changes.json +6 -0
- package/src/inbound-mail-foundation/changes.json +6 -0
- package/src/shared/changes.json +6 -0
- package/src/step-dispatcher/changes.json +6 -0
- package/src/subscription-paddle/changes.json +6 -0
- package/src/subscription-stripe/changes.json +6 -0
- package/src/template-resolver/changes.json +12 -0
- package/src/tenant-inactivity/changes.json +6 -0
- package/src/tenant-lifecycle/changes.json +6 -0
- package/src/workflow-runner/changes.json +6 -0
|
@@ -1,10 +1,10 @@
|
|
|
1
1
|
import type { Redis } from "ioredis";
|
|
2
|
-
import { type SignupHandoverBinding } from "../shared/index.ts";
|
|
2
|
+
import { normalizeEmail, type SignupHandoverBinding } from "../shared/index.ts";
|
|
3
3
|
/** Email normalization — single source for every lookup layer (used
|
|
4
4
|
* internally by the store AND by callers that need a consistent form
|
|
5
5
|
* in the return body / mail send). Previously two places called
|
|
6
6
|
* `.toLowerCase()` — one source means no drift. */
|
|
7
|
-
export
|
|
7
|
+
export { normalizeEmail };
|
|
8
8
|
export declare const SIGNUP_TOKEN_KEY_PREFIXES: {
|
|
9
9
|
readonly token: "signup:by-token:";
|
|
10
10
|
readonly email: "signup:by-email:";
|
|
@@ -10,14 +10,12 @@
|
|
|
10
10
|
// No collision with reset/verify/invite tokens: all signup keys carry the
|
|
11
11
|
// `signup:`-prefix.
|
|
12
12
|
import * as z from "zod";
|
|
13
|
-
import { createSingleUseTokenStore, hashSingleUseToken, } from "../shared/index.js";
|
|
13
|
+
import { createSingleUseTokenStore, hashSingleUseToken, normalizeEmail, } from "../shared/index.js";
|
|
14
14
|
/** Email normalization — single source for every lookup layer (used
|
|
15
15
|
* internally by the store AND by callers that need a consistent form
|
|
16
16
|
* in the return body / mail send). Previously two places called
|
|
17
17
|
* `.toLowerCase()` — one source means no drift. */
|
|
18
|
-
export
|
|
19
|
-
return email.toLowerCase();
|
|
20
|
-
}
|
|
18
|
+
export { normalizeEmail };
|
|
21
19
|
export const SIGNUP_TOKEN_KEY_PREFIXES = {
|
|
22
20
|
token: "signup:by-token:",
|
|
23
21
|
email: "signup:by-email:",
|
|
@@ -10,7 +10,7 @@ import { jsx as _jsx } from "react/jsx-runtime";
|
|
|
10
10
|
// and transitions.
|
|
11
11
|
import { CurrentUserProvider, useSessionEndedSignal, } from "@cosmicdrift/kumiko-renderer";
|
|
12
12
|
import { readCsrfToken } from "@cosmicdrift/kumiko-renderer/live";
|
|
13
|
-
import { clearRememberedListState } from "@cosmicdrift/kumiko-renderer/web";
|
|
13
|
+
import { clearNavCollapseState, clearRememberedListState } from "@cosmicdrift/kumiko-renderer/web";
|
|
14
14
|
import { createContext, useCallback, useContext, useEffect, useMemo, useState, } from "react";
|
|
15
15
|
import { AuthRequestError, fetchCurrentUser, fetchTenants, login as loginApi, logout as logoutApi, switchTenant as switchTenantApi, } from "./auth-client.js";
|
|
16
16
|
// Exported so screens that render on BOTH authenticated and anonymous public
|
|
@@ -130,6 +130,7 @@ export function SessionProvider({ children, postLogoutUrl, }) {
|
|
|
130
130
|
await logoutApi();
|
|
131
131
|
// The reload below would hide the identity change from the list-state boot.
|
|
132
132
|
clearRememberedListState();
|
|
133
|
+
clearNavCollapseState();
|
|
133
134
|
if (typeof window === "undefined") {
|
|
134
135
|
setState(UNAUTHENTICATED);
|
|
135
136
|
return;
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
/// <reference types="temporal-polyfill/global" preserve="true" />
|
|
2
2
|
import type { HandlerContext } from "@cosmicdrift/kumiko-framework/engine";
|
|
3
|
+
import type { RateLimitOption } from "@cosmicdrift/kumiko-types/handlers";
|
|
3
4
|
import { getSubscriptionForTenant } from "./get-subscription-for-tenant.ts";
|
|
4
5
|
import type { BillingFoundationOptions, BillingPlanCatalog, SubscriptionProviderPlugin } from "./types.ts";
|
|
5
6
|
/** Narrows a `readonly string[]` to the non-empty tuple shape `z.enum`
|
|
@@ -103,6 +104,7 @@ type CheckoutCapableProvider = SubscriptionProviderPlugin & {
|
|
|
103
104
|
* `mode: "payment"` (one-off top-ups etc.) skips the price/subscription
|
|
104
105
|
* gates — those apply to recurring subscriptions only. */
|
|
105
106
|
export declare function assertCheckoutAllowed(ctx: HandlerContext, options: OpenCheckoutOptions, input: OpenCheckoutInput): Promise<CheckoutCapableProvider>;
|
|
107
|
+
export declare const CHECKOUT_START_RATE_LIMIT: RateLimitOption;
|
|
106
108
|
export declare function startProviderCheckout(ctx: HandlerContext, plugin: CheckoutCapableProvider, input: OpenCheckoutInput): Promise<{
|
|
107
109
|
readonly url: string;
|
|
108
110
|
readonly providerName: string;
|
|
@@ -259,6 +259,15 @@ export async function assertCheckoutAllowed(ctx, options, input) {
|
|
|
259
259
|
}
|
|
260
260
|
return plugin;
|
|
261
261
|
}
|
|
262
|
+
// Every started checkout appends a `checkout-opened` to the tenant's event stream, and the
|
|
263
|
+
// webhook reads that whole stream, so unbounded starts would grow every later webhook. A real
|
|
264
|
+
// customer never opens this many checkouts per hour. Per handler, so each checkout-starting
|
|
265
|
+
// handler gets its own bucket.
|
|
266
|
+
export const CHECKOUT_START_RATE_LIMIT = {
|
|
267
|
+
per: "tenant+handler",
|
|
268
|
+
limit: 30,
|
|
269
|
+
windowSeconds: 60 * 60,
|
|
270
|
+
};
|
|
262
271
|
export async function startProviderCheckout(ctx, plugin, input) {
|
|
263
272
|
const result = await plugin.createCheckoutSession(ctx, {
|
|
264
273
|
priceId: input.priceId,
|
|
@@ -1,5 +1,12 @@
|
|
|
1
1
|
import type { HandlerContext } from "@cosmicdrift/kumiko-framework/engine";
|
|
2
2
|
import { type CheckoutOpenedPayload } from "./events.ts";
|
|
3
|
+
export declare const IgnoredEventReasons: {
|
|
4
|
+
readonly checkoutNotInLedger: "checkout_not_in_ledger";
|
|
5
|
+
readonly priceMismatch: "price_mismatch";
|
|
6
|
+
readonly foreignSubscription: "foreign_subscription";
|
|
7
|
+
readonly subscriptionNotYetCreated: "subscription_not_yet_created";
|
|
8
|
+
};
|
|
9
|
+
export type IgnoredEventReason = (typeof IgnoredEventReasons)[keyof typeof IgnoredEventReasons];
|
|
3
10
|
type CheckoutMode = CheckoutOpenedPayload["mode"];
|
|
4
11
|
export type CheckoutLookup = {
|
|
5
12
|
readonly providerName: string;
|
|
@@ -3,6 +3,12 @@
|
|
|
3
3
|
// accept a webhook only when it names a checkout found here.
|
|
4
4
|
import { paymentAggregateId, subscriptionAggregateId } from "./aggregate-id.js";
|
|
5
5
|
import { CHECKOUT_OPENED_EVENT_QN, checkoutOpenedPayloadSchema, PAYMENT_AGGREGATE_TYPE, SUBSCRIPTION_AGGREGATE_TYPE, } from "./events.js";
|
|
6
|
+
export const IgnoredEventReasons = {
|
|
7
|
+
checkoutNotInLedger: "checkout_not_in_ledger",
|
|
8
|
+
priceMismatch: "price_mismatch",
|
|
9
|
+
foreignSubscription: "foreign_subscription",
|
|
10
|
+
subscriptionNotYetCreated: "subscription_not_yet_created",
|
|
11
|
+
};
|
|
6
12
|
export function ledgerAggregateId(tenantId, mode) {
|
|
7
13
|
return mode === "subscription" ? subscriptionAggregateId(tenantId) : paymentAggregateId(tenantId);
|
|
8
14
|
}
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import * as z from "zod";
|
|
2
|
+
export declare const PROVIDER_ID_MAX_CHARS = 200;
|
|
2
3
|
export declare const SUBSCRIPTION_AGGREGATE_TYPE: "subscription";
|
|
3
4
|
export declare const SUBSCRIPTION_CREATED_EVENT_SHORT: "subscription-created";
|
|
4
5
|
export declare const SUBSCRIPTION_UPDATED_EVENT_SHORT: "subscription-updated";
|
|
@@ -13,6 +13,7 @@ import { piiCiphertextMaxLengthFor } from "@cosmicdrift/kumiko-framework/crypto"
|
|
|
13
13
|
import * as z from "zod";
|
|
14
14
|
import { BILLING_FOUNDATION_FEATURE, SubscriptionStatuses } from "./web/constants.js";
|
|
15
15
|
import { CONSENT_LOCALES } from "./web/consumer-protection/consent-locale.js";
|
|
16
|
+
export const PROVIDER_ID_MAX_CHARS = 200;
|
|
16
17
|
// Aggregate type for the event store. One subscription per tenant is
|
|
17
18
|
// one stream; the subscriptionAggregateId helper provides the stream ID.
|
|
18
19
|
export const SUBSCRIPTION_AGGREGATE_TYPE = "subscription";
|
|
@@ -43,9 +44,9 @@ const statusEnum = z.enum([
|
|
|
43
44
|
// PII, and event headers cannot be crypto-shredded.
|
|
44
45
|
export const subscriptionEventPayloadSchema = z.object({
|
|
45
46
|
providerName: z.string().min(1).max(50),
|
|
46
|
-
// Ciphertext, not the raw id:
|
|
47
|
-
providerCustomerId: z.string().min(1).max(piiCiphertextMaxLengthFor(
|
|
48
|
-
providerSubscriptionId: z.string().min(1).max(piiCiphertextMaxLengthFor(
|
|
47
|
+
// Ciphertext, not the raw id: the plaintext id is limited to PROVIDER_ID_MAX_CHARS.
|
|
48
|
+
providerCustomerId: z.string().min(1).max(piiCiphertextMaxLengthFor(PROVIDER_ID_MAX_CHARS)),
|
|
49
|
+
providerSubscriptionId: z.string().min(1).max(piiCiphertextMaxLengthFor(PROVIDER_ID_MAX_CHARS)),
|
|
49
50
|
status: statusEnum,
|
|
50
51
|
tier: z.string().min(1).max(50),
|
|
51
52
|
currentPeriodEndIso: z.string().min(1),
|
|
@@ -72,8 +73,8 @@ export const PAYMENT_RECEIVED_EVENT_SHORT = "payment-received";
|
|
|
72
73
|
export const PAYMENT_RECEIVED_EVENT_QN = `${BILLING_FOUNDATION_FEATURE}:event:${PAYMENT_RECEIVED_EVENT_SHORT}`;
|
|
73
74
|
export const paymentEventPayloadSchema = z.object({
|
|
74
75
|
providerName: z.string().min(1).max(50),
|
|
75
|
-
// Ciphertext, not the raw id (plaintext limit
|
|
76
|
-
providerCustomerId: z.string().min(1).max(piiCiphertextMaxLengthFor(
|
|
76
|
+
// Ciphertext, not the raw id (plaintext limit PROVIDER_ID_MAX_CHARS).
|
|
77
|
+
providerCustomerId: z.string().min(1).max(piiCiphertextMaxLengthFor(PROVIDER_ID_MAX_CHARS)),
|
|
77
78
|
priceId: z.string().min(1).max(200),
|
|
78
79
|
// Optional so payloads stored before quantity existed still parse; absent = 1.
|
|
79
80
|
quantity: z.number().int().positive().optional(),
|
|
@@ -23,7 +23,7 @@
|
|
|
23
23
|
// hand-picked priceId.
|
|
24
24
|
import { InternalError, UnprocessableError } from "@cosmicdrift/kumiko-framework/errors";
|
|
25
25
|
import * as z from "zod";
|
|
26
|
-
import { assertCheckoutAllowed, openCheckout, startProviderCheckout, } from "../checkout-core.js";
|
|
26
|
+
import { assertCheckoutAllowed, CHECKOUT_START_RATE_LIMIT, openCheckout, startProviderCheckout, } from "../checkout-core.js";
|
|
27
27
|
import { assertValidOrderItem, consentCheckoutFields, consentPayloadSchema, prepareConsent, recordConsent, } from "../consumer-protection/consent-gate.js";
|
|
28
28
|
import { withOwnProviderCustomer } from "../one-off-customer.js";
|
|
29
29
|
const createCheckoutSessionSchema = z.object({
|
|
@@ -56,6 +56,7 @@ export function createCheckoutSessionHandler(options) {
|
|
|
56
56
|
// Tenant-Admin-only — the tenant must deliberately configure its own
|
|
57
57
|
// subscription. SystemAdmin as a fallback for operator-initiated flows.
|
|
58
58
|
access: { roles: ["TenantAdmin", "SystemAdmin"] },
|
|
59
|
+
rateLimit: CHECKOUT_START_RATE_LIMIT,
|
|
59
60
|
handler: async (event, ctx) => {
|
|
60
61
|
// @cast-boundary engine-payload — dispatcher-zod-validated payload
|
|
61
62
|
const payload = event.payload;
|
|
@@ -33,10 +33,12 @@ export declare function isLateStateEvent(storedEvents: readonly {
|
|
|
33
33
|
readonly headers?: Record<string, unknown>;
|
|
34
34
|
};
|
|
35
35
|
}[], payload: ProcessEventPayload): boolean;
|
|
36
|
+
type SubscriptionStreamEvent = Awaited<ReturnType<HandlerContext["events"]["load"]>>[number];
|
|
36
37
|
export declare function clampProviderEventAt(payload: ProcessEventPayload, now: Temporal.Instant): ProcessEventPayload;
|
|
37
|
-
export declare function appendSubscriptionEvent(ctx: HandlerContext, tenantId: string, rawPayload: ProcessEventPayload, now?: Temporal.Instant, consentId?: string): Promise<{
|
|
38
|
+
export declare function appendSubscriptionEvent(ctx: HandlerContext, tenantId: string, rawPayload: ProcessEventPayload, now?: Temporal.Instant, consentId?: string, lockedStream?: readonly SubscriptionStreamEvent[]): Promise<{
|
|
38
39
|
readonly duplicate: boolean;
|
|
39
40
|
readonly stale?: true;
|
|
40
41
|
readonly subscriptionAggregateId: string;
|
|
41
42
|
}>;
|
|
42
43
|
export declare function createProcessEventHandler(now: () => Temporal.Instant): WriteHandlerDef;
|
|
44
|
+
export {};
|
|
@@ -20,9 +20,9 @@ import { propertyOf } from "@cosmicdrift/kumiko-types/type-guards";
|
|
|
20
20
|
import * as z from "zod";
|
|
21
21
|
import { subscriptionAggregateId } from "../aggregate-id.js";
|
|
22
22
|
import { findProviderPlugin } from "../checkout-core.js";
|
|
23
|
-
import { findCheckoutOpened } from "../checkout-ledger.js";
|
|
23
|
+
import { findCheckoutOpened, IgnoredEventReasons, } from "../checkout-ledger.js";
|
|
24
24
|
import { SUBSCRIPTION_PII_FIELDS, subscriptionEntity } from "../entities.js";
|
|
25
|
-
import { CHECKOUT_CONSENT_RECORDED_EVENT_QN, checkoutConsentRecordedPayloadSchema, 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";
|
|
25
|
+
import { CHECKOUT_CONSENT_RECORDED_EVENT_QN, checkoutConsentRecordedPayloadSchema, INVOICE_PAID_EVENT_QN, INVOICE_PAYMENT_FAILED_EVENT_QN, PROVIDER_ID_MAX_CHARS, SUBSCRIPTION_AGGREGATE_TYPE, SUBSCRIPTION_CANCELED_EVENT_QN, SUBSCRIPTION_CREATED_EVENT_QN, SUBSCRIPTION_UPDATED_EVENT_QN, } from "../events.js";
|
|
26
26
|
import { getSubscriptionForTenant } from "../get-subscription-for-tenant.js";
|
|
27
27
|
import { hasSeenProviderEvent } from "../provider-event-seen.js";
|
|
28
28
|
import { BILLING_SUBSCRIPTION_LOCK_NAMESPACE, isSubscriptionBlockingCheckout, isSwitchableSubscriptionStatus, SubscriptionEventTypes, SubscriptionStatuses, } from "../web/constants.js";
|
|
@@ -49,8 +49,8 @@ export const processEventSchema = z.object({
|
|
|
49
49
|
providerEventId: z.string().min(1).max(200),
|
|
50
50
|
providerName: z.string().min(1).max(50),
|
|
51
51
|
type: eventTypeSchema,
|
|
52
|
-
providerCustomerId: z.string().min(1).max(
|
|
53
|
-
providerSubscriptionId: z.string().min(1).max(
|
|
52
|
+
providerCustomerId: z.string().min(1).max(PROVIDER_ID_MAX_CHARS),
|
|
53
|
+
providerSubscriptionId: z.string().min(1).max(PROVIDER_ID_MAX_CHARS),
|
|
54
54
|
status: statusSchema,
|
|
55
55
|
tier: z.string().min(1).max(50),
|
|
56
56
|
currentPeriodEndIso: z.string().min(1),
|
|
@@ -103,12 +103,10 @@ export function isLateStateEvent(storedEvents, payload) {
|
|
|
103
103
|
}
|
|
104
104
|
});
|
|
105
105
|
}
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
// who constructs `payload` and what `providerEventId` they use.
|
|
111
|
-
// =============================================================================
|
|
106
|
+
async function lockAndLoadSubscriptionStream(ctx, aggId) {
|
|
107
|
+
await ctx.db.advisoryXactLock(BILLING_SUBSCRIPTION_LOCK_NAMESPACE, aggId);
|
|
108
|
+
return ctx.events.load(aggId);
|
|
109
|
+
}
|
|
112
110
|
// A provider timestamp far in the future would make every later, genuine event look late.
|
|
113
111
|
const PROVIDER_EVENT_CLOCK_SKEW_SECONDS = 300;
|
|
114
112
|
export function clampProviderEventAt(payload, now) {
|
|
@@ -119,13 +117,12 @@ export function clampProviderEventAt(payload, now) {
|
|
|
119
117
|
? { ...payload, providerEventAtIso: ceiling.toString() }
|
|
120
118
|
: payload;
|
|
121
119
|
}
|
|
122
|
-
export async function appendSubscriptionEvent(ctx, tenantId, rawPayload, now = Temporal.Now.instant(), consentId) {
|
|
120
|
+
export async function appendSubscriptionEvent(ctx, tenantId, rawPayload, now = Temporal.Now.instant(), consentId, lockedStream) {
|
|
123
121
|
const aggId = subscriptionAggregateId(tenantId);
|
|
124
122
|
const payload = clampProviderEventAt(rawPayload, now);
|
|
125
|
-
//
|
|
126
|
-
// stream version itself, so without
|
|
127
|
-
//
|
|
128
|
-
await ctx.db.advisoryXactLock(BILLING_SUBSCRIPTION_LOCK_NAMESPACE, aggId);
|
|
123
|
+
// The lock serialises the read (idempotency + late check) with the append: the append re-reads the
|
|
124
|
+
// stream version itself, so without it a concurrent delivery could slip in between and the late
|
|
125
|
+
// check would have judged an outdated stream. A caller that already holds it passes its stream.
|
|
129
126
|
// ---------------------------------------------------------------
|
|
130
127
|
// 1. Idempotency: load the subscription stream and check whether this
|
|
131
128
|
// providerEventId was already seen. A provider retry storm (Stripe
|
|
@@ -137,7 +134,7 @@ export async function appendSubscriptionEvent(ctx, tenantId, rawPayload, now = T
|
|
|
137
134
|
// streams, optimize via snapshot or a per-tenant dedup table as the
|
|
138
135
|
// idempotency anchor (like cap-counter).
|
|
139
136
|
// ---------------------------------------------------------------
|
|
140
|
-
const existingEvents = await ctx
|
|
137
|
+
const existingEvents = lockedStream ?? (await lockAndLoadSubscriptionStream(ctx, aggId));
|
|
141
138
|
if (hasSeenProviderEvent(existingEvents, payload)) {
|
|
142
139
|
return { duplicate: true, subscriptionAggregateId: aggId };
|
|
143
140
|
}
|
|
@@ -240,23 +237,32 @@ function isBoundToLedgerEntry(ctx, entry, payload) {
|
|
|
240
237
|
return plugin?.priceToTier?.[entry.priceId] === payload.tier;
|
|
241
238
|
}
|
|
242
239
|
// A plan switch has no checkout of its own: its consent is the newest one recorded for the target
|
|
243
|
-
// tier
|
|
244
|
-
|
|
245
|
-
|
|
240
|
+
// tier, as long as no stored subscription event carries it yet. No window by state events: another
|
|
241
|
+
// state event (renewal, status change) may arrive between the consent and the tier change. The age
|
|
242
|
+
// limit keeps an abandoned consent from being attached to a portal switch months later.
|
|
243
|
+
const SWITCH_CONSENT_MAX_AGE_HOURS = 24;
|
|
244
|
+
function providerEventInstant(payload, now) {
|
|
245
|
+
const iso = clampProviderEventAt(payload, now).providerEventAtIso;
|
|
246
|
+
return iso === undefined ? now : Temporal.Instant.from(iso);
|
|
247
|
+
}
|
|
248
|
+
function pendingSwitchConsentId(storedEvents, payload, now) {
|
|
249
|
+
const referenceAt = providerEventInstant(payload, now);
|
|
250
|
+
const oldestAcceptedAt = referenceAt.subtract({ hours: SWITCH_CONSENT_MAX_AGE_HOURS });
|
|
246
251
|
const carried = new Set();
|
|
247
|
-
|
|
252
|
+
for (const stored of storedEvents) {
|
|
248
253
|
// skip: only subscription state events can carry a consent
|
|
249
254
|
if (!STATE_EVENT_QNS.has(stored.type))
|
|
250
|
-
|
|
251
|
-
lastStateIndex = index;
|
|
255
|
+
continue;
|
|
252
256
|
const consentId = propertyOf(stored.payload, "consentId");
|
|
253
257
|
if (typeof consentId === "string")
|
|
254
258
|
carried.add(consentId);
|
|
255
|
-
}
|
|
256
|
-
for (let index = storedEvents.length - 1; index
|
|
259
|
+
}
|
|
260
|
+
for (let index = storedEvents.length - 1; index >= 0; index--) {
|
|
257
261
|
const stored = storedEvents[index];
|
|
258
262
|
if (stored?.type !== CHECKOUT_CONSENT_RECORDED_EVENT_QN)
|
|
259
263
|
continue;
|
|
264
|
+
if (Temporal.Instant.compare(stored.createdAt, oldestAcceptedAt) < 0)
|
|
265
|
+
continue;
|
|
260
266
|
const parsed = checkoutConsentRecordedPayloadSchema.safeParse(stored.payload);
|
|
261
267
|
if (!parsed.success)
|
|
262
268
|
continue;
|
|
@@ -270,7 +276,18 @@ function pendingSwitchConsentId(storedEvents, payload) {
|
|
|
270
276
|
}
|
|
271
277
|
return undefined;
|
|
272
278
|
}
|
|
273
|
-
|
|
279
|
+
// A `created` that never comes (subscription from before the ledger, foreign custom_data, deleted
|
|
280
|
+
// subscription) would otherwise answer 503 until the provider gives up, and Stripe disables an
|
|
281
|
+
// endpoint that keeps failing. Only a young event may still be overtaken by its `created`.
|
|
282
|
+
// A provider that sends no event time (mollie) cannot be aged and keeps retrying.
|
|
283
|
+
const MISSING_SUBSCRIPTION_RETRY_WINDOW_MINUTES = 60;
|
|
284
|
+
function isWithinMissingSubscriptionRetryWindow(payload, now) {
|
|
285
|
+
if (payload.providerEventAtIso === undefined)
|
|
286
|
+
return true;
|
|
287
|
+
const oldestRetriedAt = now.subtract({ minutes: MISSING_SUBSCRIPTION_RETRY_WINDOW_MINUTES });
|
|
288
|
+
return Temporal.Instant.compare(providerEventInstant(payload, now), oldestRetriedAt) >= 0;
|
|
289
|
+
}
|
|
290
|
+
function admitProviderEvent(ctx, storedEvents, current, payload, now) {
|
|
274
291
|
const entry = payload.providerCheckoutId === undefined
|
|
275
292
|
? undefined
|
|
276
293
|
: findCheckoutOpened(storedEvents, {
|
|
@@ -282,18 +299,23 @@ function admitProviderEvent(ctx, storedEvents, current, payload) {
|
|
|
282
299
|
return { admitted: true, ...(entry.consentId !== undefined && { consentId: entry.consentId }) };
|
|
283
300
|
}
|
|
284
301
|
if (payload.type === SubscriptionEventTypes.created) {
|
|
285
|
-
return { admitted: false, reason:
|
|
302
|
+
return { admitted: false, reason: IgnoredEventReasons.checkoutNotInLedger };
|
|
286
303
|
}
|
|
287
304
|
// The provider does not guarantee order: an update that beats the `created` of its
|
|
288
305
|
// subscription must be redelivered, not dropped.
|
|
289
|
-
if (current === null)
|
|
290
|
-
return {
|
|
306
|
+
if (current === null) {
|
|
307
|
+
return {
|
|
308
|
+
admitted: false,
|
|
309
|
+
reason: IgnoredEventReasons.subscriptionNotYetCreated,
|
|
310
|
+
...(isWithinMissingSubscriptionRetryWindow(payload, now) && { retry: true }),
|
|
311
|
+
};
|
|
312
|
+
}
|
|
291
313
|
const isCurrentSubscription = current.providerName === payload.providerName &&
|
|
292
314
|
current.providerSubscriptionId === payload.providerSubscriptionId;
|
|
293
315
|
if (!isCurrentSubscription)
|
|
294
|
-
return { admitted: false, reason:
|
|
316
|
+
return { admitted: false, reason: IgnoredEventReasons.foreignSubscription };
|
|
295
317
|
const switchConsentId = payload.type === SubscriptionEventTypes.updated && current.tier !== payload.tier
|
|
296
|
-
? pendingSwitchConsentId(storedEvents, payload)
|
|
318
|
+
? pendingSwitchConsentId(storedEvents, payload, now)
|
|
297
319
|
: undefined;
|
|
298
320
|
return { admitted: true, ...(switchConsentId !== undefined && { consentId: switchConsentId }) };
|
|
299
321
|
}
|
|
@@ -307,8 +329,11 @@ export function createProcessEventHandler(now) {
|
|
|
307
329
|
// @cast-boundary engine-payload — dispatcher-zod-validated payload
|
|
308
330
|
const payload = event.payload;
|
|
309
331
|
const aggId = subscriptionAggregateId(event.user.tenantId);
|
|
332
|
+
// One locked load serves admission and the append; the stream grows with every opened checkout.
|
|
333
|
+
// The lock comes first so the stream and `current` are both read under it.
|
|
334
|
+
const stream = await lockAndLoadSubscriptionStream(ctx, aggId);
|
|
310
335
|
const current = await getSubscriptionForTenant(ctx, event.user.tenantId);
|
|
311
|
-
const admission = admitProviderEvent(ctx,
|
|
336
|
+
const admission = admitProviderEvent(ctx, stream, current, payload, now());
|
|
312
337
|
if (!admission.admitted) {
|
|
313
338
|
ctx.obs.log?.warn(`[billing-foundation:process-event] ignored ${payload.type} ${payload.providerEventId} (${admission.reason}): provider ${payload.providerName}`);
|
|
314
339
|
return {
|
|
@@ -328,7 +353,7 @@ export function createProcessEventHandler(now) {
|
|
|
328
353
|
data: { duplicate: false, stale: true, subscriptionAggregateId: aggId },
|
|
329
354
|
};
|
|
330
355
|
}
|
|
331
|
-
const result = await appendSubscriptionEvent(ctx, event.user.tenantId, payload, now(), admission.consentId);
|
|
356
|
+
const result = await appendSubscriptionEvent(ctx, event.user.tenantId, payload, now(), admission.consentId, stream);
|
|
332
357
|
return { isSuccess: true, data: result };
|
|
333
358
|
},
|
|
334
359
|
};
|
|
@@ -14,15 +14,15 @@
|
|
|
14
14
|
import { configuredPiiSubjectKms, encryptPiiFieldValues, } from "@cosmicdrift/kumiko-framework/crypto";
|
|
15
15
|
import * as z from "zod";
|
|
16
16
|
import { paymentAggregateId } from "../aggregate-id.js";
|
|
17
|
-
import { findCheckoutOpened } from "../checkout-ledger.js";
|
|
17
|
+
import { findCheckoutOpened, IgnoredEventReasons } from "../checkout-ledger.js";
|
|
18
18
|
import { PAYMENT_PII_FIELDS, paymentEntity } from "../entities.js";
|
|
19
|
-
import { PAYMENT_AGGREGATE_TYPE, PAYMENT_RECEIVED_EVENT_QN, } from "../events.js";
|
|
19
|
+
import { PAYMENT_AGGREGATE_TYPE, PAYMENT_RECEIVED_EVENT_QN, PROVIDER_ID_MAX_CHARS, } from "../events.js";
|
|
20
20
|
import { hasSeenProviderEvent } from "../provider-event-seen.js";
|
|
21
21
|
export const processPaymentEventSchema = z.object({
|
|
22
22
|
providerEventId: z.string().min(1).max(200),
|
|
23
23
|
providerName: z.string().min(1).max(50),
|
|
24
24
|
providerCheckoutId: z.string().min(1).max(200),
|
|
25
|
-
providerCustomerId: z.string().min(1).max(
|
|
25
|
+
providerCustomerId: z.string().min(1).max(PROVIDER_ID_MAX_CHARS),
|
|
26
26
|
priceId: z.string().min(1).max(200),
|
|
27
27
|
quantity: z.number().int().positive().optional(),
|
|
28
28
|
});
|
|
@@ -61,9 +61,9 @@ export const processPaymentEventHandler = {
|
|
|
61
61
|
mode: "payment",
|
|
62
62
|
});
|
|
63
63
|
const rejection = entry === undefined
|
|
64
|
-
?
|
|
64
|
+
? IgnoredEventReasons.checkoutNotInLedger
|
|
65
65
|
: entry.priceId !== payload.priceId
|
|
66
|
-
?
|
|
66
|
+
? IgnoredEventReasons.priceMismatch
|
|
67
67
|
: undefined;
|
|
68
68
|
if (rejection !== undefined) {
|
|
69
69
|
ctx.obs.log?.warn(`[billing-foundation:process-payment-event] ignored ${payload.providerEventId} (${rejection}): checkout ${payload.providerCheckoutId} of provider ${payload.providerName}`);
|
|
@@ -4,7 +4,7 @@
|
|
|
4
4
|
// Only registered when `createBillingFoundationFeature` gets a `catalog`.
|
|
5
5
|
import { FeatureDisabledError, UnprocessableError } from "@cosmicdrift/kumiko-framework/errors";
|
|
6
6
|
import * as z from "zod";
|
|
7
|
-
import { assertBillingEnabled, assertNoActiveSubscription, isNonEmptyStringArray, joinBaseUrl, listOfferedCatalogProviders, openCheckout, } from "../checkout-core.js";
|
|
7
|
+
import { assertBillingEnabled, assertNoActiveSubscription, CHECKOUT_START_RATE_LIMIT, isNonEmptyStringArray, joinBaseUrl, listOfferedCatalogProviders, openCheckout, } from "../checkout-core.js";
|
|
8
8
|
import { consentCheckoutFields, consentPayloadSchema, prepareConsent, recordConsent, } from "../consumer-protection/consent-gate.js";
|
|
9
9
|
import { purchaseRolesOf, resolvePlanPrices } from "../plan-catalog.js";
|
|
10
10
|
import { BILLING_FOUNDATION_FEATURE } from "../web/constants.js";
|
|
@@ -48,6 +48,7 @@ export function createStartPlanCheckoutHandler(options, catalog) {
|
|
|
48
48
|
description: "Starts a hosted checkout for a plan tier when the tenant has no active subscription; the server picks price and redirect URLs. Name the provider with providerName when the catalog offers several.",
|
|
49
49
|
schema,
|
|
50
50
|
access: { roles: purchaseRolesOf(catalog) },
|
|
51
|
+
rateLimit: CHECKOUT_START_RATE_LIMIT,
|
|
51
52
|
handler: async (event, ctx) => {
|
|
52
53
|
// @cast-boundary engine-payload — dispatcher-zod-validated payload
|
|
53
54
|
const payload = event.payload;
|
|
@@ -5,8 +5,8 @@
|
|
|
5
5
|
// webhook signature in verify() IS the auth, so no c.get("user") here.
|
|
6
6
|
import { ExtraRouteRejection, signatureRoute } from "@cosmicdrift/kumiko-framework/api";
|
|
7
7
|
import { propertyOf } from "@cosmicdrift/kumiko-types/type-guards";
|
|
8
|
+
import { IgnoredEventReasons } from "./checkout-ledger.js";
|
|
8
9
|
import { BILLING_FOUNDATION_FEATURE, BillingEventKinds, SUBSCRIPTION_PROVIDER_EXTENSION, SubscriptionFoundationHandlers, } from "./web/constants.js";
|
|
9
|
-
const IGNORED_CHECKOUT_NOT_IN_LEDGER = "checkout_not_in_ledger";
|
|
10
10
|
const DEFAULT_WEBHOOK_PATH = "/api/subscription/webhook/:providerName";
|
|
11
11
|
function resolveProvider(registry, providerName) {
|
|
12
12
|
return registry
|
|
@@ -122,7 +122,7 @@ async function redeliveryReason(dispatched, event, deps) {
|
|
|
122
122
|
return undefined;
|
|
123
123
|
if (propertyOf(dispatched.data, "retry") === true)
|
|
124
124
|
return reason;
|
|
125
|
-
if (reason !==
|
|
125
|
+
if (reason !== IgnoredEventReasons.checkoutNotInLedger)
|
|
126
126
|
return undefined;
|
|
127
127
|
const plugin = resolveProvider(deps.registry, event.providerName);
|
|
128
128
|
const redeliver = await plugin?.shouldRedeliverIgnoredEvent?.({ event, reason, deps });
|
|
@@ -7,6 +7,9 @@ export declare const WHATSAPP_THROTTLED_EVENT_SHORT: "throttled";
|
|
|
7
7
|
export declare const WHATSAPP_MESSAGE_RECEIVED_EVENT_QN: "channel-whatsapp:event:message-received";
|
|
8
8
|
export declare const WHATSAPP_STATUS_UPDATED_EVENT_QN: "channel-whatsapp:event:status-updated";
|
|
9
9
|
export declare const WHATSAPP_THROTTLED_EVENT_QN: "channel-whatsapp:event:throttled";
|
|
10
|
+
export declare const WAMID_MAX_CHARS = 256;
|
|
11
|
+
export declare const PHONE_NUMBER_ID_MAX_CHARS = 64;
|
|
12
|
+
export declare const MIME_TYPE_MAX_CHARS = 255;
|
|
10
13
|
export declare const RAW_STATUS_MAX_CHARS = 64;
|
|
11
14
|
export declare const receiveMessageInputSchema: z.ZodObject<{
|
|
12
15
|
phoneNumberId: z.ZodString;
|
|
@@ -10,8 +10,9 @@ export const WHATSAPP_MESSAGE_RECEIVED_EVENT_QN = `${CHANNEL_WHATSAPP_FEATURE}:e
|
|
|
10
10
|
export const WHATSAPP_STATUS_UPDATED_EVENT_QN = `${CHANNEL_WHATSAPP_FEATURE}:event:${WHATSAPP_STATUS_UPDATED_EVENT_SHORT}`;
|
|
11
11
|
export const WHATSAPP_THROTTLED_EVENT_QN = `${CHANNEL_WHATSAPP_FEATURE}:event:${WHATSAPP_THROTTLED_EVENT_SHORT}`;
|
|
12
12
|
const E164_MAX_CHARS = 32;
|
|
13
|
-
const WAMID_MAX_CHARS = 256;
|
|
14
|
-
const PHONE_NUMBER_ID_MAX_CHARS = 64;
|
|
13
|
+
export const WAMID_MAX_CHARS = 256;
|
|
14
|
+
export const PHONE_NUMBER_ID_MAX_CHARS = 64;
|
|
15
|
+
export const MIME_TYPE_MAX_CHARS = 255;
|
|
15
16
|
export const RAW_STATUS_MAX_CHARS = 64;
|
|
16
17
|
// What the webhook route hands to the write handlers: normalized, still plaintext.
|
|
17
18
|
export const receiveMessageInputSchema = z.object({
|
|
@@ -24,7 +25,7 @@ export const receiveMessageInputSchema = z.object({
|
|
|
24
25
|
buttonPayload: z.string().max(WHATSAPP_BUTTON_PAYLOAD_MAX_CHARS).nullable(),
|
|
25
26
|
contextWamid: z.string().max(WAMID_MAX_CHARS).nullable(),
|
|
26
27
|
mediaId: z.string().max(WAMID_MAX_CHARS).nullable(),
|
|
27
|
-
mimeType: z.string().max(
|
|
28
|
+
mimeType: z.string().max(MIME_TYPE_MAX_CHARS).nullable(),
|
|
28
29
|
});
|
|
29
30
|
export const recordStatusInputSchema = z.object({
|
|
30
31
|
phoneNumberId: z.string().min(1).max(PHONE_NUMBER_ID_MAX_CHARS),
|
|
@@ -3,12 +3,18 @@ import { InternalError, RateLimitError } from "@cosmicdrift/kumiko-framework/err
|
|
|
3
3
|
import { whatsappMessageAggregateId, whatsappStatusAggregateId } from "./aggregate-id.js";
|
|
4
4
|
import { receiveMessageInputSchema, recordStatusInputSchema, WHATSAPP_MESSAGE_AGGREGATE_TYPE, WHATSAPP_MESSAGE_RECEIVED_EVENT_QN, WHATSAPP_STATUS_AGGREGATE_TYPE, WHATSAPP_STATUS_UPDATED_EVENT_QN, WHATSAPP_THROTTLED_EVENT_QN, } from "./events.js";
|
|
5
5
|
import { encryptWhatsappPii, WhatsappPiiFields } from "./pii.js";
|
|
6
|
+
const WHATSAPP_STREAM_LOCK_NAMESPACE = 0x77616d73;
|
|
6
7
|
const OUTCOME_STORED = { isSuccess: true, data: { outcome: "stored" } };
|
|
7
8
|
const OUTCOME_DUPLICATE = { isSuccess: true, data: { outcome: "duplicate" } };
|
|
8
9
|
const OUTCOME_THROTTLED = { isSuccess: true, data: { outcome: "throttled" } };
|
|
9
10
|
// Counts one message against every per-sender window. Only a RateLimitError means "throttled";
|
|
10
11
|
// anything else (Redis down, bad config) propagates so the webhook answers 5xx and Meta redelivers.
|
|
11
|
-
|
|
12
|
+
// A one-token marker bucket per wamid makes the charge once-only across failed rounds and
|
|
13
|
+
// concurrent deliveries. The marker is taken before the charge: a crash in between loses one
|
|
14
|
+
// charge, never doubles one. A redelivery after a throttled-then-failed attempt skips the charge.
|
|
15
|
+
// ponytail: that redelivery also skips the throttle decision (RateLimitResolver cannot read without
|
|
16
|
+
// consuming), so at most one message per failed round gets past the limit; upgrade: add a peek.
|
|
17
|
+
async function chargeSender(ctx, options, tenantId, from, wamid) {
|
|
12
18
|
if (options.senderRateLimits.length === 0)
|
|
13
19
|
return null;
|
|
14
20
|
const { rateLimit } = ctx.services;
|
|
@@ -18,6 +24,18 @@ async function chargeSender(ctx, options, tenantId, from) {
|
|
|
18
24
|
message: "channel-whatsapp: the per-sender limit needs a rate limiter and a digest key",
|
|
19
25
|
});
|
|
20
26
|
}
|
|
27
|
+
const markerWindowSeconds = Math.max(...options.senderRateLimits.map((l) => l.windowSeconds));
|
|
28
|
+
try {
|
|
29
|
+
await rateLimit.enforce(`whatsapp-inbound-charged:${tenantId}:${wamid}`, {
|
|
30
|
+
limit: 1,
|
|
31
|
+
windowSeconds: markerWindowSeconds,
|
|
32
|
+
});
|
|
33
|
+
}
|
|
34
|
+
catch (error) {
|
|
35
|
+
if (error instanceof RateLimitError)
|
|
36
|
+
return null;
|
|
37
|
+
throw error;
|
|
38
|
+
}
|
|
21
39
|
const senderKey = `whatsapp-inbound:${tenantId}:${digest(from)}`;
|
|
22
40
|
try {
|
|
23
41
|
await rateLimit.enforceAll(options.senderRateLimits.map(({ limit, windowSeconds }) => ({
|
|
@@ -44,10 +62,12 @@ export function createReceiveMessageHandler(options) {
|
|
|
44
62
|
const input = event.payload;
|
|
45
63
|
const tenantId = event.user.tenantId;
|
|
46
64
|
const aggregateId = whatsappMessageAggregateId(tenantId, input.wamid);
|
|
65
|
+
// tryAppend re-reads the stream version, so a delivery that committed after our load would land as a second event.
|
|
66
|
+
await ctx.db.advisoryXactLock(WHATSAPP_STREAM_LOCK_NAMESPACE, aggregateId);
|
|
47
67
|
// Dedupe before the limit: Meta's redeliveries must not use up the sender's budget.
|
|
48
68
|
if ((await ctx.events.load(aggregateId)).length > 0)
|
|
49
69
|
return OUTCOME_DUPLICATE;
|
|
50
|
-
const throttle = await chargeSender(ctx, options, tenantId, input.from);
|
|
70
|
+
const throttle = await chargeSender(ctx, options, tenantId, input.from, input.wamid);
|
|
51
71
|
const requestId = `channel-whatsapp:receive-message:${aggregateId}`;
|
|
52
72
|
const from = await encryptWhatsappPii(tenantId, throttle ? WhatsappPiiFields.throttledFrom : WhatsappPiiFields.receivedFrom, input.from, requestId);
|
|
53
73
|
if (throttle) {
|
|
@@ -82,7 +102,6 @@ export function createReceiveMessageHandler(options) {
|
|
|
82
102
|
mediaId: input.mediaId,
|
|
83
103
|
mimeType: input.mimeType,
|
|
84
104
|
};
|
|
85
|
-
// A concurrent delivery of the same wamid that won the race counts as a duplicate.
|
|
86
105
|
const appended = await ctx.events.tryAppend({
|
|
87
106
|
aggregateId,
|
|
88
107
|
aggregateType: WHATSAPP_MESSAGE_AGGREGATE_TYPE,
|
|
@@ -105,6 +124,8 @@ export function createRecordStatusHandler(options) {
|
|
|
105
124
|
const input = event.payload;
|
|
106
125
|
const tenantId = event.user.tenantId;
|
|
107
126
|
const aggregateId = whatsappStatusAggregateId(tenantId, input.wamid, input.status, input.rawStatus);
|
|
127
|
+
// tryAppend re-reads the stream version, so a delivery that committed after our load would land as a second event.
|
|
128
|
+
await ctx.db.advisoryXactLock(WHATSAPP_STREAM_LOCK_NAMESPACE, aggregateId);
|
|
108
129
|
if ((await ctx.events.load(aggregateId)).length > 0)
|
|
109
130
|
return OUTCOME_DUPLICATE;
|
|
110
131
|
const payload = {
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { Temporal } from "@cosmicdrift/kumiko-types/temporal";
|
|
2
2
|
import * as z from "zod";
|
|
3
3
|
import { WHATSAPP_BUTTON_PAYLOAD_MAX_CHARS, WHATSAPP_STATUS_KINDS, WHATSAPP_TEXT_MAX_CHARS, } from "./constants.js";
|
|
4
|
-
import { RAW_STATUS_MAX_CHARS, } from "./events.js";
|
|
4
|
+
import { MIME_TYPE_MAX_CHARS, PHONE_NUMBER_ID_MAX_CHARS, RAW_STATUS_MAX_CHARS, WAMID_MAX_CHARS, } from "./events.js";
|
|
5
5
|
// Meta adds fields and message types without notice. Every nested object is `.catch(undefined)`,
|
|
6
6
|
// so one unexpected shape costs that detail and not the whole message.
|
|
7
7
|
const mediaSchema = z.object({ id: z.string().optional(), mime_type: z.string().optional() });
|
|
@@ -34,7 +34,7 @@ const statusSchema = z.object({
|
|
|
34
34
|
timestamp: z.string().optional(),
|
|
35
35
|
recipient_id: z.string().optional(),
|
|
36
36
|
errors: z
|
|
37
|
-
.array(z.object({ code: z.number().optional() }))
|
|
37
|
+
.array(z.object({ code: z.number().int().optional().catch(undefined) }))
|
|
38
38
|
.optional()
|
|
39
39
|
.catch(undefined),
|
|
40
40
|
});
|
|
@@ -54,6 +54,8 @@ const webhookSchema = z.object({
|
|
|
54
54
|
.optional()
|
|
55
55
|
.catch(undefined),
|
|
56
56
|
});
|
|
57
|
+
// Temporal.Instant throws beyond 8.64e15 epoch milliseconds.
|
|
58
|
+
const MAX_EPOCH_SECONDS = 8.64e12;
|
|
57
59
|
const DIGITS_PATTERN = /^\d{5,20}$/;
|
|
58
60
|
function toE164(raw) {
|
|
59
61
|
const digits = raw.replace(/^\+/, "");
|
|
@@ -61,7 +63,10 @@ function toE164(raw) {
|
|
|
61
63
|
}
|
|
62
64
|
function toIso(unixSeconds, fallbackIso) {
|
|
63
65
|
const seconds = Number(unixSeconds);
|
|
64
|
-
return unixSeconds !== undefined &&
|
|
66
|
+
return unixSeconds !== undefined &&
|
|
67
|
+
Number.isFinite(seconds) &&
|
|
68
|
+
seconds > 0 &&
|
|
69
|
+
seconds <= MAX_EPOCH_SECONDS
|
|
65
70
|
? Temporal.Instant.fromEpochMilliseconds(Math.floor(seconds) * 1000).toString()
|
|
66
71
|
: fallbackIso;
|
|
67
72
|
}
|
|
@@ -72,6 +77,10 @@ const NO_CONTENT = { text: null, buttonPayload: null, mediaId: null, mimeType: n
|
|
|
72
77
|
function optionalClip(value, maxChars) {
|
|
73
78
|
return value === undefined ? null : clip(value, maxChars);
|
|
74
79
|
}
|
|
80
|
+
// A truncated id would point at another object, so an oversized one is dropped, not clipped.
|
|
81
|
+
function optionalId(value) {
|
|
82
|
+
return value === undefined || value.length > WAMID_MAX_CHARS ? null : value;
|
|
83
|
+
}
|
|
75
84
|
function buttonContentOf(message) {
|
|
76
85
|
const reply = message.interactive?.button_reply;
|
|
77
86
|
if (message.type === "interactive" && reply) {
|
|
@@ -102,8 +111,8 @@ function mediaContentOf(message) {
|
|
|
102
111
|
return {
|
|
103
112
|
...NO_CONTENT,
|
|
104
113
|
messageType: message.type,
|
|
105
|
-
mediaId: media.id
|
|
106
|
-
mimeType: media.mime_type
|
|
114
|
+
mediaId: optionalId(media.id),
|
|
115
|
+
mimeType: optionalClip(media.mime_type, MIME_TYPE_MAX_CHARS),
|
|
107
116
|
};
|
|
108
117
|
}
|
|
109
118
|
function contentOf(message) {
|
|
@@ -121,6 +130,9 @@ function normalizeMessage(raw, phoneNumberId, nowIso) {
|
|
|
121
130
|
if (!parsed.success)
|
|
122
131
|
return null;
|
|
123
132
|
const message = parsed.data;
|
|
133
|
+
if (message.id.length > WAMID_MAX_CHARS || phoneNumberId.length > PHONE_NUMBER_ID_MAX_CHARS) {
|
|
134
|
+
return null;
|
|
135
|
+
}
|
|
124
136
|
const from = toE164(message.from);
|
|
125
137
|
if (from === null)
|
|
126
138
|
return null;
|
|
@@ -129,7 +141,7 @@ function normalizeMessage(raw, phoneNumberId, nowIso) {
|
|
|
129
141
|
wamid: message.id,
|
|
130
142
|
from,
|
|
131
143
|
timestampIso: toIso(message.timestamp, nowIso),
|
|
132
|
-
contextWamid: message.context?.id
|
|
144
|
+
contextWamid: optionalId(message.context?.id),
|
|
133
145
|
...contentOf(message),
|
|
134
146
|
};
|
|
135
147
|
}
|
|
@@ -141,6 +153,9 @@ function normalizeStatus(raw, phoneNumberId, nowIso) {
|
|
|
141
153
|
if (!parsed.success)
|
|
142
154
|
return null;
|
|
143
155
|
const status = parsed.data;
|
|
156
|
+
if (status.id.length > WAMID_MAX_CHARS || phoneNumberId.length > PHONE_NUMBER_ID_MAX_CHARS) {
|
|
157
|
+
return null;
|
|
158
|
+
}
|
|
144
159
|
const recipient = toE164(status.recipient_id ?? "");
|
|
145
160
|
if (recipient === null)
|
|
146
161
|
return null;
|
|
@@ -33,6 +33,8 @@ export const setProfileWrite = defineWriteHandler({
|
|
|
33
33
|
// SystemAdmin can set profiles for customer setup through the platform-
|
|
34
34
|
// operator path; TenantAdmin can set them only for their own tenant.
|
|
35
35
|
access: { roles: access.admin },
|
|
36
|
+
// The profile picks the retention preset, so a change can shorten how long data is kept before the purge.
|
|
37
|
+
agent: { risk: "high" },
|
|
36
38
|
description: "Sets or replaces a tenant's compliance profile key plus an optional JSON override, for onboarding or a later region change; a system admin may target a different tenant through tenantIdOverride.",
|
|
37
39
|
handler: async (event, ctx) => {
|
|
38
40
|
const tenantId = (event.payload.tenantIdOverride ?? event.user.tenantId); // @cast-boundary engine-payload
|