@theokit/gateway-sms 0.5.0 → 0.6.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/CHANGELOG.md +6 -0
- package/README.md +17 -2
- package/dist/index.cjs +147 -58
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +28 -6
- package/dist/index.d.ts +28 -6
- package/dist/index.js +147 -58
- package/dist/index.js.map +1 -1
- package/package.json +2 -2
package/dist/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/errors.ts","../src/phone.ts","../src/backend/plivo.ts","../src/backend/twilio.ts","../src/backend/vonage.ts","../src/backend/index.ts","../src/normalize.ts","../src/refuse-attachments.ts","../src/split.ts","../src/adapter.ts","../src/channel.ts","../src/parse-inbound.ts","../src/twilio-verifier.ts","../src/twiml.ts","../src/webhook-server.ts","../src/webhook-verifier.ts"],"names":["GatewayConfigurationError","parsePhoneNumberFromString","parseFormUrlEncoded","chunkByGrapheme","splitKeepingRows","BasePlatformAdapter","createHmac","timingSafeEqual","loadPeer","rawBodyCapture","DEFAULT_WEBHOOK_MAX_BYTES","listenerLifecycle"],"mappings":";;;;;;;AA8BO,IAAM,kBAAA,GAAN,cAAiCA,iCAAA,CAA0B;AAAA,EAC9C,IAAA,GAAO,oBAAA;AAAA,EACzB,YAAY,IAAA,EAAiC;AAC3C,IAAA,KAAA,CAAM,eAAe,IAAI,CAAA;AAAA,EAC3B;AACF;AASO,IAAM,wBAAA,GAAN,cAAuC,kBAAA,CAAmB;AAAA,EAC/D,WAAA,CAAY,SAAwC,OAAA,EAAiB;AACnE,IAAA,KAAA,CAAM;AAAA,MACJ,IAAA,EAAM,uBAAA;AAAA,MACN,SAAS,CAAA,uBAAA,EAA0B,OAAO,CAAA,6BAAA,EAAgC,OAAO,iCAAiC,OAAO,CAAA,CAAA;AAAA,MACzH,MAAA,EAAQ;AAAA,KACT,CAAA;AAAA,EACH;AACF;AC3B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*\n * - `ConfigurationError` — programmer error at construction time\n * (missing signing secret, missing backend SDK install, malformed\n * phone number on outbound). Thrown synchronously.\n * - `BackendNotInstalledError` — peer-dep optional backend (twilio /\n * plivo / @vonage/server-sdk) was selected but the npm package is\n * not installed. Carries actionable install hint.\n *\n * `ConfigurationError` extends the shared core `GatewayConfigurationError`\n * base (roadmap M2); the SDK still consumes structured errors via\n * `metadata.code`. Behavior byte-identical (pinned by `tests/errors.test.ts`).\n *\n * @internal — re-exported by `src/index.ts`.\n */\n\nimport { GatewayConfigurationError, type GatewayConfigurationErrorOptions } from \"@theokit/gateway\";\n\n/** @knipignore — public input shape for `ConfigurationError` constructor (caller-extensible). */\nexport type ConfigurationErrorOptions = GatewayConfigurationErrorOptions;\n\n/**\n * Misconfiguration of this adapter, raised before any network call.\n *\n * Extends the shared core base so every gateway package reports configuration faults in one shape:\n * a structured `code` the caller can branch on, tagged with `\"gateway-sms\"` as the origin. A\n * missing credential or an unsupported option is a programmer error, not a transient failure —\n * these are never retried.\n */\nexport class ConfigurationError extends GatewayConfigurationError {\n override readonly name = \"ConfigurationError\";\n constructor(opts: ConfigurationErrorOptions) {\n super(\"gateway-sms\", opts);\n }\n}\n\n/**\n * The provider SDK for the selected backend is not installed.\n *\n * `gateway-sms` speaks to Twilio, Plivo or Vonage, and declares all three as optional peers — a\n * project installs only the one it uses. Selecting a backend whose SDK is absent is caught here, at\n * connect time, with the package name and the command that installs it.\n */\nexport class BackendNotInstalledError extends ConfigurationError {\n constructor(backend: \"twilio\" | \"plivo\" | \"vonage\", pkgName: string) {\n super({\n code: \"backend_not_installed\",\n message: `gateway-sms: peer-dep \"${pkgName}\" not installed but backend=\"${backend}\" was selected. Run: pnpm add ${pkgName}`,\n detail: pkgName,\n });\n }\n}\n","/**\n * E.164 phone normalization (D391, EC-6).\n *\n * Wraps `libphonenumber-js` (full — accepts mobile + toll-free; the\n * `/mobile` sub-bundle was inadequate because it rejects toll-free\n * US 1-800 numbers).\n *\n * @internal\n */\n\nimport { parsePhoneNumberFromString } from \"libphonenumber-js\";\n\nimport { ConfigurationError } from \"./errors.js\";\n\n/**\n * Normalize a free-form phone number to canonical E.164 (`+5511999999999`).\n *\n * Accepts:\n * - International with `+`: `\"+5511999999999\"` → unchanged.\n * - National without `+` when `defaultCountry` is provided: `(\"11999999999\", \"BR\")` → `\"+5511999999999\"`.\n * - Toll-free US (EC-6): `\"+18001234567\"` → unchanged.\n *\n * Throws `ConfigurationError({ code: \"invalid_phone_number\" })` on any\n * input that cannot be parsed to a valid number.\n */\nexport function normalizeE164(input: string, defaultCountry?: string): string {\n if (input.length === 0) {\n throw new ConfigurationError({\n code: \"invalid_phone_number\",\n message: \"gateway-sms: phone number is empty\",\n detail: \"<empty>\",\n });\n }\n const parsed = parsePhoneNumberFromString(\n input,\n defaultCountry as Parameters<typeof parsePhoneNumberFromString>[1],\n );\n if (parsed === undefined || !parsed.isValid()) {\n throw new ConfigurationError({\n code: \"invalid_phone_number\",\n message: `gateway-sms: invalid phone number ${JSON.stringify(input)}`,\n detail: input,\n });\n }\n return parsed.format(\"E.164\");\n}\n","/**\n * Plivo backend impl.\n *\n * - SDK: `plivo` (peer-dep, optional).\n * - Signature: `X-Plivo-Signature-V3` is HMAC-SHA256 of the request URL\n * + nonce + body. `validateV3Signature` is exposed by the SDK; we\n * delegate to avoid reimplementation.\n *\n * @internal\n */\n\nimport type { SendResult } from \"@theokit/gateway\";\nimport type { SignatureContext, SMSBackend, SMSInbound } from \"../backend-types.js\";\nimport { BackendNotInstalledError } from \"../errors.js\";\nimport { normalizeE164 } from \"../phone.js\";\nimport type { PlivoOptions } from \"../types.js\";\n\ninterface PlivoCreateResponse {\n apiId?: string;\n messageUuid?: string[];\n message_uuid?: string[];\n}\n\ninterface PlivoClient {\n messages: {\n // The actual SDK uses positional args: create(src, dst, text, ...).\n create(src: string, dst: string, text: string): Promise<PlivoCreateResponse>;\n };\n}\n\ninterface PlivoModule {\n Client: new (authId?: string, authToken?: string) => PlivoClient;\n // Real SDK signature: validateV3Signature(method, uri, nonce, authToken, v3Signature)\n validateV3Signature?: (\n method: string,\n uri: string,\n nonce: string,\n authToken: string,\n signature: string,\n ) => boolean;\n}\n\nasync function loadPlivo(): Promise<PlivoModule> {\n try {\n // Plivo's published types are stricter (positional args) than our\n // generic mock; we narrow at call sites and pass through unknown.\n const mod = (await import(\"plivo\")) as unknown as PlivoModule;\n return mod;\n } catch {\n throw new BackendNotInstalledError(\"plivo\", \"plivo\");\n }\n}\n\nexport class PlivoBackend implements SMSBackend {\n readonly kind = \"plivo\" as const;\n private mod: PlivoModule | undefined;\n private client: PlivoClient | undefined;\n\n constructor(private readonly opts: PlivoOptions) {}\n\n async connect(): Promise<boolean> {\n if (this.client !== undefined) return true;\n this.mod = await loadPlivo();\n this.client = new this.mod.Client(this.opts.authId, this.opts.authToken);\n return true;\n }\n\n async disconnect(): Promise<void> {\n this.client = undefined;\n }\n\n verifySignature(ctx: SignatureContext): boolean {\n if (this.mod?.validateV3Signature === undefined) return false;\n const signature = ctx.headers[\"x-plivo-signature-v3\"];\n const nonce = ctx.headers[\"x-plivo-signature-v3-nonce\"];\n if (signature === undefined || nonce === undefined) return false;\n try {\n return this.mod.validateV3Signature(\"POST\", ctx.url, nonce, this.opts.authToken, signature);\n } catch {\n return false;\n }\n }\n\n parseInbound(ctx: SignatureContext): SMSInbound {\n let params: Record<string, string> = {};\n // Plivo posts JSON or form-encoded depending on application config.\n if ((ctx.headers[\"content-type\"] ?? \"\").includes(\"application/json\")) {\n try {\n params = JSON.parse(ctx.rawBody) as Record<string, string>;\n } catch {\n params = {};\n }\n } else {\n params = parseFormUrlEncoded(ctx.rawBody);\n }\n return {\n from: normalizeE164(params.From ?? \"\", this.opts.defaultCountry),\n to: normalizeE164(params.To ?? \"\", this.opts.defaultCountry),\n body: params.Text ?? params.text ?? \"\",\n messageId: params.MessageUUID ?? params.message_uuid ?? \"\",\n receivedAt: Date.now(),\n raw: params,\n };\n }\n\n async sendMessage(to: string, body: string): Promise<SendResult> {\n if (this.client === undefined) {\n return {\n ok: false,\n error: { code: \"not_connected\", message: \"PlivoBackend.connect() not called\" },\n };\n }\n try {\n const resp = await this.client.messages.create(this.opts.fromNumber, to, body);\n const id = resp.messageUuid?.[0] ?? resp.message_uuid?.[0] ?? resp.apiId ?? \"\";\n return { ok: true, messageId: id };\n } catch (err) {\n return mapPlivoError(err);\n }\n }\n}\n\nfunction parseFormUrlEncoded(body: string): Record<string, string> {\n const params: Record<string, string> = {};\n for (const pair of body.split(\"&\")) {\n if (pair.length === 0) continue;\n const eqIdx = pair.indexOf(\"=\");\n const k = eqIdx < 0 ? pair : pair.slice(0, eqIdx);\n const v = eqIdx < 0 ? \"\" : pair.slice(eqIdx + 1);\n params[decodeURIComponent(k.replace(/\\+/g, \" \"))] = decodeURIComponent(v.replace(/\\+/g, \" \"));\n }\n return params;\n}\n\ninterface PlivoRestError {\n statusCode?: number;\n status?: number;\n message?: string;\n}\n\nfunction mapPlivoError(err: unknown): SendResult {\n const e = err as PlivoRestError;\n const status = e.statusCode ?? e.status ?? 0;\n if (status === 429)\n return { ok: false, error: { code: \"rate_limit\", message: e.message ?? \"Plivo rate limit\" } };\n if (status === 401 || status === 403) {\n return {\n ok: false,\n error: { code: \"permission_denied\", message: e.message ?? \"Plivo auth error\" },\n };\n }\n if (status === 400) {\n return {\n ok: false,\n error: { code: \"invalid_request\", message: e.message ?? \"Plivo rejected request\" },\n };\n }\n return {\n ok: false,\n error: {\n code: \"send_failed\",\n message: e.message ?? (err instanceof Error ? err.message : String(err)),\n },\n };\n}\n","/**\n * Twilio backend impl.\n *\n * - SDK: `twilio` (peer-dep, optional). Loaded lazily so packages\n * that pick other backends don't pay the cost.\n * - Signature: `X-Twilio-Signature` is HMAC-SHA1 of `(fullUrl + sortedParams)`.\n * We delegate to `twilio.validateRequest` so we don't reimplement.\n *\n * @internal\n */\n\nimport type { SendResult } from \"@theokit/gateway\";\nimport type { SignatureContext, SMSBackend, SMSInbound } from \"../backend-types.js\";\nimport { BackendNotInstalledError } from \"../errors.js\";\nimport { normalizeE164 } from \"../phone.js\";\nimport type { TwilioOptions } from \"../types.js\";\n\ninterface TwilioCreateArgs {\n from: string;\n to: string;\n body: string;\n}\n\ninterface TwilioMessageInstance {\n sid: string;\n status?: string;\n}\n\ninterface TwilioClientInstance {\n messages: {\n create(args: TwilioCreateArgs): Promise<TwilioMessageInstance>;\n };\n}\n\ninterface TwilioFactory {\n (accountSid: string, authToken: string): TwilioClientInstance;\n validateRequest(\n authToken: string,\n signature: string,\n url: string,\n params: Record<string, string>,\n ): boolean;\n}\n\nasync function loadTwilio(): Promise<TwilioFactory> {\n try {\n const mod = await import(\"twilio\");\n // ESM ships { default: factory }; CJS ships factory.\n const candidate =\n (mod as { default?: TwilioFactory }).default ?? (mod as unknown as TwilioFactory);\n return candidate;\n } catch {\n throw new BackendNotInstalledError(\"twilio\", \"twilio\");\n }\n}\n\nexport class TwilioBackend implements SMSBackend {\n readonly kind = \"twilio\" as const;\n private client: TwilioClientInstance | undefined;\n private twilio: TwilioFactory | undefined;\n\n constructor(private readonly opts: TwilioOptions) {}\n\n async connect(): Promise<boolean> {\n if (this.client !== undefined) return true;\n this.twilio = await loadTwilio();\n this.client = this.twilio(this.opts.accountSid, this.opts.authToken);\n return true;\n }\n\n async disconnect(): Promise<void> {\n // No persistent connection — REST client is GC'd on dereference.\n this.client = undefined;\n }\n\n verifySignature(ctx: SignatureContext): boolean {\n if (this.twilio === undefined) return false;\n const signature = ctx.headers[\"x-twilio-signature\"];\n if (signature === undefined) return false;\n const params = parseFormUrlEncoded(ctx.rawBody);\n try {\n return this.twilio.validateRequest(this.opts.authToken, signature, ctx.url, params);\n } catch {\n return false;\n }\n }\n\n parseInbound(ctx: SignatureContext): SMSInbound {\n const params = parseFormUrlEncoded(ctx.rawBody);\n return {\n from: normalizeE164(params.From ?? \"\", this.opts.defaultCountry),\n to: normalizeE164(params.To ?? \"\", this.opts.defaultCountry),\n body: params.Body ?? \"\",\n messageId: params.MessageSid ?? params.SmsMessageSid ?? \"\",\n receivedAt: Date.now(),\n raw: params,\n };\n }\n\n async sendMessage(to: string, body: string): Promise<SendResult> {\n if (this.client === undefined) {\n return {\n ok: false,\n error: { code: \"not_connected\", message: \"TwilioBackend.connect() not called\" },\n };\n }\n try {\n const msg = await this.client.messages.create({ from: this.opts.fromNumber, to, body });\n return { ok: true, messageId: msg.sid };\n } catch (err) {\n return mapTwilioError(err);\n }\n }\n}\n\n/**\n * Parse `application/x-www-form-urlencoded` request body to a flat\n * `Record<string, string>`. Twilio POSTs in this format.\n *\n * @internal\n */\nfunction parseFormUrlEncoded(body: string): Record<string, string> {\n const params: Record<string, string> = {};\n for (const pair of body.split(\"&\")) {\n if (pair.length === 0) continue;\n const eqIdx = pair.indexOf(\"=\");\n const k = eqIdx < 0 ? pair : pair.slice(0, eqIdx);\n const v = eqIdx < 0 ? \"\" : pair.slice(eqIdx + 1);\n params[decodeURIComponent(k.replace(/\\+/g, \" \"))] = decodeURIComponent(v.replace(/\\+/g, \" \"));\n }\n return params;\n}\n\ninterface TwilioRestError {\n status?: number;\n code?: number | string;\n message?: string;\n}\n\nfunction mapTwilioError(err: unknown): SendResult {\n const e = err as TwilioRestError;\n const status = e.status ?? 0;\n if (status === 429) {\n return { ok: false, error: { code: \"rate_limit\", message: e.message ?? \"Twilio rate limit\" } };\n }\n if (status === 401 || status === 403) {\n return {\n ok: false,\n error: { code: \"permission_denied\", message: e.message ?? \"Twilio auth error\" },\n };\n }\n if (status === 400) {\n return {\n ok: false,\n error: { code: \"invalid_request\", message: e.message ?? \"Twilio rejected request\" },\n };\n }\n return {\n ok: false,\n error: {\n code: \"send_failed\",\n message: e.message ?? (err instanceof Error ? err.message : String(err)),\n },\n };\n}\n","/**\n * Vonage backend impl.\n *\n * - SDK: `@vonage/server-sdk` (peer-dep, optional).\n * - Signature: `Authorization: Bearer <JWT>` signed with the Signature\n * Secret (NOT the API secret). The SDK exposes `Auth.verifySignature`\n * for this purpose.\n *\n * @internal\n */\n\nimport type { SendResult } from \"@theokit/gateway\";\nimport type { SignatureContext, SMSBackend, SMSInbound } from \"../backend-types.js\";\nimport { BackendNotInstalledError } from \"../errors.js\";\nimport { normalizeE164 } from \"../phone.js\";\nimport type { VonageOptions } from \"../types.js\";\n\ninterface VonageSmsClient {\n send(args: { to: string; from: string; text: string }): Promise<{\n messages?: Array<{ \"message-id\"?: string; messageId?: string; status?: string }>;\n }>;\n}\n\ninterface VonageInstance {\n sms: VonageSmsClient;\n}\n\ninterface VonageModule {\n Vonage: new (creds: {\n apiKey: string;\n apiSecret: string;\n signatureSecret?: string;\n }) => VonageInstance;\n Auth?: {\n verifySignature?: (token: string, secret: string) => boolean;\n };\n}\n\nasync function loadVonage(): Promise<VonageModule> {\n try {\n // SDK ships ESM/CJS variants; we narrow at call sites and pass through.\n const raw = await import(\"@vonage/server-sdk\");\n return raw as unknown as VonageModule;\n } catch {\n throw new BackendNotInstalledError(\"vonage\", \"@vonage/server-sdk\");\n }\n}\n\nexport class VonageBackend implements SMSBackend {\n readonly kind = \"vonage\" as const;\n private mod: VonageModule | undefined;\n private vonage: VonageInstance | undefined;\n\n constructor(private readonly opts: VonageOptions) {}\n\n async connect(): Promise<boolean> {\n if (this.vonage !== undefined) return true;\n this.mod = await loadVonage();\n this.vonage = new this.mod.Vonage({\n apiKey: this.opts.apiKey,\n apiSecret: this.opts.apiSecret,\n signatureSecret: this.opts.signatureSecret,\n });\n return true;\n }\n\n async disconnect(): Promise<void> {\n this.vonage = undefined;\n }\n\n verifySignature(ctx: SignatureContext): boolean {\n const auth = ctx.headers.authorization;\n if (auth === undefined) return false;\n const m = auth.match(/^Bearer\\s+(.+)$/i);\n if (m === null) return false;\n const token = m[1] ?? \"\";\n if (token.length === 0) return false;\n if (this.mod?.Auth?.verifySignature === undefined) return false;\n try {\n return this.mod.Auth.verifySignature(token, this.opts.signatureSecret);\n } catch {\n return false;\n }\n }\n\n parseInbound(ctx: SignatureContext): SMSInbound {\n let payload: Record<string, string> = {};\n try {\n payload = JSON.parse(ctx.rawBody) as Record<string, string>;\n } catch {\n payload = {};\n }\n return {\n from: normalizeE164(payload.msisdn ?? payload.from ?? \"\", this.opts.defaultCountry),\n to: normalizeE164(payload.to ?? \"\", this.opts.defaultCountry),\n body: payload.text ?? \"\",\n messageId: payload.messageId ?? payload[\"message-id\"] ?? \"\",\n receivedAt: Date.now(),\n raw: payload,\n };\n }\n\n async sendMessage(to: string, body: string): Promise<SendResult> {\n if (this.vonage === undefined) {\n return {\n ok: false,\n error: { code: \"not_connected\", message: \"VonageBackend.connect() not called\" },\n };\n }\n try {\n const resp = await this.vonage.sms.send({ from: this.opts.fromNumber, to, text: body });\n const msg = resp.messages?.[0];\n const id = msg?.[\"message-id\"] ?? msg?.messageId ?? \"\";\n if (msg?.status !== undefined && msg.status !== \"0\") {\n return {\n ok: false,\n error: { code: \"send_failed\", message: `Vonage returned status=${msg.status}` },\n };\n }\n return { ok: true, messageId: id };\n } catch (err) {\n return mapVonageError(err);\n }\n }\n}\n\ninterface VonageRestError {\n status?: number;\n response?: { status?: number };\n message?: string;\n}\n\nfunction mapVonageError(err: unknown): SendResult {\n const e = err as VonageRestError;\n const status = e.status ?? e.response?.status ?? 0;\n if (status === 429)\n return { ok: false, error: { code: \"rate_limit\", message: e.message ?? \"Vonage rate limit\" } };\n if (status === 401 || status === 403) {\n return {\n ok: false,\n error: { code: \"permission_denied\", message: e.message ?? \"Vonage auth error\" },\n };\n }\n return {\n ok: false,\n error: {\n code: \"send_failed\",\n message: e.message ?? (err instanceof Error ? err.message : String(err)),\n },\n };\n}\n","/**\n * Backend factory — picks the right impl from `opts.backend`.\n *\n * @internal\n */\n\nimport type { SMSBackend } from \"../backend-types.js\";\nimport type { SMSAdapterOptions } from \"../types.js\";\nimport { PlivoBackend } from \"./plivo.js\";\nimport { TwilioBackend } from \"./twilio.js\";\nimport { VonageBackend } from \"./vonage.js\";\n\nexport function createBackend(opts: SMSAdapterOptions): SMSBackend {\n switch (opts.backend) {\n case \"twilio\":\n return new TwilioBackend(opts);\n case \"plivo\":\n return new PlivoBackend(opts);\n case \"vonage\":\n return new VonageBackend(opts);\n default: {\n const _exhaustive: never = opts;\n throw new Error(`unknown backend: ${JSON.stringify(_exhaustive)}`);\n }\n }\n}\n","/**\n * Inbound normalization: `SMSInbound` → `SMSMessageEvent`.\n *\n * `from` and `to` are already E.164 (backend.parseInbound enforces this).\n * `channel.id` is `from` because SMS conversations are flat per-pair\n * (D394 — no threading).\n *\n * @internal\n */\n\nimport type { SMSMessageEvent } from \"@theokit/gateway\";\n\nimport type { SMSInbound } from \"./backend-types.js\";\n\nexport function inboundToMessageEvent(\n inbound: SMSInbound,\n backend: \"twilio\" | \"plivo\" | \"vonage\",\n): SMSMessageEvent {\n return {\n id: inbound.messageId,\n platform: \"sms\",\n sender: { id: inbound.from },\n channel: { id: inbound.from, type: \"dm\" },\n text: inbound.body,\n receivedAt: inbound.receivedAt,\n sms: {\n backend,\n messageId: inbound.messageId,\n from: inbound.from,\n to: inbound.to,\n raw: inbound.raw,\n },\n };\n}\n","/**\n * The refusal this adapter answers for an outbound that carries attachments (B-674).\n *\n * This adapter sends text only, so an outbound carrying attachments is refused rather than sent without its images.\n *\n * The check runs before any other, so a refusal makes no platform call. It lives in this package\n * rather than in `@theokit/gateway` so that the adapter calls nothing its declared core floor\n * lacks; only the `OutboundMessage` type is imported.\n */\n\nimport type { OutboundMessage, SendResult } from \"@theokit/gateway\";\n\n/**\n * `attachments_unsupported` when `out` carries attachments, otherwise `undefined`.\n *\n * Absent, `null` and an empty list carry nothing. `!== 0`, not `> 0`: any other non-array value\n * from a JavaScript caller has no numeric length and is refused rather than taken for an empty\n * list (EC-1).\n */\nexport function refuseAttachments(out: OutboundMessage): SendResult | undefined {\n if (out.attachments == null || out.attachments.length === 0) return undefined;\n return {\n ok: false,\n error: { code: \"attachments_unsupported\", message: \"sms adapter cannot send attachments\" },\n };\n}\n","/**\n * `splitForSMS` — grapheme-cluster-safe multipart segmentation (D393, EC-7), keeping table rows\n * whole.\n *\n * Concatenated SMS (UDH) on modern carriers reassemble at the recipient,\n * but each TCP/IP-layer chunk is one billed message. We segment at\n * 1600 chars (default) so the API call doesn't reject and each part is\n * prefixed with `(i/N) ` to allow manual reordering when carriers\n * deliver out of sequence (EC-7).\n *\n * A text within the limit goes through core `chunkByGrapheme` as before. A longer one is cut at\n * the last grapheme boundary within each part, which is where `chunkByGrapheme`'s greedy walk\n * ends a part, so emoji (🇧🇷) and combining sequences are never severed and text with no table\n * row splits exactly as it did (pinned by `tests/split-no-table-baseline.test.ts` and the\n * equivalence test in `tests/split-tables.test.ts`). A cut that falls inside a Markdown table row\n * which fits in a part moves back to the start of that row (B-556). The rule is core\n * `splitKeepingRows`, shared with gateway-line. The `(i/N) ` prefix (and its reserved width) stays here since it is SMS-specific.\n *\n * @internal\n */\n\nimport { chunkByGrapheme, splitKeepingRows } from \"@theokit/gateway\";\n\n/**\n * Width of `\"(i/total) \"` when `i` has as many digits as `total` — the widest\n * the prefix can get for a given part count. `(99/99) ` is 8, `(100/126) ` is\n * 10, `(1000/1234) ` is 12.\n *\n * This used to be the constant 8, commented `\"(99/99) \" worst case`. It is the\n * worst case only below 100 parts; from the hundredth part on, every prefix\n * overflowed its reservation and each part exceeded the caller's declared cap\n * by 2 chars, which the provider rejects.\n */\nfunction prefixWidthFor(total: number): number {\n return 2 * String(total).length + 4;\n}\n\n/** One fixed-point pass: the parts of `text` with `partLimit` left beside the prefix. */\nfunction partsFor(text: string, limit: number, partLimit: number): string[] {\n if (text.length <= limit) return chunkByGrapheme(text, { limit, partLimit });\n // The core's RangeError for a limit of 0, 1.5 or NaN, with the message it had before.\n chunkByGrapheme(\"\", { limit, partLimit });\n return splitKeepingRows(text, partLimit);\n}\n\nexport function splitForSMS(text: string, limit = 1600): string[] {\n // Chicken and egg: the reservation depends on the part count, and the part\n // count depends on the reservation. Widening the prefix shrinks the payload,\n // which can push the count into another digit — so iterate to a fixed point.\n // It converges fast because the width grows with the LOGARITHM of the count;\n // the bound is a backstop against a pathological input, not the expected path.\n let reserved = prefixWidthFor(1);\n for (let pass = 0; pass < 8; pass += 1) {\n const partLimit = limit - reserved;\n if (partLimit <= 0) {\n throw new RangeError(\n `limit ${limit} is too small to carry an SMS part: the \"(i/N) \" prefix alone needs ${reserved} chars`,\n );\n }\n const parts = partsFor(text, limit, partLimit);\n if (parts.length <= 1) return parts; // short-circuit / single part: skip prefix\n const needed = prefixWidthFor(parts.length);\n if (needed <= reserved) {\n const total = parts.length;\n return parts.map((p, i) => `(${i + 1}/${total}) ${p}`);\n }\n reserved = needed;\n }\n /* c8 ignore next 3 -- unreachable: 8 passes cover part counts up to 10^8. */\n throw new RangeError(\n `could not settle the \"(i/N) \" prefix width for a ${text.length}-char message at limit ${limit}`,\n );\n}\n","/**\n * `SMSAdapter` — implements `BasePlatformAdapter` over a backend\n * (twilio / plivo / vonage). ADRs D389-D396.\n *\n * Lifecycle:\n * - `connect()` initializes the chosen backend (lazy peer-dep import).\n * - `disconnect()` releases the backend; idempotent.\n * - `sendMessage()` splits multipart (D393) and sends each part via backend.\n * - `onInbound(handler)` replaces previous handler (EC-H, mirror D276).\n *\n * Inbound dispatch is driven by the webhook server (`webhook-server.ts`)\n * which calls `adapter.dispatchInbound(ctx)` after signature verification.\n *\n * @public\n */\n\nimport {\n BasePlatformAdapter,\n type MessageEvent as GatewayMessageEvent,\n type OutboundMessage,\n type SendResult,\n} from \"@theokit/gateway\";\nimport { createBackend } from \"./backend/index.js\";\nimport type { SignatureContext, SMSBackend } from \"./backend-types.js\";\nimport { ConfigurationError } from \"./errors.js\";\nimport { inboundToMessageEvent } from \"./normalize.js\";\nimport { normalizeE164 } from \"./phone.js\";\nimport { refuseAttachments } from \"./refuse-attachments.js\";\nimport { splitForSMS } from \"./split.js\";\nimport type { SMSAdapterOptions } from \"./types.js\";\n\nexport class SMSAdapter extends BasePlatformAdapter {\n /**\n * Whether the \"this medium carries no formatting\" warning has already been emitted.\n *\n * Once per adapter, not once per message: a gateway answering a busy channel would turn a\n * useful diagnostic into a log flood, and a flooded log is one nobody reads — the same\n * reason the group-mention and allowlist drops elsewhere in this family log once.\n */\n private warnedAboutFormat = false;\n\n /**\n * Say, once, that a declared format is being dropped.\n *\n * `OutboundMessage.format` is the caller stating intent, and this medium has nowhere to put\n * it: no flag, no markup, no alternative part. Discarding it in silence is the swallowed-\n * error shape `rules/error-handling.md` refuses — nothing fails, and the caller learns their\n * formatting never arrived from a user, weeks later.\n *\n * @internal\n */\n private warnFormatUnsupported(format: string | undefined): void {\n // The \"is there anything to say\" question lives here rather than at the call site: a\n // `sendMessage` already at its complexity limit should ask one thing, not three.\n if (format === undefined || format === \"plain\") return;\n if (this.warnedAboutFormat) return;\n this.warnedAboutFormat = true;\n process.stderr.write(\n `[gateway-sms] format=\"${format}\" was declared, and SMS cannot carry it — ` +\n \"the medium is plain text. Sending unformatted; this is logged once.\\n\",\n );\n }\n\n readonly platform = \"sms\" as const;\n\n /**\n * The URL the provider POSTs inbound to, as the provider sees it.\n *\n * Required by all three backend option shapes and documented there as \"used by signature\n * verifier\" — and, measured 2026-08-31, read by nothing: it appeared only in the type and in test\n * fixtures. Twilio SIGNS this URL, so the value matters most in exactly the case where the\n * request cannot supply it: behind a proxy or a tunnel, the request's own URL is the internal one\n * and will not match what was signed.\n *\n * Exposed so {@link smsWebhookVerifier} can use it, which is what makes the option true.\n */\n readonly publicUrl: string;\n\n private readonly backend: SMSBackend;\n private inboundHandler: ((event: GatewayMessageEvent) => Promise<void>) | undefined;\n private connected = false;\n private readonly defaultCountry: string | undefined;\n\n constructor(opts: SMSAdapterOptions) {\n super();\n // EC-1: refuse to operate without signing secret.\n const secret = secretFromOpts(opts);\n if (secret.length === 0) {\n throw new ConfigurationError({\n code: \"signing_secret_required\",\n message: `gateway-sms: backend=\"${opts.backend}\" requires a signing secret (would accept unsigned webhooks)`,\n });\n }\n this.defaultCountry = opts.defaultCountry;\n this.publicUrl = opts.publicUrl;\n this.backend = createBackend(opts);\n }\n\n async connect(): Promise<boolean> {\n if (this.connected) return true;\n const ok = await this.backend.connect();\n this.connected = ok;\n return ok;\n }\n\n async disconnect(): Promise<void> {\n if (!this.connected) return;\n await this.backend.disconnect();\n this.connected = false;\n this.inboundHandler = undefined;\n }\n\n async sendMessage(out: OutboundMessage): Promise<SendResult> {\n return refuseAttachments(out) ?? this.sendText(out);\n }\n\n private async sendText(out: OutboundMessage): Promise<SendResult> {\n if (out.text.length === 0) {\n return { ok: false, error: { code: \"empty_text\", message: \"outbound text is empty\" } };\n }\n let toE164: string;\n try {\n toE164 = normalizeE164(out.channel.id, this.defaultCountry);\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err);\n return { ok: false, error: { code: \"invalid_phone_number\", message: msg } };\n }\n const parts = splitForSMS(out.text);\n // Send sequentially so the recipient sees them in order; concurrent\n // submit would still cost the same but breaks ordering at carriers.\n let lastResult: SendResult | undefined;\n // SMS is plain text by definition. Reading the field is not ceremony: it is what turns a\n // silent discard into a stated one.\n this.warnFormatUnsupported(out.format);\n\n for (const part of parts) {\n lastResult = await this.backend.sendMessage(toE164, part);\n if (lastResult.ok !== true) {\n return {\n ok: false,\n error: {\n code: lastResult.error?.code ?? \"partial_send_failure\",\n message: `partial send failed after ${parts.indexOf(part)}/${parts.length}: ${lastResult.error?.message ?? \"unknown\"}`,\n },\n };\n }\n }\n return lastResult ?? { ok: false, error: { code: \"send_failed\", message: \"no parts sent\" } };\n }\n\n onInbound(handler: (event: GatewayMessageEvent) => Promise<void>): () => void {\n // EC-H: replace, not stack.\n this.inboundHandler = handler;\n return () => {\n if (this.inboundHandler === handler) this.inboundHandler = undefined;\n };\n }\n\n /**\n * Webhook hook — called by `createWebhookServer` AFTER signature\n * verification + parseInbound. Returns dispatch outcome (used for\n * 200/204 vs 500 by the webhook handler).\n *\n * @internal\n */\n async dispatchInbound(ctx: SignatureContext): Promise<\"ok\" | \"no_handler\" | \"parse_failed\"> {\n if (!this.backend.verifySignature(ctx)) {\n // Caller (webhook-server) inspects this via verifySignature directly,\n // but we re-check defensively if anyone calls dispatch directly.\n return \"parse_failed\";\n }\n let inbound: ReturnType<SMSBackend[\"parseInbound\"]>;\n try {\n inbound = this.backend.parseInbound(ctx);\n } catch {\n return \"parse_failed\";\n }\n if (this.inboundHandler === undefined) return \"no_handler\";\n const event = inboundToMessageEvent(inbound, this.backend.kind);\n try {\n await this.inboundHandler(event);\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err);\n process.stderr.write(`[gateway-sms] handler threw: ${msg}\\n`);\n }\n return \"ok\";\n }\n\n /**\n * Direct signature check — used by the webhook server to respond\n * `401` BEFORE dispatch when signature is invalid.\n *\n * @internal\n */\n verifySignature(ctx: SignatureContext): boolean {\n return this.backend.verifySignature(ctx);\n }\n\n /**\n * Direct parse — used by the webhook server when signature was already\n * validated upstream. Returns the normalized `SMSMessageEvent` to be\n * dispatched.\n *\n * @internal\n */\n buildEventFromCtx(ctx: SignatureContext): GatewayMessageEvent {\n const inbound = this.backend.parseInbound(ctx);\n return inboundToMessageEvent(inbound, this.backend.kind);\n }\n\n /**\n * Dispatch a pre-built event (used by webhook server after manual\n * signature + parse). Honors EC-H replace semantics and isolates\n * handler exceptions per `gateway-runner` contract.\n *\n * @internal\n */\n async dispatchEvent(event: GatewayMessageEvent): Promise<\"ok\" | \"no_handler\"> {\n if (this.inboundHandler === undefined) return \"no_handler\";\n try {\n await this.inboundHandler(event);\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err);\n process.stderr.write(`[gateway-sms] handler threw: ${msg}\\n`);\n }\n return \"ok\";\n }\n\n /** Backend kind (escape hatch for callers needing to introspect). */\n getBackendKind(): \"twilio\" | \"plivo\" | \"vonage\" {\n return this.backend.kind;\n }\n\n /**\n * Deliver an event that arrived out of band — the ingest `onInbound` had no counterpart for (#83).\n *\n * One line over `runHandler`, which owns the containment: a handler is user code, its throw is\n * named as the handler's failure rather than the platform's, and delivery continues.\n */\n override async deliver(\n event: GatewayMessageEvent,\n ): Promise<\"ok\" | \"no_handler\" | \"handler_threw\"> {\n return this.runHandler(this.inboundHandler, event);\n }\n}\n\nfunction secretFromOpts(opts: SMSAdapterOptions): string {\n switch (opts.backend) {\n case \"twilio\":\n return opts.authToken;\n case \"plivo\":\n return opts.authToken;\n case \"vonage\":\n return opts.signatureSecret;\n default: {\n const _exhaustive: never = opts;\n void _exhaustive;\n return \"\";\n }\n }\n}\n","/**\n * `smsChannel` — the SMS channel (Twilio backend only) described as data.\n *\n * Typed locally on purpose: the object is structurally a `ChannelDescriptor`, but a published\n * `.d.ts` naming a core type must not break a consumer on an older peer floor.\n */\n\nimport { SMSAdapter } from \"./adapter.js\";\nimport { ConfigurationError } from \"./errors.js\";\n\nconst KEYS = [\"accountSid\", \"authToken\", \"fromNumber\", \"publicUrl\"] as const;\n\nfunction readString(config: Readonly<Record<string, unknown>>, key: string): string {\n const value = config[key];\n if (typeof value !== \"string\" || value.trim().length === 0) {\n throw new ConfigurationError({\n code: \"invalid_config\",\n message: `gateway-sms: config.${key} must be a non-empty string`,\n detail: key,\n });\n }\n return value;\n}\n\n/** One configuration field, shaped like the core's `ChannelConfigField` (typed locally). */\ninterface ConfigField {\n readonly key: string;\n readonly required: boolean;\n readonly secret: boolean;\n readonly env: string;\n readonly description: string;\n}\n\nconst CONFIG: ReadonlyArray<ConfigField> = [\n {\n key: \"accountSid\",\n required: true,\n secret: false,\n env: \"SMS_ACCOUNT_SID\",\n description: \"The Twilio account SID.\",\n },\n {\n key: \"authToken\",\n required: true,\n secret: true,\n env: \"SMS_AUTH_TOKEN\",\n description: \"The Twilio auth token; also verifies inbound signatures.\",\n },\n {\n key: \"fromNumber\",\n required: true,\n secret: false,\n env: \"SMS_FROM_NUMBER\",\n description: \"The bot's own E.164 number, used as the sender.\",\n },\n {\n key: \"publicUrl\",\n required: true,\n secret: false,\n env: \"SMS_PUBLIC_URL\",\n description: \"The public URL Twilio posts inbound messages to.\",\n },\n];\n\n/**\n * The SMS channel on the Twilio backend. `transport` is `\"socket\"` as the issue requires; inbound\n * messages still arrive through a webhook the app hosts (see the README).\n *\n * `create` validates each value with this package's `ConfigurationError` and makes no network call.\n *\n * @public\n */\nexport const smsChannel = {\n platform: \"sms\" as const,\n transport: \"socket\" as const,\n config: CONFIG,\n create(config: Readonly<Record<string, unknown>>): SMSAdapter {\n const [accountSid, authToken, fromNumber, publicUrl] = KEYS.map((k) => readString(config, k));\n return new SMSAdapter({\n backend: \"twilio\",\n accountSid: accountSid as string,\n authToken: authToken as string,\n fromNumber: fromNumber as string,\n publicUrl: publicUrl as string,\n });\n },\n};\n","/**\n * Translating a raw provider webhook into the canonical event.\n *\n * **This does NOT go through TheoKit's `handleChannelWebhook`.** Signature verification here needs\n * the RAW body, the headers and the exact URL — `ChannelMessage` carries none of the three, so the\n * check cannot be performed from inside `onMessage` whatever the provider sends. Twilio adds a\n * second obstacle: it posts `application/x-www-form-urlencoded`, and that seam reads the body with\n * `request.json()` and answers 400 when it is not JSON. (Plivo accepts either encoding and Vonage\n * posts JSON, so only the first reason applies to them.)\n *\n * For an Express app, `createWebhookServer` is the whole path and you never call this — it builds\n * the {@link SignatureContext}, verifies the signature and goes through the adapter. This export is\n * for a route you host yourself: build the context from a request whose body you have not parsed,\n * then call this. It composes two functions that\n * already existed and were both private: each backend's `parseInbound`, which turns a provider's\n * raw body into the provider-agnostic {@link SMSInbound}, and `inboundToMessageEvent`, which turns\n * that into the canonical event. Neither is duplicated here — per ADR D426 the mapping stays in one\n * place, and this is composition, not a second translator.\n *\n * **Why it takes the adapter's options.** Parsing is provider-specific (`Twilio` posts\n * `MessageSid`, Plivo posts `MessageUUID`) and, for Twilio, country-dependent: a number that is not\n * already in E.164 is normalised against `defaultCountry`. Both live in the options an app already\n * holds, because it constructed the adapter with them. `createBackend` only stores them — it opens\n * no connection and loads no SDK, so this stays a pure function over its inputs.\n */\n\nimport type { SMSMessageEvent } from \"@theokit/gateway\";\n\nimport { createBackend } from \"./backend/index.js\";\nimport type { SignatureContext, SMSInbound } from \"./backend-types.js\";\nimport { inboundToMessageEvent } from \"./normalize.js\";\nimport type { SMSAdapterOptions } from \"./types.js\";\n\n/**\n * Translate one raw provider webhook into an {@link SMSMessageEvent}.\n *\n * Returns `null` — never throws — when the body is not one this provider recognises. The caller is\n * whatever holds the {@link SignatureContext}: `createWebhookServer` here, or your own route. It\n * returns `null` rather than throwing because a throw out of a webhook handler becomes a failed\n * request, and the provider then sees a delivery failure for a body that was merely unrecognised\n * (ADR D428, whose original rationale — \"runs after the 200\" — was measured false on 2026-08-24).\n *\n * `null` here means \"this body is not a parseable inbound message\".\n *\n * **One class of configuration error is not distinguishable from a bad body, and is not pretended\n * to be.** `defaultCountry` is read while parsing the body's own numbers, and `normalizeE164`\n * raises the same `ConfigurationError` for a bad configured country as for a bad number in the\n * body. An invalid `defaultCountry` therefore degrades to `null` rather than throwing.\n *\n * An earlier version tried to separate them by validating `options.fromNumber` up front. That was\n * wrong twice: `fromNumber` is passed raw to the provider SDK everywhere else in this package and\n * validated nowhere, and the invented rule rejected four documented, valid configurations — a\n * Vonage alphanumeric sender ID (`\"ACME\"`), a Twilio short code (`\"12345\"`), a Messaging Service\n * SID (`\"MG…\"`), and a national number with `defaultCountry` set. Each one threw out of\n * `onMessage`, turning a message the provider delivered into a failed request — precisely the\n * failure the check was written to prevent.\n * Inventing a validation stricter than the package's own is how that happened.\n *\n * @public\n */\nexport function parseInbound(\n options: SMSAdapterOptions,\n ctx: SignatureContext,\n): SMSMessageEvent | null {\n // `createBackend` is the CONFIGURATION step and sits outside the try on purpose: an unsupported\n // `backend` is a programmer error and must surface, not become the same `null` a malformed body\n // produces.\n const backend = createBackend(options);\n\n let inbound: SMSInbound;\n try {\n inbound = backend.parseInbound(ctx);\n } catch {\n // Everything from here is body-dependent, so any error means the body was unreadable. Caught\n // whatever its type: `decodeURIComponent` raises `URIError` on a malformed percent-escape\n // (`From=%zz`) and `normalizeE164` raises `ConfigurationError` on a number the body carried.\n // Both are bad requests, and returning `null` is what keeps them from failing the request:\n // measured against `theokit@0.48.14`, `handleChannelWebhook` awaits `onMessage` BEFORE\n // building the 200 and catches nothing around it, so a throw here escapes it entirely and\n // the 200 is never built (ADR D428, whose original rationale — \"runs after the 200\" — was\n // measured false on 2026-08-24).\n return null;\n }\n\n // A body the provider posted that carries no message id.\n //\n // Deliberately does NOT also check `inbound.from === \"\"`: all three backends build `from` with\n // `normalizeE164(x ?? \"\")`, which throws on an empty string, so the branch was unreachable and a\n // mutation deleting it survived the suite.\n if (inbound.messageId === \"\") return null;\n\n return inboundToMessageEvent(inbound, options.backend);\n}\n","/**\n * Standalone Twilio request verifier.\n *\n * Twilio signs voice webhooks exactly like SMS webhooks: `X-Twilio-Signature` is the base64\n * HMAC-SHA1 (keyed with the auth token) of the full URL followed by every POST parameter, sorted by\n * name, as `name + value`. No adapter and no `twilio` SDK are needed.\n *\n * @public\n */\n\nimport { createHmac, timingSafeEqual } from \"node:crypto\";\n\nimport type { WebhookVerifyResult } from \"./webhook-verifier.js\";\n\n/** Options for {@link twilioRequestVerifier}. @public */\nexport interface TwilioRequestVerifierOptions {\n /** The Twilio auth token the signature is keyed with. */\n readonly authToken: string;\n /**\n * The URL Twilio POSTs to, as Twilio sees it. Defaults to the request URL, which behind a proxy\n * or tunnel is the internal one and will not match.\n */\n readonly publicUrl?: string;\n}\n\nfunction decode(s: string): string {\n return decodeURIComponent(s.replace(/\\+/g, \" \"));\n}\n\n/** Parse a form body keeping repeated keys: Twilio signs every value of a repeated name. */\nfunction parseForm(body: string): Array<[string, string]> {\n const out: Array<[string, string]> = [];\n for (const pair of body.split(\"&\")) {\n if (pair.length === 0) continue;\n const eq = pair.indexOf(\"=\");\n out.push([decode(eq < 0 ? pair : pair.slice(0, eq)), decode(eq < 0 ? \"\" : pair.slice(eq + 1))]);\n }\n return out;\n}\n\nfunction compare(a: string, b: string): number {\n if (a === b) return 0;\n return a < b ? -1 : 1;\n}\n\nfunction sign(authToken: string, url: string, pairs: Array<[string, string]>): string {\n const sorted = [...pairs].sort((x, y) => compare(x[0], y[0]) || compare(x[1], y[1]));\n let data = url;\n for (const [k, v] of sorted) data += k + v;\n return createHmac(\"sha1\", authToken).update(data, \"utf8\").digest(\"base64\");\n}\n\n/**\n * Build a verifier for Twilio webhooks (SMS or voice).\n *\n * The request body is READ; pass a clone if it is needed afterwards.\n *\n * @public\n */\nexport function twilioRequestVerifier(\n opts: TwilioRequestVerifierOptions,\n): (request: Request) => Promise<WebhookVerifyResult> {\n return async (request: Request): Promise<WebhookVerifyResult> => {\n const header = request.headers.get(\"x-twilio-signature\");\n if (header === null || header.length === 0) {\n return { ok: false, reason: \"missing X-Twilio-Signature header\" };\n }\n let pairs: Array<[string, string]>;\n try {\n pairs = parseForm(await request.text());\n } catch {\n return { ok: false, reason: \"unparseable body\" };\n }\n const expected = Buffer.from(sign(opts.authToken, opts.publicUrl ?? request.url, pairs));\n const actual = Buffer.from(header);\n if (expected.length !== actual.length || !timingSafeEqual(expected, actual)) {\n return { ok: false, reason: \"signature mismatch\" };\n }\n return { ok: true };\n };\n}\n","/**\n * Minimal TwiML builders. Every text node and attribute value is XML-escaped.\n *\n * @public\n */\n\n// biome-ignore lint/suspicious/noControlCharactersInRegex: stripping XML-illegal controls on purpose\nconst ILLEGAL = /[\\u0000-\\u0008\\u000B\\u000C\\u000E-\\u001F]/g;\n\nfunction esc(s: string): string {\n return s\n .replace(ILLEGAL, \"\")\n .replace(/&/g, \"&\")\n .replace(/</g, \"<\")\n .replace(/>/g, \">\")\n .replace(/\"/g, \""\")\n .replace(/'/g, \"'\");\n}\n\nfunction attrs(a: Record<string, string | number | undefined>): string {\n let out = \"\";\n for (const [k, v] of Object.entries(a)) {\n if (v !== undefined) out += ` ${k}=\"${esc(String(v))}\"`;\n }\n return out;\n}\n\n/**\n * TwiML verb builders for Twilio voice webhooks. Each returns an XML string; combine them with\n * `twiml.response`.\n *\n * @public\n */\nexport const twiml = {\n say(text: string, opts: { voice?: string; language?: string } = {}): string {\n return `<Say${attrs({ voice: opts.voice, language: opts.language })}>${esc(text)}</Say>`;\n },\n gather(opts: {\n action: string;\n input?: \"speech\" | \"dtmf\";\n timeoutSeconds?: number;\n prompt?: string;\n }): string {\n const a = attrs({ action: opts.action, input: opts.input, timeout: opts.timeoutSeconds });\n return opts.prompt === undefined\n ? `<Gather${a}/>`\n : `<Gather${a}>${twiml.say(opts.prompt)}</Gather>`;\n },\n redirect(url: string): string {\n return `<Redirect>${esc(url)}</Redirect>`;\n },\n hangup(): string {\n return \"<Hangup/>\";\n },\n /** Wrap verbs in `<Response>`. Verbs must come from the builders above. */\n response(...verbs: string[]): string {\n return `<?xml version=\"1.0\" encoding=\"UTF-8\"?><Response>${verbs.join(\"\")}</Response>`;\n },\n};\n","/**\n * `createWebhookServer` — Express helper for inbound SMS webhooks.\n *\n * Registers per-backend routes (`/sms/twilio`, `/sms/plivo`, `/sms/vonage`)\n * each with the matching parser middleware. All three:\n *\n * 1. Read the raw body verbatim (signature verification depends on the\n * exact bytes — even one extra `\\r\\n` invalidates the HMAC).\n * 2. Call `adapter.verifySignature(ctx)` → 401 if false.\n * 3. Call `adapter.buildEventFromCtx(ctx)` → `dispatchEvent(event)`.\n * 4. Return 204 No Content.\n *\n * Caller can pass an existing Express app (`opts.app`) or let the helper\n * create one. `start()` / `stop()` are idempotent.\n *\n * @public\n */\n\nimport {\n DEFAULT_WEBHOOK_MAX_BYTES,\n listenerLifecycle,\n loadPeer,\n rawBodyCapture,\n} from \"@theokit/gateway\";\nimport type { Express, Request, Response } from \"express\";\nimport type { SMSAdapter } from \"./adapter.js\";\nimport type { SignatureContext } from \"./backend-types.js\";\n\nimport { ConfigurationError } from \"./errors.js\";\n\nexport interface WebhookServerOptions {\n readonly adapter: SMSAdapter;\n /** Mount path prefix; default `\"/sms\"`. The full path is `${path}/${backend}`. */\n readonly path?: string;\n /** Listen port. Ignored when `app` is provided. Default `3000`. */\n readonly port?: number;\n /** Inject an existing Express app instead of creating one. */\n readonly app?: Express;\n}\n\n/** A started HTTP listener, with the handle needed to shut it down again. */\nexport interface WebhookServer {\n start(): Promise<void>;\n stop(): Promise<void>;\n}\n\nasync function loadExpress(): Promise<() => Express> {\n return loadPeer<() => Express>(\n async () => import(\"express\"),\n () => {\n throw new ConfigurationError({\n code: \"express_not_installed\",\n message: 'gateway-sms: peer-dep \"express\" not installed. Run: pnpm add express',\n });\n },\n );\n}\n\n/**\n * The URL the provider signed.\n *\n * `publicUrl` wins when it is configured, because it is the only value that survives a proxy. The\n * provider verifies against the address IT posted to, and behind a tunnel, an ingress, or a load\n * balancer terminating TLS the reconstruction below yields the internal one — so a correct\n * signature fails, on every delivery, with nothing in the log naming the cause.\n *\n * The header reconstruction stays as the fallback: an app served directly has nothing to configure\n * and the headers are the truth. Measured 2026-08-31 — `publicUrl` is required by all three backend\n * option shapes and documented as \"used by signature verifier\", and until this commit no source\n * file read it.\n */\nfunction signedUrl(\n req: Request,\n headers: Readonly<Record<string, string>>,\n publicUrl?: string,\n): string {\n if (publicUrl !== undefined && publicUrl !== \"\") return publicUrl;\n const protoHeader = headers[\"x-forwarded-proto\"];\n const proto = protoHeader ?? (req.secure ? \"https\" : \"http\");\n const host = req.get(\"host\") ?? \"localhost\";\n return `${proto}://${host}${req.originalUrl}`;\n}\n\nfunction buildSignatureContext(req: Request, publicUrl?: string): SignatureContext {\n const rawBody = (req as Request & { rawBody?: string }).rawBody ?? \"\";\n const headers: Record<string, string> = {};\n for (const [k, v] of Object.entries(req.headers)) {\n headers[k.toLowerCase()] = Array.isArray(v) ? v.join(\",\") : (v ?? \"\");\n }\n return { headers, rawBody, url: signedUrl(req, headers, publicUrl) };\n}\n\n/**\n * Build the HTTP listener that receives the provider's inbound-SMS callbacks.\n *\n * The provider dials in, so this endpoint must be reachable over public HTTPS and registered in the\n * provider console — inbound cannot work behind a firewall. `express` is loaded lazily, so a project\n * that only sends messages never pays for it.\n */\nexport async function createWebhookServer(opts: WebhookServerOptions): Promise<WebhookServer> {\n const createApp = await loadExpress();\n const app: Express = opts.app ?? createApp();\n const prefix = opts.path ?? \"/sms\";\n const backend = opts.adapter.getBackendKind();\n\n const handler = (req: Request, res: Response): void => {\n const ctx = buildSignatureContext(req, opts.adapter.publicUrl);\n if (!opts.adapter.verifySignature(ctx)) {\n res.status(401).type(\"text/plain\").send(\"invalid signature\");\n return;\n }\n let event: ReturnType<typeof opts.adapter.buildEventFromCtx>;\n try {\n event = opts.adapter.buildEventFromCtx(ctx);\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err);\n res.status(400).type(\"text/plain\").send(`parse failed: ${msg}`);\n return;\n }\n // Same contract as the LINE server: the provider is answered before the handler runs, so a\n // slow handler cannot become a provider retry. That makes the dispatch floated, and a floated\n // rejection ends the process — so it is caught here rather than left to the runtime (#41).\n void opts.adapter.dispatchEvent(event).catch((err: unknown) => {\n const message = err instanceof Error ? err.message : String(err);\n process.stderr.write(`[gateway-sms] webhook dispatch failed: ${message}\\n`);\n });\n // Twilio expects either TwiML or 204; 204 keeps things simple\n // and avoids accidentally double-replying.\n res.status(204).end();\n };\n\n app.post(\n `${prefix}/${backend}`,\n rawBodyCapture(\"gateway-sms\", { maxBytes: DEFAULT_WEBHOOK_MAX_BYTES }),\n handler,\n );\n\n // The lifecycle lives in `@theokit/gateway`, written once. It was duplicated here and in\n // gateway-line, and the same write-once latch bug had to be fixed in both files by one commit —\n // which is what turned the duplication from a style question into a defect (#89).\n return listenerLifecycle({ app, port: opts.port ?? 3000, injected: opts.app !== undefined });\n}\n","/**\n * The SMS half of a channel webhook, in the shape a framework webhook seam expects.\n *\n * `theokit/server/webhook` ships validators for the platforms whose signature is a plain HMAC it\n * can compute itself. SMS is not one of them: Twilio signs the URL plus the sorted POST parameters,\n * Plivo signs a different string again, and Vonage uses a JWT. Those three schemes already exist in\n * this package, correctly, with their own tests — reimplementing them one repository over would put\n * security-critical code in two places and guarantee they drift.\n *\n * So the direction is inverted. The framework declares the SHAPE; the package that owns the\n * platform provides the implementation. The shape is structural, so nothing here imports the\n * framework and this package gains no dependency:\n *\n * ```ts\n * await handleChannelWebhook(request, pathname, {\n * validators: { sms: smsWebhookVerifier(adapter) },\n * })\n * ```\n *\n * @public\n */\n\nimport type { SMSAdapter } from \"./adapter.js\";\nimport type { SignatureContext } from \"./backend-types.js\";\n\n/**\n * What a verifier answers. Structurally identical to the framework's `VerifyResult`, declared here\n * so this package does not depend on the framework to describe its own return value.\n *\n * @public\n */\nexport type WebhookVerifyResult =\n | { readonly ok: true }\n | { readonly ok: false; readonly reason: string };\n\n/** Options for {@link smsWebhookVerifier}. @public */\nexport interface SMSWebhookVerifierOptions {\n /**\n * The URL the provider POSTs to, as the provider sees it.\n *\n * Twilio signs the URL, so verification compares against whatever string is passed here — and\n * behind a proxy or a tunnel the request's own URL is the INTERNAL one, which will not match.\n * Defaults to the adapter's configured `publicUrl` when it has one, and to the request URL\n * otherwise.\n */\n readonly publicUrl?: string;\n}\n\n/**\n * The subset of the adapter this verifier reads. Stated as an interface so the parameter is honest\n * about its requirements, and so a test can supply the two members without a live provider SDK.\n */\ninterface VerifiableAdapter {\n verifySignature(ctx: SignatureContext): boolean;\n readonly publicUrl?: string;\n}\n\n/**\n * The lowercased header map {@link SignatureContext} promises its consumers.\n *\n * No `toLowerCase()` here, and that is the point rather than an omission: the Fetch `Headers` object\n * normalises names on the way in, so iterating it already yields `x-twilio-signature` however the\n * sender wrote it. Lowercasing again was in the first version and mutation testing showed it dead —\n * removing it changed no test, because the platform had already done the work.\n */\nfunction headersOf(request: Request): Record<string, string> {\n const out: Record<string, string> = {};\n request.headers.forEach((value, key) => {\n out[key] = value;\n });\n return out;\n}\n\n/**\n * Build a verifier for one configured SMS adapter.\n *\n * The request is READ, so pass a clone if the body is needed afterwards — a framework seam that\n * hands validators a `clone()` already does this. Reading it raw is not optional: every provider\n * signs the exact bytes, and a body that was parsed and re-serialised hashes differently.\n *\n * **Connect the adapter first.** Each backend loads its provider SDK during `connect()`, and until\n * it has, `verifySignature` answers `false` for everything — so a verifier wired before connect\n * refuses every genuine delivery as a bad signature. The two are NOT distinguishable here: the\n * backend contract returns a boolean, and inventing a reason this function cannot actually observe\n * would be worse than the ambiguity. The behaviour is pinned by a test rather than papered over,\n * and telling them apart needs a readiness signal the adapter does not expose today.\n *\n * @public\n */\nexport function smsWebhookVerifier(\n adapter: SMSAdapter | VerifiableAdapter,\n opts: SMSWebhookVerifierOptions = {},\n): (request: Request) => Promise<WebhookVerifyResult> {\n return async (request: Request): Promise<WebhookVerifyResult> => {\n const rawBody = await request.text();\n const ctx: SignatureContext = {\n headers: headersOf(request),\n rawBody,\n url: opts.publicUrl ?? adapter.publicUrl ?? request.url,\n };\n return adapter.verifySignature(ctx)\n ? { ok: true }\n : { ok: false, reason: \"signature mismatch\" };\n };\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/errors.ts","../src/phone.ts","../src/backend/plivo.ts","../src/backend/twilio.ts","../src/backend/vonage.ts","../src/backend/index.ts","../src/normalize.ts","../src/refuse-attachments.ts","../src/split.ts","../src/adapter.ts","../src/parse-inbound.ts","../src/twilio-verifier.ts","../src/fetch-webhook.ts","../src/channel.ts","../src/twiml.ts","../src/webhook-server.ts","../src/webhook-verifier.ts"],"names":["GatewayConfigurationError","parsePhoneNumberFromString","parseFormUrlEncoded","chunkByGrapheme","splitKeepingRows","BasePlatformAdapter","options","createHmac","timingSafeEqual","loadPeer","rawBodyCapture","DEFAULT_WEBHOOK_MAX_BYTES","listenerLifecycle"],"mappings":";;;;;;;AA8BO,IAAM,kBAAA,GAAN,cAAiCA,iCAAA,CAA0B;AAAA,EAC9C,IAAA,GAAO,oBAAA;AAAA,EACzB,YAAY,IAAA,EAAiC;AAC3C,IAAA,KAAA,CAAM,eAAe,IAAI,CAAA;AAAA,EAC3B;AACF;AASO,IAAM,wBAAA,GAAN,cAAuC,kBAAA,CAAmB;AAAA,EAC/D,WAAA,CAAY,SAAwC,OAAA,EAAiB;AACnE,IAAA,KAAA,CAAM;AAAA,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Error` — programmer error at construction time\n * (missing signing secret, missing backend SDK install, malformed\n * phone number on outbound). Thrown synchronously.\n * - `BackendNotInstalledError` — peer-dep optional backend (twilio /\n * plivo / @vonage/server-sdk) was selected but the npm package is\n * not installed. Carries actionable install hint.\n *\n * `ConfigurationError` extends the shared core `GatewayConfigurationError`\n * base (roadmap M2); the SDK still consumes structured errors via\n * `metadata.code`. Behavior byte-identical (pinned by `tests/errors.test.ts`).\n *\n * @internal — re-exported by `src/index.ts`.\n */\n\nimport { GatewayConfigurationError, type GatewayConfigurationErrorOptions } from \"@theokit/gateway\";\n\n/** @knipignore — public input shape for `ConfigurationError` constructor (caller-extensible). */\nexport type ConfigurationErrorOptions = GatewayConfigurationErrorOptions;\n\n/**\n * Misconfiguration of this adapter, raised before any network call.\n *\n * Extends the shared core base so every gateway package reports configuration faults in one shape:\n * a structured `code` the caller can branch on, tagged with `\"gateway-sms\"` as the origin. A\n * missing credential or an unsupported option is a programmer error, not a transient failure —\n * these are never retried.\n */\nexport class ConfigurationError extends GatewayConfigurationError {\n override readonly name = \"ConfigurationError\";\n constructor(opts: ConfigurationErrorOptions) {\n super(\"gateway-sms\", opts);\n }\n}\n\n/**\n * The provider SDK for the selected backend is not installed.\n *\n * `gateway-sms` speaks to Twilio, Plivo or Vonage, and declares all three as optional peers — a\n * project installs only the one it uses. Selecting a backend whose SDK is absent is caught here, at\n * connect time, with the package name and the command that installs it.\n */\nexport class BackendNotInstalledError extends ConfigurationError {\n constructor(backend: \"twilio\" | \"plivo\" | \"vonage\", pkgName: string) {\n super({\n code: \"backend_not_installed\",\n message: `gateway-sms: peer-dep \"${pkgName}\" not installed but backend=\"${backend}\" was selected. Run: pnpm add ${pkgName}`,\n detail: pkgName,\n });\n }\n}\n","/**\n * E.164 phone normalization (D391, EC-6).\n *\n * Wraps `libphonenumber-js` (full — accepts mobile + toll-free; the\n * `/mobile` sub-bundle was inadequate because it rejects toll-free\n * US 1-800 numbers).\n *\n * @internal\n */\n\nimport { parsePhoneNumberFromString } from \"libphonenumber-js\";\n\nimport { ConfigurationError } from \"./errors.js\";\n\n/**\n * Normalize a free-form phone number to canonical E.164 (`+5511999999999`).\n *\n * Accepts:\n * - International with `+`: `\"+5511999999999\"` → unchanged.\n * - National without `+` when `defaultCountry` is provided: `(\"11999999999\", \"BR\")` → `\"+5511999999999\"`.\n * - Toll-free US (EC-6): `\"+18001234567\"` → unchanged.\n *\n * Throws `ConfigurationError({ code: \"invalid_phone_number\" })` on any\n * input that cannot be parsed to a valid number.\n */\nexport function normalizeE164(input: string, defaultCountry?: string): string {\n if (input.length === 0) {\n throw new ConfigurationError({\n code: \"invalid_phone_number\",\n message: \"gateway-sms: phone number is empty\",\n detail: \"<empty>\",\n });\n }\n const parsed = parsePhoneNumberFromString(\n input,\n defaultCountry as Parameters<typeof parsePhoneNumberFromString>[1],\n );\n if (parsed === undefined || !parsed.isValid()) {\n throw new ConfigurationError({\n code: \"invalid_phone_number\",\n message: `gateway-sms: invalid phone number ${JSON.stringify(input)}`,\n detail: input,\n });\n }\n return parsed.format(\"E.164\");\n}\n","/**\n * Plivo backend impl.\n *\n * - SDK: `plivo` (peer-dep, optional).\n * - Signature: `X-Plivo-Signature-V3` is HMAC-SHA256 of the request URL\n * + nonce + body. `validateV3Signature` is exposed by the SDK; we\n * delegate to avoid reimplementation.\n *\n * @internal\n */\n\nimport type { SendResult } from \"@theokit/gateway\";\nimport type { SignatureContext, SMSBackend, SMSInbound } from \"../backend-types.js\";\nimport { BackendNotInstalledError } from \"../errors.js\";\nimport { normalizeE164 } from \"../phone.js\";\nimport type { PlivoOptions } from \"../types.js\";\n\ninterface PlivoCreateResponse {\n apiId?: string;\n messageUuid?: string[];\n message_uuid?: string[];\n}\n\ninterface PlivoClient {\n messages: {\n // The actual SDK uses positional args: create(src, dst, text, ...).\n create(src: string, dst: string, text: string): Promise<PlivoCreateResponse>;\n };\n}\n\ninterface PlivoModule {\n Client: new (authId?: string, authToken?: string) => PlivoClient;\n // Real SDK signature: validateV3Signature(method, uri, nonce, authToken, v3Signature)\n validateV3Signature?: (\n method: string,\n uri: string,\n nonce: string,\n authToken: string,\n signature: string,\n ) => boolean;\n}\n\nasync function loadPlivo(): Promise<PlivoModule> {\n try {\n // Plivo's published types are stricter (positional args) than our\n // generic mock; we narrow at call sites and pass through unknown.\n const mod = (await import(\"plivo\")) as unknown as PlivoModule;\n return mod;\n } catch {\n throw new BackendNotInstalledError(\"plivo\", \"plivo\");\n }\n}\n\nexport class PlivoBackend implements SMSBackend {\n readonly kind = \"plivo\" as const;\n private mod: PlivoModule | undefined;\n private client: PlivoClient | undefined;\n\n constructor(private readonly opts: PlivoOptions) {}\n\n async connect(): Promise<boolean> {\n if (this.client !== undefined) return true;\n this.mod = await loadPlivo();\n this.client = new this.mod.Client(this.opts.authId, this.opts.authToken);\n return true;\n }\n\n async disconnect(): Promise<void> {\n this.client = undefined;\n }\n\n verifySignature(ctx: SignatureContext): boolean {\n if (this.mod?.validateV3Signature === undefined) return false;\n const signature = ctx.headers[\"x-plivo-signature-v3\"];\n const nonce = ctx.headers[\"x-plivo-signature-v3-nonce\"];\n if (signature === undefined || nonce === undefined) return false;\n try {\n return this.mod.validateV3Signature(\"POST\", ctx.url, nonce, this.opts.authToken, signature);\n } catch {\n return false;\n }\n }\n\n parseInbound(ctx: SignatureContext): SMSInbound {\n let params: Record<string, string> = {};\n // Plivo posts JSON or form-encoded depending on application config.\n if ((ctx.headers[\"content-type\"] ?? \"\").includes(\"application/json\")) {\n try {\n params = JSON.parse(ctx.rawBody) as Record<string, string>;\n } catch {\n params = {};\n }\n } else {\n params = parseFormUrlEncoded(ctx.rawBody);\n }\n return {\n from: normalizeE164(params.From ?? \"\", this.opts.defaultCountry),\n to: normalizeE164(params.To ?? \"\", this.opts.defaultCountry),\n body: params.Text ?? params.text ?? \"\",\n messageId: params.MessageUUID ?? params.message_uuid ?? \"\",\n receivedAt: Date.now(),\n raw: params,\n };\n }\n\n async sendMessage(to: string, body: string): Promise<SendResult> {\n if (this.client === undefined) {\n return {\n ok: false,\n error: { code: \"not_connected\", message: \"PlivoBackend.connect() not called\" },\n };\n }\n try {\n const resp = await this.client.messages.create(this.opts.fromNumber, to, body);\n const id = resp.messageUuid?.[0] ?? resp.message_uuid?.[0] ?? resp.apiId ?? \"\";\n return { ok: true, messageId: id };\n } catch (err) {\n return mapPlivoError(err);\n }\n }\n}\n\nfunction parseFormUrlEncoded(body: string): Record<string, string> {\n const params: Record<string, string> = {};\n for (const pair of body.split(\"&\")) {\n if (pair.length === 0) continue;\n const eqIdx = pair.indexOf(\"=\");\n const k = eqIdx < 0 ? pair : pair.slice(0, eqIdx);\n const v = eqIdx < 0 ? \"\" : pair.slice(eqIdx + 1);\n params[decodeURIComponent(k.replace(/\\+/g, \" \"))] = decodeURIComponent(v.replace(/\\+/g, \" \"));\n }\n return params;\n}\n\ninterface PlivoRestError {\n statusCode?: number;\n status?: number;\n message?: string;\n}\n\nfunction mapPlivoError(err: unknown): SendResult {\n const e = err as PlivoRestError;\n const status = e.statusCode ?? e.status ?? 0;\n if (status === 429)\n return { ok: false, error: { code: \"rate_limit\", message: e.message ?? \"Plivo rate limit\" } };\n if (status === 401 || status === 403) {\n return {\n ok: false,\n error: { code: \"permission_denied\", message: e.message ?? \"Plivo auth error\" },\n };\n }\n if (status === 400) {\n return {\n ok: false,\n error: { code: \"invalid_request\", message: e.message ?? \"Plivo rejected request\" },\n };\n }\n return {\n ok: false,\n error: {\n code: \"send_failed\",\n message: e.message ?? (err instanceof Error ? err.message : String(err)),\n },\n };\n}\n","/**\n * Twilio backend impl.\n *\n * - SDK: `twilio` (peer-dep, optional). Loaded lazily so packages\n * that pick other backends don't pay the cost.\n * - Signature: `X-Twilio-Signature` is HMAC-SHA1 of `(fullUrl + sortedParams)`.\n * We delegate to `twilio.validateRequest` so we don't reimplement.\n *\n * @internal\n */\n\nimport type { SendResult } from \"@theokit/gateway\";\nimport type { SignatureContext, SMSBackend, SMSInbound } from \"../backend-types.js\";\nimport { BackendNotInstalledError } from \"../errors.js\";\nimport { normalizeE164 } from \"../phone.js\";\nimport type { TwilioOptions } from \"../types.js\";\n\ninterface TwilioCreateArgs {\n from: string;\n to: string;\n body: string;\n}\n\ninterface TwilioMessageInstance {\n sid: string;\n status?: string;\n}\n\ninterface TwilioClientInstance {\n messages: {\n create(args: TwilioCreateArgs): Promise<TwilioMessageInstance>;\n };\n}\n\ninterface TwilioFactory {\n (accountSid: string, authToken: string): TwilioClientInstance;\n validateRequest(\n authToken: string,\n signature: string,\n url: string,\n params: Record<string, string>,\n ): boolean;\n}\n\nasync function loadTwilio(): Promise<TwilioFactory> {\n try {\n const mod = await import(\"twilio\");\n // ESM ships { default: factory }; CJS ships factory.\n const candidate =\n (mod as { default?: TwilioFactory }).default ?? (mod as unknown as TwilioFactory);\n return candidate;\n } catch {\n throw new BackendNotInstalledError(\"twilio\", \"twilio\");\n }\n}\n\nexport class TwilioBackend implements SMSBackend {\n readonly kind = \"twilio\" as const;\n private client: TwilioClientInstance | undefined;\n private twilio: TwilioFactory | undefined;\n\n constructor(private readonly opts: TwilioOptions) {}\n\n async connect(): Promise<boolean> {\n if (this.client !== undefined) return true;\n this.twilio = await loadTwilio();\n this.client = this.twilio(this.opts.accountSid, this.opts.authToken);\n return true;\n }\n\n async disconnect(): Promise<void> {\n // No persistent connection — REST client is GC'd on dereference.\n this.client = undefined;\n }\n\n verifySignature(ctx: SignatureContext): boolean {\n if (this.twilio === undefined) return false;\n const signature = ctx.headers[\"x-twilio-signature\"];\n if (signature === undefined) return false;\n const params = parseFormUrlEncoded(ctx.rawBody);\n try {\n return this.twilio.validateRequest(this.opts.authToken, signature, ctx.url, params);\n } catch {\n return false;\n }\n }\n\n parseInbound(ctx: SignatureContext): SMSInbound {\n const params = parseFormUrlEncoded(ctx.rawBody);\n return {\n from: normalizeE164(params.From ?? \"\", this.opts.defaultCountry),\n to: normalizeE164(params.To ?? \"\", this.opts.defaultCountry),\n body: params.Body ?? \"\",\n messageId: params.MessageSid ?? params.SmsMessageSid ?? \"\",\n receivedAt: Date.now(),\n raw: params,\n };\n }\n\n async sendMessage(to: string, body: string): Promise<SendResult> {\n if (this.client === undefined) {\n return {\n ok: false,\n error: { code: \"not_connected\", message: \"TwilioBackend.connect() not called\" },\n };\n }\n try {\n const msg = await this.client.messages.create({ from: this.opts.fromNumber, to, body });\n return { ok: true, messageId: msg.sid };\n } catch (err) {\n return mapTwilioError(err);\n }\n }\n}\n\n/**\n * Parse `application/x-www-form-urlencoded` request body to a flat\n * `Record<string, string>`. Twilio POSTs in this format.\n *\n * @internal\n */\nfunction parseFormUrlEncoded(body: string): Record<string, string> {\n const params: Record<string, string> = {};\n for (const pair of body.split(\"&\")) {\n if (pair.length === 0) continue;\n const eqIdx = pair.indexOf(\"=\");\n const k = eqIdx < 0 ? pair : pair.slice(0, eqIdx);\n const v = eqIdx < 0 ? \"\" : pair.slice(eqIdx + 1);\n params[decodeURIComponent(k.replace(/\\+/g, \" \"))] = decodeURIComponent(v.replace(/\\+/g, \" \"));\n }\n return params;\n}\n\ninterface TwilioRestError {\n status?: number;\n code?: number | string;\n message?: string;\n}\n\nfunction mapTwilioError(err: unknown): SendResult {\n const e = err as TwilioRestError;\n const status = e.status ?? 0;\n if (status === 429) {\n return { ok: false, error: { code: \"rate_limit\", message: e.message ?? \"Twilio rate limit\" } };\n }\n if (status === 401 || status === 403) {\n return {\n ok: false,\n error: { code: \"permission_denied\", message: e.message ?? \"Twilio auth error\" },\n };\n }\n if (status === 400) {\n return {\n ok: false,\n error: { code: \"invalid_request\", message: e.message ?? \"Twilio rejected request\" },\n };\n }\n return {\n ok: false,\n error: {\n code: \"send_failed\",\n message: e.message ?? (err instanceof Error ? err.message : String(err)),\n },\n };\n}\n","/**\n * Vonage backend impl.\n *\n * - SDK: `@vonage/server-sdk` (peer-dep, optional).\n * - Signature: `Authorization: Bearer <JWT>` signed with the Signature\n * Secret (NOT the API secret). The SDK exposes `Auth.verifySignature`\n * for this purpose.\n *\n * @internal\n */\n\nimport type { SendResult } from \"@theokit/gateway\";\nimport type { SignatureContext, SMSBackend, SMSInbound } from \"../backend-types.js\";\nimport { BackendNotInstalledError } from \"../errors.js\";\nimport { normalizeE164 } from \"../phone.js\";\nimport type { VonageOptions } from \"../types.js\";\n\ninterface VonageSmsClient {\n send(args: { to: string; from: string; text: string }): Promise<{\n messages?: Array<{ \"message-id\"?: string; messageId?: string; status?: string }>;\n }>;\n}\n\ninterface VonageInstance {\n sms: VonageSmsClient;\n}\n\ninterface VonageModule {\n Vonage: new (creds: {\n apiKey: string;\n apiSecret: string;\n signatureSecret?: string;\n }) => VonageInstance;\n Auth?: {\n verifySignature?: (token: string, secret: string) => boolean;\n };\n}\n\nasync function loadVonage(): Promise<VonageModule> {\n try {\n // SDK ships ESM/CJS variants; we narrow at call sites and pass through.\n const raw = await import(\"@vonage/server-sdk\");\n return raw as unknown as VonageModule;\n } catch {\n throw new BackendNotInstalledError(\"vonage\", \"@vonage/server-sdk\");\n }\n}\n\nexport class VonageBackend implements SMSBackend {\n readonly kind = \"vonage\" as const;\n private mod: VonageModule | undefined;\n private vonage: VonageInstance | undefined;\n\n constructor(private readonly opts: VonageOptions) {}\n\n async connect(): Promise<boolean> {\n if (this.vonage !== undefined) return true;\n this.mod = await loadVonage();\n this.vonage = new this.mod.Vonage({\n apiKey: this.opts.apiKey,\n apiSecret: this.opts.apiSecret,\n signatureSecret: this.opts.signatureSecret,\n });\n return true;\n }\n\n async disconnect(): Promise<void> {\n this.vonage = undefined;\n }\n\n verifySignature(ctx: SignatureContext): boolean {\n const auth = ctx.headers.authorization;\n if (auth === undefined) return false;\n const m = auth.match(/^Bearer\\s+(.+)$/i);\n if (m === null) return false;\n const token = m[1] ?? \"\";\n if (token.length === 0) return false;\n if (this.mod?.Auth?.verifySignature === undefined) return false;\n try {\n return this.mod.Auth.verifySignature(token, this.opts.signatureSecret);\n } catch {\n return false;\n }\n }\n\n parseInbound(ctx: SignatureContext): SMSInbound {\n let payload: Record<string, string> = {};\n try {\n payload = JSON.parse(ctx.rawBody) as Record<string, string>;\n } catch {\n payload = {};\n }\n return {\n from: normalizeE164(payload.msisdn ?? payload.from ?? \"\", this.opts.defaultCountry),\n to: normalizeE164(payload.to ?? \"\", this.opts.defaultCountry),\n body: payload.text ?? \"\",\n messageId: payload.messageId ?? payload[\"message-id\"] ?? \"\",\n receivedAt: Date.now(),\n raw: payload,\n };\n }\n\n async sendMessage(to: string, body: string): Promise<SendResult> {\n if (this.vonage === undefined) {\n return {\n ok: false,\n error: { code: \"not_connected\", message: \"VonageBackend.connect() not called\" },\n };\n }\n try {\n const resp = await this.vonage.sms.send({ from: this.opts.fromNumber, to, text: body });\n const msg = resp.messages?.[0];\n const id = msg?.[\"message-id\"] ?? msg?.messageId ?? \"\";\n if (msg?.status !== undefined && msg.status !== \"0\") {\n return {\n ok: false,\n error: { code: \"send_failed\", message: `Vonage returned status=${msg.status}` },\n };\n }\n return { ok: true, messageId: id };\n } catch (err) {\n return mapVonageError(err);\n }\n }\n}\n\ninterface VonageRestError {\n status?: number;\n response?: { status?: number };\n message?: string;\n}\n\nfunction mapVonageError(err: unknown): SendResult {\n const e = err as VonageRestError;\n const status = e.status ?? e.response?.status ?? 0;\n if (status === 429)\n return { ok: false, error: { code: \"rate_limit\", message: e.message ?? \"Vonage rate limit\" } };\n if (status === 401 || status === 403) {\n return {\n ok: false,\n error: { code: \"permission_denied\", message: e.message ?? \"Vonage auth error\" },\n };\n }\n return {\n ok: false,\n error: {\n code: \"send_failed\",\n message: e.message ?? (err instanceof Error ? err.message : String(err)),\n },\n };\n}\n","/**\n * Backend factory — picks the right impl from `opts.backend`.\n *\n * @internal\n */\n\nimport type { SMSBackend } from \"../backend-types.js\";\nimport type { SMSAdapterOptions } from \"../types.js\";\nimport { PlivoBackend } from \"./plivo.js\";\nimport { TwilioBackend } from \"./twilio.js\";\nimport { VonageBackend } from \"./vonage.js\";\n\nexport function createBackend(opts: SMSAdapterOptions): SMSBackend {\n switch (opts.backend) {\n case \"twilio\":\n return new TwilioBackend(opts);\n case \"plivo\":\n return new PlivoBackend(opts);\n case \"vonage\":\n return new VonageBackend(opts);\n default: {\n const _exhaustive: never = opts;\n throw new Error(`unknown backend: ${JSON.stringify(_exhaustive)}`);\n }\n }\n}\n","/**\n * Inbound normalization: `SMSInbound` → `SMSMessageEvent`.\n *\n * `from` and `to` are already E.164 (backend.parseInbound enforces this).\n * `channel.id` is `from` because SMS conversations are flat per-pair\n * (D394 — no threading).\n *\n * @internal\n */\n\nimport type { SMSMessageEvent } from \"@theokit/gateway\";\n\nimport type { SMSInbound } from \"./backend-types.js\";\n\nexport function inboundToMessageEvent(\n inbound: SMSInbound,\n backend: \"twilio\" | \"plivo\" | \"vonage\",\n): SMSMessageEvent {\n return {\n id: inbound.messageId,\n platform: \"sms\",\n sender: { id: inbound.from },\n channel: { id: inbound.from, type: \"dm\" },\n text: inbound.body,\n receivedAt: inbound.receivedAt,\n sms: {\n backend,\n messageId: inbound.messageId,\n from: inbound.from,\n to: inbound.to,\n raw: inbound.raw,\n },\n };\n}\n","/**\n * The refusal this adapter answers for an outbound that carries attachments (B-674).\n *\n * This adapter sends text only, so an outbound carrying attachments is refused rather than sent without its images.\n *\n * The check runs before any other, so a refusal makes no platform call. It lives in this package\n * rather than in `@theokit/gateway` so that the adapter calls nothing its declared core floor\n * lacks; only the `OutboundMessage` type is imported.\n */\n\nimport type { OutboundMessage, SendResult } from \"@theokit/gateway\";\n\n/**\n * `attachments_unsupported` when `out` carries attachments, otherwise `undefined`.\n *\n * Absent, `null` and an empty list carry nothing. `!== 0`, not `> 0`: any other non-array value\n * from a JavaScript caller has no numeric length and is refused rather than taken for an empty\n * list (EC-1).\n */\nexport function refuseAttachments(out: OutboundMessage): SendResult | undefined {\n if (out.attachments == null || out.attachments.length === 0) return undefined;\n return {\n ok: false,\n error: { code: \"attachments_unsupported\", message: \"sms adapter cannot send attachments\" },\n };\n}\n","/**\n * `splitForSMS` — grapheme-cluster-safe multipart segmentation (D393, EC-7), keeping table rows\n * whole.\n *\n * Concatenated SMS (UDH) on modern carriers reassemble at the recipient,\n * but each TCP/IP-layer chunk is one billed message. We segment at\n * 1600 chars (default) so the API call doesn't reject and each part is\n * prefixed with `(i/N) ` to allow manual reordering when carriers\n * deliver out of sequence (EC-7).\n *\n * A text within the limit goes through core `chunkByGrapheme` as before. A longer one is cut at\n * the last grapheme boundary within each part, which is where `chunkByGrapheme`'s greedy walk\n * ends a part, so emoji (🇧🇷) and combining sequences are never severed and text with no table\n * row splits exactly as it did (pinned by `tests/split-no-table-baseline.test.ts` and the\n * equivalence test in `tests/split-tables.test.ts`). A cut that falls inside a Markdown table row\n * which fits in a part moves back to the start of that row (B-556). The rule is core\n * `splitKeepingRows`, shared with gateway-line. The `(i/N) ` prefix (and its reserved width) stays here since it is SMS-specific.\n *\n * @internal\n */\n\nimport { chunkByGrapheme, splitKeepingRows } from \"@theokit/gateway\";\n\n/**\n * Width of `\"(i/total) \"` when `i` has as many digits as `total` — the widest\n * the prefix can get for a given part count. `(99/99) ` is 8, `(100/126) ` is\n * 10, `(1000/1234) ` is 12.\n *\n * This used to be the constant 8, commented `\"(99/99) \" worst case`. It is the\n * worst case only below 100 parts; from the hundredth part on, every prefix\n * overflowed its reservation and each part exceeded the caller's declared cap\n * by 2 chars, which the provider rejects.\n */\nfunction prefixWidthFor(total: number): number {\n return 2 * String(total).length + 4;\n}\n\n/** One fixed-point pass: the parts of `text` with `partLimit` left beside the prefix. */\nfunction partsFor(text: string, limit: number, partLimit: number): string[] {\n if (text.length <= limit) return chunkByGrapheme(text, { limit, partLimit });\n // The core's RangeError for a limit of 0, 1.5 or NaN, with the message it had before.\n chunkByGrapheme(\"\", { limit, partLimit });\n return splitKeepingRows(text, partLimit);\n}\n\nexport function splitForSMS(text: string, limit = 1600): string[] {\n // Chicken and egg: the reservation depends on the part count, and the part\n // count depends on the reservation. Widening the prefix shrinks the payload,\n // which can push the count into another digit — so iterate to a fixed point.\n // It converges fast because the width grows with the LOGARITHM of the count;\n // the bound is a backstop against a pathological input, not the expected path.\n let reserved = prefixWidthFor(1);\n for (let pass = 0; pass < 8; pass += 1) {\n const partLimit = limit - reserved;\n if (partLimit <= 0) {\n throw new RangeError(\n `limit ${limit} is too small to carry an SMS part: the \"(i/N) \" prefix alone needs ${reserved} chars`,\n );\n }\n const parts = partsFor(text, limit, partLimit);\n if (parts.length <= 1) return parts; // short-circuit / single part: skip prefix\n const needed = prefixWidthFor(parts.length);\n if (needed <= reserved) {\n const total = parts.length;\n return parts.map((p, i) => `(${i + 1}/${total}) ${p}`);\n }\n reserved = needed;\n }\n /* c8 ignore next 3 -- unreachable: 8 passes cover part counts up to 10^8. */\n throw new RangeError(\n `could not settle the \"(i/N) \" prefix width for a ${text.length}-char message at limit ${limit}`,\n );\n}\n","/**\n * `SMSAdapter` — implements `BasePlatformAdapter` over a backend\n * (twilio / plivo / vonage). ADRs D389-D396.\n *\n * Lifecycle:\n * - `connect()` initializes the chosen backend (lazy peer-dep import).\n * - `disconnect()` releases the backend; idempotent.\n * - `sendMessage()` splits multipart (D393) and sends each part via backend.\n * - `onInbound(handler)` replaces previous handler (EC-H, mirror D276).\n *\n * Inbound dispatch is driven by the webhook server (`webhook-server.ts`)\n * which calls `adapter.dispatchInbound(ctx)` after signature verification.\n *\n * @public\n */\n\nimport {\n BasePlatformAdapter,\n type MessageEvent as GatewayMessageEvent,\n type OutboundMessage,\n type SendResult,\n} from \"@theokit/gateway\";\nimport { createBackend } from \"./backend/index.js\";\nimport type { SignatureContext, SMSBackend } from \"./backend-types.js\";\nimport { ConfigurationError } from \"./errors.js\";\nimport { inboundToMessageEvent } from \"./normalize.js\";\nimport { normalizeE164 } from \"./phone.js\";\nimport { refuseAttachments } from \"./refuse-attachments.js\";\nimport { splitForSMS } from \"./split.js\";\nimport type { SMSAdapterOptions } from \"./types.js\";\n\nexport class SMSAdapter extends BasePlatformAdapter {\n /**\n * Whether the \"this medium carries no formatting\" warning has already been emitted.\n *\n * Once per adapter, not once per message: a gateway answering a busy channel would turn a\n * useful diagnostic into a log flood, and a flooded log is one nobody reads — the same\n * reason the group-mention and allowlist drops elsewhere in this family log once.\n */\n private warnedAboutFormat = false;\n\n /**\n * Say, once, that a declared format is being dropped.\n *\n * `OutboundMessage.format` is the caller stating intent, and this medium has nowhere to put\n * it: no flag, no markup, no alternative part. Discarding it in silence is the swallowed-\n * error shape `rules/error-handling.md` refuses — nothing fails, and the caller learns their\n * formatting never arrived from a user, weeks later.\n *\n * @internal\n */\n private warnFormatUnsupported(format: string | undefined): void {\n // The \"is there anything to say\" question lives here rather than at the call site: a\n // `sendMessage` already at its complexity limit should ask one thing, not three.\n if (format === undefined || format === \"plain\") return;\n if (this.warnedAboutFormat) return;\n this.warnedAboutFormat = true;\n process.stderr.write(\n `[gateway-sms] format=\"${format}\" was declared, and SMS cannot carry it — ` +\n \"the medium is plain text. Sending unformatted; this is logged once.\\n\",\n );\n }\n\n readonly platform = \"sms\" as const;\n\n /**\n * The URL the provider POSTs inbound to, as the provider sees it.\n *\n * Required by all three backend option shapes and documented there as \"used by signature\n * verifier\" — and, measured 2026-08-31, read by nothing: it appeared only in the type and in test\n * fixtures. Twilio SIGNS this URL, so the value matters most in exactly the case where the\n * request cannot supply it: behind a proxy or a tunnel, the request's own URL is the internal one\n * and will not match what was signed.\n *\n * Exposed so {@link smsWebhookVerifier} can use it, which is what makes the option true.\n */\n readonly publicUrl: string;\n\n private readonly backend: SMSBackend;\n private inboundHandler: ((event: GatewayMessageEvent) => Promise<void>) | undefined;\n private connected = false;\n private readonly defaultCountry: string | undefined;\n\n constructor(opts: SMSAdapterOptions) {\n super();\n // EC-1: refuse to operate without signing secret.\n const secret = secretFromOpts(opts);\n if (secret.length === 0) {\n throw new ConfigurationError({\n code: \"signing_secret_required\",\n message: `gateway-sms: backend=\"${opts.backend}\" requires a signing secret (would accept unsigned webhooks)`,\n });\n }\n this.defaultCountry = opts.defaultCountry;\n this.publicUrl = opts.publicUrl;\n this.backend = createBackend(opts);\n }\n\n async connect(): Promise<boolean> {\n if (this.connected) return true;\n const ok = await this.backend.connect();\n this.connected = ok;\n return ok;\n }\n\n async disconnect(): Promise<void> {\n if (!this.connected) return;\n await this.backend.disconnect();\n this.connected = false;\n this.inboundHandler = undefined;\n }\n\n async sendMessage(out: OutboundMessage): Promise<SendResult> {\n return refuseAttachments(out) ?? this.sendText(out);\n }\n\n private async sendText(out: OutboundMessage): Promise<SendResult> {\n if (out.text.length === 0) {\n return { ok: false, error: { code: \"empty_text\", message: \"outbound text is empty\" } };\n }\n let toE164: string;\n try {\n toE164 = normalizeE164(out.channel.id, this.defaultCountry);\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err);\n return { ok: false, error: { code: \"invalid_phone_number\", message: msg } };\n }\n const parts = splitForSMS(out.text);\n // Send sequentially so the recipient sees them in order; concurrent\n // submit would still cost the same but breaks ordering at carriers.\n let lastResult: SendResult | undefined;\n // SMS is plain text by definition. Reading the field is not ceremony: it is what turns a\n // silent discard into a stated one.\n this.warnFormatUnsupported(out.format);\n\n for (const part of parts) {\n lastResult = await this.backend.sendMessage(toE164, part);\n if (lastResult.ok !== true) {\n return {\n ok: false,\n error: {\n code: lastResult.error?.code ?? \"partial_send_failure\",\n message: `partial send failed after ${parts.indexOf(part)}/${parts.length}: ${lastResult.error?.message ?? \"unknown\"}`,\n },\n };\n }\n }\n return lastResult ?? { ok: false, error: { code: \"send_failed\", message: \"no parts sent\" } };\n }\n\n onInbound(handler: (event: GatewayMessageEvent) => Promise<void>): () => void {\n // EC-H: replace, not stack.\n this.inboundHandler = handler;\n return () => {\n if (this.inboundHandler === handler) this.inboundHandler = undefined;\n };\n }\n\n /**\n * Webhook hook — called by `createWebhookServer` AFTER signature\n * verification + parseInbound. Returns dispatch outcome (used for\n * 200/204 vs 500 by the webhook handler).\n *\n * @internal\n */\n async dispatchInbound(ctx: SignatureContext): Promise<\"ok\" | \"no_handler\" | \"parse_failed\"> {\n if (!this.backend.verifySignature(ctx)) {\n // Caller (webhook-server) inspects this via verifySignature directly,\n // but we re-check defensively if anyone calls dispatch directly.\n return \"parse_failed\";\n }\n let inbound: ReturnType<SMSBackend[\"parseInbound\"]>;\n try {\n inbound = this.backend.parseInbound(ctx);\n } catch {\n return \"parse_failed\";\n }\n if (this.inboundHandler === undefined) return \"no_handler\";\n const event = inboundToMessageEvent(inbound, this.backend.kind);\n try {\n await this.inboundHandler(event);\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err);\n process.stderr.write(`[gateway-sms] handler threw: ${msg}\\n`);\n }\n return \"ok\";\n }\n\n /**\n * Direct signature check — used by the webhook server to respond\n * `401` BEFORE dispatch when signature is invalid.\n *\n * @internal\n */\n verifySignature(ctx: SignatureContext): boolean {\n return this.backend.verifySignature(ctx);\n }\n\n /**\n * Direct parse — used by the webhook server when signature was already\n * validated upstream. Returns the normalized `SMSMessageEvent` to be\n * dispatched.\n *\n * @internal\n */\n buildEventFromCtx(ctx: SignatureContext): GatewayMessageEvent {\n const inbound = this.backend.parseInbound(ctx);\n return inboundToMessageEvent(inbound, this.backend.kind);\n }\n\n /**\n * Dispatch a pre-built event (used by webhook server after manual\n * signature + parse). Honors EC-H replace semantics and isolates\n * handler exceptions per `gateway-runner` contract.\n *\n * @internal\n */\n async dispatchEvent(event: GatewayMessageEvent): Promise<\"ok\" | \"no_handler\"> {\n if (this.inboundHandler === undefined) return \"no_handler\";\n try {\n await this.inboundHandler(event);\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err);\n process.stderr.write(`[gateway-sms] handler threw: ${msg}\\n`);\n }\n return \"ok\";\n }\n\n /** Backend kind (escape hatch for callers needing to introspect). */\n getBackendKind(): \"twilio\" | \"plivo\" | \"vonage\" {\n return this.backend.kind;\n }\n\n /**\n * Deliver an event that arrived out of band — the ingest `onInbound` had no counterpart for (#83).\n *\n * One line over `runHandler`, which owns the containment: a handler is user code, its throw is\n * named as the handler's failure rather than the platform's, and delivery continues.\n */\n override async deliver(\n event: GatewayMessageEvent,\n ): Promise<\"ok\" | \"no_handler\" | \"handler_threw\"> {\n return this.runHandler(this.inboundHandler, event);\n }\n\n /**\n * Deliver like {@link deliver}, but a throwing handler is logged by name only: its message can\n * carry the inbound text, which the webhook route must not write to a log line.\n *\n * @internal\n */\n async deliverQuietly(event: GatewayMessageEvent): Promise<\"ok\" | \"no_handler\" | \"handler_threw\"> {\n const handler = this.inboundHandler;\n if (handler === undefined) return \"no_handler\";\n try {\n await handler(event);\n } catch {\n process.stderr.write(`[sms] handler threw\\n`);\n return \"handler_threw\";\n }\n return \"ok\";\n }\n}\n\nfunction secretFromOpts(opts: SMSAdapterOptions): string {\n switch (opts.backend) {\n case \"twilio\":\n return opts.authToken;\n case \"plivo\":\n return opts.authToken;\n case \"vonage\":\n return opts.signatureSecret;\n default: {\n const _exhaustive: never = opts;\n void _exhaustive;\n return \"\";\n }\n }\n}\n","/**\n * Translating a raw provider webhook into the canonical event.\n *\n * **This does NOT go through TheoKit's `handleChannelWebhook`.** Signature verification here needs\n * the RAW body, the headers and the exact URL — `ChannelMessage` carries none of the three, so the\n * check cannot be performed from inside `onMessage` whatever the provider sends. Twilio adds a\n * second obstacle: it posts `application/x-www-form-urlencoded`, and that seam reads the body with\n * `request.json()` and answers 400 when it is not JSON. (Plivo accepts either encoding and Vonage\n * posts JSON, so only the first reason applies to them.)\n *\n * For an Express app, `createWebhookServer` is the whole path and you never call this — it builds\n * the {@link SignatureContext}, verifies the signature and goes through the adapter. This export is\n * for a route you host yourself: build the context from a request whose body you have not parsed,\n * then call this. It composes two functions that\n * already existed and were both private: each backend's `parseInbound`, which turns a provider's\n * raw body into the provider-agnostic {@link SMSInbound}, and `inboundToMessageEvent`, which turns\n * that into the canonical event. Neither is duplicated here — per ADR D426 the mapping stays in one\n * place, and this is composition, not a second translator.\n *\n * **Why it takes the adapter's options.** Parsing is provider-specific (`Twilio` posts\n * `MessageSid`, Plivo posts `MessageUUID`) and, for Twilio, country-dependent: a number that is not\n * already in E.164 is normalised against `defaultCountry`. Both live in the options an app already\n * holds, because it constructed the adapter with them. `createBackend` only stores them — it opens\n * no connection and loads no SDK, so this stays a pure function over its inputs.\n */\n\nimport type { SMSMessageEvent } from \"@theokit/gateway\";\n\nimport { createBackend } from \"./backend/index.js\";\nimport type { SignatureContext, SMSInbound } from \"./backend-types.js\";\nimport { inboundToMessageEvent } from \"./normalize.js\";\nimport type { SMSAdapterOptions } from \"./types.js\";\n\n/**\n * Translate one raw provider webhook into an {@link SMSMessageEvent}.\n *\n * Returns `null` — never throws — when the body is not one this provider recognises. The caller is\n * whatever holds the {@link SignatureContext}: `createWebhookServer` here, or your own route. It\n * returns `null` rather than throwing because a throw out of a webhook handler becomes a failed\n * request, and the provider then sees a delivery failure for a body that was merely unrecognised\n * (ADR D428, whose original rationale — \"runs after the 200\" — was measured false on 2026-08-24).\n *\n * `null` here means \"this body is not a parseable inbound message\".\n *\n * **One class of configuration error is not distinguishable from a bad body, and is not pretended\n * to be.** `defaultCountry` is read while parsing the body's own numbers, and `normalizeE164`\n * raises the same `ConfigurationError` for a bad configured country as for a bad number in the\n * body. An invalid `defaultCountry` therefore degrades to `null` rather than throwing.\n *\n * An earlier version tried to separate them by validating `options.fromNumber` up front. That was\n * wrong twice: `fromNumber` is passed raw to the provider SDK everywhere else in this package and\n * validated nowhere, and the invented rule rejected four documented, valid configurations — a\n * Vonage alphanumeric sender ID (`\"ACME\"`), a Twilio short code (`\"12345\"`), a Messaging Service\n * SID (`\"MG…\"`), and a national number with `defaultCountry` set. Each one threw out of\n * `onMessage`, turning a message the provider delivered into a failed request — precisely the\n * failure the check was written to prevent.\n * Inventing a validation stricter than the package's own is how that happened.\n *\n * @public\n */\nexport function parseInbound(\n options: SMSAdapterOptions,\n ctx: SignatureContext,\n): SMSMessageEvent | null {\n // `createBackend` is the CONFIGURATION step and sits outside the try on purpose: an unsupported\n // `backend` is a programmer error and must surface, not become the same `null` a malformed body\n // produces.\n const backend = createBackend(options);\n\n let inbound: SMSInbound;\n try {\n inbound = backend.parseInbound(ctx);\n } catch {\n // Everything from here is body-dependent, so any error means the body was unreadable. Caught\n // whatever its type: `decodeURIComponent` raises `URIError` on a malformed percent-escape\n // (`From=%zz`) and `normalizeE164` raises `ConfigurationError` on a number the body carried.\n // Both are bad requests, and returning `null` is what keeps them from failing the request:\n // measured against `theokit@0.48.14`, `handleChannelWebhook` awaits `onMessage` BEFORE\n // building the 200 and catches nothing around it, so a throw here escapes it entirely and\n // the 200 is never built (ADR D428, whose original rationale — \"runs after the 200\" — was\n // measured false on 2026-08-24).\n return null;\n }\n\n // A body the provider posted that carries no message id.\n //\n // Deliberately does NOT also check `inbound.from === \"\"`: all three backends build `from` with\n // `normalizeE164(x ?? \"\")`, which throws on an empty string, so the branch was unreachable and a\n // mutation deleting it survived the suite.\n if (inbound.messageId === \"\") return null;\n\n return inboundToMessageEvent(inbound, options.backend);\n}\n","/**\n * Standalone Twilio request verifier.\n *\n * Twilio signs voice webhooks exactly like SMS webhooks: `X-Twilio-Signature` is the base64\n * HMAC-SHA1 (keyed with the auth token) of the full URL followed by every POST parameter, sorted by\n * name, as `name + value`. No adapter and no `twilio` SDK are needed.\n *\n * @public\n */\n\nimport { createHmac, timingSafeEqual } from \"node:crypto\";\n\nimport type { WebhookVerifyResult } from \"./webhook-verifier.js\";\n\n/** Options for {@link twilioRequestVerifier}. @public */\nexport interface TwilioRequestVerifierOptions {\n /** The Twilio auth token the signature is keyed with. */\n readonly authToken: string;\n /**\n * The URL Twilio POSTs to, as Twilio sees it. Defaults to the request URL, which behind a proxy\n * or tunnel is the internal one and will not match.\n */\n readonly publicUrl?: string;\n}\n\nfunction decode(s: string): string {\n return decodeURIComponent(s.replace(/\\+/g, \" \"));\n}\n\n/** Parse a form body keeping repeated keys: Twilio signs every value of a repeated name. */\nfunction parseForm(body: string): Array<[string, string]> {\n const out: Array<[string, string]> = [];\n for (const pair of body.split(\"&\")) {\n if (pair.length === 0) continue;\n const eq = pair.indexOf(\"=\");\n out.push([decode(eq < 0 ? pair : pair.slice(0, eq)), decode(eq < 0 ? \"\" : pair.slice(eq + 1))]);\n }\n return out;\n}\n\nfunction compare(a: string, b: string): number {\n if (a === b) return 0;\n return a < b ? -1 : 1;\n}\n\nfunction sign(authToken: string, url: string, pairs: Array<[string, string]>): string {\n const sorted = [...pairs].sort((x, y) => compare(x[0], y[0]) || compare(x[1], y[1]));\n let data = url;\n for (const [k, v] of sorted) data += k + v;\n return createHmac(\"sha1\", authToken).update(data, \"utf8\").digest(\"base64\");\n}\n\n/**\n * Whether `signature` is Twilio's signature of `url` plus the form fields in `rawBody`, compared in\n * constant time. Synchronous, needs no adapter and no SDK; `twilioRequestVerifier` is built on it.\n *\n * @internal\n */\nexport function verifyTwilioSignature(\n authToken: string,\n url: string,\n rawBody: string,\n signature: string | undefined,\n): boolean {\n if (signature === undefined || signature.length === 0) return false;\n let pairs: Array<[string, string]>;\n try {\n pairs = parseForm(rawBody);\n } catch {\n return false;\n }\n const expected = Buffer.from(sign(authToken, url, pairs));\n const actual = Buffer.from(signature);\n return expected.length === actual.length && timingSafeEqual(expected, actual);\n}\n\n/**\n * Build a verifier for Twilio webhooks (SMS or voice).\n *\n * The request body is READ; pass a clone if it is needed afterwards.\n *\n * @public\n */\nexport function twilioRequestVerifier(\n opts: TwilioRequestVerifierOptions,\n): (request: Request) => Promise<WebhookVerifyResult> {\n return async (request: Request): Promise<WebhookVerifyResult> => {\n const header = request.headers.get(\"x-twilio-signature\");\n if (header === null || header.length === 0) {\n return { ok: false, reason: \"missing X-Twilio-Signature header\" };\n }\n const ok = verifyTwilioSignature(\n opts.authToken,\n opts.publicUrl ?? request.url,\n await request.text(),\n header,\n );\n if (!ok) return { ok: false, reason: \"signature mismatch\" };\n return { ok: true };\n };\n}\n","/**\n * The SMS (Twilio) half of the descriptor's webhook, answered through `ChannelWebhook.handle` so a\n * host mounts it with `createWebhookHandler`.\n *\n * Twilio signs the public URL plus the form fields, so verification always uses the configured\n * `publicUrl`, never the request's own URL or Host header. The adapter's options are recorded here\n * by the descriptor's `create`, keyed by the adapter, so no secret sits on a public field. An\n * adapter the descriptor did not build has none and every request to it is refused.\n *\n * No secret, signature or body text is logged or answered.\n */\n\nimport type { SMSAdapter } from \"./adapter.js\";\nimport { parseInbound } from \"./parse-inbound.js\";\nimport { verifyTwilioSignature } from \"./twilio-verifier.js\";\nimport type { SMSAdapterOptions } from \"./types.js\";\n\ntype TwilioOptions = Extract<SMSAdapterOptions, { backend: \"twilio\" }>;\n\nconst options = new WeakMap<object, TwilioOptions>();\n\n/** Record the options of an adapter the descriptor built. */\nexport function rememberSmsOptions(adapter: object, opts: TwilioOptions): void {\n options.set(adapter, opts);\n}\n\nexport interface WebhookRequestShape {\n readonly rawBody: string;\n readonly headers: Readonly<Record<string, string | undefined>>;\n readonly method?: string;\n readonly url?: string;\n}\n\nexport interface WebhookAnswerShape {\n readonly status: number;\n}\n\ntype Outcome = \"ok\" | \"no_handler\" | \"handler_threw\";\n\n/** Same mapping as the core's `statusForDeliver`, kept local so the older peer floor still loads. */\nfunction statusFor(outcomes: ReadonlyArray<Outcome>): 200 | 500 | 503 {\n let status: 200 | 500 | 503 = 200;\n for (const outcome of outcomes) {\n if (outcome === \"handler_threw\") status = 500;\n else if (outcome === \"no_handler\" && status === 200) status = 503;\n }\n return status;\n}\n\nfunction lowerHeaders(\n headers: Readonly<Record<string, string | undefined>>,\n): Record<string, string> {\n const out: Record<string, string> = {};\n for (const [key, value] of Object.entries(headers)) {\n if (value !== undefined) out[key.toLowerCase()] = value;\n }\n return out;\n}\n\n/** The one check `verify` and `handle` share: Twilio's signature over the configured public URL. */\nfunction verified(opts: TwilioOptions | undefined, request: WebhookRequestShape): boolean {\n if (opts === undefined || opts.authToken.trim().length === 0) return false;\n return verifyTwilioSignature(\n opts.authToken,\n opts.publicUrl,\n request.rawBody,\n lowerHeaders(request.headers)[\"x-twilio-signature\"],\n );\n}\n\nfunction toEvent(opts: TwilioOptions, rawBody: string, headers: Record<string, string>) {\n return parseInbound(opts, { headers, rawBody, url: opts.publicUrl });\n}\n\n/** The webhook half of the Twilio descriptor. */\nexport const twilioWebhook = {\n methods: [\"POST\"] as const,\n /** The same check `handle` makes; needs no connection. */\n verify(adapter: SMSAdapter, request: WebhookRequestShape): boolean {\n return verified(options.get(adapter), request);\n },\n /** A payload of form fields (as an object) is parsed like the form body and delivered. */\n async ingest(\n adapter: SMSAdapter,\n payload: unknown,\n ): Promise<\"delivered\" | \"malformed\" | \"no_handler\"> {\n const opts = options.get(adapter);\n if (opts === undefined || payload === null || typeof payload !== \"object\") return \"malformed\";\n const form = new URLSearchParams();\n for (const [key, value] of Object.entries(payload)) {\n if (typeof value === \"string\") form.set(key, value);\n }\n const event = toEvent(opts, form.toString(), {});\n if (event === null) return \"malformed\";\n return statusFor([await adapter.deliverQuietly(event)]) === 200 ? \"delivered\" : \"no_handler\";\n },\n async handle(adapter: SMSAdapter, request: WebhookRequestShape): Promise<WebhookAnswerShape> {\n const opts = options.get(adapter);\n if (opts === undefined || !verified(opts, request)) return { status: 401 };\n const event = toEvent(opts, request.rawBody, lowerHeaders(request.headers));\n if (event === null) return { status: 400 };\n return { status: statusFor([await adapter.deliverQuietly(event)]) };\n },\n};\n","/**\n * `smsChannel` — the SMS channel (Twilio backend only) described as data.\n *\n * Typed locally on purpose: the object is structurally a `ChannelDescriptor`, but a published\n * `.d.ts` naming a core type must not break a consumer on an older peer floor.\n */\n\nimport { SMSAdapter } from \"./adapter.js\";\nimport { ConfigurationError } from \"./errors.js\";\nimport { rememberSmsOptions, twilioWebhook } from \"./fetch-webhook.js\";\n\nconst KEYS = [\"accountSid\", \"authToken\", \"fromNumber\", \"publicUrl\"] as const;\n\nfunction readString(config: Readonly<Record<string, unknown>>, key: string): string {\n const value = config[key];\n if (typeof value !== \"string\" || value.trim().length === 0) {\n throw new ConfigurationError({\n code: \"invalid_config\",\n message: `gateway-sms: config.${key} must be a non-empty string`,\n detail: key,\n });\n }\n return value;\n}\n\n/** One configuration field, shaped like the core's `ChannelConfigField` (typed locally). */\ninterface ConfigField {\n readonly key: string;\n readonly required: boolean;\n readonly secret: boolean;\n readonly env: string;\n readonly description: string;\n}\n\nconst CONFIG: ReadonlyArray<ConfigField> = [\n {\n key: \"accountSid\",\n required: true,\n secret: false,\n env: \"SMS_ACCOUNT_SID\",\n description: \"The Twilio account SID.\",\n },\n {\n key: \"authToken\",\n required: true,\n secret: true,\n env: \"SMS_AUTH_TOKEN\",\n description: \"The Twilio auth token; also verifies inbound signatures.\",\n },\n {\n key: \"fromNumber\",\n required: true,\n secret: false,\n env: \"SMS_FROM_NUMBER\",\n description: \"The bot's own E.164 number, used as the sender.\",\n },\n {\n key: \"publicUrl\",\n required: true,\n secret: false,\n env: \"SMS_PUBLIC_URL\",\n description: \"The public URL Twilio posts inbound messages to.\",\n },\n];\n\n/**\n * The SMS channel on the Twilio backend. Inbound messages arrive by webhook: mount\n * `createWebhookHandler` (see the README); `webhook.handle` verifies against the configured\n * `publicUrl`.\n *\n * `create` validates each value with this package's `ConfigurationError` and makes no network call.\n *\n * @public\n */\nexport const smsChannel = {\n platform: \"sms\" as const,\n transport: \"webhook\" as const,\n webhook: twilioWebhook,\n config: CONFIG,\n create(config: Readonly<Record<string, unknown>>): SMSAdapter {\n const [accountSid, authToken, fromNumber, publicUrl] = KEYS.map((k) => readString(config, k));\n const opts = {\n backend: \"twilio\" as const,\n accountSid: accountSid as string,\n authToken: authToken as string,\n fromNumber: fromNumber as string,\n publicUrl: publicUrl as string,\n };\n const adapter = new SMSAdapter(opts);\n rememberSmsOptions(adapter, opts);\n return adapter;\n },\n};\n","/**\n * Minimal TwiML builders. Every text node and attribute value is XML-escaped.\n *\n * @public\n */\n\n// biome-ignore lint/suspicious/noControlCharactersInRegex: stripping XML-illegal controls on purpose\nconst ILLEGAL = /[\\u0000-\\u0008\\u000B\\u000C\\u000E-\\u001F]/g;\n\nfunction esc(s: string): string {\n return s\n .replace(ILLEGAL, \"\")\n .replace(/&/g, \"&\")\n .replace(/</g, \"<\")\n .replace(/>/g, \">\")\n .replace(/\"/g, \""\")\n .replace(/'/g, \"'\");\n}\n\nfunction attrs(a: Record<string, string | number | undefined>): string {\n let out = \"\";\n for (const [k, v] of Object.entries(a)) {\n if (v !== undefined) out += ` ${k}=\"${esc(String(v))}\"`;\n }\n return out;\n}\n\n/**\n * TwiML verb builders for Twilio voice webhooks. Each returns an XML string; combine them with\n * `twiml.response`.\n *\n * @public\n */\nexport const twiml = {\n say(text: string, opts: { voice?: string; language?: string } = {}): string {\n return `<Say${attrs({ voice: opts.voice, language: opts.language })}>${esc(text)}</Say>`;\n },\n gather(opts: {\n action: string;\n input?: \"speech\" | \"dtmf\";\n timeoutSeconds?: number;\n prompt?: string;\n }): string {\n const a = attrs({ action: opts.action, input: opts.input, timeout: opts.timeoutSeconds });\n return opts.prompt === undefined\n ? `<Gather${a}/>`\n : `<Gather${a}>${twiml.say(opts.prompt)}</Gather>`;\n },\n redirect(url: string): string {\n return `<Redirect>${esc(url)}</Redirect>`;\n },\n hangup(): string {\n return \"<Hangup/>\";\n },\n /** Wrap verbs in `<Response>`. Verbs must come from the builders above. */\n response(...verbs: string[]): string {\n return `<?xml version=\"1.0\" encoding=\"UTF-8\"?><Response>${verbs.join(\"\")}</Response>`;\n },\n};\n","/**\n * `createWebhookServer` — Express helper for inbound SMS webhooks.\n *\n * Registers per-backend routes (`/sms/twilio`, `/sms/plivo`, `/sms/vonage`)\n * each with the matching parser middleware. All three:\n *\n * 1. Read the raw body verbatim (signature verification depends on the\n * exact bytes — even one extra `\\r\\n` invalidates the HMAC).\n * 2. Call `adapter.verifySignature(ctx)` → 401 if false.\n * 3. Call `adapter.buildEventFromCtx(ctx)` → `dispatchEvent(event)`.\n * 4. Return 204 No Content.\n *\n * Caller can pass an existing Express app (`opts.app`) or let the helper\n * create one. `start()` / `stop()` are idempotent.\n *\n * @public\n */\n\nimport {\n DEFAULT_WEBHOOK_MAX_BYTES,\n listenerLifecycle,\n loadPeer,\n rawBodyCapture,\n} from \"@theokit/gateway\";\nimport type { Express, Request, Response } from \"express\";\nimport type { SMSAdapter } from \"./adapter.js\";\nimport type { SignatureContext } from \"./backend-types.js\";\n\nimport { ConfigurationError } from \"./errors.js\";\n\nexport interface WebhookServerOptions {\n readonly adapter: SMSAdapter;\n /** Mount path prefix; default `\"/sms\"`. The full path is `${path}/${backend}`. */\n readonly path?: string;\n /** Listen port. Ignored when `app` is provided. Default `3000`. */\n readonly port?: number;\n /** Inject an existing Express app instead of creating one. */\n readonly app?: Express;\n}\n\n/** A started HTTP listener, with the handle needed to shut it down again. */\nexport interface WebhookServer {\n start(): Promise<void>;\n stop(): Promise<void>;\n}\n\nasync function loadExpress(): Promise<() => Express> {\n return loadPeer<() => Express>(\n async () => import(\"express\"),\n () => {\n throw new ConfigurationError({\n code: \"express_not_installed\",\n message: 'gateway-sms: peer-dep \"express\" not installed. Run: pnpm add express',\n });\n },\n );\n}\n\n/**\n * The URL the provider signed.\n *\n * `publicUrl` wins when it is configured, because it is the only value that survives a proxy. The\n * provider verifies against the address IT posted to, and behind a tunnel, an ingress, or a load\n * balancer terminating TLS the reconstruction below yields the internal one — so a correct\n * signature fails, on every delivery, with nothing in the log naming the cause.\n *\n * The header reconstruction stays as the fallback: an app served directly has nothing to configure\n * and the headers are the truth. Measured 2026-08-31 — `publicUrl` is required by all three backend\n * option shapes and documented as \"used by signature verifier\", and until this commit no source\n * file read it.\n */\nfunction signedUrl(\n req: Request,\n headers: Readonly<Record<string, string>>,\n publicUrl?: string,\n): string {\n if (publicUrl !== undefined && publicUrl !== \"\") return publicUrl;\n const protoHeader = headers[\"x-forwarded-proto\"];\n const proto = protoHeader ?? (req.secure ? \"https\" : \"http\");\n const host = req.get(\"host\") ?? \"localhost\";\n return `${proto}://${host}${req.originalUrl}`;\n}\n\nfunction buildSignatureContext(req: Request, publicUrl?: string): SignatureContext {\n const rawBody = (req as Request & { rawBody?: string }).rawBody ?? \"\";\n const headers: Record<string, string> = {};\n for (const [k, v] of Object.entries(req.headers)) {\n headers[k.toLowerCase()] = Array.isArray(v) ? v.join(\",\") : (v ?? \"\");\n }\n return { headers, rawBody, url: signedUrl(req, headers, publicUrl) };\n}\n\n/**\n * Build the HTTP listener that receives the provider's inbound-SMS callbacks.\n *\n * The provider dials in, so this endpoint must be reachable over public HTTPS and registered in the\n * provider console — inbound cannot work behind a firewall. `express` is loaded lazily, so a project\n * that only sends messages never pays for it.\n */\nexport async function createWebhookServer(opts: WebhookServerOptions): Promise<WebhookServer> {\n const createApp = await loadExpress();\n const app: Express = opts.app ?? createApp();\n const prefix = opts.path ?? \"/sms\";\n const backend = opts.adapter.getBackendKind();\n\n const handler = (req: Request, res: Response): void => {\n const ctx = buildSignatureContext(req, opts.adapter.publicUrl);\n if (!opts.adapter.verifySignature(ctx)) {\n res.status(401).type(\"text/plain\").send(\"invalid signature\");\n return;\n }\n let event: ReturnType<typeof opts.adapter.buildEventFromCtx>;\n try {\n event = opts.adapter.buildEventFromCtx(ctx);\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err);\n res.status(400).type(\"text/plain\").send(`parse failed: ${msg}`);\n return;\n }\n // Same contract as the LINE server: the provider is answered before the handler runs, so a\n // slow handler cannot become a provider retry. That makes the dispatch floated, and a floated\n // rejection ends the process — so it is caught here rather than left to the runtime (#41).\n void opts.adapter.dispatchEvent(event).catch((err: unknown) => {\n const message = err instanceof Error ? err.message : String(err);\n process.stderr.write(`[gateway-sms] webhook dispatch failed: ${message}\\n`);\n });\n // Twilio expects either TwiML or 204; 204 keeps things simple\n // and avoids accidentally double-replying.\n res.status(204).end();\n };\n\n app.post(\n `${prefix}/${backend}`,\n rawBodyCapture(\"gateway-sms\", { maxBytes: DEFAULT_WEBHOOK_MAX_BYTES }),\n handler,\n );\n\n // The lifecycle lives in `@theokit/gateway`, written once. It was duplicated here and in\n // gateway-line, and the same write-once latch bug had to be fixed in both files by one commit —\n // which is what turned the duplication from a style question into a defect (#89).\n return listenerLifecycle({ app, port: opts.port ?? 3000, injected: opts.app !== undefined });\n}\n","/**\n * The SMS half of a channel webhook, in the shape a framework webhook seam expects.\n *\n * `theokit/server/webhook` ships validators for the platforms whose signature is a plain HMAC it\n * can compute itself. SMS is not one of them: Twilio signs the URL plus the sorted POST parameters,\n * Plivo signs a different string again, and Vonage uses a JWT. Those three schemes already exist in\n * this package, correctly, with their own tests — reimplementing them one repository over would put\n * security-critical code in two places and guarantee they drift.\n *\n * So the direction is inverted. The framework declares the SHAPE; the package that owns the\n * platform provides the implementation. The shape is structural, so nothing here imports the\n * framework and this package gains no dependency:\n *\n * ```ts\n * await handleChannelWebhook(request, pathname, {\n * validators: { sms: smsWebhookVerifier(adapter) },\n * })\n * ```\n *\n * @public\n */\n\nimport type { SMSAdapter } from \"./adapter.js\";\nimport type { SignatureContext } from \"./backend-types.js\";\n\n/**\n * What a verifier answers. Structurally identical to the framework's `VerifyResult`, declared here\n * so this package does not depend on the framework to describe its own return value.\n *\n * @public\n */\nexport type WebhookVerifyResult =\n | { readonly ok: true }\n | { readonly ok: false; readonly reason: string };\n\n/** Options for {@link smsWebhookVerifier}. @public */\nexport interface SMSWebhookVerifierOptions {\n /**\n * The URL the provider POSTs to, as the provider sees it.\n *\n * Twilio signs the URL, so verification compares against whatever string is passed here — and\n * behind a proxy or a tunnel the request's own URL is the INTERNAL one, which will not match.\n * Defaults to the adapter's configured `publicUrl` when it has one, and to the request URL\n * otherwise.\n */\n readonly publicUrl?: string;\n}\n\n/**\n * The subset of the adapter this verifier reads. Stated as an interface so the parameter is honest\n * about its requirements, and so a test can supply the two members without a live provider SDK.\n */\ninterface VerifiableAdapter {\n verifySignature(ctx: SignatureContext): boolean;\n readonly publicUrl?: string;\n}\n\n/**\n * The lowercased header map {@link SignatureContext} promises its consumers.\n *\n * No `toLowerCase()` here, and that is the point rather than an omission: the Fetch `Headers` object\n * normalises names on the way in, so iterating it already yields `x-twilio-signature` however the\n * sender wrote it. Lowercasing again was in the first version and mutation testing showed it dead —\n * removing it changed no test, because the platform had already done the work.\n */\nfunction headersOf(request: Request): Record<string, string> {\n const out: Record<string, string> = {};\n request.headers.forEach((value, key) => {\n out[key] = value;\n });\n return out;\n}\n\n/**\n * Build a verifier for one configured SMS adapter.\n *\n * The request is READ, so pass a clone if the body is needed afterwards — a framework seam that\n * hands validators a `clone()` already does this. Reading it raw is not optional: every provider\n * signs the exact bytes, and a body that was parsed and re-serialised hashes differently.\n *\n * **Connect the adapter first.** Each backend loads its provider SDK during `connect()`, and until\n * it has, `verifySignature` answers `false` for everything — so a verifier wired before connect\n * refuses every genuine delivery as a bad signature. The two are NOT distinguishable here: the\n * backend contract returns a boolean, and inventing a reason this function cannot actually observe\n * would be worse than the ambiguity. The behaviour is pinned by a test rather than papered over,\n * and telling them apart needs a readiness signal the adapter does not expose today.\n *\n * @public\n */\nexport function smsWebhookVerifier(\n adapter: SMSAdapter | VerifiableAdapter,\n opts: SMSWebhookVerifierOptions = {},\n): (request: Request) => Promise<WebhookVerifyResult> {\n return async (request: Request): Promise<WebhookVerifyResult> => {\n const rawBody = await request.text();\n const ctx: SignatureContext = {\n headers: headersOf(request),\n rawBody,\n url: opts.publicUrl ?? adapter.publicUrl ?? request.url,\n };\n return adapter.verifySignature(ctx)\n ? { ok: true }\n : { ok: false, reason: \"signature mismatch\" };\n };\n}\n"]}
|
package/dist/index.d.cts
CHANGED
|
@@ -149,12 +149,27 @@ declare class SMSAdapter extends BasePlatformAdapter {
|
|
|
149
149
|
}
|
|
150
150
|
|
|
151
151
|
/**
|
|
152
|
-
*
|
|
152
|
+
* The SMS (Twilio) half of the descriptor's webhook, answered through `ChannelWebhook.handle` so a
|
|
153
|
+
* host mounts it with `createWebhookHandler`.
|
|
153
154
|
*
|
|
154
|
-
*
|
|
155
|
-
*
|
|
155
|
+
* Twilio signs the public URL plus the form fields, so verification always uses the configured
|
|
156
|
+
* `publicUrl`, never the request's own URL or Host header. The adapter's options are recorded here
|
|
157
|
+
* by the descriptor's `create`, keyed by the adapter, so no secret sits on a public field. An
|
|
158
|
+
* adapter the descriptor did not build has none and every request to it is refused.
|
|
159
|
+
*
|
|
160
|
+
* No secret, signature or body text is logged or answered.
|
|
156
161
|
*/
|
|
157
162
|
|
|
163
|
+
interface WebhookRequestShape {
|
|
164
|
+
readonly rawBody: string;
|
|
165
|
+
readonly headers: Readonly<Record<string, string | undefined>>;
|
|
166
|
+
readonly method?: string;
|
|
167
|
+
readonly url?: string;
|
|
168
|
+
}
|
|
169
|
+
interface WebhookAnswerShape {
|
|
170
|
+
readonly status: number;
|
|
171
|
+
}
|
|
172
|
+
|
|
158
173
|
/** One configuration field, shaped like the core's `ChannelConfigField` (typed locally). */
|
|
159
174
|
interface ConfigField {
|
|
160
175
|
readonly key: string;
|
|
@@ -164,8 +179,9 @@ interface ConfigField {
|
|
|
164
179
|
readonly description: string;
|
|
165
180
|
}
|
|
166
181
|
/**
|
|
167
|
-
* The SMS channel on the Twilio backend.
|
|
168
|
-
*
|
|
182
|
+
* The SMS channel on the Twilio backend. Inbound messages arrive by webhook: mount
|
|
183
|
+
* `createWebhookHandler` (see the README); `webhook.handle` verifies against the configured
|
|
184
|
+
* `publicUrl`.
|
|
169
185
|
*
|
|
170
186
|
* `create` validates each value with this package's `ConfigurationError` and makes no network call.
|
|
171
187
|
*
|
|
@@ -173,7 +189,13 @@ interface ConfigField {
|
|
|
173
189
|
*/
|
|
174
190
|
declare const smsChannel: {
|
|
175
191
|
platform: "sms";
|
|
176
|
-
transport: "
|
|
192
|
+
transport: "webhook";
|
|
193
|
+
webhook: {
|
|
194
|
+
methods: readonly ["POST"];
|
|
195
|
+
verify(adapter: SMSAdapter, request: WebhookRequestShape): boolean;
|
|
196
|
+
ingest(adapter: SMSAdapter, payload: unknown): Promise<"delivered" | "malformed" | "no_handler">;
|
|
197
|
+
handle(adapter: SMSAdapter, request: WebhookRequestShape): Promise<WebhookAnswerShape>;
|
|
198
|
+
};
|
|
177
199
|
config: readonly ConfigField[];
|
|
178
200
|
create(config: Readonly<Record<string, unknown>>): SMSAdapter;
|
|
179
201
|
};
|
package/dist/index.d.ts
CHANGED
|
@@ -149,12 +149,27 @@ declare class SMSAdapter extends BasePlatformAdapter {
|
|
|
149
149
|
}
|
|
150
150
|
|
|
151
151
|
/**
|
|
152
|
-
*
|
|
152
|
+
* The SMS (Twilio) half of the descriptor's webhook, answered through `ChannelWebhook.handle` so a
|
|
153
|
+
* host mounts it with `createWebhookHandler`.
|
|
153
154
|
*
|
|
154
|
-
*
|
|
155
|
-
*
|
|
155
|
+
* Twilio signs the public URL plus the form fields, so verification always uses the configured
|
|
156
|
+
* `publicUrl`, never the request's own URL or Host header. The adapter's options are recorded here
|
|
157
|
+
* by the descriptor's `create`, keyed by the adapter, so no secret sits on a public field. An
|
|
158
|
+
* adapter the descriptor did not build has none and every request to it is refused.
|
|
159
|
+
*
|
|
160
|
+
* No secret, signature or body text is logged or answered.
|
|
156
161
|
*/
|
|
157
162
|
|
|
163
|
+
interface WebhookRequestShape {
|
|
164
|
+
readonly rawBody: string;
|
|
165
|
+
readonly headers: Readonly<Record<string, string | undefined>>;
|
|
166
|
+
readonly method?: string;
|
|
167
|
+
readonly url?: string;
|
|
168
|
+
}
|
|
169
|
+
interface WebhookAnswerShape {
|
|
170
|
+
readonly status: number;
|
|
171
|
+
}
|
|
172
|
+
|
|
158
173
|
/** One configuration field, shaped like the core's `ChannelConfigField` (typed locally). */
|
|
159
174
|
interface ConfigField {
|
|
160
175
|
readonly key: string;
|
|
@@ -164,8 +179,9 @@ interface ConfigField {
|
|
|
164
179
|
readonly description: string;
|
|
165
180
|
}
|
|
166
181
|
/**
|
|
167
|
-
* The SMS channel on the Twilio backend.
|
|
168
|
-
*
|
|
182
|
+
* The SMS channel on the Twilio backend. Inbound messages arrive by webhook: mount
|
|
183
|
+
* `createWebhookHandler` (see the README); `webhook.handle` verifies against the configured
|
|
184
|
+
* `publicUrl`.
|
|
169
185
|
*
|
|
170
186
|
* `create` validates each value with this package's `ConfigurationError` and makes no network call.
|
|
171
187
|
*
|
|
@@ -173,7 +189,13 @@ interface ConfigField {
|
|
|
173
189
|
*/
|
|
174
190
|
declare const smsChannel: {
|
|
175
191
|
platform: "sms";
|
|
176
|
-
transport: "
|
|
192
|
+
transport: "webhook";
|
|
193
|
+
webhook: {
|
|
194
|
+
methods: readonly ["POST"];
|
|
195
|
+
verify(adapter: SMSAdapter, request: WebhookRequestShape): boolean;
|
|
196
|
+
ingest(adapter: SMSAdapter, payload: unknown): Promise<"delivered" | "malformed" | "no_handler">;
|
|
197
|
+
handle(adapter: SMSAdapter, request: WebhookRequestShape): Promise<WebhookAnswerShape>;
|
|
198
|
+
};
|
|
177
199
|
config: readonly ConfigField[];
|
|
178
200
|
create(config: Readonly<Record<string, unknown>>): SMSAdapter;
|
|
179
201
|
};
|