From 6c4e2440940675236ca519bb4b4e577b54b13d09 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rados=C5=82aw=20Smoli=C5=84ski?= Date: Thu, 26 Nov 2026 10:57:32 +0100 Subject: [PATCH] Development hosts, review V-1 to V-3: a malformed list stops the start, a trailing dot and Unicode patterns match, every send reads the store - V-1: assertDevelopmentHosts - iapl({ developmentHosts }), mail.relay.developmentHosts and mailAdapter({ relay }) refuse anything but an array of non-empty host patterns, and a pattern of `*` alone (it would make the public site a development address). Nothing is ignored silently any more. - V-2: one trailing dot of the host is stripped before matching; patterns are punycoded, so one written in Unicode matches; a `*` inside a non-ASCII label is refused. - V-3: the 30-second memory of other hosts is gone. A dump restored into a running development site stops its very next e-mail. - docs, AGENT.md, changelog draft, skills Co-Authored-By: Claude Fable 5.2 --- docs/CHANGELOG.md | 4 +- docs/agent/AGENT.md | 2 +- docs/agent/skills/iapl-debug/SKILL.md | 1 + docs/agent/skills/iapl-setup/SKILL.md | 2 +- docs/agent/skills/iapl-upgrade/SKILL.md | 2 +- docs/email.md | 4 +- reference/.agents/skills/iapl-debug/SKILL.md | 1 + reference/.agents/skills/iapl-setup/SKILL.md | 2 +- .../.agents/skills/iapl-upgrade/SKILL.md | 2 +- src/index.ts | 2 +- src/modules/email/mailAdapter.ts | 3 ++ src/modules/email/relay/options.ts | 6 ++- src/modules/email/relay/session.ts | 28 ++-------- src/modules/shared/developmentHosts.ts | 53 ++++++++++++++++++- src/plugin.ts | 4 +- src/types.ts | 4 +- test/mailRelay.test.ts | 50 ++++++++++++++--- test/plugin.test.ts | 11 +++- 18 files changed, 135 insertions(+), 46 deletions(-) diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md index ba1cd46..03a7b38 100644 --- a/docs/CHANGELOG.md +++ b/docs/CHANGELOG.md @@ -109,7 +109,9 @@ once there are more than 20. variable**: holding a copy of another site's data, it does not mail real people by itself (the table above). `*.dev.netscale.pl` is Intecion's own development domain, where the team's sites are built before launch; a project replaces the list with its own patterns or empties it (`[]`). Building blocks: `matchDevelopmentHost`, - `isDevelopmentHost`, `pluginDevelopmentHosts`, `siteIsNonPublic`, `siteNonPublicSignal` (`NonPublicSignal`). + `isDevelopmentHost`, `assertDevelopmentHosts`, `pluginDevelopmentHosts`, `siteIsNonPublic`, `siteNonPublicSignal` (`NonPublicSignal`). + A malformed list (not an array of non-empty host patterns, or a lone `*`) stops the start instead of being + ignored; patterns are punycoded, a trailing dot and the port are ignored. Doctor: `mail-non-public` (info, deep) names the signal that makes a site non-public. The list is about mail only: it does not make a development host noindex. Keeping development addresses out of search engines stays the hosting's business (Coolify) or `IAPL_NOINDEX=1`. Nothing changes in what a site serves to robots on upgrade. - **Panel:** the state block on the e-mail tab (transport in effect, the site's state with the service, sender and reply address, what is left of the limits, a replaced sender name; "Check now", "Connect again", "Disconnect"; diff --git a/docs/agent/AGENT.md b/docs/agent/AGENT.md index 14b27e4..2039b7d 100644 --- a/docs/agent/AGENT.md +++ b/docs/agent/AGENT.md @@ -1335,7 +1335,7 @@ overrides per adapter; `resolveRelayOptions` reads what is in effect): | `url` | `RELAY_BASE_URL` | a relay of your own (same contract) | | `host` | host of `serverURL` (`relayHost`, `isPublicHost`) | the public host the service calls back | | `otherHosts` | `'auto'` | a database holding another host's connection: a public site enrols by itself (launch, a move), a non-public one (`IAPL_NOINDEX=1` / `developmentHosts`) neither enrols nor sends until "Connect again"; a list of the site's own other hosts; `'wait'` (a public site without a connection waits too); `'enrol'` (no rule) | -| `developmentHosts` | `iapl({ developmentHosts })`, default `DEFAULT_DEVELOPMENT_HOSTS` = `['*.dev.netscale.pl']` (`pluginDevelopmentHosts`) | host patterns (`*`) of development and staging addresses, for the mail service alone: a site there is non-public for `otherHosts` with no env (`siteIsNonPublic`, `siteNonPublicSignal` → `NonPublicSignal`, `matchDevelopmentHost`, `isDevelopmentHost`); `[]` = none | +| `developmentHosts` | `iapl({ developmentHosts })`, default `DEFAULT_DEVELOPMENT_HOSTS` = `['*.dev.netscale.pl']` (`pluginDevelopmentHosts`) | host patterns (`*`) of development and staging addresses, for the mail service alone: a site there is non-public for `otherHosts` with no env (`siteIsNonPublic`, `siteNonPublicSignal` → `NonPublicSignal`, `matchDevelopmentHost`, `isDevelopmentHost`); `[]` = none. Checked when the config is built (`assertDevelopmentHosts`): not an array of non-empty host patterns, or a lone `*` → the site does not start; Unicode patterns are punycoded, a trailing dot and the port are ignored | | `enrol` | `'auto'` | `'manual'` (only "Connect again" / `enrolRelay`), `false` (token from `token` / `setRelayToken`) | | `accessKeyField` | `false` | `true`: admins get "Enter an access key" in the state block (a hand-issued token) | | `token` | — | a token from elsewhere; nothing is stored, the site does not enrol | diff --git a/docs/agent/skills/iapl-debug/SKILL.md b/docs/agent/skills/iapl-debug/SKILL.md index 3fb1e8e..08163ff 100644 --- a/docs/agent/skills/iapl-debug/SKILL.md +++ b/docs/agent/skills/iapl-debug/SKILL.md @@ -103,6 +103,7 @@ through this procedure. Ask only when you are missing something you cannot get y | `relay-refused`, cause `host-not-allowed` / "This site has no public address yet" | the site runs on `localhost`, a private name, or `serverURL` is empty | expected in development (use SMTP / Mailpit there); in production set `serverURL` | | `relay-refused` on a site whose token was entered by hand ("does not know the server this site now runs on" / "access key … no longer valid") | the site moved or got a second server, or its token expired; a site with a hand-issued token cannot enrol by itself | Intecion adds the server's address, or issues a new token — set it with `setRelayToken(payload, token)` from a script (`pnpm payload run`), or in the panel when the project has `mail.relay.accessKeyField: true` (email.md "The token") | | a site sends nothing: "The data comes from another site (…), so this copy does not send e-mails by itself" / `relay-refused`, cause `client-other-host` | the site is non-public — its host matches `developmentHosts` (built in: `*.dev.netscale.pl`) or `IAPL_NOINDEX=1` is set; `iapl-doctor --deep` says which (`mail-non-public`) — and its database holds another host's connection: a staging copy of production, or production's data copied back onto the development address. Expected — a copy with production's data must not mail real people by itself | should it send: "Connect again" in the state block, once (until the data is replaced). A copy that must never send: `mail: { relay: false }` or SMTP to a catcher. **The production site itself says this:** `IAPL_NOINDEX` was left set after launch — remove it; or its host matches a development pattern — take it out of `iapl({ developmentHosts })` | +| the site does not start: "[iapl] … developmentHosts must be an array of host patterns …" | the list is not an array of non-empty host patterns (a single string, `null`, `['']`), or holds a lone `*` | write it as `['*.dev.netscale.pl', 'staging.client.pl']`; `[]` = none; to change who waits use `mail.relay.otherHosts` | | a staging or test copy **does** send, to real addresses | its host matches no development pattern and it has no `IAPL_NOINDEX=1`, so it looks like a launch (a public site enrols by itself); the doctor's deep run notes "the database also holds the mail-service connection of another host" | name its host in `iapl({ developmentHosts: ['*.dev.netscale.pl', ''] })`, or `IAPL_NOINDEX=1` on the copy; to be sure: `mail: { relay: false }` or SMTP to a catcher | | `relay-pending` / "waiting for approval" | the exception: the service holds new sites for approval when many appear at once, or Intecion approves by hand (a site is normally active as soon as it enrols) | Intecion approves it on the service; nothing to change on the site; the same token then works | | `relay-suspended` | Intecion stopped the site (abuse, a flood from a form) | contact Intecion; fill in SMTP meanwhile | diff --git a/docs/agent/skills/iapl-setup/SKILL.md b/docs/agent/skills/iapl-setup/SKILL.md index c8584be..ba795c4 100644 --- a/docs/agent/skills/iapl-setup/SKILL.md +++ b/docs/agent/skills/iapl-setup/SKILL.md @@ -646,7 +646,7 @@ scaling (5). `●` routes for pages need the database at build time (PROGRAMISTA 6. **Notifications**: form messages in every language. 7. **Site integrations → E-mail sending**: "Sender name" (the client's name; empty = the site name) and **"Sender address"** (the client's address: with the mail service replies go there). SMTP fields **only** when the client asked - for its own server. On the production domain: the block "How e-mails are sent" must say "Connected to IWSN" (a site is active as soon as it enrols; "waiting for approval" is the exception — ask Intecion; the real domain enrols by itself at launch although the site was connected on its development address — nothing to press; "The data comes from another site" = the site is non-public (its host matches `developmentHosts`, built in `*.dev.netscale.pl`, or `IAPL_NOINDEX=1`) and holds a copy of another site's data: press "Connect again" only if the copy should send — on the production domain it means `IAPL_NOINDEX` was left set. A development address under `*.dev.netscale.pl` needs nothing; a staging or test copy on any other host must have its host in `iapl({ developmentHosts: […] })` or `IAPL_NOINDEX=1`, or it mails the real addresses in its data), then **Send test e-mail** → "through IWSN". Turnstile (for testing site + for its own server. On the production domain: the block "How e-mails are sent" must say "Connected to IWSN" (a site is active as soon as it enrols; "waiting for approval" is the exception — ask Intecion; the real domain enrols by itself at launch although the site was connected on its development address — nothing to press; "The data comes from another site" = the site is non-public (its host matches `developmentHosts`, built in `*.dev.netscale.pl`, or `IAPL_NOINDEX=1`) and holds a copy of another site's data: press "Connect again" only if the copy should send — on the production domain it means `IAPL_NOINDEX` was left set. A development address under `*.dev.netscale.pl` needs nothing; a staging or test copy on any other host must have its host in `iapl({ developmentHosts: […] })` (an array of host patterns: a single string, an empty entry or a lone `*` stops the start) or `IAPL_NOINDEX=1`, or it mails the real addresses in its data), then **Send test e-mail** → "through IWSN". Turnstile (for testing site `1x00000000000000000000AA`, secret `1x0000000000000000000000000000000AA`; production keys from the client), analytics/pixel IDs, IndexNow → generate key. Mail/Turnstile errors show up as a dashboard alert. 8. **Forms**: check the addresses in the Emails tab of the seeded forms. diff --git a/docs/agent/skills/iapl-upgrade/SKILL.md b/docs/agent/skills/iapl-upgrade/SKILL.md index 4805138..eee6aef 100644 --- a/docs/agent/skills/iapl-upgrade/SKILL.md +++ b/docs/agent/skills/iapl-upgrade/SKILL.md @@ -576,7 +576,7 @@ PROGRAMISTA §6, item 73; email.md; AGENT.md §7.2) — nothing to run; read whi **Launch and a domain move need nothing:** the real domain enrols by itself although the database holds the development address's connection. **A staging or test copy of the database** neither enrols nor sends by itself **when it is non-public**: its host matches `iapl({ developmentHosts })` — built in `*.dev.netscale.pl`, so the - team's development addresses need no env and no edit; add the project's other copy hosts to the list — or it + team's development addresses need no env and no edit; add the project's other copy hosts to the list (an array of host patterns; a string, an empty entry or a lone `*` stops the start) — or it has `IAPL_NOINDEX=1`. The panel says so until an admin presses "Connect again"; `iapl-doctor --deep` names the signal (`mail-non-public`). A copy on another host without the variable sends to the real addresses in its data; keep a copy silent for good with `mail: { relay: false }` or SMTP to a catcher. Production must not have `IAPL_NOINDEX` set (it would send diff --git a/docs/email.md b/docs/email.md index f248416..45c684d 100644 --- a/docs/email.md +++ b/docs/email.md @@ -284,6 +284,7 @@ await runWithMailKind('account', () => sendWelcomeMails(payload, user)) other: **replace it** with your own patterns (`developmentHosts: ['*.preview.agency.example', 'staging.client.pl']`), or pass **`[]`** so that no host is a development address. `mail: { relay: { developmentHosts } }` overrides the list for the mail service alone. +- A malformed list stops the start (`assertDevelopmentHosts`): the value must be an array of non-empty host patterns — a single string, `null`, a number, an empty string, a scheme or a path are refused, and so is a pattern made of `*` alone (it would make the public site a development address). Patterns are compared as hosts are written on the wire: lowercase, punycode (a pattern may be written in Unicode), a trailing dot ignored, the port ignored. - **By the variable.** `IAPL_NOINDEX=1` marks any other staging, preview or test copy. - The list is about mail only: it does **not** make a development host noindex. Keeping development addresses out of search engines stays the hosting's business (Coolify) or `IAPL_NOINDEX=1`. - The panel state (`nonPublicBy`, `nonPublicPattern`), `siteNonPublicSignal(payload)` and the doctor @@ -316,7 +317,8 @@ await runWithMailKind('account', () => sendWelcomeMails(payload, user)) called back at that host). - After "Connect again" a copy sends until its data is replaced. - A development site that keeps running **on the launched database** (not a copy of it) stops sending by itself - once the real domain has enrolled; other processes notice within 30 seconds. + once the real domain has enrolled. The check reads the database at every send, so a dump restored into a running + development site stops its very next e-mail. - **A copy that must never send:** `iapl({ mail: { relay: false } })` there, or SMTP to a catcher. That is the safe set-up for staging; the rule above only protects until somebody presses the button. - **`otherHosts`** changes the rule: a list (`['client.dev.agency.example']`) names hosts as this site's own — a diff --git a/reference/.agents/skills/iapl-debug/SKILL.md b/reference/.agents/skills/iapl-debug/SKILL.md index 3fb1e8e..08163ff 100644 --- a/reference/.agents/skills/iapl-debug/SKILL.md +++ b/reference/.agents/skills/iapl-debug/SKILL.md @@ -103,6 +103,7 @@ through this procedure. Ask only when you are missing something you cannot get y | `relay-refused`, cause `host-not-allowed` / "This site has no public address yet" | the site runs on `localhost`, a private name, or `serverURL` is empty | expected in development (use SMTP / Mailpit there); in production set `serverURL` | | `relay-refused` on a site whose token was entered by hand ("does not know the server this site now runs on" / "access key … no longer valid") | the site moved or got a second server, or its token expired; a site with a hand-issued token cannot enrol by itself | Intecion adds the server's address, or issues a new token — set it with `setRelayToken(payload, token)` from a script (`pnpm payload run`), or in the panel when the project has `mail.relay.accessKeyField: true` (email.md "The token") | | a site sends nothing: "The data comes from another site (…), so this copy does not send e-mails by itself" / `relay-refused`, cause `client-other-host` | the site is non-public — its host matches `developmentHosts` (built in: `*.dev.netscale.pl`) or `IAPL_NOINDEX=1` is set; `iapl-doctor --deep` says which (`mail-non-public`) — and its database holds another host's connection: a staging copy of production, or production's data copied back onto the development address. Expected — a copy with production's data must not mail real people by itself | should it send: "Connect again" in the state block, once (until the data is replaced). A copy that must never send: `mail: { relay: false }` or SMTP to a catcher. **The production site itself says this:** `IAPL_NOINDEX` was left set after launch — remove it; or its host matches a development pattern — take it out of `iapl({ developmentHosts })` | +| the site does not start: "[iapl] … developmentHosts must be an array of host patterns …" | the list is not an array of non-empty host patterns (a single string, `null`, `['']`), or holds a lone `*` | write it as `['*.dev.netscale.pl', 'staging.client.pl']`; `[]` = none; to change who waits use `mail.relay.otherHosts` | | a staging or test copy **does** send, to real addresses | its host matches no development pattern and it has no `IAPL_NOINDEX=1`, so it looks like a launch (a public site enrols by itself); the doctor's deep run notes "the database also holds the mail-service connection of another host" | name its host in `iapl({ developmentHosts: ['*.dev.netscale.pl', ''] })`, or `IAPL_NOINDEX=1` on the copy; to be sure: `mail: { relay: false }` or SMTP to a catcher | | `relay-pending` / "waiting for approval" | the exception: the service holds new sites for approval when many appear at once, or Intecion approves by hand (a site is normally active as soon as it enrols) | Intecion approves it on the service; nothing to change on the site; the same token then works | | `relay-suspended` | Intecion stopped the site (abuse, a flood from a form) | contact Intecion; fill in SMTP meanwhile | diff --git a/reference/.agents/skills/iapl-setup/SKILL.md b/reference/.agents/skills/iapl-setup/SKILL.md index c8584be..ba795c4 100644 --- a/reference/.agents/skills/iapl-setup/SKILL.md +++ b/reference/.agents/skills/iapl-setup/SKILL.md @@ -646,7 +646,7 @@ scaling (5). `●` routes for pages need the database at build time (PROGRAMISTA 6. **Notifications**: form messages in every language. 7. **Site integrations → E-mail sending**: "Sender name" (the client's name; empty = the site name) and **"Sender address"** (the client's address: with the mail service replies go there). SMTP fields **only** when the client asked - for its own server. On the production domain: the block "How e-mails are sent" must say "Connected to IWSN" (a site is active as soon as it enrols; "waiting for approval" is the exception — ask Intecion; the real domain enrols by itself at launch although the site was connected on its development address — nothing to press; "The data comes from another site" = the site is non-public (its host matches `developmentHosts`, built in `*.dev.netscale.pl`, or `IAPL_NOINDEX=1`) and holds a copy of another site's data: press "Connect again" only if the copy should send — on the production domain it means `IAPL_NOINDEX` was left set. A development address under `*.dev.netscale.pl` needs nothing; a staging or test copy on any other host must have its host in `iapl({ developmentHosts: […] })` or `IAPL_NOINDEX=1`, or it mails the real addresses in its data), then **Send test e-mail** → "through IWSN". Turnstile (for testing site + for its own server. On the production domain: the block "How e-mails are sent" must say "Connected to IWSN" (a site is active as soon as it enrols; "waiting for approval" is the exception — ask Intecion; the real domain enrols by itself at launch although the site was connected on its development address — nothing to press; "The data comes from another site" = the site is non-public (its host matches `developmentHosts`, built in `*.dev.netscale.pl`, or `IAPL_NOINDEX=1`) and holds a copy of another site's data: press "Connect again" only if the copy should send — on the production domain it means `IAPL_NOINDEX` was left set. A development address under `*.dev.netscale.pl` needs nothing; a staging or test copy on any other host must have its host in `iapl({ developmentHosts: […] })` (an array of host patterns: a single string, an empty entry or a lone `*` stops the start) or `IAPL_NOINDEX=1`, or it mails the real addresses in its data), then **Send test e-mail** → "through IWSN". Turnstile (for testing site `1x00000000000000000000AA`, secret `1x0000000000000000000000000000000AA`; production keys from the client), analytics/pixel IDs, IndexNow → generate key. Mail/Turnstile errors show up as a dashboard alert. 8. **Forms**: check the addresses in the Emails tab of the seeded forms. diff --git a/reference/.agents/skills/iapl-upgrade/SKILL.md b/reference/.agents/skills/iapl-upgrade/SKILL.md index 4805138..eee6aef 100644 --- a/reference/.agents/skills/iapl-upgrade/SKILL.md +++ b/reference/.agents/skills/iapl-upgrade/SKILL.md @@ -576,7 +576,7 @@ PROGRAMISTA §6, item 73; email.md; AGENT.md §7.2) — nothing to run; read whi **Launch and a domain move need nothing:** the real domain enrols by itself although the database holds the development address's connection. **A staging or test copy of the database** neither enrols nor sends by itself **when it is non-public**: its host matches `iapl({ developmentHosts })` — built in `*.dev.netscale.pl`, so the - team's development addresses need no env and no edit; add the project's other copy hosts to the list — or it + team's development addresses need no env and no edit; add the project's other copy hosts to the list (an array of host patterns; a string, an empty entry or a lone `*` stops the start) — or it has `IAPL_NOINDEX=1`. The panel says so until an admin presses "Connect again"; `iapl-doctor --deep` names the signal (`mail-non-public`). A copy on another host without the variable sends to the real addresses in its data; keep a copy silent for good with `mail: { relay: false }` or SMTP to a catcher. Production must not have `IAPL_NOINDEX` set (it would send diff --git a/src/index.ts b/src/index.ts index f39f4ac..da55583 100644 --- a/src/index.ts +++ b/src/index.ts @@ -519,7 +519,7 @@ export type { SitemapRouteOptions, SitemapStyleOptions } from './modules/seo/ind export { applyCollectionOverride } from './modules/shared/collectionOverride.js' export type { CollectionOverride } from './modules/shared/collectionOverride.js' // Development addresses by pattern (no env): the built-in list and the matcher behind `developmentHosts`. -export { DEFAULT_DEVELOPMENT_HOSTS, isDevelopmentHost, matchDevelopmentHost } from './modules/shared/developmentHosts.js' +export { assertDevelopmentHosts, DEFAULT_DEVELOPMENT_HOSTS, isDevelopmentHost, matchDevelopmentHost } from './modules/shared/developmentHosts.js' export { clientIp, setRateLimitStore, setUnknownIpFactor, UNKNOWN_IP_FACTOR } from './modules/shared/rateLimit.js' export type { ClientIpOptions, RateLimitStore } from './modules/shared/rateLimit.js' export { buildSlugField, toSlug } from './modules/slug/index.js' diff --git a/src/modules/email/mailAdapter.ts b/src/modules/email/mailAdapter.ts index bcb62d4..64a87ae 100644 --- a/src/modules/email/mailAdapter.ts +++ b/src/modules/email/mailAdapter.ts @@ -2,6 +2,7 @@ import type { PayloadEmailAdapter, SendEmailOptions } from 'payload' import { type IntegrationStatus, recordIntegrationStatus } from '../integrations/status.js' import { getSiteIntegrations } from '../payload/index.js' +import { assertDevelopmentHosts } from '../shared/developmentHosts.js' import { sendAccountMailAfterCommit } from './accountMailAfterCommit.js' import { graphAdapter, type GraphAdapterArgs, graphLargeAttachmentSupport } from './graphAdapter.js' import { attachmentBytes, GRAPH_INLINE_MAX_BYTES, toGraphAttachments } from './graphAttachments.js' @@ -112,6 +113,8 @@ export function graphAvailable(): boolean { export const mailAdapter = (args: MailAdapterArgs = {}): PayloadEmailAdapter => (deps) => { + // a malformed list must stop the start, not be found at the first e-mail of a copy + if (args.relay && args.relay.developmentHosts !== undefined) {assertDevelopmentHosts(args.relay.developmentHosts, 'mailAdapter({ relay: { developmentHosts } })')} // Build both delegates once; each still resolves its own config per send. const smtp = panelSmtpAdapter({ fallbackFromAddress: args.fallbackFromAddress, diff --git a/src/modules/email/relay/options.ts b/src/modules/email/relay/options.ts index 7d89d4f..4db6762 100644 --- a/src/modules/email/relay/options.ts +++ b/src/modules/email/relay/options.ts @@ -2,7 +2,7 @@ import type { BasePayload, SendEmailOptions } from 'payload' import type { MailKind } from './kinds.js' -import { DEFAULT_DEVELOPMENT_HOSTS } from '../../shared/developmentHosts.js' +import { assertDevelopmentHosts, DEFAULT_DEVELOPMENT_HOSTS } from '../../shared/developmentHosts.js' import { RELAY_BASE_URL } from './constants.js' /** @@ -102,7 +102,8 @@ export function pluginMailOptions(payload: Pick): PluginM */ export function pluginDevelopmentHosts(payload: Pick): string[] { const own = (payload.config?.custom as { iapl?: { developmentHosts?: unknown } } | undefined)?.iapl?.developmentHosts - return Array.isArray(own) ? own.filter((p): p is string => typeof p === 'string') : [...DEFAULT_DEVELOPMENT_HOSTS] + // (written by iapl(), which refuses a malformed list; a value put here by hand is checked the same way) + return own === undefined ? [...DEFAULT_DEVELOPMENT_HOSTS] : assertDevelopmentHosts(own, 'config.custom.iapl.developmentHosts') } /** @@ -113,6 +114,7 @@ export function resolveRelayOptions(payload: Pick, own?: const fromPlugin = pluginMailOptions(payload).relay if (own === false || (own === undefined && fromPlugin === false)) {return null} const merged: RelayOptions = { ...(fromPlugin || {}), ...(own || {}) } + if (merged.developmentHosts !== undefined) {assertDevelopmentHosts(merged.developmentHosts, 'mail.relay.developmentHosts')} const url = (merged.url ?? RELAY_BASE_URL).replace(/\/+$/, '') return { ...merged, developmentHosts: merged.developmentHosts ?? pluginDevelopmentHosts(payload), ownUrl: url !== RELAY_BASE_URL, url } } diff --git a/src/modules/email/relay/session.ts b/src/modules/email/relay/session.ts index 483ee7b..e3995ab 100644 --- a/src/modules/email/relay/session.ts +++ b/src/modules/email/relay/session.ts @@ -77,23 +77,6 @@ export function enrolRelay(payload: BasePayload, options: ResolvedRelayOptions, return run } -/** Short memory of which other hosts have an entry: a non-public site asks on every send. Per Payload instance. */ -const otherHostsSeen = new WeakMap() -const OTHER_HOSTS_TTL_MS = 30_000 - -/** For tests, and after this site's own connection changed. */ -export function forgetOtherHosts(payload?: object): void { - if (payload) {otherHostsSeen.delete(payload)} -} - -async function otherHostsNow(payload: BasePayload, host: string, fresh: boolean): Promise { - const seen = otherHostsSeen.get(payload) - if (!fresh && seen && seen.host === host && Date.now() - seen.at < OTHER_HOSTS_TTL_MS) {return seen.hosts} - const hosts = await otherRelayHosts(payload, host) - otherHostsSeen.set(payload, { at: Date.now(), host, hosts }) - return hosts -} - const bare = (host: string) => host.trim().toLowerCase().replace(/^www\./, '') /** Why a site counts as non-public: its host matches a development pattern, or `IAPL_NOINDEX` is set. */ @@ -125,13 +108,12 @@ export function siteIsNonPublic(payload: BasePayload, options: Pick, stored: RelayStored, - { fresh = true }: { fresh?: boolean } = {}, ): Promise { const mode = options.otherHosts if (mode === 'enrol') {return []} @@ -139,7 +121,7 @@ export async function otherHostsInTheWay( if (mode === 'wait' && connected) {return []} if (mode !== 'wait' && !siteIsNonPublic(payload, options)) {return []} const own = [...(Array.isArray(mode) ? mode : []), ...(stored.acceptedHosts ?? [])].map(bare) - return (await otherHostsNow(payload, relayHost(payload, options), fresh)).filter((h) => !own.includes(bare(h))) + return (await otherRelayHosts(payload, relayHost(payload, options))).filter((h) => !own.includes(bare(h))) } const otherHostMessage = (host: string, foreign: string[]) => @@ -168,7 +150,7 @@ async function enrolOnce(payload: BasePayload, options: ResolvedRelayOptions, fo // A copy of another site's database does not enrol BY ITSELF (otherHostsInTheWay): with that site's data it // would mail real people. An admin's "Connect again" (`force`) does, and the hosts found then are accepted. - const others = force ? await otherHostsNow(payload, host, true) : [] + const others = force ? await otherRelayHosts(payload, host) : [] const foreign = force ? [] : await otherHostsInTheWay(payload, options, stored) if (foreign.length) { const message = otherHostMessage(host, foreign) @@ -215,7 +197,6 @@ async function enrolOnce(payload: BasePayload, options: ResolvedRelayOptions, fo token: candidate.token, })) await dropRelayCandidate(payload, options) - forgetOtherHosts(payload) return { ok: true, state } } // Used or not, this nonce is over. A token the call-back did deliver stays beside the one in use. @@ -310,7 +291,7 @@ export async function withRelayToken( const token = candidate?.token ?? stored.token // A non-public copy holding another site's data does not SEND by itself either, token or not. if (token && round === 0) { - const foreign = await otherHostsInTheWay(payload, options, stored, { fresh: false }) + const foreign = await otherHostsInTheWay(payload, options, stored) if (foreign.length) {return refusal(LOCAL_CODES.otherHost, otherHostMessage(relayHost(payload, options), foreign), { reason: foreign[0] })} } @@ -495,7 +476,6 @@ export async function setRelayToken(payload: BasePayload, token: string, options // the entry is this site's own: `options.host`, else `mail.relay.host`, else the host of serverURL options = { host: options.host ?? (pluginMailOptions(payload).relay || {}).host } const others = await otherRelayHosts(payload, relayHost(payload, options)) - forgetOtherHosts(payload) await dropRelayCandidate(payload, options) await updateRelayStore(payload, options, (current) => ({ ...current, diff --git a/src/modules/shared/developmentHosts.ts b/src/modules/shared/developmentHosts.ts index 3a6383f..619bced 100644 --- a/src/modules/shared/developmentHosts.ts +++ b/src/modules/shared/developmentHosts.ts @@ -19,7 +19,8 @@ export function hostOf(value: null | string | undefined): string { const raw = (value ?? '').trim() if (!raw) {return ''} try { - return new URL(/^[a-z][a-z0-9+.-]*:\/\//i.test(raw) ? raw : `https://${raw}`).host.toLowerCase() + // (a fully qualified name may end in a dot — `acme.dev.example.pl.` is the same host) + return new URL(/^[a-z][a-z0-9+.-]*:\/\//i.test(raw) ? raw : `https://${raw}`).host.toLowerCase().replace(/\.(?=:\d+$|$)/, '') } catch { return '' } @@ -33,12 +34,60 @@ export function matchDevelopmentHost(host: null | string | undefined, patterns: const name = hostOf(host).replace(/:\d+$/, '') if (!name) {return null} for (const pattern of patterns) { - const source = pattern.trim().toLowerCase().split('*').map((part) => part.replace(/[.+?^${}()|[\]\\]/g, '\\$&')).join('.*') + // a pattern is compared the way hosts are written on the wire: lowercase, punycode, no trailing dot + const written = typeof pattern === 'string' ? (asciiPattern(pattern) ?? pattern.trim().toLowerCase()) : '' + const source = written.split('*').map((part) => part.replace(/[.+?^${}()|[\]\\]/g, '\\$&')).join('.*') if (source && new RegExp(`^${source}$`).test(name)) {return pattern} } return null } +const STAR = 'zq9star9qz' + +/** + * A pattern as hosts are written: lowercase, punycode (`*.dev.zażółć.pl` → `*.dev.xn--za-….pl`), no trailing + * dot, no port. null when it is not a host pattern at all (empty, a space inside, a `*` in a label with + * non-ASCII letters, …). + */ +function asciiPattern(pattern: string): null | string { + const raw = pattern.trim().toLowerCase().replace(/\.$/, '') + if (!raw || /[\s/@?#\\]/.test(raw)) {return null} + const stars = raw.split('*').length - 1 + try { + const host = new URL(`https://${raw.replaceAll('*', STAR)}`).hostname + // (a `*` inside a punycoded label would stand for nothing a person could mean) + if (host.split(STAR).length - 1 !== stars || host.split('.').some((label) => label.startsWith('xn--') && label.includes(STAR))) {return null} + return host.replaceAll(STAR, '*') + } catch { + return null + } +} + +/** + * Checks a `developmentHosts` value when the project's config is built, and returns the list as given. + * Throws — the site does not start — on anything but an array of host patterns, because a list that is + * silently ignored or silently empty means a copy of production's data mails real people: + * - not an array (a single string, `null`, an object); + * - an entry that is not a non-empty string, or not a host pattern; + * - a pattern made of `*` alone (with or without dots): it would make EVERY host a development address, + * the public site included. To switch the mail rule's waiting off or on for all hosts use + * `mail.relay.otherHosts` instead. + * `[]` is valid: no host is a development address. `undefined` is not checked here (the default applies). + */ +export function assertDevelopmentHosts(value: unknown, option = 'developmentHosts'): string[] { + const fail = (why: string): never => { + throw new Error(`[iapl] ${option} must be an array of host patterns such as ['*.dev.netscale.pl'] ([] = none): ${why}. Got ${JSON.stringify(value)}.`) + } + if (!Array.isArray(value)) {return fail('it is not an array')} + value.forEach((entry, index) => { + if (typeof entry !== 'string' || !entry.trim()) {fail(`entry ${index} is not a non-empty string`)} + const written = asciiPattern(entry as string) + if (!written) {fail(`entry ${index} ("${entry}") is not a host pattern — a host name with \`*\` for any characters, no scheme, no path`)} + if (!/[^*.]/.test(written as string)) {fail(`entry ${index} ("${entry}") matches every host, so the public site would count as a development address`)} + }) + return value as string[] +} + /** Is `host` a development address (`matchDevelopmentHost` as a yes or no)? */ export const isDevelopmentHost = (host: null | string | undefined, patterns: readonly string[] = DEFAULT_DEVELOPMENT_HOSTS): boolean => matchDevelopmentHost(host, patterns) !== null diff --git a/src/plugin.ts b/src/plugin.ts index 0cc8df9..2dd37f1 100644 --- a/src/plugin.ts +++ b/src/plugin.ts @@ -66,6 +66,7 @@ import { buildIndexNowHook } from './modules/seo/indexNow.js' import { searchSettingsFields } from './modules/seo/searchSettings.js' import { migrateTitleSeparator } from './modules/seo/titleSeparator.js' import { applyCollectionOverride } from './modules/shared/collectionOverride.js' +import { assertDevelopmentHosts } from './modules/shared/developmentHosts.js' import { buildStatsCollection, buildStatsEndpoint } from './modules/stats/index.js' import { visitorCookieFor } from './modules/stats/visitorCookie.js' @@ -753,10 +754,11 @@ export const iapl = (options: IaplOptions): Plugin => { // --- e-mail: the Intecion Notifications Webservice (docs/email.md; off with mail: { relay: false }) --- // What mailAdapter() reads at send time; born under the new name (`custom.iapl`). const relay = options.mail?.relay + if (relay && relay.developmentHosts !== undefined) {assertDevelopmentHosts(relay.developmentHosts, 'iapl({ mail: { relay: { developmentHosts } } })')} const iaplCustom = (config.custom?.iapl ?? {}) as object config.custom = { ...config.custom, - iapl: { ...iaplCustom, ...(Array.isArray(options.developmentHosts) ? { developmentHosts: [...options.developmentHosts] } : {}), mail: { ...(options.mail?.graphDeprecationWarning === false ? { graphDeprecationWarning: false } : {}), relay: relay === false ? false : (relay ?? {}) } }, + iapl: { ...iaplCustom, ...(options.developmentHosts !== undefined ? { developmentHosts: [...assertDevelopmentHosts(options.developmentHosts, 'iapl({ developmentHosts })')] } : {}), mail: { ...(options.mail?.graphDeprecationWarning === false ? { graphDeprecationWarning: false } : {}), relay: relay === false ? false : (relay ?? {}) } }, } // "Forgot password" and "verify your e-mail" through mailAdapter(): sent right after their transaction // commits, not inside it (mail.accountMailAfterCommit; docs/deployment.md §4.3a). diff --git a/src/types.ts b/src/types.ts index baae410..11dce12 100644 --- a/src/types.ts +++ b/src/types.ts @@ -140,7 +140,9 @@ export type IaplOptions = { * matches is "non-public" with no environment variable: when its database holds the mail-service * connection of another host (a copy of production's data), it does not mail real people by itself * (docs/email.md "Staging, copies and several hosts"). Replace the list with your own patterns, or - * pass `[]` so that no host is a development address. Mail only: the option does not make a + * pass `[]` so that no host is a development address. Anything but an array of non-empty host + * patterns, and a pattern of `*` alone, stops the start (`assertDevelopmentHosts`); a pattern may + * be written in Unicode (it is punycoded), a trailing dot and the port are ignored. Mail only: the option does not make a * development host noindex (that is the hosting's business, or `IAPL_NOINDEX=1`). `mail.relay.developmentHosts` overrides it * for the mail service alone. */ diff --git a/test/mailRelay.test.ts b/test/mailRelay.test.ts index 22e382d..3968fc5 100644 --- a/test/mailRelay.test.ts +++ b/test/mailRelay.test.ts @@ -21,11 +21,11 @@ import { bareAddresses, buildRelayMessage, cleanSubject } from '../src/modules/e import { isPublicHost, pluginDevelopmentHosts, relayHost, resolveRelayOptions } from '../src/modules/email/relay/options.js' import { mailPanelState } from '../src/modules/email/relay/panel.js' import { clearUnconfirmedRelayMessages, sendThroughRelay } from '../src/modules/email/relay/send.js' -import { disconnectRelay, enrolRelay, forgetOtherHosts, getRelayStatus, provesToken, refreshRelayStatus, rotateRelayToken, setRelayToken, siteIsNonPublic, siteNonPublicSignal } from '../src/modules/email/relay/session.js' +import { disconnectRelay, enrolRelay, getRelayStatus, provesToken, refreshRelayStatus, rotateRelayToken, setRelayToken, siteIsNonPublic, siteNonPublicSignal } from '../src/modules/email/relay/session.js' import { holdNonce, otherRelayHosts, readRelayCandidate, readRelayStore, updateRelayStore } from '../src/modules/email/relay/store.js' import { NOTIFICATION_FALLBACK, NOTIFICATION_FALLBACK_PL } from '../src/modules/notifications/defaults.js' import { resolveFormMessage } from '../src/modules/notifications/resolveFormMessage.js' -import { DEFAULT_DEVELOPMENT_HOSTS, isDevelopmentHost, matchDevelopmentHost } from '../src/modules/shared/developmentHosts.js' +import { assertDevelopmentHosts, DEFAULT_DEVELOPMENT_HOSTS, isDevelopmentHost, matchDevelopmentHost } from '../src/modules/shared/developmentHosts.js' import { setRateLimitStore } from '../src/modules/shared/rateLimit.js' import { callConfirmRoute, relayPayload, relaySite } from './mailRelay/helpers.js' @@ -754,7 +754,6 @@ describe('the token over time', () => { await sendThroughRelay(apart.payload, apart.options, MESSAGE) expect((await sendThroughRelay(apart.payload, apart.options, { ...MESSAGE, subject: 'Dev, later' })).sent).toBe(true) // …but a development site that still runs ON the launched database now holds the live site's data: it stops by itself - forgetOtherHosts(dev.payload) const before = dev.fake.requests.length expect(await sendThroughRelay(dev.payload, dev.options, { ...MESSAGE, to: 'a-real-customer@example.org' })).toMatchObject({ cause: 'client-other-host', code: 'relay-refused', sent: false }) expect(dev.fake.requests).toHaveLength(before) @@ -784,7 +783,6 @@ describe('the token over time', () => { // months later: production's data is copied back onto the development address, to work on a bug copy(live.store, dev.store) - forgetOtherHosts(dev.payload) expect((await readRelayStore(dev.payload)).token).toMatch(/^ims_/) // its own old entry came back with the copy const requests = service.requests.length const held = await sendThroughRelay(dev.payload, dev.options, { ...MESSAGE, to: 'a-real-customer@example.org' }) @@ -798,7 +796,6 @@ describe('the token over time', () => { expect((await mailPanelState({ payload: dev.payload }, dev.options)).relay?.refusal).toBeUndefined() // the next fresh copy is held again: the consent was this database's, and the copy replaced it copy(live.store, dev.store) - forgetOtherHosts(dev.payload) expect(await sendThroughRelay(dev.payload, dev.options, MESSAGE)).toMatchObject({ cause: 'client-other-host', sent: false }) // production never noticed any of it expect((await readRelayStore(live.payload)).token).toBe(liveToken) @@ -897,6 +894,48 @@ describe('the token over time', () => { expect((await sendThroughRelay(copy.payload, { ...copy.options, developmentHosts: [] }, MESSAGE)).sent).toBe(true) }) + test('V-3: production\'s dump restored into the RUNNING development site right after it sent a mail — the very next mail is refused', async () => { + const live = shared({ serverURL: 'https://client.pl' }) + await sendThroughRelay(live.payload, live.options, MESSAGE) + const dev = shared({ serverURL: `https://${DEV}` }) + const on = { ...dev.options, fetchImpl: live.fake.fetch, url: live.fake.url } + // the development site is connected and has just sent (its own database, its own data) + await setRelayToken(dev.payload, live.fake.issueToken(DEV), on) + expect((await sendThroughRelay(dev.payload, on, MESSAGE)).sent).toBe(true) + // the restore: production's entries land in the database of the running process + for (const [key, value] of live.store) {dev.store.set(key, structuredClone(value))} + const requests = live.fake.requests.length + expect(await sendThroughRelay(dev.payload, on, { ...MESSAGE, to: 'a-real-customer@example.org' })).toMatchObject({ cause: 'client-other-host', sent: false }) + expect(live.fake.requests).toHaveLength(requests) + expect((await mailPanelState({ payload: dev.payload }, on)).relay?.refusal).toMatchObject({ code: 'client-other-host', reason: 'client.pl' }) + }) + + test('V-1, V-2: a malformed list stops the start; a trailing dot and a Unicode pattern still match', async () => { + // what is refused — by the checker, by the options in effect, by a value left in the config by hand + for (const bad of ['*.dev.netscale.pl', null, {}, [1, 2], [''], [' '], ['*.dev.netscale.pl', 7], ['*'], ['*.*'], [' * '], ['https://x.dev.example.com'], ['x.example.com/path'], ['a b.example.com'], ['*ż.example.com']]) { + expect(() => assertDevelopmentHosts(bad), JSON.stringify(bad)).toThrow(/must be an array of host patterns/) + const site = relayPayload({ custom: { iapl: { developmentHosts: bad } } }) + expect(() => resolveRelayOptions(site.payload, {}), JSON.stringify(bad)).toThrow(/developmentHosts/) + expect(() => resolveRelayOptions(relayPayload().payload, { developmentHosts: bad as never }), JSON.stringify(bad)).toThrow(/mail\.relay\.developmentHosts/) + } + expect(() => assertDevelopmentHosts(['*'])).toThrow(/matches every host/) + expect(() => assertDevelopmentHosts('*.dev.netscale.pl', 'iapl({ developmentHosts })')).toThrow('[iapl] iapl({ developmentHosts }) must be an array') + // what is taken + for (const good of [[], ['*.dev.netscale.pl'], ['staging.client.pl', '*.Preview.Agency-Example.com ', 'acme.*', '*.dev.zażółć.pl', '*.dev.netscale.pl.']]) {expect(assertDevelopmentHosts(good)).toBe(good)} + // a fully qualified name with the dot, in the address and in the pattern + expect(matchDevelopmentHost('https://acme.dev.netscale.pl.')).toBe('*.dev.netscale.pl') + expect(matchDevelopmentHost('https://acme.dev.netscale.pl.:8443/pl')).toBe('*.dev.netscale.pl') + expect(matchDevelopmentHost('acme.dev.netscale.pl', ['*.dev.netscale.pl.'])).toBe('*.dev.netscale.pl.') + const dotted = relayPayload({ serverURL: 'https://acme.dev.netscale.pl.' }) + expect(siteNonPublicSignal(dotted.payload, resolveRelayOptions(dotted.payload, {})!)).toEqual({ by: 'development-host', pattern: '*.dev.netscale.pl' }) + // a pattern written in Unicode matches the punycode host, and the other way round + expect(matchDevelopmentHost('https://acme.dev.zażółć.pl', ['*.dev.zażółć.pl'])).toBe('*.dev.zażółć.pl') + expect(new URL('https://zażółć.pl').hostname).toMatch(/^xn--/) + expect(matchDevelopmentHost(`acme.dev.${new URL('https://zażółć.pl').hostname}`, ['*.dev.ZAŻÓŁĆ.pl'])).toBe('*.dev.ZAŻÓŁĆ.pl') + expect(matchDevelopmentHost('https://acme.dev.zażółć.pl', [`*.dev.${new URL('https://zażółć.pl').hostname}`])).not.toBeNull() + expect(matchDevelopmentHost('acme.dev.zazolc.pl', ['*.dev.zażółć.pl'])).toBeNull() + }) + test('a developer\'s `localhost` on the production database, no env: refused before any call, nothing written', async () => { const production = shared({ serverURL: 'https://client.pl' }) await sendThroughRelay(production.payload, production.options, MESSAGE) @@ -933,7 +972,6 @@ describe('the token over time', () => { expect((await mailPanelState({ payload: staging.payload }, staging.options)).nonPublic).toBeUndefined() // the same site once it says so: held from the next e-mail on, although it has a token by now vi.stubEnv('IAPL_NOINDEX', '1') - forgetOtherHosts(staging.payload) expect(await sendThroughRelay(staging.payload, staging.options, MESSAGE)).toMatchObject({ cause: 'client-other-host', sent: false }) }) diff --git a/test/plugin.test.ts b/test/plugin.test.ts index dd535e0..47b98f4 100644 --- a/test/plugin.test.ts +++ b/test/plugin.test.ts @@ -4,6 +4,7 @@ import { describe, expect, test, vi } from 'vitest' import type { I18nConfig } from '../src/modules/i18n/types.js' +import { mailAdapter } from '../src/modules/email/mailAdapter.js' import { pluginDevelopmentHosts } from '../src/modules/email/relay/options.js' import { iapl } from '../src/plugin.js' import { withTotpParts } from './helpers.js' @@ -24,13 +25,19 @@ const base = (): Config => describe('iapl — config transform', () => { test('developmentHosts: nothing in the config by default (the built-in list applies), the project\'s list when given, an empty list too', async () => { - const hosts = async (own?: string[]) => { - const config = await iapl({ access: { authCollection: 'users' }, i18n, twoFactor: false, ...(own ? { developmentHosts: own } : {}) })(base()) + const hosts = async (...own: [string[]?]) => { + const config = await iapl({ access: { authCollection: 'users' }, i18n, twoFactor: false, ...(own.length ? { developmentHosts: own[0] } : {}) })(base()) return pluginDevelopmentHosts({ config } as never) } expect(await hosts()).toEqual(['*.dev.netscale.pl']) expect(await hosts(['*.preview.agency-example.com'])).toEqual(['*.preview.agency-example.com']) expect(await hosts([])).toEqual([]) + // V-1: a malformed list stops the start — the plugin option, the mail option, the adapter's own + for (const bad of ['*.dev.netscale.pl', null, [1, 2], [''], ['*']]) { + await expect(hosts(bad as never), JSON.stringify(bad)).rejects.toThrow('[iapl] iapl({ developmentHosts }) must be an array of host patterns') + await expect(Promise.resolve().then(() => iapl({ access: { authCollection: 'users' }, i18n, mail: { relay: { developmentHosts: bad as never } }, twoFactor: false })(base()))).rejects.toThrow('iapl({ mail: { relay: { developmentHosts } } })') + expect(() => mailAdapter({ relay: { developmentHosts: bad as never } })({ payload: {} as never }), JSON.stringify(bad)).toThrow('mailAdapter({ relay: { developmentHosts } })') + } }) test('adds globals, endpoint, localization and roles', async () => {