Mail relay: state block without an import-map entry, e2e on the reference site, sharper failure reports
- the state block is rendered by IntegrationStatusBanner (no new admin component: generate:importmap gives no diff) - reference site: e2e/mail-relay.spec.ts with a fixture and setup script; e2e:built runs it with both bundlers - a failed enrolment is reported as what it was; the service's own refusal after a fresh enrolment - a message keeps its key after any failure that is not final - a local site is shown as refused in the panel before any e-mail Co-Authored-By: Claude Fable 5.2 <[email protected]>
This commit is contained in:
co-authored by
Claude Fable 5.2
parent
dd3792cbc7
commit
2cceceffd0
+5
-5
@@ -13,7 +13,7 @@ once there are more than 20.
|
||||
|
||||
> **Read before upgrading.** Nothing has to change in a project. The plugin's name is now **IAPL** (Intecion
|
||||
> Advanced Payload Library); it was ipal-kit. **The package is still `@intecion/ipal-kit`**, and every name a
|
||||
> project uses keeps working. The rename changes no option, schema, migration or import map. This release also carries the
|
||||
> project uses keeps working. No schema, migration or import-map change. This release also carries the
|
||||
> security follow-ups listed under 1.16.8 below (prepared, not released on their own).
|
||||
>
|
||||
> **E-mail — read which of three cases the site is.** A site with **no SMTP server in Site integrations and no
|
||||
@@ -22,14 +22,14 @@ once there are more than 20.
|
||||
> host and the plugin version, receives its own token through a new public route, and sends from
|
||||
> `[email protected]` under the panel's "Sender name". **A site with SMTP filled in is not
|
||||
> affected and contacts nothing. A site on Microsoft Graph keeps working and prints one deprecation warning at
|
||||
> start.** Each new behaviour has its opt-out (table below). No schema change, no migration; one import-map entry.
|
||||
> start.** Each new behaviour has its opt-out (table below).
|
||||
> **The service must be live for the first case: until Intecion announces it, such a site reports
|
||||
> `relay-unreachable` and sends nothing, as it sent nothing before.**
|
||||
|
||||
### Requires project changes
|
||||
- **Every site: `pnpm payload generate:importmap`, commit.** The e-mail tab of Site integrations has a new block
|
||||
("How e-mails are sent", component `@intecion/ipal-kit/admin#MailRelayStatus`); with a stale import map the block is
|
||||
blank. Nothing else changes in the panel's data: no field was added, "Sending method" keeps its two stored values.
|
||||
- **Nothing has to be run.** The e-mail tab of Site integrations has a new block ("How e-mails are sent"); it is
|
||||
rendered by the status banner already in every import map, so `generate:importmap` gives no diff. No field was
|
||||
added; "Sending method" keeps its two stored values.
|
||||
- **What changes for an existing site on upgrade — e-mail:**
|
||||
|
||||
| Site today | After the upgrade | Opt-out |
|
||||
|
||||
+2
-2
@@ -1262,8 +1262,8 @@ export default buildConfig({
|
||||
})
|
||||
```
|
||||
|
||||
Then `pnpm generate:importmap` (the e-mail tab has a new component, `@intecion/ipal-kit/admin#MailRelayStatus`).
|
||||
No env variable, no key, no field to fill in. **Do not** add `nodemailer`, `resend`, an `api/send` route or a
|
||||
No env variable, no key, no field to fill in, no import-map change (the tab's state block rides on the status
|
||||
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
|
||||
|
||||
@@ -114,7 +114,6 @@ through this procedure. Ask only when you are missing something you cannot get y
|
||||
| replies to the site's mail are lost | "Sender address" is empty: the service's own address has no mailbox | fill it in (doctor: `mail-reply-address`) |
|
||||
| the site enrols again and again (`reverify` in the log) | requests leave from many changing addresses (serverless, a pool of egress addresses) | Intecion raises the site's limit of server addresses, or SMTP |
|
||||
| start log: "Microsoft Graph as the e-mail transport is deprecated" | `GRAPH_*` is set | email.md "Moving off Microsoft Graph"; silence only: `mail: { graphDeprecationWarning: false }` |
|
||||
| the e-mail tab shows a blank where "How e-mails are sent" should be | stale import map | `pnpm payload generate:importmap`, commit, redeploy |
|
||||
| old email sender | mail client cache | check the raw headers |
|
||||
| form: `unknown_fields` | field outside the definition (honeypot not removed) | `iapl-form` → actions.ts |
|
||||
| an account logs in to `/admin` and sees "Unauthorized" (its API calls still work) | `accounts.panelRole`: the panel opens for `editor` and above; the account has only `user`, or no role | give it `editor` (an admin edits the account), or `accounts: { panelRole: 'user' }`; nobody can get in: a script with the Local API sets `roles: ['admin']`, or `accounts: { panelRole: false }` + redeploy |
|
||||
|
||||
@@ -535,8 +535,8 @@ Every name from before keeps working: `ipalKit()` and the other old exports, the
|
||||
`ipal-doctor.json`, `ipal-audit-skip`, the old pointer block. The package is still `@intecion/ipal-kit`; routes
|
||||
`/api/ipal/*`, `--ipal-*` tokens, `data-ipal` hooks and the cookie `ipal_vid` are unchanged (AGENT.md "Names: IAPL and
|
||||
ipal-kit"). **Do not rename anything in the project unless the owner asks.**
|
||||
1. Update the package, `pnpm install`. The rename itself changes no option, schema, migration or import map; the mail
|
||||
service of the same release adds one admin component — see the next block.
|
||||
1. Update the package, `pnpm install`. No option, schema, migration or import-map change (`pnpm payload generate:importmap`
|
||||
gives no diff).
|
||||
2. Refresh the skills: `pnpm exec iapl-skills` (the project's `ipal:skills` script, where it has one, runs the same program). It
|
||||
installs `iapl-*`, removes the 16 old `ipal-*` folders by name (a skill of the project's own named `ipal-…` stays),
|
||||
and rewrites the pointer block in `AGENTS.md` in place. Commit the result. Old skill names written by hand in
|
||||
@@ -553,10 +553,9 @@ ipal-kit"). **Do not rename anything in the project unless the owner asks.**
|
||||
builds; the panel opens; the old commands (`pnpm exec ipal-doctor`) still run.
|
||||
|
||||
**→ 1.17.0, e-mail (the Intecion mail service is the default transport; Microsoft Graph deprecated; CHANGELOG 1.17.0;
|
||||
PROGRAMISTA §6, item 73; email.md; AGENT.md §7.2) — one command for every site, then read which case the site is:**
|
||||
1. **Every site:** `pnpm payload generate:importmap` and commit — the e-mail tab has a new component
|
||||
(`@intecion/ipal-kit/admin#MailRelayStatus`); with a stale map the block "How e-mails are sent" is blank. No schema
|
||||
change, no migration.
|
||||
PROGRAMISTA §6, item 73; email.md; AGENT.md §7.2) — nothing to run; read which case the site is:**
|
||||
1. **Every site:** no schema change, no migration, no import-map change. The e-mail tab gains the block "How e-mails
|
||||
are sent" and new wording ("Automatic", "Own SMTP server").
|
||||
2. **Which case** — Site integrations → E-mail sending, and the Coolify env:
|
||||
- **SMTP filled in** (server, user name, password): nothing changes, the site contacts nobody. Done.
|
||||
- **`GRAPH_*` set:** mail as before; one deprecation warning per start, doctor warning `mail-graph-deprecated`.
|
||||
|
||||
@@ -680,7 +680,7 @@ Do one item at a time, build, check. Order by importance:
|
||||
| 70 | **1.16.7** — `next build --webpack`: `'server-only' cannot be imported from a Client Component module`, from a `'use client'` file that imports `isAdmin`, `isEditor` or `hasMinimumRole` | Import them from `@intecion/ipal-kit/client` in client components, keep the second argument (`isAdmin(user, config)`); `import type` may stay on the main entry | CHANGELOG 1.16.7, access.md |
|
||||
| 71 | **1.16.8 — security** — a site built with Turbopack (`next build` without `--webpack`) serves `/_next/static/media/package.<hash>.json`; or the project has a staff collection of its own without access rules; or a plugin listed after iapl copies a staff collection or sets `admin.user`; or the start log says `No staff account holds the role "admin", so NOBODY can …` | Update, `pnpm exec iapl-skills`, `rm -rf .next`, rebuild; no option, schema, migration or import map. Turbopack: `find .next/static -name 'package*.json'` empty, purge a CDN. Own staff collection: a `roles` list that can hold `editor` / `admin` → only an admin manages its accounts (write own rules otherwise; one account must hold `admin`); a single select with only `user` / `editor` / `admin` → its accounts manage each other again (own rules if your code goes by the value). A copy: `access.update: adminOrSelfIn('copy')`, or `custom.ipal.accountRules: false` | CHANGELOG 1.16.8, access.md "Account rules" |
|
||||
| 72 | **1.17.0 — the plugin is called IAPL** — you see `iapl()`, `iapl-doctor`, `IAPL_IP_HEADER`, `iapl-doctor.json`, `[iapl]` in docs and logs and wonder whether the project must change | No. Every old name works through 1.x (`ipalKit`, `ipal-*` commands, `IPAL_*` env, `ipal-doctor.json`, `ipal-audit-skip`, the old pointer block); the package is still `@intecion/ipal-kit`. Run `pnpm exec iapl-skills` (or the project's `ipal:skills` script) and commit; change a log filter on `[ipal]` to `[iapl]`. Rename the rest only when the owner asks (`iapl-upgrade` "→ 1.17.0", AGENT.md "Names: IAPL and ipal-kit"). Never set `storageNames: 'iapl'` on an existing site |
|
||||
| 73 | **1.17.0 — e-mail: the Intecion mail service is the default transport** — a site with no SMTP server in the panel and no `GRAPH_*` starts sending through the service after the upgrade (an outbound call with its host; a new public route `POST /api/iapl/mail-relay/confirm`; mail from `[email protected]`); the e-mail tab is blank where "How e-mails are sent" should be; a Graph site warns at start | `pnpm payload generate:importmap` and commit (new component `MailRelayStatus`). SMTP site: nothing else. Graph site: nothing now — deprecated, move when the owner says. Site with neither: agree it with the owner; `serverURL` = the public address, "Sender address" filled in, the host listed by Intecion; or `iapl({ mail: { relay: false } })` to keep the old behaviour | `iapl-upgrade` "→ 1.17.0, e-mail", AGENT.md §7.2, email.md |
|
||||
| 73 | **1.17.0 — e-mail: the Intecion mail service is the default transport** — a site with no SMTP server in the panel and no `GRAPH_*` starts sending through the service after the upgrade (an outbound call with its host; a new public route `POST /api/iapl/mail-relay/confirm`; mail from `[email protected]`); a Graph site warns at start | Nothing to run (no schema, migration or import-map change). SMTP site: nothing. Graph site: nothing now — deprecated, move when the owner says. Site with neither: agree it with the owner; `serverURL` = the public address, "Sender address" filled in, the host listed by Intecion; or `iapl({ mail: { relay: false } })` to keep the old behaviour | `iapl-upgrade` "→ 1.17.0, e-mail", AGENT.md §7.2, email.md |
|
||||
|
||||
After updating the package: `pnpm exec iapl-skills` (new skill versions), `pnpm payload generate:importmap`, `rm -rf .next`, restart dev, grep for the new symbol in
|
||||
`node_modules/@intecion/ipal-kit/dist`.
|
||||
|
||||
+2
-2
@@ -193,8 +193,8 @@ await runWithMailKind('account', () => sendWelcomeMails(payload, user))
|
||||
|
||||
### The state block in the panel
|
||||
|
||||
Site integrations → E-mail sending starts with "How e-mails are sent" (component `MailRelayStatus`, import-map
|
||||
entry `@intecion/ipal-kit/admin#MailRelayStatus` — **run `payload generate:importmap` after upgrading**): the
|
||||
Site integrations → E-mail sending starts with "How e-mails are sent" (component `MailRelayStatus` from `/admin`,
|
||||
rendered by the tab's status banner — **no import-map entry of its own, so nothing to regenerate**): the
|
||||
transport in effect; for the mail service the state (connected, waiting for approval, stopped, not connected and
|
||||
why), the address mail leaves from, where replies go, what is left of the hour and the day, and a sender name the
|
||||
service replaced. Buttons: **Check now**, **Connect again**, **Disconnect**, **Enter an access key**.
|
||||
|
||||
@@ -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" (`mailRelayStatus`, a `ui` field — 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 }`), `emailTransport` (`smtp` = "Automatic" / `graph` = deprecated), `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 |
|
||||
|
||||
|
||||
@@ -97,7 +97,23 @@ 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 transport / empty Emails tab | email.md; Send test in the panel |
|
||||
| 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 |
|
||||
| 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` |
|
||||
| `relay-pending` / "waiting for approval" | the host is not on Intecion's list | Intecion approves it on the service; nothing to change on the site; the same token then works |
|
||||
| `relay-suspended` | Intecion stopped the site (abuse, a flood from a form) | contact Intecion; fill in SMTP meanwhile |
|
||||
| `relay-disconnected` | an admin pressed "Disconnect" | "Connect again", or SMTP |
|
||||
| `relay-quota` | the site's hour or day is used up (30 / 200 by default), more than 10 recipients, more than 10 confirmations to one address a day, too many new addresses, or the site's own limit on account mail (`mail.relay.accountMail`) | the server log names the limit; look for a form being abused (Turnstile on? rate limit?); a site that really sends more: Intecion raises the limits, or SMTP |
|
||||
| `relay-too-large` / `relay-attachment-refused` | files over the service's limit (10 MB a message); a program or script as attachment | lower the File field's maximum (`iapl-form`); other file types; SMTP for larger files |
|
||||
| `relay-recipient-suppressed` | one recipient's mailbox bounced or complained before (for any site); nothing was sent to anybody | correct the address in the form's Emails tab; ask Intecion to clear the address |
|
||||
| `relay-unreachable` | the service or its mail back end failed, or the server cannot reach `webservices.intecion.net` | `curl -s https://webservices.intecion.net/mail/health` from the server → `{"ok":true}`; if it persists: SMTP, and tell Intecion |
|
||||
| `relay-not-confirmed` / "may have been sent" | no answer from the service (time-out, connection lost) | check the recipient's mailbox **before** sending again; the same message sent again cannot double |
|
||||
| `relay-error` | the service refused the request as wrong (a bug), or the message has no valid recipient or no body | server log line `[iapl] mail service: …` → `iapl-plugin-gap` |
|
||||
| the mail arrives under the site's host instead of the client's name | the service did not accept "Sender name" (an address, a bank or provider name, mixed scripts, over 64 characters) — the state block says which name was used | another name; an honest name that is still replaced → Intecion |
|
||||
| replies to the site's mail are lost | "Sender address" is empty: the service's own address has no mailbox | fill it in (doctor: `mail-reply-address`) |
|
||||
| the site enrols again and again (`reverify` in the log) | requests leave from many changing addresses (serverless, a pool of egress addresses) | Intecion raises the site's limit of server addresses, or SMTP |
|
||||
| start log: "Microsoft Graph as the e-mail transport is deprecated" | `GRAPH_*` is set | email.md "Moving off Microsoft Graph"; silence only: `mail: { graphDeprecationWarning: false }` |
|
||||
| old email sender | mail client cache | check the raw headers |
|
||||
| form: `unknown_fields` | field outside the definition (honeypot not removed) | `iapl-form` → actions.ts |
|
||||
| an account logs in to `/admin` and sees "Unauthorized" (its API calls still work) | `accounts.panelRole`: the panel opens for `editor` and above; the account has only `user`, or no role | give it `editor` (an admin edits the account), or `accounts: { panelRole: 'user' }`; nobody can get in: a script with the Local API sets `roles: ['admin']`, or `accounts: { panelRole: false }` + redeploy |
|
||||
|
||||
@@ -21,6 +21,10 @@ Full reference: `node_modules/@intecion/ipal-kit/docs/doctor.md`.
|
||||
```
|
||||
2. Show the user the **full output**. Every finding names its rule, the file, a fix and a doc.
|
||||
3. Fix every `error`. A `warning` is drift — fix it or tell the user why not. `info` is a note.
|
||||
E-mail findings (`--deep`): `mail-transport` (nothing set up, or sending fails), `mail-relay-state` (the site's state
|
||||
with the Intecion mail service: waiting for approval, stopped, refused, disconnected, a replaced sender name),
|
||||
`mail-reply-address`, `mail-graph-deprecated`, `mail-relay-route` (trailing slashes, another API route, a redirect or a
|
||||
block in front of `/api/iapl/mail-relay/confirm`) — fixes: `iapl-debug` "Consent / analytics / forms / email".
|
||||
4. A deliberate exception (the owner's decision) goes into `iapl-doctor.json` **with a reason** — the same reason as in
|
||||
AGENTS.md "Project decisions". Never silence a rule just to make the run pass:
|
||||
```json
|
||||
|
||||
@@ -109,6 +109,8 @@ Never build this by hand (your own `<input type="file">`, upload route or upload
|
||||
the visitor that the problem is the **file**, why, and what to do (a smaller file, another format; on an
|
||||
optional field also "send the form without the file"). They show at the File field; what the visitor typed stays.
|
||||
6. Mail size: **Site integrations → E-mail sending → Test e-mail** with **Attach a 10 MB test file** must arrive.
|
||||
The mail service (the default transport): 10 MB for all files of one message unless Intecion set another number
|
||||
for the site — the form's limit follows what the service reports by itself, and programs and scripts are refused.
|
||||
SMTP: the provider's limit decides (a 10 MB server limit carries only ~7 MB of file — lower the field's
|
||||
maximum). Microsoft Graph: files of 3 MB and more need the `Mail.ReadWrite` permission on the agency app
|
||||
(email.md "Attachments"); without it they go over SMTP when the panel has SMTP settings, else the form's limit
|
||||
|
||||
@@ -43,7 +43,8 @@ Before I set up the site I need your decisions on:
|
||||
1. Languages: which ones, which is the default, URLs — every language with a prefix (/pl/…, /en/…) or the default without one?
|
||||
2. Styling: a design system / DESIGN.md, or Tailwind tokens from scratch? Brand colours, fonts, light/dark theme?
|
||||
3. Pages and content: which pages? Lists with their own URLs (blog, case studies, products) and their archive pages?
|
||||
4. Forms: which forms, who receives the submissions, e-mail via SMTP (panel) or Microsoft Graph?
|
||||
4. Forms: which forms, who receives the submissions? E-mail works through the built-in Intecion mail service with no
|
||||
setup — does the client want its **own SMTP server and sender address** instead? (Never offer Microsoft Graph: deprecated.)
|
||||
5. Analytics and consent: GA4 / GTM / Meta / other pixels? Consent Mode basic or advanced? Cookie dialog
|
||||
inline / modal / detailed? Cookie scan of the finished site?
|
||||
6. SEO/GEO: market, local business (address, opening hours)? AI access (llms.txt, Markdown, MCP, AI bots) — on?
|
||||
@@ -199,8 +200,9 @@ export default buildConfig({
|
||||
`.env.example` (no values, in the repo): `DATABASE_URI`, `PAYLOAD_SECRET`, `NEXT_PUBLIC_SERVER_URL`, `R2_BUCKET`,
|
||||
`R2_ENDPOINT`, `R2_ACCESS_KEY_ID`, `R2_SECRET_ACCESS_KEY`, `R2_PUBLIC_URL` (empty = media through the app — the default), `IAPL_IP_HEADER` (`cf-connecting-ip`
|
||||
behind Cloudflare, `x-forwarded-for` behind a plain proxy), `IAPL_NOINDEX` (empty; `1` on staging only), `INDEXNOW_KEY`,
|
||||
`NEXT_PUBLIC_TURNSTILE_SITE_KEY`, `TURNSTILE_SECRET_KEY` (deprecated fallback — production keys go into the panel), with Graph `GRAPH_TENANT_ID`,
|
||||
`GRAPH_CLIENT_ID`, `GRAPH_CLIENT_SECRET`, `GRAPH_SENDER`. Local `.env` with `PAYLOAD_SECRET` ≥ 32 characters (in production `iaplEnvRules` refuses a shorter one; `secretMinLength` changes it).
|
||||
`NEXT_PUBLIC_TURNSTILE_SITE_KEY`, `TURNSTILE_SECRET_KEY` (deprecated fallback — production keys go into the panel). **No variable for mail**: the
|
||||
mail service needs none, SMTP is typed in the panel, and `GRAPH_TENANT_ID` / `GRAPH_CLIENT_ID` / `GRAPH_CLIENT_SECRET` / `GRAPH_SENDER` (Microsoft Graph, deprecated, removed in 2.0)
|
||||
are never added to a new site. Local `.env` with `PAYLOAD_SECRET` ≥ 32 characters (in production `iaplEnvRules` refuses a shorter one; `secretMinLength` changes it).
|
||||
One language: one entry in `locales`, no `[locale]` folder (i18n.md).
|
||||
|
||||
**Check.** `pnpm payload generate:importmap` (whiteLabel adds admin components) and `pnpm generate:types` without
|
||||
@@ -295,7 +297,10 @@ the panel shows Site settings, Site integrations, Cookies, Form messages, the Fo
|
||||
preview image (`/api/ipal/admin-og`) from Site settings; `agency` names who supports the technology (default
|
||||
Intecion.com). Turn off: `adminMeta: false`, `agency: false`; your own `admin.meta` keys win. Check:
|
||||
`curl -s localhost:3000/admin/login | grep -E 'og:|robots'` → `noindex, nofollow`, `og:site_name` = Site settings name.
|
||||
- Mail: any Payload adapter instead of `mailAdapter()`; `mailAdapter({ fallbackFromAddress, smtp, graph })`.
|
||||
- Mail: the Intecion mail service is the default transport (AGENT.md §7.2, email.md). Off: `iapl({ mail: { relay: false } })`
|
||||
(SMTP only, no outbound call, no `/api/iapl/mail-relay/*` routes). Override: `mail: { relay: { host, enrol, token, senderName,
|
||||
kind, accountMail, url } }`, `mailAdapter({ fallbackFromAddress, relay, smtp })`; the transport alone: `relayAdapter()`; any
|
||||
Payload adapter instead of `mailAdapter()`. `serverURL` must be the public address — the service calls the site back there.
|
||||
- R2: other storage-s3 options (prefix, clientUploads) → call `s3Storage` yourself instead of `buildR2Storage`.
|
||||
- `forms: { adminGroup, fields, formOverrides, formSubmissionOverrides, beforeEmail, emailLayout }` (forms.md).
|
||||
- `adminRoute: '/its'` — requires moving `app/(payload)/admin` → `its`, a proxy matcher with `its` (stage 6)
|
||||
@@ -572,8 +577,10 @@ every language, consent checkbox). Cookies: skill **iapl-consent-check** — `co
|
||||
Cookies → Cookie list; on the cookie policy page a block with `<CookieTable>` (`/rsc`, data from `getCookieTable`);
|
||||
the same list appears in the `settings="detailed"` dialog (labels: Cookies → Settings window → Cookie list headings, every language).
|
||||
|
||||
**Check.** Panel → Forms: the seeded form; a submission on `/pl` → an entry in Form Submissions + 2 emails (SMTP:
|
||||
Site integrations → E-mail sending → Send test); with Turnstile test keys the widget is visible, without a token the submission is rejected;
|
||||
**Check.** Panel → Forms: the seeded form; a submission on `/pl` → an entry in Form Submissions + 2 emails. Mail on a
|
||||
development machine: the mail service does not enrol a site on `localhost` (the state block says so; nothing leaves the
|
||||
machine) — fill in a local SMTP catcher (Mailpit: server `127.0.0.1`, port `1025`, any user name and password) in Site
|
||||
integrations → E-mail sending and use **Send test e-mail**; on the deployed domain empty the SMTP fields again; with Turnstile test keys the widget is visible, without a token the submission is rejected;
|
||||
`node .agents/skills/iapl-consent-check/scripts/consent-check.mjs http://localhost:3000/pl` = 0 errors;
|
||||
after a choice in the banner a new record in Consent records.
|
||||
|
||||
@@ -637,7 +644,11 @@ scaling (5). `●` routes for pages need the database at build time (PROGRAMISTA
|
||||
5. **Cookies**: banner texts, Privacy link label, Policy version, Cookies (import from the scan), Detail labels —
|
||||
in every language.
|
||||
6. **Notifications**: form messages in every language.
|
||||
7. **Site integrations**: SMTP or Graph (From Name/Address; Send test), Turnstile (for testing site
|
||||
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 the built-in mail
|
||||
service" ("waiting for approval" = ask Intecion to approve the host), then **Send test e-mail** → "through the built-in
|
||||
mail service". 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.
|
||||
@@ -645,7 +656,7 @@ scaling (5). `●` routes for pages need the database at build time (PROGRAMISTA
|
||||
**Deployment (Coolify — the only path; the user/team does it, you prepare the inputs).** Full procedure:
|
||||
`node_modules/@intecion/ipal-kit/docs/deployment.md` §4. Hand over:
|
||||
- the env list for the Coolify app, each marked **build time** and/or **runtime** — `NEXT_PUBLIC_*` both; secrets
|
||||
(`PAYLOAD_SECRET`, `R2_*`, `GRAPH_*`, `TURNSTILE_SECRET_KEY`, `IAPL_IP_HEADER`) runtime; `DATABASE_URI` /
|
||||
(`PAYLOAD_SECRET`, `R2_*`, `TURNSTILE_SECRET_KEY`, `IAPL_IP_HEADER`) runtime; `DATABASE_URI` /
|
||||
`PAYLOAD_SECRET` also build time when pages are prerendered from the database (§3a3);
|
||||
- domains `https://client.pl,https://www.client.pl` with the www ↔ apex redirect matching `NEXT_PUBLIC_SERVER_URL`;
|
||||
port 3000; health check `/api/health`;
|
||||
|
||||
@@ -552,6 +552,34 @@ ipal-kit"). **Do not rename anything in the project unless the owner asks.**
|
||||
**Check:** `pnpm exec iapl-doctor` shows no new error or warning (new rules: `legacy-names`, `storage-names`); the site
|
||||
builds; the panel opens; the old commands (`pnpm exec ipal-doctor`) still run.
|
||||
|
||||
**→ 1.17.0, e-mail (the Intecion mail service is the default transport; Microsoft Graph deprecated; CHANGELOG 1.17.0;
|
||||
PROGRAMISTA §6, item 73; email.md; AGENT.md §7.2) — nothing to run; read which case the site is:**
|
||||
1. **Every site:** no schema change, no migration, no import-map change. The e-mail tab gains the block "How e-mails
|
||||
are sent" and new wording ("Automatic", "Own SMTP server").
|
||||
2. **Which case** — Site integrations → E-mail sending, and the Coolify env:
|
||||
- **SMTP filled in** (server, user name, password): nothing changes, the site contacts nobody. Done.
|
||||
- **`GRAPH_*` set:** mail as before; one deprecation warning per start, doctor warning `mail-graph-deprecated`.
|
||||
Do **not** remove the variables in passing — moving the site is the owner's decision (email.md "Moving off
|
||||
Microsoft Graph"). Note: with `GRAPH_*` set and SMTP filled in, the panel's choice decides as before.
|
||||
- **Neither** (mail failed with "not configured" until now): **on its next e-mail the site contacts
|
||||
`webservices.intecion.net` with its host and the plugin version**, receives its own token through the new public
|
||||
route `POST /api/iapl/mail-relay/confirm`, and from then on sends from `[email protected]`
|
||||
under the panel's "Sender name". Agree it with the owner **before** the deploy; to keep the old behaviour:
|
||||
`iapl({ mail: { relay: false } })`.
|
||||
3. **For a site that will use the mail service:** `serverURL` is the public address the site answers on without a
|
||||
redirect; no proxy or WAF rule blocks `/api/iapl/mail-relay/confirm`; `trailingSlash: true` or another `routes.api` →
|
||||
Intecion sets the site's confirm address first; "Sender address" is filled in (replies go there); Intecion has listed
|
||||
the host (otherwise "waiting for approval"); the client's processing agreement names the service.
|
||||
4. Code that compared the result of `payload.sendEmail` needs no change for SMTP and Graph. A send through the mail
|
||||
service returns `{ sent, transport: 'relay', … }`; `sent: false` with `confirmed: false` means "may have been sent".
|
||||
5. Your own account mail (invitations): mark it — `withMailKind(message, 'account')`. Form mail and Payload's
|
||||
"forgot password" are marked by the plugin.
|
||||
**Check:** `pnpm exec iapl-doctor --deep --url <site>` → no `mail-transport` / `mail-relay-state` / `mail-reply-address` /
|
||||
`mail-relay-route` finding (or only `mail-graph-deprecated` on a Graph site); Site integrations → E-mail sending →
|
||||
**Send test e-mail** names the transport you expect; a form submission arrives. **The service has to be live for a site
|
||||
without SMTP: until Intecion says so, such a site reports `relay-unreachable` and sends nothing — keep SMTP, or
|
||||
`relay: false`.**
|
||||
|
||||
## 2. Inventory (no code changes)
|
||||
**What changed for projects** between your old and new plugin version is exactly the reference site's diff —
|
||||
`git diff v<old> v<new> -- reference/` in the IAPL repo (or the two `docs/agent/reference-site/INDEX.md` files):
|
||||
|
||||
@@ -58,4 +58,6 @@ E2E_ADMIN_PASSWORD=e2e-RC2nC29eKC8HJHfg
|
||||
E2E_TOTP_SECRET=JPURUZNWYTZX2L42MT4SS7736WWNQWBL
|
||||
# Port of the mail sink the smoke tests start (e2e/smtp-sink.ts); create-test-admin.ts points e-mail sending at it
|
||||
E2E_SMTP_PORT=2526
|
||||
# Port of the mail service's stand-in in e2e/mail-relay.spec.ts
|
||||
E2E_RELAY_PORT=2527
|
||||
# @starter:endif
|
||||
|
||||
@@ -0,0 +1,10 @@
|
||||
/**
|
||||
* Test fixture, on only with E2E_MAIL_RELAY_URL (e2e/mail-relay.spec.ts): points the mail service's client at
|
||||
* a stand-in the spec starts on this machine, so the spec can watch a built site enrol through its own confirm
|
||||
* route and send — without the real service. Never part of a real site: the starter drops `e2e/` and the lines
|
||||
* that use this file; a real site names no address (the plugin's own is used).
|
||||
*/
|
||||
export const E2E_MAIL_RELAY_URL = process.env.E2E_MAIL_RELAY_URL || undefined
|
||||
|
||||
/** `iapl({ mail })` for the test, `undefined` (the plugin's defaults) otherwise. */
|
||||
export const e2eMail = E2E_MAIL_RELAY_URL ? { relay: { retryBackoffMs: 50, url: E2E_MAIL_RELAY_URL } } : undefined
|
||||
@@ -0,0 +1,26 @@
|
||||
/**
|
||||
* For e2e/mail-relay.spec.ts — LOCAL / CI database only:
|
||||
* pnpm payload run e2e/mail-relay-setup.ts the site has no SMTP server and no token: its next e-mail
|
||||
* goes to the mail service, enrolling first
|
||||
* Afterwards the spec runs e2e/create-test-admin.ts again, which points e-mail back at the tests' SMTP sink.
|
||||
*/
|
||||
import config from '@payload-config'
|
||||
import { RELAY_KV_KEY } from '@intecion/ipal-kit'
|
||||
import { isLocalDatabase } from '@intecion/ipal-kit/seed'
|
||||
import { getPayload } from 'payload'
|
||||
|
||||
if (process.env.NODE_ENV === 'production' && !process.env.CI) {throw new Error('Refusing: NODE_ENV=production outside CI.')}
|
||||
if (!isLocalDatabase(process.env.DATABASE_URI ?? '')) {throw new Error('Refusing: DATABASE_URI is not a local database.')}
|
||||
|
||||
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,
|
||||
overrideAccess: true,
|
||||
})
|
||||
for (const key of await payload.kv.keys()) {
|
||||
if (key === RELAY_KV_KEY || key.startsWith(`${RELAY_KV_KEY}:`)) {await payload.kv.delete(key)}
|
||||
}
|
||||
console.log('[e2e] no SMTP server and no mail-service token: the next e-mail enrols and goes through the mail service')
|
||||
process.exit(0)
|
||||
@@ -0,0 +1,92 @@
|
||||
import { expect, test } from '@playwright/test'
|
||||
import { execFileSync } from 'node:child_process'
|
||||
|
||||
import { createFakeRelay } from '@intecion/ipal-kit'
|
||||
|
||||
import { totp } from './totp'
|
||||
|
||||
/**
|
||||
* The mail service on a BUILT site (pnpm e2e:built runs this with webpack and with Turbopack): a stand-in for
|
||||
* the service runs inside this test and calls the site back over HTTP, as the real one would.
|
||||
* - the e-mail tab shows the state block (it rides on the status banner: no import-map entry of its own);
|
||||
* - the admin's test e-mail makes the site enrol through its own public confirm route and send;
|
||||
* - nothing the browser receives carries the token, and the confirm route tells a stranger nothing.
|
||||
* Needs the site started with E2E_MAIL_RELAY_URL (playwright.config.ts sets it) and the E2E_* test admin.
|
||||
*/
|
||||
const PORT = Number(process.env.E2E_RELAY_PORT ?? 2527)
|
||||
const { E2E_ADMIN_EMAIL: email, E2E_ADMIN_PASSWORD: password, E2E_TOTP_SECRET: secret } = process.env
|
||||
const run = (script: string) => execFileSync('pnpm', ['payload', 'run', script], { env: { ...process.env, NODE_ENV: 'development' }, stdio: 'inherit' })
|
||||
|
||||
test.describe('the mail service', () => {
|
||||
test.skip(!email || !password || !secret, 'E2E_* test admin not configured')
|
||||
let relay: ReturnType<typeof createFakeRelay>
|
||||
let server: Awaited<ReturnType<ReturnType<typeof createFakeRelay>['listen']>>
|
||||
let site = ''
|
||||
|
||||
test.beforeAll(async ({ baseURL }) => {
|
||||
site = new URL(baseURL!).host
|
||||
// the site's host is listed, so it is active as soon as it enrols; `localhost` may be called back over http
|
||||
relay = createFakeRelay({ allow: [site], allowLocalHosts: true })
|
||||
server = await relay.listen(PORT)
|
||||
run('e2e/mail-relay-setup.ts')
|
||||
})
|
||||
test.afterAll(async () => {
|
||||
await server?.close()
|
||||
run('e2e/create-test-admin.ts') // e-mail back to the tests' SMTP sink, the test admins as they were
|
||||
})
|
||||
|
||||
test('the confirm route is public and tells a stranger nothing', async ({ request }) => {
|
||||
const res = await request.post('/api/iapl/mail-relay/confirm', { data: { nonce: 'n'.repeat(43), state: 'active', token: `ims_${'a'.repeat(43)}` } })
|
||||
expect(res.status()).toBe(404)
|
||||
expect(await res.text()).toBe('')
|
||||
expect((await request.get('/api/iapl/mail-relay/status')).status()).toBe(401)
|
||||
expect(relay.requests).toEqual([])
|
||||
})
|
||||
|
||||
test('the state block, the first e-mail through the confirm route, and no token in the browser', async ({ baseURL, page }) => {
|
||||
const seen: string[] = []
|
||||
page.on('response', (response) => {
|
||||
if (response.url().includes('/api/')) {void response.text().then((body) => seen.push(body)).catch(() => undefined)}
|
||||
})
|
||||
await page.goto('/admin/login')
|
||||
await page.fill('#field-email', email!)
|
||||
await page.fill('#field-password', password!)
|
||||
await page.click('.form-submit button')
|
||||
await page.waitForURL(/verify-totp|\/admin(\?|$)/, { waitUntil: 'commit' })
|
||||
if (page.url().includes('verify-totp')) {
|
||||
await page.getByRole('textbox').first().click()
|
||||
await page.keyboard.type(totp(secret!))
|
||||
}
|
||||
await expect(page).toHaveTitle(/Dashboard|Pulpit/, { timeout: 20_000 })
|
||||
|
||||
await page.goto('/admin/globals/site-integrations')
|
||||
await page.getByRole('tab', { name: /E-mail sending|Wysyłka e-mail/ }).or(page.getByRole('button', { name: /E-mail sending|Wysyłka e-mail/ })).first().click()
|
||||
// the block is there in a production bundle, with the transport the settings give
|
||||
const block = page.locator('[data-mail-transport]')
|
||||
await expect(block).toHaveAttribute('data-mail-transport', 'relay', { timeout: 20_000 })
|
||||
await expect(block).toContainText('[email protected]')
|
||||
await expect(block).toContainText(/Not connected yet|Jeszcze nie połączono/)
|
||||
|
||||
await page.fill('#ipal-test-email-to', '[email protected]')
|
||||
await page.getByRole('button', { name: /Send test e-mail|Wyślij testowy e-mail/ }).click()
|
||||
// the answer of the test e-mail names the transport and the sender name that was used
|
||||
await expect(page.getByText(/Test e-mail sent to anna@example\.org through the built-in mail service|Testowy e-mail wysłano na adres anna@example\.org przez wbudowaną usługę pocztową/)).toBeVisible({ timeout: 30_000 })
|
||||
|
||||
// the service was asked once, called the site's confirm route, and took one message
|
||||
expect(relay.requests.map((r) => r.path).slice(0, 2)).toEqual(['/v1/enrol', '/v1/send'])
|
||||
expect(relay.outbox).toHaveLength(1)
|
||||
expect(relay.outbox[0]).toMatchObject({ fromName: 'Example Studio', host: site, kind: 'test', replyTo: '[email protected]', to: ['[email protected]'] })
|
||||
|
||||
// "Check now" asks the service; the block then says connected and what is left of the hour
|
||||
await block.getByRole('button', { name: /Check now|Sprawdź teraz/ }).click()
|
||||
await expect(block).toContainText(/Connected to the built-in mail service|Połączono z wbudowaną usługą pocztową/)
|
||||
await expect(block).toContainText(/Left this hour: 29|Pozostało w tej godzinie: 29/)
|
||||
|
||||
// (Payload takes the login cookie only from the site's own origin, so the request says where it comes from)
|
||||
const status = await page.request.get('/api/iapl/mail-relay/status', { headers: { origin: baseURL! } })
|
||||
expect(await status.json()).toMatchObject({ ok: true, relay: { connected: true, state: 'active', tokenSource: 'enrolment' }, transport: 'relay' })
|
||||
// nothing the browser saw carries the token: not the page, not an API answer
|
||||
await page.waitForLoadState('networkidle')
|
||||
for (const body of [await page.content(), await status.text(), ...seen]) {expect(body).not.toContain('ims_')}
|
||||
})
|
||||
})
|
||||
@@ -28,7 +28,9 @@ export default defineConfig({
|
||||
use: { baseURL, trace: 'retain-on-failure' },
|
||||
webServer: {
|
||||
command: 'pnpm start',
|
||||
env: { PORT: new URL(baseURL).port || '3000' },
|
||||
// E2E_MAIL_RELAY_URL: the mail service's stand-in that e2e/mail-relay.spec.ts starts (nothing listens there otherwise,
|
||||
// and the other specs send through the SMTP sink, so the site never calls it)
|
||||
env: { E2E_MAIL_RELAY_URL: `http://127.0.0.1:${process.env.E2E_RELAY_PORT ?? 2527}/mail`, PORT: new URL(baseURL).port || '3000' },
|
||||
reuseExistingServer: process.env.E2E_REUSE_SERVER === '1',
|
||||
url: `${baseURL}/api/health`,
|
||||
},
|
||||
|
||||
+1121
-12
File diff suppressed because it is too large
Load Diff
@@ -20,6 +20,7 @@ import { Posts } from './collections/Posts'
|
||||
// @starter:endif
|
||||
// @starter:if demo
|
||||
import { E2E_LATE_STAFF, E2E_STAFF_SLUGS, e2eEarlyStaff, e2eLateStaff } from '../e2e/late-staff-fixture'
|
||||
import { e2eMail } from '../e2e/mail-relay-fixture'
|
||||
// @starter:endif
|
||||
import { contentConfig } from './content.config'
|
||||
import { db } from './db'
|
||||
@@ -51,7 +52,7 @@ export default buildConfig({
|
||||
globals: [Header, Footer, Company],
|
||||
db,
|
||||
editor: lexicalEditor(),
|
||||
email: mailAdapter(), // transport from Site integrations (SMTP / Graph); without it form e-mails are not sent
|
||||
email: mailAdapter(), // the Intecion mail service, or the SMTP server from Site integrations; without it form e-mails are not sent
|
||||
secret: process.env.PAYLOAD_SECRET ?? '',
|
||||
sharp,
|
||||
typescript: { outputFile: path.resolve(dirname, 'payload-types.ts') },
|
||||
@@ -65,6 +66,8 @@ export default buildConfig({
|
||||
// with `stats` on, the layout passes visitorCookie={IAPL_VISITOR_COOKIE} to match
|
||||
storageNames: 'iapl',
|
||||
// @starter:if demo
|
||||
// a test fixture: `undefined` (the plugin's defaults) without E2E_MAIL_RELAY_URL (e2e/mail-relay-fixture.ts)
|
||||
mail: e2eMail,
|
||||
// (the staffCollections entry exists only for e2e/late-staff.spec.ts, with E2E_LATE_STAFF=1)
|
||||
access: { authCollection: 'users', ...(E2E_LATE_STAFF ? { staffCollections: E2E_STAFF_SLUGS } : {}) },
|
||||
// @starter:else
|
||||
|
||||
@@ -8,7 +8,8 @@
|
||||
* once with Turbopack:
|
||||
* 1. production build with the late-staff fixture (E2E_LATE_STAFF=1, reference/e2e/late-staff-fixture.ts);
|
||||
* 2. no package manifest under .next/static (checked on disk, before anything is started);
|
||||
* 3. Playwright against `next start`: e2e/late-staff.spec.ts and the smoke test "no package.json is published".
|
||||
* 3. Playwright against `next start`: e2e/late-staff.spec.ts, e2e/mail-relay.spec.ts (the mail service: the confirm
|
||||
* route under Next, the state block in the panel's production bundle) and the smoke test "no package.json is published".
|
||||
*
|
||||
* Needs what the reference site's "Production check" needs (reference/README.md): reference/.env with a local,
|
||||
* seeded database and the E2E_* test admin. The test admins are reset by Playwright's global setup.
|
||||
@@ -80,7 +81,7 @@ for (const bundler of bundlers) {
|
||||
process.exit(1)
|
||||
}
|
||||
console.log(`[e2e:built] ✓ ${bundler}: no package manifest among ${files.length} public files`)
|
||||
run(`${bundler}: the built site — late-staff spec and the published-files check`, 'pnpm', ['exec', 'playwright', 'test', 'late-staff', 'smoke', '--grep', 'late staff collection|no package.json is published'], site, { ALLOW_LOCAL_MEDIA: process.env.ALLOW_LOCAL_MEDIA ?? '1', E2E_LATE_STAFF: '1' })
|
||||
run(`${bundler}: the built site — late-staff spec, the mail service and the published-files check`, 'pnpm', ['exec', 'playwright', 'test', 'late-staff', 'mail-relay', 'smoke', '--grep', 'late staff collection|the mail service|no package.json is published'], site, { ALLOW_LOCAL_MEDIA: process.env.ALLOW_LOCAL_MEDIA ?? '1', E2E_LATE_STAFF: '1' })
|
||||
passed.push(bundler)
|
||||
}
|
||||
console.log(`\n[e2e:built] passed: ${passed.join(' and ')}. (The reference site's .next now holds the ${passed.at(-1)} build WITH the fixture: rebuild with \`pnpm build\` there before other checks.)`)
|
||||
|
||||
@@ -36,7 +36,8 @@ const warn = { ...line, color: 'var(--theme-warning-600, #b45309)' } as const
|
||||
* a sender name the service did not accept. "Check now" asks the service; "Connect again" and
|
||||
* "Disconnect" act on the site's connection. No token is ever shown or sent to this component.
|
||||
*
|
||||
* Assigned via a `ui` field's admin.components.Field. Texts: `mailRelay*` keys.
|
||||
* Rendered by IntegrationStatusBanner on the e-mail tab (`mailRelay` prop) — it has no import-map entry of its
|
||||
* own; a project's own panel can import it from `/admin`. Texts: `mailRelay*` keys.
|
||||
*/
|
||||
export const MailRelayStatus = () => {
|
||||
const { t } = useTranslation()
|
||||
|
||||
@@ -18,18 +18,17 @@ const usesSmtp: Condition = (_, siblingData) => siblingData?.emailTransport !==
|
||||
/**
|
||||
* 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 `ui` block only.
|
||||
* No stored field differs between the two: labels, descriptions and one client prop only.
|
||||
*/
|
||||
export const buildSmtpFields = ({ relay = true }: { relay?: boolean } = {}): Field[] => [
|
||||
// Which transport is in effect, and the site's state with the Intecion mail service.
|
||||
...(relay
|
||||
? [{ name: 'mailRelayStatus', type: 'ui' as const, admin: { components: { Field: '@intecion/ipal-kit/admin#MailRelayStatus' } } }]
|
||||
: []),
|
||||
// Status written by mailAdapter on every send (throttled) — banner on this tab.
|
||||
// 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
|
||||
// service (MailRelayStatus): no import-map entry of its own, so an upgrade needs no `generate:importmap`.
|
||||
buildIntegrationStatusBanner(
|
||||
'emailStatus',
|
||||
{ en: 'E-mail sending', pl: 'Wysyłka e-mail' },
|
||||
{ failing: 'statusEmailFailing', hint: 'statusEmailHint' },
|
||||
{ mailRelay: relay },
|
||||
),
|
||||
{
|
||||
name: 'emailTransport',
|
||||
|
||||
@@ -9,7 +9,7 @@ import { getSiteIntegrations } from '../../payload/index.js'
|
||||
import { graphAvailable, type MailTransport, resolveMailTransport } from '../mailAdapter.js'
|
||||
import { RELAY_SENDER_ADDRESS } from './adapter.js'
|
||||
import { RELAY_CONFIRM_PATH, RELAY_CONNECT_PATH, RELAY_DISCONNECT_PATH, RELAY_STATUS_PATH } from './constants.js'
|
||||
import { resolveRelayOptions } from './options.js'
|
||||
import { isPublicHost, resolveRelayOptions } from './options.js'
|
||||
import { disconnectRelay, enrolRelay, type EnrolResult, getRelayStatus, LOCAL_CODES, type RelayStatus, setRelayToken } from './session.js'
|
||||
|
||||
type Settings = {
|
||||
@@ -48,7 +48,13 @@ export async function mailPanelState(req: Pick<PayloadRequest, 'payload'>, own:
|
||||
const settings = await getSiteIntegrations<Settings>(payload)
|
||||
const options = resolveRelayOptions(payload, own)
|
||||
const transport = resolveMailTransport(settings, { graphEnv: graphAvailable(), relay: Boolean(options) })
|
||||
const status = options ? await getRelayStatus(payload, options, { refresh: refresh && transport === 'relay' }) : null
|
||||
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.
|
||||
if (status && options && !status.connected && !status.refusal && !options.ownUrl && options.enrol !== false && options.token === undefined) {
|
||||
const code = !status.host ? LOCAL_CODES.noHost : !isPublicHost(status.host) ? 'host-not-allowed' : null
|
||||
if (code) {status = { ...status, refusal: { at: new Date().toISOString(), code } }}
|
||||
}
|
||||
const api = payload.config.routes?.api ?? '/api'
|
||||
return {
|
||||
...(status?.host ? { confirmUrl: `https://${status.host}${api}${RELAY_CONFIRM_PATH}` } : {}),
|
||||
|
||||
@@ -48,9 +48,11 @@ type SendBody = { id?: string; messageId?: string; replayed?: boolean; senderNam
|
||||
const sleep = (ms: number) => new Promise<void>((resolve) => setTimeout(resolve, ms))
|
||||
|
||||
/**
|
||||
* Messages whose outcome the service never confirmed, by the hash of their bytes: sent again within
|
||||
* 24 hours they go out under the SAME key, so the service answers with what happened to the first
|
||||
* attempt instead of sending a second mail. Per process; a message of a new content always gets a new key.
|
||||
* Messages the service gave no final answer for (no answer at all, a retryable failure, an error page
|
||||
* of the network in front), by the hash of their bytes: sent again within 24 hours they go out under
|
||||
* the SAME key, so the service answers with what happened to the first attempt instead of sending a
|
||||
* second mail. Per process (there is no stored outbox): after a restart, or from another instance of
|
||||
* the site, the same message gets a new key. A message of a new content always gets a new key.
|
||||
*/
|
||||
const unconfirmed = new Map<string, { at: number; key: string }>()
|
||||
const DAY = 24 * 60 * 60_000
|
||||
@@ -180,6 +182,8 @@ export async function sendThroughRelay(payload: BasePayload, options: ResolvedRe
|
||||
use,
|
||||
)
|
||||
if (answer.ok || !answer.retryable || attempts >= RELAY_DEFAULTS.attempts) {break}
|
||||
// The site could not enrol: the message was never handed over, and asking again would not change that.
|
||||
if (use.enrolment && !use.enrolment.ok) {break}
|
||||
const wait = answer.retryAfter !== undefined ? answer.retryAfter * 1000 : attempts * (options.retryBackoffMs ?? 1000)
|
||||
// The ten seconds win over retryAfter: stop at once and report.
|
||||
if (waited + wait > budget) {break}
|
||||
@@ -228,8 +232,10 @@ export async function sendThroughRelay(payload: BasePayload, options: ResolvedRe
|
||||
}
|
||||
|
||||
const result = describeRefusal(answer)
|
||||
// Not confirmed, or failed in a way the back end does not explain: the same key if this message is tried again.
|
||||
if (!result.confirmed || result.detail.startsWith('Probably not sent')) {unconfirmed.set(hash, { at: Date.now(), key: idempotencyKey })}
|
||||
// Whenever the service did not give a final "no" (no answer, a failure it calls retryable, an answer that was
|
||||
// not its own): the same key if this message is tried again. Reusing a key is always safe — the service either
|
||||
// answers with what happened to the first attempt or sends the message now; a new key could send it twice.
|
||||
if (answer.noAnswer || answer.retryable) {unconfirmed.set(hash, { at: Date.now(), key: idempotencyKey })}
|
||||
else {unconfirmed.delete(hash)}
|
||||
if (answer.code === 'site-pending' || answer.code === 'site-suspended') {
|
||||
const state = answer.code === 'site-pending' ? 'pending' : 'suspended'
|
||||
|
||||
@@ -170,10 +170,16 @@ export async function withRelayToken<T>(
|
||||
const token = candidate?.token ?? stored.token
|
||||
|
||||
const enrolNow = async (): Promise<null | RelayRefusal> => {
|
||||
if (!enrol || use.enrolled) {return refusal(LOCAL_CODES.noToken, 'The site is not connected to the mail service.')}
|
||||
// once per message: a second request for it says again why the first enrolment failed
|
||||
const failed = () => (use.enrolment && !use.enrolment.ok ? refusal(use.enrolment.code, use.enrolment.message, { reason: use.enrolment.reason, retryable: use.enrolment.retryable }) : null)
|
||||
if (!enrol || use.enrolled) {return failed() ?? refusal(LOCAL_CODES.noToken, 'The site is not connected to the mail service.')}
|
||||
use.enrolled = true
|
||||
use.enrolment = await enrolRelay(payload, options)
|
||||
return use.enrolment.ok ? null : refusal(use.enrolment.code, use.enrolment.message, { reason: use.enrolment.reason, retryable: use.enrolment.retryable })
|
||||
if (use.enrolment.ok) {return null}
|
||||
// The enrolment has no good answer, but the call-back may have delivered a token all the same (the
|
||||
// service's answer was lost): try it — the service says at once whether it made that token valid.
|
||||
if (round < 3 && (await readRelayCandidate(payload))) {return null}
|
||||
return failed()
|
||||
}
|
||||
|
||||
if (!token) {
|
||||
@@ -191,7 +197,7 @@ export async function withRelayToken<T>(
|
||||
continue
|
||||
}
|
||||
const failed = await enrolNow()
|
||||
if (failed) {return use.enrolment ? failed : answer}
|
||||
if (failed) {return use.enrolment && !use.enrolment.ok ? failed : answer}
|
||||
continue
|
||||
}
|
||||
if (candidate) {
|
||||
@@ -201,7 +207,7 @@ export async function withRelayToken<T>(
|
||||
}
|
||||
if (!answer.ok && answer.code === 'reverify') {
|
||||
const failed = await enrolNow()
|
||||
if (failed) {return use.enrolment ? failed : answer}
|
||||
if (failed) {return use.enrolment && !use.enrolment.ok ? failed : answer}
|
||||
continue
|
||||
}
|
||||
return answer
|
||||
|
||||
@@ -3,12 +3,15 @@ import { useFormFields, useTranslation } from '@payloadcms/ui'
|
||||
|
||||
import type { IntegrationBannerTexts } from './status.js'
|
||||
|
||||
import { MailRelayStatus } from '../../globals/SiteIntegrations/components/MailRelayStatus.js'
|
||||
import { formatDateTime, iaplT } from '../admin-i18n/t.js'
|
||||
import { type IntegrationLabel, resolveLabel, STATUS_CODE_TEXTS } from './texts.js'
|
||||
|
||||
type Props = {
|
||||
/** Integration name shown in the banner, e.g. { en: 'Spam protection', pl: 'Ochrona przed spamem' }. */
|
||||
label: IntegrationLabel
|
||||
/** The e-mail tab: show the block "How e-mails are sent" (transport, the mail service's state) above the banner. */
|
||||
mailRelay?: boolean
|
||||
/** Name of the hidden status group (buildIntegrationStatusField). */
|
||||
statusField: string
|
||||
/** Texts keys for this integration's failing heading and hint. */
|
||||
@@ -20,7 +23,17 @@ type Props = {
|
||||
* the integration has been used once; a red box while it's failing; a short
|
||||
* green line once it works again. Wording comes from the integration (`texts`).
|
||||
*/
|
||||
export function IntegrationStatusBanner({ label, statusField, texts = {} }: Props) {
|
||||
export function IntegrationStatusBanner({ mailRelay, ...props }: Props) {
|
||||
if (!mailRelay) {return <StatusBanner {...props} />}
|
||||
return (
|
||||
<>
|
||||
<MailRelayStatus />
|
||||
<StatusBanner {...props} />
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
function StatusBanner({ label, statusField, texts = {} }: Omit<Props, 'mailRelay'>) {
|
||||
const { i18n, t } = useTranslation()
|
||||
const state = useFormFields(([f]) => f[`${statusField}.state`]?.value) as string | undefined
|
||||
const message = useFormFields(([f]) => f[`${statusField}.message`]?.value) as string | undefined
|
||||
|
||||
@@ -66,6 +66,11 @@ export function buildIntegrationStatusBanner(
|
||||
statusField: string,
|
||||
label: IntegrationLabel,
|
||||
texts: IntegrationBannerTexts = {},
|
||||
/**
|
||||
* `mailRelay`: the e-mail tab's block "How e-mails are sent" (MailRelayStatus) above the banner. It
|
||||
* rides on this component so that no site has to regenerate its import map for it.
|
||||
*/
|
||||
extra: { mailRelay?: boolean } = {},
|
||||
): Field {
|
||||
return {
|
||||
name: `${statusField}Banner`,
|
||||
@@ -73,7 +78,7 @@ export function buildIntegrationStatusBanner(
|
||||
admin: {
|
||||
components: {
|
||||
Field: {
|
||||
clientProps: { label, statusField, texts },
|
||||
clientProps: { label, statusField, texts, ...(extra.mailRelay ? { mailRelay: true } : {}) },
|
||||
path: '@intecion/ipal-kit/admin#IntegrationStatusBanner',
|
||||
},
|
||||
},
|
||||
|
||||
@@ -13,6 +13,7 @@ import { relayAdapter } from '../src/modules/email/relay/adapter.js'
|
||||
import { withMailKind } from '../src/modules/email/relay/kinds.js'
|
||||
import { bareAddresses, buildRelayMessage, cleanSubject } from '../src/modules/email/relay/message.js'
|
||||
import { isPublicHost, relayHost, resolveRelayOptions } from '../src/modules/email/relay/options.js'
|
||||
import { mailPanelState } from '../src/modules/email/relay/panel.js'
|
||||
import { clearUnconfirmedRelayMessages, sendThroughRelay } from '../src/modules/email/relay/send.js'
|
||||
import { disconnectRelay, enrolRelay, getRelayStatus, refreshRelayStatus, rotateRelayToken, setRelayToken } from '../src/modules/email/relay/session.js'
|
||||
import { holdNonce, readRelayCandidate, readRelayStore, updateRelayStore } from '../src/modules/email/relay/store.js'
|
||||
@@ -251,6 +252,17 @@ describe('when the service asks the site to enrol again', () => {
|
||||
expect((await readRelayStore(payload)).token).not.toBe(old)
|
||||
})
|
||||
|
||||
test('a service that keeps refusing the token: one enrolment for the message, not a loop', async () => {
|
||||
const { fake, options, payload } = relaySite({ fake: { allow: [HOST] } })
|
||||
await sendThroughRelay(payload, options, MESSAGE)
|
||||
fake.intercept = (request) =>
|
||||
request.url.endsWith('/v1/send') ? Response.json({ code: 'invalid-token', message: 'x', ok: false, retryable: false }, { status: 401 }) : undefined
|
||||
const before = fake.requests.length
|
||||
const result = await sendThroughRelay(payload, options, { ...MESSAGE, subject: 'Refused twice' })
|
||||
expect(result).toMatchObject({ cause: 'invalid-token', code: 'relay-refused', sent: false })
|
||||
expect(fake.requests.slice(before).filter((r) => r.path === '/v1/enrol')).toHaveLength(1)
|
||||
})
|
||||
|
||||
test('a site enrols at most once per message, and a refused enrolment is not asked again for a while', async () => {
|
||||
const { fake, options, payload } = relaySite({ fake: { allow: [HOST], callSite: async () => new Response(null, { status: 404 }) } })
|
||||
const first = await sendThroughRelay(payload, options, MESSAGE)
|
||||
@@ -266,6 +278,18 @@ describe('when the service asks the site to enrol again', () => {
|
||||
expect(fake.requests.map((r) => r.path)).toEqual(['/v1/enrol', '/v1/enrol'])
|
||||
})
|
||||
|
||||
test('the service cannot be reached at all: one enrolment is tried, nothing is sent, and the status says "unreachable"', async () => {
|
||||
const { fake, options, payload } = relaySite({ fake: { allow: [HOST] } })
|
||||
fake.intercept = () => 'drop'
|
||||
const result = await sendThroughRelay(payload, options, MESSAGE)
|
||||
// the message never left the site, so it is "not sent" (confirmed), not "may have been sent"
|
||||
expect(result).toMatchObject({ cause: 'unavailable', code: 'relay-unreachable', confirmed: true, sent: false })
|
||||
expect(fake.outbox).toHaveLength(0)
|
||||
// not a refusal: the next message tries again at once
|
||||
fake.intercept = undefined
|
||||
expect((await sendThroughRelay(payload, options, MESSAGE)).sent).toBe(true)
|
||||
})
|
||||
|
||||
test('the answer to /v1/enrol is lost: the delivered token is tried next and becomes the token once the service accepts it', async () => {
|
||||
const { fake, options, payload } = relaySite({ fake: { allow: [HOST] } })
|
||||
fake.intercept = async (request) => {
|
||||
@@ -352,6 +376,16 @@ describe('one message: one key, one encoding, three attempts', () => {
|
||||
const sends = capture(fake, [page(), page(), page()])
|
||||
expect(await sendThroughRelay(payload, options, MESSAGE)).toMatchObject({ cause: 'unavailable', code: 'relay-unreachable', confirmed: true, sent: false })
|
||||
expect(sends).toHaveLength(3)
|
||||
// an error page says nothing about what the service did: the same message sent again keeps its key
|
||||
const again = capture(fake, [])
|
||||
expect((await sendThroughRelay(payload, options, MESSAGE)).sent).toBe(true)
|
||||
expect(again[0].key).toBe(sends[0].key)
|
||||
// a final refusal does not: the next try is a new message
|
||||
const refused = capture(fake, [failing(429, { code: 'quota-exceeded', limit: 'hour', retryable: false })])
|
||||
await sendThroughRelay(payload, options, { ...MESSAGE, subject: 'Refused' })
|
||||
const after = capture(fake, [])
|
||||
await sendThroughRelay(payload, options, { ...MESSAGE, subject: 'Refused' })
|
||||
expect(after[0].key).not.toBe(refused[0].key)
|
||||
// also a 200 whose body is not the contract's
|
||||
const odd = capture(fake, [new Response('', { status: 200 }), Response.json(['ok']), Response.json({ ok: true }, { status: 201 })])
|
||||
expect((await sendThroughRelay(payload, options, { ...MESSAGE, subject: 'Odd' })).sent).toBe(false)
|
||||
@@ -562,6 +596,9 @@ describe('the token over time', () => {
|
||||
expect(refusedByService.status).toBe(401)
|
||||
const before = fake.requests.length
|
||||
expect(await sendThroughRelay(payload, options, MESSAGE)).toMatchObject({ code: 'relay-disconnected', sent: false })
|
||||
// nor does anything else enrol the site by itself (a script, a status read): only "Connect again" does
|
||||
expect(await enrolRelay(payload, options)).toMatchObject({ ok: false, status: 'relay-disconnected' })
|
||||
await refreshRelayStatus(payload, options)
|
||||
expect(fake.requests.length).toBe(before)
|
||||
expect((await enrolRelay(payload, options, { force: true })).ok).toBe(true)
|
||||
expect((await sendThroughRelay(payload, options, MESSAGE)).sent).toBe(true)
|
||||
@@ -588,6 +625,23 @@ describe('the token over time', () => {
|
||||
})
|
||||
})
|
||||
|
||||
describe('what the panel is told', () => {
|
||||
test('a site that runs locally is shown as refused before any e-mail; a public one as "not connected yet"; SMTP and "off" say so', async () => {
|
||||
const local = relayPayload({ serverURL: 'http://localhost:3000' })
|
||||
expect(await mailPanelState(local, {})).toMatchObject({ relay: { connected: false, refusal: { code: 'host-not-allowed' } }, replyAddress: null, transport: 'relay' })
|
||||
const nowhere = relayPayload({ serverURL: '' })
|
||||
expect((await mailPanelState(nowhere, {})).relay?.refusal?.code).toBe('client-no-host')
|
||||
const fresh = relayPayload({ integrations: { smtpFromAddress: ' [email protected] ' } })
|
||||
const state = await mailPanelState(fresh, {})
|
||||
expect(state).toMatchObject({ confirmUrl: 'https://example.com/api/iapl/mail-relay/confirm', relay: { connected: false, host: HOST, senderAddress: '[email protected]' }, replyAddress: '[email protected]', transport: 'relay' })
|
||||
expect(state.relay?.refusal).toBeUndefined()
|
||||
const smtp = relayPayload({ integrations: { smtpHost: 'smtp.example.com', smtpPassword: 'x', smtpUser: 'u' } })
|
||||
expect((await mailPanelState(smtp, {})).transport).toBe('smtp')
|
||||
expect(await mailPanelState(fresh, false)).toMatchObject({ relay: null, transport: 'none' })
|
||||
expect(JSON.stringify([state])).not.toContain('ims_')
|
||||
})
|
||||
})
|
||||
|
||||
describe('the adapter on its own, and the deprecated Graph line', () => {
|
||||
test('relayAdapter() is a whole e-mail adapter', async () => {
|
||||
const { fake, payload } = relaySite({ fake: { allow: [HOST] }, integrations: { smtpFromName: 'Kancelaria Example' } })
|
||||
|
||||
@@ -290,8 +290,10 @@ describe('switched off, and what did not change', () => {
|
||||
const on = await makeConfig(undefined, 'relayon')
|
||||
expect(endpoints(on)).toEqual(expect.arrayContaining(['post /iapl/mail-relay/confirm', 'get /iapl/mail-relay/status', 'post /iapl/mail-relay/connect', 'post /iapl/mail-relay/disconnect']))
|
||||
expect(endpoints(off).filter((e) => e.includes('mail-relay'))).toEqual([])
|
||||
expect(emailTab(on)).toContain('MailRelayStatus')
|
||||
expect(emailTab(off)).not.toContain('MailRelayStatus')
|
||||
expect(emailTab(on)).toContain('"mailRelay":true')
|
||||
expect(emailTab(off)).not.toContain('mailRelay')
|
||||
// no admin component of its own: a site's committed import map stays as it is
|
||||
expect(emailTab(on)).not.toContain('#MailRelayStatus')
|
||||
expect(emailTab(off)).not.toContain('Intecion')
|
||||
expect((off.custom as { iapl: { mail: { relay: unknown } } }).iapl.mail.relay).toBe(false)
|
||||
const hooks = (config: SanitizedConfig) => config.collections?.find((c) => c.slug === 'users')?.hooks?.beforeOperation?.length ?? 0
|
||||
|
||||
Reference in New Issue
Block a user