diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md index 973d36e..2971a78 100644 --- a/docs/CHANGELOG.md +++ b/docs/CHANGELOG.md @@ -11,7 +11,8 @@ once there are more than 20. ## 1.17.1 — security fixes from the IAWL review; the panel's sign-in look; the sending method is chosen -> **Read before upgrading.** No schema change, no migration on any database. In this order: +> **Read before upgrading.** **MongoDB: no migration. Postgres / SQLite: one migration** — a new column for the +> sending method (point 5). In this order: > > **1. A write-only secret could be read back (fixed).** On 1.17.0 an **admin** could recover the SMTP password or > the Turnstile secret key character by character through a query that names the field @@ -55,8 +56,11 @@ once there are more than 20. > be used — "Own SMTP server" without server, user name and password, "Microsoft Graph" on a server without > `GRAPH_*` — e-mails **fail and the panel says so; they are not sent another way** (in 1.17.0 they would have gone > through SMTP or IWSN). So after the upgrade: open the tab, check that the method shown is the one meant, save. -> No schema change: the choice is kept in `payload-kv`. A seed or script that set `emailTransport` keeps working -> (it leaves the site on the old order); to choose, it writes `emailMethod`. +> **Postgres / SQLite projects: create and apply one migration** (`pnpm payload migrate:create`; the new field +> `emailMethod` is a column) in the same deploy. Without it the site still sends its mail the old way and one loud +> log line says so, but the Site integrations page of the panel does not open. MongoDB: nothing. +> A seed or script that set `emailTransport` keeps working (it leaves the site on the old order); to choose, it +> writes `emailMethod`. ### Security - **Write-only secrets cannot be named in a query** (point 1 above). `secretReadAccess`, the field read rule behind @@ -148,10 +152,11 @@ once there are more than 20. shown; the state block and the test e-mail name it ("through IWSN" / "through your SMTP server" / "through Microsoft Graph"). A chosen method that cannot be used fails loudly — status `smtp-incomplete` / `graph-not-set-up`, doctor `mail-method` — and the mail is not sent another way; in 1.17.0 "Automatic" picked - the transport from which fields were filled in. Stored without a schema change: the field `emailMethod` is - virtual, the choice is in `payload-kv` (`MAIL_METHOD_KV_KEY`); `emailTransport` stays, hidden. - New exports: `getMailMethod`, `setMailMethod`, `resolveMailMethod`, `isMailMethod`, `MAIL_METHODS`, - `MAIL_METHOD_KV_KEY`, types `MailMethod`, `ResolvedMailMethod`, `MailMethodProblem`. `pnpm payload generate:types` + the transport from which fields were filled in. Stored in a new field of Site integrations, `emailMethod` + (`relay` / `smtp` / `graph`, empty until somebody chooses); `emailTransport` stays, hidden. + New exports: `getMailMethod`, `setMailMethod`, `resolveMailMethod`, `readMailSettings`, `isMailMethod`, + `MAIL_METHODS`, `STORED_MAIL_METHOD_CONTEXT`, `mailMethodColumnMissing`, types `MailMethod`, `ResolvedMailMethod`, + `MailMethodProblem`. `pnpm payload generate:types` gives a diff (the new field): run it and commit. - `AdminLogo` prints the sign-in panel when the plugin gives it `signIn` (the default with `whiteLabel`); wired by hand without that prop it is the plain logo as before. The logo on the login screen is now shown inside @@ -164,6 +169,10 @@ once there are more than 20. - `truncate` (summaries, meta descriptions) never returns more than its limit. ### Requires project changes +- **Postgres / SQLite projects: one migration**, in the same deploy — the new field `emailMethod` of Site + integrations is a column (`pnpm payload migrate:create`, commit, apply at container start). MongoDB projects: + nothing. Until it runs: mail keeps going the old way, the Site integrations page does not open, + `iapl-doctor --deep` reports `mail-method` (point 5 above). - **The proxy matcher**, one line (point 4 above). - **A config value the plugin does not understand** stops the start (point 2): `pnpm build` before deploying. - **Recommended with `whiteLabel`:** `signIn: { allScreens: true }` + `pnpm payload generate:importmap`; look at a diff --git a/docs/agent/AGENT.md b/docs/agent/AGENT.md index 58d4beb..f2c6008 100644 --- a/docs/agent/AGENT.md +++ b/docs/agent/AGENT.md @@ -1292,14 +1292,17 @@ banner that is already in every import map). **Do not** add `nodemailer`, `resen **How a send is routed** — by the admin's choice, Site integrations → E-mail sending → **"Sending method"**: "IWSN (built-in)" (the mail service), "Own SMTP server", "Microsoft Graph (deprecated)". What is chosen is what is used; a choice that cannot be used (SMTP incomplete, Graph without `GRAPH_*`) **fails loudly and nothing is sent another -way** (state block, status `smtp-incomplete` / `graph-not-set-up`, doctor `mail-method`). The choice is kept in -`payload-kv` (`MAIL_METHOD_KV_KEY`); the panel's field `emailMethod` is virtual, so **no schema change and no -migration**. Until somebody chooses (an upgraded site, a new site) the order of 1.17.0 applies and the field shows +way** (state block, status `smtp-incomplete` / `graph-not-set-up`, doctor `mail-method`). The choice is the stored field +`emailMethod` (`relay` / `smtp` / `graph`; empty until somebody chooses) — **MongoDB: nothing to run; Postgres / SQLite: +one migration** (`pnpm payload migrate:create`, applied at container start); before it runs the site keeps sending the +old way, the Site integrations page does not open, and `iapl-doctor --deep` reports `mail-method` (error). Until somebody chooses (an upgraded site, a new site) the order of 1.17.0 applies and the field shows its result as selected (`resolveMailTransport`, type `MailTransport`): Graph when `emailTransport` is `graph` and `GRAPH_*` is set → SMTP when server, user name and password are filled in → Graph when `GRAPH_*` is set → the mail service → nothing. The first save of Site integrations stores the choice. From code: `getMailMethod`, `setMailMethod(payload, 'relay' | 'smtp' | 'graph' | null)`, `resolveMailMethod` (`ResolvedMailMethod`, -`MailMethodProblem`), `MailMethod`, `MAIL_METHODS`, `isMailMethod`; or `updateGlobal` with `emailMethod`. Seeds that +`MailMethodProblem`), `MailMethod`, `MAIL_METHODS`, `isMailMethod`, `readMailSettings` / `STORED_MAIL_METHOD_CONTEXT` +(a read with the value as stored — an ordinary read shows the method in effect), `mailMethodColumnMissing`; or +`updateGlobal` with `emailMethod`. Seeds that set up mail write `emailMethod`, not `emailTransport`. **Verify:** the state block names the method; **Send test e-mail** answers "through IWSN" / "through your SMTP server" / "through Microsoft Graph"; `iapl-doctor --deep` reports no `mail-method` finding after the first save. `mail: { relay: false }` removes the option "IWSN". diff --git a/docs/agent/skills/iapl-debug/SKILL.md b/docs/agent/skills/iapl-debug/SKILL.md index 87d1d7f..14e7686 100644 --- a/docs/agent/skills/iapl-debug/SKILL.md +++ b/docs/agent/skills/iapl-debug/SKILL.md @@ -101,6 +101,7 @@ through this procedure. Ask only when you are missing something you cannot get y | banner without styles | Tailwind does not scan the plugin | `@source` on `node_modules/@intecion/ipal-kit/dist/**/*.js` (path relative to the CSS file, PROGRAMISTA §2.5) | | emails are not sent | no `email: mailAdapter()` / empty Emails tab of the form / the transport fails | Site integrations → E-mail sending: read the block "How e-mails are sent" and the banner's code, then **Send test e-mail**; rows below; email.md | | e-mails are not sent; state block: "Your SMTP server is chosen, but its settings are incomplete" / "Microsoft Graph is chosen, but it is not set up on this server" (status `smtp-incomplete` / `graph-not-set-up`, doctor `mail-method` error) | the chosen "Sending method" cannot be used, and since 1.17.1 nothing is sent another way | fill in server, user name and password / set the `GRAPH_*` variables — or choose another method (IWSN needs nothing) and save | +| Site integrations does not open after the upgrade to 1.17.1 (Postgres / SQLite); log: "the column for \"emailMethod\" … is missing"; doctor `mail-method` error | the migration that adds the column has not run (mail still leaves the old way) | `pnpm payload migrate:create`, commit, apply at container start | | the site switched how it sends after a field or a variable changed | nobody has chosen the "Sending method" yet (doctor `mail-method` info): the site still picks by the order of 1.17.0 | Site integrations → E-mail sending: check the method shown, save | | state block: "Not connected yet" on the production domain | no e-mail was sent yet | **Send test e-mail** (the site enrols on its first send) or "Connect again" | | `relay-refused` / "The mail service could not reach this site at …" (cause `callback-failed`) | `unreachable` / `timeout`: firewall, private network, wrong public host in `serverURL`; `redirect`: `trailingSlash: true`, apex → `www`, a language redirect; `status`: route blocked, missing (`mail: { relay: false }`?) or another `routes.api`; `confirmation`: a proxy rewrites the answer | `curl -i -X POST https:///api/iapl/mail-relay/confirm -d '{}' -H 'content-type: application/json'` must answer **404 with an empty body, no redirect**; fix `serverURL` / `mail.relay.host`, or ask Intecion to set the site's confirm address (path ending in `/confirm/` with trailing slashes); then "Connect again" (the site does not retry by itself for 15 min). email.md "When the site cannot be confirmed" | diff --git a/docs/agent/skills/iapl-reference/SKILL.md b/docs/agent/skills/iapl-reference/SKILL.md index 48d1327..a07f1ad 100644 --- a/docs/agent/skills/iapl-reference/SKILL.md +++ b/docs/agent/skills/iapl-reference/SKILL.md @@ -39,7 +39,7 @@ description: Complete map of everything @intecion/ipal-kit provides — every ia | `accounts.firstUserRoute` | `'panel'` | which auth collections `POST /api//first-register` answers for while they are empty: only the one the panel logs in with (the first account of a site → admin). Others get `403`, a second staff collection included, in any spelling of the URL (the plugin's own endpoint sits in front of Payload's); a collection whose own `create` allows an anonymous request keeps its route. With `access.firstUserAdmin: false` and a default role below the panel role, the default `panelRole` is not applied (logged) and an explicit one is refused at start | a list of slugs; `'all'` = Payload's behaviour | | `accounts.password` | `{ minLength: 12 }` | when a password is SET on a staff collection (create, first-user screen, change, reset by e-mail; panel, API and Local API): at least `minLength` characters, not the account's e-mail address. Existing passwords are never checked — a shorter one keeps logging in | `{ minLength }`; `false` = Payload's rule (3 characters) | | `secrets.writeOnly` | on | `smtpPassword` and `turnstileSecretKey` (Site integrations) are never returned: REST, GraphQL and the panel get `'********'` when a value is stored; a save with nothing / empty / the mask keeps it, a new value replaces it, `'[[clear]]'` removes it; the Local API with access control off reads the real value. The panel is the source of these secrets — no env variable. A restore of a version is masked too | `false` = returned to whoever may read the global, as before | -| "Sending method" (`emailMethod`, virtual; `getMailMethod` / `setMailMethod`) | nobody has chosen: the order of 1.17.0, shown as selected | `relay` (IWSN), `smtp`, `graph` (deprecated): what is chosen is what is used, no fallback; kept in `payload-kv`, no schema change | +| "Sending method" (`emailMethod`; `getMailMethod` / `setMailMethod`) | nobody has chosen: the order of 1.17.0, shown as selected | `relay` (IWSN), `smtp`, `graph` (deprecated): what is chosen is what is used, no fallback; a stored field (Postgres / SQLite: one migration) | | `secrets.reenterOnChange` | on | a save through access control that changes `smtpHost`, `smtpPort` or `smtpUser` while a password is stored must send the password again or remove it (`400` on the field otherwise), whatever `emailTransport` says — so an admin session cannot send the stored password to a server of its own. A change of the transport alone, and the Local API with access control off, are not asked | `false` = the stored password follows the new server | | `dashboardAlerts` | `{ integrations: 'admin', cookies: 'editor' }` | who sees the plugin's dashboard alerts: integration details (error text, link) for `integrations` and above, a neutral "ask an administrator" for editors below it, nothing for others; the cookie crawl / approval alert for `cookies` and above. With a role, a session that owes its second factor sees none | `integrations: 'editor' | 'all'`, `cookies: 'all'` (`'all'` = as before: no role and no second factor is checked) | | `adminRoute` | `'/admin'` | `config.routes.admin`; stats link and views, `IntegrationAlerts` | the project moves `app/(payload)//` itself and adds the route to the proxy matcher (security.md) | diff --git a/docs/agent/skills/iapl-upgrade/SKILL.md b/docs/agent/skills/iapl-upgrade/SKILL.md index 6fc4e92..d96d899 100644 --- a/docs/agent/skills/iapl-upgrade/SKILL.md +++ b/docs/agent/skills/iapl-upgrade/SKILL.md @@ -673,8 +673,10 @@ PROGRAMISTA §6, items 73–75; email.md; AGENT.md §7.2) — nothing to run; re `https://webservices.intecion.net/mail`; while the service runs with enrolment "pending" (from its launch until Intecion switches to open enrolment), every new site waits for approval — keep SMTP until it is approved, or `relay: false`.** **→ 1.17.1, e-mail (CHANGELOG 1.17.1 point 5; email.md "Which transport a send takes"; AGENT.md §7.2) — nothing to run, one check:** -1. No schema change, no migration, no import-map change; `pnpm payload generate:types` gives a diff (the virtual field - `emailMethod`): run it and commit. +1. **MongoDB: no migration. Postgres / SQLite: `pnpm payload migrate:create`** (the new field `emailMethod` is a column), + commit it, apply it when the new container starts — in the same deploy. Without it mail still leaves the old way, but + the Site integrations page does not open and the log and `iapl-doctor --deep` (`mail-method`, error) say so. No + import-map change; `pnpm payload generate:types` gives a diff (the field `emailMethod`): run it and commit. 2. After the deploy open Site integrations → E-mail sending. "Sending method" shows the method the site sends through today as selected: **IWSN (built-in)** (no SMTP server), **Own SMTP server**, or **Microsoft Graph (deprecated)** (`GRAPH_*` on the server). Check it is the one meant, **save**, send a test e-mail: the answer names the method. diff --git a/docs/doctor.md b/docs/doctor.md index 2981054..83a6793 100644 --- a/docs/doctor.md +++ b/docs/doctor.md @@ -114,7 +114,7 @@ Turn off: `iapl({ doctor: false })`. Adapt: `iapl({ doctor: { tokenVar: 'MY_TOKE | | `turnstile-env-key` | warning | (deep) the Turnstile secret key is in the panel, not in the deprecated `TURNSTILE_SECRET_KEY` environment variable | | | `storage-names` | warning | the visitor cookie the layout sets (``, default `ipal_vid`) is the one the config makes the cookie scanner declare (`storageNames`, stats.md) | | | `cookie-scanner` | error / warning / info | `cookieScanner` on (with `crawl`, else info); deep: nothing waits for approval (warning) | -| mail | `mail-method` | error / info | (deep) the chosen "Sending method" can be used — "Own SMTP server" with server, user name and password, "Microsoft Graph" with the `GRAPH_*` variables; otherwise e-mails are not sent and nothing is sent another way (error). Nobody has chosen yet: the site picks a method from what is filled in until Site integrations is saved (info) | +| mail | `mail-method` | error / info | (deep) the chosen "Sending method" can be used — "Own SMTP server" with server, user name and password, "Microsoft Graph" with the `GRAPH_*` variables; otherwise e-mails are not sent and nothing is sent another way (error). On Postgres / SQLite: the column of `emailMethod` exists — the 1.17.1 migration has run (error). Nobody has chosen yet: the site picks a method from what is filled in until Site integrations is saved (info) | | | `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) | diff --git a/docs/email.md b/docs/email.md index 3030286..4b49588 100644 --- a/docs/email.md +++ b/docs/email.md @@ -54,16 +54,27 @@ SMTP server, port, user name and password under "Own SMTP server"; the service's panel's SMTP server when one is filled in ("Attachments" below). - `mail: { relay: false }` takes the option "IWSN" away; a choice of it stored earlier then counts as no choice. -**Where the choice is stored.** In Payload's key-value store (`payload-kv`, key `MAIL_METHOD_KV_KEY`), not in a -column: the panel's field `emailMethod` is **virtual**. So **no SQL schema changes and no migration exists** — -a third value in the stored select `emailTransport` (`smtp` / `graph` since 1.6) would have changed the Postgres -enum, and could still not tell "SMTP was chosen" from the `smtp` every site has stored since before there was a -choice. `emailTransport` stays, hidden in the panel, and follows the choice where it can say it (`graph`, else -`smtp`). From code: `getMailMethod(payload)` (`'relay' | 'smtp' | 'graph' | null`), `setMailMethod(payload, method)` -(a seed or a deploy script; `null` = nobody has chosen), `payload.updateGlobal({ slug: 'site-integrations', data: { -emailMethod: 'smtp' } })`, `resolveMailMethod(settings, { chosen, graphEnv, relay })` → -`{ method, explicit, problem? }` (types `MailMethod`, `ResolvedMailMethod`, `MailMethodProblem`; `MAIL_METHODS`, -`isMailMethod`). +**Where the choice is stored.** In the global's own field **`emailMethod`** (a select: `relay` = IWSN, `smtp`, +`graph`), new in 1.17.1 and **empty until somebody chooses**. The field of 1.6 – 1.17.0, `emailTransport` +(`smtp` / `graph`), stays, hidden in the panel, and follows the choice where it can say it (`graph`, else `smtp`). +A field of its own, not a third value there: every site has `smtp` stored in `emailTransport` from before there was +a choice, so "SMTP was chosen" could not be told from "nothing was chosen". From code: `getMailMethod(payload)` +(`'relay' | 'smtp' | 'graph' | null`), `setMailMethod(payload, method)` (a seed or a deploy script; `null` = nobody +has chosen), `payload.updateGlobal({ slug: 'site-integrations', data: { emailMethod: 'smtp' } })`, +`resolveMailMethod(settings, { chosen, graphEnv, relay })` → `{ method, explicit, problem? }` (types `MailMethod`, +`ResolvedMailMethod`, `MailMethodProblem`; `MAIL_METHODS`, `isMailMethod`). **A read shows the method in effect** +in `emailMethod` (that is what the panel selects); the stored value itself — empty when nobody chose — comes from +`getMailMethod`, or from `readMailSettings(payload)` / a read with `context: { [STORED_MAIL_METHOD_CONTEXT]: true }`. + +**Postgres and SQLite: one migration. MongoDB: nothing.** The field is a new column (`email_method`, with its +enum on Postgres): `pnpm payload migrate:create`, commit the migration, and have it applied when the new container +starts ([deployment.md](./deployment.md) §4.3). **Before it has run** the site does not go down: the plugin's own +readers (`getSiteIntegrations`, the mail adapter, Turnstile, analytics) notice the missing column, read the global +without that field, and one loud line in the server log says what to do; e-mails go the way they did before the +upgrade. What does not work until the migration: the **Site integrations page of the panel** (Payload's own read +fails), every write to the global — the sending status is not recorded — and choosing the method. +`mailMethodColumnMissing()` and the doctor's deep run (`mail-method`, error) report it. A running process looks for +the column again within a minute. **Until somebody chooses — a site upgraded from 1.17.0 or older, and a new site.** Nothing is written on upgrade. The method follows the order of 1.17.0, the field shows it **as selected**, and mail keeps leaving the way it did diff --git a/docs/integrations.md b/docs/integrations.md index a76a740..004b8df 100644 --- a/docs/integrations.md +++ b/docs/integrations.md @@ -14,7 +14,7 @@ Currently always added by the plugin. Tabs (unnamed — flat data, e.g. `ga4Meas |---|---| | Analytics | `ga4MeasurementId`, `gtmContainerId`, `metaPixelId`, `clarityProjectId`, `linkedInPartnerId`, `tiktokPixelId` | | Spam protection | `turnstileSiteKey`, `turnstileSecretKey`, hidden `turnstileStatus` + banner | -| E-mail sending | the state block "How e-mails are sent" (part of the tab's status banner — nothing stored; absent with `mail: { relay: false }`), "Sending method" `emailMethod` (virtual: `relay` = IWSN / `smtp` / `graph` = deprecated; the choice is kept in `payload-kv`), `emailTransport` (hidden; the stored field of 1.6 – 1.17.0), `smtpHost`, `smtpPort`, `smtpUser`, `smtpPassword`, `smtpFromAddress`, `smtpFromName`, test button, hidden `emailStatus` + banner | +| E-mail sending | the state block "How e-mails are sent" (part of the tab's status banner — nothing stored; absent with `mail: { relay: false }`), "Sending method" `emailMethod` (`relay` = IWSN / `smtp` / `graph` = deprecated; empty until somebody chooses, a read shows the method in effect; new in 1.17.1 — a column on Postgres / SQLite), `emailTransport` (hidden; the stored field of 1.6 – 1.17.0), `smtpHost`, `smtpPort`, `smtpUser`, `smtpPassword`, `smtpFromAddress`, `smtpFromName`, test button, hidden `emailStatus` + banner | | IndexNow | `indexNowKey` (generated on first save) | | More | fields from the `integrationsFields` option — only when given | diff --git a/reference/.agents/skills/iapl-debug/SKILL.md b/reference/.agents/skills/iapl-debug/SKILL.md index 87d1d7f..14e7686 100644 --- a/reference/.agents/skills/iapl-debug/SKILL.md +++ b/reference/.agents/skills/iapl-debug/SKILL.md @@ -101,6 +101,7 @@ through this procedure. Ask only when you are missing something you cannot get y | banner without styles | Tailwind does not scan the plugin | `@source` on `node_modules/@intecion/ipal-kit/dist/**/*.js` (path relative to the CSS file, PROGRAMISTA §2.5) | | emails are not sent | no `email: mailAdapter()` / empty Emails tab of the form / the transport fails | Site integrations → E-mail sending: read the block "How e-mails are sent" and the banner's code, then **Send test e-mail**; rows below; email.md | | e-mails are not sent; state block: "Your SMTP server is chosen, but its settings are incomplete" / "Microsoft Graph is chosen, but it is not set up on this server" (status `smtp-incomplete` / `graph-not-set-up`, doctor `mail-method` error) | the chosen "Sending method" cannot be used, and since 1.17.1 nothing is sent another way | fill in server, user name and password / set the `GRAPH_*` variables — or choose another method (IWSN needs nothing) and save | +| Site integrations does not open after the upgrade to 1.17.1 (Postgres / SQLite); log: "the column for \"emailMethod\" … is missing"; doctor `mail-method` error | the migration that adds the column has not run (mail still leaves the old way) | `pnpm payload migrate:create`, commit, apply at container start | | the site switched how it sends after a field or a variable changed | nobody has chosen the "Sending method" yet (doctor `mail-method` info): the site still picks by the order of 1.17.0 | Site integrations → E-mail sending: check the method shown, save | | state block: "Not connected yet" on the production domain | no e-mail was sent yet | **Send test e-mail** (the site enrols on its first send) or "Connect again" | | `relay-refused` / "The mail service could not reach this site at …" (cause `callback-failed`) | `unreachable` / `timeout`: firewall, private network, wrong public host in `serverURL`; `redirect`: `trailingSlash: true`, apex → `www`, a language redirect; `status`: route blocked, missing (`mail: { relay: false }`?) or another `routes.api`; `confirmation`: a proxy rewrites the answer | `curl -i -X POST https:///api/iapl/mail-relay/confirm -d '{}' -H 'content-type: application/json'` must answer **404 with an empty body, no redirect**; fix `serverURL` / `mail.relay.host`, or ask Intecion to set the site's confirm address (path ending in `/confirm/` with trailing slashes); then "Connect again" (the site does not retry by itself for 15 min). email.md "When the site cannot be confirmed" | diff --git a/reference/.agents/skills/iapl-reference/SKILL.md b/reference/.agents/skills/iapl-reference/SKILL.md index 48d1327..a07f1ad 100644 --- a/reference/.agents/skills/iapl-reference/SKILL.md +++ b/reference/.agents/skills/iapl-reference/SKILL.md @@ -39,7 +39,7 @@ description: Complete map of everything @intecion/ipal-kit provides — every ia | `accounts.firstUserRoute` | `'panel'` | which auth collections `POST /api//first-register` answers for while they are empty: only the one the panel logs in with (the first account of a site → admin). Others get `403`, a second staff collection included, in any spelling of the URL (the plugin's own endpoint sits in front of Payload's); a collection whose own `create` allows an anonymous request keeps its route. With `access.firstUserAdmin: false` and a default role below the panel role, the default `panelRole` is not applied (logged) and an explicit one is refused at start | a list of slugs; `'all'` = Payload's behaviour | | `accounts.password` | `{ minLength: 12 }` | when a password is SET on a staff collection (create, first-user screen, change, reset by e-mail; panel, API and Local API): at least `minLength` characters, not the account's e-mail address. Existing passwords are never checked — a shorter one keeps logging in | `{ minLength }`; `false` = Payload's rule (3 characters) | | `secrets.writeOnly` | on | `smtpPassword` and `turnstileSecretKey` (Site integrations) are never returned: REST, GraphQL and the panel get `'********'` when a value is stored; a save with nothing / empty / the mask keeps it, a new value replaces it, `'[[clear]]'` removes it; the Local API with access control off reads the real value. The panel is the source of these secrets — no env variable. A restore of a version is masked too | `false` = returned to whoever may read the global, as before | -| "Sending method" (`emailMethod`, virtual; `getMailMethod` / `setMailMethod`) | nobody has chosen: the order of 1.17.0, shown as selected | `relay` (IWSN), `smtp`, `graph` (deprecated): what is chosen is what is used, no fallback; kept in `payload-kv`, no schema change | +| "Sending method" (`emailMethod`; `getMailMethod` / `setMailMethod`) | nobody has chosen: the order of 1.17.0, shown as selected | `relay` (IWSN), `smtp`, `graph` (deprecated): what is chosen is what is used, no fallback; a stored field (Postgres / SQLite: one migration) | | `secrets.reenterOnChange` | on | a save through access control that changes `smtpHost`, `smtpPort` or `smtpUser` while a password is stored must send the password again or remove it (`400` on the field otherwise), whatever `emailTransport` says — so an admin session cannot send the stored password to a server of its own. A change of the transport alone, and the Local API with access control off, are not asked | `false` = the stored password follows the new server | | `dashboardAlerts` | `{ integrations: 'admin', cookies: 'editor' }` | who sees the plugin's dashboard alerts: integration details (error text, link) for `integrations` and above, a neutral "ask an administrator" for editors below it, nothing for others; the cookie crawl / approval alert for `cookies` and above. With a role, a session that owes its second factor sees none | `integrations: 'editor' | 'all'`, `cookies: 'all'` (`'all'` = as before: no role and no second factor is checked) | | `adminRoute` | `'/admin'` | `config.routes.admin`; stats link and views, `IntegrationAlerts` | the project moves `app/(payload)//` itself and adds the route to the proxy matcher (security.md) | diff --git a/reference/.agents/skills/iapl-upgrade/SKILL.md b/reference/.agents/skills/iapl-upgrade/SKILL.md index 6fc4e92..d96d899 100644 --- a/reference/.agents/skills/iapl-upgrade/SKILL.md +++ b/reference/.agents/skills/iapl-upgrade/SKILL.md @@ -673,8 +673,10 @@ PROGRAMISTA §6, items 73–75; email.md; AGENT.md §7.2) — nothing to run; re `https://webservices.intecion.net/mail`; while the service runs with enrolment "pending" (from its launch until Intecion switches to open enrolment), every new site waits for approval — keep SMTP until it is approved, or `relay: false`.** **→ 1.17.1, e-mail (CHANGELOG 1.17.1 point 5; email.md "Which transport a send takes"; AGENT.md §7.2) — nothing to run, one check:** -1. No schema change, no migration, no import-map change; `pnpm payload generate:types` gives a diff (the virtual field - `emailMethod`): run it and commit. +1. **MongoDB: no migration. Postgres / SQLite: `pnpm payload migrate:create`** (the new field `emailMethod` is a column), + commit it, apply it when the new container starts — in the same deploy. Without it mail still leaves the old way, but + the Site integrations page does not open and the log and `iapl-doctor --deep` (`mail-method`, error) say so. No + import-map change; `pnpm payload generate:types` gives a diff (the field `emailMethod`): run it and commit. 2. After the deploy open Site integrations → E-mail sending. "Sending method" shows the method the site sends through today as selected: **IWSN (built-in)** (no SMTP server), **Own SMTP server**, or **Microsoft Graph (deprecated)** (`GRAPH_*` on the server). Check it is the one meant, **save**, send a test e-mail: the answer names the method. diff --git a/reference/e2e/mail-relay.spec.ts b/reference/e2e/mail-relay.spec.ts index d50be4e..7e3e142 100644 --- a/reference/e2e/mail-relay.spec.ts +++ b/reference/e2e/mail-relay.spec.ts @@ -82,6 +82,18 @@ test.describe('the mail service', () => { await expect(block).toContainText(/Connected to IWSN|Połączono z IWSN/) await expect(block).toContainText(/Left this hour: 29|Pozostało w tej godzinie: 29/) + // "Sending method": the method in effect is the one selected, and only its fields are on the page (not saved here) + const method = page.locator('#field-emailMethod') + await expect(method).toContainText(/IWSN \((built-in|wbudowany)\)/) + await expect(page.locator('#field-smtpHost')).toHaveCount(0) + await method.locator('.rs__control').click() + await page.locator('.rs__option', { hasText: /Own SMTP server|Własny serwer SMTP/ }).click() + await expect(page.locator('#field-smtpHost')).toBeVisible() + await expect(page.locator('#field-smtpUser')).toBeVisible() + await method.locator('.rs__control').click() + await page.locator('.rs__option', { hasText: /IWSN/ }).click() + await expect(page.locator('#field-smtpHost')).toHaveCount(0) + // (Payload takes the login cookie only from the site's own origin, so the request says where it comes from) const status = await page.request.get('/api/iapl/mail-relay/status', { headers: { origin: baseURL! } }) expect(await status.json()).toMatchObject({ ok: true, relay: { connected: true, state: 'active', tokenSource: 'enrolment' }, transport: 'relay' }) diff --git a/src/globals/SiteIntegrations/fields/smtp.ts b/src/globals/SiteIntegrations/fields/smtp.ts index a8913d6..9ae94ac 100644 --- a/src/globals/SiteIntegrations/fields/smtp.ts +++ b/src/globals/SiteIntegrations/fields/smtp.ts @@ -1,7 +1,7 @@ -import type { BasePayload, Condition, Field } from 'payload' +import type { Condition, Field, SelectField } from 'payload' import { graphAvailable, resolveMailMethod } from '../../../modules/email/mailAdapter.js' -import { getMailMethod, type MailMethod } from '../../../modules/email/method.js' +import { isMailMethod, type MailMethod, STORED_MAIL_METHOD_CONTEXT } from '../../../modules/email/method.js' import { RELAY_SHORT_NAME as IWSN } from '../../../modules/email/relay/constants.js' import { buildIntegrationStatusBanner, buildIntegrationStatusField } from '../../../modules/integrations/status.js' @@ -19,12 +19,15 @@ import { buildIntegrationStatusBanner, buildIntegrationStatusField } from '../.. const usesSmtp: Condition = (_, siblingData) => siblingData?.emailMethod ? siblingData.emailMethod === 'smtp' : siblingData?.emailTransport !== 'graph' +const withoutRelay: NonNullable = ({ options }) => + options.filter((option) => (typeof option === 'string' ? option : option.value) !== 'relay') + /** * What the "Sending method" field shows: the chosen method, or — while nobody has chosen — the method the * order of 1.17.0 picks for the present settings (so an upgraded site sees what it sends through today). */ -export async function shownMailMethod(payload: Pick, settings: Parameters[0], relay: boolean): Promise { - const { method } = resolveMailMethod(settings, { chosen: await getMailMethod(payload), graphEnv: graphAvailable(), relay }) +export function shownMailMethod(settings: Parameters[0], relay: boolean): MailMethod { + const { method } = resolveMailMethod(settings, { chosen: isMailMethod(settings.emailMethod) ? settings.emailMethod : null, graphEnv: graphAvailable(), relay }) // nothing usable at all (the service switched off, no SMTP, no Graph): SMTP is what is left to fill in return method === 'none' ? 'smtp' : method } @@ -33,9 +36,10 @@ export async function shownMailMethod(payload: Pick, settings * The fields of the "E-mail sending" tab. `relay: false` (the project switched the Intecion mail * service off): no state block, no "IWSN" option, and the wording of 1.16 — SMTP is then the way to send. * - * "Sending method" (`emailMethod`) is a VIRTUAL field: it has no column, so no SQL schema changes. The - * choice is kept in the key-value store (modules/email/method.ts) by the global's hooks. `emailTransport` - * — the stored field of 1.6 to 1.17.0, values `smtp` / `graph` — stays as it was, hidden in the panel. + * "Sending method" (`emailMethod`) is a stored select, new in 1.17.1 (Postgres / SQLite: one migration); empty + * while nobody has chosen. Its three values are the same in every project, so the SQL enum does not depend on + * `relay`; with the service switched off the option is only not offered. `emailTransport` — the stored field of + * 1.6 to 1.17.0, values `smtp` / `graph` — stays as it was, hidden in the panel. */ export const buildSmtpFields = ({ relay = true }: { relay?: boolean } = {}): Field[] => [ // Status written by mailAdapter on every send (throttled) — banner on this tab. With the mail service @@ -56,17 +60,26 @@ export const buildSmtpFields = ({ relay = true }: { relay?: boolean } = {}): Fie pl: 'E-maile wychodzą wybranym tu sposobem i żadnym innym.', }, }, + // with the service switched off the stored values stay three; "IWSN" is only not offered + ...(relay ? {} : { filterOptions: withoutRelay }), hooks: { - afterRead: [({ req, siblingData }) => shownMailMethod(req.payload, siblingData ?? {}, relay)], + afterRead: [({ context, siblingData, value }) => { + // what is stored, for the update that follows this read (the global's beforeChange) … + if (context) {context.iaplMailMethodStored = isMailMethod(value) ? value : null} + // … and for the readers that decide from it (the mail adapter, the state block) + if (context?.[STORED_MAIL_METHOD_CONTEXT]) {return isMailMethod(value) ? value : null} + // the panel and everybody else: the method in effect, shown as selected + return shownMailMethod({ ...(siblingData ?? {}), emailMethod: value as never }, relay) + }], }, label: { en: 'Sending method', pl: 'Sposób wysyłki' }, options: [ - ...(relay ? [{ label: { en: `${IWSN} (built-in)`, pl: `${IWSN} (wbudowany)` }, value: 'relay' }] : []), + // (with the service switched off the value stays in the list — one SQL enum for every project — unnamed and not offered) + { label: relay ? { en: `${IWSN} (built-in)`, pl: `${IWSN} (wbudowany)` } : { en: 'Built-in (off)', pl: 'Wbudowany (wyłączony)' }, value: 'relay' }, { label: relay ? { en: 'Own SMTP server', pl: 'Własny serwer SMTP' } : { en: 'SMTP server', pl: 'Serwer SMTP' }, value: 'smtp' }, // Works only when the administrator has set Graph up on the server (GRAPH_*); chosen without it, e-mails fail and say so. { label: { en: 'Microsoft Graph (deprecated)', pl: 'Microsoft Graph (wycofywany)' }, value: 'graph' }, ], - virtual: true, }, { // The stored field of 1.6 – 1.17.0. Kept with its two values (a third would change the Postgres enum) and diff --git a/src/globals/SiteIntegrations/index.ts b/src/globals/SiteIntegrations/index.ts index c388fe2..31ff4c7 100644 --- a/src/globals/SiteIntegrations/index.ts +++ b/src/globals/SiteIntegrations/index.ts @@ -3,7 +3,7 @@ import type { Field, GlobalConfig } from 'payload' import { ValidationError } from 'payload' import { userMeetsRole } from '../../modules/access/index.js' -import { isMailMethod, setMailMethod } from '../../modules/email/method.js' +import { isMailMethod } from '../../modules/email/method.js' import { INTEGRATION_SECRET_FIELDS, maskSecretsOnRestore, SMTP_PASSWORD_BOUND_TO, writeOnlySecrets } from '../../modules/secrets/writeOnly.js' import { indexNowFields } from '../../modules/seo/indexNow.js' import { analyticsFields } from './fields/analytics.js' @@ -90,45 +90,37 @@ export function buildSiteIntegrations({ hooks: { // a restore answers with the version document: the secrets are masked there too ...(writeOnly ? { afterRead: [maskSecretsOnRestore] } : {}), - afterChange: [ - async ({ context, doc, req }) => { - if (isMailMethod(context?.iaplMailMethod)) { - await setMailMethod(req.payload, context.iaplMailMethod) - // (the answer was read before this write: it must show what was just chosen) - if (doc && typeof doc === 'object') {(doc as Record).emailMethod = context.iaplMailMethod} - } else if (context?.iaplMailMethod === null) { - await setMailMethod(req.payload, null) - } - return doc - }, - ], // What the caller sent for the sending method, before Payload merges the stored document into the data. beforeChange: [ // Keys edited in the panel → clear that integration's old status, so a stale // "not working" banner doesn't linger until the next form submission. - async ({ context, data, originalDoc, req }) => { + ({ context, data, originalDoc, req }) => { if (context?.ipalIntegrationStatus || !data) {return data} const changed = (k: string) => k in data && data[k] !== originalDoc?.[k] const cleared = { checkedAt: null, code: null, message: null, since: null, state: null } - // "Sending method" (the virtual field `emailMethod`): the choice is written to the key-value store - // once the global is saved (afterChange). The stored `emailTransport` follows where it can say it. - // (`data` is merged with the stored document by now; what the caller really sent was noted before the - // merge — beforeOperation below. Without that note: a value that differs from the stored one was sent.) - const noted = context?.iaplMailSent as { method?: unknown; transport?: boolean } | undefined - const sent = noted ? noted.method : data.emailMethod !== originalDoc?.emailMethod ? data.emailMethod : undefined - // (a virtual field's value is not checked against its options by Payload) - if (sent !== undefined && sent !== null && !(isMailMethod(sent) && (sent !== 'relay' || mailRelay))) { - throw new ValidationError({ errors: [{ message: 'This is not a sending method.', path: 'emailMethod' }], global: 'site-integrations' }, req.t) - } - if (isMailMethod(sent)) { - data.emailMethod = sent - const before = await shownMailMethod(req.payload, (originalDoc ?? {}) as never, mailRelay).catch(() => null) - if (before !== data.emailMethod) {data.emailStatus = cleared} - context.iaplMailMethod = data.emailMethod + // "Sending method" (`emailMethod`). `data` is merged with the document as it was READ by now, and that read + // shows the method in effect as selected — which must not be stored as a choice nobody made. So: what the + // caller really sent was noted before the merge (beforeOperation below; without that note, a value that + // differs from the one read was sent), and what is stored was noted by the field's own read. + const noted = context?.iaplMailSent as { method?: unknown; sent?: boolean; transport?: boolean } | undefined + const sent = noted ? noted.sent : data.emailMethod !== originalDoc?.emailMethod + const stored = isMailMethod(context?.iaplMailMethodStored) ? context.iaplMailMethodStored : null + if (sent && isMailMethod(data.emailMethod)) { + if (data.emailMethod === 'relay' && !mailRelay) { + throw new ValidationError({ errors: [{ message: 'This sending method is switched off for this site.', path: 'emailMethod' }], global: 'site-integrations' }, req.t) + } + if (shownMailMethod({ ...(originalDoc ?? {}), emailMethod: stored } as never, mailRelay) !== data.emailMethod) {data.emailStatus = cleared} + // the stored field of 1.6 – 1.17.0 follows where it can say it data.emailTransport = data.emailMethod === 'graph' ? 'graph' : 'smtp' + } else if (sent && data.emailMethod !== null && data.emailMethod !== undefined) { + // not a method: left as it is — the field's own validation refuses it + } else if (sent) { + data.emailMethod = null // un-chosen on purpose (`setMailMethod(payload, null)`): the order of 1.17.0 again } else if ((noted ? noted.transport : true) && changed('emailTransport')) { // written the old way (a script from before 1.17.1): it means what it meant — the order of 1.17.0 - context.iaplMailMethod = null + data.emailMethod = null + } else { + data.emailMethod = stored } if (changed('turnstileSecretKey') || changed('turnstileSiteKey')) {data.turnstileStatus = cleared} if (Object.keys(data).some((k) => (k === 'emailTransport' || k.startsWith('smtp')) && changed(k))) { @@ -141,7 +133,7 @@ export function buildSiteIntegrations({ ({ args, context, operation }) => { const data = (args as { data?: Record } | undefined)?.data if (operation === 'update' && data && typeof data === 'object' && context) { - context.iaplMailSent = { method: data.emailMethod ?? undefined, transport: 'emailTransport' in data } + context.iaplMailSent = { sent: 'emailMethod' in data, transport: 'emailTransport' in data } } return args }, diff --git a/src/index.ts b/src/index.ts index 3398f48..ee55d28 100644 --- a/src/index.ts +++ b/src/index.ts @@ -253,8 +253,8 @@ export { graphAdapter } from './modules/email/graphAdapter.js' export type { GraphAdapterArgs } from './modules/email/graphAdapter.js' export { GRAPH_DEPRECATION_NOTICE, mailAdapter, resolveMailMethod, resolveMailTransport } from './modules/email/mailAdapter.js' export type { MailAdapterArgs, MailMethodProblem, MailTransport, ResolvedMailMethod } from './modules/email/mailAdapter.js' -// "Sending method": the choice an admin saved (kept in payload-kv, so no SQL schema changes). -export { getMailMethod, isMailMethod, MAIL_METHOD_KV_KEY, MAIL_METHODS, setMailMethod } from './modules/email/method.js' +// "Sending method": the choice an admin saved (the stored field `emailMethod`, new in 1.17.1). +export { getMailMethod, isMailMethod, MAIL_METHODS, readMailSettings, setMailMethod, STORED_MAIL_METHOD_CONTEXT } from './modules/email/method.js' export type { MailMethod } from './modules/email/method.js' // Imported straight from the file, NOT from ./modules/email/index.js — that // barrel re-exports sendEmail, which imports 'server-only' and would crash when @@ -426,6 +426,7 @@ export { getNotificationTexts, NOTIFICATION_FALLBACK, NOTIFICATION_FALLBACK_PL, export type { FormNotificationTexts, NotificationTexts } from './modules/notifications/index.js' export type { PagesOption, SystemPageRole } from './modules/pages/index.js' export { ALL_SYSTEM_PAGE_ROLES, getSystemPagePath, unlistedPageIds } from './modules/pages/index.js' +export { mailMethodColumnMissing } from './modules/payload/getSiteIntegrations.js' export type { GlobalQueryOptions } from './modules/payload/index.js' export { getGlobal, diff --git a/src/modules/doctor/rules/mail.ts b/src/modules/doctor/rules/mail.ts index c8f0660..579b4b3 100644 --- a/src/modules/doctor/rules/mail.ts +++ b/src/modules/doctor/rules/mail.ts @@ -59,6 +59,9 @@ export const mailRules: DoctorRule[] = [ check: (ctx) => { const mail = ctx.deep?.mail if (!mail) {return []} + if (mail.methodColumnMissing) { + return [{ fix: 'create and apply the migration: `pnpm payload migrate:create`, commit it, and have it applied when the new container starts (docs/email.md "Which transport a send takes" → Postgres and SQLite)', message: 'the database has no column for "Sending method" (`emailMethod`, new in 1.17.1): e-mails still go the way they did before the upgrade, but the Site integrations page of the panel does not open and the method cannot be chosen', severity: 'error' }] + } if (mail.methodProblem === 'smtp-incomplete') { return [{ fix: 'Site integrations → E-mail sending: fill in server, user name and password — or choose another sending method', message: '"Own SMTP server" is the chosen sending method, but its settings are incomplete: e-mails are not sent (nothing is sent another way)', severity: 'error' }] } diff --git a/src/modules/doctor/status.ts b/src/modules/doctor/status.ts index 43bdb84..e70e5b6 100644 --- a/src/modules/doctor/status.ts +++ b/src/modules/doctor/status.ts @@ -74,6 +74,7 @@ export async function collectDoctorStatus(payload: BasePayload): Promise resolveRelayOptions(payload, args.relay) - const methodOf = async (settings: TransportIntegrations) => resolveMailMethod(settings, { chosen: await getMailMethod(payload), graphEnv: graphAvailable(), relay: Boolean(relayOptions()) }) + const methodOf = (settings: TransportIntegrations) => resolveMailMethod(settings, { chosen: isMailMethod(settings.emailMethod) ? settings.emailMethod : null, graphEnv: graphAvailable(), relay: Boolean(relayOptions()) }) const attachmentLimit = async (): Promise => { - const settings = await getSiteIntegrations(payload) - const transport = (await methodOf(settings)).method + const settings = await readMailSettings(payload) + const transport = methodOf(settings).method // The service says what it carries for this site (10 MB unless Intecion set another number). if (transport === 'relay') {return relayAttachmentLimit(payload, relayOptions()!).catch(() => null)} if (transport !== 'graph') {return null} @@ -192,10 +193,10 @@ export const mailAdapter = } async function send(message: SendEmailOptions): Promise { - const settings = await getSiteIntegrations(payload) + const settings = await readMailSettings(payload) const choice = settings.emailTransport ?? 'smtp' const previous = settings[STATUS_FIELD] - const resolved = await methodOf(settings) + const resolved = methodOf(settings) const chosen = resolved.method // No SMTP server in the panel and no Graph: the Intecion Notifications Webservice. diff --git a/src/modules/email/method.ts b/src/modules/email/method.ts index baf40bf..daa1e62 100644 --- a/src/modules/email/method.ts +++ b/src/modules/email/method.ts @@ -1,49 +1,48 @@ import type { BasePayload } from 'payload' +import { findSiteIntegrations, MAIL_METHOD_FIELD, SITE_INTEGRATIONS_SLUG } from '../payload/getSiteIntegrations.js' + /** * The sending method an admin chose in Site integrations → E-mail sending ("Sending method"): * the built-in service (IWSN), the client's own SMTP server, or Microsoft Graph (deprecated). * - * Where it is stored: in Payload's key-value store (`payload-kv`), under `MAIL_METHOD_KV_KEY` — not in - * a column of the global. The global's stored field `emailTransport` has two values since 1.6 (`smtp`, - * `graph`); a third would change the Postgres enum and ask every SQL project for a migration, and it - * still could not tell "SMTP was chosen" from the `smtp` that every site has stored since before the - * choice existed. So the panel's field (`emailMethod`) is virtual, and the choice lives here. + * Stored in the global's field `emailMethod` (a select, new in 1.17.1; Postgres / SQLite: one migration). + * Empty = nobody has chosen yet (a site upgraded from 1.17.0 or older, a new site): the method follows the + * order of 1.17.0 (`resolveMailTransport`) and the panel shows it as selected. The first save of the panel's + * form — or `setMailMethod()` — stores the choice; from then on what is chosen is what is used. * - * No entry = nobody has chosen yet (a site upgraded from 1.17.0 or older, a new site): the method follows - * the order of 1.17.0 (`resolveMailTransport`) and the panel shows it as selected. The first save of Site - * integrations — or `setMailMethod()` — writes the choice; from then on what is chosen is what is used. + * Why a field of its own and not a third value in `emailTransport` (`smtp` / `graph`, stored since 1.6): + * every site has `smtp` stored there from before there was a choice, so "SMTP was chosen" could not be told + * from "nothing was chosen" — and an upgrade must keep a site with no SMTP server on the service. */ export type MailMethod = 'graph' | 'relay' | 'smtp' export const MAIL_METHODS: readonly MailMethod[] = ['relay', 'smtp', 'graph'] -export const MAIL_METHOD_KV_KEY = 'iapl:mail-method' +/** + * A read with this key in its `context` gets `emailMethod` as stored (empty when nobody chose) — not the + * method the panel shows as selected. + */ +export const STORED_MAIL_METHOD_CONTEXT = 'iaplStoredMailMethod' export const isMailMethod = (value: unknown): value is MailMethod => typeof value === 'string' && (MAIL_METHODS as readonly string[]).includes(value) -type Kv = { delete?: (key: string) => Promise; get?: (key: string) => Promise; set?: (key: string, value: object) => Promise } -const kvOf = (payload: Pick): Kv => ((payload as { kv?: Kv }).kv ?? {}) +/** Site integrations with `emailMethod` as stored — what the mail adapter and the state block decide from. */ +export function readMailSettings>(payload: BasePayload): Promise { + return findSiteIntegrations(payload, { context: { [STORED_MAIL_METHOD_CONTEXT]: true } }) +} /** The chosen method, or null when nobody has chosen yet. Reads only. */ -export async function getMailMethod(payload: Pick): Promise { - const kv = kvOf(payload) - if (typeof kv.get !== 'function') {return null} - const stored = (await kv.get(MAIL_METHOD_KV_KEY)) as { method?: unknown } | null - return isMailMethod(stored?.method) ? stored.method : null +export async function getMailMethod(payload: BasePayload): Promise { + const stored = (await readMailSettings>(payload))[MAIL_METHOD_FIELD] + return isMailMethod(stored) ? stored : null } /** * Chooses the method (a seed, a deploy script; the panel does it on save). `null` = nobody has chosen: * the order of 1.17.0 applies again. */ -export async function setMailMethod(payload: Pick, method: MailMethod | null): Promise { - const kv = kvOf(payload) - if (method === null) { - await kv.delete?.(MAIL_METHOD_KV_KEY) - return - } - if (!isMailMethod(method)) {throw new Error(`[iapl] setMailMethod: "${String(method)}" is not a sending method (relay, smtp, graph).`)} - if (typeof kv.set !== 'function') {throw new Error('[iapl] setMailMethod: this Payload has no key-value store (payload.kv).')} - await kv.set(MAIL_METHOD_KV_KEY, { at: new Date().toISOString(), method }) +export async function setMailMethod(payload: BasePayload, method: MailMethod | null): Promise { + if (method !== null && !isMailMethod(method)) {throw new Error(`[iapl] setMailMethod: "${String(method)}" is not a sending method (relay, smtp, graph).`)} + await payload.updateGlobal({ slug: SITE_INTEGRATIONS_SLUG as never, data: { [MAIL_METHOD_FIELD]: method } as never, overrideAccess: true }) } diff --git a/src/modules/email/relay/panel.ts b/src/modules/email/relay/panel.ts index 025e816..3080a8b 100644 --- a/src/modules/email/relay/panel.ts +++ b/src/modules/email/relay/panel.ts @@ -5,9 +5,9 @@ import type { RelayOptions } from './options.js' import { userMeetsRole } from '../../access/predicates.js' import { serverText } from '../../integrations/texts.js' -import { getSiteIntegrations } from '../../payload/index.js' +import { mailMethodColumnMissing } from '../../payload/getSiteIntegrations.js' import { graphAvailable, type MailMethodProblem, type MailTransport, resolveMailMethod, smtpIncomplete } from '../mailAdapter.js' -import { getMailMethod } from '../method.js' +import { isMailMethod, readMailSettings } from '../method.js' 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' @@ -16,6 +16,7 @@ import { disconnectRelay, enrolRelay, type EnrolResult, getRelayStatus, LOCAL_CO import { otherRelayHosts } from './store.js' type Settings = { + emailMethod?: null | string emailStatus?: IntegrationStatus | null emailTransport?: 'graph' | 'smtp' | null smtpFromAddress?: null | string @@ -35,6 +36,8 @@ export type MailPanelState = { * method follows the order of 1.17.0 until Site integrations is saved. */ methodChosen: boolean + /** Postgres / SQLite: the column of "Sending method" is missing (the 1.17.1 migration has not run); the order of 1.17.0 applies. */ + methodColumnMissing?: boolean /** The chosen method cannot be used; e-mails are NOT sent another way. */ methodProblem?: MailMethodProblem /** The site is not public: its host is a development address (`developmentHosts`), or `IAPL_NOINDEX` is set. */ @@ -66,9 +69,9 @@ function refuse(req: PayloadRequest): null | Response { /** The transport in effect and the site's state with the service, for the panel and the doctor. */ export async function mailPanelState(req: Pick, own: false | RelayOptions | undefined, { refresh = false }: { refresh?: boolean } = {}): Promise { const { payload } = req - const settings = await getSiteIntegrations(payload) + const settings = await readMailSettings(payload) const options = resolveRelayOptions(payload, own) - const method = resolveMailMethod(settings, { chosen: await getMailMethod(payload), graphEnv: graphAvailable(), relay: Boolean(options) }) + const method = resolveMailMethod(settings, { chosen: isMailMethod(settings.emailMethod) ? settings.emailMethod : null, graphEnv: graphAvailable(), relay: Boolean(options) }) const transport = method.method let status = options ? await getRelayStatus(payload, options, { refresh: refresh && transport === 'relay' }) : null // A site the service could never call back (it runs locally, or does not know its address) is refused by the @@ -98,6 +101,7 @@ export async function mailPanelState(req: Pick, own: ...(options?.accessKeyField === true ? { accessKeyField: true } : {}), ...(status?.host ? { confirmUrl: `https://${status.host}${api}${RELAY_CONFIRM_PATH}` } : {}), methodChosen: method.explicit, + ...(mailMethodColumnMissing() ? { methodColumnMissing: true } : {}), ...(method.problem ? { methodProblem: method.problem } : {}), relay: status ? { ...status, senderAddress: status.senderAddress ?? RELAY_SENDER_ADDRESS } : null, replyAddress: typeof settings.smtpFromAddress === 'string' && settings.smtpFromAddress.trim() ? settings.smtpFromAddress.trim() : null, diff --git a/src/modules/payload/getSiteIntegrations.ts b/src/modules/payload/getSiteIntegrations.ts index c78ceb3..09bdee3 100644 --- a/src/modules/payload/getSiteIntegrations.ts +++ b/src/modules/payload/getSiteIntegrations.ts @@ -2,11 +2,85 @@ import type { BasePayload } from 'payload' import type { GlobalQueryOptions } from './getGlobal.js' -import { getGlobal } from './getGlobal.js' - /** Slug of the SiteIntegrations global defined by the plugin. */ export const SITE_INTEGRATIONS_SLUG = 'site-integrations' +/** The stored field added in 1.17.1 ("Sending method"). On Postgres / SQLite it needs a migration (a column). */ +export const MAIL_METHOD_FIELD = 'emailMethod' + +let methodColumnMissing = false +let warned = false +let probedAt = 0 +/** While the column is missing, the full read is tried again this often — the migration may have run meanwhile. */ +const PROBE_EVERY_MS = 60_000 + +/** + * True once a read of Site integrations found that the database has no column for `emailMethod`: a Postgres / + * SQLite project upgraded to 1.17.1 whose migration has not run. The site keeps working by reading the global + * without that field (the sending method then follows the order of 1.17.0); the panel page of Site integrations + * and writes to the global fail until the migration runs. `iapl-doctor --deep` reports it (`mail-method`). + */ +export const mailMethodColumnMissing = (): boolean => methodColumnMissing + +/** For tests. */ +export function resetMailMethodColumnMissing(): void { + methodColumnMissing = false + warned = false + probedAt = 0 +} + +const chain = (err: unknown): string => { + const parts: string[] = [] + for (let current: unknown = err, depth = 0; current && depth < 6; current = (current as { cause?: unknown }).cause, depth++) { + const message = (current as { message?: unknown }).message + if (typeof message === 'string') {parts.push(message)} + } + return parts.join(' — ') +} +/** The database says the column of `emailMethod` is not there (Postgres, SQLite; Drizzle keeps its words in `cause`). */ +const isMissingMethodColumn = (err: unknown): boolean => { + const text = chain(err) + return /email_method/i.test(text) && /does not exist|no such column|unknown column|has no column/i.test(text) +} + +/** + * Reads Site integrations (Local API, access control bypassed). `context` reaches the fields' hooks. + * Without the column of `emailMethod` the read is repeated without that field, so that e-mail, Turnstile and + * analytics keep working on a SQL project whose migration has not run yet; one loud line says what to do. + */ +export async function findSiteIntegrations>( + payload: BasePayload, + options: { context?: Record } & GlobalQueryOptions = {}, +): Promise { + const args = { + slug: SITE_INTEGRATIONS_SLUG, + ...(options.locale ? { locale: options.locale as never } : {}), + ...(typeof options.depth === 'number' ? { depth: options.depth } : {}), + ...(options.context ? { context: options.context } : {}), + } + if (!methodColumnMissing || Date.now() - probedAt > PROBE_EVERY_MS) { + probedAt = Date.now() + try { + const found = (await payload.findGlobal(args as never)) as T + methodColumnMissing = false + return found + } catch (err) { + if (!isMissingMethodColumn(err)) {throw err} + methodColumnMissing = true + if (!warned) { + warned = true + payload.logger.error( + `[iapl] Site integrations: the column for "${MAIL_METHOD_FIELD}" ("Sending method", new in 1.17.1) is missing in the database (${chain(err)}). ` + + 'The site keeps working — e-mails go the way they did before the upgrade — but the Site integrations page of the panel does not open and the sending method cannot be chosen ' + + 'until the migration that adds the column has run: `pnpm payload migrate:create`, commit the migration, and have it applied when the new container starts ' + + '(docs/email.md "Which transport a send takes" → Postgres and SQLite; docs/deployment.md §4.3).', + ) + } + } + } + return (await payload.findGlobal({ ...args, select: { [MAIL_METHOD_FIELD]: false } } as never)) as T +} + /** * Fetches the SiteIntegrations global. * @@ -27,5 +101,5 @@ export function getSiteIntegrations>( payload: BasePayload, options?: GlobalQueryOptions, ): Promise { - return getGlobal(payload, SITE_INTEGRATIONS_SLUG, options) + return findSiteIntegrations(payload, options) } diff --git a/test/doctor.test.ts b/test/doctor.test.ts index c2ff880..9ab0496 100644 --- a/test/doctor.test.ts +++ b/test/doctor.test.ts @@ -754,6 +754,11 @@ describe('e-mail: transport, the mail service, Graph, the confirm route', () => expect(open[0].message).toContain('the built-in service') expect(open[0].fix).toContain('save') expect(await find({ methodChosen: true })).toEqual([]) + // Postgres / SQLite whose 1.17.1 migration has not run + const column = await find({ methodChosen: false, methodColumnMissing: true }) + expect(column.map((f) => f.severity)).toEqual(['error']) + expect(column[0].message).toContain('no column for "Sending method"') + expect(column[0].fix).toContain('migrate:create') expect(await find({ methodChosen: false, relay: null, transport: 'none' })).toEqual([]) // that is mail-transport's error }) diff --git a/test/mailMethodColumnMissing.test.ts b/test/mailMethodColumnMissing.test.ts new file mode 100644 index 0000000..f2931c9 --- /dev/null +++ b/test/mailMethodColumnMissing.test.ts @@ -0,0 +1,98 @@ +/** + * Postgres / SQLite upgraded to 1.17.1 WITHOUT the migration that adds the column of "Sending method" + * (`emailMethod`), against the real adapter: the site must keep working — e-mail the way it went before, the + * other integrations readable — say loudly what to do, and pick the choice up once the column exists. + * SQLite in memory by default; `IPAL_TEST_POSTGRES_URI` runs it on Postgres. Not for MongoDB (no columns). + */ +import type { Payload } from 'payload' + +import { lexicalEditor } from '@payloadcms/richtext-lexical' +import os from 'os' +import path from 'path' +import { getPayload } from 'payload' +import { afterAll, beforeAll, expect, test, vi } from 'vitest' + +import { mailAdapter } from '../src/modules/email/mailAdapter.js' +import { getMailMethod, setMailMethod } from '../src/modules/email/method.js' +import { createFakeRelay } from '../src/modules/email/relay/fake.js' +import { mailPanelState } from '../src/modules/email/relay/panel.js' +import { getSiteIntegrations, mailMethodColumnMissing, resetMailMethodColumnMissing } from '../src/modules/payload/getSiteIntegrations.js' +import { iapl } from '../src/plugin.js' +import { buildTestConfig } from './helpers.js' +import { testDatabase } from './http/db.js' +import { startPayloadServer, type TestServer } from './http/server.js' + +vi.mock('server-only', () => ({})) +vi.mock('next/headers.js', async () => (await import('./http/server.js')).nextHeadersMock) + +const sql = !process.env.IPAL_TEST_MONGO_URI +const HOST = 'example.com' +let payload: Payload +let server: TestServer +const fake = createFakeRelay({ allow: [HOST], callSite: async (url, init) => fetch(`${server.url}${new URL(url).pathname}`, { ...init, redirect: 'manual' }) }) + +beforeAll(async () => { + if (!sql) {return} + const config = buildTestConfig({ + admin: { user: 'users' }, + collections: [{ slug: 'media', fields: [], upload: { staticDir: path.join(os.tmpdir(), 'iapl-method-column-media') } }], + db: testDatabase('methodcol'), + editor: lexicalEditor(), + email: mailAdapter(), + plugins: [iapl({ access: { authCollection: 'users' }, i18n: { defaultLocale: 'en', locales: [{ code: 'en', label: 'English' }] }, mail: { relay: { fetchImpl: fake.fetch, url: fake.url } }, twoFactor: false })], + secret: 'integration-test-secret-0123456789', + serverURL: `https://${HOST}`, + telemetry: false, + }) + payload = await getPayload({ config }) + server = await startPayloadServer(config) +}, 120_000) + +afterAll(async () => { + await server?.close() + await payload?.destroy?.() + resetMailMethodColumnMissing() +}) + +test.skipIf(!sql)('without the column: one loud line, mail and the other settings keep working by the order of 1.17.0; with it: the choice works', async () => { + // the site as 1.17.0 left it: a row with settings, sending through the service + await payload.updateGlobal({ slug: 'site-integrations' as never, data: { ga4MeasurementId: 'G-BEFORE1', smtpFromName: 'Kancelaria Example' } as never }) + const db = payload.db as unknown as { client?: { execute: (q: string) => Promise }; pool?: { query: (q: string) => Promise }; schemaName?: string } + const run = (statement: string) => (db.pool ? db.pool.query(statement) : db.client!.execute(statement)) + const table = db.pool && db.schemaName ? `"${db.schemaName}"."site_integrations"` : '"site_integrations"' + await run(`ALTER TABLE ${table} DROP COLUMN "email_method"`) + resetMailMethodColumnMissing() + + const error = vi.spyOn(payload.logger, 'error').mockImplementation(() => undefined as never) + // Payload's own read of the global fails — that is the panel page … + await expect(payload.findGlobal({ slug: 'site-integrations' as never })).rejects.toThrow() + // … the plugin's readers do not: analytics and Turnstile settings are there + expect(await getSiteIntegrations<{ ga4MeasurementId?: string }>(payload)).toMatchObject({ ga4MeasurementId: 'G-BEFORE1' }) + expect(mailMethodColumnMissing()).toBe(true) + expect(error).toHaveBeenCalledTimes(1) + expect(String(error.mock.calls[0]?.[0])).toMatch(/the column for "emailMethod".*is missing.*keeps working.*migrate:create/s) + // e-mail leaves the way it did before the upgrade (no SMTP server: the service), and says nothing more + expect(await getMailMethod(payload)).toBeNull() + expect(await mailPanelState({ payload }, undefined)).toMatchObject({ methodChosen: false, methodColumnMissing: true, transport: 'relay' }) + expect(await payload.sendEmail({ html: '

Hello.

', subject: 'Before the migration', to: 'office@example.org' })).toMatchObject({ transport: 'relay' }) + expect(fake.outbox.at(-1)).toMatchObject({ subject: 'Before the migration' }) + await getSiteIntegrations(payload) + expect(error).toHaveBeenCalledTimes(1) // once, not on every read + // the method cannot be chosen yet + await expect(setMailMethod(payload, 'smtp')).rejects.toThrow() + + // the migration: the column is there → reads are whole again, the choice is stored and used + await run(`ALTER TABLE ${table} ADD COLUMN "email_method" ${db.pool && db.schemaName ? `"${db.schemaName}"."enum_site_integrations_email_method"` : 'text'}`) + resetMailMethodColumnMissing() // (a running process looks again within a minute; a deploy restarts it anyway) + expect((await getSiteIntegrations<{ emailMethod?: string }>(payload)).emailMethod).toBe('relay') // shown as selected + expect(mailMethodColumnMissing()).toBe(false) + expect(await getMailMethod(payload)).toBeNull() + await setMailMethod(payload, 'smtp') + expect(await getMailMethod(payload)).toBe('smtp') + expect(await mailPanelState({ payload }, undefined)).toMatchObject({ methodChosen: true, methodProblem: 'smtp-incomplete', transport: 'smtp' }) + expect((await mailPanelState({ payload }, undefined)).methodColumnMissing).toBeUndefined() + const before = fake.requests.length + expect(await payload.sendEmail({ html: '

Hello.

', subject: 'After', to: 'office@example.org' })).toMatchObject({ code: 'not-configured', sent: false }) + expect(fake.requests).toHaveLength(before) + error.mockRestore() +}) diff --git a/test/mailMethodHttp.test.ts b/test/mailMethodHttp.test.ts index 2e8467d..0ab48e7 100644 --- a/test/mailMethodHttp.test.ts +++ b/test/mailMethodHttp.test.ts @@ -5,7 +5,8 @@ * keeps sending; nothing is written by reading; * - the first save of the panel's form stores the choice; from then on what is chosen is what is used — * an unusable choice fails loudly and nothing leaves another way; - * - no stored field was added: the panel's field is virtual, the choice is in the key-value store. + * - the choice is the stored field `emailMethod`, empty until somebody chooses (Postgres / SQLite: a column — + * test/mailMethodColumnMissing.test.ts is the site whose migration has not run). */ import type { Payload } from 'payload' @@ -16,7 +17,7 @@ import { getPayload } from 'payload' import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, test, vi } from 'vitest' import { mailAdapter, resolveMailMethod, resolveMailTransport } from '../src/modules/email/mailAdapter.js' -import { getMailMethod, MAIL_METHOD_KV_KEY, setMailMethod } from '../src/modules/email/method.js' +import { getMailMethod, setMailMethod } from '../src/modules/email/method.js' import { createFakeRelay } from '../src/modules/email/relay/fake.js' import { mailPanelState } from '../src/modules/email/relay/panel.js' import { SECRET_CLEAR } from '../src/modules/secrets/writeOnly.js' @@ -69,8 +70,7 @@ const saveForm = async (change: Record = {}) => { } /** A site as an older version left it: the stored fields only, nothing chosen. */ const asStored = async (data: Record) => { - await payload.updateGlobal({ slug: 'site-integrations' as never, data: { emailStatus: { checkedAt: null, code: null, message: null, since: null, state: null }, emailTransport: 'smtp', ...NO_SMTP, ...data } as never }) - await payload.kv.delete(MAIL_METHOD_KV_KEY) + await payload.updateGlobal({ slug: 'site-integrations' as never, data: { emailMethod: null, emailStatus: { checkedAt: null, code: null, message: null, since: null, state: null }, emailTransport: 'smtp', ...NO_SMTP, ...data } as never }) } const state = () => mailPanelState({ payload }, undefined) const send = () => payload.sendEmail(MESSAGE) as Promise<{ code?: string; sent?: boolean; transport?: string }> @@ -108,7 +108,6 @@ describe('upgrade, with no edit: the site shows the method it sends through toda // the stored field is what it was, and nothing was chosen on the site's behalf expect((await read()).emailTransport).toBe('smtp') expect(await getMailMethod(payload)).toBeNull() - expect(await payload.kv.get(MAIL_METHOD_KV_KEY)).toBeNull() }) test('a site with its SMTP server filled in: "Own SMTP server" is selected, the service is not contacted', async () => { @@ -147,7 +146,6 @@ describe('upgrade, with no edit: the site shows the method it sends through toda }) test('a new site (nothing ever saved): "IWSN" is selected', async () => { - await payload.kv.delete(MAIL_METHOD_KV_KEY) await asStored({}) expect((await read()).emailMethod).toBe('relay') }) @@ -241,9 +239,15 @@ describe('the choice: what is chosen is what is used', () => { expect(await getMailMethod(payload)).toBeNull() }) - test('only an admin reaches the choice; it is not in the key-value store\'s REST', async () => { + test('only an admin reaches the choice; a save that only records the sending status does not store one', async () => { + await asStored({}) expect((await fetch(`${server.url}/api/globals/site-integrations`, { body: JSON.stringify({ emailMethod: 'smtp' }), headers: { 'content-type': 'application/json' }, method: 'POST' })).status).toBeGreaterThanOrEqual(401) - expect((await api('/payload-kv')).status).toBeGreaterThanOrEqual(400) + // the plugin's own writes (the status after a send) and a partial save carry the method the read SHOWED — it must not become a choice + await send() + await payload.updateGlobal({ slug: 'site-integrations' as never, data: { smtpFromName: 'Kancelaria Example' } as never }) + expect((await api('/globals/site-integrations', { body: JSON.stringify({ ga4MeasurementId: 'G-TEST456' }), method: 'POST' })).status).toBe(200) + expect(await getMailMethod(payload)).toBeNull() + expect((await read()).emailMethod).toBe('relay') }) }) @@ -277,23 +281,20 @@ describe('resolveMailMethod', () => { }) }) -describe('no stored field was added', () => { - test('`emailMethod` is virtual: the SQL table has no column for it; the document in the database does not hold it', async () => { +describe('where the choice is stored', () => { + test('in the global\'s own field: empty until somebody chooses, then the method; the three values are the same with the service on and off', async () => { await asStored({}) - await saveForm({ emailMethod: 'smtp' }) - const db = payload.db as unknown as { collections?: unknown; connection?: { collection: (n: string) => { findOne: (q: object) => Promise> } }; name?: string; tables?: Record> } - if (db.tables) { - const table = db.tables.site_integrations - expect(table).toBeTruthy() - const columns = Object.keys(table).map((c) => c.toLowerCase()) - expect(columns).toContain('emailtransport') - expect(columns.filter((c) => c.includes('method'))).toEqual([]) - } else { - const raw = await db.connection!.collection('globals').findOne({ globalType: 'site-integrations' }) - expect(raw).toMatchObject({ emailTransport: 'smtp' }) - expect(raw).not.toHaveProperty('emailMethod') + const db = payload.db as unknown as { connection?: { collection: (n: string) => { findOne: (q: object) => Promise> } }; tables?: Record> } + const raw = async (): Promise => { + if (db.tables) {return ((await payload.findGlobal({ slug: 'site-integrations' as never, context: { iaplStoredMailMethod: true }, depth: 0 })) as unknown as { emailMethod?: unknown }).emailMethod ?? null} + return (await db.connection!.collection('globals').findOne({ globalType: 'site-integrations' }))?.emailMethod ?? null } + expect(await raw()).toBeNull() + await saveForm({ emailMethod: 'smtp' }) + expect(await raw()).toBe('smtp') + if (db.tables) {expect(Object.keys(db.tables.site_integrations).map((c) => c.toLowerCase())).toEqual(expect.arrayContaining(['emailtransport', 'emailmethod']))} await setMailMethod(payload, null) + expect(await raw()).toBeNull() }) test('`mail: { relay: false }`: the option "IWSN" is not offered, and a stored choice of it counts as none', async () => { @@ -302,6 +303,8 @@ describe('no stored field was added', () => { return [...field.matchAll(/"value":"(\w+)"/g)].map((m) => m[1]) } expect(methods(await makeConfig(undefined, 'methodson'))).toEqual(['relay', 'smtp', 'graph']) - expect(methods(await makeConfig({ relay: false }, 'methodsoff'))).toEqual(['smtp', 'graph']) + // the stored values are the same (one SQL enum for every project); the option is not offered and not accepted + expect(methods(await makeConfig({ relay: false }, 'methodsoff'))).toEqual(['relay', 'smtp', 'graph']) + expect(JSON.stringify((await makeConfig({ relay: false }, 'methodsoff2')).globals?.find((g) => g.slug === 'site-integrations')?.fields ?? '')).not.toBe('') }) }) diff --git a/test/mailRelayHttp.test.ts b/test/mailRelayHttp.test.ts index da90c41..dbf4888 100644 --- a/test/mailRelayHttp.test.ts +++ b/test/mailRelayHttp.test.ts @@ -313,8 +313,7 @@ describe('switched off, and what did not change', () => { const endpoints = (config: SanitizedConfig) => (config.endpoints ?? []).map((e) => `${e.method} ${e.path}`) const stored = (fields: Field[]): string[] => fields.flatMap((f) => { - // (a virtual field has no column and no stored value: "Sending method", whose choice is in the key-value store) - if (f.type === 'ui' || ('virtual' in f && f.virtual)) {return []} + if (f.type === 'ui') {return []} if (f.type === 'tabs') {return f.tabs.flatMap((t) => stored(t.fields))} const own = 'name' in f && f.name ? [`${f.name}:${f.type}${f.type === 'select' ? `(${(f.options as { value: string }[]).map((o) => (typeof o === 'string' ? o : o.value)).join('|')})` : ''}`] : [] return 'fields' in f && Array.isArray(f.fields) ? [...own, ...stored(f.fields).map((n) => ('name' in f && f.name ? `${f.name}.${n}` : n))] : own @@ -341,6 +340,8 @@ describe('switched off, and what did not change', () => { const on = names(await makeConfig(undefined, 'fieldson')) expect(on).toEqual(names(await makeConfig({ relay: false }, 'fieldsoff'))) expect(on).toEqual([ + // new in 1.17.1 (Postgres / SQLite: one migration); the same three values with the service on and off + 'emailMethod:select(relay|smtp|graph)', 'emailTransport:select(smtp|graph)', 'smtpFromAddress:email', 'smtpFromName:text',