From 2b7626d63e142d12009b41851ac8a86a5f64afaa Mon Sep 17 00:00:00 2001 From: Schero94 <64200582+Schero94@users.noreply.github.com> Date: Fri, 20 Nov 2026 00:30:47 +0100 Subject: [PATCH 1/2] fix: correct provider edge cases found in the API audit Audit of the Meta, Twilio, seven.io and Telegram adapters against the providers' official specs and docs (docs/audits/2026-11-20-provider-apis.md). - seven.io: tell the owner to use the JSON webhook request method and log signed non-JSON webhooks instead of dropping them silently; cut SMS at the documented 1520 characters; map 101/500/501/407004 correctly; read sms_mo Unix timestamps and the HLR roaming object. - Twilio: 21610 and OptOutType=STOP revoke consent; 21611 is transient. - Telegram: never cut the HTML text inside an entity. - Follow api.rest.prefix for webhook URLs, status callbacks, file links and the raw-body middleware. - Keep surrogate pairs whole when cutting text; honour HTTP-date Retry-After. Co-Authored-By: Claude Opus 5.5 --- AGENTS.md | 34 +++--- CHANGELOG.md | 18 +++ README.md | 5 + admin/src/pages/Accounts/AccountWizard.jsx | 6 +- admin/src/pages/Accounts/index.jsx | 3 +- admin/src/translations/de.json | 2 + admin/src/translations/en.json | 2 + admin/src/translations/es.json | 2 + admin/src/translations/fr.json | 2 + admin/src/translations/pt.json | 2 + admin/src/utils/providers.mjs | 26 ++++ docs/audits/2026-11-20-provider-apis.md | 46 +++++++ docs/site/llms-full.txt | 39 +++--- server/src/adapters/http.js | 27 ++++- server/src/adapters/meta.js | 7 ++ server/src/adapters/seven.js | 58 +++++++-- server/src/adapters/telegram.js | 6 +- server/src/adapters/twilio.js | 11 +- server/src/controllers/admin.js | 3 +- server/src/core/accounts.js | 2 +- server/src/core/attachments.js | 4 +- server/src/core/context.js | 20 +++- server/src/core/outbox.js | 7 +- server/src/core/sender.js | 14 ++- server/src/core/templates.js | 2 +- server/src/core/webhooks.js | 42 ++++++- server/src/index.js | 5 +- server/src/services/index.js | 1 + server/src/utils/template-engine.js | 42 ++++++- tests/adapters.test.js | 132 +++++++++++++++++++++ tests/admin.test.js | 4 + tests/plugin.test.js | 41 +++++++ tests/webhooks.test.js | 61 ++++++++++ 33 files changed, 602 insertions(+), 74 deletions(-) create mode 100644 docs/audits/2026-11-20-provider-apis.md diff --git a/AGENTS.md b/AGENTS.md index c9e6c69..4f165fd 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -360,23 +360,23 @@ Use the delivery id to ignore repeats. No phone numbers, names or message text in any payload. Every event is emitted by exactly one process. -| Event | Payload | -| ------------------------------------- | ---------------------------------------------------------------------------------------------- | -| `messagegate.message.queued` | `{ messageId, channel, templateKey, status, code?, at }` | -| `messagegate.message.sent` | same | -| `messagegate.message.delivered` | same | -| `messagegate.message.read` | same | -| `messagegate.message.failed` | same, `code` set | -| `messagegate.message.uncertain` | same, `code` set | -| `messagegate.message.expired` | same, `code: 'DEADLINE_PASSED'` | -| `messagegate.message.discarded` | same | -| `messagegate.message.fallback` | `{ messageId, channel, templateKey, status: 'fallback', code, at }` (`channel` = next channel) | -| `messagegate.message.received` | `{ inboundId, contactId, channel, replyTo, kind, buttonPayload?, media?: { status }, at }` | -| `messagegate.media.ready` | `{ inboundId, fileId, mime, size, at }` (`fileId` is the media library id) | -| `messagegate.media.failed` | `{ inboundId, code, at }` | -| `messagegate.contact.opted-out` | `{ channel, at }` | -| `messagegate.contact.unreachable` | `{ channel: 'whatsapp', at }` | -| `messagegate.template.status-changed` | template id, key, language, new status | +| Event | Payload | +| ------------------------------------- | ---------------------------------------------------------------------------------------------------- | +| `messagegate.message.queued` | `{ messageId, channel, templateKey, status, code?, at }` | +| `messagegate.message.sent` | same | +| `messagegate.message.delivered` | same | +| `messagegate.message.read` | same | +| `messagegate.message.failed` | same, `code` set | +| `messagegate.message.uncertain` | same, `code` set | +| `messagegate.message.expired` | same, `code: 'DEADLINE_PASSED'` | +| `messagegate.message.discarded` | same | +| `messagegate.message.fallback` | `{ messageId, channel, templateKey, status: 'fallback', code, at }` (`channel` = next channel) | +| `messagegate.message.received` | `{ inboundId, contactId, channel, replyTo, kind, buttonPayload?, media?: { status }, at }` | +| `messagegate.media.ready` | `{ inboundId, fileId, mime, size, at }` (`fileId` is the media library id) | +| `messagegate.media.failed` | `{ inboundId, code, at }` | +| `messagegate.contact.opted-out` | `{ channel, at }`: opt-out keyword, `/stop`, Twilio `OptOutType=STOP`, Twilio 21610, seven.io 407004 | +| `messagegate.contact.unreachable` | `{ channel: 'whatsapp', at }` | +| `messagegate.template.status-changed` | template id, key, language, new status | ```js strapi.eventHub.on('messagegate.message.read', ({ messageId, templateKey }) => { diff --git a/CHANGELOG.md b/CHANGELOG.md index aec7611..8708cb5 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,23 @@ # Changelog +## [Unreleased] + +### Fixed + +- seven.io: the admin and README now say to set the webhook's request method to **JSON**. seven.io's default sends form fields, which MessageGate cannot read; such a signed webhook now logs a warning instead of being dropped without a trace. +- seven.io: SMS texts are cut at 1520 characters (the documented limit) instead of 1600, so texts between 1521 and 1600 characters no longer fail with code 401. +- seven.io: return code 101 for the single recipient is a rejection with the recipient's own error code instead of `uncertain`; 500 (no credit) and 501 (spending limit) mark the account unhealthy; 407004 (recipient unsubscribed) revokes SMS consent. +- seven.io: inbound SMS keep their real receive time (`time` is a Unix timestamp); HLR checks return `roaming` from the documented object. +- Twilio: error 21610 (recipient replied STOP) and an inbound `OptOutType=STOP` (Advanced Opt-Out) revoke consent for the channel, so later sends stop at the consent check instead of failing at Twilio. Error 21611 (sender queue full) is retried. +- Telegram: long texts with `&`, `<` or `>` are no longer cut inside an HTML entity (the Bot API refused them); the 4096 limit counts visible characters. +- Webhook URLs, Twilio status callbacks, signed file links and the webhook raw-body capture follow `api.rest.prefix`. With a custom prefix every webhook used to fail the signature check. +- Outgoing texts are never cut inside an emoji. +- `Retry-After` given as an HTTP date is honoured (capped at 24 hours). + +### Documentation + +- `docs/audits/2026-11-20-provider-apis.md`: audit of all four provider APIs against their official specs and docs. + ## [1.1.2](https://github.com/Schero94/Magic-MessageGate/compare/messagegate-v1.1.1...messagegate-v1.1.2) (2026-11-18) diff --git a/README.md b/README.md index 42a361a..4bd9b9d 100644 --- a/README.md +++ b/README.md @@ -182,6 +182,11 @@ Then, in **Accounts → Connect a channel → WhatsApp**, pick one of two ways: Copy the webhook URL shown for the account into the provider's status and inbound settings so delivery receipts and replies arrive. +- **seven.io**: dashboard → Developer → Webhooks, add the URL for the events `dlr` and `sms_mo` and set the **request method to JSON**. seven.io's default sends form fields, which MessageGate ignores (the Strapi log then says so). SMS texts are cut at 1520 characters, seven.io's limit. +- **Twilio**: set the URL as the status callback and the incoming-message webhook of the number or Messaging Service. With Advanced Opt-Out, a `STOP` reply revokes consent even when the keyword is not in MessageGate's own list, and Twilio error 21610 (recipient unsubscribed) does the same. + +Webhook URLs and file links follow `api.rest.prefix` from `config/api` (default `/api`). + ### RCS (Twilio) 1. Get an RCS sender approved in the Twilio Console and add it to a **Messaging Service**. diff --git a/admin/src/pages/Accounts/AccountWizard.jsx b/admin/src/pages/Accounts/AccountWizard.jsx index f9d1c50..70b6491 100644 --- a/admin/src/pages/Accounts/AccountWizard.jsx +++ b/admin/src/pages/Accounts/AccountWizard.jsx @@ -19,6 +19,7 @@ import { credentialPayload, fieldsFor, validateCredentials, + webhookHint, } from '../../utils/providers.mjs'; import { reasonText } from '../../utils/reasons'; @@ -614,10 +615,7 @@ export const AccountWizard = ({ mode, account, hasDefault, onClose, onSaved }) = name="webhookUrl" label={t('accounts.webhookUrl', 'Webhook URL')} value={result.account.webhookUrl} - hint={t( - 'accounts.webhookUrl.hint', - 'Enter it in the provider console for delivery and read receipts.' - )} + hint={webhookHint(t, result.account.provider)} /> ) : null} {result.account.provider === 'meta' && !result.steps ? ( diff --git a/admin/src/pages/Accounts/index.jsx b/admin/src/pages/Accounts/index.jsx index bd98939..009bf9d 100644 --- a/admin/src/pages/Accounts/index.jsx +++ b/admin/src/pages/Accounts/index.jsx @@ -16,6 +16,7 @@ import { useReturnFocus } from '../../hooks/useReturnFocus'; import { ToneBadge } from '../../components/ui/StatusBadge'; import { useT } from '../../hooks/useT'; import { channelLabels, providerLabels } from '../../utils/channels'; +import { webhookHint } from '../../utils/providers.mjs'; import { reasonText } from '../../utils/reasons'; import { AccountWizard } from './AccountWizard'; @@ -149,7 +150,7 @@ const AccountCard = ({ account, rbac, onEdit, onChanged }) => { hint={ account.provider === 'telegram' ? t('accounts.webhookUrl.telegram', 'Registered with Telegram automatically on "Test connection".') - : t('accounts.webhookUrl.hint', 'Enter it in the provider console for delivery and read receipts.') + : webhookHint(t, account.provider) } /> ) : ( diff --git a/admin/src/translations/de.json b/admin/src/translations/de.json index db117b4..6278771 100644 --- a/admin/src/translations/de.json +++ b/admin/src/translations/de.json @@ -84,7 +84,9 @@ "accounts.webhookUrl": "Webhook-URL", "accounts.webhookUrl.hint": "In der Konsole des Anbieters eintragen, für Zustell- und Lesebestätigungen.", "accounts.webhookUrl.missing": "Keine öffentliche URL konfiguriert (server.url), daher keine Webhook-URL. Zustellberichte brauchen sie.", + "accounts.webhookUrl.seven": "seven.io-Dashboard > Entwickler > Webhooks: diese URL für die Ereignisse „dlr“ und „sms_mo“ mit der Anfragemethode JSON eintragen.", "accounts.webhookUrl.telegram": "Wird bei „Verbindung testen“ automatisch bei Telegram registriert.", + "accounts.webhookUrl.twilio": "Twilio Console: als Status-Callback und als Webhook für eingehende Nachrichten der Nummer oder des Messaging Service eintragen.", "accounts.wizard.checkTitle": "Gespeichert, aber der Test schlug fehl", "accounts.wizard.choose": "Welcher Kanal soll verbunden werden?", "accounts.wizard.connectTest": "Verbinden und testen", diff --git a/admin/src/translations/en.json b/admin/src/translations/en.json index 846198f..fb7371a 100644 --- a/admin/src/translations/en.json +++ b/admin/src/translations/en.json @@ -84,7 +84,9 @@ "accounts.webhookUrl": "Webhook URL", "accounts.webhookUrl.hint": "Enter it in the provider console for delivery and read receipts.", "accounts.webhookUrl.missing": "No public URL configured (server.url), so no webhook URL can be shown. Delivery receipts need it.", + "accounts.webhookUrl.seven": "seven.io dashboard > Developer > Webhooks: add this URL for the events \"dlr\" and \"sms_mo\" with the request method JSON.", "accounts.webhookUrl.telegram": "Registered with Telegram automatically on \"Test connection\".", + "accounts.webhookUrl.twilio": "Twilio Console: use it as the status callback and the incoming message webhook of the number or Messaging Service.", "accounts.wizard.checkTitle": "Saved, but the test failed", "accounts.wizard.choose": "Which channel do you want to connect?", "accounts.wizard.connectTest": "Connect and test", diff --git a/admin/src/translations/es.json b/admin/src/translations/es.json index 7ad171e..6d5b575 100644 --- a/admin/src/translations/es.json +++ b/admin/src/translations/es.json @@ -84,7 +84,9 @@ "accounts.webhookUrl": "URL del webhook", "accounts.webhookUrl.hint": "Introdúcela en la consola del proveedor para las confirmaciones de entrega y lectura.", "accounts.webhookUrl.missing": "No hay URL pública configurada (server.url), así que no se puede mostrar la URL del webhook. Los informes de entrega la necesitan.", + "accounts.webhookUrl.seven": "Panel de seven.io > Developer > Webhooks: añade esta URL para los eventos «dlr» y «sms_mo» con el método de solicitud JSON.", "accounts.webhookUrl.telegram": "Se registra automáticamente en Telegram al pulsar «Probar conexión».", + "accounts.webhookUrl.twilio": "Twilio Console: úsala como status callback y como webhook de mensajes entrantes del número o del Messaging Service.", "accounts.wizard.checkTitle": "Guardada, pero la prueba falló", "accounts.wizard.choose": "¿Qué canal quieres conectar?", "accounts.wizard.connectTest": "Conectar y probar", diff --git a/admin/src/translations/fr.json b/admin/src/translations/fr.json index 53a35c0..9dd197f 100644 --- a/admin/src/translations/fr.json +++ b/admin/src/translations/fr.json @@ -84,7 +84,9 @@ "accounts.webhookUrl": "URL du webhook", "accounts.webhookUrl.hint": "À saisir dans la console du fournisseur pour les accusés de livraison et de lecture.", "accounts.webhookUrl.missing": "Aucune URL publique configurée (server.url), donc aucune URL de webhook. Les accusés de livraison en ont besoin.", + "accounts.webhookUrl.seven": "Tableau de bord seven.io > Developer > Webhooks : ajoutez cette URL pour les événements « dlr » et « sms_mo » avec la méthode de requête JSON.", "accounts.webhookUrl.telegram": "Enregistré automatiquement auprès de Telegram lors de « Tester la connexion ».", + "accounts.webhookUrl.twilio": "Twilio Console : utilisez-la comme status callback et comme webhook des messages entrants du numéro ou du Messaging Service.", "accounts.wizard.checkTitle": "Enregistré, mais le test a échoué", "accounts.wizard.choose": "Quel canal voulez-vous connecter ?", "accounts.wizard.connectTest": "Connecter et tester", diff --git a/admin/src/translations/pt.json b/admin/src/translations/pt.json index 0f00fa0..aae0982 100644 --- a/admin/src/translations/pt.json +++ b/admin/src/translations/pt.json @@ -84,7 +84,9 @@ "accounts.webhookUrl": "URL do webhook", "accounts.webhookUrl.hint": "Informe no console do provedor para as confirmações de entrega e leitura.", "accounts.webhookUrl.missing": "Nenhuma URL pública configurada (server.url), por isso não há URL de webhook. Os relatórios de entrega precisam dela.", + "accounts.webhookUrl.seven": "Painel da seven.io > Developer > Webhooks: adicione esta URL para os eventos \"dlr\" e \"sms_mo\" com o método de requisição JSON.", "accounts.webhookUrl.telegram": "Registrada automaticamente no Telegram ao usar \"Testar conexão\".", + "accounts.webhookUrl.twilio": "Twilio Console: use-a como status callback e como webhook de mensagens recebidas do número ou do Messaging Service.", "accounts.wizard.checkTitle": "Salva, mas o teste falhou", "accounts.wizard.choose": "Qual canal você quer conectar?", "accounts.wizard.connectTest": "Conectar e testar", diff --git a/admin/src/utils/providers.mjs b/admin/src/utils/providers.mjs index 2d07700..ef9e92e 100644 --- a/admin/src/utils/providers.mjs +++ b/admin/src/utils/providers.mjs @@ -147,3 +147,29 @@ export function credentialPayload(provider, values, channel = PROVIDER_CHANNEL[p } return config; } + +/** + * Where the owner enters an account's webhook URL, per provider. seven.io + * posts form fields unless the hook's request method is JSON, which + * MessageGate needs to read delivery reports and replies + * (https://docs.seven.io/en/rest-api/endpoints/webhooks). + * + * @param {(id: string, fallback: string, values?: object) => string} t - Translator. + * @param {string} provider + * @returns {string} + */ +export function webhookHint(t, provider) { + if (provider === 'seven') { + return t( + 'accounts.webhookUrl.seven', + 'seven.io dashboard > Developer > Webhooks: add this URL for the events "dlr" and "sms_mo" with the request method JSON.' + ); + } + if (provider === 'twilio') { + return t( + 'accounts.webhookUrl.twilio', + 'Twilio Console: use it as the status callback and the incoming message webhook of the number or Messaging Service.' + ); + } + return t('accounts.webhookUrl.hint', 'Enter it in the provider console for delivery and read receipts.'); +} diff --git a/docs/audits/2026-11-20-provider-apis.md b/docs/audits/2026-11-20-provider-apis.md new file mode 100644 index 0000000..6a17300 --- /dev/null +++ b/docs/audits/2026-11-20-provider-apis.md @@ -0,0 +1,46 @@ +# Provider API audit (2026-11-20) + +Every adapter in `server/src/adapters` was read against the providers' current official documentation and, where one exists, their official machine-readable specification. All sources were retrieved on 2026-11-20. + +## Sources + +| Provider | Official machine-readable spec (pinned) | Human docs read | +| ---------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| Meta WhatsApp Cloud API | [facebook/openapi](https://github.com/facebook/openapi) `business-messaging-api_v23.0.yaml`, commit `e96a1c9dbf240c2937b6a95920685230458e346b` (2026-08-11), sha256 `5c197326…bd9b09d` | [Messages](https://developers.facebook.com/docs/whatsapp/cloud-api/reference/messages), [error codes](https://developers.facebook.com/docs/whatsapp/cloud-api/support/error-codes), [webhooks](https://developers.facebook.com/docs/graph-api/webhooks/getting-started), [Graph API versions](https://developers.facebook.com/docs/graph-api/changelog/versions) | +| Twilio Messaging, Lookup v2, Content API | [twilio/twilio-oai](https://github.com/twilio/twilio-oai) `spec/json/twilio_api_v2010.json`, `twilio_lookups_v2.json`, `twilio_content_v1.json`, tag `2.11.1` = commit `090e1654f5ca1f6a01b6a117fbec5f75c44f44d7` (2026-11-17) | [Message resource](https://www.twilio.com/docs/messaging/api/message-resource), [webhook request](https://www.twilio.com/docs/messaging/guides/webhook-request), [webhook security](https://www.twilio.com/docs/usage/webhooks/webhooks-security), [error 21610](https://www.twilio.com/docs/api/errors/21610), [test credentials](https://www.twilio.com/docs/iam/test-credentials), [OptOutType](https://support.twilio.com/hc/en-us/articles/31560110671259) | +| seven.io | [seven-io/api-schemes](https://github.com/seven-io/api-schemes) `json/openapi.json` ("Official API Schemes for seven.io"), commit `0c976749e132089f51fe50fc865004c1294d198f` (2026-05-26) | [SMS](https://docs.seven.io/en/rest-api/endpoints/sms), [webhooks](https://docs.seven.io/en/rest-api/webhooks), [webhook endpoints](https://docs.seven.io/en/rest-api/endpoints/webhooks), [signing](https://docs.seven.io/en/rest-api/signing), [status reports](https://docs.seven.io/en/rest-api/endpoints/status-reports) | +| Telegram Bot API | none: Telegram publishes no OpenAPI. The contract tests use a snapshot of the method and type tables of the official HTML page, Bot API 10.4 (2026-11-09) | [core.telegram.org/bots/api](https://core.telegram.org/bots/api) | + +## Findings + +Severity: **high** = messages or receipts are lost silently, **medium** = wrong outcome for a documented case, **low** = wrong detail, **info** = documented behaviour, no change. + +| # | Area | Finding | Severity | Status | +| --- | ----------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | -------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| 1 | seven.io webhooks | seven.io sends webhooks form-encoded unless the hook's request method is `JSON` ("POST (default): application/x-www-form-urlencoded"). MessageGate only parsed JSON, so with the default setting every signed delivery report and inbound SMS was answered `200` and dropped without a trace. | high | Fixed: the admin now says "request method JSON" next to the seven.io webhook URL (5 locales), README says it, and a signed non-JSON body logs a warning that names the fix. Parsing the form shape is not done because seven.io documents only the JSON payload. | +| 2 | REST prefix | Webhook URLs, the Twilio `StatusCallback`, signed file links, the Meta app webhook URL and the raw-body middleware were hard-coded to `/api`. With a custom `api.rest.prefix` ([Strapi API config](https://docs.strapi.io/cms/configurations/api)) every webhook failed the signature check (no raw body) and every URL shown to the owner was wrong. | medium | Fixed: all of them use `api.rest.prefix`. | +| 3 | Telegram send | The adapter cut the HTML text to 4096 UTF-16 units. Escaped text (`&` counts as one visible character) can be longer than 4096 units while within the Bot API's "1-4096 characters after entities parsing"; the cut could split an entity, which the Bot API refuses ("can't parse entities") as a permanent failure. | medium | Fixed: the limit is applied to visible characters and never inside an entity; the attachment-link fallback keeps room for the link. | +| 4 | seven.io send | MessageGate cut SMS text at 1600 characters; the official OpenAPI says `text` "may not exceed 1520 characters" and seven.io answers code 401. Texts between 1521 and 1600 characters always failed. | medium | Fixed: the seven.io adapter cuts at 1520. | +| 5 | Text cuts | Every `slice(0, n)` on outgoing text could cut an emoji (surrogate pair) in half and send an invalid string. | low | Fixed: `safeSlice` keeps pairs whole. | +| 6 | seven.io codes | 101 with one recipient means that recipient failed, but was reported as `uncertain` (admin decision). 501 (spending limit) and 500 (no credit) did not mark the account unhealthy. 407004 (recipient unsubscribed) did not revoke consent. | medium | Fixed: 101 uses the message's own error code and is a rejection; 500/501 flag the account; 407004 revokes SMS consent. | +| 7 | Twilio opt-out | Error 21610 (recipient replied STOP; Twilio blocks the sender until START) failed the message but kept consent `granted`, so every later send failed again. Advanced Opt-Out's `OptOutType=STOP` was ignored when the keyword was not in MessageGate's own list (Twilio's list also has STOPALL, CANCEL, END, QUIT, …). | medium | Fixed: both revoke consent for the channel (`source: provider-opt-out`). `START` is not taken as consent. | +| 8 | seven.io inbound | `sms_mo` `time` is a Unix timestamp ("1605878104" in the official example); `Date.parse` returned `NaN`, so inbound SMS got the arrival time instead. | low | Fixed. | +| 9 | seven.io HLR | The official schema documents `roaming` as an object (`{status: unknown \| roaming \| not_roaming}`); the adapter only read a string and always returned `null`. | low | Fixed (both shapes). | +| 10 | Retry-After | Only delay-seconds were read; the HTTP-date form (RFC 9110 10.2.3) was ignored. | low | Fixed, capped at 24 hours. | +| 11 | Meta Graph version | Default `v23.0` matches the official OpenAPI (v23.0) and is available until 2027-10-08 (v24.0 until 2028-02-18, v25.0 until 2028-07-29, v26.0 current). | info | A test now fails 90 days before the end of support. Moving the default is an owner decision (see "Open decisions"). | +| 12 | Meta statuses | Official webhook enum: `sent`, `delivered`, `read`, `failed`. `played` is not documented; the mapping keeps it as an alias of `read`. | info | No change. | +| 13 | Meta errors | Throttling codes 4, 80007, 130429, 131048, 131056, 133016 are transient; 1, 2, 131000 ambiguous; 131026 marks WhatsApp unreachable; 131047 (re-engagement, 24-hour window) is a rejection. Matches the error-code page. | info | No change. | +| 14 | 24-hour window | Free text on WhatsApp is only routed inside 24 h after the contact's last WhatsApp message (`sender.js`, `WINDOW_MS`); outside it a template is required. | info | No change. | +| 15 | Signatures | Meta `X-Hub-Signature-256` (HMAC-SHA256, raw body, app secret), Twilio `X-Twilio-Signature` (HMAC-SHA1, URL + sorted form pairs), Telegram `X-Telegram-Bot-Api-Secret-Token`, seven.io `X-Signature` (HMAC-SHA256 over timestamp, nonce, method, URL, MD5 of body, optional account id; 30 s window; nonce once) all match the docs and compare in constant time. | info | No change; covered by contract tests. | +| 16 | seven.io retries | seven.io retries only on 429, 5xx and network errors, up to 14 times over 3.5 days, with fresh `X-Timestamp`/`X-Nonce` per attempt; 4xx is final. MessageGate's `401` on a bad signature and `500` on a processing error fit this. | info | No change. | +| 17 | seven.io sandbox | `POST /api/sms` has no sandbox or debug switch in the current docs or OpenAPI (only a `debug` field in the response). Every accepted SMS is billed. | info | The live suite only sends with an explicit opt-in. | +| 18 | Twilio test credentials | Test credentials work for `POST /Messages` and Lookup v2 with the magic numbers (`From +15005550006` valid, `+15005550001` → 21212, `+15005550007` → 21606, `+15005550008` → 21611; `To +15005550001` → 21211, `+15005550002` → 21612, `+15005550003` → 21408, `+15005550004` → 21610, `+15005550009` → 21614). They answer 403 for every other resource (so the account check `GET /Accounts/{sid}` cannot run), do not accept a Messaging Service and trigger no status callbacks. | info | The live suite uses them for the error mapping. | +| 18a | Twilio 21611 | "SMS queue for this number is full" was a permanent rejection; nothing was sent and a later try works. | low | Fixed: transient (next account or retry with backoff). | +| 19 | Idempotency | None of the four APIs offers an idempotency key for sends. MessageGate never retries an ambiguous send; seven.io's own 180-second duplicate block (402) is reported as `uncertain` because the first copy was sent. | info | No change. | +| 20 | Unicode / GSM-7 | `smsSegments` follows GSM 03.38 (basic set, extension table counts double) and UCS-2 (70/67, astral characters count two units). | info | No change. | + +## Open decisions + +- Move the Meta default from `v23.0` to `v25.0` (supported until 2028-07-29) once Meta publishes an OpenAPI for it; the official spec is still v23.0. +- Register the seven.io webhook automatically on "Test connection" (`POST /api/hooks` with `request_method=JSON`, like Telegram's `setWebhook`), instead of asking the owner to enter it. +- Parse the form-encoded seven.io webhook once seven.io documents its field names, or once a live run records them. diff --git a/docs/site/llms-full.txt b/docs/site/llms-full.txt index b1cfb52..644efc8 100644 --- a/docs/site/llms-full.txt +++ b/docs/site/llms-full.txt @@ -187,6 +187,11 @@ Then, in **Accounts → Connect a channel → WhatsApp**, pick one of two ways: Copy the webhook URL shown for the account into the provider's status and inbound settings so delivery receipts and replies arrive. +- **seven.io**: dashboard → Developer → Webhooks, add the URL for the events `dlr` and `sms_mo` and set the **request method to JSON**. seven.io's default sends form fields, which MessageGate ignores (the Strapi log then says so). SMS texts are cut at 1520 characters, seven.io's limit. +- **Twilio**: set the URL as the status callback and the incoming-message webhook of the number or Messaging Service. With Advanced Opt-Out, a `STOP` reply revokes consent even when the keyword is not in MessageGate's own list, and Twilio error 21610 (recipient unsubscribed) does the same. + +Webhook URLs and file links follow `api.rest.prefix` from `config/api` (default `/api`). + ### RCS (Twilio) 1. Get an RCS sender approved in the Twilio Console and add it to a **Messaging Service**. @@ -862,23 +867,23 @@ Use the delivery id to ignore repeats. No phone numbers, names or message text in any payload. Every event is emitted by exactly one process. -| Event | Payload | -| ------------------------------------- | ---------------------------------------------------------------------------------------------- | -| `messagegate.message.queued` | `{ messageId, channel, templateKey, status, code?, at }` | -| `messagegate.message.sent` | same | -| `messagegate.message.delivered` | same | -| `messagegate.message.read` | same | -| `messagegate.message.failed` | same, `code` set | -| `messagegate.message.uncertain` | same, `code` set | -| `messagegate.message.expired` | same, `code: 'DEADLINE_PASSED'` | -| `messagegate.message.discarded` | same | -| `messagegate.message.fallback` | `{ messageId, channel, templateKey, status: 'fallback', code, at }` (`channel` = next channel) | -| `messagegate.message.received` | `{ inboundId, contactId, channel, replyTo, kind, buttonPayload?, media?: { status }, at }` | -| `messagegate.media.ready` | `{ inboundId, fileId, mime, size, at }` (`fileId` is the media library id) | -| `messagegate.media.failed` | `{ inboundId, code, at }` | -| `messagegate.contact.opted-out` | `{ channel, at }` | -| `messagegate.contact.unreachable` | `{ channel: 'whatsapp', at }` | -| `messagegate.template.status-changed` | template id, key, language, new status | +| Event | Payload | +| ------------------------------------- | ---------------------------------------------------------------------------------------------------- | +| `messagegate.message.queued` | `{ messageId, channel, templateKey, status, code?, at }` | +| `messagegate.message.sent` | same | +| `messagegate.message.delivered` | same | +| `messagegate.message.read` | same | +| `messagegate.message.failed` | same, `code` set | +| `messagegate.message.uncertain` | same, `code` set | +| `messagegate.message.expired` | same, `code: 'DEADLINE_PASSED'` | +| `messagegate.message.discarded` | same | +| `messagegate.message.fallback` | `{ messageId, channel, templateKey, status: 'fallback', code, at }` (`channel` = next channel) | +| `messagegate.message.received` | `{ inboundId, contactId, channel, replyTo, kind, buttonPayload?, media?: { status }, at }` | +| `messagegate.media.ready` | `{ inboundId, fileId, mime, size, at }` (`fileId` is the media library id) | +| `messagegate.media.failed` | `{ inboundId, code, at }` | +| `messagegate.contact.opted-out` | `{ channel, at }`: opt-out keyword, `/stop`, Twilio `OptOutType=STOP`, Twilio 21610, seven.io 407004 | +| `messagegate.contact.unreachable` | `{ channel: 'whatsapp', at }` | +| `messagegate.template.status-changed` | template id, key, language, new status | ```js strapi.eventHub.on('messagegate.message.read', ({ messageId, templateKey }) => { diff --git a/server/src/adapters/http.js b/server/src/adapters/http.js index 986c892..f52e900 100644 --- a/server/src/adapters/http.js +++ b/server/src/adapters/http.js @@ -45,6 +45,28 @@ function causeCode(error) { return typeof code === 'string' ? code : String(error?.name || 'FETCH_ERROR'); } +/** + * Retry-After is either delay-seconds or an HTTP-date (RFC 9110, section + * 10.2.3). Values are capped at one day so a broken header cannot park a + * message for weeks. + * + * @param {string|null} header + * @param {number} [now] + * @returns {number|null} Milliseconds to wait, or null. + */ +function parseRetryAfter(header, now = Date.now()) { + const value = String(header ?? '').trim(); + if (!value) return null; + let ms = null; + if (/^\d{1,9}$/.test(value)) ms = Number(value) * 1000; + else { + const at = Date.parse(value); + if (Number.isFinite(at)) ms = at - now; + } + if (ms === null || !(ms > 0)) return null; + return Math.min(ms, 86_400_000); +} + /** * Performs one request and classifies the outcome. * @@ -88,8 +110,7 @@ async function request({ url, method = 'POST', headers = {}, body, timeoutMs = 1 } } const status = response.status; - const retryAfterHeader = Number(response.headers.get('retry-after')); - const retryAfterMs = Number.isFinite(retryAfterHeader) && retryAfterHeader > 0 ? retryAfterHeader * 1000 : null; + const retryAfterMs = parseRetryAfter(response.headers.get('retry-after')); if (status >= 200 && status < 300) return { outcome: 'accepted', status, json, code: null, retryAfterMs: null }; if (status === 429 || status === 503) return { outcome: 'transient', status, json, code: `HTTP_${status}`, retryAfterMs }; @@ -99,4 +120,4 @@ async function request({ url, method = 'POST', headers = {}, body, timeoutMs = 1 return { outcome: 'rejected', status, json, code: `HTTP_${status}`, retryAfterMs: null }; } -module.exports = { request, PRE_SEND_CODES }; +module.exports = { request, parseRetryAfter, PRE_SEND_CODES }; diff --git a/server/src/adapters/meta.js b/server/src/adapters/meta.js index d28e65f..5833930 100644 --- a/server/src/adapters/meta.js +++ b/server/src/adapters/meta.js @@ -25,6 +25,13 @@ * /upload: with `Authorization: OAuth ` and `file_offset: 0`, * answer `{ h }`): https://developers.facebook.com/docs/graph-api/guides/upload * and .../whatsapp/templates/components.md + * + * Re-checked 2026-11-20 against Meta's official OpenAPI + * (github.com/facebook/openapi, business-messaging-api_v23.0.yaml at + * e96a1c9d) and the Graph API + * versions table (https://developers.facebook.com/docs/graph-api/changelog/versions): + * v23.0 is available until 2027-10-08. The webhook status enum is sent, + * delivered, read, failed; `played` is kept as an alias of read. */ const { request } = require('./http'); const { fetchLimited, onHost } = require('../utils/download'); diff --git a/server/src/adapters/seven.js b/server/src/adapters/seven.js index 12eea48..fa1c7bb 100644 --- a/server/src/adapters/seven.js +++ b/server/src/adapters/seven.js @@ -13,6 +13,20 @@ * DELIVERED, NOTDELIVERED, BUFFERED, TRANSMITTED, ACCEPTED, EXPIRED, * REJECTED, FAILED. * - Webhooks are signed like requests (see utils/signatures.js). + * + * Re-read 2026-11-20 (provider audit, docs/audits/2026-11-20-provider-apis.md): + * - `text` "may not exceed 1520 characters" (official OpenAPI, + * github.com/seven-io/api-schemes json/openapi.json); longer texts are + * refused with code 401, so the adapter cuts at 1520 like the SMS path + * cuts at 1600 for Twilio. + * - Return codes (docs.seven.io/en/rest-api/endpoints/sms): 101 "sending to + * at least one recipient failed" (one recipient here, so it failed), 402 + * duplicate within 180 seconds (the first one was sent), 403 daily limit + * for this recipient, 407001-407005 declined / country blocked / number + * blocked / recipient unsubscribed / price limit, 500 no credit, 501 + * spending limit, 900-903 authentication. + * - There is no sandbox or debug switch for POST /api/sms; every accepted + * SMS is billed. * - https://docs.seven.io/en/rest-api/endpoints/lookup (read 2026-11-11): * GET /api/lookup/hlr?number=…, fields `valid_number` (valid | not_valid | * unknown), `reachable` (reachable | absent | bad_number | unknown), @@ -21,13 +35,19 @@ * Paid per request (0.01 EUR per seven.io price list). */ const { request } = require('./http'); +const { safeSlice } = require('../utils/template-engine'); const DEFAULT_BASE = 'https://gateway.seven.io'; +/** Longest `text` seven.io accepts (official OpenAPI: "may not exceed 1520 characters"). */ +const MAX_TEXT = 1520; + /** Return codes that prove nothing was sent and a later try can work. */ const TRANSIENT = new Set(['500', '403']); -/** Return codes that point at the account configuration. */ -const ACCOUNT = new Set(['201', '900', '901', '902', '903']); +/** Return codes that point at the account configuration (no credit, spending limit, auth, sender). */ +const ACCOUNT = new Set(['201', '500', '501', '900', '901', '902', '903']); +/** Recipient opted out at seven.io: consent for SMS is revoked. */ +const OPTED_OUT = new Set(['407004']); /** Return codes where the SMS may already have been sent. */ const AMBIGUOUS = new Set(['402', '600']); @@ -47,13 +67,14 @@ module.exports = { channel: 'sms', provider: 'seven', DLR_STATUS, + MAX_TEXT, /** * @param {{config: object, to: string, payload: {text: string}, messageId?: string, settings?: object, fetchImpl?: Function}} input * @returns {Promise<{outcome: string, providerMessageId: string|null, code: string|null, retryAfterMs: number|null, accountProblem: boolean}>} */ async send({ config, to, payload, messageId, settings, fetchImpl }) { - const form = new URLSearchParams({ to, text: payload.text }); + const form = new URLSearchParams({ to, text: safeSlice(payload.text, MAX_TEXT) }); if (config.senderId) form.set('from', config.senderId); if (messageId) form.set('foreign_id', String(messageId).slice(0, 64)); const res = await request({ @@ -87,9 +108,29 @@ module.exports = { accountProblem: false, }; } - const code = `SEVEN_${success || 'UNKNOWN'}`; - if (TRANSIENT.has(success)) - return { outcome: 'transient', providerMessageId: null, code, retryAfterMs: null, accountProblem: false }; + // One recipient per request: 101 ("at least one recipient failed") means + // this one failed, and the message entry carries the reason. + const messageError = first && first.success === false && first.error ? String(first.error).slice(0, 20) : ''; + const reason = success === '101' && /^\d{3,6}$/.test(messageError) ? messageError : success; + const code = `SEVEN_${reason || 'UNKNOWN'}`; + if (TRANSIENT.has(reason)) + return { + outcome: 'transient', + providerMessageId: null, + code, + retryAfterMs: null, + accountProblem: ACCOUNT.has(reason), + }; + if (success === '101' && first?.success === false) { + return { + outcome: 'rejected', + providerMessageId: null, + code, + retryAfterMs: null, + accountProblem: ACCOUNT.has(reason), + optedOut: OPTED_OUT.has(reason), + }; + } if (AMBIGUOUS.has(success) || success === '101' || !success) { return { outcome: 'ambiguous', @@ -105,6 +146,7 @@ module.exports = { code, retryAfterMs: null, accountProblem: ACCOUNT.has(success), + optedOut: OPTED_OUT.has(success), }; }, @@ -141,7 +183,9 @@ module.exports = { valid: word(j.valid_number), reachable: word(j.reachable), ported: word(j.ported), - roaming: typeof j.roaming === 'string' ? word(j.roaming) : null, + // The official schema documents `roaming` as an object with `status` + // (unknown | roaming | not_roaming); older answers sent a string. + roaming: typeof j.roaming === 'string' ? word(j.roaming) : word(j.roaming?.status), network: typeof carrier.name === 'string' ? carrier.name.slice(0, 60) : null, networkType: word(carrier.network_type), }; diff --git a/server/src/adapters/telegram.js b/server/src/adapters/telegram.js index 8052ea9..f165334 100644 --- a/server/src/adapters/telegram.js +++ b/server/src/adapters/telegram.js @@ -16,6 +16,7 @@ */ const { request } = require('./http'); const { fetchLimited } = require('../utils/download'); +const { truncateTelegramText } = require('../utils/template-engine'); /** getFile downloads are limited to 20 MB by the Bot API. */ const MAX_DOWNLOAD = 20 * 1024 * 1024; @@ -88,7 +89,10 @@ module.exports = { let method = 'sendMessage'; let body = { chat_id: to, - text: String(payload.text).slice(0, MAX_TEXT), + // `text` is HTML (parse_mode HTML). Cutting the raw string could split an + // entity such as `&` and the Bot API would refuse the message, so the + // limit is applied to visible characters. + text: truncateTelegramText(payload.text, MAX_TEXT), parse_mode: 'HTML', link_preview_options: { is_disabled: true }, }; diff --git a/server/src/adapters/twilio.js b/server/src/adapters/twilio.js index d2c75b9..b8549a7 100644 --- a/server/src/adapters/twilio.js +++ b/server/src/adapters/twilio.js @@ -45,6 +45,12 @@ const CONTENT_BASE = 'https://content.twilio.com'; /** Twilio error codes that are about the recipient (permanent). */ const RECIPIENT_CODES = new Set([21211, 21214, 21408, 21610, 21612, 21614, 63021, 63035, 63036]); +/** + * 21610 "Attempt to send to unsubscribed recipient": the recipient replied + * STOP and Twilio blocks every further message from this sender until they + * reply START (https://www.twilio.com/docs/api/errors/21610). + */ +const OPTED_OUT_CODES = new Set([21610]); /** Twilio error codes about the account or sender configuration. */ const ACCOUNT_CODES = new Set([20003, 20404, 21212, 21606, 21659, 30007]); @@ -124,7 +130,9 @@ module.exports = { const twilioCode = Number(res.json?.code); if (Number.isFinite(twilioCode)) { const code = `TWILIO_${twilioCode}`; - if (twilioCode === 20429) + // 20429 too many requests; 21611 the From number's queue is full + // (https://www.twilio.com/docs/api/errors/21611): nothing was sent. + if (twilioCode === 20429 || twilioCode === 21611) return { outcome: 'transient', providerMessageId: null, @@ -139,6 +147,7 @@ module.exports = { code, retryAfterMs: null, accountProblem: ACCOUNT_CODES.has(twilioCode), + optedOut: OPTED_OUT_CODES.has(twilioCode), }; } } diff --git a/server/src/controllers/admin.js b/server/src/controllers/admin.js index 3561362..9d16505 100644 --- a/server/src/controllers/admin.js +++ b/server/src/controllers/admin.js @@ -111,8 +111,7 @@ module.exports = ({ strapi }) => { appId: signup.appId || null, configId: signup.configId || null, graphVersion: c.ctx.config.providers.meta.graphVersion || 'v23.0', - webhookUrl: - signup.verifyToken && c.ctx.publicUrl ? `${c.ctx.publicUrl}/api/magic-messagegate/webhooks/meta/app` : null, + webhookUrl: signup.verifyToken && c.ctx.publicUrl ? `${c.ctx.apiBase}/webhooks/meta/app` : null, }; }; diff --git a/server/src/core/accounts.js b/server/src/core/accounts.js index 2e17fb2..fb7c6c6 100644 --- a/server/src/core/accounts.js +++ b/server/src/core/accounts.js @@ -199,7 +199,7 @@ function createAccounts(ctx) { */ function webhookUrl(row) { if (!ctx.publicUrl) return null; - return `${ctx.publicUrl}/api/magic-messagegate/webhooks/${row.provider}/${row.webhook_path}`; + return `${ctx.apiBase}/webhooks/${row.provider}/${row.webhook_path}`; } /** diff --git a/server/src/core/attachments.js b/server/src/core/attachments.js index f1743f5..515eb80 100644 --- a/server/src/core/attachments.js +++ b/server/src/core/attachments.js @@ -220,7 +220,7 @@ function createAttachments(ctx) { * @returns {Promise} Absolute URL. */ async createLink(file, ttlHours, { dryRun = false } = {}) { - if (dryRun) return `${ctx.publicUrl}/api/magic-messagegate/files/`; + if (dryRun) return `${ctx.apiBase}/files/`; const ref = { source: file.source, fileId: file.fileId, @@ -248,7 +248,7 @@ function createAttachments(ctx) { created_at: ctx.now(), }); return { - url: `${ctx.publicUrl}/api/magic-messagegate/files/${id}.${exp}.${sign(`${id}.${exp}`)}`, + url: `${ctx.apiBase}/files/${id}.${exp}.${sign(`${id}.${exp}`)}`, expiresAt: exp * 1000, }; }, diff --git a/server/src/core/context.js b/server/src/core/context.js index c358cab..d142bdc 100644 --- a/server/src/core/context.js +++ b/server/src/core/context.js @@ -24,11 +24,28 @@ const { adapterFor } = require('../adapters'); * @property {string} nodeId * @property {object|null} magicMail - Magic Mail email-router service when installed. * @property {string} publicUrl + * @property {string} apiBase - `publicUrl` plus the REST prefix and plugin id, e.g. `https://cms.example.test/api/magic-messagegate`. * @property {string} [encryptionKey] * @property {{get: Function, localPath?: Function, fetchRemote?: Function}|null} files - Media library access. * @property {(provider: string) => object|null} adapter - Provider adapter (live or sandbox). */ +/** + * Normalises Strapi's `api.rest.prefix` (default `/api`, + * https://docs.strapi.io/cms/configurations/api): one leading slash, no + * trailing slash. + * + * @param {string|undefined|null} prefix + * @returns {string} e.g. `/api`, `/v1`, or `` for an empty prefix. + */ +function restPrefixOf(prefix) { + if (prefix === undefined || prefix === null) return '/api'; + const trimmed = String(prefix) + .trim() + .replace(/^\/+|\/+$/g, ''); + return trimmed ? `/${trimmed}` : ''; +} + /** * @param {object} input * @returns {CoreContext} @@ -48,6 +65,7 @@ function createContext(input) { nodeId: input.nodeId || `${os.hostname().slice(0, 30)}:${process.pid}:${crypto.randomBytes(3).toString('hex')}`, magicMail: input.magicMail || null, publicUrl: String(input.publicUrl || config.publicUrl || '').replace(/\/+$/, ''), + apiBase: `${String(input.publicUrl || config.publicUrl || '').replace(/\/+$/, '')}${restPrefixOf(input.restPrefix)}/magic-messagegate`, encryptionKey: config.encryptionKey, files: input.files || null, adapter: (provider) => adapterFor(provider, config.providers.mode), @@ -83,4 +101,4 @@ function parseJson(text, fallback) { } } -module.exports = { createContext, newId, parseJson }; +module.exports = { createContext, newId, parseJson, restPrefixOf }; diff --git a/server/src/core/outbox.js b/server/src/core/outbox.js index 4cbc0b9..dd108df 100644 --- a/server/src/core/outbox.js +++ b/server/src/core/outbox.js @@ -293,7 +293,7 @@ function createOutbox(ctx, deps) { const settings = ctx.config.providers[account.provider] || {}; const statusCallbackUrl = account.provider === 'twilio' && ctx.publicUrl - ? `${ctx.publicUrl}/api/magic-messagegate/webhooks/twilio/${account.webhook_path}` + ? `${ctx.apiBase}/webhooks/twilio/${account.webhook_path}` : undefined; try { result = await adapter.send({ @@ -376,6 +376,11 @@ function createOutbox(ctx, deps) { if (result.outcome === 'rejected') { if (result.blocked && row.contact_id) await deps.contacts.suppress(row.contact_id, 'telegram', 'blocked_bot'); + // The provider reports that the recipient unsubscribed there (Twilio + // 21610, seven.io 407004): record it, so the next send stops at consent. + if (result.optedOut && row.contact_id) { + await deps.contacts.setConsent(row.contact_id, row.channel, 'revoked', 'provider-opt-out'); + } await fail(row, result.code || 'REJECTED', { account_id: usedAccount.id }); return 'failed'; } diff --git a/server/src/core/sender.js b/server/src/core/sender.js index c6d43ff..08ee624 100644 --- a/server/src/core/sender.js +++ b/server/src/core/sender.js @@ -204,18 +204,18 @@ function createSender(ctx, deps) { rendered = { payload: { kind: 'buttons', - text: text.slice(0, 1024), + text: engine.safeSlice(text, 1024), buttons: seed.buttons.map((b) => ({ id: b.payload, title: engine.clean(b.title) })), }, }; - } else rendered = { payload: { kind: 'text', text: text.slice(0, 4096) } }; + } else rendered = { payload: { kind: 'text', text: engine.safeSlice(text, 4096) } }; } else if (channel === 'telegram') { rendered = { payload: { text: engine.escapeHtml(text) } }; if (seed.buttons?.length) { rendered.payload.buttons = seed.buttons.map((b) => ({ payload: b.payload, title: engine.clean(b.title) })); } - } else if (channel === 'rcs') rendered = { payload: { kind: 'rcs', text: text.slice(0, 1600) } }; - else rendered = { payload: { text: text.slice(0, 1600) } }; + } else if (channel === 'rcs') rendered = { payload: { kind: 'rcs', text: engine.safeSlice(text, 1600) } }; + else rendered = { payload: { text: engine.safeSlice(text, 1600) } }; rendered.preview = text; } if (!file || !plan) return rendered; @@ -246,11 +246,13 @@ function createSender(ctx, deps) { }; } const url = await link(); - return { ...rendered, payload: { ...payload, text: `${payload.text}\n\n${engine.escapeHtml(url)}` } }; + // The Bot API counts at most 4096 visible characters; keep room for the link. + const text = engine.truncateTelegramText(payload.text, 4096 - url.length - 2); + return { ...rendered, payload: { ...payload, text: `${text}\n\n${engine.escapeHtml(url)}` } }; } const url = await link(); const room = 1600 - url.length - 1; - return { ...rendered, payload: { text: `${String(payload.text).slice(0, room)}\n${url}` } }; + return { ...rendered, payload: { text: `${engine.safeSlice(payload.text, room)}\n${url}` } }; } /** diff --git a/server/src/core/templates.js b/server/src/core/templates.js index eb58aaa..1e83416 100644 --- a/server/src/core/templates.js +++ b/server/src/core/templates.js @@ -524,7 +524,7 @@ function createTemplates(ctx, deps) { language: dto.language.split('_')[0], variables: Object.fromEntries(order.map((name, i) => [String(i + 1), sample(name)])), card, - text: numbered(c.title ? `${c.title}\n\n${c.text}` : c.text).slice(0, 1600), + text: engine.safeSlice(numbered(c.title ? `${c.title}\n\n${c.text}` : c.text), 1600), }, settings: ctx.config.providers.twilio, fetchImpl: ctx.fetchImpl, diff --git a/server/src/core/webhooks.js b/server/src/core/webhooks.js index 62d3edd..d7bffb4 100644 --- a/server/src/core/webhooks.js +++ b/server/src/core/webhooks.js @@ -321,7 +321,16 @@ function createWebhooks(ctx, deps) { * @returns {Promise} */ async function sevenEvent(account, body) { - const event = body?.webhook_event; + if (!body || typeof body !== 'object') { + // seven.io sends webhooks form-encoded unless the hook's request method + // is JSON (docs.seven.io/en/rest-api/endpoints/webhooks). The signature + // was valid, so the account is right but the hook is set up wrong. + ctx.log.warn( + '[magic-messagegate] seven.io webhook ignored: set the request method of the seven.io webhook to JSON' + ); + return; + } + const event = body.webhook_event; const data = body?.data || {}; if (event === 'dlr' && data.msg_id && typeof data.status === 'string') { const mapped = seven.DLR_STATUS[data.status.toUpperCase()]; @@ -346,7 +355,7 @@ function createWebhooks(ctx, deps) { account, kind: 'text', text: String(data.text || '').slice(0, 4096), - at: Date.parse(String(data.time || '').replace(' ', 'T')) || ctx.now(), + at: sevenTime(data.time) || ctx.now(), }); } } @@ -470,20 +479,43 @@ function createWebhooks(ctx, deps) { if (/^whatsapp:/i.test(from)) return { status: 200 }; const contact = await contactByPhone(from); if (!contact) return { status: 200 }; - await receive({ + const channel = /^rcs:/i.test(from) || account.channel === 'rcs' ? 'rcs' : 'sms'; + const row = await receive({ provider: 'twilio', providerMessageId: sid, - channel: /^rcs:/i.test(from) || account.channel === 'rcs' ? 'rcs' : 'sms', + channel, contact, account, at: ctx.now(), ...twilioMessage(params), }); + // Advanced Opt-Out sends OptOutType=STOP|START|HELP when the whole + // message matched one of the Messaging Service's keywords; Twilio then + // blocks further messages (error 21610). START is not treated as + // consent: consent comes from the app. + if (row && String(params.OptOutType || '').toUpperCase() === 'STOP') { + await deps.contacts.setConsent(contact.id, channel, 'revoked', 'provider-opt-out'); + } } return { status: 200 }; } } +/** + * seven.io inbound SMS time: a Unix timestamp in seconds ("1605878104" in + * the official sms_mo example, docs.seven.io/en/rest-api/webhooks); older + * payloads used "YYYY-MM-DD hh:mm:ss". + * + * @param {unknown} value + * @returns {number|null} Milliseconds, or null when unknown. + */ +function sevenTime(value) { + const text = String(value ?? '').trim(); + if (/^\d{9,11}$/.test(text)) return Number(text) * 1000; + const parsed = Date.parse(text.replace(' ', 'T')); + return Number.isFinite(parsed) ? parsed : null; +} + /** * Maps Twilio inbound webhook parameters (SMS, MMS, RCS) to MessageGate fields. * https://www.twilio.com/docs/messaging/guides/webhook-request @@ -522,4 +554,4 @@ function twilioMessage(p) { return out; } -module.exports = { createWebhooks, META_STATUS, twilioMessage }; +module.exports = { createWebhooks, META_STATUS, twilioMessage, sevenTime }; diff --git a/server/src/index.js b/server/src/index.js index c3c526a..943f9c7 100644 --- a/server/src/index.js +++ b/server/src/index.js @@ -15,6 +15,7 @@ const controllers = require('./controllers'); const services = require('./services'); const { createRawBodyMiddleware } = require('./utils/raw-body'); const { registerActions } = require('./permissions'); +const { restPrefixOf } = require('./core/context'); const timers = new WeakMap(); @@ -40,7 +41,9 @@ function every(fn, ms) { module.exports = { register({ strapi }) { - strapi.server.use(createRawBodyMiddleware({ pathPrefix: '/api/magic-messagegate/webhooks/' })); + // Content API routes live under `api.rest.prefix` (default `/api`). + const prefix = restPrefixOf(strapi.config.get('api.rest.prefix', '/api')); + strapi.server.use(createRawBodyMiddleware({ pathPrefix: `${prefix}/magic-messagegate/webhooks/` })); }, async bootstrap({ strapi }) { diff --git a/server/src/services/index.js b/server/src/services/index.js index 8baf49a..4389caf 100644 --- a/server/src/services/index.js +++ b/server/src/services/index.js @@ -43,6 +43,7 @@ function coreFor(strapi) { } }, publicUrl: config.publicUrl || strapi.config.get('server.url') || '', + restPrefix: strapi.config.get('api.rest.prefix', '/api'), magicMail, files: strapi.db?.query ? createFiles(strapi) : null, }) diff --git a/server/src/utils/template-engine.js b/server/src/utils/template-engine.js index 8f4a668..9e0bfa4 100644 --- a/server/src/utils/template-engine.js +++ b/server/src/utils/template-engine.js @@ -164,6 +164,40 @@ const telegramVisibleLength = (html) => .replace(/&(?:#\d+|#x[0-9a-f]+|[a-z]+);/gi, '_'), ].length; +/** + * Cuts a text to at most `max` UTF-16 code units without splitting a + * surrogate pair (an emoji cut in half is an invalid string that providers + * reject or render as a replacement character). + * + * @param {string} value + * @param {number} max + * @returns {string} + */ +function safeSlice(value, max) { + const text = String(value ?? ''); + if (text.length <= max) return text; + const cut = text.slice(0, max); + const last = cut.charCodeAt(cut.length - 1); + return last >= 0xd800 && last <= 0xdbff ? cut.slice(0, -1) : cut; +} + +/** + * Shortens escaped Telegram text (no tags, only `&`-style entities) to + * `max` visible characters without cutting an entity in half, which the Bot + * API would refuse with "can't parse entities". Text with tags is returned + * unchanged: templates are length-checked when they are rendered. + * + * @param {string} html + * @param {number} max - Visible characters (entities count as one). + * @returns {string} + */ +function truncateTelegramText(html, max) { + const value = String(html ?? ''); + if (/<[^>]*>/.test(value) || telegramVisibleLength(value) <= max) return value; + const tokens = value.match(/&(?:#\d+|#x[0-9a-f]+|[a-z]+);|[\s\S]/giu) || []; + return tokens.slice(0, max).join(''); +} + /** * Validates variables and renders a template for its channel. * @@ -272,7 +306,7 @@ function render(template, input, options = {}) { } if (template.channel === 'rcs') { - const text = fill(c.text, values, format).slice(0, 1600); + const text = safeSlice(fill(c.text, values, format), 1600); const title = c.title ? fill(c.title, values, format).slice(0, 200) : null; if (c.contentSid) { // Twilio Content templates use numbered variables ({{1}}, {{2}} …) in @@ -284,19 +318,21 @@ function render(template, input, options = {}) { preview: [title, text].filter(Boolean).join('\n\n'), }; } - const body = title ? `${title}\n\n${text}`.slice(0, 1600) : text; + const body = title ? safeSlice(`${title}\n\n${text}`, 1600) : text; return { payload: { kind: 'rcs', text: body, ...(c.mediaUrl ? { mediaUrl: c.mediaUrl } : {}) }, preview: body, }; } - const text = fill(c.text, values, format).slice(0, 1600); + const text = safeSlice(fill(c.text, values, format), 1600); return { payload: { text }, preview: text, sms: smsSegments(text) }; } module.exports = { telegramVisibleLength, + truncateTelegramText, + safeSlice, placeholders, templateVariables, variablesSchema, diff --git a/tests/adapters.test.js b/tests/adapters.test.js index 52b3b01..d425a46 100644 --- a/tests/adapters.test.js +++ b/tests/adapters.test.js @@ -364,3 +364,135 @@ test('twilio: Lookup v2 line type intelligence', async () => { assert.equal(req.url, `/lookup/v2/PhoneNumbers/${encodeURIComponent(TO)}?Fields=line_type_intelligence`); assert.equal(req.method, 'GET'); }); + +/* ------------------------------------------------ provider audit 2026-11-20 */ + +test('http: Retry-After as seconds or HTTP-date, capped at one day', () => { + const { parseRetryAfter } = require('../server/src/adapters/http'); + const now = Date.parse('2026-11-20T10:00:00Z'); + assert.equal(parseRetryAfter('7', now), 7000); + assert.equal(parseRetryAfter('Fri, 20 Nov 2026 10:00:30 GMT', now), 30_000); + assert.equal(parseRetryAfter('Fri, 20 Nov 2026 09:00:00 GMT', now), null, 'a date in the past'); + assert.equal(parseRetryAfter('999999', now), 86_400_000); + assert.equal(parseRetryAfter('soon', now), null); + assert.equal(parseRetryAfter(null, now), null); +}); + +test('telegram: long HTML text is never cut inside an entity', async () => { + const escaped = '&'.repeat(4096); // 4096 visible characters, 20480 bytes of HTML + await telegram.send({ + config: CREDS.telegram, + to: '12345', + payload: { text: escaped }, + settings: fake.providers.telegram, + fetchImpl: loopbackFetch, + }); + const [req] = fake.of('telegram.send'); + assert.equal(req.json.text, escaped, 'within 4096 visible characters the text is sent unchanged'); + await telegram.send({ + config: CREDS.telegram, + to: '12345', + payload: { text: `${escaped}x<` }, + settings: fake.providers.telegram, + fetchImpl: loopbackFetch, + }); + const long = fake.of('telegram.send')[1].json.text; + assert.equal(long, escaped, 'cut at 4096 visible characters, after a whole entity'); +}); + +test('seven: text is cut to the documented 1520 characters without splitting an emoji', async () => { + const text = `${'a'.repeat(1519)}😀tail`; + await seven.send({ + config: CREDS.seven, + to: TO, + payload: { text }, + settings: fake.providers.seven, + fetchImpl: loopbackFetch, + }); + const [req] = fake.of('seven.send'); + assert.equal(req.form.text, 'a'.repeat(1519), 'the surrogate pair at 1520/1521 is dropped, not split'); + assert.equal(seven.MAX_TEXT, 1520); +}); + +test('seven: 101 with one failed recipient, opt-out, credit and spending limit codes', async () => { + const cases = [ + [ + { success: '101', messages: [{ id: null, success: false, error: '407004' }] }, + 'rejected', + 'SEVEN_407004', + false, + true, + ], + [{ success: '101', messages: [{ id: null, success: false, error: '202' }] }, 'rejected', 'SEVEN_202', false, false], + [{ success: '407004' }, 'rejected', 'SEVEN_407004', false, true], + [{ success: '501' }, 'rejected', 'SEVEN_501', true, false], + [{ success: '500' }, 'transient', 'SEVEN_500', true, undefined], + [{ success: '101' }, 'ambiguous', 'SEVEN_101', false, undefined], + ]; + for (const [json, outcome, code, accountProblem, optedOut] of cases) { + fake.queue('seven.send', { status: 200, json }); + const res = await seven.send({ + config: CREDS.seven, + to: TO, + payload: { text: 'Hi' }, + settings: fake.providers.seven, + fetchImpl: loopbackFetch, + }); + assert.equal(res.outcome, outcome, JSON.stringify(json)); + assert.equal(res.code, code); + assert.equal(res.accountProblem, accountProblem, `account problem for ${code}`); + assert.equal(res.optedOut, optedOut, `opted out for ${code}`); + } +}); + +test('seven: HLR roaming is read from the documented object', async () => { + fake.queue('seven.hlr', { + status: 200, + json: { valid_number: 'valid', reachable: 'reachable', roaming: { status: 'not_roaming' }, current_carrier: {} }, + }); + const res = await seven.hlr({ + config: CREDS.seven, + e164: TO, + settings: fake.providers.seven, + fetchImpl: loopbackFetch, + }); + assert.equal(res.roaming, 'not_roaming'); +}); + +test('twilio: 21610 (recipient replied STOP) is a permanent opt-out', async () => { + fake.queue('twilio.send', { + status: 400, + json: { code: 21610, message: 'Attempt to send to unsubscribed recipient', status: 400 }, + }); + const res = await twilio.send({ + config: CREDS.twilio, + to: TO, + payload: { text: 'Hi' }, + settings: fake.providers.twilio, + fetchImpl: loopbackFetch, + }); + assert.equal(res.outcome, 'rejected'); + assert.equal(res.code, 'TWILIO_21610'); + assert.equal(res.optedOut, true); + fake.queue('twilio.send', { status: 400, json: { code: 21611, message: 'queue full', status: 400 } }); + const full = await twilio.send({ + config: CREDS.twilio, + to: TO, + payload: { text: 'Hi' }, + settings: fake.providers.twilio, + fetchImpl: loopbackFetch, + }); + assert.equal(full.outcome, 'transient', '21611: the sender queue is full, nothing was sent'); +}); + +test('meta: the pinned Graph API version stays supported for at least 90 more days', () => { + // https://developers.facebook.com/docs/graph-api/changelog/versions (read + // 2026-11-20): v23.0 released 2025-05-29, available until 2027-10-08. The + // official WhatsApp OpenAPI (github.com/facebook/openapi) describes v23.0. + // This test fails 90 days before the end so the default can be moved in time. + const EXPIRES = { 'v23.0': '2027-10-08' }; + const source = require('node:fs').readFileSync(require.resolve('../server/src/adapters/meta'), 'utf8'); + const version = /const DEFAULT_VERSION = '(v\d+\.\d)'/.exec(source)?.[1]; + assert.ok(EXPIRES[version], `add the end of support of ${version} to this test`); + assert.ok(Date.parse(EXPIRES[version]) - Date.now() > 90 * 86_400_000, `${version} ends on ${EXPIRES[version]}`); +}); diff --git a/tests/admin.test.js b/tests/admin.test.js index 54872b0..b86c82e 100644 --- a/tests/admin.test.js +++ b/tests/admin.test.js @@ -215,6 +215,10 @@ test('utils: provider credentials, send form, settings, messages, contacts, form apiKey: 'k', senderId: 'Shop', }); + const echo = (id) => id; + assert.equal(pr.webhookHint(echo, 'seven'), 'accounts.webhookUrl.seven', 'seven.io needs the JSON request method'); + assert.equal(pr.webhookHint(echo, 'twilio'), 'accounts.webhookUrl.twilio'); + assert.equal(pr.webhookHint(echo, 'meta'), 'accounts.webhookUrl.hint'); const { validateSend } = await load('utils/send.mjs'); assert.deepEqual(validateSend({ to: '', isText: true, text: '' }), { to: 'required', text: 'required' }); diff --git a/tests/plugin.test.js b/tests/plugin.test.js index 2e08d4f..e024f1e 100644 --- a/tests/plugin.test.js +++ b/tests/plugin.test.js @@ -304,3 +304,44 @@ test('admin API: a paid number lookup needs contacts.manage; the free check does await admin.lookup(ctx); assert.equal(ctx.status, 200); }); + +test('a custom api.rest.prefix is used for the raw-body middleware and every public URL', async () => { + const { restPrefixOf } = require('../server/src/core/context'); + assert.equal(restPrefixOf(undefined), '/api'); + assert.equal(restPrefixOf('/v1/'), '/v1'); + assert.equal(restPrefixOf('v2'), '/v2'); + assert.equal(restPrefixOf(''), ''); + + const strapi = await fakeStrapi(); + const get = strapi.config.get; + strapi.config.get = (key, fallback) => (key === 'api.rest.prefix' ? '/v1' : get(key, fallback)); + const middlewares = []; + strapi.server = { use: (fn) => middlewares.push(fn) }; + plugin.register({ strapi }); + const [mw] = middlewares; + const ctx = { + method: 'POST', + path: '/v1/magic-messagegate/webhooks/meta/x', + req: Object.assign(require('node:stream').Readable.from([Buffer.from('{}')]), { + headers: { 'content-type': 'application/json' }, + }), + state: {}, + get: () => '', + }; + await mw(ctx, async () => {}); + assert.equal(ctx.state.messagegateRaw?.toString(), '{}', 'webhooks under /v1 keep their raw body'); + + const { createCore } = require('../server/src/core'); + const { sqliteKnex, TEST_KEY } = require('./helpers/core'); + const core = createCore({ + knex: sqliteKnex(), + config: { encryptionKey: TEST_KEY, publicUrl: 'https://cms.example.test' }, + restPrefix: '/v1', + }); + await core.init(); + const account = await core.accounts.create({ channel: 'sms', provider: 'seven', name: 'SMS', config: CREDS.seven }); + assert.match( + account.webhookUrl, + /^https:\/\/cms\.example\.test\/v1\/magic-messagegate\/webhooks\/seven\/[A-Za-z0-9]+$/ + ); +}); diff --git a/tests/webhooks.test.js b/tests/webhooks.test.js index 68a44d7..13688b3 100644 --- a/tests/webhooks.test.js +++ b/tests/webhooks.test.js @@ -409,3 +409,64 @@ test('webhooks are rate limited per account', async () => { } assert.deepEqual(statuses.slice(-2), [200, 429]); }); + +/* ------------------------------------------------ provider audit 2026-11-20 */ + +test('seven: sms_mo time is a Unix timestamp; a form-encoded hook is logged, not processed', async () => { + const { sevenTime } = require('../server/src/core/webhooks'); + assert.equal(sevenTime('1605878104'), 1605878104000, 'official sms_mo example'); + assert.equal(sevenTime('2021-08-24 08:08:00'), Date.parse('2021-08-24T08:08:00')); + assert.equal(sevenTime('soon'), null); + + const { strapi, core, accounts, call } = await setup(); + const url = `https://cms.example.test/api/magic-messagegate/webhooks/seven/${accounts.seven.path}`; + const raw = JSON.stringify({ + webhook_event: 'sms_mo', + data: { id: '681590', sender: '4915123456789', system: '4930000000', text: 'Hallo', time: '1605878104' }, + }); + assert.equal((await call('seven', { raw, headers: sevenHeaders(raw, url) })).status, 200); + const [message] = (await core.inbound.list({})).results; + assert.equal(new Date(message.receivedAt).getTime(), 1605878104000); + + const form = 'webhook_event=dlr&data%5Bmsg_id%5D=1&data%5Bstatus%5D=DELIVERED'; + const headers = { ...sevenHeaders(form, url), 'content-type': 'application/x-www-form-urlencoded' }; + assert.equal((await call('seven', { raw: form, headers })).status, 200); + assert.ok( + strapi.logs.some(([level, m]) => level === 'warn' && /request method of the seven\.io webhook to JSON/.test(m)), + 'the owner is told how to fix the hook' + ); +}); + +test('twilio: OptOutType=STOP from Advanced Opt-Out revokes SMS consent', async () => { + const { core, accounts, call, contact } = await setup(); + const url = `https://cms.example.test/api/magic-messagegate/webhooks/twilio/${accounts.twilio.path}`; + const hex = (n) => n.toString(16).padStart(32, '0'); + const params = { + AccountSid: CREDS.twilio.accountSid, + MessageSid: `SM${hex(77)}`, + From: PHONE, + To: '+15005550006', + Body: 'Cancel', + OptOutType: 'STOP', + }; + const { raw, headers } = twilioRequest(url, params); + assert.equal((await call('twilio', { raw, headers })).status, 200); + assert.equal(await core.contacts.consentStatus(contact.id, 'sms'), 'revoked'); +}); + +test('outbox: a provider opt-out (seven.io 407004) revokes consent so the next send stops', async () => { + const { core, contact } = await setup(); + fake.queue('seven.send', { status: 200, json: { success: '407004' } }); + const res = await core.sender.send({ + to: PHONE, + channel: 'sms', + template: 'hello', + language: 'de', + variables: { name: 'Ana' }, + }); + await core.outbox.tick(); + const row = await core.outbox.getRow(res.id); + assert.equal(row.status, 'failed'); + assert.equal(row.error_code, 'SEVEN_407004'); + assert.equal(await core.contacts.consentStatus(contact.id, 'sms'), 'revoked'); +}); From f0d902e8d58689b63feaa38393fdd5d8c0f55fff Mon Sep 17 00:00:00 2001 From: Schero94 <64200582+Schero94@users.noreply.github.com> Date: Fri, 20 Nov 2026 00:49:37 +0100 Subject: [PATCH 2/2] test: accept base64url webhook paths in the REST prefix test Co-Authored-By: Claude Opus 5.5 --- tests/plugin.test.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/plugin.test.js b/tests/plugin.test.js index e024f1e..1ce5bf4 100644 --- a/tests/plugin.test.js +++ b/tests/plugin.test.js @@ -342,6 +342,6 @@ test('a custom api.rest.prefix is used for the raw-body middleware and every pub const account = await core.accounts.create({ channel: 'sms', provider: 'seven', name: 'SMS', config: CREDS.seven }); assert.match( account.webhookUrl, - /^https:\/\/cms\.example\.test\/v1\/magic-messagegate\/webhooks\/seven\/[A-Za-z0-9]+$/ + /^https:\/\/cms\.example\.test\/v1\/magic-messagegate\/webhooks\/seven\/[A-Za-z0-9_-]+$/ ); });