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 <[email protected]>
This commit is contained in:
Radosław Smoliński
2026-11-26 10:57:32 +01:00
co-authored by Claude Fable 5.2
parent 99c73ed0ff
commit 6c4e244094
18 changed files with 135 additions and 46 deletions
+3 -1
View File
@@ -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). 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 `*.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`, 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. 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 - **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"; reply address, what is left of the limits, a replaced sender name; "Check now", "Connect again", "Disconnect";
+1 -1
View File
@@ -1335,7 +1335,7 @@ overrides per adapter; `resolveRelayOptions` reads what is in effect):
| `url` | `RELAY_BASE_URL` | a relay of your own (same contract) | | `url` | `RELAY_BASE_URL` | a relay of your own (same contract) |
| `host` | host of `serverURL` (`relayHost`, `isPublicHost`) | the public host the service calls back | | `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) | | `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`) | | `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) | | `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 | | `token` | — | a token from elsewhere; nothing is stored, the site does not enrol |
+1
View File
@@ -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`, 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") | | `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 })` | | 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', '<the copy's pattern>'] })`, or `IAPL_NOINDEX=1` on the copy; to be sure: `mail: { relay: false }` or SMTP to a catcher | | 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', '<the copy's pattern>'] })`, 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-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-suspended` | Intecion stopped the site (abuse, a flood from a form) | contact Intecion; fill in SMTP meanwhile |
+1 -1
View File
@@ -646,7 +646,7 @@ scaling (5). `●` routes for pages need the database at build time (PROGRAMISTA
6. **Notifications**: form messages in every language. 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 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 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 `1x00000000000000000000AA`, secret `1x0000000000000000000000000000000AA`; production keys from the client), analytics/pixel
IDs, IndexNow → generate key. Mail/Turnstile errors show up as a dashboard alert. 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. 8. **Forms**: check the addresses in the Emails tab of the seeded forms.
+1 -1
View File
@@ -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 **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 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 **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 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 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 with `mail: { relay: false }` or SMTP to a catcher. Production must not have `IAPL_NOINDEX` set (it would send
+3 -1
View File
@@ -284,6 +284,7 @@ await runWithMailKind('account', () => sendWelcomeMails(payload, user))
other: **replace it** with your own patterns (`developmentHosts: ['*.preview.agency.example', 'staging.client.pl']`), 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 or pass **`[]`** so that no host is a development address. `mail: { relay: { developmentHosts } }` overrides the
list for the mail service alone. 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. - **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 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 - 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). called back at that host).
- After "Connect again" a copy sends until its data is replaced. - 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 - 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 - **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. 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 - **`otherHosts`** changes the rule: a list (`['client.dev.agency.example']`) names hosts as this site's own — a
@@ -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`, 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") | | `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 })` | | 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', '<the copy's pattern>'] })`, or `IAPL_NOINDEX=1` on the copy; to be sure: `mail: { relay: false }` or SMTP to a catcher | | 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', '<the copy's pattern>'] })`, 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-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-suspended` | Intecion stopped the site (abuse, a flood from a form) | contact Intecion; fill in SMTP meanwhile |
+1 -1
View File
@@ -646,7 +646,7 @@ scaling (5). `●` routes for pages need the database at build time (PROGRAMISTA
6. **Notifications**: form messages in every language. 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 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 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 `1x00000000000000000000AA`, secret `1x0000000000000000000000000000000AA`; production keys from the client), analytics/pixel
IDs, IndexNow → generate key. Mail/Turnstile errors show up as a dashboard alert. 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. 8. **Forms**: check the addresses in the Emails tab of the seeded forms.
@@ -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 **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 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 **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 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 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 with `mail: { relay: false }` or SMTP to a catcher. Production must not have `IAPL_NOINDEX` set (it would send
+1 -1
View File
@@ -519,7 +519,7 @@ export type { SitemapRouteOptions, SitemapStyleOptions } from './modules/seo/ind
export { applyCollectionOverride } from './modules/shared/collectionOverride.js' export { applyCollectionOverride } from './modules/shared/collectionOverride.js'
export type { CollectionOverride } 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`. // 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 { clientIp, setRateLimitStore, setUnknownIpFactor, UNKNOWN_IP_FACTOR } from './modules/shared/rateLimit.js'
export type { ClientIpOptions, RateLimitStore } from './modules/shared/rateLimit.js' export type { ClientIpOptions, RateLimitStore } from './modules/shared/rateLimit.js'
export { buildSlugField, toSlug } from './modules/slug/index.js' export { buildSlugField, toSlug } from './modules/slug/index.js'
+3
View File
@@ -2,6 +2,7 @@ import type { PayloadEmailAdapter, SendEmailOptions } from 'payload'
import { type IntegrationStatus, recordIntegrationStatus } from '../integrations/status.js' import { type IntegrationStatus, recordIntegrationStatus } from '../integrations/status.js'
import { getSiteIntegrations } from '../payload/index.js' import { getSiteIntegrations } from '../payload/index.js'
import { assertDevelopmentHosts } from '../shared/developmentHosts.js'
import { sendAccountMailAfterCommit } from './accountMailAfterCommit.js' import { sendAccountMailAfterCommit } from './accountMailAfterCommit.js'
import { graphAdapter, type GraphAdapterArgs, graphLargeAttachmentSupport } from './graphAdapter.js' import { graphAdapter, type GraphAdapterArgs, graphLargeAttachmentSupport } from './graphAdapter.js'
import { attachmentBytes, GRAPH_INLINE_MAX_BYTES, toGraphAttachments } from './graphAttachments.js' import { attachmentBytes, GRAPH_INLINE_MAX_BYTES, toGraphAttachments } from './graphAttachments.js'
@@ -112,6 +113,8 @@ export function graphAvailable(): boolean {
export const mailAdapter = export const mailAdapter =
(args: MailAdapterArgs = {}): PayloadEmailAdapter => (args: MailAdapterArgs = {}): PayloadEmailAdapter =>
(deps) => { (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. // Build both delegates once; each still resolves its own config per send.
const smtp = panelSmtpAdapter({ const smtp = panelSmtpAdapter({
fallbackFromAddress: args.fallbackFromAddress, fallbackFromAddress: args.fallbackFromAddress,
+4 -2
View File
@@ -2,7 +2,7 @@ import type { BasePayload, SendEmailOptions } from 'payload'
import type { MailKind } from './kinds.js' 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' import { RELAY_BASE_URL } from './constants.js'
/** /**
@@ -102,7 +102,8 @@ export function pluginMailOptions(payload: Pick<BasePayload, 'config'>): PluginM
*/ */
export function pluginDevelopmentHosts(payload: Pick<BasePayload, 'config'>): string[] { export function pluginDevelopmentHosts(payload: Pick<BasePayload, 'config'>): string[] {
const own = (payload.config?.custom as { iapl?: { developmentHosts?: unknown } } | undefined)?.iapl?.developmentHosts 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<BasePayload, 'config'>, own?:
const fromPlugin = pluginMailOptions(payload).relay const fromPlugin = pluginMailOptions(payload).relay
if (own === false || (own === undefined && fromPlugin === false)) {return null} if (own === false || (own === undefined && fromPlugin === false)) {return null}
const merged: RelayOptions = { ...(fromPlugin || {}), ...(own || {}) } const merged: RelayOptions = { ...(fromPlugin || {}), ...(own || {}) }
if (merged.developmentHosts !== undefined) {assertDevelopmentHosts(merged.developmentHosts, 'mail.relay.developmentHosts')}
const url = (merged.url ?? RELAY_BASE_URL).replace(/\/+$/, '') const url = (merged.url ?? RELAY_BASE_URL).replace(/\/+$/, '')
return { ...merged, developmentHosts: merged.developmentHosts ?? pluginDevelopmentHosts(payload), ownUrl: url !== RELAY_BASE_URL, url } return { ...merged, developmentHosts: merged.developmentHosts ?? pluginDevelopmentHosts(payload), ownUrl: url !== RELAY_BASE_URL, url }
} }
+4 -24
View File
@@ -77,23 +77,6 @@ export function enrolRelay(payload: BasePayload, options: ResolvedRelayOptions,
return run 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<object, { at: number; host: string; hosts: string[] }>()
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<string[]> {
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\./, '') 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. */ /** 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<RelayOptions
* told about holds a copy of that site's data. Also when it has a token of its own: production's * told about holds a copy of that site's data. Also when it has a token of its own: production's
* database copied BACK onto the development address brings the development site's old entry with it. * database copied BACK onto the development address brings the development site's old entry with it.
* Hosts the project named as its own, and hosts an admin accepted with "Connect again", do not count. * Hosts the project named as its own, and hosts an admin accepted with "Connect again", do not count.
* `fresh`: read the store now (an enrolment); otherwise what was seen in the last half minute. * Always read from the store now: a restored dump must stop the very next e-mail, not one half a minute later.
*/ */
export async function otherHostsInTheWay( export async function otherHostsInTheWay(
payload: BasePayload, payload: BasePayload,
options: Pick<ResolvedRelayOptions, 'developmentHosts' | 'host' | 'otherHosts'>, options: Pick<ResolvedRelayOptions, 'developmentHosts' | 'host' | 'otherHosts'>,
stored: RelayStored, stored: RelayStored,
{ fresh = true }: { fresh?: boolean } = {},
): Promise<string[]> { ): Promise<string[]> {
const mode = options.otherHosts const mode = options.otherHosts
if (mode === 'enrol') {return []} if (mode === 'enrol') {return []}
@@ -139,7 +121,7 @@ export async function otherHostsInTheWay(
if (mode === 'wait' && connected) {return []} if (mode === 'wait' && connected) {return []}
if (mode !== 'wait' && !siteIsNonPublic(payload, options)) {return []} if (mode !== 'wait' && !siteIsNonPublic(payload, options)) {return []}
const own = [...(Array.isArray(mode) ? mode : []), ...(stored.acceptedHosts ?? [])].map(bare) 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[]) => 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 // 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. // 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) const foreign = force ? [] : await otherHostsInTheWay(payload, options, stored)
if (foreign.length) { if (foreign.length) {
const message = otherHostMessage(host, foreign) const message = otherHostMessage(host, foreign)
@@ -215,7 +197,6 @@ async function enrolOnce(payload: BasePayload, options: ResolvedRelayOptions, fo
token: candidate.token, token: candidate.token,
})) }))
await dropRelayCandidate(payload, options) await dropRelayCandidate(payload, options)
forgetOtherHosts(payload)
return { ok: true, state } return { ok: true, state }
} }
// Used or not, this nonce is over. A token the call-back did deliver stays beside the one in use. // 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<T>(
const token = candidate?.token ?? stored.token const token = candidate?.token ?? stored.token
// A non-public copy holding another site's data does not SEND by itself either, token or not. // A non-public copy holding another site's data does not SEND by itself either, token or not.
if (token && round === 0) { 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] })} 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 // 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 } options = { host: options.host ?? (pluginMailOptions(payload).relay || {}).host }
const others = await otherRelayHosts(payload, relayHost(payload, options)) const others = await otherRelayHosts(payload, relayHost(payload, options))
forgetOtherHosts(payload)
await dropRelayCandidate(payload, options) await dropRelayCandidate(payload, options)
await updateRelayStore(payload, options, (current) => ({ await updateRelayStore(payload, options, (current) => ({
...current, ...current,
+51 -2
View File
@@ -19,7 +19,8 @@ export function hostOf(value: null | string | undefined): string {
const raw = (value ?? '').trim() const raw = (value ?? '').trim()
if (!raw) {return ''} if (!raw) {return ''}
try { 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 { } catch {
return '' return ''
} }
@@ -33,12 +34,60 @@ export function matchDevelopmentHost(host: null | string | undefined, patterns:
const name = hostOf(host).replace(/:\d+$/, '') const name = hostOf(host).replace(/:\d+$/, '')
if (!name) {return null} if (!name) {return null}
for (const pattern of patterns) { 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} if (source && new RegExp(`^${source}$`).test(name)) {return pattern}
} }
return null 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)? */ /** 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 => export const isDevelopmentHost = (host: null | string | undefined, patterns: readonly string[] = DEFAULT_DEVELOPMENT_HOSTS): boolean =>
matchDevelopmentHost(host, patterns) !== null matchDevelopmentHost(host, patterns) !== null
+3 -1
View File
@@ -66,6 +66,7 @@ import { buildIndexNowHook } from './modules/seo/indexNow.js'
import { searchSettingsFields } from './modules/seo/searchSettings.js' import { searchSettingsFields } from './modules/seo/searchSettings.js'
import { migrateTitleSeparator } from './modules/seo/titleSeparator.js' import { migrateTitleSeparator } from './modules/seo/titleSeparator.js'
import { applyCollectionOverride } from './modules/shared/collectionOverride.js' import { applyCollectionOverride } from './modules/shared/collectionOverride.js'
import { assertDevelopmentHosts } from './modules/shared/developmentHosts.js'
import { buildStatsCollection, buildStatsEndpoint } from './modules/stats/index.js' import { buildStatsCollection, buildStatsEndpoint } from './modules/stats/index.js'
import { visitorCookieFor } from './modules/stats/visitorCookie.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 }) --- // --- 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`). // What mailAdapter() reads at send time; born under the new name (`custom.iapl`).
const relay = options.mail?.relay const relay = options.mail?.relay
if (relay && relay.developmentHosts !== undefined) {assertDevelopmentHosts(relay.developmentHosts, 'iapl({ mail: { relay: { developmentHosts } } })')}
const iaplCustom = (config.custom?.iapl ?? {}) as object const iaplCustom = (config.custom?.iapl ?? {}) as object
config.custom = { config.custom = {
...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 // "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). // commits, not inside it (mail.accountMailAfterCommit; docs/deployment.md §4.3a).
+3 -1
View File
@@ -140,7 +140,9 @@ export type IaplOptions = {
* matches is "non-public" with no environment variable: when its database holds the mail-service * 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 * 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 * (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 * development host noindex (that is the hosting's business, or `IAPL_NOINDEX=1`). `mail.relay.developmentHosts` overrides it
* for the mail service alone. * for the mail service alone.
*/ */
+44 -6
View File
@@ -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 { isPublicHost, pluginDevelopmentHosts, relayHost, resolveRelayOptions } from '../src/modules/email/relay/options.js'
import { mailPanelState } from '../src/modules/email/relay/panel.js' import { mailPanelState } from '../src/modules/email/relay/panel.js'
import { clearUnconfirmedRelayMessages, sendThroughRelay } from '../src/modules/email/relay/send.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 { 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 { NOTIFICATION_FALLBACK, NOTIFICATION_FALLBACK_PL } from '../src/modules/notifications/defaults.js'
import { resolveFormMessage } from '../src/modules/notifications/resolveFormMessage.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 { setRateLimitStore } from '../src/modules/shared/rateLimit.js'
import { callConfirmRoute, relayPayload, relaySite } from './mailRelay/helpers.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) await sendThroughRelay(apart.payload, apart.options, MESSAGE)
expect((await sendThroughRelay(apart.payload, apart.options, { ...MESSAGE, subject: 'Dev, later' })).sent).toBe(true) 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 // …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 const before = dev.fake.requests.length
expect(await sendThroughRelay(dev.payload, dev.options, { ...MESSAGE, to: '[email protected]' })).toMatchObject({ cause: 'client-other-host', code: 'relay-refused', sent: false }) expect(await sendThroughRelay(dev.payload, dev.options, { ...MESSAGE, to: '[email protected]' })).toMatchObject({ cause: 'client-other-host', code: 'relay-refused', sent: false })
expect(dev.fake.requests).toHaveLength(before) 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 // months later: production's data is copied back onto the development address, to work on a bug
copy(live.store, dev.store) 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 expect((await readRelayStore(dev.payload)).token).toMatch(/^ims_/) // its own old entry came back with the copy
const requests = service.requests.length const requests = service.requests.length
const held = await sendThroughRelay(dev.payload, dev.options, { ...MESSAGE, to: '[email protected]' }) const held = await sendThroughRelay(dev.payload, dev.options, { ...MESSAGE, to: '[email protected]' })
@@ -798,7 +796,6 @@ describe('the token over time', () => {
expect((await mailPanelState({ payload: dev.payload }, dev.options)).relay?.refusal).toBeUndefined() 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 // the next fresh copy is held again: the consent was this database's, and the copy replaced it
copy(live.store, dev.store) copy(live.store, dev.store)
forgetOtherHosts(dev.payload)
expect(await sendThroughRelay(dev.payload, dev.options, MESSAGE)).toMatchObject({ cause: 'client-other-host', sent: false }) expect(await sendThroughRelay(dev.payload, dev.options, MESSAGE)).toMatchObject({ cause: 'client-other-host', sent: false })
// production never noticed any of it // production never noticed any of it
expect((await readRelayStore(live.payload)).token).toBe(liveToken) 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) 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: '[email protected]' })).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 () => { 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' }) const production = shared({ serverURL: 'https://client.pl' })
await sendThroughRelay(production.payload, production.options, MESSAGE) 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() 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 // 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') vi.stubEnv('IAPL_NOINDEX', '1')
forgetOtherHosts(staging.payload)
expect(await sendThroughRelay(staging.payload, staging.options, MESSAGE)).toMatchObject({ cause: 'client-other-host', sent: false }) expect(await sendThroughRelay(staging.payload, staging.options, MESSAGE)).toMatchObject({ cause: 'client-other-host', sent: false })
}) })
+9 -2
View File
@@ -4,6 +4,7 @@ import { describe, expect, test, vi } from 'vitest'
import type { I18nConfig } from '../src/modules/i18n/types.js' 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 { pluginDevelopmentHosts } from '../src/modules/email/relay/options.js'
import { iapl } from '../src/plugin.js' import { iapl } from '../src/plugin.js'
import { withTotpParts } from './helpers.js' import { withTotpParts } from './helpers.js'
@@ -24,13 +25,19 @@ const base = (): Config =>
describe('iapl — config transform', () => { 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 () => { 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 hosts = async (...own: [string[]?]) => {
const config = await iapl({ access: { authCollection: 'users' }, i18n, twoFactor: false, ...(own ? { developmentHosts: own } : {}) })(base()) const config = await iapl({ access: { authCollection: 'users' }, i18n, twoFactor: false, ...(own.length ? { developmentHosts: own[0] } : {}) })(base())
return pluginDevelopmentHosts({ config } as never) return pluginDevelopmentHosts({ config } as never)
} }
expect(await hosts()).toEqual(['*.dev.netscale.pl']) expect(await hosts()).toEqual(['*.dev.netscale.pl'])
expect(await hosts(['*.preview.agency-example.com'])).toEqual(['*.preview.agency-example.com']) expect(await hosts(['*.preview.agency-example.com'])).toEqual(['*.preview.agency-example.com'])
expect(await hosts([])).toEqual([]) 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 () => { test('adds globals, endpoint, localization and roles', async () => {