# twilio

Transactional SMS. Used by:
- `/api/auth-send-code.js` (passwordless SMS OTP)
- escalation-cycle workflow (SMS alerts when the operator opted in for the +$5/loc/month add-on)

## Endpoint

`POST https://api.twilio.com/2010-04-01/Accounts/{TWILIO_ACCOUNT_SID}/Messages.json`

## Auth

HTTP Basic. Username = `TWILIO_ACCOUNT_SID`, password = `TWILIO_AUTH_TOKEN`.

## Required env vars

- `TWILIO_ACCOUNT_SID`
- `TWILIO_AUTH_TOKEN`
- `TWILIO_FROM_NUMBER` - the sending number (E.164, e.g. `+19705551234`). Must be a Twilio-owned number or a number registered for A2P 10DLC.

## A2P 10DLC

The US carriers require business SMS senders to register their brand and campaigns (Application-to-Person 10-Digit Long Code) since 2023. Failure to register triggers heavy throttling or outright blocking by AT&T / T-Mobile / Verizon.

Action items:
1. Register the FranchiseFrontline brand in Twilio's brand registration UI.
2. Register two campaigns: one for OTP (passwordless code), one for alerts.
3. Wait 1-3 business days for vetting.
4. Move the `TWILIO_FROM_NUMBER` to the approved campaign.

Until 10DLC registration completes, SMS may throttle. The passwordless email channel is the fallback for sign-in.

## Rate limits

- Twilio's default sending rate is 1 message per second per number. Higher rates available via Messaging Services and high-throughput numbers.
- Our peak is the morning escalation-alert flurry on Mondays; we handle that with a small queue and respect Twilio's response codes for retries.

## Message constraints

- SMS body length: 160 chars for a single segment; longer messages split into multi-segment (each charged separately).
- Our OTP message is short: `FranchiseFrontline sign-in code: 123456. Expires in 10 minutes.` - 64 chars.
- Alert SMS is also kept under 160 chars: `New 1-star at Durango (Main) - Google. "Ordered ahead, waited 25 min..." Open: ff.com/a/esc-abc123`.

## Failure modes

- **20003 (Authentication error):** SID/token mismatch. Engineer alert.
- **21610 (Unsubscribed recipient):** the operator's number opted out (`STOP`). Mark `sms_opt_out=true` on the operator record; do not retry; fall back to email.
- **30007 (Carrier filtered):** A2P 10DLC compliance issue. Until registration is complete, expect this on AT&T and T-Mobile.

## Compliance

- The first SMS to a new number includes the `Reply STOP to unsubscribe. Msg & data rates may apply.` footer.
- Operator opt-in is collected at sign-up; SMS alerts do not fire unless the operator added their number AND checked the SMS-alerts box.
