Mail relay: review round 2 — the store is keyed by host, a copied database does not enrol by itself
- Q-1 one entry per host (iapl:mail-relay:site:<host>); a read never deletes or writes; another host's
entry is neither used nor touched (a developer's process on the live database, www and apex, a copy)
- a database that holds another host's connection and none of this site's does not enrol by itself:
"Connect again" does, once; mail.relay.otherHosts ('wait' | 'enrol' | the site's own other hosts);
panel text and doctor finding; a site with an empty store enrols by itself as before
- Q-2 the file limit answers from what is stored and never asks the service
- Q-3 a file whose mail was not confirmed is not reported as a wrong file, and no notice mail follows
- Q-4 its own text when the access-key field is off
- D-1 docs for open enrolment; staging, copies and several hosts
Co-Authored-By: Claude Fable 5.2 <[email protected]>
This commit is contained in:
co-authored by
Claude Fable 5.2
parent
edee3a321f
commit
85ed92bb89
+4
-3
@@ -39,8 +39,9 @@ once there are more than 20.
|
||||
| SMTP filled in (server, user name, password) | Nothing. No call to Intecion | — |
|
||||
| `GRAPH_*` set and "Microsoft Graph" chosen | Mail as before. One deprecation warning in the start log, one doctor warning (`mail-graph-deprecated`) | `mail: { graphDeprecationWarning: false }` (the log line) |
|
||||
| `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 } })` |
|
||||
| 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]`. The site is active as soon as it enrols (the service holds a site for approval only as an exception) | `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 |
|
||||
| **A copy** of a site's database on another host (staging made from production), with no SMTP there | It does **not** connect by itself — its data is production's, and it would mail real people: sends report `relay-refused`, the panel and the doctor say why. "Connect again" lets it send; `mail: { relay: false }` or SMTP to a catcher keeps it silent for good | `mail: { relay: { otherHosts: 'enrol' } }` |
|
||||
| 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 | — |
|
||||
@@ -88,7 +89,7 @@ once there are more than 20.
|
||||
The admin panel calls it **IWSN**; docs, logs and the doctor use the full name.
|
||||
`mailAdapter()` now picks per send: Graph when the panel says so and `GRAPH_*` is set → SMTP when the panel has a
|
||||
server → Graph when `GRAPH_*` is set → the mail service → not configured (`resolveMailTransport`). The site holds no
|
||||
mail key: it enrols by a call-back to its own domain and keeps its token in `payload-kv` (key `iapl:mail-relay` —
|
||||
mail key: it enrols by a call-back to its own domain and keeps its token in `payload-kv` (one entry per host, `iapl:mail-relay:site:<host>` —
|
||||
no field, no column; not readable over REST or GraphQL, an admin included; proven by a test). The token is bound to
|
||||
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
|
||||
@@ -101,7 +102,7 @@ once there are more than 20.
|
||||
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, accessKeyField, totalTimeoutMs, timeoutMs, retryBackoffMs, fetchImpl }, graphDeprecationWarning }`; `mailAdapter({ relay })`.
|
||||
confirmRateLimit, accessKeyField, otherHosts, 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" for a token issued by hand only with `mail.relay.accessKeyField: true`); "Sending method" reads "Automatic" / "Microsoft Graph (deprecated)"; the server field reads
|
||||
|
||||
+8
-2
@@ -1282,7 +1282,12 @@ the mail service → nothing (`mail: { relay: false }` and no SMTP). A site with
|
||||
3. The server may call `https://webservices.intecion.net`.
|
||||
4. Site integrations → E-mail sending: "Sender name" (else the site name is used) and **"Sender address"** — with
|
||||
the mail service that is where replies go; the service's own address has no mailbox.
|
||||
5. Intecion has listed the host; otherwise the site enrols and waits for approval (`relay-pending`).
|
||||
5. Nothing to arrange with Intecion: a site that passes the call-back is active at once (`relay-pending`, held for
|
||||
approval, is the exception — the panel says so).
|
||||
6. **Staging made from a copy of production's database** does not connect by itself (it would mail production's
|
||||
real addresses): it stays "not connected" until an admin presses "Connect again". For a copy that must never
|
||||
send: `mail: { relay: false }` or SMTP to a catcher. After a **domain move** press "Connect again" once, or set
|
||||
`mail: { relay: { otherHosts: ['old-domain.example'] } }`. A site before launch (empty store) enrols by itself.
|
||||
|
||||
**Verify:** Site integrations → E-mail sending → the block "How e-mails are sent" says "Connected to IWSN"; **Send test e-mail** answers "through IWSN, as <name>"; the mail arrives from
|
||||
`[email protected]` with the client's name and `Reply-To` the client's address; `iapl-doctor
|
||||
@@ -1315,6 +1320,7 @@ overrides per adapter; `resolveRelayOptions` reads what is in effect):
|
||||
| `relay: false` | on | no mail service: no outbound call, no routes, no state block |
|
||||
| `url` | `RELAY_BASE_URL` | a relay of your own (same contract) |
|
||||
| `host` | host of `serverURL` (`relayHost`, `isPublicHost`) | the public host the service calls back |
|
||||
| `otherHosts` | `'wait'` | a database holding another host's connection and none of this site's (a copy, a moved domain): wait for "Connect again"; a list of the site's own other hosts; or `'enrol'` |
|
||||
| `enrol` | `'auto'` | `'manual'` (only "Connect again" / `enrolRelay`), `false` (token from `token` / `setRelayToken`) |
|
||||
| `accessKeyField` | `false` | `true`: admins get "Enter an access key" in the state block (a hand-issued token) |
|
||||
| `token` | — | a token from elsewhere; nothing is stored, the site does not enrol |
|
||||
@@ -1363,7 +1369,7 @@ The panel has no field for it unless the project sets `mail: { relay: { accessKe
|
||||
cannot heal by itself: after a move to another server it reports `relay-refused` until Intecion adds the address
|
||||
or issues a new token. A token of another host is refused on every way in.
|
||||
|
||||
**Never:** read or print the token (`payload.kv`, key `iapl:mail-relay`); add a field or env variable for it; call
|
||||
**Never:** read or print the token (`payload.kv`, keys `iapl:mail-relay:…`, one entry per host); add a field or env variable for it; call
|
||||
the service from a client component; retry a failed send in a loop of your own; mark form mail as `account`.
|
||||
|
||||
---
|
||||
|
||||
@@ -102,8 +102,8 @@ through this procedure. Ask only when you are missing something you cannot get y
|
||||
| `relay-refused` / "The mail service could not reach this site at …" (cause `callback-failed`) | `unreachable` / `timeout`: firewall, private network, wrong public host in `serverURL`; `redirect`: `trailingSlash: true`, apex → `www`, a language redirect; `status`: route blocked, missing (`mail: { relay: false }`?) or another `routes.api`; `confirmation`: a proxy rewrites the answer | `curl -i -X POST https://<host>/api/iapl/mail-relay/confirm -d '{}' -H 'content-type: application/json'` must answer **404 with an empty body, no redirect**; fix `serverURL` / `mail.relay.host`, or ask Intecion to set the site's confirm address (path ending in `/confirm/` with trailing slashes); then "Connect again" (the site does not retry by itself for 15 min). email.md "When the site cannot be confirmed" |
|
||||
| `relay-refused`, cause `host-not-allowed` / "This site has no public address yet" | the site runs on `localhost`, a private name, or `serverURL` is empty | expected in development (use SMTP / Mailpit there); in production set `serverURL` |
|
||||
| `relay-refused` on a site whose token was entered by hand ("does not know the server this site now runs on" / "access key … no longer valid") | the site moved or got a second server, or its token expired; a site with a hand-issued token cannot enrol by itself | Intecion adds the server's address, or issues a new token — set it with `setRelayToken(payload, token)` from a script (`pnpm payload run`), or in the panel when the project has `mail.relay.accessKeyField: true` (email.md "The token") |
|
||||
| staging sends nothing after its database was copied from production: "Not connected yet" / "waiting for approval" | expected: production's token is tied to production's host and is not used on the copy; the copy enrolled as itself | Intecion approves the staging host, or staging uses SMTP / `mail: { relay: false }` |
|
||||
| `relay-pending` / "waiting for approval" | the host is not on Intecion's list | Intecion approves it on the service; nothing to change on the site; the same token then works |
|
||||
| a site sends nothing: "The data comes from another site (…), so this site did not connect by itself" / `relay-refused`, cause `client-other-host` | the database holds another host's connection and none of this site's: a staging copy of production, a moved domain, a second domain. Expected — a copy with production's data must not mail real people by itself | should it send: "Connect again" in the state block, once. A moved or second domain: `mail: { relay: { otherHosts: ['old-domain.example'] } }`. A copy that must never send: `mail: { relay: false }` or SMTP to a catcher |
|
||||
| `relay-pending` / "waiting for approval" | the exception: the service holds new sites for approval when many appear at once, or Intecion approves by hand (a site is normally active as soon as it enrols) | Intecion approves it on the service; nothing to change on the site; the same token then works |
|
||||
| `relay-suspended` | Intecion stopped the site (abuse, a flood from a form) | contact Intecion; fill in SMTP meanwhile |
|
||||
| `relay-disconnected` | an admin pressed "Disconnect" | "Connect again", or SMTP |
|
||||
| `relay-quota` | the site's hour or day is used up (30 / 200 by default), more than 10 recipients, more than 10 confirmations to one address a day, too many new addresses, or the site's own limit on account mail (`mail.relay.accountMail`) | the server log names the limit; look for a form being abused (Turnstile on? rate limit?); a site that really sends more: Intecion raises the limits, or SMTP |
|
||||
|
||||
@@ -646,7 +646,7 @@ scaling (5). `●` routes for pages need the database at build time (PROGRAMISTA
|
||||
6. **Notifications**: form messages in every language.
|
||||
7. **Site integrations → E-mail sending**: "Sender name" (the client's name; empty = the site name) and **"Sender
|
||||
address"** (the client's address: with the mail service replies go there). SMTP fields **only** when the client asked
|
||||
for its own server. On the production domain: the block "How e-mails are sent" must say "Connected to IWSN" ("waiting for approval" = ask Intecion to approve the host), then **Send test e-mail** → "through IWSN". Turnstile (for testing site
|
||||
for its own server. On the production domain: the block "How e-mails are sent" must say "Connected to IWSN" (a site is active as soon as it enrols; "waiting for approval" is the exception — ask Intecion; "The data comes from another site" = this database is a copy: press "Connect again" only if the copy should send), then **Send test e-mail** → "through IWSN". Turnstile (for testing site
|
||||
`1x00000000000000000000AA`, secret `1x0000000000000000000000000000000AA`; production keys from the client), analytics/pixel
|
||||
IDs, IndexNow → generate key. Mail/Turnstile errors show up as a dashboard alert.
|
||||
8. **Forms**: check the addresses in the Emails tab of the seeded forms.
|
||||
|
||||
@@ -571,8 +571,11 @@ PROGRAMISTA §6, item 73; email.md; AGENT.md §7.2) — nothing to run; read whi
|
||||
`iapl({ mail: { relay: false } })`.
|
||||
3. **For a site that will use the mail service:** `serverURL` is the public address the site answers on without a
|
||||
redirect; no proxy or WAF rule blocks `/api/iapl/mail-relay/confirm`; `trailingSlash: true` or another `routes.api` →
|
||||
Intecion sets the site's confirm address first; "Sender address" is filled in (replies go there); Intecion has listed
|
||||
the host (otherwise "waiting for approval"); the client's processing agreement names the service.
|
||||
Intecion sets the site's confirm address first; "Sender address" is filled in (replies go there); the client's
|
||||
processing agreement names the service. Nothing to arrange with Intecion: the site is active as soon as it enrols.
|
||||
**A staging copy of the database** does not connect by itself (it would mail production's real addresses): it
|
||||
says so in the panel until an admin presses "Connect again"; keep it silent with `mail: { relay: false }` or SMTP
|
||||
to a catcher. After a domain move: "Connect again" once, or `mail: { relay: { otherHosts: ['old-domain.example'] } }`.
|
||||
4. Code that compared the result of `payload.sendEmail` needs no change for SMTP and Graph. A send through the mail
|
||||
service returns `{ sent, transport: 'relay', … }`; `sent: false` with `confirmed: false` means "may have been sent".
|
||||
5. Your own account mail (invitations): mark it — `withMailKind(message, 'account')`. Form mail and Payload's
|
||||
|
||||
+7
-3
@@ -54,9 +54,13 @@ Mail needs **no variable**. A site with no SMTP server in the panel sends throug
|
||||
- **That route reachable from the internet** — no basic auth on the Coolify app, no firewall or WAF rule in front of
|
||||
`/api/iapl/`; behind Cloudflare leave it uncached and unchallenged.
|
||||
- **Outbound HTTPS** to `webservices.intecion.net`.
|
||||
- A staging copy on its own domain enrols as its own site (its own token, its own limits, its own approval) —
|
||||
**also when its database is a copy of production's**: the stored token is tied to production's host and is not
|
||||
used on another one. A staging copy that must not send: `iapl({ mail: { relay: false } })` or SMTP to a catcher.
|
||||
- **Staging.** A site is active as soon as it enrols, so a staging site sends real mail. A staging site made from a
|
||||
**copy of production's database** does not connect by itself (its data is production's; it stays "not connected"
|
||||
until an admin presses "Connect again") and never uses or touches production's connection. The safe set-up for a
|
||||
copy that must not send: `iapl({ mail: { relay: false } })` or SMTP to a catcher ([email.md](./email.md)
|
||||
"Staging, copies and several hosts").
|
||||
- **A domain move** (the same database under a new host): press "Connect again" once after the move, or set
|
||||
`mail: { relay: { otherHosts: ['old-domain.example'] } }` before it.
|
||||
- Several containers of one site share the database, so they share the token; a restore of an old database dump
|
||||
brings back an old token — the site then enrols again by itself on its next e-mail.
|
||||
|
||||
|
||||
+1
-1
@@ -113,7 +113,7 @@ Turn off: `iapl({ doctor: false })`. Adapt: `iapl({ doctor: { tokenVar: 'MY_TOKE
|
||||
| | `storage-names` | warning | the visitor cookie the layout sets (`<PageStats visitorCookie>`, default `ipal_vid`) is the one the config makes the cookie scanner declare (`storageNames`, stats.md) |
|
||||
| | `cookie-scanner` | error / warning / info | `cookieScanner` on (with `crawl`, else info); deep: nothing waits for approval (warning) |
|
||||
| mail | `mail-transport` | error / warning | (deep) an e-mail transport is in effect (not: the mail service switched off and no SMTP server); the last sends worked — failing: warning, error once it has lasted 24 hours |
|
||||
| | `mail-relay-state` | error / warning / info | (deep) on the Intecion mail service: not disconnected and not stopped (error), not waiting for approval, not refused at enrolment, the sender name not replaced (warning); not enrolled yet (info) |
|
||||
| | `mail-relay-state` | error / warning / info | (deep) on the Intecion mail service: not disconnected and not stopped (error), not waiting for approval, not refused at enrolment, not a copied database that waits for "Connect again" (`client-other-host`), the sender name not replaced (warning); not enrolled yet (info) |
|
||||
| | `mail-reply-address` | warning | (deep) on the mail service, "Sender address" is filled in: replies go there |
|
||||
| | `mail-graph-deprecated` | warning | Microsoft Graph is not in use: no `GRAPH_*` variables on the site (deep), no `graphAdapter` / `emailGraph: true` in the config — deprecated, removed in 2.0 |
|
||||
| | `mail-relay-route` | warning | nothing keeps the mail service from confirming the site: no `trailingSlash: true`, `routes.api` is `/api` (else Intecion sets the site's confirm address); live, on the mail service: `/api/iapl/mail-relay/confirm` answers without a redirect, a block or a server error. Skipped with `relay: false` |
|
||||
|
||||
+38
-19
@@ -78,8 +78,10 @@ What the site needs for it:
|
||||
443, **without a redirect** — the service follows none. No basic auth, no firewall rule, no maintenance page in
|
||||
front of it. (Coolify: nothing to set; the route is part of Payload's API.)
|
||||
- **Outbound HTTPS** from the server to `webservices.intecion.net`.
|
||||
- A host Intecion has **listed** is active at once. Any other host is enrolled but **waits for approval**: mail is
|
||||
not sent until Intecion approves it, then the same token works. The panel says which it is.
|
||||
- **A site that passes the call-back is active at once.** Waiting for approval is the exception: the service
|
||||
holds a new site back when many new sites appear at once (more than a few a day from one address or domain, or
|
||||
more than its daily number in all), or when Intecion has set it to approve by hand. Mail is then not sent until
|
||||
Intecion approves the site; the same token works afterwards, and the panel says so.
|
||||
|
||||
A site on `localhost`, on a private address or without `serverURL` is refused **by the plugin itself**, before any
|
||||
call leaves the server — development machines do not contact the service. To test mail locally use SMTP (a local
|
||||
@@ -126,7 +128,9 @@ The numbers are the service's, per site, and can be changed by Intecion for one
|
||||
|
||||
A message over a limit is refused whole (`relay-quota`, `relay-too-large`); the site is not suspended for it.
|
||||
`mailAttachmentLimit(payload)` reports the file limit the service named, so a form's File field never promises
|
||||
more ([forms.md](./forms.md) "Files"); until the site has enrolled it is `null` (the plugin has no number of its own).
|
||||
more ([forms.md](./forms.md) "Files"). It answers from what is stored — never by asking the service while a page
|
||||
is read — and is renewed after a send, once an hour; until the site has enrolled and sent once it is `null` (the
|
||||
plugin has no number of its own).
|
||||
|
||||
**Account mail is limited by the site itself.** "Forgot password" is a visitor's lever like a form, and the
|
||||
service lets account mail use the whole hour. So the relay transport holds back more than **5 account e-mails to
|
||||
@@ -194,13 +198,13 @@ await runWithMailKind('account', () => sendWelcomeMails(payload, user))
|
||||
### The token
|
||||
|
||||
- Kept in Payload's key-value store (`payload.kv`, the `payload-kv` collection Payload itself adds; key
|
||||
`RELAY_KV_KEY` = `iapl:mail-relay`). **No field, no column, no migration.** That collection refuses every
|
||||
one entry per host under `RELAY_KV_KEY` = `iapl:mail-relay`). **No field, no column, no migration.** That collection refuses every
|
||||
operation through access control and is hidden in the panel, so the token cannot be read over REST or GraphQL —
|
||||
not by an admin either. It is never logged and never sent to a browser.
|
||||
- **The token belongs to the host it was issued for.** A store found on another host — a production database
|
||||
copied to a staging domain, a site moved to a new domain — is not used: the copy forgets the token (nothing is
|
||||
revoked, the other site keeps working), starts unenrolled and enrols as itself, with its own token, limits and
|
||||
approval. The start log says so once.
|
||||
- **The token belongs to the host it was issued for, and is stored under that host** (key
|
||||
`iapl:mail-relay:site:<host>`). A site reads and writes its own entry only; another host's entry in the same
|
||||
database — production's in a copy, the old domain's after a move, the live site's when a developer's process
|
||||
reads the live database — is neither used nor touched. **A read never deletes or changes anything.**
|
||||
- The token works only from the server addresses the site enrolled from. After a move to another server the
|
||||
service answers "enrol again"; the site does, by the same call-back, and sends. A site whose requests leave from
|
||||
many changing addresses (serverless, a pool of egress addresses) needs its limit of addresses raised by Intecion.
|
||||
@@ -248,16 +252,29 @@ 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
|
||||
### Staging, copies and several hosts
|
||||
|
||||
- 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.
|
||||
- **A site that passes the call-back is active at once** and can send. A staging site on its own domain is its own
|
||||
site to the service: its own enrolment, token and limits.
|
||||
- **A copy of production's database does not connect by itself.** Its data is production's — real customers'
|
||||
addresses in form submissions and accounts — and a copy that enrolled by itself would mail real people as soon
|
||||
as a form or a password reset ran. So a site whose database already holds the connection of **another host** and
|
||||
none of its own stays "not connected": sends report `relay-refused` (cause `client-other-host`), the state block
|
||||
says "The data comes from another site (…), so this site did not connect by itself", the doctor reports it
|
||||
(`mail-relay-state`), and no call leaves the server. An admin who wants the copy to send presses **Connect
|
||||
again**, once; from then on it is a site of its own and heals by itself.
|
||||
- **A site before launch is not affected:** with an empty store it enrols by itself on its first e-mail.
|
||||
- **A copy that must never send:** `iapl({ mail: { relay: false } })` there, or SMTP to a catcher. That is the
|
||||
safe set-up for staging; "not connected" only protects until somebody presses the button.
|
||||
- **`www.` and the bare domain** are one site: either enrols by itself beside the other (each keeps its own entry).
|
||||
- **A moved domain** (the same data under a new host) looks like a copy: after the move press **Connect again**
|
||||
once, or name the old host as the site's own — `mail: { relay: { otherHosts: ['old-domain.example'] } }` — and
|
||||
the site enrols by itself. The same list is for a second domain of one site.
|
||||
- **`otherHosts: 'enrol'`** switches the rule off: a site enrols by itself whatever else the database holds.
|
||||
- Production's connection is never used, changed or revoked by a copy — "Disconnect" on a copy included, and on the
|
||||
same server too. A developer's process on `localhost` reading the live database changes nothing either.
|
||||
- Not covered: a copy that keeps production's `serverURL` is the same site to the plugin (and to the service, if it
|
||||
can be called back at that host).
|
||||
|
||||
### The state block in the panel
|
||||
|
||||
@@ -290,7 +307,7 @@ the service), each with a text in the editor's language:
|
||||
|
||||
| Code | Meaning | What to do |
|
||||
|---|---|---|
|
||||
| `relay-pending` | enrolled, waiting for approval by Intecion | Intecion approves the host; nothing to do on the site |
|
||||
| `relay-pending` | enrolled, but held for approval by Intecion — the exception (many new sites at once, or approval by hand); a site is normally active as soon as it enrols | Intecion approves the host; nothing to do on the site |
|
||||
| `relay-suspended` | stopped by Intecion | contact Intecion; SMTP in the panel sends meanwhile |
|
||||
| `relay-refused` | the site could not enrol; or a token issued by hand stopped working (new server address, token no longer valid) | "When the site cannot be confirmed" below; hand-issued: ask Intecion for the address to be added or for a new token |
|
||||
| `relay-disconnected` | an admin pressed "Disconnect" | "Connect again", or fill in SMTP |
|
||||
@@ -332,6 +349,7 @@ message); "Connect again" asks at once. Other causes: `host-not-allowed` (not a
|
||||
| `relay: false` | — | switches the mail service off: no enrolment, no outbound call, no confirm route, no state block, the panel wording of 1.16 |
|
||||
| `url` | `RELAY_BASE_URL` (`https://webservices.intecion.net/mail`) | another base address — a relay of your own that speaks the same contract |
|
||||
| `host` | host of `serverURL` (`relayHost(payload, options)`) | the public host the service calls back |
|
||||
| `otherHosts` | `'wait'` | a database that holds another host's connection and none of this site's (a copy, a moved domain): `'wait'` = no enrolment until "Connect again"; a list = those hosts are this site's own; `'enrol'` = enrol by itself anyway |
|
||||
| `enrol` | `'auto'` | `'manual'`: only "Connect again" or `enrolRelay()` enrols. `false`: never (the token comes from `token` or `setRelayToken`) |
|
||||
| `accessKeyField` | `false` | `true` shows "Enter an access key" in the state block and lets its route store a hand-issued token an admin pastes |
|
||||
| `token` | — | a token from elsewhere (`string` or a function): the stored token is not used and the site does not enrol |
|
||||
@@ -501,7 +519,8 @@ Works on any `text` field. After wiring it in a project you may need
|
||||
To the mail service (when the owner says so):
|
||||
|
||||
1. Upgrade; check that `serverURL` is the site's public address.
|
||||
2. Intecion lists the host on the service (or approves it after the first send).
|
||||
2. Nothing to arrange with Intecion beforehand: the site is active as soon as it enrols (in the rare case that it
|
||||
is held for approval, the panel says so).
|
||||
3. Remove the four `GRAPH_*` variables in Coolify and redeploy. If "Sending method" says Microsoft Graph, set it
|
||||
to "Automatic".
|
||||
4. Site integrations → E-mail sending → send a test e-mail: the answer says "through IWSN".
|
||||
|
||||
+2
-2
@@ -1004,8 +1004,8 @@ 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** | both sides hold a token to its host: every request names the site (`X-Intecion-Site`) and the service refuses another host's token (`host-mismatch`); and on the site 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 |
|
||||
| **Where the token is** | `payload-kv`, one entry per host (`iapl:mail-relay:site:<host>`). 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** | both sides hold a token to its host: every request names the site (`X-Intecion-Site`) and the service refuses another host's token (`host-mismatch`); and on the site the token is stored under the host it was issued for: a copy on a staging domain neither uses nor touches production's entry (a read never deletes), and **does not enrol by itself** — with production's data it would mail real people — until an admin presses "Connect again" (`mail.relay.otherHosts`) |
|
||||
| **A token of another site** (stored by a script, set as `relay.token`, or pasted into the access-key field — which is off unless the project sets `mail.relay.accessKeyField`) | 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 |
|
||||
|
||||
@@ -102,8 +102,8 @@ through this procedure. Ask only when you are missing something you cannot get y
|
||||
| `relay-refused` / "The mail service could not reach this site at …" (cause `callback-failed`) | `unreachable` / `timeout`: firewall, private network, wrong public host in `serverURL`; `redirect`: `trailingSlash: true`, apex → `www`, a language redirect; `status`: route blocked, missing (`mail: { relay: false }`?) or another `routes.api`; `confirmation`: a proxy rewrites the answer | `curl -i -X POST https://<host>/api/iapl/mail-relay/confirm -d '{}' -H 'content-type: application/json'` must answer **404 with an empty body, no redirect**; fix `serverURL` / `mail.relay.host`, or ask Intecion to set the site's confirm address (path ending in `/confirm/` with trailing slashes); then "Connect again" (the site does not retry by itself for 15 min). email.md "When the site cannot be confirmed" |
|
||||
| `relay-refused`, cause `host-not-allowed` / "This site has no public address yet" | the site runs on `localhost`, a private name, or `serverURL` is empty | expected in development (use SMTP / Mailpit there); in production set `serverURL` |
|
||||
| `relay-refused` on a site whose token was entered by hand ("does not know the server this site now runs on" / "access key … no longer valid") | the site moved or got a second server, or its token expired; a site with a hand-issued token cannot enrol by itself | Intecion adds the server's address, or issues a new token — set it with `setRelayToken(payload, token)` from a script (`pnpm payload run`), or in the panel when the project has `mail.relay.accessKeyField: true` (email.md "The token") |
|
||||
| staging sends nothing after its database was copied from production: "Not connected yet" / "waiting for approval" | expected: production's token is tied to production's host and is not used on the copy; the copy enrolled as itself | Intecion approves the staging host, or staging uses SMTP / `mail: { relay: false }` |
|
||||
| `relay-pending` / "waiting for approval" | the host is not on Intecion's list | Intecion approves it on the service; nothing to change on the site; the same token then works |
|
||||
| a site sends nothing: "The data comes from another site (…), so this site did not connect by itself" / `relay-refused`, cause `client-other-host` | the database holds another host's connection and none of this site's: a staging copy of production, a moved domain, a second domain. Expected — a copy with production's data must not mail real people by itself | should it send: "Connect again" in the state block, once. A moved or second domain: `mail: { relay: { otherHosts: ['old-domain.example'] } }`. A copy that must never send: `mail: { relay: false }` or SMTP to a catcher |
|
||||
| `relay-pending` / "waiting for approval" | the exception: the service holds new sites for approval when many appear at once, or Intecion approves by hand (a site is normally active as soon as it enrols) | Intecion approves it on the service; nothing to change on the site; the same token then works |
|
||||
| `relay-suspended` | Intecion stopped the site (abuse, a flood from a form) | contact Intecion; fill in SMTP meanwhile |
|
||||
| `relay-disconnected` | an admin pressed "Disconnect" | "Connect again", or SMTP |
|
||||
| `relay-quota` | the site's hour or day is used up (30 / 200 by default), more than 10 recipients, more than 10 confirmations to one address a day, too many new addresses, or the site's own limit on account mail (`mail.relay.accountMail`) | the server log names the limit; look for a form being abused (Turnstile on? rate limit?); a site that really sends more: Intecion raises the limits, or SMTP |
|
||||
|
||||
@@ -646,7 +646,7 @@ scaling (5). `●` routes for pages need the database at build time (PROGRAMISTA
|
||||
6. **Notifications**: form messages in every language.
|
||||
7. **Site integrations → E-mail sending**: "Sender name" (the client's name; empty = the site name) and **"Sender
|
||||
address"** (the client's address: with the mail service replies go there). SMTP fields **only** when the client asked
|
||||
for its own server. On the production domain: the block "How e-mails are sent" must say "Connected to IWSN" ("waiting for approval" = ask Intecion to approve the host), then **Send test e-mail** → "through IWSN". Turnstile (for testing site
|
||||
for its own server. On the production domain: the block "How e-mails are sent" must say "Connected to IWSN" (a site is active as soon as it enrols; "waiting for approval" is the exception — ask Intecion; "The data comes from another site" = this database is a copy: press "Connect again" only if the copy should send), then **Send test e-mail** → "through IWSN". Turnstile (for testing site
|
||||
`1x00000000000000000000AA`, secret `1x0000000000000000000000000000000AA`; production keys from the client), analytics/pixel
|
||||
IDs, IndexNow → generate key. Mail/Turnstile errors show up as a dashboard alert.
|
||||
8. **Forms**: check the addresses in the Emails tab of the seeded forms.
|
||||
|
||||
@@ -571,8 +571,11 @@ PROGRAMISTA §6, item 73; email.md; AGENT.md §7.2) — nothing to run; read whi
|
||||
`iapl({ mail: { relay: false } })`.
|
||||
3. **For a site that will use the mail service:** `serverURL` is the public address the site answers on without a
|
||||
redirect; no proxy or WAF rule blocks `/api/iapl/mail-relay/confirm`; `trailingSlash: true` or another `routes.api` →
|
||||
Intecion sets the site's confirm address first; "Sender address" is filled in (replies go there); Intecion has listed
|
||||
the host (otherwise "waiting for approval"); the client's processing agreement names the service.
|
||||
Intecion sets the site's confirm address first; "Sender address" is filled in (replies go there); the client's
|
||||
processing agreement names the service. Nothing to arrange with Intecion: the site is active as soon as it enrols.
|
||||
**A staging copy of the database** does not connect by itself (it would mail production's real addresses): it
|
||||
says so in the panel until an admin presses "Connect again"; keep it silent with `mail: { relay: false }` or SMTP
|
||||
to a catcher. After a domain move: "Connect again" once, or `mail: { relay: { otherHosts: ['old-domain.example'] } }`.
|
||||
4. Code that compared the result of `payload.sendEmail` needs no change for SMTP and Graph. A send through the mail
|
||||
service returns `{ sent, transport: 'relay', … }`; `sent: false` with `confirmed: false` means "may have been sent".
|
||||
5. Your own account mail (invitations): mark it — `withMailKind(message, 'account')`. Form mail and Payload's
|
||||
|
||||
@@ -34,6 +34,7 @@ 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}}`,
|
||||
mailRelayRefusedOtherHost: 'The data comes from another site ({{host}}), so this site did not connect by itself. Press "Connect again" if it should send e-mails.',
|
||||
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}}.',
|
||||
@@ -44,6 +45,7 @@ export const integrationsTexts = defineTexts({
|
||||
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',
|
||||
mailRelayTokenFieldOff: 'An access key cannot be entered in the panel on this site. It is set by the site\'s developer.',
|
||||
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}.`,
|
||||
@@ -152,6 +154,7 @@ 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}}`,
|
||||
mailRelayRefusedOtherHost: 'Dane pochodzą z innej witryny ({{host}}), więc ta witryna nie połączyła się sama. Kliknij „Połącz ponownie”, jeśli ma wysyłać e-maile.',
|
||||
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}}.',
|
||||
@@ -162,6 +165,7 @@ export const integrationsTexts = defineTexts({
|
||||
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',
|
||||
mailRelayTokenFieldOff: 'W tej witrynie klucza dostępu nie wpisuje się w panelu. Ustawia go programista witryny.',
|
||||
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}.`,
|
||||
|
||||
@@ -59,6 +59,12 @@ export const mailRules: DoctorRule[] = [
|
||||
out.push({ fix: 'contact Intecion; meanwhile an SMTP server in the panel sends the site\'s mail', message: 'Intecion has stopped e-mail sending for this site (suspended)', severity: 'error' })
|
||||
} else if (relay.state === 'pending') {
|
||||
out.push({ fix: 'Intecion approves the host on the service (`ims approve <host>`); the same token then works', message: 'the site is enrolled with the Intecion mail service but waits for approval: e-mails are not sent yet', severity: 'warning' })
|
||||
} else if (!relay.connected && relay.refusal === 'client-other-host') {
|
||||
out.push({
|
||||
fix: 'if this site should send e-mails: Site integrations → E-mail sending → "Connect again" (once); a moved domain or a second domain of the same site: mail: { relay: { otherHosts: [\'old-domain.example\'] } }; a staging copy that must not send: mail: { relay: false } or SMTP to a catcher',
|
||||
message: `the database holds the mail-service connection of another site (${relay.reason ?? 'another host'}) and none of this one — a copied database or a new domain: the site does not connect by itself, e-mails are not sent`,
|
||||
severity: 'warning',
|
||||
})
|
||||
} else if (!relay.connected && relay.refusal) {
|
||||
const path = relay.refusal === 'callback-failed' ? ` (${relay.reason ?? 'unknown'}): the service could not confirm the site at its public address` : ''
|
||||
out.push({
|
||||
|
||||
@@ -4,10 +4,9 @@ import type { RelayOptions, ResolvedRelayOptions } from './options.js'
|
||||
|
||||
import { type IntegrationStatus, recordIntegrationStatus } from '../../integrations/status.js'
|
||||
import { getSiteIntegrations } from '../../payload/index.js'
|
||||
import { RELAY_DEFAULTS } from './constants.js'
|
||||
import { resolveRelayOptions } from './options.js'
|
||||
import { type RelaySendResult, sendThroughRelay } from './send.js'
|
||||
import { readSiteStore, refreshRelayStatus } from './session.js'
|
||||
import { readSiteStore } from './session.js'
|
||||
|
||||
/** The address mail leaves from until the service has been asked (`/v1/status` reports the real one). */
|
||||
export const RELAY_SENDER_ADDRESS = '[email protected]'
|
||||
@@ -54,17 +53,14 @@ export async function sendRelayWithPanel(payload: BasePayload, options: Resolved
|
||||
}
|
||||
|
||||
/**
|
||||
* The largest total attachment size the service carries for this site, as it last reported
|
||||
* (`limits.maxAttachmentBytes` of `/v1/status`) — read again when older than an hour. `null` until
|
||||
* the site has enrolled: the plugin has no constant of its own for it.
|
||||
* The largest total attachment size the service carries for this site, **as it last reported**
|
||||
* (`limits.maxAttachmentBytes` of `/v1/status`). Answered from what is stored, whatever its age, and never
|
||||
* by asking the service: this is read while a visitor waits for a page (every read of a form with a File
|
||||
* field). The stored answer is renewed after a send, once an hour. `null` until the site has enrolled and
|
||||
* sent once: the plugin has no constant of its own for it.
|
||||
*/
|
||||
export async function relayAttachmentLimit(payload: BasePayload, options: ResolvedRelayOptions): Promise<null | number> {
|
||||
let stored = await readSiteStore(payload, options)
|
||||
const stale = !stored.service || Date.now() - Date.parse(stored.service.fetchedAt) > RELAY_DEFAULTS.statusTtlMs
|
||||
if (stale && (stored.token || options.token !== undefined) && !stored.disconnected) {
|
||||
stored = (await refreshRelayStatus(payload, options)).stored
|
||||
}
|
||||
const limit = stored.service?.limits?.maxAttachmentBytes
|
||||
const limit = (await readSiteStore(payload, options)).service?.limits?.maxAttachmentBytes
|
||||
return typeof limit === 'number' && limit >= 0 ? limit : null
|
||||
}
|
||||
|
||||
|
||||
@@ -61,8 +61,10 @@ export function relayConfirmEndpoint(options: Pick<RelayOptions, 'confirmRateLim
|
||||
}
|
||||
try {
|
||||
// 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 })
|
||||
const held = await takeNonce(req.payload, nonce)
|
||||
if (!held) {return refuse()}
|
||||
// the token is for the host that started this enrolment: stored beside THAT host's token
|
||||
await writeRelayCandidate(req.payload, { at: new Date().toISOString(), nonceHash: sha256Hex(nonce), state: state as 'active' | 'pending' | 'suspended', token }, held.host)
|
||||
} 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)}`)
|
||||
return notFound()
|
||||
|
||||
@@ -39,6 +39,15 @@ export type RelayOptions = {
|
||||
host?: string
|
||||
/** The kind of a message that carries no mark of its own; return undefined to keep the default (`system`). */
|
||||
kind?: (message: SendEmailOptions) => MailKind | undefined
|
||||
/**
|
||||
* What a site does when its database already holds the connection of ANOTHER host and none of its own —
|
||||
* the sign of a copied database (staging made from production), of a moved domain, or of two sites on one
|
||||
* database. Default `'wait'`: the site does not enrol by itself (a copy with production's data would start
|
||||
* mailing real people); an admin presses "Connect again", once. `'enrol'`: enrol by itself all the same.
|
||||
* A list: these hosts are this site's own (its old domain, its second domain) — beside them it enrols by
|
||||
* itself, beside any other it waits. `www.` and the bare domain are always one site.
|
||||
*/
|
||||
otherHosts?: 'enrol' | 'wait' | string[]
|
||||
/**
|
||||
* The wait before the next attempt when the service names none, in ms, multiplied by the attempt's
|
||||
* number. Default 1000. The ten seconds of waiting in all are not changed by it. Mostly for tests.
|
||||
|
||||
@@ -11,7 +11,7 @@ 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'
|
||||
import { disconnectRelay, enrolRelay, type EnrolResult, getRelayStatus, LOCAL_CODES, otherHostsInTheWay, readSiteStore, type RelayStatus, setRelayToken } from './session.js'
|
||||
|
||||
type Settings = {
|
||||
emailStatus?: IntegrationStatus | null
|
||||
@@ -60,6 +60,11 @@ export async function mailPanelState(req: Pick<PayloadRequest, 'payload'>, own:
|
||||
const code = !status.host ? LOCAL_CODES.noHost : !isPublicHost(status.host) ? 'host-not-allowed' : null
|
||||
if (code) {status = { ...status, refusal: { at: new Date().toISOString(), code } }}
|
||||
}
|
||||
// …and so is a copy of another site's database: it waits for an admin's "Connect again".
|
||||
if (status && options && !status.connected && !status.disconnected && !status.refusal && options.enrol !== false && options.token === undefined) {
|
||||
const foreign = await otherHostsInTheWay(payload, options, await readSiteStore(payload, options))
|
||||
if (foreign.length) {status = { ...status, refusal: { at: new Date().toISOString(), code: LOCAL_CODES.otherHost, reason: foreign[0] } }}
|
||||
}
|
||||
const api = payload.config.routes?.api ?? '/api'
|
||||
return {
|
||||
...(options?.accessKeyField === true ? { accessKeyField: true } : {}),
|
||||
@@ -89,6 +94,8 @@ export function enrolRefusalText(i18n: I18n, refusal: { code: string; message?:
|
||||
return serverText(i18n, 'mailRelayRefusedNoHost')
|
||||
case LOCAL_CODES.noRoute:
|
||||
return serverText(i18n, 'mailRelayRefusedSetup')
|
||||
case LOCAL_CODES.otherHost:
|
||||
return serverText(i18n, 'mailRelayRefusedOtherHost', { host: refusal.reason ?? '' })
|
||||
case 'reverify':
|
||||
return serverText(i18n, 'mailRelayRefusedAddress')
|
||||
case 'site-suspended':
|
||||
@@ -138,7 +145,7 @@ export function relayPanelEndpoints(own?: false | RelayOptions): Endpoint[] {
|
||||
}
|
||||
if (typeof body.token === 'string' && body.token.trim()) {
|
||||
// the field is off unless the project switched it on: a token is then set in code or by a script only
|
||||
if (options.accessKeyField !== true) {return json({ error: serverText(i18n, 'mailRelayForbidden'), ok: false }, 403)}
|
||||
if (options.accessKeyField !== true) {return json({ error: serverText(i18n, 'mailRelayTokenFieldOff'), ok: false }, 403)}
|
||||
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
|
||||
|
||||
@@ -10,8 +10,8 @@ import { RELAY_DEFAULTS, type RelayStatusCode, relayStatusFor } from './constant
|
||||
import { currentMailKind, type MailKind, mailKindOf, takeExpectedMail } from './kinds.js'
|
||||
import { bareAddresses, buildRelayMessage, type RelaySendRequest } from './message.js'
|
||||
import { relayHost } from './options.js'
|
||||
import { LOCAL_CODES, readSiteStore, refreshRelayStatus, rotateRelayToken, type TokenUse, withRelayToken } from './session.js'
|
||||
import { readRelayStore, sha256Hex, updateRelayStore } from './store.js'
|
||||
import { LOCAL_CODES, readSiteStore, refreshRelayStatus, rotateRelayToken, type TokenUse, updateSiteStore, withRelayToken } from './session.js'
|
||||
import { sha256Hex } from './store.js'
|
||||
|
||||
export type RelaySendResult =
|
||||
| {
|
||||
@@ -85,7 +85,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 (([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)}
|
||||
if (([LOCAL_CODES.foreignToken, LOCAL_CODES.noHost, LOCAL_CODES.noRoute, LOCAL_CODES.noToken, LOCAL_CODES.otherHost] 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') {
|
||||
@@ -227,11 +227,11 @@ export async function sendThroughRelay(payload: BasePayload, options: ResolvedRe
|
||||
const used = typeof answer.body.senderName === 'string' ? answer.body.senderName : ''
|
||||
const replaced = warnings.includes('sender-name-replaced')
|
||||
try {
|
||||
const now = await readRelayStore(payload)
|
||||
const now = await readSiteStore(payload, options)
|
||||
const known = now.nameReplaced
|
||||
const nameChanged = replaced ? known?.used !== used || known?.asked !== (request.senderName ?? '') : Boolean(known)
|
||||
if (nameChanged || now.state !== 'active' || now.refusal) {
|
||||
await updateRelayStore(payload, (current) => ({
|
||||
await updateSiteStore(payload, options, (current) => ({
|
||||
...current,
|
||||
nameReplaced: replaced ? { asked: request.senderName ?? '', at: new Date().toISOString(), used } : null,
|
||||
refusal: null,
|
||||
@@ -269,19 +269,20 @@ export async function sendThroughRelay(payload: BasePayload, options: ResolvedRe
|
||||
else {unconfirmed.delete(hash)}
|
||||
if (answer.code === 'site-pending' || answer.code === 'site-suspended') {
|
||||
const state = answer.code === 'site-pending' ? 'pending' : 'suspended'
|
||||
if (stored.state !== state) {await updateRelayStore(payload, (current) => ({ ...current, state })).catch(() => undefined)}
|
||||
if (stored.state !== state) {await updateSiteStore(payload, options, (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)
|
||||
// (written when the code changes, or every ten minutes while it lasts). Not for a refusal of the site's own
|
||||
// making that never reached the service (a local host, a copied database): such a process writes nothing.
|
||||
if (!answer.code.startsWith('client-') && !(answer.code === 'host-not-allowed' && answer.status === 0)) {try {
|
||||
const now = await readSiteStore(payload, options)
|
||||
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 } }))
|
||||
await updateSiteStore(payload, options, (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
|
||||
}
|
||||
|
||||
@@ -7,23 +7,24 @@ import type { ResolvedRelayOptions } from './options.js'
|
||||
import { PLUGIN_VERSION } from '../../../version.js'
|
||||
import { type RelayAnswer, type RelayRefusal, relayRequest } from './client.js'
|
||||
import { RELAY_CONFIRM_PATH, RELAY_DEFAULTS, RELAY_PRODUCT, type RelayStatusCode, relayStatusFor } from './constants.js'
|
||||
import { isPublicHost, relayHost } from './options.js'
|
||||
import {
|
||||
clearRelayStore,
|
||||
dropRelayCandidate,
|
||||
holdNonce,
|
||||
readOwnRelayStore,
|
||||
readRelayCandidate,
|
||||
readRelayStore,
|
||||
type RelaySiteState,
|
||||
type RelayStored,
|
||||
releaseNonce,
|
||||
sha256Hex,
|
||||
updateRelayStore,
|
||||
} from './store.js'
|
||||
import { isPublicHost, pluginMailOptions, relayHost } from './options.js'
|
||||
import * as store from './store.js'
|
||||
import { otherRelayHosts, type RelaySiteState, type RelayStored, releaseNonce, sha256Hex } from './store.js'
|
||||
|
||||
/** The stored entry of this site — never one made on another host (store.ts). */
|
||||
export const readSiteStore = (payload: BasePayload, options: Pick<ResolvedRelayOptions, 'host'>) => readOwnRelayStore(payload, relayHost(payload, options))
|
||||
type HostOptions = Pick<ResolvedRelayOptions, 'host'>
|
||||
|
||||
// The store is keyed by host: everything here reads and writes the entry of THIS site's host
|
||||
// (`relay.host`, else the host of `serverURL`) and never another host's.
|
||||
const readRelayStore = (payload: BasePayload, options: HostOptions) => store.readRelayStore(payload, relayHost(payload, options))
|
||||
const updateRelayStore = (payload: BasePayload, options: HostOptions, change: (current: RelayStored) => RelayStored) => store.updateRelayStore(payload, change, relayHost(payload, options))
|
||||
const clearRelayStore = (payload: BasePayload, options: HostOptions, keep: Pick<RelayStored, 'disconnected'> = {}) => store.clearRelayStore(payload, keep, relayHost(payload, options))
|
||||
const readRelayCandidate = (payload: BasePayload, options: HostOptions) => store.readRelayCandidate(payload, relayHost(payload, options))
|
||||
const dropRelayCandidate = (payload: BasePayload, options: HostOptions) => store.dropRelayCandidate(payload, relayHost(payload, options))
|
||||
|
||||
/** The stored entry of this site — never one made on another host (store.ts). A read changes nothing. */
|
||||
export const readSiteStore = readRelayStore
|
||||
/** Changes the stored entry of this site. */
|
||||
export const updateSiteStore = updateRelayStore
|
||||
|
||||
const sleep = (ms: number) => new Promise<void>((resolve) => setTimeout(resolve, ms))
|
||||
const refusal = (code: string, message: string, extra: Partial<RelayRefusal> = {}): RelayRefusal => ({ code, message, noAnswer: false, ok: false, retryable: false, status: 0, ...extra })
|
||||
@@ -33,6 +34,8 @@ 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',
|
||||
/** The database holds another host's connection and none of this site's: a copy does not enrol by itself. */
|
||||
otherHost: 'client-other-host',
|
||||
/** This config has no confirm route, so the service could not call the site back. */
|
||||
noHost: 'client-no-host',
|
||||
noRoute: 'client-no-route',
|
||||
@@ -51,7 +54,7 @@ const enrolFailure = (answer: RelayRefusal): { ok: false } & EnrolResult => ({
|
||||
retryable: answer.retryable,
|
||||
status:
|
||||
answer.code === LOCAL_CODES.disconnected ? 'relay-disconnected'
|
||||
: ([LOCAL_CODES.foreignToken, LOCAL_CODES.noHost, LOCAL_CODES.noRoute, LOCAL_CODES.noToken] as string[]).includes(answer.code) ? 'relay-refused'
|
||||
: ([LOCAL_CODES.foreignToken, LOCAL_CODES.noHost, LOCAL_CODES.noRoute, LOCAL_CODES.noToken, LOCAL_CODES.otherHost] as string[]).includes(answer.code) ? 'relay-refused'
|
||||
: relayStatusFor(answer.code, answer.retryable),
|
||||
})
|
||||
|
||||
@@ -72,6 +75,16 @@ export function enrolRelay(payload: BasePayload, options: ResolvedRelayOptions,
|
||||
return run
|
||||
}
|
||||
|
||||
/**
|
||||
* Other hosts' connections that keep this site from enrolling by itself: none when the site has (or had) a
|
||||
* connection of its own, when the project said `otherHosts: 'enrol'`, or for hosts it named as its own.
|
||||
*/
|
||||
export async function otherHostsInTheWay(payload: BasePayload, options: Pick<ResolvedRelayOptions, 'host' | 'otherHosts'>, stored: RelayStored): Promise<string[]> {
|
||||
if (stored.token || stored.enrolledAt || options.otherHosts === 'enrol') {return []}
|
||||
const own = Array.isArray(options.otherHosts) ? options.otherHosts.map((h) => h.trim().toLowerCase().replace(/^www\./, '')) : []
|
||||
return (await otherRelayHosts(payload, relayHost(payload, options))).filter((h) => !own.includes(h.replace(/^www\./, '')))
|
||||
}
|
||||
|
||||
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.'))}
|
||||
@@ -92,11 +105,23 @@ async function enrolOnce(payload: BasePayload, options: ResolvedRelayOptions, fo
|
||||
return enrolFailure(refusal('host-not-allowed', `"${host}" is not a public host name, so the mail service cannot call this site back.`))
|
||||
}
|
||||
|
||||
// A copied database: another host's connection is here and this site has never had one. With production's
|
||||
// data a copy would mail real people as soon as it could send, so it does not enrol BY ITSELF — an admin's
|
||||
// "Connect again" (`force`) does, once; from then on the site has its own entry and heals like any other.
|
||||
// A site with an empty store (before launch) is not affected.
|
||||
const foreign = force ? [] : await otherHostsInTheWay(payload, options, stored)
|
||||
if (foreign.length) {
|
||||
const now = Date.now()
|
||||
const message = `This database holds the mail-service connection of another site (${foreign.join(', ')}) and none of "${host}": a copied database, or a new domain. The site does not connect by itself; press "Connect again" in Site integrations → E-mail sending if it should send e-mails (or set mail.relay.otherHosts).`
|
||||
await updateRelayStore(payload, options, (current) => ({ ...current, refusal: { at: new Date(now).toISOString(), code: LOCAL_CODES.otherHost, message, reason: foreign[0], until: new Date(now + RELAY_DEFAULTS.refusalCooldownMs).toISOString() } }))
|
||||
return enrolFailure(refusal(LOCAL_CODES.otherHost, message, { reason: foreign[0] }))
|
||||
}
|
||||
|
||||
let answer: RelayAnswer<{ state?: string }> | undefined
|
||||
let nonce = ''
|
||||
for (let attempt = 0; attempt < 2; attempt++) {
|
||||
nonce = randomBytes(32).toString('base64url')
|
||||
const nonceHash = await holdNonce(payload, nonce, RELAY_DEFAULTS.nonceTtlMs)
|
||||
const nonceHash = await store.holdNonce(payload, nonce, RELAY_DEFAULTS.nonceTtlMs, host)
|
||||
answer = await relayRequest<{ state?: string }>({
|
||||
body: Buffer.from(JSON.stringify({ host, nonce, product: RELAY_PRODUCT, productVersion: PLUGIN_VERSION })),
|
||||
fetchImpl: options.fetchImpl,
|
||||
@@ -106,13 +131,13 @@ async function enrolOnce(payload: BasePayload, options: ResolvedRelayOptions, fo
|
||||
url: options.url,
|
||||
})
|
||||
if (answer.ok) {
|
||||
const candidate = await readRelayCandidate(payload)
|
||||
const candidate = await readRelayCandidate(payload, options)
|
||||
if (!candidate || candidate.nonceHash !== nonceHash) {
|
||||
// The service says yes, but the token did not reach this store (another instance with a store of its own?).
|
||||
return enrolFailure(refusal('callback-failed', 'The mail service confirmed the enrolment, but its token did not reach this site\'s store.', { reason: 'store' }))
|
||||
}
|
||||
const state: RelaySiteState = answer.body.state === 'pending' || answer.body.state === 'suspended' ? answer.body.state : 'active'
|
||||
await updateRelayStore(payload, (current) => ({
|
||||
await updateRelayStore(payload, options, (current) => ({
|
||||
...current,
|
||||
disconnected: false,
|
||||
enrolledAt: new Date().toISOString(),
|
||||
@@ -125,7 +150,7 @@ async function enrolOnce(payload: BasePayload, options: ResolvedRelayOptions, fo
|
||||
state,
|
||||
token: candidate.token,
|
||||
}))
|
||||
await dropRelayCandidate(payload)
|
||||
await dropRelayCandidate(payload, options)
|
||||
return { ok: true, state }
|
||||
}
|
||||
// Used or not, this nonce is over. A token the call-back did deliver stays beside the one in use.
|
||||
@@ -133,15 +158,15 @@ async function enrolOnce(payload: BasePayload, options: ResolvedRelayOptions, fo
|
||||
if (answer.code !== 'enrolment-in-progress' || attempt > 0) {break}
|
||||
// Another process of this site is enrolling: wait, then look whether the token is here by now.
|
||||
await sleep(Math.min((answer.retryAfter ?? 2) * 1000, 5000))
|
||||
const now = await readRelayStore(payload)
|
||||
if ((now.token && now.token !== stored.token) || (await readRelayCandidate(payload))) {return { ok: true, state: now.state ?? 'active' }}
|
||||
const now = await readRelayStore(payload, options)
|
||||
if ((now.token && now.token !== stored.token) || (await readRelayCandidate(payload, options))) {return { ok: true, state: now.state ?? 'active' }}
|
||||
}
|
||||
|
||||
const failed = answer as RelayRefusal
|
||||
if (!failed.retryable) {
|
||||
// Asking again at once would give the same answer (and a call-back that times out costs 8 seconds a time).
|
||||
const now = Date.now()
|
||||
await updateRelayStore(payload, (current) => ({
|
||||
await updateRelayStore(payload, options, (current) => ({
|
||||
...current,
|
||||
refusal: { at: new Date(now).toISOString(), code: failed.code, message: failed.message, ...(failed.reason ? { reason: failed.reason } : {}), until: new Date(now + RELAY_DEFAULTS.refusalCooldownMs).toISOString() },
|
||||
...(failed.code === 'site-suspended' ? { state: 'suspended' as const } : {}),
|
||||
@@ -159,9 +184,9 @@ const HAND_ISSUED = {
|
||||
* A site with a token issued by hand cannot be called back, so "enrol again" is not open to it
|
||||
* (contract §2): it stops, says what to ask Intecion for, and keeps the token.
|
||||
*/
|
||||
async function handIssued(payload: BasePayload, code: keyof typeof HAND_ISSUED): Promise<RelayRefusal> {
|
||||
async function handIssued(payload: BasePayload, options: HostOptions, code: keyof typeof HAND_ISSUED): Promise<RelayRefusal> {
|
||||
const now = new Date().toISOString()
|
||||
await updateRelayStore(payload, (current) => (current.refusal?.code === code ? current : { ...current, refusal: { at: now, code, message: HAND_ISSUED[code], until: now } }))
|
||||
await updateRelayStore(payload, options, (current) => (current.refusal?.code === code ? current : { ...current, refusal: { at: now, code, message: HAND_ISSUED[code], until: now } }))
|
||||
return refusal(code, HAND_ISSUED[code])
|
||||
}
|
||||
|
||||
@@ -216,7 +241,7 @@ export async function withRelayToken<T>(
|
||||
for (let round = 0; round < 4; round++) {
|
||||
const stored = await readSiteStore(payload, options)
|
||||
if (stored.disconnected) {return refusal(LOCAL_CODES.disconnected, 'The site was disconnected from the mail service in the panel.')}
|
||||
const candidate = await readRelayCandidate(payload)
|
||||
const candidate = await readRelayCandidate(payload, options)
|
||||
const token = candidate?.token ?? stored.token
|
||||
|
||||
const enrolNow = async (): Promise<null | RelayRefusal> => {
|
||||
@@ -228,7 +253,7 @@ export async function withRelayToken<T>(
|
||||
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.
|
||||
if (round < 3 && (await readRelayCandidate(payload))) {return null}
|
||||
if (round < 3 && (await readRelayCandidate(payload, options))) {return null}
|
||||
return failed()
|
||||
}
|
||||
|
||||
@@ -243,10 +268,10 @@ export async function withRelayToken<T>(
|
||||
if (!answer.ok && answer.code === 'invalid-token') {
|
||||
if (candidate) {
|
||||
// The service never made this token valid: back to the earlier one.
|
||||
await dropRelayCandidate(payload)
|
||||
await dropRelayCandidate(payload, options)
|
||||
continue
|
||||
}
|
||||
if (stored.manual) {return handIssued(payload, 'invalid-token')}
|
||||
if (stored.manual) {return handIssued(payload, options, 'invalid-token')}
|
||||
const failed = await enrolNow()
|
||||
if (failed) {return use.enrolment && !use.enrolment.ok ? failed : answer}
|
||||
continue
|
||||
@@ -257,8 +282,8 @@ export async function withRelayToken<T>(
|
||||
// revoked — and the site enrols as itself; a site that cannot be called back is told to ask for its own.
|
||||
const message = `The token belongs to another site, not to "${relayHost(payload, options)}": it is not used. Ask Intecion for a token for this site.`
|
||||
const now = new Date().toISOString()
|
||||
await dropRelayCandidate(payload)
|
||||
await updateRelayStore(payload, (current) => ({ ...current, hostChecked: false, manual: false, service: null, source: undefined, state: undefined, token: undefined, ...(stored.manual ? { refusal: { at: now, code: LOCAL_CODES.foreignToken, message, until: now } } : {}) }))
|
||||
await dropRelayCandidate(payload, options)
|
||||
await updateRelayStore(payload, options, (current) => ({ ...current, hostChecked: false, manual: false, service: null, source: undefined, state: undefined, token: undefined, ...(stored.manual ? { refusal: { at: now, code: LOCAL_CODES.foreignToken, message, until: now } } : {}) }))
|
||||
if (stored.manual) {return refusal(LOCAL_CODES.foreignToken, message)}
|
||||
const failed = await enrolNow()
|
||||
if (failed) {return use.enrolment && !use.enrolment.ok ? failed : answer}
|
||||
@@ -267,11 +292,11 @@ export async function withRelayToken<T>(
|
||||
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, hostChecked: true, manual: false, source: 'enrolment', state: candidate.state, token: candidate.token }))
|
||||
await dropRelayCandidate(payload)
|
||||
await updateRelayStore(payload, options, (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, options)
|
||||
}
|
||||
if (!answer.ok && answer.code === 'reverify') {
|
||||
if (stored.manual) {return handIssued(payload, 'reverify')}
|
||||
if (stored.manual) {return handIssued(payload, options, 'reverify')}
|
||||
const failed = await enrolNow()
|
||||
if (failed) {return use.enrolment && !use.enrolment.ok ? failed : answer}
|
||||
continue
|
||||
@@ -313,11 +338,11 @@ export async function refreshRelayStatus(payload: BasePayload, options: Resolved
|
||||
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 }))
|
||||
await dropRelayCandidate(payload, options)
|
||||
const stored = await updateRelayStore(payload, options, (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) => ({
|
||||
const stored = await updateRelayStore(payload, options, (current) => ({
|
||||
...current,
|
||||
hostChecked: true,
|
||||
service: {
|
||||
@@ -349,7 +374,7 @@ export async function rotateRelayToken(payload: BasePayload, options: ResolvedRe
|
||||
const answer = await relayRequest<{ token?: string }>({ fetchImpl: options.fetchImpl, method: 'POST', path: '/v1/rotate', site: relayHost(payload, options), 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) => ({
|
||||
await updateRelayStore(payload, options, (current) => ({
|
||||
...current,
|
||||
enrolledAt: new Date().toISOString(),
|
||||
service: current.service ? { ...current.service, rotateAfter: undefined } : current.service,
|
||||
@@ -359,13 +384,13 @@ export async function rotateRelayToken(payload: BasePayload, options: ResolvedRe
|
||||
return 'rotated'
|
||||
}
|
||||
if (!answer.ok && answer.code === 'already-rotated') {
|
||||
const now = await readRelayStore(payload)
|
||||
const now = await readRelayStore(payload, options)
|
||||
// No newer token here: this one is on its way out. Forget it, so the next send enrols at once.
|
||||
if (now.token === used) {await updateRelayStore(payload, (current) => ({ ...current, service: null, token: undefined }))}
|
||||
if (now.token === used) {await updateRelayStore(payload, options, (current) => ({ ...current, service: null, token: undefined }))}
|
||||
return 'failed'
|
||||
}
|
||||
// Asked once; not again before the status has been read anew.
|
||||
await updateRelayStore(payload, (current) => ({ ...current, service: current.service ? { ...current.service, rotateAfter: undefined } : current.service }))
|
||||
await updateRelayStore(payload, options, (current) => ({ ...current, service: current.service ? { ...current.service, rotateAfter: undefined } : current.service }))
|
||||
return 'failed'
|
||||
}
|
||||
|
||||
@@ -383,11 +408,11 @@ export async function disconnectRelay(payload: BasePayload, options: ResolvedRel
|
||||
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 }))
|
||||
await updateRelayStore(payload, options, (current) => ({ ...current, disconnected: true, revokePending: true }))
|
||||
return { revoked: false }
|
||||
}
|
||||
}
|
||||
await clearRelayStore(payload, { disconnected: true })
|
||||
await clearRelayStore(payload, options, { disconnected: true })
|
||||
return { revoked: true }
|
||||
}
|
||||
|
||||
@@ -397,12 +422,14 @@ export async function disconnectRelay(payload: BasePayload, options: ResolvedRel
|
||||
*/
|
||||
export async function setRelayToken(payload: BasePayload, token: string, options: { host?: string } = {}): Promise<void> {
|
||||
if (!/^ims_[\w-]{43}$/.test(token)) {throw new Error('Not a token of the mail service (ims_ and 43 characters).')}
|
||||
await dropRelayCandidate(payload)
|
||||
await updateRelayStore(payload, (current) => ({
|
||||
// the entry is this site's own: `options.host`, else `mail.relay.host`, else the host of serverURL
|
||||
options = { host: options.host ?? (pluginMailOptions(payload).relay || {}).host }
|
||||
await dropRelayCandidate(payload, options)
|
||||
await updateRelayStore(payload, options, (current) => ({
|
||||
...current,
|
||||
disconnected: false,
|
||||
enrolledAt: new Date().toISOString(),
|
||||
...(options.host ? { host: options.host } : {}),
|
||||
host: relayHost(payload, options) || undefined,
|
||||
hostChecked: false,
|
||||
manual: true,
|
||||
refusal: null,
|
||||
|
||||
@@ -3,6 +3,7 @@ import type { BasePayload } from 'payload'
|
||||
import { createHash, timingSafeEqual } from 'node:crypto'
|
||||
|
||||
import { RELAY_KV_KEY } from './constants.js'
|
||||
import { pluginMailOptions, relayHost } from './options.js'
|
||||
|
||||
/**
|
||||
* Where the site keeps its token: Payload's key-value store (`payload.kv`, the `payload-kv` collection
|
||||
@@ -10,10 +11,11 @@ import { RELAY_KV_KEY } from './constants.js'
|
||||
* operation through access control and is hidden in the panel, so the token cannot be read over REST
|
||||
* or GraphQL (test/mailRelayHttp.test.ts proves it). The token is never logged and never sent to a browser.
|
||||
*
|
||||
* Three entries:
|
||||
* - `iapl:mail-relay` the token in use, the site's state, what the service last reported;
|
||||
* - `iapl:mail-relay:candidate` a token the service delivered that has not been seen accepted yet;
|
||||
* - `iapl:mail-relay:nonce:<hash>` an enrolment this site started (5 minutes, single use).
|
||||
* Three entries, the first two per host (the host is part of the key, so a database shared or copied
|
||||
* between hosts never hands one site another's token, and nothing has to be deleted to keep them apart):
|
||||
* - `iapl:mail-relay:site:<host>` the token in use, the site's state, what the service last reported;
|
||||
* - `iapl:mail-relay:candidate:<host>` a token the service delivered that has not been seen accepted yet;
|
||||
* - `iapl:mail-relay:nonce:<hash>` an enrolment a site started (5 minutes, single use), with its host.
|
||||
* The confirm route writes only the candidate and deletes only its nonce, so it can never overwrite a
|
||||
* working token.
|
||||
*/
|
||||
@@ -36,7 +38,7 @@ export type RelayStored = {
|
||||
*/
|
||||
disconnected?: boolean
|
||||
enrolledAt?: string
|
||||
/** The host the token was issued for. A store found on another host is not this site's (readOwnRelayStore). */
|
||||
/** The host the token was issued for (also in the entry's key). */
|
||||
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
|
||||
@@ -69,7 +71,7 @@ export type RelayStored = {
|
||||
|
||||
export type RelayCandidate = { at: string; nonceHash: string; state: RelaySiteState; token: string }
|
||||
|
||||
type KV = { delete: (key: string) => Promise<void>; get: (key: string) => Promise<unknown>; set: (key: string, value: object) => Promise<void> }
|
||||
type KV = { delete: (key: string) => Promise<void>; get: (key: string) => Promise<unknown>; keys?: () => Promise<string[]>; set: (key: string, value: object) => Promise<void> }
|
||||
|
||||
/** Without `payload.kv` (a Payload older than the store, or a test double): this process only. */
|
||||
const memory = new WeakMap<object, Map<string, unknown>>()
|
||||
@@ -91,87 +93,98 @@ function kvOf(payload: BasePayload): KV {
|
||||
return {
|
||||
delete: (key) => Promise.resolve(void held.delete(key)),
|
||||
get: (key) => Promise.resolve(held.get(key) ?? null),
|
||||
keys: () => Promise.resolve([...held.keys()]),
|
||||
set: (key, value) => Promise.resolve(void held.set(key, structuredClone(value))),
|
||||
}
|
||||
}
|
||||
|
||||
export const sha256Hex = (text: string) => createHash('sha256').update(text, 'utf8').digest('hex')
|
||||
|
||||
const CANDIDATE_KEY = `${RELAY_KV_KEY}:candidate`
|
||||
/** The site's own public host when a caller names none: `mail.relay.host`, else the host of `serverURL`. */
|
||||
const ownHost = (payload: BasePayload): string => relayHost(payload, pluginMailOptions(payload).relay || {})
|
||||
|
||||
const SITE_PREFIX = `${RELAY_KV_KEY}:site:`
|
||||
/** Every entry carries the host it belongs to in its KEY: a site reads and writes its own, and only its own. */
|
||||
const siteKey = (host: string) => `${SITE_PREFIX}${host || '_'}`
|
||||
const candidateKey = (host: string) => `${RELAY_KV_KEY}:candidate:${host || '_'}`
|
||||
const nonceKey = (nonceHash: string) => `${RELAY_KV_KEY}:nonce:${nonceHash}`
|
||||
|
||||
export async function readRelayStore(payload: BasePayload): Promise<RelayStored> {
|
||||
const value = (await kvOf(payload).get(RELAY_KV_KEY)) as null | RelayStored
|
||||
/**
|
||||
* The entry of the site at `host` (default: this site's own host). **A read never changes anything.**
|
||||
* What another host stored in the same database — production's entry in a copy on a staging domain, the
|
||||
* old domain's after a move, a developer's process on `localhost` reading the live database — is simply
|
||||
* not this site's: it is neither used nor touched.
|
||||
*/
|
||||
export async function readRelayStore(payload: BasePayload, host: string = ownHost(payload)): Promise<RelayStored> {
|
||||
const value = (await kvOf(payload).get(siteKey(host))) as null | RelayStored
|
||||
return value && typeof value === 'object' ? { ...value, v: 1 } : { v: 1 }
|
||||
}
|
||||
|
||||
let warnedForeign = false
|
||||
|
||||
/**
|
||||
* The entry of THIS site. A token belongs to the host it was issued for: when the store was made on
|
||||
* another host — a production database copied to a staging domain, a site moved to a new domain — the
|
||||
* token, the candidate and everything known about the service are forgotten here (nothing is revoked:
|
||||
* the other site keeps working), and this site starts unenrolled and enrols as itself.
|
||||
* An entry without a host (a token stored by a script) gets this site's host on first use.
|
||||
*/
|
||||
export async function readOwnRelayStore(payload: BasePayload, host: string): Promise<RelayStored> {
|
||||
const stored = await readRelayStore(payload)
|
||||
if (!host) {return stored}
|
||||
if (stored.host && stored.host !== host) {
|
||||
if (!warnedForeign) {
|
||||
warnedForeign = true
|
||||
payload.logger?.warn?.(`[iapl] mail service: the stored connection belongs to "${stored.host}", this site is "${host}" (a copied database, or a new domain). It is not used here; the site enrols as itself.`)
|
||||
}
|
||||
const kv = kvOf(payload)
|
||||
await kv.delete(CANDIDATE_KEY)
|
||||
await kv.delete(RELAY_KV_KEY)
|
||||
return { v: 1 }
|
||||
}
|
||||
if (stored.token && !stored.host) {return updateRelayStore(payload, (current) => ({ ...current, host }))}
|
||||
return stored
|
||||
}
|
||||
|
||||
/** Reads the entry again, applies `change` and writes it: the smallest window for two writers. */
|
||||
export async function updateRelayStore(payload: BasePayload, change: (current: RelayStored) => RelayStored): Promise<RelayStored> {
|
||||
const next = change(await readRelayStore(payload))
|
||||
await kvOf(payload).set(RELAY_KV_KEY, next)
|
||||
export async function updateRelayStore(payload: BasePayload, change: (current: RelayStored) => RelayStored, host: string = ownHost(payload)): Promise<RelayStored> {
|
||||
const next = change(await readRelayStore(payload, host))
|
||||
await kvOf(payload).set(siteKey(host), next)
|
||||
return next
|
||||
}
|
||||
|
||||
/** Forgets the token and everything known about the service (keeps nothing). */
|
||||
export async function clearRelayStore(payload: BasePayload, keep: Pick<RelayStored, 'disconnected'> = {}): Promise<void> {
|
||||
/** Forgets this host's token and everything known about the service. Other hosts' entries are not touched. */
|
||||
export async function clearRelayStore(payload: BasePayload, keep: Pick<RelayStored, 'disconnected'> = {}, host: string = ownHost(payload)): Promise<void> {
|
||||
const kv = kvOf(payload)
|
||||
await kv.delete(CANDIDATE_KEY)
|
||||
if (keep.disconnected) {await kv.set(RELAY_KV_KEY, { disconnected: true, v: 1 } satisfies RelayStored)}
|
||||
else {await kv.delete(RELAY_KV_KEY)}
|
||||
await kv.delete(candidateKey(host))
|
||||
if (keep.disconnected) {await kv.set(siteKey(host), { disconnected: true, v: 1 } satisfies RelayStored)}
|
||||
else {await kv.delete(siteKey(host))}
|
||||
}
|
||||
|
||||
export async function readRelayCandidate(payload: BasePayload): Promise<null | RelayCandidate> {
|
||||
const value = (await kvOf(payload).get(CANDIDATE_KEY)) as null | RelayCandidate
|
||||
const sameSite = (a: string, b: string) => a.replace(/^www\./, '') === b.replace(/^www\./, '')
|
||||
|
||||
/**
|
||||
* Hosts OTHER than `host` that have (or had) a connection of their own in this database — the sign of a
|
||||
* copied database, a moved domain, or two sites on one database. `www.` and the bare domain are one site.
|
||||
* Reads only. Empty when the store cannot list its keys.
|
||||
*/
|
||||
export async function otherRelayHosts(payload: BasePayload, host: string = ownHost(payload)): Promise<string[]> {
|
||||
const kv = kvOf(payload)
|
||||
if (typeof kv.keys !== 'function') {return []}
|
||||
const out: string[] = []
|
||||
for (const key of await kv.keys()) {
|
||||
if (!key.startsWith(SITE_PREFIX)) {continue}
|
||||
const other = key.slice(SITE_PREFIX.length)
|
||||
if (other === '_' || other === host || sameSite(other, host)) {continue}
|
||||
const entry = (await kv.get(key)) as null | RelayStored
|
||||
if (entry?.token || entry?.enrolledAt) {out.push(other)}
|
||||
}
|
||||
return out.sort()
|
||||
}
|
||||
|
||||
export async function readRelayCandidate(payload: BasePayload, host: string = ownHost(payload)): Promise<null | RelayCandidate> {
|
||||
const value = (await kvOf(payload).get(candidateKey(host))) as null | RelayCandidate
|
||||
return value && typeof value.token === 'string' ? value : null
|
||||
}
|
||||
|
||||
export const writeRelayCandidate = (payload: BasePayload, candidate: RelayCandidate) => kvOf(payload).set(CANDIDATE_KEY, candidate)
|
||||
export const dropRelayCandidate = (payload: BasePayload) => kvOf(payload).delete(CANDIDATE_KEY)
|
||||
export const writeRelayCandidate = (payload: BasePayload, candidate: RelayCandidate, host: string = ownHost(payload)) => kvOf(payload).set(candidateKey(host), candidate)
|
||||
export const dropRelayCandidate = (payload: BasePayload, host: string = ownHost(payload)) => kvOf(payload).delete(candidateKey(host))
|
||||
|
||||
/** Remembers that this site started an enrolment with `nonce`. Only its hash is stored. */
|
||||
export async function holdNonce(payload: BasePayload, nonce: string, ttlMs: number): Promise<string> {
|
||||
/** Remembers that the site at `host` started an enrolment with `nonce`. Only the nonce's hash is stored. */
|
||||
export async function holdNonce(payload: BasePayload, nonce: string, ttlMs: number, host: string = ownHost(payload)): Promise<string> {
|
||||
const nonceHash = sha256Hex(nonce)
|
||||
await kvOf(payload).set(nonceKey(nonceHash), { expiresAt: Date.now() + ttlMs, hash: nonceHash })
|
||||
await kvOf(payload).set(nonceKey(nonceHash), { expiresAt: Date.now() + ttlMs, hash: nonceHash, host })
|
||||
return nonceHash
|
||||
}
|
||||
|
||||
/** True when this site holds `nonce` and it has not expired. Single use: the entry is gone afterwards. */
|
||||
export async function takeNonce(payload: BasePayload, nonce: string): Promise<boolean> {
|
||||
/**
|
||||
* When this database holds `nonce` and it has not expired: the host that started that enrolment (the token
|
||||
* the service delivers belongs to it); otherwise `null`. Single use: the entry is gone afterwards.
|
||||
*/
|
||||
export async function takeNonce(payload: BasePayload, nonce: string): Promise<{ host: string } | null> {
|
||||
const kv = kvOf(payload)
|
||||
const nonceHash = sha256Hex(nonce)
|
||||
const key = nonceKey(nonceHash)
|
||||
// Found by the hash of the nonce (a look-up tells nothing about the nonce itself), then compared in constant time.
|
||||
const held = (await kv.get(key)) as { expiresAt?: number; hash?: string } | null
|
||||
if (!held || typeof held.hash !== 'string' || held.hash.length !== nonceHash.length) {return false}
|
||||
if (!timingSafeEqual(Buffer.from(held.hash), Buffer.from(nonceHash))) {return false}
|
||||
const held = (await kv.get(key)) as { expiresAt?: number; hash?: string; host?: string } | null
|
||||
if (!held || typeof held.hash !== 'string' || held.hash.length !== nonceHash.length) {return null}
|
||||
if (!timingSafeEqual(Buffer.from(held.hash), Buffer.from(nonceHash))) {return null}
|
||||
await kv.delete(key)
|
||||
return typeof held.expiresAt === 'number' && held.expiresAt > Date.now()
|
||||
return typeof held.expiresAt === 'number' && held.expiresAt > Date.now() ? { host: typeof held.host === 'string' ? held.host : ownHost(payload) } : null
|
||||
}
|
||||
|
||||
export const releaseNonce = (payload: BasePayload, nonce: string) => kvOf(payload).delete(nonceKey(sha256Hex(nonce)))
|
||||
|
||||
@@ -19,7 +19,8 @@ export const FORM_FILES_CONTEXT = 'ipalFormFiles'
|
||||
export type FormFileDelivery = {
|
||||
files: AcceptedFormFile[]
|
||||
/** Set by the delivery hook; absent = no e-mail was attempted. */
|
||||
result?: { note?: string; state: 'failed' | 'sent' }
|
||||
/** `unconfirmed`: the transport gave no answer — the file may be out (stored as "not sent", with the note). */
|
||||
result?: { note?: string; state: 'failed' | 'sent'; unconfirmed?: boolean }
|
||||
}
|
||||
|
||||
type EmailRow = { bcc?: null | string; cc?: null | string; emailTo?: null | string }
|
||||
@@ -141,13 +142,13 @@ export function buildFormMailKindHook({ formsSlug = 'forms' }: { formsSlug?: str
|
||||
}
|
||||
}
|
||||
|
||||
type SendOutcome = { detail?: string; ok: boolean }
|
||||
type SendOutcome = { detail?: string; ok: boolean; unconfirmed?: boolean }
|
||||
|
||||
/** One send through the project's adapter. mailAdapter reports failure as `{ sent: false }`; others throw. */
|
||||
async function send(payload: BasePayload, message: { attachments?: unknown } & FormattedEmail): Promise<SendOutcome> {
|
||||
try {
|
||||
const result = (await payload.sendEmail(message as never)) as { detail?: string; error?: string; sent?: boolean } | null | undefined
|
||||
if (result && typeof result === 'object' && result.sent === false) {return { detail: result.detail ?? result.error, ok: false }}
|
||||
const result = (await payload.sendEmail(message as never)) as { confirmed?: boolean; detail?: string; error?: string; sent?: boolean } | null | undefined
|
||||
if (result && typeof result === 'object' && result.sent === false) {return { detail: result.detail ?? result.error, ok: false, ...(result.confirmed === false ? { unconfirmed: true } : {}) }}
|
||||
return { ok: true }
|
||||
} catch (err) {
|
||||
return { detail: err instanceof Error ? err.message : String(err), ok: false }
|
||||
@@ -196,6 +197,13 @@ export function buildFileDeliveryHook({ formsSlug = 'forms' }: { formsSlug?: str
|
||||
return emails.filter((email) => !carriers.includes(email))
|
||||
}
|
||||
|
||||
// No answer from the mail service for any copy: the file may be out. Nothing more is sent now (the service is
|
||||
// not answering, and a "could not be sent" notice would be wrong); the visitor is not asked to send again.
|
||||
if (outcomes.every((o) => o.unconfirmed)) {
|
||||
delivery.result = { note: 'Not confirmed: the mail service gave no answer, so the file may or may not have been delivered.', state: 'failed', unconfirmed: true }
|
||||
payload.logger.error(`[iapl] Form file not confirmed (${fileList(delivery.files)}): the mail service gave no answer`)
|
||||
return []
|
||||
}
|
||||
const detail = firstLine(outcomes.find((o) => o.detail)?.detail)
|
||||
delivery.result = { note: detail ? `The mail server did not take the message: ${detail}` : 'The mail server did not take the message.', state: 'failed' }
|
||||
payload.logger.error(`[iapl] Form file not delivered (${fileList(delivery.files)}): ${detail || 'send failed'}`)
|
||||
|
||||
@@ -98,6 +98,8 @@ export type SubmitFailure =
|
||||
reason: 'delivery'
|
||||
submissionId?: number | string
|
||||
success: false
|
||||
/** The mail transport gave no answer: the file may have been delivered; the submission is stored. */
|
||||
unconfirmed?: boolean
|
||||
}
|
||||
| {
|
||||
/** The offending field's name, when one field is at fault. */
|
||||
@@ -353,6 +355,7 @@ export async function storeSubmission({
|
||||
reason: 'delivery',
|
||||
submissionId: submission.id,
|
||||
success: false,
|
||||
...(result.unconfirmed ? { unconfirmed: true } : {}),
|
||||
...(fileField && !fileField.required ? { optional: true } : {}),
|
||||
}
|
||||
} catch (err) {
|
||||
|
||||
@@ -13,6 +13,7 @@ export const NOTIFICATION_FALLBACK: NotificationTexts = {
|
||||
consent: 'Accept the privacy policy to send the form.',
|
||||
error: 'The form could not be sent. Please try again in a moment.',
|
||||
fileCount: 'Too many files in "{field}". Remove some: the limit is {max}.',
|
||||
fileNotConfirmed: 'We have your message, but we could not confirm that the file "{file}" was delivered. Please do not send it again: we will ask you for it if needed.',
|
||||
fileNotSent: 'We could not send the file "{file}". Choose a smaller file or another format and try again.',
|
||||
fileOptional: 'You can also send the form without the file.',
|
||||
fileRefused: 'The file "{file}" was refused: it is a program or an archive, it holds macros, or its content does not match its type. Choose another file ({types}).',
|
||||
@@ -37,6 +38,7 @@ export const NOTIFICATION_FALLBACK_PL: NotificationTexts = {
|
||||
consent: 'Zaakceptuj politykę prywatności, aby wysłać formularz.',
|
||||
error: 'Nie udało się wysłać formularza. Spróbuj ponownie za chwilę.',
|
||||
fileCount: 'Za dużo plików w polu „{field}”. Usuń część: limit to {max}.',
|
||||
fileNotConfirmed: 'Mamy Twoją wiadomość, ale nie udało się potwierdzić dostarczenia pliku „{file}”. Nie wysyłaj go ponownie: w razie potrzeby poprosimy o niego.',
|
||||
fileNotSent: 'Nie udało się wysłać pliku „{file}”. Wybierz mniejszy plik lub inny format i spróbuj ponownie.',
|
||||
fileOptional: 'Możesz też wysłać formularz bez pliku.',
|
||||
fileRefused: 'Plik „{file}” został odrzucony: to program lub archiwum, zawiera makra albo jego zawartość nie odpowiada typowi. Wybierz inny plik ({types}).',
|
||||
|
||||
@@ -33,6 +33,7 @@ export async function getNotificationTexts({
|
||||
consent: f.consent || fb.consent,
|
||||
error: f.error || fb.error,
|
||||
fileCount: f.fileCount || fb.fileCount,
|
||||
fileNotConfirmed: fb.fileNotConfirmed,
|
||||
fileNotSent: f.fileNotSent || fb.fileNotSent,
|
||||
fileOptional: f.fileOptional || fb.fileOptional,
|
||||
fileRefused: f.fileRefused || fb.fileRefused,
|
||||
|
||||
@@ -5,7 +5,7 @@ import type { FormNotificationTexts } from './types.js'
|
||||
* The texts resolveFormMessage needs. The File-field texts are optional, so an
|
||||
* object written before they existed still fits (the field or general text is used).
|
||||
*/
|
||||
type FileTextKey = 'fileCount' | 'fileNotSent' | 'fileOptional' | 'fileRefused' | 'fileRemove' | 'fileTooLarge' | 'fileType'
|
||||
type FileTextKey = 'fileCount' | 'fileNotConfirmed' | 'fileNotSent' | 'fileOptional' | 'fileRefused' | 'fileRemove' | 'fileTooLarge' | 'fileType'
|
||||
export type FormMessageTexts = { [K in FileTextKey]?: string } & Omit<FormNotificationTexts, FileTextKey>
|
||||
|
||||
/** The texts of the File field problems, by result code. */
|
||||
@@ -34,6 +34,8 @@ export function resolveFormMessage(result: SubmitFormResult, texts: FormMessageT
|
||||
case 'consent':
|
||||
return texts.consent
|
||||
case 'delivery': {
|
||||
// The mail service did not answer: the file may be out, and the submission is stored — never "try again".
|
||||
if (result.unconfirmed && texts.fileNotConfirmed) {return texts.fileNotConfirmed.replace('{file}', result.file ?? '')}
|
||||
// The file could not be e-mailed: say it is the file (at its field), never the mail server's own words.
|
||||
if (!texts.fileNotSent) {return texts.error}
|
||||
return withoutFile(texts.fileNotSent.replace('{file}', result.file ?? ''), result.optional, texts)
|
||||
|
||||
@@ -12,6 +12,12 @@ export type FormNotificationTexts = {
|
||||
error: string
|
||||
/** File field: too many files, with {field} and {max}. */
|
||||
fileCount: string
|
||||
/**
|
||||
* File field: the mail service gave no answer, so the file may or may not have been delivered — the
|
||||
* submission itself is stored. Must not ask the visitor to send again. Not a panel field (no schema
|
||||
* change): the plugin's text per language; a project overrides it in the texts it passes on.
|
||||
*/
|
||||
fileNotConfirmed: string
|
||||
/** File field: the e-mail with the file could not be sent — with {file}; the visitor has to send it again. */
|
||||
fileNotSent: string
|
||||
/** File field: added to a file message when the field is not required ("…send the form without the file"). */
|
||||
|
||||
@@ -686,6 +686,11 @@ describe('e-mail: transport, the mail service, Graph, the confirm route', () =>
|
||||
expect(await run(mail({ relay: relay({ state: 'pending' }) }))).toEqual(['mail-relay-state:warning'])
|
||||
expect(await run(mail({ relay: relay({ connected: false, reason: 'redirect', refusal: 'callback-failed', state: undefined }) }))).toEqual(['mail-relay-state:warning'])
|
||||
expect(await run(mail({ relay: relay({ connected: false, state: undefined }) }))).toEqual(['mail-relay-state:info'])
|
||||
// a copy of another site's database: it does not connect by itself, and the finding says what to do
|
||||
const copy = await doctor(project({ ...base(), 'src/payload.config.ts': 'iapl({ forms: {} })' }), ids, { deepStatus: { mail: mail({ relay: relay({ connected: false, reason: 'client.pl', refusal: 'client-other-host', state: undefined }) }) } })
|
||||
expect(rules(copy)).toEqual(['mail-relay-state:warning'])
|
||||
expect(copy.findings[0].message).toContain('client.pl')
|
||||
expect(copy.findings[0].fix).toContain('otherHosts')
|
||||
expect(await run(mail({ relay: relay({ nameReplaced: true }) }))).toEqual(['mail-relay-state:warning'])
|
||||
})
|
||||
|
||||
|
||||
+158
-35
@@ -12,7 +12,7 @@ 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 { relayAdapter, relayAttachmentLimit } from '../src/modules/email/relay/adapter.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'
|
||||
@@ -22,6 +22,8 @@ import { mailPanelState } from '../src/modules/email/relay/panel.js'
|
||||
import { clearUnconfirmedRelayMessages, sendThroughRelay } from '../src/modules/email/relay/send.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 { NOTIFICATION_FALLBACK, NOTIFICATION_FALLBACK_PL } from '../src/modules/notifications/defaults.js'
|
||||
import { resolveFormMessage } from '../src/modules/notifications/resolveFormMessage.js'
|
||||
import { setRateLimitStore } from '../src/modules/shared/rateLimit.js'
|
||||
import { callConfirmRoute, relayPayload, relaySite } from './mailRelay/helpers.js'
|
||||
|
||||
@@ -652,41 +654,162 @@ describe('the token over time', () => {
|
||||
expect((await readRelayStore(payload)).manual).toBe(true)
|
||||
})
|
||||
|
||||
test('a database copied to another host does not use the first site\'s token: the copy starts unenrolled and enrols as itself', async () => {
|
||||
// one service, two sites: it calls each back at its own host
|
||||
const staging = relayPayload({ serverURL: 'https://staging.example.com' })
|
||||
const sites: Record<string, ReturnType<typeof callConfirmRoute>> = {}
|
||||
const production = relaySite({
|
||||
fake: { allow: [HOST, 'staging.example.com'], callSite: (url, init) => sites[new URL(url).host](url, init) },
|
||||
integrations: { smtpFromName: 'Example' },
|
||||
})
|
||||
sites[HOST] = callConfirmRoute(production.payload)
|
||||
sites['staging.example.com'] = callConfirmRoute(staging.payload)
|
||||
await sendThroughRelay(production.payload, production.options, MESSAGE)
|
||||
const token = (await readRelayStore(production.payload)).token!
|
||||
// the copy: the same key-value entries, another serverURL
|
||||
for (const [key, value] of production.store) {staging.store.set(key, structuredClone(value))}
|
||||
const options = resolveRelayOptions(staging.payload, { fetchImpl: production.fake.fetch, url: production.fake.url })!
|
||||
expect((await readRelayStore(staging.payload)).token).toBe(token) // it is there …
|
||||
const seen: string[] = []
|
||||
production.fake.intercept = (request) => void seen.push(request.headers.get('authorization') ?? '')
|
||||
describe('one database, several hosts (review round 2, Q-1; the store is keyed by host)', () => {
|
||||
/** One service and any number of sites on ONE key-value store; the service calls each back at its own host. */
|
||||
const shared = (fakeOptions: Parameters<typeof relaySite>[0] = {}) => {
|
||||
const sites: Record<string, ReturnType<typeof callConfirmRoute>> = {}
|
||||
const first = relaySite({ ...fakeOptions, fake: { allow: ['*'], callSite: (url, init) => sites[new URL(url).host](url, init), ...fakeOptions.fake } })
|
||||
sites[new URL(fakeOptions.serverURL ?? `https://${HOST}`).host] = callConfirmRoute(first.payload)
|
||||
const another = (serverURL: string, own: Parameters<typeof resolveRelayOptions>[1] = {}) => {
|
||||
const site = relayPayload({ serverURL })
|
||||
;(site.payload as unknown as { kv: unknown }).kv = (first.payload as unknown as { kv: unknown }).kv
|
||||
sites[new URL(serverURL).host] = callConfirmRoute(site.payload)
|
||||
return { ...site, options: resolveRelayOptions(site.payload, { fetchImpl: first.fake.fetch, retryBackoffMs: 1, url: first.fake.url, ...(own || {}) })! }
|
||||
}
|
||||
return { ...first, another }
|
||||
}
|
||||
const everything = (store: Map<string, unknown>) => JSON.stringify([...store.entries()].sort())
|
||||
|
||||
// … and is not shown as this site's, not used, and not revoked
|
||||
expect(await mailPanelState({ payload: staging.payload }, options)).toMatchObject({ relay: { connected: false, host: 'staging.example.com' } })
|
||||
expect((await readRelayStore(staging.payload)).token).toBeUndefined()
|
||||
expect(staging.logger.warn.mock.calls.map((c) => String(c[0])).join()).toMatch(/belongs to "example\.com", this site is "staging\.example\.com"/)
|
||||
await disconnectRelay(staging.payload, options) // even "Disconnect" on the copy
|
||||
expect(production.fake.requests.filter((r) => r.path === '/v1/revoke')).toEqual([])
|
||||
expect((await enrolRelay(staging.payload, options, { force: true })).ok).toBe(true)
|
||||
expect((await sendThroughRelay(staging.payload, options, { ...MESSAGE, subject: 'From staging' })).sent).toBe(true)
|
||||
expect(production.fake.outbox.at(-1)).toMatchObject({ host: 'staging.example.com', subject: 'From staging' })
|
||||
const own = (await readRelayStore(staging.payload)).token
|
||||
expect(own).not.toBe(token)
|
||||
expect(seen.every((header) => !header.includes(token))).toBe(true)
|
||||
expect(JSON.stringify(staging.logger.warn.mock.calls)).not.toContain('ims_')
|
||||
// production is untouched and still sends with its own token
|
||||
expect((await readRelayStore(production.payload)).token).toBe(token)
|
||||
expect((await sendThroughRelay(production.payload, production.options, { ...MESSAGE, subject: 'From production' })).sent).toBe(true)
|
||||
test.each([
|
||||
['enrolled by the call-back', false],
|
||||
['with a token issued by hand', true],
|
||||
])('a developer\'s process on the live database (%s): reading the state, the limit, the doctor\'s view and a send change NOTHING', async (_name, byHand) => {
|
||||
const production = shared()
|
||||
if (byHand) {await setRelayToken(production.payload, production.fake.issueToken(HOST))}
|
||||
expect((await sendThroughRelay(production.payload, production.options, MESSAGE)).sent).toBe(true)
|
||||
const before = everything(production.store)
|
||||
const requests = production.fake.requests.length
|
||||
|
||||
const dev = production.another('http://localhost:3000', { url: undefined })
|
||||
expect(await mailPanelState({ payload: dev.payload }, dev.options)).toMatchObject({ relay: { connected: false, host: 'localhost:3000', refusal: { code: 'host-not-allowed' } } })
|
||||
expect(await getRelayStatus(dev.payload, dev.options)).toMatchObject({ connected: false })
|
||||
expect(await relayAttachmentLimit(dev.payload, dev.options)).toBeNull()
|
||||
expect(await sendThroughRelay(dev.payload, dev.options, MESSAGE)).toMatchObject({ code: 'relay-refused', sent: false })
|
||||
expect(await rotateRelayToken(dev.payload, dev.options)).toBe('not-due')
|
||||
await refreshRelayStatus(dev.payload, dev.options)
|
||||
|
||||
expect(everything(production.store)).toBe(before)
|
||||
expect(production.fake.requests).toHaveLength(requests)
|
||||
expect((await sendThroughRelay(production.payload, production.options, { ...MESSAGE, subject: 'Still here' })).sent).toBe(true)
|
||||
expect(production.fake.requests.filter((r) => r.path === '/v1/enrol')).toHaveLength(byHand ? 0 : 1)
|
||||
})
|
||||
|
||||
test('`client.pl` and `www.client.pl` on one database, mail in turn: one enrolment each, not one a mail', async () => {
|
||||
const apex = shared({ serverURL: 'https://client.pl' })
|
||||
const www = apex.another('https://www.client.pl')
|
||||
const apexOptions = resolveRelayOptions(apex.payload, { fetchImpl: apex.fake.fetch, retryBackoffMs: 1, url: apex.fake.url })!
|
||||
for (let i = 0; i < 4; i++) {
|
||||
expect((await sendThroughRelay(apex.payload, apexOptions, { ...MESSAGE, subject: `apex ${i}` })).sent).toBe(true)
|
||||
expect((await sendThroughRelay(www.payload, www.options, { ...MESSAGE, subject: `www ${i}` })).sent).toBe(true)
|
||||
}
|
||||
expect(apex.fake.requests.filter((r) => r.path === '/v1/enrol')).toHaveLength(2)
|
||||
expect(apex.fake.outbox.map((m) => m.host)).toEqual(['client.pl', 'www.client.pl', 'client.pl', 'www.client.pl', 'client.pl', 'www.client.pl', 'client.pl', 'www.client.pl'])
|
||||
expect([...apex.store.keys()].filter((k) => k.includes(':site:')).sort()).toEqual(['iapl:mail-relay:site:client.pl', 'iapl:mail-relay:site:www.client.pl'])
|
||||
})
|
||||
|
||||
test('a copy of production\'s database on a staging host does not enrol by itself — and uses, changes and revokes nothing of production\'s', async () => {
|
||||
const production = shared({ integrations: { smtpFromName: 'Example' } })
|
||||
await sendThroughRelay(production.payload, production.options, MESSAGE)
|
||||
const token = (await readRelayStore(production.payload)).token!
|
||||
const before = everything(production.store)
|
||||
const staging = production.another('https://staging.example.com')
|
||||
const seen: string[] = []
|
||||
// what the copy's requests carry (production's own later request is not the copy's)
|
||||
production.fake.intercept = (request) => void (request.headers.get('x-intecion-site') !== HOST && seen.push(request.headers.get('authorization') ?? ''))
|
||||
|
||||
// a form on the copy, with production's data in it: nothing is sent, nothing is asked
|
||||
const requests = production.fake.requests.length
|
||||
const held = await sendThroughRelay(staging.payload, staging.options, { ...MESSAGE, to: '[email protected]' })
|
||||
expect(held).toMatchObject({ cause: 'client-other-host', code: 'relay-refused', confirmed: true, sent: false })
|
||||
expect(held.sent === false && held.detail).toContain('example.com')
|
||||
expect(production.fake.requests).toHaveLength(requests)
|
||||
expect(production.fake.outbox).toHaveLength(1)
|
||||
// the panel and the doctor say why, before and after that send
|
||||
expect(await mailPanelState({ payload: staging.payload }, staging.options)).toMatchObject({ relay: { connected: false, host: 'staging.example.com', refusal: { code: 'client-other-host', reason: HOST } } })
|
||||
const untouched = production.another('https://staging-2.example.com')
|
||||
expect((await mailPanelState({ payload: untouched.payload }, untouched.options)).relay?.refusal).toMatchObject({ code: 'client-other-host', reason: HOST })
|
||||
// "Disconnect" on the copy revokes nothing of production's
|
||||
await disconnectRelay(untouched.payload, untouched.options)
|
||||
expect(production.fake.requests.filter((r) => r.path === '/v1/revoke')).toEqual([])
|
||||
expect((await readRelayStore(production.payload)).token).toBe(token)
|
||||
|
||||
// an admin decides that the copy sends: "Connect again", once — then it is a site of its own and heals by itself
|
||||
expect(await enrolRelay(staging.payload, staging.options, { force: true })).toEqual({ ok: true, state: 'active' })
|
||||
expect((await sendThroughRelay(staging.payload, staging.options, { ...MESSAGE, subject: 'From staging' })).sent).toBe(true)
|
||||
expect(production.fake.outbox.at(-1)).toMatchObject({ host: 'staging.example.com', subject: 'From staging' })
|
||||
const own = (await readRelayStore(staging.payload)).token!
|
||||
expect(own).not.toBe(token)
|
||||
await production.fake.handle(new Request(`${production.fake.url}/v1/revoke`, { headers: { authorization: `Bearer ${own}`, 'x-intecion-site': 'staging.example.com' }, method: 'POST' }))
|
||||
expect((await sendThroughRelay(staging.payload, staging.options, { ...MESSAGE, subject: 'Healed' })).sent).toBe(true)
|
||||
// also when its token is gone altogether (another container rotated it away): it has been connected, so it enrols
|
||||
await updateRelayStore(staging.payload, (c) => ({ ...c, token: undefined }))
|
||||
expect((await sendThroughRelay(staging.payload, staging.options, { ...MESSAGE, subject: 'Healed again' })).sent).toBe(true)
|
||||
// a token the service delivers for ONE host waits beside that host's token only: the other host never tries it
|
||||
const nonce = `stg${'n'.repeat(40)}`
|
||||
await holdNonce(staging.payload, nonce, 60_000)
|
||||
await callConfirmRoute(staging.payload)('https://staging.example.com/api/iapl/mail-relay/confirm', { body: JSON.stringify({ nonce, state: 'active', token: `ims_${'s'.repeat(43)}` }), headers: {} })
|
||||
expect((await readRelayCandidate(staging.payload))?.token).toBe(`ims_${'s'.repeat(43)}`)
|
||||
expect(await readRelayCandidate(production.payload)).toBeNull()
|
||||
const sends = production.fake.requests.length
|
||||
expect((await sendThroughRelay(production.payload, production.options, { ...MESSAGE, subject: 'Its own token' })).sent).toBe(true)
|
||||
expect(production.fake.requests.slice(sends).map((r) => r.path)).toEqual(['/v1/send'])
|
||||
|
||||
expect(seen.every((header) => !header.includes(token))).toBe(true)
|
||||
expect(JSON.stringify([staging.logger.warn.mock.calls, staging.logger.error.mock.calls])).not.toContain('ims_')
|
||||
// production's entry is byte for byte what it was, and production sends on
|
||||
expect((await readRelayStore(production.payload)).token).toBe(token)
|
||||
expect(JSON.parse(before).find(([key]: [string]) => key === `iapl:mail-relay:site:${HOST}`)).toEqual([`iapl:mail-relay:site:${HOST}`, production.store.get(`iapl:mail-relay:site:${HOST}`)])
|
||||
production.fake.intercept = undefined
|
||||
expect((await sendThroughRelay(production.payload, production.options, { ...MESSAGE, subject: 'From production' })).sent).toBe(true)
|
||||
})
|
||||
|
||||
test('a moved domain, a second domain, or a project that wants copies to enrol: `otherHosts`', async () => {
|
||||
const old = shared()
|
||||
await sendThroughRelay(old.payload, old.options, MESSAGE)
|
||||
// the same data under a new domain: waits by default …
|
||||
const moved = old.another('https://example.org')
|
||||
expect(await sendThroughRelay(moved.payload, moved.options, MESSAGE)).toMatchObject({ cause: 'client-other-host', sent: false })
|
||||
// … named as the site's own old host, it enrols by itself
|
||||
const named = old.another('https://example.net', { otherHosts: ['example.com'] })
|
||||
expect((await sendThroughRelay(named.payload, named.options, MESSAGE)).sent).toBe(true)
|
||||
// (the list names hosts: a third one in the way still stops it — example.net is now there too)
|
||||
const third = old.another('https://example.info', { otherHosts: ['example.com'] })
|
||||
expect(await sendThroughRelay(third.payload, third.options, MESSAGE)).toMatchObject({ cause: 'client-other-host' })
|
||||
const any = old.another('https://copy.example.dev', { otherHosts: 'enrol' })
|
||||
expect((await sendThroughRelay(any.payload, any.options, MESSAGE)).sent).toBe(true)
|
||||
// a site before launch — an empty store — enrols by itself, as ever
|
||||
const fresh = relaySite({ fake: { allow: [HOST] } })
|
||||
expect((await sendThroughRelay(fresh.payload, fresh.options, MESSAGE)).sent).toBe(true)
|
||||
})
|
||||
})
|
||||
|
||||
test('Q-2: the file limit is answered from what is stored and never waits for the service', async () => {
|
||||
const { fake, options, payload } = relaySite({ fake: { allow: [HOST], limits: { maxAttachmentBytes: 4242 } } })
|
||||
await sendThroughRelay(payload, options, MESSAGE) // the status is read after the first send
|
||||
// an hour and more later, with the service hanging: the stored answer, at once, and no request
|
||||
await updateRelayStore(payload, (c) => ({ ...c, service: { ...c.service!, fetchedAt: new Date(Date.now() - 3 * 60 * 60_000).toISOString() } }))
|
||||
const hanging = (async (_input: unknown, init?: RequestInit) =>
|
||||
new Promise<Response>((_resolve, reject) => init?.signal?.addEventListener('abort', () => reject(new DOMException('aborted', 'AbortError'))))) as typeof fetch
|
||||
const requests = fake.requests.length
|
||||
const started = Date.now()
|
||||
for (let i = 0; i < 3; i++) {expect(await relayAttachmentLimit(payload, { ...options, fetchImpl: hanging })).toBe(4242)}
|
||||
expect(Date.now() - started).toBeLessThan(200)
|
||||
expect(fake.requests).toHaveLength(requests)
|
||||
// renewed by the next send, not by a read
|
||||
fake.limits.maxAttachmentBytes = 1000
|
||||
await sendThroughRelay(payload, options, { ...MESSAGE, subject: 'Renews it' })
|
||||
expect(await relayAttachmentLimit(payload, options)).toBe(1000)
|
||||
})
|
||||
|
||||
test('Q-3: a file whose mail was not confirmed is not reported as a wrong file', () => {
|
||||
const texts = NOTIFICATION_FALLBACK.form
|
||||
const failed = { field: 'cv', file: 'cv.pdf', reason: 'delivery', success: false } as const
|
||||
expect(resolveFormMessage(failed, texts)).toContain('Choose a smaller file')
|
||||
const unconfirmed = resolveFormMessage({ ...failed, unconfirmed: true }, texts)
|
||||
expect(unconfirmed).toContain('cv.pdf')
|
||||
expect(unconfirmed).toMatch(/could not confirm/)
|
||||
expect(unconfirmed).not.toMatch(/try again|smaller file/)
|
||||
expect(resolveFormMessage({ ...failed, unconfirmed: true }, NOTIFICATION_FALLBACK_PL.form)).toMatch(/Nie wysyłaj go ponownie/)
|
||||
})
|
||||
|
||||
test('a token issued by hand is stored the same way; enrol: "manual" and enrol: false never enrol by themselves', async () => {
|
||||
|
||||
@@ -40,6 +40,7 @@ export function relayPayload({ custom, endpoints = [relayConfirmEndpoint()], int
|
||||
kv: {
|
||||
delete: async (key: string) => void store.delete(key),
|
||||
get: async (key: string) => (store.has(key) ? structuredClone(store.get(key)) : null),
|
||||
keys: async () => [...store.keys()],
|
||||
set: async (key: string, value: object) => void store.set(key, structuredClone(value)),
|
||||
},
|
||||
logger,
|
||||
|
||||
@@ -30,6 +30,8 @@ vi.mock('next/headers.js', async () => (await import('./http/server.js')).nextHe
|
||||
const PASSWORD = 'a-long-test-password-1'
|
||||
const HOST = 'example.com'
|
||||
const CONFIRM = `/api${RELAY_CONFIRM_PATH}`
|
||||
/** The site's entry: one per host. */
|
||||
const SITE_KEY = `${RELAY_KV_KEY}:site:${HOST}`
|
||||
|
||||
let server: TestServer
|
||||
let payload: Payload
|
||||
@@ -139,7 +141,7 @@ describe('the token cannot be reached from outside', () => {
|
||||
test('it is in the key-value store', async () => {
|
||||
token = (await readRelayStore(payload)).token ?? ''
|
||||
expect(token).toMatch(/^ims_[\w-]{43}$/)
|
||||
const rows = await payload.db.find({ collection: 'payload-kv', limit: 0, pagination: false, where: { key: { equals: RELAY_KV_KEY } } })
|
||||
const rows = await payload.db.find({ collection: 'payload-kv', limit: 0, pagination: false, where: { key: { equals: SITE_KEY } } })
|
||||
expect(rows.docs).toHaveLength(1)
|
||||
id = (rows.docs[0] as { id: number | string }).id
|
||||
expect(JSON.stringify(rows.docs[0])).toContain(token)
|
||||
@@ -150,7 +152,7 @@ describe('the token cannot be reached from outside', () => {
|
||||
const answers = [
|
||||
await api('/payload-kv', headers),
|
||||
await api(`/payload-kv/${id}`, headers),
|
||||
await api(`/payload-kv?where[key][equals]=${encodeURIComponent(RELAY_KV_KEY)}&depth=0`, headers),
|
||||
await api(`/payload-kv?where[key][equals]=${encodeURIComponent(SITE_KEY)}&depth=0`, headers),
|
||||
await api('/payload-kv', headers, { body: JSON.stringify({ data: { token: 'x' }, key: `${RELAY_KV_KEY}:x` }), method: 'POST' }),
|
||||
await api(`/payload-kv/${id}`, headers, { body: JSON.stringify({ data: {} }), method: 'PATCH' }),
|
||||
await api(`/payload-kv/${id}`, headers, { method: 'DELETE' }),
|
||||
@@ -213,6 +215,8 @@ describe('the state routes are for admins', () => {
|
||||
expect(((await (await api('/iapl/mail-relay/status', admin)).json()) as { accessKeyField?: boolean }).accessKeyField).toBeUndefined()
|
||||
const closed = await post('/iapl/mail-relay/connect', admin, { token: fake.issueToken(HOST) })
|
||||
expect(closed.status).toBe(403)
|
||||
// said as what it is — not "only an administrator can do this" to an administrator
|
||||
expect(((await closed.json()) as { error: string }).error).toMatch(/set by the site's developer/)
|
||||
expect((await readRelayStore(payload)).token).toBe(mine)
|
||||
// a project switches the field on: mail.relay.accessKeyField
|
||||
relayOptions.accessKeyField = true
|
||||
|
||||
Reference in New Issue
Block a user