Mail relay: contract 1.6.0, the token tied to its host, IWSN in the panel
- contracts/mail-relay refreshed from IWDL 83af8c6 (1.6.0) - an answer that is not the service's JSON is 'not confirmed' unless its status is 400 to 499 - a site with a token issued by hand does not enrol to heal: it stops and says what to ask Intecion for - a store made on another host (a database copied to staging) is not used: the copy enrols as itself, nothing is revoked - the panel calls the service IWSN (RELAY_SHORT_NAME); docs, logs and the doctor keep the full name Co-Authored-By: Claude Fable 5.2 <[email protected]>
This commit is contained in:
co-authored by
Claude Fable 5.2
parent
7d766b6d58
commit
0ee74ab2a4
@@ -1,6 +1,22 @@
|
||||
# Changelog of the wire contract
|
||||
|
||||
## 1.5.0 — 2026-11-25 (not released; no tag yet)
|
||||
## 1.6.0 — 2026-11-25 (not released; no tag yet)
|
||||
|
||||
From the first client built against the contract (IAPL's). **The service did not change**; these are the
|
||||
contract's words. What a client built against 1.5.0 has to change is marked.
|
||||
|
||||
- **An answer that is not the service's JSON** is no longer "like `503 unavailable`" for the report: with a
|
||||
status from 400 to 499 it is *not sent*, with any other status (200 included) *not confirmed*.
|
||||
**Client: change the report for that case.** Retrying it is as before.
|
||||
- **A client that cannot keep key and bytes** (§1): no retry by itself after the report; a repeat by a person
|
||||
is a new message; keys derived from the message's record are described, and for such a key
|
||||
`idempotency-conflict` means "already handled". **Client: nothing must change; derived keys are an option.**
|
||||
- **A site with a hand-issued token** does not enrol on `reverify` / `invalid-token`; it reports
|
||||
`relay-refused` and what to ask Intecion for. **Client: nothing, if it already does this.**
|
||||
- **`Origin` / `Sec-Fetch-Site`:** a client sends neither; said in §1. **Client: nothing for Node.**
|
||||
- A stand-in need not reproduce the service's lists; said in §10.
|
||||
|
||||
## 1.5.0 — 2026-11-25 (never released)
|
||||
|
||||
After the third review.
|
||||
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
8573bc968031c595b4e06f6694dd50e1d8e813255023b0397922352dcbc0a758 README.md
|
||||
fc5bd405549ceffe38e47de8e30ce4041556559fd65fb7aa4097c26fb494e9e5 CHANGELOG.md
|
||||
acb57a7135b2d7d6e665f67f056e21353023b93835f54def1ae523bf76f1bfb3 VERSION
|
||||
a5cc857363323400a6d24b45804c8fd964392cd0e61e99a8b120b354ac803e33 README.md
|
||||
05d026ddc45ee9824534ce13f5b8f14bd1475688fe98949e3297f90548e3abb0 CHANGELOG.md
|
||||
cb1d9a30bc4ab8a397f39b7d786bb82aca0b816077eefc35d7c822017d75f6a5 VERSION
|
||||
275ee643112eac77430dba9ea3f93c8f53dc1676b8d56ba95a25dd3f35a8746f schema.json
|
||||
be56a59e13474a8184576fef90cc01145cc3233886d4147e2ac2b867921fba1d runner.mjs
|
||||
913d3776b27076bf1d89639ef903f80c1c1b9bcd702851e9913def2588d73d83 runner.mjs
|
||||
7c46860adee597e570832c72bcdb418752a20b9f7d1b2d7a656ed065f9632b2a checksums.mjs
|
||||
df6015faf02a7cf7e9b5816b9e22b2e82968678ddd72a61c1f9665a8c0897ddf examples/callback-confirm-wordpress.json
|
||||
f5018ca4fb7d25794ee92168d715aaf47feeba3d907c0550651b16c10a691ceb examples/callback-confirm.json
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
# Intecion Notifications Webservice — wire contract
|
||||
|
||||
Version: see [`VERSION`](VERSION) (this text describes **1.5.0**). Path prefix of this major version: `/v1`.
|
||||
Version: see [`VERSION`](VERSION) (this text describes **1.6.0**). Path prefix of this major version: `/v1`.
|
||||
|
||||
This is the whole agreement between the Intecion Notifications Webservice ("the service" below) and a client (the mail transport built into a
|
||||
site's plugin). It names no product: nothing here says Payload, WordPress, IAPL or IAWL except the values of
|
||||
@@ -24,12 +24,19 @@ the `product` field. A client written from this document, in any language, works
|
||||
- HTTPS only. Bodies are JSON in UTF-8. A request with a body carries `Content-Type: application/json`.
|
||||
- **The service is for servers, not browsers.** It sends no CORS header, and it refuses any request that
|
||||
carries an `Origin` header or a `Sec-Fetch-Site` header other than `none` (`403 browser-not-allowed`).
|
||||
A client must send neither. A server runtime's `fetch` that adds them by itself has to be told not to, or the
|
||||
header removed, or the service will take the site for a browser. (`Sec-Fetch-Mode` and `Sec-Fetch-Dest` are
|
||||
not looked at: Node's `fetch` sends `sec-fetch-mode: cors` and passes.)
|
||||
- **Requests are closed:** an unknown field is refused with `400 invalid-request` and the field's name. A
|
||||
client cannot set `From`, `Sender`, `Return-Path` or any free header — there are no such fields.
|
||||
- **Answers are open:** a client ignores fields it does not know.
|
||||
- A client identifies itself with `User-Agent: <product>/<version>` (not checked, used for the log).
|
||||
- **An answer that is not JSON** — an error page of the network in front of the service, an empty body, a cut-off
|
||||
answer — is treated exactly like `503 unavailable` with `retryable: true`, whatever its status.
|
||||
- **An answer that is not the service's JSON** — an error page of the network in front of the service, an empty
|
||||
body, a cut-off answer — is no answer of the service. The client may retry it (as if `retryable` were true),
|
||||
and what it means for a message depends on the status alone:
|
||||
- status **400 to 499**: the request was turned away before the service handled it — **not sent**;
|
||||
- **any other status, `200` included**: the service may have handled the request and only its answer was
|
||||
lost — **not confirmed**, exactly like no answer at all (§1, "Retrying").
|
||||
|
||||
### Answers
|
||||
|
||||
@@ -100,9 +107,29 @@ What the client reports:
|
||||
|---|---|---|
|
||||
| `200` | was accepted | sent |
|
||||
| A refusal with `retryable: false` | was not sent | the status of that code |
|
||||
| `rate-limited`, `unavailable`, `enrolment-in-progress` | was not sent | `relay-unreachable` |
|
||||
| `rate-limited`, `unavailable`, `enrolment-in-progress` (as the service's own JSON), or an answer that is not the service's JSON with a status from 400 to 499 | was not sent | `relay-unreachable` |
|
||||
| `backend-failed`, `internal`, or a code the client does not know | **probably** not sent — the mail back end failed in a way it does not explain, and it does not say whether such a message can still go out | `relay-unreachable`, worded as "probably not sent". Like the next row: the same key and bytes if it is tried again |
|
||||
| **No answer** (time-out, connection lost), or `409 in-progress` | **may have been sent** — the service cannot say yet, or will never be able to | `relay-unreachable`, worded as "not confirmed", never as "not sent". If the client tries this message again later it uses the **same key and bytes**: within 24 hours of the first attempt that cannot produce a second mail — once the service has handed a message to the mail back end, its key either answers with the result or goes on answering `in-progress`; it is never sent again. A client never sends the message under a new key by itself |
|
||||
| **No answer** (time-out, connection lost), an answer that is not the service's JSON with any status outside 400–499, or `409 in-progress` | **may have been sent** — the service cannot say yet, or will never be able to | `relay-unreachable`, worded as "not confirmed", never as "not sent". If the client tries this message again later it uses the **same key and bytes**: within 24 hours of the first attempt that cannot produce a second mail — once the service has handed a message to the mail back end, its key either answers with the result or goes on answering `in-progress`; it is never sent again. A client never sends the message under a new key by itself |
|
||||
|
||||
**"The same key and bytes" — and a client that cannot keep them.** The promise that a message is not sent
|
||||
twice holds for as long as the client still has the message's key and its encoded bytes. What a client does
|
||||
depends on what it can keep:
|
||||
|
||||
- **Within one attempt to deliver a message** (the three tries above) every client keeps both in memory.
|
||||
- **A client with storage for unsent mail** keeps key and bytes with the message and may try again later.
|
||||
- **A client without such storage** does not try again by itself once it has reported. "Not confirmed" is then
|
||||
final for that message: the report says that the mail may or may not have gone out. If a person causes the
|
||||
mail again — submits the form again, presses "send again" — that is a **new message with a new key**, and
|
||||
when the first one did go out, the recipient gets it twice. The service cannot prevent that and a client
|
||||
need not; it should say "not confirmed" in a way that does not invite an immediate repeat.
|
||||
- **A key derived from the message's own record** narrows this without storing the mail: when the mail belongs
|
||||
to something the site stores anyway (a form submission, a password-reset request), the client may build the
|
||||
key from that record's id and the mail's role in it (for example the SHA-256 of both, in the key's
|
||||
alphabet). A second attempt for the same record — after a restart, from another process — then arrives under
|
||||
the same key, and the service answers it with the first result (`replayed`), with `in-progress`, or, when the
|
||||
bytes differ because the mail was built again, with `409 idempotency-conflict`. For a derived key the client
|
||||
treats **`idempotency-conflict` as "this record's mail was already handled"**, not as a bug: no second mail
|
||||
either way. A deliberate "send again" by a person uses a new key (the record's id and a counter).
|
||||
|
||||
## 2. Enrolment — `POST /v1/enrol`
|
||||
|
||||
@@ -194,6 +221,12 @@ Rules a client must know:
|
||||
itself after `401 reverify`; beyond the limit the address used longest ago is dropped and gets `reverify`
|
||||
again. A site whose requests leave from many changing addresses (serverless hosting, a pool of egress
|
||||
addresses) must have the limit raised by Intecion, or it will enrol in a loop.
|
||||
- **A site with a token issued by hand cannot heal by itself.** It holds such a token because it cannot be
|
||||
called back, so "enrol again" is not open to it. Its client does **not** enrol on `401 reverify` or
|
||||
`401 invalid-token`; it stops and reports `relay-refused`, with what the administrator has to ask Intecion
|
||||
for: after `reverify` (the site sends from a server address Intecion does not know yet — after a move, or
|
||||
from a second server) that the new address be added; after `invalid-token` a new token. A client knows that
|
||||
its token was issued by hand because it was pasted into it; the service's answer does not say so.
|
||||
- A site on `localhost` or behind a firewall cannot be called back. Intecion can issue a token by hand; the
|
||||
site stores it the same way.
|
||||
- Use the token only from the site's server. Never print it, never send it to a browser.
|
||||
@@ -317,7 +350,7 @@ not go out ([`StatusResponse`](schema.json)):
|
||||
|
||||
```json
|
||||
{ "ok": true, "state": "active", "host": "example.com", "product": "iapl",
|
||||
"service": { "name": "Intecion Notifications Webservice", "version": "1.0.0", "contract": "1.5.0" },
|
||||
"service": { "name": "Intecion Notifications Webservice", "version": "1.0.0", "contract": "1.6.0" },
|
||||
"sender": { "address": "[email protected]" },
|
||||
"limits": { "messagesPerHour": 30, "messagesPerDay": 200, "recipientsPerMessage": 10,
|
||||
"perRecipientPerDay": 10, "newRecipientsPerDay": 50,
|
||||
@@ -444,6 +477,12 @@ for (const example of examples) await runExample(example, driver) // throws on
|
||||
The service runs every example against the Worker under the local Workers runtime
|
||||
(`services/mail-relay/test/contract.test.ts`). A client's local stand-in for the service runs the same files.
|
||||
|
||||
**A stand-in is not the service.** The examples are chosen so that the rules stated in this document decide
|
||||
them (a sender name with an address in it; a file called `.exe`). The service's own lists — names that are
|
||||
never a client's, file types it does not carry — are not part of the contract, can change without a new
|
||||
version, and need not be reproduced: a stand-in approximates them, and a client must not rely on a name or a
|
||||
file type passing because its stand-in let it pass.
|
||||
|
||||
## 11. Using the contract in a client
|
||||
|
||||
Until a client lives in this repository it **copies** this folder (all of it, `CHECKSUMS` included) from a
|
||||
@@ -456,11 +495,14 @@ Checklist for a client:
|
||||
2. A confirm endpoint (public, rate-limited, `404` unless it holds the nonce, constant-time compare, single
|
||||
use, answers the confirmation as the only output, keeps the earlier token until the new one is accepted).
|
||||
3. A token store that is never readable from outside and never printed.
|
||||
4. Enrol on the first send without a token, after `invalid-token` and after `reverify`. Guard against two
|
||||
processes enrolling at once (`enrolment-in-progress`).
|
||||
4. Enrol on the first send without a token, after `invalid-token` and after `reverify` — unless the token was
|
||||
issued by hand: then stop and report (§2). Guard against two processes enrolling at once
|
||||
(`enrolment-in-progress`).
|
||||
5. One `Idempotency-Key` per message and one encoding of it, both kept across retries; at most three attempts,
|
||||
30 seconds each, ten seconds of waiting in all, only when `retryable`; an enrolment on the way does not
|
||||
count; "no answer" and `in-progress` are reported as not confirmed, never as not sent.
|
||||
count; "no answer", `in-progress` and an answer that is not the service's JSON (unless its status is 400 to
|
||||
499) are reported as not confirmed, never as not sent. No `Origin` or `Sec-Fetch-Site` header. Without
|
||||
storage for unsent mail: no retry after the report; consider keys derived from the record (§1).
|
||||
6. **Limit what a visitor can make the site send as `account` mail.** "Forgot password" for an address somebody
|
||||
types is a visitor's lever like a form: the service lets `account` mail use the whole hour and day and no
|
||||
limit per address, so thirty requests use up the site's hour. The client's own limiter (per address and per
|
||||
|
||||
@@ -1 +1 @@
|
||||
1.5.0
|
||||
1.6.0
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
// No dependency. Works in Node 20+ and in the Workers runtime (uses only WebCrypto, btoa and TextEncoder).
|
||||
// How to use it: README.md, "The examples and the runner".
|
||||
|
||||
export const CONTRACT_VERSION = '1.5.0'
|
||||
export const CONTRACT_VERSION = '1.6.0'
|
||||
|
||||
export class ContractError extends Error {
|
||||
constructor(exampleId, message) {
|
||||
|
||||
+5
-3
@@ -81,12 +81,14 @@ once there are more than 20.
|
||||
keep their doctor rule ids, so settings in a project's doctor file still match.
|
||||
|
||||
### Added
|
||||
- **The Intecion Notifications Webservice as the default e-mail transport** ([email.md](./email.md), AGENT.md §7.2).
|
||||
- **The Intecion Notifications Webservice (IWSN) as the default e-mail transport** ([email.md](./email.md), AGENT.md §7.2).
|
||||
The admin panel calls it **IWSN**; docs, logs and the doctor use the full name.
|
||||
`mailAdapter()` now picks per send: Graph when the panel says so and `GRAPH_*` is set → SMTP when the panel has a
|
||||
server → Graph when `GRAPH_*` is set → the mail service → not configured (`resolveMailTransport`). The site holds no
|
||||
mail key: it enrols by a call-back to its own domain and keeps its token in `payload-kv` (key `iapl:mail-relay` —
|
||||
no field, no column; not readable over REST or GraphQL, an admin included; proven by a test). The token is bound to
|
||||
the site's server addresses, rotated every 90 days, healed by re-enrolment. One message = one `Idempotency-Key` and
|
||||
the site's server addresses and to the host it was issued for (a database copied to another host enrols as itself),
|
||||
rotated every 90 days, healed by re-enrolment. One message = one `Idempotency-Key` and
|
||||
one encoding across at most three attempts; a send with no answer is reported as **not confirmed** (it may be out)
|
||||
and cannot double when sent again. Every message says what it is (form notification, form confirmation, account,
|
||||
test, system): form mail and Payload's "forgot password" are marked by the plugin; `withMailKind` /
|
||||
@@ -109,7 +111,7 @@ once there are more than 20.
|
||||
`withMailKind`, `runWithMailKind`, `mailKindOf`, `expectMailTo`, `buildFormMailKindHook`, `createFakeRelay` (the
|
||||
service in memory, for tests), the constants `RELAY_*`, `MAIL_KINDS`, `MAIL_KIND`, `GRAPH_DEPRECATION_NOTICE`, and
|
||||
their types; `MailRelayStatus` from `/admin`.
|
||||
- The wire contract of the service (version 1.5.0) is copied in the repository (`contracts/mail-relay/`) with a
|
||||
- The wire contract of the service (version 1.6.0) is copied in the repository (`contracts/mail-relay/`) with a
|
||||
checksum test; every example of it runs against the plugin's fake service and against the plugin's client.
|
||||
- **`iapl-doctor` rule `legacy-names`** (info): lists the old names a project still uses, each with the new one.
|
||||
Information, not a defect. A warning only for `iapl-doctor.json` and `ipal-doctor.json` side by side, or one variable
|
||||
|
||||
+5
-3
@@ -121,7 +121,7 @@ the ready-to-send list is in **iapl-setup** stage 0 (iapl-site phase 0 uses the
|
||||
| Languages | which locales, the default locale, URL structure (`/pl/…` for every language, or the default without a prefix) |
|
||||
| Styling | a design system / `DESIGN.md` or plain Tailwind tokens, brand colours, fonts, light/dark theme |
|
||||
| Content | the pages, the collections (blog, case studies, products…), archive pages |
|
||||
| Forms | which forms, who receives them; e-mail: the built-in mail service by default — ask only whether the client wants its **own SMTP server and sender address** (never offer Microsoft Graph: deprecated) |
|
||||
| Forms | which forms, who receives them; e-mail: the Intecion mail service (IWSN in the panel) by default — ask only whether the client wants its **own SMTP server and sender address** (never offer Microsoft Graph: deprecated) |
|
||||
| Analytics and consent | GA4 / GTM / pixels, Consent Mode basic or advanced, cookie banner mode, cookie scan |
|
||||
| SEO / GEO | market and local business data, AI crawler policy (llms.txt, Markdown, MCP, AI bots) |
|
||||
| Data and media | database (Postgres or MongoDB) and its names (`<domain without dots>_prod` / `_dev` — derive, then confirm), media storage (R2 or local disk) |
|
||||
@@ -1249,6 +1249,9 @@ add missing hosts with flags / `extra`; (3) change `mode` to `'enforce'` in both
|
||||
|
||||
### 7.2 E-mail — the mail service (default), SMTP (on request), Graph (deprecated)
|
||||
|
||||
The service is the **Intecion Notifications Webservice**; the admin panel calls it **IWSN** (constant
|
||||
`RELAY_SHORT_NAME`) — say "IWSN" when you tell a client what the panel shows.
|
||||
|
||||
**What you wire — three lines, every site:**
|
||||
|
||||
```ts
|
||||
@@ -1281,8 +1284,7 @@ the mail service → nothing (`mail: { relay: false }` and no SMTP). A site with
|
||||
the mail service that is where replies go; the service's own address has no mailbox.
|
||||
5. Intecion has listed the host; otherwise the site enrols and waits for approval (`relay-pending`).
|
||||
|
||||
**Verify:** Site integrations → E-mail sending → the block "How e-mails are sent" says "Connected to the built-in
|
||||
mail service"; **Send test e-mail** answers "through the built-in mail service, as <name>"; the mail arrives from
|
||||
**Verify:** Site integrations → E-mail sending → the block "How e-mails are sent" says "Connected to IWSN"; **Send test e-mail** answers "through IWSN, as <name>"; the mail arrives from
|
||||
`[email protected]` with the client's name and `Reply-To` the client's address; `iapl-doctor
|
||||
--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()`.
|
||||
|
||||
@@ -101,6 +101,8 @@ through this procedure. Ask only when you are missing something you cannot get y
|
||||
| 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-refused` on a site whose token was entered by hand ("does not know the server this site now runs on" / "access key … no longer valid") | the site moved or got a second server, or its token expired; a site with a hand-issued token cannot enrol by itself | Intecion adds the server's address, or issues a new token (state block → "Enter an access key") |
|
||||
| staging sends nothing after its database was copied from production: "Not connected yet" / "waiting for approval" | expected: production's token is tied to production's host and is not used on the copy; the copy enrolled as itself | Intecion approves the staging host, or staging uses SMTP / `mail: { relay: false }` |
|
||||
| `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 |
|
||||
|
||||
@@ -22,7 +22,7 @@ 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),
|
||||
with the Intecion mail service (IWSN in the panel): 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
|
||||
|
||||
@@ -109,7 +109,7 @@ 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
|
||||
The mail service (the default transport) (IWSN in the panel): 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
|
||||
|
||||
@@ -43,7 +43,7 @@ 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 works through the built-in Intecion mail service with no
|
||||
4. Forms: which forms, who receives the submissions? E-mail works through the built-in Intecion mail service (IWSN in the panel) 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?
|
||||
@@ -646,9 +646,7 @@ scaling (5). `●` routes for pages need the database at build time (PROGRAMISTA
|
||||
6. **Notifications**: form messages in every language.
|
||||
7. **Site integrations → E-mail sending**: "Sender name" (the client's name; empty = the site name) and **"Sender
|
||||
address"** (the client's address: with the mail service replies go there). SMTP fields **only** when the client asked
|
||||
for its own server. On the production domain: the block "How e-mails are sent" must say "Connected to 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
|
||||
for its own server. On the production domain: the block "How e-mails are sent" must say "Connected to IWSN" ("waiting for approval" = ask Intecion to approve the host), 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.
|
||||
|
||||
@@ -552,7 +552,7 @@ 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;
|
||||
**→ 1.17.0, e-mail (the Intecion mail service (IWSN in the panel) 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").
|
||||
|
||||
+3
-2
@@ -54,8 +54,9 @@ Mail needs **no variable**. A site with no SMTP server in the panel sends throug
|
||||
- **That route reachable from the internet** — no basic auth on the Coolify app, no firewall or WAF rule in front of
|
||||
`/api/iapl/`; behind Cloudflare leave it uncached and unchallenged.
|
||||
- **Outbound HTTPS** to `webservices.intecion.net`.
|
||||
- A staging copy on its own domain enrols as its own site (its own token, its own limits, its own approval); a
|
||||
staging copy that must not send: `iapl({ mail: { relay: false } })` or SMTP to a catcher.
|
||||
- A staging copy on its own domain enrols as its own site (its own token, its own limits, its own approval) —
|
||||
**also when its database is a copy of production's**: the stored token is tied to production's host and is not
|
||||
used on another one. A staging copy that must not send: `iapl({ mail: { relay: false } })` or SMTP to a catcher.
|
||||
- Several containers of one site share the database, so they share the token; a restore of an old database dump
|
||||
brings back an old token — the site then enrols again by itself on its next e-mail.
|
||||
|
||||
|
||||
+22
-8
@@ -1,7 +1,8 @@
|
||||
# email
|
||||
|
||||
Mail works with **no setup**: a site with no SMTP server in the panel sends through the
|
||||
**Intecion Notifications Webservice** (below: "the mail service"), from
|
||||
**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 |
|
||||
@@ -165,11 +166,17 @@ await runWithMailKind('account', () => sendWelcomeMails(payload, user))
|
||||
- A message is encoded **once**; exactly those bytes go out on every attempt, under one `Idempotency-Key`. At most
|
||||
**three attempts**, 30 seconds each, at most ten seconds of waiting between them in all — and only after an answer
|
||||
the service marks retryable, or after no answer. An enrolment on the way is not one of the three.
|
||||
- **No answer at all** (time-out, connection lost) is reported as `relay-not-confirmed` with `confirmed: false`: the
|
||||
message **may have been sent**. Sending the same message again within 24 hours reuses the same key, so the
|
||||
service answers with what happened to the first attempt (`replayed: true`) and no second mail goes out.
|
||||
- **No answer of the service** — a time-out, a lost connection, or an answer that is not the service's own JSON (an
|
||||
error page of the network in front, a cut-off body) with any status outside 400–499, `200` included — is reported
|
||||
as `relay-not-confirmed` with `confirmed: false`: the message **may have been sent**. Such an answer with a status
|
||||
from 400 to 499 was turned away before the service handled it: `relay-unreachable`, not sent.
|
||||
- **"Not confirmed" is final for that message.** The plugin keeps no unsent mail (no stored outbox), so it does not
|
||||
try again by itself after the report. While the same process is running, the same message sent again within
|
||||
24 hours goes out under the same key — the service then answers with what happened to the first attempt
|
||||
(`replayed: true`) and no second mail goes out. After a restart, or from another instance of the site, a repeat
|
||||
(a visitor submitting the form again) is a new message: if the first one did go out, the recipient gets two.
|
||||
That is why the panel says "it may have been sent; check the mailbox before trying again".
|
||||
- The form **keeps working** meanwhile — the submission is saved in Form Submissions; only the mail is missing.
|
||||
- There is no stored outbox: a message that failed is not sent later by itself.
|
||||
|
||||
### The token
|
||||
|
||||
@@ -177,6 +184,10 @@ await runWithMailKind('account', () => sendWelcomeMails(payload, user))
|
||||
`RELAY_KV_KEY` = `iapl:mail-relay`). **No field, no column, no migration.** That collection refuses every
|
||||
operation through access control and is hidden in the panel, so the token cannot be read over REST or GraphQL —
|
||||
not by an admin either. It is never logged and never sent to a browser.
|
||||
- **The token belongs to the host it was issued for.** A store found on another host — a production database
|
||||
copied to a staging domain, a site moved to a new domain — is not used: the copy forgets the token (nothing is
|
||||
revoked, the other site keeps working), starts unenrolled and enrols as itself, with its own token, limits and
|
||||
approval. The start log says so once.
|
||||
- The token works only from the server addresses the site enrolled from. After a move to another server the
|
||||
service answers "enrol again"; the site does, by the same call-back, and sends. A site whose requests leave from
|
||||
many changing addresses (serverless, a pool of egress addresses) needs its limit of addresses raised by Intecion.
|
||||
@@ -188,6 +199,9 @@ await runWithMailKind('account', () => sendWelcomeMails(payload, user))
|
||||
the site from enrolling by itself until "Connect again" (`enrolRelay(payload, { force: true })`).
|
||||
- **A token issued by hand** — for a site the service cannot call back (behind a firewall): Intecion issues one,
|
||||
an admin enters it in the state block ("Enter an access key"), or a script calls `setRelayToken(payload, token)`.
|
||||
**Such a site cannot heal by itself:** it never enrols on its own. When the service no longer knows its server
|
||||
address (after a move, or a second server) or its token, the send reports `relay-refused` and the state block
|
||||
says what to ask Intecion for — the new address added, or a new token.
|
||||
- Encryption at rest: none, like `smtpPassword`. A token read from a database dump is of little use — it does not
|
||||
work from another server address.
|
||||
|
||||
@@ -223,7 +237,7 @@ the service), each with a text in the editor's language:
|
||||
|---|---|---|
|
||||
| `relay-pending` | enrolled, waiting for approval by Intecion | Intecion approves the host; nothing to do on the site |
|
||||
| `relay-suspended` | stopped by Intecion | contact Intecion; SMTP in the panel sends meanwhile |
|
||||
| `relay-refused` | the site could not enrol | "When the site cannot be confirmed" below |
|
||||
| `relay-refused` | the site could not enrol; or a token issued by hand stopped working (new server address, token no longer valid) | "When the site cannot be confirmed" below; hand-issued: ask Intecion for the address to be added or for a new token |
|
||||
| `relay-disconnected` | an admin pressed "Disconnect" | "Connect again", or fill in SMTP |
|
||||
| `relay-quota` | a limit of the site or of the whole service; too many recipients; the site's own limit on account mail | wait; ask Intecion for other limits; SMTP for a site that sends more |
|
||||
| `relay-too-large` | text or files over the service's limit | a smaller file; `forms.attachments.maxFileSize`; SMTP |
|
||||
@@ -430,7 +444,7 @@ To the mail service (when the owner says so):
|
||||
2. Intecion lists the host on the service (or approves it after the first send).
|
||||
3. Remove the four `GRAPH_*` variables in Coolify and redeploy. If "Sending method" says Microsoft Graph, set it
|
||||
to "Automatic".
|
||||
4. Site integrations → E-mail sending → send a test e-mail: the answer says "through the built-in mail service".
|
||||
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).
|
||||
|
||||
@@ -576,7 +590,7 @@ The large path, step by step, and what happens when it fails:
|
||||
## Test send — button in the panel
|
||||
|
||||
The E-mail sending tab has a **Send test e-mail** button: enter an address, click, and a test mail goes out through
|
||||
the CURRENT transport (`payload.sendEmail`). The answer names the transport ("through the built-in mail service,
|
||||
the CURRENT transport (`payload.sendEmail`). The answer names the transport ("through IWSN,
|
||||
as …", "through your SMTP server") and, for the mail service, the sender name that was used. Tick **Attach a 10 MB
|
||||
test file** to check that a file of that size gets through ("Attachments" above). Endpoint
|
||||
`POST /api/ipal/test-email`, body `{ to, attachmentMB? }` (`admin` role only — needs roles from the `access` option:
|
||||
|
||||
+2
-1
@@ -998,13 +998,14 @@ document, the fields under `version`, where field hooks do not run: the global's
|
||||
|
||||
## The mail service's token and its public route (`mail.relay`)
|
||||
|
||||
A site that sends through the Intecion Notifications Webservice ([email.md](./email.md)) holds one secret: its own
|
||||
A site that sends through the Intecion Notifications Webservice (IWSN in the panel; [email.md](./email.md)) holds one secret: its own
|
||||
token. What protects it, and what the new public route can and cannot do:
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| **No key in the package** | The plugin carries the service's address and nothing else. A site gets its token by proving it is served at its host: it makes a nonce, the service calls `POST https://<host>/api/iapl/mail-relay/confirm` with the nonce and a token, and only an answer that hashes both makes the token valid |
|
||||
| **Where the token is** | `payload-kv`, key `iapl:mail-relay`. The collection refuses every operation through access control (`read`, `create`, `update`, `delete` are `false`) and is hidden: REST, GraphQL and the panel cannot reach it — an admin included (test: `test/mailRelayHttp.test.ts`). Server code with the Local API can, like `smtpPassword`. It is stored as it is (no encryption at rest), never logged, never sent to a browser, never part of a route's answer |
|
||||
| **A database copied to another host** | the token is tied to the host it was issued for: a copy on a staging domain does not use production's token — it forgets it, without revoking it, and enrols as itself |
|
||||
| **A token read from a database dump** | does not work from another server: the service accepts a token only from the addresses the site enrolled from (IPv6: the same `/64`) and answers anything else "enrol again" — which needs the call-back to the real site. It cannot send as another site, and the limits below apply |
|
||||
| **What a token can do at most** | send within the site's limits (30 an hour, 200 a day, 10 recipients, 10 MB by default) from the service's fixed address, under a sender name the service checks, with `X-Intecion-Site: <host>` on every mail. It cannot set `From`, `Return-Path` or any header, and cannot address a security alert |
|
||||
| **The confirm route** | public by design, `404` with an empty body unless the body carries a nonce **this site** made in the last 5 minutes (kept as a hash, compared in constant time, single use). It stores the delivered token **beside** the one in use and never replaces a working token: a token becomes the one in use only after the service has accepted it. Rate-limited per address (10 a minute, `mail.relay.confirmRateLimit`). A stranger who calls it learns nothing and changes nothing |
|
||||
|
||||
@@ -101,6 +101,8 @@ through this procedure. Ask only when you are missing something you cannot get y
|
||||
| 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-refused` on a site whose token was entered by hand ("does not know the server this site now runs on" / "access key … no longer valid") | the site moved or got a second server, or its token expired; a site with a hand-issued token cannot enrol by itself | Intecion adds the server's address, or issues a new token (state block → "Enter an access key") |
|
||||
| staging sends nothing after its database was copied from production: "Not connected yet" / "waiting for approval" | expected: production's token is tied to production's host and is not used on the copy; the copy enrolled as itself | Intecion approves the staging host, or staging uses SMTP / `mail: { relay: false }` |
|
||||
| `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 |
|
||||
|
||||
@@ -22,7 +22,7 @@ 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),
|
||||
with the Intecion mail service (IWSN in the panel): 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
|
||||
|
||||
@@ -109,7 +109,7 @@ 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
|
||||
The mail service (the default transport) (IWSN in the panel): 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
|
||||
|
||||
@@ -43,7 +43,7 @@ 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 works through the built-in Intecion mail service with no
|
||||
4. Forms: which forms, who receives the submissions? E-mail works through the built-in Intecion mail service (IWSN in the panel) 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?
|
||||
@@ -646,9 +646,7 @@ scaling (5). `●` routes for pages need the database at build time (PROGRAMISTA
|
||||
6. **Notifications**: form messages in every language.
|
||||
7. **Site integrations → E-mail sending**: "Sender name" (the client's name; empty = the site name) and **"Sender
|
||||
address"** (the client's address: with the mail service replies go there). SMTP fields **only** when the client asked
|
||||
for its own server. On the production domain: the block "How e-mails are sent" must say "Connected to 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
|
||||
for its own server. On the production domain: the block "How e-mails are sent" must say "Connected to IWSN" ("waiting for approval" = ask Intecion to approve the host), 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.
|
||||
|
||||
@@ -552,7 +552,7 @@ 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;
|
||||
**→ 1.17.0, e-mail (the Intecion mail service (IWSN in the panel) 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").
|
||||
|
||||
@@ -70,7 +70,7 @@ test.describe('the mail service', () => {
|
||||
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 })
|
||||
await expect(page.getByText(/Test e-mail sent to anna@example\.org through IWSN|Testowy e-mail wysłano na adres anna@example\.org przez IWSN/)).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'])
|
||||
@@ -79,7 +79,7 @@ test.describe('the mail service', () => {
|
||||
|
||||
// "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(/Connected to IWSN|Połączono z IWSN/)
|
||||
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)
|
||||
|
||||
@@ -2783,7 +2783,7 @@ export interface SiteIntegration {
|
||||
checkedAt?: string | null;
|
||||
};
|
||||
/**
|
||||
* Automatic uses your SMTP server when it is filled in below, and the built-in mail service otherwise.
|
||||
* Automatic uses your SMTP server when it is filled in below, and IWSN otherwise.
|
||||
*/
|
||||
emailTransport?: ('smtp' | 'graph') | null;
|
||||
/**
|
||||
@@ -2795,7 +2795,7 @@ export interface SiteIntegration {
|
||||
*/
|
||||
smtpFromName?: string | null;
|
||||
/**
|
||||
* Optional: fill in only to send through your own mail server instead of the built-in mail service.
|
||||
* Optional: fill in only to send through your own mail server instead of IWSN.
|
||||
*/
|
||||
smtpHost?: string | null;
|
||||
/**
|
||||
|
||||
@@ -82,11 +82,13 @@ export const MailRelayStatus = () => {
|
||||
const relay = state.relay
|
||||
const onRelay = state.transport === 'relay'
|
||||
const relayState = !relay ? '' : relay.disconnected ? text('mailRelayStateDisconnected')
|
||||
: !relay.connected ? (state.refusalText ?? text('mailRelayStateNotConnected'))
|
||||
// why the service does not take this site: a refused enrolment, or a hand-issued token that stopped working
|
||||
: state.refusalText ? state.refusalText
|
||||
: !relay.connected ? text('mailRelayStateNotConnected')
|
||||
: relay.state === 'pending' ? text('mailRelayStatePending')
|
||||
: relay.state === 'suspended' ? text('mailRelayStateSuspended')
|
||||
: text('mailRelayStateActive')
|
||||
const attention = Boolean(relay && onRelay && (relay.disconnected || relay.state === 'pending' || relay.state === 'suspended' || (!relay.connected && state.refusalText)))
|
||||
const attention = Boolean(relay && onRelay && (relay.disconnected || relay.state === 'pending' || relay.state === 'suspended' || state.refusalText))
|
||||
|
||||
return (
|
||||
<div data-mail-transport={state.transport} style={box}>
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import type { Condition, Field } from 'payload'
|
||||
|
||||
import { RELAY_SHORT_NAME as IWSN } from '../../../modules/email/relay/constants.js'
|
||||
import { buildIntegrationStatusBanner, buildIntegrationStatusField } from '../../../modules/integrations/status.js'
|
||||
|
||||
/**
|
||||
@@ -36,8 +37,8 @@ export const buildSmtpFields = ({ relay = true }: { relay?: boolean } = {}): Fie
|
||||
admin: {
|
||||
description: relay
|
||||
? {
|
||||
en: 'Automatic uses your SMTP server when it is filled in below, and the built-in mail service otherwise.',
|
||||
pl: 'Automatycznie: przez Twój serwer SMTP, jeśli jest uzupełniony poniżej, a w innym razie przez wbudowaną usługę pocztową.',
|
||||
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.',
|
||||
@@ -108,8 +109,8 @@ export const buildSmtpFields = ({ relay = true }: { relay?: boolean } = {}): Fie
|
||||
...(relay
|
||||
? {
|
||||
description: {
|
||||
en: 'Optional: fill in only to send through your own mail server instead of the built-in mail service.',
|
||||
pl: 'Opcjonalne: uzupełnij tylko, aby wysyłać przez własny serwer zamiast wbudowanej usługi pocztowej.',
|
||||
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}.`,
|
||||
},
|
||||
}
|
||||
: {}),
|
||||
|
||||
@@ -243,6 +243,7 @@ export {
|
||||
RELAY_PRODUCT,
|
||||
RELAY_SENDER_ADDRESS,
|
||||
RELAY_SERVICE_NAME,
|
||||
RELAY_SHORT_NAME,
|
||||
RELAY_STATUS_CODES,
|
||||
relayAdapter,
|
||||
relayAttachmentLimit,
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { RELAY_SHORT_NAME as IWSN } from '../../email/relay/constants.js'
|
||||
import { defineTexts } from '../define.js'
|
||||
|
||||
/** Admin component texts — integrations. Placeholders use Payload's {{name}} syntax. */
|
||||
@@ -12,37 +13,39 @@ export const integrationsTexts = defineTexts({
|
||||
// Intecion mail service: the state block on the e-mail tab (MailRelayStatus) and its routes
|
||||
mailRelayCheck: 'Check now',
|
||||
mailRelayConnect: 'Connect again',
|
||||
mailRelayConnected: 'The site is connected to the built-in mail service.',
|
||||
mailRelayConnected: `The site is connected to ${IWSN}.`,
|
||||
mailRelayConnectFailed: 'The site could not be connected. {{reason}}',
|
||||
mailRelayDisconnect: 'Disconnect',
|
||||
mailRelayDisconnectConfirm: 'Disconnect the site from the built-in mail service? E-mails will not be sent until you connect again or fill in an SMTP server.',
|
||||
mailRelayDisconnected: 'The site is disconnected from the built-in mail service.',
|
||||
mailRelayDisconnectConfirm: `Disconnect the site from ${IWSN}? E-mails will not be sent until you connect again or fill in an SMTP server.`,
|
||||
mailRelayDisconnected: `The site is disconnected from ${IWSN}.`,
|
||||
mailRelayForbidden: 'Only an administrator can do this.',
|
||||
mailRelayHeading: 'How e-mails are sent',
|
||||
mailRelayLoadFailed: 'The state could not be read. Try again.',
|
||||
mailRelayLoggedOut: 'Your session has ended. Log in again.',
|
||||
mailRelayNameReplaced: 'The sender name "{{asked}}" was not accepted, so e-mails leave as "{{used}}". Choose another name below.',
|
||||
mailRelayNameReplaced: `${IWSN} did not accept the sender name "{{asked}}", so e-mails leave as "{{used}}". Choose another name below.`,
|
||||
mailRelayNoReplyAddress: 'No reply address is set. Fill in "Sender address" below, or replies to these e-mails will be lost.',
|
||||
mailRelayOff: 'The built-in mail service is switched off for this site.',
|
||||
mailRelayOff: `${IWSN} is switched off for this site.`,
|
||||
mailRelayQuota: 'Left this hour: {{hour}}. Left today: {{day}}.',
|
||||
mailRelayRefusedCallback: 'The mail service could not reach this site at {{url}}. Reason: {{reason}}. Ask your administrator.',
|
||||
mailRelayRefusedClosed: 'The mail service does not take new sites at the moment. Ask your administrator.',
|
||||
mailRelayRefusedHost: 'This site has no public address yet ({{host}}). The mail service works once the site runs on its domain.',
|
||||
mailRelayRefusedAddress: `${IWSN} does not know the server this site now runs on. Ask your administrator to have its address added.`,
|
||||
mailRelayRefusedCallback: `${IWSN} could not reach this site at {{url}}. Reason: {{reason}}. Ask your administrator.`,
|
||||
mailRelayRefusedClosed: `${IWSN} does not take new sites at the moment. Ask your administrator.`,
|
||||
mailRelayRefusedHost: `This site has no public address yet ({{host}}). ${IWSN} works once the site runs on its domain.`,
|
||||
mailRelayRefusedNoHost: 'The site does not know its own address. Ask your administrator.',
|
||||
mailRelayRefusedOther: 'The mail service answered: {{message}}',
|
||||
mailRelayRefusedOther: `${IWSN} answered: {{message}}`,
|
||||
mailRelayRefusedToken: `The access key of this site is no longer valid. Ask your administrator for a new one.`,
|
||||
mailRelayRepliesTo: 'Replies go to {{address}}.',
|
||||
mailRelayStateActive: 'Connected to the built-in mail service.',
|
||||
mailRelayStateActive: `Connected to ${IWSN}.`,
|
||||
mailRelayStateDisconnected: 'Disconnected. E-mails are not sent until you connect again or fill in an SMTP server.',
|
||||
mailRelayStateNotConnected: 'Not connected yet. The site connects by itself when it sends its first e-mail.',
|
||||
mailRelayStatePending: 'The site is waiting for approval, so e-mails are not sent yet. Ask your administrator.',
|
||||
mailRelayStateSuspended: 'E-mail sending was stopped for this site. Ask your administrator.',
|
||||
mailRelayToken: 'Enter an access key',
|
||||
mailRelayTokenHint: 'Only when your administrator gave you a key for this site. It is stored and never shown again.',
|
||||
mailRelayTokenInvalid: 'This is not an access key of the mail service.',
|
||||
mailRelayTokenInvalid: `This is not an access key of ${IWSN}.`,
|
||||
mailRelayTokenSave: 'Save the key',
|
||||
mailRelayTransportGraph: 'E-mails go through Microsoft Graph. This method will be removed in version 2.0.',
|
||||
mailRelayTransportNone: 'No sending method is set up. E-mails are not sent.',
|
||||
mailRelayTransportRelay: 'E-mails go through the built-in mail service, from {{address}}.',
|
||||
mailRelayTransportRelay: `E-mails go through ${IWSN}, from {{address}}.`,
|
||||
mailRelayTransportSmtp: 'E-mails go through your SMTP server.',
|
||||
mailRelayWorking: 'Working…',
|
||||
|
||||
@@ -74,17 +77,17 @@ 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.',
|
||||
statusEmailRelayAttachmentRefused: 'The built-in mail service does not carry this type of file. The e-mail was not sent.',
|
||||
statusEmailRelayDisconnected: 'The site is disconnected from the built-in mail service, so e-mails are not sent. Connect again, or fill in an SMTP server.',
|
||||
statusEmailRelayError: 'The built-in mail service refused the e-mail. Tell your administrator.',
|
||||
statusEmailRelayNotConfirmed: 'The built-in mail service did not confirm the last e-mail. It may have been 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.`,
|
||||
statusEmailRelayNotConfirmed: `${IWSN} did not confirm the last e-mail. It may have been sent.`,
|
||||
statusEmailRelayPending: 'The site is waiting for approval, so e-mails are not sent yet. Ask your administrator.',
|
||||
statusEmailRelayQuota: 'The site reached a sending limit of the built-in mail service. The e-mail was not sent.',
|
||||
statusEmailRelayRecipientSuppressed: 'The mail service refuses one of the recipients, because earlier e-mails to that address came back. Nothing was sent.',
|
||||
statusEmailRelayRefused: 'The built-in mail service did not connect this site. See the state above, or fill in an SMTP server.',
|
||||
statusEmailRelayQuota: `The site reached a sending limit of ${IWSN}. The e-mail was not sent.`,
|
||||
statusEmailRelayRecipientSuppressed: `${IWSN} refuses one of the recipients, because earlier e-mails to that address came back. Nothing was sent.`,
|
||||
statusEmailRelayRefused: `${IWSN} did not connect this site. See the state above, or fill in an SMTP server.`,
|
||||
statusEmailRelaySuspended: 'E-mail sending was stopped for this site. Ask your administrator.',
|
||||
statusEmailRelayTooLarge: 'The e-mail or its files are larger than the built-in mail service carries. The e-mail was not sent.',
|
||||
statusEmailRelayUnreachable: 'The built-in mail service could not be reached or failed. The e-mail was probably not sent.',
|
||||
statusEmailRelayTooLarge: `The e-mail or its files are larger than ${IWSN} carries. The e-mail was not sent.`,
|
||||
statusEmailRelayUnreachable: `${IWSN} could not be reached or failed. The e-mail was probably not sent.`,
|
||||
statusTurnstileBadResponse: 'Cloudflare sent an unexpected response.',
|
||||
statusTurnstileInternalError: 'Cloudflare reported an internal error. It usually passes on its own.',
|
||||
statusTurnstileInvalidSecret: 'Cloudflare rejected the secret key. Both keys must come from the same widget.',
|
||||
@@ -104,12 +107,12 @@ export const integrationsTexts = defineTexts({
|
||||
testEmailLoggedOut: 'Your session has ended. Log in again.',
|
||||
testEmailNoConnection: 'Could not reach the server. Check your connection and try again.',
|
||||
testEmailNotConfigured: 'Fill in the server, user name and password, then save.',
|
||||
testEmailNotConfirmed: 'The mail service did not confirm the test e-mail. It may have been sent; check the mailbox before trying again.',
|
||||
testEmailNotConfirmed: `${IWSN} did not confirm the test e-mail. It may have been sent; check the mailbox before trying again.`,
|
||||
testEmailRecipient: 'Recipient address',
|
||||
testEmailSend: 'Send test e-mail',
|
||||
testEmailSending: 'Sending…',
|
||||
testEmailSent: 'Test e-mail sent to {{to}}.',
|
||||
testEmailSentRelay: 'Test e-mail sent to {{to}} through the built-in mail service, as "{{name}}".',
|
||||
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}}',
|
||||
testEmailSubjectGeneric: 'Test e-mail from your website',
|
||||
@@ -123,37 +126,39 @@ export const integrationsTexts = defineTexts({
|
||||
|
||||
mailRelayCheck: 'Sprawdź teraz',
|
||||
mailRelayConnect: 'Połącz ponownie',
|
||||
mailRelayConnected: 'Witryna jest połączona z wbudowaną usługą pocztową.',
|
||||
mailRelayConnected: `Witryna jest połączona z ${IWSN}.`,
|
||||
mailRelayConnectFailed: 'Nie udało się połączyć witryny. {{reason}}',
|
||||
mailRelayDisconnect: 'Rozłącz',
|
||||
mailRelayDisconnectConfirm: 'Rozłączyć witrynę z wbudowaną usługą pocztową? E-maile nie będą wysyłane, dopóki nie połączysz jej ponownie albo nie uzupełnisz serwera SMTP.',
|
||||
mailRelayDisconnected: 'Witryna jest rozłączona z wbudowaną usługą pocztową.',
|
||||
mailRelayDisconnectConfirm: `Rozłączyć witrynę z ${IWSN}? E-maile nie będą wysyłane, dopóki nie połączysz jej ponownie albo nie uzupełnisz serwera SMTP.`,
|
||||
mailRelayDisconnected: `Witryna jest rozłączona z ${IWSN}.`,
|
||||
mailRelayForbidden: 'Tylko administrator może to zrobić.',
|
||||
mailRelayHeading: 'Jak wysyłane są e-maile',
|
||||
mailRelayLoadFailed: 'Nie udało się odczytać stanu. Spróbuj ponownie.',
|
||||
mailRelayLoggedOut: 'Sesja wygasła. Zaloguj się ponownie.',
|
||||
mailRelayNameReplaced: 'Nazwa nadawcy „{{asked}}” nie została przyjęta, więc e-maile wychodzą jako „{{used}}”. Wybierz inną nazwę poniżej.',
|
||||
mailRelayNameReplaced: `${IWSN} nie przyjął nazwy nadawcy „{{asked}}”, więc e-maile wychodzą jako „{{used}}”. Wybierz inną nazwę poniżej.`,
|
||||
mailRelayNoReplyAddress: 'Nie ustawiono adresu do odpowiedzi. Uzupełnij „Adres nadawcy” poniżej, inaczej odpowiedzi na te e-maile przepadną.',
|
||||
mailRelayOff: 'Wbudowana usługa pocztowa jest wyłączona dla tej witryny.',
|
||||
mailRelayOff: `${IWSN} jest wyłączony dla tej witryny.`,
|
||||
mailRelayQuota: 'Pozostało w tej godzinie: {{hour}}. Pozostało dziś: {{day}}.',
|
||||
mailRelayRefusedCallback: 'Usługa pocztowa nie mogła połączyć się z witryną pod adresem {{url}}. Powód: {{reason}}. Zapytaj administratora.',
|
||||
mailRelayRefusedClosed: 'Usługa pocztowa nie przyjmuje teraz nowych witryn. Zapytaj administratora.',
|
||||
mailRelayRefusedHost: 'Witryna nie ma jeszcze publicznego adresu ({{host}}). Usługa pocztowa zadziała, gdy witryna będzie dostępna pod swoją domeną.',
|
||||
mailRelayRefusedAddress: `${IWSN} nie zna serwera, na którym teraz działa witryna. Poproś administratora o dodanie jego adresu.`,
|
||||
mailRelayRefusedCallback: `${IWSN} nie mógł połączyć się z witryną pod adresem {{url}}. Powód: {{reason}}. Zapytaj administratora.`,
|
||||
mailRelayRefusedClosed: `${IWSN} nie przyjmuje teraz nowych witryn. Zapytaj administratora.`,
|
||||
mailRelayRefusedHost: `Witryna nie ma jeszcze publicznego adresu ({{host}}). ${IWSN} zadziała, gdy witryna będzie dostępna pod swoją domeną.`,
|
||||
mailRelayRefusedNoHost: 'Witryna nie zna własnego adresu. Zapytaj administratora.',
|
||||
mailRelayRefusedOther: 'Usługa pocztowa odpowiedziała: {{message}}',
|
||||
mailRelayRefusedOther: `${IWSN} odpowiedział: {{message}}`,
|
||||
mailRelayRefusedToken: `Klucz dostępu tej witryny stracił ważność. Poproś administratora o nowy.`,
|
||||
mailRelayRepliesTo: 'Odpowiedzi trafiają na adres {{address}}.',
|
||||
mailRelayStateActive: 'Połączono z wbudowaną usługą pocztową.',
|
||||
mailRelayStateActive: `Połączono z ${IWSN}.`,
|
||||
mailRelayStateDisconnected: 'Rozłączono. E-maile nie są wysyłane, dopóki nie połączysz witryny ponownie albo nie uzupełnisz serwera SMTP.',
|
||||
mailRelayStateNotConnected: 'Jeszcze nie połączono. Witryna połączy się sama, gdy wyśle pierwszy e-mail.',
|
||||
mailRelayStatePending: 'Witryna czeka na zatwierdzenie, więc e-maile nie są jeszcze wysyłane. Zapytaj administratora.',
|
||||
mailRelayStateSuspended: 'Wysyłka e-maili z tej witryny została wstrzymana. Zapytaj administratora.',
|
||||
mailRelayToken: 'Wpisz klucz dostępu',
|
||||
mailRelayTokenHint: 'Tylko jeśli administrator przekazał Ci klucz dla tej witryny. Klucz zostanie zapisany i nie będzie więcej pokazywany.',
|
||||
mailRelayTokenInvalid: 'To nie jest klucz dostępu usługi pocztowej.',
|
||||
mailRelayTokenInvalid: `To nie jest klucz dostępu ${IWSN}.`,
|
||||
mailRelayTokenSave: 'Zapisz klucz',
|
||||
mailRelayTransportGraph: 'E-maile idą przez Microsoft Graph. Ten sposób zostanie usunięty w wersji 2.0.',
|
||||
mailRelayTransportNone: 'Nie ustawiono żadnego sposobu wysyłki. E-maile nie są wysyłane.',
|
||||
mailRelayTransportRelay: 'E-maile idą przez wbudowaną usługę pocztową, z adresu {{address}}.',
|
||||
mailRelayTransportRelay: `E-maile idą przez ${IWSN}, z adresu {{address}}.`,
|
||||
mailRelayTransportSmtp: 'E-maile idą przez Twój serwer SMTP.',
|
||||
mailRelayWorking: 'Trwa…',
|
||||
|
||||
@@ -182,17 +187,17 @@ 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.',
|
||||
statusEmailRelayAttachmentRefused: 'Wbudowana usługa pocztowa nie przesyła plików tego typu. E-mail nie został wysłany.',
|
||||
statusEmailRelayDisconnected: 'Witryna jest rozłączona z wbudowaną usługą pocztową, więc e-maile nie są wysyłane. Połącz ją ponownie albo uzupełnij serwer SMTP.',
|
||||
statusEmailRelayError: 'Wbudowana usługa pocztowa odrzuciła e-mail. Powiadom administratora.',
|
||||
statusEmailRelayNotConfirmed: 'Wbudowana usługa pocztowa nie potwierdziła ostatniego e-maila. Mógł zostać wysłany.',
|
||||
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.`,
|
||||
statusEmailRelayNotConfirmed: `${IWSN} nie potwierdził ostatniego e-maila. Mógł zostać wysłany.`,
|
||||
statusEmailRelayPending: 'Witryna czeka na zatwierdzenie, więc e-maile nie są jeszcze wysyłane. Zapytaj administratora.',
|
||||
statusEmailRelayQuota: 'Witryna osiągnęła limit wysyłki we wbudowanej usłudze pocztowej. E-mail nie został wysłany.',
|
||||
statusEmailRelayRecipientSuppressed: 'Usługa pocztowa odrzuca jednego z odbiorców, bo wcześniejsze e-maile na ten adres wróciły. Nic nie zostało wysłane.',
|
||||
statusEmailRelayRefused: 'Wbudowana usługa pocztowa nie połączyła tej witryny. Zobacz stan powyżej albo uzupełnij serwer SMTP.',
|
||||
statusEmailRelayQuota: `Witryna osiągnęła limit wysyłki w ${IWSN}. E-mail nie został wysłany.`,
|
||||
statusEmailRelayRecipientSuppressed: `${IWSN} odrzuca jednego z odbiorców, bo wcześniejsze e-maile na ten adres wróciły. Nic nie zostało wysłane.`,
|
||||
statusEmailRelayRefused: `${IWSN} nie połączył tej witryny. Zobacz stan powyżej albo uzupełnij serwer SMTP.`,
|
||||
statusEmailRelaySuspended: 'Wysyłka e-maili z tej witryny została wstrzymana. Zapytaj administratora.',
|
||||
statusEmailRelayTooLarge: 'E-mail lub jego pliki są większe, niż przesyła wbudowana usługa pocztowa. E-mail nie został wysłany.',
|
||||
statusEmailRelayUnreachable: 'Wbudowana usługa pocztowa była nieosiągalna albo zawiodła. E-mail prawdopodobnie nie został wysłany.',
|
||||
statusEmailRelayTooLarge: `E-mail lub jego pliki są większe, niż przesyła ${IWSN}. E-mail nie został wysłany.`,
|
||||
statusEmailRelayUnreachable: `${IWSN} był nieosiągalny albo zawiódł. E-mail prawdopodobnie nie został wysłany.`,
|
||||
statusTurnstileBadResponse: 'Cloudflare zwrócił nieoczekiwaną odpowiedź.',
|
||||
statusTurnstileInternalError: 'Cloudflare zgłosił błąd wewnętrzny. Zwykle ustępuje samoczynnie.',
|
||||
statusTurnstileInvalidSecret: 'Cloudflare odrzucił klucz tajny. Oba klucze muszą pochodzić z tego samego widżetu.',
|
||||
@@ -211,12 +216,12 @@ export const integrationsTexts = defineTexts({
|
||||
testEmailLoggedOut: 'Sesja wygasła. Zaloguj się ponownie.',
|
||||
testEmailNoConnection: 'Brak połączenia z serwerem. Sprawdź połączenie i spróbuj ponownie.',
|
||||
testEmailNotConfigured: 'Uzupełnij serwer, nazwę użytkownika i hasło, a następnie zapisz.',
|
||||
testEmailNotConfirmed: 'Usługa pocztowa nie potwierdziła testowego e-maila. Mógł zostać wysłany; sprawdź skrzynkę, zanim spróbujesz ponownie.',
|
||||
testEmailNotConfirmed: `${IWSN} nie potwierdził testowego e-maila. Mógł zostać wysłany; sprawdź skrzynkę, zanim spróbujesz ponownie.`,
|
||||
testEmailRecipient: 'Adres odbiorcy',
|
||||
testEmailSend: 'Wyślij testowy e-mail',
|
||||
testEmailSending: 'Wysyłanie…',
|
||||
testEmailSent: 'Testowy e-mail wysłano na adres {{to}}.',
|
||||
testEmailSentRelay: 'Testowy e-mail wysłano na adres {{to}} przez wbudowaną usługę pocztową, jako „{{name}}”.',
|
||||
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}}',
|
||||
testEmailSubjectGeneric: 'Testowy e-mail z witryny',
|
||||
|
||||
@@ -7,8 +7,7 @@ import { getSiteIntegrations } from '../../payload/index.js'
|
||||
import { RELAY_DEFAULTS } from './constants.js'
|
||||
import { resolveRelayOptions } from './options.js'
|
||||
import { type RelaySendResult, sendThroughRelay } from './send.js'
|
||||
import { refreshRelayStatus } from './session.js'
|
||||
import { readRelayStore } from './store.js'
|
||||
import { readSiteStore, refreshRelayStatus } from './session.js'
|
||||
|
||||
/** The address mail leaves from until the service has been asked (`/v1/status` reports the real one). */
|
||||
export const RELAY_SENDER_ADDRESS = '[email protected]'
|
||||
@@ -60,7 +59,7 @@ export async function sendRelayWithPanel(payload: BasePayload, options: Resolved
|
||||
* the site has enrolled: the plugin has no constant of its own for it.
|
||||
*/
|
||||
export async function relayAttachmentLimit(payload: BasePayload, options: ResolvedRelayOptions): Promise<null | number> {
|
||||
let stored = await readRelayStore(payload)
|
||||
let stored = await readSiteStore(payload, options)
|
||||
const stale = !stored.service || Date.now() - Date.parse(stored.service.fetchedAt) > RELAY_DEFAULTS.statusTtlMs
|
||||
if (stale && (stored.token || options.token !== undefined) && !stored.disconnected) {
|
||||
stored = (await refreshRelayStatus(payload, options)).stored
|
||||
|
||||
@@ -7,7 +7,10 @@ export type RelayRefusal = {
|
||||
field?: string
|
||||
limit?: string
|
||||
message: string
|
||||
/** No usable answer came at all (time-out, connection lost): the request may have been carried out. */
|
||||
/**
|
||||
* No answer of the service came (time-out, connection lost, or an answer that is not its JSON with a status
|
||||
* outside 400–499): the request may have been carried out.
|
||||
*/
|
||||
noAnswer: boolean
|
||||
ok: false
|
||||
reason?: string
|
||||
@@ -37,8 +40,9 @@ const firstLine = (text: string) => text.split('\n')[0].slice(0, 300)
|
||||
|
||||
/**
|
||||
* One request to the service. Never throws. An answer that is not the contract's JSON — an error page
|
||||
* of the network in front, an empty or cut-off body, a redirect — is `503 unavailable`, retryable; a
|
||||
* request that got no answer at all is the same with `noAnswer: true`.
|
||||
* of the network in front, an empty or cut-off body, a redirect — is `unavailable`, retryable, and
|
||||
* counts as no answer (`noAnswer: true`) unless its status is 400 to 499; a request that got no answer
|
||||
* at all is the same with `noAnswer: true`.
|
||||
*/
|
||||
export async function relayRequest<T = Record<string, unknown>>(call: RelayCall): Promise<RelayAnswer<T>> {
|
||||
const controller = new AbortController()
|
||||
@@ -83,7 +87,10 @@ export async function relayRequest<T = Record<string, unknown>>(call: RelayCall)
|
||||
...(typeof body.reason === 'string' ? { reason: body.reason } : {}),
|
||||
}
|
||||
}
|
||||
return { code: 'unavailable', message: `The mail service answered ${status} without a usable body.`, noAnswer: false, ok: false, retryable: true, status }
|
||||
// Not the service's own JSON (an error page of the network in front, an empty or cut-off body). It may be
|
||||
// retried; what it says about the message depends on the status alone (contract §1): 400 to 499 — turned
|
||||
// away before the service handled it; anything else, 200 included — the service may have handled it.
|
||||
return { code: 'unavailable', message: `The mail service answered ${status} without a usable body.`, noAnswer: status < 400 || status > 499, ok: false, retryable: true, status }
|
||||
} catch (err) {
|
||||
const aborted = controller.signal.aborted
|
||||
return {
|
||||
|
||||
@@ -7,11 +7,13 @@
|
||||
/** Base address: host and path together, joined with a path as text. Override: `mail: { relay: { url } }`. */
|
||||
export const RELAY_BASE_URL = 'https://webservices.intecion.net/mail'
|
||||
/** The version of the copied contract this client speaks (`contracts/mail-relay/VERSION`). */
|
||||
export const RELAY_CONTRACT_VERSION = '1.5.0'
|
||||
export const RELAY_CONTRACT_VERSION = '1.6.0'
|
||||
/** The `product` value of this plugin. */
|
||||
export const RELAY_PRODUCT = 'iapl'
|
||||
/** The service's name, for texts. */
|
||||
/** The service's name, for docs, logs and the doctor. */
|
||||
export const RELAY_SERVICE_NAME = 'Intecion Notifications Webservice'
|
||||
/** Its short name: what the admin panel calls it, in every language. The one place it is written. */
|
||||
export const RELAY_SHORT_NAME = 'IWSN'
|
||||
/** Where the service calls a site of this product back, under Payload's API route. Fixed by the contract. */
|
||||
export const RELAY_CONFIRM_PATH = '/iapl/mail-relay/confirm'
|
||||
/** Admin-only routes of the panel's status block. */
|
||||
|
||||
@@ -16,6 +16,7 @@ export {
|
||||
RELAY_KV_KEY,
|
||||
RELAY_PRODUCT,
|
||||
RELAY_SERVICE_NAME,
|
||||
RELAY_SHORT_NAME,
|
||||
RELAY_STATUS_CODES,
|
||||
relayStatusFor,
|
||||
} from './constants.js'
|
||||
|
||||
@@ -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 { isPublicHost, resolveRelayOptions } from './options.js'
|
||||
import { isPublicHost, relayHost, resolveRelayOptions } from './options.js'
|
||||
import { disconnectRelay, enrolRelay, type EnrolResult, getRelayStatus, LOCAL_CODES, type RelayStatus, setRelayToken } from './session.js'
|
||||
|
||||
type Settings = {
|
||||
@@ -73,8 +73,13 @@ export function enrolRefusalText(i18n: I18n, refusal: { code: string; message?:
|
||||
return serverText(i18n, 'mailRelayRefusedClosed')
|
||||
case 'host-not-allowed':
|
||||
return serverText(i18n, 'mailRelayRefusedHost', { host: state.relay?.host ?? '' })
|
||||
// a token issued by hand that stopped working: the site cannot heal by itself
|
||||
case 'invalid-token':
|
||||
return serverText(i18n, 'mailRelayRefusedToken')
|
||||
case LOCAL_CODES.noHost:
|
||||
return serverText(i18n, 'mailRelayRefusedNoHost')
|
||||
case 'reverify':
|
||||
return serverText(i18n, 'mailRelayRefusedAddress')
|
||||
case 'site-suspended':
|
||||
return serverText(i18n, 'mailRelayStateSuspended')
|
||||
default:
|
||||
@@ -121,7 +126,7 @@ export function relayPanelEndpoints(own?: false | RelayOptions): Endpoint[] {
|
||||
}
|
||||
if (typeof body.token === 'string' && body.token.trim()) {
|
||||
try {
|
||||
await setRelayToken(req.payload, body.token.trim())
|
||||
await setRelayToken(req.payload, body.token.trim(), { host: relayHost(req.payload, options) || undefined })
|
||||
} catch {
|
||||
return json({ error: serverText(i18n, 'mailRelayTokenInvalid'), ok: false }, 400)
|
||||
}
|
||||
|
||||
@@ -9,7 +9,7 @@ import { type RelayAnswer, type RelayRefusal, relayRequest } from './client.js'
|
||||
import { RELAY_DEFAULTS, type RelayStatusCode, relayStatusFor } from './constants.js'
|
||||
import { currentMailKind, type MailKind, mailKindOf, takeExpectedMail } from './kinds.js'
|
||||
import { bareAddresses, buildRelayMessage, type RelaySendRequest } from './message.js'
|
||||
import { LOCAL_CODES, refreshRelayStatus, rotateRelayToken, type TokenUse, withRelayToken } from './session.js'
|
||||
import { LOCAL_CODES, readSiteStore, refreshRelayStatus, rotateRelayToken, type TokenUse, withRelayToken } from './session.js'
|
||||
import { readRelayStore, sha256Hex, updateRelayStore } from './store.js'
|
||||
|
||||
export type RelaySendResult =
|
||||
@@ -144,7 +144,7 @@ export async function sendThroughRelay(payload: BasePayload, options: ResolvedRe
|
||||
}
|
||||
}
|
||||
|
||||
const stored = await readRelayStore(payload)
|
||||
const stored = await readSiteStore(payload, options)
|
||||
const limits = stored.service && Date.now() - Date.parse(stored.service.fetchedAt) < RELAY_DEFAULTS.statusTtlMs ? stored.service.limits : undefined
|
||||
if (limits) {
|
||||
// What the service said within the last hour: no need to upload 10 MB to hear it again.
|
||||
|
||||
@@ -12,6 +12,7 @@ import {
|
||||
clearRelayStore,
|
||||
dropRelayCandidate,
|
||||
holdNonce,
|
||||
readOwnRelayStore,
|
||||
readRelayCandidate,
|
||||
readRelayStore,
|
||||
type RelaySiteState,
|
||||
@@ -21,6 +22,9 @@ import {
|
||||
updateRelayStore,
|
||||
} from './store.js'
|
||||
|
||||
/** The stored entry of this site — never one made on another host (store.ts). */
|
||||
export const readSiteStore = (payload: BasePayload, options: Pick<ResolvedRelayOptions, 'host'>) => readOwnRelayStore(payload, relayHost(payload, options))
|
||||
|
||||
const sleep = (ms: number) => new Promise<void>((resolve) => setTimeout(resolve, ms))
|
||||
const refusal = (code: string, message: string, extra: Partial<RelayRefusal> = {}): RelayRefusal => ({ code, message, noAnswer: false, ok: false, retryable: false, status: 0, ...extra })
|
||||
|
||||
@@ -65,7 +69,7 @@ export function enrolRelay(payload: BasePayload, options: ResolvedRelayOptions,
|
||||
}
|
||||
|
||||
async function enrolOnce(payload: BasePayload, options: ResolvedRelayOptions, force: boolean): Promise<EnrolResult> {
|
||||
const stored = await readRelayStore(payload)
|
||||
const stored = await readSiteStore(payload, options)
|
||||
if (stored.disconnected && !force) {return enrolFailure(refusal(LOCAL_CODES.disconnected, 'The site was disconnected from the mail service in the panel.'))}
|
||||
if (!force && stored.refusal && Date.parse(stored.refusal.until) > Date.now()) {
|
||||
return enrolFailure(refusal(stored.refusal.code, stored.refusal.message ?? stored.refusal.code, { reason: stored.refusal.reason }))
|
||||
@@ -104,6 +108,7 @@ async function enrolOnce(payload: BasePayload, options: ResolvedRelayOptions, fo
|
||||
disconnected: false,
|
||||
enrolledAt: new Date().toISOString(),
|
||||
host,
|
||||
manual: false,
|
||||
refusal: null,
|
||||
source: 'enrolment',
|
||||
state,
|
||||
@@ -134,6 +139,21 @@ async function enrolOnce(payload: BasePayload, options: ResolvedRelayOptions, fo
|
||||
return enrolFailure(failed)
|
||||
}
|
||||
|
||||
const HAND_ISSUED = {
|
||||
'invalid-token': 'The token issued by hand for this site is no longer valid, and the site cannot enrol by itself: ask Intecion for a new token.',
|
||||
reverify: 'The site sends from a server address the mail service does not know, and with a token issued by hand it cannot enrol by itself: ask Intecion to add this server\'s address.',
|
||||
} as const
|
||||
|
||||
/**
|
||||
* A site with a token issued by hand cannot be called back, so "enrol again" is not open to it
|
||||
* (contract §2): it stops, says what to ask Intecion for, and keeps the token.
|
||||
*/
|
||||
async function handIssued(payload: BasePayload, code: keyof typeof HAND_ISSUED): Promise<RelayRefusal> {
|
||||
const now = new Date().toISOString()
|
||||
await updateRelayStore(payload, (current) => (current.refusal?.code === code ? current : { ...current, refusal: { at: now, code, message: HAND_ISSUED[code], until: now } }))
|
||||
return refusal(code, HAND_ISSUED[code])
|
||||
}
|
||||
|
||||
/** A token from the `token` option (a relay of one's own, a deployment secret), when the project set one. */
|
||||
async function optionToken(options: ResolvedRelayOptions): Promise<string | undefined> {
|
||||
if (options.token === undefined) {return undefined}
|
||||
@@ -164,7 +184,7 @@ export async function withRelayToken<T>(
|
||||
if (options.token !== undefined) {return refusal(LOCAL_CODES.noToken, 'mail.relay.token returned no token.')}
|
||||
|
||||
for (let round = 0; round < 4; round++) {
|
||||
const stored = await readRelayStore(payload)
|
||||
const stored = await readSiteStore(payload, options)
|
||||
if (stored.disconnected) {return refusal(LOCAL_CODES.disconnected, 'The site was disconnected from the mail service in the panel.')}
|
||||
const candidate = await readRelayCandidate(payload)
|
||||
const token = candidate?.token ?? stored.token
|
||||
@@ -196,16 +216,18 @@ export async function withRelayToken<T>(
|
||||
await dropRelayCandidate(payload)
|
||||
continue
|
||||
}
|
||||
if (stored.manual) {return handIssued(payload, 'invalid-token')}
|
||||
const failed = await enrolNow()
|
||||
if (failed) {return use.enrolment && !use.enrolment.ok ? failed : answer}
|
||||
continue
|
||||
}
|
||||
if (candidate) {
|
||||
// Seen accepted: this is the token now.
|
||||
await updateRelayStore(payload, (current) => ({ ...current, enrolledAt: candidate.at, host: relayHost(payload, options) || current.host, source: 'enrolment', state: candidate.state, token: candidate.token }))
|
||||
await updateRelayStore(payload, (current) => ({ ...current, enrolledAt: candidate.at, host: relayHost(payload, options) || current.host, manual: false, source: 'enrolment', state: candidate.state, token: candidate.token }))
|
||||
await dropRelayCandidate(payload)
|
||||
}
|
||||
if (!answer.ok && answer.code === 'reverify') {
|
||||
if (stored.manual) {return handIssued(payload, 'reverify')}
|
||||
const failed = await enrolNow()
|
||||
if (failed) {return use.enrolment && !use.enrolment.ok ? failed : answer}
|
||||
continue
|
||||
@@ -238,7 +260,7 @@ export async function refreshRelayStatus(payload: BasePayload, options: Resolved
|
||||
{},
|
||||
{ first: false },
|
||||
)
|
||||
if (!answer.ok) {return { error: answer, stored: await readRelayStore(payload) }}
|
||||
if (!answer.ok) {return { error: answer, stored: await readSiteStore(payload, options) }}
|
||||
const body = answer.body
|
||||
const stored = await updateRelayStore(payload, (current) => ({
|
||||
...current,
|
||||
@@ -263,7 +285,7 @@ export async function refreshRelayStatus(payload: BasePayload, options: Resolved
|
||||
* when the store already holds a newer token, else the site enrols again on its next send.
|
||||
*/
|
||||
export async function rotateRelayToken(payload: BasePayload, options: ResolvedRelayOptions, { force = false }: { force?: boolean } = {}): Promise<'failed' | 'not-due' | 'rotated'> {
|
||||
const stored = await readRelayStore(payload)
|
||||
const stored = await readSiteStore(payload, options)
|
||||
if (!stored.token || options.token !== undefined) {return 'not-due'}
|
||||
const due = stored.service?.rotateAfter ? Date.parse(stored.service.rotateAfter) : Number.NaN
|
||||
if (!force && !(due <= Date.now())) {return 'not-due'}
|
||||
@@ -293,7 +315,8 @@ export async function rotateRelayToken(payload: BasePayload, options: ResolvedRe
|
||||
|
||||
/** Gives the token up on the service (every token of the site stops working) and forgets it here. */
|
||||
export async function disconnectRelay(payload: BasePayload, options: ResolvedRelayOptions): Promise<void> {
|
||||
const stored = await readRelayStore(payload)
|
||||
// (a store copied from another host is dropped by this read: that site's token is never revoked from here)
|
||||
const stored = await readSiteStore(payload, options)
|
||||
if (stored.token && options.token === undefined) {
|
||||
await relayRequest({ fetchImpl: options.fetchImpl, method: 'POST', path: '/v1/revoke', token: stored.token, url: options.url })
|
||||
}
|
||||
@@ -312,6 +335,7 @@ export async function setRelayToken(payload: BasePayload, token: string, options
|
||||
disconnected: false,
|
||||
enrolledAt: new Date().toISOString(),
|
||||
...(options.host ? { host: options.host } : {}),
|
||||
manual: true,
|
||||
refusal: null,
|
||||
service: null,
|
||||
source: 'manual',
|
||||
@@ -357,7 +381,7 @@ export function describeRelayStore(payload: BasePayload, options: ResolvedRelayO
|
||||
* (`/v1/status`); otherwise what was last stored is returned and nothing leaves the server.
|
||||
*/
|
||||
export async function getRelayStatus(payload: BasePayload, options: ResolvedRelayOptions, { refresh = false }: { refresh?: boolean } = {}): Promise<{ error?: string } & RelayStatus> {
|
||||
if (!refresh) {return describeRelayStore(payload, options, await readRelayStore(payload))}
|
||||
if (!refresh) {return describeRelayStore(payload, options, await readSiteStore(payload, options))}
|
||||
const { error, stored } = await refreshRelayStatus(payload, options)
|
||||
return { ...describeRelayStore(payload, options, stored), ...(error && error.code !== LOCAL_CODES.noToken ? { error: error.code } : {}) }
|
||||
}
|
||||
|
||||
@@ -33,8 +33,10 @@ export type RelayStored = {
|
||||
/** An admin pressed "Disconnect": no send and no enrolment until "Connect again". */
|
||||
disconnected?: boolean
|
||||
enrolledAt?: string
|
||||
/** The host the token was issued for. */
|
||||
/** The host the token was issued for. A store found on another host is not this site's (readOwnRelayStore). */
|
||||
host?: string
|
||||
/** The token was issued by hand: the site cannot be called back, so it never enrols by itself to heal. */
|
||||
manual?: boolean
|
||||
/** The last warning about the sender name: the name the mail left under instead. */
|
||||
nameReplaced?: { asked: string; at: string; used: string } | null
|
||||
/** The last refusal of an enrolment; no new enrolment by itself before `until`. */
|
||||
@@ -94,6 +96,32 @@ export async function readRelayStore(payload: BasePayload): Promise<RelayStored>
|
||||
return value && typeof value === 'object' ? { ...value, v: 1 } : { v: 1 }
|
||||
}
|
||||
|
||||
let warnedForeign = false
|
||||
|
||||
/**
|
||||
* The entry of THIS site. A token belongs to the host it was issued for: when the store was made on
|
||||
* another host — a production database copied to a staging domain, a site moved to a new domain — the
|
||||
* token, the candidate and everything known about the service are forgotten here (nothing is revoked:
|
||||
* the other site keeps working), and this site starts unenrolled and enrols as itself.
|
||||
* An entry without a host (a token stored by a script) gets this site's host on first use.
|
||||
*/
|
||||
export async function readOwnRelayStore(payload: BasePayload, host: string): Promise<RelayStored> {
|
||||
const stored = await readRelayStore(payload)
|
||||
if (!host) {return stored}
|
||||
if (stored.host && stored.host !== host) {
|
||||
if (!warnedForeign) {
|
||||
warnedForeign = true
|
||||
payload.logger?.warn?.(`[iapl] mail service: the stored connection belongs to "${stored.host}", this site is "${host}" (a copied database, or a new domain). It is not used here; the site enrols as itself.`)
|
||||
}
|
||||
const kv = kvOf(payload)
|
||||
await kv.delete(CANDIDATE_KEY)
|
||||
await kv.delete(RELAY_KV_KEY)
|
||||
return { v: 1 }
|
||||
}
|
||||
if (stored.token && !stored.host) {return updateRelayStore(payload, (current) => ({ ...current, host }))}
|
||||
return stored
|
||||
}
|
||||
|
||||
/** Reads the entry again, applies `change` and writes it: the smallest window for two writers. */
|
||||
export async function updateRelayStore(payload: BasePayload, change: (current: RelayStored) => RelayStored): Promise<RelayStored> {
|
||||
const next = change(await readRelayStore(payload))
|
||||
|
||||
@@ -53,7 +53,7 @@ export async function askAnswers(ask: Ask): Promise<StarterAnswers> {
|
||||
const collections = (await list(' Collections with their own URLs: posts, caseStudies', 'none')) as ContentCollection[]
|
||||
const forms = await list('5. Forms', 'Contact form')
|
||||
const recipient = await text(' Inbox that receives submissions')
|
||||
const transport = await choice(' E-mail: relay = the built-in mail service (no setup), smtp = the client asked for its own server', ['relay', 'smtp'] as const, 'relay')
|
||||
const transport = await choice(' E-mail: relay = the Intecion mail service, IWSN (no setup), smtp = the client asked for its own server', ['relay', 'smtp'] as const, 'relay')
|
||||
const tools = (await list('6. Analytics: ga4, gtm, metaPixel, linkedIn, tiktok, clarity', 'ga4')) as AnalyticsTool[]
|
||||
const consentMode = await choice(' Consent Mode', ['advanced', 'basic'] as const, 'advanced')
|
||||
const banner = await choice(' Cookie settings window', ['detailed', 'modal', 'inline'] as const, 'detailed')
|
||||
|
||||
+102
-3
@@ -8,8 +8,11 @@ import type { PayloadEmailAdapter } from 'payload'
|
||||
|
||||
import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest'
|
||||
|
||||
import { buildSmtpFields } from '../src/globals/SiteIntegrations/fields/smtp.js'
|
||||
import { adminTexts } from '../src/modules/admin-i18n/index.js'
|
||||
import { mailAdapter, resetGraphDeprecationWarning, resolveMailTransport } from '../src/modules/email/mailAdapter.js'
|
||||
import { relayAdapter } from '../src/modules/email/relay/adapter.js'
|
||||
import { RELAY_SHORT_NAME } from '../src/modules/email/relay/constants.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'
|
||||
@@ -370,12 +373,24 @@ describe('one message: one key, one encoding, three attempts', () => {
|
||||
expect(Date.now() - started).toBeLessThan(2000)
|
||||
})
|
||||
|
||||
test('an answer that is not JSON (an error page of the network in front) is "unavailable": retried, then not sent', async () => {
|
||||
test('an answer that is not the service\'s JSON: retried; "not confirmed" unless its status is 400 to 499 (contract 1.6.0)', async () => {
|
||||
const { fake, options, payload } = await ready()
|
||||
const page = () => new Response('<html>502 Bad Gateway</html>', { headers: { 'content-type': 'text/html' }, status: 502 })
|
||||
const page = (status = 502) => new Response(`<html>${status}</html>`, { headers: { 'content-type': 'text/html' }, status })
|
||||
// an error page of the network in front, after the service may have handled the request: it may be out
|
||||
const sends = capture(fake, [page(), page(), page()])
|
||||
expect(await sendThroughRelay(payload, options, MESSAGE)).toMatchObject({ cause: 'unavailable', code: 'relay-unreachable', confirmed: true, sent: false })
|
||||
expect(await sendThroughRelay(payload, options, MESSAGE)).toMatchObject({ cause: 'unavailable', code: 'relay-not-confirmed', confirmed: false, sent: false })
|
||||
expect(sends).toHaveLength(3)
|
||||
// turned away before the service handled it (a firewall's 403, a proxy's 404): not sent, and said so
|
||||
for (const status of [400, 403, 404, 499]) {
|
||||
const refusedInFront = capture(fake, [page(status), page(status), page(status)])
|
||||
expect(await sendThroughRelay(payload, options, { ...MESSAGE, subject: `Blocked ${status}` })).toMatchObject({ cause: 'unavailable', code: 'relay-unreachable', confirmed: true, sent: false })
|
||||
expect(refusedInFront).toHaveLength(3)
|
||||
}
|
||||
// a 200 whose body was cut off, a 500 page, a redirect: the same as no answer
|
||||
for (const answer of [new Response('{"ok":tr', { status: 200 }), page(500), new Response(null, { headers: { location: 'https://elsewhere.example' }, status: 302 })]) {
|
||||
capture(fake, [answer, answer.clone(), answer.clone()])
|
||||
expect(await sendThroughRelay(payload, options, { ...MESSAGE, subject: `Lost ${answer.status}` })).toMatchObject({ code: 'relay-not-confirmed', confirmed: false })
|
||||
}
|
||||
// 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)
|
||||
@@ -604,6 +619,74 @@ describe('the token over time', () => {
|
||||
expect((await sendThroughRelay(payload, options, MESSAGE)).sent).toBe(true)
|
||||
})
|
||||
|
||||
test('a site with a token issued by hand does not enrol to heal: it stops and says what to ask for (contract 1.6.0)', async () => {
|
||||
// the site CAN be called back here (the fake would confirm it) — it still must not enrol by itself
|
||||
const { fake, options, payload } = relaySite({ fake: { allow: [HOST] } })
|
||||
await setRelayToken(payload, fake.issueToken(HOST), { host: HOST })
|
||||
expect((await sendThroughRelay(payload, options, MESSAGE)).sent).toBe(true)
|
||||
const token = (await readRelayStore(payload)).token
|
||||
|
||||
fake.clientAddress = '198.51.100.30' // the site moved, or a second server sends
|
||||
const moved = await sendThroughRelay(payload, options, { ...MESSAGE, subject: 'Moved' })
|
||||
expect(moved).toMatchObject({ cause: 'reverify', code: 'relay-refused', confirmed: true, sent: false })
|
||||
expect(moved.sent === false && moved.detail).toMatch(/ask Intecion to add this server's address/)
|
||||
expect((await getRelayStatus(payload, options)).refusal).toMatchObject({ code: 'reverify' })
|
||||
expect(await mailPanelState({ payload }, options)).toMatchObject({ relay: { connected: true, refusal: { code: 'reverify' }, tokenSource: 'manual' } })
|
||||
|
||||
fake.clientAddress = '203.0.113.10'
|
||||
await fake.handle(new Request(`${fake.url}/v1/revoke`, { headers: { authorization: `Bearer ${token}` }, method: 'POST' }))
|
||||
const gone = await sendThroughRelay(payload, options, { ...MESSAGE, subject: 'Gone' })
|
||||
expect(gone).toMatchObject({ cause: 'invalid-token', code: 'relay-refused', sent: false })
|
||||
expect(gone.sent === false && gone.detail).toMatch(/ask Intecion for a new token/)
|
||||
// not one enrolment, and the token was kept
|
||||
expect(fake.requests.map((r) => r.path)).not.toContain('/v1/enrol')
|
||||
expect((await readRelayStore(payload)).token).toBe(token)
|
||||
// a new token from Intecion, or "Connect again" by an admin (when the site can be called back), heals it
|
||||
await setRelayToken(payload, fake.issueToken(HOST), { host: HOST })
|
||||
expect((await sendThroughRelay(payload, options, { ...MESSAGE, subject: 'New token' })).sent).toBe(true)
|
||||
expect((await getRelayStatus(payload, options)).refusal).toBeUndefined()
|
||||
// rotation does not make it a site that enrols: it is still hand-issued
|
||||
expect(await rotateRelayToken(payload, options, { force: true })).toBe('rotated')
|
||||
expect((await readRelayStore(payload)).manual).toBe(true)
|
||||
})
|
||||
|
||||
test('a database copied to another host does not use the first site\'s token: the copy starts unenrolled and enrols as itself', async () => {
|
||||
// one service, two sites: it calls each back at its own host
|
||||
const staging = relayPayload({ serverURL: 'https://staging.example.com' })
|
||||
const sites: Record<string, ReturnType<typeof callConfirmRoute>> = {}
|
||||
const production = relaySite({
|
||||
fake: { allow: [HOST, 'staging.example.com'], callSite: (url, init) => sites[new URL(url).host](url, init) },
|
||||
integrations: { smtpFromName: 'Example' },
|
||||
})
|
||||
sites[HOST] = callConfirmRoute(production.payload)
|
||||
sites['staging.example.com'] = callConfirmRoute(staging.payload)
|
||||
await sendThroughRelay(production.payload, production.options, MESSAGE)
|
||||
const token = (await readRelayStore(production.payload)).token!
|
||||
// the copy: the same key-value entries, another serverURL
|
||||
for (const [key, value] of production.store) {staging.store.set(key, structuredClone(value))}
|
||||
const options = resolveRelayOptions(staging.payload, { fetchImpl: production.fake.fetch, url: production.fake.url })!
|
||||
expect((await readRelayStore(staging.payload)).token).toBe(token) // it is there …
|
||||
const seen: string[] = []
|
||||
production.fake.intercept = (request) => void seen.push(request.headers.get('authorization') ?? '')
|
||||
|
||||
// … and is not shown as this site's, not used, and not revoked
|
||||
expect(await mailPanelState({ payload: staging.payload }, options)).toMatchObject({ relay: { connected: false, host: 'staging.example.com' } })
|
||||
expect((await readRelayStore(staging.payload)).token).toBeUndefined()
|
||||
expect(staging.logger.warn.mock.calls.map((c) => String(c[0])).join()).toMatch(/belongs to "example\.com", this site is "staging\.example\.com"/)
|
||||
await disconnectRelay(staging.payload, options) // even "Disconnect" on the copy
|
||||
expect(production.fake.requests.filter((r) => r.path === '/v1/revoke')).toEqual([])
|
||||
expect((await enrolRelay(staging.payload, options, { force: true })).ok).toBe(true)
|
||||
expect((await sendThroughRelay(staging.payload, options, { ...MESSAGE, subject: 'From staging' })).sent).toBe(true)
|
||||
expect(production.fake.outbox.at(-1)).toMatchObject({ host: 'staging.example.com', subject: 'From staging' })
|
||||
const own = (await readRelayStore(staging.payload)).token
|
||||
expect(own).not.toBe(token)
|
||||
expect(seen.every((header) => !header.includes(token))).toBe(true)
|
||||
expect(JSON.stringify(staging.logger.warn.mock.calls)).not.toContain('ims_')
|
||||
// production is untouched and still sends with its own token
|
||||
expect((await readRelayStore(production.payload)).token).toBe(token)
|
||||
expect((await sendThroughRelay(production.payload, production.options, { ...MESSAGE, subject: 'From production' })).sent).toBe(true)
|
||||
})
|
||||
|
||||
test('a token issued by hand is stored the same way; enrol: "manual" and enrol: false never enrol by themselves', async () => {
|
||||
const manual = relaySite({ options: { enrol: 'manual' } })
|
||||
expect(await sendThroughRelay(manual.payload, manual.options, MESSAGE)).toMatchObject({ code: 'relay-refused', sent: false })
|
||||
@@ -626,6 +709,22 @@ describe('the token over time', () => {
|
||||
})
|
||||
|
||||
describe('what the panel is told', () => {
|
||||
test('the panel calls the service by its short name, IWSN, in both languages — one constant, never another name', () => {
|
||||
expect(RELAY_SHORT_NAME).toBe('IWSN')
|
||||
for (const lang of ['en', 'pl'] as const) {
|
||||
const texts = Object.entries(adminTexts[lang] as Record<string, string>).filter(([key]) => /^(?:mailRelay|statusEmailRelay|testEmailSentRelay|testEmailNotConfirmed)/.test(key))
|
||||
expect(texts.length).toBeGreaterThan(40)
|
||||
const named = texts.filter(([, text]) => text.includes(RELAY_SHORT_NAME))
|
||||
expect(named.length).toBeGreaterThan(20)
|
||||
for (const [key, text] of texts) {expect(text, key).not.toMatch(/mail service|usług|Intecion|Webservice/i)}
|
||||
}
|
||||
const tab = JSON.stringify(buildSmtpFields())
|
||||
expect(tab).toContain('IWSN')
|
||||
expect(tab).not.toMatch(/mail service|usług/)
|
||||
expect(JSON.stringify(buildSmtpFields({ relay: false }))).not.toContain('IWSN')
|
||||
})
|
||||
|
||||
|
||||
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' })
|
||||
|
||||
Reference in New Issue
Block a user