Skip to content

feat(sms): B-Twilio-1 — Twilio SMS ChannelTransport (fail-closed config, signed webhook, TCPA STOP/HELP rail) - #68

Merged
supmo668 merged 10 commits into
mainfrom
mangyinm/b-twilio-1-sms-adapter
Jul 15, 2026
Merged

supmo668 merged 10 commits into
mainfrom
mangyinm/b-twilio-1-sms-adapter

Conversation

@supmo668

@supmo668 supmo668 commented Jul 15, 2026 •

Copy link
Copy Markdown

B-Twilio-1 per the approved AD-onboarding-channels: new vendor-agnostic 'sms' channel with Twilio transport. Scoped API keys on per-env subaccounts (authToken = webhook-HMAC only); fail-closed credential completeness (channel inert until fully provisioned); outbound REST send; X-Twilio-Signature validation reusing the voice-call HMAC validator; TCPA STOP/HELP/START opt-out rail (durable store in openclaw's own DB per ADR-0001 — never the Journal PHI DB); PHI-deny (sms third-party). QG: 4-reviewer + adversarial re-verify — CRITICAL (compliance ack suppressed by opt-out guard) fixed via unguarded compliance-ack path, confirmed resolved; DoS cap + inbound gate added. 80/80 tests, all gates clean. Live verification gated on principal Twilio provisioning.

🤖 Generated with Claude Code

Summary by CodeRabbit

  • New Features

    • Added Twilio SMS integration for sending and receiving messages.
    • Added configurable inbound access policies, including disabled, pairing, and allowlist modes.
    • Added secure webhook validation and request-size protection.
    • Added TCPA compliance handling for STOP, START, and HELP messages.
    • Added durable opt-out tracking and automatic suppression of messages to opted-out recipients.
  • Bug Fixes

    • Improved failure handling to prevent credential exposure and fail safely when configuration or compliance storage is unavailable.
  • Tests

    • Added comprehensive coverage for configuration, sending, receiving, security, compliance, and opt-out behavior.

supmo668 and others added 10 commits July 14, 2026 00:44
…(scoped API keys / per-env subaccount, fail-closed)

First slice of B-Twilio-1 (Twilio SMS ChannelTransport adapter, greenfield). The auth + number config contract per AD-onboarding-channels §4.2/4.3.

- Scoped Standard API Keys (SID+Secret) on per-env SUBACCOUNTS, NEVER the master Auth Token (test/prod isolation by construction); subaccount Auth Token retained ONLY as the X-Twilio-Signature HMAC key (§4.3).
- E.164 sender + allowFrom validation; inbound policy defaults to 'pairing' (deny-by-default, mirrors SYNTROPY_GATE).
- resolveTwilioSmsConfig: FAIL-CLOSED on credential completeness — returns null (channel INERT, registers nothing) unless EVERY credential + the sender number is present; no partial Twilio wiring. authToken REQUIRED (an SMS channel with no way to validate inbound signatures must not run).
- Infisical channels/twilio/{env} → runtime env fallback; config wins per-field.

Red-first: 11 tests (E.164 valid/invalid, strict-schema typo-safety, inbound default, credential-completeness incl. each-single-missing → null, authToken-required, env fallback, config precedence). tsgo clean, oxfmt clean. Standalone module — no plugin wiring yet (slice 5). Slices 2-6 (send / webhook+sig / TCPA STOP-HELP hard rail / plugin wiring / rails tests) per B-TWILIO-1-PLAN.md.

Generated-With: Claude Code
Co-Authored-By: cto <[email protected]>
Co-Authored-By: Claude <[email protected]>
…coped API-key auth, injectable fetch, fail-closed secret hygiene)

send.ts: sendSms() → Twilio REST POST /2010-04-01/Accounts/{accountSid}/Messages.json. Basic-auth apiKeySid:apiKeySecret (scoped API key §4.2), NOT the authToken (webhook-HMAC only). Form-encoded From/To/Body. Injectable fetch seam (default global fetch). Discriminated {ok:true,sid}|{ok:false,status,error} — never throws, never leaks the api-key secret in error/return. No media v1. Does NOT import voice-call's twilioApiRequest (keeps the vendor-agnostic single-extension rail; that helper is account-auth + non-injectable). 6 red-first tests: URL/path, scoped-key auth (asserts NOT account:authToken), form fields, success sid, HTTP-error no-leak, network-throw no-leak. Full twilio suite 17/17; tsgo+lint+fmt clean.

Generated-With: Claude Code
Co-Authored-By: cto <[email protected]>
Co-Authored-By: Claude <[email protected]>
…+ X-Twilio-Signature gate (validate BEFORE routing)

webhook.ts: decideInboundSms() pure security gate — non-POST 405; X-Twilio-Signature validated (HMAC-SHA1, subaccount authToken §4.3) BEFORE any parse/route, mismatch/absent => 403 and inbound NEVER surfaced; authenticated-but-no-From => 400; authenticated+routable => 200 with {from,body}. Validator REUSED from voice-call (validateTwilioSignature, pure timing-safe) — single source of truth for the crypto (precedent: syntropy-mcp reuses syntropy/src). createSmsWebhookHandler: thin IncomingMessage/ServerResponse adapter (body read, header/url extraction, empty-TwiML 200); resolveUrl seam for proxy URL reconstruction. 9 red-first tests incl. genuine-HMAC accept + tamper-detection (good sig + altered body => 403) proving reject-on-mismatch end-to-end. Full twilio suite 26/26; tsgo+lint+fmt clean.

Generated-With: Claude Code
Co-Authored-By: cto <[email protected]>
Co-Authored-By: Claude <[email protected]>
…rail (QG-blocking behavioral pin, CTO openclaw#3559)

compliance.ts: the non-negotiable opt-out rail. classifyCompliance() EXACT-match (trim/upper/strip-punct) STOP/STOPALL/UNSUBSCRIBE/CANCEL/END/QUIT->stop, START/YES/UNSTOP->start, HELP/INFO->help — conversational text containing a keyword as substring does NOT opt-out (no false positives). handleInboundCompliance(): STOP persists durable opt-out + confirmation, START clears, HELP replies (no state change), else passthrough to agent; replies are generic (no PHI/clerk-id/pairing). guardedSendSms(): enforcement half — checks opt-out FAIL-CLOSED (store throws => suppress, never send) before delegating to sendSms. ★ BEHAVIORAL PIN GREEN: a STOP'd number receives ZERO subsequent sends (fetch never called) + fail-closed. OptOutStore is an injectable seam; durable DB impl wired at slice 5. 12 red-first tests. Full twilio suite 38/38; tsgo+lint+fmt clean.

Generated-With: Claude Code
Co-Authored-By: cto <[email protected]>
Co-Authored-By: Claude <[email protected]>
…r (send→OutboundDeliveryResult, opt-out=terminal sentinel)

outbound.ts buildSmsOutboundAdapter(): maps guardedSendSms → ChannelOutboundAdapter.sendText per the delivery-queue semantics (returned result=ack/terminal, throw=fail/retry). Opt-out suppression returns a TERMINAL sentinel {messageId:'suppressed:optout',meta.suppressed} so a STOP'd recipient never re-enters the retry queue; genuine send failure THROWS (retryable); resolveConfig→null throws not-configured. deliveryMode 'direct'. Config/store/fetch injected — pure testable mapping. Secret never in thrown error. 6 red-first tests. Full twilio suite 44/44; tsgo+lint+fmt clean. Remaining slice-5 parts: 5a config-adapter bridge, 5c durable pg OptOutStore, 5d plugin object + register()/registerHttpRoute wiring, 5e manifest.

Generated-With: Claude Code
Co-Authored-By: cto <[email protected]>
Co-Authored-By: Claude <[email protected]>
…ore (ADR 0001: OpenClaw's own DB, user-independent key)

optout-store.ts: ensureOptOutSchema (idempotent CREATE TABLE IF NOT EXISTS lp_sms_optouts) + createPgOptOutStore backing the slice-4 OptOutStore seam. Per ADR 0001: lives in OpenClaw's OWN persist-user-identity Postgres, NEVER the Journal PHI DB; keyed by bare E.164 (user-independent) so a pre-pairing STOP is honored. Injected-sql convention (mirrors persist-user-identity/db.ts) via a minimal structural SqlTag type — zero new deps, decoupled from the postgres driver (real postgres.Sql satisfies it structurally at the wiring site). 4 tests via fake-sql round-trip (optOut->isOptedOut true, optIn clears, unknown=false, DDL issued). Full twilio suite 48/48; tsgo+lint+fmt clean. Remaining: 5d plugin object + register() (create pg client from DATABASE_URL, ensureSchema, wire channel + /twilio/sms route + compliance-before-gateway), 5e manifest.

Generated-With: Claude Code
Co-Authored-By: cto <[email protected]>
Co-Authored-By: Claude <[email protected]>
…bridge (OpenClawConfig.channels.sms → resolveTwilioSmsConfig)

accounts.ts: resolveSmsAccount reads cfg.channels.sms (ChannelsConfig index signature — no core config-type change) → TwilioSmsConfigSchema.safeParse → resolveTwilioSmsConfig (+ TWILIO_* env fallback). Inert until credential-complete (configured=false, config=null); malformed config object is ignored (falls back to env) rather than throwing. v1 single-account (listSmsAccountIds → [DEFAULT_ACCOUNT_ID]). Exports smsConfigAdapter (ChannelConfigAdapter) for the plugin object (5d). 7 red-first tests (full/inert/env-fallback/partial-fail-closed/bad-schema/default-account). Full twilio suite 55/55; tsgo+lint+fmt clean.

Generated-With: Claude Code
Co-Authored-By: cto <[email protected]>
Co-Authored-By: Claude <[email protected]>
…d + registered (channel + inbound webhook → compliance → agent)

Wires the tested blocks into a live channel. package.json (@openclaw/twilio, postgres dep, openclaw.extensions entry — the extension now LOADS). db.ts: own pg pool to DATABASE_URL (ADR 0001, OpenClaw's DB). channel.ts: createSmsPlugin factory (id 'sms', direct-only, no media, config adapter + opt-out-guarded outbound; 5 tests). index.ts register(): build durable pg opt-out store (fail-closed if no DATABASE_URL), api.registerChannel, api.registerHttpRoute('/twilio/sms') → createSmsWebhookHandler; onInbound runs handleInboundCompliance FIRST (STOP/START/HELP reply via guardedSendSms, no agent) else routeInboundToAgent (buildAgentPeerSessionKey agent:main:sms:direct:<e164> + minimal MsgContext → dispatchInboundMessageWithDispatcher, agent reply delivered via opt-out-guarded send); gateway_stop closes the pool. webhook.ts: handler now resolves config lazily (503 when inert) — honors unprovisioned/changed config. Deep core imports (dispatch/session-key/MsgContext) per established twitch/syntropy-mcp precedent. Full twilio suite 60/60; tsgo+lint+fmt clean. Remaining: 5e manifest (uiHints) + slice 6 integration/rails tests.

Generated-With: Claude Code
Co-Authored-By: cto <[email protected]>
Co-Authored-By: Claude <[email protected]>
… + rails/integration tests (PHI-deny, register wiring)

5e: openclaw.plugin.json uiHints — apiKeySecret+authToken marked sensitive (masked in config UI), field labels/help/placeholders. 6: rails.test.ts — (a) PHI boundary: isThirdPartyChannel('sms')===true (sms can never be phiApproved via plain config; B5 deny-unknown), (b) register() wiring integration: fake api confirms registerChannel(id 'sms') + registerHttpRoute('/twilio/sms') + gateway_stop cleanup, forcing the no-DB branch for determinism. Signature-negative + opt-out-suppression rails already covered in webhook/compliance suites. Full twilio suite 62/62; tsgo+lint+fmt clean. B-Twilio-1 feature-complete.

Generated-With: Claude Code
Co-Authored-By: cto <[email protected]>
Co-Authored-By: Claude <[email protected]>
…ession (CRITICAL), webhook DoS cap, inbound-policy enforcement + coverage

Addresses all confirmed 4-reviewer QG findings.
CRITICAL (code+test+security): STOP/HELP compliance acks were suppressed by guardedSendSms (which re-checks isOptedOut after optOut persists) → the CTIA/TCPA-mandated confirmation never sent. Fix: extract testable inbound.ts (handleInboundSms) from index.ts's inline closures; compliance acks now go via UNGUARDED sendSms (mandated replies exempt from the opt-out gate); agent-generated replies stay opt-out-guarded (createSmsReplyDeliver).
MEDIUM (security): readBody had no size cap on the unauthenticated webhook (CWE-770 OOM DoS) → MAX_INBOUND_BODY_BYTES=64KB, 413 on Content-Length over cap AND on streamed overflow.
MEDIUM (design): inbound policy (disabled/allowlist/pairing) was declared but never enforced → inboundAllowed() gates passthrough (STOP always honored first regardless).
LOW: send.ts success-path JSON.parse guarded (never-throws contract); outbound.ts uses SMS_CHANNEL_ID not literal.
Coverage (test): +18 tests → inbound.test.ts (STOP-ack-sends-despite-optout ★, HELP-to-opted-out, compliance-first ordering, policy enforcement, pin-#1 at the agent-reply deliver), webhook-handler.test.ts (503 inert / 200→onInbound / forged→no-onInbound / 413), send missing-sid + non-JSON, classify blank-body, strengthened outbound secret-leak assertion. Full twilio suite 80/80; tsgo+lint+fmt clean.

Generated-With: Claude Code
Co-Authored-By: cto <[email protected]>
Co-Authored-By: Claude <[email protected]>
@coderabbitai

coderabbitai Bot commented Jul 15, 2026 •

Copy link
Copy Markdown

Review Change Stack

Caution

Review failed

The pull request is closed.

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: ASSERTIVE

Plan: Pro Plus

Run ID: 2c9fbd6f-7064-4b24-a803-355ca50dfd9b

📥 Commits

Reviewing files that changed from the base of the PR and between 71f40ab and 26f9e68.

⛔ Files ignored due to path filters (1)
  • pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml
📒 Files selected for processing (24)
  • extensions/twilio/openclaw.plugin.json
  • extensions/twilio/package.json
  • extensions/twilio/src/accounts.test.ts
  • extensions/twilio/src/accounts.ts
  • extensions/twilio/src/channel.test.ts
  • extensions/twilio/src/channel.ts
  • extensions/twilio/src/compliance.test.ts
  • extensions/twilio/src/compliance.ts
  • extensions/twilio/src/config.test.ts
  • extensions/twilio/src/config.ts
  • extensions/twilio/src/db.ts
  • extensions/twilio/src/inbound.test.ts
  • extensions/twilio/src/inbound.ts
  • extensions/twilio/src/index.ts
  • extensions/twilio/src/optout-store.test.ts
  • extensions/twilio/src/optout-store.ts
  • extensions/twilio/src/outbound.test.ts
  • extensions/twilio/src/outbound.ts
  • extensions/twilio/src/rails.test.ts
  • extensions/twilio/src/send.test.ts
  • extensions/twilio/src/send.ts
  • extensions/twilio/src/webhook-handler.test.ts
  • extensions/twilio/src/webhook.test.ts
  • extensions/twilio/src/webhook.ts

Disabled knowledge base sources:

  • Linear integration is disabled

You can enable these sources in your CodeRabbit configuration.


📝 Walkthrough

Walkthrough

Adds a complete Twilio SMS extension with strict credential resolution, REST sending, signed inbound webhooks, TCPA opt-out enforcement, Postgres persistence, inbound policy controls, OpenClaw channel registration, and comprehensive tests.

Changes

Twilio SMS channel

Layer / File(s) Summary
Configuration and account resolution
extensions/twilio/openclaw.plugin.json, extensions/twilio/package.json, extensions/twilio/src/config.ts, extensions/twilio/src/accounts.ts, extensions/twilio/src/*test.ts
Defines plugin metadata, strict E.164 and credential schemas, environment fallback, fail-closed resolution, and a single default SMS account.
Opt-out persistence
extensions/twilio/src/db.ts, extensions/twilio/src/optout-store.ts, extensions/twilio/src/optout-store.test.ts
Adds a bounded Postgres client and durable lp_sms_optouts storage with opt-in, opt-out, and lookup operations.
Compliance-first inbound processing
extensions/twilio/src/compliance.ts, extensions/twilio/src/inbound.ts, extensions/twilio/src/compliance.test.ts, extensions/twilio/src/inbound.test.ts
Classifies STOP, START, and HELP messages, applies inbound policies, sends mandated acknowledgements, and routes permitted messages to the agent with guarded replies.
Twilio REST outbound delivery
extensions/twilio/src/send.ts, extensions/twilio/src/outbound.ts, extensions/twilio/src/send.test.ts, extensions/twilio/src/outbound.test.ts
Sends form-encoded SMS through scoped API-key authentication, returns structured failures, suppresses opted-out recipients, and preserves retry behavior for failed sends.
Inbound webhook security
extensions/twilio/src/webhook.ts, extensions/twilio/src/webhook.test.ts, extensions/twilio/src/webhook-handler.test.ts
Validates POST requests and Twilio signatures, limits request size, parses inbound SMS fields, and returns 503, 413, 403, 400, or 200 responses by decision outcome.
Plugin registration and channel wiring
extensions/twilio/src/channel.ts, extensions/twilio/src/index.ts, extensions/twilio/src/channel.test.ts, extensions/twilio/src/rails.test.ts
Registers the SMS channel, /twilio/sms route, Postgres-backed opt-out store, and gateway shutdown cleanup while declaring SMS capabilities and third-party channel metadata.

Estimated code review effort: 4 (Complex) | ~60 minutes

Sequence Diagram(s)

sequenceDiagram
  participant Twilio
  participant WebhookHandler
  participant InboundPipeline
  participant OptOutStore
  participant Agent
  participant TwilioREST
  Twilio->>WebhookHandler: Signed SMS webhook
  WebhookHandler->>InboundPipeline: Validated inbound message
  InboundPipeline->>OptOutStore: Apply STOP or START state
  InboundPipeline->>TwilioREST: Send compliance acknowledgement
  InboundPipeline->>Agent: Dispatch permitted message
  Agent->>OptOutStore: Check recipient suppression
  Agent->>TwilioREST: Send guarded reply
Loading

Poem

I’m a rabbit hopping through SMS code,
With STOP and START on the compliance road.
Twilio whispers, signed and bright,
Postgres guards each opt-out right.
Send safe messages—then nibble a byte! 🐇

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch mangyinm/b-twilio-1-sms-adapter

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@github-actions

Copy link
Copy Markdown

⚠️ Formal models conformance drift detected

The formal models extracted constants (generated/*) do not match this openclaw PR.

This check is informational (not blocking merges yet).
See the formal-models-conformance-drift artifact for the diff.

If this change is intentional, follow up by updating the formal models repo or regenerating the extracted artifacts there.

@supmo668
supmo668 merged commit 26961d0 into main Jul 15, 2026
21 of 27 checks passed
@supmo668
supmo668 deleted the mangyinm/b-twilio-1-sms-adapter branch July 15, 2026 04:13
supmo668 added a commit that referenced this pull request Aug 24, 2026
…able, not credential-absence

The SMS ruling took a capability out of scope but did not remove the code: B-Twilio-1 is landed (PR #68, extensions/twilio in-tree). The ruling ORPHANED a shipped transport surface, and that surface was inert on staging ONLY because no channel credentials existed — inert by accident, which activates the moment anyone provisions credentials for an unrelated reason.

register() now refuses before ANY wiring unless pluginConfig.enableDespiteSmsOutOfScopeRuling is set. Not a runtime check after setup, a refusal ahead of it.

THE FLAG NAME IS THE ACKNOWLEDGEMENT: enabling requires literally writing 'DespiteSmsOutOfScopeRuling' into config. A comment can be read past; a config key cannot be set without stating what you are overriding, and it surfaces in whatever diff turns it on. You cannot enable this absent-mindedly, which was the only failure mode actually live.

The basis lives AT the gate, including the STRUCTURAL death: SMS is unpairable because pairing binds channel='sms' via an allowlist the principal declined to fund, so an SMS onboarding path cannot authenticate regardless of preference. Structural death outranks preference and stops the question reopening on taste.

RED ARM — the one a labelled disable normally never gets: full valid Twilio credentials provisioned in the test environment, register() driven, result zero channels, zero routes, the labelled refusal. It exercises exactly the accident the disable exists to prevent. A disable that has never refused a live credential is a claim; one that has is a control.

Not deleted, deliberately: retirement is a larger call than a disable, and an explicit labelled disable is reversible and honest where deletion is neither.

Verified before landing: 1 commit, 3 files, +138/-1, off origin/main with main 0 ahead. Job-level green, zero failures. 93/93 twilio, tsgo 0.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant