From e51f0bcb38a4af6330bff9fc604bc177bb311c2c Mon Sep 17 00:00:00 2001 From: Tim Walsh Date: Fri, 9 Oct 2026 17:33:48 -0700 Subject: [PATCH] Implement Phase 6: guides, compliance fixes, credential checks, release prep Add guides for getting started, migrating from twilio-ruby, migrating from Noticed's Twilio method, a compliance primer, and writing a provider, plus a test that every setting, constant, and generator they name exists. Compliance research changed defaults: HELP replies name a support contact (support_contact), the opt-out confirmation follows CTIA wording, keywords ignore internal spaces so "opt out" matches, and opt_out_all_scopes prepares for the FCC revoke-all provision. Fix the Noticed adapter reusing Noticed's own wait/queue/priority keys, which delayed a message twice; its job options are now sms_queue and sms_priority. Implement Smswire.verify_credentials! for Twilio, Telnyx, and Vonage. Settle open decisions 4 to 6 as implemented, list known limitations, and add RELEASING.md and a tag-triggered trusted-publishing workflow. The version is unchanged; publishing 1.0 is left to the maintainer. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01L5SuBiSMN4r9qr5CXbKkHV --- .github/workflows/release.yml | 25 +++ CHANGELOG.md | 14 ++ README.md | 13 +- RELEASING.md | 47 ++++++ docs/SPEC.md | 40 ++++- docs/guides/compliance.md | 124 ++++++++++++++ docs/guides/getting-started.md | 154 ++++++++++++++++++ docs/guides/migrating-from-noticed-twilio.md | 105 ++++++++++++ docs/guides/migrating-from-twilio-ruby.md | 146 +++++++++++++++++ docs/guides/writing-a-provider.md | 126 ++++++++++++++ .../install/templates/initializer.rb.tt | 7 +- lib/smswire.rb | 6 + lib/smswire/configuration.rb | 27 ++- lib/smswire/http.rb | 13 ++ lib/smswire/keywords.rb | 11 +- lib/smswire/noticed_delivery_method.rb | 8 +- lib/smswire/providers/base.rb | 16 ++ lib/smswire/providers/log.rb | 2 + lib/smswire/providers/null.rb | 2 + lib/smswire/providers/telnyx.rb | 6 + lib/smswire/providers/test.rb | 2 + lib/smswire/providers/twilio.rb | 5 + lib/smswire/providers/vonage.rb | 7 + smswire.gemspec | 2 +- test/documentation_test.rb | 47 ++++++ test/inbound_test.rb | 33 +++- test/noticed_test.rb | 27 ++- test/verify_credentials_test.rb | 36 ++++ 28 files changed, 1023 insertions(+), 28 deletions(-) create mode 100644 .github/workflows/release.yml create mode 100644 RELEASING.md create mode 100644 docs/guides/compliance.md create mode 100644 docs/guides/getting-started.md create mode 100644 docs/guides/migrating-from-noticed-twilio.md create mode 100644 docs/guides/migrating-from-twilio-ruby.md create mode 100644 docs/guides/writing-a-provider.md create mode 100644 test/documentation_test.rb create mode 100644 test/verify_credentials_test.rb diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml new file mode 100644 index 0000000..7e4b13c --- /dev/null +++ b/.github/workflows/release.yml @@ -0,0 +1,25 @@ +name: Release + +on: + push: + tags: ["v*"] + +jobs: + release: + runs-on: ubuntu-latest + environment: rubygems + permissions: + contents: write + id-token: write + steps: + - uses: actions/checkout@v4 + - uses: ruby/setup-ruby@v1 + with: + ruby-version: "3.4" + bundler-cache: true + - run: bundle exec rake test + - name: Check the tag matches the gem version + run: | + version=$(ruby -r ./lib/smswire/version -e 'print Smswire::VERSION') + test "v${version}" = "${GITHUB_REF_NAME}" || { echo "Tag ${GITHUB_REF_NAME} does not match version ${version}"; exit 1; } + - uses: rubygems/release-gem@v1 diff --git a/CHANGELOG.md b/CHANGELOG.md index 1e3276c..a0b68c3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,20 @@ All notable changes to this project are documented here. The format follows ### Added +- Guides: getting started, migrating from twilio-ruby, migrating from + Noticed's Twilio method, compliance primer, and writing a provider. +- `Smswire.verify_credentials!` with checks for Twilio, Telnyx, and Vonage. +- `support_contact` for HELP replies and `opt_out_all_scopes`. +- Release workflow publishing to RubyGems with trusted publishing. + +### Changed + +- Keyword replies follow CTIA guidance: the opt-out confirmation says no + further messages will be sent, and HELP names a support contact. +- Keywords ignore internal spaces and hyphens, so "opt out" and "stop all" match. +- Noticed adapter job options are `sms_queue` and `sms_priority`, so Noticed's + own `wait` no longer delays a message twice. + - Telnyx adapter (Messaging API v2) with Ed25519 webhook verification. - Vonage adapter (SMS API) with signed webhook verification for `md5hash` and HMAC methods. diff --git a/README.md b/README.md index 4c7d27c..73bd158 100644 --- a/README.md +++ b/README.md @@ -10,8 +10,17 @@ consent and STOP / HELP / START handling, quiet hours, previews, and a [Noticed](https://github.com/excid3/noticed) delivery method are included. See the [specification](docs/SPEC.md) for the full design. -**Status:** pre-release. Phases 1 to 5 of the spec are implemented; the -published `0.0.1.pre` gem only reserves the name. +**Status:** pre-release. All six phases of the spec are implemented; the +published `0.0.1.pre` gem only reserves the name. See +[RELEASING.md](RELEASING.md) for the release steps. + +## Guides + +- [Getting started](docs/guides/getting-started.md) +- [Migrating from direct twilio-ruby calls](docs/guides/migrating-from-twilio-ruby.md) +- [Migrating from Noticed's Twilio delivery method](docs/guides/migrating-from-noticed-twilio.md) +- [Compliance primer](docs/guides/compliance.md) +- [Writing a provider adapter](docs/guides/writing-a-provider.md) ## Requirements diff --git a/RELEASING.md b/RELEASING.md new file mode 100644 index 0000000..d307ee1 --- /dev/null +++ b/RELEASING.md @@ -0,0 +1,47 @@ +# Releasing + +Releases publish to RubyGems from GitHub Actions with +[trusted publishing](https://guides.rubygems.org/trusted-publishing/), so no +API key or one-time code is stored anywhere. The gem requires MFA for +manual pushes. + +## One-time setup + +1. On rubygems.org, open the `smswire` gem, then **Trusted publishers**, and + add a GitHub Actions publisher: + - Repository: `timimsms/smswire` + - Workflow filename: `release.yml` + - Environment: `rubygems` +2. In the GitHub repository settings, create an environment named + `rubygems`. Add required reviewers if releases should need approval. + +## Before 1.0 + +- Merge the phase pull requests in order, so `main` holds the release. +- Confirm open decisions 4 to 6 in `docs/SPEC.md`. +- Review the known limitations listed under Phase 6 in `docs/SPEC.md`. +- Try the getting-started guide in a new Rails app against a real provider + account, including a STOP reply and a delivery status callback. + +## Each release + +1. Make sure CI is green on `main`. +2. Update `lib/smswire/version.rb`. +3. In `CHANGELOG.md`, rename `[Unreleased]` to the version and the release + date, and start a new empty `[Unreleased]` section. +4. Commit: `Release vX.Y.Z`. +5. Tag and push: + + ``` + git tag -a vX.Y.Z -m "vX.Y.Z" + git push origin main vX.Y.Z + ``` + +6. The release workflow runs the tests, builds the gem, and pushes it to + RubyGems. Check https://rubygems.org/gems/smswire afterwards. +7. Create a GitHub release from the tag with the changelog section. + +## If a release goes wrong + +`gem yank smswire -v X.Y.Z` removes a version from installs, but the version +number cannot be reused. Fix forward with a patch release. diff --git a/docs/SPEC.md b/docs/SPEC.md index d5ba349..fb7632a 100644 --- a/docs/SPEC.md +++ b/docs/SPEC.md @@ -462,7 +462,8 @@ class OrderShippedNotifier < Noticed::Event config.messenger = "OrderMessenger" config.action = :shipped config.params = -> { {order: record} } - # Optional: config.category, config.wait, config.if + # Optional: config.args, config.kwargs, config.params, config.sms_queue; + # Noticed options such as config.wait and config.if apply to its own job end end ``` @@ -634,6 +635,23 @@ next. No phase includes a calendar estimate. - Guides: getting started, migrating from direct twilio-ruby, migrating from Noticed `twilio_messaging`, compliance primer, provider authoring. - `1.0.0` once the adapter contract and schema are considered stable. +- Status: guides written in `docs/guides`, with a test that every setting, + constant, and generator they name exists. Compliance research changed the + defaults: HELP replies include `support_contact`, the opt-out confirmation + follows CTIA wording, keywords ignore spaces ("opt out"), and + `opt_out_all_scopes` prepares for the FCC revoke-all provision. + `Smswire.verify_credentials!` from section 6.8 is implemented. Release + steps are in `RELEASING.md`; publishing 1.0 is left to the maintainer. + +### Known limitations at 1.0 + +- Free-text opt-outs ("please stop texting me") are stored but not acted on; + the compliance guide shows an observer for review. +- Rate limits can be exceeded briefly by concurrent sends. +- Vonage receipts for the second and later parts of a long message are + acknowledged but not matched to the delivery. +- Vonage uses the SMS API, not the newer Messages API, and has no MMS. +- Telnyx ignores `validity_period`. ## 10. Risks and mitigations @@ -647,7 +665,8 @@ next. No phase includes a calendar estimate. ## 11. Open decisions -Decisions 1 to 3 are settled. The rest should be settled before 1.0. +Decisions 1 to 3 are settled. Decisions 4 to 6 are proposed as settled in +Phase 6, matching the implementation; confirm them before tagging 1.0. 1. **Name.** `smswire` is recommended; `textable` and `smsable` are the fallbacks. Decide before the pre-release push. @@ -655,10 +674,13 @@ Decisions 1 to 3 are settled. The rest should be settled before 1.0. `categories: { otp: { store_body: false } }` as the shipped default. 3. **UUID vs. bigint** primary keys. Settled in Phase 2: the migration follows the app's generator `primary_key_type`, so both work without a choice here. -4. **Phone validation**: `phonelib` soft dependency vs. a vendored minimal - E.164 validator. -5. **Whether `deliver_now` should be allowed in production** or warn, given - Noticed's stance that inline delivery slows requests. Spec allows it; the - Noticed adapter always uses `deliver_later`. -6. **MMS in 1.0.** `media_urls` is on the message object; whether adapters - must support it for 1.0 is open. +4. **Phone validation.** Proposed: both. The built-in validator handles E.164 + input and North American national formats with no dependency; `phonelib` + is used automatically when it is in the bundle, for other regions. +5. **`deliver_now` in production.** Proposed: allowed without a warning. It + returns a `Result`, which is useful for interactive flows such as + verification codes. Guides recommend `deliver_later`, and the Noticed + adapter always uses it. +6. **MMS in 1.0.** Proposed: a capability, not a requirement. Twilio and + Telnyx send `media_urls`; Vonage's SMS API does not and does not declare + `:mms`. The contract does not require it. diff --git a/docs/guides/compliance.md b/docs/guides/compliance.md new file mode 100644 index 0000000..e7eee51 --- /dev/null +++ b/docs/guides/compliance.md @@ -0,0 +1,124 @@ +# Compliance primer + +This primer explains what Smswire does for SMS compliance, what it leaves to +you, and which settings matter. It summarizes US rules and industry +guidance as of 2026 and is not legal advice. Have counsel review your +messaging program. + +## The rules in brief + +- **TCPA and FCC rules** govern automated texts in the US. Marketing texts + need prior express written consent. Consumers may revoke consent by any + reasonable means, and since April 11, 2025 a revocation must be honored + within 10 days. One confirmation text is allowed after an opt-out; it must + not contain marketing and may ask the person to clarify what they want to + stop. +- **The FCC "revoke all" provision**, which makes an opt-out from one kind of + message apply to all of a sender's unrelated messages, is delayed to + January 31, 2027. +- **Quiet hours.** Federal rules restrict telemarketing outside 8am to 9pm in + the recipient's local time. Several states are stricter. +- **CTIA Messaging Principles and Best Practices** are what carriers enforce. + They expect opt-out keywords to work regardless of case or punctuation; one + confirmation after an opt-out and then silence; HELP replies that name the + brand and give a support contact; and consent specific to the program it + was collected for. +- **Carrier registration.** US long codes need 10DLC brand and campaign + registration. Toll-free numbers need verification. Unregistered traffic is + filtered or blocked. + +## What Smswire does + +| Requirement | Smswire | +|---|---| +| Honor STOP-type replies | STOP, STOPALL, UNSUBSCRIBE, CANCEL, END, QUIT, OPTOUT (or "opt out"), and REVOKE opt the number out immediately | +| One confirmation, no marketing | one opt-out reply through the `compliance` category; deduplication blocks repeats inside 10 minutes | +| HELP reply with brand and contact | HELP and INFO reply with `program_name` and `support_contact` | +| Re-subscribe | START, YES, and UNSTOP opt back in | +| Refuse sends to opted-out numbers | every category except `compliance` checks consent first | +| Marketing needs opt-in | `marketing` requires `opted_in` consent | +| Quiet hours | `marketing` waits outside 9pm to 8am, recipient time | +| Carrier opt-outs | a provider "recipient opted out" error records an opt-out | +| Evidence | consent rows keep source, timestamps, last keyword, and your metadata | + +## What you must do + +1. **Collect and record opt-in** before marketing. Store the evidence: + + ```ruby + Smswire::Consent.opt_in!(user.phone, source: :web_form, + metadata: {ip: request.remote_ip, form: "checkout", copy: SMS_TERMS, at: Time.current.iso8601}) + ``` + +2. **Set your program name and support contact.** + + ```ruby + config.program_name = "Acme Alerts" + config.support_contact = "help@acme.example" + ``` + + Without a contact, HELP replies omit it and Smswire logs a warning. + +3. **Route incoming messages to Smswire** at `/smswire/inbound/`. + Without this, STOP replies never reach your app. If your provider handles + opt-outs itself, such as Twilio Advanced Opt-Out, Smswire still records + them and skips its own reply. + +4. **Watch for free-text opt-outs.** Smswire matches keywords only when they + are the whole message. "Please stop texting me" is stored but not acted + on, yet it is a reasonable revocation. Review unmatched messages: + + ```ruby + class OptOutReview + def self.sms_received(message) + return if message.keyword + SupportTicket.create!(phone: message.from_number, body: message.body) if message.body.match?(/\b(stop|unsubscribe|remove me)\b/i) + end + end + Smswire.register_observer(OptOutReview) + ``` + +5. **Honor opt-outs from other channels.** When a customer opts out by email + or phone, call `Smswire::Consent.opt_out!(phone, source: :support)`. + +6. **Choose consent scopes deliberately.** By default STOP applies to the + `consent_scope` of the number that received it, so two programs on two + numbers keep separate consent. To make every STOP apply everywhere, as the + FCC revoke-all provision will require across a sender's messages, set: + + ```ruby + config.opt_out_all_scopes = true + ``` + +7. **Check your categories.** Anything promotional must use + `category: :marketing`. Transactional messages skip the opt-in + requirement, so mislabeling a promotion as transactional defeats the + checks. + +8. **Set time zones.** Quiet hours use `recipient.time_zone` when the + recipient object has one, and `config.default_time_zone` otherwise. + +9. **Register with the carriers** and keep your messages consistent with the + registered campaign: brand name in messages, opt-out instructions at least + periodically, and content matching the sample messages. + +## Settings reference + +| Setting | Default | Notes | +|---|---|---| +| `enforce_consent` | `true` | turn off only if another system owns consent | +| `categories` | see README | merged per key over the shipped rules | +| `keywords` | the lists above | add synonyms, such as `ARRET` | +| `keyword_replies` | CTIA-style replies | `%{program}` and `%{contact}` are replaced; `nil` sends no reply | +| `program_name` | the app name | | +| `support_contact` | none | phone, email, or URL | +| `opt_out_all_scopes` | `false` | STOP applies to every scope | +| `default_time_zone` | `Time.zone` | for quiet hours | + +## Sources + +- [FCC consent revocation order, FCC 24-24](https://docs.fcc.gov/public/attachments/FCC-24-24A1.pdf) +- [FCC revocation rule effective April 11, 2025 (JD Supra)](https://www.jdsupra.com/legalnews/fcc-s-tcpa-consent-revocation-rule-8022288/) +- [Revoke-all provision delayed to January 31, 2027 (Wiley)](https://www.wiley.law/alert-FCC-Extends-Limited-Waiver-for-Part-of-the-TCPA-Consent-Revocation-Rule) +- [CTIA Messaging Principles summary (Bird)](https://bird.com/explained/compliance/what-are-the-ctia-messaging-principles) +- [Vonage 10DLC traffic compliance](https://api.support.vonage.com/hc/en-us/articles/8443130026140-10DLC-Traffic-compliance) diff --git a/docs/guides/getting-started.md b/docs/guides/getting-started.md new file mode 100644 index 0000000..46a3957 --- /dev/null +++ b/docs/guides/getting-started.md @@ -0,0 +1,154 @@ +# Getting started + +This guide takes a Rails app from no SMS to a tested, previewable message +with delivery tracking. It assumes Rails 7.1 or newer and Ruby 3.2 or newer. + +## Install + +```ruby +# Gemfile +gem "smswire" +``` + +``` +bundle install +bin/rails generate smswire:install +bin/rails db:migrate +``` + +The install generator: + +- copies three tables: `smswire_deliveries`, `smswire_consents`, and + `smswire_inbound_messages`; +- writes `config/initializers/smswire.rb` and `app/messengers/application_messenger.rb`; +- mounts the engine at `/smswire` in `config/routes.rb`. + +Out of the box, development uses the `:log` provider, which writes each +message to the log, and tests use the `:test` provider, which records +messages in memory. Nothing is sent until you configure a real provider. + +## Configure a sender and a provider + +```ruby +# config/initializers/smswire.rb +Smswire.configure do |config| + config.default_provider = :twilio if Rails.env.production? + config.providers = { + twilio: { + account_sid: Rails.application.credentials.dig(:twilio, :account_sid), + auth_token: Rails.application.credentials.dig(:twilio, :auth_token) + } + } + config.senders = { + transactional: {number: "+15555550100"} + } + config.callbacks_url = "https://app.example.com/smswire" + config.program_name = "Acme" + config.support_contact = "help@acme.example" +end +``` + +Twilio credentials default to `Rails.application.credentials.twilio`, so the +`providers` entry can be omitted when the credentials file has `account_sid` +and `auth_token` under `twilio:`. Telnyx and Vonage work the same way under +`telnyx:` and `vonage:`. + +`callbacks_url` is the public URL of the engine mount. With it set, every +message asks the provider to post delivery status back, and each +`Smswire::Delivery` row moves from `pending` to `delivered` or `failed`. + +## Write a messenger + +``` +bin/rails generate smswire:messenger Order shipped +``` + +```ruby +# app/messengers/order_messenger.rb +class OrderMessenger < ApplicationMessenger + def shipped(user) + @order = params[:order] + text to: user + end +end +``` + +```erb +<%# app/views/order_messenger/shipped.text.erb %> +Order <%= @order.number %> has shipped. Track it: <%= order_url(@order) %> +``` + +`text to:` accepts an E.164 string or any object with `phone_number`. Use +`config.recipient_resolver` if your column is named differently. URL helpers +use `Rails.application.routes.default_url_options`, so set a host there. + +Send it: + +```ruby +OrderMessenger.with(order:).shipped(user).deliver_later +``` + +`deliver_later` is the right default. `deliver_now` runs the pipeline inline +and returns a `Smswire::Result`: + +```ruby +result = OrderMessenger.with(order:).shipped(user).deliver_now +result.status # :accepted, :failed, :duplicate, :rejected_opted_out, ... +result.delivery # the Smswire::Delivery row +``` + +## Preview it + +Open `http://localhost:3000/smswire/previews`. The generator wrote a preview +in `test/messengers/previews/order_messenger_preview.rb`; point it at real +records: + +```ruby +class OrderMessengerPreview < Smswire::Preview + def shipped + OrderMessenger.with(order: Order.last).shipped(User.first) + end +end +``` + +Each preview shows the message in a phone frame with its encoding, segment +count, and remaining characters, and names any character that forces UCS-2, +which cuts a segment from 160 characters to 70. The inbox at +`/smswire/inbox` shows what development sent and lets you simulate a reply +such as STOP. + +## Test it + +```ruby +class OrderTest < ActiveSupport::TestCase + include Smswire::TestHelper + + test "shipping texts the customer" do + assert_sms_delivered(to: users(:ada).phone_number, messenger: OrderMessenger, body: /has shipped/) do + orders(:one).ship! + end + end +end +``` + +Inside the block, `deliver_later` jobs are performed. RSpec users can +`require "smswire/rspec"` for `deliver_sms` and `have_enqueued_sms`. + +## Point the provider at the webhooks + +| Webhook | URL | +|---|---| +| Delivery status | sent automatically per message when `callbacks_url` is set | +| Incoming messages | `https://app.example.com/smswire/inbound/` | + +Incoming messages are needed for STOP, START, and HELP handling. Read the +[compliance primer](compliance.md) before sending marketing messages. + +## Before production + +- Set `config.default_provider` and real credentials. +- Run `Smswire.verify_credentials!` from a boot check or health endpoint. +- In staging, register `Smswire::Interceptors::Allowlist` so only your team's + numbers receive messages. +- Register your sender with the carriers: 10DLC brand and campaign + registration for US long codes, or toll-free verification. diff --git a/docs/guides/migrating-from-noticed-twilio.md b/docs/guides/migrating-from-noticed-twilio.md new file mode 100644 index 0000000..f2edf68 --- /dev/null +++ b/docs/guides/migrating-from-noticed-twilio.md @@ -0,0 +1,105 @@ +# Migrating from Noticed's Twilio delivery method + +Noticed is a good fit for notification inboxes and fan-out across channels. +Its `twilio_messaging` delivery method posts a message string to Twilio and +leaves templates, consent, retries, and delivery tracking to the app. +Smswire adds a `deliver_by :smswire` delivery method, so you keep Noticed +and move only the SMS channel. + +## Before + +```ruby +class OrderShippedNotifier < Noticed::Event + deliver_by :twilio_messaging do |config| + config.json = -> { + { + From: Rails.application.credentials.dig(:twilio, :phone_number), + To: recipient.phone_number, + Body: "Order #{params[:order].number} has shipped" + } + } + config.error_handler = ->(response) { ... } + end +end +``` + +## After + +```ruby +class OrderShippedNotifier < Noticed::Event + deliver_by :smswire do |config| + config.messenger = "OrderMessenger" + config.action = :shipped + end +end +``` + +```ruby +class OrderMessenger < ApplicationMessenger + # Called with the Noticed recipient. params holds the event params plus + # notification, record, and recipient. + def shipped(user) + @order = params[:order] + text to: user + end +end +``` + +```erb +<%# app/views/order_messenger/shipped.text.erb %> +Order <%= @order.number %> has shipped +``` + +Install Smswire first with the [getting started](getting-started.md) steps. +The delivery method loads automatically when Noticed is in the bundle. + +## Options + +| Option | Default | Use | +|---|---|---| +| `messenger` | required | class or class name | +| `action` | required | messenger action | +| `args` | `[recipient]` | positional arguments for the action | +| `kwargs` | `{}` | keyword arguments | +| `params` | the event params | the messenger's `params`, merged with `notification`, `record`, `recipient` | +| `sms_queue`, `sms_priority` | Smswire's defaults | queue and priority for `Smswire::DeliveryJob` | + +Noticed's own options, such as `if`, `unless`, `wait`, and `queue`, still +apply to the Noticed job. A `wait` delays the message once; Smswire does not +add a second delay. + +## Credentials + +Noticed reads `Rails.application.credentials.twilio`, and so does Smswire. +The `phone_number` key becomes a sender: + +```ruby +config.senders = {transactional: {number: Rails.application.credentials.dig(:twilio, :phone_number)}} +``` + +## Error handling + +`config.error_handler` received Twilio's 4xx response. With Smswire: + +- permanent errors become a `:failed` delivery with a reason, such as + `:invalid_number` or `:opted_out`; +- a 21610 opt-out also records the opt-out, so later sends are refused; +- 429 and 5xx errors are retried by `Smswire::DeliveryJob`. + +Use an observer for alerting; see the +[twilio-ruby guide](migrating-from-twilio-ruby.md#3-map-your-error-handling). + +## Joining notifications and deliveries + +Each `Smswire::Delivery` stores `noticed_notification_id` and +`noticed_event_id` in `metadata`, and `recipient` points at the Noticed +recipient when it is an Active Record model. + +## What you gain + +- Templates, previews, and test helpers for the SMS body. +- Delivery status from Twilio callbacks on every send. +- STOP / START / HELP handling and consent checks before sending. +- Quiet hours and rate limits per category. +- Deduplication and retries. +- The same code works with Telnyx or Vonage by changing the provider. diff --git a/docs/guides/migrating-from-twilio-ruby.md b/docs/guides/migrating-from-twilio-ruby.md new file mode 100644 index 0000000..cf7eafa --- /dev/null +++ b/docs/guides/migrating-from-twilio-ruby.md @@ -0,0 +1,146 @@ +# Migrating from direct twilio-ruby calls + +Many apps send SMS by calling the Twilio SDK from models, jobs, or service +objects. This guide moves that code onto Smswire one message at a time. +Both can run side by side during the move. + +## What changes + +| Before | After | +|---|---| +| `client.messages.create(from:, to:, body:)` | a messenger action plus `deliver_later` | +| bodies built in Ruby strings | `.text.erb` templates with I18n and URL helpers | +| your own job and retry logic | `Smswire::DeliveryJob` with transient and permanent errors separated | +| `rescue Twilio::REST::RestError` | a `Smswire::Result` with a status and a reason | +| your own status callback controller | the engine's signed `/smswire/status/twilio` endpoint | +| stubbing the Twilio client in tests | `Smswire::TestHelper` and the `:test` provider | +| `twilio-ruby` in the Gemfile | no provider SDK | + +Smswire calls Twilio's REST API directly. You can remove `twilio-ruby` once +nothing else uses it, such as Voice or Verify. + +## 1. Install and keep your credentials + +Run the [getting started](getting-started.md) install steps. Smswire reads +`Rails.application.credentials.twilio[:account_sid]` and `[:auth_token]`, the +same keys most apps already use. Move the sending number into a sender: + +```ruby +config.senders = { + transactional: {number: Rails.application.credentials.dig(:twilio, :phone_number)}, + # A Messaging Service maps to messaging_service: + # marketing: {messaging_service: "MG...", consent_scope: "marketing"} +} +``` + +## 2. Replace one send + +Before: + +```ruby +class ShipmentNotifier + def call(order) + client = Twilio::REST::Client.new(sid, token) + client.messages.create( + from: ENV["TWILIO_NUMBER"], + to: order.customer.phone, + body: "Order #{order.number} has shipped", + status_callback: twilio_status_url(order_id: order.id) + ) + rescue Twilio::REST::RestError => error + Rails.logger.error(error.message) + end +end +``` + +After: + +```ruby +class OrderMessenger < ApplicationMessenger + def shipped(order) + @order = order + text to: order.customer.phone + end +end + +OrderMessenger.shipped(order).deliver_later +``` + +```erb +<%# app/views/order_messenger/shipped.text.erb %> +Order <%= @order.number %> has shipped +``` + +`text to:` takes a string here. Pass the customer instead if it has a +`phone_number` method, which also links the delivery row to the customer. + +## 3. Map your error handling + +Smswire turns Twilio errors into outcomes: + +| Twilio | Smswire | +|---|---| +| 21211, 21214, 21217, 21614 invalid number | `:failed`, `error.reason == :invalid_number` | +| 21610 recipient replied STOP | `:failed`, reason `:opted_out`, and the number is opted out | +| 21408, 21606, 21612 cannot route | `:failed`, reason `:unroutable` | +| 401, 403, 20003 | `:failed`, reason `:authentication` | +| 429 | retried after `Retry-After` | +| 5xx, timeouts | retried with backoff, up to `retry_attempts` | +| other 4xx | `:failed`, reason `:rejected` | + +Code that rescued `RestError` to log or alert becomes an observer: + +```ruby +class SmsAlerts + def self.delivered_sms(result) + Sentry.capture_message("SMS failed: #{result.error.message}") if result.failed? + end +end +Smswire.register_observer(SmsAlerts) +``` + +## 4. Retire your status controller + +If you had a controller for Twilio status callbacks, set +`config.callbacks_url` and delete it. Every message then carries a +`StatusCallback` URL with its delivery id, the engine checks the +`X-Twilio-Signature`, and `Smswire::Delivery#status` only moves forward. Use +`sms_status_updated(delivery, update)` on an observer for anything you did +in that controller. + +Behind a load balancer that terminates TLS, the signature still verifies +because Smswire rebuilds the URL from `callbacks_url`. + +## 5. Point incoming messages at the engine + +Set the number's or Messaging Service's incoming webhook to +`https://app.example.com/smswire/inbound/twilio`. If you use Twilio Advanced +Opt-Out, Smswire records the opt-out and skips its own reply, since Twilio +already sent one. + +## 6. Update tests + +Before: + +```ruby +client = instance_double(Twilio::REST::Client) +expect(client).to receive_message_chain(:messages, :create) +``` + +After: + +```ruby +assert_sms_delivered(to: "+15555550100", messenger: OrderMessenger) { order.ship! } +``` + +The test environment uses the `:test` provider automatically, so no request +leaves the process. + +## Behaviour to expect + +- **Duplicates.** The same messenger, action, recipient, and body inside 10 + minutes returns `:duplicate`. Pass `idempotency_key:` to `text`, or set + `config.dedupe_window = nil`. +- **Opt-outs.** Opted-out numbers are refused for every category. +- **Marketing.** Messages with `category: :marketing` need an opt-in and wait + for quiet hours to end. diff --git a/docs/guides/writing-a-provider.md b/docs/guides/writing-a-provider.md new file mode 100644 index 0000000..bb69f23 --- /dev/null +++ b/docs/guides/writing-a-provider.md @@ -0,0 +1,126 @@ +# Writing a provider adapter + +An adapter connects Smswire to one SMS API. It sends messages, classifies +errors, and optionally verifies and parses webhooks. Every adapter must pass +`Smswire::ProviderContract`, a Minitest suite shipped in the gem. + +## Generate the skeleton + +``` +bin/rails generate smswire:provider Acme +``` + +This writes: + +- `app/sms_providers/acme_provider.rb`, a working adapter for a fictional API; +- `test/sms_providers/acme_provider_test.rb`, which runs the contract against it; +- a `Smswire::Providers.register(:acme, "AcmeProvider")` line in the initializer. + +The generated pair passes the contract as generated. Change the API calls, +error codes, and stubs together, running the test as you go. + +## The adapter contract + +```ruby +class AcmeProvider < Smswire::Providers::Base + def deliver(message) # => Smswire::Receipt, or raises + def capabilities # => Set of :mms, :status_callbacks, :inbound, :messaging_services, :scheduling + def verify_credentials! # => true, or raises; nil if unsupported + + # With :status_callbacks or :inbound: + def verify_signature!(request, url:) # raises Smswire::SignatureError + def parse_status_callback(request) # => Smswire::StatusUpdate, or nil if not a status event + def parse_inbound(request) # => Smswire::Inbound, or nil if not an inbound message + def inbound_response # => [body, content_type], or nil for 204 +end +``` + +`options` holds `Smswire.config.providers[:acme]` with symbol keys, and +`name` is the registered name. + +### Sending + +Read `message.to` (E.164), `from`, `messaging_service`, `body`, +`media_urls`, `validity_period`, and `status_callback_url`. Use +`Smswire::HTTP.post_form` or `post_json`; both turn network failures into +`TransientError` and never log bodies. Return `receipt(provider_id:, status:, +segments:, price_amount:, price_currency:, raw:)` with a status from the +normalized vocabulary: `:queued`, `:accepted`, `:sent`, `:delivered`, +`:undelivered`, `:failed`, `:read`. + +### Errors + +| Situation | Raise | +|---|---| +| network failure, timeout, 5xx | `Smswire::TransientError` (retried) | +| rate limit | `Smswire::ThrottledError.new(..., retry_after: seconds)` | +| retrying cannot help | `Smswire::PermanentError.new(..., reason:)` | +| missing credentials or settings | `Smswire::ConfigurationError` | + +Pass `provider: name, provider_code:, http_status:, raw:` to error +constructors. Reasons are `:invalid_number`, `:opted_out`, `:unroutable`, +`:authentication`, and `:rejected`. Use `:opted_out` only for an error that +specifically means the recipient opted out, because Smswire records an +opt-out when it sees one. If the provider has no such error, define +`contract_reports_opt_outs?` as `false` in the test. + +### Webhooks + +Verify before parsing. Use constant-time comparison, such as +`ActiveSupport::SecurityUtils.secure_compare`, and reject stale timestamps +when the provider signs them. `url:` is the public URL the provider posted +to, rebuilt from `config.callbacks_url` when that is set. + +Return `nil` from `parse_status_callback` for events that are not status +updates, and from `parse_inbound` for events that are not messages. The +engine tries both, so a provider that posts every event to one URL works. + +## Contract hooks + +```ruby +class AcmeProviderTest < ActiveSupport::TestCase + include Smswire::TestHelper + include Smswire::ProviderContract + + def contract_provider_name = :acme + def contract_provider_options = {api_key: "test-key"} + + # Stub the API for :success, :invalid_number, :opted_out, :authentication, + # :throttled, :server_error, and :timeout. Return the WebMock stub. + def stub_contract_send(outcome, message) = ... + + # With :status_callbacks; status is :delivered or :undelivered. + def contract_status_request(provider_id:, status:, signed: true) = ... + + # With :inbound. + def contract_inbound_request(from:, to:, body:, signed: true) = ... +end +``` + +Build requests with `contract_request(url, params:)` for form posts or +`contract_request(url, body: json)` for JSON, plus `headers:`. Override +`contract_message` to run the contract with one of your own messengers. + +The suite checks: + +- the receipt, its provider id, and its status; +- a full pipeline send that records a delivery row; +- each permanent outcome's reason, and that throttling, server errors, and + timeouts are retryable; +- for declared capabilities, that signed requests parse and verify and + unsigned ones raise `SignatureError`, and that status and inbound events + are not mistaken for each other. + +The bundled Twilio, Telnyx, and Vonage adapters pass the same suite; their +tests in `test/provider_contract_test.rb` in the Smswire repository are +worked examples. + +## Sharing an adapter + +Publish it as a gem that depends on `smswire` and registers itself: + +```ruby +# lib/smswire-acme.rb +require "smswire" +Smswire::Providers.register(:acme, "Smswire::Acme::Provider") +``` diff --git a/lib/generators/smswire/install/templates/initializer.rb.tt b/lib/generators/smswire/install/templates/initializer.rb.tt index 12decc5..a4c2b13 100644 --- a/lib/generators/smswire/install/templates/initializer.rb.tt +++ b/lib/generators/smswire/install/templates/initializer.rb.tt @@ -16,8 +16,13 @@ Smswire.configure do |config| # Public URL where Smswire::Engine is mounted. Enables delivery status callbacks. # config.callbacks_url = "https://example.com/smswire" - # Used in STOP / START / HELP auto-replies. + # Used in STOP / START / HELP auto-replies. HELP replies should name a + # support contact (phone, email, or URL). # config.program_name = "<%= Rails.application.class.module_parent_name.titleize rescue "My App" %>" + # config.support_contact = "support@example.com" + + # Verify provider credentials at boot (one read-only API call): + # Rails.application.config.after_initialize { Smswire.verify_credentials! } if Rails.env.production? # Category rules merge over the defaults (marketing requires opt-in and has quiet hours). # config.categories = {marketing: {rate_limit: {max: 3, per: 1.day}}} diff --git a/lib/smswire.rb b/lib/smswire.rb index b48a270..14f2110 100644 --- a/lib/smswire.rb +++ b/lib/smswire.rb @@ -43,6 +43,12 @@ def logger config.logger || ActiveSupport::Logger.new($stdout) end + # Check the credentials of +provider+ (default: the default provider) + # with one read-only API call, for boot checks and health endpoints. + def verify_credentials!(provider = nil) + Providers.resolve(provider).verify_credentials! + end + # Interceptors respond to +delivering_sms(message)+. They run after the # recipient is normalized and before the provider is called, and may # mutate the message or cancel it with +message.cancel!+. diff --git a/lib/smswire/configuration.rb b/lib/smswire/configuration.rb index c3d795b..50a8385 100644 --- a/lib/smswire/configuration.rb +++ b/lib/smswire/configuration.rb @@ -20,11 +20,15 @@ class Configuration help: %w[HELP INFO] }.freeze + # CTIA guidance: the opt-out confirmation names the brand, confirms the + # removal, and says no further messages will be sent; the HELP reply + # names the brand and a support contact. DEFAULT_KEYWORD_REPLIES = { - opt_out: "You have been unsubscribed from %{program} messages and will not receive any more. Reply START to resubscribe.", - opt_in: "You are subscribed to %{program} messages again. Reply STOP to unsubscribe, HELP for help.", - help: "%{program}: Reply STOP to unsubscribe. Msg & data rates may apply." + opt_out: "%{program}: You are unsubscribed and will no longer receive any further messages. Reply START to resubscribe.", + opt_in: "%{program}: You are subscribed again. Reply HELP for help, STOP to unsubscribe. Msg & data rates may apply.", + help: "%{program}: For help, contact %{contact}. Reply STOP to unsubscribe. Msg & data rates may apply." }.freeze + HELP_WITHOUT_CONTACT = "%{program}: Reply STOP to unsubscribe. Msg & data rates may apply.".freeze PHONE_VALIDATORS = %i[auto phonelib e164].freeze # Provider name used when a message or sender does not name one. @@ -107,6 +111,15 @@ class Configuration attr_accessor :program_name + # Phone number, email, or URL for customer care, used in HELP replies + # as %{contact}. CTIA guidance expects one. + attr_accessor :support_contact + + # When true, STOP to any sender opts the number out of every consent + # scope, as STOPALL does. The FCC rule applying a revocation to all of a + # sender's unrelated messages is delayed to January 31, 2027. + attr_accessor :opt_out_all_scopes + # Development tools served by the engine. Both default to true in # development only. Set them in config/application.rb or an environment # file as config.smswire.show_previews, since preview paths are @@ -138,6 +151,8 @@ def initialize @keywords = DEFAULT_KEYWORDS.transform_values(&:dup) @keyword_replies = DEFAULT_KEYWORD_REPLIES.dup @program_name = nil + @support_contact = nil + @opt_out_all_scopes = false @show_previews = false @show_inbox = false @preview_paths = [] @@ -182,7 +197,11 @@ def consent_scopes def keyword_reply(kind) template = keyword_replies[kind.to_sym] or return nil - format(template, program: program_name || default_program_name) + if template.include?("%{contact}") && support_contact.blank? + Smswire.logger.warn("[Smswire] Set config.support_contact; HELP replies should include a support contact.") + template = HELP_WITHOUT_CONTACT if template == DEFAULT_KEYWORD_REPLIES[:help] + end + format(template, program: program_name || default_program_name, contact: support_contact.to_s) end def store_body?(category) diff --git a/lib/smswire/http.rb b/lib/smswire/http.rb index b026153..00ba273 100644 --- a/lib/smswire/http.rb +++ b/lib/smswire/http.rb @@ -43,6 +43,19 @@ def post_json(url, payload, headers: {}, open_timeout: 5, read_timeout: 15, prov raise TransientError.new("#{error.class}: #{error.message}", provider:) end + def get(url, basic_auth: nil, headers: {}, open_timeout: 5, read_timeout: 15, provider: nil) + uri = URI(url) + request = Net::HTTP::Get.new(uri, {"User-Agent" => "smswire/#{Smswire::VERSION}", + "Accept" => "application/json"}.merge(headers)) + request.basic_auth(*basic_auth) if basic_auth + + Net::HTTP.start(uri.host, uri.port, use_ssl: uri.scheme == "https", open_timeout:, read_timeout:) do |http| + http.request(request) + end + rescue *NETWORK_ERRORS => error + raise TransientError.new("#{error.class}: #{error.message}", provider:) + end + def parse_json(body) JSON.parse(body.to_s) rescue JSON::ParserError diff --git a/lib/smswire/keywords.rb b/lib/smswire/keywords.rb index d2e040d..1262529 100644 --- a/lib/smswire/keywords.rb +++ b/lib/smswire/keywords.rb @@ -3,8 +3,9 @@ module Smswire # consent, and sends the configured auto-reply. # # A keyword matches only when it is the whole message, ignoring case, - # surrounding whitespace, and surrounding punctuation, which is how - # carriers and Twilio match them. + # spaces, and surrounding punctuation, so "Opt out." matches OPTOUT and + # "stop all" matches STOPALL. Free-text requests such as "please stop + # texting me" are recorded but not matched; see docs/guides/compliance.md. module Keywords STORED = {opt_out: "stop", opt_in: "start", help: "help"}.freeze @@ -12,11 +13,11 @@ module Keywords # Returns [kind, word] or nil. def classify(body) - word = body.to_s.strip.gsub(/\A[^[:alnum:]]+|[^[:alnum:]]+\z/, "").upcase + word = body.to_s.strip.gsub(/\A[^[:alnum:]]+|[^[:alnum:]]+\z/, "").gsub(/[[:space:]-]+/, "").upcase return nil if word.empty? Smswire.config.keywords.each do |kind, words| - return [kind.to_sym, word] if words.map(&:upcase).include?(word) + return [kind.to_sym, word] if words.map { |candidate| candidate.upcase.delete(" -") }.include?(word) end nil end @@ -29,7 +30,7 @@ def handle(record, inbound, provider:) scope = Consent.scope_for_sender(number: record.to_number, messaging_service: record.messaging_service) case kind when :opt_out - if word == "STOPALL" + if word == "STOPALL" || Smswire.config.opt_out_all_scopes Consent.opt_out_everywhere!(phone, source: :keyword, keyword: word) else Consent.opt_out!(phone, scope:, source: :keyword, keyword: word) diff --git a/lib/smswire/noticed_delivery_method.rb b/lib/smswire/noticed_delivery_method.rb index f7d3d90..9590aa9 100644 --- a/lib/smswire/noticed_delivery_method.rb +++ b/lib/smswire/noticed_delivery_method.rb @@ -13,7 +13,8 @@ module DeliveryMethods # # config.args = -> { [recipient] } # default # # config.kwargs = -> { {} } # # config.params = -> { {order: record} } # default: the event params - # # config.wait, config.queue, config.priority # for Smswire::DeliveryJob + # # config.sms_queue, config.sms_priority # for Smswire::DeliveryJob + # # config.wait, config.queue, config.if, ... # Noticed's own job options # end # end # @@ -43,9 +44,10 @@ def messenger_params ) end + # Noticed reads wait, wait_until, queue, and priority for its own job, + # which already applies any delay, so Smswire's job takes separate keys. def job_options - {wait: evaluate_option(:wait), wait_until: evaluate_option(:wait_until), - queue: evaluate_option(:queue), priority: evaluate_option(:priority)}.compact + {queue: evaluate_option(:sms_queue), priority: evaluate_option(:sms_priority)}.compact end end end diff --git a/lib/smswire/providers/base.rb b/lib/smswire/providers/base.rb index b44783b..eab6c4f 100644 --- a/lib/smswire/providers/base.rb +++ b/lib/smswire/providers/base.rb @@ -19,6 +19,14 @@ def capabilities Set.new end + # Make one authenticated, read-only call to the provider. Returns true, + # raises ConfigurationError when credentials are rejected or missing, + # or TransientError when the provider cannot be reached. Returns nil + # for adapters that cannot check. + def verify_credentials! + nil + end + # Raise Smswire::SignatureError unless +request+ was signed by the # provider. +url+ is the public URL the provider posted to. def verify_signature!(request, url:) @@ -42,6 +50,14 @@ def parse_status_callback(request) private + def check_credentials_response(response) + status = response.code.to_i + return true if status.between?(200, 299) + raise TransientError.new("#{name} returned #{status}", provider: name, http_status: status) if status >= 500 + + raise ConfigurationError, "#{name} rejected the configured credentials (HTTP #{status})" + end + def receipt(**attributes) Receipt.new(provider: name, **attributes) end diff --git a/lib/smswire/providers/log.rb b/lib/smswire/providers/log.rb index 3795dd4..9fe1352 100644 --- a/lib/smswire/providers/log.rb +++ b/lib/smswire/providers/log.rb @@ -5,6 +5,8 @@ module Providers # Writes messages, including the body, to Smswire.logger instead of # sending them. The default provider in development. class Log < Base + def verify_credentials! = true + def deliver(message) analysis = message.analysis sender = message.from || message.messaging_service || "(none)" diff --git a/lib/smswire/providers/null.rb b/lib/smswire/providers/null.rb index 5bccc39..7db5f3b 100644 --- a/lib/smswire/providers/null.rb +++ b/lib/smswire/providers/null.rb @@ -2,6 +2,8 @@ module Smswire module Providers # Accepts and discards every message. class Null < Base + def verify_credentials! = true + def deliver(message) receipt(status: :accepted, segments: message.segments) end diff --git a/lib/smswire/providers/telnyx.rb b/lib/smswire/providers/telnyx.rb index a9a131d..21e00b6 100644 --- a/lib/smswire/providers/telnyx.rb +++ b/lib/smswire/providers/telnyx.rb @@ -46,10 +46,16 @@ def deliver(message) handle(response) end + BALANCE_URL = "https://api.telnyx.com/v2/balance".freeze + def capabilities Set[:mms, :status_callbacks, :inbound, :messaging_services] end + def verify_credentials! + check_credentials_response(HTTP.get(BALANCE_URL, headers: {"Authorization" => "Bearer #{credential(:api_key)}"}, provider: name)) + end + def payload_for(message) profile = message.messaging_service || options[:messaging_profile_id] if message.from.blank? && profile.blank? diff --git a/lib/smswire/providers/test.rb b/lib/smswire/providers/test.rb index 980ddcd..febc210 100644 --- a/lib/smswire/providers/test.rb +++ b/lib/smswire/providers/test.rb @@ -40,6 +40,8 @@ def clear! end end + def verify_credentials! = true + def deliver(message) if (error = self.class.next_failure) raise error diff --git a/lib/smswire/providers/twilio.rb b/lib/smswire/providers/twilio.rb index 27e9059..9b0439b 100644 --- a/lib/smswire/providers/twilio.rb +++ b/lib/smswire/providers/twilio.rb @@ -42,6 +42,11 @@ def capabilities Set[:mms, :status_callbacks, :inbound, :messaging_services] end + def verify_credentials! + url = "#{options.fetch(:api_base, API_BASE)}/Accounts/#{account_sid}.json" + check_credentials_response(HTTP.get(url, basic_auth: [account_sid, auth_token], provider: name)) + end + def form_for(message) pairs = [["To", message.to]] if message.messaging_service diff --git a/lib/smswire/providers/vonage.rb b/lib/smswire/providers/vonage.rb index d00cbe0..fc0d165 100644 --- a/lib/smswire/providers/vonage.rb +++ b/lib/smswire/providers/vonage.rb @@ -46,10 +46,17 @@ def deliver(message) handle(response) end + BALANCE_URL = "https://rest.nexmo.com/account/get-balance".freeze + def capabilities Set[:status_callbacks, :inbound] end + def verify_credentials! + query = URI.encode_www_form(api_key: credential(:api_key), api_secret: credential(:api_secret)) + check_credentials_response(HTTP.get("#{BALANCE_URL}?#{query}", provider: name)) + end + def form_for(message) raise ConfigurationError, "Vonage requires a from number or sender id" if message.from.blank? diff --git a/smswire.gemspec b/smswire.gemspec index a65d275..2e1d5a6 100644 --- a/smswire.gemspec +++ b/smswire.gemspec @@ -22,7 +22,7 @@ Gem::Specification.new do |spec| spec.metadata["source_code_uri"] = "https://github.com/timimsms/smswire" spec.metadata["changelog_uri"] = "https://github.com/timimsms/smswire/blob/main/CHANGELOG.md" spec.metadata["bug_tracker_uri"] = "https://github.com/timimsms/smswire/issues" - spec.metadata["documentation_uri"] = "https://github.com/timimsms/smswire/blob/main/docs/SPEC.md" + spec.metadata["documentation_uri"] = "https://github.com/timimsms/smswire/tree/main/docs/guides" spec.metadata["rubygems_mfa_required"] = "true" spec.files = Dir.chdir(__dir__) do diff --git a/test/documentation_test.rb b/test/documentation_test.rb new file mode 100644 index 0000000..610c79b --- /dev/null +++ b/test/documentation_test.rb @@ -0,0 +1,47 @@ +require "test_helper" + +# Keeps the README, spec, and guides in step with the code: every +# Smswire.configure setting and every Smswire constant they name must exist. +class DocumentationTest < Smswire::TestCase + ROOT = File.expand_path("..", __dir__) + DOCS = [File.join(ROOT, "README.md"), *Dir[File.join(ROOT, "docs/guides/*.md")]].freeze + + # Options set inside Noticed `deliver_by` blocks, not on Smswire.config. + NOTICED_OPTIONS = %w[messenger action args kwargs params sms_queue sms_priority json error_handler credentials + wait wait_until queue priority if unless].freeze + + def ruby_snippets(path) + File.read(path).scan(/```ruby\n(.*?)```/m).flatten + end + + test "documented settings exist" do + DOCS.each do |path| + ruby_snippets(path).each do |snippet| + snippet.scan(/\bconfig\.([a-z_]+)\s*=(?!=)/).flatten.uniq.each do |setting| + next if NOTICED_OPTIONS.include?(setting) + + assert_respond_to Smswire.config, :"#{setting}=", "#{File.basename(path)} documents config.#{setting}" + end + end + end + end + + test "documented Smswire constants exist" do + (DOCS + [File.join(ROOT, "docs/SPEC.md")]).each do |path| + File.read(path).scan(/\bSmswire::[A-Z][A-Za-z]*(?:::[A-Z][A-Za-z]*)*/).uniq.each do |name| + next if name.start_with?("Smswire::Acme") # example adapter gem in the provider guide + + assert Object.const_defined?(name), "#{File.basename(path)} mentions #{name}" + end + end + end + + test "documented generators exist" do + DOCS.each do |path| + File.read(path).scan(/generate (smswire:[a-z_]+)/).flatten.uniq.each do |generator| + file = File.join(ROOT, "lib/generators/smswire", generator.delete_prefix("smswire:")) + assert Dir.exist?(file), "#{File.basename(path)} mentions #{generator}" + end + end + end +end diff --git a/test/inbound_test.rb b/test/inbound_test.rb index b234b4e..0ce9789 100644 --- a/test/inbound_test.rb +++ b/test/inbound_test.rb @@ -6,7 +6,7 @@ class InboundTest < Smswire::IntegrationTest OUR_NUMBER = "+15005550006" setup do - stub_request(:post, twilio_url).to_return(twilio_success) + stub_request(:post, twilio_url).to_return { twilio_success(sid: "SM#{SecureRandom.hex(6)}") } end def receive(body, sid: "SMin#{SecureRandom.hex(4)}", signature: :valid, **extra) @@ -36,7 +36,7 @@ def receive(body, sid: "SMin#{SecureRandom.hex(4)}", signature: :valid, **extra) perform_enqueued_jobs reply = Smswire::Delivery.sole assert_equal ["compliance", OUR_NUMBER, "twilio", "queued"], [reply.category, reply.from_number, reply.provider, reply.status] - assert_equal "You have been unsubscribed from Dummy messages and will not receive any more. Reply START to resubscribe.", + assert_equal "Dummy: You are unsubscribed and will no longer receive any further messages. Reply START to resubscribe.", reply.body assert_equal :rejected_opted_out, OrderMessenger.literal(PHONE, "Your order shipped").deliver_now.status @@ -64,6 +64,35 @@ def receive(body, sid: "SMin#{SecureRandom.hex(4)}", signature: :valid, **extra) assert_equal [["orders", "opted_out"]], Smswire::Consent.pluck(:scope, :status) end + test "keywords ignore spaces and hyphens" do + receive("Opt out.") + receive("stop all") + assert_equal %w[stop stop], Smswire::InboundMessage.pluck(:keyword) + end + + test "HELP includes the support contact, and warns when none is set" do + with_config(support_contact: "help@acme.example") do + receive("HELP") + perform_enqueued_jobs + end + assert_equal "Dummy: For help, contact help@acme.example. Reply STOP to unsubscribe. Msg & data rates may apply.", + Smswire::Delivery.sole.body + + output = StringIO.new + with_config(logger: Logger.new(output)) do + receive("INFO") + perform_enqueued_jobs + end + assert_includes output.string, "Set config.support_contact" + assert_equal "Dummy: Reply STOP to unsubscribe. Msg & data rates may apply.", Smswire::Delivery.order(:created_at).last.body + end + + test "STOP can opt out of every scope" do + senders = Smswire.config.senders.merge(brand_b: {number: "+15005550001", consent_scope: "brand_b"}) + with_config(senders:, opt_out_all_scopes: true) { receive("STOP") } + assert_equal %w[brand_b default], Smswire::Consent.where(status: "opted_out").pluck(:scope).sort + end + test "keywords must be the whole message" do receive("please stop texting me") assert_nil Smswire::InboundMessage.sole.keyword diff --git a/test/noticed_test.rb b/test/noticed_test.rb index 7da06f3..9cffebf 100644 --- a/test/noticed_test.rb +++ b/test/noticed_test.rb @@ -35,6 +35,31 @@ class NoticedTest < Smswire::TestCase assert_empty sms_deliveries end + test "Noticed's wait delays only Noticed's job" do + notifier = Class.new(Noticed::Event) do + def self.name = "DelayedShippedNotifier" + + deliver_by :smswire do |config| + config.messenger = "OrderMessenger" + config.action = :notify_shipped + config.wait = 5.minutes + end + end + Object.const_set(:DelayedShippedNotifier, notifier) + + travel_to Time.utc(2026, 1, 15, 12) do + perform_enqueued_jobs(only: Noticed::EventJob) { notifier.with(order_number: "R8").deliver(@customer) } + noticed_job = enqueued_jobs.find { |job| job[:job] == Noticed::DeliveryMethods::Smswire } + assert_equal 5.minutes.from_now.to_f, noticed_job[:at] + + perform_enqueued_jobs(only: Noticed::DeliveryMethods::Smswire) + sms_job = enqueued_jobs.find { |job| job[:job] == Smswire::DeliveryJob } + assert_nil sms_job[:at], "Smswire's job must not add a second delay" + end + ensure + Object.send(:remove_const, :DelayedShippedNotifier) if Object.const_defined?(:DelayedShippedNotifier) + end + test "custom args, params, and job options" do notifier = Class.new(Noticed::Event) do def self.name = "CustomShippedNotifier" @@ -45,7 +70,7 @@ def self.name = "CustomShippedNotifier" config.args = -> { [recipient.phone_number] } config.kwargs = -> { {window: "9-11am"} } config.params = -> { {order_number: "R7"} } - config.queue = :sms + config.sms_queue = :sms end end Object.const_set(:CustomShippedNotifier, notifier) diff --git a/test/verify_credentials_test.rb b/test/verify_credentials_test.rb new file mode 100644 index 0000000..94acafd --- /dev/null +++ b/test/verify_credentials_test.rb @@ -0,0 +1,36 @@ +require "test_helper" + +class VerifyCredentialsTest < Smswire::TestCase + test "built-in development providers always pass" do + assert Smswire.verify_credentials! + assert Smswire.verify_credentials!(:log) + end + + test "twilio checks the account endpoint" do + stub = stub_request(:get, "https://api.twilio.com/2010-04-01/Accounts/ACtest.json") + .with(basic_auth: %w[ACtest secret]).to_return(status: 200, body: "{}") + assert Smswire.verify_credentials!(:twilio) + assert_requested stub + + stub_request(:get, "https://api.twilio.com/2010-04-01/Accounts/ACtest.json").to_return(status: 401) + assert_raises(Smswire::ConfigurationError) { Smswire.verify_credentials!(:twilio) } + end + + test "telnyx and vonage check their balance endpoints" do + providers = Smswire.config.providers.merge(telnyx: {api_key: "KEY"}, vonage: {api_key: "k", api_secret: "s"}) + with_config(providers:) do + stub_request(:get, "https://api.telnyx.com/v2/balance").with(headers: {"Authorization" => "Bearer KEY"}).to_return(status: 200) + stub_request(:get, "https://rest.nexmo.com/account/get-balance?api_key=k&api_secret=s").to_return(status: 200, body: "{}") + assert Smswire.verify_credentials!(:telnyx) + assert Smswire.verify_credentials!(:vonage) + + stub_request(:get, "https://api.telnyx.com/v2/balance").to_return(status: 503) + assert_raises(Smswire::TransientError) { Smswire.verify_credentials!(:telnyx) } + end + end + + test "custom adapters that cannot check return nil" do + Smswire::Providers.register(:silent, Class.new(Smswire::Providers::Base)) + assert_nil Smswire.verify_credentials!(:silent) + end +end