@cosmicdrift/kumiko-bundled-features 0.414.0 → 0.416.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/agent-tools/tool-catalog.js +20 -1
- package/dist/agent-tools/tool-dispatch.js +14 -5
- 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/constants.d.ts +1 -0
- package/dist/channel-whatsapp/constants.js +1 -0
- package/dist/channel-whatsapp/events.d.ts +3 -0
- package/dist/channel-whatsapp/events.js +4 -3
- package/dist/channel-whatsapp/graph-client.d.ts +2 -0
- package/dist/channel-whatsapp/graph-client.js +29 -2
- 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/handbook-knowledge/constants.d.ts +6 -0
- package/dist/handbook-knowledge/constants.js +6 -0
- package/dist/handbook-knowledge/feature.d.ts +9 -0
- package/dist/handbook-knowledge/feature.js +17 -0
- package/dist/handbook-knowledge/handbook-index.d.ts +26 -0
- package/dist/handbook-knowledge/handbook-index.js +51 -0
- package/dist/handbook-knowledge/handlers.d.ts +28 -0
- package/dist/handbook-knowledge/handlers.js +67 -0
- package/dist/handbook-knowledge/index.d.ts +3 -0
- package/dist/handbook-knowledge/index.js +2 -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/signature/entity.d.ts +552 -0
- package/dist/signature/entity.js +156 -0
- package/dist/signature/feature.d.ts +3 -0
- package/dist/signature/feature.js +91 -0
- package/dist/signature/files.d.ts +23 -0
- package/dist/signature/files.js +64 -0
- package/dist/signature/grant.d.ts +32 -0
- package/dist/signature/grant.js +44 -0
- package/dist/signature/handlers/anonymous.write.d.ts +14 -0
- package/dist/signature/handlers/anonymous.write.js +52 -0
- package/dist/signature/handlers/cancel.write.d.ts +6 -0
- package/dist/signature/handlers/cancel.write.js +30 -0
- package/dist/signature/handlers/issue-link.write.d.ts +9 -0
- package/dist/signature/handlers/issue-link.write.js +57 -0
- package/dist/signature/handlers/lifecycle.write.d.ts +16 -0
- package/dist/signature/handlers/lifecycle.write.js +70 -0
- package/dist/signature/handlers/link-internal.write.d.ts +23 -0
- package/dist/signature/handlers/link-internal.write.js +186 -0
- package/dist/signature/handlers/request.write.d.ts +19 -0
- package/dist/signature/handlers/request.write.js +67 -0
- package/dist/signature/handlers/revoke-link.write.d.ts +6 -0
- package/dist/signature/handlers/revoke-link.write.js +18 -0
- package/dist/signature/handlers/sign-in-person.write.d.ts +8 -0
- package/dist/signature/handlers/sign-in-person.write.js +52 -0
- package/dist/signature/i18n.d.ts +6 -0
- package/dist/signature/i18n.js +49 -0
- package/dist/signature/index.d.ts +5 -0
- package/dist/signature/index.js +2 -0
- package/dist/signature/lib.d.ts +54 -0
- package/dist/signature/lib.js +68 -0
- package/dist/signature/options.d.ts +31 -0
- package/dist/signature/options.js +5 -0
- package/dist/signature/payloads.d.ts +60 -0
- package/dist/signature/payloads.js +53 -0
- package/dist/signature/png.d.ts +11 -0
- package/dist/signature/png.js +159 -0
- package/dist/signature/screens.d.ts +3 -0
- package/dist/signature/screens.js +95 -0
- package/dist/signature/signature-page.d.ts +25 -0
- package/dist/signature/signature-page.js +62 -0
- package/dist/signature/signing.d.ts +19 -0
- package/dist/signature/signing.js +46 -0
- package/dist/signature/static-sign.d.ts +17 -0
- package/dist/signature/static-sign.js +44 -0
- package/dist/signature/sweep.d.ts +3 -0
- package/dist/signature/sweep.js +113 -0
- package/dist/signature/user-data.d.ts +3 -0
- package/dist/signature/user-data.js +135 -0
- package/dist/signature/web/constants.d.ts +69 -0
- package/dist/signature/web/constants.js +68 -0
- package/dist/signature/web/index.d.ts +3 -0
- package/dist/signature/web/index.js +2 -0
- package/dist/signature/web/pad.d.ts +20 -0
- package/dist/signature/web/pad.js +104 -0
- package/dist/signature/web/signature-pad.d.ts +19 -0
- package/dist/signature/web/signature-pad.js +36 -0
- 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/feature.d.ts +6 -0
- package/dist/subscription-stripe/feature.js +3 -0
- package/dist/subscription-stripe/plugin-methods.d.ts +3 -1
- package/dist/subscription-stripe/plugin-methods.js +2 -1
- 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 +43 -11
- package/src/agent-tools/changes.json +6 -0
- package/src/auth-mfa/changes.json +6 -0
- package/src/billing-foundation/changes.json +24 -0
- package/src/channel-whatsapp/changes.json +30 -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/handbook-knowledge/changes.json +8 -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/signature/changes.json +15 -0
- package/src/step-dispatcher/changes.json +6 -0
- package/src/subscription-paddle/changes.json +6 -0
- package/src/subscription-stripe/changes.json +12 -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
|
@@ -318,7 +318,26 @@ function buildAskUserTool() {
|
|
|
318
318
|
type: "object",
|
|
319
319
|
properties: {
|
|
320
320
|
question: { type: "string" },
|
|
321
|
-
options: {
|
|
321
|
+
options: {
|
|
322
|
+
type: "array",
|
|
323
|
+
items: {
|
|
324
|
+
anyOf: [
|
|
325
|
+
{ type: "string" },
|
|
326
|
+
{
|
|
327
|
+
type: "object",
|
|
328
|
+
properties: {
|
|
329
|
+
label: { type: "string" },
|
|
330
|
+
preview: {
|
|
331
|
+
type: "string",
|
|
332
|
+
description: "The text you will write if the user picks this option.",
|
|
333
|
+
},
|
|
334
|
+
},
|
|
335
|
+
required: ["label"],
|
|
336
|
+
additionalProperties: false,
|
|
337
|
+
},
|
|
338
|
+
],
|
|
339
|
+
},
|
|
340
|
+
},
|
|
322
341
|
},
|
|
323
342
|
required: ["question"],
|
|
324
343
|
additionalProperties: false,
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { isKumikoError } from "@cosmicdrift/kumiko-framework/errors";
|
|
2
2
|
import { runAsAgentToolCallEntry } from "@cosmicdrift/kumiko-framework/internal/request-context";
|
|
3
3
|
import { createFallbackLogger } from "@cosmicdrift/kumiko-framework/logging";
|
|
4
|
-
import { isOneOf } from "@cosmicdrift/kumiko-types/type-guards";
|
|
4
|
+
import { isOneOf, propertyOf } from "@cosmicdrift/kumiko-types/type-guards";
|
|
5
5
|
import { FILTER_OPS, isRecord } from "./filter-ops.js";
|
|
6
6
|
export const TOOL_CALL_ERROR_CODES = {
|
|
7
7
|
invalidToolCall: "invalid_tool_call",
|
|
@@ -263,8 +263,17 @@ function dispatchClientOpenForm(descriptor, input) {
|
|
|
263
263
|
data: { kind: "open_form", screenId, handlerQn, prefill: input["prefill"] ?? {} },
|
|
264
264
|
};
|
|
265
265
|
}
|
|
266
|
-
function
|
|
267
|
-
|
|
266
|
+
function isAskUserOption(value) {
|
|
267
|
+
if (typeof value === "string")
|
|
268
|
+
return true;
|
|
269
|
+
if (typeof value !== "object" || value === null || Array.isArray(value))
|
|
270
|
+
return false;
|
|
271
|
+
const preview = propertyOf(value, "preview");
|
|
272
|
+
return (typeof propertyOf(value, "label") === "string" &&
|
|
273
|
+
(preview === undefined || typeof preview === "string"));
|
|
274
|
+
}
|
|
275
|
+
function isAskUserOptions(value) {
|
|
276
|
+
return Array.isArray(value) && value.every(isAskUserOption);
|
|
268
277
|
}
|
|
269
278
|
function dispatchClientAskUser(input) {
|
|
270
279
|
const question = input["question"];
|
|
@@ -275,8 +284,8 @@ function dispatchClientAskUser(input) {
|
|
|
275
284
|
if (options === undefined) {
|
|
276
285
|
return { ok: true, data: { kind: "ask_user", question } };
|
|
277
286
|
}
|
|
278
|
-
if (!
|
|
279
|
-
return invalidToolCall(`ask_user "options" argument must be an array of strings`);
|
|
287
|
+
if (!isAskUserOptions(options)) {
|
|
288
|
+
return invalidToolCall(`ask_user "options" argument must be an array of strings or { label, preview? } objects`);
|
|
280
289
|
}
|
|
281
290
|
return { ok: true, data: { kind: "ask_user", question, options } };
|
|
282
291
|
}
|
|
@@ -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 });
|
|
@@ -23,3 +23,4 @@ export declare const WHATSAPP_TEXT_MAX_CHARS = 4096;
|
|
|
23
23
|
export declare const WHATSAPP_BUTTON_PAYLOAD_MAX_CHARS = 256;
|
|
24
24
|
export declare const WHATSAPP_BUTTON_TITLE_MAX_CHARS = 20;
|
|
25
25
|
export declare const WHATSAPP_MAX_REPLY_BUTTONS = 3;
|
|
26
|
+
export declare const WHATSAPP_MAX_TEMPLATE_BUTTONS = 10;
|
|
@@ -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),
|
|
@@ -59,6 +59,8 @@ export type WhatsappTemplateInput = SendBase & {
|
|
|
59
59
|
readonly templateName: string;
|
|
60
60
|
readonly languageCode: string;
|
|
61
61
|
readonly bodyParameters?: readonly string[];
|
|
62
|
+
readonly quickReplyPayloads?: readonly string[];
|
|
63
|
+
readonly headerImageLink?: string;
|
|
62
64
|
};
|
|
63
65
|
export type WhatsappReplyButton = {
|
|
64
66
|
readonly payload: string;
|
|
@@ -2,7 +2,7 @@ import { BlockedHostError, egress } from "@cosmicdrift/kumiko-framework/http";
|
|
|
2
2
|
import { SYSTEM_USER_ID } from "@cosmicdrift/kumiko-types/identifiers";
|
|
3
3
|
import { propertyOf } from "@cosmicdrift/kumiko-types/type-guards";
|
|
4
4
|
import { checkChatWebhookTarget } from "../delivery/index.js";
|
|
5
|
-
import { WHATSAPP_BUTTON_PAYLOAD_MAX_CHARS, WHATSAPP_BUTTON_TITLE_MAX_CHARS, WHATSAPP_MAX_REPLY_BUTTONS, WHATSAPP_SECRET_KEYS, WHATSAPP_TEXT_MAX_CHARS, } from "./constants.js";
|
|
5
|
+
import { WHATSAPP_BUTTON_PAYLOAD_MAX_CHARS, WHATSAPP_BUTTON_TITLE_MAX_CHARS, WHATSAPP_MAX_REPLY_BUTTONS, WHATSAPP_MAX_TEMPLATE_BUTTONS, WHATSAPP_SECRET_KEYS, WHATSAPP_TEXT_MAX_CHARS, } from "./constants.js";
|
|
6
6
|
import { resolveWhatsappOptions, } from "./options.js";
|
|
7
7
|
const PHONE_NUMBER_ID_PATTERN = /^\d{1,32}$/;
|
|
8
8
|
const RECIPIENT_PATTERN = /^\+?\d{5,20}$/;
|
|
@@ -220,13 +220,40 @@ export function buildWhatsappClient(resolved) {
|
|
|
220
220
|
!LANGUAGE_CODE_PATTERN.test(input.languageCode)) {
|
|
221
221
|
return Promise.resolve({ ok: false, code: "invalid_message" });
|
|
222
222
|
}
|
|
223
|
+
const quickReplyPayloads = input.quickReplyPayloads;
|
|
224
|
+
if (quickReplyPayloads !== undefined &&
|
|
225
|
+
(quickReplyPayloads.length === 0 ||
|
|
226
|
+
quickReplyPayloads.length > WHATSAPP_MAX_TEMPLATE_BUTTONS ||
|
|
227
|
+
quickReplyPayloads.some((payload) => payload === "" || payload.length > WHATSAPP_BUTTON_PAYLOAD_MAX_CHARS))) {
|
|
228
|
+
return Promise.resolve({ ok: false, code: "invalid_message" });
|
|
229
|
+
}
|
|
230
|
+
if (input.headerImageLink !== undefined && !isPublicMediaLink(input.headerImageLink, true)) {
|
|
231
|
+
return Promise.resolve({ ok: false, code: "invalid_message" });
|
|
232
|
+
}
|
|
223
233
|
const parameters = (input.bodyParameters ?? []).map((text) => ({ type: "text", text }));
|
|
234
|
+
const components = [
|
|
235
|
+
...(input.headerImageLink !== undefined
|
|
236
|
+
? [
|
|
237
|
+
{
|
|
238
|
+
type: "header",
|
|
239
|
+
parameters: [{ type: "image", image: { link: input.headerImageLink } }],
|
|
240
|
+
},
|
|
241
|
+
]
|
|
242
|
+
: []),
|
|
243
|
+
...(parameters.length > 0 ? [{ type: "body", parameters }] : []),
|
|
244
|
+
...(quickReplyPayloads ?? []).map((payload, index) => ({
|
|
245
|
+
type: "button",
|
|
246
|
+
sub_type: "quick_reply",
|
|
247
|
+
index: String(index),
|
|
248
|
+
parameters: [{ type: "payload", payload }],
|
|
249
|
+
})),
|
|
250
|
+
];
|
|
224
251
|
return postMessage(ctx, input, {
|
|
225
252
|
type: "template",
|
|
226
253
|
template: {
|
|
227
254
|
name: input.templateName,
|
|
228
255
|
language: { code: input.languageCode },
|
|
229
|
-
...(
|
|
256
|
+
...(components.length > 0 && { components }),
|
|
230
257
|
},
|
|
231
258
|
});
|
|
232
259
|
},
|