From 14abf369dacd50b7c089901cdea7254a74749e1e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rados=C5=82aw=20Smoli=C5=84ski?= Date: Thu, 26 Nov 2026 10:26:12 +0100 Subject: [PATCH] Mail relay: development hosts are known by pattern, with no env - built in: *.dev.netscale.pl The launch rule called a site non-public only when IAPL_NOINDEX was set (or the project named its hosts). The owner's development sites set nothing, so production's database copied onto a development address counted as a launch and would have mailed real people. - iapl({ developmentHosts }): host patterns of development addresses. Default DEFAULT_DEVELOPMENT_HOSTS = ['*.dev.netscale.pl'], Intecion's own development domain; a project replaces the list or empties it. mail.relay.developmentHosts overrides it for the mail service. - a site whose host matches is non-public exactly as with IAPL_NOINDEX=1; either signal is enough - siteNonPublicSignal, matchDevelopmentHost, isDevelopmentHost, pluginDevelopmentHosts exported - panel state: nonPublicBy, nonPublicPattern; doctor: mail-non-public (info) names the signal - every case of the launch table runs with no env on the built-in pattern - docs, AGENT.md, skills, changelog draft Co-Authored-By: Claude Fable 5.2 --- docs/CHANGELOG.md | 9 ++- docs/agent/AGENT.md | 16 ++-- docs/agent/skills/iapl-debug/SKILL.md | 4 +- docs/agent/skills/iapl-setup/SKILL.md | 2 +- docs/agent/skills/iapl-upgrade/SKILL.md | 7 +- docs/deployment.md | 6 +- docs/doctor.md | 1 + docs/email.md | 38 ++++++--- docs/security.md | 2 +- reference/.agents/skills/iapl-debug/SKILL.md | 4 +- reference/.agents/skills/iapl-setup/SKILL.md | 2 +- .../.agents/skills/iapl-upgrade/SKILL.md | 7 +- src/index.ts | 7 +- src/modules/doctor/rules/mail.ts | 31 +++++++- src/modules/doctor/status.ts | 2 +- src/modules/doctor/types.ts | 3 + src/modules/email/relay/index.ts | 17 ++-- src/modules/email/relay/options.ts | 24 ++++-- src/modules/email/relay/panel.ts | 13 ++-- src/modules/email/relay/session.ts | 32 +++++--- src/modules/shared/developmentHosts.ts | 44 +++++++++++ src/plugin.ts | 2 +- src/types.ts | 14 +++- test/doctor.test.ts | 24 +++++- test/mailRelay.test.ts | 77 +++++++++++++++++-- test/plugin.test.ts | 11 +++ 26 files changed, 319 insertions(+), 80 deletions(-) create mode 100644 src/modules/shared/developmentHosts.ts diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md index 081f916..9a8df66 100644 --- a/docs/CHANGELOG.md +++ b/docs/CHANGELOG.md @@ -41,7 +41,7 @@ once there are more than 20. | `GRAPH_*` set, "Sending method" on SMTP, no SMTP server (mail failed until now) | Mail goes through Graph | fill in SMTP, or remove the variables | | Neither (mail failed until now with "not configured") | **An outbound call:** on the next e-mail the site enrols with the service — `POST https://webservices.intecion.net/mail/v1/enrol` with its host and the plugin version — and then sends through it, from `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 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 copy** of a site's database on a non-public site — a host that matches `developmentHosts` (built in: `*.dev.netscale.pl`, Intecion's development domain; no env needed) or one with `IAPL_NOINDEX=1` (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 on another host without the variable 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 | @@ -104,6 +104,13 @@ once there are more than 20. unless Intecion set others); `mailAttachmentLimit` reports the latter. - **Plugin option `mail`**: `mail: { relay: false | { url, host, enrol, token, senderName, kind, accountMail, confirmRateLimit, accessKeyField, otherHosts, developmentHosts, totalTimeoutMs, timeoutMs, retryBackoffMs, fetchImpl }, graphDeprecationWarning }`; `mailAdapter({ relay })`. +- **Plugin option `developmentHosts`** (default `DEFAULT_DEVELOPMENT_HOSTS` = `['*.dev.netscale.pl']`): host patterns + of development, preview and staging addresses. A site whose own host matches is non-public **with no environment + variable**: holding a copy of another site's data, it does not mail real people by itself (the table above). + `*.dev.netscale.pl` is Intecion's own development domain, where the team's sites are built before launch; a + project replaces the list with its own patterns or empties it (`[]`). Building blocks: `matchDevelopmentHost`, + `isDevelopmentHost`, `pluginDevelopmentHosts`, `siteIsNonPublic`, `siteNonPublicSignal` (`NonPublicSignal`). + Doctor: `mail-non-public` (info, deep) names the signal that makes a site non-public. - **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 diff --git a/docs/agent/AGENT.md b/docs/agent/AGENT.md index 22cb5c6..053162c 100644 --- a/docs/agent/AGENT.md +++ b/docs/agent/AGENT.md @@ -1290,14 +1290,16 @@ the mail service → nothing (`mail: { relay: false }` and no SMTP). A site with approval, is the exception — the panel says so). 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 + whose host matches `iapl({ developmentHosts })` — default `['*.dev.netscale.pl']`, Intecion's development + domain, so the team's development addresses need **no env and no option**; replace the list with the project's + own patterns, `[]` empties it — or that has `IAPL_NOINDEX=1`, and 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`, + enrols nor sends until an admin presses "Connect again". **A copy on another host without `IAPL_NOINDEX=1` 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 + must never send: `mail: { relay: false }` or SMTP to a catcher. If the project's copies live on other hosts than + `*.dev.netscale.pl`, name them in `developmentHosts`. The doctor's deep run says which signal applies + (`mail-non-public`). 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 @@ -1332,7 +1334,7 @@ overrides per adapter; `resolveRelayOptions` reads what is in effect): | `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` | `'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`) | +| `developmentHosts` | `iapl({ developmentHosts })`, default `DEFAULT_DEVELOPMENT_HOSTS` = `['*.dev.netscale.pl']` (`pluginDevelopmentHosts`) | host patterns (`*`) of development and staging addresses, for the mail service alone: a site there is non-public for `otherHosts` with no env (`siteIsNonPublic`, `siteNonPublicSignal` → `NonPublicSignal`, `matchDevelopmentHost`, `isDevelopmentHost`); `[]` = none | | `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 8407441..3fb1e8e 100644 --- a/docs/agent/skills/iapl-debug/SKILL.md +++ b/docs/agent/skills/iapl-debug/SKILL.md @@ -102,8 +102,8 @@ through this procedure. Ask only when you are missing something you cannot get y | `relay-refused` / "The mail service could not reach this site at …" (cause `callback-failed`) | `unreachable` / `timeout`: firewall, private network, wrong public host in `serverURL`; `redirect`: `trailingSlash: true`, apex → `www`, a language redirect; `status`: route blocked, missing (`mail: { relay: false }`?) or another `routes.api`; `confirmation`: a proxy rewrites the answer | `curl -i -X POST https:///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 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 | +| 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 is non-public — its host matches `developmentHosts` (built in: `*.dev.netscale.pl`) or `IAPL_NOINDEX=1` is set; `iapl-doctor --deep` says which (`mail-non-public`) — 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; or its host matches a development pattern — take it out of `iapl({ developmentHosts })` | +| a staging or test copy **does** send, to real addresses | its host matches no development pattern and it has no `IAPL_NOINDEX=1`, 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" | name its host in `iapl({ developmentHosts: ['*.dev.netscale.pl', ''] })`, or `IAPL_NOINDEX=1` on the copy; 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 6db9a23..c8584be 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 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 + 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 is non-public (its host matches `developmentHosts`, built in `*.dev.netscale.pl`, or `IAPL_NOINDEX=1`) 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 development address under `*.dev.netscale.pl` needs nothing; a staging or test copy on any other host must have its host in `iapl({ developmentHosts: […] })` or `IAPL_NOINDEX=1`, 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 76868dc..4805138 100644 --- a/docs/agent/skills/iapl-upgrade/SKILL.md +++ b/docs/agent/skills/iapl-upgrade/SKILL.md @@ -575,9 +575,10 @@ PROGRAMISTA §6, item 73; email.md; AGENT.md §7.2) — nothing to run; read whi processing agreement names the service. Nothing to arrange with Intecion: the site is active as soon as it enrols. **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 + **when it is non-public**: its host matches `iapl({ developmentHosts })` — built in `*.dev.netscale.pl`, so the + team's development addresses need no env and no edit; add the project's other copy hosts to the list — or it + has `IAPL_NOINDEX=1`. The panel says so until an admin presses "Connect again"; `iapl-doctor --deep` names the + signal (`mail-non-public`). A copy on another host without the variable 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 diff --git a/docs/deployment.md b/docs/deployment.md index f6508fe..9c7677c 100644 --- a/docs/deployment.md +++ b/docs/deployment.md @@ -59,10 +59,10 @@ Mail needs **no variable**. A site with no SMTP server in the panel sends throug 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 + production's database** on a non-public site — a host that matches `iapl({ developmentHosts })` (built in: + `*.dev.netscale.pl`, Intecion's development domain; **no env needed**) or one with `IAPL_NOINDEX=1` — 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 + production's connection. **A copy on another host without `IAPL_NOINDEX=1` 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"). diff --git a/docs/doctor.md b/docs/doctor.md index a20d5e3..563089e 100644 --- a/docs/doctor.md +++ b/docs/doctor.md @@ -113,6 +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-non-public` | info | (deep) on the mail service: says which signal makes the site a non-public copy — its host matches a development pattern (`developmentHosts`, named in the finding) or `IAPL_NOINDEX` is set — and what to change if the site is in fact the public one | | | `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 | diff --git a/docs/email.md b/docs/email.md index 246e37c..94bd78b 100644 --- a/docs/email.md +++ b/docs/email.md @@ -262,8 +262,8 @@ await runWithMailKind('account', () => sendWelcomeMails(payload, user)) 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'] } }`** + tells the two apart by **direction**: a site that is **not public** — its host matches a development pattern, or + `IAPL_NOINDEX=1` is set; either is enough (see "Which sites are non-public" below) — 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. @@ -272,7 +272,21 @@ await runWithMailKind('account', () => sendWelcomeMails(payload, user)) - **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. + e-mail, on a development address too — clients test their forms there. + +**Which sites are non-public.** No environment variable is needed: + +- **By host, from code.** `iapl({ developmentHosts })` is a list of host patterns (`*` = any characters; the whole + host must match). Its default is `DEFAULT_DEVELOPMENT_HOSTS` = **`['*.dev.netscale.pl']`**. That name is in the + plugin on purpose: it is Intecion's own development domain, every site of the team is built at + `.dev.netscale.pl` before it moves to its real domain, and nothing in those sites' environments marks them + as development copies — with the pattern built in they are protected without an edit. It is a default like any + other: **replace it** with your own patterns (`developmentHosts: ['*.preview.agency.example', 'staging.client.pl']`), + or pass **`[]`** so that no host is a development address. `mail: { relay: { developmentHosts } }` overrides the + list for the mail service alone. +- **By the variable.** `IAPL_NOINDEX=1` marks any other staging, preview or test copy. +- The panel state (`nonPublicBy`, `nonPublicPattern`), `siteNonPublicSignal(payload)` and the doctor + (`mail-non-public`) say which of the two applies. | The site | Public? | Its database holds | By itself | |---|---|---|---| @@ -280,16 +294,20 @@ await runWithMailKind('account', () => sendWelcomeMails(payload, user)) | 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" | +| staging / test copy of production on a development host, or with `IAPL_NOINDEX=1` | 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 | +| a copy on a host **outside** the development patterns, without `IAPL_NOINDEX` | 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 copy on a host that matches no development pattern and has no `IAPL_NOINDEX=1` 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`). A project + whose copies live elsewhere than `*.dev.netscale.pl` names its own patterns in `developmentHosts`. + - A project that empties the list (`developmentHosts: []`) has only `IAPL_NOINDEX` left as a mark. + - A **public** site served on a host that matches a development pattern is treated as a development address: + it sends its own mail, but after a copy of another site's data it waits for "Connect again". Take the host out + of the list. - 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"). @@ -381,7 +399,7 @@ message); "Connect again" asks at once. Other causes: `host-not-allowed` (not a | `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` | `'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)`) | +| `developmentHosts` | the plugin's list: `iapl({ developmentHosts })`, default `['*.dev.netscale.pl']` (`pluginDevelopmentHosts(payload)`) | host patterns (`*` = any characters) of development, staging and preview addresses, for the mail service alone: a site on such a host is non-public for `otherHosts`, like one with `IAPL_NOINDEX=1`, with no environment variable (`siteIsNonPublic`, `siteNonPublicSignal`, `matchDevelopmentHost`, `isDevelopmentHost`). `[]` = none | | `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 b18b895..6697c5b 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 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 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 non-public copy (a host that matches `developmentHosts` — built in: `*.dev.netscale.pl`, no env needed — or `IAPL_NOINDEX=1`) **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 on a host outside those patterns, without the variable, 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 8407441..3fb1e8e 100644 --- a/reference/.agents/skills/iapl-debug/SKILL.md +++ b/reference/.agents/skills/iapl-debug/SKILL.md @@ -102,8 +102,8 @@ through this procedure. Ask only when you are missing something you cannot get y | `relay-refused` / "The mail service could not reach this site at …" (cause `callback-failed`) | `unreachable` / `timeout`: firewall, private network, wrong public host in `serverURL`; `redirect`: `trailingSlash: true`, apex → `www`, a language redirect; `status`: route blocked, missing (`mail: { relay: false }`?) or another `routes.api`; `confirmation`: a proxy rewrites the answer | `curl -i -X POST https:///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 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 | +| 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 is non-public — its host matches `developmentHosts` (built in: `*.dev.netscale.pl`) or `IAPL_NOINDEX=1` is set; `iapl-doctor --deep` says which (`mail-non-public`) — 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; or its host matches a development pattern — take it out of `iapl({ developmentHosts })` | +| a staging or test copy **does** send, to real addresses | its host matches no development pattern and it has no `IAPL_NOINDEX=1`, 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" | name its host in `iapl({ developmentHosts: ['*.dev.netscale.pl', ''] })`, or `IAPL_NOINDEX=1` on the copy; 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 6db9a23..c8584be 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 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 + 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 is non-public (its host matches `developmentHosts`, built in `*.dev.netscale.pl`, or `IAPL_NOINDEX=1`) 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 development address under `*.dev.netscale.pl` needs nothing; a staging or test copy on any other host must have its host in `iapl({ developmentHosts: […] })` or `IAPL_NOINDEX=1`, 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 76868dc..4805138 100644 --- a/reference/.agents/skills/iapl-upgrade/SKILL.md +++ b/reference/.agents/skills/iapl-upgrade/SKILL.md @@ -575,9 +575,10 @@ PROGRAMISTA §6, item 73; email.md; AGENT.md §7.2) — nothing to run; read whi processing agreement names the service. Nothing to arrange with Intecion: the site is active as soon as it enrols. **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 + **when it is non-public**: its host matches `iapl({ developmentHosts })` — built in `*.dev.netscale.pl`, so the + team's development addresses need no env and no edit; add the project's other copy hosts to the list — or it + has `IAPL_NOINDEX=1`. The panel says so until an admin presses "Connect again"; `iapl-doctor --deep` names the + signal (`mail-non-public`). A copy on another host without the variable 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 diff --git a/src/index.ts b/src/index.ts index 213874e..f39f4ac 100644 --- a/src/index.ts +++ b/src/index.ts @@ -238,6 +238,7 @@ export { MAIL_KIND, MAIL_KINDS, mailKindOf, + pluginDevelopmentHosts, RELAY_BASE_URL, RELAY_CONFIRM_PATH, RELAY_CONTRACT_VERSION, @@ -261,6 +262,7 @@ export { sendThroughRelay, setRelayToken, siteIsNonPublic, + siteNonPublicSignal, withMailKind, } from './modules/email/relay/index.js' export type { @@ -268,6 +270,7 @@ export type { BuiltRelayMessage, EnrolResult, MailKind, + NonPublicSignal, RelayAdapterArgs, RelayAnswer, RelayCall, @@ -428,7 +431,6 @@ export { UPLOAD_SECURITY_HEADERS, withSecurityConfig, } from './modules/security/index.js' - export type { BuildAdminCspArgs, BuildCspArgs, @@ -440,6 +442,7 @@ export type { TotpUser, WithSecurityConfigOptions, } from './modules/security/index.js' + export type { BuildSecurityHeadersArgs, SecurityHeader } from './modules/security/index.js' export { findImportMapFile, missingImportMapEntries } from './modules/security/totp/importMapCheck.js' export { changedViewKeys, copyViews, SAFE_TOTP_VIEW, safeAdminBack, totpViewImportKey, wrapTotpViews } from './modules/security/totp/safeBack.js' @@ -515,6 +518,8 @@ export { buildSitemapCss, buildSitemapIndexXml, buildSitemapXml, DEFAULT_SITEMAP export type { SitemapRouteOptions, SitemapStyleOptions } from './modules/seo/index.js' export { applyCollectionOverride } from './modules/shared/collectionOverride.js' export type { CollectionOverride } from './modules/shared/collectionOverride.js' +// Development addresses by pattern (no env): the built-in list and the matcher behind `developmentHosts`. +export { DEFAULT_DEVELOPMENT_HOSTS, isDevelopmentHost, matchDevelopmentHost } from './modules/shared/developmentHosts.js' export { clientIp, setRateLimitStore, setUnknownIpFactor, UNKNOWN_IP_FACTOR } from './modules/shared/rateLimit.js' export type { ClientIpOptions, RateLimitStore } from './modules/shared/rateLimit.js' export { buildSlugField, toSlug } from './modules/slug/index.js' diff --git a/src/modules/doctor/rules/mail.ts b/src/modules/doctor/rules/mail.ts index d18b689..c2981cb 100644 --- a/src/modules/doctor/rules/mail.ts +++ b/src/modules/doctor/rules/mail.ts @@ -15,6 +15,14 @@ const since = (iso?: null | string) => (iso ? `, since ${iso.slice(0, 16).replac * Intecion Notifications Webservice, the deprecated Graph transport, the reply address, and whether * the service can reach the site's confirm route. Ids carry no brand, like `agents-md`. */ +/** "this site is non-public because …" — the signal named, for the findings that depend on it. */ +const nonPublicBecause = (mail: { nonPublicBy?: 'development-host' | 'noindex'; nonPublicPattern?: string }): string => + mail.nonPublicBy === 'noindex' + ? 'this site is non-public because IAPL_NOINDEX is set' + : mail.nonPublicBy === 'development-host' + ? `this site is non-public because its host matches the development pattern "${mail.nonPublicPattern ?? '?'}" (developmentHosts)` + : 'this site is non-public (a development host, or IAPL_NOINDEX)' + export const mailRules: DoctorRule[] = [ { // Which transport a send takes right now, and whether the last sends worked. @@ -45,6 +53,25 @@ export const mailRules: DoctorRule[] = [ group: 'mail', source: 'deep', }, + { + // Which signal makes the site a non-public copy for the mail service — said plainly, because that signal + // decides whether a copy of another site's data mails real people. + id: 'mail-non-public', + check: (ctx) => { + const mail = ctx.deep?.mail + if (!mail || mail.transport !== 'relay' || !mail.relay || !mail.nonPublic) {return []} + return [{ + fix: mail.nonPublicBy === 'noindex' + ? 'right for a development, staging or test copy. On the PUBLIC site this is a mistake: remove IAPL_NOINDEX there (it also keeps the site out of search engines)' + : 'right for a development address. If this host is the PUBLIC site, take it out of the list: iapl({ developmentHosts: [...] }) (`[]` = no development hosts)', + message: `${nonPublicBecause(mail)}: for the Intecion mail service it is a non-public site — it sends its own e-mails, but with a copy of another site's data it sends nothing by itself`, + severity: 'info', + }] + }, + docs: 'docs/email.md', + group: 'mail', + source: 'deep', + }, { // The site's state with the Intecion mail service, when that is how it sends. id: 'mail-relay-state', @@ -61,8 +88,8 @@ export const mailRules: DoctorRule[] = [ 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.refusal === 'client-other-host') { out.push({ - 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`, + 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, or take the host out of iapl({ developmentHosts })', + message: `${nonPublicBecause(mail)} 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) { diff --git a/src/modules/doctor/status.ts b/src/modules/doctor/status.ts index 743e175..0475715 100644 --- a/src/modules/doctor/status.ts +++ b/src/modules/doctor/status.ts @@ -71,7 +71,7 @@ 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"). + * Whether this site counts as a non-public copy for `mail.relay.otherHosts`: its host matches a development + * pattern (`developmentHosts`; built in: `*.dev.netscale.pl`), or `IAPL_NOINDEX=1`. 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 ?? {})) + +/** Which signal says so — `{ by: 'development-host', pattern }` or `{ by: 'noindex' }` — or null for a public site. */ +export const siteNonPublicSignal = (payload: BasePayload, options?: RelayOptions): NonPublicSignal | null => + nonPublicSignal(payload, resolveRelayOptions(payload, options) || (options ?? {})) diff --git a/src/modules/email/relay/options.ts b/src/modules/email/relay/options.ts index 4e1f518..7d89d4f 100644 --- a/src/modules/email/relay/options.ts +++ b/src/modules/email/relay/options.ts @@ -2,6 +2,7 @@ import type { BasePayload, SendEmailOptions } from 'payload' import type { MailKind } from './kinds.js' +import { DEFAULT_DEVELOPMENT_HOSTS } from '../../shared/developmentHosts.js' import { RELAY_BASE_URL } from './constants.js' /** @@ -25,9 +26,11 @@ export type RelayOptions = { /** 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. + * Host patterns of development and preview addresses (`*` = any characters), for the mail service only. + * Default: the plugin's list — `iapl({ developmentHosts })`, which itself defaults to + * `DEFAULT_DEVELOPMENT_HOSTS` (`['*.dev.netscale.pl']`, Intecion's own development domain). A site on such a + * host is treated as a non-public copy for `otherHosts`, exactly like a site with `IAPL_NOINDEX=1`; no + * environment variable is needed. `[]` = no host is a development address. */ developmentHosts?: string[] /** @@ -50,7 +53,7 @@ export type RelayOptions = { * 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 + * nobody. A **non-public** site (a host in `developmentHosts`, or `IAPL_NOINDEX=1`) 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". * @@ -84,7 +87,7 @@ export type RelayOptions = { url?: string } -export type ResolvedRelayOptions = { ownUrl: boolean; url: string } & Omit +export type ResolvedRelayOptions = { developmentHosts: string[]; ownUrl: boolean; url: string } & Omit type PluginMail = { graphDeprecationWarning?: boolean; relay?: false | RelayOptions } @@ -93,6 +96,15 @@ export function pluginMailOptions(payload: Pick): PluginM return ((payload.config?.custom as { iapl?: { mail?: PluginMail } } | undefined)?.iapl?.mail ?? {}) } +/** + * The plugin's development-host patterns: `iapl({ developmentHosts })` as left in the config + * (`config.custom.iapl.developmentHosts`), else the built-in list. + */ +export function pluginDevelopmentHosts(payload: Pick): string[] { + const own = (payload.config?.custom as { iapl?: { developmentHosts?: unknown } } | undefined)?.iapl?.developmentHosts + return Array.isArray(own) ? own.filter((p): p is string => typeof p === 'string') : [...DEFAULT_DEVELOPMENT_HOSTS] +} + /** * The options in effect: the adapter's own `relay` argument over the plugin option. `null` = the relay * is switched off. @@ -102,7 +114,7 @@ export function resolveRelayOptions(payload: Pick, own?: if (own === false || (own === undefined && fromPlugin === false)) {return null} const merged: RelayOptions = { ...(fromPlugin || {}), ...(own || {}) } const url = (merged.url ?? RELAY_BASE_URL).replace(/\/+$/, '') - return { ...merged, ownUrl: url !== RELAY_BASE_URL, url } + return { ...merged, developmentHosts: merged.developmentHosts ?? pluginDevelopmentHosts(payload), ownUrl: url !== RELAY_BASE_URL, url } } const LABEL = /^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/ diff --git a/src/modules/email/relay/panel.ts b/src/modules/email/relay/panel.ts index acd8e36..5b2d1ae 100644 --- a/src/modules/email/relay/panel.ts +++ b/src/modules/email/relay/panel.ts @@ -11,7 +11,7 @@ import { RELAY_SENDER_ADDRESS } from './adapter.js' import { relayRequest } from './client.js' import { RELAY_CONFIRM_PATH, RELAY_CONNECT_PATH, RELAY_DISCONNECT_PATH, RELAY_STATUS_PATH } from './constants.js' import { isPublicHost, relayHost, resolveRelayOptions } from './options.js' -import { disconnectRelay, enrolRelay, type EnrolResult, getRelayStatus, LOCAL_CODES, otherHostsInTheWay, readSiteStore, type RelayStatus, setRelayToken, siteIsNonPublic } from './session.js' +import { disconnectRelay, enrolRelay, type EnrolResult, getRelayStatus, LOCAL_CODES, type NonPublicSignal, otherHostsInTheWay, readSiteStore, type RelayStatus, setRelayToken, siteNonPublicSignal } from './session.js' import { otherRelayHosts } from './store.js' type Settings = { @@ -29,8 +29,11 @@ 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`). */ + /** The site is not public: its host is a development address (`developmentHosts`), or `IAPL_NOINDEX` is set. */ nonPublic?: boolean + /** Which signal says so; with `development-host`, `nonPublicPattern` is the pattern that matched. */ + nonPublicBy?: NonPublicSignal['by'] + nonPublicPattern?: string /** 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`). */ @@ -67,10 +70,10 @@ export async function mailPanelState(req: Pick, own: } // …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 signal: NonPublicSignal | null = null let otherHostEntries = false if (status && options && options.token === undefined) { - nonPublic = siteIsNonPublic(payload, options) + signal = siteNonPublicSignal(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 @@ -87,7 +90,7 @@ 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 } : {}), + ...(signal ? { nonPublic: true, nonPublicBy: signal.by, ...(signal.by === 'development-host' ? { nonPublicPattern: signal.pattern } : {}) } : {}), ...(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 e08fec4..483ee7b 100644 --- a/src/modules/email/relay/session.ts +++ b/src/modules/email/relay/session.ts @@ -2,13 +2,14 @@ import type { BasePayload } from 'payload' import { randomBytes } from 'node:crypto' -import type { ResolvedRelayOptions } from './options.js' +import type { RelayOptions, ResolvedRelayOptions } from './options.js' import { PLUGIN_VERSION } from '../../../version.js' import { isSiteNoindex } from '../../seo/siteNoindex.js' +import { matchDevelopmentHost } from '../../shared/developmentHosts.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' +import { isPublicHost, pluginDevelopmentHosts, pluginMailOptions, relayHost } from './options.js' import * as store from './store.js' import { otherRelayHosts, type RelaySiteState, type RelayStored, releaseNonce, sha256Hex } from './store.js' @@ -95,17 +96,24 @@ async function otherHostsNow(payload: BasePayload, host: string, fresh: boolean) const bare = (host: string) => host.trim().toLowerCase().replace(/^www\./, '') +/** Why a site counts as non-public: its host matches a development pattern, or `IAPL_NOINDEX` is set. */ +export type NonPublicSignal = { by: 'development-host'; pattern: string } | { by: 'noindex' } + /** - * 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`. + * Which signal makes this site a non-public copy — a development, preview or staging address — or null for a + * public site. Either is enough: its host matches a development pattern (`mail.relay.developmentHosts`, else + * `iapl({ developmentHosts })`, else the built-in list — no environment variable needed), or `IAPL_NOINDEX=1`. + * The host is named first: it is the signal a site has without anybody setting anything. */ -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) - }) +export function siteNonPublicSignal(payload: BasePayload, options: Pick): NonPublicSignal | null { + const pattern = matchDevelopmentHost(relayHost(payload, options), options.developmentHosts ?? pluginDevelopmentHosts(payload)) + if (pattern) {return { by: 'development-host', pattern }} + return isSiteNoindex() ? { by: 'noindex' } : null +} + +/** Is this site a non-public copy (`siteNonPublicSignal` as a yes or no)? */ +export function siteIsNonPublic(payload: BasePayload, options: Pick): boolean { + return siteNonPublicSignal(payload, options) !== null } /** @@ -135,7 +143,7 @@ export async function otherHostsInTheWay( } 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).` + `This database holds the mail-service connection of another site (${foreign.join(', ')}), and this site ("${host}") is a non-public copy (a development host, or IAPL_NOINDEX) 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) diff --git a/src/modules/shared/developmentHosts.ts b/src/modules/shared/developmentHosts.ts new file mode 100644 index 0000000..3a6383f --- /dev/null +++ b/src/modules/shared/developmentHosts.ts @@ -0,0 +1,44 @@ +/** + * Development addresses, known by pattern — no environment variable needed. + * + * A site whose own host matches one of these patterns is a development, preview or staging address: not the + * public site. The plugin uses that for one decision today: such a site, when its database holds the mail-service + * connection of ANOTHER host, is a copy of that site's data and does not mail real people by itself + * (docs/email.md "Staging, copies and several hosts"). + * + * Why a name is built in: `*.dev.netscale.pl` is Intecion's own development domain. Every site the team builds + * starts there (`.dev.netscale.pl`) and moves to its real domain at launch, and nothing in those sites' + * environments marks them as development copies. With the pattern in the plugin they are protected without an + * edit or an env step. It is a default like any other: `iapl({ developmentHosts: [...] })` replaces the list, + * `[]` empties it, and another agency names its own pattern there. + */ +export const DEFAULT_DEVELOPMENT_HOSTS: readonly string[] = ['*.dev.netscale.pl'] + +/** Lowercase host of a URL or a bare host (`https://Acme.dev.example.pl/x` → `acme.dev.example.pl`); '' when unreadable. Keeps the port. */ +export function hostOf(value: null | string | undefined): string { + const raw = (value ?? '').trim() + if (!raw) {return ''} + try { + return new URL(/^[a-z][a-z0-9+.-]*:\/\//i.test(raw) ? raw : `https://${raw}`).host.toLowerCase() + } catch { + return '' + } +} + +/** + * The pattern that makes `host` a development address, or null. `*` stands for any characters (dots included); + * a pattern without `*` must equal the host. The whole host must match; a port is not part of it. + */ +export function matchDevelopmentHost(host: null | string | undefined, patterns: readonly string[] = DEFAULT_DEVELOPMENT_HOSTS): null | string { + const name = hostOf(host).replace(/:\d+$/, '') + if (!name) {return null} + for (const pattern of patterns) { + const source = pattern.trim().toLowerCase().split('*').map((part) => part.replace(/[.+?^${}()|[\]\\]/g, '\\$&')).join('.*') + if (source && new RegExp(`^${source}$`).test(name)) {return pattern} + } + return null +} + +/** Is `host` a development address (`matchDevelopmentHost` as a yes or no)? */ +export const isDevelopmentHost = (host: null | string | undefined, patterns: readonly string[] = DEFAULT_DEVELOPMENT_HOSTS): boolean => + matchDevelopmentHost(host, patterns) !== null diff --git a/src/plugin.ts b/src/plugin.ts index 160884a..0cc8df9 100644 --- a/src/plugin.ts +++ b/src/plugin.ts @@ -756,7 +756,7 @@ export const iapl = (options: IaplOptions): Plugin => { const iaplCustom = (config.custom?.iapl ?? {}) as object config.custom = { ...config.custom, - iapl: { ...iaplCustom, mail: { ...(options.mail?.graphDeprecationWarning === false ? { graphDeprecationWarning: false } : {}), relay: relay === false ? false : (relay ?? {}) } }, + iapl: { ...iaplCustom, ...(Array.isArray(options.developmentHosts) ? { developmentHosts: [...options.developmentHosts] } : {}), mail: { ...(options.mail?.graphDeprecationWarning === false ? { graphDeprecationWarning: false } : {}), relay: relay === false ? false : (relay ?? {}) } }, } // "Forgot password" and "verify your e-mail" through mailAdapter(): sent right after their transaction // commits, not inside it (mail.accountMailAfterCommit; docs/deployment.md §4.3a). diff --git a/src/types.ts b/src/types.ts index 9d111a4..9eade1c 100644 --- a/src/types.ts +++ b/src/types.ts @@ -133,6 +133,18 @@ export type IaplOptions = { */ dashboardAlerts?: { cookies?: 'all' | 'editor'; integrations?: 'admin' | 'all' | 'editor' } + /** + * Host patterns of the project's development, preview and staging addresses (`*` = any characters). + * Default: `DEFAULT_DEVELOPMENT_HOSTS` — `['*.dev.netscale.pl']`, Intecion's own development domain, + * where every site of the team is built before it moves to its real domain. A site whose own host + * matches is "non-public" with no environment variable: when its database holds the mail-service + * connection of another host (a copy of production's data), it does not mail real people by itself + * (docs/email.md "Staging, copies and several hosts"). Replace the list with your own patterns, or + * pass `[]` so that no host is a development address. `mail.relay.developmentHosts` overrides it + * for the mail service alone. + */ + developmentHosts?: string[] + /** * GET /api/ipal/doctor — read-only counts for `iapl-doctor --url` (users without 2FA, cookies * waiting for approval, versions). Answers 404 until IAPL_DOCTOR_TOKEN (≥ 32 characters) is set; @@ -147,7 +159,6 @@ export type IaplOptions = { * onInit work or admin components. */ enabled?: boolean - /** * Text written in one language fills the same field in every language that is * still empty; a language with its own text is never overwritten. Default on @@ -157,6 +168,7 @@ export type IaplOptions = { * Building blocks: buildFillEmptyLocalesGlobalHook / …CollectionHook. */ fillEmptyLocales?: { 'cookie-review'?: string[]; 'cookie-settings'?: string[] } | boolean + forms?: FormsOption /** diff --git a/test/doctor.test.ts b/test/doctor.test.ts index 3421c0a..b386ad5 100644 --- a/test/doctor.test.ts +++ b/test/doctor.test.ts @@ -661,7 +661,7 @@ describe('iapl-doctor: first-seen dates', () => { }) describe('e-mail: transport, the mail service, Graph, the confirm route', () => { - const ids = ['mail-transport', 'mail-relay-state', 'mail-reply-address', 'mail-graph-deprecated', 'mail-relay-route'] + const ids = ['mail-transport', 'mail-non-public', 'mail-relay-state', 'mail-reply-address', 'mail-graph-deprecated', 'mail-relay-route'] const relay = (extra: object = {}) => ({ connected: true, disconnected: false, nameReplaced: false, state: 'active', ...extra }) const mail = (extra: object = {}) => ({ graphEnv: false, relay: relay(), replyAddress: true, status: null, transport: 'relay', ...extra }) const run = async (deep: null | object, files: Record = {}) => @@ -692,14 +692,32 @@ describe('e-mail: transport, the mail service, Graph, the confirm route', () => expect(copy.findings[0].message).toContain('client.pl') 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']) + expect(await run(mail({ nonPublic: true, nonPublicBy: 'noindex', relay: relay({ reason: 'client.pl', refusal: 'client-other-host' }) }))).toEqual(['mail-relay-state:warning', 'mail-non-public:info']) // 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({ nonPublic: true, nonPublicBy: 'noindex', otherHostEntries: true }))).toEqual(['mail-non-public:info']) + }) + + test('mail-non-public: says which signal makes the site a non-public copy — the development pattern, or IAPL_NOINDEX', async () => { + const find = async (deep: object) => (await doctor(project({ ...base(), 'src/payload.config.ts': 'iapl({ forms: {} })' }), ids, { deepStatus: { mail: mail(deep) } })).findings + const byHost = await find({ nonPublic: true, nonPublicBy: 'development-host', nonPublicPattern: '*.dev.netscale.pl' }) + expect(byHost.map((f) => `${f.rule}:${f.severity}`)).toEqual(['mail-non-public:info']) + expect(byHost[0].message).toContain('its host matches the development pattern "*.dev.netscale.pl"') + expect(byHost[0].fix).toContain('developmentHosts') + const byEnv = await find({ nonPublic: true, nonPublicBy: 'noindex' }) + expect(byEnv[0].message).toContain('IAPL_NOINDEX is set') + expect(byEnv[0].fix).toContain('remove IAPL_NOINDEX') + // the copy warning names the same signal + const held = await find({ nonPublic: true, nonPublicBy: 'development-host', nonPublicPattern: '*.dev.netscale.pl', relay: relay({ reason: 'client.pl', refusal: 'client-other-host' }) }) + expect(held.map((f) => `${f.rule}:${f.severity}`)).toEqual(['mail-relay-state:warning', 'mail-non-public:info']) + expect(held[0].message).toContain('"*.dev.netscale.pl"') + // a public site, a site on SMTP: nothing + expect(await run(mail({}))).toEqual([]) + expect(await run(mail({ nonPublic: true, nonPublicBy: 'noindex', relay: relay({ connected: false, state: undefined }), replyAddress: false, transport: 'smtp' }))).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 104288b..22e382d 100644 --- a/test/mailRelay.test.ts +++ b/test/mailRelay.test.ts @@ -18,13 +18,14 @@ import { RELAY_DEFAULTS, RELAY_SHORT_NAME } from '../src/modules/email/relay/co 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 { isPublicHost, pluginDevelopmentHosts, 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, forgetOtherHosts, getRelayStatus, provesToken, refreshRelayStatus, rotateRelayToken, setRelayToken, siteIsNonPublic } from '../src/modules/email/relay/session.js' +import { disconnectRelay, enrolRelay, forgetOtherHosts, getRelayStatus, provesToken, refreshRelayStatus, rotateRelayToken, setRelayToken, siteIsNonPublic, siteNonPublicSignal } 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 { DEFAULT_DEVELOPMENT_HOSTS, isDevelopmentHost, matchDevelopmentHost } from '../src/modules/shared/developmentHosts.js' import { setRateLimitStore } from '../src/modules/shared/rateLimit.js' import { callConfirmRoute, relayPayload, relaySite } from './mailRelay/helpers.js' @@ -711,19 +712,25 @@ describe('the token over time', () => { }) // 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'] } + // development address is known by its host: the built-in pattern `*.dev.netscale.pl`, with NO environment + // variable and no option (every test here runs with IAPL_NOINDEX empty unless it says otherwise). + const DEV = 'acme.dev.netscale.pl' + const DEV_HOSTS = {} + const AGENCY = { 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(process.env.IAPL_NOINDEX).toBe('') expect(siteIsNonPublic(dev.payload, dev.options)).toBe(true) + expect(siteNonPublicSignal(dev.payload, dev.options)).toEqual({ by: 'development-host', pattern: '*.dev.netscale.pl' }) + expect(await mailPanelState({ payload: dev.payload }, dev.options)).toMatchObject({ nonPublic: true, nonPublicBy: 'development-host', nonPublicPattern: '*.dev.netscale.pl' }) 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(siteNonPublicSignal(noindex.payload, noindex.options)).toEqual({ by: 'noindex' }) + expect(await mailPanelState({ payload: noindex.payload }, noindex.options)).toMatchObject({ nonPublic: true, nonPublicBy: 'noindex' }) expect((await sendThroughRelay(noindex.payload, noindex.options, MESSAGE)).sent).toBe(true) }) @@ -849,6 +856,60 @@ describe('the token over time', () => { expect((await readRelayStore(production.payload)).token).toBe(token) }) + test('the development pattern is a default a project can replace or empty — the plugin option, the mail option, the matcher', async () => { + const at = (serverURL: string, custom?: object, own: Parameters[1] = {}) => { + const site = relayPayload({ custom, serverURL }) + return siteNonPublicSignal(site.payload, resolveRelayOptions(site.payload, own)!) + } + // built in: Intecion's development domain, any depth, any case, with a port; nothing that merely looks like it + expect(DEFAULT_DEVELOPMENT_HOSTS).toEqual(['*.dev.netscale.pl']) + expect(at('https://acme.dev.netscale.pl')).toEqual({ by: 'development-host', pattern: '*.dev.netscale.pl' }) + expect(at('https://WWW.Acme.dev.netscale.pl:8443/pl')).toEqual({ by: 'development-host', pattern: '*.dev.netscale.pl' }) + for (const url of ['https://client.pl', 'https://dev.netscale.pl', 'https://acme.dev.netscale.pl.evil.example', 'https://acme-dev.netscale.pl', 'https://netscale.pl', 'http://localhost:3000']) {expect(at(url)).toBeNull()} + // iapl({ developmentHosts }) replaces the list… + const own = { iapl: { developmentHosts: ['*.preview.agency-example.com', 'staging.client.pl'] } } + expect(at('https://x.preview.agency-example.com', own)).toEqual({ by: 'development-host', pattern: '*.preview.agency-example.com' }) + expect(at('https://staging.client.pl', own)).toEqual({ by: 'development-host', pattern: 'staging.client.pl' }) + expect(at('https://acme.dev.netscale.pl', own)).toBeNull() + expect(pluginDevelopmentHosts(relayPayload({ custom: own }).payload)).toEqual(own.iapl.developmentHosts) + // …`[]` empties it (the project's choice: then only IAPL_NOINDEX marks a copy)… + expect(at('https://acme.dev.netscale.pl', { iapl: { developmentHosts: [] } })).toBeNull() + // …and mail.relay.developmentHosts wins for the mail service + expect(at('https://acme.dev.netscale.pl', own, { developmentHosts: ['acme.*'] })).toEqual({ by: 'development-host', pattern: 'acme.*' }) + expect(at('https://acme.dev.netscale.pl', undefined, { developmentHosts: [] })).toBeNull() + // either signal is enough; the host is named first + vi.stubEnv('IAPL_NOINDEX', '1') + expect(at('https://client.pl')).toEqual({ by: 'noindex' }) + expect(at('https://acme.dev.netscale.pl')).toEqual({ by: 'development-host', pattern: '*.dev.netscale.pl' }) + vi.stubEnv('IAPL_NOINDEX', '') + // the matcher alone + expect(matchDevelopmentHost('https://a.dev.netscale.pl/x')).toBe('*.dev.netscale.pl') + expect(isDevelopmentHost('a.b.dev.netscale.pl')).toBe(true) + expect(isDevelopmentHost('a.dev.netscale.pl', [])).toBe(false) + expect(isDevelopmentHost('', ['*'])).toBe(false) + expect(matchDevelopmentHost('x.example.com', [' ', '*.Example.com '])).toBe('*.Example.com ') + + // what emptying the list means: production's data on the development address is then a "launch", and sends + const live = shared({ serverURL: 'https://client.pl' }) + await sendThroughRelay(live.payload, live.options, MESSAGE) + const copy = live.another(`https://${DEV}`) + expect(await sendThroughRelay(copy.payload, copy.options, MESSAGE)).toMatchObject({ cause: 'client-other-host', sent: false }) + expect((await sendThroughRelay(copy.payload, { ...copy.options, developmentHosts: [] }, MESSAGE)).sent).toBe(true) + }) + + test('a developer\'s `localhost` on the production database, no env: refused before any call, nothing written', async () => { + const production = shared({ serverURL: 'https://client.pl' }) + await sendThroughRelay(production.payload, production.options, MESSAGE) + const before = everything(production.store) + const requests = production.fake.requests.length + const local = production.another('http://localhost:3000') + const real = { ...local.options, ownUrl: false } + expect(siteNonPublicSignal(local.payload, real)).toBeNull() + expect(await sendThroughRelay(local.payload, real, { ...MESSAGE, to: 'a-real-customer@example.org' })).toMatchObject({ cause: 'host-not-allowed', code: 'relay-refused', sent: false }) + expect(production.fake.requests).toHaveLength(requests) + expect(everything(production.store)).toBe(before) + }) + 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) @@ -893,10 +954,10 @@ describe('the token over time', () => { 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' }) + const any = old.another('https://copy.dev.agency-example.com', { ...AGENCY, otherHosts: 'enrol' }) expect((await sendThroughRelay(any.payload, any.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'] }) + const partly = old.another('https://two.dev.agency-example.com', { ...AGENCY, 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' }) diff --git a/test/plugin.test.ts b/test/plugin.test.ts index 1b8c5dc..dd535e0 100644 --- a/test/plugin.test.ts +++ b/test/plugin.test.ts @@ -4,6 +4,7 @@ import { describe, expect, test, vi } from 'vitest' import type { I18nConfig } from '../src/modules/i18n/types.js' +import { pluginDevelopmentHosts } from '../src/modules/email/relay/options.js' import { iapl } from '../src/plugin.js' import { withTotpParts } from './helpers.js' @@ -22,6 +23,16 @@ const base = (): Config => }) as unknown as Config describe('iapl — config transform', () => { + test('developmentHosts: nothing in the config by default (the built-in list applies), the project\'s list when given, an empty list too', async () => { + const hosts = async (own?: string[]) => { + const config = await iapl({ access: { authCollection: 'users' }, i18n, twoFactor: false, ...(own ? { developmentHosts: own } : {}) })(base()) + return pluginDevelopmentHosts({ config } as never) + } + expect(await hosts()).toEqual(['*.dev.netscale.pl']) + expect(await hosts(['*.preview.agency-example.com'])).toEqual(['*.preview.agency-example.com']) + expect(await hosts([])).toEqual([]) + }) + test('adds globals, endpoint, localization and roles', async () => { const config = await iapl({ access: { authCollection: 'users' }, i18n, twoFactor: false })(base())