@crvouga/mockingbird-service-twilio

中文文档
3.11.0发布于 2026/11/11MITTypeScriptES Module构建来源已验证近 30 天下载 1.5万

Stateful emulator of Twilio Verify, Lookup v2, Messaging and Recordings on one port, with signed inbound SMS and voice webhooks (Mockingbird service contract).

原始使用文档
文档目录10 节
  1. Install
  2. Usage
  3. Pointing the app at it (G-T1)
  4. Reading the OTP in a test
  5. Routes
  6. Webhooks (S8.4)
  7. Admin (beyond the standard contract)
  8. Namespaces
  9. Deliberately not modelled
  10. API

@crvouga/mockingbird-service-twilio

Local emulators. Real API contracts. Part of Mockingbird.

Stateful emulator of Twilio for test suites: Lookup v2 phone validation, Verify v2 phone OTP (with the real state machine: wrong codes, attempt limits, 10-minute expiry on the emulator clock), Programmable Messaging with an outbox, and call Recordings. It also signs and posts Twilio's inbound SMS and voice webhooks to your app. Every product is served on one port. A suite reads the OTP from the admin plane instead of bypassing verification (E2E_OTP_BYPASS_*).

  • Operation coverage: SUPPORT.md
  • The contract (openapi.yaml) is trimmed from Twilio's API reference to what our consumer calls. Lookup v2 responses are checked byte for byte against the live API (scripts/parity.ts, recorded in test/fixtures/lookups.live.json).

Install

npm install -D @crvouga/mockingbird-service-twilio

ESM only. Node >= 22 or Bun >= 1.2. Lookup validation uses libphonenumber-js (Twilio's Lookup is libphonenumber). Serve it with npx mockingbird-twilio serve, with createServer from ./server (Node), or with createRuntime in any Fetch server.

Usage

npx mockingbird-twilio serve --port 8798 \
  --app-url http://127.0.0.1:3000 \
  --public-base-url "$TWILIO_VOICE_WEBHOOK_BASE_URL" \
  --account-sid "$TWILIO_ACCOUNT_SID" --auth-token "$TWILIO_AUTH_TOKEN" \
  --caller-id "$TWILIO_VOICE_CALLER_ID"

Pointing the app at it (G-T1)

twilio-node builds a host for each product (api.twilio.com, verify.twilio.com, lookups.twilio.com). The emulator takes that host as the first path segment: {emulator}/api/2010-04-01/…, {emulator}/verify/v2/…, {emulator}/lookups/v2/…. Pass every new Twilio(...) an httpClient that rewrites the URL. twilioMockUrl does the rewrite:

import twilio from "twilio"
import { twilioMockUrl } from "@crvouga/mockingbird-service-twilio"
import { createServer } from "@crvouga/mockingbird-service-twilio/server"

const server = await createServer() // or process.env.TWILIO_API_BASE_URL, e.g. http://127.0.0.1:8798

type RequestOptions = Parameters<twilio.RequestClient["request"]>[0]

/** https://verify.twilio.com/v2/Services/VA…/Verifications → {base}/verify/v2/Services/VA…/Verifications */
class MockRequestClient extends twilio.RequestClient {
  override request(opts: RequestOptions): Promise<never> {
    const uri = twilioMockUrl(opts.uri, server.url)
    return super.request({ ...opts, uri }) as Promise<never>
  }
}

// The app's own Twilio client. Only its HTTP client changes.
const client = twilio("AC00000000000000000000000000000000", "fixture-token", {
  httpClient: new MockRequestClient(),
})
const lookup = await client.lookups.v2.phoneNumbers("+12025550123").fetch()
// lookup.valid === true, lookup.nationalFormat === "(202) 555-0123"
await server.close()

The example type-checks with twilio 5.13.1 or later; 5.10.0 runs it the same way, but its exports map hides the typings from moduleResolution: nodenext.

The emulator also routes by the Host header. A request that reaches it as lookups.twilio.com (through a DNS override or a proxy) and has no prefix is served as /lookups/…. The recording adapter's raw fetch of https://api.twilio.com/2010-04-01/… becomes twilioMockUrl(url, TWILIO_API_BASE_URL). RecordingUrl in webhooks keeps the canonical https://api.twilio.com form that the adapter checks.

Reading the OTP in a test

import twilio from "twilio"
import { twilioMockUrl } from "@crvouga/mockingbird-service-twilio"
import { createServer } from "@crvouga/mockingbird-service-twilio/server"

// Test setup: the emulator, and the app's Twilio client pointed at it as above.
const server = await createServer()
type RequestOptions = Parameters<twilio.RequestClient["request"]>[0]
class MockRequestClient extends twilio.RequestClient {
  override request(opts: RequestOptions): Promise<never> {
    const uri = twilioMockUrl(opts.uri, server.url)
    return super.request({ ...opts, uri }) as Promise<never>
  }
}
const client = twilio("AC00000000000000000000000000000000", "fixture-token", {
  httpClient: new MockRequestClient(),
})
const verify = client.verify.v2.services("VA00000000000000000000000000000000")

// The app sends the code.
const verification = await verify.verifications.create({ to: "+12025550123", channel: "sms" })

// The test reads it from the admin plane, the way a user reads the SMS.
const latest = await fetch(`${server.url}/__admin/verify/+12025550123/latest`)
const { code } = (await latest.json()) as { code: string; sid: string; status: string }

// The app checks it.
const check = await verify.verificationChecks.create({ verificationSid: verification.sid, code })
// check.status === "approved"
await server.close()

Routes

RouteBehaviour
GET /lookups/v2/PhoneNumbers/{PhoneNumber}Validates the number the way the live API does (libphonenumber): valid, validation_errors (TOO_SHORT, TOO_LONG, INVALID_BUT_POSSIBLE, INVALID_COUNTRY_CODE, INVALID_LENGTH, NOT_A_NUMBER), phone_number, national_format, calling_country_code, country_code, url. Every data package is null. A national number with no CountryCode must be a valid US number, otherwise the answer is INVALID_COUNTRY_CODE. Fictional 555-01xx numbers are valid.
POST /verify/v2/Services/{VA}/VerificationsTo (valid E.164, or an email for Channel=email), Channel, optional CustomCode. Creates a VE… verification with a 6-digit code (or fixedCode). Sending again to the same pending verification keeps its sid and code and adds a send_code_attempts entry. The 6th send to one number within 10 minutes is 429 60203. A bad To is 400 60200. An unknown service sid (not VA + 32 hex) is 404 20404.
POST /verify/v2/Services/{VA}/VerificationCheckCode plus VerificationSid or To. The right code returns 200 approved, valid: true. A wrong code returns 200 pending and counts an attempt. The 6th check is 429 60202. A missing, approved, canceled or expired (10 minutes on the emulator clock) verification is 404 20404.
GET / POST /verify/v2/Services/{VA}/Verifications/{VE}Fetches a verification, or sets Status=canceled|approved on one.
POST /api/2010-04-01/Accounts/{AC}/Messages.jsonTo, Body or MediaUrl, and From or MessagingServiceSid. Returns 201 with an SM… sid (MM… with media) and RFC 2822 dates. MessagingServiceSid alone is status accepted, from: null, num_segments: "0" (a sender is not chosen yet). From alone is status queued. Both are kept and the status is queued (Twilio queues on a specific sender). There is no idempotency key: the same body creates another sid. Errors: 21604 (no To), 21602 (no Body), 21603 (no From), 21211 (invalid To), 21617 (over 1600 characters). The message is recorded in the outbox.
GET /api/2010-04-01/Accounts/{AC}/Messages/{SM}.jsonReads a message back.
GET /api/2010-04-01/Accounts/{AC}/Messages.jsonNewest-first Message resources for that account. PageSize defaults to 50 (1–1000), PageToken follows next_page_uri/previous_page_uri; Page is client state. Links keep the vendor path without /api, so apply the normal product-prefix rewrite. To and From filter stored resources.
GET /api/2010-04-01/Accounts/{AC}/Recordings/{RE}.wavThe recording as a RIFF WAV. With RequestedChannels=2 you get both channels. Otherwise a dual-channel recording is mixed down to mono, as Twilio does.
GET / DELETE /api/2010-04-01/Accounts/{AC}/Recordings/{RE}.jsonMetadata, or a delete (204; a second delete is 404, which our consumer tolerates).

Errors use Twilio's body, {code, message, more_info, status}, with X-Twilio-Error-Code. Authentication is HTTP Basic: an AC… (or SK…) username and a non-empty password. With accounts (or --account-sid plus --auth-token) only those pairs are accepted. A missing or wrong credential is 401 20003. For a wrong token the message matches the live one: authentication failed, auth token is not valid for account AC….

Webhooks (S8.4)

The emulator signs inbound webhooks with X-Twilio-Signature. The signature is base64 HMAC-SHA1(auth token, public URL + sorted key+value params), the same computation as twilio.validateRequest. It signs against the public base URL the app is configured with (--public-base-url, i.e. TWILIO_VOICE_WEBHOOK_BASE_URL), not the localhost address it posts to. Twilio does not retry these webhooks, so the emulator sends each one once.

TriggerPosts toPayload
POST /__admin/inbound/sms {from, body, to?, media?, messageSid?, params?}/messaging/inbound/smsMessageSid/SmsSid (SM…, or MM… with media), AccountSid, From, To (default: --caller-id), Body, NumMedia, MediaUrl{i}, MediaContentType{i}, SmsStatus=received, …
POST /__admin/voice/twiml/admin/messaging/voice/twimlCallSid, From=client:<uuid>, To, CallStatus=ringing plus the body's fields (e.g. conversationId)
POST /__admin/voice/disclosure/admin/messaging/voice/disclosureCallSid, CallStatus=in-progress
POST /__admin/voice/status/admin/messaging/voice/statusCallSid, CallStatus=completed, CallDuration
POST /__admin/voice/recording/admin/messaging/voice/recordingRecordingSid, canonical RecordingUrl, RecordingStatus=completed, RecordingDuration, RecordingChannels=2. It also stores a dual-channel WAV so the download works.

Every body field overrides a default. The admin answer lists each delivery with the app's status and response body (e.g. <Response/>). Event types for PUT /__admin/webhook-endpoints filters are sms.inbound and voice.{twiml,disclosure,status,recording}.

Admin (beyond the standard contract)

RouteEffect
GET /__admin/verify/:e164/latest{code, sid, status, to, channel, serviceSid, attempts, sendAttempts, createdAt, expiresAt} for the newest verification to that number. This is how a test reads the OTP.
GET / PUT /__admin/verify{fixedCode: "000000" | null, ttlSeconds, maxCheckAttempts, maxSendAttempts, sendWindowSeconds} for the calling namespace.
PUT /__admin/lookups/:e164{valid, validationErrors?} overrides Lookup for that number (Verify and Messages use it too). DELETE removes the override.
PUT /__admin/recordings/:REUploads a recording: a raw WAV body (content-type: audio/wav), {"wavBase64": …}, or {channels?, seconds?} for a synthesised 8 kHz 16-bit tone.
GET /__admin/outbox?to=&since=&kind=sms|verifyEverything "sent": SMS ({to, from, messagingServiceSid, body, sid}) and every Verify code delivery ({code, body: "Your verification code is: …"}).
GET /__admin/messagesMessage resources in the namespace.

Fault presets (POST /__admin/faults {"preset": "<name>", "count"?: n, "latencyMs"?: n}; list them with GET /__admin/faults/presets, and read hits / remaining from GET /__admin/faults). A preset applies to the calling namespace. verify_5xx (start and check answer 500 20500), sms_drop_before_accept (Messages.json drops the socket before a Message exists; still registered as sms_socket_drop), sms_accepted_then_socket_drop (the Message and outbox entry are stored, then the socket closes before any response bytes), sms_4xx (400 21211), sms_429 (429 20429 with Retry-After: 1), sms_5xx (500 20500, no Retry-After), sms_missing_sid (201 whose body omits sid; the outbox still has the message), lookup_5xx (503 20503; the EMR fails open), webhook_duplicate, webhook_drop. A 503 on Messages.json is the same envelope with code 20503 and Retry-After (a standard fault, not a separate preset). None of the status faults store a message.

Namespaces

The Twilio SDK cannot add headers, so a suite picks a namespace by AccountSid: PUT /__admin/credentials {"credentials": {"<TWILIO_ACCOUNT_SID>": "<namespace>"}}. A namespace can also come from the x-mockingbird-namespace header or a /__admin/ns/<name> prefix on the base URL (twilioMockUrl keeps the prefix).

Deliberately not modelled

  • Delivery: messages stay queued/accepted, no status callbacks are sent (our consumer sets no statusCallback), and no voice calls, conferences or media streams happen.
  • Message collection DateSent filters (messages are never sent by the emulator).
  • Paid Lookup data packages (Fields=line_type_intelligence, caller_name, …) are always null.
  • Verify channels other than SMS are accepted and recorded, but nothing is delivered. Verify Service configuration (code length, friendly name, rate-limit buckets) is global, set with PUT /__admin/verify.
  • Accounts: any AC… sid is its own account, and the path's {AccountSid} is not cross-checked against the credential.
  • libphonenumber-js drops "local only" lengths from its metadata. The emulator restores them for NANP (7) and GB (4–6, 8), which is enough for the fictional numbers tests use. Other countries may answer TOO_SHORT where Twilio answers INVALID_BUT_POSSIBLE.

API

ExportKindDescription
TwilioAPIclassThe in-process emulator: fetch(request), reset(), latestVerification(to), resolveLookup(raw, country?), setLookup(e164, override), putRecording(sid, input), outbox(), messages(). Options: sqlite, now, namespace, verify, accounts.
createRuntimefunctionThe emulator with the full service contract (health, admin, namespaces, credentials, presets, outbox, webhooks), plus host routing. Options: app: {url, publicBaseUrl?, authToken, accountSid?, callerId?, messagingServiceSid?}, verify, accounts, retryDelaysMs, fetch, clock, seed, adminKey, onLog. The returned runtime also has inboundSms(input) and voiceWebhook(kind, params).
TWILIO_PRESETSobjectEvery named fault preset.
TWILIO_WEBHOOK_EVENTSobjectWebhook event type → the app path it posts to.
twilioMockUrlfunctionRewrites an upstream https://<product>.twilio.com/… URL onto an emulator base URL (for the G-T1 httpClient).
TWILIO_PRODUCTSarrayThe product prefixes served: api, verify, lookups.
lookupfunctionLookup v2 validation of a raw input (optionally in a CountryCode region).
e164Keyfunction+ and digits: the key that admin overrides use.
twilioErrorfunctionA Twilio error response, {code, message, more_info, status}.
DEFAULT_VERIFY_SETTINGSobjectVerify defaults: 10-minute expiry, 5 checks, 5 sends per 10 minutes, random codes.
DEFAULT_ACCOUNT_SIDstringThe account used when the credential is an API key.
TWILIO_NAMESPACEstringThe service name, "twilio".
synthesizeWav, readWav, mixDownToMonofunctionsMake a PCM WAV, read its format, mix a multi-channel WAV down to mono.
document, operationIds, supportedOperationIdsvaluesThe vendored OpenAPI contract and its operation ids.
createServer, serveTarget, DEFAULT_PORT (./server)NodeServe over node:http; the serve CLI target; port 8798.

Part of mockingbird.

版本与发布记录

@crvouga/mockingbird-service-twilio 共发布 38 个版本,首次发布于 2026/09/23;过去 12 个月发布了 38 个版本。最新版本附带 npm provenance 构建来源证明,可追溯到公开的 CI 构建记录。

版本发布日期距今
3.11.0latest2026/11/11今天
3.10.52026/11/038 天前
3.10.42026/11/038 天前
3.10.32026/11/038 天前
3.10.22026/11/038 天前
3.10.12026/11/038 天前

关于 @crvouga/mockingbird-service-twilio 的常见问题

@crvouga/mockingbird-service-twilio 是什么?

Stateful emulator of Twilio Verify, Lookup v2, Messaging and Recordings on one port, with signed inbound SMS and voice webhooks (Mockingbird service contract).

如何安装 @crvouga/mockingbird-service-twilio?

在项目目录运行 npm install @crvouga/mockingbird-service-twilio,或使用 pnpm add / yarn add / bun add。它还提供命令行工具 mockingbird-twilio,可以用 npx mockingbird-twilio 直接运行。

@crvouga/mockingbird-service-twilio 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@crvouga/mockingbird-service-twilio 支持 ESM 还是 CommonJS?

以 ES Module 形式发布,推荐使用 import 引入。在 CommonJS 项目中,Node.js 20.19+ / 22.12+ 可以直接 require() 不含顶层 await 的 ES Module,更早的版本需要改用动态 import()。

@crvouga/mockingbird-service-twilio 可以商用吗?

@crvouga/mockingbird-service-twilio 使用 MIT 许可。宽松许可:允许商业使用、修改和再分发,通常只需在分发时保留原版权与许可声明。以上为概括,不构成法律意见,请以许可原文为准。

@crvouga/mockingbird-service-twilio 的下载量有多少?

根据 npm 官方下载统计,@crvouga/mockingbird-service-twilio 在 2026/10/11 – 2026/11/09 这 30 天内被下载 15,461 次,日均约 515 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@crvouga/mockingbird-service-twilio 还在维护吗?

最新版本 3.11.0 发布于 2026/11/11(今天);至今共发布 38 个版本,其中过去 12 个月发布了 38 个;首次发布于 2026/09/23。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。