SMS
SMS sends and receives text messages for the whole app. It has providers (Twilio, shared phones paired with the
Sysgear app, and your own), numbers on each provider, routing that picks a number and fails over to the next, an
outbox and inbound log, and a light mass send from the admin. Other modules use it through
Notify (it is Notify's SMS driver), Inbox (the sms
channel) and the sms:* hooks.
The package is @frigear-nu/sms. Twilio is called with fetch and its webhooks are checked with Web Crypto, so it
runs on Cloudflare Workers.
What you get
sendSms(server): routing byfrom, the operation's default number and priority, with failover.- Notify's SMS driver:
dispatchSMSNotificationand the SMS channel ofnotifyUsergo out throughsendSms. Anotify.sms.driveryou set wins. - Providers: Twilio and paired phones built in; more through
extendSms. - Paired phones (with the database): shared phones that send from their SIM lines, receive texts and get pushes.
- Inbox channel (with the database and Inbox): texts become threads, replies leave from the number they came in on.
- Admin (with Admin): Settings, SMS, with Providers, Numbers, Phones and Messages tabs, and a "Send SMS" action for groups.
- Hooks:
sms:received,sms:sent,sms:delivered,sms:failed,sms:device:status.
@frigear-nu/module-kit, Auth, Notify
and UI.Optional:@nuxthub/core with hub.db (the database), Push (pushes to the phones),
Inbox (the sms channel), Admin and
Menu (the admin pages and their menu item).Quick setup
Install SMS
pnpm add @frigear-nu/sms
export default defineNuxtConfig({
modules: ['@nuxthub/core', '@frigear-nu/sms'],
sms: {
providers: {
// Filled in by NUXT_SMS_PROVIDERS_TWILIO_ACCOUNT_SID, _AUTH_TOKEN and _NUMBERS.
twilio: { type: 'twilio', accountSid: '', authToken: '', numbers: '' },
},
},
})
Generate the migration
With hub.db SMS stores its providers, phones and messages, so it needs its tables:
pnpm db:generate
Send a message
export default defineEventHandler(async (event) => {
return sendSms({ to: '+4512345678', body: 'Your shift starts at 18:00.', source: 'shifts', event })
// { id: 'smo_…', status: 'sent', numberId: 'twilio:+4520000001', providerId: 'twilio', externalId: 'SM…', error: null }
})
Who sent a message
Every message records the module that sent it (source) and, through Notify, the topic (topic). The Messages tab
shows them in a "Sent by" column and filters by them, and the sms:* hooks carry them.
notifyUsersets them for you:sourceis the topic's module (shiftsforshifts.reminder),topicthe topic.- A module that calls
dispatchSMSNotificationitself passes its name:meta: { source: 'crew', topic: 'crew.status' }. Without it the message is labellednotify. sendSmstakessourceandtopicdirectly. SMS's own sends aresms(the admin's test, texts composed on a phone) andsms-broadcast(group sends); inbox replies areinbox.
The Messages tab names a module by the i18n key sms.messages.sources.<module>, else by its name.
With or without the database
sms.database decides: 'auto' (the default) is on when the app has hub.db, true requires it (the build fails
without hub.db) and false never uses it.
| Without the database | With the database | |
|---|---|---|
| Providers | sms.providers only | Also added in the admin, secrets encrypted |
| Paired phones | No | Yes |
| Message log | None: only the sms:* hooks see messages (sendSms answers an id that is not stored) | Every message is an sms_outbox row, every text an sms_inbound row |
| Duplicate inbound texts | Remembered for a day in Nitro storage (sms) | A unique row per provider message id |
| Inbox channel, broadcasts, tasks | No | Yes |
| Admin | Providers (read-only) and "Send test message" | Every tab |
Providers
A provider is set up in one of two places:
sms.providersinnuxt.config, by id, with its settings filled in by environment variables (NUXT_SMS_PROVIDERS_<ID>_<SETTING>). The admin shows it read-only, and a provider whose required settings are empty shows as "Not configured" and is never used.- The admin (with the database). Its secret settings are sealed with AES-GCM under
NUXT_SMS_SECRET_KEYor, without it, a key derived fromNUXT_APP_SECRET. Without either, saving a provider with a secret answers 501. Changing the key makes the stored secrets unreadable: those providers turn off until their secrets are saved again.
| Setting of a config provider | What it is |
|---|---|
type | A registered type: twilio, or your own. |
name | What the admin shows. Defaults to the id. |
priority | Lower goes first when numbers tie. Default 100. |
enabled | false turns it off. |
numbers | Its numbers in E.164, as a list or comma separated. Each sends and receives. |
| Its type's settings | Twilio: accountSid, authToken (secret), messagingServiceSid (optional). |
Twilio
Set the number's "A message comes in" webhook to https://<host>/api/sms/webhooks/<providerId>/inbound. Delivery
reports come to .../status by themselves: sendSms passes it as StatusCallback when it knows the request's origin.
Both webhooks are checked against X-Twilio-Signature with the auth token; behind a proxy, the URL Twilio signed must be
the one the app sees (x-forwarded-host and x-forwarded-proto are read).
Your own provider
Register a type from a module's setup() and default-export the adapter:
import { extendSms } from '@frigear-nu/sms/utils'
export default defineNuxtModule({
setup(_options, nuxt) {
const resolver = createResolver(import.meta.url)
extendSms(nuxt, {
providers: [{
type: 'acme',
label: 'Acme SMS',
adapter: resolver.resolve('./runtime/acme'),
configSchema: [{ key: 'apiKey', label: 'API key', secret: true, required: true }],
}],
})
},
})
import { defineSmsProvider } from '@frigear-nu/sms/utils'
export default defineSmsProvider({
async send({ provider, number, message }) {
const sent = await $fetch<{ id: string }>('https://sms.acme.test/send', {
method: 'POST',
headers: { authorization: `Bearer ${provider.secrets.apiKey}` },
body: { from: number.number, to: message.to, text: message.body },
})
return { externalId: sent.id }
},
// Optional: read POST /api/sms/webhooks/:providerId/inbound and .../status (verify the request first, throw 401),
// and `verify(provider)` for the admin's test action.
})
send throws to fail the message (routing tries the next number), or answers { queued: true } when the result comes
later. The host can add types with sms.extraProviders; a later type with the same name replaces an earlier one.
Routing and failover
sendSms({ to, body, from?, operationId?, source?, ref?, failover?, defer? }) picks the numbers to try, in order:
from(a number or a number id), if given. Withfailover: falseit is the only one.- Then, automatically: the numbers of
operationId, then numbers of no operation, then other operations' numbers. Within each, the default number first, then by priority (lower first), then the provider's priority.
A phone's line is used automatically only when the phone offers notify SMS. Bulk sources (every named
source but sms and inbox: modules' notifications, group sends, campaigns) skip offline Android phones, and phones
at their limit (rateLimit messages per 30 minutes, 30 by default, as Android allows). sms-broadcast and campaigns put
every API number before every phone. iPhones come last in automatic routing, after every API number and Android phone
(see iPhones); an explicit from may still pick one.
On a provider error the next number is tried, and the message records the numbers it tried (triedNumberIds). A message
for a phone is queued for the phone instead; the sms:sweep task moves it on when the phone does not claim it within
claimTimeoutSeconds (iosClaimTimeoutSeconds for an iPhone), and the phone's failure report does the same at once. A message nothing could send answers
status: 'failed' and fires sms:failed; sendSms only throws for a bad recipient (400 invalid_number) or body.
defer: true stores the message and leaves it to the sms:deliver task.
Paired phones
A phone is the device provider: its SIM lines are numbers. Phones are paired with the Sysgear app, and the phone keeps
nothing but its own token.
- An admin adds the phone (Phones tab) and shows its pairing code: a QR holding
{ server, code, purpose: 'pair' }, valid once for 10 minutes. - The app sends the code to
POST /api/sms/pairand gets the phone's token once:smd_and 43 characters. Only its SHA-256 is stored. - The phone reports its SIM lines on pairing and in heartbeats. A new line starts off; an admin labels it, fills in its number when the SIM does not know it, and turns it on.
An admin can also sign in on the phone (OAuth with the sms-pair scope, holding sms:pair) and pair without a code;
the app signs that admin out right after. Changing what the phone offers (channels) needs an unlock code: a fresh QR
from the admin (purpose unlock), or POST /api/sms/unlock as an admin signed in on the phone.
Routes of a paired phone, with Authorization: Bearer smd_…:
| Route | What it does |
|---|---|
POST /api/sms/device/heartbeat | { platform?, lines? }: online, its lines, and how many messages wait. |
POST /api/sms/device/outbox/claim | { limit? }: claims the waiting messages (id, to, body, from, simSubscriptionId). |
POST /api/sms/device/outbox/:id/result | { status: 'sent' | 'delivered' | 'failed', error? }. A failure fails over. |
POST /api/sms/device/inbound | { from, to? or subscriptionId?, body, externalId, receivedAt? }: a text it received, stored once per externalId. |
POST /api/sms/device/send | { to, body, from? }: a text composed on the phone, logged and queued for the phone. |
PATCH /api/sms/device/channels | { channels, unlockCode }. |
POST /api/sms/device/push | Push's device registration body: the phone gets pushes (owner sms-device). |
A phone's token holds only sms:device, a device permission: authorize
answers 403 for it on every other route, and no user or role ever holds it. A policy on a device permission blocks every
device, and the authorization:before hook never runs for devices, so check a phone in its route. Revoking a phone
(Phones tab) stops its token at once and moves its waiting messages on.
sms:sweep (every minute) marks a phone offline after offlineAfterMinutes without a heartbeat and fires
sms:device:status. When Push is installed, a phone with messages waiting gets a push (at most every 30 seconds), and
smsPushToDevices(event, { operationId, title, body }) reaches the phones of an operation that offer push.
iPhones
iOS lets no app send or read texts on its own, so an iPhone works through two Shortcuts personal automations, set up by hand on each phone (iOS 17 or later, "Run Immediately"). The Sysgear app's iPhone setup screen walks through both, with the URLs and the phone's token (shown after an admin unlocks it).
- Send: "When I get an email" from the server's sender, subject
Sysgear: messages waiting→ claim (POST /api/sms/device/outbox/claim) → Send Message for each item (Show When Run off) →POST …/outbox/:id/result. A push cannot start a shortcut, so the server emails the phone's wake-up email (set in the phone's edit in the admin) when messages are queued for it, through notify's email, at most once a minute while they wait. - Receive: "When I get a message" →
POST /api/sms/device/inbound. - Its number: iOS cannot tell it, so the admin types it in the phone's edit; it becomes the phone's one line
(subscription id
0), off until turned on.
Limits: it sends from the default line only, may need the phone unlocked, reports no delivery (results stop at
sent), and each phone is set up by hand. An iPhone has iosClaimTimeoutSeconds (600 by default) to claim a message
before routing moves on, as email and the automation take longer than an Android phone's polling.
Inbox
With Inbox installed, SMS registers the sms channel. Add a channel account for each receive number in the inbox
settings, with the number (E.164) as its address. A text to that number becomes a thread, and a reply leaves from the
same number. The sender's number is their identity on SMS (a caller ID): a text joins that number's open or pending
thread on the same receive number, else it starts a new one. Senders are not verified (numbers can be spoofed), so a
text never links the contact to an account or renames it. A phone whose "Two-way inbox" is off is left out.
Sending to groups
The Messages tab's "Send SMS" (sms:broadcast) sends one text to the members of some grants (roles, teams, operations:
whatever kinds the installed modules register with extendGrants) and typed numbers, each number once. public and
signed-in are refused. Phones come from Notify's recipient store, and people who turned SMS off for the sms.broadcast
topic are left out; the form shows the count first. The messages are sent in batches by sms:deliver.
For newsletters with unsubscribe links and lists people sign up to, use Campaigns.
Hooks
export default defineNitroPlugin((nitroApp) => {
nitroApp.hooks.hook('sms:received', async ({ from, to, body, operationId }) => {
// Stored first; fired once per message, also when the provider retries the webhook.
})
})
| Hook | Context |
|---|---|
sms:received | { id, to, from, body, receivedAt, providerId, numberId, deviceId?, operationId?, event? } |
sms:sent, sms:delivered, sms:failed | { id, to, from, source, topic, ref, providerId, error? } |
sms:device:status | { deviceId, status: 'online' | 'offline' } |
Access
| Permission | Who | What |
|---|---|---|
system-admin:access | admin | The SMS item of the admin. |
system-admin:read | admin | Providers, numbers, phones and the message log. |
system-admin:write | admin, session only | Change them, pair phones (it stores secrets and mints phone tokens). |
sms:broadcast | admin | Send SMS to groups. |
sms:send-numbers | admin | GET /api/admin/sms/send-numbers: the numbers a message can go out from now ({ id, number, label, operationId, isDefault }), for a "From" picker such as Campaigns'. Grant it to a role that writes campaigns without the system settings. |
sms:pair | admin, scope sms-pair | Pair a phone or unlock it from the phone app. |
sms:device | paired phones only | The device routes. |
Options
| Option | Default | What it does |
|---|---|---|
database | 'auto' | Use the database (see above). |
providers | {} | Config providers, by id. |
extraProviders | [] | The host's own provider types. |
claimTimeoutSeconds | 60 | How long a phone has to claim a message before failover. |
iosClaimTimeoutSeconds | 600 | The same for an iPhone, woken by email. |
offlineAfterMinutes | 5 | Minutes without a heartbeat before a phone is offline. |
retentionDays | 90 | Days messages are kept; false keeps them. |
batchSize | 100 | Messages sms:deliver sends per run. |
cron | '* * * * *' | When sms:sweep and sms:deliver run; false registers them without a schedule. |
pages.admin | true | The admin pages under /admin/sms; a path moves them, false leaves them out. |
NUXT_SMS_SECRET_KEY (32+ characters) seals the secrets of admin providers.