Merge claude/mail-transport-choice: "Sending method" is an explicit choice in the panel (IWSN, own SMTP, Graph); nothing changes until another option is picked
Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
+33
-2
@@ -9,9 +9,10 @@ versions at once, go through every "Requires project changes" section in order,
|
||||
version you have. A new release = a new section at the top; we remove the oldest ones only
|
||||
once there are more than 20.
|
||||
|
||||
## 1.17.1 — security fixes from the IAWL review; the panel's sign-in look
|
||||
## 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
|
||||
@@ -46,6 +47,21 @@ once there are more than 20.
|
||||
> **4. One line in each project:** the proxy matcher (`src/proxy.ts`) —
|
||||
> `'/((?!(?:api|admin|_next)(?:/|$)|.*\\..*).*)'`; `iapl-doctor` warns `proxy-matcher` until it is changed. Without it
|
||||
> pages whose names only start with `api` / `admin` / `_next` skip the proxy, as before.
|
||||
>
|
||||
> **5. E-mail — nothing to do, one thing to know.** "Sending method" in Site integrations → E-mail sending is a
|
||||
> choice again: IWSN (built-in), Own SMTP server, Microsoft Graph (deprecated). **Upgrading writes nothing and
|
||||
> loses no mail:** the field shows the method the site sends through today as selected (no SMTP server → IWSN; an
|
||||
> SMTP server → Own SMTP server; `GRAPH_*` → Microsoft Graph), and the site keeps sending that way. **Nothing changes
|
||||
> until somebody picks another option:** saving the page with the method shown stores no choice. A different option
|
||||
> picked and saved is stored, and from then on the site sends that way only.** If the chosen method cannot
|
||||
> 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). The panel warns while the option is being picked, before the save.
|
||||
> **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
|
||||
@@ -134,6 +150,17 @@ once there are more than 20.
|
||||
the e-mail — every account may change its own e-mail (security.md).
|
||||
|
||||
### Changed
|
||||
- **E-mail: "Sending method" is an explicit choice again** — "IWSN (built-in)", "Own SMTP server", "Microsoft
|
||||
Graph (deprecated)" — and what is chosen is what is used (point 5 above). Only the chosen method's fields are
|
||||
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 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
|
||||
240 × 72 px (it was up to 420 × 120).
|
||||
@@ -145,6 +172,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
|
||||
|
||||
+22
-6
@@ -1257,7 +1257,7 @@ add missing hosts with flags / `extra`; (3) change `mode` to `'enforce'` in both
|
||||
| Sitemap split / CDN cache / memo | `sitemapOptions: { maxUrls: Infinity, cacheControl: false, memoSeconds: 0 }` | `sitemapEntries`, `createSitemapRouteHandler`, `buildSitemapIndexXml`, `buildSitemapEntries` |
|
||||
| Sitemap error = 503 + `Retry-After` | — (correct HTTP behaviour) | your own route with `buildSitemapXml` |
|
||||
| IndexNow silent with `IAPL_NOINDEX` | `indexNow` off by default | `submitToIndexNow` by hand |
|
||||
| A site with no SMTP server in the panel sends through the Intecion mail service: it enrols by itself on its first send (an outbound call with its host and the plugin version) and gets its own token through the public route `POST /api/iapl/mail-relay/confirm` | `mail: { relay: false }` (no call, no routes, no state block) | `mail.relay: { url, host, enrol, token, senderName, kind, accountMail, confirmRateLimit, timeoutMs, retryBackoffMs, fetchImpl }`; `mailAdapter({ relay })`; §7.2 |
|
||||
| A site sends through the Intecion mail service unless an admin chose another "Sending method" (SMTP, Graph): it enrols by itself on its first send (an outbound call with its host and the plugin version) and gets its own token through the public route `POST /api/iapl/mail-relay/confirm` | `mail: { relay: false }` (no call, no routes, no state block) | `mail.relay: { url, host, enrol, token, senderName, kind, accountMail, confirmRateLimit, timeoutMs, retryBackoffMs, fetchImpl }`; `mailAdapter({ relay })`; §7.2 |
|
||||
| The mail service's token is kept in `payload.kv` (never in a field, never readable over REST or GraphQL), bound to the site's server addresses, rotated every 90 days | "Disconnect" in the panel; `disconnectRelay` | `enrolRelay`, `rotateRelayToken`, `setRelayToken`, `getRelayStatus` |
|
||||
| Account e-mails through the mail service: at most 5 to one address and 10 asked for by one visitor an hour | `mail: { relay: { accountMail: false } }` | `accountMail: { perAddress, perVisitor, windowMinutes }` |
|
||||
| Every message says what it is (form notification, form confirmation, account, test, system) | — (other transports ignore the mark) | `withMailKind`, `runWithMailKind`, `expectMailTo`, `mail.relay.kind`, `buildFormMailKindHook` |
|
||||
@@ -1289,9 +1289,25 @@ No env variable, no key, no field to fill in, no import-map change (the tab's st
|
||||
banner that is already in every import map). **Do not** add `nodemailer`, `resend`, an `api/send` route or a
|
||||
`GRAPH_*` variable to a project.
|
||||
|
||||
**How a send is routed** (`resolveMailTransport`, type `MailTransport`): Microsoft Graph when the panel says so and
|
||||
`GRAPH_*` is set (deprecated) → SMTP when server, user name and password are filled in → Graph when `GRAPH_*` is set →
|
||||
the mail service → nothing (`mail: { relay: false }` and no SMTP). A site with SMTP filled in never contacts the service.
|
||||
**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 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. Saving with the method shown stores no choice: only picking another option does (the owner's
|
||||
rule: nothing changes until somebody picks another option); `setMailMethod` fixes it from code. The state block warns
|
||||
while an unusable option is picked, before the save. From code: `getMailMethod`,
|
||||
`setMailMethod(payload, 'relay' | 'smtp' | 'graph' | null)`, `resolveMailMethod` (`ResolvedMailMethod`,
|
||||
`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 `mail-method` info (nothing picked yet) or nothing (picked and usable). `mail: { relay: false }` removes the option "IWSN".
|
||||
|
||||
**What the site needs for the mail service** — check each one:
|
||||
|
||||
@@ -1324,8 +1340,8 @@ the mail service → nothing (`mail: { relay: false }` and no SMTP). A site with
|
||||
--deep --url <site>` reports no `mail-*` finding. On `localhost` the plugin refuses to enrol (nothing leaves the machine): test
|
||||
mail locally with SMTP (Mailpit) or `createFakeRelay()`.
|
||||
|
||||
**The client wants its own mail server:** fill in "Own SMTP server", user name, password and "Sender address" in the
|
||||
panel, send a test. Nothing in code. **A site on `GRAPH_*`:** keeps working, warns once per start; move it when the
|
||||
**The client wants its own mail server:** "Sending method" → "Own SMTP server", fill in server, user name, password
|
||||
and "Sender address", save, send a test. Nothing in code. **A site on `GRAPH_*`:** keeps working, warns once per start; move it when the
|
||||
owner says so (email.md "Moving off Microsoft Graph").
|
||||
|
||||
**Your own mail** goes through `payload.sendEmail`. Say what it is when it is not a generic system message:
|
||||
|
||||
@@ -1244,7 +1244,7 @@ const payload = await getPayload({ config })
|
||||
await payload.updateGlobal({
|
||||
slug: 'site-integrations',
|
||||
context: { ipalIntegrationStatus: true },
|
||||
data: { emailStatus: { checkedAt: null, code: null, message: null, since: null, state: null }, emailTransport: 'smtp', smtpFromAddress: 'site@example-studio.test', smtpFromName: 'Example Studio', smtpHost: null, smtpPassword: null, smtpUser: null } as never,
|
||||
data: { emailStatus: { checkedAt: null, code: null, message: null, since: null, state: null }, emailMethod: 'relay', emailTransport: 'smtp', smtpFromAddress: 'site@example-studio.test', smtpFromName: 'Example Studio', smtpHost: null, smtpPassword: null, smtpUser: null } as never,
|
||||
overrideAccess: true,
|
||||
})
|
||||
for (const key of await payload.kv.keys()) {
|
||||
|
||||
@@ -100,6 +100,9 @@ through this procedure. Ask only when you are missing something you cannot get y
|
||||
| pixel before consent (consent-check) | script wired by hand (`<Script>`) | only through the panel → `<Analytics>` (GA/GTM/pixels) or `<ConsentScript>` (analytics.md, consent.md) |
|
||||
| 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 | nothing, if that is wanted (the owner's rule: no change until another option is picked); to fix it: pick the method (another option, then this one) or `setMailMethod(payload, '<method>')` |
|
||||
| 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://<host>/api/iapl/mail-relay/confirm -d '{}' -H 'content-type: application/json'` must answer **404 with an empty body, no redirect**; fix `serverURL` / `mail.relay.host`, or ask Intecion to set the site's confirm address (path ending in `/confirm/` with trailing slashes); then "Connect again" (the site does not retry by itself for 15 min). email.md "When the site cannot be confirmed" |
|
||||
| `relay-refused`, cause `host-not-allowed` / "This site has no public address yet" | the site runs on `localhost`, a private name, or `serverURL` is empty | expected in development (use SMTP / Mailpit there); in production set `serverURL` |
|
||||
|
||||
@@ -39,6 +39,7 @@ description: Complete map of everything @intecion/ipal-kit provides — every ia
|
||||
| `accounts.firstUserRoute` | `'panel'` | which auth collections `POST /api/<slug>/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`; `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)/<route>/` itself and adds the route to the proxy matcher (security.md) |
|
||||
|
||||
@@ -660,8 +660,8 @@ scaling (5). `●` routes for pages need the database at build time (PROGRAMISTA
|
||||
in every language.
|
||||
6. **Notifications**: form messages in every language.
|
||||
7. **Site integrations → E-mail sending**: "Sender name" (the client's name; empty = the site name) and **"Sender
|
||||
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" ("waiting for approval": while the service runs with enrolment "pending" (from its launch until Intecion switches to open enrolment), every new site waits for approval — ask Intecion to approve the host; under open enrolment it is the exception; 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
|
||||
address"** (the client's address: with the mail service replies go there). "Sending method" stays **IWSN (built-in)**; choose **Own SMTP server** and fill in its fields **only** when the client asked
|
||||
for its own server — what is chosen is what is used, an incomplete SMTP server sends nothing. A new site sends through IWSN with nothing picked; picking another option and saving stores it (the panel warns before the save when its settings are incomplete). On the production domain: the block "How e-mails are sent" must say "Connected to IWSN" ("waiting for approval": while the service runs with enrolment "pending" (from its launch until Intecion switches to open enrolment), every new site waits for approval — ask Intecion to approve the host; under open enrolment it is the exception; 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.
|
||||
|
||||
@@ -672,6 +672,22 @@ PROGRAMISTA §6, items 73–75; email.md; AGENT.md §7.2) — nothing to run; re
|
||||
**Send test e-mail** names the transport you expect; a form submission arrives. **The service is live at
|
||||
`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. **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). Nothing to save: the site keeps sending exactly as before **until somebody picks another
|
||||
option** (saving with the shown method stores nothing); `iapl-doctor --deep` notes it (`mail-method`, info). Send a
|
||||
test e-mail: the answer names the method.
|
||||
3. From the save on what is chosen is what is used: "Own SMTP server" with an incomplete server, or "Microsoft Graph"
|
||||
without `GRAPH_*`, sends **nothing** and says so (state block, `mail-method` error) — no fallback to another method.
|
||||
Tell the owner before changing the method on a live site.
|
||||
4. Seeds and scripts that set up mail: write `emailMethod: 'relay' | 'smtp' | 'graph'` (or `setMailMethod(payload, …)`).
|
||||
`emailTransport` written alone still works and means the old order.
|
||||
|
||||
**→ 1.17.1, the sign-in look (CHANGELOG 1.17.1; PROGRAMISTA §6, item 80; white-label.md → "The sign-in screens") — nothing is required:**
|
||||
1. **Sites with `whiteLabel`:** after the update the login screen and the 2FA screens (code, setup) have the new
|
||||
look — a dark panel with the client's logo or the site's name beside the form. No edit, no
|
||||
|
||||
+2
-1
@@ -45,7 +45,8 @@ they will have to log in again.
|
||||
|
||||
### Email — nothing in env
|
||||
|
||||
Mail needs **no variable**. A site with no SMTP server in the panel sends through the Intecion mail service
|
||||
Mail needs **no variable**. A site sends through the Intecion mail service unless an admin chose another
|
||||
"Sending method" in the panel
|
||||
([email.md](./email.md)); SMTP is typed in the panel. What the deploy needs for the mail service:
|
||||
|
||||
- **`NEXT_PUBLIC_SERVER_URL` / `serverURL` = the public address the site answers on without a redirect** (the service
|
||||
|
||||
+2
-1
@@ -114,7 +114,8 @@ 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 (`<PageStats visitorCookie>`, default `ipal_vid`) is the one the config makes the cookie scanner declare (`storageNames`, stats.md) |
|
||||
| | `cookie-scanner` | error / warning / info | `cookieScanner` on (with `crawl`, else info); deep: nothing waits for approval (warning) |
|
||||
| mail | `mail-transport` | error / warning | (deep) an e-mail transport is in effect (not: the mail service switched off and no SMTP server); the last sends worked — failing: warning, error once it has lasted 24 hours |
|
||||
| mail | `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) |
|
||||
| | `mail-reply-address` | warning | (deep) on the mail service, "Sender address" is filled in: replies go there |
|
||||
|
||||
+80
-21
@@ -1,19 +1,19 @@
|
||||
# email
|
||||
|
||||
Mail works with **no setup**: a site with no SMTP server in the panel sends through the
|
||||
Mail works with **no setup**: a new site sends through the
|
||||
**Intecion Notifications Webservice** — **IWSN** for short, the name the admin panel uses (constant
|
||||
`RELAY_SHORT_NAME`); below also "the mail service" — from
|
||||
`[email protected]`, under the site's own sender name. Two more transports exist:
|
||||
|
||||
| Transport | When | Sender address |
|
||||
|---|---|---|
|
||||
| **The mail service** (`relayAdapter`, inside `mailAdapter()`) | the default — nothing filled in | `[email protected]`; replies go to the panel's "Sender address" |
|
||||
| **SMTP from the panel** (`panelSmtpAdapter`) | on the client's request: its own mail server, its own sender address | the panel's "Sender address" |
|
||||
| **Microsoft Graph** (`graphAdapter`) | **deprecated since 1.17.0, removed in 2.0** — sites that have the `GRAPH_*` variables | `GRAPH_SENDER` |
|
||||
| **The mail service** (`relayAdapter`, inside `mailAdapter()`) | the default — "Sending method": **IWSN (built-in)** | `[email protected]`; replies go to the panel's "Sender address" |
|
||||
| **SMTP from the panel** (`panelSmtpAdapter`) | "Sending method": **Own SMTP server** — on the client's request: its own mail server, its own sender address | the panel's "Sender address" |
|
||||
| **Microsoft Graph** (`graphAdapter`) | "Sending method": **Microsoft Graph (deprecated)** — **deprecated since 1.17.0, removed in 2.0**; needs the `GRAPH_*` variables on the server | `GRAPH_SENDER` |
|
||||
|
||||
All three implement Payload's `PayloadEmailAdapter`, so `payload.sendEmail`, form mail, password reset and
|
||||
account verification work whatever the transport. The project wires **one** adapter,
|
||||
`buildConfig({ email: mailAdapter() })`; which transport a send takes is decided on every send.
|
||||
`buildConfig({ email: mailAdapter() })`; which transport a send takes is the admin's choice in the panel.
|
||||
A separate `sendEmail` helper (from `/server`) sends **always through the SMTP** from the panel.
|
||||
|
||||
## Wiring
|
||||
@@ -33,26 +33,84 @@ The plugin does **not** set `config.email` — without `email:` Payload uses a m
|
||||
|
||||
## Which transport a send takes
|
||||
|
||||
Decided on every send from Site integrations → E-mail sending, with no stored value of its own
|
||||
**The one an admin chose** in Site integrations → E-mail sending → **"Sending method"** (since 1.17.1): "IWSN
|
||||
(built-in)", "Own SMTP server" or "Microsoft Graph (deprecated)". What is chosen is what is used, and it is shown:
|
||||
the state block names it, the test e-mail names it, and only the fields of the chosen method are on the page (the
|
||||
SMTP server, port, user name and password under "Own SMTP server"; the service's state block under "IWSN").
|
||||
|
||||
- **No silent switch.** Which fields happen to be filled in, or which variables the server has, no longer picks
|
||||
the method. "IWSN" chosen with an SMTP server filled in sends through the service; "Own SMTP server" chosen
|
||||
never contacts the service.
|
||||
- **A chosen method that cannot be used fails loudly, and nothing is sent another way:**
|
||||
|
||||
| Chosen | What is wrong | A send | Where it shows |
|
||||
|---|---|---|---|
|
||||
| Own SMTP server | server, user name or password missing | `{ sent: false, code: 'not-configured' }` | state block: "Your SMTP server is chosen, but its settings are incomplete…"; status `smtp-incomplete`; doctor `mail-method` (error) |
|
||||
| Microsoft Graph | the `GRAPH_*` variables are not on this server | `{ sent: false, code: 'graph-not-set-up' }` — SMTP is **not** tried | state block: "Microsoft Graph is chosen, but it is not set up on this server…"; status `graph-not-set-up`; doctor `mail-method` (error) |
|
||||
| IWSN | the service cannot call the site back, the site is disconnected, waits for approval, is a held copy … | `relay-refused`, `relay-pending`, … (below) | the service's state block; doctor `mail-relay-state` |
|
||||
|
||||
A form submission is stored whatever happens to its e-mail, as before.
|
||||
- One exception that was always there: with **Microsoft Graph** chosen, a file too large for Graph goes over the
|
||||
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 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
|
||||
(`resolveMailTransport(settings, { graphEnv, relay })` returns `'graph' | 'smtp' | 'relay' | 'none'`, type `MailTransport`):
|
||||
|
||||
1. "Sending method" is Microsoft Graph **and** the four `GRAPH_*` variables are set → **Graph**, as before (deprecated).
|
||||
1. `emailTransport` is `graph` **and** the four `GRAPH_*` variables are set → **Graph** (deprecated).
|
||||
2. The panel has an SMTP server (server, user name and password) → **SMTP**.
|
||||
3. The four `GRAPH_*` variables are set → **Graph** (deprecated), until they are removed.
|
||||
3. The four `GRAPH_*` variables are set → **Graph** (deprecated).
|
||||
4. Otherwise → **the mail service**, unless it is switched off (`mail: { relay: false }`).
|
||||
5. Otherwise nothing is configured: the send reports `{ sent: false, code: 'not-configured' }`, as before 1.17.0.
|
||||
5. Otherwise nothing is configured: the send reports `{ sent: false, code: 'not-configured' }`.
|
||||
|
||||
**Half an SMTP set-up** (a server and a user name without a password, say) is not an SMTP server: until 1.16 such
|
||||
a site refused to send; now its mail goes through the mail service. The server log says so once and the state
|
||||
block shows "The SMTP settings below are incomplete".
|
||||
| The site before the upgrade | "Sending method" shows | Mail |
|
||||
|---|---|---|
|
||||
| 1.17.0, no SMTP server (sends through the service) | IWSN (built-in) | as before |
|
||||
| SMTP server filled in (1.16.x or 1.17.0) | Own SMTP server | as before |
|
||||
| `GRAPH_*` on the server (with "Microsoft Graph" stored, or with no SMTP server) | Microsoft Graph (deprecated) | as before, with the deprecation notice |
|
||||
| half an SMTP set-up, no `GRAPH_*` | IWSN (built-in), with the hint "The SMTP settings below are incomplete" | through the service, as in 1.17.0 |
|
||||
| a new site | IWSN (built-in) | through the service |
|
||||
|
||||
**Nothing changes until somebody picks another option.** Saving Site integrations with the method shown stores no
|
||||
choice — the site keeps sending exactly as before and keeps following what is filled in, as in 1.17.0 (owner's rule,
|
||||
2026-11-26). Picking a **different** option and saving stores it; from then on the method is fixed (a save that keeps
|
||||
it keeps it). The state block says "The site sends the way it did before. It changes only when you pick another
|
||||
sending method." meanwhile, and the doctor's deep run notes it (`mail-method`, info). To fix the method shown without
|
||||
picking another, a script calls `setMailMethod(payload, 'relay')`.
|
||||
|
||||
**A warning before the save.** The state block reads the form as it is being edited: "Own SMTP server" picked with
|
||||
server, user name or password empty says "Fill in server, user name and password below. If you save without them,
|
||||
e-mails will not be sent."; "Microsoft Graph" picked on a server without `GRAPH_*` says the same for Graph. After the
|
||||
save the block reloads and shows the saved state (the error above, if it was saved anyway). Saving is not refused:
|
||||
an admin may set the method first and the server after. A script
|
||||
of before 1.17.1 that writes `emailTransport` alone still means what it meant: it puts the site back on the order
|
||||
above (write `emailMethod` to choose).
|
||||
|
||||
- **A site with SMTP filled in never contacts the mail service.** Nothing changes for it.
|
||||
- **SMTP on the client's request:** an admin fills in "Own SMTP server", user name and password; from the next send
|
||||
the site uses the client's server and the client's own sender address. Emptying the server returns the site to
|
||||
the mail service.
|
||||
- There is **no fallback** from a failing SMTP server to the mail service: a client who asked for its own server
|
||||
gets no mail from another address.
|
||||
- "Sending method" keeps its two stored values (`smtp`, shown as "Automatic", and `graph`); no field was added.
|
||||
|
||||
## The mail service
|
||||
|
||||
@@ -466,8 +524,9 @@ expect(relay.outbox[0]).toMatchObject({ kind: 'system', to: ['[email protected]'] })
|
||||
## SMTP — on the client's request
|
||||
|
||||
The panel's SMTP fields (`smtpHost`, `smtpPort` (default 587), `smtpUser`, `smtpPassword`, `smtpFromAddress`,
|
||||
`smtpFromName`) and `emailTransport` live in Site integrations (E-mail sending tab). Filling in server, user name
|
||||
and password switches the site to the client's server.
|
||||
`smtpFromName`) live in Site integrations (E-mail sending tab); server, port, user name and password are shown
|
||||
while "Sending method" is "Own SMTP server". Choose that method, fill them in and save: the site sends through the
|
||||
client's server (a site nobody has chosen a method for yet does so as soon as the three are filled in).
|
||||
|
||||
- **The password is write-only and stays with its server**: the panel shows "A value is set"; changing the
|
||||
server, port or user name asks for the password again ([security.md](./security.md) "Stored secrets").
|
||||
@@ -587,8 +646,8 @@ To the mail service (when the owner says so):
|
||||
|
||||
1. Upgrade; check that `serverURL` is the site's public address.
|
||||
2. Tell Intecion the host: while the service runs with enrolment "pending" (from its launch until Intecion switches to open enrolment), every new site waits for approval; the panel says so. Under open enrolment the site is active as soon as it enrols.
|
||||
3. Remove the four `GRAPH_*` variables in Coolify and redeploy. If "Sending method" says Microsoft Graph, set it
|
||||
to "Automatic".
|
||||
3. Site integrations → E-mail sending → "Sending method": choose **IWSN (built-in)** and save. Then remove the four
|
||||
`GRAPH_*` variables in Coolify and redeploy.
|
||||
4. Site integrations → E-mail sending → send a test e-mail: the answer says "through IWSN".
|
||||
5. Check "Sender name" and "Sender address" (now the reply address), and tell the client that mail now comes from
|
||||
`[email protected]` instead of the present mailbox (allow-lists, filters).
|
||||
|
||||
@@ -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 }`), `emailTransport` (`smtp` = "Automatic" / `graph` = deprecated), `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 |
|
||||
|
||||
@@ -37,7 +37,7 @@ The state block above it reads `GET /api/iapl/mail-relay/status` and acts throug
|
||||
or at most every 10 min while an error lasts; it never throws. The same change already being written (many sends
|
||||
failing at once) is written once; while every transaction place of a Postgres pool is taken
|
||||
([deployment.md](./deployment.md) §4.3a) the write goes on in the background instead of holding the caller.
|
||||
- **Changing keys in the admin panel** (Turnstile, `emailTransport` / `smtp*`) clears that integration's old status.
|
||||
- **Changing keys in the admin panel** (Turnstile, the sending method / `smtp*`) clears that integration's old status.
|
||||
- **`emailStatus.code`** of a send through the Intecion mail service is one of the `relay-…` codes (`relay-pending`,
|
||||
`relay-quota`, `relay-unreachable`, …), each with a text in the editor's language — the list and what to do:
|
||||
[email.md](./email.md) "Status codes". The token of the mail service is **not** in this global: it lives in
|
||||
|
||||
+3
-3
@@ -1063,9 +1063,9 @@ not enough on its own: an admin session could point `smtpHost` / `smtpPort` at a
|
||||
"Send test e-mail", and read the password off the connection. So a save **through access control** (the panel,
|
||||
REST, GraphQL) that changes `smtpHost`, `smtpPort` or `smtpUser` while a password is stored must send the
|
||||
password again — or remove it (`'[[clear]]'`, "Remove the stored value") for a server without one. **Whatever
|
||||
the transport says:** "Microsoft Graph" in the panel does not mean Graph sends — the mail adapter falls back to
|
||||
SMTP when Graph is not configured, and for attachments Graph cannot take. A change of `emailTransport` alone
|
||||
asks for nothing. Values are compared exactly (`587` and `'587'` are the same; another letter case or a space
|
||||
the sending method says:** with "Microsoft Graph" chosen the SMTP server is still used for attachments Graph cannot
|
||||
take (and, on a site nobody has chosen a method for, when Graph is not configured). A change of the sending method
|
||||
alone asks for nothing. Values are compared exactly (`587` and `'587'` are the same; another letter case or a space
|
||||
is a change), and a value never saved — or a `NULL` in a SQL row — counts as the field's default, so saving
|
||||
the form unchanged asks for nothing. Server code — a seed, a script with the Local API and access control off
|
||||
— is not asked. `iapl({ secrets: { reenterOnChange: false } })` = the stored password follows the new
|
||||
|
||||
@@ -100,6 +100,9 @@ through this procedure. Ask only when you are missing something you cannot get y
|
||||
| pixel before consent (consent-check) | script wired by hand (`<Script>`) | only through the panel → `<Analytics>` (GA/GTM/pixels) or `<ConsentScript>` (analytics.md, consent.md) |
|
||||
| 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 | nothing, if that is wanted (the owner's rule: no change until another option is picked); to fix it: pick the method (another option, then this one) or `setMailMethod(payload, '<method>')` |
|
||||
| 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://<host>/api/iapl/mail-relay/confirm -d '{}' -H 'content-type: application/json'` must answer **404 with an empty body, no redirect**; fix `serverURL` / `mail.relay.host`, or ask Intecion to set the site's confirm address (path ending in `/confirm/` with trailing slashes); then "Connect again" (the site does not retry by itself for 15 min). email.md "When the site cannot be confirmed" |
|
||||
| `relay-refused`, cause `host-not-allowed` / "This site has no public address yet" | the site runs on `localhost`, a private name, or `serverURL` is empty | expected in development (use SMTP / Mailpit there); in production set `serverURL` |
|
||||
|
||||
@@ -39,6 +39,7 @@ description: Complete map of everything @intecion/ipal-kit provides — every ia
|
||||
| `accounts.firstUserRoute` | `'panel'` | which auth collections `POST /api/<slug>/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`; `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)/<route>/` itself and adds the route to the proxy matcher (security.md) |
|
||||
|
||||
@@ -660,8 +660,8 @@ scaling (5). `●` routes for pages need the database at build time (PROGRAMISTA
|
||||
in every language.
|
||||
6. **Notifications**: form messages in every language.
|
||||
7. **Site integrations → E-mail sending**: "Sender name" (the client's name; empty = the site name) and **"Sender
|
||||
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" ("waiting for approval": while the service runs with enrolment "pending" (from its launch until Intecion switches to open enrolment), every new site waits for approval — ask Intecion to approve the host; under open enrolment it is the exception; 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
|
||||
address"** (the client's address: with the mail service replies go there). "Sending method" stays **IWSN (built-in)**; choose **Own SMTP server** and fill in its fields **only** when the client asked
|
||||
for its own server — what is chosen is what is used, an incomplete SMTP server sends nothing. A new site sends through IWSN with nothing picked; picking another option and saving stores it (the panel warns before the save when its settings are incomplete). On the production domain: the block "How e-mails are sent" must say "Connected to IWSN" ("waiting for approval": while the service runs with enrolment "pending" (from its launch until Intecion switches to open enrolment), every new site waits for approval — ask Intecion to approve the host; under open enrolment it is the exception; 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.
|
||||
|
||||
@@ -672,6 +672,22 @@ PROGRAMISTA §6, items 73–75; email.md; AGENT.md §7.2) — nothing to run; re
|
||||
**Send test e-mail** names the transport you expect; a form submission arrives. **The service is live at
|
||||
`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. **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). Nothing to save: the site keeps sending exactly as before **until somebody picks another
|
||||
option** (saving with the shown method stores nothing); `iapl-doctor --deep` notes it (`mail-method`, info). Send a
|
||||
test e-mail: the answer names the method.
|
||||
3. From the save on what is chosen is what is used: "Own SMTP server" with an incomplete server, or "Microsoft Graph"
|
||||
without `GRAPH_*`, sends **nothing** and says so (state block, `mail-method` error) — no fallback to another method.
|
||||
Tell the owner before changing the method on a live site.
|
||||
4. Seeds and scripts that set up mail: write `emailMethod: 'relay' | 'smtp' | 'graph'` (or `setMailMethod(payload, …)`).
|
||||
`emailTransport` written alone still works and means the old order.
|
||||
|
||||
**→ 1.17.1, the sign-in look (CHANGELOG 1.17.1; PROGRAMISTA §6, item 80; white-label.md → "The sign-in screens") — nothing is required:**
|
||||
1. **Sites with `whiteLabel`:** after the update the login screen and the 2FA screens (code, setup) have the new
|
||||
look — a dark panel with the client's logo or the site's name beside the form. No edit, no
|
||||
|
||||
@@ -41,7 +41,7 @@ for (const [address, role] of [[email, 'admin'], [secondTestAdmin(email), 'admin
|
||||
const smtpPort = Number(process.env.E2E_SMTP_PORT ?? 2526)
|
||||
await payload.updateGlobal({
|
||||
slug: 'site-integrations',
|
||||
data: { emailTransport: 'smtp', smtpFromAddress: '[email protected]', smtpHost: '127.0.0.1', smtpPassword: 'e2e-sink', smtpPort, smtpUser: 'e2e' } as never,
|
||||
data: { emailMethod: 'smtp', emailTransport: 'smtp', smtpFromAddress: '[email protected]', smtpHost: '127.0.0.1', smtpPassword: 'e2e-sink', smtpPort, smtpUser: 'e2e' } as never,
|
||||
overrideAccess: true,
|
||||
})
|
||||
console.log(`[e2e] e-mail sending points at the local sink 127.0.0.1:${smtpPort}`)
|
||||
|
||||
@@ -16,7 +16,7 @@ const payload = await getPayload({ config })
|
||||
await payload.updateGlobal({
|
||||
slug: 'site-integrations',
|
||||
context: { ipalIntegrationStatus: true },
|
||||
data: { emailStatus: { checkedAt: null, code: null, message: null, since: null, state: null }, emailTransport: 'smtp', smtpFromAddress: '[email protected]', smtpFromName: 'Example Studio', smtpHost: null, smtpPassword: null, smtpUser: null } as never,
|
||||
data: { emailStatus: { checkedAt: null, code: null, message: null, since: null, state: null }, emailMethod: 'relay', emailTransport: 'smtp', smtpFromAddress: '[email protected]', smtpFromName: 'Example Studio', smtpHost: null, smtpPassword: null, smtpUser: null } as never,
|
||||
overrideAccess: true,
|
||||
})
|
||||
for (const key of await payload.kv.keys()) {
|
||||
|
||||
@@ -82,6 +82,21 @@ 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()
|
||||
// picked, not saved, and the server is empty: the block warns at once
|
||||
await expect(page.locator('[data-mail-method-warning="smtp"]')).toBeVisible()
|
||||
await method.locator('.rs__control').click()
|
||||
await page.locator('.rs__option', { hasText: /IWSN/ }).click()
|
||||
await expect(page.locator('#field-smtpHost')).toHaveCount(0)
|
||||
await expect(page.locator('[data-mail-method-warning]')).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' })
|
||||
|
||||
@@ -2783,8 +2783,9 @@ export interface SiteIntegration {
|
||||
checkedAt?: string | null;
|
||||
};
|
||||
/**
|
||||
* Automatic uses your SMTP server when it is filled in below, and IWSN otherwise.
|
||||
* E-mails are sent the way chosen here, and no other way.
|
||||
*/
|
||||
emailMethod?: ('relay' | 'smtp' | 'graph') | null;
|
||||
emailTransport?: ('smtp' | 'graph') | null;
|
||||
/**
|
||||
* Replies go to this address; with your own SMTP server, e-mails are also sent from it.
|
||||
@@ -2794,9 +2795,6 @@ export interface SiteIntegration {
|
||||
* The name recipients see, e.g. the company name; when empty, the site name.
|
||||
*/
|
||||
smtpFromName?: string | null;
|
||||
/**
|
||||
* Optional: fill in only to send through your own mail server instead of IWSN.
|
||||
*/
|
||||
smtpHost?: string | null;
|
||||
/**
|
||||
* Usually 587, or 465.
|
||||
@@ -3218,6 +3216,7 @@ export interface SiteIntegrationsSelect<T extends boolean = true> {
|
||||
since?: T;
|
||||
checkedAt?: T;
|
||||
};
|
||||
emailMethod?: T;
|
||||
emailTransport?: T;
|
||||
smtpFromAddress?: T;
|
||||
smtpFromName?: T;
|
||||
|
||||
@@ -1,16 +1,20 @@
|
||||
'use client'
|
||||
|
||||
import { useConfig, useTranslation } from '@payloadcms/ui'
|
||||
import { useConfig, useFormFields, useTranslation } from '@payloadcms/ui'
|
||||
import { useCallback, useEffect, useState } from 'react'
|
||||
|
||||
import { formatDateTime, iaplT } from '../../../modules/admin-i18n/t.js'
|
||||
import { RELAY_CONNECT_PATH, RELAY_DISCONNECT_PATH, RELAY_STATUS_PATH } from '../../../modules/email/relay/constants.js'
|
||||
import { SECRET_CLEAR } from '../../../modules/secrets/constants.js'
|
||||
|
||||
type Window = { limit: number; remaining: number }
|
||||
type State = {
|
||||
accessKeyField?: boolean
|
||||
error?: string
|
||||
graphReady?: boolean
|
||||
message?: string
|
||||
methodChosen?: boolean
|
||||
methodProblem?: 'graph-not-set-up' | 'smtp-incomplete'
|
||||
ok?: boolean
|
||||
refusalText?: string
|
||||
relay?: {
|
||||
@@ -74,9 +78,18 @@ export const MailRelayStatus = () => {
|
||||
[api, t],
|
||||
)
|
||||
|
||||
// the form as it is now — before it is saved: a method picked that cannot send is said at once
|
||||
const formMethod = useFormFields(([f]) => f.emailMethod?.value) as string | undefined
|
||||
const formHost = useFormFields(([f]) => f.smtpHost?.value) as string | undefined
|
||||
const formUser = useFormFields(([f]) => f.smtpUser?.value) as string | undefined
|
||||
// (a stored password arrives as the mask: set; "Remove the stored value" is SECRET_CLEAR: not set)
|
||||
const formPassword = useFormFields(([f]) => f.smtpPassword?.value) as string | undefined
|
||||
const savedAt = useFormFields(([f]) => f.updatedAt?.value) as string | undefined
|
||||
|
||||
// on load, and again after every save of the page: the state block says what the saved settings do
|
||||
useEffect(() => {
|
||||
void call(RELAY_STATUS_PATH)
|
||||
}, [call])
|
||||
}, [call, savedAt])
|
||||
|
||||
const post = (path: string, body?: object) =>
|
||||
call(path, { body: body ? JSON.stringify(body) : undefined, headers: body ? { 'Content-Type': 'application/json' } : undefined, method: 'POST' }, true)
|
||||
@@ -104,6 +117,16 @@ export const MailRelayStatus = () => {
|
||||
: state.transport === 'graph' ? text('mailRelayTransportGraph')
|
||||
: text(relay ? 'mailRelayTransportNone' : 'mailRelayOff')}
|
||||
</p>
|
||||
{formMethod === 'smtp' && !(formHost?.trim() && formUser?.trim() && formPassword && formPassword !== SECRET_CLEAR) && !(state.methodProblem === 'smtp-incomplete' && state.transport === 'smtp') ? (
|
||||
<p data-mail-method-warning="smtp" role="alert" style={warn}>{text('mailMethodSmtpIncompleteForm')}</p>
|
||||
) : formMethod === 'graph' && state.graphReady === false && state.methodProblem !== 'graph-not-set-up' ? (
|
||||
<p data-mail-method-warning="graph" role="alert" style={warn}>{text('mailMethodGraphNotSetUpForm')}</p>
|
||||
) : null}
|
||||
{state.methodProblem ? (
|
||||
<p data-mail-method-problem={state.methodProblem} role="alert" style={warn}>{text(state.methodProblem === 'graph-not-set-up' ? 'mailMethodGraphNotSetUp' : 'mailMethodSmtpIncomplete')}</p>
|
||||
) : state.methodChosen === false && state.transport !== 'none' ? (
|
||||
<p style={{ ...line, fontSize: '0.85rem', opacity: 0.75 }}>{text('mailMethodNotChosen')}</p>
|
||||
) : null}
|
||||
{onRelay && relay ? (
|
||||
<>
|
||||
<p role={attention ? 'alert' : undefined} style={attention ? warn : line}>{relayState}</p>
|
||||
|
||||
@@ -1,29 +1,49 @@
|
||||
import type { Condition, Field } from 'payload'
|
||||
import type { Condition, Field, SelectField } from 'payload'
|
||||
|
||||
import { graphAvailable, resolveMailMethod } from '../../../modules/email/mailAdapter.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'
|
||||
|
||||
/**
|
||||
* E-mail sending settings. No field is needed for mail to work: a site with no SMTP server here
|
||||
* sends through the Intecion Notifications Webservice (modules/email/relay). The SMTP fields are
|
||||
* for a client who wants its own mail server; Microsoft Graph (set up on the server) is deprecated.
|
||||
* E-mail sending settings. "Sending method" names how e-mails leave: the built-in Intecion Notifications
|
||||
* Webservice (modules/email/relay; no other field is needed for it), the client's own SMTP server, or
|
||||
* Microsoft Graph (set up on the server; deprecated). What is chosen is what is used.
|
||||
*
|
||||
* Protected at the global level (SiteIntegrations requires an authenticated
|
||||
* user), so all fields — including the password — stay editable in the admin
|
||||
* panel while remaining inaccessible to anonymous API requests.
|
||||
*/
|
||||
|
||||
// SMTP fields only matter with the SMTP transport — hidden while Graph is selected.
|
||||
const usesSmtp: Condition = (_, siblingData) => siblingData?.emailTransport !== 'graph'
|
||||
// SMTP fields are shown only while "Own SMTP server" is the sending method.
|
||||
const usesSmtp: Condition = (_, siblingData) =>
|
||||
siblingData?.emailMethod ? siblingData.emailMethod === 'smtp' : siblingData?.emailTransport !== 'graph'
|
||||
|
||||
const withoutRelay: NonNullable<SelectField['filterOptions']> = ({ 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 function shownMailMethod(settings: Parameters<typeof resolveMailMethod>[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
|
||||
}
|
||||
|
||||
/**
|
||||
* The fields of the "E-mail sending" tab. `relay: false` (the project switched the Intecion mail
|
||||
* service off): no state block, and the wording of 1.16 — SMTP is then the way to send.
|
||||
* No stored field differs between the two: labels, descriptions and one client prop only.
|
||||
* 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 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
|
||||
// enabled the same component shows, above it, which transport is in effect and the site's state with the
|
||||
// enabled the same component shows, above it, which method is in effect and the site's state with the
|
||||
// service (MailRelayStatus): no import-map entry of its own, so an upgrade needs no `generate:importmap`.
|
||||
buildIntegrationStatusBanner(
|
||||
'emailStatus',
|
||||
@@ -32,29 +52,45 @@ export const buildSmtpFields = ({ relay = true }: { relay?: boolean } = {}): Fie
|
||||
{ mailRelay: relay },
|
||||
),
|
||||
{
|
||||
name: 'emailTransport',
|
||||
name: 'emailMethod',
|
||||
type: 'select',
|
||||
admin: {
|
||||
description: relay
|
||||
? {
|
||||
en: `Automatic uses your SMTP server when it is filled in below, and ${IWSN} otherwise.`,
|
||||
pl: `Automatycznie: przez Twój serwer SMTP, jeśli jest uzupełniony poniżej, a w innym razie przez ${IWSN}.`,
|
||||
}
|
||||
: {
|
||||
en: 'Microsoft Graph works only when your administrator has set it up on the server.',
|
||||
pl: 'Microsoft Graph działa tylko wtedy, gdy administrator skonfiguruje go na serwerze.',
|
||||
},
|
||||
// The Graph option only makes sense when agency credentials exist in env.
|
||||
// We can't read process.env in the admin UI directly, so a client project
|
||||
// that hasn't set up Graph should filter this option via integrationsFields
|
||||
// override, or simply leave it on 'smtp'. The adapter enforces the real
|
||||
// availability at send time regardless of what's selected here.
|
||||
description: {
|
||||
en: 'E-mails are sent the way chosen here, and no other way.',
|
||||
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: [({ 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)
|
||||
}],
|
||||
},
|
||||
defaultValue: 'smtp',
|
||||
label: { en: 'Sending method', pl: 'Sposób wysyłki' },
|
||||
options: [
|
||||
// Labels only: the two stored values stay (a new value would change the Postgres enum).
|
||||
{ label: relay ? { en: 'Automatic', pl: 'Automatycznie' } : { en: 'SMTP server', pl: 'Serwer SMTP' }, value: 'smtp' },
|
||||
// (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' },
|
||||
],
|
||||
},
|
||||
{
|
||||
// The stored field of 1.6 – 1.17.0. Kept with its two values (a third would change the Postgres enum) and
|
||||
// kept in step with the choice where it can say it (`graph`, else `smtp`); the panel shows `emailMethod`.
|
||||
name: 'emailTransport',
|
||||
type: 'select',
|
||||
admin: { hidden: true },
|
||||
defaultValue: 'smtp',
|
||||
label: { en: 'Sending method (stored)', pl: 'Sposób wysyłki (zapis)' },
|
||||
options: [
|
||||
{ label: { en: 'SMTP server', pl: 'Serwer SMTP' }, value: 'smtp' },
|
||||
{ label: { en: 'Microsoft Graph (deprecated)', pl: 'Microsoft Graph (wycofywany)' }, value: 'graph' },
|
||||
],
|
||||
},
|
||||
@@ -106,18 +142,10 @@ export const buildSmtpFields = ({ relay = true }: { relay?: boolean } = {}): Fie
|
||||
name: 'smtpHost',
|
||||
type: 'text',
|
||||
admin: {
|
||||
...(relay
|
||||
? {
|
||||
description: {
|
||||
en: `Optional: fill in only to send through your own mail server instead of ${IWSN}.`,
|
||||
pl: `Opcjonalne: uzupełnij tylko, aby wysyłać przez własny serwer zamiast ${IWSN}.`,
|
||||
},
|
||||
}
|
||||
: {}),
|
||||
placeholder: 'smtp.example.com',
|
||||
width: '70%',
|
||||
},
|
||||
label: relay ? { en: 'Own SMTP server', pl: 'Własny serwer SMTP' } : { en: 'Server', pl: 'Serwer' },
|
||||
label: { en: 'Server', pl: 'Serwer' },
|
||||
},
|
||||
{
|
||||
name: 'smtpPort',
|
||||
|
||||
@@ -1,10 +1,13 @@
|
||||
import type { Field, GlobalConfig } from 'payload'
|
||||
|
||||
import { ValidationError } from 'payload'
|
||||
|
||||
import { userMeetsRole } from '../../modules/access/index.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'
|
||||
import { buildSmtpFields } from './fields/smtp.js'
|
||||
import { buildSmtpFields, shownMailMethod } from './fields/smtp.js'
|
||||
import { turnstileFields } from './fields/turnstile.js'
|
||||
|
||||
type BuildSiteIntegrationsArgs = {
|
||||
@@ -87,7 +90,47 @@ export function buildSiteIntegrations({
|
||||
hooks: {
|
||||
// a restore answers with the version document: the secrets are masked there too
|
||||
...(writeOnly ? { afterRead: [maskSecretsOnRestore] } : {}),
|
||||
// What the caller sent for the sending method, before Payload merges the stored document into the data.
|
||||
beforeChange: [
|
||||
// "Sending method" (`emailMethod`) — on EVERY write, the plugin's own included (the status written after a
|
||||
// send): `data` is merged with the document as it was READ by now, and that read shows the method in effect
|
||||
// as selected — which must never 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.
|
||||
({ context, data, originalDoc, req }) => {
|
||||
if (!data) {return data}
|
||||
const noted = context?.iaplMailSent as { sent?: boolean; transport?: boolean } | undefined
|
||||
const sent = noted ? noted.sent : data.emailMethod !== originalDoc?.emailMethod
|
||||
const stored = isMailMethod(context?.iaplMailMethodStored) ? context.iaplMailMethodStored : null
|
||||
const refuse = (message: string): never => {
|
||||
throw new ValidationError({ errors: [{ message, path: 'emailMethod' }], global: 'site-integrations' }, req.t)
|
||||
}
|
||||
// the owner's rule: a site keeps sending the way it does now until somebody picks ANOTHER option — a save that
|
||||
// sends the method already shown, while nothing is stored, stores nothing
|
||||
const shown = shownMailMethod({ ...(originalDoc ?? {}), emailMethod: stored } as never, mailRelay)
|
||||
if (sent && stored === null && data.emailMethod === shown) {
|
||||
data.emailMethod = null
|
||||
} else if (sent && data.emailMethod !== null && data.emailMethod !== undefined) {
|
||||
// anything but one of the three values (a number, a list, another word) is refused here: the database
|
||||
// would answer with an error of its own, or take it
|
||||
if (!isMailMethod(data.emailMethod)) {return refuse('This is not a sending method.')}
|
||||
if (data.emailMethod === 'relay' && !mailRelay) {return refuse('This sending method is switched off for this site.')}
|
||||
if (shown !== data.emailMethod) {
|
||||
data.emailStatus = { checkedAt: null, code: null, message: null, since: null, state: null }
|
||||
}
|
||||
// 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 // un-chosen on purpose (`setMailMethod(payload, null)`): the order of 1.17.0 again
|
||||
} else if ((noted ? noted.transport : true) && 'emailTransport' in data && data.emailTransport !== originalDoc?.emailTransport) {
|
||||
// written the old way (a script from before 1.17.1): it means what it meant — the order of 1.17.0
|
||||
data.emailMethod = null
|
||||
} else {
|
||||
// a write that does not name the method leaves what is stored — empty included
|
||||
data.emailMethod = stored
|
||||
}
|
||||
return data
|
||||
},
|
||||
// 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.
|
||||
({ context, data, originalDoc }) => {
|
||||
@@ -101,6 +144,15 @@ export function buildSiteIntegrations({
|
||||
return data
|
||||
},
|
||||
],
|
||||
beforeOperation: [
|
||||
({ args, context, operation }) => {
|
||||
const data = (args as { data?: Record<string, unknown> } | undefined)?.data
|
||||
if (operation === 'update' && data && typeof data === 'object' && context) {
|
||||
context.iaplMailSent = { sent: 'emailMethod' in data, transport: 'emailTransport' in data }
|
||||
}
|
||||
return args
|
||||
},
|
||||
],
|
||||
},
|
||||
label: { en: 'Site integrations', pl: 'Integracje' },
|
||||
}
|
||||
|
||||
+6
-2
@@ -250,8 +250,11 @@ export { holdAccountMail, releaseAccountMail, sendAccountMailAfterCommit, withAc
|
||||
export { mailAttachmentLimit } from './modules/email/attachmentLimit.js'
|
||||
export { graphAdapter } from './modules/email/graphAdapter.js'
|
||||
export type { GraphAdapterArgs } from './modules/email/graphAdapter.js'
|
||||
export { GRAPH_DEPRECATION_NOTICE, mailAdapter, resolveMailTransport } from './modules/email/mailAdapter.js'
|
||||
export type { MailAdapterArgs, MailTransport } from './modules/email/mailAdapter.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 (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
|
||||
// Payload loads the config (or runs generate:importmap) as a plain Node script.
|
||||
@@ -422,6 +425,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,
|
||||
|
||||
@@ -11,6 +11,11 @@ export const integrationsTexts = defineTexts({
|
||||
alertsUnknownError: 'Unknown error.',
|
||||
|
||||
// Intecion mail service: the state block on the e-mail tab (MailRelayStatus) and its routes
|
||||
mailMethodGraphNotSetUp: 'Microsoft Graph is chosen, but it is not set up on this server. E-mails are not sent. Ask your administrator.',
|
||||
mailMethodGraphNotSetUpForm: 'Microsoft Graph is not set up on this server. If you save this, e-mails will not be sent.',
|
||||
mailMethodNotChosen: 'The site sends the way it did before. It changes only when you pick another sending method.',
|
||||
mailMethodSmtpIncomplete: 'Your SMTP server is chosen, but its settings are incomplete. E-mails are not sent. Fill in server, user name and password.',
|
||||
mailMethodSmtpIncompleteForm: 'Fill in server, user name and password below. If you save without them, e-mails will not be sent.',
|
||||
mailRelayCheck: 'Check now',
|
||||
mailRelayConnect: 'Connect again',
|
||||
mailRelayConnected: `The site is connected to ${IWSN}.`,
|
||||
@@ -84,6 +89,8 @@ export const integrationsTexts = defineTexts({
|
||||
'Microsoft Graph cannot send files of 3 MB and more here, so larger form files are limited or go over SMTP. Ask your administrator.',
|
||||
statusEmailGraphUnavailable:
|
||||
'Microsoft Graph is selected but not set up on the server, so e-mails go over SMTP. Ask your administrator.',
|
||||
statusEmailMethodGraphNotSetUp: 'Microsoft Graph is chosen, but it is not set up on this server. E-mails are not sent.',
|
||||
statusEmailMethodSmtpIncomplete: 'Your SMTP server is chosen, but its settings are incomplete. E-mails are not sent.',
|
||||
statusEmailRelayAttachmentRefused: `${IWSN} does not carry this type of file. The e-mail was not sent.`,
|
||||
statusEmailRelayDisconnected: `The site is disconnected from ${IWSN}, so e-mails are not sent. Connect again, or fill in an SMTP server.`,
|
||||
statusEmailRelayError: `${IWSN} refused the e-mail. Tell your administrator.`,
|
||||
@@ -119,6 +126,7 @@ export const integrationsTexts = defineTexts({
|
||||
testEmailSend: 'Send test e-mail',
|
||||
testEmailSending: 'Sending…',
|
||||
testEmailSent: 'Test e-mail sent to {{to}}.',
|
||||
testEmailSentGraph: 'Test e-mail sent to {{to}} through Microsoft Graph.',
|
||||
testEmailSentRelay: `Test e-mail sent to {{to}} through ${IWSN}, as "{{name}}".`,
|
||||
testEmailSentSmtp: 'Test e-mail sent to {{to}} through your SMTP server.',
|
||||
testEmailSubject: 'Test e-mail from {{site}}',
|
||||
@@ -131,6 +139,11 @@ export const integrationsTexts = defineTexts({
|
||||
alertsLink: 'Przejdź do integracji',
|
||||
alertsUnknownError: 'Nieznany błąd.',
|
||||
|
||||
mailMethodGraphNotSetUp: 'Wybrano Microsoft Graph, ale nie jest on skonfigurowany na tym serwerze. E-maile nie są wysyłane. Zapytaj administratora.',
|
||||
mailMethodGraphNotSetUpForm: 'Microsoft Graph nie jest skonfigurowany na tym serwerze. Jeśli to zapiszesz, e-maile nie będą wysyłane.',
|
||||
mailMethodNotChosen: 'Witryna wysyła tak jak dotąd. Zmieni to dopiero wybór innego sposobu wysyłki.',
|
||||
mailMethodSmtpIncomplete: 'Wybrano Twój serwer SMTP, ale jego ustawienia są niepełne. E-maile nie są wysyłane. Uzupełnij serwer, nazwę użytkownika i hasło.',
|
||||
mailMethodSmtpIncompleteForm: 'Uzupełnij poniżej serwer, nazwę użytkownika i hasło. Jeśli zapiszesz bez nich, e-maile nie będą wysyłane.',
|
||||
mailRelayCheck: 'Sprawdź teraz',
|
||||
mailRelayConnect: 'Połącz ponownie',
|
||||
mailRelayConnected: `Witryna jest połączona z ${IWSN}.`,
|
||||
@@ -201,6 +214,8 @@ export const integrationsTexts = defineTexts({
|
||||
'Microsoft Graph nie może tu wysyłać plików od 3 MB, więc większe pliki z formularzy są ograniczone lub idą przez SMTP. Zapytaj administratora.',
|
||||
statusEmailGraphUnavailable:
|
||||
'Wybrano Microsoft Graph, ale nie jest on skonfigurowany na serwerze, więc e-maile idą przez SMTP. Zapytaj administratora.',
|
||||
statusEmailMethodGraphNotSetUp: 'Wybrano Microsoft Graph, ale nie jest on skonfigurowany na tym serwerze. E-maile nie są wysyłane.',
|
||||
statusEmailMethodSmtpIncomplete: 'Wybrano Twój serwer SMTP, ale jego ustawienia są niepełne. E-maile nie są wysyłane.',
|
||||
statusEmailRelayAttachmentRefused: `${IWSN} nie przesyła plików tego typu. E-mail nie został wysłany.`,
|
||||
statusEmailRelayDisconnected: `Witryna jest rozłączona z ${IWSN}, więc e-maile nie są wysyłane. Połącz ją ponownie albo uzupełnij serwer SMTP.`,
|
||||
statusEmailRelayError: `${IWSN} odrzucił e-mail. Powiadom administratora.`,
|
||||
@@ -235,6 +250,7 @@ export const integrationsTexts = defineTexts({
|
||||
testEmailSend: 'Wyślij testowy e-mail',
|
||||
testEmailSending: 'Wysyłanie…',
|
||||
testEmailSent: 'Testowy e-mail wysłano na adres {{to}}.',
|
||||
testEmailSentGraph: 'Testowy e-mail wysłano na adres {{to}} przez Microsoft Graph.',
|
||||
testEmailSentRelay: `Testowy e-mail wysłano na adres {{to}} przez ${IWSN}, jako „{{name}}”.`,
|
||||
testEmailSentSmtp: 'Testowy e-mail wysłano na adres {{to}} przez Twój serwer SMTP.',
|
||||
testEmailSubject: 'Testowy e-mail z witryny {{site}}',
|
||||
|
||||
@@ -53,6 +53,30 @@ export const mailRules: DoctorRule[] = [
|
||||
group: 'mail',
|
||||
source: 'deep',
|
||||
},
|
||||
{
|
||||
// "Sending method": what is chosen is what is used. A choice that cannot be used sends nothing.
|
||||
id: 'mail-method',
|
||||
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' }]
|
||||
}
|
||||
if (mail.methodProblem === 'graph-not-set-up') {
|
||||
return [{ fix: 'set the four GRAPH_* variables on the server — or choose another sending method in Site integrations → E-mail sending (Microsoft Graph is deprecated and removed in 2.0)', message: '"Microsoft Graph" is the chosen sending method, but the GRAPH_* variables are missing on this server: e-mails are not sent (nothing is sent another way)', severity: 'error' }]
|
||||
}
|
||||
if (mail.methodChosen === false && mail.transport !== 'none') {
|
||||
return [{ fix: 'nothing to do while it sends the way it should; to fix the method, pick it in Site integrations → E-mail sending (another option, or setMailMethod)', message: `nobody has picked a sending method: the site sends the way it did before the upgrade (now: ${mail.transport === 'relay' ? 'the built-in service' : mail.transport === 'smtp' ? 'the SMTP server' : 'Microsoft Graph'}) and follows what is filled in, as before`, severity: 'info' }]
|
||||
}
|
||||
return []
|
||||
},
|
||||
docs: 'docs/email.md',
|
||||
group: 'mail',
|
||||
source: 'deep',
|
||||
},
|
||||
{
|
||||
// Which signal makes the site a non-public copy for the mail service — said plainly, because that signal
|
||||
// decides whether a copy of another site's data mails real people.
|
||||
|
||||
@@ -73,6 +73,8 @@ export async function collectDoctorStatus(payload: BasePayload): Promise<DoctorS
|
||||
graphEnv: graphAvailable(),
|
||||
...(state.nonPublic ? { nonPublic: true, ...(state.nonPublicBy ? { nonPublicBy: state.nonPublicBy } : {}), ...(state.nonPublicPattern ? { nonPublicPattern: state.nonPublicPattern } : {}) } : {}),
|
||||
...(state.otherHostEntries ? { otherHostEntries: true } : {}),
|
||||
methodChosen: state.methodChosen,
|
||||
...(state.methodColumnMissing ? { methodColumnMissing: true } : {}),
|
||||
relay: state.relay
|
||||
? {
|
||||
connected: state.relay.connected,
|
||||
@@ -84,6 +86,7 @@ export async function collectDoctorStatus(payload: BasePayload): Promise<DoctorS
|
||||
: null,
|
||||
replyAddress: Boolean(state.replyAddress),
|
||||
status: integrations.emailStatus?.state ? { code: integrations.emailStatus.code ?? null, since: integrations.emailStatus.since ?? null, state: integrations.emailStatus.state } : null,
|
||||
...(state.methodProblem ? { methodProblem: state.methodProblem } : {}),
|
||||
transport: state.transport,
|
||||
}
|
||||
} catch {
|
||||
|
||||
@@ -67,6 +67,12 @@ export type DoctorStatus = {
|
||||
mail?: {
|
||||
/** The four GRAPH_* variables are set (Microsoft Graph: deprecated). */
|
||||
graphEnv: boolean
|
||||
/** An admin chose the sending method ("Sending method" was saved); false = the order of 1.17.0 still decides. */
|
||||
methodChosen?: boolean
|
||||
/** Postgres / SQLite: the column of "Sending method" is missing — the 1.17.1 migration has not run. */
|
||||
methodColumnMissing?: boolean
|
||||
/** The chosen method cannot be used: e-mails are not sent. */
|
||||
methodProblem?: 'graph-not-set-up' | 'smtp-incomplete'
|
||||
/** The site says it is not public (`IAPL_NOINDEX`, or a development host): a copy of another site's data does not mail by itself. */
|
||||
nonPublic?: boolean
|
||||
/** Which signal makes it non-public: the host matches a development pattern (`nonPublicPattern`), or `IAPL_NOINDEX`. */
|
||||
|
||||
@@ -1,18 +1,20 @@
|
||||
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'
|
||||
import { isMailMethod, type MailMethod, readMailSettings } from './method.js'
|
||||
import { panelSmtpAdapter, type PanelSmtpAdapterArgs } from './panelSmtpAdapter.js'
|
||||
import { relayAttachmentLimit, sendRelayWithPanel } from './relay/adapter.js'
|
||||
import { pluginMailOptions, type RelayOptions, resolveRelayOptions } from './relay/options.js'
|
||||
|
||||
type TransportIntegrations = {
|
||||
emailStatus?: IntegrationStatus | null
|
||||
/** 'smtp' | 'graph' — chosen by the editor in SiteIntegrations. */
|
||||
/** "Sending method" as stored: empty = nobody has chosen. */
|
||||
emailMethod?: null | string
|
||||
emailStatus?: IntegrationStatus | null
|
||||
emailTransport?: 'graph' | 'smtp' | null
|
||||
smtpFromAddress?: null | string
|
||||
smtpFromName?: null | string
|
||||
@@ -46,6 +48,32 @@ export function resolveMailTransport(settings: TransportIntegrations, state: { g
|
||||
return state.relay ? 'relay' : 'none'
|
||||
}
|
||||
|
||||
/** Why the chosen method cannot be used. The mail is NOT sent another way. */
|
||||
export type MailMethodProblem = 'graph-not-set-up' | 'smtp-incomplete'
|
||||
|
||||
export type ResolvedMailMethod = {
|
||||
/** An admin chose it ("Sending method" was saved); false = nobody has chosen yet, the order of 1.17.0 decides. */
|
||||
explicit: boolean
|
||||
method: MailTransport
|
||||
/** Set only for an explicit choice that cannot be used; sends fail and say so. */
|
||||
problem?: MailMethodProblem
|
||||
}
|
||||
|
||||
/**
|
||||
* The sending method in effect. With a choice (`emailMethod`, as stored): exactly that method — an SMTP choice with
|
||||
* an incomplete server, or Graph without the `GRAPH_*` variables, is a problem and the mail fails loudly;
|
||||
* nothing is sent another way. Without a choice: `resolveMailTransport`, the order of 1.17.0.
|
||||
* A choice of the built-in service counts as no choice when the project switched the service off
|
||||
* (`mail: { relay: false }` removes the option).
|
||||
*/
|
||||
export function resolveMailMethod(settings: TransportIntegrations, state: { chosen: MailMethod | null; graphEnv: boolean; relay: boolean }): ResolvedMailMethod {
|
||||
const chosen = state.chosen === 'relay' && !state.relay ? null : state.chosen
|
||||
if (!chosen) {return { explicit: false, method: resolveMailTransport(settings, state) }}
|
||||
if (chosen === 'smtp') {return { explicit: true, method: 'smtp', ...(smtpConfigured(settings) ? {} : { problem: 'smtp-incomplete' as const }) }}
|
||||
if (chosen === 'graph') {return { explicit: true, method: 'graph', ...(state.graphEnv ? {} : { problem: 'graph-not-set-up' as const }) }}
|
||||
return { explicit: true, method: 'relay' }
|
||||
}
|
||||
|
||||
/** Graph result codes that mean "Graph cannot carry an attachment this large" — SMTP may. */
|
||||
const GRAPH_TOO_LARGE = new Set(['graph-large-off', 'graph-permission'])
|
||||
|
||||
@@ -137,11 +165,11 @@ export const mailAdapter =
|
||||
* without SMTP settings the ceiling is GRAPH_INLINE_MAX_BYTES.
|
||||
*/
|
||||
const relayOptions = () => resolveRelayOptions(payload, args.relay)
|
||||
const transportOf = (settings: TransportIntegrations) => resolveMailTransport(settings, { 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<null | number> => {
|
||||
const settings = await getSiteIntegrations<TransportIntegrations>(payload)
|
||||
const transport = transportOf(settings)
|
||||
const settings = await readMailSettings<TransportIntegrations>(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}
|
||||
@@ -165,24 +193,33 @@ export const mailAdapter =
|
||||
}
|
||||
|
||||
async function send(message: SendEmailOptions): Promise<unknown> {
|
||||
const settings = await getSiteIntegrations<TransportIntegrations>(payload)
|
||||
const settings = await readMailSettings<TransportIntegrations>(payload)
|
||||
const choice = settings.emailTransport ?? 'smtp'
|
||||
const previous = settings[STATUS_FIELD]
|
||||
const chosen = transportOf(settings)
|
||||
const resolved = methodOf(settings)
|
||||
const chosen = resolved.method
|
||||
|
||||
// No SMTP server in the panel and no Graph: the Intecion Notifications Webservice.
|
||||
if (chosen === 'relay') {
|
||||
// Half an SMTP set-up was "not configured" before 1.17.0; now the mail leaves another way: say so once.
|
||||
if (smtpIncomplete(settings) && !warnedSmtpIncomplete) {
|
||||
if (!resolved.explicit && smtpIncomplete(settings) && !warnedSmtpIncomplete) {
|
||||
warnedSmtpIncomplete = true
|
||||
payload.logger.warn('[iapl] The SMTP settings in Site integrations are incomplete (server, user name and password are all needed), so e-mails go through the Intecion Notifications Webservice. Complete them to use the SMTP server, or empty them.')
|
||||
}
|
||||
return sendRelayWithPanel(payload, relayOptions()!, message, settings)
|
||||
}
|
||||
|
||||
// Graph was chosen, but this server has no GRAPH_* variables: the mail fails, and says so. It does not
|
||||
// leave another way — what is chosen is what is used.
|
||||
if (resolved.problem === 'graph-not-set-up') {
|
||||
const error = 'Microsoft Graph is chosen as the sending method, but it is not set up on this server (the GRAPH_* variables are missing). Nothing was sent.'
|
||||
await recordIntegrationStatus(payload, STATUS_FIELD, previous, { code: 'graph-not-set-up', message: error, state: 'degraded' })
|
||||
return { code: 'graph-not-set-up', error, sent: false }
|
||||
}
|
||||
|
||||
const useGraph = chosen === 'graph'
|
||||
// "Graph" in the panel without its variables is reported only while SMTP carries the mail instead.
|
||||
const graphFallback = choice === 'graph' && !useGraph
|
||||
const graphFallback = !resolved.explicit && choice === 'graph' && !useGraph
|
||||
|
||||
if (graphFallback) {
|
||||
// Panel asked for Graph but the agency creds aren't configured for
|
||||
@@ -206,7 +243,8 @@ export const mailAdapter =
|
||||
const viaGraph = useGraph && !largeOverSmtp
|
||||
|
||||
const transport = viaGraph ? 'Microsoft Graph' : 'SMTP'
|
||||
const code = viaGraph ? 'graph-error' : 'smtp-error'
|
||||
// (SMTP was chosen and its settings are incomplete: its own code, so the panel can say what to fill in)
|
||||
const code = viaGraph ? 'graph-error' : resolved.problem === 'smtp-incomplete' ? 'smtp-incomplete' : 'smtp-error'
|
||||
let result: unknown
|
||||
try {
|
||||
result = await (viaGraph ? graph : smtp).sendEmail(message)
|
||||
|
||||
@@ -0,0 +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).
|
||||
*
|
||||
* 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.
|
||||
*
|
||||
* 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']
|
||||
|
||||
/**
|
||||
* 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)
|
||||
|
||||
/** Site integrations with `emailMethod` as stored — what the mail adapter and the state block decide from. */
|
||||
export function readMailSettings<T = Record<string, unknown>>(payload: BasePayload): Promise<T> {
|
||||
return findSiteIntegrations<T>(payload, { context: { [STORED_MAIL_METHOD_CONTEXT]: true } })
|
||||
}
|
||||
|
||||
/** The chosen method, or null when nobody has chosen yet. Reads only. */
|
||||
export async function getMailMethod(payload: BasePayload): Promise<MailMethod | null> {
|
||||
const stored = (await readMailSettings<Record<string, unknown>>(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: BasePayload, method: MailMethod | null): Promise<void> {
|
||||
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 })
|
||||
}
|
||||
@@ -5,8 +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 { graphAvailable, type MailTransport, resolveMailTransport, smtpIncomplete } from '../mailAdapter.js'
|
||||
import { mailMethodColumnMissing } from '../../payload/getSiteIntegrations.js'
|
||||
import { graphAvailable, type MailMethodProblem, type MailTransport, resolveMailMethod, smtpIncomplete } from '../mailAdapter.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'
|
||||
@@ -15,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
|
||||
@@ -29,6 +31,17 @@ export type MailPanelState = {
|
||||
accessKeyField?: boolean
|
||||
/** The address the service calls this site back at. */
|
||||
confirmUrl?: string
|
||||
/** The four `GRAPH_*` variables are set on this server (whether "Microsoft Graph" could send). */
|
||||
graphReady: boolean
|
||||
/**
|
||||
* An admin chose the method in effect ("Sending method" was saved). False: nobody has chosen yet, and the
|
||||
* 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. */
|
||||
nonPublic?: boolean
|
||||
/** Which signal says so; with `development-host`, `nonPublicPattern` is the pattern that matched. */
|
||||
@@ -58,9 +71,10 @@ 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<PayloadRequest, 'payload'>, own: false | RelayOptions | undefined, { refresh = false }: { refresh?: boolean } = {}): Promise<MailPanelState> {
|
||||
const { payload } = req
|
||||
const settings = await getSiteIntegrations<Settings>(payload)
|
||||
const settings = await readMailSettings<Settings>(payload)
|
||||
const options = resolveRelayOptions(payload, own)
|
||||
const transport = resolveMailTransport(settings, { 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
|
||||
// plugin before any call: say so now, not only after the first failed e-mail.
|
||||
@@ -88,11 +102,16 @@ export async function mailPanelState(req: Pick<PayloadRequest, 'payload'>, own:
|
||||
return {
|
||||
...(options?.accessKeyField === true ? { accessKeyField: true } : {}),
|
||||
...(status?.host ? { confirmUrl: `https://${status.host}${api}${RELAY_CONFIRM_PATH}` } : {}),
|
||||
graphReady: graphAvailable(),
|
||||
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,
|
||||
...(signal ? { nonPublic: true, nonPublicBy: signal.by, ...(signal.by === 'development-host' ? { nonPublicPattern: signal.pattern } : {}) } : {}),
|
||||
...(otherHostEntries ? { otherHostEntries: true } : {}),
|
||||
...(smtpIncomplete(settings) ? { smtpIncomplete: true } : {}),
|
||||
// (the hint of a site nobody chose a method for: its half-filled SMTP server is passed over)
|
||||
...(!method.explicit && smtpIncomplete(settings) ? { smtpIncomplete: true } : {}),
|
||||
transport,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -90,7 +90,9 @@ export const testEmailEndpoint: Endpoint = {
|
||||
req.payload.logger.error(`[iapl] Test email not sent: ${failed?.detail ?? failed?.error ?? 'unknown reason'}`)
|
||||
const relayText = failed?.code ? STATUS_CODE_TEXTS[failed.code] : undefined
|
||||
const error =
|
||||
failed?.code === 'not-configured'
|
||||
failed?.code === 'graph-not-set-up'
|
||||
? serverText(i18n, 'statusEmailMethodGraphNotSetUp')
|
||||
: failed?.code === 'not-configured'
|
||||
? serverText(i18n, 'testEmailNotConfigured')
|
||||
: failed?.confirmed === false
|
||||
? serverText(i18n, 'testEmailNotConfirmed')
|
||||
@@ -104,12 +106,15 @@ export const testEmailEndpoint: Endpoint = {
|
||||
// The answer names the transport that carried it: the mail service says so itself; SMTP is told by the
|
||||
// settings (the dispatcher's results for SMTP and Graph are what they were before 1.17.0).
|
||||
const sentBy = info as { senderName?: string; transport?: string } | null
|
||||
const smtp = !sentBy?.transport && req.payload.email?.name === 'ipal-mail-dispatcher' && transportBefore === 'smtp'
|
||||
const byDispatcher = !sentBy?.transport && req.payload.email?.name === 'ipal-mail-dispatcher'
|
||||
const smtp = byDispatcher && transportBefore === 'smtp'
|
||||
const graph = byDispatcher && transportBefore === 'graph'
|
||||
const message =
|
||||
sentBy?.transport === 'relay' ? serverText(i18n, 'testEmailSentRelay', { name: sentBy.senderName ?? '', to })
|
||||
: smtp ? serverText(i18n, 'testEmailSentSmtp', { to })
|
||||
: graph ? serverText(i18n, 'testEmailSentGraph', { to })
|
||||
: serverText(i18n, 'testEmailSent', { to })
|
||||
return Response.json({ message, ok: true, ...(sentBy?.transport === 'relay' ? { transport: 'relay' } : smtp ? { transport: 'smtp' } : {}) })
|
||||
return Response.json({ message, ok: true, ...(sentBy?.transport === 'relay' ? { transport: 'relay' } : smtp ? { transport: 'smtp' } : graph ? { transport: 'graph' } : {}) })
|
||||
} catch (err) {
|
||||
const message = err instanceof Error ? err.message : String(err)
|
||||
req.payload.logger.error(`[iapl] Test email failed: ${message}`)
|
||||
|
||||
@@ -18,6 +18,7 @@ export function resolveLabel(label: IntegrationLabel | undefined, language: stri
|
||||
export const STATUS_CODE_TEXTS: Record<string, AdminTextKey> = {
|
||||
'bad-response': 'statusTurnstileBadResponse',
|
||||
'graph-large-files': 'statusEmailGraphLargeFiles',
|
||||
'graph-not-set-up': 'statusEmailMethodGraphNotSetUp',
|
||||
'graph-unavailable': 'statusEmailGraphUnavailable',
|
||||
'internal-error': 'statusTurnstileInternalError',
|
||||
'invalid-input-secret': 'statusTurnstileInvalidSecret',
|
||||
@@ -35,6 +36,7 @@ export const STATUS_CODE_TEXTS: Record<string, AdminTextKey> = {
|
||||
'relay-suspended': 'statusEmailRelaySuspended',
|
||||
'relay-too-large': 'statusEmailRelayTooLarge',
|
||||
'relay-unreachable': 'statusEmailRelayUnreachable',
|
||||
'smtp-incomplete': 'statusEmailMethodSmtpIncomplete',
|
||||
}
|
||||
|
||||
type I18nLike = { language?: string; t?: (key: never, vars?: Record<string, unknown>) => string } | undefined
|
||||
|
||||
@@ -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<T = Record<string, unknown>>(
|
||||
payload: BasePayload,
|
||||
options: { context?: Record<string, unknown> } & GlobalQueryOptions = {},
|
||||
): Promise<T> {
|
||||
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<T = Record<string, unknown>>(
|
||||
payload: BasePayload,
|
||||
options?: GlobalQueryOptions,
|
||||
): Promise<T> {
|
||||
return getGlobal<T>(payload, SITE_INTEGRATIONS_SLUG, options)
|
||||
return findSiteIntegrations<T>(payload, options)
|
||||
}
|
||||
|
||||
+24
-1
@@ -699,7 +699,7 @@ describe('iapl-doctor: first-seen dates', () => {
|
||||
})
|
||||
|
||||
describe('e-mail: transport, the mail service, Graph, the confirm route', () => {
|
||||
const ids = ['mail-transport', 'mail-non-public', 'mail-relay-state', 'mail-reply-address', 'mail-graph-deprecated', 'mail-relay-route']
|
||||
const ids = ['mail-transport', 'mail-method', 'mail-non-public', 'mail-relay-state', 'mail-reply-address', 'mail-graph-deprecated', 'mail-relay-route']
|
||||
const relay = (extra: object = {}) => ({ connected: true, disconnected: false, nameReplaced: false, state: 'active', ...extra })
|
||||
const mail = (extra: object = {}) => ({ graphEnv: false, relay: relay(), replyAddress: true, status: null, transport: 'relay', ...extra })
|
||||
const run = async (deep: null | object, files: Record<string, string> = {}) =>
|
||||
@@ -740,6 +740,29 @@ describe('e-mail: transport, the mail service, Graph, the confirm route', () =>
|
||||
expect(await run(mail({ nonPublic: true, nonPublicBy: 'noindex', otherHostEntries: true }))).toEqual(['mail-non-public:info'])
|
||||
})
|
||||
|
||||
test('mail-method: a chosen method that cannot be used is an error; nothing chosen yet is information', async () => {
|
||||
const find = async (deep: object) => (await doctor(project({ ...base(), 'src/payload.config.ts': 'iapl({ forms: {} })' }), ids, { deepStatus: { mail: mail(deep) } })).findings.filter((f) => f.rule === 'mail-method')
|
||||
const smtp = await find({ methodChosen: true, methodProblem: 'smtp-incomplete', relay: relay({ connected: false, state: undefined }), replyAddress: false, transport: 'smtp' })
|
||||
expect(smtp.map((f) => f.severity)).toEqual(['error'])
|
||||
expect(smtp[0].message).toContain('e-mails are not sent')
|
||||
expect(smtp[0].fix).toContain('server, user name and password')
|
||||
const graph = await find({ methodChosen: true, methodProblem: 'graph-not-set-up', relay: relay({ connected: false, state: undefined }), replyAddress: false, transport: 'graph' })
|
||||
expect(graph.map((f) => f.severity)).toEqual(['error'])
|
||||
expect(graph[0].message).toContain('GRAPH_*')
|
||||
const open = await find({ methodChosen: false })
|
||||
expect(open.map((f) => f.severity)).toEqual(['info'])
|
||||
expect(open[0].message).toContain('the built-in service')
|
||||
expect(open[0].message).toContain('the way it did before the upgrade')
|
||||
expect(open[0].fix).toContain('nothing to do')
|
||||
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
|
||||
})
|
||||
|
||||
test('mail-non-public: says which signal makes the site a non-public copy — the development pattern, or IAPL_NOINDEX', async () => {
|
||||
const find = async (deep: object) => (await doctor(project({ ...base(), 'src/payload.config.ts': 'iapl({ forms: {} })' }), ids, { deepStatus: { mail: mail(deep) } })).findings
|
||||
const byHost = await find({ nonPublic: true, nonPublicBy: 'development-host', nonPublicPattern: '*.dev.netscale.pl' })
|
||||
|
||||
@@ -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<unknown> }; pool?: { query: (q: string) => Promise<unknown> }; 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: '<p>Hello.</p>', subject: 'Before the migration', to: '[email protected]' })).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: '<p>Hello.</p>', subject: 'After', to: '[email protected]' })).toMatchObject({ code: 'not-configured', sent: false })
|
||||
expect(fake.requests).toHaveLength(before)
|
||||
error.mockRestore()
|
||||
})
|
||||
@@ -0,0 +1,380 @@
|
||||
/**
|
||||
* "Sending method" on a running Payload (SQLite by default; MongoDB and Postgres through
|
||||
* IPAL_TEST_MONGO_URI / IPAL_TEST_POSTGRES_URI — test/http/db.ts): the explicit choice of 1.17.1.
|
||||
* - upgrade: a site of 1.17.0 or 1.16.x, with nothing chosen, shows the method it sends through today and
|
||||
* 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;
|
||||
* - 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'
|
||||
|
||||
import { lexicalEditor } from '@payloadcms/richtext-lexical'
|
||||
import os from 'os'
|
||||
import path from 'path'
|
||||
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, 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'
|
||||
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 PASSWORD = 'a-long-test-password-1'
|
||||
const HOST = 'example.com'
|
||||
const GRAPH_ENV = ['GRAPH_TENANT_ID', 'GRAPH_CLIENT_ID', 'GRAPH_CLIENT_SECRET', 'GRAPH_SENDER']
|
||||
// a mail server nobody listens on: an SMTP attempt fails at once, and is told apart from "not attempted"
|
||||
const SMTP = { smtpHost: '127.0.0.1', smtpPassword: 'smtp-test-password', smtpPort: 9, smtpUser: 'mailer' }
|
||||
const NO_SMTP = { smtpHost: null, smtpPassword: SECRET_CLEAR, smtpPort: 587, smtpUser: null }
|
||||
const MESSAGE = { html: '<p>Hello.</p>', subject: 'New enquiry', to: '[email protected]' }
|
||||
|
||||
let server: TestServer
|
||||
let payload: Payload
|
||||
let admin: Record<string, string>
|
||||
|
||||
const fake = createFakeRelay({
|
||||
allow: [HOST],
|
||||
callSite: async (url, init) => fetch(`${server.url}${new URL(url).pathname}`, { ...init, redirect: 'manual' }),
|
||||
})
|
||||
|
||||
const makeConfig = (mail?: Parameters<typeof iapl>[0]['mail'], name = 'mailmethod') =>
|
||||
buildTestConfig({
|
||||
admin: { user: 'users' },
|
||||
collections: [{ slug: 'media', fields: [], upload: { staticDir: path.join(os.tmpdir(), 'iapl-mail-method-media') } }],
|
||||
db: testDatabase(name),
|
||||
editor: lexicalEditor(),
|
||||
email: mailAdapter({ smtp: { connectionTimeout: 2000 } as never }),
|
||||
plugins: [iapl({ access: { authCollection: 'users' }, i18n: { defaultLocale: 'pl', locales: [{ code: 'pl', label: 'Polski' }] }, mail, twoFactor: false })],
|
||||
secret: 'integration-test-secret-0123456789',
|
||||
serverURL: `https://${HOST}`,
|
||||
telemetry: false,
|
||||
})
|
||||
|
||||
const api = (pathname: string, init: RequestInit = {}) =>
|
||||
fetch(`${server.url}/api${pathname}`, { ...init, headers: { 'content-type': 'application/json', ...admin, ...(init.headers as Record<string, string>) } })
|
||||
/** The global as the panel reads it. */
|
||||
const read = async () => (await (await api('/globals/site-integrations?depth=0')).json()) as Record<string, unknown>
|
||||
/** A save the way the panel's form makes it: the whole document, with what the form shows. */
|
||||
const saveForm = async (change: Record<string, unknown> = {}) => {
|
||||
const { id: _i, createdAt: _c, emailStatus: _s, globalType: _g, smtpPassword: _p, turnstileStatus: _t, updatedAt: _u, ...form } = await read()
|
||||
return api('/globals/site-integrations', { body: JSON.stringify({ ...form, ...change }), method: 'POST' })
|
||||
}
|
||||
/** A site as an older version left it: the stored fields only, nothing chosen. */
|
||||
const asStored = async (data: Record<string, unknown>) => {
|
||||
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 }>
|
||||
const relayCalls = () => fake.requests.filter((r) => r.path === '/v1/send').length
|
||||
const status = async () => ((await payload.findGlobal({ slug: 'site-integrations' as never, depth: 0 })) as unknown as { emailStatus?: { code?: string; state?: string } }).emailStatus
|
||||
|
||||
beforeAll(async () => {
|
||||
const config = makeConfig({ relay: { fetchImpl: fake.fetch, url: fake.url } })
|
||||
payload = await getPayload({ config })
|
||||
server = await startPayloadServer(config)
|
||||
await payload.create({ collection: 'users' as never, data: { email: '[email protected]', password: PASSWORD, roles: ['admin'] } as never })
|
||||
const res = await fetch(`${server.url}/api/users/login`, { body: JSON.stringify({ email: '[email protected]', password: PASSWORD }), headers: { 'content-type': 'application/json' }, method: 'POST' })
|
||||
admin = { authorization: `JWT ${((await res.json()) as { token: string }).token}` }
|
||||
}, 120_000)
|
||||
|
||||
afterAll(async () => {
|
||||
await server?.close()
|
||||
await payload?.destroy?.()
|
||||
})
|
||||
|
||||
beforeEach(() => {
|
||||
for (const name of GRAPH_ENV) {vi.stubEnv(name, '')}
|
||||
})
|
||||
afterEach(() => vi.unstubAllEnvs())
|
||||
|
||||
describe('upgrade, with no edit: the site shows the method it sends through today, and keeps sending', () => {
|
||||
test('a 1.17.0 site that sends through the service because SMTP is empty: "IWSN" is selected, mail leaves through it, reading writes nothing', async () => {
|
||||
await asStored({ smtpFromAddress: '[email protected]', smtpFromName: 'Kancelaria Example' })
|
||||
expect((await read()).emailMethod).toBe('relay')
|
||||
expect(await state()).toMatchObject({ methodChosen: false, transport: 'relay' })
|
||||
const before = relayCalls()
|
||||
expect(await send()).toMatchObject({ transport: 'relay' })
|
||||
expect(relayCalls()).toBe(before + 1)
|
||||
expect(fake.outbox.at(-1)).toMatchObject({ subject: 'New enquiry' })
|
||||
// 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()
|
||||
})
|
||||
|
||||
test('a site with its SMTP server filled in: "Own SMTP server" is selected, the service is not contacted', async () => {
|
||||
await asStored(SMTP)
|
||||
expect((await read()).emailMethod).toBe('smtp')
|
||||
expect(await state()).toMatchObject({ methodChosen: false, transport: 'smtp' })
|
||||
const before = fake.requests.length
|
||||
const sent = await send().catch((e: Error) => ({ code: 'threw', error: e.message, sent: false }))
|
||||
expect(sent.sent).not.toBe(true) // nobody listens on the port: SMTP was tried, and only SMTP
|
||||
expect(fake.requests).toHaveLength(before)
|
||||
expect((await status())?.code).toBe('smtp-error')
|
||||
})
|
||||
|
||||
test('a Graph site: "Microsoft Graph (deprecated)" is selected — with the choice stored as `graph`, or with only the GRAPH_* variables', async () => {
|
||||
for (const name of GRAPH_ENV) {vi.stubEnv(name, 'x')}
|
||||
await asStored({ emailTransport: 'graph' })
|
||||
expect((await read()).emailMethod).toBe('graph')
|
||||
expect(await state()).toMatchObject({ methodChosen: false, transport: 'graph' })
|
||||
await asStored({})
|
||||
expect((await read()).emailMethod).toBe('graph')
|
||||
// and with SMTP filled in beside the variables: SMTP, as in 1.17.0 and 1.16
|
||||
await asStored(SMTP)
|
||||
expect((await read()).emailMethod).toBe('smtp')
|
||||
})
|
||||
|
||||
test('1.16.x straight to 1.17.1: "Graph" stored without the variables and SMTP filled in → SMTP; half an SMTP set-up → the service, with the hint', async () => {
|
||||
await asStored({ emailTransport: 'graph', ...SMTP })
|
||||
expect((await read()).emailMethod).toBe('smtp')
|
||||
expect(await state()).toMatchObject({ methodChosen: false, transport: 'smtp' })
|
||||
await asStored({ smtpHost: 'smtp.example.com', smtpUser: 'mailer' })
|
||||
expect((await read()).emailMethod).toBe('relay')
|
||||
expect(await state()).toMatchObject({ methodChosen: false, smtpIncomplete: true, transport: 'relay' })
|
||||
const before = relayCalls()
|
||||
expect(await send()).toMatchObject({ transport: 'relay' })
|
||||
expect(relayCalls()).toBe(before + 1)
|
||||
})
|
||||
|
||||
test('a new site (nothing ever saved): "IWSN" is selected', async () => {
|
||||
await asStored({})
|
||||
expect((await read()).emailMethod).toBe('relay')
|
||||
})
|
||||
})
|
||||
|
||||
describe('the choice: what is chosen is what is used', () => {
|
||||
test('the owner\'s rule: saving without picking another option stores nothing and changes nothing; picking another one stores it', async () => {
|
||||
// an upgraded site on the service: the form is saved as it is, twice — nothing is chosen, mail goes as before
|
||||
await asStored({})
|
||||
for (const change of [{}, { smtpFromName: 'Kancelaria Example' }]) {
|
||||
const saved = await saveForm(change)
|
||||
expect(saved.status).toBe(200)
|
||||
expect(((await saved.json()) as { result: { emailMethod: string } }).result.emailMethod).toBe('relay')
|
||||
expect(await getMailMethod(payload)).toBeNull()
|
||||
}
|
||||
expect(await state()).toMatchObject({ methodChosen: false, transport: 'relay' })
|
||||
// …and it still follows what is filled in, as before (the old order): an SMTP server is filled in → SMTP
|
||||
await payload.updateGlobal({ slug: 'site-integrations' as never, data: SMTP as never })
|
||||
expect((await read()).emailMethod).toBe('smtp')
|
||||
expect(await getMailMethod(payload)).toBeNull()
|
||||
// a Graph site saved as it is stays a Graph site (the old order), with the variables
|
||||
for (const name of GRAPH_ENV) {vi.stubEnv(name, 'x')}
|
||||
await asStored({ emailTransport: 'graph' })
|
||||
await saveForm({})
|
||||
expect(await getMailMethod(payload)).toBeNull()
|
||||
expect(await read()).toMatchObject({ emailMethod: 'graph', emailTransport: 'graph' })
|
||||
for (const name of GRAPH_ENV) {vi.stubEnv(name, '')}
|
||||
// picking ANOTHER option stores it, and the answer shows it; the stored field of 1.17.0 follows
|
||||
await asStored({})
|
||||
const changed = await saveForm({ emailMethod: 'graph' })
|
||||
expect(((await changed.json()) as { result: { emailMethod: string; emailTransport: string } }).result).toMatchObject({ emailMethod: 'graph', emailTransport: 'graph' })
|
||||
expect(await getMailMethod(payload)).toBe('graph')
|
||||
// once chosen, a save that keeps it keeps it, and the method no longer follows what is filled in
|
||||
await saveForm({ emailMethod: 'relay' })
|
||||
expect(await getMailMethod(payload)).toBe('relay')
|
||||
await saveForm({ smtpFromName: 'Kancelaria Example' })
|
||||
expect(await getMailMethod(payload)).toBe('relay')
|
||||
await payload.updateGlobal({ slug: 'site-integrations' as never, data: SMTP as never })
|
||||
expect(await state()).toMatchObject({ methodChosen: true, transport: 'relay' })
|
||||
await saveForm({ emailMethod: 'smtp' })
|
||||
expect(await read()).toMatchObject({ emailMethod: 'smtp', emailTransport: 'smtp' })
|
||||
})
|
||||
|
||||
test('the state block is told whether Graph could send, for its warning before the save', async () => {
|
||||
await asStored({})
|
||||
expect((await state()).graphReady).toBe(false)
|
||||
for (const name of GRAPH_ENV) {vi.stubEnv(name, 'x')}
|
||||
expect((await state()).graphReady).toBe(true)
|
||||
})
|
||||
|
||||
test('"IWSN" chosen: the service carries the mail although an SMTP server is filled in and the GRAPH_* variables are set', async () => {
|
||||
await asStored(SMTP)
|
||||
await saveForm({ emailMethod: 'relay' })
|
||||
for (const name of GRAPH_ENV) {vi.stubEnv(name, 'x')}
|
||||
expect(await state()).toMatchObject({ methodChosen: true, transport: 'relay' })
|
||||
const before = relayCalls()
|
||||
expect(await send()).toMatchObject({ transport: 'relay' })
|
||||
expect(relayCalls()).toBe(before + 1)
|
||||
expect((await read()).emailMethod).toBe('relay')
|
||||
})
|
||||
|
||||
test('"Own SMTP server" chosen with nothing filled in: the mail fails and says so — nothing goes through the service', async () => {
|
||||
await asStored({})
|
||||
expect((await saveForm({ emailMethod: 'smtp' })).status).toBe(200)
|
||||
expect(await state()).toMatchObject({ methodChosen: true, methodProblem: 'smtp-incomplete', transport: 'smtp' })
|
||||
const before = fake.requests.length
|
||||
expect(await send()).toMatchObject({ code: 'not-configured', sent: false })
|
||||
expect(fake.requests).toHaveLength(before)
|
||||
expect(await status()).toMatchObject({ code: 'smtp-incomplete', state: 'degraded' })
|
||||
// the test e-mail says the same to the admin, and still nothing leaves another way
|
||||
const tested = await api('/ipal/test-email', { body: JSON.stringify({ to: '[email protected]' }), method: 'POST' })
|
||||
expect(tested.status).toBe(502)
|
||||
expect(fake.requests).toHaveLength(before)
|
||||
// the form still shows what was chosen, not what would work
|
||||
expect((await read()).emailMethod).toBe('smtp')
|
||||
})
|
||||
|
||||
test('"Microsoft Graph" chosen on a server without GRAPH_*: fails loudly; neither SMTP (filled in) nor the service is tried', async () => {
|
||||
await asStored(SMTP)
|
||||
await saveForm({ emailMethod: 'graph' })
|
||||
expect(await state()).toMatchObject({ methodChosen: true, methodProblem: 'graph-not-set-up', transport: 'graph' })
|
||||
const before = fake.requests.length
|
||||
expect(await send()).toMatchObject({ code: 'graph-not-set-up', sent: false })
|
||||
expect(fake.requests).toHaveLength(before)
|
||||
expect(await status()).toMatchObject({ code: 'graph-not-set-up', state: 'degraded' }) // not `smtp-error`: SMTP was not tried
|
||||
const tested = await api('/ipal/test-email', { body: JSON.stringify({ to: '[email protected]' }), method: 'POST' })
|
||||
expect(tested.status).toBe(502)
|
||||
expect(((await tested.json()) as { code: string; error: string })).toMatchObject({ code: 'graph-not-set-up' })
|
||||
// with the variables the problem is gone (no send here: that would call Microsoft)
|
||||
for (const name of GRAPH_ENV) {vi.stubEnv(name, 'x')}
|
||||
expect((await state()).methodProblem).toBeUndefined()
|
||||
})
|
||||
|
||||
test('the test e-mail names the method that carried it', async () => {
|
||||
await asStored({ smtpFromName: 'Kancelaria Example' })
|
||||
await saveForm({ emailMethod: 'relay' })
|
||||
const tested = await api('/ipal/test-email', { body: JSON.stringify({ to: '[email protected]' }), method: 'POST' })
|
||||
expect(tested.status).toBe(200)
|
||||
expect(await tested.json()).toMatchObject({ ok: true, transport: 'relay' })
|
||||
})
|
||||
|
||||
test('a save that names nothing about e-mail leaves the choice alone; the old field written alone means what it meant', async () => {
|
||||
await asStored({})
|
||||
await setMailMethod(payload, 'smtp')
|
||||
expect((await api('/globals/site-integrations', { body: JSON.stringify({ ga4MeasurementId: 'G-TEST123' }), method: 'POST' })).status).toBe(200)
|
||||
expect(await getMailMethod(payload)).toBe('smtp')
|
||||
// a script from before 1.17.1 writes `emailTransport`: the order of 1.17.0 applies again
|
||||
expect((await api('/globals/site-integrations', { body: JSON.stringify({ emailTransport: 'graph' }), method: 'POST' })).status).toBe(200)
|
||||
expect(await getMailMethod(payload)).toBeNull()
|
||||
expect((await read()).emailMethod).toBe('relay') // Graph stored, no variables, no SMTP: the service, as in 1.17.0
|
||||
// the Local API, and the building blocks
|
||||
await payload.updateGlobal({ slug: 'site-integrations' as never, data: { emailMethod: 'smtp' } as never })
|
||||
expect(await getMailMethod(payload)).toBe('smtp')
|
||||
await setMailMethod(payload, null)
|
||||
expect(await getMailMethod(payload)).toBeNull()
|
||||
await expect(setMailMethod(payload, 'sendmail' as never)).rejects.toThrow('not a sending method')
|
||||
// a value that is not a method is refused by the field
|
||||
expect((await api('/globals/site-integrations', { body: JSON.stringify({ emailMethod: 'sendmail' }), method: 'POST' })).status).toBe(400)
|
||||
expect(await getMailMethod(payload)).toBeNull()
|
||||
})
|
||||
|
||||
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)
|
||||
// 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')
|
||||
})
|
||||
})
|
||||
|
||||
describe('review M-1, M-2', () => {
|
||||
test('M-1: the plugin\'s own status write never stores a choice — a failed send, then a send that works again', async () => {
|
||||
// an upgraded site with an SMTP server nobody listens on: nothing chosen, SMTP shown
|
||||
await asStored(SMTP)
|
||||
expect(await getMailMethod(payload)).toBeNull()
|
||||
await send().catch(() => undefined)
|
||||
expect((await status())?.state).toBe('degraded') // the status WAS written
|
||||
expect(await getMailMethod(payload)).toBeNull()
|
||||
// the admin empties the SMTP server later: the site goes back to the service, as the old order says
|
||||
await payload.updateGlobal({ slug: 'site-integrations' as never, data: NO_SMTP as never })
|
||||
expect(await getMailMethod(payload)).toBeNull()
|
||||
// (emptying the server cleared the old status; a status written the plugin's way, then a send that works: degraded → ok)
|
||||
await payload.updateGlobal({ slug: 'site-integrations' as never, context: { ipalIntegrationStatus: true }, data: { emailStatus: { code: 'relay-error', state: 'degraded' } } as never })
|
||||
expect(await getMailMethod(payload)).toBeNull()
|
||||
expect(await send()).toMatchObject({ transport: 'relay' })
|
||||
expect((await status())?.state).toBe('ok')
|
||||
expect(await getMailMethod(payload)).toBeNull()
|
||||
expect((await read()).emailMethod).toBe('relay')
|
||||
// and a stored choice survives the same writes
|
||||
await setMailMethod(payload, 'smtp')
|
||||
await send()
|
||||
expect((await status())?.code).toBe('smtp-incomplete')
|
||||
expect(await getMailMethod(payload)).toBe('smtp')
|
||||
await setMailMethod(payload, 'relay')
|
||||
await send()
|
||||
expect(await getMailMethod(payload)).toBe('relay')
|
||||
})
|
||||
|
||||
test('M-2: anything but null or one of the three values is refused with 400, and nothing is stored', async () => {
|
||||
await asStored({})
|
||||
for (const bad of [0, 1, true, ['relay'], { method: 'relay' }, 'sendmail', '', 'RELAY']) {
|
||||
const res = await api('/globals/site-integrations', { body: JSON.stringify({ emailMethod: bad }), method: 'POST' })
|
||||
expect(res.status, JSON.stringify(bad)).toBe(400)
|
||||
await expect(payload.updateGlobal({ slug: 'site-integrations' as never, data: { emailMethod: bad } as never }), JSON.stringify(bad)).rejects.toThrow()
|
||||
}
|
||||
expect(await getMailMethod(payload)).toBeNull()
|
||||
expect((await api('/globals/site-integrations', { body: JSON.stringify({ emailMethod: null }), method: 'POST' })).status).toBe(200)
|
||||
expect((await api('/globals/site-integrations', { body: JSON.stringify({ emailMethod: 'smtp' }), method: 'POST' })).status).toBe(200)
|
||||
expect(await getMailMethod(payload)).toBe('smtp')
|
||||
})
|
||||
})
|
||||
|
||||
describe('resolveMailMethod', () => {
|
||||
const full = { smtpHost: 'smtp.example.com', smtpPassword: 'x', smtpUser: 'u' }
|
||||
const half = { smtpHost: 'smtp.example.com' }
|
||||
const on = { graphEnv: true, relay: true }
|
||||
const off = { graphEnv: false, relay: true }
|
||||
|
||||
test.each([
|
||||
// chosen, settings, env → method, problem
|
||||
['relay', full, on, 'relay', undefined],
|
||||
['relay', {}, off, 'relay', undefined],
|
||||
['smtp', full, on, 'smtp', undefined],
|
||||
['smtp', half, on, 'smtp', 'smtp-incomplete'],
|
||||
['smtp', {}, off, 'smtp', 'smtp-incomplete'],
|
||||
['graph', full, on, 'graph', undefined],
|
||||
['graph', full, off, 'graph', 'graph-not-set-up'],
|
||||
['graph', {}, off, 'graph', 'graph-not-set-up'],
|
||||
] as const)('chosen %s, %j, %j → %s (%s)', (chosen, settings, state, method, problem) => {
|
||||
expect(resolveMailMethod(settings, { ...state, chosen })).toEqual({ explicit: true, method, ...(problem ? { problem } : {}) })
|
||||
})
|
||||
|
||||
test('nothing chosen: the order of 1.17.0, never a problem; "IWSN" chosen with the service switched off counts as nothing chosen', () => {
|
||||
for (const settings of [{}, half, full, { emailTransport: 'graph' as const }, { emailTransport: 'graph' as const, ...full }]) {
|
||||
for (const state of [on, off, { graphEnv: true, relay: false }, { graphEnv: false, relay: false }]) {
|
||||
expect(resolveMailMethod(settings, { ...state, chosen: null })).toEqual({ explicit: false, method: resolveMailTransport(settings, state) })
|
||||
expect(resolveMailMethod(settings, { ...state, chosen: 'relay', relay: false })).toEqual({ explicit: false, method: resolveMailTransport(settings, { ...state, relay: false }) })
|
||||
}
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
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({})
|
||||
const db = payload.db as unknown as { connection?: { collection: (n: string) => { findOne: (q: object) => Promise<null | Record<string, unknown>> } }; tables?: Record<string, Record<string, unknown>> }
|
||||
const raw = async (): Promise<unknown> => {
|
||||
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 () => {
|
||||
const methods = (config: Awaited<ReturnType<typeof makeConfig>>) => {
|
||||
const field = JSON.stringify(config.globals?.find((g) => g.slug === 'site-integrations')?.fields).match(/"name":"emailMethod".*?"options":\[(.*?)\]/)?.[1] ?? ''
|
||||
return [...field.matchAll(/"value":"(\w+)"/g)].map((m) => m[1])
|
||||
}
|
||||
expect(methods(await makeConfig(undefined, 'methodson'))).toEqual(['relay', '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('')
|
||||
})
|
||||
})
|
||||
@@ -340,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',
|
||||
|
||||
Reference in New Issue
Block a user