Merge claude/mail-relay-dev-hosts: development hosts by pattern with no env, built in *.dev.netscale.pl

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
Radosław Smoliński
2026-11-26 11:08:15 +01:00
co-authored by Claude Opus 5.5
30 changed files with 457 additions and 110 deletions
+10 -1
View File
@@ -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 `[email protected]`. The site is active as soon as it enrols (the service holds a site for approval only as an exception) | `iapl({ mail: { relay: false } })` |
| Any site with the mail service enabled (the default) | **A new public route:** `POST /api/iapl/mail-relay/confirm` — answers `404` and changes nothing unless the site itself started an enrolment in the last 5 minutes; rate-limited. Three admin-only routes beside it (`…/status`, `…/connect`, `…/disconnect`) | `mail: { relay: false }` removes all four |
| **A copy** of a site's database on 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,15 @@ 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`, `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";
"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
+10 -7
View File
@@ -1290,14 +1290,17 @@ 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`). 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 <name>"; the mail arrives from
@@ -1332,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` | `[]` | 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. 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 |
+7
View File
@@ -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`
+3 -2
View File
@@ -102,8 +102,9 @@ through this procedure. Ask only when you are missing something you cannot get y
| `relay-refused` / "The mail service could not reach this site at …" (cause `callback-failed`) | `unreachable` / `timeout`: firewall, private network, wrong public host in `serverURL`; `redirect`: `trailingSlash: true`, apex → `www`, a language redirect; `status`: route blocked, missing (`mail: { relay: false }`?) or another `routes.api`; `confirmation`: a proxy rewrites the answer | `curl -i -X POST https://<host>/api/iapl/mail-relay/confirm -d '{}' -H 'content-type: application/json'` must answer **404 with an empty body, no redirect**; fix `serverURL` / `mail.relay.host`, or ask Intecion to set the site's confirm address (path ending in `/confirm/` with trailing slashes); then "Connect again" (the site does not retry by itself for 15 min). email.md "When the site cannot be confirmed" |
| `relay-refused`, cause `host-not-allowed` / "This site has no public address yet" | the site runs on `localhost`, a private name, or `serverURL` is empty | expected in development (use SMTP / Mailpit there); in production set `serverURL` |
| `relay-refused` on a site whose token was entered by hand ("does not know the server this site now runs on" / "access key … no longer valid") | the site moved or got a second server, or its token expired; a site with a hand-issued token cannot enrol by itself | Intecion adds the server's address, or issues a new token — set it with `setRelayToken(payload, token)` from a script (`pnpm payload run`), or in the panel when the project has `mail.relay.accessKeyField: true` (email.md "The token") |
| 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 })` |
| 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 |
| `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 |
+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.
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: […] })` (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.
+4 -3
View File
@@ -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 (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
nothing).
4. Code that compared the result of `payload.sendEmail` needs no change for SMTP and Graph. A send through the mail
+3 -3
View File
@@ -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").
+1
View File
@@ -113,6 +113,7 @@ Turn off: `iapl({ doctor: false })`. Adapt: `iapl({ doctor: { tokenVar: 'MY_TOKE
| | `storage-names` | warning | the visitor cookie the layout sets (`<PageStats visitorCookie>`, default `ipal_vid`) is the one the config makes the cookie scanner declare (`storageNames`, stats.md) |
| | `cookie-scanner` | error / warning / info | `cookieScanner` on (with `crawl`, else info); deep: nothing waits for approval (warning) |
| mail | `mail-transport` | error / warning | (deep) an e-mail transport is in effect (not: the mail service switched off and no SMTP server); the last sends worked — failing: warning, error once it has lasted 24 hours |
| | `mail-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 |
+32 -11
View File
@@ -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,23 @@ 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
`<name>.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.
- 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
(`mail-non-public`) say which of the two applies.
| The site | Public? | Its database holds | By itself |
|---|---|---|---|
@@ -280,16 +296,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").
@@ -297,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
@@ -381,7 +402,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 |
+1 -1
View File
@@ -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://<host>/api/iapl/mail-relay/confirm` with the nonce and a token, and only an answer that hashes both makes the token valid |
| **Where the token is** | `payload-kv`, one entry per host (`iapl:mail-relay:site:<host>`). The collection refuses every operation through access control (`read`, `create`, `update`, `delete` are `false`) and is hidden: REST, GraphQL and the panel cannot reach it — an admin included (test: `test/mailRelayHttp.test.ts`). Server code with the Local API can, like `smtpPassword`. It is stored as it is (no encryption at rest), never logged, never sent to a browser, never part of a route's answer |
| **A database copied to another host** | both sides hold a token to its host: every request names the site (`X-Intecion-Site`) and the service refuses another host's token (`host-mismatch`); and on the site the token is stored under the host it was issued for: a copy on a staging domain neither uses nor touches production's entry (a read never deletes), and 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: <host>` on every mail. It cannot set `From`, `Return-Path` or any header, and cannot address a security alert |
+3 -2
View File
@@ -102,8 +102,9 @@ through this procedure. Ask only when you are missing something you cannot get y
| `relay-refused` / "The mail service could not reach this site at …" (cause `callback-failed`) | `unreachable` / `timeout`: firewall, private network, wrong public host in `serverURL`; `redirect`: `trailingSlash: true`, apex → `www`, a language redirect; `status`: route blocked, missing (`mail: { relay: false }`?) or another `routes.api`; `confirmation`: a proxy rewrites the answer | `curl -i -X POST https://<host>/api/iapl/mail-relay/confirm -d '{}' -H 'content-type: application/json'` must answer **404 with an empty body, no redirect**; fix `serverURL` / `mail.relay.host`, or ask Intecion to set the site's confirm address (path ending in `/confirm/` with trailing slashes); then "Connect again" (the site does not retry by itself for 15 min). email.md "When the site cannot be confirmed" |
| `relay-refused`, cause `host-not-allowed` / "This site has no public address yet" | the site runs on `localhost`, a private name, or `serverURL` is empty | expected in development (use SMTP / Mailpit there); in production set `serverURL` |
| `relay-refused` on a site whose token was entered by hand ("does not know the server this site now runs on" / "access key … no longer valid") | the site moved or got a second server, or its token expired; a site with a hand-issued token cannot enrol by itself | Intecion adds the server's address, or issues a new token — set it with `setRelayToken(payload, token)` from a script (`pnpm payload run`), or in the panel when the project has `mail.relay.accessKeyField: true` (email.md "The token") |
| 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 })` |
| 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 |
| `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 |
+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.
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: […] })` (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.
@@ -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 (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
nothing).
4. Code that compared the result of `payload.sendEmail` needs no change for SMTP and Graph. A send through the mail
+7
View File
@@ -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
+3 -1
View File
@@ -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
+6 -1
View File
@@ -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 { 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'
+29 -2
View File
@@ -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 <host>`); the same token then works', message: 'the site is enrolled with the Intecion mail service but waits for approval: e-mails are not sent yet', severity: 'warning' })
} else if (relay.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) {
+1 -1
View File
@@ -71,7 +71,7 @@ export async function collectDoctorStatus(payload: BasePayload): Promise<DoctorS
}
mail = {
graphEnv: graphAvailable(),
...(state.nonPublic ? { nonPublic: true } : {}),
...(state.nonPublic ? { nonPublic: true, ...(state.nonPublicBy ? { nonPublicBy: state.nonPublicBy } : {}), ...(state.nonPublicPattern ? { nonPublicPattern: state.nonPublicPattern } : {}) } : {}),
...(state.otherHostEntries ? { otherHostEntries: true } : {}),
relay: state.relay
? {
+3
View File
@@ -69,6 +69,9 @@ export type DoctorStatus = {
graphEnv: boolean
/** The site says it is not public (`IAPL_NOINDEX`, or a development host): a copy of another site's data does not mail by itself. */
nonPublic?: boolean
/** Which signal makes it non-public: the host matches a development pattern (`nonPublicPattern`), or `IAPL_NOINDEX`. */
nonPublicBy?: 'development-host' | 'noindex'
nonPublicPattern?: string
/** The database also holds the mail-service connection of another host that this site did not name as its own. */
otherHostEntries?: boolean
/** null = the mail service is switched off in the project. */
+3
View File
@@ -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,
+11 -6
View File
@@ -1,7 +1,7 @@
import type { BasePayload } from 'payload'
import { type RelayOptions, resolveRelayOptions } from './options.js'
import { disconnectRelay as disconnect, enrolRelay as enrol, type EnrolResult, siteIsNonPublic as nonPublic, type RelayStatus, rotateRelayToken as rotate, getRelayStatus as status } from './session.js'
import { disconnectRelay as disconnect, enrolRelay as enrol, type EnrolResult, siteIsNonPublic as nonPublic, type NonPublicSignal, siteNonPublicSignal as nonPublicSignal, type RelayStatus, rotateRelayToken as rotate, getRelayStatus as status } from './session.js'
export { RELAY_SENDER_ADDRESS, relayAdapter, relayAttachmentLimit, relaySenderName } from './adapter.js'
export type { RelayAdapterArgs } from './adapter.js'
@@ -25,12 +25,12 @@ export { expectMailTo, MAIL_KIND, MAIL_KINDS, mailKindOf, runWithMailKind, withM
export type { MailKind } from './kinds.js'
export { bareAddress, bareAddresses, buildRelayMessage, cleanSubject } from './message.js'
export type { BuildRelayMessageArgs, BuiltRelayMessage, RelaySendRequest } from './message.js'
export { isPublicHost, relayHost, resolveRelayOptions } from './options.js'
export { isPublicHost, pluginDevelopmentHosts, relayHost, resolveRelayOptions } from './options.js'
export type { RelayOptions } from './options.js'
export { sendThroughRelay } from './send.js'
export type { RelaySendContext, RelaySendResult } from './send.js'
export { setRelayToken } from './session.js'
export type { EnrolResult, RelayStatus } from './session.js'
export type { EnrolResult, NonPublicSignal, RelayStatus } from './session.js'
const DISABLED = 'The mail service is switched off for this project (mail: { relay: false }).'
@@ -67,8 +67,13 @@ export const disconnectRelay = (payload: BasePayload, options?: RelayOptions): P
export const rotateRelayToken = (payload: BasePayload, options?: RelayOptions) => 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 ?? {}))
+20 -6
View File
@@ -2,6 +2,7 @@ import type { BasePayload, SendEmailOptions } from 'payload'
import type { MailKind } from './kinds.js'
import { assertDevelopmentHosts, 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<RelayOptions, 'url'>
export type ResolvedRelayOptions = { developmentHosts: string[]; ownUrl: boolean; url: string } & Omit<RelayOptions, 'developmentHosts' | 'url'>
type PluginMail = { graphDeprecationWarning?: boolean; relay?: false | RelayOptions }
@@ -93,6 +96,16 @@ export function pluginMailOptions(payload: Pick<BasePayload, 'config'>): 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<BasePayload, 'config'>): string[] {
const own = (payload.config?.custom as { iapl?: { developmentHosts?: unknown } } | undefined)?.iapl?.developmentHosts
// (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')
}
/**
* The options in effect: the adapter's own `relay` argument over the plugin option. `null` = the relay
* is switched off.
@@ -101,8 +114,9 @@ export function resolveRelayOptions(payload: Pick<BasePayload, 'config'>, 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, 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])?$/
+8 -5
View File
@@ -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<PayloadRequest, 'payload'>, 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<PayloadRequest, 'payload'>, 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,
+24 -36
View File
@@ -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'
@@ -76,36 +77,26 @@ 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<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\./, '')
/** 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<ResolvedRelayOptions, 'developmentHosts' | 'host'>): 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<RelayOptions, 'developmentHosts' | 'host'>): 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<RelayOptions, 'developmentHosts' | 'host'>): boolean {
return siteNonPublicSignal(payload, options) !== null
}
/**
@@ -117,13 +108,12 @@ export function siteIsNonPublic(payload: BasePayload, options: Pick<ResolvedRela
* told about holds a copy of that site's data. Also when it has a token of its own: production's
* database copied BACK onto the development address brings the development site's old entry with it.
* Hosts the project named as its own, and hosts an admin accepted with "Connect again", do not count.
* `fresh`: read the store now (an enrolment); otherwise what was seen in the last half minute.
* 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(
payload: BasePayload,
options: Pick<ResolvedRelayOptions, 'developmentHosts' | 'host' | 'otherHosts'>,
stored: RelayStored,
{ fresh = true }: { fresh?: boolean } = {},
): Promise<string[]> {
const mode = options.otherHosts
if (mode === 'enrol') {return []}
@@ -131,11 +121,11 @@ 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[]) =>
`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<EnrolResult> {
const stored = await readSiteStore(payload, options)
@@ -160,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)
@@ -207,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.
@@ -302,7 +291,7 @@ export async function withRelayToken<T>(
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] })}
}
@@ -487,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,
+93
View File
@@ -0,0 +1,93 @@
/**
* 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 (`<name>.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 {
// (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 ''
}
}
/**
* 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) {
// 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
+3 -1
View File
@@ -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, 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).
+16 -1
View File
@@ -133,6 +133,21 @@ 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. 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.
*/
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 +162,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 +171,7 @@ export type IaplOptions = {
* Building blocks: buildFillEmptyLocalesGlobalHook / …CollectionHook.
*/
fillEmptyLocales?: { 'cookie-review'?: string[]; 'cookie-settings'?: string[] } | boolean
forms?: FormsOption
/**
+21 -3
View File
@@ -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<string, string> = {}) =>
@@ -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'])
})
+111 -12
View File
@@ -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, 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 { 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'
@@ -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)
})
@@ -747,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: '[email protected]' })).toMatchObject({ cause: 'client-other-host', code: 'relay-refused', sent: false })
expect(dev.fake.requests).toHaveLength(before)
@@ -777,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: '[email protected]' })
@@ -791,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)
@@ -849,6 +853,102 @@ 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<typeof resolveRelayOptions>[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('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 () => {
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: '[email protected]' })).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)
@@ -872,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 })
})
@@ -893,10 +992,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' })
+18
View File
@@ -4,6 +4,8 @@ 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'
@@ -22,6 +24,22 @@ 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.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 () => {
const config = await iapl({ access: { authCollection: 'users' }, i18n, twoFactor: false })(base())