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 1/6] 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()) From bc3aac249f67fdff98d0561bde4ace69f531330f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rados=C5=82aw=20Smoli=C5=84ski?= Date: Thu, 26 Nov 2026 10:31:03 +0100 Subject: [PATCH 2/6] A development host is kept out of search engines without IAPL_NOINDEX (developmentNoindex, default on) Separate from the mail rule so that it can be taken or left. A site whose address matches iapl({ developmentHosts }) - built in: *.dev.netscale.pl - is noindex with no env: robots.txt disallows everything, pages carry noindex, IndexNow sends nothing, buildSecurityHeaders() adds X-Robots-Tag. Nothing kept a development copy out of search engines until now unless somebody set the variable. - iapl({ developmentNoindex: false }) switches it off for the project, IAPL_NOINDEX=0 for one environment - buildSecurityHeaders({ developmentHosts, serverUrl }): next.config runs before the plugin - the mail rule keeps its own two signals: the development pattern, and the variable itself - changelog "what changes on upgrade", deployment.md, security.md, AGENT.md, skills Co-Authored-By: Claude Fable 5.2 --- docs/CHANGELOG.md | 11 +++ docs/agent/AGENT.md | 2 +- docs/agent/skills/iapl-reference/SKILL.md | 2 +- docs/agent/skills/iapl-setup/SKILL.md | 2 +- docs/agent/skills/iapl-upgrade/SKILL.md | 5 ++ docs/deployment.md | 4 +- docs/security.md | 2 +- .../.agents/skills/iapl-reference/SKILL.md | 2 +- reference/.agents/skills/iapl-setup/SKILL.md | 2 +- .../.agents/skills/iapl-upgrade/SKILL.md | 5 ++ src/modules/email/relay/session.ts | 5 +- src/modules/security/buildSecurityHeaders.ts | 17 ++++- src/modules/seo/buildMetadata.ts | 2 +- src/modules/seo/buildRobots.ts | 4 +- src/modules/seo/indexNow.ts | 2 +- src/modules/seo/siteNoindex.ts | 46 +++++++++-- src/modules/shared/developmentHosts.ts | 18 +++++ src/plugin.ts | 2 + src/types.ts | 9 +++ test/indexNow.test.ts | 10 +++ test/mailRelay.test.ts | 4 + test/plugin.test.ts | 7 ++ test/seo.test.ts | 76 +++++++++++++++++++ 23 files changed, 215 insertions(+), 24 deletions(-) diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md index 9a8df66..8e82563 100644 --- a/docs/CHANGELOG.md +++ b/docs/CHANGELOG.md @@ -32,6 +32,15 @@ once there are more than 20. - **Nothing else has to be run.** The e-mail tab of Site integrations has a new block ("How e-mails are sent"); it is rendered by the status banner already in every import map, so `generate:importmap` gives no diff. No field was added; "Sending method" keeps its two stored values. +- **What changes for an existing site on upgrade — search engines, on a development host only:** a site whose + address (`NEXT_PUBLIC_SERVER_URL`) matches `iapl({ developmentHosts })` — built in: `*.dev.netscale.pl` — is now + **noindex without `IAPL_NOINDEX`**: robots.txt answers `Disallow: /`, every page carries `noindex, nofollow`, + `buildSecurityHeaders()` adds `X-Robots-Tag: noindex, nofollow`, IndexNow sends nothing. Until now nothing kept a + development copy out of search engines unless somebody set the variable. A site on its real domain is not + affected, and at launch the rule ends by itself with the address. An SEO check (Lighthouse, `iapl-seo-check`) run + against the development address now reports the noindex — run it with `IAPL_NOINDEX=0`, or against the real + domain. To keep the old behaviour: `iapl({ developmentNoindex: false })` (the project), `IAPL_NOINDEX=0` (one + environment), `buildSecurityHeaders({ developmentHosts: false })` (the header). - **What changes for an existing site on upgrade — e-mail:** | Site today | After the upgrade | Opt-out | @@ -111,6 +120,8 @@ once there are more than 20. 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. +- **Plugin option `developmentNoindex`** (default `true`): a development host is kept out of search engines + without `IAPL_NOINDEX` (above). `buildSecurityHeaders({ developmentHosts, serverUrl })` for the header. - **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 053162c..29bdcc9 100644 --- a/docs/agent/AGENT.md +++ b/docs/agent/AGENT.md @@ -333,7 +333,7 @@ one is better. Google ignores the same description on many pages. | "Thank you" after a form, a confirmation page | **yes** | | internal search results, filter/parameter pages | **yes** (+ `disallowParams` in robots) | | a test page, a draft page, a landing page only for a paid campaign | **yes** | -| staging, preview, a test copy of the whole site | **`IAPL_NOINDEX=1` in that environment's env** — not the checkbox | +| staging, preview, a test copy of the whole site | **`IAPL_NOINDEX=1` in that environment's env** — not the checkbox. A **development host** needs nothing: an address that matches `iapl({ developmentHosts })` (default `['*.dev.netscale.pl']`) is noindex by itself — robots.txt, page meta, IndexNow, and `X-Robots-Tag` from `buildSecurityHeaders()` (pass it `developmentHosts` too if the project changed the list; `next.config` runs before the plugin). Off: `iapl({ developmentNoindex: false })`, or `IAPL_NOINDEX=0` in one environment. Verify: `curl -sI https:/// \| grep -i x-robots-tag` and `/robots.txt` says `Disallow: /`; on the real domain neither | | homepage, archives (blog, projects) | **never** — the panel blocks saving | | services, offer, contact, about us, posts | **never** | | privacy policy, cookies, terms | **no** by default (they are a credibility signal, they do no harm); `noindex` only at the client's request | diff --git a/docs/agent/skills/iapl-reference/SKILL.md b/docs/agent/skills/iapl-reference/SKILL.md index 187cdde..88b1844 100644 --- a/docs/agent/skills/iapl-reference/SKILL.md +++ b/docs/agent/skills/iapl-reference/SKILL.md @@ -266,7 +266,7 @@ The plugin's own variables are `IAPL_`; a deploy that sets the spelling fr | `IAPL_IP_HEADER` | `ipHeader: true` + production | rate limit trusts any IP header (spoofing) + warning in prod | env: `cf-connecting-ip` (Cloudflare) / `x-forwarded-for` (Traefik/nginx) | | `IAPL_COOKIE_SCAN_URL`, `IAPL_COOKIE_SCAN_TOKEN` | `cookieScanner.crawl` (`iaplEnvRules({ cookieCrawl: true })` requires both in production; token ≥ 16 chars) | **Check site** disabled, the box names the missing variable | env; the token also goes into the scanner service's `IAPL_CRAWLER_SITES` as `host=token` | | `IAPL_DOCTOR_TOKEN` | no; ≥ 32 characters | `GET /api/ipal/doctor` answers 404; with it the endpoint answers a Bearer token, and `iapl-doctor --url` with the same variable reads the deep counts | env (Coolify) and the doctor's shell; also read by the doctor: `CI`, `NO_COLOR`, `PAYLOAD_CONFIG_PATH` (`--deep`), `IAPL_DOCTOR_IMPORT_MAP` (internal) — doctor.md | -| `IAPL_NOINDEX` | no; `1`/`true`/`yes` **staging/preview only** | — (when set: robots Disallow, meta noindex, `X-Robots-Tag`, IndexNow sends nothing) | staging env | +| `IAPL_NOINDEX` | no; `1`/`true`/`yes` **staging/preview only**; `0` = not noindex although on a development host | — (when set: robots Disallow, meta noindex, `X-Robots-Tag`, IndexNow sends nothing). A host matching `iapl({ developmentHosts })` (default `*.dev.netscale.pl`) is noindex without it (`developmentNoindex: false` to switch off) | staging env | | `NEXT_PHASE` | set by Next | only tells `next build` from runtime: during the build an unreachable database gives an empty sitemap; at runtime the sitemap throws (route → 503) | do not set by hand | | `NEXT_RUNTIME` | set by Next | `instrumentation.ts` checks for `nodejs`; missing (scripts, seed) → `buildRevalidateHook` does not revalidate | do not set by hand | diff --git a/docs/agent/skills/iapl-setup/SKILL.md b/docs/agent/skills/iapl-setup/SKILL.md index c8584be..ae6c1e5 100644 --- a/docs/agent/skills/iapl-setup/SKILL.md +++ b/docs/agent/skills/iapl-setup/SKILL.md @@ -529,7 +529,7 @@ overrides the default; CSP: `buildCsp` flags (`youtube`, `googleMaps`, `metaPixe = no policy; after clean reports `mode: 'enforce'` (site and admin); nonces only for pages that already render per request (`createProxy({ csp })` + ``); `withSecurityConfig(config, { hidePoweredBy: false })` keeps `X-Powered-By`; `buildImagesConfig({ extraHosts })`; env validation is fully opt-in — filter/add rules -(`iaplEnvRules(…).filter(…)`). Staging: `IAPL_NOINDEX=1` (also stops IndexNow). Search engines: `robots` instead of +(`iaplEnvRules(…).filter(…)`). Staging: `IAPL_NOINDEX=1` (also stops IndexNow); a development address under `iapl({ developmentHosts })` (default `*.dev.netscale.pl`) is noindex by itself, nothing to set — check `/robots.txt` there says `Disallow: /` and on the real domain it does not. Search engines: `robots` instead of `getRobots` ignores the panel; `iapl({ searchSettings: false })` removes the tab; per-bot exceptions in code: `createContentHelpers({ robots: { aiBotRules: [{ userAgent, access }] } })`. Sitemap: `sitemapOptions: { maxUrls, cacheControl, memoSeconds }`, `sitemapEntries: (entries) => entries` (add/remove URLs), `underConstructionSeo: false`. diff --git a/docs/agent/skills/iapl-upgrade/SKILL.md b/docs/agent/skills/iapl-upgrade/SKILL.md index 4805138..3ea5358 100644 --- a/docs/agent/skills/iapl-upgrade/SKILL.md +++ b/docs/agent/skills/iapl-upgrade/SKILL.md @@ -581,6 +581,11 @@ PROGRAMISTA §6, item 73; email.md; AGENT.md §7.2) — nothing to run; read whi 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). + **A development address is now noindex by itself** (host matches `iapl({ developmentHosts })`, default + `*.dev.netscale.pl`): robots.txt `Disallow: /`, page meta, `X-Robots-Tag`, no IndexNow — with no `IAPL_NOINDEX`. + Nothing to do; tell the owner if an SEO check is run against the development address (use `IAPL_NOINDEX=0` + there, or the real domain). A project with its own list passes it to `buildSecurityHeaders({ developmentHosts })` + in `next.config` too. Old behaviour: `iapl({ developmentNoindex: false })`. 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 9c7677c..9bf055b 100644 --- a/docs/deployment.md +++ b/docs/deployment.md @@ -115,7 +115,7 @@ URLs point at that domain. Outside production, `R2_PUBLIC_URL` alone → read-on | `NEXT_PUBLIC_TURNSTILE_SITE_KEY`, `TURNSTILE_SECRET_KEY` | ⬜ | forms | fallback when the Turnstile keys are not in Site integrations. **`TURNSTILE_SECRET_KEY` is deprecated** — put the secret key into the panel (turnstile.md); the variable keeps working until a later, announced release | | `INDEXNOW_KEY` | ⬜ | SEO | IndexNow key (takes precedence over the key from the panel) | | `IAPL_COOKIE_SCAN_URL`, `IAPL_COOKIE_SCAN_TOKEN` | ⬜ (✅ prod with `iaplEnvRules({ cookieCrawl: true })`) | consent | cookie crawl (`cookieScanner.crawl`): the shared scanner service's URL and this site's token ([cookie-scanner.md](./cookie-scanner.md#browser-crawl)) | -| `IAPL_NOINDEX` | ⬜ | SEO | `1`/`true`/`yes` **on staging only** — the whole site is noindex (robots, meta, `X-Robots-Tag`) | +| `IAPL_NOINDEX` | ⬜ | SEO | `1`/`true`/`yes` **on staging only** — the whole site is noindex (robots, meta, `X-Robots-Tag`). Not needed on a development host: a site whose `NEXT_PUBLIC_SERVER_URL` matches `iapl({ developmentHosts })` (built in: `*.dev.netscale.pl`) is noindex by itself; `0` there switches that off for the environment, `iapl({ developmentNoindex: false })` for the project | | `IAPL_DOCTOR_TOKEN` | ⬜ | ops | ≥ 32 characters turns on the `iapl-doctor` status endpoint `GET /api/ipal/doctor` (404 without it) — [doctor.md](./doctor.md) | "✅ prod" = required by `iaplEnvRules({ storage: true })` / `({ ipHeader: true })` with @@ -318,7 +318,7 @@ checkbox; default: both). A changed variable takes effect only after a **redeplo | `DATABASE_URI`, `PAYLOAD_SECRET` | ✅ only if the build prerenders from the database (§3a3), otherwise ⬜ | ✅ | SSG (`generateStaticParams`) needs the database during `pnpm build`; DB-reading routes stay `force-dynamic` either way (§3b) | | `R2_*`, `GRAPH_*`, `TURNSTILE_SECRET_KEY`, `INDEXNOW_KEY`, `IAPL_IP_HEADER` | ⬜ | ✅ | read at runtime only — keep secrets out of the build | | `NODE_ENV` | — | — | do not set by hand: `next build` / `next start` use `production` | -| `IAPL_NOINDEX` | — | ✅ staging only | never on production | +| `IAPL_NOINDEX` | — | ✅ staging only (a development host needs none) | never on production | Multiline values (keys) → mark *Multiline*; values containing `$` → mark *Literal* (otherwise Coolify interpolates them). Coolify adds its own variables (`COOLIFY_FQDN`, `COOLIFY_URL`, `SOURCE_COMMIT`, `PORT`, `HOST`) — do not use diff --git a/docs/security.md b/docs/security.md index 6697c5b..8f22a72 100644 --- a/docs/security.md +++ b/docs/security.md @@ -61,7 +61,7 @@ export default withPayload(withSecurityConfig(nextConfig)) | `csp` | `false` | `buildCsp` args → the CSP header (+ `Reporting-Endpoints` with `reportUri`) | | `additional` | `[]` | extra headers; the same key overrides (also the `csp` ones) | -With `IAPL_NOINDEX=1` (staging), `X-Robots-Tag: noindex, nofollow` is added to every response. +With `IAPL_NOINDEX=1` (staging), or on a development host — the site's address (`serverUrl`, default `NEXT_PUBLIC_SERVER_URL`) matches `developmentHosts` (default `['*.dev.netscale.pl']`, Intecion's development domain) — `X-Robots-Tag: noindex, nofollow` is added to every response. `next.config` runs before the plugin, so a project that changed `iapl({ developmentHosts })` passes the same list: `buildSecurityHeaders({ developmentHosts: [...] })`; `developmentHosts: false` or `IAPL_NOINDEX=0` leaves the header out. **Uploads:** `buildUploadSecurityHeaders({ collections = ['media'] })` returns `headers()` rules for `/api//file/*` (sandbox, no scripts) — an SVG from local disk cannot run a script on the site's diff --git a/reference/.agents/skills/iapl-reference/SKILL.md b/reference/.agents/skills/iapl-reference/SKILL.md index 187cdde..88b1844 100644 --- a/reference/.agents/skills/iapl-reference/SKILL.md +++ b/reference/.agents/skills/iapl-reference/SKILL.md @@ -266,7 +266,7 @@ The plugin's own variables are `IAPL_`; a deploy that sets the spelling fr | `IAPL_IP_HEADER` | `ipHeader: true` + production | rate limit trusts any IP header (spoofing) + warning in prod | env: `cf-connecting-ip` (Cloudflare) / `x-forwarded-for` (Traefik/nginx) | | `IAPL_COOKIE_SCAN_URL`, `IAPL_COOKIE_SCAN_TOKEN` | `cookieScanner.crawl` (`iaplEnvRules({ cookieCrawl: true })` requires both in production; token ≥ 16 chars) | **Check site** disabled, the box names the missing variable | env; the token also goes into the scanner service's `IAPL_CRAWLER_SITES` as `host=token` | | `IAPL_DOCTOR_TOKEN` | no; ≥ 32 characters | `GET /api/ipal/doctor` answers 404; with it the endpoint answers a Bearer token, and `iapl-doctor --url` with the same variable reads the deep counts | env (Coolify) and the doctor's shell; also read by the doctor: `CI`, `NO_COLOR`, `PAYLOAD_CONFIG_PATH` (`--deep`), `IAPL_DOCTOR_IMPORT_MAP` (internal) — doctor.md | -| `IAPL_NOINDEX` | no; `1`/`true`/`yes` **staging/preview only** | — (when set: robots Disallow, meta noindex, `X-Robots-Tag`, IndexNow sends nothing) | staging env | +| `IAPL_NOINDEX` | no; `1`/`true`/`yes` **staging/preview only**; `0` = not noindex although on a development host | — (when set: robots Disallow, meta noindex, `X-Robots-Tag`, IndexNow sends nothing). A host matching `iapl({ developmentHosts })` (default `*.dev.netscale.pl`) is noindex without it (`developmentNoindex: false` to switch off) | staging env | | `NEXT_PHASE` | set by Next | only tells `next build` from runtime: during the build an unreachable database gives an empty sitemap; at runtime the sitemap throws (route → 503) | do not set by hand | | `NEXT_RUNTIME` | set by Next | `instrumentation.ts` checks for `nodejs`; missing (scripts, seed) → `buildRevalidateHook` does not revalidate | do not set by hand | diff --git a/reference/.agents/skills/iapl-setup/SKILL.md b/reference/.agents/skills/iapl-setup/SKILL.md index c8584be..ae6c1e5 100644 --- a/reference/.agents/skills/iapl-setup/SKILL.md +++ b/reference/.agents/skills/iapl-setup/SKILL.md @@ -529,7 +529,7 @@ overrides the default; CSP: `buildCsp` flags (`youtube`, `googleMaps`, `metaPixe = no policy; after clean reports `mode: 'enforce'` (site and admin); nonces only for pages that already render per request (`createProxy({ csp })` + ``); `withSecurityConfig(config, { hidePoweredBy: false })` keeps `X-Powered-By`; `buildImagesConfig({ extraHosts })`; env validation is fully opt-in — filter/add rules -(`iaplEnvRules(…).filter(…)`). Staging: `IAPL_NOINDEX=1` (also stops IndexNow). Search engines: `robots` instead of +(`iaplEnvRules(…).filter(…)`). Staging: `IAPL_NOINDEX=1` (also stops IndexNow); a development address under `iapl({ developmentHosts })` (default `*.dev.netscale.pl`) is noindex by itself, nothing to set — check `/robots.txt` there says `Disallow: /` and on the real domain it does not. Search engines: `robots` instead of `getRobots` ignores the panel; `iapl({ searchSettings: false })` removes the tab; per-bot exceptions in code: `createContentHelpers({ robots: { aiBotRules: [{ userAgent, access }] } })`. Sitemap: `sitemapOptions: { maxUrls, cacheControl, memoSeconds }`, `sitemapEntries: (entries) => entries` (add/remove URLs), `underConstructionSeo: false`. diff --git a/reference/.agents/skills/iapl-upgrade/SKILL.md b/reference/.agents/skills/iapl-upgrade/SKILL.md index 4805138..3ea5358 100644 --- a/reference/.agents/skills/iapl-upgrade/SKILL.md +++ b/reference/.agents/skills/iapl-upgrade/SKILL.md @@ -581,6 +581,11 @@ PROGRAMISTA §6, item 73; email.md; AGENT.md §7.2) — nothing to run; read whi 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). + **A development address is now noindex by itself** (host matches `iapl({ developmentHosts })`, default + `*.dev.netscale.pl`): robots.txt `Disallow: /`, page meta, `X-Robots-Tag`, no IndexNow — with no `IAPL_NOINDEX`. + Nothing to do; tell the owner if an SEO check is run against the development address (use `IAPL_NOINDEX=0` + there, or the real domain). A project with its own list passes it to `buildSecurityHeaders({ developmentHosts })` + in `next.config` too. Old behaviour: `iapl({ developmentNoindex: false })`. 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/modules/email/relay/session.ts b/src/modules/email/relay/session.ts index 483ee7b..878c9d7 100644 --- a/src/modules/email/relay/session.ts +++ b/src/modules/email/relay/session.ts @@ -5,7 +5,7 @@ import { randomBytes } from 'node:crypto' import type { RelayOptions, ResolvedRelayOptions } from './options.js' import { PLUGIN_VERSION } from '../../../version.js' -import { isSiteNoindex } from '../../seo/siteNoindex.js' +import { noindexEnv } 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' @@ -108,7 +108,8 @@ export type NonPublicSignal = { by: 'development-host'; pattern: string } | { by 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 + // the variable itself: whether a development host is ALSO kept out of search engines is another question + return noindexEnv() === true ? { by: 'noindex' } : null } /** Is this site a non-public copy (`siteNonPublicSignal` as a yes or no)? */ diff --git a/src/modules/security/buildSecurityHeaders.ts b/src/modules/security/buildSecurityHeaders.ts index 6d4a92a..1f99b3a 100644 --- a/src/modules/security/buildSecurityHeaders.ts +++ b/src/modules/security/buildSecurityHeaders.ts @@ -1,6 +1,7 @@ import type { BuildCspArgs } from './buildCsp.js' import { isSiteNoindex } from '../seo/siteNoindex.js' +import { DEFAULT_DEVELOPMENT_HOSTS } from '../shared/developmentHosts.js' import { buildCspHeaders } from './buildCsp.js' /** @@ -29,6 +30,14 @@ export type BuildSecurityHeadersArgs = { * reports, then `mode: 'enforce'` (the only change). See docs/security.md. */ csp?: BuildCspArgs | false + /** + * Development-host patterns for the noindex header: a site whose address (`serverUrl`) matches gets + * `X-Robots-Tag: noindex, nofollow` without `IAPL_NOINDEX`. Default: the plugin's built-in list + * (`DEFAULT_DEVELOPMENT_HOSTS`, `['*.dev.netscale.pl']`). `next.config` runs before the plugin, so a + * project that changed `iapl({ developmentHosts })` passes the same list here; `false` = the variable + * alone decides. + */ + developmentHosts?: false | string[] /** * X-Frame-Options value. 'DENY' (default) blocks all framing; 'SAMEORIGIN' * allows same-origin framing. Note: CSP frame-ancestors supersedes this in @@ -56,6 +65,8 @@ export type BuildSecurityHeadersArgs = { permissionsPolicy?: null | string /** Referrer-Policy. Default 'strict-origin-when-cross-origin' (browser default, explicit). */ referrerPolicy?: null | string + /** The site's address, for `developmentHosts`. Default: `NEXT_PUBLIC_SERVER_URL`. */ + serverUrl?: string } /** @@ -93,7 +104,9 @@ export function buildSecurityHeaders(args: BuildSecurityHeadersArgs = {}): Secur hstsPreload = false, permissionsPolicy = 'camera=(), microphone=(), geolocation=()', referrerPolicy = 'strict-origin-when-cross-origin', + serverUrl, } = args + const developmentHosts = args.developmentHosts ?? DEFAULT_DEVELOPMENT_HOSTS const headers: SecurityHeader[] = [] @@ -124,8 +137,8 @@ export function buildSecurityHeaders(args: BuildSecurityHeadersArgs = {}): Secur headers.push({ key: 'Cross-Origin-Opener-Policy', value: coop }) } - // Staging / preview (IAPL_NOINDEX=1): keep every response out of search engines. - if (isSiteNoindex()) { + // Staging / preview (IAPL_NOINDEX=1) or a development host: keep every response out of search engines. + if (isSiteNoindex({ developmentHosts, host: serverUrl })) { headers.push({ key: 'X-Robots-Tag', value: 'noindex, nofollow' }) } diff --git a/src/modules/seo/buildMetadata.ts b/src/modules/seo/buildMetadata.ts index c976c0e..b57b780 100644 --- a/src/modules/seo/buildMetadata.ts +++ b/src/modules/seo/buildMetadata.ts @@ -213,7 +213,7 @@ export function buildMetadata({ // robots: noindex pages are excluded (follow keeps link authority). Indexed // pages get generous snippet/preview limits so Google can show rich results // (long snippets, large image previews, full video previews). - ...(isSiteNoindex() + ...(isSiteNoindex({ host: origin }) ? { robots: { follow: false, index: false } } : noindex || meta?.noindex ? { robots: { follow: true, index: false } } diff --git a/src/modules/seo/buildRobots.ts b/src/modules/seo/buildRobots.ts index a391824..0c9ee47 100644 --- a/src/modules/seo/buildRobots.ts +++ b/src/modules/seo/buildRobots.ts @@ -140,8 +140,8 @@ export function buildRobots({ sitemap = true, }: BuildRobotsArgs): RobotsRules { const origin = baseUrl.replace(/\/$/, '') - // Staging / preview (IAPL_NOINDEX=1): nothing may be crawled. - if (isSiteNoindex()) {return { rules: { disallow: ['/'], userAgent: '*' } }} + // Staging / preview (IAPL_NOINDEX=1) or a development host (iapl({ developmentHosts })): nothing may be crawled. + if (isSiteNoindex({ host: origin })) {return { rules: { disallow: ['/'], userAgent: '*' } }} const defaults = [...(adminRoute ? [adminRoute] : []), '/api'] const paramRules = disallowParams diff --git a/src/modules/seo/indexNow.ts b/src/modules/seo/indexNow.ts index 9175aea..7090b7c 100644 --- a/src/modules/seo/indexNow.ts +++ b/src/modules/seo/indexNow.ts @@ -87,7 +87,7 @@ export function createIndexNowKeyRoute({ getCachedPayload }: { getCachedPayload: */ function publicOrigin(baseUrl?: string): null | string { const origin = (baseUrl ?? process.env.NEXT_PUBLIC_SERVER_URL ?? '').replace(/\/$/, '') - if (isSiteNoindex()) {return null} + if (isSiteNoindex({ host: origin })) {return null} if (process.env.NODE_ENV !== 'production' || !/^https:\/\//i.test(origin)) {return null} if (/localhost|127\.0\.0\.1|\.local\b|\.test\b/i.test(origin)) {return null} return origin diff --git a/src/modules/seo/siteNoindex.ts b/src/modules/seo/siteNoindex.ts index 5ae6b3a..201109d 100644 --- a/src/modules/seo/siteNoindex.ts +++ b/src/modules/seo/siteNoindex.ts @@ -1,19 +1,49 @@ +import { isDevelopmentHost, noindexDevelopmentHosts } from '../shared/developmentHosts.js' import { readEnv } from '../shared/envName.js' /** - * Whole-site noindex for staging, previews and test copies: set IAPL_NOINDEX=1 - * in that environment's env (the old spelling IPAL_NOINDEX is still read). Then robots.txt disallows everything, every page - * gets `robots: noindex, nofollow`, and buildSecurityHeaders adds - * `X-Robots-Tag: noindex, nofollow` to every response (files and API too). - * Production never sets it — a forgotten staging copy indexed by Google is a - * duplicate of the real site. + * Whole-site noindex for development, staging, preview and test copies. Then robots.txt disallows everything, + * every page gets `robots: noindex, nofollow`, buildSecurityHeaders adds `X-Robots-Tag: noindex, nofollow` to + * every response (files and API too), and IndexNow sends nothing. + * + * Two ways in: + * - `IAPL_NOINDEX=1` in that environment's env (the old spelling IPAL_NOINDEX is still read); + * - by host, with no env: the site's address (`NEXT_PUBLIC_SERVER_URL`) matches a development pattern — + * `iapl({ developmentHosts })`, built in `*.dev.netscale.pl`. A development copy indexed by Google is a + * duplicate of the real site, and nothing else keeps it out. + * `IAPL_NOINDEX=0` (or `false`, `no`, `off`) says otherwise for one environment; `iapl({ developmentNoindex: + * false })` switches the host rule off for the project. Production never sets the variable and is on no + * development host. */ /** The variable's name before 1.17.0. Still read; kept under this constant so `process.env[SITE_NOINDEX_ENV]` in a project means what it meant. */ export const SITE_NOINDEX_ENV = 'IPAL_NOINDEX' /** The variable's name since 1.17.0. Read it with `isSiteNoindex()` or `readEnv(IAPL_SITE_NOINDEX_ENV)`, which fall back to the old one. */ export const IAPL_SITE_NOINDEX_ENV = 'IAPL_NOINDEX' -export function isSiteNoindex(): boolean { +/** What the variable says: `true` (1 / true / yes), `false` (0 / false / no / off), or `undefined` when it says nothing. */ +export function noindexEnv(): boolean | undefined { const v = readEnv(IAPL_SITE_NOINDEX_ENV)?.trim().toLowerCase() - return v === '1' || v === 'true' || v === 'yes' + if (v === '1' || v === 'true' || v === 'yes') {return true} + if (v === '0' || v === 'false' || v === 'no' || v === 'off') {return false} + return undefined +} + +export type SiteNoindexArgs = { + /** The development patterns to go by; `false` = the variable alone decides. Default: the plugin's list. */ + developmentHosts?: false | readonly string[] + /** The site's address or host. Default: `NEXT_PUBLIC_SERVER_URL`. */ + host?: null | string +} + +/** Which signal makes the site noindex: the variable, its development host, or nothing. */ +export function siteNoindexSignal(args: SiteNoindexArgs = {}): 'development-host' | 'env' | null { + const env = noindexEnv() + if (env !== undefined) {return env ? 'env' : null} + const patterns = args.developmentHosts ?? noindexDevelopmentHosts() + if (patterns === false) {return null} + return isDevelopmentHost(args.host || process.env.NEXT_PUBLIC_SERVER_URL, patterns) ? 'development-host' : null +} + +export function isSiteNoindex(args: SiteNoindexArgs = {}): boolean { + return siteNoindexSignal(args) !== null } diff --git a/src/modules/shared/developmentHosts.ts b/src/modules/shared/developmentHosts.ts index 3a6383f..6ea9540 100644 --- a/src/modules/shared/developmentHosts.ts +++ b/src/modules/shared/developmentHosts.ts @@ -42,3 +42,21 @@ export function matchDevelopmentHost(host: null | string | undefined, patterns: /** 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 + +// What `iapl({ developmentHosts, developmentNoindex })` set for this process — read by the helpers that run +// without a Payload config at hand (robots, metadata, IndexNow). `next.config` runs before the plugin: there, +// `buildSecurityHeaders({ developmentHosts })` takes the same list when the project changed it. +let configured: { hosts?: readonly string[]; noindex?: boolean } = {} + +/** Called by the plugin with its options; a later call replaces the earlier one. */ +export function configureDevelopmentHosts(options: { hosts?: readonly string[]; noindex?: boolean } = {}): void { + configured = { ...(options.hosts ? { hosts: [...options.hosts] } : {}), ...(options.noindex === false ? { noindex: false } : {}) } +} + +/** + * The patterns whose hosts are kept out of search engines by default: the plugin's development hosts, or + * `false` when the project switched that off (`iapl({ developmentNoindex: false })`). + */ +export function noindexDevelopmentHosts(): false | readonly string[] { + return configured.noindex === false ? false : (configured.hosts ?? DEFAULT_DEVELOPMENT_HOSTS) +} diff --git a/src/plugin.ts b/src/plugin.ts index 0cc8df9..e441626 100644 --- a/src/plugin.ts +++ b/src/plugin.ts @@ -66,6 +66,7 @@ import { buildIndexNowHook } from './modules/seo/indexNow.js' import { searchSettingsFields } from './modules/seo/searchSettings.js' import { migrateTitleSeparator } from './modules/seo/titleSeparator.js' import { applyCollectionOverride } from './modules/shared/collectionOverride.js' +import { configureDevelopmentHosts } from './modules/shared/developmentHosts.js' import { buildStatsCollection, buildStatsEndpoint } from './modules/stats/index.js' import { visitorCookieFor } from './modules/stats/visitorCookie.js' @@ -752,6 +753,7 @@ export const iapl = (options: IaplOptions): Plugin => { // --- e-mail: the Intecion Notifications Webservice (docs/email.md; off with mail: { relay: false }) --- // What mailAdapter() reads at send time; born under the new name (`custom.iapl`). + configureDevelopmentHosts({ hosts: Array.isArray(options.developmentHosts) ? options.developmentHosts : undefined, noindex: options.developmentNoindex }) const relay = options.mail?.relay const iaplCustom = (config.custom?.iapl ?? {}) as object config.custom = { diff --git a/src/types.ts b/src/types.ts index 9eade1c..c68ce0e 100644 --- a/src/types.ts +++ b/src/types.ts @@ -145,6 +145,15 @@ export type IaplOptions = { */ developmentHosts?: string[] + /** + * A site on a development host (`developmentHosts`) is kept out of search engines without + * `IAPL_NOINDEX`: robots.txt disallows everything, pages carry `noindex, nofollow`, IndexNow sends + * nothing (and `buildSecurityHeaders()` adds `X-Robots-Tag`). Default `true`. `false` = only + * `IAPL_NOINDEX=1` makes a site noindex, as before 1.17.0. `IAPL_NOINDEX=0` switches it off for one + * environment. + */ + developmentNoindex?: boolean + /** * 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; diff --git a/test/indexNow.test.ts b/test/indexNow.test.ts index 5a64746..d88244b 100644 --- a/test/indexNow.test.ts +++ b/test/indexNow.test.ts @@ -75,6 +75,16 @@ describe('IndexNow hook', () => { expect(fetchSpy).not.toHaveBeenCalled() }) + test('a development host sends nothing, with no variable; IAPL_NOINDEX=0 says otherwise', async () => { + vi.stubEnv('IAPL_NOINDEX', '') + vi.stubEnv('NEXT_PUBLIC_SERVER_URL', 'https://acme.dev.netscale.pl') + await run({ _status: 'published' }) + expect(fetchSpy).not.toHaveBeenCalled() + vi.stubEnv('IAPL_NOINDEX', '0') + await run({ _status: 'published' }) + expect(fetchSpy).toHaveBeenCalledOnce() + }) + test('staging copy (IAPL_NOINDEX) sends nothing even in production', async () => { vi.stubEnv('IAPL_NOINDEX', '1') await run({ _status: 'published' }) diff --git a/test/mailRelay.test.ts b/test/mailRelay.test.ts index 22e382d..fc8bd00 100644 --- a/test/mailRelay.test.ts +++ b/test/mailRelay.test.ts @@ -877,6 +877,10 @@ describe('the token over time', () => { // …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() + // (that a development host is also kept out of search engines is not the mail service's signal: only the variable is) + vi.stubEnv('NEXT_PUBLIC_SERVER_URL', 'https://acme.dev.netscale.pl') + expect(at('https://acme.dev.netscale.pl', undefined, { developmentHosts: [] })).toBeNull() + vi.stubEnv('NEXT_PUBLIC_SERVER_URL', '') // either signal is enough; the host is named first vi.stubEnv('IAPL_NOINDEX', '1') expect(at('https://client.pl')).toEqual({ by: 'noindex' }) diff --git a/test/plugin.test.ts b/test/plugin.test.ts index dd535e0..cc43185 100644 --- a/test/plugin.test.ts +++ b/test/plugin.test.ts @@ -5,6 +5,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 { noindexDevelopmentHosts } from '../src/modules/shared/developmentHosts.js' import { iapl } from '../src/plugin.js' import { withTotpParts } from './helpers.js' @@ -31,6 +32,12 @@ describe('iapl — config transform', () => { expect(await hosts()).toEqual(['*.dev.netscale.pl']) expect(await hosts(['*.preview.agency-example.com'])).toEqual(['*.preview.agency-example.com']) expect(await hosts([])).toEqual([]) + // the same options reach the helpers that have no config at hand (robots, metadata, IndexNow) + expect(noindexDevelopmentHosts()).toEqual([]) + await iapl({ access: { authCollection: 'users' }, developmentNoindex: false, i18n, twoFactor: false })(base()) + expect(noindexDevelopmentHosts()).toBe(false) + await iapl({ access: { authCollection: 'users' }, i18n, twoFactor: false })(base()) + expect(noindexDevelopmentHosts()).toEqual(['*.dev.netscale.pl']) }) test('adds globals, endpoint, localization and roles', async () => { diff --git a/test/seo.test.ts b/test/seo.test.ts index b6b30d5..b20e522 100644 --- a/test/seo.test.ts +++ b/test/seo.test.ts @@ -264,6 +264,82 @@ describe('site-wide noindex (IAPL_NOINDEX) and Markdown headers', () => { }) }) +describe('a development host is noindex without IAPL_NOINDEX (iapl({ developmentHosts, developmentNoindex }))', () => { + const DISALLOW_ALL = { rules: { disallow: ['/'], userAgent: '*' } } + const tag = (args?: Parameters[0]) => buildSecurityHeaders(args).find((h) => h.key === 'X-Robots-Tag')?.value + const load = async () => ({ + ...(await import('../src/modules/seo/buildMetadata.js')), + ...(await import('../src/modules/seo/siteNoindex.js')), + ...(await import('../src/modules/shared/developmentHosts.js')), + vi: (await import('vitest')).vi, + }) + const DEV = 'https://acme.dev.netscale.pl' + + test('robots, the page meta and the header on the built-in development domain, with no variable; the real domain is untouched', async () => { + const { buildMetadata, configureDevelopmentHosts, isSiteNoindex, siteNoindexSignal, vi } = await load() + configureDevelopmentHosts() + vi.stubEnv('IAPL_NOINDEX', '') + vi.stubEnv('IPAL_NOINDEX', '') + try { + expect(buildRobots({ baseUrl: DEV })).toEqual(DISALLOW_ALL) + expect(buildRobots({ baseUrl: 'https://acme.pl' })).not.toEqual(DISALLOW_ALL) + expect(buildMetadata({ baseUrl: DEV, config, locale: 'pl', slugs: { pl: 'x' } }).robots).toEqual({ follow: false, index: false }) + expect(buildMetadata({ baseUrl: 'https://acme.pl', config, locale: 'pl', slugs: { pl: 'x' } }).robots).toMatchObject({ index: true }) + expect(tag({ serverUrl: DEV })).toBe('noindex, nofollow') + expect(tag({ serverUrl: 'https://acme.pl' })).toBeUndefined() + expect(siteNoindexSignal({ host: DEV })).toBe('development-host') + // helpers that are given no address read NEXT_PUBLIC_SERVER_URL + vi.stubEnv('NEXT_PUBLIC_SERVER_URL', DEV) + expect(tag()).toBe('noindex, nofollow') + expect(isSiteNoindex()).toBe(true) + expect(buildMetadata({ config, locale: 'pl', slugs: { pl: 'x' } }).robots).toEqual({ follow: false, index: false }) + vi.stubEnv('NEXT_PUBLIC_SERVER_URL', 'https://acme.pl') + expect(tag()).toBeUndefined() + expect(isSiteNoindex()).toBe(false) + } finally { + vi.unstubAllEnvs() + } + }) + + test('the switches: IAPL_NOINDEX=0 for one environment, developmentNoindex: false, another list, an empty list', async () => { + const { configureDevelopmentHosts, isSiteNoindex, noindexDevelopmentHosts, siteNoindexSignal, vi } = await load() + vi.stubEnv('IAPL_NOINDEX', '') + vi.stubEnv('IPAL_NOINDEX', '') + try { + configureDevelopmentHosts() + for (const off of ['0', 'false', 'no', 'OFF']) { + vi.stubEnv('IAPL_NOINDEX', off) + expect(buildRobots({ baseUrl: DEV })).not.toEqual(DISALLOW_ALL) + expect(tag({ serverUrl: DEV })).toBeUndefined() + } + vi.stubEnv('IAPL_NOINDEX', '1') // the variable still works everywhere + expect(siteNoindexSignal({ host: 'https://acme.pl' })).toBe('env') + vi.stubEnv('IAPL_NOINDEX', 'maybe') // says nothing: the host decides + expect(isSiteNoindex({ host: DEV })).toBe(true) + vi.stubEnv('IAPL_NOINDEX', '') + + configureDevelopmentHosts({ noindex: false }) // iapl({ developmentNoindex: false }) + expect(noindexDevelopmentHosts()).toBe(false) + expect(buildRobots({ baseUrl: DEV })).not.toEqual(DISALLOW_ALL) + expect(isSiteNoindex({ host: DEV })).toBe(false) + + configureDevelopmentHosts({ hosts: ['*.preview.agency-example.com'] }) // iapl({ developmentHosts: [...] }) + expect(buildRobots({ baseUrl: 'https://x.preview.agency-example.com' })).toEqual(DISALLOW_ALL) + expect(buildRobots({ baseUrl: DEV })).not.toEqual(DISALLOW_ALL) + configureDevelopmentHosts({ hosts: [] }) + expect(isSiteNoindex({ host: DEV })).toBe(false) + + // next.config runs before the plugin: the header builder takes the list itself + expect(tag({ developmentHosts: ['*.preview.agency-example.com'], serverUrl: 'https://x.preview.agency-example.com' })).toBe('noindex, nofollow') + expect(tag({ developmentHosts: false, serverUrl: DEV })).toBeUndefined() + expect(tag({ developmentHosts: [], serverUrl: DEV })).toBeUndefined() + } finally { + configureDevelopmentHosts() + vi.unstubAllEnvs() + } + }) +}) + describe('createPageMetadata — siteDescription fallback', () => { // Regresja 1.10.0: readSiteMetaConfig czytał siteDescription, ale nie trafiał do buildMetadata — // strona bez meta.description nie miała (Lighthouse SEO). From 463b966365da7cb929185aedf21985f96e718737 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rados=C5=82aw=20Smoli=C5=84ski?= Date: Thu, 26 Nov 2026 10:36:59 +0100 Subject: [PATCH 3/6] Reference site: a test fixture for development hosts (E2E_DEVELOPMENT_HOSTS), for the built-site run of the launch cases Co-Authored-By: Claude Fable 5.2 --- reference/e2e/mail-relay-fixture.ts | 7 +++++++ reference/src/payload.config.ts | 4 +++- 2 files changed, 10 insertions(+), 1 deletion(-) diff --git a/reference/e2e/mail-relay-fixture.ts b/reference/e2e/mail-relay-fixture.ts index cae1198..d83ab9a 100644 --- a/reference/e2e/mail-relay-fixture.ts +++ b/reference/e2e/mail-relay-fixture.ts @@ -8,3 +8,10 @@ export const E2E_MAIL_RELAY_URL = process.env.E2E_MAIL_RELAY_URL || undefined /** `iapl({ mail })` for the test, `undefined` (the plugin's defaults) otherwise. */ export const e2eMail = E2E_MAIL_RELAY_URL ? { relay: { retryBackoffMs: 50, url: E2E_MAIL_RELAY_URL } } : undefined + +/** + * `iapl({ developmentHosts })` for a test that plays a development address on this machine (the built-in + * pattern, `*.dev.netscale.pl`, cannot be served from localhost): E2E_DEVELOPMENT_HOSTS, comma-separated + * patterns. `undefined` (the plugin's built-in list) otherwise. + */ +export const e2eDevelopmentHosts = process.env.E2E_DEVELOPMENT_HOSTS ? process.env.E2E_DEVELOPMENT_HOSTS.split(',').map((p) => p.trim()).filter(Boolean) : undefined diff --git a/reference/src/payload.config.ts b/reference/src/payload.config.ts index 5b44e36..46802a5 100644 --- a/reference/src/payload.config.ts +++ b/reference/src/payload.config.ts @@ -20,7 +20,7 @@ import { Posts } from './collections/Posts' // @starter:endif // @starter:if demo import { E2E_LATE_STAFF, E2E_STAFF_SLUGS, e2eEarlyStaff, e2eLateStaff } from '../e2e/late-staff-fixture' -import { e2eMail } from '../e2e/mail-relay-fixture' +import { e2eDevelopmentHosts, e2eMail } from '../e2e/mail-relay-fixture' // @starter:endif import { contentConfig } from './content.config' import { db } from './db' @@ -68,6 +68,8 @@ export default buildConfig({ // @starter:if demo // a test fixture: `undefined` (the plugin's defaults) without E2E_MAIL_RELAY_URL (e2e/mail-relay-fixture.ts) mail: e2eMail, + // a test fixture: `undefined` (the built-in list) without E2E_DEVELOPMENT_HOSTS + developmentHosts: e2eDevelopmentHosts, // (the staffCollections entry exists only for e2e/late-staff.spec.ts, with E2E_LATE_STAFF=1) access: { authCollection: 'users', ...(E2E_LATE_STAFF ? { staffCollections: E2E_STAFF_SLUGS } : {}) }, // @starter:else From 5df5358768d896dfa104157181670ef989e69193 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rados=C5=82aw=20Smoli=C5=84ski?= Date: Thu, 26 Nov 2026 10:38:29 +0100 Subject: [PATCH 4/6] Revert "A development host is kept out of search engines without IAPL_NOINDEX (developmentNoindex, default on)" This reverts commit bc3aac249f67fdff98d0561bde4ace69f531330f. --- docs/CHANGELOG.md | 11 --- docs/agent/AGENT.md | 2 +- docs/agent/skills/iapl-reference/SKILL.md | 2 +- docs/agent/skills/iapl-setup/SKILL.md | 2 +- docs/agent/skills/iapl-upgrade/SKILL.md | 5 -- docs/deployment.md | 4 +- docs/security.md | 2 +- .../.agents/skills/iapl-reference/SKILL.md | 2 +- reference/.agents/skills/iapl-setup/SKILL.md | 2 +- .../.agents/skills/iapl-upgrade/SKILL.md | 5 -- src/modules/email/relay/session.ts | 5 +- src/modules/security/buildSecurityHeaders.ts | 17 +---- src/modules/seo/buildMetadata.ts | 2 +- src/modules/seo/buildRobots.ts | 4 +- src/modules/seo/indexNow.ts | 2 +- src/modules/seo/siteNoindex.ts | 46 ++--------- src/modules/shared/developmentHosts.ts | 18 ----- src/plugin.ts | 2 - src/types.ts | 9 --- test/indexNow.test.ts | 10 --- test/mailRelay.test.ts | 4 - test/plugin.test.ts | 7 -- test/seo.test.ts | 76 ------------------- 23 files changed, 24 insertions(+), 215 deletions(-) diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md index 8e82563..9a8df66 100644 --- a/docs/CHANGELOG.md +++ b/docs/CHANGELOG.md @@ -32,15 +32,6 @@ once there are more than 20. - **Nothing else has to be run.** The e-mail tab of Site integrations has a new block ("How e-mails are sent"); it is rendered by the status banner already in every import map, so `generate:importmap` gives no diff. No field was added; "Sending method" keeps its two stored values. -- **What changes for an existing site on upgrade — search engines, on a development host only:** a site whose - address (`NEXT_PUBLIC_SERVER_URL`) matches `iapl({ developmentHosts })` — built in: `*.dev.netscale.pl` — is now - **noindex without `IAPL_NOINDEX`**: robots.txt answers `Disallow: /`, every page carries `noindex, nofollow`, - `buildSecurityHeaders()` adds `X-Robots-Tag: noindex, nofollow`, IndexNow sends nothing. Until now nothing kept a - development copy out of search engines unless somebody set the variable. A site on its real domain is not - affected, and at launch the rule ends by itself with the address. An SEO check (Lighthouse, `iapl-seo-check`) run - against the development address now reports the noindex — run it with `IAPL_NOINDEX=0`, or against the real - domain. To keep the old behaviour: `iapl({ developmentNoindex: false })` (the project), `IAPL_NOINDEX=0` (one - environment), `buildSecurityHeaders({ developmentHosts: false })` (the header). - **What changes for an existing site on upgrade — e-mail:** | Site today | After the upgrade | Opt-out | @@ -120,8 +111,6 @@ once there are more than 20. 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. -- **Plugin option `developmentNoindex`** (default `true`): a development host is kept out of search engines - without `IAPL_NOINDEX` (above). `buildSecurityHeaders({ developmentHosts, serverUrl })` for the header. - **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 29bdcc9..053162c 100644 --- a/docs/agent/AGENT.md +++ b/docs/agent/AGENT.md @@ -333,7 +333,7 @@ one is better. Google ignores the same description on many pages. | "Thank you" after a form, a confirmation page | **yes** | | internal search results, filter/parameter pages | **yes** (+ `disallowParams` in robots) | | a test page, a draft page, a landing page only for a paid campaign | **yes** | -| staging, preview, a test copy of the whole site | **`IAPL_NOINDEX=1` in that environment's env** — not the checkbox. A **development host** needs nothing: an address that matches `iapl({ developmentHosts })` (default `['*.dev.netscale.pl']`) is noindex by itself — robots.txt, page meta, IndexNow, and `X-Robots-Tag` from `buildSecurityHeaders()` (pass it `developmentHosts` too if the project changed the list; `next.config` runs before the plugin). Off: `iapl({ developmentNoindex: false })`, or `IAPL_NOINDEX=0` in one environment. Verify: `curl -sI https:/// \| grep -i x-robots-tag` and `/robots.txt` says `Disallow: /`; on the real domain neither | +| staging, preview, a test copy of the whole site | **`IAPL_NOINDEX=1` in that environment's env** — not the checkbox | | homepage, archives (blog, projects) | **never** — the panel blocks saving | | services, offer, contact, about us, posts | **never** | | privacy policy, cookies, terms | **no** by default (they are a credibility signal, they do no harm); `noindex` only at the client's request | diff --git a/docs/agent/skills/iapl-reference/SKILL.md b/docs/agent/skills/iapl-reference/SKILL.md index 88b1844..187cdde 100644 --- a/docs/agent/skills/iapl-reference/SKILL.md +++ b/docs/agent/skills/iapl-reference/SKILL.md @@ -266,7 +266,7 @@ The plugin's own variables are `IAPL_`; a deploy that sets the spelling fr | `IAPL_IP_HEADER` | `ipHeader: true` + production | rate limit trusts any IP header (spoofing) + warning in prod | env: `cf-connecting-ip` (Cloudflare) / `x-forwarded-for` (Traefik/nginx) | | `IAPL_COOKIE_SCAN_URL`, `IAPL_COOKIE_SCAN_TOKEN` | `cookieScanner.crawl` (`iaplEnvRules({ cookieCrawl: true })` requires both in production; token ≥ 16 chars) | **Check site** disabled, the box names the missing variable | env; the token also goes into the scanner service's `IAPL_CRAWLER_SITES` as `host=token` | | `IAPL_DOCTOR_TOKEN` | no; ≥ 32 characters | `GET /api/ipal/doctor` answers 404; with it the endpoint answers a Bearer token, and `iapl-doctor --url` with the same variable reads the deep counts | env (Coolify) and the doctor's shell; also read by the doctor: `CI`, `NO_COLOR`, `PAYLOAD_CONFIG_PATH` (`--deep`), `IAPL_DOCTOR_IMPORT_MAP` (internal) — doctor.md | -| `IAPL_NOINDEX` | no; `1`/`true`/`yes` **staging/preview only**; `0` = not noindex although on a development host | — (when set: robots Disallow, meta noindex, `X-Robots-Tag`, IndexNow sends nothing). A host matching `iapl({ developmentHosts })` (default `*.dev.netscale.pl`) is noindex without it (`developmentNoindex: false` to switch off) | staging env | +| `IAPL_NOINDEX` | no; `1`/`true`/`yes` **staging/preview only** | — (when set: robots Disallow, meta noindex, `X-Robots-Tag`, IndexNow sends nothing) | staging env | | `NEXT_PHASE` | set by Next | only tells `next build` from runtime: during the build an unreachable database gives an empty sitemap; at runtime the sitemap throws (route → 503) | do not set by hand | | `NEXT_RUNTIME` | set by Next | `instrumentation.ts` checks for `nodejs`; missing (scripts, seed) → `buildRevalidateHook` does not revalidate | do not set by hand | diff --git a/docs/agent/skills/iapl-setup/SKILL.md b/docs/agent/skills/iapl-setup/SKILL.md index ae6c1e5..c8584be 100644 --- a/docs/agent/skills/iapl-setup/SKILL.md +++ b/docs/agent/skills/iapl-setup/SKILL.md @@ -529,7 +529,7 @@ overrides the default; CSP: `buildCsp` flags (`youtube`, `googleMaps`, `metaPixe = no policy; after clean reports `mode: 'enforce'` (site and admin); nonces only for pages that already render per request (`createProxy({ csp })` + ``); `withSecurityConfig(config, { hidePoweredBy: false })` keeps `X-Powered-By`; `buildImagesConfig({ extraHosts })`; env validation is fully opt-in — filter/add rules -(`iaplEnvRules(…).filter(…)`). Staging: `IAPL_NOINDEX=1` (also stops IndexNow); a development address under `iapl({ developmentHosts })` (default `*.dev.netscale.pl`) is noindex by itself, nothing to set — check `/robots.txt` there says `Disallow: /` and on the real domain it does not. Search engines: `robots` instead of +(`iaplEnvRules(…).filter(…)`). Staging: `IAPL_NOINDEX=1` (also stops IndexNow). Search engines: `robots` instead of `getRobots` ignores the panel; `iapl({ searchSettings: false })` removes the tab; per-bot exceptions in code: `createContentHelpers({ robots: { aiBotRules: [{ userAgent, access }] } })`. Sitemap: `sitemapOptions: { maxUrls, cacheControl, memoSeconds }`, `sitemapEntries: (entries) => entries` (add/remove URLs), `underConstructionSeo: false`. diff --git a/docs/agent/skills/iapl-upgrade/SKILL.md b/docs/agent/skills/iapl-upgrade/SKILL.md index 3ea5358..4805138 100644 --- a/docs/agent/skills/iapl-upgrade/SKILL.md +++ b/docs/agent/skills/iapl-upgrade/SKILL.md @@ -581,11 +581,6 @@ PROGRAMISTA §6, item 73; email.md; AGENT.md §7.2) — nothing to run; read whi 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). - **A development address is now noindex by itself** (host matches `iapl({ developmentHosts })`, default - `*.dev.netscale.pl`): robots.txt `Disallow: /`, page meta, `X-Robots-Tag`, no IndexNow — with no `IAPL_NOINDEX`. - Nothing to do; tell the owner if an SEO check is run against the development address (use `IAPL_NOINDEX=0` - there, or the real domain). A project with its own list passes it to `buildSecurityHeaders({ developmentHosts })` - in `next.config` too. Old behaviour: `iapl({ developmentNoindex: false })`. 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 9bf055b..9c7677c 100644 --- a/docs/deployment.md +++ b/docs/deployment.md @@ -115,7 +115,7 @@ URLs point at that domain. Outside production, `R2_PUBLIC_URL` alone → read-on | `NEXT_PUBLIC_TURNSTILE_SITE_KEY`, `TURNSTILE_SECRET_KEY` | ⬜ | forms | fallback when the Turnstile keys are not in Site integrations. **`TURNSTILE_SECRET_KEY` is deprecated** — put the secret key into the panel (turnstile.md); the variable keeps working until a later, announced release | | `INDEXNOW_KEY` | ⬜ | SEO | IndexNow key (takes precedence over the key from the panel) | | `IAPL_COOKIE_SCAN_URL`, `IAPL_COOKIE_SCAN_TOKEN` | ⬜ (✅ prod with `iaplEnvRules({ cookieCrawl: true })`) | consent | cookie crawl (`cookieScanner.crawl`): the shared scanner service's URL and this site's token ([cookie-scanner.md](./cookie-scanner.md#browser-crawl)) | -| `IAPL_NOINDEX` | ⬜ | SEO | `1`/`true`/`yes` **on staging only** — the whole site is noindex (robots, meta, `X-Robots-Tag`). Not needed on a development host: a site whose `NEXT_PUBLIC_SERVER_URL` matches `iapl({ developmentHosts })` (built in: `*.dev.netscale.pl`) is noindex by itself; `0` there switches that off for the environment, `iapl({ developmentNoindex: false })` for the project | +| `IAPL_NOINDEX` | ⬜ | SEO | `1`/`true`/`yes` **on staging only** — the whole site is noindex (robots, meta, `X-Robots-Tag`) | | `IAPL_DOCTOR_TOKEN` | ⬜ | ops | ≥ 32 characters turns on the `iapl-doctor` status endpoint `GET /api/ipal/doctor` (404 without it) — [doctor.md](./doctor.md) | "✅ prod" = required by `iaplEnvRules({ storage: true })` / `({ ipHeader: true })` with @@ -318,7 +318,7 @@ checkbox; default: both). A changed variable takes effect only after a **redeplo | `DATABASE_URI`, `PAYLOAD_SECRET` | ✅ only if the build prerenders from the database (§3a3), otherwise ⬜ | ✅ | SSG (`generateStaticParams`) needs the database during `pnpm build`; DB-reading routes stay `force-dynamic` either way (§3b) | | `R2_*`, `GRAPH_*`, `TURNSTILE_SECRET_KEY`, `INDEXNOW_KEY`, `IAPL_IP_HEADER` | ⬜ | ✅ | read at runtime only — keep secrets out of the build | | `NODE_ENV` | — | — | do not set by hand: `next build` / `next start` use `production` | -| `IAPL_NOINDEX` | — | ✅ staging only (a development host needs none) | never on production | +| `IAPL_NOINDEX` | — | ✅ staging only | never on production | Multiline values (keys) → mark *Multiline*; values containing `$` → mark *Literal* (otherwise Coolify interpolates them). Coolify adds its own variables (`COOLIFY_FQDN`, `COOLIFY_URL`, `SOURCE_COMMIT`, `PORT`, `HOST`) — do not use diff --git a/docs/security.md b/docs/security.md index 8f22a72..6697c5b 100644 --- a/docs/security.md +++ b/docs/security.md @@ -61,7 +61,7 @@ export default withPayload(withSecurityConfig(nextConfig)) | `csp` | `false` | `buildCsp` args → the CSP header (+ `Reporting-Endpoints` with `reportUri`) | | `additional` | `[]` | extra headers; the same key overrides (also the `csp` ones) | -With `IAPL_NOINDEX=1` (staging), or on a development host — the site's address (`serverUrl`, default `NEXT_PUBLIC_SERVER_URL`) matches `developmentHosts` (default `['*.dev.netscale.pl']`, Intecion's development domain) — `X-Robots-Tag: noindex, nofollow` is added to every response. `next.config` runs before the plugin, so a project that changed `iapl({ developmentHosts })` passes the same list: `buildSecurityHeaders({ developmentHosts: [...] })`; `developmentHosts: false` or `IAPL_NOINDEX=0` leaves the header out. +With `IAPL_NOINDEX=1` (staging), `X-Robots-Tag: noindex, nofollow` is added to every response. **Uploads:** `buildUploadSecurityHeaders({ collections = ['media'] })` returns `headers()` rules for `/api//file/*` (sandbox, no scripts) — an SVG from local disk cannot run a script on the site's diff --git a/reference/.agents/skills/iapl-reference/SKILL.md b/reference/.agents/skills/iapl-reference/SKILL.md index 88b1844..187cdde 100644 --- a/reference/.agents/skills/iapl-reference/SKILL.md +++ b/reference/.agents/skills/iapl-reference/SKILL.md @@ -266,7 +266,7 @@ The plugin's own variables are `IAPL_`; a deploy that sets the spelling fr | `IAPL_IP_HEADER` | `ipHeader: true` + production | rate limit trusts any IP header (spoofing) + warning in prod | env: `cf-connecting-ip` (Cloudflare) / `x-forwarded-for` (Traefik/nginx) | | `IAPL_COOKIE_SCAN_URL`, `IAPL_COOKIE_SCAN_TOKEN` | `cookieScanner.crawl` (`iaplEnvRules({ cookieCrawl: true })` requires both in production; token ≥ 16 chars) | **Check site** disabled, the box names the missing variable | env; the token also goes into the scanner service's `IAPL_CRAWLER_SITES` as `host=token` | | `IAPL_DOCTOR_TOKEN` | no; ≥ 32 characters | `GET /api/ipal/doctor` answers 404; with it the endpoint answers a Bearer token, and `iapl-doctor --url` with the same variable reads the deep counts | env (Coolify) and the doctor's shell; also read by the doctor: `CI`, `NO_COLOR`, `PAYLOAD_CONFIG_PATH` (`--deep`), `IAPL_DOCTOR_IMPORT_MAP` (internal) — doctor.md | -| `IAPL_NOINDEX` | no; `1`/`true`/`yes` **staging/preview only**; `0` = not noindex although on a development host | — (when set: robots Disallow, meta noindex, `X-Robots-Tag`, IndexNow sends nothing). A host matching `iapl({ developmentHosts })` (default `*.dev.netscale.pl`) is noindex without it (`developmentNoindex: false` to switch off) | staging env | +| `IAPL_NOINDEX` | no; `1`/`true`/`yes` **staging/preview only** | — (when set: robots Disallow, meta noindex, `X-Robots-Tag`, IndexNow sends nothing) | staging env | | `NEXT_PHASE` | set by Next | only tells `next build` from runtime: during the build an unreachable database gives an empty sitemap; at runtime the sitemap throws (route → 503) | do not set by hand | | `NEXT_RUNTIME` | set by Next | `instrumentation.ts` checks for `nodejs`; missing (scripts, seed) → `buildRevalidateHook` does not revalidate | do not set by hand | diff --git a/reference/.agents/skills/iapl-setup/SKILL.md b/reference/.agents/skills/iapl-setup/SKILL.md index ae6c1e5..c8584be 100644 --- a/reference/.agents/skills/iapl-setup/SKILL.md +++ b/reference/.agents/skills/iapl-setup/SKILL.md @@ -529,7 +529,7 @@ overrides the default; CSP: `buildCsp` flags (`youtube`, `googleMaps`, `metaPixe = no policy; after clean reports `mode: 'enforce'` (site and admin); nonces only for pages that already render per request (`createProxy({ csp })` + ``); `withSecurityConfig(config, { hidePoweredBy: false })` keeps `X-Powered-By`; `buildImagesConfig({ extraHosts })`; env validation is fully opt-in — filter/add rules -(`iaplEnvRules(…).filter(…)`). Staging: `IAPL_NOINDEX=1` (also stops IndexNow); a development address under `iapl({ developmentHosts })` (default `*.dev.netscale.pl`) is noindex by itself, nothing to set — check `/robots.txt` there says `Disallow: /` and on the real domain it does not. Search engines: `robots` instead of +(`iaplEnvRules(…).filter(…)`). Staging: `IAPL_NOINDEX=1` (also stops IndexNow). Search engines: `robots` instead of `getRobots` ignores the panel; `iapl({ searchSettings: false })` removes the tab; per-bot exceptions in code: `createContentHelpers({ robots: { aiBotRules: [{ userAgent, access }] } })`. Sitemap: `sitemapOptions: { maxUrls, cacheControl, memoSeconds }`, `sitemapEntries: (entries) => entries` (add/remove URLs), `underConstructionSeo: false`. diff --git a/reference/.agents/skills/iapl-upgrade/SKILL.md b/reference/.agents/skills/iapl-upgrade/SKILL.md index 3ea5358..4805138 100644 --- a/reference/.agents/skills/iapl-upgrade/SKILL.md +++ b/reference/.agents/skills/iapl-upgrade/SKILL.md @@ -581,11 +581,6 @@ PROGRAMISTA §6, item 73; email.md; AGENT.md §7.2) — nothing to run; read whi 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). - **A development address is now noindex by itself** (host matches `iapl({ developmentHosts })`, default - `*.dev.netscale.pl`): robots.txt `Disallow: /`, page meta, `X-Robots-Tag`, no IndexNow — with no `IAPL_NOINDEX`. - Nothing to do; tell the owner if an SEO check is run against the development address (use `IAPL_NOINDEX=0` - there, or the real domain). A project with its own list passes it to `buildSecurityHeaders({ developmentHosts })` - in `next.config` too. Old behaviour: `iapl({ developmentNoindex: false })`. 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/modules/email/relay/session.ts b/src/modules/email/relay/session.ts index 878c9d7..483ee7b 100644 --- a/src/modules/email/relay/session.ts +++ b/src/modules/email/relay/session.ts @@ -5,7 +5,7 @@ import { randomBytes } from 'node:crypto' import type { RelayOptions, ResolvedRelayOptions } from './options.js' import { PLUGIN_VERSION } from '../../../version.js' -import { noindexEnv } from '../../seo/siteNoindex.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' @@ -108,8 +108,7 @@ export type NonPublicSignal = { by: 'development-host'; pattern: string } | { by 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 }} - // the variable itself: whether a development host is ALSO kept out of search engines is another question - return noindexEnv() === true ? { by: 'noindex' } : null + return isSiteNoindex() ? { by: 'noindex' } : null } /** Is this site a non-public copy (`siteNonPublicSignal` as a yes or no)? */ diff --git a/src/modules/security/buildSecurityHeaders.ts b/src/modules/security/buildSecurityHeaders.ts index 1f99b3a..6d4a92a 100644 --- a/src/modules/security/buildSecurityHeaders.ts +++ b/src/modules/security/buildSecurityHeaders.ts @@ -1,7 +1,6 @@ import type { BuildCspArgs } from './buildCsp.js' import { isSiteNoindex } from '../seo/siteNoindex.js' -import { DEFAULT_DEVELOPMENT_HOSTS } from '../shared/developmentHosts.js' import { buildCspHeaders } from './buildCsp.js' /** @@ -30,14 +29,6 @@ export type BuildSecurityHeadersArgs = { * reports, then `mode: 'enforce'` (the only change). See docs/security.md. */ csp?: BuildCspArgs | false - /** - * Development-host patterns for the noindex header: a site whose address (`serverUrl`) matches gets - * `X-Robots-Tag: noindex, nofollow` without `IAPL_NOINDEX`. Default: the plugin's built-in list - * (`DEFAULT_DEVELOPMENT_HOSTS`, `['*.dev.netscale.pl']`). `next.config` runs before the plugin, so a - * project that changed `iapl({ developmentHosts })` passes the same list here; `false` = the variable - * alone decides. - */ - developmentHosts?: false | string[] /** * X-Frame-Options value. 'DENY' (default) blocks all framing; 'SAMEORIGIN' * allows same-origin framing. Note: CSP frame-ancestors supersedes this in @@ -65,8 +56,6 @@ export type BuildSecurityHeadersArgs = { permissionsPolicy?: null | string /** Referrer-Policy. Default 'strict-origin-when-cross-origin' (browser default, explicit). */ referrerPolicy?: null | string - /** The site's address, for `developmentHosts`. Default: `NEXT_PUBLIC_SERVER_URL`. */ - serverUrl?: string } /** @@ -104,9 +93,7 @@ export function buildSecurityHeaders(args: BuildSecurityHeadersArgs = {}): Secur hstsPreload = false, permissionsPolicy = 'camera=(), microphone=(), geolocation=()', referrerPolicy = 'strict-origin-when-cross-origin', - serverUrl, } = args - const developmentHosts = args.developmentHosts ?? DEFAULT_DEVELOPMENT_HOSTS const headers: SecurityHeader[] = [] @@ -137,8 +124,8 @@ export function buildSecurityHeaders(args: BuildSecurityHeadersArgs = {}): Secur headers.push({ key: 'Cross-Origin-Opener-Policy', value: coop }) } - // Staging / preview (IAPL_NOINDEX=1) or a development host: keep every response out of search engines. - if (isSiteNoindex({ developmentHosts, host: serverUrl })) { + // Staging / preview (IAPL_NOINDEX=1): keep every response out of search engines. + if (isSiteNoindex()) { headers.push({ key: 'X-Robots-Tag', value: 'noindex, nofollow' }) } diff --git a/src/modules/seo/buildMetadata.ts b/src/modules/seo/buildMetadata.ts index b57b780..c976c0e 100644 --- a/src/modules/seo/buildMetadata.ts +++ b/src/modules/seo/buildMetadata.ts @@ -213,7 +213,7 @@ export function buildMetadata({ // robots: noindex pages are excluded (follow keeps link authority). Indexed // pages get generous snippet/preview limits so Google can show rich results // (long snippets, large image previews, full video previews). - ...(isSiteNoindex({ host: origin }) + ...(isSiteNoindex() ? { robots: { follow: false, index: false } } : noindex || meta?.noindex ? { robots: { follow: true, index: false } } diff --git a/src/modules/seo/buildRobots.ts b/src/modules/seo/buildRobots.ts index 0c9ee47..a391824 100644 --- a/src/modules/seo/buildRobots.ts +++ b/src/modules/seo/buildRobots.ts @@ -140,8 +140,8 @@ export function buildRobots({ sitemap = true, }: BuildRobotsArgs): RobotsRules { const origin = baseUrl.replace(/\/$/, '') - // Staging / preview (IAPL_NOINDEX=1) or a development host (iapl({ developmentHosts })): nothing may be crawled. - if (isSiteNoindex({ host: origin })) {return { rules: { disallow: ['/'], userAgent: '*' } }} + // Staging / preview (IAPL_NOINDEX=1): nothing may be crawled. + if (isSiteNoindex()) {return { rules: { disallow: ['/'], userAgent: '*' } }} const defaults = [...(adminRoute ? [adminRoute] : []), '/api'] const paramRules = disallowParams diff --git a/src/modules/seo/indexNow.ts b/src/modules/seo/indexNow.ts index 7090b7c..9175aea 100644 --- a/src/modules/seo/indexNow.ts +++ b/src/modules/seo/indexNow.ts @@ -87,7 +87,7 @@ export function createIndexNowKeyRoute({ getCachedPayload }: { getCachedPayload: */ function publicOrigin(baseUrl?: string): null | string { const origin = (baseUrl ?? process.env.NEXT_PUBLIC_SERVER_URL ?? '').replace(/\/$/, '') - if (isSiteNoindex({ host: origin })) {return null} + if (isSiteNoindex()) {return null} if (process.env.NODE_ENV !== 'production' || !/^https:\/\//i.test(origin)) {return null} if (/localhost|127\.0\.0\.1|\.local\b|\.test\b/i.test(origin)) {return null} return origin diff --git a/src/modules/seo/siteNoindex.ts b/src/modules/seo/siteNoindex.ts index 201109d..5ae6b3a 100644 --- a/src/modules/seo/siteNoindex.ts +++ b/src/modules/seo/siteNoindex.ts @@ -1,49 +1,19 @@ -import { isDevelopmentHost, noindexDevelopmentHosts } from '../shared/developmentHosts.js' import { readEnv } from '../shared/envName.js' /** - * Whole-site noindex for development, staging, preview and test copies. Then robots.txt disallows everything, - * every page gets `robots: noindex, nofollow`, buildSecurityHeaders adds `X-Robots-Tag: noindex, nofollow` to - * every response (files and API too), and IndexNow sends nothing. - * - * Two ways in: - * - `IAPL_NOINDEX=1` in that environment's env (the old spelling IPAL_NOINDEX is still read); - * - by host, with no env: the site's address (`NEXT_PUBLIC_SERVER_URL`) matches a development pattern — - * `iapl({ developmentHosts })`, built in `*.dev.netscale.pl`. A development copy indexed by Google is a - * duplicate of the real site, and nothing else keeps it out. - * `IAPL_NOINDEX=0` (or `false`, `no`, `off`) says otherwise for one environment; `iapl({ developmentNoindex: - * false })` switches the host rule off for the project. Production never sets the variable and is on no - * development host. + * Whole-site noindex for staging, previews and test copies: set IAPL_NOINDEX=1 + * in that environment's env (the old spelling IPAL_NOINDEX is still read). Then robots.txt disallows everything, every page + * gets `robots: noindex, nofollow`, and buildSecurityHeaders adds + * `X-Robots-Tag: noindex, nofollow` to every response (files and API too). + * Production never sets it — a forgotten staging copy indexed by Google is a + * duplicate of the real site. */ /** The variable's name before 1.17.0. Still read; kept under this constant so `process.env[SITE_NOINDEX_ENV]` in a project means what it meant. */ export const SITE_NOINDEX_ENV = 'IPAL_NOINDEX' /** The variable's name since 1.17.0. Read it with `isSiteNoindex()` or `readEnv(IAPL_SITE_NOINDEX_ENV)`, which fall back to the old one. */ export const IAPL_SITE_NOINDEX_ENV = 'IAPL_NOINDEX' -/** What the variable says: `true` (1 / true / yes), `false` (0 / false / no / off), or `undefined` when it says nothing. */ -export function noindexEnv(): boolean | undefined { +export function isSiteNoindex(): boolean { const v = readEnv(IAPL_SITE_NOINDEX_ENV)?.trim().toLowerCase() - if (v === '1' || v === 'true' || v === 'yes') {return true} - if (v === '0' || v === 'false' || v === 'no' || v === 'off') {return false} - return undefined -} - -export type SiteNoindexArgs = { - /** The development patterns to go by; `false` = the variable alone decides. Default: the plugin's list. */ - developmentHosts?: false | readonly string[] - /** The site's address or host. Default: `NEXT_PUBLIC_SERVER_URL`. */ - host?: null | string -} - -/** Which signal makes the site noindex: the variable, its development host, or nothing. */ -export function siteNoindexSignal(args: SiteNoindexArgs = {}): 'development-host' | 'env' | null { - const env = noindexEnv() - if (env !== undefined) {return env ? 'env' : null} - const patterns = args.developmentHosts ?? noindexDevelopmentHosts() - if (patterns === false) {return null} - return isDevelopmentHost(args.host || process.env.NEXT_PUBLIC_SERVER_URL, patterns) ? 'development-host' : null -} - -export function isSiteNoindex(args: SiteNoindexArgs = {}): boolean { - return siteNoindexSignal(args) !== null + return v === '1' || v === 'true' || v === 'yes' } diff --git a/src/modules/shared/developmentHosts.ts b/src/modules/shared/developmentHosts.ts index 6ea9540..3a6383f 100644 --- a/src/modules/shared/developmentHosts.ts +++ b/src/modules/shared/developmentHosts.ts @@ -42,21 +42,3 @@ export function matchDevelopmentHost(host: null | string | undefined, patterns: /** 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 - -// What `iapl({ developmentHosts, developmentNoindex })` set for this process — read by the helpers that run -// without a Payload config at hand (robots, metadata, IndexNow). `next.config` runs before the plugin: there, -// `buildSecurityHeaders({ developmentHosts })` takes the same list when the project changed it. -let configured: { hosts?: readonly string[]; noindex?: boolean } = {} - -/** Called by the plugin with its options; a later call replaces the earlier one. */ -export function configureDevelopmentHosts(options: { hosts?: readonly string[]; noindex?: boolean } = {}): void { - configured = { ...(options.hosts ? { hosts: [...options.hosts] } : {}), ...(options.noindex === false ? { noindex: false } : {}) } -} - -/** - * The patterns whose hosts are kept out of search engines by default: the plugin's development hosts, or - * `false` when the project switched that off (`iapl({ developmentNoindex: false })`). - */ -export function noindexDevelopmentHosts(): false | readonly string[] { - return configured.noindex === false ? false : (configured.hosts ?? DEFAULT_DEVELOPMENT_HOSTS) -} diff --git a/src/plugin.ts b/src/plugin.ts index e441626..0cc8df9 100644 --- a/src/plugin.ts +++ b/src/plugin.ts @@ -66,7 +66,6 @@ import { buildIndexNowHook } from './modules/seo/indexNow.js' import { searchSettingsFields } from './modules/seo/searchSettings.js' import { migrateTitleSeparator } from './modules/seo/titleSeparator.js' import { applyCollectionOverride } from './modules/shared/collectionOverride.js' -import { configureDevelopmentHosts } from './modules/shared/developmentHosts.js' import { buildStatsCollection, buildStatsEndpoint } from './modules/stats/index.js' import { visitorCookieFor } from './modules/stats/visitorCookie.js' @@ -753,7 +752,6 @@ export const iapl = (options: IaplOptions): Plugin => { // --- e-mail: the Intecion Notifications Webservice (docs/email.md; off with mail: { relay: false }) --- // What mailAdapter() reads at send time; born under the new name (`custom.iapl`). - configureDevelopmentHosts({ hosts: Array.isArray(options.developmentHosts) ? options.developmentHosts : undefined, noindex: options.developmentNoindex }) const relay = options.mail?.relay const iaplCustom = (config.custom?.iapl ?? {}) as object config.custom = { diff --git a/src/types.ts b/src/types.ts index c68ce0e..9eade1c 100644 --- a/src/types.ts +++ b/src/types.ts @@ -145,15 +145,6 @@ export type IaplOptions = { */ developmentHosts?: string[] - /** - * A site on a development host (`developmentHosts`) is kept out of search engines without - * `IAPL_NOINDEX`: robots.txt disallows everything, pages carry `noindex, nofollow`, IndexNow sends - * nothing (and `buildSecurityHeaders()` adds `X-Robots-Tag`). Default `true`. `false` = only - * `IAPL_NOINDEX=1` makes a site noindex, as before 1.17.0. `IAPL_NOINDEX=0` switches it off for one - * environment. - */ - developmentNoindex?: boolean - /** * 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; diff --git a/test/indexNow.test.ts b/test/indexNow.test.ts index d88244b..5a64746 100644 --- a/test/indexNow.test.ts +++ b/test/indexNow.test.ts @@ -75,16 +75,6 @@ describe('IndexNow hook', () => { expect(fetchSpy).not.toHaveBeenCalled() }) - test('a development host sends nothing, with no variable; IAPL_NOINDEX=0 says otherwise', async () => { - vi.stubEnv('IAPL_NOINDEX', '') - vi.stubEnv('NEXT_PUBLIC_SERVER_URL', 'https://acme.dev.netscale.pl') - await run({ _status: 'published' }) - expect(fetchSpy).not.toHaveBeenCalled() - vi.stubEnv('IAPL_NOINDEX', '0') - await run({ _status: 'published' }) - expect(fetchSpy).toHaveBeenCalledOnce() - }) - test('staging copy (IAPL_NOINDEX) sends nothing even in production', async () => { vi.stubEnv('IAPL_NOINDEX', '1') await run({ _status: 'published' }) diff --git a/test/mailRelay.test.ts b/test/mailRelay.test.ts index fc8bd00..22e382d 100644 --- a/test/mailRelay.test.ts +++ b/test/mailRelay.test.ts @@ -877,10 +877,6 @@ describe('the token over time', () => { // …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() - // (that a development host is also kept out of search engines is not the mail service's signal: only the variable is) - vi.stubEnv('NEXT_PUBLIC_SERVER_URL', 'https://acme.dev.netscale.pl') - expect(at('https://acme.dev.netscale.pl', undefined, { developmentHosts: [] })).toBeNull() - vi.stubEnv('NEXT_PUBLIC_SERVER_URL', '') // either signal is enough; the host is named first vi.stubEnv('IAPL_NOINDEX', '1') expect(at('https://client.pl')).toEqual({ by: 'noindex' }) diff --git a/test/plugin.test.ts b/test/plugin.test.ts index cc43185..dd535e0 100644 --- a/test/plugin.test.ts +++ b/test/plugin.test.ts @@ -5,7 +5,6 @@ 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 { noindexDevelopmentHosts } from '../src/modules/shared/developmentHosts.js' import { iapl } from '../src/plugin.js' import { withTotpParts } from './helpers.js' @@ -32,12 +31,6 @@ describe('iapl — config transform', () => { expect(await hosts()).toEqual(['*.dev.netscale.pl']) expect(await hosts(['*.preview.agency-example.com'])).toEqual(['*.preview.agency-example.com']) expect(await hosts([])).toEqual([]) - // the same options reach the helpers that have no config at hand (robots, metadata, IndexNow) - expect(noindexDevelopmentHosts()).toEqual([]) - await iapl({ access: { authCollection: 'users' }, developmentNoindex: false, i18n, twoFactor: false })(base()) - expect(noindexDevelopmentHosts()).toBe(false) - await iapl({ access: { authCollection: 'users' }, i18n, twoFactor: false })(base()) - expect(noindexDevelopmentHosts()).toEqual(['*.dev.netscale.pl']) }) test('adds globals, endpoint, localization and roles', async () => { diff --git a/test/seo.test.ts b/test/seo.test.ts index b20e522..b6b30d5 100644 --- a/test/seo.test.ts +++ b/test/seo.test.ts @@ -264,82 +264,6 @@ describe('site-wide noindex (IAPL_NOINDEX) and Markdown headers', () => { }) }) -describe('a development host is noindex without IAPL_NOINDEX (iapl({ developmentHosts, developmentNoindex }))', () => { - const DISALLOW_ALL = { rules: { disallow: ['/'], userAgent: '*' } } - const tag = (args?: Parameters[0]) => buildSecurityHeaders(args).find((h) => h.key === 'X-Robots-Tag')?.value - const load = async () => ({ - ...(await import('../src/modules/seo/buildMetadata.js')), - ...(await import('../src/modules/seo/siteNoindex.js')), - ...(await import('../src/modules/shared/developmentHosts.js')), - vi: (await import('vitest')).vi, - }) - const DEV = 'https://acme.dev.netscale.pl' - - test('robots, the page meta and the header on the built-in development domain, with no variable; the real domain is untouched', async () => { - const { buildMetadata, configureDevelopmentHosts, isSiteNoindex, siteNoindexSignal, vi } = await load() - configureDevelopmentHosts() - vi.stubEnv('IAPL_NOINDEX', '') - vi.stubEnv('IPAL_NOINDEX', '') - try { - expect(buildRobots({ baseUrl: DEV })).toEqual(DISALLOW_ALL) - expect(buildRobots({ baseUrl: 'https://acme.pl' })).not.toEqual(DISALLOW_ALL) - expect(buildMetadata({ baseUrl: DEV, config, locale: 'pl', slugs: { pl: 'x' } }).robots).toEqual({ follow: false, index: false }) - expect(buildMetadata({ baseUrl: 'https://acme.pl', config, locale: 'pl', slugs: { pl: 'x' } }).robots).toMatchObject({ index: true }) - expect(tag({ serverUrl: DEV })).toBe('noindex, nofollow') - expect(tag({ serverUrl: 'https://acme.pl' })).toBeUndefined() - expect(siteNoindexSignal({ host: DEV })).toBe('development-host') - // helpers that are given no address read NEXT_PUBLIC_SERVER_URL - vi.stubEnv('NEXT_PUBLIC_SERVER_URL', DEV) - expect(tag()).toBe('noindex, nofollow') - expect(isSiteNoindex()).toBe(true) - expect(buildMetadata({ config, locale: 'pl', slugs: { pl: 'x' } }).robots).toEqual({ follow: false, index: false }) - vi.stubEnv('NEXT_PUBLIC_SERVER_URL', 'https://acme.pl') - expect(tag()).toBeUndefined() - expect(isSiteNoindex()).toBe(false) - } finally { - vi.unstubAllEnvs() - } - }) - - test('the switches: IAPL_NOINDEX=0 for one environment, developmentNoindex: false, another list, an empty list', async () => { - const { configureDevelopmentHosts, isSiteNoindex, noindexDevelopmentHosts, siteNoindexSignal, vi } = await load() - vi.stubEnv('IAPL_NOINDEX', '') - vi.stubEnv('IPAL_NOINDEX', '') - try { - configureDevelopmentHosts() - for (const off of ['0', 'false', 'no', 'OFF']) { - vi.stubEnv('IAPL_NOINDEX', off) - expect(buildRobots({ baseUrl: DEV })).not.toEqual(DISALLOW_ALL) - expect(tag({ serverUrl: DEV })).toBeUndefined() - } - vi.stubEnv('IAPL_NOINDEX', '1') // the variable still works everywhere - expect(siteNoindexSignal({ host: 'https://acme.pl' })).toBe('env') - vi.stubEnv('IAPL_NOINDEX', 'maybe') // says nothing: the host decides - expect(isSiteNoindex({ host: DEV })).toBe(true) - vi.stubEnv('IAPL_NOINDEX', '') - - configureDevelopmentHosts({ noindex: false }) // iapl({ developmentNoindex: false }) - expect(noindexDevelopmentHosts()).toBe(false) - expect(buildRobots({ baseUrl: DEV })).not.toEqual(DISALLOW_ALL) - expect(isSiteNoindex({ host: DEV })).toBe(false) - - configureDevelopmentHosts({ hosts: ['*.preview.agency-example.com'] }) // iapl({ developmentHosts: [...] }) - expect(buildRobots({ baseUrl: 'https://x.preview.agency-example.com' })).toEqual(DISALLOW_ALL) - expect(buildRobots({ baseUrl: DEV })).not.toEqual(DISALLOW_ALL) - configureDevelopmentHosts({ hosts: [] }) - expect(isSiteNoindex({ host: DEV })).toBe(false) - - // next.config runs before the plugin: the header builder takes the list itself - expect(tag({ developmentHosts: ['*.preview.agency-example.com'], serverUrl: 'https://x.preview.agency-example.com' })).toBe('noindex, nofollow') - expect(tag({ developmentHosts: false, serverUrl: DEV })).toBeUndefined() - expect(tag({ developmentHosts: [], serverUrl: DEV })).toBeUndefined() - } finally { - configureDevelopmentHosts() - vi.unstubAllEnvs() - } - }) -}) - describe('createPageMetadata — siteDescription fallback', () => { // Regresja 1.10.0: readSiteMetaConfig czytał siteDescription, ale nie trafiał do buildMetadata — // strona bez meta.description nie miała (Lighthouse SEO). From 99c73ed0ffc22c6d6b2a92bcb5ea8bce2c0a5ddd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rados=C5=82aw=20Smoli=C5=84ski?= Date: Thu, 26 Nov 2026 10:40:33 +0100 Subject: [PATCH 5/6] Development hosts are about mail only: one sentence on robots; the reference index after the fixture Co-Authored-By: Claude Fable 5.2 --- docs/CHANGELOG.md | 2 +- docs/agent/AGENT.md | 3 ++- docs/agent/reference-site/INDEX.md | 7 +++++++ docs/email.md | 1 + src/types.ts | 3 ++- 5 files changed, 13 insertions(+), 3 deletions(-) diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md index 9a8df66..ba1cd46 100644 --- a/docs/CHANGELOG.md +++ b/docs/CHANGELOG.md @@ -110,7 +110,7 @@ once there are more than 20. `*.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. + Doctor: `mail-non-public` (info, deep) names the signal that makes a site non-public. The list is about mail only: it does not make a development host noindex. Keeping development addresses out of search engines stays the hosting's business (Coolify) or `IAPL_NOINDEX=1`. Nothing changes in what a site serves to robots on upgrade. - **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 053162c..14b27e4 100644 --- a/docs/agent/AGENT.md +++ b/docs/agent/AGENT.md @@ -1299,7 +1299,8 @@ the mail service → nothing (`mail: { relay: false }` and no SMTP). A site with 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 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 + (`mail-non-public`). The option does not touch robots: noindex on a development address is the hosting's + business or `IAPL_NOINDEX=1`. 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 diff --git a/docs/agent/reference-site/INDEX.md b/docs/agent/reference-site/INDEX.md index b227d58..24669aa 100644 --- a/docs/agent/reference-site/INDEX.md +++ b/docs/agent/reference-site/INDEX.md @@ -1209,6 +1209,13 @@ export const E2E_MAIL_RELAY_URL = process.env.E2E_MAIL_RELAY_URL || undefined /** `iapl({ mail })` for the test, `undefined` (the plugin's defaults) otherwise. */ export const e2eMail = E2E_MAIL_RELAY_URL ? { relay: { retryBackoffMs: 50, url: E2E_MAIL_RELAY_URL } } : undefined + +/** + * `iapl({ developmentHosts })` for a test that plays a development address on this machine (the built-in + * pattern, `*.dev.netscale.pl`, cannot be served from localhost): E2E_DEVELOPMENT_HOSTS, comma-separated + * patterns. `undefined` (the plugin's built-in list) otherwise. + */ +export const e2eDevelopmentHosts = process.env.E2E_DEVELOPMENT_HOSTS ? process.env.E2E_DEVELOPMENT_HOSTS.split(',').map((p) => p.trim()).filter(Boolean) : undefined ``` ### `e2e/mail-relay-setup.ts` diff --git a/docs/email.md b/docs/email.md index 94bd78b..f248416 100644 --- a/docs/email.md +++ b/docs/email.md @@ -285,6 +285,7 @@ await runWithMailKind('account', () => sendWelcomeMails(payload, user)) 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 list is about mail only: it does **not** make a development host noindex. Keeping development addresses out of search engines stays the hosting's business (Coolify) or `IAPL_NOINDEX=1`. - The panel state (`nonPublicBy`, `nonPublicPattern`), `siteNonPublicSignal(payload)` and the doctor (`mail-non-public`) say which of the two applies. diff --git a/src/types.ts b/src/types.ts index 9eade1c..baae410 100644 --- a/src/types.ts +++ b/src/types.ts @@ -140,7 +140,8 @@ export type IaplOptions = { * 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 + * pass `[]` so that no host is a development address. Mail only: the option does not make a + * development host noindex (that is the hosting's business, or `IAPL_NOINDEX=1`). `mail.relay.developmentHosts` overrides it * for the mail service alone. */ developmentHosts?: string[] From 6c4e2440940675236ca519bb4b4e577b54b13d09 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rados=C5=82aw=20Smoli=C5=84ski?= Date: Thu, 26 Nov 2026 10:57:32 +0100 Subject: [PATCH 6/6] Development hosts, review V-1 to V-3: a malformed list stops the start, a trailing dot and Unicode patterns match, every send reads the store - V-1: assertDevelopmentHosts - iapl({ developmentHosts }), mail.relay.developmentHosts and mailAdapter({ relay }) refuse anything but an array of non-empty host patterns, and a pattern of `*` alone (it would make the public site a development address). Nothing is ignored silently any more. - V-2: one trailing dot of the host is stripped before matching; patterns are punycoded, so one written in Unicode matches; a `*` inside a non-ASCII label is refused. - V-3: the 30-second memory of other hosts is gone. A dump restored into a running development site stops its very next e-mail. - docs, AGENT.md, changelog draft, skills Co-Authored-By: Claude Fable 5.2 --- docs/CHANGELOG.md | 4 +- docs/agent/AGENT.md | 2 +- docs/agent/skills/iapl-debug/SKILL.md | 1 + docs/agent/skills/iapl-setup/SKILL.md | 2 +- docs/agent/skills/iapl-upgrade/SKILL.md | 2 +- docs/email.md | 4 +- reference/.agents/skills/iapl-debug/SKILL.md | 1 + reference/.agents/skills/iapl-setup/SKILL.md | 2 +- .../.agents/skills/iapl-upgrade/SKILL.md | 2 +- src/index.ts | 2 +- src/modules/email/mailAdapter.ts | 3 ++ src/modules/email/relay/options.ts | 6 ++- src/modules/email/relay/session.ts | 28 ++-------- src/modules/shared/developmentHosts.ts | 53 ++++++++++++++++++- src/plugin.ts | 4 +- src/types.ts | 4 +- test/mailRelay.test.ts | 50 ++++++++++++++--- test/plugin.test.ts | 11 +++- 18 files changed, 135 insertions(+), 46 deletions(-) diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md index ba1cd46..03a7b38 100644 --- a/docs/CHANGELOG.md +++ b/docs/CHANGELOG.md @@ -109,7 +109,9 @@ once there are more than 20. 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`). + `isDevelopmentHost`, `assertDevelopmentHosts`, `pluginDevelopmentHosts`, `siteIsNonPublic`, `siteNonPublicSignal` (`NonPublicSignal`). + A malformed list (not an array of non-empty host patterns, or a lone `*`) stops the start instead of being + ignored; patterns are punycoded, a trailing dot and the port are ignored. Doctor: `mail-non-public` (info, deep) names the signal that makes a site non-public. The list is about mail only: it does not make a development host noindex. Keeping development addresses out of search engines stays the hosting's business (Coolify) or `IAPL_NOINDEX=1`. Nothing changes in what a site serves to robots on upgrade. - **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"; diff --git a/docs/agent/AGENT.md b/docs/agent/AGENT.md index 14b27e4..2039b7d 100644 --- a/docs/agent/AGENT.md +++ b/docs/agent/AGENT.md @@ -1335,7 +1335,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` | `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 | +| `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. Checked when the config is built (`assertDevelopmentHosts`): not an array of non-empty host patterns, or a lone `*` → the site does not start; Unicode patterns are punycoded, a trailing dot and the port are ignored | | `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 3fb1e8e..08163ff 100644 --- a/docs/agent/skills/iapl-debug/SKILL.md +++ b/docs/agent/skills/iapl-debug/SKILL.md @@ -103,6 +103,7 @@ through this procedure. Ask only when you are missing something you cannot get y | `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 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 })` | +| the site does not start: "[iapl] … developmentHosts must be an array of host patterns …" | the list is not an array of non-empty host patterns (a single string, `null`, `['']`), or holds a lone `*` | write it as `['*.dev.netscale.pl', 'staging.client.pl']`; `[]` = none; to change who waits use `mail.relay.otherHosts` | | 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 | diff --git a/docs/agent/skills/iapl-setup/SKILL.md b/docs/agent/skills/iapl-setup/SKILL.md index c8584be..ba795c4 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 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 + 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: […] })` (an array of host patterns: a single string, an empty entry or a lone `*` stops the start) 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 4805138..eee6aef 100644 --- a/docs/agent/skills/iapl-upgrade/SKILL.md +++ b/docs/agent/skills/iapl-upgrade/SKILL.md @@ -576,7 +576,7 @@ PROGRAMISTA §6, item 73; email.md; AGENT.md §7.2) — nothing to run; read whi **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 **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 + team's development addresses need no env and no edit; add the project's other copy hosts to the list (an array of host patterns; a string, an empty entry or a lone `*` stops the start) — 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 diff --git a/docs/email.md b/docs/email.md index f248416..45c684d 100644 --- a/docs/email.md +++ b/docs/email.md @@ -284,6 +284,7 @@ await runWithMailKind('account', () => sendWelcomeMails(payload, user)) 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. +- A malformed list stops the start (`assertDevelopmentHosts`): the value must be an array of non-empty host patterns — a single string, `null`, a number, an empty string, a scheme or a path are refused, and so is a pattern made of `*` alone (it would make the public site a development address). Patterns are compared as hosts are written on the wire: lowercase, punycode (a pattern may be written in Unicode), a trailing dot ignored, the port ignored. - **By the variable.** `IAPL_NOINDEX=1` marks any other staging, preview or test copy. - The list is about mail only: it does **not** make a development host noindex. Keeping development addresses out of search engines stays the hosting's business (Coolify) or `IAPL_NOINDEX=1`. - The panel state (`nonPublicBy`, `nonPublicPattern`), `siteNonPublicSignal(payload)` and the doctor @@ -316,7 +317,8 @@ await runWithMailKind('account', () => sendWelcomeMails(payload, user)) 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. + once the real domain has enrolled. The check reads the database at every send, so a dump restored into a running + development site stops its very next 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; 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 diff --git a/reference/.agents/skills/iapl-debug/SKILL.md b/reference/.agents/skills/iapl-debug/SKILL.md index 3fb1e8e..08163ff 100644 --- a/reference/.agents/skills/iapl-debug/SKILL.md +++ b/reference/.agents/skills/iapl-debug/SKILL.md @@ -103,6 +103,7 @@ through this procedure. Ask only when you are missing something you cannot get y | `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 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 })` | +| the site does not start: "[iapl] … developmentHosts must be an array of host patterns …" | the list is not an array of non-empty host patterns (a single string, `null`, `['']`), or holds a lone `*` | write it as `['*.dev.netscale.pl', 'staging.client.pl']`; `[]` = none; to change who waits use `mail.relay.otherHosts` | | 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 | diff --git a/reference/.agents/skills/iapl-setup/SKILL.md b/reference/.agents/skills/iapl-setup/SKILL.md index c8584be..ba795c4 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 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 + 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: […] })` (an array of host patterns: a single string, an empty entry or a lone `*` stops the start) 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 4805138..eee6aef 100644 --- a/reference/.agents/skills/iapl-upgrade/SKILL.md +++ b/reference/.agents/skills/iapl-upgrade/SKILL.md @@ -576,7 +576,7 @@ PROGRAMISTA §6, item 73; email.md; AGENT.md §7.2) — nothing to run; read whi **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 **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 + team's development addresses need no env and no edit; add the project's other copy hosts to the list (an array of host patterns; a string, an empty entry or a lone `*` stops the start) — 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 diff --git a/src/index.ts b/src/index.ts index f39f4ac..da55583 100644 --- a/src/index.ts +++ b/src/index.ts @@ -519,7 +519,7 @@ export type { SitemapRouteOptions, SitemapStyleOptions } from './modules/seo/ind 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 { assertDevelopmentHosts, 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/email/mailAdapter.ts b/src/modules/email/mailAdapter.ts index bcb62d4..64a87ae 100644 --- a/src/modules/email/mailAdapter.ts +++ b/src/modules/email/mailAdapter.ts @@ -2,6 +2,7 @@ import type { PayloadEmailAdapter, SendEmailOptions } from 'payload' import { type IntegrationStatus, recordIntegrationStatus } from '../integrations/status.js' import { getSiteIntegrations } from '../payload/index.js' +import { assertDevelopmentHosts } from '../shared/developmentHosts.js' import { sendAccountMailAfterCommit } from './accountMailAfterCommit.js' import { graphAdapter, type GraphAdapterArgs, graphLargeAttachmentSupport } from './graphAdapter.js' import { attachmentBytes, GRAPH_INLINE_MAX_BYTES, toGraphAttachments } from './graphAttachments.js' @@ -112,6 +113,8 @@ export function graphAvailable(): boolean { export const mailAdapter = (args: MailAdapterArgs = {}): PayloadEmailAdapter => (deps) => { + // a malformed list must stop the start, not be found at the first e-mail of a copy + if (args.relay && args.relay.developmentHosts !== undefined) {assertDevelopmentHosts(args.relay.developmentHosts, 'mailAdapter({ relay: { developmentHosts } })')} // Build both delegates once; each still resolves its own config per send. const smtp = panelSmtpAdapter({ fallbackFromAddress: args.fallbackFromAddress, diff --git a/src/modules/email/relay/options.ts b/src/modules/email/relay/options.ts index 7d89d4f..4db6762 100644 --- a/src/modules/email/relay/options.ts +++ b/src/modules/email/relay/options.ts @@ -2,7 +2,7 @@ import type { BasePayload, SendEmailOptions } from 'payload' import type { MailKind } from './kinds.js' -import { DEFAULT_DEVELOPMENT_HOSTS } from '../../shared/developmentHosts.js' +import { assertDevelopmentHosts, DEFAULT_DEVELOPMENT_HOSTS } from '../../shared/developmentHosts.js' import { RELAY_BASE_URL } from './constants.js' /** @@ -102,7 +102,8 @@ export function pluginMailOptions(payload: Pick): PluginM */ 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] + // (written by iapl(), which refuses a malformed list; a value put here by hand is checked the same way) + return own === undefined ? [...DEFAULT_DEVELOPMENT_HOSTS] : assertDevelopmentHosts(own, 'config.custom.iapl.developmentHosts') } /** @@ -113,6 +114,7 @@ export function resolveRelayOptions(payload: Pick, own?: const fromPlugin = pluginMailOptions(payload).relay if (own === false || (own === undefined && fromPlugin === false)) {return null} const merged: RelayOptions = { ...(fromPlugin || {}), ...(own || {}) } + if (merged.developmentHosts !== undefined) {assertDevelopmentHosts(merged.developmentHosts, 'mail.relay.developmentHosts')} const url = (merged.url ?? RELAY_BASE_URL).replace(/\/+$/, '') return { ...merged, developmentHosts: merged.developmentHosts ?? pluginDevelopmentHosts(payload), ownUrl: url !== RELAY_BASE_URL, url } } diff --git a/src/modules/email/relay/session.ts b/src/modules/email/relay/session.ts index 483ee7b..e3995ab 100644 --- a/src/modules/email/relay/session.ts +++ b/src/modules/email/relay/session.ts @@ -77,23 +77,6 @@ export function enrolRelay(payload: BasePayload, options: ResolvedRelayOptions, return run } -/** 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\./, '') /** Why a site counts as non-public: its host matches a development pattern, or `IAPL_NOINDEX` is set. */ @@ -125,13 +108,12 @@ export function siteIsNonPublic(payload: BasePayload, options: Pick, stored: RelayStored, - { fresh = true }: { fresh?: boolean } = {}, ): Promise { const mode = options.otherHosts if (mode === 'enrol') {return []} @@ -139,7 +121,7 @@ export async function otherHostsInTheWay( 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))) + return (await otherRelayHosts(payload, relayHost(payload, options))).filter((h) => !own.includes(bare(h))) } const otherHostMessage = (host: string, foreign: string[]) => @@ -168,7 +150,7 @@ async function enrolOnce(payload: BasePayload, options: ResolvedRelayOptions, fo // 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 others = force ? await otherRelayHosts(payload, host) : [] const foreign = force ? [] : await otherHostsInTheWay(payload, options, stored) if (foreign.length) { const message = otherHostMessage(host, foreign) @@ -215,7 +197,6 @@ 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. @@ -310,7 +291,7 @@ export async function withRelayToken( 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 }) + const foreign = await otherHostsInTheWay(payload, options, stored) if (foreign.length) {return refusal(LOCAL_CODES.otherHost, otherHostMessage(relayHost(payload, options), foreign), { reason: foreign[0] })} } @@ -495,7 +476,6 @@ export async function setRelayToken(payload: BasePayload, token: string, options // 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, diff --git a/src/modules/shared/developmentHosts.ts b/src/modules/shared/developmentHosts.ts index 3a6383f..619bced 100644 --- a/src/modules/shared/developmentHosts.ts +++ b/src/modules/shared/developmentHosts.ts @@ -19,7 +19,8 @@ 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() + // (a fully qualified name may end in a dot — `acme.dev.example.pl.` is the same host) + return new URL(/^[a-z][a-z0-9+.-]*:\/\//i.test(raw) ? raw : `https://${raw}`).host.toLowerCase().replace(/\.(?=:\d+$|$)/, '') } catch { return '' } @@ -33,12 +34,60 @@ export function matchDevelopmentHost(host: null | string | undefined, patterns: 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('.*') + // a pattern is compared the way hosts are written on the wire: lowercase, punycode, no trailing dot + const written = typeof pattern === 'string' ? (asciiPattern(pattern) ?? pattern.trim().toLowerCase()) : '' + const source = written.split('*').map((part) => part.replace(/[.+?^${}()|[\]\\]/g, '\\$&')).join('.*') if (source && new RegExp(`^${source}$`).test(name)) {return pattern} } return null } +const STAR = 'zq9star9qz' + +/** + * A pattern as hosts are written: lowercase, punycode (`*.dev.zażółć.pl` → `*.dev.xn--za-….pl`), no trailing + * dot, no port. null when it is not a host pattern at all (empty, a space inside, a `*` in a label with + * non-ASCII letters, …). + */ +function asciiPattern(pattern: string): null | string { + const raw = pattern.trim().toLowerCase().replace(/\.$/, '') + if (!raw || /[\s/@?#\\]/.test(raw)) {return null} + const stars = raw.split('*').length - 1 + try { + const host = new URL(`https://${raw.replaceAll('*', STAR)}`).hostname + // (a `*` inside a punycoded label would stand for nothing a person could mean) + if (host.split(STAR).length - 1 !== stars || host.split('.').some((label) => label.startsWith('xn--') && label.includes(STAR))) {return null} + return host.replaceAll(STAR, '*') + } catch { + return null + } +} + +/** + * Checks a `developmentHosts` value when the project's config is built, and returns the list as given. + * Throws — the site does not start — on anything but an array of host patterns, because a list that is + * silently ignored or silently empty means a copy of production's data mails real people: + * - not an array (a single string, `null`, an object); + * - an entry that is not a non-empty string, or not a host pattern; + * - a pattern made of `*` alone (with or without dots): it would make EVERY host a development address, + * the public site included. To switch the mail rule's waiting off or on for all hosts use + * `mail.relay.otherHosts` instead. + * `[]` is valid: no host is a development address. `undefined` is not checked here (the default applies). + */ +export function assertDevelopmentHosts(value: unknown, option = 'developmentHosts'): string[] { + const fail = (why: string): never => { + throw new Error(`[iapl] ${option} must be an array of host patterns such as ['*.dev.netscale.pl'] ([] = none): ${why}. Got ${JSON.stringify(value)}.`) + } + if (!Array.isArray(value)) {return fail('it is not an array')} + value.forEach((entry, index) => { + if (typeof entry !== 'string' || !entry.trim()) {fail(`entry ${index} is not a non-empty string`)} + const written = asciiPattern(entry as string) + if (!written) {fail(`entry ${index} ("${entry}") is not a host pattern — a host name with \`*\` for any characters, no scheme, no path`)} + if (!/[^*.]/.test(written as string)) {fail(`entry ${index} ("${entry}") matches every host, so the public site would count as a development address`)} + }) + return value as string[] +} + /** 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 0cc8df9..2dd37f1 100644 --- a/src/plugin.ts +++ b/src/plugin.ts @@ -66,6 +66,7 @@ import { buildIndexNowHook } from './modules/seo/indexNow.js' import { searchSettingsFields } from './modules/seo/searchSettings.js' import { migrateTitleSeparator } from './modules/seo/titleSeparator.js' import { applyCollectionOverride } from './modules/shared/collectionOverride.js' +import { assertDevelopmentHosts } from './modules/shared/developmentHosts.js' import { buildStatsCollection, buildStatsEndpoint } from './modules/stats/index.js' import { visitorCookieFor } from './modules/stats/visitorCookie.js' @@ -753,10 +754,11 @@ export const iapl = (options: IaplOptions): Plugin => { // --- e-mail: the Intecion Notifications Webservice (docs/email.md; off with mail: { relay: false }) --- // What mailAdapter() reads at send time; born under the new name (`custom.iapl`). const relay = options.mail?.relay + if (relay && relay.developmentHosts !== undefined) {assertDevelopmentHosts(relay.developmentHosts, 'iapl({ mail: { relay: { developmentHosts } } })')} const iaplCustom = (config.custom?.iapl ?? {}) as object config.custom = { ...config.custom, - iapl: { ...iaplCustom, ...(Array.isArray(options.developmentHosts) ? { developmentHosts: [...options.developmentHosts] } : {}), mail: { ...(options.mail?.graphDeprecationWarning === false ? { graphDeprecationWarning: false } : {}), relay: relay === false ? false : (relay ?? {}) } }, + iapl: { ...iaplCustom, ...(options.developmentHosts !== undefined ? { developmentHosts: [...assertDevelopmentHosts(options.developmentHosts, 'iapl({ 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 baae410..11dce12 100644 --- a/src/types.ts +++ b/src/types.ts @@ -140,7 +140,9 @@ export type IaplOptions = { * 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 only: the option does not make a + * pass `[]` so that no host is a development address. Anything but an array of non-empty host + * patterns, and a pattern of `*` alone, stops the start (`assertDevelopmentHosts`); a pattern may + * be written in Unicode (it is punycoded), a trailing dot and the port are ignored. Mail only: the option does not make a * development host noindex (that is the hosting's business, or `IAPL_NOINDEX=1`). `mail.relay.developmentHosts` overrides it * for the mail service alone. */ diff --git a/test/mailRelay.test.ts b/test/mailRelay.test.ts index 22e382d..3968fc5 100644 --- a/test/mailRelay.test.ts +++ b/test/mailRelay.test.ts @@ -21,11 +21,11 @@ import { bareAddresses, buildRelayMessage, cleanSubject } from '../src/modules/e 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, siteNonPublicSignal } from '../src/modules/email/relay/session.js' +import { disconnectRelay, enrolRelay, 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 { assertDevelopmentHosts, 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' @@ -754,7 +754,6 @@ describe('the token over time', () => { 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) @@ -784,7 +783,6 @@ describe('the token over time', () => { // 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' }) @@ -798,7 +796,6 @@ describe('the token over time', () => { 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) @@ -897,6 +894,48 @@ describe('the token over time', () => { expect((await sendThroughRelay(copy.payload, { ...copy.options, developmentHosts: [] }, MESSAGE)).sent).toBe(true) }) + test('V-3: production\'s dump restored into the RUNNING development site right after it sent a mail — the very next mail is refused', async () => { + const live = shared({ serverURL: 'https://client.pl' }) + await sendThroughRelay(live.payload, live.options, MESSAGE) + const dev = shared({ serverURL: `https://${DEV}` }) + const on = { ...dev.options, fetchImpl: live.fake.fetch, url: live.fake.url } + // the development site is connected and has just sent (its own database, its own data) + await setRelayToken(dev.payload, live.fake.issueToken(DEV), on) + expect((await sendThroughRelay(dev.payload, on, MESSAGE)).sent).toBe(true) + // the restore: production's entries land in the database of the running process + for (const [key, value] of live.store) {dev.store.set(key, structuredClone(value))} + const requests = live.fake.requests.length + expect(await sendThroughRelay(dev.payload, on, { ...MESSAGE, to: 'a-real-customer@example.org' })).toMatchObject({ cause: 'client-other-host', sent: false }) + expect(live.fake.requests).toHaveLength(requests) + expect((await mailPanelState({ payload: dev.payload }, on)).relay?.refusal).toMatchObject({ code: 'client-other-host', reason: 'client.pl' }) + }) + + test('V-1, V-2: a malformed list stops the start; a trailing dot and a Unicode pattern still match', async () => { + // what is refused — by the checker, by the options in effect, by a value left in the config by hand + for (const bad of ['*.dev.netscale.pl', null, {}, [1, 2], [''], [' '], ['*.dev.netscale.pl', 7], ['*'], ['*.*'], [' * '], ['https://x.dev.example.com'], ['x.example.com/path'], ['a b.example.com'], ['*ż.example.com']]) { + expect(() => assertDevelopmentHosts(bad), JSON.stringify(bad)).toThrow(/must be an array of host patterns/) + const site = relayPayload({ custom: { iapl: { developmentHosts: bad } } }) + expect(() => resolveRelayOptions(site.payload, {}), JSON.stringify(bad)).toThrow(/developmentHosts/) + expect(() => resolveRelayOptions(relayPayload().payload, { developmentHosts: bad as never }), JSON.stringify(bad)).toThrow(/mail\.relay\.developmentHosts/) + } + expect(() => assertDevelopmentHosts(['*'])).toThrow(/matches every host/) + expect(() => assertDevelopmentHosts('*.dev.netscale.pl', 'iapl({ developmentHosts })')).toThrow('[iapl] iapl({ developmentHosts }) must be an array') + // what is taken + for (const good of [[], ['*.dev.netscale.pl'], ['staging.client.pl', '*.Preview.Agency-Example.com ', 'acme.*', '*.dev.zażółć.pl', '*.dev.netscale.pl.']]) {expect(assertDevelopmentHosts(good)).toBe(good)} + // a fully qualified name with the dot, in the address and in the pattern + expect(matchDevelopmentHost('https://acme.dev.netscale.pl.')).toBe('*.dev.netscale.pl') + expect(matchDevelopmentHost('https://acme.dev.netscale.pl.:8443/pl')).toBe('*.dev.netscale.pl') + expect(matchDevelopmentHost('acme.dev.netscale.pl', ['*.dev.netscale.pl.'])).toBe('*.dev.netscale.pl.') + const dotted = relayPayload({ serverURL: 'https://acme.dev.netscale.pl.' }) + expect(siteNonPublicSignal(dotted.payload, resolveRelayOptions(dotted.payload, {})!)).toEqual({ by: 'development-host', pattern: '*.dev.netscale.pl' }) + // a pattern written in Unicode matches the punycode host, and the other way round + expect(matchDevelopmentHost('https://acme.dev.zażółć.pl', ['*.dev.zażółć.pl'])).toBe('*.dev.zażółć.pl') + expect(new URL('https://zażółć.pl').hostname).toMatch(/^xn--/) + expect(matchDevelopmentHost(`acme.dev.${new URL('https://zażółć.pl').hostname}`, ['*.dev.ZAŻÓŁĆ.pl'])).toBe('*.dev.ZAŻÓŁĆ.pl') + expect(matchDevelopmentHost('https://acme.dev.zażółć.pl', [`*.dev.${new URL('https://zażółć.pl').hostname}`])).not.toBeNull() + expect(matchDevelopmentHost('acme.dev.zazolc.pl', ['*.dev.zażółć.pl'])).toBeNull() + }) + 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) @@ -933,7 +972,6 @@ describe('the token over time', () => { 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 }) }) diff --git a/test/plugin.test.ts b/test/plugin.test.ts index dd535e0..47b98f4 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 { mailAdapter } from '../src/modules/email/mailAdapter.js' import { pluginDevelopmentHosts } from '../src/modules/email/relay/options.js' import { iapl } from '../src/plugin.js' import { withTotpParts } from './helpers.js' @@ -24,13 +25,19 @@ const base = (): 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()) + const hosts = async (...own: [string[]?]) => { + const config = await iapl({ access: { authCollection: 'users' }, i18n, twoFactor: false, ...(own.length ? { developmentHosts: own[0] } : {}) })(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([]) + // V-1: a malformed list stops the start — the plugin option, the mail option, the adapter's own + for (const bad of ['*.dev.netscale.pl', null, [1, 2], [''], ['*']]) { + await expect(hosts(bad as never), JSON.stringify(bad)).rejects.toThrow('[iapl] iapl({ developmentHosts }) must be an array of host patterns') + await expect(Promise.resolve().then(() => iapl({ access: { authCollection: 'users' }, i18n, mail: { relay: { developmentHosts: bad as never } }, twoFactor: false })(base()))).rejects.toThrow('iapl({ mail: { relay: { developmentHosts } } })') + expect(() => mailAdapter({ relay: { developmentHosts: bad as never } })({ payload: {} as never }), JSON.stringify(bad)).toThrow('mailAdapter({ relay: { developmentHosts } })') + } }) test('adds globals, endpoint, localization and roles', async () => {