Mail relay: review of 7d766b6 — R-1 to R-12, four mutations, two sentences

- R-1 a delivered token becomes the one in use only on 200 or a refusal given after authentication
- R-2 a token of another site is refused by what /v1/status says (access-key field, scripts); docs for staging
- R-3 the confirm route looks the nonce up first and counts only refused calls
- R-4 one budget of time per message (10 s, 30 s with files), enrolment and retries included
- R-5 'Disconnect' without the service's answer is not confirmed and keeps the token to try again
- R-6 no enrolment without the confirm route in the config
- R-7 half an SMTP set-up: one log line and a hint in the panel
- R-8 to R-10, R-12 docs; R-11 the last failure stays in the state block
- tests for redirect: manual, the candidate's nonce, the expectation taken back, one recipient only

Co-Authored-By: Claude Fable 5.2 <[email protected]>
This commit is contained in:
Radosław Smoliński
2026-11-25 22:07:10 +01:00
co-authored by Claude Fable 5.2
parent 0ee74ab2a4
commit a2b07b1dc1
23 changed files with 584 additions and 69 deletions
+8 -3
View File
@@ -27,7 +27,9 @@ once there are more than 20.
> `relay-unreachable` and sends nothing, as it sent nothing before.**
### Requires project changes
- **Nothing has to be run.** The e-mail tab of Site integrations has a new block ("How e-mails are sent"); it is
- **A CI that compares generated types:** `payload generate:types` gives a diff on upgrade — four field descriptions
of Site integrations changed (no type did). Run it and commit `payload-types.ts`. The import map does not change.
- **Nothing else has to be run.** The e-mail tab of Site integrations has a new block ("How e-mails are sent"); it is
rendered by the status banner already in every import map, so `generate:importmap` gives no diff. No field was
added; "Sending method" keeps its two stored values.
- **What changes for an existing site on upgrade — e-mail:**
@@ -39,6 +41,7 @@ once there are more than 20.
| `GRAPH_*` set, "Sending method" on SMTP, no SMTP server (mail failed until now) | Mail goes through Graph | fill in SMTP, or remove the variables |
| Neither (mail failed until now with "not configured") | **An outbound call:** on the next e-mail the site enrols with the service — `POST https://webservices.intecion.net/mail/v1/enrol` with its host and the plugin version — and then sends through it, from `[email protected]`. A host Intecion has not listed waits for approval first | `iapl({ mail: { relay: false } })` |
| Any site with the mail service enabled (the default) | **A new public route:** `POST /api/iapl/mail-relay/confirm` — answers `404` and changes nothing unless the site itself started an enrolment in the last 5 minutes; rate-limited. Three admin-only routes beside it (`…/status`, `…/connect`, `…/disconnect`) | `mail: { relay: false }` removes all four |
| SMTP **half** filled in — a server or a user name, but not server, user name and password (until now: refused, "Fill in the server, user name and password") | Sent through the mail service; one line in the server log and a hint in the state block say that the SMTP settings are incomplete | complete or empty the SMTP fields; `mail: { relay: false }` |
| "Microsoft Graph" chosen in the panel but `GRAPH_*` missing (until now: SMTP with a warning) | SMTP if filled in, otherwise the mail service | as above |
| A site on `localhost` or without `serverURL` | Refused by the plugin itself; nothing leaves the machine. Development: SMTP (a local catcher) as before | — |
@@ -90,13 +93,15 @@ once there are more than 20.
the site's server addresses and to the host it was issued for (a database copied to another host enrols as itself),
rotated every 90 days, healed by re-enrolment. One message = one `Idempotency-Key` and
one encoding across at most three attempts; a send with no answer is reported as **not confirmed** (it may be out)
and cannot double when sent again. Every message says what it is (form notification, form confirmation, account,
and, while the same process runs, goes out under the same key when sent again (after a restart or from another
instance a repeat is a new message). One message has one budget of time — 10 seconds, 30 with files
(`mail.relay.totalTimeoutMs`) — so a service that hangs does not hold a form's visitor for the sum of the attempts. Every message says what it is (form notification, form confirmation, account,
test, system): form mail and Payload's "forgot password" are marked by the plugin; `withMailKind` /
`runWithMailKind` for a project's own. Account mail is limited by the site itself (5 an hour to one address, 10 by
one visitor; `mail.relay.accountMail`). Limits and the file size come from the service (30 an hour, 200 a day, 10 MB
unless Intecion set others); `mailAttachmentLimit` reports the latter.
- **Plugin option `mail`**: `mail: { relay: false | { url, host, enrol, token, senderName, kind, accountMail,
confirmRateLimit, timeoutMs, retryBackoffMs, fetchImpl }, graphDeprecationWarning }`; `mailAdapter({ relay })`.
confirmRateLimit, totalTimeoutMs, timeoutMs, retryBackoffMs, fetchImpl }, graphDeprecationWarning }`; `mailAdapter({ relay })`.
- **Panel:** the state block on the e-mail tab (transport in effect, the site's state with the service, sender and
reply address, what is left of the limits, a replaced sender name; "Check now", "Connect again", "Disconnect",
"Enter an access key"); "Sending method" reads "Automatic" / "Microsoft Graph (deprecated)"; the server field reads
+4 -1
View File
@@ -1321,6 +1321,7 @@ overrides per adapter; `resolveRelayOptions` reads what is in effect):
| `kind` | — | kind of a message nobody marked |
| `accountMail` | `{ perAddress: 5, perVisitor: 10, windowMinutes: 60 }` | the site's own limit on account mail; `false` = none |
| `confirmRateLimit` | `{ max: 10, windowMs: 60000 }` | the public confirm route, per address |
| `totalTimeoutMs` | 10 s, 30 s with files | all one message may take (a visitor waits for the form) — a number or `{ plain, files }` |
| `timeoutMs`, `retryBackoffMs`, `fetchImpl` | 30 s, 1 s, `fetch` | one attempt; wait between attempts; tests |
| `graphDeprecationWarning` | `true` | `false` = no start warning on a Graph site (`GRAPH_DEPRECATION_NOTICE`) |
@@ -1333,7 +1334,9 @@ the site itself just started an enrolment, rate-limited; allow it in any WAF or
`relay-attachment-refused`, `relay-recipient-suppressed`, `relay-unreachable`, `relay-not-confirmed`, `relay-error`
(and the warning `relay-name-replaced`) — what each means and what to do: `iapl-debug`, "E-mail". A send returns
`RelaySendResult`; `confirmed: false` means the message **may** have been sent — do not send it again under
another content; the same message sent again reuses its key and cannot double.
another content. Inside one running process the same message sent again reuses its key and cannot double; after a
restart, or from another instance, a repeat is a new message and can. One message has one budget of time
(`totalTimeoutMs`: 10 s, 30 s with files) for enrolment, attempts and waits together.
**Limits** (the service's; per site): 30 messages an hour, 200 a day, 10 recipients a message, 10 MB of files —
read from the service (`mailAttachmentLimit`, `relayAttachmentLimit`), never typed into a project. A site that
+5 -1
View File
@@ -110,7 +110,11 @@ through this procedure. Ask only when you are missing something you cannot get y
| `relay-too-large` / `relay-attachment-refused` | files over the service's limit (10 MB a message); a program or script as attachment | lower the File field's maximum (`iapl-form`); other file types; SMTP for larger files |
| `relay-recipient-suppressed` | one recipient's mailbox bounced or complained before (for any site); nothing was sent to anybody | correct the address in the form's Emails tab; ask Intecion to clear the address |
| `relay-unreachable` | the service or its mail back end failed, or the server cannot reach `webservices.intecion.net` | `curl -s https://webservices.intecion.net/mail/health` from the server → `{"ok":true}`; if it persists: SMTP, and tell Intecion |
| `relay-not-confirmed` / "may have been sent" | no answer from the service (time-out, connection lost) | check the recipient's mailbox **before** sending again; the same message sent again cannot double |
| `relay-not-confirmed` / "may have been sent" | no answer of the service: a time-out, a lost connection, an error page of a proxy in front, or the message's time budget (10 s, 30 s with files) ran out while an attempt was open | check the recipient's mailbox **before** sending again — a repeat after a restart or from another instance is a new message and can double. A service that hangs for everybody: SMTP meanwhile, tell Intecion |
| state block: "the disconnection is not confirmed" | "Disconnect" could not reach the service: the site stopped sending, the token still works there | press "Disconnect" again when the service answers |
| "This access key belongs to another site" | a token issued for another host was pasted | ask Intecion for a token for this host |
| `relay-refused`, cause `client-no-route` | the config has no `POST /api/iapl/mail-relay/confirm`: `mailAdapter()` without `iapl()`, or beside `mail: { relay: false }` | use the plugin option, or add `relayConfirmEndpoint()` to `endpoints` |
| log: "The SMTP settings in Site integrations are incomplete" | server, user name or password is missing, so the mail service carries the mail | complete the three fields, or empty them |
| `relay-error` | the service refused the request as wrong (a bug), or the message has no valid recipient or no body | server log line `[iapl] mail service: …` → `iapl-plugin-gap` |
| the mail arrives under the site's host instead of the client's name | the service did not accept "Sender name" (an address, a bank or provider name, mixed scripts, over 64 characters) — the state block says which name was used | another name; an honest name that is still replaced → Intecion |
| replies to the site's mail are lost | "Sender address" is empty: the service's own address has no mailbox | fill it in (doctor: `mail-reply-address`) |
+4 -1
View File
@@ -554,13 +554,16 @@ builds; the panel opens; the old commands (`pnpm exec ipal-doctor`) still run.
**→ 1.17.0, e-mail (the Intecion mail service (IWSN in the panel) is the default transport; Microsoft Graph deprecated; CHANGELOG 1.17.0;
PROGRAMISTA §6, item 73; email.md; AGENT.md §7.2) — nothing to run; read which case the site is:**
1. **Every site:** no schema change, no migration, no import-map change. The e-mail tab gains the block "How e-mails
1. **Every site:** no schema change, no migration, no import-map change. `pnpm payload generate:types` gives a small diff
(four field descriptions of Site integrations): run it and commit, or a CI that compares types fails. The e-mail tab gains the block "How e-mails
are sent" and new wording ("Automatic", "Own SMTP server").
2. **Which case** — Site integrations → E-mail sending, and the Coolify env:
- **SMTP filled in** (server, user name, password): nothing changes, the site contacts nobody. Done.
- **`GRAPH_*` set:** mail as before; one deprecation warning per start, doctor warning `mail-graph-deprecated`.
Do **not** remove the variables in passing — moving the site is the owner's decision (email.md "Moving off
Microsoft Graph"). Note: with `GRAPH_*` set and SMTP filled in, the panel's choice decides as before.
- **SMTP half filled in** (a server or user name without the rest; refused until now): mail now goes through the
mail service, with one log line and a hint in the panel — complete or empty the fields.
- **Neither** (mail failed with "not configured" until now): **on its next e-mail the site contacts
`webservices.intecion.net` with its host and the plugin version**, receives its own token through the new public
route `POST /api/iapl/mail-relay/confirm`, and from then on sends from `[email protected]`
+40 -5
View File
@@ -42,6 +42,10 @@ Decided on every send from Site integrations → E-mail sending, with no stored
4. Otherwise → **the mail service**, unless it is switched off (`mail: { relay: false }`).
5. Otherwise nothing is configured: the send reports `{ sent: false, code: 'not-configured' }`, as before 1.17.0.
**Half an SMTP set-up** (a server and a user name without a password, say) is not an SMTP server: until 1.16 such
a site refused to send; now its mail goes through the mail service. The server log says so once and the state
block shows "The SMTP settings below are incomplete".
- **A site with SMTP filled in never contacts the mail service.** Nothing changes for it.
- **SMTP on the client's request:** an admin fills in "Own SMTP server", user name and password; from the next send
the site uses the client's server and the client's own sender address. Emptying the server returns the site to
@@ -157,7 +161,9 @@ await runWithMailKind('account', () => sendWelcomeMails(payload, user))
- `mailKindOf(message)` reads the mark (the key is the symbol `MAIL_KIND`; other transports ignore it).
- `mail.relay.kind: (message) => MailKind | undefined` decides for messages nobody marked.
- `expectMailTo(address, kind, { visitor })` says what the **next** message to one address is, for mail a library
composes by itself; the plugin uses it for Payload's account mail. It lasts ten seconds and one message.
composes by itself; the plugin uses it for Payload's account mail. It lasts ten seconds and one message. So an
**unmarked** mail of your own to the same single address within ten seconds of a "forgot password" that Payload
did not answer with a mail is counted as account mail; a marked mail (every form mail) never is.
- Mark `account` only for mail to an account holder, and `form-confirmation` for mail to an address a visitor typed.
A wrong kind gives a visitor room the service did not mean to give.
@@ -176,7 +182,12 @@ await runWithMailKind('account', () => sendWelcomeMails(payload, user))
(`replayed: true`) and no second mail goes out. After a restart, or from another instance of the site, a repeat
(a visitor submitting the form again) is a new message: if the first one did go out, the recipient gets two.
That is why the panel says "it may have been sent; check the mailbox before trying again".
- **One budget of time per message:** 10 seconds, 30 with files (`totalTimeoutMs`), for the enrolment, the
attempts and the waits together — a visitor waits for the form's answer while the mail is sent, and a service
that hangs must not hold them for the sum of the time-outs. So in practice a hanging service means one attempt.
- The form **keeps working** meanwhile — the submission is saved in Form Submissions; only the mail is missing.
- The panel's banner shows the **last** send. A mail that was not sent stays visible in the state block
("An e-mail was not sent on …", with its code) after later mail went out.
### The token
@@ -196,7 +207,13 @@ await runWithMailKind('account', () => sendWelcomeMails(payload, user))
each other off (they share the database). `rotateRelayToken(payload)` does it now.
- **A lost token heals itself:** the next send enrols again.
- **Disconnect:** "Disconnect" in the panel (`disconnectRelay(payload)`) gives the token up on the service and stops
the site from enrolling by itself until "Connect again" (`enrolRelay(payload, { force: true })`).
the site from enrolling by itself until "Connect again" (`enrolRelay(payload, { force: true })`). It answers
`{ revoked }`: when the service could not be reached the site stops using the token at once, but the token
**still works at the service** — the panel says "not confirmed" and keeps it so that "Disconnect" can be pressed
again; only then is it revoked and forgotten.
- **A token of another site is refused.** The access-key field asks the service whose token it is before it stores
anything, and a token stored by a script is checked the same way before its first use (`/v1/status` names the
host): another site's token is not saved, not used and not revoked.
- **A token issued by hand** — for a site the service cannot call back (behind a firewall): Intecion issues one,
an admin enters it in the state block ("Enter an access key"), or a script calls `setRelayToken(payload, token)`.
**Such a site cannot heal by itself:** it never enrols on its own. When the service no longer knows its server
@@ -205,6 +222,17 @@ await runWithMailKind('account', () => sendWelcomeMails(payload, user))
- Encryption at rest: none, like `smtpPassword`. A token read from a database dump is of little use — it does not
work from another server address.
### Staging and copies
- A staging site on its own domain is **its own site** to the service: its own enrolment, token, limits and
approval ("waiting for approval" until Intecion approves it, unless its host is listed).
- **A copy of production's database does not carry production's connection.** The stored token is tied to the host
it was issued for; on another host it is forgotten (never revoked), and the copy enrols as itself. This also holds
on the same server, where production's token would otherwise work.
- "Disconnect" on a copy revokes nothing of production's.
- A staging copy that must not send at all: `iapl({ mail: { relay: false } })` there, or SMTP to a catcher.
- Not covered: a copy that keeps production's `serverURL` is the same site to the plugin.
### The state block in the panel
Site integrations → E-mail sending starts with "How e-mails are sent" (component `MailRelayStatus` from `/admin`,
@@ -220,7 +248,7 @@ Routes (all three need the `admin` role: not logged in → 401, other role → 4
| `GET /api/iapl/mail-relay/status` | the transport and the stored state; `?refresh=1` asks the service |
| `POST /api/iapl/mail-relay/connect` | enrol now; with `{ token }` store a token issued by hand |
| `POST /api/iapl/mail-relay/disconnect` | give the token up |
| `POST /api/iapl/mail-relay/confirm` | **public** — the service's call-back. `404` and no change unless the site itself started an enrolment in the last 5 minutes; rate-limited (10 a minute per address, `mail.relay.confirmRateLimit`) |
| `POST /api/iapl/mail-relay/confirm` | **public** — the service's call-back. `404` and no change unless the site itself started an enrolment in the last 5 minutes; **refused** calls are rate-limited (10 a minute per address, `mail.relay.confirmRateLimit`) — a call that carries the nonce is never turned away by the limit, so junk from the same address cannot keep the site from enrolling |
These are the first routes under `/api/iapl/`; the others stay under `/api/ipal/` until 2.0. The confirm path is
fixed by the service for this product — a project cannot move it. For your own panel:
@@ -283,7 +311,8 @@ message); "Connect again" asks at once. Other causes: `host-not-allowed` (not a
| `kind` | — | the kind of a message nobody marked |
| `accountMail` | `{ perAddress: 5, perVisitor: 10, windowMinutes: 60 }` | the site's own limit on account mail; `false` = none |
| `confirmRateLimit` | `{ max: 10, windowMs: 60000 }` | calls to the public confirm route per address |
| `timeoutMs` | `30000` | one attempt of a send |
| `totalTimeoutMs` | `10000`; `30000` with files | everything one message may take — enrolment, attempts and waits together. Somebody waits for the request that sends the mail; after it the message is reported ("not confirmed" when an attempt was cut off). A number, or `{ plain, files }` |
| `timeoutMs` | `30000` | one attempt of a send; never more than what is left of `totalTimeoutMs` |
| `retryBackoffMs` | `1000` | the wait before the next attempt when the service names none (times the attempt's number) |
| `fetchImpl` | `fetch` | for tests |
| `graphDeprecationWarning` (on `mail`) | `true` | `false` silences the start warning of a site on Microsoft Graph |
@@ -307,6 +336,9 @@ the confirm path under the API route, `RELAY_SENDER_ADDRESS` the sender address
panel's sender name and reply address when Site integrations exists. `relayAttachmentLimit(payload, options)` is
its file limit.
- **The confirm route alone:** `relayConfirmEndpoint()`, for a project that builds its own config without `iapl()`.
**Without that route in the config the site does not ask to be enrolled at all** (`mailAdapter()` without `iapl()`,
or `mailAdapter({ relay: {} })` beside `mail: { relay: false }`): the send reports `relay-refused` and says which
route is missing. A token from `relay.token` needs no route.
- **Your own e-mail adapter:** `email:` in `buildConfig` is the project's and wins over everything here ("Your own
e-mail adapter" below).
@@ -519,7 +551,10 @@ to the client's address. The OAuth token is cached in the process until a minute
The service names its limit (10 MB in all files of one message, 20 files, unless Intecion set other numbers for the
site); the plugin reads it from the service and `mailAttachmentLimit(payload)` reports it. A message over the limit
is refused before it is uploaded (`relay-too-large`). Programs and scripts are refused by file name
(`relay-attachment-refused`). Content must be a `Buffer` or a string — a stream or a file path is not carried.
(`relay-attachment-refused`). Content must be a `Buffer` or a string — a stream or a file path is not carried, and
such a message fails whole (`relay-error`). **Inline images** (`cid:` attachments) are carried as ordinary files:
the picture shows as an attachment and as a broken image in the text — link images by URL instead. Only the first
`replyTo` address is used; free headers (`List-Unsubscribe` among them) are dropped.
The test e-mail's 10 MB file is at the limit: it shows whether the site's limit is the default.
### SMTP
+6 -3
View File
@@ -1006,16 +1006,19 @@ token. What protects it, and what the new public route can and cannot do:
| **No key in the package** | The plugin carries the service's address and nothing else. A site gets its token by proving it is served at its host: it makes a nonce, the service calls `POST https://<host>/api/iapl/mail-relay/confirm` with the nonce and a token, and only an answer that hashes both makes the token valid |
| **Where the token is** | `payload-kv`, key `iapl:mail-relay`. The collection refuses every operation through access control (`read`, `create`, `update`, `delete` are `false`) and is hidden: REST, GraphQL and the panel cannot reach it — an admin included (test: `test/mailRelayHttp.test.ts`). Server code with the Local API can, like `smtpPassword`. It is stored as it is (no encryption at rest), never logged, never sent to a browser, never part of a route's answer |
| **A database copied to another host** | the token is tied to the host it was issued for: a copy on a staging domain does not use production's token — it forgets it, without revoking it, and enrols as itself |
| **A token read from a database dump** | does not work from another server: the service accepts a token only from the addresses the site enrolled from (IPv6: the same `/64`) and answers anything else "enrol again" — which needs the call-back to the real site. It cannot send as another site, and the limits below apply |
| **A token of another site** (pasted into the access-key field, stored by a script) | refused: the service is asked which host the token is for before it is stored or used; a foreign one is not saved, not used, not revoked |
| **A token read from a database dump** | **works from the same server** (a staging site on the machine production runs on shares its outgoing address) — which is why the store is tied to its host, above. From another server it does not work: the service accepts a token only from the addresses the site enrolled from (IPv6: the same `/64`) and answers anything else "enrol again" — which needs the call-back to the real site. It cannot send as another site, and the limits below apply |
| **What a token can do at most** | send within the site's limits (30 an hour, 200 a day, 10 recipients, 10 MB by default) from the service's fixed address, under a sender name the service checks, with `X-Intecion-Site: <host>` on every mail. It cannot set `From`, `Return-Path` or any header, and cannot address a security alert |
| **The confirm route** | public by design, `404` with an empty body unless the body carries a nonce **this site** made in the last 5 minutes (kept as a hash, compared in constant time, single use). It stores the delivered token **beside** the one in use and never replaces a working token: a token becomes the one in use only after the service has accepted it. Rate-limited per address (10 a minute, `mail.relay.confirmRateLimit`). A stranger who calls it learns nothing and changes nothing |
| **The confirm route** | public by design, `404` with an empty body unless the body carries a nonce **this site** made in the last 5 minutes (kept as a hash, compared in constant time, single use). It stores the delivered token **beside** the one in use and never replaces a working token: a token becomes the one in use only after the service has accepted it — a `200`, or a refusal the service gives after it has checked the token; no answer, an error page or `rate-limited` prove nothing and leave both as they are. **Refused** calls are rate-limited per address (10 a minute, `mail.relay.confirmRateLimit`); the nonce is looked up first, so junk from the address the service shares with others cannot keep the site's own enrolment out. A stranger who calls it learns nothing and changes nothing |
| **Who can start an enrolment** | the server itself (a send without a token) and an admin ("Connect again"). The three state routes need the `admin` role and answer with states only |
| **A site taken over by an attacker with admin rights** | can send mail through the service under any sender name the service's check lets through, within the limits — as it could through the site's SMTP server. Intecion sees the host on every mail and can suspend the site (`relay-suspended`) |
| **Visitors** | cannot reach the service: only the server calls it. What a visitor can trigger is a form's mail (rate limit, Turnstile) and "forgot password" — limited by the site per address and per visitor (`mail.relay.accountMail`), because the service does not limit account mail per address |
| **A subject or name typed by a visitor** | line breaks, control characters, direction marks and other invisible characters are removed before the message leaves (`cleanSubject`); recipients are reduced to bare addresses; a message has no header field |
Turn off: `iapl({ mail: { relay: false } })` — no route, no outbound call, no token. Give the token up:
"Disconnect" in the panel (`disconnectRelay`), which revokes it on the service at once.
"Disconnect" in the panel (`disconnectRelay`), which revokes it on the service — at once when the service answers;
when it cannot be reached the site stops using the token, the panel says the disconnection is not confirmed, and
the token stays valid at the service until "Disconnect" is pressed again and answered.
## Dashboard alerts by role (`dashboardAlerts`)
+5 -1
View File
@@ -110,7 +110,11 @@ through this procedure. Ask only when you are missing something you cannot get y
| `relay-too-large` / `relay-attachment-refused` | files over the service's limit (10 MB a message); a program or script as attachment | lower the File field's maximum (`iapl-form`); other file types; SMTP for larger files |
| `relay-recipient-suppressed` | one recipient's mailbox bounced or complained before (for any site); nothing was sent to anybody | correct the address in the form's Emails tab; ask Intecion to clear the address |
| `relay-unreachable` | the service or its mail back end failed, or the server cannot reach `webservices.intecion.net` | `curl -s https://webservices.intecion.net/mail/health` from the server → `{"ok":true}`; if it persists: SMTP, and tell Intecion |
| `relay-not-confirmed` / "may have been sent" | no answer from the service (time-out, connection lost) | check the recipient's mailbox **before** sending again; the same message sent again cannot double |
| `relay-not-confirmed` / "may have been sent" | no answer of the service: a time-out, a lost connection, an error page of a proxy in front, or the message's time budget (10 s, 30 s with files) ran out while an attempt was open | check the recipient's mailbox **before** sending again — a repeat after a restart or from another instance is a new message and can double. A service that hangs for everybody: SMTP meanwhile, tell Intecion |
| state block: "the disconnection is not confirmed" | "Disconnect" could not reach the service: the site stopped sending, the token still works there | press "Disconnect" again when the service answers |
| "This access key belongs to another site" | a token issued for another host was pasted | ask Intecion for a token for this host |
| `relay-refused`, cause `client-no-route` | the config has no `POST /api/iapl/mail-relay/confirm`: `mailAdapter()` without `iapl()`, or beside `mail: { relay: false }` | use the plugin option, or add `relayConfirmEndpoint()` to `endpoints` |
| log: "The SMTP settings in Site integrations are incomplete" | server, user name or password is missing, so the mail service carries the mail | complete the three fields, or empty them |
| `relay-error` | the service refused the request as wrong (a bug), or the message has no valid recipient or no body | server log line `[iapl] mail service: …` → `iapl-plugin-gap` |
| the mail arrives under the site's host instead of the client's name | the service did not accept "Sender name" (an address, a bank or provider name, mixed scripts, over 64 characters) — the state block says which name was used | another name; an honest name that is still replaced → Intecion |
| replies to the site's mail are lost | "Sender address" is empty: the service's own address has no mailbox | fill it in (doctor: `mail-reply-address`) |
@@ -554,13 +554,16 @@ builds; the panel opens; the old commands (`pnpm exec ipal-doctor`) still run.
**→ 1.17.0, e-mail (the Intecion mail service (IWSN in the panel) is the default transport; Microsoft Graph deprecated; CHANGELOG 1.17.0;
PROGRAMISTA §6, item 73; email.md; AGENT.md §7.2) — nothing to run; read which case the site is:**
1. **Every site:** no schema change, no migration, no import-map change. The e-mail tab gains the block "How e-mails
1. **Every site:** no schema change, no migration, no import-map change. `pnpm payload generate:types` gives a small diff
(four field descriptions of Site integrations): run it and commit, or a CI that compares types fails. The e-mail tab gains the block "How e-mails
are sent" and new wording ("Automatic", "Own SMTP server").
2. **Which case** — Site integrations → E-mail sending, and the Coolify env:
- **SMTP filled in** (server, user name, password): nothing changes, the site contacts nobody. Done.
- **`GRAPH_*` set:** mail as before; one deprecation warning per start, doctor warning `mail-graph-deprecated`.
Do **not** remove the variables in passing — moving the site is the owner's decision (email.md "Moving off
Microsoft Graph"). Note: with `GRAPH_*` set and SMTP filled in, the panel's choice decides as before.
- **SMTP half filled in** (a server or user name without the rest; refused until now): mail now goes through the
mail service, with one log line and a hint in the panel — complete or empty the fields.
- **Neither** (mail failed with "not configured" until now): **on its next e-mail the site contacts
`webservices.intecion.net` with its host and the plugin version**, receives its own token through the new public
route `POST /api/iapl/mail-relay/confirm`, and from then on sends from `[email protected]`
@@ -3,7 +3,7 @@
import { useConfig, useTranslation } from '@payloadcms/ui'
import { useCallback, useEffect, useState } from 'react'
import { iaplT } from '../../../modules/admin-i18n/t.js'
import { formatDateTime, iaplT } from '../../../modules/admin-i18n/t.js'
import { RELAY_CONNECT_PATH, RELAY_DISCONNECT_PATH, RELAY_STATUS_PATH } from '../../../modules/email/relay/constants.js'
type Window = { limit: number; remaining: number }
@@ -15,13 +15,16 @@ type State = {
relay?: {
connected?: boolean
disconnected?: boolean
lastFailure?: { at: string; code: string }
nameReplaced?: { asked: string; used: string }
quota?: { day?: Window; hour?: Window }
revokePending?: boolean
senderAddress?: string
state?: 'active' | 'pending' | 'suspended'
tokenSource?: string
} | null
replyAddress?: null | string
smtpIncomplete?: boolean
transport?: 'graph' | 'none' | 'relay' | 'smtp'
}
@@ -40,7 +43,7 @@ const warn = { ...line, color: 'var(--theme-warning-600, #b45309)' } as const
* own; a project's own panel can import it from `/admin`. Texts: `mailRelay*` keys.
*/
export const MailRelayStatus = () => {
const { t } = useTranslation()
const { i18n, t } = useTranslation()
const { config } = useConfig()
const api = config.routes?.api ?? '/api'
const text = (key: Parameters<typeof iaplT>[1], vars?: Record<string, unknown>) => iaplT(t as never, key, vars)
@@ -81,7 +84,7 @@ export const MailRelayStatus = () => {
}
const relay = state.relay
const onRelay = state.transport === 'relay'
const relayState = !relay ? '' : relay.disconnected ? text('mailRelayStateDisconnected')
const relayState = !relay ? '' : relay.disconnected ? text(relay.revokePending ? 'mailRelayDisconnectUnconfirmed' : 'mailRelayStateDisconnected')
// why the service does not take this site: a refused enrolment, or a hand-issued token that stopped working
: state.refusalText ? state.refusalText
: !relay.connected ? text('mailRelayStateNotConnected')
@@ -103,6 +106,8 @@ export const MailRelayStatus = () => {
<>
<p role={attention ? 'alert' : undefined} style={attention ? warn : line}>{relayState}</p>
<p style={state.replyAddress ? line : warn}>{state.replyAddress ? text('mailRelayRepliesTo', { address: state.replyAddress }) : text('mailRelayNoReplyAddress')}</p>
{state.smtpIncomplete ? <p style={warn}>{text('mailRelaySmtpIncomplete')}</p> : null}
{relay.lastFailure ? <p style={{ ...line, fontSize: '0.85rem', opacity: 0.75 }}>{text('mailRelayLastFailure', { code: relay.lastFailure.code, date: formatDateTime(relay.lastFailure.at, i18n.language) })}</p> : null}
{relay.nameReplaced ? <p style={warn}>{text('mailRelayNameReplaced', { asked: relay.nameReplaced.asked, used: relay.nameReplaced.used })}</p> : null}
{relay.quota?.hour && relay.quota.day ? (
<p style={{ ...line, fontSize: '0.85rem', opacity: 0.75 }}>{text('mailRelayQuota', { day: relay.quota.day.remaining, hour: relay.quota.hour.remaining })}</p>
@@ -115,7 +120,7 @@ export const MailRelayStatus = () => {
<button className="btn btn--style-secondary btn--size-small" disabled={busy} onClick={() => void post(RELAY_CONNECT_PATH)} style={{ margin: 0 }} type="button">
{text('mailRelayConnect')}
</button>
{relay.connected ? (
{relay.connected || relay.revokePending ? (
<button
className="btn btn--style-secondary btn--size-small"
disabled={busy}
@@ -18,8 +18,10 @@ export const integrationsTexts = defineTexts({
mailRelayDisconnect: 'Disconnect',
mailRelayDisconnectConfirm: `Disconnect the site from ${IWSN}? E-mails will not be sent until you connect again or fill in an SMTP server.`,
mailRelayDisconnected: `The site is disconnected from ${IWSN}.`,
mailRelayDisconnectUnconfirmed: `${IWSN} could not be reached, so the disconnection is not confirmed. E-mails are no longer sent; press Disconnect again later.`,
mailRelayForbidden: 'Only an administrator can do this.',
mailRelayHeading: 'How e-mails are sent',
mailRelayLastFailure: 'An e-mail was not sent on {{date}}. Code: {{code}}.',
mailRelayLoadFailed: 'The state could not be read. Try again.',
mailRelayLoggedOut: 'Your session has ended. Log in again.',
mailRelayNameReplaced: `${IWSN} did not accept the sender name "{{asked}}", so e-mails leave as "{{used}}". Choose another name below.`,
@@ -32,14 +34,17 @@ export const integrationsTexts = defineTexts({
mailRelayRefusedHost: `This site has no public address yet ({{host}}). ${IWSN} works once the site runs on its domain.`,
mailRelayRefusedNoHost: 'The site does not know its own address. Ask your administrator.',
mailRelayRefusedOther: `${IWSN} answered: {{message}}`,
mailRelayRefusedSetup: `${IWSN} is not fully set up on this site. Ask your administrator.`,
mailRelayRefusedToken: `The access key of this site is no longer valid. Ask your administrator for a new one.`,
mailRelayRepliesTo: 'Replies go to {{address}}.',
mailRelaySmtpIncomplete: `The SMTP settings below are incomplete, so e-mails go through ${IWSN}. Fill in server, user name and password, or empty them.`,
mailRelayStateActive: `Connected to ${IWSN}.`,
mailRelayStateDisconnected: 'Disconnected. E-mails are not sent until you connect again or fill in an SMTP server.',
mailRelayStateNotConnected: 'Not connected yet. The site connects by itself when it sends its first e-mail.',
mailRelayStatePending: 'The site is waiting for approval, so e-mails are not sent yet. Ask your administrator.',
mailRelayStateSuspended: 'E-mail sending was stopped for this site. Ask your administrator.',
mailRelayToken: 'Enter an access key',
mailRelayTokenForeign: 'This access key belongs to another site, so it was not saved. Ask your administrator for a key for this site.',
mailRelayTokenHint: 'Only when your administrator gave you a key for this site. It is stored and never shown again.',
mailRelayTokenInvalid: `This is not an access key of ${IWSN}.`,
mailRelayTokenSave: 'Save the key',
@@ -131,8 +136,10 @@ export const integrationsTexts = defineTexts({
mailRelayDisconnect: 'Rozłącz',
mailRelayDisconnectConfirm: `Rozłączyć witrynę z ${IWSN}? E-maile nie będą wysyłane, dopóki nie połączysz jej ponownie albo nie uzupełnisz serwera SMTP.`,
mailRelayDisconnected: `Witryna jest rozłączona z ${IWSN}.`,
mailRelayDisconnectUnconfirmed: `Nie udało się połączyć z ${IWSN}, więc rozłączenie nie jest potwierdzone. E-maile nie są już wysyłane; kliknij Rozłącz ponownie później.`,
mailRelayForbidden: 'Tylko administrator może to zrobić.',
mailRelayHeading: 'Jak wysyłane są e-maile',
mailRelayLastFailure: 'E-mail nie został wysłany {{date}}. Kod: {{code}}.',
mailRelayLoadFailed: 'Nie udało się odczytać stanu. Spróbuj ponownie.',
mailRelayLoggedOut: 'Sesja wygasła. Zaloguj się ponownie.',
mailRelayNameReplaced: `${IWSN} nie przyjął nazwy nadawcy „{{asked}}”, więc e-maile wychodzą jako „{{used}}”. Wybierz inną nazwę poniżej.`,
@@ -145,14 +152,17 @@ export const integrationsTexts = defineTexts({
mailRelayRefusedHost: `Witryna nie ma jeszcze publicznego adresu ({{host}}). ${IWSN} zadziała, gdy witryna będzie dostępna pod swoją domeną.`,
mailRelayRefusedNoHost: 'Witryna nie zna własnego adresu. Zapytaj administratora.',
mailRelayRefusedOther: `${IWSN} odpowiedział: {{message}}`,
mailRelayRefusedSetup: `${IWSN} nie jest w pełni skonfigurowany w tej witrynie. Zapytaj administratora.`,
mailRelayRefusedToken: `Klucz dostępu tej witryny stracił ważność. Poproś administratora o nowy.`,
mailRelayRepliesTo: 'Odpowiedzi trafiają na adres {{address}}.',
mailRelaySmtpIncomplete: `Ustawienia SMTP poniżej są niepełne, więc e-maile idą przez ${IWSN}. Uzupełnij serwer, nazwę użytkownika i hasło albo je wyczyść.`,
mailRelayStateActive: `Połączono z ${IWSN}.`,
mailRelayStateDisconnected: 'Rozłączono. E-maile nie są wysyłane, dopóki nie połączysz witryny ponownie albo nie uzupełnisz serwera SMTP.',
mailRelayStateNotConnected: 'Jeszcze nie połączono. Witryna połączy się sama, gdy wyśle pierwszy e-mail.',
mailRelayStatePending: 'Witryna czeka na zatwierdzenie, więc e-maile nie są jeszcze wysyłane. Zapytaj administratora.',
mailRelayStateSuspended: 'Wysyłka e-maili z tej witryny została wstrzymana. Zapytaj administratora.',
mailRelayToken: 'Wpisz klucz dostępu',
mailRelayTokenForeign: 'Ten klucz dostępu należy do innej witryny, więc nie został zapisany. Poproś administratora o klucz dla tej witryny.',
mailRelayTokenHint: 'Tylko jeśli administrator przekazał Ci klucz dla tej witryny. Klucz zostanie zapisany i nie będzie więcej pokazywany.',
mailRelayTokenInvalid: `To nie jest klucz dostępu ${IWSN}.`,
mailRelayTokenSave: 'Zapisz klucz',
+11 -1
View File
@@ -20,6 +20,9 @@ type TransportIntegrations = {
}
const smtpConfigured = (s: TransportIntegrations) => Boolean(s.smtpHost && s.smtpUser && s.smtpPassword)
/** Some of server, user name and password are filled in, but not all: the SMTP server cannot be used. */
export const smtpIncomplete = (s: TransportIntegrations) => !smtpConfigured(s) && Boolean(s.smtpHost || s.smtpUser || s.smtpPassword)
let warnedSmtpIncomplete = false
/** Which transport a send takes. `none`: nothing is set up and the relay is switched off. */
export type MailTransport = 'graph' | 'none' | 'relay' | 'smtp'
@@ -156,7 +159,14 @@ export const mailAdapter =
const chosen = transportOf(settings)
// No SMTP server in the panel and no Graph: the Intecion Notifications Webservice.
if (chosen === 'relay') {return sendRelayWithPanel(payload, relayOptions()!, message, settings)}
if (chosen === 'relay') {
// Half an SMTP set-up was "not configured" before 1.17.0; now the mail leaves another way: say so once.
if (smtpIncomplete(settings) && !warnedSmtpIncomplete) {
warnedSmtpIncomplete = true
payload.logger.warn('[iapl] The SMTP settings in Site integrations are incomplete (server, user name and password are all needed), so e-mails go through the Intecion Notifications Webservice. Complete them to use the SMTP server, or empty them.')
}
return sendRelayWithPanel(payload, relayOptions()!, message, settings)
}
const useGraph = chosen === 'graph'
// "Graph" in the panel without its variables is reported only while SMTP carries the mail instead.
+2 -1
View File
@@ -36,7 +36,8 @@ export type RelayCall = {
url: string
}
const firstLine = (text: string) => text.split('\n')[0].slice(0, 300)
/** One line of the service's own words for a log or the panel: no control or invisible characters, capped. */
const firstLine = (text: string) => text.split('\n')[0].replace(/[\p{Cc}\p{Cf}\p{Zl}\p{Zp}]/gu, ' ').slice(0, 200)
/**
* One request to the service. Never throws. An answer that is not the contract's JSON — an error page
+13 -7
View File
@@ -36,7 +36,8 @@ async function readBody(req: PayloadRequest): Promise<unknown> {
* replaced by one the service has not accepted — and answers `200` with exactly
* `{ "confirmation": hex(SHA-256(nonce + "." + token)) }`, which only an endpoint that holds the
* nonce and has read the token can compute;
* - it is rate-limited per address.
* - refused calls are rate-limited per address; a call that carries a nonce the site holds is never
* turned away by the limit.
* The path is fixed for this product by the service's contract; a project cannot move it (a site with
* another API route asks Intecion to set its confirm address).
*/
@@ -45,17 +46,22 @@ export function relayConfirmEndpoint(options: Pick<RelayOptions, 'confirmRateLim
const windowMs = options.confirmRateLimit?.windowMs ?? RELAY_DEFAULTS.confirmRateLimit.windowMs
return {
handler: async (req: PayloadRequest) => {
const limit = await consumeRateLimit({ key: clientIp(req.headers), max, scope: 'mail-relay-confirm', windowMs })
if (!limit.ok) {return tooManyRequests(limit.retryAfter, { error: 'Too many requests.' })}
// Only calls that are REFUSED count against the limit, and the nonce is looked up first: the address the
// service calls from is shared (every Cloudflare Worker reaches a site behind Cloudflare from the same
// one), so a stranger who fills a per-address bucket must not keep the site's own enrolment out.
const refuse = async () => {
const limit = await consumeRateLimit({ key: clientIp(req.headers), max, scope: 'mail-relay-confirm', windowMs })
return limit.ok ? notFound() : tooManyRequests(limit.retryAfter, { error: 'Too many requests.' })
}
const body = (await readBody(req)) as { nonce?: unknown; state?: unknown; token?: unknown } | null
if (!body || typeof body !== 'object') {return notFound()}
if (!body || typeof body !== 'object') {return refuse()}
const { nonce, state, token } = body
if (typeof nonce !== 'string' || !NONCE.test(nonce) || typeof token !== 'string' || !TOKEN.test(token) || typeof state !== 'string' || !STATES.has(state)) {
return notFound()
return refuse()
}
try {
if (!(await takeNonce(req.payload, nonce))) {return notFound()}
// one read of the key-value store for a well-formed call; a wrong nonce is refused and counted
if (!(await takeNonce(req.payload, nonce))) {return refuse()}
await writeRelayCandidate(req.payload, { at: new Date().toISOString(), nonceHash: sha256Hex(nonce), state: state as 'active' | 'pending' | 'suspended', token })
} catch (err) {
req.payload.logger.error(`[iapl] mail service: the confirm route could not use the store: ${err instanceof Error ? err.message.split('\n')[0] : String(err)}`)
+7
View File
@@ -40,6 +40,13 @@ export const RELAY_DEFAULTS = {
refusalCooldownMs: 15 * 60_000,
/** How long the limits read from `/v1/status` are used before they are read again. */
statusTtlMs: 60 * 60_000,
/**
* Everything a send may take, enrolment and retries included: somebody waits for the request that sends
* the mail (a form's visitor). After it the message is reported and nothing more is tried.
*/
totalTimeoutMs: 10_000,
/** The same for a message with files: a 10 MB upload has to fit. */
totalTimeoutWithFilesMs: 30_000,
/** Other calls (status, rotate, revoke). */
timeoutMs: 10_000,
/** Waiting between the attempts for one message, in all. Wins over `retryAfter`. */
+5 -1
View File
@@ -56,8 +56,12 @@ export const getRelayStatus = (payload: BasePayload, options?: { refresh?: boole
return status(payload, resolved(payload, Object.keys(own).length ? own : undefined), { refresh })
}
/**
* `revoked: false` = the service could not be asked: the site stops using the token, but it still works there
* until this is called again and answered.
*/
/** Gives the site's token up on the service and forgets it; the site sends nothing through the service until it is connected again. */
export const disconnectRelay = (payload: BasePayload, options?: RelayOptions): Promise<void> => disconnect(payload, resolved(payload, options))
export const disconnectRelay = (payload: BasePayload, options?: RelayOptions): Promise<{ revoked: boolean }> => disconnect(payload, resolved(payload, options))
/** Asks for a new token now (the adapter does it by itself when the service says the token is due). */
export const rotateRelayToken = (payload: BasePayload, options?: RelayOptions) => rotate(payload, resolved(payload, options), { force: true })
+8 -1
View File
@@ -39,13 +39,20 @@ export type RelayOptions = {
retryBackoffMs?: number
/** The display name of outgoing mail. Default: the panel's "Sender name", else the site name. */
senderName?: ((args: { payload: BasePayload }) => null | Promise<null | string | undefined> | string | undefined) | string
/** One attempt of a send, in ms. Default 30 000 (a 10 MB attachment has to fit). */
/** One attempt of a send, in ms. Default 30 000 (a 10 MB attachment has to fit); never more than what is left of `totalTimeoutMs`. */
timeoutMs?: number
/**
* A token from elsewhere (a relay of your own, or a secret of your deployment). When set, the stored
* token is not used and the site does not enrol.
*/
token?: (() => Promise<string | undefined> | string | undefined) | string
/**
* Everything one message may take, in ms — enrolment, attempts and waits together. Default 10 000, and
* 30 000 for a message with files. A form's visitor waits for the mail, so a service that hangs must not
* hold the request for the sum of the attempts. After it the message is reported ("not confirmed" when an
* attempt was cut off). `{ plain, files }` sets the two apart; a job that nobody waits for may raise it.
*/
totalTimeoutMs?: { files?: number; plain?: number } | number
/** Base address of the service. Default `https://webservices.intecion.net/mail`. A relay of your own speaks the same contract. */
url?: string
}
+29 -7
View File
@@ -6,8 +6,9 @@ import type { RelayOptions } from './options.js'
import { userMeetsRole } from '../../access/predicates.js'
import { serverText } from '../../integrations/texts.js'
import { getSiteIntegrations } from '../../payload/index.js'
import { graphAvailable, type MailTransport, resolveMailTransport } from '../mailAdapter.js'
import { graphAvailable, type MailTransport, resolveMailTransport, smtpIncomplete } from '../mailAdapter.js'
import { RELAY_SENDER_ADDRESS } from './adapter.js'
import { relayRequest } from './client.js'
import { RELAY_CONFIRM_PATH, RELAY_CONNECT_PATH, RELAY_DISCONNECT_PATH, RELAY_STATUS_PATH } from './constants.js'
import { isPublicHost, relayHost, resolveRelayOptions } from './options.js'
import { disconnectRelay, enrolRelay, type EnrolResult, getRelayStatus, LOCAL_CODES, type RelayStatus, setRelayToken } from './session.js'
@@ -28,6 +29,8 @@ export type MailPanelState = {
/** Enabled in the project (`mail.relay` is not `false`). */
relay: ({ senderAddress: string } & RelayStatus) | null
replyAddress: null | string
/** Server, user name or password is filled in, but not all three: the SMTP server is not used. */
smtpIncomplete?: boolean
transport: MailTransport
}
@@ -60,6 +63,7 @@ export async function mailPanelState(req: Pick<PayloadRequest, 'payload'>, own:
...(status?.host ? { confirmUrl: `https://${status.host}${api}${RELAY_CONFIRM_PATH}` } : {}),
relay: status ? { ...status, senderAddress: status.senderAddress ?? RELAY_SENDER_ADDRESS } : null,
replyAddress: typeof settings.smtpFromAddress === 'string' && settings.smtpFromAddress.trim() ? settings.smtpFromAddress.trim() : null,
...(smtpIncomplete(settings) ? { smtpIncomplete: true } : {}),
transport,
}
}
@@ -76,8 +80,12 @@ export function enrolRefusalText(i18n: I18n, refusal: { code: string; message?:
// a token issued by hand that stopped working: the site cannot heal by itself
case 'invalid-token':
return serverText(i18n, 'mailRelayRefusedToken')
case LOCAL_CODES.foreignToken:
return serverText(i18n, 'mailRelayTokenForeign')
case LOCAL_CODES.noHost:
return serverText(i18n, 'mailRelayRefusedNoHost')
case LOCAL_CODES.noRoute:
return serverText(i18n, 'mailRelayRefusedSetup')
case 'reverify':
return serverText(i18n, 'mailRelayRefusedAddress')
case 'site-suspended':
@@ -125,12 +133,22 @@ export function relayPanelEndpoints(own?: false | RelayOptions): Endpoint[] {
/* no body: plain "connect again" */
}
if (typeof body.token === 'string' && body.token.trim()) {
try {
await setRelayToken(req.payload, body.token.trim(), { host: relayHost(req.payload, options) || undefined })
} catch {
return json({ error: serverText(i18n, 'mailRelayTokenInvalid'), ok: false }, 400)
const pasted = body.token.trim()
if (!/^ims_[\w-]{43}$/.test(pasted)) {return json({ error: serverText(i18n, 'mailRelayTokenInvalid'), ok: false }, 400)}
// Ask the service whose token this is BEFORE it replaces anything: a token of another site, or one the
// service does not know, is refused and the site's present connection stays as it is.
const ownHost = relayHost(req.payload, options)
const asked = await relayRequest<{ host?: string }>({ fetchImpl: options.fetchImpl, method: 'GET', path: '/v1/status', token: pasted, url: options.url })
if (asked.ok && ownHost && asked.body.host && asked.body.host !== ownHost) {return json({ error: serverText(i18n, 'mailRelayTokenForeign'), ok: false }, 400)}
if (!asked.ok && asked.code === 'invalid-token' && !asked.noAnswer) {return json({ error: serverText(i18n, 'mailRelayTokenInvalid'), ok: false }, 400)}
if (!asked.ok && asked.code !== 'reverify') {return json({ error: serverText(i18n, 'mailRelayLoadFailed'), ok: false }, 502)}
await setRelayToken(req.payload, pasted, { host: ownHost || undefined })
// the service says which host the token is for: another site's is refused and forgotten
const checked = await mailPanelState(req, own, { refresh: true })
if (checked.relay?.refusal?.code === LOCAL_CODES.foreignToken) {
return json({ ...checked, error: serverText(i18n, 'mailRelayTokenForeign'), ok: false, refusalText: serverText(i18n, 'mailRelayTokenForeign') }, 400)
}
return answer(req, own, { message: serverText(i18n, 'mailRelayConnected') }, true)
return answer(req, own, { message: serverText(i18n, 'mailRelayConnected') })
}
const result: EnrolResult = await enrolRelay(req.payload, options, { force: true })
if (!result.ok) {
@@ -148,7 +166,11 @@ export function relayPanelEndpoints(own?: false | RelayOptions): Endpoint[] {
if (refused) {return refused}
const options = resolveRelayOptions(req.payload, own)
if (!options) {return json({ error: serverText(req.i18n as I18n, 'mailRelayOff'), ok: false }, 409)}
await disconnectRelay(req.payload, options)
const { revoked } = await disconnectRelay(req.payload, options)
if (!revoked) {
// the site stopped using the token, but the service has not confirmed that it gave it up
return json({ ...(await mailPanelState(req, own)), error: serverText(req.i18n as I18n, 'mailRelayDisconnectUnconfirmed'), ok: false }, 502)
}
return answer(req, own, { message: serverText(req.i18n as I18n, 'mailRelayDisconnected') })
},
method: 'post',
+45 -6
View File
@@ -84,7 +84,7 @@ function describeRefusal(answer: RelayRefusal): { sent: false } & RelaySendResul
const extra = [answer.limit ? `limit: ${answer.limit}` : '', answer.reason ? `reason: ${answer.reason}` : '', answer.field ? `field: ${answer.field}` : ''].filter(Boolean).join(', ')
const said = `${answer.code}${extra ? ` (${extra})` : ''}: ${answer.message}`
if (answer.code === LOCAL_CODES.disconnected) {return failure('relay-disconnected', answer.code, answer.message)}
if (answer.code === LOCAL_CODES.noToken || answer.code === LOCAL_CODES.noHost) {return failure('relay-refused', answer.code, answer.message)}
if (([LOCAL_CODES.foreignToken, LOCAL_CODES.noHost, LOCAL_CODES.noRoute, LOCAL_CODES.noToken] as string[]).includes(answer.code)) {return failure('relay-refused', answer.code, answer.message)}
// No answer at all, or a send the service cannot report on yet: it may be out.
if (answer.noAnswer || answer.code === 'in-progress') {return failure('relay-not-confirmed', answer.code, `Not confirmed — the message may have been sent. ${said}`, false)}
if (answer.code === 'callback-failed' && answer.reason === 'status') {
@@ -113,6 +113,9 @@ export type RelaySendContext = {
* `Idempotency-Key`: at most three attempts, 30 seconds each, at most ten seconds of waiting between
* them in all (which win over the service's `retryAfter`), and only after an answer that says
* `retryable` or after no answer. An enrolment made on the way is not one of the three.
*
* All of it shares one budget (`totalTimeoutMs`: 10 seconds, 30 with files): the request that sends the
* mail has somebody waiting. An attempt cut off by it counts as no answer — "not confirmed".
*/
export async function sendThroughRelay(payload: BasePayload, options: ResolvedRelayOptions, message: SendEmailOptions, context: RelaySendContext = {}): Promise<RelaySendResult> {
// What the message is: its own mark; else what an auth operation said about a message to this address
@@ -158,26 +161,51 @@ export async function sendThroughRelay(payload: BasePayload, options: ResolvedRe
}
}
// Somebody waits for this request (a form's visitor): everything from here on — a check, an enrolment, the
// attempts and the waits between them — shares one budget. A service that hangs costs that much, not the
// sum of the attempts' time-outs.
const total = options.totalTimeoutMs
const hasFiles = Boolean(request.attachments?.length)
const budgetMs =
typeof total === 'number' ? total
: hasFiles ? (total?.files ?? RELAY_DEFAULTS.totalTimeoutWithFilesMs)
: (total?.plain ?? RELAY_DEFAULTS.totalTimeoutMs)
const deadline = Date.now() + Math.max(1, budgetMs)
const left = () => deadline - Date.now()
// A token stored by hand is used only once the service has said that it is this host's (a token of another
// site, pasted in or copied, must not send as that site).
if (stored.token && stored.manual && !stored.hostChecked && options.token === undefined) {
const checked = await refreshRelayStatus(payload, options, { timeoutMs: Math.max(1, left()) })
if (checked.error && checked.error.code !== 'reverify' && checked.error.code !== 'invalid-token') {
// nothing was sent: the check itself did not get through, or the token is another site's
return checked.error.code === LOCAL_CODES.foreignToken
? failure('relay-refused', checked.error.code, checked.error.message)
: failure('relay-unreachable', checked.error.code, `The token stored by hand could not be checked with the mail service, so nothing was sent. ${checked.error.message}`)
}
}
if (stored.service?.rotateAfter && Date.parse(stored.service.rotateAfter) <= Date.now()) {
await rotateRelayToken(payload, options).catch(() => undefined)
await rotateRelayToken(payload, options, { timeoutMs: Math.max(1, left()) }).catch(() => undefined)
}
const body = Buffer.from(JSON.stringify(request), 'utf8')
const hash = createHash('sha256').update(body).digest('hex')
const idempotencyKey = keyFor(hash)
const use: TokenUse = {}
const use: TokenUse = { deadline }
const budget = RELAY_DEFAULTS.waitBudgetMs
let attempts = 0
let waited = 0
let answer: RelayAnswer<SendBody> = { code: 'unavailable', message: 'not tried', noAnswer: false, ok: false, retryable: false, status: 0 }
while (attempts < RELAY_DEFAULTS.attempts) {
if (left() <= 0) {break} // the time is up: report what the last attempt said
answer = await withRelayToken<SendBody>(
payload,
options,
(token) => {
attempts += 1
return relayRequest<SendBody>({ body, fetchImpl: options.fetchImpl, idempotencyKey, method: 'POST', path: '/v1/send', timeoutMs: options.timeoutMs ?? RELAY_DEFAULTS.attemptTimeoutMs, token, url: options.url })
return relayRequest<SendBody>({ body, fetchImpl: options.fetchImpl, idempotencyKey, method: 'POST', path: '/v1/send', timeoutMs: Math.max(1, Math.min(options.timeoutMs ?? RELAY_DEFAULTS.attemptTimeoutMs, left())), token, url: options.url })
},
use,
)
@@ -186,7 +214,7 @@ export async function sendThroughRelay(payload: BasePayload, options: ResolvedRe
if (use.enrolment && !use.enrolment.ok) {break}
const wait = answer.retryAfter !== undefined ? answer.retryAfter * 1000 : attempts * (options.retryBackoffMs ?? 1000)
// The ten seconds win over retryAfter: stop at once and report.
if (waited + wait > budget) {break}
if (waited + wait > budget || wait >= left()) {break}
await sleep(wait)
waited += wait
}
@@ -214,7 +242,7 @@ export async function sendThroughRelay(payload: BasePayload, options: ResolvedRe
// Limits, quota and the day to rotate: read again once they are an hour old. Awaited (one short GET an
// hour): a write to the store that lands after the request has ended could undo a "Disconnect" or a rotation.
if (!now.service || Date.now() - Date.parse(now.service.fetchedAt) > RELAY_DEFAULTS.statusTtlMs) {
await refreshRelayStatus(payload, options)
await refreshRelayStatus(payload, options, { timeoutMs: Math.max(2000, left()) })
}
} catch {
/* bookkeeping must not turn a sent mail into a failed one */
@@ -241,6 +269,17 @@ export async function sendThroughRelay(payload: BasePayload, options: ResolvedRe
const state = answer.code === 'site-pending' ? 'pending' : 'suspended'
if (stored.state !== state) {await updateRelayStore(payload, (current) => ({ ...current, state })).catch(() => undefined)}
}
// The panel's status is the LAST send's; a later good mail must not hide this one: kept with its time
// (written when the code changes, or every ten minutes while it lasts).
try {
const now = await readRelayStore(payload)
const last = now.lastFailure
if (!last || last.code !== result.code || Date.now() - Date.parse(last.at) > 10 * 60_000) {
await updateRelayStore(payload, (current) => ({ ...current, lastFailure: { at: new Date().toISOString(), code: result.code, kind } }))
}
} catch {
/* bookkeeping only */
}
payload.logger.error(`[iapl] mail service: e-mail ${result.confirmed ? 'not sent' : 'not confirmed'} (${result.code}; ${answer.code}${answer.limit ? `, ${answer.limit}` : ''}${answer.reason ? `, ${answer.reason}` : ''}).`)
return result
}
+81 -19
View File
@@ -6,7 +6,7 @@ import type { ResolvedRelayOptions } from './options.js'
import { PLUGIN_VERSION } from '../../../version.js'
import { type RelayAnswer, type RelayRefusal, relayRequest } from './client.js'
import { RELAY_DEFAULTS, RELAY_PRODUCT, type RelayStatusCode, relayStatusFor } from './constants.js'
import { RELAY_CONFIRM_PATH, RELAY_DEFAULTS, RELAY_PRODUCT, type RelayStatusCode, relayStatusFor } from './constants.js'
import { isPublicHost, relayHost } from './options.js'
import {
clearRelayStore,
@@ -31,7 +31,11 @@ const refusal = (code: string, message: string, extra: Partial<RelayRefusal> = {
/** Codes this client makes up for what never reached the service. */
export const LOCAL_CODES = {
disconnected: 'client-disconnected',
/** A token that belongs to another site (the service says which host it is for). */
foreignToken: 'client-foreign-token',
/** This config has no confirm route, so the service could not call the site back. */
noHost: 'client-no-host',
noRoute: 'client-no-route',
noToken: 'client-no-token',
} as const
@@ -47,7 +51,7 @@ const enrolFailure = (answer: RelayRefusal): { ok: false } & EnrolResult => ({
retryable: answer.retryable,
status:
answer.code === LOCAL_CODES.disconnected ? 'relay-disconnected'
: answer.code === LOCAL_CODES.noHost || answer.code === LOCAL_CODES.noToken ? 'relay-refused'
: ([LOCAL_CODES.foreignToken, LOCAL_CODES.noHost, LOCAL_CODES.noRoute, LOCAL_CODES.noToken] as string[]).includes(answer.code) ? 'relay-refused'
: relayStatusFor(answer.code, answer.retryable),
})
@@ -60,15 +64,15 @@ const inFlight = new WeakMap<object, Promise<EnrolResult>>()
*
* `force`: also when an earlier enrolment was refused a moment ago, or the site was disconnected.
*/
export function enrolRelay(payload: BasePayload, options: ResolvedRelayOptions, { force = false }: { force?: boolean } = {}): Promise<EnrolResult> {
export function enrolRelay(payload: BasePayload, options: ResolvedRelayOptions, { deadline, force = false }: { deadline?: number; force?: boolean } = {}): Promise<EnrolResult> {
const running = inFlight.get(payload)
if (running) {return running}
const run = enrolOnce(payload, options, force).finally(() => inFlight.delete(payload))
const run = enrolOnce(payload, options, force, deadline).finally(() => inFlight.delete(payload))
inFlight.set(payload, run)
return run
}
async function enrolOnce(payload: BasePayload, options: ResolvedRelayOptions, force: boolean): Promise<EnrolResult> {
async function enrolOnce(payload: BasePayload, options: ResolvedRelayOptions, force: boolean, deadline?: number): Promise<EnrolResult> {
const stored = await readSiteStore(payload, options)
if (stored.disconnected && !force) {return enrolFailure(refusal(LOCAL_CODES.disconnected, 'The site was disconnected from the mail service in the panel.'))}
if (!force && stored.refusal && Date.parse(stored.refusal.until) > Date.now()) {
@@ -78,6 +82,11 @@ async function enrolOnce(payload: BasePayload, options: ResolvedRelayOptions, fo
if (!host) {
return enrolFailure(refusal(LOCAL_CODES.noHost, 'The site does not know its public address: set serverURL in the Payload config, or mail.relay.host.'))
}
// Without the confirm route in this config the call-back can only fail: mailAdapter() without iapl(), or
// beside `mail: { relay: false }`. Nothing is asked of the service then.
if (!(payload.config.endpoints ?? []).some((e) => e.path === RELAY_CONFIRM_PATH && e.method === 'post')) {
return enrolFailure(refusal(LOCAL_CODES.noRoute, `This config has no route POST ${RELAY_CONFIRM_PATH}, so the mail service cannot confirm the site: use iapl() without mail: { relay: false }, or add relayConfirmEndpoint() to the endpoints.`))
}
// Intecion's service calls back public DNS names only; a relay of one's own (or the local stand-in) decides itself.
if (!options.ownUrl && !isPublicHost(host)) {
return enrolFailure(refusal('host-not-allowed', `"${host}" is not a public host name, so the mail service cannot call this site back.`))
@@ -93,7 +102,7 @@ async function enrolOnce(payload: BasePayload, options: ResolvedRelayOptions, fo
fetchImpl: options.fetchImpl,
method: 'POST',
path: '/v1/enrol',
timeoutMs: RELAY_DEFAULTS.enrolTimeoutMs,
timeoutMs: deadline === undefined ? RELAY_DEFAULTS.enrolTimeoutMs : Math.max(1, Math.min(RELAY_DEFAULTS.enrolTimeoutMs, deadline - Date.now())),
url: options.url,
})
if (answer.ok) {
@@ -108,8 +117,10 @@ async function enrolOnce(payload: BasePayload, options: ResolvedRelayOptions, fo
disconnected: false,
enrolledAt: new Date().toISOString(),
host,
hostChecked: true, // issued for this host a moment ago, through this host's own route
manual: false,
refusal: null,
revokePending: false,
source: 'enrolment',
state,
token: candidate.token,
@@ -154,6 +165,16 @@ async function handIssued(payload: BasePayload, code: keyof typeof HAND_ISSUED):
return refusal(code, HAND_ISSUED[code])
}
/**
* Refusals the service answers only after it has authenticated the token: such an answer proves the token.
* `rate-limited` is not among them (its per-address gate runs before the token is looked at), nor are
* `invalid-request`, `too-large`, `unavailable`, `internal` and the answers that are not the service's own.
*/
const TOKEN_SEEN = new Set(['already-rotated', 'attachment-refused', 'backend-failed', 'idempotency-conflict', 'in-progress', 'quota-exceeded', 'recipient-suppressed', 'reverify', 'site-pending', 'site-suspended', 'too-many-recipients'])
/** Whether an answer shows that the service accepted the token it was sent with. */
export const provesToken = (answer: RelayAnswer<unknown>): boolean => answer.ok || (!answer.noAnswer && TOKEN_SEEN.has(answer.code))
/** A token from the `token` option (a relay of one's own, a deployment secret), when the project set one. */
async function optionToken(options: ResolvedRelayOptions): Promise<string | undefined> {
if (options.token === undefined) {return undefined}
@@ -162,7 +183,12 @@ async function optionToken(options: ResolvedRelayOptions): Promise<string | unde
}
/** Kept across the retries of one message: a site enrols at most once per message. */
export type TokenUse = { enrolled?: boolean; enrolment?: EnrolResult }
export type TokenUse = {
/** When the message's whole time is up (ms since the epoch): an enrolment on the way ends by then too. */
deadline?: number
enrolled?: boolean
enrolment?: EnrolResult
}
/**
* Runs `call` with the site's token and deals with what the answer says about the token:
@@ -170,7 +196,10 @@ export type TokenUse = { enrolled?: boolean; enrolment?: EnrolResult }
* - a token the call-back delivered but `/v1/enrol` never confirmed is tried first; on
* `401 invalid-token` it is dropped and the earlier token is used again;
* - `401 invalid-token` or `401 reverify` → enrol again once, then call again.
* Any answer but `invalid-token` proves the token: a candidate then becomes the token in use.
* A candidate becomes the token in use only when the service has SEEN IT ACCEPTED: a `200`, or a refusal
* the service gives after it has checked the token (TOKEN_SEEN). No answer, an error page, the
* per-address `rate-limited` and `browser-not-allowed` say nothing about a token — the candidate then stays
* beside the working token, which is never thrown away for it.
*/
export async function withRelayToken<T>(
payload: BasePayload,
@@ -194,7 +223,7 @@ export async function withRelayToken<T>(
const failed = () => (use.enrolment && !use.enrolment.ok ? refusal(use.enrolment.code, use.enrolment.message, { reason: use.enrolment.reason, retryable: use.enrolment.retryable }) : null)
if (!enrol || use.enrolled) {return failed() ?? refusal(LOCAL_CODES.noToken, 'The site is not connected to the mail service.')}
use.enrolled = true
use.enrolment = await enrolRelay(payload, options)
use.enrolment = await enrolRelay(payload, options, { deadline: use.deadline })
if (use.enrolment.ok) {return null}
// The enrolment has no good answer, but the call-back may have delivered a token all the same (the
// service's answer was lost): try it — the service says at once whether it made that token valid.
@@ -221,9 +250,10 @@ export async function withRelayToken<T>(
if (failed) {return use.enrolment && !use.enrolment.ok ? failed : answer}
continue
}
if (candidate && !provesToken(answer)) {return answer} // says nothing about the token: both stay as they are
if (candidate) {
// Seen accepted: this is the token now.
await updateRelayStore(payload, (current) => ({ ...current, enrolledAt: candidate.at, host: relayHost(payload, options) || current.host, manual: false, source: 'enrolment', state: candidate.state, token: candidate.token }))
await updateRelayStore(payload, (current) => ({ ...current, enrolledAt: candidate.at, host: relayHost(payload, options) || current.host, hostChecked: true, manual: false, source: 'enrolment', state: candidate.state, token: candidate.token }))
await dropRelayCandidate(payload)
}
if (!answer.ok && answer.code === 'reverify') {
@@ -238,6 +268,7 @@ export async function withRelayToken<T>(
}
type StatusBody = {
host?: string
limits?: NonNullable<RelayStored['service']>['limits']
quota?: NonNullable<RelayStored['service']>['quota']
sender?: { address?: string }
@@ -252,18 +283,29 @@ type StatusBody = {
* (`401 reverify`) enrols again, as on a send. Returns the stored entry as it is afterwards; `error`
* when the service could not be asked.
*/
export async function refreshRelayStatus(payload: BasePayload, options: ResolvedRelayOptions): Promise<{ error?: RelayRefusal; stored: RelayStored }> {
export async function refreshRelayStatus(payload: BasePayload, options: ResolvedRelayOptions, { timeoutMs }: { timeoutMs?: number } = {}): Promise<{ error?: RelayRefusal; stored: RelayStored }> {
const answer = await withRelayToken<StatusBody>(
payload,
options,
(token) => relayRequest<StatusBody>({ fetchImpl: options.fetchImpl, method: 'GET', path: '/v1/status', token, url: options.url }),
{},
(token) => relayRequest<StatusBody>({ fetchImpl: options.fetchImpl, method: 'GET', path: '/v1/status', timeoutMs, token, url: options.url }),
timeoutMs === undefined ? {} : { deadline: Date.now() + timeoutMs },
{ first: false },
)
if (!answer.ok) {return { error: answer, stored: await readSiteStore(payload, options) }}
const body = answer.body
// A token belongs to one host. One that the service knows as another site's (pasted into the access-key
// field, or stored by a script) is not this site's to use: forgotten here, never revoked there.
const own = relayHost(payload, options)
if (own && typeof body.host === 'string' && body.host && body.host !== own && options.token === undefined) {
const now = new Date().toISOString()
const message = `The token belongs to "${body.host}", not to this site ("${own}"): it is not used. Ask Intecion for a token for this site.`
await dropRelayCandidate(payload)
const stored = await updateRelayStore(payload, (current) => ({ ...current, hostChecked: false, manual: false, refusal: { at: now, code: LOCAL_CODES.foreignToken, message, until: now }, service: null, source: undefined, state: undefined, token: undefined }))
return { error: refusal(LOCAL_CODES.foreignToken, message), stored }
}
const stored = await updateRelayStore(payload, (current) => ({
...current,
hostChecked: true,
service: {
name: body.service?.name,
contract: body.service?.contract,
@@ -284,13 +326,13 @@ export async function refreshRelayStatus(payload: BasePayload, options: Resolved
* the site read the store again in time. `409 already-rotated` = another process won: nothing to do
* when the store already holds a newer token, else the site enrols again on its next send.
*/
export async function rotateRelayToken(payload: BasePayload, options: ResolvedRelayOptions, { force = false }: { force?: boolean } = {}): Promise<'failed' | 'not-due' | 'rotated'> {
export async function rotateRelayToken(payload: BasePayload, options: ResolvedRelayOptions, { force = false, timeoutMs }: { force?: boolean; timeoutMs?: number } = {}): Promise<'failed' | 'not-due' | 'rotated'> {
const stored = await readSiteStore(payload, options)
if (!stored.token || options.token !== undefined) {return 'not-due'}
const due = stored.service?.rotateAfter ? Date.parse(stored.service.rotateAfter) : Number.NaN
if (!force && !(due <= Date.now())) {return 'not-due'}
const used = stored.token
const answer = await relayRequest<{ token?: string }>({ fetchImpl: options.fetchImpl, method: 'POST', path: '/v1/rotate', token: used, url: options.url })
const answer = await relayRequest<{ token?: string }>({ fetchImpl: options.fetchImpl, method: 'POST', path: '/v1/rotate', timeoutMs, token: used, url: options.url })
if (answer.ok && typeof answer.body.token === 'string' && answer.body.token) {
const fresh = answer.body.token
await updateRelayStore(payload, (current) => ({
@@ -313,14 +355,26 @@ export async function rotateRelayToken(payload: BasePayload, options: ResolvedRe
return 'failed'
}
/** Gives the token up on the service (every token of the site stops working) and forgets it here. */
export async function disconnectRelay(payload: BasePayload, options: ResolvedRelayOptions): Promise<void> {
/**
* Gives the token up on the service (every token of the site stops working) and forgets it here.
* `revoked: false`: the service could not be asked — the site no longer uses the token, but it is still
* valid there until this is called again and answered.
*/
export async function disconnectRelay(payload: BasePayload, options: ResolvedRelayOptions): Promise<{ revoked: boolean }> {
// (a store copied from another host is dropped by this read: that site's token is never revoked from here)
const stored = await readSiteStore(payload, options)
if (stored.token && options.token === undefined) {
await relayRequest({ fetchImpl: options.fetchImpl, method: 'POST', path: '/v1/revoke', token: stored.token, url: options.url })
const answer = await relayRequest({ fetchImpl: options.fetchImpl, method: 'POST', path: '/v1/revoke', token: stored.token, url: options.url })
// Only the service's own word counts: "done", or "I do not know this token" (it is gone already).
if (!answer.ok && !(answer.code === 'invalid-token' && !answer.noAnswer)) {
// Not confirmed: the site stops using the token now, but it still works at the service. It is kept so
// that "Disconnect" can be pressed again.
await updateRelayStore(payload, (current) => ({ ...current, disconnected: true, revokePending: true }))
return { revoked: false }
}
}
await clearRelayStore(payload, { disconnected: true })
return { revoked: true }
}
/**
@@ -335,8 +389,10 @@ export async function setRelayToken(payload: BasePayload, token: string, options
disconnected: false,
enrolledAt: new Date().toISOString(),
...(options.host ? { host: options.host } : {}),
hostChecked: false,
manual: true,
refusal: null,
revokePending: false,
service: null,
source: 'manual',
state: current.state ?? 'active',
@@ -349,10 +405,14 @@ export type RelayStatus = {
connected: boolean
disconnected: boolean
host: string
/** The last message that was not sent or not confirmed, with its time and status code. */
lastFailure?: { at: string; code: string; kind?: string }
limits?: NonNullable<RelayStored['service']>['limits']
nameReplaced?: { asked: string; at: string; used: string }
quota?: NonNullable<RelayStored['service']>['quota']
refusal?: { at: string; code: string; message?: string; reason?: string }
/** "Disconnect" was not confirmed by the service: the token still works there. */
revokePending?: boolean
senderAddress?: string
serviceName?: string
state?: RelaySiteState
@@ -362,8 +422,10 @@ export type RelayStatus = {
export function describeRelayStore(payload: BasePayload, options: ResolvedRelayOptions, stored: RelayStored): RelayStatus {
const fromOption = options.token !== undefined
return {
connected: fromOption || Boolean(stored.token),
connected: fromOption || (Boolean(stored.token) && !stored.disconnected),
disconnected: Boolean(stored.disconnected),
...(stored.lastFailure ? { lastFailure: stored.lastFailure } : {}),
...(stored.revokePending ? { revokePending: true } : {}),
host: relayHost(payload, options) || stored.host || '',
...(stored.service?.limits ? { limits: stored.service.limits } : {}),
...(stored.nameReplaced ? { nameReplaced: stored.nameReplaced } : {}),
+10 -1
View File
@@ -30,17 +30,26 @@ export type RelayLimits = {
}
export type RelayStored = {
/** An admin pressed "Disconnect": no send and no enrolment until "Connect again". */
/**
* An admin pressed "Disconnect": no send and no enrolment until "Connect again". The token is still here
* only while the service has not confirmed that it gave it up (`revokePending`).
*/
disconnected?: boolean
enrolledAt?: string
/** The host the token was issued for. A store found on another host is not this site's (readOwnRelayStore). */
host?: string
/** The service itself said that the token is this host's (`/v1/status`). A hand-issued token is not used before that. */
hostChecked?: boolean
/** The last message that was not sent (or not confirmed): the next good one does not hide it. */
lastFailure?: { at: string; code: string; kind?: string } | null
/** The token was issued by hand: the site cannot be called back, so it never enrols by itself to heal. */
manual?: boolean
/** The last warning about the sender name: the name the mail left under instead. */
nameReplaced?: { asked: string; at: string; used: string } | null
/** The last refusal of an enrolment; no new enrolment by itself before `until`. */
refusal?: { at: string; code: string; message?: string; reason?: string; until: string } | null
/** "Disconnect" could not reach the service: the token still works there; pressing it again tries again. */
revokePending?: boolean
/** What `/v1/status` last said. */
service?: {
contract?: string
+256 -3
View File
@@ -11,14 +11,16 @@ import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest'
import { buildSmtpFields } from '../src/globals/SiteIntegrations/fields/smtp.js'
import { adminTexts } from '../src/modules/admin-i18n/index.js'
import { mailAdapter, resetGraphDeprecationWarning, resolveMailTransport } from '../src/modules/email/mailAdapter.js'
import { withAccountMailMark } from '../src/modules/email/relay/accountMail.js'
import { relayAdapter } from '../src/modules/email/relay/adapter.js'
import { RELAY_SHORT_NAME } from '../src/modules/email/relay/constants.js'
import { withMailKind } from '../src/modules/email/relay/kinds.js'
import { relayRequest } from '../src/modules/email/relay/client.js'
import { RELAY_DEFAULTS, RELAY_SHORT_NAME } from '../src/modules/email/relay/constants.js'
import { dropExpectedMail, expectMailTo, takeExpectedMail, withMailKind } from '../src/modules/email/relay/kinds.js'
import { bareAddresses, buildRelayMessage, cleanSubject } from '../src/modules/email/relay/message.js'
import { isPublicHost, relayHost, resolveRelayOptions } from '../src/modules/email/relay/options.js'
import { mailPanelState } from '../src/modules/email/relay/panel.js'
import { clearUnconfirmedRelayMessages, sendThroughRelay } from '../src/modules/email/relay/send.js'
import { disconnectRelay, enrolRelay, getRelayStatus, refreshRelayStatus, rotateRelayToken, setRelayToken } from '../src/modules/email/relay/session.js'
import { disconnectRelay, enrolRelay, getRelayStatus, provesToken, refreshRelayStatus, rotateRelayToken, setRelayToken } from '../src/modules/email/relay/session.js'
import { holdNonce, readRelayCandidate, readRelayStore, updateRelayStore } from '../src/modules/email/relay/store.js'
import { setRateLimitStore } from '../src/modules/shared/rateLimit.js'
import { callConfirmRoute, relayPayload, relaySite } from './mailRelay/helpers.js'
@@ -708,6 +710,257 @@ describe('the token over time', () => {
})
})
describe('review of 7d766b6: R-1 to R-7, R-11, and four mutations it found uncaught', () => {
const html = (status: number) => new Response('<html></html>', { headers: { 'content-type': 'text/html' }, status })
const refusalOf = (status: number, code: string, retryable = false) => Response.json({ code, message: 'x', ok: false, retryable }, { status })
/** A site with a working token and, beside it, a token the service never made valid. */
const withBadCandidate = async (own: Parameters<typeof relaySite>[0] = {}) => {
const site = relaySite({ fake: { allow: [HOST] }, ...own })
expect((await enrolRelay(site.payload, site.options, { force: true })).ok).toBe(true)
const working = (await readRelayStore(site.payload)).token!
const nonce = `bad${'c'.repeat(40)}`
await holdNonce(site.payload, nonce, 60_000)
await callConfirmRoute(site.payload)(`https://${HOST}/api/iapl/mail-relay/confirm`, { body: JSON.stringify({ nonce, state: 'active', token: `ims_${'z'.repeat(43)}` }), headers: {} })
expect((await readRelayCandidate(site.payload))?.token).toBe(`ims_${'z'.repeat(43)}`)
return { ...site, working }
}
describe('R-1: a delivered token never replaces a working one before the service has accepted it', () => {
const silent: Array<[string, () => 'drop' | Response]> = [
['an error page (502)', () => html(502)],
['no answer', () => 'drop'],
['429 rate-limited (the gate in front of the token check)', () => refusalOf(429, 'rate-limited', true)],
['403 browser-not-allowed', () => refusalOf(403, 'browser-not-allowed')],
['503 unavailable', () => refusalOf(503, 'unavailable', true)],
['400 invalid-request', () => refusalOf(400, 'invalid-request')],
]
for (const enrol of ['auto', 'manual'] as const) {
test.each(silent)(`enrol: '${enrol}', first answer %s: the working token is kept, and the next send goes out with it`, async (_name, first) => {
const { fake, options, payload, working } = await withBadCandidate({ options: { enrol } })
let answered = false
fake.intercept = (request) => {
if (answered || !request.url.endsWith('/v1/send')) {return undefined}
answered = true
return first()
}
await sendThroughRelay(payload, { ...options, totalTimeoutMs: 400 }, MESSAGE)
expect((await readRelayStore(payload)).token).toBe(working)
fake.intercept = undefined
// later: the candidate is tried, the service says invalid-token, it is dropped, the working token sends
const before = fake.requests.filter((r) => r.path === '/v1/enrol').length
expect((await sendThroughRelay(payload, options, { ...MESSAGE, subject: 'Later' })).sent).toBe(true)
expect((await readRelayStore(payload)).token).toBe(working)
expect(await readRelayCandidate(payload)).toBeNull()
expect(fake.requests.filter((r) => r.path === '/v1/enrol')).toHaveLength(before)
})
}
test('answers the service gives after it has checked the token do promote a delivered one', async () => {
expect(provesToken({ body: {}, ok: true, status: 200 })).toBe(true)
const answer = (code: string, noAnswer = false) => ({ code, message: '', noAnswer, ok: false as const, retryable: false, status: 0 })
for (const code of ['site-pending', 'site-suspended', 'quota-exceeded', 'too-many-recipients', 'attachment-refused', 'recipient-suppressed', 'backend-failed', 'in-progress', 'idempotency-conflict', 'reverify', 'already-rotated']) {
expect(provesToken(answer(code)), code).toBe(true)
}
for (const code of ['invalid-token', 'rate-limited', 'browser-not-allowed', 'unavailable', 'internal', 'invalid-request', 'too-large', 'not-found', 'a-code-of-next-year']) {
expect(provesToken(answer(code)), code).toBe(false)
}
expect(provesToken(answer('quota-exceeded', true))).toBe(false)
// a real one: the enrolment's answer is lost, the site is pending — `site-pending` proves the delivered token
const { fake, options, payload } = relaySite()
fake.intercept = async (request) => {
if (!request.url.endsWith('/v1/enrol')) {return undefined}
fake.intercept = undefined
await fake.handle(request)
return 'drop'
}
expect(await sendThroughRelay(payload, options, MESSAGE)).toMatchObject({ code: 'relay-pending' })
expect((await readRelayStore(payload)).token).toMatch(/^ims_/)
expect(await readRelayCandidate(payload)).toBeNull()
})
})
test('R-2: a token of another site, stored by hand, is refused by what /v1/status says — nothing is sent, nothing is revoked', async () => {
const { fake, options, payload } = relaySite({ fake: { allow: [HOST] } })
const foreign = fake.issueToken('other-client.example.org')
await setRelayToken(payload, foreign) // a script, or the access-key field
const result = await sendThroughRelay(payload, options, MESSAGE)
expect(result).toMatchObject({ cause: 'client-foreign-token', code: 'relay-refused', sent: false })
expect(fake.outbox).toHaveLength(0)
expect(fake.requests.map((r) => r.path)).toEqual(['/v1/status'])
expect((await readRelayStore(payload)).token).toBeUndefined()
expect((await getRelayStatus(payload, options)).refusal).toMatchObject({ code: 'client-foreign-token' })
// the other site's token still works there
expect((await fake.handle(new Request(`${fake.url}/v1/status`, { headers: { authorization: `Bearer ${foreign}` } }))).status).toBe(200)
// the site's own token, issued by hand for its host, passes the same check
await setRelayToken(payload, fake.issueToken(HOST))
expect((await sendThroughRelay(payload, options, MESSAGE)).sent).toBe(true)
expect(await readRelayStore(payload)).toMatchObject({ host: HOST, hostChecked: true, manual: true })
// when the service cannot be asked, a token stored by hand is not used unchecked
await setRelayToken(payload, fake.issueToken(HOST))
fake.intercept = () => 'drop'
expect(await sendThroughRelay(payload, { ...options, totalTimeoutMs: 300 }, MESSAGE)).toMatchObject({ code: 'relay-unreachable', confirmed: true, sent: false })
})
test('R-3: junk calls to the confirm route do not keep the site\'s own enrolment out', async () => {
const { fake, options, payload } = relaySite({ fake: { allow: [HOST] } })
const confirm = callConfirmRoute(payload) // every call comes from one address, as the service's does
const url = `https://${HOST}/api/iapl/mail-relay/confirm`
const junk = () => confirm(url, { body: JSON.stringify({ nonce: 'j'.repeat(43), state: 'active', token: `ims_${'j'.repeat(43)}` }), headers: {} })
const statuses: number[] = []
for (let i = 0; i < 14; i++) {statuses.push((await junk()).status)}
expect(statuses.slice(0, 10)).toEqual(Array(10).fill(404))
expect(statuses.slice(10)).toEqual([429, 429, 429, 429]) // refused calls are limited …
// … and the call that carries a nonce the site holds is answered all the same
expect(await enrolRelay(payload, options)).toEqual({ ok: true, state: 'active' })
expect((await getRelayStatus(payload, options)).refusal).toBeUndefined()
expect((await sendThroughRelay(payload, options, MESSAGE)).sent).toBe(true)
expect(fake.requests.filter((r) => r.path === '/v1/enrol')).toHaveLength(1)
})
describe('R-4: one message has one budget of time', () => {
const hanging = (async (_input: unknown, init?: RequestInit) =>
new Promise<Response>((_resolve, reject) => init?.signal?.addEventListener('abort', () => reject(new DOMException('aborted', 'AbortError'))))) as typeof fetch
test('the defaults: ten seconds, thirty with files', () => {
expect(RELAY_DEFAULTS).toMatchObject({ attempts: 3, attemptTimeoutMs: 30_000, totalTimeoutMs: 10_000, totalTimeoutWithFilesMs: 30_000 })
})
test('a service that accepts the connection and says nothing: the visitor waits the budget, not three time-outs', async () => {
const { options, payload } = relaySite({ fake: { allow: [HOST] } })
await enrolRelay(payload, options)
const started = Date.now()
const result = await sendThroughRelay(payload, { ...options, fetchImpl: hanging, timeoutMs: 30_000, totalTimeoutMs: 500 }, MESSAGE)
const took = Date.now() - started
// cut off while the service may have been handling it: not confirmed
expect(result).toMatchObject({ code: 'relay-not-confirmed', confirmed: false, sent: false })
expect(took).toBeGreaterThanOrEqual(450)
expect(took).toBeLessThan(1500)
})
test('the budget covers an enrolment on the way, and a message with files has its own', async () => {
const { options, payload } = relaySite({ fake: { allow: [HOST] } }) // not enrolled: the first call is /v1/enrol
let started = Date.now()
const result = await sendThroughRelay(payload, { ...options, fetchImpl: hanging, totalTimeoutMs: { files: 900, plain: 300 } }, MESSAGE)
// the message never left the site: not sent, and said so
expect(result).toMatchObject({ code: 'relay-unreachable', confirmed: true, sent: false })
expect(Date.now() - started).toBeLessThan(800)
started = Date.now()
await sendThroughRelay(payload, { ...options, fetchImpl: hanging, totalTimeoutMs: { files: 900, plain: 300 } }, { ...MESSAGE, attachments: [{ content: Buffer.from('x'), filename: 'a.txt' }] })
expect(Date.now() - started).toBeGreaterThanOrEqual(850)
expect(Date.now() - started).toBeLessThan(1900)
})
test('retries stop when the time is up, and a wait that would pass it is not waited', async () => {
const { fake, options, payload } = relaySite({ fake: { allow: [HOST] } })
await enrolRelay(payload, options)
let sends = 0
fake.intercept = (request) => (request.url.endsWith('/v1/send') ? (sends++, refusalOf(503, 'unavailable', true)) : undefined)
const started = Date.now()
await sendThroughRelay(payload, { ...options, retryBackoffMs: 400, totalTimeoutMs: 300 }, MESSAGE)
expect(sends).toBe(1)
expect(Date.now() - started).toBeLessThan(300)
})
})
test('R-5: "Disconnect" while the service is down is not confirmed: the token is kept to try again, and not used', async () => {
const { fake, options, payload } = relaySite({ fake: { allow: [HOST] } })
await sendThroughRelay(payload, options, MESSAGE)
const token = (await readRelayStore(payload)).token!
fake.intercept = () => html(502)
expect(await disconnectRelay(payload, options)).toEqual({ revoked: false })
expect(await readRelayStore(payload)).toMatchObject({ disconnected: true, revokePending: true, token })
expect(await getRelayStatus(payload, options)).toMatchObject({ connected: false, disconnected: true, revokePending: true })
fake.intercept = undefined
// the token still works at the service — that is why the panel must not say "done"
expect((await fake.handle(new Request(`${fake.url}/v1/status`, { headers: { authorization: `Bearer ${token}` } }))).status).toBe(200)
expect(await sendThroughRelay(payload, options, MESSAGE)).toMatchObject({ code: 'relay-disconnected', sent: false })
// pressed again with the service back: revoked and forgotten
expect(await disconnectRelay(payload, options)).toEqual({ revoked: true })
expect(await readRelayStore(payload)).toEqual({ disconnected: true, v: 1 })
expect((await fake.handle(new Request(`${fake.url}/v1/status`, { headers: { authorization: `Bearer ${token}` } }))).status).toBe(401)
})
test('R-6: without the confirm route in the config the site does not ask to be enrolled', async () => {
const { fake, options, payload } = relaySite({ endpoints: [], fake: { allow: [HOST] } })
const result = await sendThroughRelay(payload, options, MESSAGE)
expect(result).toMatchObject({ cause: 'client-no-route', code: 'relay-refused', sent: false })
expect(result.sent === false && result.detail).toContain('relayConfirmEndpoint()')
expect(fake.requests).toEqual([])
// a token from elsewhere needs no route
const token = fake.issueToken(HOST)
expect((await sendThroughRelay(payload, { ...options, enrol: false, token }, MESSAGE)).sent).toBe(true)
})
test('R-7: half an SMTP set-up is said, once in the log and in the panel', async () => {
const { fake, logger, options, payload } = relaySite({ fake: { allow: [HOST] }, integrations: { smtpHost: 'smtp.example.com', smtpUser: '[email protected]' } })
const adapter = adapterOf(mailAdapter({ relay: options }), payload)
expect(((await adapter.sendEmail(MESSAGE)) as { transport?: string }).transport).toBe('relay')
await adapter.sendEmail(MESSAGE)
expect(logger.warn.mock.calls.map((c) => String(c[0])).filter((m) => m.includes('SMTP settings in Site integrations are incomplete'))).toHaveLength(1)
expect(await mailPanelState({ payload }, options)).toMatchObject({ smtpIncomplete: true, transport: 'relay' })
expect((await mailPanelState(relayPayload(), {})).smtpIncomplete).toBeUndefined()
expect(fake.outbox).toHaveLength(2)
})
test('R-11: a mail that was not sent stays visible after the next one went out', async () => {
const { fake, options, payload } = relaySite({ fake: { allow: [HOST] } })
await sendThroughRelay(payload, options, MESSAGE)
fake.backend = 'recipient-suppressed'
await sendThroughRelay(payload, options, withMailKind({ ...MESSAGE, subject: 'Lost' }, 'form-confirmation'))
fake.backend = 'ok'
expect((await sendThroughRelay(payload, options, { ...MESSAGE, subject: 'Fine' })).sent).toBe(true)
const status = await getRelayStatus(payload, options)
expect(status.lastFailure).toMatchObject({ code: 'relay-recipient-suppressed', kind: 'form-confirmation' })
expect(Date.parse(status.lastFailure!.at)).toBeGreaterThan(Date.now() - 5000)
})
test('the token never follows a redirect, and the service\'s words are one clean line', async () => {
const seen: RequestInit[] = []
const fetchImpl = (async (_input: unknown, init?: RequestInit) => {
seen.push(init ?? {})
return Response.json({ code: 'quota-exceeded', message: 'Line one\u202E\u0007 of it\nsecond line', ok: false, retryable: false }, { status: 429 })
}) as typeof fetch
const answer = await relayRequest({ fetchImpl, method: 'POST', path: '/v1/send', token: `ims_${'t'.repeat(43)}`, url: 'https://relay.example.net/mail' })
expect(seen[0].redirect).toBe('manual')
expect(answer).toMatchObject({ message: 'Line one of it', ok: false })
const headers = new Headers(seen[0].headers)
expect(headers.has('origin')).toBe(false)
expect(headers.has('sec-fetch-site')).toBe(false)
})
test('an enrolment is not taken for done when the token that arrived belongs to another nonce', async () => {
const { fake, options, payload } = relaySite({ fake: { allow: [HOST] } })
// a token delivered for some OTHER enrolment is in the store; the service answers 200 to this one without calling back
const other = `oth${'e'.repeat(40)}`
await holdNonce(payload, other, 60_000)
await callConfirmRoute(payload)(`https://${HOST}/api/iapl/mail-relay/confirm`, { body: JSON.stringify({ nonce: other, state: 'active', token: `ims_${'o'.repeat(43)}` }), headers: {} })
fake.intercept = (request) => (request.url.endsWith('/v1/enrol') ? Response.json({ ok: true, state: 'active' }) : undefined)
expect(await enrolRelay(payload, options)).toMatchObject({ code: 'callback-failed', ok: false })
expect((await readRelayStore(payload)).token).toBeUndefined()
})
test('what an operation said about its mail is for one recipient and is taken back when it sent none', () => {
expectMailTo('[email protected]', 'account', { visitor: '198.51.100.9' })
expect(takeExpectedMail(['[email protected]', '[email protected]'])).toBeUndefined() // a mail to several is not that mail
expect(takeExpectedMail(['[email protected]'])).toEqual({ kind: 'account', visitor: '198.51.100.9' })
expect(takeExpectedMail(['[email protected]'])).toBeUndefined() // used up
expectMailTo('[email protected]', 'account')
dropExpectedMail(' [email protected] ')
expect(takeExpectedMail(['[email protected]'])).toBeUndefined()
// the hook pair on an auth collection does exactly that around an operation
const marked = withAccountMailMark({ slug: 'users', auth: true, fields: [] })
const before = marked.hooks!.beforeOperation!.at(-1) as (args: object) => unknown
const after = marked.hooks!.afterOperation!.at(-1) as (args: object) => unknown
const args = { args: { data: { email: '[email protected]' } }, operation: 'forgotPassword', req: { headers: new Headers() } }
before(args)
after({ ...args, result: null })
expect(takeExpectedMail(['[email protected]'])).toBeUndefined()
before(args)
expect(takeExpectedMail(['[email protected]'])?.kind).toBe('account')
expect(withAccountMailMark(marked)).toBe(marked) // not added twice
})
})
describe('what the panel is told', () => {
test('the panel calls the service by its short name, IWSN, in both languages — one constant, never another name', () => {
expect(RELAY_SHORT_NAME).toBe('IWSN')
+2 -2
View File
@@ -30,12 +30,12 @@ export const contractExamples = (): ContractExample[] =>
.map((f) => JSON.parse(readFileSync(path.join(CONTRACT_DIR, 'examples', f), 'utf8')) as ContractExample)
/** The slice of Payload the relay client touches: the key-value store, the config, the logger, the two globals. */
export function relayPayload({ custom, integrations = {}, serverURL = 'https://example.com', siteName = '' }: { custom?: object; integrations?: Record<string, unknown>; serverURL?: string; siteName?: string } = {}) {
export function relayPayload({ custom, endpoints = [relayConfirmEndpoint()], integrations = {}, serverURL = 'https://example.com', siteName = '' }: { custom?: object; endpoints?: unknown[]; integrations?: Record<string, unknown>; serverURL?: string; siteName?: string } = {}) {
const store = new Map<string, unknown>()
const logger = { error: vi.fn(), info: vi.fn(), warn: vi.fn() }
const settings = { ...integrations }
const payload = {
config: { custom: custom ?? {}, globals: [{ slug: 'site-integrations' }, { slug: 'site-settings' }], routes: { api: '/api' }, serverURL },
config: { custom: custom ?? {}, endpoints, globals: [{ slug: 'site-integrations' }, { slug: 'site-settings' }], routes: { api: '/api' }, serverURL },
findGlobal: vi.fn(async ({ slug }: { slug: string }) => (slug === 'site-settings' ? { siteName } : settings)),
kv: {
delete: async (key: string) => void store.delete(key),
+20
View File
@@ -205,6 +205,13 @@ describe('the state routes are for admins', () => {
})
test('"Disconnect" and "Connect again" work for an admin, and neither shows a token', async () => {
// a token of another site pasted while the site is connected: refused, and the site's own token stays
const mine = (await readRelayStore(payload)).token
const stranger = fake.issueToken('someone-else.example.org')
expect((await post('/iapl/mail-relay/connect', admin, { token: stranger })).status).toBe(400)
expect((await readRelayStore(payload)).token).toBe(mine)
expect(mine).toMatch(/^ims_/)
const off = await post('/iapl/mail-relay/disconnect', admin)
const offBody = (await off.json()) as Record<string, unknown>
expect(offBody).toMatchObject({ ok: true, relay: { connected: false, disconnected: true } })
@@ -213,6 +220,19 @@ describe('the state routes are for admins', () => {
const bad = await post('/iapl/mail-relay/connect', admin, { token: 'ims_not-a-token' })
expect(bad.status).toBe(400)
// the access-key field: a token the service does not know, and a token of ANOTHER site, are refused before
// anything is stored; the other site's token is not revoked
expect((await post('/iapl/mail-relay/connect', admin, { token: `ims_${'q'.repeat(43)}` })).status).toBe(400)
const foreign = fake.issueToken('other-client.example.org')
const refused = await post('/iapl/mail-relay/connect', admin, { token: foreign })
expect(refused.status).toBe(400)
expect(await refused.text()).not.toContain('ims_')
expect((await readRelayStore(payload)).token).toBeUndefined()
expect((await fake.handle(new Request(`${fake.url}/v1/status`, { headers: { authorization: `Bearer ${foreign}` } }))).status).toBe(200)
// a token issued by hand for THIS host is taken, and the state says where it came from
const own = await post('/iapl/mail-relay/connect', admin, { token: fake.issueToken(HOST) })
expect(await own.json()).toMatchObject({ ok: true, relay: { connected: true, tokenSource: 'manual' } })
await post('/iapl/mail-relay/disconnect', admin)
const on = await post('/iapl/mail-relay/connect', admin)
const onBody = (await on.json()) as Record<string, unknown>
expect(onBody, JSON.stringify(onBody)).toMatchObject({ ok: true, relay: { connected: true, disconnected: false, state: 'active' } })