@theokit/gateway-sms 0.2.3 → 0.3.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 +91 -0
- package/README.md +13 -0
- package/dist/index.cjs +65 -68
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +92 -1
- package/dist/index.d.ts +92 -1
- package/dist/index.js +66 -70
- 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/split.ts","../src/adapter.ts","../src/parse-inbound.ts","../src/webhook-server.ts"],"names":["GatewayConfigurationError","parsePhoneNumberFromString","parseFormUrlEncoded","chunkByGrapheme","BasePlatformAdapter"],"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;AC3BO,SAAS,aAAA,CAAc,OAAe,cAAA,EAAiC;AAC5E,EAAA,IAAI,KAAA,CAAM,WAAW,CAAA,EAAG;AACtB,IAAA,MAAM,IAAI,kBAAA,CAAmB;AAAA,MAC3B,IAAA,EAAM,sBAAA;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A,IAAI,OAAA,GAAU,KAAA;AACd,EAAA,IAAI,OAAA,GAAU,KAAA;AAEd,EAAA,OAAO;AAAA,IACL,MAAM,KAAA,GAAuB;AAC3B,MAAA,IAAI,OAAA,IAAW,IAAA,CAAK,GAAA,KAAQ,MAAA,EAAW;AAErC,QAAA,OAAA,GAAU,IAAA;AACV,QAAA;AAAA,MACF;AAGA,MAAA,OAAA,GAAU,KAAA;AACV,MAAA,MAAM,IAAA,GAAO,KAAK,IAAA,IAAQ,GAAA;AAC1B,MAAA,MAAM,IAAI,OAAA,CAAc,CAAC,OAAA,KAAY;AACnC,QAAA,MAAA,GAAS,GAAA,CAAI,MAAA,CAAO,IAAA,EAAM,MAAM,SAAS,CAAA;AAAA,MAC3C,CAAC,CAAA;AACD,MAAA,OAAA,GAAU,IAAA;AAAA,IACZ,CAAA;AAAA,IACA,MAAM,IAAA,GAAsB;AAC1B,MAAA,IAAI,OAAA,EAAS;AACb,MAAA,OAAA,GAAU,IAAA;AAIV,MAAA,OAAA,GAAU,KAAA;AACV,MAAA,IAAI,WAAW,MAAA,EAAW;AAC1B,MAAA,MAAM,IAAI,OAAA,CAAc,CAAC,OAAA,KAAY;AACnC,QAAA,MAAA,EAAQ,KAAA,CAAM,MAAM,OAAA,EAAS,CAAA;AAAA,MAC/B,CAAC,CAAA;AACD,MAAA,MAAA,GAAS,MAAA;AAAA,IACX;AAAA,GACF;AACF","file":"index.cjs","sourcesContent":["/**\n * Typed errors for `@theokit/gateway-sms` (D389-D396).\n *\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 * `splitForSMS` — grapheme-cluster-safe multipart segmentation (D393, EC-7).\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 * Thin wrapper over core `chunkByGrapheme` (roadmap M1) — single-sources the\n * `Intl.Segmenter` grapheme walk so emoji (🇧🇷) and combining sequences are\n * never severed. The `(i/N) ` prefix (and its reserved width) stays here since\n * it is SMS-specific. Output is byte-identical to the previous implementation\n * (pinned by `tests/split.test.ts`).\n *\n * @internal\n */\n\nimport { chunkByGrapheme } 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\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 = chunkByGrapheme(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 { 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 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.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 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\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 * `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 type { Express, NextFunction, Request, Response } from \"express\";\nimport type { SMSAdapter } from \"./adapter.js\";\nimport type { SignatureContext } from \"./backend-types.js\";\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<{ default: () => Express }> {\n try {\n const mod = await import(\"express\");\n // Both ESM and CJS forms; normalize to { default }.\n const fn = (mod as { default?: () => Express }).default ?? (mod as unknown as () => Express);\n return { default: fn };\n } catch {\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\nfunction buildSignatureContext(req: Request): 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 const protoHeader = headers[\"x-forwarded-proto\"];\n const proto = protoHeader ?? (req.secure ? \"https\" : \"http\");\n const host = req.get(\"host\") ?? \"localhost\";\n const url = `${proto}://${host}${req.originalUrl}`;\n return { headers, rawBody, url };\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 expressMod = await loadExpress();\n const app: Express = opts.app ?? expressMod.default();\n const prefix = opts.path ?? \"/sms\";\n const backend = opts.adapter.getBackendKind();\n\n // Raw-body capture middleware — must run BEFORE express.urlencoded/json,\n // since signature verification needs the exact byte sequence.\n const rawCapture = (req: Request, _res: Response, next: NextFunction) => {\n // Someone else already drained the stream — a global `express.json()` or\n // `express.urlencoded()` mounted ahead of this router is the usual cause.\n // Without this branch, `req.on(\"end\")` never fires for a stream that already\n // ended, `next()` is never called, and the request HANGS with no response:\n // the provider times out and retries, and nothing is logged. Failing loudly\n // and continuing is strictly better — verification then refuses the empty\n // body with a 401, a visible symptom that points at the real cause.\n if (req.readableEnded || req.complete) {\n process.stderr.write(\n \"[gateway-sms] raw body already consumed before signature capture — mount this router \" +\n \"BEFORE any global body parser, or signature verification cannot see the bytes it \" +\n \"must hash\\n\",\n );\n (req as Request & { rawBody: string }).rawBody = \"\";\n next();\n return;\n }\n let buf = \"\";\n req.setEncoding(\"utf8\");\n req.on(\"data\", (chunk: string) => {\n buf += chunk;\n });\n req.on(\"end\", () => {\n (req as Request & { rawBody: string }).rawBody = buf;\n next();\n });\n req.on(\"error\", (err) => next(err));\n };\n\n const handler = (req: Request, res: Response): void => {\n const ctx = buildSignatureContext(req);\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(`${prefix}/${backend}`, rawCapture, handler);\n\n let server: import(\"node:http\").Server | undefined;\n let started = false;\n let stopped = false;\n\n return {\n async start(): Promise<void> {\n if (started || opts.app !== undefined) {\n // When caller injected its own app, we don't manage the listener.\n started = true;\n return;\n }\n // Cleared here, not in stop(): a server that was stopped and is starting again is no longer\n // stopped, and leaving the flag latched made the NEXT stop() a no-op that left the listener up.\n stopped = false;\n const port = opts.port ?? 3000;\n await new Promise<void>((resolve) => {\n server = app.listen(port, () => resolve());\n });\n started = true;\n },\n async stop(): Promise<void> {\n if (stopped) return;\n stopped = true;\n // The pair of latches used to be write-once, so `start()` after a `stop()` returned without\n // creating a listener and the server was silently dead — no error, no log, just a port nothing\n // answers on. Resetting `started` is what makes a restart a restart.\n started = false;\n if (server === undefined) return;\n await new Promise<void>((resolve) => {\n server?.close(() => resolve());\n });\n server = undefined;\n },\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/split.ts","../src/adapter.ts","../src/parse-inbound.ts","../src/webhook-server.ts","../src/webhook-verifier.ts"],"names":["GatewayConfigurationError","parsePhoneNumberFromString","parseFormUrlEncoded","chunkByGrapheme","BasePlatformAdapter","loadPeer","rawBodyCapture","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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AAA,OAAOC,yBAAA,CAAkB,EAAE,GAAA,EAAK,IAAA,EAAM,IAAA,CAAK,IAAA,IAAQ,GAAA,EAAM,QAAA,EAAU,IAAA,CAAK,GAAA,KAAQ,MAAA,EAAW,CAAA;AAC7F;;;ACnEA,SAAS,UAAU,OAAA,EAA0C;AAC3D,EAAA,MAAM,MAA8B,EAAC;AACrC,EAAA,OAAA,CAAQ,OAAA,CAAQ,OAAA,CAAQ,CAAC,KAAA,EAAO,GAAA,KAAQ;AACtC,IAAA,GAAA,CAAI,GAAG,CAAA,GAAI,KAAA;AAAA,EACb,CAAC,CAAA;AACD,EAAA,OAAO,GAAA;AACT;AAkBO,SAAS,kBAAA,CACd,OAAA,EACA,IAAA,GAAkC,EAAC,EACiB;AACpD,EAAA,OAAO,OAAO,OAAA,KAAmD;AAC/D,IAAA,MAAM,OAAA,GAAU,MAAM,OAAA,CAAQ,IAAA,EAAK;AACnC,IAAA,MAAM,GAAA,GAAwB;AAAA,MAC5B,OAAA,EAAS,UAAU,OAAO,CAAA;AAAA,MAC1B,OAAA;AAAA,MACA,GAAA,EAAK,IAAA,CAAK,SAAA,IAAa,OAAA,CAAQ,aAAa,OAAA,CAAQ;AAAA,KACtD;AACA,IAAA,OAAO,OAAA,CAAQ,eAAA,CAAgB,GAAG,CAAA,GAC9B,EAAE,EAAA,EAAI,IAAA,EAAK,GACX,EAAE,EAAA,EAAI,KAAA,EAAO,MAAA,EAAQ,oBAAA,EAAqB;AAAA,EAChD,CAAA;AACF","file":"index.cjs","sourcesContent":["/**\n * Typed errors for `@theokit/gateway-sms` (D389-D396).\n *\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 * `splitForSMS` — grapheme-cluster-safe multipart segmentation (D393, EC-7).\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 * Thin wrapper over core `chunkByGrapheme` (roadmap M1) — single-sources the\n * `Intl.Segmenter` grapheme walk so emoji (🇧🇷) and combining sequences are\n * never severed. The `(i/N) ` prefix (and its reserved width) stays here since\n * it is SMS-specific. Output is byte-identical to the previous implementation\n * (pinned by `tests/split.test.ts`).\n *\n * @internal\n */\n\nimport { chunkByGrapheme } 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\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 = chunkByGrapheme(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 { 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 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 * 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 * `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 { listenerLifecycle, loadPeer, rawBodyCapture } 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(`${prefix}/${backend}`, rawBodyCapture(\"gateway-sms\"), handler);\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
|
@@ -101,6 +101,18 @@ declare class SMSAdapter extends BasePlatformAdapter {
|
|
|
101
101
|
*/
|
|
102
102
|
private warnedAboutFormat;
|
|
103
103
|
readonly platform: "sms";
|
|
104
|
+
/**
|
|
105
|
+
* The URL the provider POSTs inbound to, as the provider sees it.
|
|
106
|
+
*
|
|
107
|
+
* Required by all three backend option shapes and documented there as "used by signature
|
|
108
|
+
* verifier" — and, measured 2026-08-31, read by nothing: it appeared only in the type and in test
|
|
109
|
+
* fixtures. Twilio SIGNS this URL, so the value matters most in exactly the case where the
|
|
110
|
+
* request cannot supply it: behind a proxy or a tunnel, the request's own URL is the internal one
|
|
111
|
+
* and will not match what was signed.
|
|
112
|
+
*
|
|
113
|
+
* Exposed so {@link smsWebhookVerifier} can use it, which is what makes the option true.
|
|
114
|
+
*/
|
|
115
|
+
readonly publicUrl: string;
|
|
104
116
|
private readonly backend;
|
|
105
117
|
private inboundHandler;
|
|
106
118
|
private connected;
|
|
@@ -112,6 +124,13 @@ declare class SMSAdapter extends BasePlatformAdapter {
|
|
|
112
124
|
onInbound(handler: (event: MessageEvent) => Promise<void>): () => void;
|
|
113
125
|
/** Backend kind (escape hatch for callers needing to introspect). */
|
|
114
126
|
getBackendKind(): "twilio" | "plivo" | "vonage";
|
|
127
|
+
/**
|
|
128
|
+
* Deliver an event that arrived out of band — the ingest `onInbound` had no counterpart for (#83).
|
|
129
|
+
*
|
|
130
|
+
* One line over `runHandler`, which owns the containment: a handler is user code, its throw is
|
|
131
|
+
* named as the handler's failure rather than the platform's, and delivery continues.
|
|
132
|
+
*/
|
|
133
|
+
deliver(event: MessageEvent): Promise<"ok" | "no_handler" | "handler_threw">;
|
|
115
134
|
}
|
|
116
135
|
|
|
117
136
|
/**
|
|
@@ -302,4 +321,76 @@ interface WebhookServer {
|
|
|
302
321
|
*/
|
|
303
322
|
declare function createWebhookServer(opts: WebhookServerOptions): Promise<WebhookServer>;
|
|
304
323
|
|
|
305
|
-
|
|
324
|
+
/**
|
|
325
|
+
* The SMS half of a channel webhook, in the shape a framework webhook seam expects.
|
|
326
|
+
*
|
|
327
|
+
* `theokit/server/webhook` ships validators for the platforms whose signature is a plain HMAC it
|
|
328
|
+
* can compute itself. SMS is not one of them: Twilio signs the URL plus the sorted POST parameters,
|
|
329
|
+
* Plivo signs a different string again, and Vonage uses a JWT. Those three schemes already exist in
|
|
330
|
+
* this package, correctly, with their own tests — reimplementing them one repository over would put
|
|
331
|
+
* security-critical code in two places and guarantee they drift.
|
|
332
|
+
*
|
|
333
|
+
* So the direction is inverted. The framework declares the SHAPE; the package that owns the
|
|
334
|
+
* platform provides the implementation. The shape is structural, so nothing here imports the
|
|
335
|
+
* framework and this package gains no dependency:
|
|
336
|
+
*
|
|
337
|
+
* ```ts
|
|
338
|
+
* await handleChannelWebhook(request, pathname, {
|
|
339
|
+
* validators: { sms: smsWebhookVerifier(adapter) },
|
|
340
|
+
* })
|
|
341
|
+
* ```
|
|
342
|
+
*
|
|
343
|
+
* @public
|
|
344
|
+
*/
|
|
345
|
+
|
|
346
|
+
/**
|
|
347
|
+
* What a verifier answers. Structurally identical to the framework's `VerifyResult`, declared here
|
|
348
|
+
* so this package does not depend on the framework to describe its own return value.
|
|
349
|
+
*
|
|
350
|
+
* @public
|
|
351
|
+
*/
|
|
352
|
+
type WebhookVerifyResult = {
|
|
353
|
+
readonly ok: true;
|
|
354
|
+
} | {
|
|
355
|
+
readonly ok: false;
|
|
356
|
+
readonly reason: string;
|
|
357
|
+
};
|
|
358
|
+
/** Options for {@link smsWebhookVerifier}. @public */
|
|
359
|
+
interface SMSWebhookVerifierOptions {
|
|
360
|
+
/**
|
|
361
|
+
* The URL the provider POSTs to, as the provider sees it.
|
|
362
|
+
*
|
|
363
|
+
* Twilio signs the URL, so verification compares against whatever string is passed here — and
|
|
364
|
+
* behind a proxy or a tunnel the request's own URL is the INTERNAL one, which will not match.
|
|
365
|
+
* Defaults to the adapter's configured `publicUrl` when it has one, and to the request URL
|
|
366
|
+
* otherwise.
|
|
367
|
+
*/
|
|
368
|
+
readonly publicUrl?: string;
|
|
369
|
+
}
|
|
370
|
+
/**
|
|
371
|
+
* The subset of the adapter this verifier reads. Stated as an interface so the parameter is honest
|
|
372
|
+
* about its requirements, and so a test can supply the two members without a live provider SDK.
|
|
373
|
+
*/
|
|
374
|
+
interface VerifiableAdapter {
|
|
375
|
+
verifySignature(ctx: SignatureContext): boolean;
|
|
376
|
+
readonly publicUrl?: string;
|
|
377
|
+
}
|
|
378
|
+
/**
|
|
379
|
+
* Build a verifier for one configured SMS adapter.
|
|
380
|
+
*
|
|
381
|
+
* The request is READ, so pass a clone if the body is needed afterwards — a framework seam that
|
|
382
|
+
* hands validators a `clone()` already does this. Reading it raw is not optional: every provider
|
|
383
|
+
* signs the exact bytes, and a body that was parsed and re-serialised hashes differently.
|
|
384
|
+
*
|
|
385
|
+
* **Connect the adapter first.** Each backend loads its provider SDK during `connect()`, and until
|
|
386
|
+
* it has, `verifySignature` answers `false` for everything — so a verifier wired before connect
|
|
387
|
+
* refuses every genuine delivery as a bad signature. The two are NOT distinguishable here: the
|
|
388
|
+
* backend contract returns a boolean, and inventing a reason this function cannot actually observe
|
|
389
|
+
* would be worse than the ambiguity. The behaviour is pinned by a test rather than papered over,
|
|
390
|
+
* and telling them apart needs a readiness signal the adapter does not expose today.
|
|
391
|
+
*
|
|
392
|
+
* @public
|
|
393
|
+
*/
|
|
394
|
+
declare function smsWebhookVerifier(adapter: SMSAdapter | VerifiableAdapter, opts?: SMSWebhookVerifierOptions): (request: Request) => Promise<WebhookVerifyResult>;
|
|
395
|
+
|
|
396
|
+
export { BackendNotInstalledError, ConfigurationError, type PlivoOptions, SMSAdapter, type SMSAdapterOptions, type SMSWebhookVerifierOptions, type TwilioOptions, type VonageOptions, type WebhookServer, type WebhookServerOptions, type WebhookVerifyResult, createWebhookServer, normalizeE164, parseInbound, smsWebhookVerifier, splitForSMS };
|
package/dist/index.d.ts
CHANGED
|
@@ -101,6 +101,18 @@ declare class SMSAdapter extends BasePlatformAdapter {
|
|
|
101
101
|
*/
|
|
102
102
|
private warnedAboutFormat;
|
|
103
103
|
readonly platform: "sms";
|
|
104
|
+
/**
|
|
105
|
+
* The URL the provider POSTs inbound to, as the provider sees it.
|
|
106
|
+
*
|
|
107
|
+
* Required by all three backend option shapes and documented there as "used by signature
|
|
108
|
+
* verifier" — and, measured 2026-08-31, read by nothing: it appeared only in the type and in test
|
|
109
|
+
* fixtures. Twilio SIGNS this URL, so the value matters most in exactly the case where the
|
|
110
|
+
* request cannot supply it: behind a proxy or a tunnel, the request's own URL is the internal one
|
|
111
|
+
* and will not match what was signed.
|
|
112
|
+
*
|
|
113
|
+
* Exposed so {@link smsWebhookVerifier} can use it, which is what makes the option true.
|
|
114
|
+
*/
|
|
115
|
+
readonly publicUrl: string;
|
|
104
116
|
private readonly backend;
|
|
105
117
|
private inboundHandler;
|
|
106
118
|
private connected;
|
|
@@ -112,6 +124,13 @@ declare class SMSAdapter extends BasePlatformAdapter {
|
|
|
112
124
|
onInbound(handler: (event: MessageEvent) => Promise<void>): () => void;
|
|
113
125
|
/** Backend kind (escape hatch for callers needing to introspect). */
|
|
114
126
|
getBackendKind(): "twilio" | "plivo" | "vonage";
|
|
127
|
+
/**
|
|
128
|
+
* Deliver an event that arrived out of band — the ingest `onInbound` had no counterpart for (#83).
|
|
129
|
+
*
|
|
130
|
+
* One line over `runHandler`, which owns the containment: a handler is user code, its throw is
|
|
131
|
+
* named as the handler's failure rather than the platform's, and delivery continues.
|
|
132
|
+
*/
|
|
133
|
+
deliver(event: MessageEvent): Promise<"ok" | "no_handler" | "handler_threw">;
|
|
115
134
|
}
|
|
116
135
|
|
|
117
136
|
/**
|
|
@@ -302,4 +321,76 @@ interface WebhookServer {
|
|
|
302
321
|
*/
|
|
303
322
|
declare function createWebhookServer(opts: WebhookServerOptions): Promise<WebhookServer>;
|
|
304
323
|
|
|
305
|
-
|
|
324
|
+
/**
|
|
325
|
+
* The SMS half of a channel webhook, in the shape a framework webhook seam expects.
|
|
326
|
+
*
|
|
327
|
+
* `theokit/server/webhook` ships validators for the platforms whose signature is a plain HMAC it
|
|
328
|
+
* can compute itself. SMS is not one of them: Twilio signs the URL plus the sorted POST parameters,
|
|
329
|
+
* Plivo signs a different string again, and Vonage uses a JWT. Those three schemes already exist in
|
|
330
|
+
* this package, correctly, with their own tests — reimplementing them one repository over would put
|
|
331
|
+
* security-critical code in two places and guarantee they drift.
|
|
332
|
+
*
|
|
333
|
+
* So the direction is inverted. The framework declares the SHAPE; the package that owns the
|
|
334
|
+
* platform provides the implementation. The shape is structural, so nothing here imports the
|
|
335
|
+
* framework and this package gains no dependency:
|
|
336
|
+
*
|
|
337
|
+
* ```ts
|
|
338
|
+
* await handleChannelWebhook(request, pathname, {
|
|
339
|
+
* validators: { sms: smsWebhookVerifier(adapter) },
|
|
340
|
+
* })
|
|
341
|
+
* ```
|
|
342
|
+
*
|
|
343
|
+
* @public
|
|
344
|
+
*/
|
|
345
|
+
|
|
346
|
+
/**
|
|
347
|
+
* What a verifier answers. Structurally identical to the framework's `VerifyResult`, declared here
|
|
348
|
+
* so this package does not depend on the framework to describe its own return value.
|
|
349
|
+
*
|
|
350
|
+
* @public
|
|
351
|
+
*/
|
|
352
|
+
type WebhookVerifyResult = {
|
|
353
|
+
readonly ok: true;
|
|
354
|
+
} | {
|
|
355
|
+
readonly ok: false;
|
|
356
|
+
readonly reason: string;
|
|
357
|
+
};
|
|
358
|
+
/** Options for {@link smsWebhookVerifier}. @public */
|
|
359
|
+
interface SMSWebhookVerifierOptions {
|
|
360
|
+
/**
|
|
361
|
+
* The URL the provider POSTs to, as the provider sees it.
|
|
362
|
+
*
|
|
363
|
+
* Twilio signs the URL, so verification compares against whatever string is passed here — and
|
|
364
|
+
* behind a proxy or a tunnel the request's own URL is the INTERNAL one, which will not match.
|
|
365
|
+
* Defaults to the adapter's configured `publicUrl` when it has one, and to the request URL
|
|
366
|
+
* otherwise.
|
|
367
|
+
*/
|
|
368
|
+
readonly publicUrl?: string;
|
|
369
|
+
}
|
|
370
|
+
/**
|
|
371
|
+
* The subset of the adapter this verifier reads. Stated as an interface so the parameter is honest
|
|
372
|
+
* about its requirements, and so a test can supply the two members without a live provider SDK.
|
|
373
|
+
*/
|
|
374
|
+
interface VerifiableAdapter {
|
|
375
|
+
verifySignature(ctx: SignatureContext): boolean;
|
|
376
|
+
readonly publicUrl?: string;
|
|
377
|
+
}
|
|
378
|
+
/**
|
|
379
|
+
* Build a verifier for one configured SMS adapter.
|
|
380
|
+
*
|
|
381
|
+
* The request is READ, so pass a clone if the body is needed afterwards — a framework seam that
|
|
382
|
+
* hands validators a `clone()` already does this. Reading it raw is not optional: every provider
|
|
383
|
+
* signs the exact bytes, and a body that was parsed and re-serialised hashes differently.
|
|
384
|
+
*
|
|
385
|
+
* **Connect the adapter first.** Each backend loads its provider SDK during `connect()`, and until
|
|
386
|
+
* it has, `verifySignature` answers `false` for everything — so a verifier wired before connect
|
|
387
|
+
* refuses every genuine delivery as a bad signature. The two are NOT distinguishable here: the
|
|
388
|
+
* backend contract returns a boolean, and inventing a reason this function cannot actually observe
|
|
389
|
+
* would be worse than the ambiguity. The behaviour is pinned by a test rather than papered over,
|
|
390
|
+
* and telling them apart needs a readiness signal the adapter does not expose today.
|
|
391
|
+
*
|
|
392
|
+
* @public
|
|
393
|
+
*/
|
|
394
|
+
declare function smsWebhookVerifier(adapter: SMSAdapter | VerifiableAdapter, opts?: SMSWebhookVerifierOptions): (request: Request) => Promise<WebhookVerifyResult>;
|
|
395
|
+
|
|
396
|
+
export { BackendNotInstalledError, ConfigurationError, type PlivoOptions, SMSAdapter, type SMSAdapterOptions, type SMSWebhookVerifierOptions, type TwilioOptions, type VonageOptions, type WebhookServer, type WebhookServerOptions, type WebhookVerifyResult, createWebhookServer, normalizeE164, parseInbound, smsWebhookVerifier, splitForSMS };
|