WIP: sending method as an explicit choice, kept in payload-kv (superseded: the choice moves to a stored field)
Co-Authored-By: Claude Fable 5.2 <[email protected]>
This commit is contained in:
co-authored by
Claude Fable 5.2
parent
68a2555277
commit
c6841a1674
+22
-1
@@ -9,7 +9,7 @@ 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:
|
||||
>
|
||||
@@ -46,6 +46,17 @@ 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. **The first save
|
||||
> of Site integrations stores that choice; 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). So after the upgrade: open the tab, check that the method shown is the one meant, save.
|
||||
> No schema change: the choice is kept in `payload-kv`. A seed or script that set `emailTransport` keeps working
|
||||
> (it leaves the site on the old order); to choose, it writes `emailMethod`.
|
||||
|
||||
### Security
|
||||
- **Write-only secrets cannot be named in a query** (point 1 above). `secretReadAccess`, the field read rule behind
|
||||
@@ -132,6 +143,16 @@ 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 without a schema change: the field `emailMethod` is
|
||||
virtual, the choice is in `payload-kv` (`MAIL_METHOD_KV_KEY`); `emailTransport` stays, hidden.
|
||||
New exports: `getMailMethod`, `setMailMethod`, `resolveMailMethod`, `isMailMethod`, `MAIL_METHODS`,
|
||||
`MAIL_METHOD_KV_KEY`, types `MailMethod`, `ResolvedMailMethod`, `MailMethodProblem`. `pnpm payload generate:types`
|
||||
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).
|
||||
|
||||
+17
-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,20 @@ 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 kept in
|
||||
`payload-kv` (`MAIL_METHOD_KV_KEY`); the panel's field `emailMethod` is virtual, so **no schema change and no
|
||||
migration**. Until somebody chooses (an upgraded site, a new site) the order of 1.17.0 applies and the field shows
|
||||
its result as selected (`resolveMailTransport`, type `MailTransport`): Graph when `emailTransport` is `graph` and
|
||||
`GRAPH_*` is set → SMTP when server, user name and password are filled in → Graph when `GRAPH_*` is set → the mail
|
||||
service → nothing. The first save of Site integrations stores the choice. From code: `getMailMethod`,
|
||||
`setMailMethod(payload, 'relay' | 'smtp' | 'graph' | null)`, `resolveMailMethod` (`ResolvedMailMethod`,
|
||||
`MailMethodProblem`), `MailMethod`, `MAIL_METHODS`, `isMailMethod`; or `updateGlobal` with `emailMethod`. Seeds that
|
||||
set up mail write `emailMethod`, not `emailTransport`. **Verify:** the state block names the method; **Send test
|
||||
e-mail** answers "through IWSN" / "through your SMTP server" / "through Microsoft Graph"; `iapl-doctor --deep`
|
||||
reports no `mail-method` finding after the first save. `mail: { relay: false }` removes the option "IWSN".
|
||||
|
||||
**What the site needs for the mail service** — check each one:
|
||||
|
||||
@@ -1324,8 +1335,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,8 @@ 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 |
|
||||
| the site switched how it sends after a field or a variable changed | nobody has chosen the "Sending method" yet (doctor `mail-method` info): the site still picks by the order of 1.17.0 | Site integrations → E-mail sending: check the method shown, save |
|
||||
| state block: "Not connected yet" on the production domain | no e-mail was sent yet | **Send test e-mail** (the site enrols on its first send) or "Connect again" |
|
||||
| `relay-refused` / "The mail service could not reach this site at …" (cause `callback-failed`) | `unreachable` / `timeout`: firewall, private network, wrong public host in `serverURL`; `redirect`: `trailingSlash: true`, apex → `www`, a language redirect; `status`: route blocked, missing (`mail: { relay: false }`?) or another `routes.api`; `confirmation`: a proxy rewrites the answer | `curl -i -X POST https://<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`, virtual; `getMailMethod` / `setMailMethod`) | nobody has chosen: the order of 1.17.0, shown as selected | `relay` (IWSN), `smtp`, `graph` (deprecated): what is chosen is what is used, no fallback; kept in `payload-kv`, no schema change |
|
||||
| `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. Save the tab once so the choice is stored. 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,19 @@ 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. No schema change, no migration, no import-map change; `pnpm payload generate:types` gives a diff (the virtual field
|
||||
`emailMethod`): run it and commit.
|
||||
2. After the deploy open Site integrations → E-mail sending. "Sending method" shows the method the site sends through
|
||||
today as selected: **IWSN (built-in)** (no SMTP server), **Own SMTP server**, or **Microsoft Graph (deprecated)**
|
||||
(`GRAPH_*` on the server). Check it is the one meant, **save**, send a test e-mail: the answer names the method.
|
||||
Until that save the site keeps the order of 1.17.0 and `iapl-doctor --deep` notes it (`mail-method`, info).
|
||||
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). 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 |
|
||||
|
||||
+60
-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,64 @@ 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 Payload's key-value store (`payload-kv`, key `MAIL_METHOD_KV_KEY`), not in a
|
||||
column: the panel's field `emailMethod` is **virtual**. So **no SQL schema changes and no migration exists** —
|
||||
a third value in the stored select `emailTransport` (`smtp` / `graph` since 1.6) would have changed the Postgres
|
||||
enum, and could still not tell "SMTP was chosen" from the `smtp` every site has stored since before there was a
|
||||
choice. `emailTransport` stays, hidden in the panel, and follows the choice where it can say it (`graph`, else
|
||||
`smtp`). From code: `getMailMethod(payload)` (`'relay' | 'smtp' | 'graph' | null`), `setMailMethod(payload, method)`
|
||||
(a seed or a deploy script; `null` = nobody has chosen), `payload.updateGlobal({ slug: 'site-integrations', data: {
|
||||
emailMethod: 'smtp' } })`, `resolveMailMethod(settings, { chosen, graphEnv, relay })` →
|
||||
`{ method, explicit, problem? }` (types `MailMethod`, `ResolvedMailMethod`, `MailMethodProblem`; `MAIL_METHODS`,
|
||||
`isMailMethod`).
|
||||
|
||||
**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 |
|
||||
|
||||
**The first save of Site integrations stores what the form shows** (the form always sends the field), and from
|
||||
then on the method is fixed. The state block says "Nobody has chosen the sending method yet, so the site picked
|
||||
this one. Save this page to keep it." until then, and the doctor's deep run notes it (`mail-method`, info). 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 +504,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 +626,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` (virtual: `relay` = IWSN / `smtp` / `graph` = deprecated; the choice is kept in `payload-kv`), `emailTransport` (hidden; the stored field of 1.6 – 1.17.0), `smtpHost`, `smtpPort`, `smtpUser`, `smtpPassword`, `smtpFromAddress`, `smtpFromName`, test button, hidden `emailStatus` + banner |
|
||||
| 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,8 @@ 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 |
|
||||
| the site switched how it sends after a field or a variable changed | nobody has chosen the "Sending method" yet (doctor `mail-method` info): the site still picks by the order of 1.17.0 | Site integrations → E-mail sending: check the method shown, save |
|
||||
| state block: "Not connected yet" on the production domain | no e-mail was sent yet | **Send test e-mail** (the site enrols on its first send) or "Connect again" |
|
||||
| `relay-refused` / "The mail service could not reach this site at …" (cause `callback-failed`) | `unreachable` / `timeout`: firewall, private network, wrong public host in `serverURL`; `redirect`: `trailingSlash: true`, apex → `www`, a language redirect; `status`: route blocked, missing (`mail: { relay: false }`?) or another `routes.api`; `confirmation`: a proxy rewrites the answer | `curl -i -X POST https://<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`, virtual; `getMailMethod` / `setMailMethod`) | nobody has chosen: the order of 1.17.0, shown as selected | `relay` (IWSN), `smtp`, `graph` (deprecated): what is chosen is what is used, no fallback; kept in `payload-kv`, no schema change |
|
||||
| `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. Save the tab once so the choice is stored. 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,19 @@ 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. No schema change, no migration, no import-map change; `pnpm payload generate:types` gives a diff (the virtual field
|
||||
`emailMethod`): run it and commit.
|
||||
2. After the deploy open Site integrations → E-mail sending. "Sending method" shows the method the site sends through
|
||||
today as selected: **IWSN (built-in)** (no SMTP server), **Own SMTP server**, or **Microsoft Graph (deprecated)**
|
||||
(`GRAPH_*` on the server). Check it is the one meant, **save**, send a test e-mail: the answer names the method.
|
||||
Until that save the site keeps the order of 1.17.0 and `iapl-doctor --deep` notes it (`mail-method`, info).
|
||||
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()) {
|
||||
|
||||
@@ -11,6 +11,8 @@ type State = {
|
||||
accessKeyField?: boolean
|
||||
error?: string
|
||||
message?: string
|
||||
methodChosen?: boolean
|
||||
methodProblem?: 'graph-not-set-up' | 'smtp-incomplete'
|
||||
ok?: boolean
|
||||
refusalText?: string
|
||||
relay?: {
|
||||
@@ -104,6 +106,11 @@ export const MailRelayStatus = () => {
|
||||
: state.transport === 'graph' ? text('mailRelayTransportGraph')
|
||||
: text(relay ? 'mailRelayTransportNone' : 'mailRelayOff')}
|
||||
</p>
|
||||
{state.methodProblem ? (
|
||||
<p 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,45 @@
|
||||
import type { Condition, Field } from 'payload'
|
||||
import type { BasePayload, Condition, Field } from 'payload'
|
||||
|
||||
import { graphAvailable, resolveMailMethod } from '../../../modules/email/mailAdapter.js'
|
||||
import { getMailMethod, type MailMethod } 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'
|
||||
|
||||
/**
|
||||
* What the "Sending method" field shows: the chosen method, or — while nobody has chosen — the method the
|
||||
* order of 1.17.0 picks for the present settings (so an upgraded site sees what it sends through today).
|
||||
*/
|
||||
export async function shownMailMethod(payload: Pick<BasePayload, 'kv'>, settings: Parameters<typeof resolveMailMethod>[0], relay: boolean): Promise<MailMethod> {
|
||||
const { method } = resolveMailMethod(settings, { chosen: await getMailMethod(payload), 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 VIRTUAL field: it has no column, so no SQL schema changes. The
|
||||
* choice is kept in the key-value store (modules/email/method.ts) by the global's hooks. `emailTransport`
|
||||
* — the stored field of 1.6 to 1.17.0, values `smtp` / `graph` — stays as it was, hidden in the panel.
|
||||
*/
|
||||
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 +48,36 @@ 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.',
|
||||
},
|
||||
},
|
||||
hooks: {
|
||||
afterRead: [({ req, siblingData }) => shownMailMethod(req.payload, siblingData ?? {}, 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' },
|
||||
...(relay ? [{ label: { en: `${IWSN} (built-in)`, pl: `${IWSN} (wbudowany)` }, value: 'relay' }] : []),
|
||||
{ label: relay ? { en: 'Own SMTP server', pl: 'Własny serwer SMTP' } : { en: 'SMTP server', pl: 'Serwer SMTP' }, value: 'smtp' },
|
||||
// Works only when the administrator has set Graph up on the server (GRAPH_*); chosen without it, e-mails fail and say so.
|
||||
{ label: { en: 'Microsoft Graph (deprecated)', pl: 'Microsoft Graph (wycofywany)' }, value: 'graph' },
|
||||
],
|
||||
virtual: true,
|
||||
},
|
||||
{
|
||||
// The stored field of 1.6 – 1.17.0. Kept with its two values (a third would change the Postgres enum) and
|
||||
// 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 +129,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, setMailMethod } 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,13 +90,46 @@ export function buildSiteIntegrations({
|
||||
hooks: {
|
||||
// a restore answers with the version document: the secrets are masked there too
|
||||
...(writeOnly ? { afterRead: [maskSecretsOnRestore] } : {}),
|
||||
afterChange: [
|
||||
async ({ context, doc, req }) => {
|
||||
if (isMailMethod(context?.iaplMailMethod)) {
|
||||
await setMailMethod(req.payload, context.iaplMailMethod)
|
||||
// (the answer was read before this write: it must show what was just chosen)
|
||||
if (doc && typeof doc === 'object') {(doc as Record<string, unknown>).emailMethod = context.iaplMailMethod}
|
||||
} else if (context?.iaplMailMethod === null) {
|
||||
await setMailMethod(req.payload, null)
|
||||
}
|
||||
return doc
|
||||
},
|
||||
],
|
||||
// What the caller sent for the sending method, before Payload merges the stored document into the data.
|
||||
beforeChange: [
|
||||
// Keys edited in the panel → clear that integration's old status, so a stale
|
||||
// "not working" banner doesn't linger until the next form submission.
|
||||
({ context, data, originalDoc }) => {
|
||||
async ({ context, data, originalDoc, req }) => {
|
||||
if (context?.ipalIntegrationStatus || !data) {return data}
|
||||
const changed = (k: string) => k in data && data[k] !== originalDoc?.[k]
|
||||
const cleared = { checkedAt: null, code: null, message: null, since: null, state: null }
|
||||
// "Sending method" (the virtual field `emailMethod`): the choice is written to the key-value store
|
||||
// once the global is saved (afterChange). The stored `emailTransport` follows where it can say it.
|
||||
// (`data` is merged with the stored document by now; what the caller really sent was noted before the
|
||||
// merge — beforeOperation below. Without that note: a value that differs from the stored one was sent.)
|
||||
const noted = context?.iaplMailSent as { method?: unknown; transport?: boolean } | undefined
|
||||
const sent = noted ? noted.method : data.emailMethod !== originalDoc?.emailMethod ? data.emailMethod : undefined
|
||||
// (a virtual field's value is not checked against its options by Payload)
|
||||
if (sent !== undefined && sent !== null && !(isMailMethod(sent) && (sent !== 'relay' || mailRelay))) {
|
||||
throw new ValidationError({ errors: [{ message: 'This is not a sending method.', path: 'emailMethod' }], global: 'site-integrations' }, req.t)
|
||||
}
|
||||
if (isMailMethod(sent)) {
|
||||
data.emailMethod = sent
|
||||
const before = await shownMailMethod(req.payload, (originalDoc ?? {}) as never, mailRelay).catch(() => null)
|
||||
if (before !== data.emailMethod) {data.emailStatus = cleared}
|
||||
context.iaplMailMethod = data.emailMethod
|
||||
data.emailTransport = data.emailMethod === 'graph' ? 'graph' : 'smtp'
|
||||
} else if ((noted ? noted.transport : true) && changed('emailTransport')) {
|
||||
// written the old way (a script from before 1.17.1): it means what it meant — the order of 1.17.0
|
||||
context.iaplMailMethod = null
|
||||
}
|
||||
if (changed('turnstileSecretKey') || changed('turnstileSiteKey')) {data.turnstileStatus = cleared}
|
||||
if (Object.keys(data).some((k) => (k === 'emailTransport' || k.startsWith('smtp')) && changed(k))) {
|
||||
data.emailStatus = cleared
|
||||
@@ -101,6 +137,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 = { method: data.emailMethod ?? undefined, transport: 'emailTransport' in data }
|
||||
}
|
||||
return args
|
||||
},
|
||||
],
|
||||
},
|
||||
label: { en: 'Site integrations', pl: 'Integracje' },
|
||||
}
|
||||
|
||||
+5
-2
@@ -251,8 +251,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 (kept in payload-kv, so no SQL schema changes).
|
||||
export { getMailMethod, isMailMethod, MAIL_METHOD_KV_KEY, MAIL_METHODS, setMailMethod } 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.
|
||||
|
||||
@@ -11,6 +11,9 @@ 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.',
|
||||
mailMethodNotChosen: 'Nobody has chosen the sending method yet, so the site picked this one. Save this page to keep it.',
|
||||
mailMethodSmtpIncomplete: 'Your SMTP server is chosen, but its settings are incomplete. E-mails are not sent. Fill in server, user name and password.',
|
||||
mailRelayCheck: 'Check now',
|
||||
mailRelayConnect: 'Connect again',
|
||||
mailRelayConnected: `The site is connected to ${IWSN}.`,
|
||||
@@ -84,6 +87,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 +124,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 +137,9 @@ 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.',
|
||||
mailMethodNotChosen: 'Nikt jeszcze nie wybrał sposobu wysyłki, więc witryna dobrała ten. Zapisz tę stronę, aby go zachować.',
|
||||
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.',
|
||||
mailRelayCheck: 'Sprawdź teraz',
|
||||
mailRelayConnect: 'Połącz ponownie',
|
||||
mailRelayConnected: `Witryna jest połączona z ${IWSN}.`,
|
||||
@@ -201,6 +210,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 +246,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,27 @@ 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.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: 'open Site integrations → E-mail sending, check "Sending method" and save: from then on the site sends that way only', message: `nobody has chosen the sending method yet: the site picks one from what is filled in (now: ${mail.transport === 'relay' ? 'the built-in service' : mail.transport === 'smtp' ? 'the SMTP server' : 'Microsoft Graph'}), and would switch by itself if that changed`, 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,7 @@ 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,
|
||||
relay: state.relay
|
||||
? {
|
||||
connected: state.relay.connected,
|
||||
@@ -84,6 +85,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,10 @@ 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
|
||||
/** 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`. */
|
||||
|
||||
@@ -6,6 +6,7 @@ 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 { getMailMethod, type MailMethod } 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'
|
||||
@@ -46,6 +47,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 (`getMailMethod`): 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 +164,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 = async (settings: TransportIntegrations) => resolveMailMethod(settings, { chosen: await getMailMethod(payload), graphEnv: graphAvailable(), relay: Boolean(relayOptions()) })
|
||||
|
||||
const attachmentLimit = async (): Promise<null | number> => {
|
||||
const settings = await getSiteIntegrations<TransportIntegrations>(payload)
|
||||
const transport = transportOf(settings)
|
||||
const transport = (await 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}
|
||||
@@ -168,21 +195,30 @@ export const mailAdapter =
|
||||
const settings = await getSiteIntegrations<TransportIntegrations>(payload)
|
||||
const choice = settings.emailTransport ?? 'smtp'
|
||||
const previous = settings[STATUS_FIELD]
|
||||
const chosen = transportOf(settings)
|
||||
const resolved = await 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 +242,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,49 @@
|
||||
import type { BasePayload } from 'payload'
|
||||
|
||||
/**
|
||||
* The sending method an admin chose in Site integrations → E-mail sending ("Sending method"):
|
||||
* the built-in service (IWSN), the client's own SMTP server, or Microsoft Graph (deprecated).
|
||||
*
|
||||
* Where it is stored: in Payload's key-value store (`payload-kv`), under `MAIL_METHOD_KV_KEY` — not in
|
||||
* a column of the global. The global's stored field `emailTransport` has two values since 1.6 (`smtp`,
|
||||
* `graph`); a third would change the Postgres enum and ask every SQL project for a migration, and it
|
||||
* still could not tell "SMTP was chosen" from the `smtp` that every site has stored since before the
|
||||
* choice existed. So the panel's field (`emailMethod`) is virtual, and the choice lives here.
|
||||
*
|
||||
* No entry = nobody has chosen yet (a site upgraded from 1.17.0 or older, a new site): the method follows
|
||||
* the order of 1.17.0 (`resolveMailTransport`) and the panel shows it as selected. The first save of Site
|
||||
* integrations — or `setMailMethod()` — writes the choice; from then on what is chosen is what is used.
|
||||
*/
|
||||
export type MailMethod = 'graph' | 'relay' | 'smtp'
|
||||
|
||||
export const MAIL_METHODS: readonly MailMethod[] = ['relay', 'smtp', 'graph']
|
||||
|
||||
export const MAIL_METHOD_KV_KEY = 'iapl:mail-method'
|
||||
|
||||
export const isMailMethod = (value: unknown): value is MailMethod => typeof value === 'string' && (MAIL_METHODS as readonly string[]).includes(value)
|
||||
|
||||
type Kv = { delete?: (key: string) => Promise<unknown>; get?: (key: string) => Promise<unknown>; set?: (key: string, value: object) => Promise<unknown> }
|
||||
const kvOf = (payload: Pick<BasePayload, 'kv'>): Kv => ((payload as { kv?: Kv }).kv ?? {})
|
||||
|
||||
/** The chosen method, or null when nobody has chosen yet. Reads only. */
|
||||
export async function getMailMethod(payload: Pick<BasePayload, 'kv'>): Promise<MailMethod | null> {
|
||||
const kv = kvOf(payload)
|
||||
if (typeof kv.get !== 'function') {return null}
|
||||
const stored = (await kv.get(MAIL_METHOD_KV_KEY)) as { method?: unknown } | null
|
||||
return isMailMethod(stored?.method) ? stored.method : null
|
||||
}
|
||||
|
||||
/**
|
||||
* Chooses the method (a seed, a deploy script; the panel does it on save). `null` = nobody has chosen:
|
||||
* the order of 1.17.0 applies again.
|
||||
*/
|
||||
export async function setMailMethod(payload: Pick<BasePayload, 'kv'>, method: MailMethod | null): Promise<void> {
|
||||
const kv = kvOf(payload)
|
||||
if (method === null) {
|
||||
await kv.delete?.(MAIL_METHOD_KV_KEY)
|
||||
return
|
||||
}
|
||||
if (!isMailMethod(method)) {throw new Error(`[iapl] setMailMethod: "${String(method)}" is not a sending method (relay, smtp, graph).`)}
|
||||
if (typeof kv.set !== 'function') {throw new Error('[iapl] setMailMethod: this Payload has no key-value store (payload.kv).')}
|
||||
await kv.set(MAIL_METHOD_KV_KEY, { at: new Date().toISOString(), method })
|
||||
}
|
||||
@@ -6,7 +6,8 @@ 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 { graphAvailable, type MailMethodProblem, type MailTransport, resolveMailMethod, smtpIncomplete } from '../mailAdapter.js'
|
||||
import { getMailMethod } 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'
|
||||
@@ -29,6 +30,13 @@ export type MailPanelState = {
|
||||
accessKeyField?: boolean
|
||||
/** The address the service calls this site back at. */
|
||||
confirmUrl?: string
|
||||
/**
|
||||
* 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
|
||||
/** 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. */
|
||||
@@ -60,7 +68,8 @@ export async function mailPanelState(req: Pick<PayloadRequest, 'payload'>, own:
|
||||
const { payload } = req
|
||||
const settings = await getSiteIntegrations<Settings>(payload)
|
||||
const options = resolveRelayOptions(payload, own)
|
||||
const transport = resolveMailTransport(settings, { graphEnv: graphAvailable(), relay: Boolean(options) })
|
||||
const method = resolveMailMethod(settings, { chosen: await getMailMethod(payload), 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 +97,14 @@ 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}` } : {}),
|
||||
methodChosen: method.explicit,
|
||||
...(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
|
||||
|
||||
+18
-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,23 @@ 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].fix).toContain('save')
|
||||
expect(await find({ methodChosen: true })).toEqual([])
|
||||
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,307 @@
|
||||
/**
|
||||
* "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;
|
||||
* - no stored field was added: the panel's field is virtual, the choice is in the key-value store.
|
||||
*/
|
||||
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, MAIL_METHOD_KV_KEY, 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: { emailStatus: { checkedAt: null, code: null, message: null, since: null, state: null }, emailTransport: 'smtp', ...NO_SMTP, ...data } as never })
|
||||
await payload.kv.delete(MAIL_METHOD_KV_KEY)
|
||||
}
|
||||
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()
|
||||
expect(await payload.kv.get(MAIL_METHOD_KV_KEY)).toBeNull()
|
||||
})
|
||||
|
||||
test('a site with its SMTP server filled in: "Own SMTP server" is selected, the service is not contacted', async () => {
|
||||
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 payload.kv.delete(MAIL_METHOD_KV_KEY)
|
||||
await asStored({})
|
||||
expect((await read()).emailMethod).toBe('relay')
|
||||
})
|
||||
})
|
||||
|
||||
describe('the choice: what is chosen is what is used', () => {
|
||||
test('the first save of the panel\'s form stores what the form shows; the answer shows it; the stored field of 1.17.0 follows', async () => {
|
||||
await asStored({})
|
||||
const saved = await saveForm({ smtpFromName: 'Kancelaria Example' })
|
||||
expect(saved.status).toBe(200)
|
||||
expect(((await saved.json()) as { result: { emailMethod: string } }).result.emailMethod).toBe('relay')
|
||||
expect(await getMailMethod(payload)).toBe('relay')
|
||||
expect(await state()).toMatchObject({ methodChosen: true, transport: 'relay' })
|
||||
// a choice changed in the form
|
||||
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')
|
||||
expect((await read()).emailMethod).toBe('graph')
|
||||
await saveForm({ emailMethod: 'smtp' })
|
||||
expect(await read()).toMatchObject({ emailMethod: 'smtp', emailTransport: 'smtp' })
|
||||
})
|
||||
|
||||
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; it is not in the key-value store\'s REST', async () => {
|
||||
expect((await fetch(`${server.url}/api/globals/site-integrations`, { body: JSON.stringify({ emailMethod: 'smtp' }), headers: { 'content-type': 'application/json' }, method: 'POST' })).status).toBeGreaterThanOrEqual(401)
|
||||
expect((await api('/payload-kv')).status).toBeGreaterThanOrEqual(400)
|
||||
})
|
||||
})
|
||||
|
||||
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('no stored field was added', () => {
|
||||
test('`emailMethod` is virtual: the SQL table has no column for it; the document in the database does not hold it', async () => {
|
||||
await asStored({})
|
||||
await saveForm({ emailMethod: 'smtp' })
|
||||
const db = payload.db as unknown as { collections?: unknown; connection?: { collection: (n: string) => { findOne: (q: object) => Promise<null | Record<string, unknown>> } }; name?: string; tables?: Record<string, Record<string, unknown>> }
|
||||
if (db.tables) {
|
||||
const table = db.tables.site_integrations
|
||||
expect(table).toBeTruthy()
|
||||
const columns = Object.keys(table).map((c) => c.toLowerCase())
|
||||
expect(columns).toContain('emailtransport')
|
||||
expect(columns.filter((c) => c.includes('method'))).toEqual([])
|
||||
} else {
|
||||
const raw = await db.connection!.collection('globals').findOne({ globalType: 'site-integrations' })
|
||||
expect(raw).toMatchObject({ emailTransport: 'smtp' })
|
||||
expect(raw).not.toHaveProperty('emailMethod')
|
||||
}
|
||||
await setMailMethod(payload, null)
|
||||
})
|
||||
|
||||
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'])
|
||||
expect(methods(await makeConfig({ relay: false }, 'methodsoff'))).toEqual(['smtp', 'graph'])
|
||||
})
|
||||
})
|
||||
@@ -313,7 +313,8 @@ describe('switched off, and what did not change', () => {
|
||||
const endpoints = (config: SanitizedConfig) => (config.endpoints ?? []).map((e) => `${e.method} ${e.path}`)
|
||||
const stored = (fields: Field[]): string[] =>
|
||||
fields.flatMap((f) => {
|
||||
if (f.type === 'ui') {return []}
|
||||
// (a virtual field has no column and no stored value: "Sending method", whose choice is in the key-value store)
|
||||
if (f.type === 'ui' || ('virtual' in f && f.virtual)) {return []}
|
||||
if (f.type === 'tabs') {return f.tabs.flatMap((t) => stored(t.fields))}
|
||||
const own = 'name' in f && f.name ? [`${f.name}:${f.type}${f.type === 'select' ? `(${(f.options as { value: string }[]).map((o) => (typeof o === 'string' ? o : o.value)).join('|')})` : ''}`] : []
|
||||
return 'fields' in f && Array.isArray(f.fields) ? [...own, ...stored(f.fields).map((n) => ('name' in f && f.name ? `${f.name}.${n}` : n))] : own
|
||||
|
||||
Reference in New Issue
Block a user