diff --git a/contracts/mail-relay/CHANGELOG.md b/contracts/mail-relay/CHANGELOG.md index ae44985..067232b 100644 --- a/contracts/mail-relay/CHANGELOG.md +++ b/contracts/mail-relay/CHANGELOG.md @@ -1,6 +1,14 @@ # Changelog of the wire contract -## 1.7.0 — 2026-11-25 (not released; no tag yet) +## 1.7.1 — 2026-11-25 (not released; no tag yet) + +Wording only; nothing for a client to change, and a copy of 1.7.0 need not be refreshed for it. + +- **1.7.0 is required, not optional.** A client of 1.6 or older gets `400 invalid-request` on every request + that carries a token, because it does not send `X-Intecion-Site`. By the rule for development versions (§9) + it was numbered as a minor; read it as a breaking step. No client of 1.6 or older was released. + +## 1.7.0 — 2026-11-25 (never released) From the independent review of the first client. What a client built against 1.6.0 has to change is marked. diff --git a/contracts/mail-relay/CHECKSUMS b/contracts/mail-relay/CHECKSUMS index d47d2e5..ab7b170 100644 --- a/contracts/mail-relay/CHECKSUMS +++ b/contracts/mail-relay/CHECKSUMS @@ -1,8 +1,8 @@ -9b254d1aebe0e3e11539f95bb9eabba8984a77f27ea1a12ab9c259f3a3f2df94 README.md -cf9e7137ac9190773856b5d284544d04c188c852a3f3a92f6f68f561060c8626 CHANGELOG.md -bb7320d831e7a151aa901c35e7326c752fa2ef5024f30768c42319b8bed171ed VERSION +3d5c4b7ed53fe6fe2c7c28826c0cf666f9c1d0b79f861b404503e7029728a61f README.md +53da77d5dfff9948d68fca26b828563e21f83418245053d78b03a5aecac6c1d1 CHANGELOG.md +249182a01164b81a5f7af87e5c5cdbd3344a80a7a66dfca624cecfb1501b2420 VERSION 2ff0ad5b6a245365c0fa8733fa17b7bbd3ab91d4825981709d0fd02b762b939f schema.json -766fe0ed81037c230ab64e9fea2f9e6e5e828c5744bd90c61d9a2ad374a83100 runner.mjs +9d8381d2e3465e97dc801a61f598fcf822e27e73a2c0729877744ec307097910 runner.mjs 7c46860adee597e570832c72bcdb418752a20b9f7d1b2d7a656ed065f9632b2a checksums.mjs df6015faf02a7cf7e9b5816b9e22b2e82968678ddd72a61c1f9665a8c0897ddf examples/callback-confirm-wordpress.json f5018ca4fb7d25794ee92168d715aaf47feeba3d907c0550651b16c10a691ceb examples/callback-confirm.json diff --git a/contracts/mail-relay/README.md b/contracts/mail-relay/README.md index f11fc17..cbd1ae5 100644 --- a/contracts/mail-relay/README.md +++ b/contracts/mail-relay/README.md @@ -1,6 +1,6 @@ # Intecion Notifications Webservice — wire contract -Version: see [`VERSION`](VERSION) (this text describes **1.7.0**). Path prefix of this major version: `/v1`. +Version: see [`VERSION`](VERSION) (this text describes **1.7.1**). Path prefix of this major version: `/v1`. This is the whole agreement between the Intecion Notifications Webservice ("the service" below) and a client (the mail transport built into a site's plugin). It names no product: nothing here says Payload, WordPress, IAPL or IAWL except the values of @@ -360,7 +360,7 @@ not go out ([`StatusResponse`](schema.json)): ```json { "ok": true, "state": "active", "host": "example.com", "product": "iapl", - "service": { "name": "Intecion Notifications Webservice", "version": "1.0.0", "contract": "1.7.0" }, + "service": { "name": "Intecion Notifications Webservice", "version": "1.0.0", "contract": "1.7.1" }, "sender": { "address": "notification@webservices.intecion.net" }, "limits": { "messagesPerHour": 30, "messagesPerDay": 200, "recipientsPerMessage": 10, "perRecipientPerDay": 10, "newRecipientsPerDay": 50, diff --git a/contracts/mail-relay/VERSION b/contracts/mail-relay/VERSION index bd8bf88..943f9cb 100644 --- a/contracts/mail-relay/VERSION +++ b/contracts/mail-relay/VERSION @@ -1 +1 @@ -1.7.0 +1.7.1 diff --git a/contracts/mail-relay/runner.mjs b/contracts/mail-relay/runner.mjs index 8159fc3..c5a67d6 100644 --- a/contracts/mail-relay/runner.mjs +++ b/contracts/mail-relay/runner.mjs @@ -2,7 +2,7 @@ // No dependency. Works in Node 20+ and in the Workers runtime (uses only WebCrypto, btoa and TextEncoder). // How to use it: README.md, "The examples and the runner". -export const CONTRACT_VERSION = '1.7.0' +export const CONTRACT_VERSION = '1.7.1' export class ContractError extends Error { constructor(exampleId, message) { diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md index 576b737..7787b48 100644 --- a/docs/CHANGELOG.md +++ b/docs/CHANGELOG.md @@ -41,7 +41,8 @@ once there are more than 20. | `GRAPH_*` set, "Sending method" on SMTP, no SMTP server (mail failed until now) | Mail goes through Graph | fill in SMTP, or remove the variables | | Neither (mail failed until now with "not configured") | **An outbound call:** on the next e-mail the site enrols with the service — `POST https://webservices.intecion.net/mail/v1/enrol` with its host and the plugin version — and then sends through it, from `notification@webservices.intecion.net`. 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' } }` | + | **A copy** of a site's database on a site that says it is not public — `IAPL_NOINDEX=1`, or a host in `mail.relay.developmentHosts` (staging made from production; production's data copied back onto the development address), with no SMTP there | It does **not** enrol or send 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. **A copy without either mark sends** (it looks like launch day); a production site that kept `IAPL_NOINDEX=1` sends nothing | `mail: { relay: { otherHosts: 'enrol' } }` | + | A site launched on its real domain after it was built on a development address; a moved domain | Nothing to do: it enrols by itself on its first e-mail | `mail: { relay: { otherHosts: 'wait' } }` makes it wait for "Connect again" | | 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 | — | @@ -102,7 +103,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, otherHosts, totalTimeoutMs, timeoutMs, retryBackoffMs, fetchImpl }, graphDeprecationWarning }`; `mailAdapter({ relay })`. + confirmRateLimit, accessKeyField, otherHosts, developmentHosts, 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 @@ -117,7 +118,7 @@ once there are more than 20. `withMailKind`, `runWithMailKind`, `mailKindOf`, `expectMailTo`, `buildFormMailKindHook`, `createFakeRelay` (the service in memory, for tests), the constants `RELAY_*`, `MAIL_KINDS`, `MAIL_KIND`, `GRAPH_DEPRECATION_NOTICE`, and their types; `MailRelayStatus` from `/admin`. -- The wire contract of the service (version 1.7.0) is copied in the repository (`contracts/mail-relay/`) with a +- The wire contract of the service (version 1.7.1) is copied in the repository (`contracts/mail-relay/`) with a checksum test; every example of it runs against the plugin's fake service and against the plugin's client. - **`iapl-doctor` rule `legacy-names`** (info): lists the old names a project still uses, each with the new one. Information, not a defect. A warning only for `iapl-doctor.json` and `ipal-doctor.json` side by side, or one variable diff --git a/docs/agent/AGENT.md b/docs/agent/AGENT.md index a3963d3..588b850 100644 --- a/docs/agent/AGENT.md +++ b/docs/agent/AGENT.md @@ -1284,10 +1284,17 @@ the mail service → nothing (`mail: { relay: false }` and no SMTP). A site with the mail service that is where replies go; the service's own address has no mailbox. 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. +6. **Launch needs nobody:** a site enrolled on its development address and then served on the real domain (or moved + to another domain) enrols by itself on its first e-mail. **A non-public copy does not send by itself:** a site + with `IAPL_NOINDEX=1` — set it on every staging, preview and test copy — or on a host matched by + `mail: { relay: { developmentHosts: ['*.dev.agency.example'] } }`, whose database holds another host's + connection (staging made from production; production's data copied back onto the development address), neither + enrols nor sends until an admin presses "Connect again". **A copy with neither mark sends to the real addresses + in its data** — the plugin cannot tell it from launch day; the doctor's deep run notes it (`mail-relay-state`, + info). A production site that kept `IAPL_NOINDEX=1` sends nothing until the variable is removed. For a copy that + must never send: `mail: { relay: false }` or SMTP to a catcher. If the project's development addresses share a + pattern, set `developmentHosts` in its config. Verify: on the copy, Site integrations → E-mail sending says "The + data comes from another site (…)" and a test e-mail is refused; on the launched site it says "Connected to IWSN". **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 "; the mail arrives from `notification@webservices.intecion.net` with the client's name and `Reply-To` the client's address; `iapl-doctor @@ -1320,7 +1327,8 @@ 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'` | +| `otherHosts` | `'auto'` | a database holding another host's connection: a public site enrols by itself (launch, a move), a non-public one (`IAPL_NOINDEX=1` / `developmentHosts`) neither enrols nor sends until "Connect again"; a list of the site's own other hosts; `'wait'` (a public site without a connection waits too); `'enrol'` (no rule) | +| `developmentHosts` | `[]` | host patterns (`*`) of development and staging addresses: a site there is non-public for `otherHosts` (`siteIsNonPublic`) | | `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 | diff --git a/docs/agent/skills/iapl-debug/SKILL.md b/docs/agent/skills/iapl-debug/SKILL.md index 9933936..300ba8d 100644 --- a/docs/agent/skills/iapl-debug/SKILL.md +++ b/docs/agent/skills/iapl-debug/SKILL.md @@ -102,7 +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:///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") | -| 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 | +| a site sends nothing: "The data comes from another site (…), so this copy does not send e-mails by itself" / `relay-refused`, cause `client-other-host` | the site says it is not public (`IAPL_NOINDEX=1`, or a host in `mail.relay.developmentHosts`) and its database holds another host's connection: a staging copy of production, or production's data copied back onto the development address. Expected — a copy with production's data must not mail real people by itself | should it send: "Connect again" in the state block, once (until the data is replaced). A copy that must never send: `mail: { relay: false }` or SMTP to a catcher. **The production site itself says this:** `IAPL_NOINDEX` was left set after launch — remove it | +| a staging or test copy **does** send, to real addresses | it does not say it is not public, so it looks like a launch (a public site enrols by itself); the doctor's deep run notes "the database also holds the mail-service connection of another host" | `IAPL_NOINDEX=1` on the copy, or `mail: { relay: { developmentHosts: ['*.dev.agency.example'] } }`; to be sure: `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 | diff --git a/docs/agent/skills/iapl-setup/SKILL.md b/docs/agent/skills/iapl-setup/SKILL.md index 08931f6..6db9a23 100644 --- a/docs/agent/skills/iapl-setup/SKILL.md +++ b/docs/agent/skills/iapl-setup/SKILL.md @@ -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" (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 + 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 real domain enrols by itself at launch although the site was connected on its development address — nothing to press; "The data comes from another site" = the site says it is not public (`IAPL_NOINDEX=1` or a development host) and holds a copy of another site's data: press "Connect again" only if the copy should send — on the production domain it means `IAPL_NOINDEX` was left set. A staging or test copy must have `IAPL_NOINDEX=1` (or its host in `mail: { relay: { developmentHosts: […] } }`), or it mails the real addresses in its data), 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. diff --git a/docs/agent/skills/iapl-upgrade/SKILL.md b/docs/agent/skills/iapl-upgrade/SKILL.md index 3beeb56..552f3c8 100644 --- a/docs/agent/skills/iapl-upgrade/SKILL.md +++ b/docs/agent/skills/iapl-upgrade/SKILL.md @@ -573,9 +573,13 @@ PROGRAMISTA §6, item 73; email.md; AGENT.md §7.2) — nothing to run; read whi 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); 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'] } }`. + **Launch and a domain move need nothing:** the real domain enrols by itself although the database holds the + development address's connection. **A staging or test copy of the database** neither enrols nor sends by itself + **if it says it is not public** — `IAPL_NOINDEX=1` (check that every copy has it) or its host in + `mail: { relay: { developmentHosts: ['*.dev.agency.example'] } }`: the panel says so until an admin presses + "Connect again". A copy with neither mark sends to the real addresses in its data; keep a copy silent for good + with `mail: { relay: false }` or SMTP to a catcher. Production must not have `IAPL_NOINDEX` set (it would send + nothing). 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 diff --git a/docs/deployment.md b/docs/deployment.md index 234b617..500c806 100644 --- a/docs/deployment.md +++ b/docs/deployment.md @@ -54,13 +54,18 @@ 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`. -- **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. +- **Launch and a domain move need nobody.** A site built on a development address and then served on its real + domain (or moved to another one) enrols by itself on its first e-mail; the old address's connection in the + database is its own past. Remove `IAPL_NOINDEX` at launch as always — a site that still has it counts as a + non-public copy and sends nothing. +- **Staging and copies.** A site is active as soon as it enrols, so a staging site sends real mail. A **copy of + production's database** on a site that says it is not public — `IAPL_NOINDEX=1` (set on every staging, preview and + test copy) or a host in `mail: { relay: { developmentHosts: ['*.dev.agency.example'] } }` — neither enrols nor + sends by itself (its data is production's) until an admin presses "Connect again", and never uses or touches + production's connection. **A copy without either mark sends**, to the real addresses in its data: the plugin + cannot tell it from launch day (the doctor's deep run notes it). 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"). - 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. diff --git a/docs/doctor.md b/docs/doctor.md index 497bb22..a20d5e3 100644 --- a/docs/doctor.md +++ b/docs/doctor.md @@ -113,7 +113,7 @@ Turn off: `iapl({ doctor: false })`. Adapt: `iapl({ doctor: { tokenVar: 'MY_TOKE | | `storage-names` | warning | the visitor cookie the layout sets (``, 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, not a copied database that waits for "Connect again" (`client-other-host`), 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 non-public copy of another site's database that waits for "Connect again" (`client-other-host`), the sender name not replaced (warning); not enrolled yet, and a public site whose database also holds another host's connection — its own past after a launch or a move, or a copy that forgot `IAPL_NOINDEX=1` (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` | diff --git a/docs/email.md b/docs/email.md index c2cb3ed..850873e 100644 --- a/docs/email.md +++ b/docs/email.md @@ -256,25 +256,56 @@ await runWithMailKind('account', () => sendWelcomeMails(payload, user)) - **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. +- **Launch and a domain move need nobody.** A site is usually built and enrolled on a development address + (`client.dev.agency.example`) and then served on its real domain, with the same data. The real domain finds the + development address's connection in its database, treats it as its own past, enrols by itself on its first + e-mail and sends. The same after a move to another domain. No button, no option. +- **A non-public copy does not send by itself.** A copy of production's data holds real customers' addresses — + form submissions, accounts — and would mail real people as soon as a form or a password reset ran. The plugin + tells the two apart by **direction**: a site that says it is not public — **`IAPL_NOINDEX=1`** (every staging, + preview and test copy sets it anyway) or a host matched by **`mail: { relay: { developmentHosts: ['*.dev.agency.example'] } }`** + — and whose database holds the connection of **another host** neither enrols nor sends: sends report + `relay-refused` (cause `client-other-host`), the state block says "The data comes from another site (…), so this + copy does not send e-mails by itself", the doctor reports it (`mail-relay-state`), and no call leaves the server. + This also holds when the copy has a token of its own: production's database copied **back** onto the development + address brings that address's old connection with it, and still mails nobody. +- **An admin who wants the copy to send** presses **Connect again**, once. That is stored in the copy's database; + the next fresh copy of production replaces it and waits again. +- **A site before launch is not affected:** with no other host in its database it enrols by itself on its first + e-mail, noindex or not. + +| The site | Public? | Its database holds | By itself | +|---|---|---|---| +| on its development address, before launch | no | nothing, or only its own connection | enrols and sends | +| on the real domain, launch day (the development site may still run on its own database) | yes | the development address's connection | **enrols and sends — no click** | +| after a domain move; a second domain | yes | the old domain's connection | enrols and sends | +| `www.` and the bare domain | either | each other's | one site: both send, each with its own entry | +| staging / test copy of production (`IAPL_NOINDEX=1` or a development host) | no | production's connection | **sends nothing** until "Connect again" | +| production's database copied back onto the development address | no | production's and its own old one | **sends nothing** until "Connect again" | +| a developer's `localhost` on the production database | — | production's | refused before any call (not a public host); reads and writes nothing of production's | +| a copy that **forgot** `IAPL_NOINDEX` and is on no development host | yes | production's | **enrols and sends, to the real addresses in its data** — see below | + +- **What remains possible — say it to whoever sets up a copy:** + - A copy that does not say it is not public (no `IAPL_NOINDEX=1`, host not in `developmentHosts`) looks exactly + like launch day and **sends**. The doctor's deep run reports the only sign there is, as information: "the + database also holds the mail-service connection of another host, and this site is public" (`mail-relay-state`). + Projects that put every copy under one pattern should set `developmentHosts` once, in the shared config. + - A production site that still has `IAPL_NOINDEX=1` after launch counts as non-public: it finds the development + address's connection and **sends nothing** (and is not indexed either). The state block and the doctor say why; + removing the variable is the fix ([deployment.md](./deployment.md): "`IAPL_NOINDEX` NOT set in production"). + - 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). + - After "Connect again" a copy sends until its data is replaced. + - A development site that keeps running **on the launched database** (not a copy of it) stops sending by itself + once the real domain has enrolled; other processes notice within 30 seconds. +- **A copy that must never send:** `iapl({ mail: { relay: false } })` there, or SMTP to a catcher. That is the safe + set-up for staging; the rule above only protects until somebody presses the button. +- **`otherHosts`** changes the rule: a list (`['client.dev.agency.example']`) names hosts as this site's own — a + non-public site is not held by them, and the doctor's note about a launched site goes away; `'wait'` is the + stricter rule — also a public site without a connection of its own waits for "Connect again"; `'enrol'` switches + the rule off. - 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 @@ -349,7 +380,8 @@ 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 | +| `otherHosts` | `'auto'` | a database that holds another host's connection. `'auto'`: a public site enrols by itself (launch, a domain move); a non-public one (`IAPL_NOINDEX=1` or `developmentHosts`) neither enrols nor sends until "Connect again". A list = those hosts are this site's own. `'wait'` = a public site without a connection of its own waits too. `'enrol'` = no rule | +| `developmentHosts` | `[]` | host patterns (`*` = any characters) of development, staging and preview addresses, for example `['*.dev.agency.example']`: a site on such a host is non-public for `otherHosts`, like one with `IAPL_NOINDEX=1` (`siteIsNonPublic(payload, options)`) | | `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 | diff --git a/docs/security.md b/docs/security.md index ce91688..b18b895 100644 --- a/docs/security.md +++ b/docs/security.md @@ -1005,7 +1005,7 @@ 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:///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`, one entry per host (`iapl:mail-relay:site:`). 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 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 a copy that says it is not public (`IAPL_NOINDEX=1`, or a host in `mail.relay.developmentHosts`) **neither enrols nor sends by itself** — with production's data it would mail real people — until an admin presses "Connect again", also when it has a token of its own (production's data copied back onto a development address). A public site is never held (launch and a domain move must work unattended), so **a copy that does not say it is not public sends**; the doctor notes a public site whose database knows another host (`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: ` on every mail. It cannot set `From`, `Return-Path` or any header, and cannot address a security alert | diff --git a/reference/.agents/skills/iapl-debug/SKILL.md b/reference/.agents/skills/iapl-debug/SKILL.md index 9933936..300ba8d 100644 --- a/reference/.agents/skills/iapl-debug/SKILL.md +++ b/reference/.agents/skills/iapl-debug/SKILL.md @@ -102,7 +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:///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") | -| 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 | +| a site sends nothing: "The data comes from another site (…), so this copy does not send e-mails by itself" / `relay-refused`, cause `client-other-host` | the site says it is not public (`IAPL_NOINDEX=1`, or a host in `mail.relay.developmentHosts`) and its database holds another host's connection: a staging copy of production, or production's data copied back onto the development address. Expected — a copy with production's data must not mail real people by itself | should it send: "Connect again" in the state block, once (until the data is replaced). A copy that must never send: `mail: { relay: false }` or SMTP to a catcher. **The production site itself says this:** `IAPL_NOINDEX` was left set after launch — remove it | +| a staging or test copy **does** send, to real addresses | it does not say it is not public, so it looks like a launch (a public site enrols by itself); the doctor's deep run notes "the database also holds the mail-service connection of another host" | `IAPL_NOINDEX=1` on the copy, or `mail: { relay: { developmentHosts: ['*.dev.agency.example'] } }`; to be sure: `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 | diff --git a/reference/.agents/skills/iapl-setup/SKILL.md b/reference/.agents/skills/iapl-setup/SKILL.md index 08931f6..6db9a23 100644 --- a/reference/.agents/skills/iapl-setup/SKILL.md +++ b/reference/.agents/skills/iapl-setup/SKILL.md @@ -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" (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 + 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 real domain enrols by itself at launch although the site was connected on its development address — nothing to press; "The data comes from another site" = the site says it is not public (`IAPL_NOINDEX=1` or a development host) and holds a copy of another site's data: press "Connect again" only if the copy should send — on the production domain it means `IAPL_NOINDEX` was left set. A staging or test copy must have `IAPL_NOINDEX=1` (or its host in `mail: { relay: { developmentHosts: […] } }`), or it mails the real addresses in its data), 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. diff --git a/reference/.agents/skills/iapl-upgrade/SKILL.md b/reference/.agents/skills/iapl-upgrade/SKILL.md index 3beeb56..552f3c8 100644 --- a/reference/.agents/skills/iapl-upgrade/SKILL.md +++ b/reference/.agents/skills/iapl-upgrade/SKILL.md @@ -573,9 +573,13 @@ PROGRAMISTA §6, item 73; email.md; AGENT.md §7.2) — nothing to run; read whi 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); 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'] } }`. + **Launch and a domain move need nothing:** the real domain enrols by itself although the database holds the + development address's connection. **A staging or test copy of the database** neither enrols nor sends by itself + **if it says it is not public** — `IAPL_NOINDEX=1` (check that every copy has it) or its host in + `mail: { relay: { developmentHosts: ['*.dev.agency.example'] } }`: the panel says so until an admin presses + "Connect again". A copy with neither mark sends to the real addresses in its data; keep a copy silent for good + with `mail: { relay: false }` or SMTP to a catcher. Production must not have `IAPL_NOINDEX` set (it would send + nothing). 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 diff --git a/src/index.ts b/src/index.ts index a2751ae..eac299f 100644 --- a/src/index.ts +++ b/src/index.ts @@ -257,6 +257,7 @@ export { runWithMailKind, sendThroughRelay, setRelayToken, + siteIsNonPublic, withMailKind, } from './modules/email/relay/index.js' export type { diff --git a/src/modules/admin-i18n/texts/integrations.ts b/src/modules/admin-i18n/texts/integrations.ts index 1abc15b..3763955 100644 --- a/src/modules/admin-i18n/texts/integrations.ts +++ b/src/modules/admin-i18n/texts/integrations.ts @@ -34,7 +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.', + mailRelayRefusedOtherHost: 'The data comes from another site ({{host}}), so this copy does not send e-mails by itself. Press "Connect again" if it should.', 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}}.', @@ -154,7 +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.', + mailRelayRefusedOtherHost: 'Dane pochodzą z innej witryny ({{host}}), więc ta kopia nie wysyła e-maili sama. Kliknij „Połącz ponownie”, jeśli ma je wysyłać.', 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}}.', diff --git a/src/modules/doctor/rules/mail.ts b/src/modules/doctor/rules/mail.ts index 8aebddc..d18b689 100644 --- a/src/modules/doctor/rules/mail.ts +++ b/src/modules/doctor/rules/mail.ts @@ -59,10 +59,10 @@ 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 `); 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') { + } else if (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`, + fix: 'expected for a copy that must not mail real people. If this copy should send e-mails: Site integrations → E-mail sending → "Connect again" (once). To keep it silent for good: mail: { relay: false } or SMTP to a catcher. If this is NOT a copy but the site itself, it is wrongly marked non-public: remove IAPL_NOINDEX / the host from mail.relay.developmentHosts', + message: `this site is non-public (IAPL_NOINDEX or a development host) and its database holds the mail-service connection of another site (${relay.reason ?? 'another host'}) — a copy of that site's data: it does not connect or send by itself, e-mails are not sent`, severity: 'warning', }) } else if (!relay.connected && relay.refusal) { @@ -75,6 +75,15 @@ export const mailRules: DoctorRule[] = [ } else if (!relay.connected) { out.push({ fix: 'send a test e-mail from Site integrations → E-mail sending', message: 'the site has not enrolled with the Intecion mail service yet (it does so on its first e-mail)', severity: 'info' }) } + if (mail.otherHostEntries && !mail.nonPublic) { + // Right after a launch or a domain move this is the site's own past. On a COPY that forgot to say it is not + // public it is the last warning before real people get its mail. + out.push({ + fix: 'the site itself after a launch or a move: nothing to do — name the old host to silence this: mail: { relay: { otherHosts: [\'\'] } }. A staging or test COPY of that site: set IAPL_NOINDEX=1 there (it then waits for "Connect again"), or mail: { relay: false } / SMTP to a catcher', + message: 'the database also holds the mail-service connection of another host, and this site is public: if it is a copy of that site, it sends e-mails to the real addresses in its data', + severity: 'info', + }) + } if (relay.nameReplaced) { out.push({ fix: 'Site integrations → E-mail sending → Sender name: a name that is the client\'s own (no address, no other company\'s name)', message: 'the mail service did not accept the sender name, so e-mails leave under the site\'s host', severity: 'warning' }) } diff --git a/src/modules/doctor/status.ts b/src/modules/doctor/status.ts index 000ff68..743e175 100644 --- a/src/modules/doctor/status.ts +++ b/src/modules/doctor/status.ts @@ -71,6 +71,8 @@ export async function collectDoctorStatus(payload: BasePayload): Promise rotate(payload, resolved(payload, options), { force: true }) + +/** + * Whether this site counts as a non-public copy for `mail.relay.otherHosts`: `IAPL_NOINDEX=1`, or its host is + * matched by `mail.relay.developmentHosts`. Such a site neither enrols nor sends by itself while its database + * holds another host's connection (docs/email.md "Staging, copies and several hosts"). + */ +export const siteIsNonPublic = (payload: BasePayload, options?: RelayOptions): boolean => nonPublic(payload, resolveRelayOptions(payload, options) || (options ?? {})) diff --git a/src/modules/email/relay/options.ts b/src/modules/email/relay/options.ts index 307b58e..4e1f518 100644 --- a/src/modules/email/relay/options.ts +++ b/src/modules/email/relay/options.ts @@ -24,6 +24,12 @@ export type RelayOptions = { accountMail?: { perAddress?: number; perVisitor?: number; windowMinutes?: number } | false /** Calls to the public confirm route per address. Default 10 a minute. */ confirmRateLimit?: { max?: number; windowMs?: number } + /** + * Host patterns of development and preview addresses (`*` = any characters), for example + * `['*.dev.example-agency.pl']`. A site on such a host is treated as a non-public copy for `otherHosts`, + * exactly like a site with `IAPL_NOINDEX=1`. Nothing is built in: name the agency's own pattern here. + */ + developmentHosts?: string[] /** * `'auto'` (default): the site enrols by itself on the first send without a token, and again after * the service asks for it. `'manual'`: only "Connect" in the panel or `enrolRelay()` enrols. @@ -40,14 +46,19 @@ export type RelayOptions = { /** 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. + * What a site does when its database holds the connection of ANOTHER host — a launch (the development + * address's entry is still there), a moved domain, or a copy of another site's database. + * + * Default (`'auto'`): by direction. A **public** site enrols by itself — launch day and a domain move need + * nobody. A **non-public** site (`IAPL_NOINDEX=1`, or a host in `developmentHosts`) that finds another + * host's connection it was never told about is a copy of that site's data: it does not enrol and does not + * send by itself (it would mail real people), until an admin presses "Connect again". + * + * `'wait'`: every site waits for "Connect again" when it has no connection of its own (the rule of the + * first cut). `'enrol'`: no rule at all. A list: these hosts are this site's own (never "another host"). + * `www.` and the bare domain are always one site; a site with an empty store always enrols by itself. */ - otherHosts?: 'enrol' | 'wait' | string[] + otherHosts?: 'auto' | '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. diff --git a/src/modules/email/relay/panel.ts b/src/modules/email/relay/panel.ts index ed041d2..acd8e36 100644 --- a/src/modules/email/relay/panel.ts +++ b/src/modules/email/relay/panel.ts @@ -11,7 +11,8 @@ 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, otherHostsInTheWay, readSiteStore, type RelayStatus, setRelayToken } from './session.js' +import { disconnectRelay, enrolRelay, type EnrolResult, getRelayStatus, LOCAL_CODES, otherHostsInTheWay, readSiteStore, type RelayStatus, setRelayToken, siteIsNonPublic } from './session.js' +import { otherRelayHosts } from './store.js' type Settings = { emailStatus?: IntegrationStatus | null @@ -28,6 +29,10 @@ export type MailPanelState = { accessKeyField?: boolean /** The address the service calls this site back at. */ confirmUrl?: string + /** The site says it is not public (`IAPL_NOINDEX`, or a host in `mail.relay.developmentHosts`). */ + nonPublic?: boolean + /** The database also holds the connection of a host this site did not name as its own, and the site is not held for it. */ + otherHostEntries?: boolean /** Enabled in the project (`mail.relay` is not `false`). */ relay: ({ senderAddress: string } & RelayStatus) | null replyAddress: null | string @@ -60,10 +65,21 @@ export async function mailPanelState(req: Pick, 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] } }} + // …and so is a non-public copy of another site's database: it waits for an admin's "Connect again", with or + // without a token of its own. Asked now, not read from what a past send left: the rule ends with its reason. + let nonPublic = false + let otherHostEntries = false + if (status && options && options.token === undefined) { + nonPublic = siteIsNonPublic(payload, options) + const stored = await readSiteStore(payload, options) + const foreign = status.disconnected ? [] : await otherHostsInTheWay(payload, options, stored) + const known = status.refusal?.code === LOCAL_CODES.otherHost + if (foreign.length && (!status.refusal || known)) {status = { ...status, refusal: { at: status.refusal?.at ?? new Date().toISOString(), code: LOCAL_CODES.otherHost, reason: foreign[0] } }} + else if (known) {status = { ...status, refusal: undefined }} + // other hosts' entries a PUBLIC site did not name as its own: its development address after launch — or the + // sign that this is a copy which forgot to say that it is not public + const named = [...(Array.isArray(options.otherHosts) ? options.otherHosts : []), ...(stored.acceptedHosts ?? [])].map((h) => h.trim().toLowerCase().replace(/^www\./, '')) + otherHostEntries = !foreign.length && (await otherRelayHosts(payload, status.host)).some((h) => !named.includes(h.replace(/^www\./, ''))) } const api = payload.config.routes?.api ?? '/api' return { @@ -71,6 +87,8 @@ export async function mailPanelState(req: Pick, own: ...(status?.host ? { confirmUrl: `https://${status.host}${api}${RELAY_CONFIRM_PATH}` } : {}), relay: status ? { ...status, senderAddress: status.senderAddress ?? RELAY_SENDER_ADDRESS } : null, replyAddress: typeof settings.smtpFromAddress === 'string' && settings.smtpFromAddress.trim() ? settings.smtpFromAddress.trim() : null, + ...(nonPublic ? { nonPublic: true } : {}), + ...(otherHostEntries ? { otherHostEntries: true } : {}), ...(smtpIncomplete(settings) ? { smtpIncomplete: true } : {}), transport, } diff --git a/src/modules/email/relay/session.ts b/src/modules/email/relay/session.ts index a3e4d94..e08fec4 100644 --- a/src/modules/email/relay/session.ts +++ b/src/modules/email/relay/session.ts @@ -5,6 +5,7 @@ import { randomBytes } from 'node:crypto' import type { ResolvedRelayOptions } from './options.js' import { PLUGIN_VERSION } from '../../../version.js' +import { isSiteNoindex } from '../../seo/siteNoindex.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, pluginMailOptions, relayHost } from './options.js' @@ -75,20 +76,72 @@ 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, stored: RelayStored): Promise { - 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\./, ''))) +/** Short memory of which other hosts have an entry: a non-public site asks on every send. Per Payload instance. */ +const otherHostsSeen = new WeakMap() +const OTHER_HOSTS_TTL_MS = 30_000 + +/** For tests, and after this site's own connection changed. */ +export function forgetOtherHosts(payload?: object): void { + if (payload) {otherHostsSeen.delete(payload)} } +async function otherHostsNow(payload: BasePayload, host: string, fresh: boolean): Promise { + const seen = otherHostsSeen.get(payload) + if (!fresh && seen && seen.host === host && Date.now() - seen.at < OTHER_HOSTS_TTL_MS) {return seen.hosts} + const hosts = await otherRelayHosts(payload, host) + otherHostsSeen.set(payload, { at: Date.now(), host, hosts }) + return hosts +} + +const bare = (host: string) => host.trim().toLowerCase().replace(/^www\./, '') + +/** + * Is this site a non-public copy — a development, preview or staging address? `IAPL_NOINDEX=1` (the switch + * such a site already has), or a host that matches `mail.relay.developmentHosts`. + */ +export function siteIsNonPublic(payload: BasePayload, options: Pick): boolean { + if (isSiteNoindex()) {return true} + const host = relayHost(payload, options) + return (options.developmentHosts ?? []).some((pattern) => { + const source = pattern.trim().toLowerCase().split('*').map((part) => part.replace(/[.+?^${}()|[\]\\]/g, '\\$&')).join('.*') + return Boolean(source) && new RegExp(`^${source}$`).test(host) + }) +} + +/** + * Other hosts' connections that keep this site from enrolling — and, for a non-public site, from sending — + * BY ITSELF (`mail.relay.otherHosts`). Decided by direction: + * - a public site is never held: the entry of its development address (launch) or of its old domain (a + * move) is simply its past; + * - a non-public site (noindex, or a development host) that finds the connection of a host it was never + * told about holds a copy of that site's data. Also when it has a token of its own: production's + * database copied BACK onto the development address brings the development site's old entry with it. + * Hosts the project named as its own, and hosts an admin accepted with "Connect again", do not count. + * `fresh`: read the store now (an enrolment); otherwise what was seen in the last half minute. + */ +export async function otherHostsInTheWay( + payload: BasePayload, + options: Pick, + stored: RelayStored, + { fresh = true }: { fresh?: boolean } = {}, +): Promise { + const mode = options.otherHosts + if (mode === 'enrol') {return []} + const connected = Boolean(stored.token || stored.enrolledAt) + if (mode === 'wait' && connected) {return []} + if (mode !== 'wait' && !siteIsNonPublic(payload, options)) {return []} + const own = [...(Array.isArray(mode) ? mode : []), ...(stored.acceptedHosts ?? [])].map(bare) + return (await otherHostsNow(payload, relayHost(payload, options), fresh)).filter((h) => !own.includes(bare(h))) +} + +const otherHostMessage = (host: string, foreign: string[]) => + `This database holds the mail-service connection of another site (${foreign.join(', ')}), and this site ("${host}") is a non-public copy (IAPL_NOINDEX, or a development host) or set to wait: it does not connect or send by itself. Press "Connect again" in Site integrations → E-mail sending if it should send e-mails (mail.relay.otherHosts).` + async function enrolOnce(payload: BasePayload, options: ResolvedRelayOptions, force: boolean, deadline?: number): Promise { const stored = await readSiteStore(payload, options) if (stored.disconnected && !force) {return enrolFailure(refusal(LOCAL_CODES.disconnected, 'The site was disconnected from the mail service in the panel.'))} - if (!force && stored.refusal && Date.parse(stored.refusal.until) > Date.now()) { + // (the copy rule is not a refusal of the service: it is asked again every time, so it ends when its reason does) + if (!force && stored.refusal && stored.refusal.code !== LOCAL_CODES.otherHost && Date.parse(stored.refusal.until) > Date.now()) { return enrolFailure(refusal(stored.refusal.code, stored.refusal.message ?? stored.refusal.code, { reason: stored.refusal.reason })) } const host = relayHost(payload, options) @@ -105,17 +158,19 @@ 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. + // A copy of another site's database does not enrol BY ITSELF (otherHostsInTheWay): with that site's data it + // would mail real people. An admin's "Connect again" (`force`) does, and the hosts found then are accepted. + const others = force ? await otherHostsNow(payload, host, true) : [] 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() } })) + const message = otherHostMessage(host, foreign) + if (stored.refusal?.code !== LOCAL_CODES.otherHost || stored.refusal.reason !== foreign[0]) { + const now = new Date().toISOString() + await updateRelayStore(payload, options, (current) => ({ ...current, refusal: { at: now, code: LOCAL_CODES.otherHost, message, reason: foreign[0], until: now } })) + } return enrolFailure(refusal(LOCAL_CODES.otherHost, message, { reason: foreign[0] })) } + if (stored.refusal?.code === LOCAL_CODES.otherHost) {await updateRelayStore(payload, options, (current) => ({ ...current, refusal: null }))} let answer: RelayAnswer<{ state?: string }> | undefined let nonce = '' @@ -139,6 +194,7 @@ async function enrolOnce(payload: BasePayload, options: ResolvedRelayOptions, fo const state: RelaySiteState = answer.body.state === 'pending' || answer.body.state === 'suspended' ? answer.body.state : 'active' await updateRelayStore(payload, options, (current) => ({ ...current, + ...(force ? { acceptedHosts: [...new Set([...(current.acceptedHosts ?? []), ...others])] } : {}), disconnected: false, enrolledAt: new Date().toISOString(), host, @@ -151,6 +207,7 @@ async function enrolOnce(payload: BasePayload, options: ResolvedRelayOptions, fo token: candidate.token, })) await dropRelayCandidate(payload, options) + forgetOtherHosts(payload) return { ok: true, state } } // Used or not, this nonce is over. A token the call-back did deliver stays beside the one in use. @@ -243,6 +300,11 @@ export async function withRelayToken( if (stored.disconnected) {return refusal(LOCAL_CODES.disconnected, 'The site was disconnected from the mail service in the panel.')} const candidate = await readRelayCandidate(payload, options) const token = candidate?.token ?? stored.token + // A non-public copy holding another site's data does not SEND by itself either, token or not. + if (token && round === 0) { + const foreign = await otherHostsInTheWay(payload, options, stored, { fresh: false }) + if (foreign.length) {return refusal(LOCAL_CODES.otherHost, otherHostMessage(relayHost(payload, options), foreign), { reason: foreign[0] })} + } const enrolNow = async (): Promise => { // once per message: a second request for it says again why the first enrolment failed @@ -424,9 +486,12 @@ export async function setRelayToken(payload: BasePayload, token: string, options if (!/^ims_[\w-]{43}$/.test(token)) {throw new Error('Not a token of the mail service (ims_ and 43 characters).')} // 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 } + const others = await otherRelayHosts(payload, relayHost(payload, options)) + forgetOtherHosts(payload) await dropRelayCandidate(payload, options) await updateRelayStore(payload, options, (current) => ({ ...current, + acceptedHosts: [...new Set([...(current.acceptedHosts ?? []), ...others])], disconnected: false, enrolledAt: new Date().toISOString(), host: relayHost(payload, options) || undefined, diff --git a/src/modules/email/relay/store.ts b/src/modules/email/relay/store.ts index 906cc19..cb44c5f 100644 --- a/src/modules/email/relay/store.ts +++ b/src/modules/email/relay/store.ts @@ -32,6 +32,12 @@ export type RelayLimits = { } export type RelayStored = { + /** + * Other hosts whose connection was in this database when a person connected this site ("Connect again", + * `setRelayToken`): a copy that was told to send does not stop for them again. A host that appears LATER + * — production's entry arriving with a fresh copy of its database — is not among them. + */ + acceptedHosts?: string[] /** * An admin pressed "Disconnect": no send and no enrolment until "Connect again". The token is still here * only while the service has not confirmed that it gave it up (`revokePending`). diff --git a/test/doctor.test.ts b/test/doctor.test.ts index d7747e5..3421c0a 100644 --- a/test/doctor.test.ts +++ b/test/doctor.test.ts @@ -690,7 +690,16 @@ describe('e-mail: transport, the mail service, Graph, the confirm route', () => 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(copy.findings[0].fix).toContain('Connect again') + // the same for a copy that has a token of its own (production's data copied back onto the development address) + expect(await run(mail({ nonPublic: true, relay: relay({ reason: 'client.pl', refusal: 'client-other-host' }) }))).toEqual(['mail-relay-state:warning']) + // a PUBLIC site whose database knows another host: the site after its launch — or a copy that forgot IAPL_NOINDEX + const launched = await doctor(project({ ...base(), 'src/payload.config.ts': 'iapl({ forms: {} })' }), ids, { deepStatus: { mail: mail({ otherHostEntries: true }) } }) + expect(rules(launched)).toEqual(['mail-relay-state:info']) + expect(launched.findings[0].message).toContain('copy') + expect(launched.findings[0].fix).toContain('IAPL_NOINDEX=1') + expect(launched.findings[0].fix).toContain('otherHosts') + expect(await run(mail({ nonPublic: true, otherHostEntries: true }))).toEqual([]) expect(await run(mail({ relay: relay({ nameReplaced: true }) }))).toEqual(['mail-relay-state:warning']) }) diff --git a/test/mailRelay.test.ts b/test/mailRelay.test.ts index 511f013..104288b 100644 --- a/test/mailRelay.test.ts +++ b/test/mailRelay.test.ts @@ -15,13 +15,14 @@ import { withAccountMailMark } from '../src/modules/email/relay/accountMail.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 { createFakeRelay } from '../src/modules/email/relay/fake.js' import { dropExpectedMail, expectMailTo, takeExpectedMail, withMailKind } from '../src/modules/email/relay/kinds.js' import { bareAddresses, buildRelayMessage, cleanSubject } from '../src/modules/email/relay/message.js' import { isPublicHost, relayHost, resolveRelayOptions } from '../src/modules/email/relay/options.js' import { mailPanelState } from '../src/modules/email/relay/panel.js' import { clearUnconfirmedRelayMessages, sendThroughRelay } from '../src/modules/email/relay/send.js' -import { disconnectRelay, enrolRelay, getRelayStatus, provesToken, refreshRelayStatus, rotateRelayToken, setRelayToken } from '../src/modules/email/relay/session.js' -import { holdNonce, readRelayCandidate, readRelayStore, updateRelayStore } from '../src/modules/email/relay/store.js' +import { disconnectRelay, enrolRelay, forgetOtherHosts, getRelayStatus, provesToken, refreshRelayStatus, rotateRelayToken, setRelayToken, siteIsNonPublic } from '../src/modules/email/relay/session.js' +import { holdNonce, otherRelayHosts, 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' @@ -56,6 +57,8 @@ beforeEach(() => { clearRateLimits() resetGraphDeprecationWarning() for (const name of GRAPH_ENV) {vi.stubEnv(name, '')} + // every site is public unless a test says otherwise + for (const name of ['IAPL_NOINDEX', 'IPAL_NOINDEX']) {vi.stubEnv(name, '')} }) afterEach(() => { vi.unstubAllEnvs() @@ -707,31 +710,117 @@ describe('the token over time', () => { 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 () => { + // The owner's sites: built and enrolled on a development address, then launched on the real domain. A + // development or staging site says so itself (IAPL_NOINDEX=1, or a host in mail.relay.developmentHosts). + const DEV = 'acme.dev.agency-example.com' + const DEV_HOSTS = { developmentHosts: ['*.dev.agency-example.com'] } + + test('before launch: the site on its development address, with an empty store, enrols and sends by itself', async () => { + const dev = shared({ options: DEV_HOSTS, serverURL: `https://${DEV}` }) + expect(siteIsNonPublic(dev.payload, dev.options)).toBe(true) + expect((await sendThroughRelay(dev.payload, dev.options, MESSAGE)).sent).toBe(true) + expect(dev.fake.outbox[0].host).toBe(DEV) + // the same with the switch such a site already has, and no option at all + vi.stubEnv('IAPL_NOINDEX', '1') + const noindex = relaySite({ fake: { allow: [HOST] } }) + expect(siteIsNonPublic(noindex.payload, noindex.options)).toBe(true) + expect((await sendThroughRelay(noindex.payload, noindex.options, MESSAGE)).sent).toBe(true) + }) + + test('launch day: the real domain finds the development address\'s entry and enrols by itself — no click; the development site on its own database sends on', async () => { + const dev = shared({ options: DEV_HOSTS, serverURL: `https://${DEV}` }) + await sendThroughRelay(dev.payload, dev.options, MESSAGE) // the test mail before launch + // launch: the same data, now served at the real domain (public: no noindex, not a development host) + const live = dev.another('https://client.pl', DEV_HOSTS) + expect(siteIsNonPublic(live.payload, live.options)).toBe(false) + const first = await sendThroughRelay(live.payload, live.options, { ...MESSAGE, subject: 'First mail after launch' }) + expect(first).toMatchObject({ sent: true }) + expect(dev.fake.outbox.at(-1)).toMatchObject({ host: 'client.pl', subject: 'First mail after launch' }) + expect(dev.fake.requests.filter((r) => r.path === '/v1/enrol')).toHaveLength(2) + expect((await mailPanelState({ payload: live.payload }, live.options)).relay?.refusal).toBeUndefined() + // the doctor can still say that the database knows another host (information, for the case that this is a copy) + expect(await mailPanelState({ payload: live.payload }, live.options)).toMatchObject({ otherHostEntries: true }) + expect((await mailPanelState({ payload: live.payload }, { ...live.options, otherHosts: [DEV] })).otherHostEntries).toBeUndefined() + + // the development site keeps running beside it on its OWN database: nothing changes for it + const apart = relaySite({ fake: { allow: ['*'] }, options: DEV_HOSTS, serverURL: `https://${DEV}` }) + await sendThroughRelay(apart.payload, apart.options, MESSAGE) + expect((await sendThroughRelay(apart.payload, apart.options, { ...MESSAGE, subject: 'Dev, later' })).sent).toBe(true) + // …but a development site that still runs ON the launched database now holds the live site's data: it stops by itself + forgetOtherHosts(dev.payload) + const before = dev.fake.requests.length + expect(await sendThroughRelay(dev.payload, dev.options, { ...MESSAGE, to: 'a-real-customer@example.org' })).toMatchObject({ cause: 'client-other-host', code: 'relay-refused', sent: false }) + expect(dev.fake.requests).toHaveLength(before) + }) + + test('production\'s database copied BACK to the development address: the copy has a token of its own, and still mails nobody by itself', async () => { + // one service, two sites, each with a database of its own + const sites: Record> = {} + const service = createFakeRelay({ allow: ['*'], callSite: (url, init) => sites[new URL(url).host](url, init) }) + const site = (serverURL: string) => { + const made = relayPayload({ serverURL }) + sites[new URL(serverURL).host] = callConfirmRoute(made.payload) + return { ...made, options: resolveRelayOptions(made.payload, { ...DEV_HOSTS, fetchImpl: service.fetch, retryBackoffMs: 1, url: service.url })! } + } + const copy = (from: Map, to: Map) => { + to.clear() + for (const [key, value] of from) {to.set(key, structuredClone(value))} + } + const dev = site(`https://${DEV}`) + expect((await sendThroughRelay(dev.payload, dev.options, MESSAGE)).sent).toBe(true) + // launch: the live site starts from the development site's data, and enrols by itself + const live = site('https://client.pl') + const liveOptions = live.options + copy(dev.store, live.store) + expect((await sendThroughRelay(live.payload, liveOptions, { ...MESSAGE, subject: 'Live' })).sent).toBe(true) + const liveToken = (await readRelayStore(live.payload)).token! + + // months later: production's data is copied back onto the development address, to work on a bug + copy(live.store, dev.store) + forgetOtherHosts(dev.payload) + expect((await readRelayStore(dev.payload)).token).toMatch(/^ims_/) // its own old entry came back with the copy + const requests = service.requests.length + const held = await sendThroughRelay(dev.payload, dev.options, { ...MESSAGE, to: 'a-real-customer@example.org' }) + expect(held).toMatchObject({ cause: 'client-other-host', code: 'relay-refused', confirmed: true, sent: false }) + expect(service.requests).toHaveLength(requests) + expect(await mailPanelState({ payload: dev.payload }, dev.options)).toMatchObject({ nonPublic: true, relay: { connected: true, refusal: { code: 'client-other-host', reason: 'client.pl' } } }) + // a developer decides that this copy sends: "Connect again", once + expect((await enrolRelay(dev.payload, dev.options, { force: true })).ok).toBe(true) + expect((await sendThroughRelay(dev.payload, dev.options, { ...MESSAGE, subject: 'On purpose' })).sent).toBe(true) + expect(service.outbox.at(-1)).toMatchObject({ host: DEV, subject: 'On purpose' }) + expect((await mailPanelState({ payload: dev.payload }, dev.options)).relay?.refusal).toBeUndefined() + // the next fresh copy is held again: the consent was this database's, and the copy replaced it + copy(live.store, dev.store) + forgetOtherHosts(dev.payload) + expect(await sendThroughRelay(dev.payload, dev.options, MESSAGE)).toMatchObject({ cause: 'client-other-host', sent: false }) + // production never noticed any of it + expect((await readRelayStore(live.payload)).token).toBe(liveToken) + expect(service.requests.map((r) => r.path)).not.toContain('/v1/revoke') + expect((await sendThroughRelay(live.payload, liveOptions, { ...MESSAGE, subject: 'Live, still' })).sent).toBe(true) + }) + + test('a staging copy of production\'s data that says it is not public (IAPL_NOINDEX) does not enrol — 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 entry = JSON.stringify(production.store.get(`iapl:mail-relay:site:${HOST}`)) 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 + vi.stubEnv('IAPL_NOINDEX', '1') // the staging process const requests = production.fake.requests.length const held = await sendThroughRelay(staging.payload, staging.options, { ...MESSAGE, to: 'a-real-customer@example.org' }) 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 }) + expect(await mailPanelState({ payload: staging.payload }, staging.options)).toMatchObject({ nonPublic: true, relay: { connected: false, host: 'staging.example.com', refusal: { code: 'client-other-host', reason: HOST } } }) // "Disconnect" on the copy revokes nothing of production's - await disconnectRelay(untouched.payload, untouched.options) + await disconnectRelay(staging.payload, staging.options) expect(production.fake.requests.filter((r) => r.path === '/v1/revoke')).toEqual([]) - expect((await readRelayStore(production.payload)).token).toBe(token) + expect(JSON.stringify(production.store.get(`iapl:mail-relay:site:${HOST}`))).toBe(entry) // 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' }) @@ -741,7 +830,7 @@ describe('the token over time', () => { 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 + // also when its token is gone altogether (another container rotated it away) 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 @@ -750,36 +839,75 @@ describe('the token over time', () => { 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() + vi.stubEnv('IAPL_NOINDEX', '') // production's process 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 () => { + test('`www` and the bare domain are one site, also for a non-public one: neither holds the other', async () => { + const apex = shared({ options: DEV_HOSTS, serverURL: `https://${DEV}` }) + const www = apex.another(`https://www.${DEV}`, DEV_HOSTS) + expect(siteIsNonPublic(www.payload, www.options)).toBe(true) + for (const site of [apex, www, apex, www]) {expect((await sendThroughRelay(site.payload, site.options, MESSAGE)).sent).toBe(true)} + expect(apex.fake.requests.filter((r) => r.path === '/v1/enrol')).toHaveLength(2) + expect((await mailPanelState({ payload: www.payload }, www.options)).otherHostEntries).toBeUndefined() + // the launched site names the development address once, with or without `www.`: both forms count + const live = apex.another('https://www.client.pl', { otherHosts: [`www.${DEV}`] }) + expect((await sendThroughRelay(live.payload, live.options, MESSAGE)).sent).toBe(true) + expect((await mailPanelState({ payload: live.payload }, live.options)).otherHostEntries).toBeUndefined() + }) + + test('what remains possible: a staging copy that forgot to say it is not public enrols and sends like a launch — the panel state and the doctor name it', async () => { + const production = shared() + await sendThroughRelay(production.payload, production.options, MESSAGE) + const staging = production.another('https://staging.example.com') // no IAPL_NOINDEX, no development host + const sent = await sendThroughRelay(staging.payload, staging.options, { ...MESSAGE, to: 'a-real-customer@example.org' }) + expect(sent).toMatchObject({ sent: true }) // the plugin cannot tell this from launch day + expect(await mailPanelState({ payload: staging.payload }, staging.options)).toMatchObject({ otherHostEntries: true, relay: { connected: true } }) + expect((await mailPanelState({ payload: staging.payload }, staging.options)).nonPublic).toBeUndefined() + // the same site once it says so: held from the next e-mail on, although it has a token by now + vi.stubEnv('IAPL_NOINDEX', '1') + forgetOtherHosts(staging.payload) + expect(await sendThroughRelay(staging.payload, staging.options, MESSAGE)).toMatchObject({ cause: 'client-other-host', sent: false }) + }) + + test('a domain move needs nobody; `otherHosts` — \'wait\', \'enrol\', the site\'s own hosts; the rule ends when its reason does', async () => { const old = shared() await sendThroughRelay(old.payload, old.options, MESSAGE) - // the same data under a new domain: waits by default … + // the same data under a new, public host: enrols by itself 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(moved.payload, moved.options, MESSAGE)).sent).toBe(true) + expect(old.fake.outbox.at(-1)?.host).toBe('example.org') + // 'wait': the rule of the first cut — a public site without a connection of its own waits too + const waiting = old.another('https://example.net', { otherHosts: 'wait' }) + expect(await sendThroughRelay(waiting.payload, waiting.options, MESSAGE)).toMatchObject({ cause: 'client-other-host', sent: false }) + // ('wait' holds a site WITHOUT a connection: the old domain, connected long ago, sends on beside the new hosts) + expect((await sendThroughRelay(old.payload, { ...old.options, otherHosts: 'wait' }, MESSAGE)).sent).toBe(true) + // …and the wait ends at once when the project names the other hosts as the site's own (no cool-down in the way) + const named = { ...waiting.options, otherHosts: ['example.com', 'www.example.org'] } + expect((await sendThroughRelay(waiting.payload, named, MESSAGE)).sent).toBe(true) + expect((await readRelayStore(waiting.payload, 'example.net')).refusal).toBeFalsy() + // a non-public copy with 'enrol': the project took the rule away + const any = old.another('https://copy.dev.agency-example.com', { ...DEV_HOSTS, 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) + // a non-public copy that names SOME hosts as its own still stops for the others + const partly = old.another('https://two.dev.agency-example.com', { ...DEV_HOSTS, otherHosts: ['example.com'] }) + expect(await sendThroughRelay(partly.payload, partly.options, MESSAGE)).toMatchObject({ cause: 'client-other-host', sent: false }) + // …the panel shows that refusal from the store, and drops it the moment its reason is gone (no send needed) + expect((await mailPanelState({ payload: partly.payload }, partly.options)).relay?.refusal).toMatchObject({ code: 'client-other-host' }) + expect((await readRelayStore(partly.payload, 'two.dev.agency-example.com')).refusal).toMatchObject({ code: 'client-other-host' }) + expect((await mailPanelState({ payload: partly.payload }, { ...partly.options, otherHosts: 'enrol' })).relay?.refusal).toBeUndefined() + // …and one that names ALL of them (with or without `www.`) sends by itself + const others = (await otherRelayHosts(partly.payload, 'two.dev.agency-example.com')).map((h) => (h === 'example.com' ? 'www.example.com' : h)) + expect(others.length).toBeGreaterThan(2) + expect((await sendThroughRelay(partly.payload, { ...partly.options, otherHosts: others }, MESSAGE)).sent).toBe(true) + expect(siteIsNonPublic(partly.payload, { developmentHosts: ['*.dev.other.example', 'two.dev.agency-exam*'], host: undefined })).toBe(true) + expect(siteIsNonPublic(partly.payload, { developmentHosts: ['dev.agency-example.com', '*.agency-example'], host: undefined })).toBe(false) }) })