diff --git a/contracts/mail-relay/CHANGELOG.md b/contracts/mail-relay/CHANGELOG.md new file mode 100644 index 0000000..1fdb41a --- /dev/null +++ b/contracts/mail-relay/CHANGELOG.md @@ -0,0 +1,75 @@ +# Changelog of the wire contract + +## 1.5.0 — 2026-11-25 (not released; no tag yet) + +After the third review. + +- `new-recipients`: `account` mail is outside it; a form's confirmations may use four fifths of it. +- Failed sends: those in flight are counted in. +- Wording: `backend-failed`, `internal` and unknown codes mean "probably not sent"; the checklist asks a client + to limit "forgot password" itself. + +## 1.4.0 — 2026-11-25 (never released) + +After the second review. + +- **Limits by kind:** `security-alert` has a budget of its own (`limit: "alerts"`, `limits.securityAlertsPerDay`) + outside hour and day; `account` mail may use the whole hour and day, every other kind four fifths. The + `quota` of a send answer is for that kind. `recipient` counts `form-confirmation` messages only. +- **The idempotency promise is now what the service does:** a key whose message was handed to the mail back end + is never sent again within 24 hours; when the result was not recorded it answers `in-progress` until then. +- **Failed sends** have a limit of their own: `429 rate-limited` after 60 in an hour. +- **Retrying:** three attempts, 30 seconds each, ten seconds of waiting in all; an enrolment on the way does + not count. +- **Subject:** U+200D, U+200C and U+00AD are allowed; everything else as before, with the rule a client strips by. +- Any mail of a site to Intecion's own address gets `[host]` in front of its subject. +- The confirm address: no redirect is followed — the usual causes and what to do; `given.quota` gains + `hour-share-used`. + +## 1.3.0 — 2026-11-25 (never released) + +- **The confirm path is fixed per product** (owner, 2026-11-25): `iapl` → `/api/iapl/mail-relay/confirm`, + `iawl` → `/?rest_route=/iawl/v1/mail-relay/confirm`. **`callbackPath` is gone from the enrolment request** + (a request that carries it is refused). A site that serves its API elsewhere has its path set by Intecion. +- Suppression is account-wide and stays so (owner, 2026-11-25): said in the code table. + +## 1.2.0 — 2026-11-25 (never released) + +After the first independent review. The wire format is the same; the text now has one reading where it had two. + +- **Retrying:** at most three attempts in ten seconds, and the ten seconds win over `retryAfter`; "no answer" + and `in-progress` are reported as *not confirmed*, never as *not sent*. +- **Idempotency:** "the same body" is the same bytes; a client encodes a message once. +- **The confirm endpoint:** exactly `200` and the JSON object, at most 1024 bytes, within 8 seconds; the site + keeps its earlier token until `/v1/enrol` answers 200. +- **An answer that is not JSON** is `unavailable`, retryable. +- `Authorization: Bearer` in any case. +- **Schema:** `code` and `warnings` are open strings (new ones are minor changes); `to` is required unless the + kind is `security-alert`; recipients' `maxItems` is the service's bound, the site's limit is in `/v1/status`; + base64 is padded to a multiple of four (said in words: a pattern for it overflows on large files); lengths are + in code points. +- **Changed behaviour:** the per-recipient limit refuses `form-confirmation` only; a subject may not start with + the service's name in brackets; a `security-alert` gets the site's host in front of its subject; + `attachment-refused` names the file in `field` (suggested status `relay-attachment-refused`); + invisible characters (all of Unicode category Cf) are refused in subject and file names. +- Added: `limits.serverAddresses` in `/v1/status`; what happens beyond it. +- Before the first release tag, versions are development versions (§9). + +## 1.1.0 — 2026-11-25 (never released) + +- **The base address is `https://webservices.intecion.net/mail`**: one host for Intecion's web services, this + one under the path `/mail`. Paths in the contract are relative to the base address, as before; a client that + kept the base address as one constant changes that constant and nothing else. +- Added: `service.name` in the answer of `/v1/status` ("Intecion Notifications Webservice"). +- The service sends from `notification@webservices.intecion.net` (owner, 2026-11-25). + +Minor, by the contract's own rule (§9): an answer field was added. No copy of 1.0.0 was released; a client that +copied it during development copies the folder again. + +## 1.0.0 — 2026-11-25 (never released) + +First version: `/v1/enrol` with the call-back and its confirmation, `/v1/send`, `/v1/status`, `/v1/rotate`, +`/v1/revoke`, `/health`; the error codes; the examples and the runner. + +Differs from the design proposal (draft 4) in one visible point: the site's confirm endpoint answers `200` with +a `confirmation` (SHA-256 of nonce and token), not a bare `204`. Reason: `services/mail-relay/DECISIONS.md`, D1. diff --git a/contracts/mail-relay/CHECKSUMS b/contracts/mail-relay/CHECKSUMS new file mode 100644 index 0000000..a3c1d95 --- /dev/null +++ b/contracts/mail-relay/CHECKSUMS @@ -0,0 +1,62 @@ +8573bc968031c595b4e06f6694dd50e1d8e813255023b0397922352dcbc0a758 README.md +fc5bd405549ceffe38e47de8e30ce4041556559fd65fb7aa4097c26fb494e9e5 CHANGELOG.md +acb57a7135b2d7d6e665f67f056e21353023b93835f54def1ae523bf76f1bfb3 VERSION +275ee643112eac77430dba9ea3f93c8f53dc1676b8d56ba95a25dd3f35a8746f schema.json +be56a59e13474a8184576fef90cc01145cc3233886d4147e2ac2b867921fba1d runner.mjs +7c46860adee597e570832c72bcdb418752a20b9f7d1b2d7a656ed065f9632b2a checksums.mjs +df6015faf02a7cf7e9b5816b9e22b2e82968678ddd72a61c1f9665a8c0897ddf examples/callback-confirm-wordpress.json +f5018ca4fb7d25794ee92168d715aaf47feeba3d907c0550651b16c10a691ceb examples/callback-confirm.json +27bd95712cc36a71519cddc52c03d857b1009c2c384940dbc052022d86bc4231 examples/callback-unknown-nonce.json +de693b060c10c3d0f88fb8edfcd38c491cf141628d747328beee1b50c700c19b examples/enrol-address-literal.json +7c4cf75eb9ab156a3031336ab2688e7c9dcd4cd266b7b7e5e4592285dcbd25ba examples/enrol-callback-no-content.json +64466afc5bf0fecfa36f986d973cd987bbe1f64867e01cdf35e0de40838eb0d1 examples/enrol-callback-not-found.json +0000bcb2b3b676e4fda6c30b8de6e062c88f98c1fa2cc9f75bcd350d65dc0db4 examples/enrol-callback-path-given.json +8b522f16bc9b9980a5c849e94cea35fb268b0ba664dcd5a2e8e0fedd67c2c034 examples/enrol-callback-redirect.json +1e6483ebd85e3851848357266d8e16628a70420428b30d3ddb15253cdc2d9a0d examples/enrol-callback-wrong-confirmation.json +f64e4c75ced60e70b0f2f8e16adbde151be888fe5ac75813cdbe7eb5ecf8a00b examples/enrol-from-browser.json +218f463c95fd79868916390d4616c796d66154398a9864615f9ad0768f801aff examples/enrol-listed-active.json +b628eb5b30e693767e6830de58e0fd172497336f67b76a49a5fb06bfa626c481 examples/enrol-localhost.json +93304590382de5153a47fa88ee98356d0a5ba8039e195959291acd3c33e4a406 examples/enrol-short-nonce.json +e86e6ab23088c1c985ba18f287f66b49c50f51a584a7ca679b8b768597130efd examples/enrol-suspended.json +fe38f1fd1394a7fd42b1a1b0b74aa604578f17ab52590bf95a462a0c0f7d6087 examples/enrol-unlisted-pending.json +b9f71fe993dc39bdbc07e775e925a37175e18e1682fd8bffcc72b3581919be17 examples/health.json +5dff4194764f6f61b01a3f7f504907e578306a486d214e22d1a70b1a207e5ca3 examples/not-found.json +7df29aaf11934bb3a73f6899c66c4f73cfcc048c804ca52871b60376323cb222 examples/revoke-ok.json +148ae206781250f5de72d8d8f024fb1a0ba9c61c3f14c2866cdbda5244940097 examples/rotate-ok.json +81b6eeec98cdc35860241b1a958ab35cf6de2872bf1ffcdb24629156f5308996 examples/rotate-previous-token.json +2e9b2d088310ed1965639ad48e3aa4753ca277bb4c7119b8b58b082d25a5f46c examples/send-attachments-too-large.json +3585fde1439db56351a99c40e8262f606a3884eb4035546c76591279adbba0e8 examples/send-backend-failed.json +938761bbe576ca2da017cff8a42c4586bee971b9f5ce27a2fa024f7643fa1d3e examples/send-bearer-any-case.json +dbfdf96f791057e7a228330dba706cdcdf07f87d46d37734e2f4a3a49d557db0 examples/send-day-quota.json +93455791565a0b2f8d464aed858cc470a014bf16c943d3883383a145e43424f9 examples/send-display-name-recipient.json +01d7927fa99572fee0adf73c9d079ca7a544c3bf90d90c068e4b85137b59b53d examples/send-executable-attachment.json +54db430c75ae132fda615f5a27a2e8d0f53157acdceedaba2c035edd1938f0e9 examples/send-from-browser.json +650c8a79f38901e0027d3e105ad8e8edaab776f091011930093b7b1bc96bad66 examples/send-from-field.json +f9db7bdf34887406fdf80e037c83212e9523c553a2566fe7d1a9411a491cd85c examples/send-headers-field.json +5679e08b88d2206dc6810f73bb2139a8f7f46b7fd0470420081f8543e4466889 examples/send-hour-quota-account.json +40828edcba271529de9d452239fb218afc63a1dd6606c5e201ad622f2748ba09 examples/send-hour-quota.json +60e2eb9841a379c3985ae53e0c821a9e8a6f1de1cffc41f55f63a2bf91ffb315 examples/send-key-reused.json +6b10a5fce8dc51188cad654804bf742d9221e3825f04c688d724c2c8893bc2af examples/send-no-sender-name.json +1c37294029f41bb3953245950bde50ef6f550f9459aa16df525d4f8897f6f610 examples/send-no-token.json +3408947e979677ab07bdac2939c716083c78bdf75ac0e06993cc68fcdbae071f examples/send-ok.json +3660c55e7a359183793fd06c73a8c8c1529670e720cd9aa933a0a915b7f18a9f examples/send-pending.json +cec3126afeffbc18ee02a23556c184dc9195f05a0fc9cff8a31be7bbd444a557 examples/send-previous-token.json +b3b8ca0aae457e1d7afaa557b73ba1ab9c6c6427727c5d159e5290427f05ad8c examples/send-recipient-quota-other-kinds.json +9ac1a9cccea648f5a54c55abd7d2271ac8b1916d789138f09bbacff1960c45eb examples/send-recipient-quota.json +84d37df95af790ade19255736868fc38295e2674082dfec1c13f64031f88571c examples/send-recipient-suppressed.json +5243b6a33a200c4e57f1f32bf285bd7a1499663e3073462e057548c2e1201d9f examples/send-replay.json +40b86320ccfbe321b2831672035df618b4f5a6b3a70e398260698b4690b9c9a8 examples/send-security-alert.json +af073fb884954c55f606fd2c6f7dc0bbedc29ec6b0daff4c77e91c16c129ac6d examples/send-sender-name-replaced.json +bf0ce766240ad5df96176a8a6e0f54e7eaa533262657c8105ce342f957f156fb examples/send-subject-direction-mark.json +47824ad6a90c27da507a98fef4e31486f8fac445d4f0657c6f98312752884da0 examples/send-subject-imitates-service.json +85d43f2c6855accbece8bf09c281544355421de308850846fe28b7aa457fab21 examples/send-subject-line-break.json +be98bd6277fadc03eacfa901ac15c9f69895ddfb3b01fbf40d849e9eeded61fe examples/send-subject-visitor-text.json +a5dddf15899dfb6d7212b63f5bc32819d7f35a14872daae4f46324555bffa0e1 examples/send-suspended.json +bcf24c613cfb4eb223667ab2eee8ca6ebe91a6f97b86e6545b9d9316c63ca728 examples/send-text-plain.json +725fc1f4b059dc192f49955f67df4263f4a67f618b7314ca87ddfd7647e4514e examples/send-to-intecion-marked.json +aac0a3d17fe69e8d6c0adbcd3513650c2802b7f43c2103d5cd3de5a0346456c0 examples/send-too-many-recipients.json +4833a6b7cf81eba320f20c33fd44cb990681144186218332c2fb97a043b774cf examples/send-unknown-address.json +1ad0d24c691ab35b5603d63f5b29c5a3a3e50265aea9524fd26d314c0b7c1437 examples/send-unknown-token.json +cd2812d7b33698851116dd96fc1019e7ddfcc7f0b14511c6fa8f1b94acbfdb7e examples/status-active.json +e1bbb759fc3f7084d4bc027fa7d490cf0d24bc8ca124bd9a82e5dde372eb7bcd examples/status-pending.json +daaf53c17b92e61049b230e6a91edf9450967d920c05d23b3da67959e27474e4 examples/status-unknown-address.json diff --git a/contracts/mail-relay/README.md b/contracts/mail-relay/README.md new file mode 100644 index 0000000..6676761 --- /dev/null +++ b/contracts/mail-relay/README.md @@ -0,0 +1,472 @@ +# Intecion Notifications Webservice — wire contract + +Version: see [`VERSION`](VERSION) (this text describes **1.5.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 +the `product` field. A client written from this document, in any language, works with the service. + +| File | What | +|---|---| +| `README.md` | This document. Where it and the schema disagree, the schema wins and that is a bug to report | +| `schema.json` | JSON Schema (2020-12) of every body, under `$defs` | +| `examples/*.json` | One request and its answer per file, with the state it needs. They are the contract tests | +| `runner.mjs` | Runs the examples against anything that speaks the contract. No dependency; works in Node and in the Workers runtime | +| `checksums.mjs`, `CHECKSUMS` | SHA-256 of every file above, to detect a hand-edited copy | +| `VERSION`, `CHANGELOG.md` | Semantic version of the contract and what changed | + +## 1. Basics + +- **Base address: `https://webservices.intecion.net/mail`** — a client keeps it as one constant, host and path + together. Every path in this document and in the examples is relative to it: `POST /v1/send` is + `POST https://webservices.intecion.net/mail/v1/send`, `GET /health` is `…/mail/health`. A client joins the + base address and the path as text; it never resolves a path against the host alone. +- 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`). +- **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: /` (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. + +### Answers + +Success is status `200` and a body with `"ok": true`. + +Every refusal has the same body ([`Error`](schema.json)) — with one exception: `/health` answers only +`{ "ok": false }`. + +```json +{ "ok": false, "code": "quota-exceeded", "message": "…", "retryable": false, "limit": "hour", "retryAfter": 1260 } +``` + +- `code` is what a client acts on. `message` is English text for a log or an administrator; never show it to a visitor. +- **`retryable` decides whether to try again, not the status.** `429 quota-exceeded` is not retryable; + `429 rate-limited` is. +- `retryAfter` (seconds) is also sent as the `Retry-After` header. +- The list of codes grows with minor versions. A client that meets a code it does not know acts on `retryable` + and shows the `message` to an administrator. + +### All codes + +| Status | `code` | Meaning | Retry | What a client does | Suggested site status | +|---|---|---|---|---|---| +| 400 | `invalid-request` | Body, header or field is wrong; `field` names it | no | Report a bug | — | +| 401 | `invalid-token` | No token, or one the service does not know (unknown, expired, revoked) | no | Enrol again, then send once more (§2, "Which token") | — | +| 401 | `reverify` | The token is good but comes from a server address the service has not seen for this site | no | Enrol again (the same call-back), then send once more | — | +| 403 | `site-pending` | Enrolled, waiting for approval by Intecion | no | Keep the token; show "waiting for approval" | `relay-pending` | +| 403 | `site-suspended` | Stopped by Intecion | no | Keep the token; show it; do not enrol again | `relay-suspended` | +| 403 | `host-not-allowed` | Enrolment: the host is not a public DNS name | no | Show it (a local or private site cannot use the service) | `relay-refused` | +| 403 | `enrolment-closed` | Enrolment is closed for this product, or altogether | no | Show it | `relay-refused` | +| 403 | `browser-not-allowed` | The request came from a browser | no | — | — | +| 404 | `not-found` | No such route | no | Report a bug | — | +| 405 | `method-not-allowed` | Wrong method | no | Report a bug | — | +| 409 | `enrolment-in-progress` | Another enrolment for this host is running right now | **yes** | Wait `retryAfter`, read your own store again (another process may have the token by now), enrol only if still without one | — | +| 409 | `in-progress` | A send with this `Idempotency-Key` is running right now — or was handed to the mail back end and its result was never recorded (then `retryAfter` is long, and the message may be out) | **yes** | Retry with the same key within the ten seconds; then report "not confirmed" | — | +| 409 | `idempotency-conflict` | This `Idempotency-Key` was used for a different message | no | Report a bug | — | +| 409 | `already-rotated` | `/v1/rotate` with a token that is no longer the current one | no | Read your own store again; if it has no newer token, enrol again | — | +| 413 | `too-large` | `limit` says what: `request`, `body` or `attachments` | no | Show it | `relay-too-large` | +| 415 | `unsupported-media-type` | Not `application/json` | no | Report a bug | — | +| 422 | `callback-failed` | Enrolment: the site's confirm endpoint did not confirm; `reason` is `unreachable`, `timeout`, `redirect`, `status` or `confirmation` | no | Show it, with the reason: firewall or wrong public host (`unreachable`, `timeout`); the site answers the confirm address with a redirect (`redirect`, §2); the endpoint is missing, blocked, or served at another path than its product's (`status`); something prints around the JSON (`confirmation`) | `relay-refused` | +| 422 | `too-many-recipients` | More than the allowed number in To, CC and BCC together | no | Show it | `relay-quota` | +| 422 | `attachment-refused` | A file type the service never carries, or a bad file name; `field` says which file (`attachments[0]`) | no | Show it; the message can be sent without that file | `relay-attachment-refused` | +| 422 | `recipient-suppressed` | The back end refuses one of the recipients (it bounced or complained before — for any site: **the suppression list is one for the whole service, and there is none per site**; an address that bounced for one client's site is refused for every other site too, until Intecion removes it). **Nothing was sent, to anybody.** The service is not told which address it is | no | Show it. With several recipients a client may send to each alone, each with a new key, to find the one | `relay-recipient-suppressed` | +| 429 | `rate-limited` | Too many requests from this address — or too many of this site's sends were refused or failed at the mail back end within the hour (60; a send that fails costs no quota, so it has a limit of its own; account mail and alerts are counted apart from the rest) | **yes** | Wait `retryAfter`; when that is longer than the ten seconds, report | `relay-unreachable` if it persists | +| 429 | `quota-exceeded` | A limit of the site (`limit`: `hour`, `day`, `recipient`, `new-recipients`, `alerts`) or of the whole service (`service`) | no | Show it; the message is not sent | `relay-quota` | +| 502 | `backend-failed` | The mail back end failed, or refused this message | **as `retryable` says** | Retry with the same key when `retryable` is true | `relay-unreachable` if it persists | +| 503 | `unavailable` | The service cannot work right now | **as `retryable` says** | Retry when `retryable` is true | `relay-unreachable` if it persists | +| 500 | `internal` | A fault in the service | **yes** | Retry | `relay-unreachable` if it persists | + +A network error or a time-out is treated like `503`. The "suggested site status" column is advice, in the words +the IAPL design uses; a product may name its own. The warning `sender-name-replaced` (below) maps to +`relay-name-replaced`. + +**Retrying — the one rule.** A client makes at most **three attempts** for one message, the same +`Idempotency-Key` and the same bytes each time, and only after an answer with `retryable: true` (or no usable +answer at all). Between the attempts it waits **at most ten seconds in all**. **The ten seconds win over +`retryAfter`:** when `retryAfter` is longer than what is left of them, the client stops at once and reports. + +- **One attempt** has a time-out of **30 seconds** from sending the request to the end of the answer (a 10 MB + attachment has to fit). An attempt that times out counts as "no answer". +- **An enrolment made on the way** — because the client had no token, or got `invalid-token` or `reverify` — is + not one of the three attempts and its time (up to 10 seconds: the call-back has 8) is not part of the ten + seconds. A client enrols at most once per message. + +What the client reports: + +| The last thing that happened | The message | Report | +|---|---|---| +| `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` | +| `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 | + +## 2. Enrolment — `POST /v1/enrol` + +A site gets its token by proving that it is served at its host. No authentication, nothing to type. + +1. The site makes a random **nonce** (32 to 128 characters of `A–Z a–z 0–9 _ -`; at least 128 bits of + randomness), keeps it for 5 minutes, and sends: + + ```json + { "host": "example.com", "nonce": "…", "product": "iapl", "productVersion": "1.17.0" } + ``` + + - `host`: the site's public DNS name, lowercase, punycode. No scheme, port, path, address literal, single + label, or private suffix (`.local`, `.internal`, `.test`, `localhost` …). + - There is **no call-back address in the request.** Where a site is called back is fixed per product + (below); a request that names a path is refused (`400`, field `callbackPath`). + +2. Before it answers, the service calls the site: `POST https://`, port 443, + no redirect followed, **8 seconds** for the whole exchange, body ([`CallbackRequest`](schema.json)): + + ```json + { "nonce": "…", "token": "ims_…", "state": "active" } + ``` + +3. **The site's confirm endpoint** accepts the call only if it holds exactly this nonce (compare in constant + time; single use; not expired). Then it stores the token and answers `200` with + + ```json + { "confirmation": "" } + ``` + + In every other case it answers `404` and changes nothing. It is a public route: rate-limit it. + + **Exactly this answer and nothing else.** Status `200` (not 201, not 204). The body is the JSON object alone, + UTF-8, at most 1024 bytes, the hex in lower case. Anything printed before or after it — a PHP notice, a + debug toolbar, a wrapper of the framework — makes the enrolment fail with `callback-failed`, reason + `confirmation`. The service reads no more than 1024 bytes and waits no longer than the 8 seconds. + + **Which token.** The call-back arrives *before* `/v1/enrol` has answered. The site stores the new token + **beside** the one it has, and makes it the token it uses when `/v1/enrol` answers `200`. If that answer + never arrives, the site tries the new token on its next request and goes back to the earlier one on + `401 invalid-token` (the service may have failed after the call-back; the earlier token is then still good). + A site never throws a working token away for one it has not seen accepted. + +4. The service checks the confirmation. Only then does the token become valid, the calling server's address + become one of the site's known addresses, and `/v1/enrol` answer `200`: + + ```json + { "ok": true, "state": "active" } + ``` + + `state` is `active` (the site may send) or `pending` (waiting for approval; sends answer `403 site-pending` + until Intecion approves, then the same token works). **The answer never carries the token.** + +Why the confirmation, and not a bare `204`: plenty of ordinary endpoints answer "no content" to any POST (a +report collector, for one). Only an endpoint that knows the nonce *and* has read the token can compute the +confirmation, so nothing else on the host can be mistaken for the confirm endpoint. + +Rules a client must know: + +- **Enrolling again is the same call** and is how a site heals: after `401 invalid-token`, after `401 reverify`, + after a lost token. The earlier token stays valid for 24 hours (so other processes of the same site are not + cut off), the state is kept — a suspended site stays suspended (`403 site-suspended`, no call-back is made). +- A failed enrolment changes nothing on the service: tokens and addresses stay as they were. +- `409 enrolment-in-progress`: an enrolment for this host from this server is already running (or the + registry changed while the site was being called). It is retryable and is not counted against the site. +- **The confirm path is fixed per product**; a site cannot choose it: + + | `product` | The service calls | Notes | + |---|---|---| + | `iapl` | `POST https:///api/iapl/mail-relay/confirm` | Under Payload's default API route (`/api`) | + | `iawl` | `POST https:///?rest_route=/iawl/v1/mail-relay/confirm` | WordPress's REST API addressed by query: the same address works with and without pretty permalinks. The route is `mail-relay/confirm` in the namespace `iawl/v1` | + + The service calls **exactly that address and follows no redirect.** A site that redirects it fails with + reason `redirect` — the usual causes: the site adds or removes a trailing slash (Next.js `trailingSlash`), + sends `example.com` to `www.example.com` (enrol the host the site really answers on), or redirects `/` by + language. On WordPress, a security plugin or a setting that blocks or redirects `?rest_route=` gives + `status`. In each case either the site is changed to answer at the address, or Intecion sets the address it + does answer at (a path ending in `/confirm/`, for a site with trailing slashes). + + **A project that serves its API somewhere else** — Payload with another `routes.api`, WordPress installed in a + sub-folder, a path prefix in front of the site — cannot say so in the request. Its path is set for its host + **by Intecion** (`ims callback-path `), before the site enrols; until then the enrolment fails + with `callback-failed`, reason `status`. A client shows that as "ask Intecion to set this site's confirm + address", with the address it serves. When an enrolled host confirms at another path than before, Intecion + is told. +- **Server addresses.** A site may send from a limited number of server addresses at a time + (`limits.serverAddresses` in `/v1/status`, 8 unless Intecion set another number). Each new address enrols by + 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 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. + +## 3. Sending — `POST /v1/send` + +Headers (`Bearer` in any case; one space; then the token exactly): + +``` +Authorization: Bearer ims_… +Idempotency-Key: <16 to 128 characters of A–Z a–z 0–9 _ -> +Content-Type: application/json +``` + +Body ([`SendRequest`](schema.json)): + +```json +{ + "product": "iapl", "productVersion": "1.17.0", + "kind": "form-notification", + "to": ["office@example.com"], + "replyTo": "visitor@example.org", + "senderName": "Kancelaria Example", + "subject": "New enquiry", + "text": "…", "html": "…", + "attachments": [{ "filename": "cv.pdf", "contentType": "application/pdf", "content": "" }] +} +``` + +- **`kind`** (required): `form-notification`, `form-confirmation`, `account`, `security-alert`, `system`, `test`. + Mail whose purpose the client does not know is `system`. **The kind decides which limits apply (§3.3), so a + client must set it truthfully for its own mail:** `account` only for mail to an account holder (password + reset, invitation), `form-confirmation` for mail to an address a visitor typed. +- **`to`, `cc`, `bcc`**: bare addresses (`name@domain`), ASCII, no display names. At least one `to` (for every + kind but `security-alert`). The total over the three lists is limited per site + (`limits.recipientsPerMessage` in `/v1/status`; the schema's 50 is only the service's upper bound). +- **`security-alert` is addressed by the service.** `to`, `cc` and `bcc` may be left out and are ignored; + whoever controls a site cannot redirect its alerts. The service puts the site's host in front of the + subject: `[example.com] …` — as it does for **any** mail of a site that has Intecion's own address among its + recipients. +- **`replyTo`**: one bare address. The sender address has no mailbox, so send one whenever a reply makes sense. +- **`senderName`**: the display name. Optional; without it the mail leaves under the site's host. See §3.1. +- **`subject`**: 1 to 300 characters, **no line breaks, no control characters, no characters that hide or + reorder text** — Unicode categories Cc, Zl, Zp, Co, lone surrogates, and Cf (zero-width space, direction + marks and overrides, word joiner, byte-order mark, tag characters) **except three that are ordinary text**: + the zero-width joiner U+200D (inside emoji), the zero-width non-joiner U+200C (Persian and other scripts) and + the soft hyphen U+00AD. A subject is often a visitor's own words: **the client strips what is not allowed + before sending** (a regular expression for it: `/[\p{Cc}\p{Zl}\p{Zp}\p{Co}\p{Cs}]|(?![\u200C\u200D\u00AD])\p{Cf}/gu`); + the service refuses, it does not repair, and a refused message is a lost one. A subject must not start with the + service's name in brackets (`[Intecion Notifications Webservice] …`): that is how the service's own notices + begin. +- **`text` and/or `html`**: at least one. Together at most `limits.maxBodyBytes` (UTF-8). +- **`senderName`**, **`subject`**: lengths are counted in characters (Unicode code points), not bytes. +- **`attachments`**: `content` is base64 (standard alphabet, padded to a multiple of four, no line breaks). + Decoded, all files together are at most `limits.maxAttachmentBytes`. File names: no path, no quotes, no + control or invisible characters. Programs and scripts are refused by extension + (`422 attachment-refused`, with `field` naming the file). +- The sender address is fixed by the service. It adds `X-Intecion-Site: ` and `X-Intecion-Product: ` + to the mail. + +Answer ([`SendResponse`](schema.json)): + +```json +{ "ok": true, "id": "…", "messageId": "…", "replayed": false, + "senderName": "Kancelaria Example", "warnings": [], + "quota": { "hour": { "limit": 30, "remaining": 29 }, "day": { "limit": 200, "remaining": 199 } } } +``` + +`200` means the back end accepted the message for delivery, not that it arrived. + +### 3.1 The sender name + +The service cleans the name and may replace it. A name that is not accepted is **not** a failed send: the mail +leaves under the site's host instead, and the answer carries `"warnings": ["sender-name-replaced"]` and the +name used in `senderName`. + +Accepted: at most 64 characters; letters, digits, spaces and `. , & ' - ( ) /`; letters of one script only. +The guard errs on the careful side and will now and then replace an honest name (one that contains a word +from the list, or reads like a web address: "Dom.Pl"). **A client shows the warning in its panel, with the name +that was used,** so that the site's owner can choose another. + +Not accepted: `@ < > " \`, anything that looks like an e-mail or web address (the site's own host is allowed), +and names on the service's list of names that are never a client's (mailbox providers, banks, "support", +"security", "administrator", "no-reply" …). The list is the service's and can change without a new contract +version. + +### 3.2 `Idempotency-Key` + +- One key per message; the same key on every retry of that message. +- **"The same body" means the same bytes.** A client encodes a message to JSON **once**, keeps those bytes with + the key, and sends exactly them on every retry. Encoding the same message again is not safe: another order of + the fields, `\/` instead of `/`, or other spacing is another body. +- The same key with the same bytes within 24 hours: no second mail; the first answer comes back with + `"replayed": true`. +- The same key with other bytes: `409 idempotency-conflict`. +- A send that was refused or failed does not use up its key. + +### 3.3 Limits + +A message that would pass a limit is refused whole with `429 quota-exceeded` and `limit`: + +| `limit` | Counted | Applies to | +|---|---|---| +| `hour` | messages in the last 60 minutes | every kind but `security-alert`. **`account` mail may use all of it; every other kind only four fifths** (24 of 30), so that a busy or abused form cannot use up the room for a password reset | +| `day` | messages this UTC day | the same: four fifths (160 of 200) for everything but `account` | +| `alerts` | `security-alert` messages this UTC day | `security-alert` only: a budget of its own (`limits.securityAlertsPerDay`, 20), outside `hour` and `day` in both directions — alerts use up nothing else, and nothing else can use up the alerts | +| `recipient` | `form-confirmation` messages to one address this UTC day | `form-confirmation` only: it is for addresses a visitor typed into a form. Other mail to one address (a form's notification to the client's office) is never refused by it | +| `new-recipients` | addresses this site has not mailed in the last 30 days, this UTC day | every kind but `account` and `security-alert`. **A form's confirmations may use four fifths of it** (40 of 50); the rest is kept for the site's other mail, so that addresses a stranger invents in a form cannot keep a notification from an office the site has not written to for a month. `account` mail is outside it altogether: a password reset goes to whoever asked | +| `service` | all sites together this UTC day | every kind | + +The numbers are the service's, per site, and are reported by `/v1/status` (`limits`; its `quota` is the whole +hour and day). The `quota` in the answer to a send is what is left **for a message of that kind**. A refused or +failed send costs no quota (failed ones are limited by themselves: 60 an hour per site, the sends that are +with the mail back end at that moment counted in, then `rate-limited`, §1). With a limit below +five nothing is set apart. + +## 4. Status — `GET /v1/status` + +`Authorization: Bearer ims_…`. Answers for a pending and a suspended site too, so a panel can say why mail does +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" }, + "sender": { "address": "notification@webservices.intecion.net" }, + "limits": { "messagesPerHour": 30, "messagesPerDay": 200, "recipientsPerMessage": 10, + "perRecipientPerDay": 10, "newRecipientsPerDay": 50, + "maxBodyBytes": 512000, "maxAttachmentBytes": 10485760, "maxAttachments": 20 }, + "quota": { "hour": { "limit": 30, "remaining": 30 }, "day": { "limit": 200, "remaining": 200 } }, + "kinds": ["form-notification", "form-confirmation", "account", "security-alert", "system", "test"], + "token": { "issuedAt": "2026-11-25T10:00:00.000Z", "rotateAfter": "2027-02-23T10:00:00.000Z" } } +``` + +A client takes its attachment limit from `limits.maxAttachmentBytes`, never from a constant of its own. + +## 5. Rotation — `POST /v1/rotate` + +`Authorization: Bearer ims_…`, no body. When `token.rotateAfter` has passed (90 days after issue), the client +asks for a new token. The answer carries it ([`RotateResponse`](schema.json)): + +```json +{ "ok": true, "token": "ims_…", "previousValidUntil": "2027-02-24T10:00:00.000Z" } +``` + +- Store the new token at once. The previous one stays valid for 24 hours. +- Only the **current** token can rotate. With several processes on one site, exactly one rotation wins; the + others get `409 already-rotated` and read the shared store again. +- If the answer is lost, the new token is lost: the old one works for 24 hours, then `401 invalid-token` leads + to a new enrolment. A client that gets `already-rotated` and finds no newer token in its store enrols again + at once instead of waiting for that. + +## 6. Giving up the token — `POST /v1/revoke` + +`Authorization: Bearer ims_…`, no body. Every token of the site stops working at once; `{ "ok": true }`. The +site's state is kept. To send again the site enrols again. + +## 7. `GET /health` + +No authentication. `200 { "ok": true }` or `503 { "ok": false }`, nothing else. For an uptime check, not for a client. + +## 8. Authentication, in one place + +- The token is `ims_` and 43 characters. It is opaque; the service keeps only its SHA-256. +- Every route except `/v1/enrol` and `/health` needs it, **and** needs the request to come from a server + address the site enrolled from (IPv6: the same `/64`). A good token from another address gets `401 reverify` + and nothing else — not even the site's state. +- A token belongs to one host and cannot act for another. + +## 9. Versions + +- `VERSION` is `major.minor.patch`. The major is the path prefix (`/v1`). +- **Minor:** something was added that an older client need not know — a new optional request field, a new + answer field, a new `kind`, a new error `code` (treat an unknown code by its `retryable`), a new warning. + For that reason `code` and `warnings` are open strings in the schema, not closed lists. +- **Before the first release** (the first `mail-relay-contract/v…` tag) these are development versions: any + change of behaviour bumps the minor, and nobody is promised that an older copy still works. From the first + tag on the rules above hold strictly. +- **Patch:** wording, examples. +- **Major:** anything else. The service keeps answering the previous major for as long as any released client + speaks it. +- `/v1/status` reports the contract version the service speaks. A client carries the `VERSION` of its copy. + +## 10. The examples and the runner + +Each file in `examples/` is one case: + +```json +{ + "id": "send-hour-quota", + "title": "…", + "given": { "site": "active", "quota": "hour-exhausted" }, + "request": { "method": "POST", "path": "/v1/send", + "headers": { "authorization": "Bearer {{token}}", "idempotency-key": "{{idempotencyKey}}", "content-type": "application/json" }, + "schema": "SendRequest", "body": { } }, + "response": { "status": 429, "schema": "Error", "body": { "ok": false, "code": "quota-exceeded", "limit": "hour" } }, + "then": { "mails": 0 }, + "client": { "retry": false, "reEnrol": false, "status": "relay-quota" } +} +``` + +- **`given`** names the state the case needs; whoever runs the examples arranges it (table below). +- **`request`** is sent as written, after `{{name}}` is replaced. `schema` names the `$defs` entry the body + must match (left out when the body is wrong on purpose). `{ "$base64Bytes": n }` stands for the base64 of + `n` bytes. +- **`response.body`** is a subset: every field written must be there with that value; more may be there. +- **`then`** says what must be true afterwards: `mails` (how many messages reached the back end in this case) + and `mail` (fields of the one message). +- **`client`** says what a client does with this answer: `retry`, `reEnrol`, and the suggested site status. + Use it to test a client against a canned answer. +- `"direction": "service-to-site"` marks a case that describes the call-back: the request is what the + service sends, the response what the site's confirm endpoint answers. + +### `given` + +| Key | Values | Meaning | +|---|---|---| +| `site` | `none`, `pending`, `active`, `suspended` | State of `{{host}}` in the registry. Anything but `none` implies a token in `{{token}}` | +| `listed` | `true`, `false` | Enrolment: whether `{{host}}` is on Intecion's list | +| `callback` | `ok`, `not-found`, `wrong-confirmation`, `redirect`, `no-content` | Enrolment: how the site's confirm endpoint behaves. `no-content` answers a bare `204` | +| `token` | `current`, `unknown`, `previous`, `none` | Which token `{{token}}` is. `previous` is a token replaced less than 24 hours ago. `none`: the header is left out | +| `address` | `known`, `unknown` | Whether the request comes from an address the site enrolled from | +| `quota` | `fresh`, `hour-exhausted`, `day-exhausted`, `recipient-exhausted`, `hour-share-used` | The site's counters. `recipient-exhausted`: `{{recipient}}` got the day's maximum of form confirmations. `hour-share-used`: mail other than `account` has used its four fifths of the hour | +| `idempotency` | `fresh`, `sent-same`, `sent-other` | Whether `{{idempotencyKey}}` was already used: for this very body, or for another | +| `backend` | `ok`, `recipient-suppressed`, `failure` | How the mail back end answers | + +Variables: `{{host}}`, `{{token}}`, `{{nonce}}`, `{{idempotencyKey}}`, `{{recipient}}`, and — read from the +service — `{{senderAddress}}`, `{{alertRecipient}}`. + +### Running them + +```js +import { runExample } from './runner.mjs' + +const driver = { + // Arrange `given`; return the variables for {{…}}. + async arrange(given, example) { return { host, token, nonce, idempotencyKey, recipient, senderAddress, alertRecipient } }, + // Send one request to the thing under test. + async request({ method, path, headers, body }) { return { status, headers, body } }, + // Optional: validate `value` against schema.json#/$defs/; return a list of problems. + validate(name, value) { return [] }, + // Optional: the messages that reached the back end since arrange(). + async mails() { return [{ from, fromName, to, cc, bcc, replyTo, subject, headers }] }, +} + +for (const example of examples) await runExample(example, driver) // throws on the first mismatch +``` + +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. + +## 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 +`mail-relay-contract/v…` tag, and has one test that runs `node checksums.mjs --check` on the copy, so a +hand-edited copy fails. The copy's `VERSION` says which contract the client speaks. + +Checklist for a client: + +1. Constants: the base address, the contract version. No secret. +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`). +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. +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 + visitor) is what decides; the service cannot tell a wanted reset from an unwanted one. +7. Strip from the subject what §3 does not allow (line breaks, control characters, direction marks and other + invisible characters — not only line breaks); bare addresses only; the right `kind` for each mail. +8. Read limits from `/v1/status`; rotate after `token.rotateAfter`. +9. Run the examples: the `client` block of each against canned answers, and the whole set against your local + stand-in. diff --git a/contracts/mail-relay/VERSION b/contracts/mail-relay/VERSION new file mode 100644 index 0000000..bc80560 --- /dev/null +++ b/contracts/mail-relay/VERSION @@ -0,0 +1 @@ +1.5.0 diff --git a/contracts/mail-relay/checksums.mjs b/contracts/mail-relay/checksums.mjs new file mode 100644 index 0000000..304374c --- /dev/null +++ b/contracts/mail-relay/checksums.mjs @@ -0,0 +1,62 @@ +#!/usr/bin/env node +// SHA-256 of every contract file, so a hand-edited copy is noticed. +// node checksums.mjs --check compare the files with CHECKSUMS (exit 1 on any difference) +// node checksums.mjs --write rewrite CHECKSUMS (only in the IWDL repository, when the contract changes) +// Node only, no dependency. Works on a copy of this folder anywhere. +import { createHash } from 'node:crypto' +import { readFileSync, readdirSync, writeFileSync, existsSync } from 'node:fs' +import { dirname, join } from 'node:path' +import { fileURLToPath } from 'node:url' + +const here = dirname(fileURLToPath(import.meta.url)) +const FIXED = ['README.md', 'CHANGELOG.md', 'VERSION', 'schema.json', 'runner.mjs', 'checksums.mjs'] + +function files() { + const examples = readdirSync(join(here, 'examples')) + .filter((f) => f.endsWith('.json')) + .sort() + .map((f) => `examples/${f}`) + return [...FIXED, ...examples] +} + +function sums() { + return files() + .map((f) => `${createHash('sha256').update(readFileSync(join(here, f))).digest('hex')} ${f}`) + .join('\n') + '\n' +} + +const mode = process.argv[2] +if (mode === '--write') { + writeFileSync(join(here, 'CHECKSUMS'), sums()) + console.log(`CHECKSUMS written (${files().length} files)`) +} else if (mode === '--check') { + if (!existsSync(join(here, 'CHECKSUMS'))) { + console.error('CHECKSUMS is missing') + process.exit(1) + } + const want = new Map( + readFileSync(join(here, 'CHECKSUMS'), 'utf8').split('\n').filter(Boolean).map((l) => { + const [sum, name] = l.split(' ') + return [name, sum] + }), + ) + const have = new Map(sums().split('\n').filter(Boolean).map((l) => { + const [sum, name] = l.split(' ') + return [name, sum] + })) + const problems = [] + for (const [name, sum] of have) { + if (!want.has(name)) problems.push(`not in CHECKSUMS: ${name}`) + else if (want.get(name) !== sum) problems.push(`changed: ${name}`) + } + for (const name of want.keys()) if (!have.has(name)) problems.push(`missing: ${name}`) + if (problems.length) { + console.error(problems.join('\n')) + console.error('\nThe contract files do not match CHECKSUMS. Copy them again from IWDL; do not edit a copy.') + process.exit(1) + } + console.log(`contract ${readFileSync(join(here, 'VERSION'), 'utf8').trim()}: ${have.size} files match CHECKSUMS`) +} else { + console.error('usage: node checksums.mjs --check | --write') + process.exit(2) +} diff --git a/contracts/mail-relay/examples/callback-confirm-wordpress.json b/contracts/mail-relay/examples/callback-confirm-wordpress.json new file mode 100644 index 0000000..44c1d8a --- /dev/null +++ b/contracts/mail-relay/examples/callback-confirm-wordpress.json @@ -0,0 +1,25 @@ +{ + "id": "callback-confirm-wordpress", + "direction": "service-to-site", + "title": "IAWL (WordPress) sites: the same call at the REST route addressed by query, which works with and without pretty permalinks", + "request": { + "method": "POST", + "path": "/?rest_route=/iawl/v1/mail-relay/confirm", + "headers": { + "content-type": "application/json" + }, + "schema": "CallbackRequest", + "body": { + "nonce": "EXAMPLEnonceEXAMPLEnonceEXAMPLEnonce00000000", + "token": "ims_EXAMPLEtokenEXAMPLEtokenEXAMPLEtoken0000000", + "state": "active" + } + }, + "response": { + "status": 200, + "schema": "CallbackResponse", + "body": { + "confirmation": "1d5818782053c1f5aae3f9abd898a530cf974c59526d240902c9e19619e0462b" + } + } +} diff --git a/contracts/mail-relay/examples/callback-confirm.json b/contracts/mail-relay/examples/callback-confirm.json new file mode 100644 index 0000000..4ca36ef --- /dev/null +++ b/contracts/mail-relay/examples/callback-confirm.json @@ -0,0 +1,25 @@ +{ + "id": "callback-confirm", + "direction": "service-to-site", + "title": "IAPL (Payload) sites: the call the service makes, and the only answer that enrols. confirmation = hex SHA-256 of nonce + \".\" + token", + "request": { + "method": "POST", + "path": "/api/iapl/mail-relay/confirm", + "headers": { + "content-type": "application/json" + }, + "schema": "CallbackRequest", + "body": { + "nonce": "EXAMPLEnonceEXAMPLEnonceEXAMPLEnonce00000000", + "token": "ims_EXAMPLEtokenEXAMPLEtokenEXAMPLEtoken0000000", + "state": "active" + } + }, + "response": { + "status": 200, + "schema": "CallbackResponse", + "body": { + "confirmation": "1d5818782053c1f5aae3f9abd898a530cf974c59526d240902c9e19619e0462b" + } + } +} diff --git a/contracts/mail-relay/examples/callback-unknown-nonce.json b/contracts/mail-relay/examples/callback-unknown-nonce.json new file mode 100644 index 0000000..727b00b --- /dev/null +++ b/contracts/mail-relay/examples/callback-unknown-nonce.json @@ -0,0 +1,21 @@ +{ + "id": "callback-unknown-nonce", + "direction": "service-to-site", + "title": "A call with a nonce the site does not hold: 404, nothing stored", + "request": { + "method": "POST", + "path": "/api/iapl/mail-relay/confirm", + "headers": { + "content-type": "application/json" + }, + "schema": "CallbackRequest", + "body": { + "nonce": "UNKNOWNnonceUNKNOWNnonceUNKNOWNnonce00000000", + "token": "ims_EXAMPLEtokenEXAMPLEtokenEXAMPLEtoken0000000", + "state": "active" + } + }, + "response": { + "status": 404 + } +} diff --git a/contracts/mail-relay/examples/enrol-address-literal.json b/contracts/mail-relay/examples/enrol-address-literal.json new file mode 100644 index 0000000..bfecb5b --- /dev/null +++ b/contracts/mail-relay/examples/enrol-address-literal.json @@ -0,0 +1,33 @@ +{ + "id": "enrol-address-literal", + "title": "An address literal is not a host", + "given": { + "site": "none" + }, + "request": { + "method": "POST", + "path": "/v1/enrol", + "headers": { + "content-type": "application/json" + }, + "body": { + "host": "192.0.2.10", + "nonce": "{{nonce}}", + "product": "iapl", + "productVersion": "1.17.0" + } + }, + "response": { + "status": 403, + "schema": "Error", + "body": { + "ok": false, + "code": "host-not-allowed" + } + }, + "client": { + "retry": false, + "reEnrol": false, + "status": "relay-refused" + } +} diff --git a/contracts/mail-relay/examples/enrol-callback-no-content.json b/contracts/mail-relay/examples/enrol-callback-no-content.json new file mode 100644 index 0000000..4eee666 --- /dev/null +++ b/contracts/mail-relay/examples/enrol-callback-no-content.json @@ -0,0 +1,37 @@ +{ + "id": "enrol-callback-no-content", + "title": "An endpoint that answers 204 to anything is not a confirm endpoint", + "given": { + "site": "none", + "listed": true, + "callback": "no-content" + }, + "request": { + "method": "POST", + "path": "/v1/enrol", + "headers": { + "content-type": "application/json" + }, + "schema": "EnrolRequest", + "body": { + "host": "{{host}}", + "nonce": "{{nonce}}", + "product": "iapl", + "productVersion": "1.17.0" + } + }, + "response": { + "status": 422, + "schema": "Error", + "body": { + "ok": false, + "code": "callback-failed", + "reason": "status" + } + }, + "client": { + "retry": false, + "reEnrol": false, + "status": "relay-refused" + } +} diff --git a/contracts/mail-relay/examples/enrol-callback-not-found.json b/contracts/mail-relay/examples/enrol-callback-not-found.json new file mode 100644 index 0000000..b308062 --- /dev/null +++ b/contracts/mail-relay/examples/enrol-callback-not-found.json @@ -0,0 +1,38 @@ +{ + "id": "enrol-callback-not-found", + "title": "Enrolment for a host whose confirm endpoint does not hold the nonce (a host the caller does not control) yields nothing", + "given": { + "site": "none", + "listed": true, + "callback": "not-found" + }, + "request": { + "method": "POST", + "path": "/v1/enrol", + "headers": { + "content-type": "application/json" + }, + "schema": "EnrolRequest", + "body": { + "host": "{{host}}", + "nonce": "{{nonce}}", + "product": "iapl", + "productVersion": "1.17.0" + } + }, + "response": { + "status": 422, + "schema": "Error", + "body": { + "ok": false, + "code": "callback-failed", + "reason": "status", + "retryable": false + } + }, + "client": { + "retry": false, + "reEnrol": false, + "status": "relay-refused" + } +} diff --git a/contracts/mail-relay/examples/enrol-callback-path-given.json b/contracts/mail-relay/examples/enrol-callback-path-given.json new file mode 100644 index 0000000..bebcb4e --- /dev/null +++ b/contracts/mail-relay/examples/enrol-callback-path-given.json @@ -0,0 +1,37 @@ +{ + "id": "enrol-callback-path-given", + "title": "A site cannot say where it is to be called back: the path is fixed per product", + "given": { + "site": "none", + "listed": true, + "callback": "ok" + }, + "request": { + "method": "POST", + "path": "/v1/enrol", + "headers": { + "content-type": "application/json" + }, + "body": { + "host": "{{host}}", + "callbackPath": "/api/iapl/mail-relay/confirm", + "nonce": "{{nonce}}", + "product": "iapl", + "productVersion": "1.17.0" + } + }, + "response": { + "status": 400, + "schema": "Error", + "body": { + "ok": false, + "code": "invalid-request", + "field": "callbackPath" + } + }, + "client": { + "retry": false, + "reEnrol": false, + "status": null + } +} diff --git a/contracts/mail-relay/examples/enrol-callback-redirect.json b/contracts/mail-relay/examples/enrol-callback-redirect.json new file mode 100644 index 0000000..1e9d947 --- /dev/null +++ b/contracts/mail-relay/examples/enrol-callback-redirect.json @@ -0,0 +1,37 @@ +{ + "id": "enrol-callback-redirect", + "title": "A redirect is never followed", + "given": { + "site": "none", + "listed": true, + "callback": "redirect" + }, + "request": { + "method": "POST", + "path": "/v1/enrol", + "headers": { + "content-type": "application/json" + }, + "schema": "EnrolRequest", + "body": { + "host": "{{host}}", + "nonce": "{{nonce}}", + "product": "iapl", + "productVersion": "1.17.0" + } + }, + "response": { + "status": 422, + "schema": "Error", + "body": { + "ok": false, + "code": "callback-failed", + "reason": "redirect" + } + }, + "client": { + "retry": false, + "reEnrol": false, + "status": "relay-refused" + } +} diff --git a/contracts/mail-relay/examples/enrol-callback-wrong-confirmation.json b/contracts/mail-relay/examples/enrol-callback-wrong-confirmation.json new file mode 100644 index 0000000..574e21a --- /dev/null +++ b/contracts/mail-relay/examples/enrol-callback-wrong-confirmation.json @@ -0,0 +1,37 @@ +{ + "id": "enrol-callback-wrong-confirmation", + "title": "A 200 answer without the right confirmation does not enrol", + "given": { + "site": "none", + "listed": true, + "callback": "wrong-confirmation" + }, + "request": { + "method": "POST", + "path": "/v1/enrol", + "headers": { + "content-type": "application/json" + }, + "schema": "EnrolRequest", + "body": { + "host": "{{host}}", + "nonce": "{{nonce}}", + "product": "iapl", + "productVersion": "1.17.0" + } + }, + "response": { + "status": 422, + "schema": "Error", + "body": { + "ok": false, + "code": "callback-failed", + "reason": "confirmation" + } + }, + "client": { + "retry": false, + "reEnrol": false, + "status": "relay-refused" + } +} diff --git a/contracts/mail-relay/examples/enrol-from-browser.json b/contracts/mail-relay/examples/enrol-from-browser.json new file mode 100644 index 0000000..0635bca --- /dev/null +++ b/contracts/mail-relay/examples/enrol-from-browser.json @@ -0,0 +1,37 @@ +{ + "id": "enrol-from-browser", + "title": "A cross-site POST from a browser is refused", + "given": { + "site": "none", + "listed": true, + "callback": "ok" + }, + "request": { + "method": "POST", + "path": "/v1/enrol", + "headers": { + "content-type": "application/json", + "origin": "https://evil.example.net" + }, + "schema": "EnrolRequest", + "body": { + "host": "{{host}}", + "nonce": "{{nonce}}", + "product": "iapl", + "productVersion": "1.17.0" + } + }, + "response": { + "status": 403, + "schema": "Error", + "body": { + "ok": false, + "code": "browser-not-allowed" + } + }, + "client": { + "retry": false, + "reEnrol": false, + "status": null + } +} diff --git a/contracts/mail-relay/examples/enrol-listed-active.json b/contracts/mail-relay/examples/enrol-listed-active.json new file mode 100644 index 0000000..5cf403a --- /dev/null +++ b/contracts/mail-relay/examples/enrol-listed-active.json @@ -0,0 +1,36 @@ +{ + "id": "enrol-listed-active", + "title": "A host on Intecion's list enrols and is active at once; the answer has no token", + "given": { + "site": "none", + "listed": true, + "callback": "ok" + }, + "request": { + "method": "POST", + "path": "/v1/enrol", + "headers": { + "content-type": "application/json" + }, + "schema": "EnrolRequest", + "body": { + "host": "{{host}}", + "nonce": "{{nonce}}", + "product": "iapl", + "productVersion": "1.17.0" + } + }, + "response": { + "status": 200, + "schema": "EnrolResponse", + "body": { + "ok": true, + "state": "active" + } + }, + "client": { + "retry": false, + "reEnrol": false, + "status": null + } +} diff --git a/contracts/mail-relay/examples/enrol-localhost.json b/contracts/mail-relay/examples/enrol-localhost.json new file mode 100644 index 0000000..320213f --- /dev/null +++ b/contracts/mail-relay/examples/enrol-localhost.json @@ -0,0 +1,33 @@ +{ + "id": "enrol-localhost", + "title": "A local name cannot be enrolled", + "given": { + "site": "none" + }, + "request": { + "method": "POST", + "path": "/v1/enrol", + "headers": { + "content-type": "application/json" + }, + "body": { + "host": "shop.localhost", + "nonce": "{{nonce}}", + "product": "iapl", + "productVersion": "1.17.0" + } + }, + "response": { + "status": 403, + "schema": "Error", + "body": { + "ok": false, + "code": "host-not-allowed" + } + }, + "client": { + "retry": false, + "reEnrol": false, + "status": "relay-refused" + } +} diff --git a/contracts/mail-relay/examples/enrol-short-nonce.json b/contracts/mail-relay/examples/enrol-short-nonce.json new file mode 100644 index 0000000..3e409db --- /dev/null +++ b/contracts/mail-relay/examples/enrol-short-nonce.json @@ -0,0 +1,36 @@ +{ + "id": "enrol-short-nonce", + "title": "A short nonce is refused", + "given": { + "site": "none", + "listed": true, + "callback": "ok" + }, + "request": { + "method": "POST", + "path": "/v1/enrol", + "headers": { + "content-type": "application/json" + }, + "body": { + "host": "{{host}}", + "nonce": "short", + "product": "iapl", + "productVersion": "1.17.0" + } + }, + "response": { + "status": 400, + "schema": "Error", + "body": { + "ok": false, + "code": "invalid-request", + "field": "nonce" + } + }, + "client": { + "retry": false, + "reEnrol": false, + "status": null + } +} diff --git a/contracts/mail-relay/examples/enrol-suspended.json b/contracts/mail-relay/examples/enrol-suspended.json new file mode 100644 index 0000000..62a1dd1 --- /dev/null +++ b/contracts/mail-relay/examples/enrol-suspended.json @@ -0,0 +1,35 @@ +{ + "id": "enrol-suspended", + "title": "A suspended site cannot enrol its way back", + "given": { + "site": "suspended", + "callback": "ok" + }, + "request": { + "method": "POST", + "path": "/v1/enrol", + "headers": { + "content-type": "application/json" + }, + "schema": "EnrolRequest", + "body": { + "host": "{{host}}", + "nonce": "{{nonce}}", + "product": "iapl", + "productVersion": "1.17.0" + } + }, + "response": { + "status": 403, + "schema": "Error", + "body": { + "ok": false, + "code": "site-suspended" + } + }, + "client": { + "retry": false, + "reEnrol": false, + "status": "relay-suspended" + } +} diff --git a/contracts/mail-relay/examples/enrol-unlisted-pending.json b/contracts/mail-relay/examples/enrol-unlisted-pending.json new file mode 100644 index 0000000..23088e2 --- /dev/null +++ b/contracts/mail-relay/examples/enrol-unlisted-pending.json @@ -0,0 +1,36 @@ +{ + "id": "enrol-unlisted-pending", + "title": "A host that is not on the list enrols and waits for approval", + "given": { + "site": "none", + "listed": false, + "callback": "ok" + }, + "request": { + "method": "POST", + "path": "/v1/enrol", + "headers": { + "content-type": "application/json" + }, + "schema": "EnrolRequest", + "body": { + "host": "{{host}}", + "nonce": "{{nonce}}", + "product": "iapl", + "productVersion": "1.17.0" + } + }, + "response": { + "status": 200, + "schema": "EnrolResponse", + "body": { + "ok": true, + "state": "pending" + } + }, + "client": { + "retry": false, + "reEnrol": false, + "status": "relay-pending" + } +} diff --git a/contracts/mail-relay/examples/health.json b/contracts/mail-relay/examples/health.json new file mode 100644 index 0000000..5f72c69 --- /dev/null +++ b/contracts/mail-relay/examples/health.json @@ -0,0 +1,17 @@ +{ + "id": "health", + "title": "Health says yes or no and nothing else", + "given": {}, + "request": { + "method": "GET", + "path": "/health", + "headers": {} + }, + "response": { + "status": 200, + "schema": "HealthResponse", + "body": { + "ok": true + } + } +} diff --git a/contracts/mail-relay/examples/not-found.json b/contracts/mail-relay/examples/not-found.json new file mode 100644 index 0000000..a755319 --- /dev/null +++ b/contracts/mail-relay/examples/not-found.json @@ -0,0 +1,18 @@ +{ + "id": "not-found", + "title": "An unknown route", + "given": {}, + "request": { + "method": "GET", + "path": "/v2/send", + "headers": {} + }, + "response": { + "status": 404, + "schema": "Error", + "body": { + "ok": false, + "code": "not-found" + } + } +} diff --git a/contracts/mail-relay/examples/revoke-ok.json b/contracts/mail-relay/examples/revoke-ok.json new file mode 100644 index 0000000..83515b9 --- /dev/null +++ b/contracts/mail-relay/examples/revoke-ok.json @@ -0,0 +1,26 @@ +{ + "id": "revoke-ok", + "title": "The site gives up its token", + "given": { + "site": "active" + }, + "request": { + "method": "POST", + "path": "/v1/revoke", + "headers": { + "authorization": "Bearer {{token}}" + } + }, + "response": { + "status": 200, + "schema": "RevokeResponse", + "body": { + "ok": true + } + }, + "client": { + "retry": false, + "reEnrol": false, + "status": null + } +} diff --git a/contracts/mail-relay/examples/rotate-ok.json b/contracts/mail-relay/examples/rotate-ok.json new file mode 100644 index 0000000..d825e3a --- /dev/null +++ b/contracts/mail-relay/examples/rotate-ok.json @@ -0,0 +1,26 @@ +{ + "id": "rotate-ok", + "title": "The current token rotates; the answer carries the new one", + "given": { + "site": "active" + }, + "request": { + "method": "POST", + "path": "/v1/rotate", + "headers": { + "authorization": "Bearer {{token}}" + } + }, + "response": { + "status": 200, + "schema": "RotateResponse", + "body": { + "ok": true + } + }, + "client": { + "retry": false, + "reEnrol": false, + "status": null + } +} diff --git a/contracts/mail-relay/examples/rotate-previous-token.json b/contracts/mail-relay/examples/rotate-previous-token.json new file mode 100644 index 0000000..ea0dd4d --- /dev/null +++ b/contracts/mail-relay/examples/rotate-previous-token.json @@ -0,0 +1,28 @@ +{ + "id": "rotate-previous-token", + "title": "A token that was already replaced cannot rotate", + "given": { + "site": "active", + "token": "previous" + }, + "request": { + "method": "POST", + "path": "/v1/rotate", + "headers": { + "authorization": "Bearer {{token}}" + } + }, + "response": { + "status": 409, + "schema": "Error", + "body": { + "ok": false, + "code": "already-rotated" + } + }, + "client": { + "retry": false, + "reEnrol": false, + "status": null + } +} diff --git a/contracts/mail-relay/examples/send-attachments-too-large.json b/contracts/mail-relay/examples/send-attachments-too-large.json new file mode 100644 index 0000000..8f5dabf --- /dev/null +++ b/contracts/mail-relay/examples/send-attachments-too-large.json @@ -0,0 +1,55 @@ +{ + "id": "send-attachments-too-large", + "title": "Attachments over the limit", + "given": { + "site": "active" + }, + "request": { + "method": "POST", + "path": "/v1/send", + "headers": { + "authorization": "Bearer {{token}}", + "idempotency-key": "{{idempotencyKey}}", + "content-type": "application/json" + }, + "schema": "SendRequest", + "body": { + "product": "iapl", + "productVersion": "1.17.0", + "kind": "form-notification", + "to": [ + "{{recipient}}" + ], + "replyTo": "visitor@example.org", + "senderName": "Kancelaria Example", + "subject": "New enquiry", + "text": "Hello.", + "attachments": [ + { + "filename": "big.pdf", + "contentType": "application/pdf", + "content": { + "$base64Bytes": 10485761 + } + } + ] + } + }, + "response": { + "status": 413, + "schema": "Error", + "body": { + "ok": false, + "code": "too-large", + "limit": "attachments" + } + }, + "then": { + "mails": 0 + }, + "client": { + "retry": false, + "reEnrol": false, + "status": "relay-too-large" + } +} diff --git a/contracts/mail-relay/examples/send-backend-failed.json b/contracts/mail-relay/examples/send-backend-failed.json new file mode 100644 index 0000000..644c79e --- /dev/null +++ b/contracts/mail-relay/examples/send-backend-failed.json @@ -0,0 +1,47 @@ +{ + "id": "send-backend-failed", + "title": "The back end fails; the client may retry with the same key", + "given": { + "site": "active", + "backend": "failure" + }, + "request": { + "method": "POST", + "path": "/v1/send", + "headers": { + "authorization": "Bearer {{token}}", + "idempotency-key": "{{idempotencyKey}}", + "content-type": "application/json" + }, + "schema": "SendRequest", + "body": { + "product": "iapl", + "productVersion": "1.17.0", + "kind": "form-notification", + "to": [ + "{{recipient}}" + ], + "replyTo": "visitor@example.org", + "senderName": "Kancelaria Example", + "subject": "New enquiry", + "text": "Hello." + } + }, + "response": { + "status": 502, + "schema": "Error", + "body": { + "ok": false, + "code": "backend-failed", + "retryable": true + } + }, + "then": { + "mails": 0 + }, + "client": { + "retry": true, + "reEnrol": false, + "status": "relay-unreachable" + } +} diff --git a/contracts/mail-relay/examples/send-bearer-any-case.json b/contracts/mail-relay/examples/send-bearer-any-case.json new file mode 100644 index 0000000..2f96416 --- /dev/null +++ b/contracts/mail-relay/examples/send-bearer-any-case.json @@ -0,0 +1,47 @@ +{ + "id": "send-bearer-any-case", + "title": "The word \"Bearer\" in any case", + "given": { + "site": "active" + }, + "request": { + "method": "POST", + "path": "/v1/send", + "headers": { + "authorization": "bearer {{token}}", + "idempotency-key": "{{idempotencyKey}}", + "content-type": "application/json" + }, + "schema": "SendRequest", + "body": { + "product": "iapl", + "productVersion": "1.17.0", + "kind": "form-notification", + "to": [ + "{{recipient}}" + ], + "replyTo": "visitor@example.org", + "senderName": "Kancelaria Example", + "subject": "New enquiry", + "text": "Hello." + } + }, + "response": { + "status": 200, + "schema": "SendResponse", + "body": { + "ok": true, + "replayed": false, + "senderName": "Kancelaria Example", + "warnings": [] + } + }, + "then": { + "mails": 1 + }, + "client": { + "retry": false, + "reEnrol": false, + "status": null + } +} diff --git a/contracts/mail-relay/examples/send-day-quota.json b/contracts/mail-relay/examples/send-day-quota.json new file mode 100644 index 0000000..a9ac848 --- /dev/null +++ b/contracts/mail-relay/examples/send-day-quota.json @@ -0,0 +1,48 @@ +{ + "id": "send-day-quota", + "title": "The daily limit refuses the message", + "given": { + "site": "active", + "quota": "day-exhausted" + }, + "request": { + "method": "POST", + "path": "/v1/send", + "headers": { + "authorization": "Bearer {{token}}", + "idempotency-key": "{{idempotencyKey}}", + "content-type": "application/json" + }, + "schema": "SendRequest", + "body": { + "product": "iapl", + "productVersion": "1.17.0", + "kind": "form-notification", + "to": [ + "{{recipient}}" + ], + "replyTo": "visitor@example.org", + "senderName": "Kancelaria Example", + "subject": "New enquiry", + "text": "Hello." + } + }, + "response": { + "status": 429, + "schema": "Error", + "body": { + "ok": false, + "code": "quota-exceeded", + "limit": "day", + "retryable": false + } + }, + "then": { + "mails": 0 + }, + "client": { + "retry": false, + "reEnrol": false, + "status": "relay-quota" + } +} diff --git a/contracts/mail-relay/examples/send-display-name-recipient.json b/contracts/mail-relay/examples/send-display-name-recipient.json new file mode 100644 index 0000000..0a84d1b --- /dev/null +++ b/contracts/mail-relay/examples/send-display-name-recipient.json @@ -0,0 +1,45 @@ +{ + "id": "send-display-name-recipient", + "title": "Recipients are bare addresses", + "given": { + "site": "active" + }, + "request": { + "method": "POST", + "path": "/v1/send", + "headers": { + "authorization": "Bearer {{token}}", + "idempotency-key": "{{idempotencyKey}}", + "content-type": "application/json" + }, + "body": { + "product": "iapl", + "productVersion": "1.17.0", + "kind": "form-notification", + "to": [ + "Jan " + ], + "replyTo": "visitor@example.org", + "senderName": "Kancelaria Example", + "subject": "New enquiry", + "text": "Hello." + } + }, + "response": { + "status": 400, + "schema": "Error", + "body": { + "ok": false, + "code": "invalid-request", + "field": "to" + } + }, + "then": { + "mails": 0 + }, + "client": { + "retry": false, + "reEnrol": false, + "status": null + } +} diff --git a/contracts/mail-relay/examples/send-executable-attachment.json b/contracts/mail-relay/examples/send-executable-attachment.json new file mode 100644 index 0000000..bf0b164 --- /dev/null +++ b/contracts/mail-relay/examples/send-executable-attachment.json @@ -0,0 +1,53 @@ +{ + "id": "send-executable-attachment", + "title": "A program is never carried", + "given": { + "site": "active" + }, + "request": { + "method": "POST", + "path": "/v1/send", + "headers": { + "authorization": "Bearer {{token}}", + "idempotency-key": "{{idempotencyKey}}", + "content-type": "application/json" + }, + "schema": "SendRequest", + "body": { + "product": "iapl", + "productVersion": "1.17.0", + "kind": "form-notification", + "to": [ + "{{recipient}}" + ], + "replyTo": "visitor@example.org", + "senderName": "Kancelaria Example", + "subject": "New enquiry", + "text": "Hello.", + "attachments": [ + { + "filename": "invoice.pdf.exe", + "contentType": "application/pdf", + "content": "TVqQAAMAAAA=" + } + ] + } + }, + "response": { + "status": 422, + "schema": "Error", + "body": { + "ok": false, + "code": "attachment-refused", + "field": "attachments[0]" + } + }, + "then": { + "mails": 0 + }, + "client": { + "retry": false, + "reEnrol": false, + "status": "relay-attachment-refused" + } +} diff --git a/contracts/mail-relay/examples/send-from-browser.json b/contracts/mail-relay/examples/send-from-browser.json new file mode 100644 index 0000000..4634f0b --- /dev/null +++ b/contracts/mail-relay/examples/send-from-browser.json @@ -0,0 +1,46 @@ +{ + "id": "send-from-browser", + "title": "A request with an Origin header is refused whatever the token", + "given": { + "site": "active" + }, + "request": { + "method": "POST", + "path": "/v1/send", + "headers": { + "authorization": "Bearer {{token}}", + "idempotency-key": "{{idempotencyKey}}", + "content-type": "application/json", + "origin": "https://evil.example.net" + }, + "schema": "SendRequest", + "body": { + "product": "iapl", + "productVersion": "1.17.0", + "kind": "form-notification", + "to": [ + "{{recipient}}" + ], + "replyTo": "visitor@example.org", + "senderName": "Kancelaria Example", + "subject": "New enquiry", + "text": "Hello." + } + }, + "response": { + "status": 403, + "schema": "Error", + "body": { + "ok": false, + "code": "browser-not-allowed" + } + }, + "then": { + "mails": 0 + }, + "client": { + "retry": false, + "reEnrol": false, + "status": null + } +} diff --git a/contracts/mail-relay/examples/send-from-field.json b/contracts/mail-relay/examples/send-from-field.json new file mode 100644 index 0000000..f07e277 --- /dev/null +++ b/contracts/mail-relay/examples/send-from-field.json @@ -0,0 +1,46 @@ +{ + "id": "send-from-field", + "title": "The sender address cannot be set", + "given": { + "site": "active" + }, + "request": { + "method": "POST", + "path": "/v1/send", + "headers": { + "authorization": "Bearer {{token}}", + "idempotency-key": "{{idempotencyKey}}", + "content-type": "application/json" + }, + "body": { + "product": "iapl", + "productVersion": "1.17.0", + "kind": "form-notification", + "to": [ + "{{recipient}}" + ], + "replyTo": "visitor@example.org", + "senderName": "Kancelaria Example", + "subject": "New enquiry", + "text": "Hello.", + "from": "ceo@example.com" + } + }, + "response": { + "status": 400, + "schema": "Error", + "body": { + "ok": false, + "code": "invalid-request", + "field": "from" + } + }, + "then": { + "mails": 0 + }, + "client": { + "retry": false, + "reEnrol": false, + "status": null + } +} diff --git a/contracts/mail-relay/examples/send-headers-field.json b/contracts/mail-relay/examples/send-headers-field.json new file mode 100644 index 0000000..be99dc0 --- /dev/null +++ b/contracts/mail-relay/examples/send-headers-field.json @@ -0,0 +1,48 @@ +{ + "id": "send-headers-field", + "title": "Free headers cannot be set", + "given": { + "site": "active" + }, + "request": { + "method": "POST", + "path": "/v1/send", + "headers": { + "authorization": "Bearer {{token}}", + "idempotency-key": "{{idempotencyKey}}", + "content-type": "application/json" + }, + "body": { + "product": "iapl", + "productVersion": "1.17.0", + "kind": "form-notification", + "to": [ + "{{recipient}}" + ], + "replyTo": "visitor@example.org", + "senderName": "Kancelaria Example", + "subject": "New enquiry", + "text": "Hello.", + "headers": { + "Return-Path": "x@example.net" + } + } + }, + "response": { + "status": 400, + "schema": "Error", + "body": { + "ok": false, + "code": "invalid-request", + "field": "headers" + } + }, + "then": { + "mails": 0 + }, + "client": { + "retry": false, + "reEnrol": false, + "status": null + } +} diff --git a/contracts/mail-relay/examples/send-hour-quota-account.json b/contracts/mail-relay/examples/send-hour-quota-account.json new file mode 100644 index 0000000..134ae95 --- /dev/null +++ b/contracts/mail-relay/examples/send-hour-quota-account.json @@ -0,0 +1,45 @@ +{ + "id": "send-hour-quota-account", + "title": "When other mail has used its share of the hour, account mail (a password reset) still goes out", + "given": { + "site": "active", + "quota": "hour-share-used" + }, + "request": { + "method": "POST", + "path": "/v1/send", + "headers": { + "authorization": "Bearer {{token}}", + "idempotency-key": "{{idempotencyKey}}", + "content-type": "application/json" + }, + "schema": "SendRequest", + "body": { + "product": "iapl", + "productVersion": "1.17.0", + "kind": "account", + "to": [ + "{{recipient}}" + ], + "replyTo": "visitor@example.org", + "senderName": "Kancelaria Example", + "subject": "New enquiry", + "text": "Hello." + } + }, + "response": { + "status": 200, + "schema": "SendResponse", + "body": { + "ok": true + } + }, + "then": { + "mails": 1 + }, + "client": { + "retry": false, + "reEnrol": false, + "status": null + } +} diff --git a/contracts/mail-relay/examples/send-hour-quota.json b/contracts/mail-relay/examples/send-hour-quota.json new file mode 100644 index 0000000..cef1e92 --- /dev/null +++ b/contracts/mail-relay/examples/send-hour-quota.json @@ -0,0 +1,48 @@ +{ + "id": "send-hour-quota", + "title": "The hourly limit refuses the message and says so", + "given": { + "site": "active", + "quota": "hour-exhausted" + }, + "request": { + "method": "POST", + "path": "/v1/send", + "headers": { + "authorization": "Bearer {{token}}", + "idempotency-key": "{{idempotencyKey}}", + "content-type": "application/json" + }, + "schema": "SendRequest", + "body": { + "product": "iapl", + "productVersion": "1.17.0", + "kind": "form-notification", + "to": [ + "{{recipient}}" + ], + "replyTo": "visitor@example.org", + "senderName": "Kancelaria Example", + "subject": "New enquiry", + "text": "Hello." + } + }, + "response": { + "status": 429, + "schema": "Error", + "body": { + "ok": false, + "code": "quota-exceeded", + "limit": "hour", + "retryable": false + } + }, + "then": { + "mails": 0 + }, + "client": { + "retry": false, + "reEnrol": false, + "status": "relay-quota" + } +} diff --git a/contracts/mail-relay/examples/send-key-reused.json b/contracts/mail-relay/examples/send-key-reused.json new file mode 100644 index 0000000..6509d4d --- /dev/null +++ b/contracts/mail-relay/examples/send-key-reused.json @@ -0,0 +1,46 @@ +{ + "id": "send-key-reused", + "title": "The same Idempotency-Key for another message", + "given": { + "site": "active", + "idempotency": "sent-other" + }, + "request": { + "method": "POST", + "path": "/v1/send", + "headers": { + "authorization": "Bearer {{token}}", + "idempotency-key": "{{idempotencyKey}}", + "content-type": "application/json" + }, + "schema": "SendRequest", + "body": { + "product": "iapl", + "productVersion": "1.17.0", + "kind": "form-notification", + "to": [ + "{{recipient}}" + ], + "replyTo": "visitor@example.org", + "senderName": "Kancelaria Example", + "subject": "New enquiry", + "text": "Hello." + } + }, + "response": { + "status": 409, + "schema": "Error", + "body": { + "ok": false, + "code": "idempotency-conflict" + } + }, + "then": { + "mails": 0 + }, + "client": { + "retry": false, + "reEnrol": false, + "status": null + } +} diff --git a/contracts/mail-relay/examples/send-no-sender-name.json b/contracts/mail-relay/examples/send-no-sender-name.json new file mode 100644 index 0000000..86cb0ce --- /dev/null +++ b/contracts/mail-relay/examples/send-no-sender-name.json @@ -0,0 +1,48 @@ +{ + "id": "send-no-sender-name", + "title": "Without a sender name the mail leaves under the host, with no warning", + "given": { + "site": "active" + }, + "request": { + "method": "POST", + "path": "/v1/send", + "headers": { + "authorization": "Bearer {{token}}", + "idempotency-key": "{{idempotencyKey}}", + "content-type": "application/json" + }, + "schema": "SendRequest", + "body": { + "product": "iapl", + "productVersion": "1.17.0", + "kind": "form-notification", + "to": [ + "{{recipient}}" + ], + "replyTo": "visitor@example.org", + "subject": "New enquiry", + "text": "Hello." + } + }, + "response": { + "status": 200, + "schema": "SendResponse", + "body": { + "ok": true, + "senderName": "{{host}}", + "warnings": [] + } + }, + "then": { + "mails": 1, + "mail": { + "fromName": "{{host}}" + } + }, + "client": { + "retry": false, + "reEnrol": false, + "status": null + } +} diff --git a/contracts/mail-relay/examples/send-no-token.json b/contracts/mail-relay/examples/send-no-token.json new file mode 100644 index 0000000..13c40e2 --- /dev/null +++ b/contracts/mail-relay/examples/send-no-token.json @@ -0,0 +1,46 @@ +{ + "id": "send-no-token", + "title": "No Authorization header", + "given": { + "site": "active", + "token": "none" + }, + "request": { + "method": "POST", + "path": "/v1/send", + "headers": { + "authorization": "Bearer {{token}}", + "idempotency-key": "{{idempotencyKey}}", + "content-type": "application/json" + }, + "schema": "SendRequest", + "body": { + "product": "iapl", + "productVersion": "1.17.0", + "kind": "form-notification", + "to": [ + "{{recipient}}" + ], + "replyTo": "visitor@example.org", + "senderName": "Kancelaria Example", + "subject": "New enquiry", + "text": "Hello." + } + }, + "response": { + "status": 401, + "schema": "Error", + "body": { + "ok": false, + "code": "invalid-token" + } + }, + "then": { + "mails": 0 + }, + "client": { + "retry": false, + "reEnrol": true, + "status": null + } +} diff --git a/contracts/mail-relay/examples/send-ok.json b/contracts/mail-relay/examples/send-ok.json new file mode 100644 index 0000000..d80bfbf --- /dev/null +++ b/contracts/mail-relay/examples/send-ok.json @@ -0,0 +1,60 @@ +{ + "id": "send-ok", + "title": "An active site sends one message", + "given": { + "site": "active" + }, + "request": { + "method": "POST", + "path": "/v1/send", + "headers": { + "authorization": "Bearer {{token}}", + "idempotency-key": "{{idempotencyKey}}", + "content-type": "application/json" + }, + "schema": "SendRequest", + "body": { + "product": "iapl", + "productVersion": "1.17.0", + "kind": "form-notification", + "to": [ + "{{recipient}}" + ], + "replyTo": "visitor@example.org", + "senderName": "Kancelaria Example", + "subject": "New enquiry", + "text": "Hello." + } + }, + "response": { + "status": 200, + "schema": "SendResponse", + "body": { + "ok": true, + "replayed": false, + "senderName": "Kancelaria Example", + "warnings": [] + } + }, + "then": { + "mails": 1, + "mail": { + "from": "{{senderAddress}}", + "fromName": "Kancelaria Example", + "to": [ + "{{recipient}}" + ], + "replyTo": "visitor@example.org", + "subject": "New enquiry", + "headers": { + "X-Intecion-Site": "{{host}}", + "X-Intecion-Product": "iapl" + } + } + }, + "client": { + "retry": false, + "reEnrol": false, + "status": null + } +} diff --git a/contracts/mail-relay/examples/send-pending.json b/contracts/mail-relay/examples/send-pending.json new file mode 100644 index 0000000..d107737 --- /dev/null +++ b/contracts/mail-relay/examples/send-pending.json @@ -0,0 +1,45 @@ +{ + "id": "send-pending", + "title": "A site waiting for approval sends nothing", + "given": { + "site": "pending" + }, + "request": { + "method": "POST", + "path": "/v1/send", + "headers": { + "authorization": "Bearer {{token}}", + "idempotency-key": "{{idempotencyKey}}", + "content-type": "application/json" + }, + "schema": "SendRequest", + "body": { + "product": "iapl", + "productVersion": "1.17.0", + "kind": "form-notification", + "to": [ + "{{recipient}}" + ], + "replyTo": "visitor@example.org", + "senderName": "Kancelaria Example", + "subject": "New enquiry", + "text": "Hello." + } + }, + "response": { + "status": 403, + "schema": "Error", + "body": { + "ok": false, + "code": "site-pending" + } + }, + "then": { + "mails": 0 + }, + "client": { + "retry": false, + "reEnrol": false, + "status": "relay-pending" + } +} diff --git a/contracts/mail-relay/examples/send-previous-token.json b/contracts/mail-relay/examples/send-previous-token.json new file mode 100644 index 0000000..2554187 --- /dev/null +++ b/contracts/mail-relay/examples/send-previous-token.json @@ -0,0 +1,45 @@ +{ + "id": "send-previous-token", + "title": "A token replaced less than 24 hours ago still sends", + "given": { + "site": "active", + "token": "previous" + }, + "request": { + "method": "POST", + "path": "/v1/send", + "headers": { + "authorization": "Bearer {{token}}", + "idempotency-key": "{{idempotencyKey}}", + "content-type": "application/json" + }, + "schema": "SendRequest", + "body": { + "product": "iapl", + "productVersion": "1.17.0", + "kind": "form-notification", + "to": [ + "{{recipient}}" + ], + "replyTo": "visitor@example.org", + "senderName": "Kancelaria Example", + "subject": "New enquiry", + "text": "Hello." + } + }, + "response": { + "status": 200, + "schema": "SendResponse", + "body": { + "ok": true + } + }, + "then": { + "mails": 1 + }, + "client": { + "retry": false, + "reEnrol": false, + "status": null + } +} diff --git a/contracts/mail-relay/examples/send-recipient-quota-other-kinds.json b/contracts/mail-relay/examples/send-recipient-quota-other-kinds.json new file mode 100644 index 0000000..23bbcd4 --- /dev/null +++ b/contracts/mail-relay/examples/send-recipient-quota-other-kinds.json @@ -0,0 +1,45 @@ +{ + "id": "send-recipient-quota-other-kinds", + "title": "Other mail to the same address is not refused by that limit (a form's notification to the client's office)", + "given": { + "site": "active", + "quota": "recipient-exhausted" + }, + "request": { + "method": "POST", + "path": "/v1/send", + "headers": { + "authorization": "Bearer {{token}}", + "idempotency-key": "{{idempotencyKey}}", + "content-type": "application/json" + }, + "schema": "SendRequest", + "body": { + "product": "iapl", + "productVersion": "1.17.0", + "kind": "form-notification", + "to": [ + "{{recipient}}" + ], + "replyTo": "visitor@example.org", + "senderName": "Kancelaria Example", + "subject": "New enquiry", + "text": "Hello." + } + }, + "response": { + "status": 200, + "schema": "SendResponse", + "body": { + "ok": true + } + }, + "then": { + "mails": 1 + }, + "client": { + "retry": false, + "reEnrol": false, + "status": null + } +} diff --git a/contracts/mail-relay/examples/send-recipient-quota.json b/contracts/mail-relay/examples/send-recipient-quota.json new file mode 100644 index 0000000..d6aba27 --- /dev/null +++ b/contracts/mail-relay/examples/send-recipient-quota.json @@ -0,0 +1,47 @@ +{ + "id": "send-recipient-quota", + "title": "A form's confirmation: one address gets only so many a day", + "given": { + "site": "active", + "quota": "recipient-exhausted" + }, + "request": { + "method": "POST", + "path": "/v1/send", + "headers": { + "authorization": "Bearer {{token}}", + "idempotency-key": "{{idempotencyKey}}", + "content-type": "application/json" + }, + "schema": "SendRequest", + "body": { + "product": "iapl", + "productVersion": "1.17.0", + "kind": "form-confirmation", + "to": [ + "{{recipient}}" + ], + "replyTo": "visitor@example.org", + "senderName": "Kancelaria Example", + "subject": "New enquiry", + "text": "Hello." + } + }, + "response": { + "status": 429, + "schema": "Error", + "body": { + "ok": false, + "code": "quota-exceeded", + "limit": "recipient" + } + }, + "then": { + "mails": 0 + }, + "client": { + "retry": false, + "reEnrol": false, + "status": "relay-quota" + } +} diff --git a/contracts/mail-relay/examples/send-recipient-suppressed.json b/contracts/mail-relay/examples/send-recipient-suppressed.json new file mode 100644 index 0000000..316629a --- /dev/null +++ b/contracts/mail-relay/examples/send-recipient-suppressed.json @@ -0,0 +1,47 @@ +{ + "id": "send-recipient-suppressed", + "title": "The back end refuses a suppressed recipient", + "given": { + "site": "active", + "backend": "recipient-suppressed" + }, + "request": { + "method": "POST", + "path": "/v1/send", + "headers": { + "authorization": "Bearer {{token}}", + "idempotency-key": "{{idempotencyKey}}", + "content-type": "application/json" + }, + "schema": "SendRequest", + "body": { + "product": "iapl", + "productVersion": "1.17.0", + "kind": "form-notification", + "to": [ + "{{recipient}}" + ], + "replyTo": "visitor@example.org", + "senderName": "Kancelaria Example", + "subject": "New enquiry", + "text": "Hello." + } + }, + "response": { + "status": 422, + "schema": "Error", + "body": { + "ok": false, + "code": "recipient-suppressed", + "retryable": false + } + }, + "then": { + "mails": 0 + }, + "client": { + "retry": false, + "reEnrol": false, + "status": "relay-recipient-suppressed" + } +} diff --git a/contracts/mail-relay/examples/send-replay.json b/contracts/mail-relay/examples/send-replay.json new file mode 100644 index 0000000..fa49231 --- /dev/null +++ b/contracts/mail-relay/examples/send-replay.json @@ -0,0 +1,46 @@ +{ + "id": "send-replay", + "title": "The same Idempotency-Key and body again: no second mail", + "given": { + "site": "active", + "idempotency": "sent-same" + }, + "request": { + "method": "POST", + "path": "/v1/send", + "headers": { + "authorization": "Bearer {{token}}", + "idempotency-key": "{{idempotencyKey}}", + "content-type": "application/json" + }, + "schema": "SendRequest", + "body": { + "product": "iapl", + "productVersion": "1.17.0", + "kind": "form-notification", + "to": [ + "{{recipient}}" + ], + "replyTo": "visitor@example.org", + "senderName": "Kancelaria Example", + "subject": "New enquiry", + "text": "Hello." + } + }, + "response": { + "status": 200, + "schema": "SendResponse", + "body": { + "ok": true, + "replayed": true + } + }, + "then": { + "mails": 0 + }, + "client": { + "retry": false, + "reEnrol": false, + "status": null + } +} diff --git a/contracts/mail-relay/examples/send-security-alert.json b/contracts/mail-relay/examples/send-security-alert.json new file mode 100644 index 0000000..3ffc984 --- /dev/null +++ b/contracts/mail-relay/examples/send-security-alert.json @@ -0,0 +1,52 @@ +{ + "id": "send-security-alert", + "title": "A security alert is addressed by the service and marked with the site's host; the recipients in the request are ignored", + "given": { + "site": "active" + }, + "request": { + "method": "POST", + "path": "/v1/send", + "headers": { + "authorization": "Bearer {{token}}", + "idempotency-key": "{{idempotencyKey}}", + "content-type": "application/json" + }, + "schema": "SendRequest", + "body": { + "product": "iapl", + "productVersion": "1.17.0", + "kind": "security-alert", + "to": [ + "attacker@example.net" + ], + "replyTo": "visitor@example.org", + "senderName": "Kancelaria Example", + "subject": "New enquiry", + "text": "Hello." + } + }, + "response": { + "status": 200, + "schema": "SendResponse", + "body": { + "ok": true + } + }, + "then": { + "mails": 1, + "mail": { + "to": [ + "{{alertRecipient}}" + ], + "cc": [], + "bcc": [], + "subject": "[{{host}}] New enquiry" + } + }, + "client": { + "retry": false, + "reEnrol": false, + "status": null + } +} diff --git a/contracts/mail-relay/examples/send-sender-name-replaced.json b/contracts/mail-relay/examples/send-sender-name-replaced.json new file mode 100644 index 0000000..2b8729b --- /dev/null +++ b/contracts/mail-relay/examples/send-sender-name-replaced.json @@ -0,0 +1,51 @@ +{ + "id": "send-sender-name-replaced", + "title": "A sender name that looks like an address is replaced by the host; the mail still goes out", + "given": { + "site": "active" + }, + "request": { + "method": "POST", + "path": "/v1/send", + "headers": { + "authorization": "Bearer {{token}}", + "idempotency-key": "{{idempotencyKey}}", + "content-type": "application/json" + }, + "schema": "SendRequest", + "body": { + "product": "iapl", + "productVersion": "1.17.0", + "kind": "form-notification", + "to": [ + "{{recipient}}" + ], + "replyTo": "visitor@example.org", + "senderName": "PayPal ", + "subject": "New enquiry", + "text": "Hello." + } + }, + "response": { + "status": 200, + "schema": "SendResponse", + "body": { + "ok": true, + "senderName": "{{host}}", + "warnings": [ + "sender-name-replaced" + ] + } + }, + "then": { + "mails": 1, + "mail": { + "fromName": "{{host}}" + } + }, + "client": { + "retry": false, + "reEnrol": false, + "status": "relay-name-replaced" + } +} diff --git a/contracts/mail-relay/examples/send-subject-direction-mark.json b/contracts/mail-relay/examples/send-subject-direction-mark.json new file mode 100644 index 0000000..e07648a --- /dev/null +++ b/contracts/mail-relay/examples/send-subject-direction-mark.json @@ -0,0 +1,46 @@ +{ + "id": "send-subject-direction-mark", + "title": "A direction override in the subject is refused: the client strips such characters first", + "given": { + "site": "active" + }, + "request": { + "method": "POST", + "path": "/v1/send", + "headers": { + "authorization": "Bearer {{token}}", + "idempotency-key": "{{idempotencyKey}}", + "content-type": "application/json" + }, + "schema": "SendRequest", + "body": { + "product": "iapl", + "productVersion": "1.17.0", + "kind": "form-notification", + "to": [ + "{{recipient}}" + ], + "replyTo": "visitor@example.org", + "senderName": "Kancelaria Example", + "subject": "Invoice ‮fdp.exe", + "text": "Hello." + } + }, + "response": { + "status": 400, + "schema": "Error", + "body": { + "ok": false, + "code": "invalid-request", + "field": "subject" + } + }, + "then": { + "mails": 0 + }, + "client": { + "retry": false, + "reEnrol": false, + "status": null + } +} diff --git a/contracts/mail-relay/examples/send-subject-imitates-service.json b/contracts/mail-relay/examples/send-subject-imitates-service.json new file mode 100644 index 0000000..22e1dfb --- /dev/null +++ b/contracts/mail-relay/examples/send-subject-imitates-service.json @@ -0,0 +1,46 @@ +{ + "id": "send-subject-imitates-service", + "title": "A subject that starts like one of the service's own notices is refused", + "given": { + "site": "active" + }, + "request": { + "method": "POST", + "path": "/v1/send", + "headers": { + "authorization": "Bearer {{token}}", + "idempotency-key": "{{idempotencyKey}}", + "content-type": "application/json" + }, + "schema": "SendRequest", + "body": { + "product": "iapl", + "productVersion": "1.17.0", + "kind": "form-notification", + "to": [ + "{{recipient}}" + ], + "replyTo": "visitor@example.org", + "senderName": "Kancelaria Example", + "subject": "[Intecion Notifications Webservice] example.com waits for approval", + "text": "Hello." + } + }, + "response": { + "status": 400, + "schema": "Error", + "body": { + "ok": false, + "code": "invalid-request", + "field": "subject" + } + }, + "then": { + "mails": 0 + }, + "client": { + "retry": false, + "reEnrol": false, + "status": null + } +} diff --git a/contracts/mail-relay/examples/send-subject-line-break.json b/contracts/mail-relay/examples/send-subject-line-break.json new file mode 100644 index 0000000..e1efc0f --- /dev/null +++ b/contracts/mail-relay/examples/send-subject-line-break.json @@ -0,0 +1,46 @@ +{ + "id": "send-subject-line-break", + "title": "A line break in the subject (header injection) is refused, not repaired", + "given": { + "site": "active" + }, + "request": { + "method": "POST", + "path": "/v1/send", + "headers": { + "authorization": "Bearer {{token}}", + "idempotency-key": "{{idempotencyKey}}", + "content-type": "application/json" + }, + "schema": "SendRequest", + "body": { + "product": "iapl", + "productVersion": "1.17.0", + "kind": "form-notification", + "to": [ + "{{recipient}}" + ], + "replyTo": "visitor@example.org", + "senderName": "Kancelaria Example", + "subject": "Hello\r\nBcc: victim@example.net", + "text": "Hello." + } + }, + "response": { + "status": 400, + "schema": "Error", + "body": { + "ok": false, + "code": "invalid-request", + "field": "subject" + } + }, + "then": { + "mails": 0 + }, + "client": { + "retry": false, + "reEnrol": false, + "status": null + } +} diff --git a/contracts/mail-relay/examples/send-subject-visitor-text.json b/contracts/mail-relay/examples/send-subject-visitor-text.json new file mode 100644 index 0000000..ab88437 --- /dev/null +++ b/contracts/mail-relay/examples/send-subject-visitor-text.json @@ -0,0 +1,50 @@ +{ + "id": "send-subject-visitor-text", + "title": "A subject with what visitors write — an emoji made of several, a soft hyphen — is carried as it is", + "given": { + "site": "active" + }, + "request": { + "method": "POST", + "path": "/v1/send", + "headers": { + "authorization": "Bearer {{token}}", + "idempotency-key": "{{idempotencyKey}}", + "content-type": "application/json" + }, + "schema": "SendRequest", + "body": { + "product": "iapl", + "productVersion": "1.17.0", + "kind": "form-notification", + "to": [ + "{{recipient}}" + ], + "replyTo": "visitor@example.org", + "senderName": "Kancelaria Example", + "subject": "👩‍💻 Straßen­bahn", + "text": "Hello." + } + }, + "response": { + "status": 200, + "schema": "SendResponse", + "body": { + "ok": true, + "replayed": false, + "senderName": "Kancelaria Example", + "warnings": [] + } + }, + "then": { + "mails": 1, + "mail": { + "subject": "👩‍💻 Straßen­bahn" + } + }, + "client": { + "retry": false, + "reEnrol": false, + "status": null + } +} diff --git a/contracts/mail-relay/examples/send-suspended.json b/contracts/mail-relay/examples/send-suspended.json new file mode 100644 index 0000000..1f3bdbd --- /dev/null +++ b/contracts/mail-relay/examples/send-suspended.json @@ -0,0 +1,45 @@ +{ + "id": "send-suspended", + "title": "A suspended site sends nothing", + "given": { + "site": "suspended" + }, + "request": { + "method": "POST", + "path": "/v1/send", + "headers": { + "authorization": "Bearer {{token}}", + "idempotency-key": "{{idempotencyKey}}", + "content-type": "application/json" + }, + "schema": "SendRequest", + "body": { + "product": "iapl", + "productVersion": "1.17.0", + "kind": "form-notification", + "to": [ + "{{recipient}}" + ], + "replyTo": "visitor@example.org", + "senderName": "Kancelaria Example", + "subject": "New enquiry", + "text": "Hello." + } + }, + "response": { + "status": 403, + "schema": "Error", + "body": { + "ok": false, + "code": "site-suspended" + } + }, + "then": { + "mails": 0 + }, + "client": { + "retry": false, + "reEnrol": false, + "status": "relay-suspended" + } +} diff --git a/contracts/mail-relay/examples/send-text-plain.json b/contracts/mail-relay/examples/send-text-plain.json new file mode 100644 index 0000000..ca585c1 --- /dev/null +++ b/contracts/mail-relay/examples/send-text-plain.json @@ -0,0 +1,45 @@ +{ + "id": "send-text-plain", + "title": "A form post (text/plain) is refused", + "given": { + "site": "active" + }, + "request": { + "method": "POST", + "path": "/v1/send", + "headers": { + "authorization": "Bearer {{token}}", + "idempotency-key": "{{idempotencyKey}}", + "content-type": "text/plain" + }, + "schema": "SendRequest", + "body": { + "product": "iapl", + "productVersion": "1.17.0", + "kind": "form-notification", + "to": [ + "{{recipient}}" + ], + "replyTo": "visitor@example.org", + "senderName": "Kancelaria Example", + "subject": "New enquiry", + "text": "Hello." + } + }, + "response": { + "status": 415, + "schema": "Error", + "body": { + "ok": false, + "code": "unsupported-media-type" + } + }, + "then": { + "mails": 0 + }, + "client": { + "retry": false, + "reEnrol": false, + "status": null + } +} diff --git a/contracts/mail-relay/examples/send-to-intecion-marked.json b/contracts/mail-relay/examples/send-to-intecion-marked.json new file mode 100644 index 0000000..7565ceb --- /dev/null +++ b/contracts/mail-relay/examples/send-to-intecion-marked.json @@ -0,0 +1,50 @@ +{ + "id": "send-to-intecion-marked", + "title": "Any mail of a site that reaches Intecion's own address gets the site's host in front of its subject", + "given": { + "site": "active" + }, + "request": { + "method": "POST", + "path": "/v1/send", + "headers": { + "authorization": "Bearer {{token}}", + "idempotency-key": "{{idempotencyKey}}", + "content-type": "application/json" + }, + "schema": "SendRequest", + "body": { + "product": "iapl", + "productVersion": "1.17.0", + "kind": "system", + "to": [ + "{{alertRecipient}}" + ], + "replyTo": "visitor@example.org", + "senderName": "Kancelaria Example", + "subject": "New enquiry", + "text": "Hello." + } + }, + "response": { + "status": 200, + "schema": "SendResponse", + "body": { + "ok": true + } + }, + "then": { + "mails": 1, + "mail": { + "to": [ + "{{alertRecipient}}" + ], + "subject": "[{{host}}] New enquiry" + } + }, + "client": { + "retry": false, + "reEnrol": false, + "status": null + } +} diff --git a/contracts/mail-relay/examples/send-too-many-recipients.json b/contracts/mail-relay/examples/send-too-many-recipients.json new file mode 100644 index 0000000..054fbe1 --- /dev/null +++ b/contracts/mail-relay/examples/send-too-many-recipients.json @@ -0,0 +1,59 @@ +{ + "id": "send-too-many-recipients", + "title": "More than ten recipients over To, CC and BCC", + "given": { + "site": "active" + }, + "request": { + "method": "POST", + "path": "/v1/send", + "headers": { + "authorization": "Bearer {{token}}", + "idempotency-key": "{{idempotencyKey}}", + "content-type": "application/json" + }, + "schema": "SendRequest", + "body": { + "product": "iapl", + "productVersion": "1.17.0", + "kind": "form-notification", + "to": [ + "a1@example.org", + "a2@example.org", + "a3@example.org", + "a4@example.org", + "a5@example.org", + "a6@example.org" + ], + "replyTo": "visitor@example.org", + "senderName": "Kancelaria Example", + "subject": "New enquiry", + "text": "Hello.", + "cc": [ + "b1@example.org", + "b2@example.org", + "b3@example.org" + ], + "bcc": [ + "c1@example.org", + "c2@example.org" + ] + } + }, + "response": { + "status": 422, + "schema": "Error", + "body": { + "ok": false, + "code": "too-many-recipients" + } + }, + "then": { + "mails": 0 + }, + "client": { + "retry": false, + "reEnrol": false, + "status": "relay-quota" + } +} diff --git a/contracts/mail-relay/examples/send-unknown-address.json b/contracts/mail-relay/examples/send-unknown-address.json new file mode 100644 index 0000000..afc01f8 --- /dev/null +++ b/contracts/mail-relay/examples/send-unknown-address.json @@ -0,0 +1,47 @@ +{ + "id": "send-unknown-address", + "title": "A good token from a server address the site never enrolled from (a stolen token)", + "given": { + "site": "active", + "address": "unknown" + }, + "request": { + "method": "POST", + "path": "/v1/send", + "headers": { + "authorization": "Bearer {{token}}", + "idempotency-key": "{{idempotencyKey}}", + "content-type": "application/json" + }, + "schema": "SendRequest", + "body": { + "product": "iapl", + "productVersion": "1.17.0", + "kind": "form-notification", + "to": [ + "{{recipient}}" + ], + "replyTo": "visitor@example.org", + "senderName": "Kancelaria Example", + "subject": "New enquiry", + "text": "Hello." + } + }, + "response": { + "status": 401, + "schema": "Error", + "body": { + "ok": false, + "code": "reverify", + "retryable": false + } + }, + "then": { + "mails": 0 + }, + "client": { + "retry": false, + "reEnrol": true, + "status": null + } +} diff --git a/contracts/mail-relay/examples/send-unknown-token.json b/contracts/mail-relay/examples/send-unknown-token.json new file mode 100644 index 0000000..befb26a --- /dev/null +++ b/contracts/mail-relay/examples/send-unknown-token.json @@ -0,0 +1,46 @@ +{ + "id": "send-unknown-token", + "title": "A token the service does not know", + "given": { + "site": "active", + "token": "unknown" + }, + "request": { + "method": "POST", + "path": "/v1/send", + "headers": { + "authorization": "Bearer {{token}}", + "idempotency-key": "{{idempotencyKey}}", + "content-type": "application/json" + }, + "schema": "SendRequest", + "body": { + "product": "iapl", + "productVersion": "1.17.0", + "kind": "form-notification", + "to": [ + "{{recipient}}" + ], + "replyTo": "visitor@example.org", + "senderName": "Kancelaria Example", + "subject": "New enquiry", + "text": "Hello." + } + }, + "response": { + "status": 401, + "schema": "Error", + "body": { + "ok": false, + "code": "invalid-token" + } + }, + "then": { + "mails": 0 + }, + "client": { + "retry": false, + "reEnrol": true, + "status": null + } +} diff --git a/contracts/mail-relay/examples/status-active.json b/contracts/mail-relay/examples/status-active.json new file mode 100644 index 0000000..a4382ce --- /dev/null +++ b/contracts/mail-relay/examples/status-active.json @@ -0,0 +1,35 @@ +{ + "id": "status-active", + "title": "Status of an active site", + "given": { + "site": "active" + }, + "request": { + "method": "GET", + "path": "/v1/status", + "headers": { + "authorization": "Bearer {{token}}" + } + }, + "response": { + "status": 200, + "schema": "StatusResponse", + "body": { + "ok": true, + "state": "active", + "host": "{{host}}", + "product": "iapl", + "service": { + "name": "Intecion Notifications Webservice" + }, + "sender": { + "address": "{{senderAddress}}" + } + } + }, + "client": { + "retry": false, + "reEnrol": false, + "status": null + } +} diff --git a/contracts/mail-relay/examples/status-pending.json b/contracts/mail-relay/examples/status-pending.json new file mode 100644 index 0000000..91e2a88 --- /dev/null +++ b/contracts/mail-relay/examples/status-pending.json @@ -0,0 +1,27 @@ +{ + "id": "status-pending", + "title": "Status answers for a pending site too", + "given": { + "site": "pending" + }, + "request": { + "method": "GET", + "path": "/v1/status", + "headers": { + "authorization": "Bearer {{token}}" + } + }, + "response": { + "status": 200, + "schema": "StatusResponse", + "body": { + "ok": true, + "state": "pending" + } + }, + "client": { + "retry": false, + "reEnrol": false, + "status": "relay-pending" + } +} diff --git a/contracts/mail-relay/examples/status-unknown-address.json b/contracts/mail-relay/examples/status-unknown-address.json new file mode 100644 index 0000000..ee9b5b7 --- /dev/null +++ b/contracts/mail-relay/examples/status-unknown-address.json @@ -0,0 +1,28 @@ +{ + "id": "status-unknown-address", + "title": "Status gives nothing to a token from an unknown address", + "given": { + "site": "active", + "address": "unknown" + }, + "request": { + "method": "GET", + "path": "/v1/status", + "headers": { + "authorization": "Bearer {{token}}" + } + }, + "response": { + "status": 401, + "schema": "Error", + "body": { + "ok": false, + "code": "reverify" + } + }, + "client": { + "retry": false, + "reEnrol": true, + "status": null + } +} diff --git a/contracts/mail-relay/runner.mjs b/contracts/mail-relay/runner.mjs new file mode 100644 index 0000000..dc64b2a --- /dev/null +++ b/contracts/mail-relay/runner.mjs @@ -0,0 +1,160 @@ +// Contract test runner for the Intecion Notifications Webservice. +// 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 class ContractError extends Error { + constructor(exampleId, message) { + super(`[${exampleId}] ${message}`) + this.name = 'ContractError' + this.exampleId = exampleId + } +} + +/** The confirmation a site's confirm endpoint answers with: lowercase hex SHA-256 of nonce + "." + token. */ +export async function confirmationFor(nonce, token) { + const bytes = new TextEncoder().encode(`${nonce}.${token}`) + const digest = await crypto.subtle.digest('SHA-256', bytes) + return [...new Uint8Array(digest)].map((b) => b.toString(16).padStart(2, '0')).join('') +} + +/** Base64 of `n` zero bytes, built without holding the bytes. */ +export function base64OfBytes(n) { + const full = Math.floor(n / 3) + const rest = n % 3 + return 'AAAA'.repeat(full) + (rest === 1 ? 'AA==' : rest === 2 ? 'AAA=' : '') +} + +/** Replace {{name}} and { "$base64Bytes": n } everywhere in a value. Unknown names are an error. */ +export function expand(value, vars, exampleId = '?') { + if (typeof value === 'string') { + return value.replace(/\{\{([A-Za-z]+)\}\}/g, (_, name) => { + if (vars[name] === undefined || vars[name] === null) { + throw new ContractError(exampleId, `the driver's arrange() gave no value for {{${name}}}`) + } + return String(vars[name]) + }) + } + if (Array.isArray(value)) return value.map((v) => expand(v, vars, exampleId)) + if (value && typeof value === 'object') { + if (typeof value.$base64Bytes === 'number') return base64OfBytes(value.$base64Bytes) + const out = {} + for (const [k, v] of Object.entries(value)) out[k] = expand(v, vars, exampleId) + return out + } + return value +} + +/** Every field of `expected` must be in `actual` with that value; `actual` may have more. Arrays must be equal. */ +export function subsetMismatch(actual, expected, path = '') { + if (expected === null || typeof expected !== 'object') { + return Object.is(actual, expected) ? null : `${path || 'value'}: expected ${JSON.stringify(expected)}, got ${JSON.stringify(actual)}` + } + if (Array.isArray(expected)) { + if (!Array.isArray(actual) || actual.length !== expected.length) { + return `${path || 'value'}: expected ${JSON.stringify(expected)}, got ${JSON.stringify(actual)}` + } + for (let i = 0; i < expected.length; i++) { + const m = subsetMismatch(actual[i], expected[i], `${path}[${i}]`) + if (m) return m + } + return null + } + if (actual === null || typeof actual !== 'object') { + return `${path || 'value'}: expected an object, got ${JSON.stringify(actual)}` + } + for (const [k, v] of Object.entries(expected)) { + const m = subsetMismatch(actual[k], v, path ? `${path}.${k}` : k) + if (m) return m + } + return null +} + +function headerLookup(headers) { + const out = {} + for (const [k, v] of Object.entries(headers ?? {})) out[k.toLowerCase()] = v + return out +} + +/** + * Run one example (direction site-to-service) against a driver. Throws ContractError on the first mismatch. + * Returns { request, response, vars } for further checks by the caller. + */ +export async function runExample(example, driver) { + const id = example.id + if (example.direction === 'service-to-site') { + throw new ContractError(id, 'this example describes the call-back; use runCallbackExample()') + } + const given = example.given ?? {} + const vars = (await driver.arrange(given, example)) ?? {} + + const headers = expand(example.request.headers ?? {}, given.token === 'none' ? { ...vars, token: '' } : vars, id) + if (given.token === 'none') delete headers.authorization + const body = example.request.body === undefined ? undefined : expand(example.request.body, vars, id) + + if (example.request.schema && driver.validate) { + const problems = driver.validate(example.request.schema, body) + if (problems.length) throw new ContractError(id, `the example's request does not match ${example.request.schema}: ${problems.join('; ')}`) + } + + const request = { method: example.request.method, path: example.request.path, headers, body } + const response = await driver.request(request) + + if (response.status !== example.response.status) { + throw new ContractError(id, `status: expected ${example.response.status}, got ${response.status} ${JSON.stringify(response.body)}`) + } + if (example.response.schema && driver.validate) { + const problems = driver.validate(example.response.schema, response.body) + if (problems.length) throw new ContractError(id, `the answer does not match ${example.response.schema}: ${problems.join('; ')}`) + } + if (example.response.body !== undefined) { + const m = subsetMismatch(response.body, expand(example.response.body, vars, id)) + if (m) throw new ContractError(id, `body: ${m}`) + } + if (response.body && response.body.ok === false) { + const got = headerLookup(response.headers) + if (typeof response.body.retryAfter === 'number' && got['retry-after'] !== undefined && String(got['retry-after']) !== String(response.body.retryAfter)) { + throw new ContractError(id, `Retry-After header (${got['retry-after']}) differs from retryAfter (${response.body.retryAfter})`) + } + if (example.client && typeof example.client.retry === 'boolean' && response.body.retryable !== example.client.retry) { + throw new ContractError(id, `retryable: expected ${example.client.retry}, got ${response.body.retryable}`) + } + } + const cors = headerLookup(response.headers)['access-control-allow-origin'] + if (cors !== undefined) throw new ContractError(id, 'the service must not send CORS headers') + + if (example.then && driver.mails) { + const mails = await driver.mails() + if (typeof example.then.mails === 'number' && mails.length !== example.then.mails) { + throw new ContractError(id, `mails handed to the back end: expected ${example.then.mails}, got ${mails.length}`) + } + if (example.then.mail) { + const m = subsetMismatch(mails[0], expand(example.then.mail, vars, id), 'mail') + if (m) throw new ContractError(id, m) + } + } + return { request, response, vars } +} + +/** + * Run a call-back example against a site's confirm endpoint. + * `site.prepare(body)` makes the site hold (or not hold) the nonce; `site.confirm(request)` calls the endpoint. + */ +export async function runCallbackExample(example, site) { + const id = example.id + if (example.direction !== 'service-to-site') throw new ContractError(id, 'not a call-back example') + const holds = example.response.status === 200 + await site.prepare({ ...example.request.body, held: holds }) + const response = await site.confirm({ ...example.request }) + if (response.status !== example.response.status) { + throw new ContractError(id, `status: expected ${example.response.status}, got ${response.status}`) + } + if (holds) { + const expected = await confirmationFor(example.request.body.nonce, example.request.body.token) + if (!response.body || response.body.confirmation !== expected) { + throw new ContractError(id, 'the confirmation is not hex SHA-256 of nonce + "." + token') + } + } + return response +} diff --git a/contracts/mail-relay/schema.json b/contracts/mail-relay/schema.json new file mode 100644 index 0000000..1ad55a8 --- /dev/null +++ b/contracts/mail-relay/schema.json @@ -0,0 +1,623 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "https://webservices.intecion.net/mail/contract/v1/schema.json", + "title": "Intecion Notifications Webservice — wire contract v1", + "description": "Bodies of every request and answer. Requests are closed (an unknown field is refused); answers are open (a client ignores fields it does not know).", + "$defs": { + "Host": { + "description": "A public DNS name, lowercase, punycode for international names. No scheme, port, path or address literal.", + "type": "string", + "minLength": 4, + "maxLength": 253, + "pattern": "^(?=.{4,253}$)([a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?\\.)+[a-z]([a-z0-9-]{0,61}[a-z0-9])$" + }, + "Product": { + "description": "The client product. The list is the service's.", + "type": "string", + "enum": [ + "iapl", + "iawl" + ] + }, + "ProductVersion": { + "type": "string", + "minLength": 1, + "maxLength": 32, + "pattern": "^[0-9A-Za-z][0-9A-Za-z.+_-]*$" + }, + "Kind": { + "type": "string", + "enum": [ + "form-notification", + "form-confirmation", + "account", + "security-alert", + "system", + "test" + ] + }, + "SiteState": { + "type": "string", + "enum": [ + "pending", + "active", + "suspended" + ] + }, + "Address": { + "description": "A bare e-mail address. No display name, no angle brackets, no comment.", + "type": "string", + "minLength": 6, + "maxLength": 254, + "pattern": "^[A-Za-z0-9!#$%&'*+/=?^_`{|}~-]+(\\.[A-Za-z0-9!#$%&'*+/=?^_`{|}~-]+)*@([A-Za-z0-9]([A-Za-z0-9-]{0,61}[A-Za-z0-9])?\\.)+[A-Za-z]([A-Za-z0-9-]{0,61}[A-Za-z0-9])$" + }, + "Nonce": { + "type": "string", + "pattern": "^[A-Za-z0-9_-]{32,128}$" + }, + "Token": { + "description": "Opaque. Never logged, never shown.", + "type": "string", + "pattern": "^ims_[A-Za-z0-9_-]{43}$" + }, + "Window": { + "type": "object", + "required": [ + "limit", + "remaining" + ], + "properties": { + "limit": { + "type": "integer", + "minimum": 0 + }, + "remaining": { + "type": "integer", + "minimum": 0 + } + } + }, + "Quota": { + "type": "object", + "required": [ + "hour", + "day" + ], + "properties": { + "hour": { + "$ref": "#/$defs/Window" + }, + "day": { + "$ref": "#/$defs/Window" + } + } + }, + "EnrolRequest": { + "type": "object", + "additionalProperties": false, + "required": [ + "host", + "nonce", + "product", + "productVersion" + ], + "properties": { + "host": { + "$ref": "#/$defs/Host" + }, + "nonce": { + "$ref": "#/$defs/Nonce" + }, + "product": { + "$ref": "#/$defs/Product" + }, + "productVersion": { + "$ref": "#/$defs/ProductVersion" + } + }, + "description": "No call-back path: the service calls the path fixed for the product (README §2)." + }, + "EnrolResponse": { + "description": "Never carries the token: it went to the site's confirm endpoint.", + "type": "object", + "required": [ + "ok", + "state" + ], + "properties": { + "ok": { + "const": true + }, + "state": { + "$ref": "#/$defs/SiteState" + } + }, + "not": { + "required": [ + "token" + ] + } + }, + "CallbackRequest": { + "description": "Sent BY the service TO the site's confirm endpoint: POST https://.", + "type": "object", + "additionalProperties": false, + "required": [ + "nonce", + "token", + "state" + ], + "properties": { + "nonce": { + "$ref": "#/$defs/Nonce" + }, + "token": { + "$ref": "#/$defs/Token" + }, + "state": { + "$ref": "#/$defs/SiteState" + } + } + }, + "CallbackResponse": { + "description": "The site's answer: status 200, a body of at most 1024 bytes that is this JSON object and nothing else, within 8 seconds. confirmation = lowercase hex SHA-256 of the UTF-8 text nonce + \".\" + token.", + "type": "object", + "required": [ + "confirmation" + ], + "properties": { + "confirmation": { + "type": "string", + "pattern": "^[0-9a-f]{64}$" + } + } + }, + "Attachment": { + "type": "object", + "additionalProperties": false, + "required": [ + "filename", + "contentType", + "content" + ], + "properties": { + "filename": { + "type": "string", + "minLength": 1, + "maxLength": 255 + }, + "contentType": { + "type": "string", + "maxLength": 127, + "pattern": "^[A-Za-z0-9][A-Za-z0-9!#$&^_.+-]*/[A-Za-z0-9][A-Za-z0-9!#$&^_.+-]*$" + }, + "content": { + "description": "Base64, standard alphabet, no line breaks, padded: the length is a multiple of four. The pattern states the alphabet only — a pattern that also stated the length would overflow regular-expression engines on a 10 MB file; the service checks the length.", + "type": "string", + "minLength": 4, + "pattern": "^[A-Za-z0-9+/]+={0,2}$" + } + } + }, + "SendRequest": { + "type": "object", + "additionalProperties": false, + "required": [ + "product", + "productVersion", + "kind", + "subject" + ], + "properties": { + "product": { + "$ref": "#/$defs/Product" + }, + "productVersion": { + "$ref": "#/$defs/ProductVersion" + }, + "kind": { + "$ref": "#/$defs/Kind" + }, + "to": { + "description": "Bare addresses. The number over to, cc and bcc together is limited per site: limits.recipientsPerMessage in /v1/status (the schema only states the service's upper bound).", + "type": "array", + "items": { + "$ref": "#/$defs/Address" + }, + "maxItems": 50 + }, + "cc": { + "description": "Bare addresses. The number over to, cc and bcc together is limited per site: limits.recipientsPerMessage in /v1/status (the schema only states the service's upper bound).", + "type": "array", + "items": { + "$ref": "#/$defs/Address" + }, + "maxItems": 50 + }, + "bcc": { + "description": "Bare addresses. The number over to, cc and bcc together is limited per site: limits.recipientsPerMessage in /v1/status (the schema only states the service's upper bound).", + "type": "array", + "items": { + "$ref": "#/$defs/Address" + }, + "maxItems": 50 + }, + "replyTo": { + "$ref": "#/$defs/Address" + }, + "senderName": { + "description": "At most 256 characters (Unicode code points).", + "type": "string", + "maxLength": 256 + }, + "subject": { + "description": "1 to 300 characters (code points). No line breaks, control characters or characters that hide or reorder text (README §3 has the exact rule and the three exceptions); must not start with the service's name in brackets.", + "type": "string", + "minLength": 1, + "maxLength": 300 + }, + "text": { + "type": "string", + "minLength": 1 + }, + "html": { + "type": "string", + "minLength": 1 + }, + "attachments": { + "type": "array", + "items": { + "$ref": "#/$defs/Attachment" + }, + "maxItems": 20 + } + }, + "anyOf": [ + { + "required": [ + "text" + ] + }, + { + "required": [ + "html" + ] + } + ], + "allOf": [ + { + "if": { + "properties": { + "kind": { + "const": "security-alert" + } + }, + "required": [ + "kind" + ] + }, + "else": { + "required": [ + "to" + ], + "properties": { + "to": { + "minItems": 1 + } + } + } + } + ] + }, + "SendResponse": { + "type": "object", + "required": [ + "ok", + "id", + "replayed", + "senderName", + "warnings", + "quota" + ], + "properties": { + "ok": { + "const": true + }, + "id": { + "description": "The service's id of this message in its log.", + "type": "string", + "minLength": 1 + }, + "messageId": { + "description": "The back end's id, when it gave one.", + "type": "string" + }, + "replayed": { + "description": "true when this Idempotency-Key was already sent and no second mail went out.", + "type": "boolean" + }, + "senderName": { + "description": "The name the mail left under.", + "type": "string" + }, + "warnings": { + "description": "Known today: sender-name-replaced. A client ignores a warning it does not know.", + "type": "array", + "items": { + "type": "string" + } + }, + "quota": { + "description": "What is left for a message of the kind just sent.", + "$ref": "#/$defs/Quota" + } + } + }, + "StatusResponse": { + "type": "object", + "required": [ + "ok", + "state", + "host", + "product", + "service", + "sender", + "limits", + "quota", + "kinds", + "token" + ], + "properties": { + "ok": { + "const": true + }, + "state": { + "$ref": "#/$defs/SiteState" + }, + "host": { + "$ref": "#/$defs/Host" + }, + "product": { + "$ref": "#/$defs/Product" + }, + "service": { + "type": "object", + "required": [ + "version", + "contract" + ], + "properties": { + "name": { + "description": "The service's name, for a panel to show.", + "type": "string" + }, + "version": { + "type": "string" + }, + "contract": { + "type": "string", + "pattern": "^[0-9]+\\.[0-9]+\\.[0-9]+$" + } + } + }, + "sender": { + "type": "object", + "required": [ + "address" + ], + "properties": { + "address": { + "$ref": "#/$defs/Address" + } + } + }, + "limits": { + "type": "object", + "required": [ + "messagesPerHour", + "messagesPerDay", + "recipientsPerMessage", + "perRecipientPerDay", + "newRecipientsPerDay", + "maxBodyBytes", + "maxAttachmentBytes", + "maxAttachments" + ], + "properties": { + "messagesPerHour": { + "type": "integer", + "minimum": 0 + }, + "messagesPerDay": { + "type": "integer", + "minimum": 0 + }, + "recipientsPerMessage": { + "type": "integer", + "minimum": 1 + }, + "perRecipientPerDay": { + "type": "integer", + "minimum": 0 + }, + "newRecipientsPerDay": { + "type": "integer", + "minimum": 0 + }, + "maxBodyBytes": { + "type": "integer", + "minimum": 0 + }, + "maxAttachmentBytes": { + "type": "integer", + "minimum": 0 + }, + "maxAttachments": { + "type": "integer", + "minimum": 0 + }, + "serverAddresses": { + "description": "Server addresses the site may send from at a time.", + "type": "integer", + "minimum": 1 + }, + "securityAlertsPerDay": { + "description": "Security alerts a day: a budget of their own, outside the hour and day limits.", + "type": "integer", + "minimum": 0 + } + } + }, + "quota": { + "$ref": "#/$defs/Quota" + }, + "kinds": { + "type": "array", + "items": { + "type": "string" + } + }, + "token": { + "type": "object", + "required": [ + "issuedAt", + "rotateAfter" + ], + "properties": { + "issuedAt": { + "type": "string", + "format": "date-time" + }, + "rotateAfter": { + "type": "string", + "format": "date-time" + } + } + }, + "senderName": { + "description": "The name the last mail left under, when there was one.", + "type": "string" + } + } + }, + "RotateResponse": { + "type": "object", + "required": [ + "ok", + "token", + "previousValidUntil" + ], + "properties": { + "ok": { + "const": true + }, + "token": { + "$ref": "#/$defs/Token" + }, + "previousValidUntil": { + "type": "string", + "format": "date-time" + } + } + }, + "RevokeResponse": { + "type": "object", + "required": [ + "ok" + ], + "properties": { + "ok": { + "const": true + } + } + }, + "HealthResponse": { + "description": "No detail on purpose — also when it says no: the one answer that is not an Error.", + "type": "object", + "additionalProperties": false, + "required": [ + "ok" + ], + "properties": { + "ok": { + "type": "boolean" + } + } + }, + "ErrorCode": { + "type": "string", + "enum": [ + "invalid-request", + "invalid-token", + "reverify", + "site-pending", + "site-suspended", + "host-not-allowed", + "enrolment-closed", + "enrolment-in-progress", + "callback-failed", + "browser-not-allowed", + "not-found", + "method-not-allowed", + "unsupported-media-type", + "idempotency-conflict", + "in-progress", + "already-rotated", + "too-large", + "too-many-recipients", + "attachment-refused", + "recipient-suppressed", + "rate-limited", + "quota-exceeded", + "backend-failed", + "unavailable", + "internal" + ], + "description": "The codes the service answers with today. The list grows with minor versions; that is why Error.code is an open string." + }, + "Error": { + "type": "object", + "required": [ + "ok", + "code", + "message", + "retryable" + ], + "properties": { + "ok": { + "const": false + }, + "code": { + "description": "One of ErrorCode today. A client that meets a code it does not know acts on `retryable`.", + "type": "string", + "minLength": 1 + }, + "message": { + "description": "For a log or an administrator. English. Never shown to a visitor.", + "type": "string" + }, + "retryable": { + "description": "true: the same request, with the same Idempotency-Key, may be sent again after a short wait.", + "type": "boolean" + }, + "retryAfter": { + "description": "Seconds.", + "type": "integer", + "minimum": 0 + }, + "field": { + "description": "With invalid-request: the field at fault. With attachment-refused: which file, as attachments[n] (n from 0).", + "type": "string" + }, + "limit": { + "description": "With quota-exceeded: hour, day, alerts, recipient, new-recipients or service. With too-large: request, body or attachments.", + "type": "string" + }, + "reason": { + "description": "With callback-failed: unreachable, timeout, redirect, status or confirmation.", + "type": "string" + } + } + } + } +} diff --git a/src/exports/admin.ts b/src/exports/admin.ts index 4bff306..4d7f0ef 100644 --- a/src/exports/admin.ts +++ b/src/exports/admin.ts @@ -5,6 +5,7 @@ * banners). Separate export so Payload's importMap can resolve them by a stable path, and so * nothing importing @payloadcms/ui ends up in /client — that entry ships to every site visitor. */ +export { MailRelayStatus } from '../globals/SiteIntegrations/components/MailRelayStatus.js' export { MaskedField } from '../globals/SiteIntegrations/components/MaskedField.js' export { TestEmailButton } from '../globals/SiteIntegrations/components/TestEmailButton.js' export { DocumentTitle } from '../modules/admin-i18n/DocumentTitle.js' diff --git a/src/globals/SiteIntegrations/components/MailRelayStatus.tsx b/src/globals/SiteIntegrations/components/MailRelayStatus.tsx new file mode 100644 index 0000000..c21308b --- /dev/null +++ b/src/globals/SiteIntegrations/components/MailRelayStatus.tsx @@ -0,0 +1,163 @@ +'use client' + +import { useConfig, useTranslation } from '@payloadcms/ui' +import { useCallback, useEffect, useState } from 'react' + +import { iaplT } from '../../../modules/admin-i18n/t.js' +import { RELAY_CONNECT_PATH, RELAY_DISCONNECT_PATH, RELAY_STATUS_PATH } from '../../../modules/email/relay/constants.js' + +type Window = { limit: number; remaining: number } +type State = { + error?: string + message?: string + ok?: boolean + refusalText?: string + relay?: { + connected?: boolean + disconnected?: boolean + nameReplaced?: { asked: string; used: string } + quota?: { day?: Window; hour?: Window } + senderAddress?: string + state?: 'active' | 'pending' | 'suspended' + tokenSource?: string + } | null + replyAddress?: null | string + transport?: 'graph' | 'none' | 'relay' | 'smtp' +} + +const box = { border: '1px solid var(--theme-elevation-150)', borderRadius: 4, marginBottom: '1.5rem', padding: '0.9rem 1rem' } as const +const line = { margin: '0.35rem 0 0' } as const +const warn = { ...line, color: 'var(--theme-warning-600, #b45309)' } as const + +/** + * Admin UI: the state block at the top of Site integrations → E-mail sending. Says which transport is + * in effect (the Intecion mail service, the site's SMTP server, Microsoft Graph), and for the mail + * service: the state, the address mail leaves from, where replies go, what is left of the limits, and + * a sender name the service did not accept. "Check now" asks the service; "Connect again" and + * "Disconnect" act on the site's connection. No token is ever shown or sent to this component. + * + * Assigned via a `ui` field's admin.components.Field. Texts: `mailRelay*` keys. + */ +export const MailRelayStatus = () => { + const { t } = useTranslation() + const { config } = useConfig() + const api = config.routes?.api ?? '/api' + const text = (key: Parameters[1], vars?: Record) => iaplT(t as never, key, vars) + const [state, setState] = useState(null) + const [busy, setBusy] = useState(false) + const [note, setNote] = useState<{ kind: 'error' | 'ok'; msg: string } | null>(null) + const [token, setToken] = useState('') + const [showToken, setShowToken] = useState(false) + + const call = useCallback( + async (path: string, init?: RequestInit, announce = false) => { + setBusy(true) + try { + const res = await fetch(`${api}${path}`, { credentials: 'include', ...init }) + const data = (await res.json()) as State + if (data.transport) {setState(data)} + if (!data.ok) {setNote({ kind: 'error', msg: data.error ?? iaplT(t as never, 'mailRelayLoadFailed') })} + else if (announce && data.message) {setNote({ kind: 'ok', msg: data.message })} + else {setNote(null)} + } catch { + setNote({ kind: 'error', msg: iaplT(t as never, 'mailRelayLoadFailed') }) + } finally { + setBusy(false) + } + }, + [api, t], + ) + + useEffect(() => { + void call(RELAY_STATUS_PATH) + }, [call]) + + const post = (path: string, body?: object) => + call(path, { body: body ? JSON.stringify(body) : undefined, headers: body ? { 'Content-Type': 'application/json' } : undefined, method: 'POST' }, true) + + if (!state?.transport) { + return note ?
{note.msg}
: null + } + const relay = state.relay + const onRelay = state.transport === 'relay' + const relayState = !relay ? '' : relay.disconnected ? text('mailRelayStateDisconnected') + : !relay.connected ? (state.refusalText ?? 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))) + + return ( +
+ {text('mailRelayHeading')} +

+ {state.transport === 'relay' ? text('mailRelayTransportRelay', { address: relay?.senderAddress ?? '' }) + : state.transport === 'smtp' ? text('mailRelayTransportSmtp') + : state.transport === 'graph' ? text('mailRelayTransportGraph') + : text(relay ? 'mailRelayTransportNone' : 'mailRelayOff')} +

+ {onRelay && relay ? ( + <> +

{relayState}

+

{state.replyAddress ? text('mailRelayRepliesTo', { address: state.replyAddress }) : text('mailRelayNoReplyAddress')}

+ {relay.nameReplaced ?

{text('mailRelayNameReplaced', { asked: relay.nameReplaced.asked, used: relay.nameReplaced.used })}

: null} + {relay.quota?.hour && relay.quota.day ? ( +

{text('mailRelayQuota', { day: relay.quota.day.remaining, hour: relay.quota.hour.remaining })}

+ ) : null} + {relay.tokenSource === 'option' ? null : ( +
+ + + {relay.connected ? ( + + ) : null} + +
+ )} + {showToken ? ( +
+

{text('mailRelayTokenHint')}

+
+ setToken(e.target.value)} style={{ flex: 1, minWidth: '220px' }} type="password" value={token} /> + +
+
+ ) : null} + + ) : null} + {note ? ( +

+ {note.msg} +

+ ) : null} +
+ ) +} + +export default MailRelayStatus diff --git a/src/globals/SiteIntegrations/fields/smtp.ts b/src/globals/SiteIntegrations/fields/smtp.ts index b8b5a57..425633d 100644 --- a/src/globals/SiteIntegrations/fields/smtp.ts +++ b/src/globals/SiteIntegrations/fields/smtp.ts @@ -3,7 +3,9 @@ import type { Condition, Field } from 'payload' import { buildIntegrationStatusBanner, buildIntegrationStatusField } from '../../../modules/integrations/status.js' /** - * E-mail sending settings (SMTP, or Microsoft Graph set up on the server). + * E-mail sending settings. No field is needed for mail to work: a site with no SMTP server here + * sends through the Intecion Notifications Webservice (modules/email/relay). The SMTP fields are + * for a client who wants its own mail server; Microsoft Graph (set up on the server) is deprecated. * * Protected at the global level (SiteIntegrations requires an authenticated * user), so all fields — including the password — stay editable in the admin @@ -13,7 +15,16 @@ import { buildIntegrationStatusBanner, buildIntegrationStatusField } from '../.. // SMTP fields only matter with the SMTP transport — hidden while Graph is selected. const usesSmtp: Condition = (_, siblingData) => siblingData?.emailTransport !== 'graph' -export const smtpFields: Field[] = [ +/** + * The fields of the "E-mail sending" tab. `relay: false` (the project switched the Intecion mail + * service off): no state block, and the wording of 1.16 — SMTP is then the way to send. + * No stored field differs between the two: labels, descriptions and one `ui` block only. + */ +export const buildSmtpFields = ({ relay = true }: { relay?: boolean } = {}): Field[] => [ + // Which transport is in effect, and the site's state with the Intecion mail service. + ...(relay + ? [{ name: 'mailRelayStatus', type: 'ui' as const, admin: { components: { Field: '@intecion/ipal-kit/admin#MailRelayStatus' } } }] + : []), // Status written by mailAdapter on every send (throttled) — banner on this tab. buildIntegrationStatusBanner( 'emailStatus', @@ -24,10 +35,15 @@ export const smtpFields: Field[] = [ name: 'emailTransport', type: 'select', admin: { - description: { - en: 'Microsoft Graph works only when your administrator has set it up on the server.', - pl: 'Microsoft Graph działa tylko wtedy, gdy administrator skonfiguruje go na serwerze.', - }, + description: relay + ? { + en: 'Automatic: e-mails go through your SMTP server when one is filled in below, otherwise through the Intecion mail service. Microsoft Graph works only when your administrator has set it up on the server; it will be removed in version 2.0.', + pl: 'Automatycznie: e-maile idą przez Twój serwer SMTP, jeśli jest uzupełniony poniżej, a w przeciwnym razie przez usługę pocztową Intecion. Microsoft Graph działa tylko wtedy, gdy administrator skonfiguruje go na serwerze; zostanie usunięty w wersji 2.0.', + } + : { + en: 'Microsoft Graph works only when your administrator has set it up on the server. It will be removed in version 2.0.', + pl: 'Microsoft Graph działa tylko wtedy, gdy administrator skonfiguruje go na serwerze. Zostanie usunięty w wersji 2.0.', + }, // The Graph option only makes sense when agency credentials exist in env. // We can't read process.env in the admin UI directly, so a client project // that hasn't set up Graph should filter this option via integrationsFields @@ -37,8 +53,9 @@ export const smtpFields: Field[] = [ defaultValue: 'smtp', label: { en: 'Sending method', pl: 'Sposób wysyłki' }, options: [ - { label: { en: 'SMTP server', pl: 'Serwer SMTP' }, value: 'smtp' }, - { label: { en: 'Microsoft Graph (Exchange)', pl: 'Microsoft Graph (Exchange)' }, value: 'graph' }, + // Labels only: the two stored values stay (a new value would change the Postgres enum). + { label: relay ? { en: 'Automatic (Intecion mail service, or your SMTP server)', pl: 'Automatycznie (usługa pocztowa Intecion albo Twój serwer SMTP)' } : { en: 'SMTP server', pl: 'Serwer SMTP' }, value: 'smtp' }, + { label: { en: 'Microsoft Graph (deprecated)', pl: 'Microsoft Graph (wycofywany)' }, value: 'graph' }, ], }, { @@ -48,10 +65,15 @@ export const smtpFields: Field[] = [ name: 'smtpFromAddress', type: 'email', admin: { - description: { - en: 'E-mails are sent from this address; with Microsoft Graph, replies go to it.', - pl: 'Z tego adresu wychodzą e-maile; przy Microsoft Graph trafiają na niego odpowiedzi.', - }, + description: relay + ? { + en: 'With your SMTP server, e-mails are sent from this address. With the Intecion mail service (and Microsoft Graph), replies go to it.', + pl: 'Przy Twoim serwerze SMTP z tego adresu wychodzą e-maile. Przy usłudze pocztowej Intecion (i Microsoft Graph) trafiają na niego odpowiedzi.', + } + : { + en: 'E-mails are sent from this address; with Microsoft Graph, replies go to it.', + pl: 'Z tego adresu wychodzą e-maile; przy Microsoft Graph trafiają na niego odpowiedzi.', + }, placeholder: 'info@example.com', width: '50%', }, @@ -61,10 +83,15 @@ export const smtpFields: Field[] = [ name: 'smtpFromName', type: 'text', admin: { - description: { - en: 'The name recipients see, e.g. the company name.', - pl: 'Nazwa widoczna dla odbiorcy, np. nazwa firmy.', - }, + description: relay + ? { + en: 'The name recipients see, e.g. the company name. Empty: the site name.', + pl: 'Nazwa widoczna dla odbiorcy, np. nazwa firmy. Puste: nazwa witryny.', + } + : { + en: 'The name recipients see, e.g. the company name.', + pl: 'Nazwa widoczna dla odbiorcy, np. nazwa firmy.', + }, width: '50%', }, label: { en: 'Sender name', pl: 'Nazwa nadawcy' }, @@ -78,8 +105,19 @@ export const smtpFields: Field[] = [ { name: 'smtpHost', type: 'text', - admin: { placeholder: 'smtp.example.com', width: '70%' }, - label: { en: 'Server', pl: 'Serwer' }, + admin: { + ...(relay + ? { + description: { + en: 'Fill in only when the site should send through your own mail server. Leave empty to use the Intecion mail service.', + pl: 'Uzupełnij tylko wtedy, gdy witryna ma wysyłać przez Twój własny serwer pocztowy. Zostaw puste, aby korzystać z usługi pocztowej Intecion.', + }, + } + : {}), + placeholder: 'smtp.example.com', + width: '70%', + }, + label: relay ? { en: 'Own SMTP server (optional)', pl: 'Własny serwer SMTP (opcjonalnie)' } : { en: 'Server', pl: 'Serwer' }, }, { name: 'smtpPort', @@ -122,3 +160,6 @@ export const smtpFields: Field[] = [ }, buildIntegrationStatusField('emailStatus'), ] + +/** The fields with the Intecion mail service enabled (the default). */ +export const smtpFields: Field[] = buildSmtpFields() diff --git a/src/globals/SiteIntegrations/index.ts b/src/globals/SiteIntegrations/index.ts index 48714f1..97a814e 100644 --- a/src/globals/SiteIntegrations/index.ts +++ b/src/globals/SiteIntegrations/index.ts @@ -4,12 +4,17 @@ import { userMeetsRole } from '../../modules/access/index.js' import { INTEGRATION_SECRET_FIELDS, maskSecretsOnRestore, SMTP_PASSWORD_BOUND_TO, writeOnlySecrets } from '../../modules/secrets/writeOnly.js' import { indexNowFields } from '../../modules/seo/indexNow.js' import { analyticsFields } from './fields/analytics.js' -import { smtpFields } from './fields/smtp.js' +import { buildSmtpFields } from './fields/smtp.js' import { turnstileFields } from './fields/turnstile.js' type BuildSiteIntegrationsArgs = { /** Extra fields injected by the client project */ additionalFields?: Field[] + /** + * The Intecion mail service is enabled in the project (`mail.relay` is not `false`): the e-mail + * tab shows its state block and says that SMTP is optional. Default true. + */ + mailRelay?: boolean /** * A save through access control that changes the SMTP server, port or user name must send the * password again (or remove it), whatever the transport. Default true; needs write-only @@ -38,6 +43,7 @@ type BuildSiteIntegrationsArgs = { */ export function buildSiteIntegrations({ additionalFields, + mailRelay = true, reenterSecretOnChange = true, writeOnlySecrets: writeOnly = true, }: BuildSiteIntegrationsArgs = {}): GlobalConfig { @@ -68,7 +74,7 @@ export function buildSiteIntegrations({ fields: secret(turnstileFields), label: { en: 'Spam protection', pl: 'Ochrona przed spamem' }, }, - { fields: secret(smtpFields), label: { en: 'E-mail sending', pl: 'Wysyłka e-mail' } }, + { fields: secret(buildSmtpFields({ relay: mailRelay })), label: { en: 'E-mail sending', pl: 'Wysyłka e-mail' } }, { fields: indexNowFields, label: { en: 'IndexNow', pl: 'IndexNow' } }, ...(additionalFields?.length ? [{ fields: additionalFields, label: { en: 'More', pl: 'Więcej' } }] diff --git a/src/index.ts b/src/index.ts index eff798b..271f977 100644 --- a/src/index.ts +++ b/src/index.ts @@ -210,17 +210,77 @@ export type { SearchResult } from './modules/content/index.js' export { mailAttachmentLimit } from './modules/email/attachmentLimit.js' export { graphAdapter } from './modules/email/graphAdapter.js' export type { GraphAdapterArgs } from './modules/email/graphAdapter.js' -export { mailAdapter } from './modules/email/mailAdapter.js' -export type { MailAdapterArgs } from './modules/email/mailAdapter.js' +export { GRAPH_DEPRECATION_NOTICE, mailAdapter, resolveMailTransport } from './modules/email/mailAdapter.js' +export type { MailAdapterArgs, MailTransport } from './modules/email/mailAdapter.js' // Imported straight from the file, NOT from ./modules/email/index.js — that // barrel re-exports sendEmail, which imports 'server-only' and would crash when // Payload loads the config (or runs generate:importmap) as a plain Node script. export { panelSmtpAdapter } from './modules/email/panelSmtpAdapter.js' export type { PanelSmtpAdapterArgs } from './modules/email/panelSmtpAdapter.js' +// The Intecion Notifications Webservice (docs/email.md): the transport of a site with no SMTP server. +// Every piece is exported, so a project can use the transport alone, enrol from a script, mark its own +// mail, build its own panel, or test against the fake service. +export { createFakeRelay } from './modules/email/relay/fake.js' +export type { FakeRelay, FakeRelayLimits, FakeRelayMail, FakeRelayOptions } from './modules/email/relay/fake.js' +export { + bareAddress, + bareAddresses, + buildRelayMessage, + cleanSubject, + disconnectRelay, + enrolRelay, + getRelayStatus, + isPublicHost, + MAIL_KIND, + MAIL_KINDS, + mailKindOf, + markNextMail, + RELAY_BASE_URL, + RELAY_CONFIRM_PATH, + RELAY_CONTRACT_VERSION, + RELAY_DEFAULTS, + RELAY_KV_KEY, + RELAY_PRODUCT, + RELAY_SENDER_ADDRESS, + RELAY_SERVICE_NAME, + RELAY_STATUS_CODES, + relayAdapter, + relayAttachmentLimit, + relayConfirmEndpoint, + relayHost, + relayRequest, + relaySenderName, + relayStatusFor, + resolveRelayOptions, + rotateRelayToken, + runWithMailKind, + sendThroughRelay, + setRelayToken, + withMailKind, +} from './modules/email/relay/index.js' +export type { + BuildRelayMessageArgs, + BuiltRelayMessage, + EnrolResult, + MailKind, + RelayAdapterArgs, + RelayAnswer, + RelayCall, + RelayOptions, + RelayRefusal, + RelaySendContext, + RelaySendRequest, + RelaySendResult, + RelayStatus, + RelayStatusCode, +} from './modules/email/relay/index.js' +export { mailPanelState, relayPanelEndpoints } from './modules/email/relay/panel.js' +export type { MailPanelState } from './modules/email/relay/panel.js' // Boot-time environment validation (fail fast on misconfigured deploys). export { assertEnv, checkDatabaseName, databaseNameFromUri, databaseNamesFor, iaplEnvRules, ipalEnvRules, legacyEnvName, readEnv } from './modules/env/index.js' export type { AssertEnvOptions, EnvKind, EnvRule, IaplEnvFeatures, IpalEnvFeatures } from './modules/env/index.js' export type { FormAttachmentsOption, FormFileScanInput, FormFileScanResult, FormSubmitEndpointOptions } from './modules/forms/attachments/config.js' +export { buildFormMailKindHook } from './modules/forms/attachments/delivery.js' export { buildFileBlock, fileBlock } from './modules/forms/attachments/fileBlock.js' export { FORM_FILE_TYPES, formatFileSize, RISKY_FILE_EXTENSIONS } from './modules/forms/attachments/fileTypes.js' export type { FormFileDetect, FormFileType } from './modules/forms/attachments/fileTypes.js' @@ -468,4 +528,4 @@ export type { IaplTokenName, IpalTokenName, TokensInput } from './modules/tokens export { getTurnstileConfig, TURNSTILE_SECRET_ENV, turnstileSecretFromEnv } from './modules/turnstile/config.js' export type { TurnstileConfig } from './modules/turnstile/config.js' export { iapl, ipalKit } from './plugin.js' -export type { IaplOptions, IpalOptions, ThemeOptions } from './types.js' +export type { IaplOptions, IpalOptions, MailOptions, ThemeOptions } from './types.js' diff --git a/src/modules/admin-i18n/texts/integrations.ts b/src/modules/admin-i18n/texts/integrations.ts index 103ba5a..9eb0382 100644 --- a/src/modules/admin-i18n/texts/integrations.ts +++ b/src/modules/admin-i18n/texts/integrations.ts @@ -9,6 +9,43 @@ export const integrationsTexts = defineTexts({ alertsLink: 'Go to Site integrations', alertsUnknownError: 'Unknown error.', + // 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 Intecion mail service.', + mailRelayConnectFailed: 'The site could not be connected: {{reason}}', + mailRelayDisconnect: 'Disconnect', + mailRelayDisconnectConfirm: 'Disconnect this site from the Intecion 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 Intecion mail service.', + 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 mail service 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 Intecion mail service is switched off for this project.', + mailRelayQuota: 'Left this hour: {{hour}}. Left today: {{day}}.', + mailRelayRefusedCallback: 'The mail service could not confirm this site at {{url}} ({{reason}}). The site must answer there from the internet, without a redirect. If the site serves its API at another address, ask Intecion to set this site\'s confirm address.', + mailRelayRefusedClosed: 'The mail service does not take new sites at the moment. Contact Intecion.', + mailRelayRefusedHost: 'This site has no public address the mail service could call back ({{host}}). It works once the site runs on its domain.', + mailRelayRefusedNoHost: 'The site does not know its own address. An administrator must set serverURL in the Payload config.', + mailRelayRefusedOther: 'The mail service answered: {{message}}', + mailRelayRepliesTo: 'Replies go to {{address}}.', + mailRelayStateActive: 'Connected to the Intecion mail service.', + 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: 'Waiting for approval by Intecion. E-mails are not sent yet.', + mailRelayStateSuspended: 'Intecion has stopped e-mail sending for this site. Contact Intecion.', + mailRelayToken: 'Token issued by Intecion', + mailRelayTokenHint: 'Only for a site the mail service cannot call back. The token is stored and never shown again.', + mailRelayTokenInvalid: 'This is not a token of the mail service.', + mailRelayTokenSave: 'Save the token', + mailRelayTransportGraph: 'E-mails go through Microsoft Graph. This method is deprecated and 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 Intecion mail service, from {{address}}.', + mailRelayTransportSmtp: 'E-mails go through your SMTP server.', + mailRelayWorking: 'Working…', + // Masked secret field maskedHide: 'Hide', maskedKeep: 'Keep the stored value', @@ -37,6 +74,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 Intecion mail service does not carry this type of file. The e-mail was not sent.', + statusEmailRelayDisconnected: 'The site is disconnected from the Intecion mail service, so e-mails are not sent. Connect again, or fill in an SMTP server.', + statusEmailRelayError: 'The Intecion mail service refused the e-mail. Tell your administrator.', + statusEmailRelayNotConfirmed: 'The Intecion mail service did not confirm the last e-mail. It may have been sent.', + statusEmailRelayPending: 'The site is waiting for approval by Intecion. E-mails are not sent yet.', + statusEmailRelayQuota: 'The site reached a sending limit of the Intecion 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. Contact Intecion.', + statusEmailRelayRefused: 'The Intecion mail service did not connect this site. See the state above, or fill in an SMTP server.', + statusEmailRelaySuspended: 'Intecion has stopped e-mail sending for this site. Contact Intecion.', + statusEmailRelayTooLarge: 'The e-mail or its files are larger than the Intecion mail service carries. The e-mail was not sent.', + statusEmailRelayUnreachable: 'The Intecion mail service 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.', @@ -56,10 +104,13 @@ 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.', 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 Intecion mail service, 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', testEmailWithFile: 'Attach a 10 MB test file', @@ -70,6 +121,42 @@ export const integrationsTexts = defineTexts({ alertsLink: 'Przejdź do integracji', alertsUnknownError: 'Nieznany błąd.', + mailRelayCheck: 'Sprawdź teraz', + mailRelayConnect: 'Połącz ponownie', + mailRelayConnected: 'Witryna jest połączona z usługą pocztową Intecion.', + mailRelayConnectFailed: 'Nie udało się połączyć witryny: {{reason}}', + mailRelayDisconnect: 'Rozłącz', + mailRelayDisconnectConfirm: 'Rozłączyć witrynę z usługą pocztową Intecion? 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 usługą pocztową Intecion.', + 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: 'Usługa pocztowa nie przyjęła 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: 'Usługa pocztowa Intecion jest wyłączona w tym projekcie.', + mailRelayQuota: 'Pozostało w tej godzinie: {{hour}}. Pozostało dziś: {{day}}.', + mailRelayRefusedCallback: 'Usługa pocztowa nie mogła potwierdzić witryny pod adresem {{url}} ({{reason}}). Witryna musi odpowiadać tam z internetu, bez przekierowania. Jeśli witryna udostępnia API pod innym adresem, poproś Intecion o ustawienie adresu potwierdzenia dla tej witryny.', + mailRelayRefusedClosed: 'Usługa pocztowa nie przyjmuje teraz nowych witryn. Skontaktuj się z Intecion.', + mailRelayRefusedHost: 'Witryna nie ma publicznego adresu, pod który usługa pocztowa mogłaby się odezwać ({{host}}). Zadziała, gdy witryna będzie dostępna pod swoją domeną.', + mailRelayRefusedNoHost: 'Witryna nie zna własnego adresu. Administrator musi ustawić serverURL w konfiguracji Payload.', + mailRelayRefusedOther: 'Usługa pocztowa odpowiedziała: {{message}}', + mailRelayRepliesTo: 'Odpowiedzi trafiają na adres {{address}}.', + mailRelayStateActive: 'Połączono z usługą pocztową Intecion.', + 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 przez Intecion. E-maile nie są jeszcze wysyłane.', + mailRelayStateSuspended: 'Intecion wstrzymał wysyłkę e-maili z tej witryny. Skontaktuj się z Intecion.', + mailRelayToken: 'Token wydany przez Intecion', + mailRelayTokenHint: 'Tylko dla witryny, do której usługa pocztowa nie może się odezwać. Token zostanie zapisany i nie będzie więcej pokazywany.', + mailRelayTokenInvalid: 'To nie jest token usługi pocztowej.', + mailRelayTokenSave: 'Zapisz token', + mailRelayTransportGraph: 'E-maile idą przez Microsoft Graph. Ten sposób jest wycofywany i 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 usługę pocztową Intecion, z adresu {{address}}.', + mailRelayTransportSmtp: 'E-maile idą przez Twój serwer SMTP.', + mailRelayWorking: 'Trwa…', + maskedHide: 'Ukryj', maskedKeep: 'Zostaw zapisaną wartość', maskedRemove: 'Usuń zapisaną wartość', @@ -95,6 +182,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: 'Usługa pocztowa Intecion nie przesyła plików tego typu. E-mail nie został wysłany.', + statusEmailRelayDisconnected: 'Witryna jest rozłączona z usługą pocztową Intecion, więc e-maile nie są wysyłane. Połącz ją ponownie albo uzupełnij serwer SMTP.', + statusEmailRelayError: 'Usługa pocztowa Intecion odrzuciła e-mail. Powiadom administratora.', + statusEmailRelayNotConfirmed: 'Usługa pocztowa Intecion nie potwierdziła ostatniego e-maila. Mógł zostać wysłany.', + statusEmailRelayPending: 'Witryna czeka na zatwierdzenie przez Intecion. E-maile nie są jeszcze wysyłane.', + statusEmailRelayQuota: 'Witryna osiągnęła limit wysyłki w usłudze pocztowej Intecion. 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. Skontaktuj się z Intecion.', + statusEmailRelayRefused: 'Usługa pocztowa Intecion nie połączyła tej witryny. Zobacz stan powyżej albo uzupełnij serwer SMTP.', + statusEmailRelaySuspended: 'Intecion wstrzymał wysyłkę e-maili z tej witryny. Skontaktuj się z Intecion.', + statusEmailRelayTooLarge: 'E-mail lub jego pliki są większe, niż przesyła usługa pocztowa Intecion. E-mail nie został wysłany.', + statusEmailRelayUnreachable: 'Usługa pocztowa Intecion była nieosiągalna albo zawiodła. 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.', @@ -113,10 +211,13 @@ 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.', 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 usługę pocztową Intecion, 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', testEmailWithFile: 'Dołącz plik testowy 10 MB', diff --git a/src/modules/doctor/rules/mail.ts b/src/modules/doctor/rules/mail.ts new file mode 100644 index 0000000..1a1d12a --- /dev/null +++ b/src/modules/doctor/rules/mail.ts @@ -0,0 +1,141 @@ +import type { DoctorContext } from '../project.js' +import type { DoctorRule, RuleFinding } from '../types.js' + +import { configFile, nextConfigFile } from '../project.js' +import { stripComments } from '../util.js' + +const CONFIRM = '/iapl/mail-relay/confirm' +const cfg = (ctx: DoctorContext) => stripComments(ctx.read(configFile(ctx) ?? '')) +const next = (ctx: DoctorContext) => stripComments(ctx.read(nextConfigFile(ctx) ?? '')) +const relayOff = (code: string) => /\brelay\s*:\s*false\b/.test(code) +const since = (iso?: null | string) => (iso ? `, since ${iso.slice(0, 16).replace('T', ' ')}` : '') + +/** + * E-mail (docs/email.md): which transport is in effect and whether it works, the site's state with the + * Intecion Notifications Webservice, the deprecated Graph transport, the reply address, and whether + * the service can reach the site's confirm route. Ids carry no brand, like `agents-md`. + */ +export const mailRules: DoctorRule[] = [ + { + // Which transport a send takes right now, and whether the last sends worked. + id: 'mail-transport', + check: (ctx) => { + const mail = ctx.deep?.mail + if (!mail) {return []} + const out: RuleFinding[] = [] + if (mail.transport === 'none') { + out.push({ + fix: 'remove `mail: { relay: false }` to send through the Intecion mail service, or fill in an SMTP server in Site integrations → E-mail sending', + message: 'no e-mail transport is set up: the Intecion mail service is switched off and the panel has no SMTP server — e-mails are not sent', + severity: 'error', + }) + } + if (mail.status?.state === 'degraded') { + const now = ctx.today === new Date().toISOString().slice(0, 10) ? Date.now() : Date.parse(`${ctx.today}T12:00:00Z`) + const hours = mail.status.since ? Math.floor((now - Date.parse(mail.status.since)) / 3_600_000) : null + out.push({ + fix: 'Site integrations → E-mail sending: read the state block, then send a test e-mail (iapl-debug, "E-mail")', + message: `e-mail sending is failing (${mail.status.code ?? 'unknown'}, transport: ${mail.transport})${since(mail.status.since)}`, + severity: hours !== null && hours >= 24 ? 'error' : 'warning', + }) + } + return out + }, + docs: 'docs/email.md', + group: 'mail', + source: 'deep', + }, + { + // The site's state with the Intecion mail service, when that is how it sends. + id: 'mail-relay-state', + check: (ctx) => { + const mail = ctx.deep?.mail + const relay = mail?.relay + if (!mail || mail.transport !== 'relay' || !relay) {return []} + const out: RuleFinding[] = [] + if (relay.disconnected) { + out.push({ fix: 'Site integrations → E-mail sending → "Connect again", or fill in an SMTP server', message: 'the site was disconnected from the Intecion mail service in the panel: e-mails are not sent', severity: 'error' }) + } else if (relay.state === 'suspended') { + out.push({ fix: 'contact Intecion; meanwhile an SMTP server in the panel sends the site\'s mail', message: 'Intecion has stopped e-mail sending for this site (suspended)', severity: 'error' }) + } else if (relay.state === 'pending') { + out.push({ fix: 'Intecion approves the host on the service (`ims approve `); the same token then works', message: 'the site is enrolled with the Intecion mail service but waits for approval: e-mails are not sent yet', severity: 'warning' }) + } else if (!relay.connected && relay.refusal) { + const path = relay.refusal === 'callback-failed' ? ` (${relay.reason ?? 'unknown'}): the service could not confirm the site at its public address` : '' + out.push({ + fix: relay.refusal === 'callback-failed' ? 'the site must answer POST /api/iapl/mail-relay/confirm from the internet without a redirect (email.md, "When the site cannot be confirmed"), then "Connect again"' : 'email.md, "When the site cannot be confirmed"; then Site integrations → E-mail sending → "Connect again"', + message: `the Intecion mail service did not connect this site: ${relay.refusal}${path}`, + severity: 'warning', + }) + } else if (!relay.connected) { + out.push({ fix: 'send a test e-mail from Site integrations → E-mail sending', message: 'the site has not enrolled with the Intecion mail service yet (it does so on its first e-mail)', severity: 'info' }) + } + if (relay.nameReplaced) { + out.push({ fix: 'Site integrations → E-mail sending → Sender name: a name that is the client\'s own (no address, no other company\'s name)', message: 'the mail service did not accept the sender name, so e-mails leave under the site\'s host', severity: 'warning' }) + } + return out + }, + docs: 'docs/email.md', + group: 'mail', + source: 'deep', + }, + { + // The sender address of the service has no mailbox: without a reply address, answers are lost. + id: 'mail-reply-address', + check: (ctx) => { + const mail = ctx.deep?.mail + return mail?.transport === 'relay' && !mail.replyAddress + ? [{ fix: 'Site integrations → E-mail sending → Sender address: the client\'s own address', message: 'no reply address is set: replies to the site\'s e-mails (other than forms that set their own) go to an address without a mailbox', severity: 'warning' }] + : [] + }, + docs: 'docs/email.md', + group: 'mail', + source: 'deep', + }, + { + // Microsoft Graph as the transport: deprecated in 1.17.0, removed in 2.0. + id: 'mail-graph-deprecated', + check: (ctx) => { + const mail = ctx.deep?.mail + const inCode = /\bgraphAdapter\s*\(|\bemailGraph\s*:\s*true\b/.test(cfg(ctx)) + if (!mail?.graphEnv && mail?.transport !== 'graph' && !inCode) {return []} + return [{ + fix: 'remove the four GRAPH_* variables (Coolify) and send a test e-mail — the site then uses the Intecion mail service — or fill in an SMTP server (email.md, "Moving off Microsoft Graph")', + message: mail?.transport === 'graph' ? 'e-mails go through Microsoft Graph, which is deprecated and will be removed in 2.0' : 'Microsoft Graph is still set up for this site (GRAPH_* variables or graphAdapter); it is deprecated and will be removed in 2.0', + severity: 'warning', + }] + }, + docs: 'docs/email.md', + group: 'mail', + source: 'static', + }, + { + // The service calls exactly https:///api/iapl/mail-relay/confirm and follows no redirect. + id: 'mail-relay-route', + check: async (ctx) => { + const code = cfg(ctx) + if (relayOff(code)) {return []} + const out: RuleFinding[] = [] + const ask = 'ask Intecion to set this site\'s confirm address (`ims callback-path `), or change the site to answer at /api/iapl/mail-relay/confirm' + if (/\btrailingSlash\s*:\s*true\b/.test(next(ctx))) { + out.push({ file: nextConfigFile(ctx) ?? 'next.config.ts', fix: `${ask} — with trailing slashes the path ends in /confirm/`, message: 'trailingSlash: true redirects the mail service\'s call-back, and the service follows no redirect: the site cannot enrol', severity: 'warning' }) + } + const api = /\broutes\s*:\s*\{[^}]*\bapi\s*:\s*['"`]([^'"`]+)['"`]/.exec(code)?.[1] + if (api && api !== '/api') { + out.push({ file: configFile(ctx) ?? 'src/payload.config.ts', fix: ask, message: `the API is served at ${api}, not /api: the mail service calls /api${CONFIRM} unless Intecion set another address for this host`, severity: 'warning' }) + } + if (ctx.live && ctx.deep?.mail?.transport === 'relay') { + const res = await ctx.live.fetch(`${api ?? '/api'}${CONFIRM}`, { redirect: 'manual' }) + // A GET finds no route there (the route is POST): 404 or 405 means the address is reached as it is. + if (res.status >= 300 && res.status < 400) { + out.push({ fix: `enrol the host the site really answers on (mail.relay.host), or ${ask}`, message: `live ${api ?? '/api'}${CONFIRM} redirects (${res.status} → ${res.headers.get('location') ?? '?'}); the mail service follows no redirect`, severity: 'warning' }) + } else if (res.status === 401 || res.status === 403 || res.status === 0 || res.status >= 500) { + out.push({ fix: 'the confirm route must be reachable from the internet: no basic auth, no firewall rule, no maintenance page in front of it', message: `live ${api ?? '/api'}${CONFIRM} → ${res.status || res.error}: the mail service cannot call the site back`, severity: 'warning' }) + } + } + return out + }, + docs: 'docs/email.md', + group: 'mail', + source: 'static', + }, +] diff --git a/src/modules/doctor/run.ts b/src/modules/doctor/run.ts index 0bf7ac9..31b9f50 100644 --- a/src/modules/doctor/run.ts +++ b/src/modules/doctor/run.ts @@ -12,6 +12,7 @@ import { envRules } from './rules/env.js' import { layoutRules } from './rules/layout.js' import { legacyRules } from './rules/legacy.js' import { createLiveFetcher, liveRules } from './rules/live.js' +import { mailRules } from './rules/mail.js' import { securityRules } from './rules/security.js' import { seedRules } from './rules/seeds.js' import { toolingRules } from './rules/tooling.js' @@ -33,6 +34,7 @@ export const doctorRules: DoctorRule[] = [ ...layoutRules, ...envRules, ...securityRules, + ...mailRules, ...agentRules, ...legacyRules, ...seedRules, diff --git a/src/modules/doctor/status.ts b/src/modules/doctor/status.ts index b0b5a64..000ff68 100644 --- a/src/modules/doctor/status.ts +++ b/src/modules/doctor/status.ts @@ -8,6 +8,8 @@ import { PLUGIN_VERSION } from '../../version.js' import { openSignUpCollections, staffCollectionsOnOwnRoles, staffCollectionsOpenToOthers } from '../access/selfRegistration.js' import { countPendingCookies } from '../consent/scanner/approval.js' import { COOKIE_REVIEW_SLUG } from '../consent/scanner/collection.js' +import { graphAvailable } from '../email/mailAdapter.js' +import { mailPanelState } from '../email/relay/panel.js' import { secondFactorPassed, SETUP_FROM_FIELD } from '../security/totp/secondFactor.js' import { countAccountsWithoutTotp } from '../security/totp/setupRequired.js' import { readEnv } from '../shared/envName.js' @@ -59,6 +61,33 @@ export async function collectDoctorStatus(payload: BasePayload): Promise g.slug === 'site-integrations')) { + try { + const state = await mailPanelState({ payload }, undefined) + const integrations = (await payload.findGlobal({ slug: 'site-integrations' as never, depth: 0, overrideAccess: true })) as unknown as { + emailStatus?: { code?: null | string; since?: null | string; state?: null | string } | null + } + mail = { + graphEnv: graphAvailable(), + relay: state.relay + ? { + connected: state.relay.connected, + disconnected: state.relay.disconnected, + nameReplaced: Boolean(state.relay.nameReplaced), + ...(state.relay.refusal ? { refusal: state.relay.refusal.code, ...(state.relay.refusal.reason ? { reason: state.relay.refusal.reason } : {}) } : {}), + ...(state.relay.state ? { state: state.relay.state } : {}), + } + : null, + replyAddress: Boolean(state.replyAddress), + status: integrations.emailStatus?.state ? { code: integrations.emailStatus.code ?? null, since: integrations.emailStatus.since ?? null, state: integrations.emailStatus.state } : null, + transport: state.transport, + } + } catch { + /* the global cannot be read: unknown */ + } + } let openSignUp: null | string[] = null try { openSignUp = await openSignUpCollections(payload as never) @@ -77,7 +106,7 @@ export async function collectDoctorStatus(payload: BasePayload): Promise Boolean(s.smtpHost && s.smtpUser && s.smtpPassword) +/** Which transport a send takes. `none`: nothing is set up and the relay is switched off. */ +export type MailTransport = 'graph' | 'none' | 'relay' | 'smtp' + +/** + * The transport in effect for the present settings, decided on every send (no stored value): + * 1. "Sending method" is Microsoft Graph and the GRAPH_* variables are complete → Graph, as before + * (deprecated; removed in 2.0); + * 2. the panel has an SMTP server (server, user name, password) → SMTP — on the client's request; + * 3. the GRAPH_* variables are complete → Graph (deprecated), until they are removed; + * 4. otherwise → the Intecion Notifications Webservice, unless it is switched off (`mail: { relay: false }`); + * 5. otherwise nothing is configured. + * A site with SMTP filled in never contacts the service. + */ +export function resolveMailTransport(settings: TransportIntegrations, state: { graphEnv: boolean; relay: boolean }): MailTransport { + if ((settings.emailTransport ?? 'smtp') === 'graph' && state.graphEnv) {return 'graph'} + if (smtpConfigured(settings)) {return 'smtp'} + if (state.graphEnv) {return 'graph'} + return state.relay ? 'relay' : 'none' +} + /** Graph result codes that mean "Graph cannot carry an attachment this large" — SMTP may. */ const GRAPH_TOO_LARGE = new Set(['graph-large-off', 'graph-permission']) +/** The one warning a site on Microsoft Graph gets per process (silence: `mail: { graphDeprecationWarning: false }`). */ +export const GRAPH_DEPRECATION_NOTICE = + '[iapl] Microsoft Graph as the e-mail transport is deprecated and will be removed in 2.0. Remove the GRAPH_* variables to send through the Intecion Notifications Webservice, or fill in an SMTP server in Site integrations (docs/email.md, "Moving off Microsoft Graph").' + const STATUS_FIELD = 'emailStatus' /** Error text for the panel: first line, no stack, capped — SMTP errors don't carry the password. */ const describe = (err: unknown) => @@ -28,12 +56,27 @@ const describe = (err: unknown) => export type MailAdapterArgs = { fallbackFromAddress?: string fallbackFromName?: string + /** @deprecated Microsoft Graph is deprecated since 1.17.0 and removed in 2.0 (docs/email.md, "Moving off Microsoft Graph"). */ graph?: GraphAdapterArgs + /** + * The Intecion Notifications Webservice — the transport of a site with no SMTP server in the panel. + * `false` switches it off for this adapter; an object overrides `iapl({ mail: { relay } })`. + */ + relay?: false | RelayOptions smtp?: PanelSmtpAdapterArgs } +let warnedGraphDeprecated = false +/** iapl() left its options in the config: it has already warned at start (plugin.ts, onInit). */ +const pluginWarnsAtStart = (payload: { config?: { custom?: unknown } }) => Boolean((payload.config?.custom as { iapl?: { mail?: unknown } } | undefined)?.iapl?.mail) + +/** For tests. */ +export function resetGraphDeprecationWarning(): void { + warnedGraphDeprecated = false +} + /** True when the agency Graph credentials are present in the environment. */ -function graphAvailable(): boolean { +export function graphAvailable(): boolean { return Boolean( process.env.GRAPH_TENANT_ID && process.env.GRAPH_CLIENT_ID && @@ -44,7 +87,9 @@ function graphAvailable(): boolean { /** * Dispatcher email adapter: wired into the config ONCE, but picks the transport - * (SMTP or Graph) per send by reading `emailTransport` from SiteIntegrations. + * per send from Site integrations (resolveMailTransport): the panel's SMTP server + * when one is filled in, Microsoft Graph while its variables last (deprecated), + * otherwise the Intecion Notifications Webservice (relay/). * This is what makes the choice switchable in the panel — Payload builds the * email adapter at boot and can't swap it at runtime, so instead of choosing * between two adapters at boot we install one that delegates on every send. @@ -84,9 +129,15 @@ export const mailAdapter = * promises more than can be sent: on Graph without the large-file path and * without SMTP settings the ceiling is GRAPH_INLINE_MAX_BYTES. */ + const relayOptions = () => resolveRelayOptions(payload, args.relay) + const transportOf = (settings: TransportIntegrations) => resolveMailTransport(settings, { graphEnv: graphAvailable(), relay: Boolean(relayOptions()) }) + const attachmentLimit = async (): Promise => { const settings = await getSiteIntegrations(payload) - if ((settings.emailTransport ?? 'smtp') !== 'graph' || !graphAvailable()) {return null} + const transport = transportOf(settings) + // The service says what it carries for this site (10 MB unless Intecion set another number). + if (transport === 'relay') {return relayAttachmentLimit(payload, relayOptions()!).catch(() => null)} + if (transport !== 'graph') {return null} const support = await graphLargeAttachmentSupport(args.graph) if (support === 'ok' || support === 'unavailable' || smtpConfigured(settings)) {return null} return GRAPH_INLINE_MAX_BYTES - 1 @@ -102,7 +153,13 @@ export const mailAdapter = const settings = await getSiteIntegrations(payload) const choice = settings.emailTransport ?? 'smtp' const previous = settings[STATUS_FIELD] - const useGraph = choice === 'graph' && graphAvailable() + const chosen = transportOf(settings) + + // No SMTP server in the panel and no Graph: the Intecion Notifications Webservice. + if (chosen === 'relay') {return sendRelayWithPanel(payload, relayOptions()!, message, settings)} + + const useGraph = chosen === 'graph' + // "Graph" in the panel without its variables is reported only while SMTP carries the mail instead. const graphFallback = choice === 'graph' && !useGraph if (graphFallback) { @@ -112,6 +169,11 @@ export const mailAdapter = '[iapl] Transport set to Graph but GRAPH_* env vars are missing; falling back to SMTP.', ) } + // A project that uses mailAdapter() without iapl()'s start warning still hears it once. + if (useGraph && !warnedGraphDeprecated && !pluginWarnsAtStart(payload) && pluginMailOptions(payload).graphDeprecationWarning !== false) { + warnedGraphDeprecated = true + payload.logger.warn(GRAPH_DEPRECATION_NOTICE) + } // A large attachment Graph cannot carry (switched off, or the app lacks // Mail.ReadWrite) goes over SMTP when the panel has SMTP settings. @@ -168,7 +230,8 @@ export const mailAdapter = } : { state: 'ok' }, ) - return result + // which transport carried it — the test e-mail says so in the panel + return result && typeof result === 'object' ? { ...result, transport: viaGraph ? 'graph' : 'smtp' } : result }, } } diff --git a/src/modules/email/relay/accountMail.ts b/src/modules/email/relay/accountMail.ts new file mode 100644 index 0000000..db52b75 --- /dev/null +++ b/src/modules/email/relay/accountMail.ts @@ -0,0 +1,31 @@ +import type { CollectionConfig } from 'payload' + +import { clientIp } from '../../shared/rateLimit.js' +import { markNextMail } from './kinds.js' + +const MARK = Symbol.for('iapl.accountMailMark') + +/** + * Payload composes and sends "forgot password" and "verify your e-mail" by itself, through + * `payload.sendEmail`, with nothing on the message that says what it is. This hook on an auth + * collection says it for the NEXT message of the request (kinds.ts): kind `account`, with the + * visitor's address so the relay transport can limit what one visitor makes the site send + * (`mail.relay.accountMail`). Other transports ignore the mark; nothing else changes. + * + * Marks `forgotPassword` always, and `create` only where the collection verifies e-mail addresses. + */ +export function withAccountMailMark(collection: CollectionConfig): CollectionConfig { + const hooks = collection.hooks?.beforeOperation ?? [] + if (hooks.some((h) => (h as { [MARK]?: boolean })[MARK])) {return collection} + const verifies = typeof collection.auth === 'object' && Boolean(collection.auth.verify) + // NOT async: the mark has to be set in the operation's own synchronous run (markNextMail). + const mark = ((args: { args?: { req?: { headers?: Headers } }; operation: string; req?: { headers?: Headers } }) => { + if (args.operation === 'forgotPassword' || (verifies && args.operation === 'create')) { + const headers = args.req?.headers ?? args.args?.req?.headers + markNextMail('account', { visitor: headers ? clientIp(headers) || undefined : undefined }) + } + return args.args + }) as unknown as { [MARK]?: boolean } & NonNullable['beforeOperation']>[number] + mark[MARK] = true + return { ...collection, hooks: { ...collection.hooks, beforeOperation: [...hooks, mark] } } +} diff --git a/src/modules/email/relay/adapter.ts b/src/modules/email/relay/adapter.ts new file mode 100644 index 0000000..3b25f55 --- /dev/null +++ b/src/modules/email/relay/adapter.ts @@ -0,0 +1,99 @@ +import type { BasePayload, PayloadEmailAdapter, SendEmailOptions } from 'payload' + +import type { RelayOptions, ResolvedRelayOptions } from './options.js' + +import { type IntegrationStatus, recordIntegrationStatus } from '../../integrations/status.js' +import { getSiteIntegrations } from '../../payload/index.js' +import { RELAY_DEFAULTS, RELAY_SERVICE_NAME } 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' + +/** The address mail leaves from until the service has been asked (`/v1/status` reports the real one). */ +export const RELAY_SENDER_ADDRESS = 'notification@webservices.intecion.net' + +type PanelSender = { emailStatus?: IntegrationStatus | null; smtpFromAddress?: null | string; smtpFromName?: null | string } + +const firstLine = (text: string) => text.split('\n')[0].slice(0, 200) + +/** The site name from Site settings (default locale), or '' — the sender name when the panel field is empty. */ +async function siteName(payload: BasePayload): Promise { + try { + if (!(payload.config.globals ?? []).some((g) => g.slug === 'site-settings')) {return ''} + const doc = (await payload.findGlobal({ slug: 'site-settings' as never, depth: 0, overrideAccess: true })) as { siteName?: unknown } + return typeof doc?.siteName === 'string' ? doc.siteName.trim() : '' + } catch { + return '' + } +} + +/** + * The display name of the site's mail: `relay.senderName`, else the panel's "Sender name", else the + * site name from Site settings. Empty = the service uses the site's host. + */ +export async function relaySenderName(payload: BasePayload, options: Pick, panelName?: null | string): Promise { + const own = typeof options.senderName === 'function' ? await options.senderName({ payload }) : options.senderName + if (typeof own === 'string' && own.trim()) {return own.trim()} + if (typeof panelName === 'string' && panelName.trim()) {return panelName.trim()} + return siteName(payload) +} + +/** One send through the service with the panel's sender name and reply address, and `emailStatus` kept. */ +export async function sendRelayWithPanel(payload: BasePayload, options: ResolvedRelayOptions, message: SendEmailOptions, settings: PanelSender): Promise { + const result = await sendThroughRelay(payload, options, message, { + replyTo: settings.smtpFromAddress, + senderName: await relaySenderName(payload, options, settings.smtpFromName), + }) + await recordIntegrationStatus( + payload, + 'emailStatus', + settings.emailStatus, + result.sent ? { state: 'ok' } : { code: result.code, message: `${RELAY_SERVICE_NAME}: ${firstLine(result.detail)}`, state: 'degraded' }, + ) + return result +} + +/** + * The largest total attachment size the service carries for this site, as it last reported + * (`limits.maxAttachmentBytes` of `/v1/status`) — read again when older than an hour. `null` until + * the site has enrolled: the plugin has no constant of its own for it. + */ +export async function relayAttachmentLimit(payload: BasePayload, options: ResolvedRelayOptions): Promise { + let stored = await readRelayStore(payload) + 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 + } + const limit = stored.service?.limits?.maxAttachmentBytes + return typeof limit === 'number' && limit >= 0 ? limit : null +} + +export type RelayAdapterArgs = { + /** Payload wants a from-address at start; the service fixes the real one. */ + fallbackFromAddress?: string + fallbackFromName?: string +} & RelayOptions + +/** + * The Intecion Notifications Webservice as a Payload e-mail adapter of its own — for a project that + * wants this transport and nothing else: + * email: relayAdapter() + * `mailAdapter()` already uses it when the panel has no SMTP server; most projects need only that. + * Reads the sender name and the reply address from Site integrations when that global exists. + */ +export const relayAdapter = + (args: RelayAdapterArgs = {}): PayloadEmailAdapter => + ({ payload }) => { + const { fallbackFromAddress, fallbackFromName, ...own } = args + const options = () => resolveRelayOptions(payload, own) as ResolvedRelayOptions + const panel = async (): Promise => + (payload.config.globals ?? []).some((g) => g.slug === 'site-integrations') ? getSiteIntegrations(payload) : {} + return { + name: 'iapl-relay', + attachmentLimit: () => relayAttachmentLimit(payload, options()), + defaultFromAddress: fallbackFromAddress ?? RELAY_SENDER_ADDRESS, + defaultFromName: fallbackFromName ?? 'Website', + sendEmail: async (message: SendEmailOptions) => sendRelayWithPanel(payload, options(), message, await panel()), + } + } diff --git a/src/modules/email/relay/client.ts b/src/modules/email/relay/client.ts new file mode 100644 index 0000000..d872e38 --- /dev/null +++ b/src/modules/email/relay/client.ts @@ -0,0 +1,101 @@ +import { PLUGIN_VERSION } from '../../../version.js' +import { RELAY_DEFAULTS, RELAY_PRODUCT } from './constants.js' + +/** A refusal of the service (contracts/mail-relay/schema.json, `Error`), or what stands in for one. */ +export type RelayRefusal = { + code: string + field?: string + limit?: string + message: string + /** No usable answer came at all (time-out, connection lost): the request may have been carried out. */ + noAnswer: boolean + ok: false + reason?: string + retryable: boolean + /** Seconds. */ + retryAfter?: number + status: number +} + +export type RelayAnswer> = { body: T; ok: true; status: number } | RelayRefusal + +export type RelayCall = { + /** The request body, already encoded. A send keeps these bytes for every retry. */ + body?: Uint8Array + fetchImpl?: typeof fetch + idempotencyKey?: string + method: 'GET' | 'POST' + /** Relative to the base address: `/v1/send`. */ + path: string + timeoutMs?: number + token?: string + /** Base address, host and path prefix together; joined with `path` as text. */ + url: string +} + +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`. + */ +export async function relayRequest>(call: RelayCall): Promise> { + const controller = new AbortController() + const timer = setTimeout(() => controller.abort(), call.timeoutMs ?? RELAY_DEFAULTS.timeoutMs) + let status = 0 + try { + const response = await (call.fetchImpl ?? fetch)(`${call.url.replace(/\/+$/, '')}${call.path}`, { + body: call.body as BodyInit | undefined, + headers: { + accept: 'application/json', + 'user-agent': `${RELAY_PRODUCT}/${PLUGIN_VERSION}`, + ...(call.body ? { 'content-type': 'application/json' } : {}), + ...(call.token ? { authorization: `Bearer ${call.token}` } : {}), + ...(call.idempotencyKey ? { 'idempotency-key': call.idempotencyKey } : {}), + }, + method: call.method, + // the token goes to the configured address and nowhere else + redirect: 'manual', + signal: controller.signal, + }) + status = response.status + const text = await response.text() + let parsed: unknown + try { + parsed = JSON.parse(text) + } catch { + parsed = null + } + const body = parsed && typeof parsed === 'object' && !Array.isArray(parsed) ? (parsed as Record) : null + if (body?.ok === true && status === 200) {return { body: body as T, ok: true, status }} + if (body?.ok === false && typeof body.code === 'string' && body.code) { + return { + code: body.code, + message: typeof body.message === 'string' ? firstLine(body.message) : body.code, + noAnswer: false, + ok: false, + retryable: body.retryable === true, + status, + ...(typeof body.retryAfter === 'number' && body.retryAfter >= 0 ? { retryAfter: body.retryAfter } : {}), + ...(typeof body.field === 'string' ? { field: body.field } : {}), + ...(typeof body.limit === 'string' ? { limit: body.limit } : {}), + ...(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 } + } catch (err) { + const aborted = controller.signal.aborted + return { + code: 'unavailable', + message: aborted ? 'The mail service did not answer in time.' : `The mail service could not be reached: ${firstLine(err instanceof Error ? err.message : String(err))}`, + // an attempt that timed out is "no answer"; a body that broke off by itself is an answer that is not JSON + noAnswer: aborted || status === 0, + ok: false, + retryable: true, + status, + } + } finally { + clearTimeout(timer) + } +} diff --git a/src/modules/email/relay/confirm.ts b/src/modules/email/relay/confirm.ts new file mode 100644 index 0000000..8b59cd1 --- /dev/null +++ b/src/modules/email/relay/confirm.ts @@ -0,0 +1,73 @@ +import type { Endpoint, PayloadRequest } from 'payload' + +import type { RelayOptions } from './options.js' + +import { clientIp, consumeRateLimit, tooManyRequests } from '../../shared/rateLimit.js' +import { RELAY_CONFIRM_PATH, RELAY_DEFAULTS } from './constants.js' +import { sha256Hex, takeNonce, writeRelayCandidate } from './store.js' + +const NONCE = /^[\w-]{32,128}$/ +const TOKEN = /^ims_[\w-]{43}$/ +const STATES = new Set(['active', 'pending', 'suspended']) +const MAX_BODY = 2048 + +const notFound = () => new Response(null, { headers: { 'cache-control': 'no-store' }, status: 404 }) + +async function readBody(req: PayloadRequest): Promise { + const length = Number(req.headers.get('content-length') ?? 0) + if (length > MAX_BODY) {return null} + try { + const read = (req as { text?: () => Promise }).text + if (typeof read !== 'function') {return (await req.json?.()) as unknown} + const text = await read.call(req) + return text.length <= MAX_BODY ? (JSON.parse(text) as unknown) : null + } catch { + return null + } +} + +/** + * `POST /api/iapl/mail-relay/confirm` — where the Intecion Notifications Webservice calls a site back + * during an enrolment the SITE started. Public, and useless to anybody else: + * + * - it answers `404` and changes nothing unless the body carries a nonce this site made in the last + * five minutes (kept as a hash, compared in constant time, single use); + * - then it stores the delivered token BESIDE the one in use (store.ts) — a working token is never + * replaced by one the service has not accepted — and answers `200` with exactly + * `{ "confirmation": hex(SHA-256(nonce + "." + token)) }`, which only an endpoint that holds the + * nonce and has read the token can compute; + * - it is rate-limited per address. + * The path is fixed for this product by the service's contract; a project cannot move it (a site with + * another API route asks Intecion to set its confirm address). + */ +export function relayConfirmEndpoint(options: Pick = {}): Endpoint { + const max = options.confirmRateLimit?.max ?? RELAY_DEFAULTS.confirmRateLimit.max + const windowMs = options.confirmRateLimit?.windowMs ?? RELAY_DEFAULTS.confirmRateLimit.windowMs + return { + handler: async (req: PayloadRequest) => { + const limit = await consumeRateLimit({ key: clientIp(req.headers), max, scope: 'mail-relay-confirm', windowMs }) + if (!limit.ok) {return tooManyRequests(limit.retryAfter, { error: 'Too many requests.' })} + + const body = (await readBody(req)) as { nonce?: unknown; state?: unknown; token?: unknown } | null + if (!body || typeof body !== 'object') {return notFound()} + const { nonce, state, token } = body + if (typeof nonce !== 'string' || !NONCE.test(nonce) || typeof token !== 'string' || !TOKEN.test(token) || typeof state !== 'string' || !STATES.has(state)) { + return notFound() + } + try { + if (!(await takeNonce(req.payload, nonce))) {return notFound()} + await writeRelayCandidate(req.payload, { at: new Date().toISOString(), nonceHash: sha256Hex(nonce), state: state as 'active' | 'pending' | 'suspended', token }) + } catch (err) { + req.payload.logger.error(`[iapl] mail service: the confirm route could not use the store: ${err instanceof Error ? err.message.split('\n')[0] : String(err)}`) + return notFound() + } + // Exactly this object and nothing else: the service reads at most 1024 bytes and checks the hash. + return new Response(JSON.stringify({ confirmation: sha256Hex(`${nonce}.${token}`) }), { + headers: { 'cache-control': 'no-store', 'content-type': 'application/json' }, + status: 200, + }) + }, + method: 'post', + path: RELAY_CONFIRM_PATH, + } +} diff --git a/src/modules/email/relay/constants.ts b/src/modules/email/relay/constants.ts new file mode 100644 index 0000000..13b6476 --- /dev/null +++ b/src/modules/email/relay/constants.ts @@ -0,0 +1,92 @@ +/** + * The Intecion Notifications Webservice, as the plugin knows it. No secret is here and none is in the + * package: a site gets its own token by enrolling (enrol.ts). The wire contract these values come from + * is copied in `contracts/mail-relay/` (test/mailRelayContract.test.ts fails on a hand-edited copy). + */ + +/** 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' +/** The `product` value of this plugin. */ +export const RELAY_PRODUCT = 'iapl' +/** The service's name, for texts. */ +export const RELAY_SERVICE_NAME = 'Intecion Notifications Webservice' +/** 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. */ +export const RELAY_STATUS_PATH = '/iapl/mail-relay/status' +export const RELAY_CONNECT_PATH = '/iapl/mail-relay/connect' +export const RELAY_DISCONNECT_PATH = '/iapl/mail-relay/disconnect' +/** Key of the site's token and state in `payload.kv`; the candidate token and the nonces hang off it. */ +export const RELAY_KV_KEY = 'iapl:mail-relay' + +export const RELAY_DEFAULTS = { + /** A visitor's lever: "forgot password" mail per address and per visitor in the window (accountMail option). */ + accountMail: { perAddress: 5, perVisitor: 10, windowMinutes: 60 }, + /** Requests for one message, the same key and bytes each time. */ + attempts: 3, + /** One attempt, from sending the request to the end of the answer. */ + attemptTimeoutMs: 30_000, + /** Calls to the confirm route per address a minute. */ + confirmRateLimit: { max: 10, windowMs: 60_000 }, + /** The enrolment call: the service's call-back has 8 seconds of it. */ + enrolTimeoutMs: 15_000, + /** How long a site keeps the nonce of an enrolment it started. */ + nonceTtlMs: 5 * 60_000, + /** After a refused enrolment the site does not ask again by itself for this long ("Connect again" does). */ + refusalCooldownMs: 15 * 60_000, + /** How long the limits read from `/v1/status` are used before they are read again. */ + statusTtlMs: 60 * 60_000, + /** Other calls (status, rotate, revoke). */ + timeoutMs: 10_000, + /** Waiting between the attempts for one message, in all. Wins over `retryAfter`. */ + waitBudgetMs: 10_000, +} as const + +/** + * What a send through the service can leave in `emailStatus.code` (Site integrations), each with a + * text in the editor's language. `relay-name-replaced` is a warning shown in the status block: the + * mail went out. + */ +export const RELAY_STATUS_CODES = [ + 'relay-pending', + 'relay-suspended', + 'relay-refused', + 'relay-quota', + 'relay-too-large', + 'relay-attachment-refused', + 'relay-recipient-suppressed', + 'relay-unreachable', + 'relay-not-confirmed', + 'relay-disconnected', + 'relay-error', + 'relay-name-replaced', +] as const +export type RelayStatusCode = (typeof RELAY_STATUS_CODES)[number] + +/** The site status for a code of the service (contract §1, "suggested site status"). */ +export function relayStatusFor(code: string, retryable: boolean): RelayStatusCode { + switch (code) { + case 'attachment-refused': + return 'relay-attachment-refused' + case 'callback-failed': + case 'enrolment-closed': + case 'host-not-allowed': + return 'relay-refused' + case 'quota-exceeded': + case 'too-many-recipients': + return 'relay-quota' + case 'recipient-suppressed': + return 'relay-recipient-suppressed' + case 'site-pending': + return 'relay-pending' + case 'site-suspended': + return 'relay-suspended' + case 'too-large': + return 'relay-too-large' + default: + // A code this client does not know is acted on by `retryable` (contract §1). + return retryable ? 'relay-unreachable' : 'relay-error' + } +} diff --git a/src/modules/email/relay/fake.ts b/src/modules/email/relay/fake.ts new file mode 100644 index 0000000..f6d77c5 --- /dev/null +++ b/src/modules/email/relay/fake.ts @@ -0,0 +1,586 @@ +import { createHash, randomBytes } from 'node:crypto' + +import { RELAY_CONTRACT_VERSION, RELAY_SERVICE_NAME } from './constants.js' +import { MAIL_KINDS, type MailKind } from './kinds.js' + +/** + * A stand-in for the Intecion Notifications Webservice, in memory, for tests — the plugin's own and + * a project's. It speaks the wire contract (`contracts/mail-relay/`): every example there runs against + * it (test/mailRelayContract.test.ts). Nothing is sent: accepted mail is recorded in `outbox`. + * + * const relay = createFakeRelay({ allow: ['example.com'] }) + * iapl({ mail: { relay: { url: relay.url, fetchImpl: relay.fetch } } }) + * + * It is NOT the service: its sender-name guard and its limits are simplified (the real lists and + * windows are the service's own), and it keeps no log. Use it to test what a site does with each + * answer, not to learn what the service will accept. + */ + +export type FakeRelayMail = { + attachments: { bytes: number; contentType: string; filename: string }[] + bcc: string[] + cc: string[] + from: string + fromName: string + headers: Record + host: string + html?: string + kind: MailKind + replyTo?: string + subject: string + text?: string + to: string[] +} + +export type FakeRelayLimits = { + maxAttachmentBytes: number + maxAttachments: number + maxBodyBytes: number + messagesPerDay: number + messagesPerHour: number + newRecipientsPerDay: number + perRecipientPerDay: number + recipientsPerMessage: number + securityAlertsPerDay: number + serverAddresses: number +} + +type Site = { + addresses: string[] + alerts: number + /** A token issued by hand binds to the first address that uses it. */ + bindOnUse: boolean + callbackPath?: string + confirmations: Map + dayAccount: number + dayOther: number + host: string + hourAccount: number + hourOther: number + issuedAt: number + keys: Map; hash: string }> + lastSenderName?: string + previous?: { token: string; until: number } + product: string + state: 'active' | 'pending' | 'suspended' + token?: string +} + +export type FakeRelayOptions = { + /** Where the service's own notices and every `security-alert` go. */ + alertRecipient?: string + /** Hosts that are active as soon as they enrol; others wait for approval (`'*'` = every host). */ + allow?: string[] + /** Also enrol hosts that are not public DNS names (`localhost:3000`), and call them back over http. For a site on this machine. */ + allowLocalHosts?: boolean + /** How the service reaches a site's confirm route. Default: `fetch`, no redirect followed. */ + callSite?: (url: string, init: { body: string; headers: Record; method: 'POST' }) => Promise + /** The address requests come from when the request carries no `x-fake-client-address` header. */ + clientAddress?: string + limits?: Partial + now?: () => number + senderAddress?: string +} + +const DEFAULT_LIMITS: FakeRelayLimits = { + maxAttachmentBytes: 10 * 1024 * 1024, + maxAttachments: 20, + maxBodyBytes: 512_000, + messagesPerDay: 200, + messagesPerHour: 30, + newRecipientsPerDay: 50, + perRecipientPerDay: 10, + recipientsPerMessage: 10, + securityAlertsPerDay: 20, + serverAddresses: 8, +} + +const DAY = 24 * 60 * 60_000 +const HOST = /^(?=.{4,253}$)(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z][a-z0-9-]{0,61}[a-z0-9]$/ +const LOCAL_HOST = /^[a-z0-9](?:[a-z0-9.-]{0,251}[a-z0-9])?(?::\d{1,5})?$/ +const PRIVATE = ['localhost', 'local', 'localdomain', 'internal', 'intranet', 'private', 'lan', 'home', 'corp', 'test', 'invalid', 'example', 'onion', 'arpa'] +const ADDRESS = /^[\w!#$%&'*+/=?^`{|}~-]+(?:\.[\w!#$%&'*+/=?^`{|}~-]+)*@(?:[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?\.)+[A-Z][A-Z0-9-]{0,61}[A-Z0-9]$/i +const NONCE = /^[\w-]{32,128}$/ +const KEY = /^[\w-]{16,128}$/ +const VERSION = /^[0-9A-Z][\w.+-]*$/i +const CONTENT_TYPE = /^[A-Z0-9][\w!#$&^.+-]*\/[A-Z0-9][\w!#$&^.+-]*$/i +// three single code points on purpose (ZWNJ, ZWJ, soft hyphen), not a joined sequence +// eslint-disable-next-line no-misleading-character-class +const UNSAFE_SUBJECT = /[\p{Cc}\p{Zl}\p{Zp}\p{Co}\p{Cs}]|(?![\u200C\u200D\u00AD])\p{Cf}/u +const UNSAFE_NAME = /[\p{Cc}\p{Zl}\p{Zp}\p{Co}\p{Cs}\p{Cf}]/u +const EXECUTABLE = new Set(['apk', 'app', 'bat', 'cmd', 'com', 'cpl', 'dll', 'dmg', 'exe', 'hta', 'jar', 'js', 'jse', 'lnk', 'msi', 'ps1', 'scr', 'sh', 'vbs', 'wsf']) +const SEND_FIELDS = new Set(['attachments', 'bcc', 'cc', 'html', 'kind', 'product', 'productVersion', 'replyTo', 'senderName', 'subject', 'text', 'to']) +const NEVER_A_CLIENT = /\b(?:admin|administrator|amazon|apple|bank|gmail|google|intecion|microsoft|no-?reply|outlook|paypal|security|support)\b/i + +const sha256 = (value: string | Uint8Array) => createHash('sha256').update(value).digest('hex') + +class Refusal extends Error { + constructor( + readonly status: number, + readonly code: string, + message: string, + readonly extra: { field?: string; limit?: string; reason?: string; retryable?: boolean; retryAfter?: number } = {}, + ) { + super(message) + } +} +const invalid = (field: string, message: string) => new Refusal(400, 'invalid-request', message, { field }) + +function isPublicHost(host: string): boolean { + return HOST.test(host) && !PRIVATE.some((s) => host === s || host.endsWith(`.${s}`)) +} + +/** The simplified sender-name guard: the name, or null when the mail leaves under the host instead. */ +function guardName(name: string, host: string): null | string { + const clean = name.replace(/\s+/g, ' ').trim() + if (!clean || [...clean].length > 64) {return null} + if (/[@<>"\\]/.test(clean) || !/^[\p{L}\p{N} .,&'’()/-]+$/u.test(clean)) {return null} + if (/\b[\w-]+\.[a-z]{2,}\b/i.test(clean) && !clean.toLowerCase().includes(host)) {return null} + if (NEVER_A_CLIENT.test(clean)) {return null} + const scripts = ['Latin', 'Cyrillic', 'Greek'].filter((s) => new RegExp(`\\p{Script=${s}}`, 'u').test(clean)) + return scripts.length > 1 ? null : clean +} + +export type FakeRelay = { + /** Lists a host: it is active as soon as it enrols (and at once when it is waiting). */ + allow: (host: string) => void + /** How the mail back end answers the next sends. */ + backend: 'failure' | 'ok' | 'recipient-suppressed' + /** The address the next requests come from (a request's own `x-fake-client-address` header wins). */ + clientAddress: string + /** `fetch` for requests under `url`; anything else goes to the real `fetch`. */ + fetch: typeof fetch + /** One request to the service: `handle(new Request(`${url}/v1/send`, …))`. */ + handle: (request: Request) => Promise + /** + * Looked at before every request: return a `Response` to answer in the service's place, `'drop'` to + * make the request fail like a lost connection, or nothing to let it through. + */ + intercept?: (request: Request) => 'drop' | Promise<'drop' | Response | undefined> | Response | undefined + /** A token for a site the service cannot call back; it binds to the first address that uses it. */ + issueToken: (host: string, product?: string) => string + limits: FakeRelayLimits + /** Starts an HTTP server for the fake (a site in another process, an end-to-end test). */ + listen: (port?: number) => Promise<{ close: () => Promise; url: string }> + /** Every message the back end accepted, oldest first. */ + outbox: FakeRelayMail[] + /** Every request that reached the service: method, path and the caller's address — never a token. */ + requests: { address: string; method: string; path: string }[] + /** Forgets every site, message and counter. */ + reset: () => void + /** Sets the confirm address of one host (a site that serves its API somewhere else). */ + setCallbackPath: (host: string, path: string) => void + /** Puts a site into a state without an enrolment; returns its token. */ + setSite: (host: string, state: 'active' | 'pending' | 'suspended', options?: { product?: string }) => string + /** For tests of limits: the counters of one site. */ + site: (host: string) => Site | undefined + url: string +} + +export function createFakeRelay(options: FakeRelayOptions = {}): FakeRelay { + const now = options.now ?? (() => Date.now()) + const senderAddress = options.senderAddress ?? 'notification@webservices.intecion.net' + const alertRecipient = options.alertRecipient ?? 'alerts@intecion.example' + const listed = new Set(options.allow ?? []) + const sites = new Map() + const tokens = new Map() // sha256(token) → host + const url = 'https://fake-relay.invalid/mail' + const seenRecipients = new Map>() + + const isListed = (host: string) => listed.has('*') || listed.has(host) + const newToken = () => `ims_${randomBytes(32).toString('base64url')}` + const blank = (host: string, product: string): Site => ({ + addresses: [], alerts: 0, bindOnUse: false, confirmations: new Map(), dayAccount: 0, dayOther: 0, host, hourAccount: 0, hourOther: 0, issuedAt: now(), keys: new Map(), product, state: 'pending', + }) + const giveToken = (site: Site): string => { + const token = newToken() + if (site.token) {site.previous = { token: site.token, until: now() + DAY }} + site.token = token + site.issuedAt = now() + tokens.set(sha256(token), site.host) + return token + } + + const relay: FakeRelay = { + allow: (host) => { + listed.add(host) + const site = sites.get(host) + if (site?.state === 'pending') {site.state = 'active'} + }, + backend: 'ok', + clientAddress: options.clientAddress ?? '203.0.113.10', + fetch: ((input: Request | string | URL, init?: RequestInit) => { + const target = typeof input === 'string' ? input : input instanceof URL ? input.href : input.url + if (!target.startsWith(url)) {return fetch(input, init)} + return relay.handle(new Request(input, init)) + }) as typeof fetch, + handle: async (request) => { + const held = await relay.intercept?.(request.clone()) + if (held === 'drop') {throw new TypeError('fetch failed')} + if (held) {return held} + return handle(request) + }, + issueToken: (host, product = 'iapl') => { + const site = sites.get(host) ?? blank(host, product) + sites.set(host, site) + site.state = site.state === 'suspended' ? 'suspended' : 'active' + site.bindOnUse = true + site.addresses = [] + return giveToken(site) + }, + limits: { ...DEFAULT_LIMITS, ...options.limits }, + listen: async (port = 0) => { + const { createServer } = await import('node:http') + const server = createServer((req, res) => { + const chunks: Buffer[] = [] + req.on('data', (c: Buffer) => chunks.push(c)) + req.on('end', () => { + void (async () => { + const headers = new Headers() + for (const [k, v] of Object.entries(req.headers)) { + if (typeof v === 'string') {headers.set(k, v)} + } + const method = (req.method ?? 'GET').toUpperCase() + const prefix = new URL(url).pathname + const path = (req.url ?? '/').startsWith(prefix) ? (req.url ?? '/').slice(prefix.length) : `/__outside${req.url ?? '/'}` + try { + const response = await relay.handle(new Request(`${url}${path}`, { body: method === 'GET' || method === 'HEAD' ? undefined : Buffer.concat(chunks), headers, method })) + response.headers.forEach((value, key) => res.setHeader(key, value)) + res.statusCode = response.status + res.end(Buffer.from(await response.arrayBuffer())) + } catch { + req.socket.destroy() + } + })() + }) + }) + await new Promise((resolve) => server.listen(port, '127.0.0.1', resolve)) + const address = server.address() + const listening = typeof address === 'object' && address ? address.port : port + return { close: () => new Promise((resolve) => server.close(() => resolve())), url: `http://127.0.0.1:${listening}${new URL(url).pathname}` } + }, + outbox: [], + requests: [], + reset: () => { + sites.clear() + tokens.clear() + seenRecipients.clear() + relay.outbox.length = 0 + relay.requests.length = 0 + relay.backend = 'ok' + relay.intercept = undefined + }, + setCallbackPath: (host, path) => { + const site = sites.get(host) ?? blank(host, 'iapl') + sites.set(host, site) + site.callbackPath = path + }, + setSite: (host, state, { product = 'iapl' } = {}) => { + const site = sites.get(host) ?? blank(host, product) + sites.set(host, site) + site.state = state + if (!site.addresses.includes(relay.clientAddress)) {site.addresses.push(relay.clientAddress)} + return site.token ?? giveToken(site) + }, + site: (host) => sites.get(host), + url, + } + + const json = (status: number, body: Record, headers: Record = {}) => + new Response(JSON.stringify(body), { headers: { 'cache-control': 'no-store', 'content-type': 'application/json', ...headers }, status }) + + const refused = (r: Refusal) => + json( + r.status, + { code: r.code, message: r.message, ok: false, retryable: r.extra.retryable ?? false, ...(r.extra.field ? { field: r.extra.field } : {}), ...(r.extra.limit ? { limit: r.extra.limit } : {}), ...(r.extra.reason ? { reason: r.extra.reason } : {}), ...(r.extra.retryAfter !== undefined ? { retryAfter: r.extra.retryAfter } : {}) }, + r.extra.retryAfter !== undefined ? { 'retry-after': String(r.extra.retryAfter) } : {}, + ) + + async function readJson(request: Request): Promise<{ bytes: Uint8Array; value: Record }> { + if (!(request.headers.get('content-type') ?? '').toLowerCase().startsWith('application/json')) { + throw new Refusal(415, 'unsupported-media-type', 'The body must be application/json.') + } + const bytes = new Uint8Array(await request.arrayBuffer()) + let value: unknown + try { + value = JSON.parse(new TextDecoder().decode(bytes)) + } catch { + throw invalid('body', 'The body is not JSON.') + } + if (!value || typeof value !== 'object' || Array.isArray(value)) {throw invalid('body', 'The body must be an object.')} + return { bytes, value: value as Record } + } + + function authenticate(request: Request, address: string): { current: boolean; site: Site } { + const match = /^bearer (\S+)$/i.exec(request.headers.get('authorization') ?? '') + const host = match ? tokens.get(sha256(match[1])) : undefined + const site = host ? sites.get(host) : undefined + const current = Boolean(site && match && site.token === match[1]) + const previous = Boolean(site && match && site.previous?.token === match[1] && site.previous.until > now()) + if (!site || (!current && !previous)) {throw new Refusal(401, 'invalid-token', 'No token, or one the service does not know.')} + if (site.bindOnUse && site.addresses.length === 0) {site.addresses.push(address)} + if (!site.addresses.includes(address)) {throw new Refusal(401, 'reverify', 'The token is good, but this server address is new for the site. Enrol again.')} + // used most recently last: beyond the limit the address used longest ago is dropped + site.addresses = [...site.addresses.filter((a) => a !== address), address] + return { current, site } + } + + async function enrol(request: Request, address: string): Promise { + const { value } = await readJson(request) + for (const key of Object.keys(value)) { + if (!['host', 'nonce', 'product', 'productVersion'].includes(key)) {throw invalid(key, `Unknown field "${key}".`)} + } + const { host, nonce, product, productVersion } = value + if (typeof host !== 'string') {throw invalid('host', 'host is required.')} + if (typeof nonce !== 'string' || !NONCE.test(nonce)) {throw invalid('nonce', 'nonce must be 32 to 128 characters of A-Z a-z 0-9 _ -.')} + if (product !== 'iapl' && product !== 'iawl') {throw invalid('product', 'Unknown product.')} + if (typeof productVersion !== 'string' || !VERSION.test(productVersion) || productVersion.length > 32) {throw invalid('productVersion', 'productVersion is required.')} + const local = Boolean(options.allowLocalHosts) && LOCAL_HOST.test(host) + if (!isPublicHost(host) && !local) {throw new Refusal(403, 'host-not-allowed', 'The host is not a public DNS name.')} + + const existing = sites.get(host) + if (existing?.state === 'suspended') {throw new Refusal(403, 'site-suspended', 'The site was stopped by Intecion.')} + const site = existing ?? blank(host, product) + const state = existing?.state === 'active' || isListed(host) ? 'active' : 'pending' + const token = newToken() + const path = site.callbackPath ?? (product === 'iawl' ? '/?rest_route=/iawl/v1/mail-relay/confirm' : '/api/iapl/mail-relay/confirm') + const target = `${local && !isPublicHost(host) ? 'http' : 'https'}://${host}${path}` + const body = JSON.stringify({ nonce, state, token }) + const fail = (reason: string) => new Refusal(422, 'callback-failed', `The site's confirm endpoint did not confirm (${reason}).`, { reason }) + let answer: Response + try { + const call = options.callSite ?? ((u, init) => fetch(u, { ...init, redirect: 'manual', signal: AbortSignal.timeout(8000) })) + answer = await call(target, { body, headers: { 'content-type': 'application/json' }, method: 'POST' }) + } catch (err) { + throw fail(err instanceof Error && err.name === 'TimeoutError' ? 'timeout' : 'unreachable') + } + if (answer.status >= 300 && answer.status < 400) {throw fail('redirect')} + if (answer.status !== 200) {throw fail('status')} + let confirmation: unknown + try { + const text = await answer.text() + confirmation = text.length <= 1024 ? (JSON.parse(text) as { confirmation?: unknown }).confirmation : undefined + } catch { + confirmation = undefined + } + if (confirmation !== sha256(`${nonce}.${token}`)) {throw fail('confirmation')} + + sites.set(host, site) + site.state = state + site.product = product + if (site.token) {site.previous = { token: site.token, until: now() + DAY }} + site.token = token + site.issuedAt = now() + site.bindOnUse = false + tokens.set(sha256(token), host) + site.addresses = [...site.addresses.filter((a) => a !== address), address].slice(-relay.limits.serverAddresses) + return json(200, { ok: true, state }) + } + + function validateSend(value: Record, site: Site) { + for (const key of Object.keys(value)) { + if (!SEND_FIELDS.has(key)) {throw invalid(key, `Unknown field "${key}".`)} + } + const kind = value.kind as MailKind + if (value.product !== 'iapl' && value.product !== 'iawl') {throw invalid('product', 'Unknown product.')} + if (typeof value.productVersion !== 'string' || !VERSION.test(value.productVersion)) {throw invalid('productVersion', 'productVersion is required.')} + if (!(MAIL_KINDS as readonly string[]).includes(kind)) {throw invalid('kind', 'Unknown kind.')} + const list = (field: 'bcc' | 'cc' | 'to'): string[] => { + const raw = value[field] + if (raw === undefined) {return []} + if (!Array.isArray(raw) || raw.some((a) => typeof a !== 'string' || a.length > 254 || !ADDRESS.test(a))) {throw invalid(field, `${field} must be a list of bare addresses.`)} + return raw as string[] + } + let to = list('to') + let cc = list('cc') + let bcc = list('bcc') + if (kind === 'security-alert') { + to = [alertRecipient] + cc = [] + bcc = [] + } else if (to.length === 0) {throw invalid('to', 'At least one recipient.')} + if (to.length + cc.length + bcc.length > relay.limits.recipientsPerMessage) { + throw new Refusal(422, 'too-many-recipients', `At most ${relay.limits.recipientsPerMessage} recipients a message.`) + } + const replyTo = value.replyTo + if (replyTo !== undefined && (typeof replyTo !== 'string' || !ADDRESS.test(replyTo))) {throw invalid('replyTo', 'replyTo must be one bare address.')} + const senderName = value.senderName + if (senderName !== undefined && (typeof senderName !== 'string' || [...senderName].length > 256)) {throw invalid('senderName', 'senderName must be at most 256 characters.')} + const subject = value.subject + if (typeof subject !== 'string' || subject.length === 0 || [...subject].length > 300) {throw invalid('subject', 'subject must be 1 to 300 characters.')} + if (UNSAFE_SUBJECT.test(subject)) {throw invalid('subject', 'subject must not contain line breaks, control or invisible characters.')} + if (subject.replace(/\s+/g, '').toLowerCase().startsWith(`[${RELAY_SERVICE_NAME.replace(/ /g, '').toLowerCase()}`)) { + throw invalid('subject', 'The subject must not start with the name of the mail service in brackets.') + } + const { html, text } = value + if (text !== undefined && (typeof text !== 'string' || !text)) {throw invalid('text', 'text must be a non-empty string.')} + if (html !== undefined && (typeof html !== 'string' || !html)) {throw invalid('html', 'html must be a non-empty string.')} + if (text === undefined && html === undefined) {throw invalid('text', 'text or html is required.')} + if (Buffer.byteLength(`${(text) ?? ''}${(html) ?? ''}`) > relay.limits.maxBodyBytes) { + throw new Refusal(413, 'too-large', 'The body is too large.', { limit: 'body' }) + } + const attachments: FakeRelayMail['attachments'] = [] + if (value.attachments !== undefined) { + if (!Array.isArray(value.attachments) || value.attachments.length > relay.limits.maxAttachments) {throw invalid('attachments', 'Too many attachments.')} + let total = 0 + value.attachments.forEach((raw: unknown, index: number) => { + const a = raw as { content?: unknown; contentType?: unknown; filename?: unknown } + if (!a || typeof a !== 'object' || Object.keys(a).some((k) => !['content', 'contentType', 'filename'].includes(k))) {throw invalid('attachments', 'Unknown field in an attachment.')} + if (typeof a.filename !== 'string' || !a.filename || a.filename.length > 255) {throw invalid('attachments', 'An attachment needs a filename.')} + if (typeof a.contentType !== 'string' || !CONTENT_TYPE.test(a.contentType)) {throw invalid('attachments', 'An attachment needs a content type.')} + if (typeof a.content !== 'string' || a.content.length < 4 || a.content.length % 4 !== 0 || !/^[A-Z0-9+/]+={0,2}$/i.test(a.content)) {throw invalid('attachments', 'content must be padded base64.')} + const refusedFile = new Refusal(422, 'attachment-refused', 'A file the service never carries, or a bad file name.', { field: `attachments[${index}]` }) + if (UNSAFE_NAME.test(a.filename) || /[/\\"<>|:*?]/.test(a.filename) || a.filename.startsWith('.')) {throw refusedFile} + if (a.filename.toLowerCase().split('.').slice(1).some((e) => EXECUTABLE.has(e))) {throw refusedFile} + const bytes = (a.content.length * 3) / 4 - (a.content.endsWith('==') ? 2 : a.content.endsWith('=') ? 1 : 0) + total += bytes + attachments.push({ bytes, contentType: a.contentType, filename: a.filename }) + }) + if (total > relay.limits.maxAttachmentBytes) {throw new Refusal(413, 'too-large', 'The attachments are too large.', { limit: 'attachments' })} + } + const asked = typeof senderName === 'string' ? senderName : '' + const accepted = asked ? guardName(asked, site.host) : null + const marked = [...bcc, ...cc, ...to].includes(alertRecipient) + return { + attachments, bcc, cc, html, kind, replaced: Boolean(asked) && !accepted, + replyTo, senderName: accepted ?? site.host, subject: marked ? `[${site.host}] ${subject}` : subject, text, to, + } + } + + /** The limits of contract §3.3, counted simply (no sliding window: `reset()` or the site's counters start them again). */ + function checkQuota(site: Site, kind: MailKind, recipients: string[]): { apply: () => void; left: { day: number; hour: number } } { + const { messagesPerDay: day, messagesPerHour: hour, newRecipientsPerDay, perRecipientPerDay, securityAlertsPerDay } = relay.limits + const over = (limit: string) => new Refusal(429, 'quota-exceeded', `The site reached its limit (${limit}).`, { limit }) + if (kind === 'security-alert') { + if (site.alerts >= securityAlertsPerDay) {throw over('alerts')} + return { apply: () => void (site.alerts += 1), left: { day: securityAlertsPerDay - site.alerts - 1, hour: securityAlertsPerDay - site.alerts - 1 } } + } + const share = (limit: number) => (kind === 'account' || limit < 5 ? limit : Math.floor((limit * 4) / 5)) + const usedHour = kind === 'account' ? site.hourAccount + site.hourOther : site.hourOther + const usedDay = kind === 'account' ? site.dayAccount + site.dayOther : site.dayOther + if (usedHour >= share(hour) || site.hourAccount + site.hourOther >= hour) {throw over('hour')} + if (usedDay >= share(day) || site.dayAccount + site.dayOther >= day) {throw over('day')} + if (kind === 'form-confirmation' && recipients.some((r) => (site.confirmations.get(r.toLowerCase()) ?? 0) >= perRecipientPerDay)) {throw over('recipient')} + const seen = seenRecipients.get(site.host) ?? new Set() + seenRecipients.set(site.host, seen) + const fresh = kind === 'account' ? [] : recipients.filter((r) => !seen.has(r.toLowerCase())) + const newToday = [...seen].filter((r) => r.startsWith('new:')).length + const newLimit = kind === 'form-confirmation' && newRecipientsPerDay >= 5 ? Math.floor((newRecipientsPerDay * 4) / 5) : newRecipientsPerDay + if (fresh.length && newToday + fresh.length > newLimit) {throw over('new-recipients')} + return { + apply: () => { + if (kind === 'account') { + site.hourAccount += 1 + site.dayAccount += 1 + } else { + site.hourOther += 1 + site.dayOther += 1 + } + if (kind === 'form-confirmation') { + for (const r of recipients) {site.confirmations.set(r.toLowerCase(), (site.confirmations.get(r.toLowerCase()) ?? 0) + 1)} + } + for (const r of fresh) { + seen.add(r.toLowerCase()) + seen.add(`new:${r.toLowerCase()}`) + } + }, + left: { day: Math.max(0, Math.min(share(day) - usedDay, day - site.dayAccount - site.dayOther) - 1), hour: Math.max(0, Math.min(share(hour) - usedHour, hour - site.hourAccount - site.hourOther) - 1) }, + } + } + + async function send(request: Request, address: string): Promise { + const { site } = authenticate(request, address) + if (site.state === 'pending') {throw new Refusal(403, 'site-pending', 'The site is waiting for approval by Intecion.')} + if (site.state === 'suspended') {throw new Refusal(403, 'site-suspended', 'The site was stopped by Intecion.')} + const key = request.headers.get('idempotency-key') ?? '' + if (!KEY.test(key)) {throw invalid('Idempotency-Key', 'Idempotency-Key must be 16 to 128 characters of A-Z a-z 0-9 _ -.')} + const { bytes, value } = await readJson(request) + const hash = sha256(bytes) + const known = site.keys.get(key) + if (known) { + if (known.hash !== hash) {throw new Refusal(409, 'idempotency-conflict', 'This Idempotency-Key was used for a different message.')} + return json(200, { ...known.answer, replayed: true }) + } + const mail = validateSend(value, site) + const quota = checkQuota(site, mail.kind, [...mail.to, ...mail.cc, ...mail.bcc]) + if (relay.backend === 'failure') {throw new Refusal(502, 'backend-failed', 'The mail back end failed.', { retryable: true })} + if (relay.backend === 'recipient-suppressed') {throw new Refusal(422, 'recipient-suppressed', 'The mail back end refuses one of the recipients. Nothing was sent.')} + quota.apply() + site.lastSenderName = mail.senderName + relay.outbox.push({ + attachments: mail.attachments, bcc: mail.bcc, cc: mail.cc, from: senderAddress, fromName: mail.senderName, + headers: { 'X-Intecion-Product': String(value.product), 'X-Intecion-Site': site.host }, host: site.host, + ...(mail.html ? { html: mail.html } : {}), kind: mail.kind, ...(mail.replyTo ? { replyTo: mail.replyTo } : {}), subject: mail.subject, ...(mail.text ? { text: mail.text } : {}), to: mail.to, + }) + const { messagesPerDay, messagesPerHour } = relay.limits + const answer = { + id: `fake-${relay.outbox.length}`, + messageId: ``, + ok: true, + quota: { day: { limit: messagesPerDay, remaining: quota.left.day }, hour: { limit: messagesPerHour, remaining: quota.left.hour } }, + replayed: false, + senderName: mail.senderName, + warnings: mail.replaced ? ['sender-name-replaced'] : [], + } + site.keys.set(key, { answer, hash }) + return json(200, answer) + } + + function status(request: Request, address: string): Response { + const { site } = authenticate(request, address) + const { messagesPerDay, messagesPerHour } = relay.limits + return json(200, { + host: site.host, + kinds: [...MAIL_KINDS], + limits: relay.limits, + ok: true, + product: site.product, + quota: { day: { limit: messagesPerDay, remaining: Math.max(0, messagesPerDay - site.dayAccount - site.dayOther) }, hour: { limit: messagesPerHour, remaining: Math.max(0, messagesPerHour - site.hourAccount - site.hourOther) } }, + sender: { address: senderAddress }, + ...(site.lastSenderName ? { senderName: site.lastSenderName } : {}), + service: { name: RELAY_SERVICE_NAME, contract: RELAY_CONTRACT_VERSION, version: '0.0.0-fake' }, + state: site.state, + token: { issuedAt: new Date(site.issuedAt).toISOString(), rotateAfter: new Date(site.issuedAt + 90 * DAY).toISOString() }, + }) + } + + async function handle(request: Request): Promise { + const path = new URL(request.url).pathname.slice(new URL(url).pathname.length) || '/' + const address = request.headers.get('x-fake-client-address') ?? relay.clientAddress + relay.requests.push({ address, method: request.method, path }) + try { + const fetchSite = request.headers.get('sec-fetch-site') + if (request.headers.has('origin') || (fetchSite !== null && fetchSite !== 'none')) {throw new Refusal(403, 'browser-not-allowed', 'The service is for servers, not browsers.')} + const routes: Record Promise | Response]> = { + '/health': ['GET', () => json(200, { ok: true })], + '/v1/enrol': ['POST', () => enrol(request, address)], + '/v1/revoke': ['POST', () => { + const { site } = authenticate(request, address) + for (const [hash, host] of tokens) { + if (host === site.host) {tokens.delete(hash)} + } + site.token = undefined + site.previous = undefined + return json(200, { ok: true }) + }], + '/v1/rotate': ['POST', () => { + const { current, site } = authenticate(request, address) + if (!current) {throw new Refusal(409, 'already-rotated', 'Only the current token can rotate.')} + const token = giveToken(site) + return json(200, { ok: true, previousValidUntil: new Date(now() + DAY).toISOString(), token }) + }], + '/v1/send': ['POST', () => send(request, address)], + '/v1/status': ['GET', () => status(request, address)], + } + const route = routes[path] + if (!route) {throw new Refusal(404, 'not-found', 'No such route.')} + if (route[0] !== request.method) {throw new Refusal(405, 'method-not-allowed', 'Wrong method.')} + return await route[1]() + } catch (err) { + if (err instanceof Refusal) {return refused(err)} + return refused(new Refusal(500, 'internal', 'A fault in the fake service.', { retryable: true })) + } + } + + return relay +} diff --git a/src/modules/email/relay/index.ts b/src/modules/email/relay/index.ts new file mode 100644 index 0000000..2cc78c7 --- /dev/null +++ b/src/modules/email/relay/index.ts @@ -0,0 +1,62 @@ +import type { BasePayload } from 'payload' + +import { type RelayOptions, resolveRelayOptions } from './options.js' +import { disconnectRelay as disconnect, enrolRelay as enrol, type EnrolResult, type RelayStatus, rotateRelayToken as rotate, getRelayStatus as status } from './session.js' + +export { RELAY_SENDER_ADDRESS, relayAdapter, relayAttachmentLimit, relaySenderName } from './adapter.js' +export type { RelayAdapterArgs } from './adapter.js' +export { relayRequest } from './client.js' +export type { RelayAnswer, RelayCall, RelayRefusal } from './client.js' +export { relayConfirmEndpoint } from './confirm.js' +export { + RELAY_BASE_URL, + RELAY_CONFIRM_PATH, + RELAY_CONTRACT_VERSION, + RELAY_DEFAULTS, + RELAY_KV_KEY, + RELAY_PRODUCT, + RELAY_SERVICE_NAME, + RELAY_STATUS_CODES, + relayStatusFor, +} from './constants.js' +export type { RelayStatusCode } from './constants.js' +export { MAIL_KIND, MAIL_KINDS, mailKindOf, markNextMail, runWithMailKind, withMailKind } from './kinds.js' +export type { MailKind } from './kinds.js' +export { bareAddress, bareAddresses, buildRelayMessage, cleanSubject } from './message.js' +export type { BuildRelayMessageArgs, BuiltRelayMessage, RelaySendRequest } from './message.js' +export { isPublicHost, relayHost, resolveRelayOptions } from './options.js' +export type { RelayOptions } from './options.js' +export { sendThroughRelay } from './send.js' +export type { RelaySendContext, RelaySendResult } from './send.js' +export { setRelayToken } from './session.js' +export type { EnrolResult, RelayStatus } from './session.js' + +const DISABLED = 'The mail service is switched off for this project (mail: { relay: false }).' + +function resolved(payload: BasePayload, options?: RelayOptions) { + const out = resolveRelayOptions(payload, options) + if (!out) {throw new Error(DISABLED)} + return out +} + +/** + * Enrols the site with the Intecion Notifications Webservice now (a deploy script, a "Connect" button + * of your own). `mailAdapter()` does this by itself on the first send. `force` also after a refusal a + * moment ago, or after "Disconnect". + */ +export const enrolRelay = (payload: BasePayload, options?: { force?: boolean } & RelayOptions): Promise => { + const { force, ...own } = options ?? {} + return enrol(payload, resolved(payload, Object.keys(own).length ? own : undefined), { force }) +} + +/** The site's state with the service — never the token. `refresh: true` asks the service; otherwise the stored state. */ +export const getRelayStatus = (payload: BasePayload, options?: { refresh?: boolean } & RelayOptions): Promise<{ error?: string } & RelayStatus> => { + const { refresh, ...own } = options ?? {} + return status(payload, resolved(payload, Object.keys(own).length ? own : undefined), { refresh }) +} + +/** Gives the site's token up on the service and forgets it; the site sends nothing through the service until it is connected again. */ +export const disconnectRelay = (payload: BasePayload, options?: RelayOptions): Promise => disconnect(payload, resolved(payload, options)) + +/** Asks for a new token now (the adapter does it by itself when the service says the token is due). */ +export const rotateRelayToken = (payload: BasePayload, options?: RelayOptions) => rotate(payload, resolved(payload, options), { force: true }) diff --git a/src/modules/email/relay/kinds.ts b/src/modules/email/relay/kinds.ts new file mode 100644 index 0000000..4fb8fee --- /dev/null +++ b/src/modules/email/relay/kinds.ts @@ -0,0 +1,58 @@ +import { AsyncLocalStorage } from 'node:async_hooks' + +/** + * What a message is for. The Intecion Notifications Webservice applies different limits per kind, so + * the kind has to be true: `account` only for mail to an account holder (password reset, invitation), + * `form-confirmation` for mail to an address a visitor typed, `form-notification` for a form's mail to + * the addresses written in the panel. Mail whose purpose is not known is `system`. + */ +export const MAIL_KINDS = ['form-notification', 'form-confirmation', 'account', 'security-alert', 'system', 'test'] as const +export type MailKind = (typeof MAIL_KINDS)[number] + +/** The key of the kind on a message. A symbol: no mail library reads it, JSON leaves it out, a spread keeps it. */ +export const MAIL_KIND = Symbol.for('iapl.mailKind') + +const isKind = (value: unknown): value is MailKind => typeof value === 'string' && (MAIL_KINDS as readonly string[]).includes(value) + +/** + * Marks a message for `payload.sendEmail`: + * await payload.sendEmail(withMailKind({ to, subject, html }, 'account')) + * Other transports (SMTP, Graph, a project's own adapter) ignore the mark. + */ +export function withMailKind(message: T, kind: MailKind): T { + return { ...message, [MAIL_KIND]: kind } +} + +/** The kind a message was marked with, if any. */ +export function mailKindOf(message: unknown): MailKind | undefined { + const kind = message && typeof message === 'object' ? (message as Record)[MAIL_KIND] : undefined + return isKind(kind) ? kind : undefined +} + +/** + * For mail the plugin does not compose itself (Payload's "forgot password" and "verify your e-mail"): + * the operation's hook says what the NEXT message of this request is, and the adapter takes it once. + */ +type MailContext = { kind: MailKind; sticky?: boolean; taken?: boolean; visitor?: string } +const context = new AsyncLocalStorage() + +/** + * Says that the next message sent in this request is of `kind`. Call it synchronously at the start of + * a hook (before the first `await`), so the operation that called the hook runs on in this context. + */ +export function markNextMail(kind: MailKind, extra: { visitor?: string } = {}): void { + context.enterWith({ kind, ...extra }) +} + +/** Runs `fn` with every message sent inside it marked as `kind` (a message's own mark still wins). */ +export function runWithMailKind(kind: MailKind, fn: () => T): T { + return context.run({ kind, sticky: true }, fn) +} + +/** The context of the message being sent now; a one-shot mark is used up by this call. */ +export function takeMailContext(): { kind: MailKind; visitor?: string } | undefined { + const current = context.getStore() + if (!current || current.taken) {return undefined} + if (!current.sticky) {current.taken = true} + return { kind: current.kind, visitor: current.visitor } +} diff --git a/src/modules/email/relay/message.ts b/src/modules/email/relay/message.ts new file mode 100644 index 0000000..2821602 --- /dev/null +++ b/src/modules/email/relay/message.ts @@ -0,0 +1,161 @@ +import type { SendEmailOptions } from 'payload' + +import { domainToASCII } from 'node:url' + +import type { MailKind } from './kinds.js' + +import { PLUGIN_VERSION } from '../../../version.js' +import { toGraphAttachments } from '../graphAttachments.js' +import { RELAY_PRODUCT, RELAY_SERVICE_NAME } from './constants.js' + +/** The body of `POST /v1/send` (contracts/mail-relay/schema.json, `SendRequest`). Closed: no other field exists. */ +export type RelaySendRequest = { + attachments?: { content: string; contentType: string; filename: string }[] + bcc?: string[] + cc?: string[] + html?: string + kind: MailKind + product: string + productVersion: string + replyTo?: string + senderName?: string + subject: string + text?: string + to?: string[] +} + +const ADDRESS = /^[\w!#$%&'*+/=?^`{|}~-]+(?:\.[\w!#$%&'*+/=?^`{|}~-]+)*@(?:[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?\.)+[A-Z][A-Z0-9-]{0,61}[A-Z0-9]$/i +const CONTENT_TYPE = /^[A-Z0-9][\w!#$&^.+-]*\/[A-Z0-9][\w!#$&^.+-]*$/i +/** What a subject may not contain (contract §3): control and invisible characters, except ZWJ, ZWNJ and the soft hyphen. */ +// three single code points on purpose (ZWNJ, ZWJ, soft hyphen), not a joined sequence +// eslint-disable-next-line no-misleading-character-class +const UNSAFE = /[\p{Cc}\p{Zl}\p{Zp}\p{Co}\p{Cs}]|(?![\u200C\u200D\u00AD])\p{Cf}/gu +const UNSAFE_STRICT = /[\p{Cc}\p{Zl}\p{Zp}\p{Co}\p{Cs}\p{Cf}]/gu + +/** One bare address (`name@domain`, ASCII; an international domain as punycode), or null. */ +export function bareAddress(value: unknown): null | string { + const raw = typeof value === 'string' ? value : value && typeof value === 'object' ? (value as { address?: unknown }).address : '' + if (typeof raw !== 'string') {return null} + const text = (raw.match(/<([^<>]+)>\s*$/)?.[1] ?? raw).trim() + const at = text.lastIndexOf('@') + if (at < 1) {return null} + const domain = /^[\x21-\x7e]+$/.test(text.slice(at + 1)) ? text.slice(at + 1) : domainToASCII(text.slice(at + 1)) + const address = `${text.slice(0, at)}@${domain}` + return address.length >= 6 && address.length <= 254 && ADDRESS.test(address) ? address : null +} + +/** + * Every address of a To / CC / BCC value as nodemailer takes it — a string ("Anna , b@y.pl"), + * an object, or a list of either — as bare addresses. `dropped` counts what was not an address. + */ +export function bareAddresses(value: unknown): { addresses: string[]; dropped: number } { + const parts: unknown[] = [] + for (const item of Array.isArray(value) ? value : value === undefined || value === null || value === '' ? [] : [value]) { + if (typeof item === 'string') { + // commas and semicolons separate addresses, except inside a quoted display name + parts.push(...(item.match(/(?:"[^"]*"|[^,;])+/g) ?? []).map((p) => p.trim()).filter(Boolean)) + } else {parts.push(item)} + } + const addresses: string[] = [] + let dropped = 0 + for (const part of parts) { + const address = bareAddress(part) + if (!address) {dropped += 1} + else if (!addresses.some((a) => a.toLowerCase() === address.toLowerCase())) {addresses.push(address)} + } + return { addresses, dropped } +} + +const codePoints = (text: string, max: number) => { + const points = [...text] + return points.length > max ? points.slice(0, max).join('') : text +} + +/** + * A subject the service accepts. It refuses, it does not repair — and a subject is often a visitor's + * own words — so line breaks become spaces, control and invisible characters go, the length is cut to + * 300 characters, and a subject that would start like the service's own notices loses its bracket. + */ +export function cleanSubject(subject: unknown): string { + let text = typeof subject === 'string' ? subject : '' + text = text.replace(/[\r\n\t\u2028\u2029]+/g, ' ').replace(UNSAFE, '').replace(/ {2,}/g, ' ').trim() + if (text.replace(/\s+/g, '').toLowerCase().startsWith(`[${RELAY_SERVICE_NAME.replace(/ /g, '').toLowerCase()}`)) {text = text.replace(/^\s*\[\s*/, '')} + return codePoints(text, 300) || '(no subject)' +} + +/** A file name the service accepts: no path, no quotes, nothing invisible. */ +export function cleanFilename(name: unknown): string { + const base = (typeof name === 'string' ? name : '').split(/[/\\]/).pop() ?? '' + const clean = base.replace(UNSAFE_STRICT, '').replace(/["<>|:*?]/g, '_').replace(/^\.+/, '').trim() + return codePoints(clean, 255) || 'attachment' +} + +const bodyText = (value: unknown): string | undefined => + typeof value === 'string' ? value || undefined : Buffer.isBuffer(value) ? value.toString('utf8') || undefined : undefined + +export type BuildRelayMessageArgs = { + /** What the message is for. Default `system`. */ + kind?: MailKind + product?: string + productVersion?: string + /** Used when the message names no reply address of its own (the panel's "Sender address"). */ + replyTo?: null | string + /** The display name (the panel's "Sender name", else the site name). Without one the mail leaves under the site's host. */ + senderName?: null | string +} + +export type BuiltRelayMessage = + | { dropped: number; ok: true; request: RelaySendRequest } + | { ok: false; problem: string } + +/** + * A Payload / nodemailer message as the request the service takes. `from` and free headers are left + * out: the service fixes the sender address, and there is no field for either. + */ +export function buildRelayMessage(message: SendEmailOptions, args: BuildRelayMessageArgs = {}): BuiltRelayMessage { + const m = message as Record + const kind = args.kind ?? 'system' + const to = bareAddresses(m.to) + const cc = bareAddresses(m.cc) + const bcc = bareAddresses(m.bcc) + if (kind !== 'security-alert' && to.addresses.length === 0) {return { ok: false, problem: 'The message has no valid recipient address.' }} + + const text = bodyText(m.text) + const html = bodyText(m.html) + if (!text && !html) {return { ok: false, problem: 'The message has no text and no HTML body.' }} + + const all = toGraphAttachments(message) + if (all === null) {return { ok: false, problem: 'An attachment has content the mail service cannot carry (pass a Buffer or a string).' }} + // an empty file cannot be written in the request (base64 of at least one byte) and carries nothing + const files = all.filter((file) => file.content.length > 0) + + const replyTo = bareAddresses(m.replyTo).addresses[0] ?? bareAddress(args.replyTo ?? '') ?? undefined + const senderName = typeof args.senderName === 'string' ? codePoints(args.senderName.replace(UNSAFE_STRICT, ' ').replace(/ {2,}/g, ' ').trim(), 256) : '' + + const request: RelaySendRequest = { + kind, + product: args.product ?? RELAY_PRODUCT, + productVersion: args.productVersion ?? PLUGIN_VERSION, + ...(kind === 'security-alert' && !to.addresses.length ? {} : { to: to.addresses }), + ...(cc.addresses.length ? { cc: cc.addresses } : {}), + ...(bcc.addresses.length ? { bcc: bcc.addresses } : {}), + ...(replyTo ? { replyTo } : {}), + ...(senderName ? { senderName } : {}), + subject: cleanSubject(m.subject), + ...(text ? { text } : {}), + ...(html ? { html } : {}), + ...(files.length + ? { + attachments: files.map((file) => { + const type = file.contentType.split(';')[0].trim() + return { + content: file.content.toString('base64'), + contentType: CONTENT_TYPE.test(type) && type.length <= 127 ? type : 'application/octet-stream', + filename: cleanFilename(file.name), + } + }), + } + : {}), + } + return { dropped: to.dropped + cc.dropped + bcc.dropped, ok: true, request } +} diff --git a/src/modules/email/relay/options.ts b/src/modules/email/relay/options.ts new file mode 100644 index 0000000..1375bf4 --- /dev/null +++ b/src/modules/email/relay/options.ts @@ -0,0 +1,97 @@ +import type { BasePayload, SendEmailOptions } from 'payload' + +import type { MailKind } from './kinds.js' + +import { RELAY_BASE_URL } from './constants.js' + +/** + * `iapl({ mail: { relay } })` and `mailAdapter({ relay })`. Every key is optional; `relay: false` + * switches the transport, the enrolment and the confirm route off. + */ +export type RelayOptions = { + /** + * "Forgot password" is a visitor's lever like a form: the service lets `account` mail use the site's + * whole hour. So the plugin limits it itself, per address and per visitor (the request's address). + * Default 5 per address and 10 per visitor an hour; `false` = no limit of the plugin's. + */ + accountMail?: { perAddress?: number; perVisitor?: number; windowMinutes?: number } | false + /** Calls to the public confirm route per address. Default 10 a minute. */ + confirmRateLimit?: { max?: number; windowMs?: number } + /** + * `'auto'` (default): the site enrols by itself on the first send without a token, and again after + * the service asks for it. `'manual'`: only "Connect" in the panel or `enrolRelay()` enrols. + * `false`: never — the token comes from `token` or `setRelayToken()`. + */ + enrol?: 'auto' | 'manual' | false + /** For tests and special networks: the `fetch` the service is called with. */ + fetchImpl?: typeof fetch + /** + * The site's public host, as the service calls it back (`example.com`). Default: the host of + * `serverURL`. Enrol the host the site really answers on (no redirect is followed). + */ + host?: string + /** The kind of a message that carries no mark of its own; return undefined to keep the default (`system`). */ + kind?: (message: SendEmailOptions) => MailKind | undefined + /** + * The wait before the next attempt when the service names none, in ms, multiplied by the attempt's + * number. Default 1000. The ten seconds of waiting in all are not changed by it. Mostly for tests. + */ + retryBackoffMs?: number + /** The display name of outgoing mail. Default: the panel's "Sender name", else the site name. */ + senderName?: ((args: { payload: BasePayload }) => null | Promise | string | undefined) | string + /** One attempt of a send, in ms. Default 30 000 (a 10 MB attachment has to fit). */ + timeoutMs?: number + /** + * A token from elsewhere (a relay of your own, or a secret of your deployment). When set, the stored + * token is not used and the site does not enrol. + */ + token?: (() => Promise | string | undefined) | string + /** Base address of the service. Default `https://webservices.intecion.net/mail`. A relay of your own speaks the same contract. */ + url?: string +} + +export type ResolvedRelayOptions = { ownUrl: boolean; url: string } & Omit + +type PluginMail = { graphDeprecationWarning?: boolean; relay?: false | RelayOptions } + +/** What `iapl({ mail })` left in the config for the adapter (`config.custom.iapl.mail`). */ +export function pluginMailOptions(payload: Pick): PluginMail { + return ((payload.config?.custom as { iapl?: { mail?: PluginMail } } | undefined)?.iapl?.mail ?? {}) +} + +/** + * The options in effect: the adapter's own `relay` argument over the plugin option. `null` = the relay + * is switched off. + */ +export function resolveRelayOptions(payload: Pick, own?: false | RelayOptions): null | ResolvedRelayOptions { + const fromPlugin = pluginMailOptions(payload).relay + if (own === false || (own === undefined && fromPlugin === false)) {return null} + const merged: RelayOptions = { ...(fromPlugin || {}), ...(own || {}) } + const url = (merged.url ?? RELAY_BASE_URL).replace(/\/+$/, '') + return { ...merged, ownUrl: url !== RELAY_BASE_URL, url } +} + +const LABEL = /^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/ +const PRIVATE_SUFFIXES = ['localhost', 'local', 'localdomain', 'internal', 'intranet', 'private', 'lan', 'home', 'corp', 'test', 'invalid', 'example', 'onion', 'arpa'] + +/** A public DNS name the service can call back: no address literal, no port, no single label, no private suffix. */ +export function isPublicHost(host: string): boolean { + if (host.length < 4 || host.length > 253) {return false} + const labels = host.split('.') + if (labels.length < 2 || !labels.every((l) => LABEL.test(l)) || !/^[a-z]/.test(labels[labels.length - 1])) {return false} + return !PRIVATE_SUFFIXES.some((s) => host === s || host.endsWith(`.${s}`)) +} + +/** + * The host this site enrols as: `relay.host`, else the host of `serverURL` — lowercase, punycode, + * without scheme, path or the default port. Empty when neither is set. + */ +export function relayHost(payload: Pick, options: Pick): string { + const raw = (options.host ?? payload.config?.serverURL ?? '').trim() + if (!raw) {return ''} + try { + return new URL(/^[a-z][a-z0-9+.-]*:\/\//i.test(raw) ? raw : `https://${raw}`).host.toLowerCase() + } catch { + return '' + } +} diff --git a/src/modules/email/relay/panel.ts b/src/modules/email/relay/panel.ts new file mode 100644 index 0000000..9028bbe --- /dev/null +++ b/src/modules/email/relay/panel.ts @@ -0,0 +1,147 @@ +import type { Endpoint, PayloadRequest } from 'payload' + +import type { IntegrationStatus } from '../../integrations/status.js' +import type { RelayOptions } from './options.js' + +import { userMeetsRole } from '../../access/predicates.js' +import { serverText } from '../../integrations/texts.js' +import { getSiteIntegrations } from '../../payload/index.js' +import { graphAvailable, type MailTransport, resolveMailTransport } from '../mailAdapter.js' +import { RELAY_SENDER_ADDRESS } from './adapter.js' +import { RELAY_CONFIRM_PATH, RELAY_CONNECT_PATH, RELAY_DISCONNECT_PATH, RELAY_STATUS_PATH } from './constants.js' +import { resolveRelayOptions } from './options.js' +import { disconnectRelay, enrolRelay, type EnrolResult, getRelayStatus, LOCAL_CODES, type RelayStatus, setRelayToken } from './session.js' + +type Settings = { + emailStatus?: IntegrationStatus | null + emailTransport?: 'graph' | 'smtp' | null + smtpFromAddress?: null | string + smtpHost?: null | string + smtpPassword?: null | string + smtpUser?: null | string +} + +/** What the state block on the e-mail tab shows. Never a token, never a password. */ +export type MailPanelState = { + /** The address the service calls this site back at. */ + confirmUrl?: string + /** Enabled in the project (`mail.relay` is not `false`). */ + relay: ({ senderAddress: string } & RelayStatus) | null + replyAddress: null | string + transport: MailTransport +} + +type I18n = Parameters[0] + +const json = (body: unknown, status = 200) => Response.json(body, { headers: { 'cache-control': 'no-store' }, status }) + +function refuse(req: PayloadRequest): null | Response { + const i18n = req.i18n as I18n + if (!req.user) {return json({ error: serverText(i18n, 'mailRelayLoggedOut'), ok: false }, 401)} + if (!userMeetsRole(req, 'admin')) {return json({ error: serverText(i18n, 'mailRelayForbidden'), ok: false }, 403)} + return null +} + +/** The transport in effect and the site's state with the service, for the panel and the doctor. */ +export async function mailPanelState(req: Pick, own: false | RelayOptions | undefined, { refresh = false }: { refresh?: boolean } = {}): Promise { + const { payload } = req + const settings = await getSiteIntegrations(payload) + const options = resolveRelayOptions(payload, own) + const transport = resolveMailTransport(settings, { graphEnv: graphAvailable(), relay: Boolean(options) }) + const status = options ? await getRelayStatus(payload, options, { refresh: refresh && transport === 'relay' }) : null + const api = payload.config.routes?.api ?? '/api' + return { + ...(status?.host ? { confirmUrl: `https://${status.host}${api}${RELAY_CONFIRM_PATH}` } : {}), + relay: status ? { ...status, senderAddress: status.senderAddress ?? RELAY_SENDER_ADDRESS } : null, + replyAddress: typeof settings.smtpFromAddress === 'string' && settings.smtpFromAddress.trim() ? settings.smtpFromAddress.trim() : null, + transport, + } +} + +/** Why an enrolment was refused, in the admin's language. */ +export function enrolRefusalText(i18n: I18n, refusal: { code: string; message?: string; reason?: string }, state: Pick): string { + switch (refusal.code) { + case 'callback-failed': + return serverText(i18n, 'mailRelayRefusedCallback', { reason: refusal.reason ?? '', url: state.confirmUrl ?? '' }) + case 'enrolment-closed': + return serverText(i18n, 'mailRelayRefusedClosed') + case 'host-not-allowed': + return serverText(i18n, 'mailRelayRefusedHost', { host: state.relay?.host ?? '' }) + case LOCAL_CODES.noHost: + return serverText(i18n, 'mailRelayRefusedNoHost') + case 'site-suspended': + return serverText(i18n, 'mailRelayStateSuspended') + default: + return serverText(i18n, 'mailRelayRefusedOther', { message: refusal.message ?? refusal.code }) + } +} + +async function answer(req: PayloadRequest, own: false | RelayOptions | undefined, extra: Record = {}, refresh = false): Promise { + const state = await mailPanelState(req, own, { refresh }) + const refusal = state.relay?.refusal + return json({ ok: true, ...state, ...(refusal ? { refusalText: enrolRefusalText(req.i18n as I18n, refusal, state) } : {}), ...extra }) +} + +/** + * The three admin-only routes behind the state block on Site integrations → E-mail sending: + * GET /api/iapl/mail-relay/status the transport in effect and the site's state (`?refresh=1` asks the service) + * POST /api/iapl/mail-relay/connect enrol now — or, with `{ token }`, store a token Intecion issued by hand + * POST /api/iapl/mail-relay/disconnect give the token up; nothing is sent through the service until "Connect again" + * None of them ever answers with a token. + */ +export function relayPanelEndpoints(own?: false | RelayOptions): Endpoint[] { + return [ + { + handler: async (req) => { + const refused = refuse(req) + if (refused) {return refused} + return answer(req, own, {}, new URL(req.url ?? 'http://x').searchParams.get('refresh') === '1') + }, + method: 'get', + path: RELAY_STATUS_PATH, + }, + { + handler: async (req) => { + const refused = refuse(req) + if (refused) {return refused} + const i18n = req.i18n as I18n + const options = resolveRelayOptions(req.payload, own) + if (!options) {return json({ error: serverText(i18n, 'mailRelayOff'), ok: false }, 409)} + let body: { token?: unknown } = {} + try { + body = ((await req.json?.()) ?? {}) as { token?: unknown } + } catch { + /* no body: plain "connect again" */ + } + if (typeof body.token === 'string' && body.token.trim()) { + try { + await setRelayToken(req.payload, body.token.trim()) + } catch { + return json({ error: serverText(i18n, 'mailRelayTokenInvalid'), ok: false }, 400) + } + return answer(req, own, { message: serverText(i18n, 'mailRelayConnected') }, true) + } + const result: EnrolResult = await enrolRelay(req.payload, options, { force: true }) + if (!result.ok) { + const state = await mailPanelState(req, own) + return json({ ...state, error: serverText(i18n, 'mailRelayConnectFailed', { reason: enrolRefusalText(i18n, result, state) }), ok: false }, 502) + } + return answer(req, own, { message: serverText(i18n, result.state === 'pending' ? 'mailRelayStatePending' : 'mailRelayConnected') }, true) + }, + method: 'post', + path: RELAY_CONNECT_PATH, + }, + { + handler: async (req) => { + const refused = refuse(req) + if (refused) {return refused} + const options = resolveRelayOptions(req.payload, own) + if (!options) {return json({ error: serverText(req.i18n as I18n, 'mailRelayOff'), ok: false }, 409)} + await disconnectRelay(req.payload, options) + return answer(req, own, { message: serverText(req.i18n as I18n, 'mailRelayDisconnected') }) + }, + method: 'post', + path: RELAY_DISCONNECT_PATH, + }, + ] +} diff --git a/src/modules/email/relay/send.ts b/src/modules/email/relay/send.ts new file mode 100644 index 0000000..9052c6b --- /dev/null +++ b/src/modules/email/relay/send.ts @@ -0,0 +1,237 @@ +import type { BasePayload, SendEmailOptions } from 'payload' + +import { createHash, randomBytes } from 'node:crypto' + +import type { ResolvedRelayOptions } from './options.js' + +import { consumeRateLimit } from '../../shared/rateLimit.js' +import { type RelayAnswer, type RelayRefusal, relayRequest } from './client.js' +import { RELAY_DEFAULTS, type RelayStatusCode, relayStatusFor } from './constants.js' +import { type MailKind, mailKindOf, takeMailContext } from './kinds.js' +import { buildRelayMessage, type RelaySendRequest } from './message.js' +import { LOCAL_CODES, refreshRelayStatus, rotateRelayToken, type TokenUse, withRelayToken } from './session.js' +import { readRelayStore, sha256Hex, updateRelayStore } from './store.js' + +export type RelaySendResult = + | { + /** The service's code, or one of this client's (`client-…`). */ + cause: string + /** A status code for `emailStatus` (RELAY_STATUS_CODES). */ + code: RelayStatusCode + /** + * `false`: the message MAY have been sent — the service gave no answer, or cannot say yet. Send + * the same message again and this client uses the same key and bytes, so no second mail can go out. + */ + confirmed: boolean + /** For the panel status and the log. English; never shown to a visitor. */ + detail: string + error: string + sent: false + transport: 'relay' + } + | { + /** The service's id of the message in its log. */ + id: string + kind: MailKind + messageId?: string + /** true: this message had been sent before (same key and bytes); no second mail went out. */ + replayed: boolean + /** The name the mail left under. */ + senderName: string + sent: true + transport: 'relay' + warnings: string[] + } + +type SendBody = { id?: string; messageId?: string; replayed?: boolean; senderName?: string; warnings?: unknown } + +const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms)) + +/** + * Messages whose outcome the service never confirmed, by the hash of their bytes: sent again within + * 24 hours they go out under the SAME key, so the service answers with what happened to the first + * attempt instead of sending a second mail. Per process; a message of a new content always gets a new key. + */ +const unconfirmed = new Map() +const DAY = 24 * 60 * 60_000 + +function keyFor(hash: string): string { + const now = Date.now() + for (const [h, entry] of unconfirmed) { + if (now - entry.at > DAY) {unconfirmed.delete(h)} + } + return unconfirmed.get(hash)?.key ?? randomBytes(24).toString('base64url') +} + +/** For tests. */ +export function clearUnconfirmedRelayMessages(): void { + unconfirmed.clear() +} + +const failure = (code: RelayStatusCode, cause: string, detail: string, confirmed = true): { sent: false } & RelaySendResult => ({ + cause, + code, + confirmed, + detail, + error: confirmed ? 'The e-mail was not sent.' : 'The e-mail may not have been sent: the mail service did not confirm it.', + sent: false, + transport: 'relay', +}) + +function describeRefusal(answer: RelayRefusal): { sent: false } & RelaySendResult { + const extra = [answer.limit ? `limit: ${answer.limit}` : '', answer.reason ? `reason: ${answer.reason}` : '', answer.field ? `field: ${answer.field}` : ''].filter(Boolean).join(', ') + const said = `${answer.code}${extra ? ` (${extra})` : ''}: ${answer.message}` + if (answer.code === LOCAL_CODES.disconnected) {return failure('relay-disconnected', answer.code, answer.message)} + if (answer.code === LOCAL_CODES.noToken || answer.code === LOCAL_CODES.noHost) {return failure('relay-refused', answer.code, answer.message)} + // No answer at all, or a send the service cannot report on yet: it may be out. + if (answer.noAnswer || answer.code === 'in-progress') {return failure('relay-not-confirmed', answer.code, `Not confirmed — the message may have been sent. ${said}`, false)} + if (answer.code === 'callback-failed' && answer.reason === 'status') { + return failure('relay-refused', answer.code, `${said} If the site serves its API at another path, ask Intecion to set this site's confirm address.`) + } + if (answer.code === 'invalid-token' || answer.code === 'reverify') {return failure('relay-refused', answer.code, said)} + const status = relayStatusFor(answer.code, answer.retryable) + // The mail back end failed without saying whether the message can still go out. + if (status === 'relay-unreachable' && !['enrolment-in-progress', 'rate-limited', 'unavailable'].includes(answer.code)) { + return failure(status, answer.code, `Probably not sent. ${said}`) + } + return failure(status, answer.code, said) +} + +export type RelaySendContext = { + /** The panel's "Sender address": where replies go when the message names no reply address. */ + replyTo?: null | string + /** The panel's "Sender name", else the site name. */ + senderName?: null | string +} + +/** + * One message through the service. Never throws. + * + * The message is encoded ONCE and 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 (which win over the service's `retryAfter`), and only after an answer that says + * `retryable` or after no answer. An enrolment made on the way is not one of the three. + */ +export async function sendThroughRelay(payload: BasePayload, options: ResolvedRelayOptions, message: SendEmailOptions, context: RelaySendContext = {}): Promise { + const marked = takeMailContext() + const kind = mailKindOf(message) ?? marked?.kind ?? options.kind?.(message) ?? 'system' + + const built = buildRelayMessage(message, { kind, replyTo: context.replyTo, senderName: context.senderName }) + if (!built.ok) {return failure('relay-error', 'client-invalid-message', built.problem)} + const request: RelaySendRequest = built.request + if (built.dropped) {payload.logger.warn(`[iapl] mail service: ${built.dropped} recipient value(s) were not e-mail addresses and were left out.`)} + + // A visitor can ask for account mail as often as they like; the service does not limit it per address. + if (kind === 'account' && options.accountMail !== false) { + const own = options.accountMail ?? {} + const windowMs = (own.windowMinutes ?? RELAY_DEFAULTS.accountMail.windowMinutes) * 60_000 + const perAddress = own.perAddress ?? RELAY_DEFAULTS.accountMail.perAddress + const checks = [ + ...(marked?.visitor ? [{ key: `visitor:${marked.visitor}`, max: own.perVisitor ?? RELAY_DEFAULTS.accountMail.perVisitor }] : []), + ...[...(request.to ?? []), ...(request.cc ?? []), ...(request.bcc ?? [])].map((address) => ({ key: `to:${sha256Hex(address.toLowerCase())}`, max: perAddress })), + ] + for (const check of checks) { + const { ok } = await consumeRateLimit({ ...check, scope: 'mail-relay-account', windowMs }) + if (!ok) { + payload.logger.warn(`[iapl] mail service: an account e-mail was held back (more than ${check.max} ${check.key.startsWith('visitor:') ? 'from one visitor' : 'to one address'} in the window; mail.relay.accountMail).`) + return failure('relay-quota', 'client-account-mail-limit', 'Too many account e-mails to one address or from one visitor; held back by the site (mail.relay.accountMail).') + } + } + } + + const stored = await readRelayStore(payload) + 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. + const bytes = (request.attachments ?? []).reduce((sum, a) => sum + Math.floor((a.content.length * 3) / 4) - (a.content.endsWith('==') ? 2 : a.content.endsWith('=') ? 1 : 0), 0) + if (typeof limits.maxAttachmentBytes === 'number' && bytes > limits.maxAttachmentBytes) { + return failure('relay-too-large', 'too-large', `too-large (limit: attachments): the files are ${bytes} bytes, the mail service carries ${limits.maxAttachmentBytes}.`) + } + const recipients = (request.to?.length ?? 0) + (request.cc?.length ?? 0) + (request.bcc?.length ?? 0) + if (typeof limits.recipientsPerMessage === 'number' && recipients > limits.recipientsPerMessage) { + return failure('relay-quota', 'too-many-recipients', `too-many-recipients: ${recipients} recipients, the mail service allows ${limits.recipientsPerMessage} a message.`) + } + } + + if (stored.service?.rotateAfter && Date.parse(stored.service.rotateAfter) <= Date.now()) { + await rotateRelayToken(payload, options).catch(() => undefined) + } + + const body = Buffer.from(JSON.stringify(request), 'utf8') + const hash = createHash('sha256').update(body).digest('hex') + const idempotencyKey = keyFor(hash) + const use: TokenUse = {} + const budget = RELAY_DEFAULTS.waitBudgetMs + let attempts = 0 + let waited = 0 + let answer: RelayAnswer = { code: 'unavailable', message: 'not tried', noAnswer: false, ok: false, retryable: false, status: 0 } + + while (attempts < RELAY_DEFAULTS.attempts) { + answer = await withRelayToken( + payload, + options, + (token) => { + attempts += 1 + return relayRequest({ body, fetchImpl: options.fetchImpl, idempotencyKey, method: 'POST', path: '/v1/send', timeoutMs: options.timeoutMs ?? RELAY_DEFAULTS.attemptTimeoutMs, token, url: options.url }) + }, + use, + ) + if (answer.ok || !answer.retryable || attempts >= RELAY_DEFAULTS.attempts) {break} + const wait = answer.retryAfter !== undefined ? answer.retryAfter * 1000 : attempts * (options.retryBackoffMs ?? 1000) + // The ten seconds win over retryAfter: stop at once and report. + if (waited + wait > budget) {break} + await sleep(wait) + waited += wait + } + + if (answer.ok) { + unconfirmed.delete(hash) + const warnings = Array.isArray(answer.body.warnings) ? answer.body.warnings.filter((w): w is string => typeof w === 'string') : [] + const used = typeof answer.body.senderName === 'string' ? answer.body.senderName : '' + const replaced = warnings.includes('sender-name-replaced') + try { + const now = await readRelayStore(payload) + const known = now.nameReplaced + const nameChanged = replaced ? known?.used !== used || known?.asked !== (request.senderName ?? '') : Boolean(known) + if (nameChanged || now.state !== 'active' || now.refusal) { + await updateRelayStore(payload, (current) => ({ + ...current, + nameReplaced: replaced ? { asked: request.senderName ?? '', at: new Date().toISOString(), used } : null, + refusal: null, + state: 'active', + })) + } + if (replaced && nameChanged) { + payload.logger.warn(`[iapl] mail service: the sender name was not accepted; the e-mail left under "${used}". Choose another name in Site integrations → E-mail sending.`) + } + // Limits, quota and the day to rotate: read again once they are an hour old. Awaited (one short GET an + // hour): a write to the store that lands after the request has ended could undo a "Disconnect" or a rotation. + if (!now.service || Date.now() - Date.parse(now.service.fetchedAt) > RELAY_DEFAULTS.statusTtlMs) { + await refreshRelayStatus(payload, options) + } + } catch { + /* bookkeeping must not turn a sent mail into a failed one */ + } + return { + id: typeof answer.body.id === 'string' ? answer.body.id : '', + kind, + ...(typeof answer.body.messageId === 'string' ? { messageId: answer.body.messageId } : {}), + replayed: answer.body.replayed === true, + senderName: used, + sent: true, + transport: 'relay', + warnings, + } + } + + const result = describeRefusal(answer) + // Not confirmed, or failed in a way the back end does not explain: the same key if this message is tried again. + if (!result.confirmed || result.detail.startsWith('Probably not sent')) {unconfirmed.set(hash, { at: Date.now(), key: idempotencyKey })} + else {unconfirmed.delete(hash)} + if (answer.code === 'site-pending' || answer.code === 'site-suspended') { + const state = answer.code === 'site-pending' ? 'pending' : 'suspended' + if (stored.state !== state) {await updateRelayStore(payload, (current) => ({ ...current, state })).catch(() => undefined)} + } + payload.logger.error(`[iapl] mail service: e-mail ${result.confirmed ? 'not sent' : 'not confirmed'} (${result.code}; ${answer.code}${answer.limit ? `, ${answer.limit}` : ''}${answer.reason ? `, ${answer.reason}` : ''}).`) + return result +} diff --git a/src/modules/email/relay/session.ts b/src/modules/email/relay/session.ts new file mode 100644 index 0000000..2676954 --- /dev/null +++ b/src/modules/email/relay/session.ts @@ -0,0 +1,359 @@ +import type { BasePayload } from 'payload' + +import { randomBytes } from 'node:crypto' + +import type { ResolvedRelayOptions } from './options.js' + +import { PLUGIN_VERSION } from '../../../version.js' +import { type RelayAnswer, type RelayRefusal, relayRequest } from './client.js' +import { RELAY_DEFAULTS, RELAY_PRODUCT, type RelayStatusCode, relayStatusFor } from './constants.js' +import { isPublicHost, relayHost } from './options.js' +import { + clearRelayStore, + dropRelayCandidate, + holdNonce, + readRelayCandidate, + readRelayStore, + type RelaySiteState, + type RelayStored, + releaseNonce, + sha256Hex, + updateRelayStore, +} from './store.js' + +const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms)) +const refusal = (code: string, message: string, extra: Partial = {}): RelayRefusal => ({ code, message, noAnswer: false, ok: false, retryable: false, status: 0, ...extra }) + +/** Codes this client makes up for what never reached the service. */ +export const LOCAL_CODES = { + disconnected: 'client-disconnected', + noHost: 'client-no-host', + noToken: 'client-no-token', +} as const + +export type EnrolResult = + | { code: string; message: string; ok: false; reason?: string; retryable: boolean; status: RelayStatusCode } + | { ok: true; state: RelaySiteState } + +const enrolFailure = (answer: RelayRefusal): { ok: false } & EnrolResult => ({ + code: answer.code, + message: answer.message, + ok: false, + ...(answer.reason ? { reason: answer.reason } : {}), + retryable: answer.retryable, + status: + answer.code === LOCAL_CODES.disconnected ? 'relay-disconnected' + : answer.code === LOCAL_CODES.noHost || answer.code === LOCAL_CODES.noToken ? 'relay-refused' + : relayStatusFor(answer.code, answer.retryable), +}) + +const inFlight = new WeakMap>() + +/** + * Enrols this site with the service: makes a nonce, asks, and the service calls the site's confirm + * route with the token before it answers (confirm.ts stores it beside the token in use). Only when the + * service answers `200` does that token become the one in use. One enrolment at a time per process. + * + * `force`: also when an earlier enrolment was refused a moment ago, or the site was disconnected. + */ +export function enrolRelay(payload: BasePayload, options: ResolvedRelayOptions, { force = false }: { force?: boolean } = {}): Promise { + const running = inFlight.get(payload) + if (running) {return running} + const run = enrolOnce(payload, options, force).finally(() => inFlight.delete(payload)) + inFlight.set(payload, run) + return run +} + +async function enrolOnce(payload: BasePayload, options: ResolvedRelayOptions, force: boolean): Promise { + const stored = await readRelayStore(payload) + 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 })) + } + const host = relayHost(payload, options) + if (!host) { + return enrolFailure(refusal(LOCAL_CODES.noHost, 'The site does not know its public address: set serverURL in the Payload config, or mail.relay.host.')) + } + // Intecion's service calls back public DNS names only; a relay of one's own (or the local stand-in) decides itself. + if (!options.ownUrl && !isPublicHost(host)) { + return enrolFailure(refusal('host-not-allowed', `"${host}" is not a public host name, so the mail service cannot call this site back.`)) + } + + let answer: RelayAnswer<{ state?: string }> | undefined + let nonce = '' + for (let attempt = 0; attempt < 2; attempt++) { + nonce = randomBytes(32).toString('base64url') + const nonceHash = await holdNonce(payload, nonce, RELAY_DEFAULTS.nonceTtlMs) + answer = await relayRequest<{ state?: string }>({ + body: Buffer.from(JSON.stringify({ host, nonce, product: RELAY_PRODUCT, productVersion: PLUGIN_VERSION })), + fetchImpl: options.fetchImpl, + method: 'POST', + path: '/v1/enrol', + timeoutMs: RELAY_DEFAULTS.enrolTimeoutMs, + url: options.url, + }) + if (answer.ok) { + const candidate = await readRelayCandidate(payload) + if (!candidate || candidate.nonceHash !== nonceHash) { + // The service says yes, but the token did not reach this store (another instance with a store of its own?). + return enrolFailure(refusal('callback-failed', 'The mail service confirmed the enrolment, but its token did not reach this site\'s store.', { reason: 'store' })) + } + const state: RelaySiteState = answer.body.state === 'pending' || answer.body.state === 'suspended' ? answer.body.state : 'active' + await updateRelayStore(payload, (current) => ({ + ...current, + disconnected: false, + enrolledAt: new Date().toISOString(), + host, + refusal: null, + source: 'enrolment', + state, + token: candidate.token, + })) + await dropRelayCandidate(payload) + return { ok: true, state } + } + // Used or not, this nonce is over. A token the call-back did deliver stays beside the one in use. + await releaseNonce(payload, nonce) + if (answer.code !== 'enrolment-in-progress' || attempt > 0) {break} + // Another process of this site is enrolling: wait, then look whether the token is here by now. + await sleep(Math.min((answer.retryAfter ?? 2) * 1000, 5000)) + const now = await readRelayStore(payload) + if ((now.token && now.token !== stored.token) || (await readRelayCandidate(payload))) {return { ok: true, state: now.state ?? 'active' }} + } + + const failed = answer as RelayRefusal + if (!failed.retryable) { + // Asking again at once would give the same answer (and a call-back that times out costs 8 seconds a time). + const now = Date.now() + await updateRelayStore(payload, (current) => ({ + ...current, + refusal: { at: new Date(now).toISOString(), code: failed.code, message: failed.message, ...(failed.reason ? { reason: failed.reason } : {}), until: new Date(now + RELAY_DEFAULTS.refusalCooldownMs).toISOString() }, + ...(failed.code === 'site-suspended' ? { state: 'suspended' as const } : {}), + })) + } + return enrolFailure(failed) +} + +/** 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 { + if (options.token === undefined) {return undefined} + const value = typeof options.token === 'function' ? await options.token() : options.token + return typeof value === 'string' && value.trim() ? value.trim() : undefined +} + +/** Kept across the retries of one message: a site enrols at most once per message. */ +export type TokenUse = { enrolled?: boolean; enrolment?: EnrolResult } + +/** + * Runs `call` with the site's token and deals with what the answer says about the token: + * - no token yet → enrol first (when `enrol` is `'auto'`), then call; + * - a token the call-back delivered but `/v1/enrol` never confirmed is tried first; on + * `401 invalid-token` it is dropped and the earlier token is used again; + * - `401 invalid-token` or `401 reverify` → enrol again once, then call again. + * Any answer but `invalid-token` proves the token: a candidate then becomes the token in use. + */ +export async function withRelayToken( + payload: BasePayload, + options: ResolvedRelayOptions, + call: (token: string) => Promise>, + use: TokenUse = {}, + { enrol = options.enrol !== 'manual' && options.enrol !== false, first = true }: { enrol?: boolean; first?: boolean } = {}, +): Promise> { + const fixed = await optionToken(options) + if (fixed) {return call(fixed)} + 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) + 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 + + const enrolNow = async (): Promise => { + if (!enrol || use.enrolled) {return refusal(LOCAL_CODES.noToken, 'The site is not connected to the mail service.')} + use.enrolled = true + use.enrolment = await enrolRelay(payload, options) + return use.enrolment.ok ? null : refusal(use.enrolment.code, use.enrolment.message, { reason: use.enrolment.reason, retryable: use.enrolment.retryable }) + } + + if (!token) { + // `first: false` (a status read): a site that never enrolled does not start because somebody looked. + if (!first) {return refusal(LOCAL_CODES.noToken, 'The site is not connected to the mail service.')} + const failed = await enrolNow() + if (failed) {return failed} + continue + } + const answer = await call(token) + if (!answer.ok && answer.code === 'invalid-token') { + if (candidate) { + // The service never made this token valid: back to the earlier one. + await dropRelayCandidate(payload) + continue + } + const failed = await enrolNow() + if (failed) {return use.enrolment ? 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 dropRelayCandidate(payload) + } + if (!answer.ok && answer.code === 'reverify') { + const failed = await enrolNow() + if (failed) {return use.enrolment ? failed : answer} + continue + } + return answer + } + return refusal('invalid-token', 'The mail service keeps refusing this site\'s token.') +} + +type StatusBody = { + limits?: NonNullable['limits'] + quota?: NonNullable['quota'] + sender?: { address?: string } + service?: { contract?: string; name?: string } + state?: RelaySiteState + token?: { rotateAfter?: string } +} + +/** + * Reads `/v1/status` and keeps what it says (limits, quota, the sender address, when to rotate). + * A site without a token is not enrolled by this; a site whose server address is new to the service + * (`401 reverify`) enrols again, as on a send. Returns the stored entry as it is afterwards; `error` + * when the service could not be asked. + */ +export async function refreshRelayStatus(payload: BasePayload, options: ResolvedRelayOptions): Promise<{ error?: RelayRefusal; stored: RelayStored }> { + const answer = await withRelayToken( + payload, + options, + (token) => relayRequest({ fetchImpl: options.fetchImpl, method: 'GET', path: '/v1/status', token, url: options.url }), + {}, + { first: false }, + ) + if (!answer.ok) {return { error: answer, stored: await readRelayStore(payload) }} + const body = answer.body + const stored = await updateRelayStore(payload, (current) => ({ + ...current, + service: { + name: body.service?.name, + contract: body.service?.contract, + fetchedAt: new Date().toISOString(), + limits: body.limits, + quota: body.quota, + rotateAfter: body.token?.rotateAfter, + senderAddress: body.sender?.address, + }, + ...(body.state ? { state: body.state } : {}), + })) + return { stored } +} + +/** + * Asks for a new token when the service said the present one is due (`token.rotateAfter`, 90 days). + * The new token is stored at once; the previous one works for 24 hours more, so other processes of + * the site read the store again in time. `409 already-rotated` = another process won: nothing to do + * 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) + 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'} + const used = stored.token + const answer = await relayRequest<{ token?: string }>({ fetchImpl: options.fetchImpl, method: 'POST', path: '/v1/rotate', token: used, url: options.url }) + if (answer.ok && typeof answer.body.token === 'string' && answer.body.token) { + const fresh = answer.body.token + await updateRelayStore(payload, (current) => ({ + ...current, + enrolledAt: new Date().toISOString(), + service: current.service ? { ...current.service, rotateAfter: undefined } : current.service, + source: 'rotation', + token: fresh, + })) + return 'rotated' + } + if (!answer.ok && answer.code === 'already-rotated') { + const now = await readRelayStore(payload) + // No newer token here: this one is on its way out. Forget it, so the next send enrols at once. + if (now.token === used) {await updateRelayStore(payload, (current) => ({ ...current, service: null, token: undefined }))} + return 'failed' + } + // Asked once; not again before the status has been read anew. + await updateRelayStore(payload, (current) => ({ ...current, service: current.service ? { ...current.service, rotateAfter: undefined } : current.service })) + return 'failed' +} + +/** 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 { + const stored = await readRelayStore(payload) + if (stored.token && options.token === undefined) { + await relayRequest({ fetchImpl: options.fetchImpl, method: 'POST', path: '/v1/revoke', token: stored.token, url: options.url }) + } + await clearRelayStore(payload, { disconnected: true }) +} + +/** + * Stores a token Intecion issued by hand (a site the service cannot call back: behind a firewall, on + * a private address). It is bound to the first server address that uses it. + */ +export async function setRelayToken(payload: BasePayload, token: string, options: { host?: string } = {}): Promise { + if (!/^ims_[\w-]{43}$/.test(token)) {throw new Error('Not a token of the mail service (ims_ and 43 characters).')} + await dropRelayCandidate(payload) + await updateRelayStore(payload, (current) => ({ + ...current, + disconnected: false, + enrolledAt: new Date().toISOString(), + ...(options.host ? { host: options.host } : {}), + refusal: null, + service: null, + source: 'manual', + state: current.state ?? 'active', + token, + })) +} + +/** What the panel and the doctor may know: never the token. */ +export type RelayStatus = { + connected: boolean + disconnected: boolean + host: string + limits?: NonNullable['limits'] + nameReplaced?: { asked: string; at: string; used: string } + quota?: NonNullable['quota'] + refusal?: { at: string; code: string; message?: string; reason?: string } + senderAddress?: string + serviceName?: string + state?: RelaySiteState + tokenSource?: 'enrolment' | 'manual' | 'option' | 'rotation' +} + +export function describeRelayStore(payload: BasePayload, options: ResolvedRelayOptions, stored: RelayStored): RelayStatus { + const fromOption = options.token !== undefined + return { + connected: fromOption || Boolean(stored.token), + disconnected: Boolean(stored.disconnected), + host: relayHost(payload, options) || stored.host || '', + ...(stored.service?.limits ? { limits: stored.service.limits } : {}), + ...(stored.nameReplaced ? { nameReplaced: stored.nameReplaced } : {}), + ...(stored.service?.quota ? { quota: stored.service.quota } : {}), + ...(stored.refusal ? { refusal: { at: stored.refusal.at, code: stored.refusal.code, message: stored.refusal.message, reason: stored.refusal.reason } } : {}), + ...(stored.service?.senderAddress ? { senderAddress: stored.service.senderAddress } : {}), + ...(stored.service?.name ? { serviceName: stored.service.name } : {}), + ...(stored.state ? { state: stored.state } : {}), + ...(fromOption ? { tokenSource: 'option' as const } : stored.source ? { tokenSource: stored.source } : {}), + } +} + +/** + * The site's state with the service, for a panel or a script. `refresh: true` asks the service + * (`/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))} + const { error, stored } = await refreshRelayStatus(payload, options) + return { ...describeRelayStore(payload, options, stored), ...(error && error.code !== LOCAL_CODES.noToken ? { error: error.code } : {}) } +} + +export { sha256Hex } diff --git a/src/modules/email/relay/store.ts b/src/modules/email/relay/store.ts new file mode 100644 index 0000000..693592e --- /dev/null +++ b/src/modules/email/relay/store.ts @@ -0,0 +1,140 @@ +import type { BasePayload } from 'payload' + +import { createHash, timingSafeEqual } from 'node:crypto' + +import { RELAY_KV_KEY } from './constants.js' + +/** + * Where the site keeps its token: Payload's key-value store (`payload.kv`, the `payload-kv` collection + * Payload itself adds — no field, no column, no migration of ours). That collection refuses every + * operation through access control and is hidden in the panel, so the token cannot be read over REST + * or GraphQL (test/mailRelayHttp.test.ts proves it). The token is never logged and never sent to a browser. + * + * Three entries: + * - `iapl:mail-relay` the token in use, the site's state, what the service last reported; + * - `iapl:mail-relay:candidate` a token the service delivered that has not been seen accepted yet; + * - `iapl:mail-relay:nonce:` an enrolment this site started (5 minutes, single use). + * The confirm route writes only the candidate and deletes only its nonce, so it can never overwrite a + * working token. + */ + +export type RelaySiteState = 'active' | 'pending' | 'suspended' + +export type RelayLimits = { + maxAttachmentBytes?: number + maxAttachments?: number + maxBodyBytes?: number + messagesPerDay?: number + messagesPerHour?: number + recipientsPerMessage?: number +} + +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. */ + host?: string + /** 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`. */ + refusal?: { at: string; code: string; message?: string; reason?: string; until: string } | null + /** What `/v1/status` last said. */ + service?: { + contract?: string + fetchedAt: string + limits?: RelayLimits + name?: string + quota?: { day?: { limit: number; remaining: number }; hour?: { limit: number; remaining: number } } + rotateAfter?: string + senderAddress?: string + } | null + /** `enrolment`: by the call-back. `manual`: issued by Intecion and stored by hand. `rotation`: from /v1/rotate. */ + source?: 'enrolment' | 'manual' | 'rotation' + state?: RelaySiteState + token?: string + v: 1 +} + +export type RelayCandidate = { at: string; nonceHash: string; state: RelaySiteState; token: string } + +type KV = { delete: (key: string) => Promise; get: (key: string) => Promise; set: (key: string, value: object) => Promise } + +/** Without `payload.kv` (a Payload older than the store, or a test double): this process only. */ +const memory = new WeakMap>() +let warnedNoStore = false + +function kvOf(payload: BasePayload): KV { + const kv = (payload as { kv?: Partial }).kv + if (typeof kv?.get === 'function' && typeof kv?.set === 'function' && typeof kv?.delete === 'function') {return kv as KV} + if (!warnedNoStore) { + warnedNoStore = true + payload.logger?.warn?.('[iapl] mail service: this Payload has no key-value store (payload.kv); the token is kept in memory and is lost on restart.') + } + let map = memory.get(payload) + if (!map) { + map = new Map() + memory.set(payload, map) + } + const held = map + return { + delete: (key) => Promise.resolve(void held.delete(key)), + get: (key) => Promise.resolve(held.get(key) ?? null), + set: (key, value) => Promise.resolve(void held.set(key, structuredClone(value))), + } +} + +export const sha256Hex = (text: string) => createHash('sha256').update(text, 'utf8').digest('hex') + +const CANDIDATE_KEY = `${RELAY_KV_KEY}:candidate` +const nonceKey = (nonceHash: string) => `${RELAY_KV_KEY}:nonce:${nonceHash}` + +export async function readRelayStore(payload: BasePayload): Promise { + const value = (await kvOf(payload).get(RELAY_KV_KEY)) as null | RelayStored + return value && typeof value === 'object' ? { ...value, v: 1 } : { v: 1 } +} + +/** 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 { + const next = change(await readRelayStore(payload)) + await kvOf(payload).set(RELAY_KV_KEY, next) + return next +} + +/** Forgets the token and everything known about the service (keeps nothing). */ +export async function clearRelayStore(payload: BasePayload, keep: Pick = {}): Promise { + const kv = kvOf(payload) + await kv.delete(CANDIDATE_KEY) + if (keep.disconnected) {await kv.set(RELAY_KV_KEY, { disconnected: true, v: 1 } satisfies RelayStored)} + else {await kv.delete(RELAY_KV_KEY)} +} + +export async function readRelayCandidate(payload: BasePayload): Promise { + const value = (await kvOf(payload).get(CANDIDATE_KEY)) as null | RelayCandidate + return value && typeof value.token === 'string' ? value : null +} + +export const writeRelayCandidate = (payload: BasePayload, candidate: RelayCandidate) => kvOf(payload).set(CANDIDATE_KEY, candidate) +export const dropRelayCandidate = (payload: BasePayload) => kvOf(payload).delete(CANDIDATE_KEY) + +/** Remembers that this site started an enrolment with `nonce`. Only its hash is stored. */ +export async function holdNonce(payload: BasePayload, nonce: string, ttlMs: number): Promise { + const nonceHash = sha256Hex(nonce) + await kvOf(payload).set(nonceKey(nonceHash), { expiresAt: Date.now() + ttlMs, hash: nonceHash }) + return nonceHash +} + +/** True when this site holds `nonce` and it has not expired. Single use: the entry is gone afterwards. */ +export async function takeNonce(payload: BasePayload, nonce: string): Promise { + const kv = kvOf(payload) + const nonceHash = sha256Hex(nonce) + const key = nonceKey(nonceHash) + // Found by the hash of the nonce (a look-up tells nothing about the nonce itself), then compared in constant time. + const held = (await kv.get(key)) as { expiresAt?: number; hash?: string } | null + if (!held || typeof held.hash !== 'string' || held.hash.length !== nonceHash.length) {return false} + if (!timingSafeEqual(Buffer.from(held.hash), Buffer.from(nonceHash))) {return false} + await kv.delete(key) + return typeof held.expiresAt === 'number' && held.expiresAt > Date.now() +} + +export const releaseNonce = (payload: BasePayload, nonce: string) => kvOf(payload).delete(nonceKey(sha256Hex(nonce))) diff --git a/src/modules/email/test/testEmailEndpoint.ts b/src/modules/email/test/testEmailEndpoint.ts index e2b7216..328a2f0 100644 --- a/src/modules/email/test/testEmailEndpoint.ts +++ b/src/modules/email/test/testEmailEndpoint.ts @@ -3,7 +3,8 @@ import type { Endpoint, PayloadRequest } from 'payload' import { addDataAndFileToRequest } from 'payload' import { userMeetsRole } from '../../access/predicates.js' -import { serverText } from '../../integrations/texts.js' +import { serverText, STATUS_CODE_TEXTS } from '../../integrations/texts.js' +import { withMailKind } from '../relay/kinds.js' /** * Custom endpoint: send a test email to a given address through whatever @@ -64,7 +65,7 @@ export const testEmailEndpoint: Endpoint = { const text = site ? serverText(i18n, 'testEmailBody', { site }) : serverText(i18n, 'testEmailBodyGeneric') try { - const info = await req.payload.sendEmail({ + const info = await req.payload.sendEmail(withMailKind({ ...(attachmentMB ? { attachments: [{ content: Buffer.alloc(attachmentMB * 1024 * 1024, 'IAPL test file\n'), contentType: 'text/plain', filename: `test-${attachmentMB}MB.txt` }] } : {}), @@ -72,7 +73,7 @@ export const testEmailEndpoint: Endpoint = { subject, text, to, - }) + }, 'test')) // Payload's sendEmail resolves with the adapter's result. Our adapters // return { sent: boolean, error?: string, code?: string }; nodemailer @@ -83,16 +84,28 @@ export const testEmailEndpoint: Endpoint = { : true if (!sent) { - const failed = info as { code?: string; detail?: string; error?: string } + const failed = info as { code?: string; confirmed?: boolean; detail?: string; error?: string } req.payload.logger.error(`[iapl] Test email not sent: ${failed?.detail ?? failed?.error ?? 'unknown reason'}`) + const relayText = failed?.code ? STATUS_CODE_TEXTS[failed.code] : undefined const error = failed?.code === 'not-configured' ? serverText(i18n, 'testEmailNotConfigured') - : serverText(i18n, 'testEmailFailed') - return Response.json({ error, ok: false }, { status: 502 }) + : failed?.confirmed === false + ? serverText(i18n, 'testEmailNotConfirmed') + // the mail service's refusal in the admin's language (waiting for approval, a limit, too large …) + : failed?.code?.startsWith('relay-') && relayText + ? serverText(i18n, relayText) + : serverText(i18n, 'testEmailFailed') + return Response.json({ code: failed?.code, error, ok: false }, { status: 502 }) } - return Response.json({ message: serverText(i18n, 'testEmailSent', { to }), ok: true }) + // The answer names the transport that carried it. + const sentBy = info as { senderName?: string; transport?: string } | null + const message = + sentBy?.transport === 'relay' ? serverText(i18n, 'testEmailSentRelay', { name: sentBy.senderName ?? '', to }) + : sentBy?.transport === 'smtp' ? serverText(i18n, 'testEmailSentSmtp', { to }) + : serverText(i18n, 'testEmailSent', { to }) + return Response.json({ message, ok: true, ...(sentBy?.transport ? { transport: sentBy.transport } : {}) }) } catch (err) { const message = err instanceof Error ? err.message : String(err) req.payload.logger.error(`[iapl] Test email failed: ${message}`) diff --git a/src/modules/forms/attachments/delivery.ts b/src/modules/forms/attachments/delivery.ts index 1537a6b..c9257ba 100644 --- a/src/modules/forms/attachments/delivery.ts +++ b/src/modules/forms/attachments/delivery.ts @@ -4,6 +4,7 @@ import type { BasePayload } from 'payload' import type { FormAttachmentsOption } from './config.js' import type { AcceptedFormFile } from './fileGate.js' +import { mailKindOf, withMailKind } from '../../email/relay/kinds.js' import { formatFileSize } from './fileTypes.js' /** @@ -121,6 +122,25 @@ export function buildFileNoticeHook({ formsSlug = 'forms', notice }: { formsSlug } } +/** + * Says what each e-mail of a form is, for a transport that asks (the Intecion mail service limits the + * two kinds differently): `form-notification` when EVERY recipient is an address written in the + * panel, `form-confirmation` otherwise — it goes to an address a visitor typed. An e-mail the + * project's own `beforeEmail` already marked keeps its mark; when the form cannot be read the purpose + * is not known (`system`). Other transports ignore the mark. + */ +export function buildFormMailKindHook({ formsSlug = 'forms' }: { formsSlug?: string } = {}): BeforeEmail { + return async (emails, args) => { + let fixed: null | Set = null + try { + fixed = await loadFixed(args, formsSlug) + } catch { + /* unknown purpose below */ + } + return emails.map((email) => (mailKindOf(email) ? email : withMailKind(email, !fixed ? 'system' : mayCarryFiles(email, fixed) ? 'form-notification' : 'form-confirmation'))) + } +} + type SendOutcome = { detail?: string; ok: boolean } /** One send through the project's adapter. mailAdapter reports failure as `{ sent: false }`; others throw. */ diff --git a/src/modules/forms/formsPluginConfig.ts b/src/modules/forms/formsPluginConfig.ts index 21be8c4..0fb6cbb 100644 --- a/src/modules/forms/formsPluginConfig.ts +++ b/src/modules/forms/formsPluginConfig.ts @@ -8,7 +8,7 @@ import type { FormsOption } from './types.js' import { userMeetsRole } from '../access/predicates.js' import { resolveFormAttachments } from './attachments/config.js' -import { buildFileDeliveryHook, buildFileNoticeHook } from './attachments/delivery.js' +import { buildFileDeliveryHook, buildFileNoticeHook, buildFormMailKindHook } from './attachments/delivery.js' import { buildFormSubmitEndpoint } from './attachments/endpoint.js' import { buildFileBlock } from './attachments/fileBlock.js' import { buildFormFilesAfterRead, buildFormFilesBeforeValidate, submissionFileFields } from './attachments/formHooks.js' @@ -218,19 +218,20 @@ export function buildFormsPlugin(forms: FormsOption): Plugin { const attachments = forms.attachments ? resolveFormAttachments(forms.attachments) : null const fileNotice = attachments ? buildFileNoticeHook({ formsSlug, notice: attachments.notice }) : undefined const fileDelivery = attachments ? buildFileDeliveryHook({ formsSlug }) : undefined - const beforeEmail: BeforeEmail | undefined = - layout || forms.beforeEmail || attachments - ? async (emails, args) => { - const noticed = fileNotice ? await fileNotice(emails, args) : emails - const laidOut = layout ? await layout(noticed, args) : noticed - const changed = forms.beforeEmail ? await Promise.resolve(forms.beforeEmail(laidOut, args)) : laidOut - return fileDelivery ? fileDelivery(changed, args) : changed - } - : undefined + // Every e-mail of a form says what it is (notification to the addresses written in the panel, or + // confirmation to an address the visitor typed): the Intecion mail service limits the two differently. + const markKinds = buildFormMailKindHook({ formsSlug }) + const beforeEmail: BeforeEmail = async (emails, args) => { + const noticed = fileNotice ? await fileNotice(emails, args) : emails + const laidOut = layout ? await layout(noticed, args) : noticed + const changed = forms.beforeEmail ? await Promise.resolve(forms.beforeEmail(laidOut, args)) : laidOut + const marked = await markKinds(changed, args) + return fileDelivery ? fileDelivery(marked, args) : marked + } const fileBlockOption = forms.fields?.file const formHooks = forms.formOverrides?.hooks const builder = formBuilderPlugin({ - ...(beforeEmail ? { beforeEmail } : {}), + beforeEmail, // Built-in types + ipal's `step`, `checkboxGroup` and `time` (builderBlocks). All are // panel choices only — a form uses what the editor adds, nothing changes on // existing forms. Switch any off with forms.fields.: false. diff --git a/src/modules/integrations/texts.ts b/src/modules/integrations/texts.ts index 0dc8188..213caa2 100644 --- a/src/modules/integrations/texts.ts +++ b/src/modules/integrations/texts.ts @@ -24,6 +24,17 @@ export const STATUS_CODE_TEXTS: Record = { 'missing-input-secret': 'statusTurnstileMissingSecret', 'missing-secret': 'statusTurnstileMissingSecret', 'network-error': 'statusTurnstileNetworkError', + 'relay-attachment-refused': 'statusEmailRelayAttachmentRefused', + 'relay-disconnected': 'statusEmailRelayDisconnected', + 'relay-error': 'statusEmailRelayError', + 'relay-not-confirmed': 'statusEmailRelayNotConfirmed', + 'relay-pending': 'statusEmailRelayPending', + 'relay-quota': 'statusEmailRelayQuota', + 'relay-recipient-suppressed': 'statusEmailRelayRecipientSuppressed', + 'relay-refused': 'statusEmailRelayRefused', + 'relay-suspended': 'statusEmailRelaySuspended', + 'relay-too-large': 'statusEmailRelayTooLarge', + 'relay-unreachable': 'statusEmailRelayUnreachable', } type I18nLike = { language?: string; t?: (key: never, vars?: Record) => string } | undefined diff --git a/src/plugin.ts b/src/plugin.ts index d635071..558f21f 100644 --- a/src/plugin.ts +++ b/src/plugin.ts @@ -31,6 +31,10 @@ import { mergeCookieScanLabels } from './modules/consent/scanner/labels.js' import { buildConstructionFields } from './modules/construction/fields.js' import { buildArchiveFields } from './modules/content/index.js' import { buildDoctorEndpoint } from './modules/doctor/status.js' +import { GRAPH_DEPRECATION_NOTICE, graphAvailable } from './modules/email/mailAdapter.js' +import { withAccountMailMark } from './modules/email/relay/accountMail.js' +import { relayConfirmEndpoint } from './modules/email/relay/confirm.js' +import { relayPanelEndpoints } from './modules/email/relay/panel.js' import { testEmailEndpoint } from './modules/email/test/testEmailEndpoint.js' import { emailSettingsFields } from './modules/forms/emailLayout.js' import { buildFormsPlugin } from './modules/forms/formsPluginConfig.js' @@ -705,6 +709,7 @@ export const iapl = (options: IaplOptions): Plugin => { }), buildSiteIntegrations({ additionalFields: options.integrationsFields, + mailRelay: options.mail?.relay !== false, reenterSecretOnChange: options.secrets?.reenterOnChange !== false, writeOnlySecrets: options.secrets?.writeOnly !== false, }), @@ -743,6 +748,22 @@ export const iapl = (options: IaplOptions): Plugin => { config.endpoints = [...(config.endpoints ?? []), testEmailEndpoint] + // --- e-mail: the Intecion Notifications Webservice (docs/email.md; off with mail: { relay: false }) --- + // What mailAdapter() reads at send time; born under the new name (`custom.iapl`). + const relay = options.mail?.relay + const iaplCustom = (config.custom?.iapl ?? {}) as object + config.custom = { + ...config.custom, + iapl: { ...iaplCustom, mail: { ...(options.mail?.graphDeprecationWarning === false ? { graphDeprecationWarning: false } : {}), relay: relay === false ? false : (relay ?? {}) } }, + } + if (relay !== false) { + // The public route the service calls a site back at (404 unless this site just started an + // enrolment), and the admin-only routes of the state block on the e-mail tab. + config.endpoints = [...config.endpoints, relayConfirmEndpoint(relay ?? {}), ...relayPanelEndpoints()] + // "Forgot password" and "verify your e-mail" are Payload's own mail: say what they are. + config.collections = (config.collections ?? []).map((c) => (c.auth ? withAccountMailMark(c) : c)) + } + // --- iapl-doctor status (404 until IAPL_DOCTOR_TOKEN is set; docs/doctor.md) --- if (options.doctor !== false) { config.endpoints = [...(config.endpoints ?? []), buildDoctorEndpoint(options.doctor ?? {})] @@ -918,6 +939,8 @@ export const iapl = (options: IaplOptions): Plugin => { ) } adoptConfig(payload) + // Microsoft Graph is deprecated (removed in 2.0): one warning per start while its variables are set. + if (graphAvailable() && options.mail?.graphDeprecationWarning !== false) {payload.logger.warn(GRAPH_DEPRECATION_NOTICE)} // Payload's dev reload swaps `payload.config` and runs no onInit: adopt the new config at once. watchPayloadConfig(payload, adoptConfig) if (staleImportMap) { diff --git a/src/types.ts b/src/types.ts index a59d740..3112049 100644 --- a/src/types.ts +++ b/src/types.ts @@ -19,6 +19,7 @@ import type { ConsentLogOptions } from './modules/consent/consentLog.js' import type { CookieScannerOptions } from './modules/consent/scanner/types.js' import type { ContentOption } from './modules/content/types.js' import type { DoctorEndpointOptions } from './modules/doctor/status.js' +import type { RelayOptions } from './modules/email/relay/options.js' import type { FormsOption } from './modules/forms/types.js' import type { RevalidatePathFn } from './modules/hooks/buildRevalidateHook.js' import type { I18nConfig } from './modules/i18n/types.js' @@ -178,6 +179,22 @@ export type IaplOptions = { */ lightbox?: boolean + /** + * E-mail (docs/email.md). A site with no SMTP server in Site integrations sends through the + * Intecion Notifications Webservice: it enrols by itself on its first send (an outbound call with + * the site's host and the plugin version) and gets its own token through the public route + * `POST /api/iapl/mail-relay/confirm`. A site with SMTP filled in never contacts the service. + * + * - `relay: false` — no enrolment, no outbound call, no confirm route, no state block in the + * panel: SMTP (or Graph) only, as before 1.17.0. + * - `relay: { … }` — the service's address (a relay of your own), the site's host, manual + * enrolment, a token from elsewhere, the sender name, the limit on account e-mails. + * - `graphDeprecationWarning: false` — no start-log warning while the site still uses the + * deprecated Microsoft Graph transport. + * `mailAdapter({ relay })` overrides `relay` for that adapter. + */ + mail?: MailOptions + /** * System-page assignments (homepage, privacy, cookies) in SiteSettings. * Provide the slug of the client's Pages collection to enable. @@ -200,7 +217,6 @@ export type IaplOptions = { * over `seo.searchSettings`. */ searchSettings?: ((defaults: Field[]) => Field[]) | false - /** * SEO — adds meta fields to chosen collections (via @payloadcms/plugin-seo) * and enables locale-aware metadata helpers. @@ -222,6 +238,7 @@ export type IaplOptions = { * follows the new server. docs/security.md "Stored secrets". */ secrets?: { reenterOnChange?: false; writeOnly?: false } + seo?: SeoOption /** Additional fields injected into SiteSettings global */ @@ -437,3 +454,10 @@ export type ThemeOptions = { /** @deprecated The name before 1.17.0; the same type as `IaplOptions`. Removed in 2.0. */ export type IpalOptions = IaplOptions + +export type MailOptions = { + /** `false` silences the one warning per process start of a site on Microsoft Graph (deprecated, removed in 2.0). */ + graphDeprecationWarning?: boolean + /** The Intecion Notifications Webservice. Default on; `false` switches it off. */ + relay?: false | RelayOptions +} diff --git a/test/mailRelay.test.ts b/test/mailRelay.test.ts new file mode 100644 index 0000000..209fa1b --- /dev/null +++ b/test/mailRelay.test.ts @@ -0,0 +1,617 @@ +/** + * The site's side of the Intecion Notifications Webservice, against the fake service: which transport + * a send takes, enrolment and the confirm route, what happens to the token, one key and one encoding + * per message across retries, "not confirmed", rotation, the limits the site keeps itself, and that + * no token ever reaches a log. + */ +import type { PayloadEmailAdapter } from 'payload' + +import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest' + +import { mailAdapter, resetGraphDeprecationWarning, resolveMailTransport } from '../src/modules/email/mailAdapter.js' +import { relayAdapter } from '../src/modules/email/relay/adapter.js' +import { withMailKind } from '../src/modules/email/relay/kinds.js' +import { bareAddresses, buildRelayMessage, cleanSubject } from '../src/modules/email/relay/message.js' +import { isPublicHost, relayHost, resolveRelayOptions } from '../src/modules/email/relay/options.js' +import { clearUnconfirmedRelayMessages, sendThroughRelay } from '../src/modules/email/relay/send.js' +import { disconnectRelay, enrolRelay, getRelayStatus, refreshRelayStatus, rotateRelayToken, setRelayToken } from '../src/modules/email/relay/session.js' +import { holdNonce, readRelayCandidate, readRelayStore, updateRelayStore } from '../src/modules/email/relay/store.js' +import { setRateLimitStore } from '../src/modules/shared/rateLimit.js' +import { callConfirmRoute, relayPayload, relaySite } from './mailRelay/helpers.js' + +vi.mock('server-only', () => ({})) + +const MESSAGE = { html: '

Hello.

', subject: 'New enquiry', to: 'office@example.org' } +const HOST = 'example.com' +const GRAPH_ENV = ['GRAPH_TENANT_ID', 'GRAPH_CLIENT_ID', 'GRAPH_CLIENT_SECRET', 'GRAPH_SENDER'] + +/** Each test counts from zero: a rate-limit store of its own. */ +function clearRateLimits(): void { + const buckets = new Map() + setRateLimitStore({ + hit: async (id: string, cost: number, windowMs: number) => { + const now = Date.now() + const current = buckets.get(id) + const bucket = current && current.resetAt > now ? current : { count: 0, resetAt: now + windowMs } + bucket.count += cost + buckets.set(id, bucket) + return bucket + }, + }) +} + +const adapterOf = (factory: PayloadEmailAdapter, payload: unknown) => factory({ payload } as never) as { attachmentLimit?: () => Promise } & ReturnType +const everythingLogged = (logger: Record) => JSON.stringify(Object.values(logger).flatMap((fn) => fn.mock.calls)) + +beforeEach(() => { + clearUnconfirmedRelayMessages() + clearRateLimits() + resetGraphDeprecationWarning() + for (const name of GRAPH_ENV) {vi.stubEnv(name, '')} +}) +afterEach(() => { + vi.unstubAllEnvs() + setRateLimitStore(null) +}) + +describe('which transport a send takes', () => { + const smtp = { smtpHost: 'smtp.example.com', smtpPassword: 'secret', smtpUser: 'info@example.com' } + + test.each([ + ['nothing set', {}, false, true, 'relay'], + ['nothing set, relay switched off', {}, false, false, 'none'], + ['SMTP filled in', smtp, false, true, 'smtp'], + ['SMTP filled in, relay off', smtp, false, false, 'smtp'], + ['SMTP half filled in', { smtpHost: 'smtp.example.com' }, false, true, 'relay'], + ['Graph chosen with its variables', { emailTransport: 'graph' }, true, true, 'graph'], + ['Graph chosen with its variables and SMTP (today: Graph, SMTP for large files)', { ...smtp, emailTransport: 'graph' }, true, true, 'graph'], + ['Graph chosen, variables missing, SMTP filled in', { ...smtp, emailTransport: 'graph' }, false, true, 'smtp'], + ['Graph chosen, variables missing, no SMTP', { emailTransport: 'graph' }, false, true, 'relay'], + ['Graph variables set, panel on automatic, no SMTP', {}, true, true, 'graph'], + ['Graph variables set, panel on automatic, SMTP filled in', smtp, true, true, 'smtp'], + ] as const)('%s → %s', (_name, settings, graphEnv, relay, expected) => { + expect(resolveMailTransport(settings, { graphEnv, relay })).toBe(expected) + }) + + test('a site with SMTP filled in never contacts the service', async () => { + const { fake, payload } = relaySite({ integrations: { smtpHost: '127.0.0.1', smtpPassword: 'x', smtpPort: 1, smtpUser: 'u' } }) + const adapter = adapterOf(mailAdapter({ relay: { fetchImpl: fake.fetch, url: fake.url } }), payload) + const result = (await adapter.sendEmail(MESSAGE)) as { sent: boolean } + expect(result.sent).toBe(false) // nothing listens on port 1 + expect(fake.requests).toEqual([]) + expect(await adapter.attachmentLimit?.()).toBeNull() + }) + + test('relay: false leaves a site without SMTP "not configured", as before 1.17.0', async () => { + const { fake, payload } = relaySite() + const result = (await adapterOf(mailAdapter({ relay: false }), payload).sendEmail(MESSAGE)) as { code: string; sent: boolean } + expect(result).toMatchObject({ code: 'not-configured', sent: false }) + expect(fake.requests).toEqual([]) + }) + + test('the plugin option switches it off for mailAdapter() too, and the adapter\'s own argument wins', async () => { + const off = relaySite({ custom: { iapl: { mail: { relay: false } } } }) + expect(resolveRelayOptions(off.payload, undefined)).toBeNull() + expect(resolveRelayOptions(off.payload, {})?.url).toBe('https://webservices.intecion.net/mail') + expect(resolveRelayOptions(off.payload, { url: 'https://relay.example.net/mail/' })).toMatchObject({ ownUrl: true, url: 'https://relay.example.net/mail' }) + const on = relaySite({ custom: { iapl: { mail: { relay: { host: 'www.example.com' } } } } }) + expect(resolveRelayOptions(on.payload, undefined)?.host).toBe('www.example.com') + expect(resolveRelayOptions(on.payload, false)).toBeNull() + }) +}) + +describe('the first send', () => { + test('enrols through the confirm route, then sends — with the panel\'s name, the reply address and the kind', async () => { + const { fake, logger, payload, settings, store } = relaySite({ fake: { allow: [HOST] }, integrations: { smtpFromAddress: 'biuro@example.com', smtpFromName: 'Kancelaria Example' } }) + const adapter = adapterOf(mailAdapter({ relay: { fetchImpl: fake.fetch, url: fake.url } }), payload) + + const result = (await adapter.sendEmail(withMailKind(MESSAGE, 'form-notification'))) as Record + expect(result).toMatchObject({ kind: 'form-notification', replayed: false, senderName: 'Kancelaria Example', sent: true, transport: 'relay', warnings: [] }) + expect(fake.requests.map((r) => `${r.method} ${r.path}`).slice(0, 2)).toEqual(['POST /v1/enrol', 'POST /v1/send']) + expect(fake.outbox).toHaveLength(1) + expect(fake.outbox[0]).toMatchObject({ + from: 'notification@webservices.intecion.net', fromName: 'Kancelaria Example', headers: { 'X-Intecion-Product': 'iapl', 'X-Intecion-Site': HOST }, + kind: 'form-notification', replyTo: 'biuro@example.com', subject: 'New enquiry', to: ['office@example.org'], + }) + // the token is in the key-value store and nowhere else: not in a log, not in the result, not in the global + const stored = await readRelayStore(payload) + expect(stored.token).toMatch(/^ims_[\w-]{43}$/) + expect(stored).toMatchObject({ host: HOST, source: 'enrolment', state: 'active' }) + expect([...store.keys()].filter((k) => k.includes(':nonce:'))).toEqual([]) + expect(await readRelayCandidate(payload)).toBeNull() + for (const text of [everythingLogged(logger), JSON.stringify(result), JSON.stringify(settings)]) {expect(text).not.toContain('ims_')} + + // the second send does not enrol again + await adapter.sendEmail(MESSAGE) + expect(fake.requests.filter((r) => r.path === '/v1/enrol')).toHaveLength(1) + expect(fake.outbox[1].kind).toBe('system') // a message nobody marked + }) + + test('the sender name falls back to the site name; a message\'s own reply address wins', async () => { + const { fake, options, payload } = relaySite({ fake: { allow: [HOST] }, integrations: { smtpFromAddress: 'biuro@example.com' }, siteName: 'Example Sp. z o.o.' }) + const adapter = adapterOf(mailAdapter({ relay: options }), payload) + await adapter.sendEmail({ ...MESSAGE, replyTo: 'Jan Kowalski ' }) + expect(fake.outbox[0]).toMatchObject({ fromName: 'Example Sp. z o.o.', replyTo: 'jan@example.org' }) + // no name anywhere: the mail leaves under the site's host + const bare = relaySite({ fake: { allow: [HOST] } }) + await adapterOf(mailAdapter({ relay: bare.options }), bare.payload).sendEmail(MESSAGE) + expect(bare.fake.outbox[0].fromName).toBe(HOST) + expect(bare.fake.outbox[0].replyTo).toBeUndefined() + }) + + test('a host Intecion has not listed waits for approval; the same token works once approved', async () => { + const { fake, options, payload, settings } = relaySite() + const adapter = adapterOf(mailAdapter({ relay: options }), payload) + const waiting = (await adapter.sendEmail(MESSAGE)) as Record + expect(waiting).toMatchObject({ code: 'relay-pending', confirmed: true, sent: false }) + expect(settings.emailStatus).toMatchObject({ code: 'relay-pending', state: 'degraded' }) + expect((await readRelayStore(payload)).state).toBe('pending') + const token = (await readRelayStore(payload)).token + + fake.allow(HOST) + expect(((await adapter.sendEmail(MESSAGE)) as { sent: boolean }).sent).toBe(true) + expect(fake.requests.filter((r) => r.path === '/v1/enrol')).toHaveLength(1) + expect(await readRelayStore(payload)).toMatchObject({ state: 'active', token }) + expect(settings.emailStatus).toMatchObject({ state: 'ok' }) + }) + + test('a site that does not know its address, or runs on a private one, is refused here — nothing leaves the server', async () => { + const calls: string[] = [] + const fetchImpl = (async (input: string) => { + calls.push(String(input)) + return Response.json({ ok: true }) + }) as unknown as typeof fetch + for (const serverURL of ['', 'http://localhost:3000', 'https://shop.internal', 'https://192.0.2.10']) { + const { payload } = relayPayload({ serverURL }) + const options = resolveRelayOptions(payload, { fetchImpl })! + const result = await sendThroughRelay(payload, options, MESSAGE) + expect(result).toMatchObject({ code: 'relay-refused', sent: false }) + } + expect(calls).toEqual([]) + expect(isPublicHost('example.com')).toBe(true) + expect(relayHost({ config: { serverURL: 'https://WWW.Example.com:443/pl' } } as never, {})).toBe('www.example.com') + }) + + test('two sends at once enrol once', async () => { + const { fake, options, payload } = relaySite({ fake: { allow: [HOST] } }) + const results = await Promise.all([sendThroughRelay(payload, options, MESSAGE), sendThroughRelay(payload, options, { ...MESSAGE, subject: 'Second' })]) + expect(results.map((r) => r.sent)).toEqual([true, true]) + expect(fake.requests.filter((r) => r.path === '/v1/enrol')).toHaveLength(1) + }) +}) + +describe('the confirm route', () => { + test('answers 404 and stores nothing for a nonce the site does not hold, an expired one, a reused one and a malformed call', async () => { + const { payload } = relayPayload() + const confirm = callConfirmRoute(payload) + const url = `https://${HOST}/api/iapl/mail-relay/confirm` + const token = `ims_${'a'.repeat(43)}` + const call = (body: unknown) => confirm(url, { body: typeof body === 'string' ? body : JSON.stringify(body), headers: {} }) + const nonce = 'n'.repeat(43) + + expect((await call({ nonce, state: 'active', token })).status).toBe(404) // unsolicited + await holdNonce(payload, nonce, -1) + expect((await call({ nonce, state: 'active', token })).status).toBe(404) // expired + await holdNonce(payload, nonce, 60_000) + for (const bad of ['not json', '[]', { nonce, state: 'active' }, { nonce, state: 'active', token: 'ims_short' }, { nonce, state: 'owner', token }, { nonce: 'short', state: 'active', token }]) { + expect((await call(bad)).status).toBe(404) + } + expect(await readRelayCandidate(payload)).toBeNull() + const good = await call({ nonce, state: 'active', token }) + expect(good.status).toBe(200) + expect(good.headers.get('content-type')).toBe('application/json') + expect((await call({ nonce, state: 'active', token: `ims_${'b'.repeat(43)}` })).status).toBe(404) // single use + expect((await readRelayCandidate(payload))?.token).toBe(token) + }) + + test('never replaces the token in use: a delivered token waits beside it until the service accepts it', async () => { + const { fake, options, payload } = relaySite({ fake: { allow: [HOST] } }) + await sendThroughRelay(payload, options, MESSAGE) + const working = (await readRelayStore(payload)).token + // somebody who knows a live nonce delivers a token the service never issued + const nonce = 'q'.repeat(43) + await holdNonce(payload, nonce, 60_000) + await callConfirmRoute(payload)(`https://${HOST}/api/iapl/mail-relay/confirm`, { body: JSON.stringify({ nonce, state: 'active', token: `ims_${'z'.repeat(43)}` }), headers: {} }) + expect((await readRelayStore(payload)).token).toBe(working) + // the next send tries it, hears invalid-token, and goes back to the working token — without enrolling again + const before = fake.requests.length + expect((await sendThroughRelay(payload, options, { ...MESSAGE, subject: 'After' })).sent).toBe(true) + expect(fake.requests.slice(before).map((r) => r.path)).toEqual(['/v1/send', '/v1/send']) + expect(await readRelayCandidate(payload)).toBeNull() + expect((await readRelayStore(payload)).token).toBe(working) + }) + + test('is rate-limited per address', async () => { + const { payload } = relayPayload() + const confirm = callConfirmRoute(payload) + const statuses: number[] = [] + for (let i = 0; i < 12; i++) {statuses.push((await confirm(`https://${HOST}/api/iapl/mail-relay/confirm`, { body: '{}', headers: {} })).status)} + expect(statuses.slice(0, 10).every((s) => s === 404)).toBe(true) + expect(statuses.slice(10)).toEqual([429, 429]) + }) +}) + +describe('when the service asks the site to enrol again', () => { + test('a new server address (401 reverify): one enrolment, then the message goes out', async () => { + const { fake, options, payload } = relaySite({ fake: { allow: [HOST] } }) + await sendThroughRelay(payload, options, MESSAGE) + fake.clientAddress = '198.51.100.20' + const before = fake.requests.length + expect((await sendThroughRelay(payload, options, { ...MESSAGE, subject: 'Moved' })).sent).toBe(true) + expect(fake.requests.slice(before).map((r) => r.path)).toEqual(['/v1/send', '/v1/enrol', '/v1/send']) + expect(fake.outbox).toHaveLength(2) + }) + + test('a token the service no longer knows (401 invalid-token): the same', async () => { + const { fake, options, payload } = relaySite({ fake: { allow: [HOST] } }) + await sendThroughRelay(payload, options, MESSAGE) + const old = (await readRelayStore(payload)).token! + await fake.handle(new Request(`${fake.url}/v1/revoke`, { headers: { authorization: `Bearer ${old}` }, method: 'POST' })) + expect((await sendThroughRelay(payload, options, { ...MESSAGE, subject: 'Again' })).sent).toBe(true) + expect((await readRelayStore(payload)).token).not.toBe(old) + }) + + test('a site enrols at most once per message, and a refused enrolment is not asked again for a while', async () => { + const { fake, options, payload } = relaySite({ fake: { allow: [HOST], callSite: async () => new Response(null, { status: 404 }) } }) + const first = await sendThroughRelay(payload, options, MESSAGE) + expect(first).toMatchObject({ cause: 'callback-failed', code: 'relay-refused', sent: false }) + expect(first.sent === false && first.detail).toContain('confirm address') + expect(fake.requests.map((r) => r.path)).toEqual(['/v1/enrol']) + // the next message does not make the service call back again (a time-out there costs 8 seconds a message) + await sendThroughRelay(payload, options, MESSAGE) + expect(fake.requests.map((r) => r.path)).toEqual(['/v1/enrol']) + expect((await getRelayStatus(payload, options)).refusal).toMatchObject({ code: 'callback-failed', reason: 'status' }) + // "Connect again" asks at once + expect((await enrolRelay(payload, options, { force: true })).ok).toBe(false) + expect(fake.requests.map((r) => r.path)).toEqual(['/v1/enrol', '/v1/enrol']) + }) + + test('the answer to /v1/enrol is lost: the delivered token is tried next and becomes the token once the service accepts it', async () => { + const { fake, options, payload } = relaySite({ fake: { allow: [HOST] } }) + fake.intercept = async (request) => { + if (!request.url.endsWith('/v1/enrol')) {return undefined} + fake.intercept = undefined + await fake.handle(request) // the service does everything, call-back included … + return 'drop' // … and its answer never arrives + } + // The enrolment has no answer, but the call-back did deliver a token: the message's next attempt tries it, + // the service accepts it, and it becomes the token — without a second enrolment. + const first = await sendThroughRelay(payload, options, MESSAGE) + expect(first.sent).toBe(true) + expect(fake.requests.filter((r) => r.path === '/v1/enrol')).toHaveLength(1) + expect(fake.outbox).toHaveLength(1) + expect((await readRelayStore(payload)).token).toMatch(/^ims_/) + expect(await readRelayCandidate(payload)).toBeNull() + }) +}) + +describe('one message: one key, one encoding, three attempts', () => { + const capture = (fake: ReturnType['fake'], answers: Array<'drop' | 'pass' | Response>) => { + const sends: { body: string; key: null | string }[] = [] + fake.intercept = async (request) => { + if (!request.url.endsWith('/v1/send')) {return undefined} + sends.push({ body: await request.clone().text(), key: request.headers.get('idempotency-key') }) + const next = answers.shift() ?? 'pass' + return next === 'pass' ? undefined : next + } + return sends + } + const failing = (status: number, body: Record) => Response.json({ message: 'x', ok: false, ...body }, { status }) + const ready = async () => { + const site = relaySite({ fake: { allow: [HOST] } }) + await enrolRelay(site.payload, site.options) + return site + } + + test('a retryable failure is tried again with the same key and the same bytes; the third attempt is the last', async () => { + const { fake, options, payload } = await ready() + const sends = capture(fake, [failing(502, { code: 'backend-failed', retryable: true }), failing(503, { code: 'unavailable', retryable: true })]) + const result = await sendThroughRelay(payload, options, MESSAGE) + expect(result.sent).toBe(true) + expect(sends).toHaveLength(3) + expect(new Set(sends.map((s) => s.key)).size).toBe(1) + expect(sends[0].key).toMatch(/^[\w-]{16,128}$/) + expect(new Set(sends.map((s) => s.body)).size).toBe(1) + expect(fake.outbox).toHaveLength(1) + + const more = capture(fake, [1, 2, 3, 4].map(() => failing(502, { code: 'backend-failed', retryable: true }))) + const failed = await sendThroughRelay(payload, options, { ...MESSAGE, subject: 'Other' }) + expect(more).toHaveLength(3) + expect(failed).toMatchObject({ cause: 'backend-failed', code: 'relay-unreachable', confirmed: true, sent: false }) + expect(failed.sent === false && failed.detail).toMatch(/^Probably not sent/) + }) + + test('an answer that is not retryable is final: one request', async () => { + const { fake, options, payload } = await ready() + for (const [status, body, code] of [ + [429, { code: 'quota-exceeded', limit: 'hour', retryable: false }, 'relay-quota'], + [422, { code: 'recipient-suppressed', retryable: false }, 'relay-recipient-suppressed'], + [413, { code: 'too-large', limit: 'attachments', retryable: false }, 'relay-too-large'], + [422, { code: 'attachment-refused', field: 'attachments[0]', retryable: false }, 'relay-attachment-refused'], + [400, { code: 'invalid-request', field: 'subject', retryable: false }, 'relay-error'], + [418, { code: 'a-code-of-next-year', retryable: false }, 'relay-error'], + ] as const) { + const sends = capture(fake, [failing(status, body)]) + expect(await sendThroughRelay(payload, options, { ...MESSAGE, subject: code })).toMatchObject({ code, confirmed: true, sent: false }) + expect(sends).toHaveLength(1) + } + }) + + test('the ten seconds win over retryAfter: a long wait is not waited, the message is reported at once', async () => { + const { fake, options, payload } = await ready() + const sends = capture(fake, [Response.json({ code: 'rate-limited', message: 'x', ok: false, retryable: true, retryAfter: 60 }, { headers: { 'retry-after': '60' }, status: 429 })]) + const started = Date.now() + expect(await sendThroughRelay(payload, options, MESSAGE)).toMatchObject({ cause: 'rate-limited', code: 'relay-unreachable', sent: false }) + expect(sends).toHaveLength(1) + 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 () => { + const { fake, options, payload } = await ready() + const page = () => new Response('502 Bad Gateway', { headers: { 'content-type': 'text/html' }, status: 502 }) + const sends = capture(fake, [page(), page(), page()]) + expect(await sendThroughRelay(payload, options, MESSAGE)).toMatchObject({ cause: 'unavailable', code: 'relay-unreachable', confirmed: true, sent: false }) + expect(sends).toHaveLength(3) + // also a 200 whose body is not the contract's + const odd = capture(fake, [new Response('', { status: 200 }), Response.json(['ok']), Response.json({ ok: true }, { status: 201 })]) + expect((await sendThroughRelay(payload, options, { ...MESSAGE, subject: 'Odd' })).sent).toBe(false) + expect(odd).toHaveLength(3) + }) + + test('no answer at all is "not confirmed", never "not sent" — and the same message later goes out under the same key', async () => { + const { fake, options, payload, settings } = await ready() + const adapter = adapterOf(mailAdapter({ relay: options }), payload) + // the service takes the message; the connection breaks before its answer arrives, three times + const lose = async (request: Request) => { + if (!request.url.endsWith('/v1/send')) {return undefined} + await fake.handle(request) + return 'drop' as const + } + const keys: (null | string)[] = [] + fake.intercept = async (request) => { + if (request.url.endsWith('/v1/send')) {keys.push(request.headers.get('idempotency-key'))} + const saved = fake.intercept + fake.intercept = undefined + try { + return await lose(request) + } finally { + fake.intercept = saved + } + } + const result = (await adapter.sendEmail(MESSAGE)) as Record + expect(result).toMatchObject({ code: 'relay-not-confirmed', confirmed: false, sent: false }) + expect(String(result.error)).toMatch(/may not have been sent/) + expect(settings.emailStatus).toMatchObject({ code: 'relay-not-confirmed', state: 'degraded' }) + expect(keys).toHaveLength(3) + expect(fake.outbox).toHaveLength(1) // it did go out, once + + // somebody sends the same message again: same key, the service answers with the first result — no second mail + fake.intercept = async (request) => void (request.url.endsWith('/v1/send') && keys.push(request.headers.get('idempotency-key'))) + const again = (await adapter.sendEmail(MESSAGE)) as Record + expect(again).toMatchObject({ replayed: true, sent: true }) + expect(new Set(keys).size).toBe(1) + expect(fake.outbox).toHaveLength(1) + // once confirmed, the same content is a new message again + await adapter.sendEmail(MESSAGE) + expect(new Set(keys).size).toBe(2) + expect(fake.outbox).toHaveLength(2) + }) + + test('409 in-progress is "not confirmed" too', async () => { + const { fake, options, payload } = await ready() + capture(fake, [1, 2, 3].map(() => Response.json({ code: 'in-progress', message: 'x', ok: false, retryable: true, retryAfter: 1 }, { status: 409 }))) + expect(await sendThroughRelay(payload, options, MESSAGE)).toMatchObject({ code: 'relay-not-confirmed', confirmed: false, sent: false }) + }, 15_000) + + test('one attempt has a time-out, and a timed-out attempt is "no answer"', async () => { + const { fake, options, payload } = await ready() + const hanging = (async (_input: unknown, init?: RequestInit) => + new Promise((_resolve, reject) => init?.signal?.addEventListener('abort', () => reject(new DOMException('aborted', 'AbortError'))))) as typeof fetch + const result = await sendThroughRelay(payload, { ...options, fetchImpl: hanging, timeoutMs: 20 }, MESSAGE) + expect(result).toMatchObject({ code: 'relay-not-confirmed', confirmed: false, sent: false }) + expect(fake.outbox).toHaveLength(0) + }) +}) + +describe('what the site sends', () => { + test('bare addresses only, a subject without what the service refuses, files as base64, nothing else', () => { + expect(bareAddresses('Anna Nowak , "Kowalski, Jan" ; biuro@example.org').addresses).toEqual(['anna@example.org', 'jan@example.org', 'biuro@example.org']) + expect(bareAddresses([{ name: 'A', address: 'a@example.org' }, 'a@example.org', 'not an address', 'info@żółw.pl'])).toEqual({ addresses: ['a@example.org', 'info@xn--w-uga1v8h.pl'], dropped: 1 }) + expect(cleanSubject('Hello\r\nBcc: victim@example.net')).toBe('Hello Bcc: victim@example.net') + expect(cleanSubject('Invoice ‮fdp.exe​')).toBe('Invoice fdp.exe') + expect(cleanSubject('\u{1F469}‍\u{1F4BB} Straßen­bahn')).toBe('\u{1F469}‍\u{1F4BB} Straßen­bahn') + expect(cleanSubject('[Intecion Notifications Webservice] example.com waits for approval')).toBe('Intecion Notifications Webservice] example.com waits for approval') + expect([...cleanSubject('x'.repeat(400))]).toHaveLength(300) + expect(cleanSubject(' \n ')).toBe('(no subject)') + + const built = buildRelayMessage( + { + attachments: [{ content: Buffer.from('%PDF-1.7'), contentType: 'application/pdf; name="cv.pdf"', filename: '../"cv".pdf' }, { content: Buffer.alloc(0), filename: 'empty.txt' }], + bcc: 'c@example.org', cc: ['b@example.org'], from: 'ceo@example.com', headers: { 'Return-Path': 'x@example.net' }, html: '

Hi

', replyTo: 'r@example.org, other@example.org', subject: 'Hi', text: 'Hi', to: 'a@example.org', + } as never, + { kind: 'form-notification', senderName: ' Kancelaria​ Example ' }, + ) + expect(built.ok && built.request).toEqual({ + attachments: [{ content: Buffer.from('%PDF-1.7').toString('base64'), contentType: 'application/pdf', filename: '_cv_.pdf' }], + bcc: ['c@example.org'], cc: ['b@example.org'], html: '

Hi

', kind: 'form-notification', product: 'iapl', productVersion: expect.stringMatching(/^\d+\.\d+\.\d+/) as string, + replyTo: 'r@example.org', senderName: 'Kancelaria Example', subject: 'Hi', text: 'Hi', to: ['a@example.org'], + }) + expect(buildRelayMessage({ subject: 'x', to: 'nobody' } as never)).toMatchObject({ ok: false }) + expect(buildRelayMessage({ subject: 'x', to: 'a@example.org' } as never)).toMatchObject({ ok: false }) + expect(buildRelayMessage({ html: 'x', subject: 'x' } as never, { kind: 'security-alert' })).toMatchObject({ ok: true }) + }) + + test('a message the service would refuse for its shape still goes out (a visitor\'s words in the subject)', async () => { + const { fake, options, payload } = relaySite({ fake: { allow: [HOST] } }) + const result = await sendThroughRelay(payload, options, { html: '

x

', subject: 'Pytanie\r\nBcc: x@example.net ‮', to: 'Biuro ' }) + expect(result.sent).toBe(true) + expect(fake.outbox[0]).toMatchObject({ subject: 'Pytanie Bcc: x@example.net', to: ['office@example.org'] }) + }) + + test('a sender name the service does not accept: the mail goes out under the host, and the panel is told', async () => { + const { fake, logger, options, payload, settings } = relaySite({ fake: { allow: [HOST] }, integrations: { smtpFromName: 'PayPal Support' } }) + const adapter = adapterOf(mailAdapter({ relay: options }), payload) + const result = (await adapter.sendEmail(MESSAGE)) as Record + expect(result).toMatchObject({ senderName: HOST, sent: true, warnings: ['sender-name-replaced'] }) + expect(settings.emailStatus).toBeUndefined() // a warning, not a failure + expect((await getRelayStatus(payload, options)).nameReplaced).toMatchObject({ asked: 'PayPal Support', used: HOST }) + expect(logger.warn).toHaveBeenCalledTimes(1) + await adapter.sendEmail(MESSAGE) + expect(logger.warn).toHaveBeenCalledTimes(1) // said once, not on every message + // a better name clears it + settings.smtpFromName = 'Kancelaria Example' + await adapter.sendEmail(MESSAGE) + expect((await getRelayStatus(payload, options)).nameReplaced).toBeUndefined() + expect(fake.outbox[2].fromName).toBe('Kancelaria Example') + }) + + test('the limit on files comes from the service, and a file over it is not uploaded to hear so', async () => { + const { fake, options, payload } = relaySite({ fake: { allow: [HOST], limits: { maxAttachmentBytes: 1000 } } }) + const adapter = adapterOf(mailAdapter({ relay: options }), payload) + expect(await adapter.attachmentLimit?.()).toBeNull() // not enrolled yet: no number of the plugin's own + await adapter.sendEmail(MESSAGE) + expect(await adapter.attachmentLimit?.()).toBe(1000) + const before = fake.requests.length + const result = (await adapter.sendEmail({ ...MESSAGE, attachments: [{ content: Buffer.alloc(1001), filename: 'big.bin' }] })) as Record + expect(result).toMatchObject({ code: 'relay-too-large', sent: false }) + expect(fake.requests.slice(before).filter((r) => r.path === '/v1/send')).toHaveLength(0) + expect(((await adapter.sendEmail({ ...MESSAGE, attachments: [{ content: Buffer.alloc(1000), filename: 'ok.bin' }] })) as { sent: boolean }).sent).toBe(true) + expect(fake.outbox.at(-1)?.attachments).toEqual([{ bytes: 1000, contentType: 'application/octet-stream', filename: 'ok.bin' }]) + }) +}) + +describe('account mail is limited by the site itself', () => { + test('per address: the sixth "forgot password" for one address within the hour is held back, without a request', async () => { + const { fake, options, payload } = relaySite({ fake: { allow: [HOST] } }) + const send = (to: string) => sendThroughRelay(payload, options, withMailKind({ html: 'reset', subject: 'Reset your password', to }, 'account')) + for (let i = 0; i < 5; i++) {expect((await send('anna@example.org')).sent).toBe(true)} + const before = fake.requests.length + expect(await send('Anna@Example.org')).toMatchObject({ cause: 'client-account-mail-limit', code: 'relay-quota', sent: false }) + expect(fake.requests.length).toBe(before) + expect((await send('jan@example.org')).sent).toBe(true) // another account holder is not affected + expect(fake.outbox.every((m) => m.kind === 'account')).toBe(true) + }) + + test('the limit is the project\'s to change or switch off, and other kinds are not counted', async () => { + const strict = relaySite({ fake: { allow: [HOST] }, options: { accountMail: { perAddress: 1 } } }) + const account = withMailKind({ html: 'x', subject: 'Reset', to: 'anna@example.org' }, 'account') + expect((await sendThroughRelay(strict.payload, strict.options, account)).sent).toBe(true) + expect((await sendThroughRelay(strict.payload, strict.options, account)).sent).toBe(false) + clearRateLimits() + const off = relaySite({ fake: { allow: [HOST], limits: { messagesPerHour: 100 } }, options: { accountMail: false } }) + for (let i = 0; i < 8; i++) {expect((await sendThroughRelay(off.payload, off.options, { ...account, subject: `Reset ${i}` })).sent).toBe(true)} + clearRateLimits() + const forms = relaySite({ fake: { allow: [HOST] } }) + for (let i = 0; i < 8; i++) {expect((await sendThroughRelay(forms.payload, forms.options, withMailKind({ ...MESSAGE, subject: `Form ${i}` }, 'form-notification'))).sent).toBe(true)} + }) +}) + +describe('the token over time', () => { + test('rotation when the service says the token is due; the new token is stored at once', async () => { + const { fake, options, payload } = relaySite({ fake: { allow: [HOST] } }) + await sendThroughRelay(payload, options, MESSAGE) + await refreshRelayStatus(payload, options) + const first = (await readRelayStore(payload)).token + expect((await readRelayStore(payload)).service?.rotateAfter).toBeTruthy() + expect(await rotateRelayToken(payload, options)).toBe('not-due') + await updateRelayStore(payload, (c) => ({ ...c, service: { ...c.service!, rotateAfter: new Date(Date.now() - 1000).toISOString() } })) + const before = fake.requests.length + expect((await sendThroughRelay(payload, options, { ...MESSAGE, subject: 'Day 91' })).sent).toBe(true) + expect(fake.requests.slice(before).map((r) => r.path).slice(0, 2)).toEqual(['/v1/rotate', '/v1/send']) + const second = (await readRelayStore(payload)).token + expect(second).not.toBe(first) + expect(second).toMatch(/^ims_/) + }) + + test('two containers of one site: one rotation wins, the other reads the shared store and carries on', async () => { + const a = relaySite({ fake: { allow: [HOST] } }) + // the second container: its own process, the same database + const b = relayPayload() + ;(b.payload as unknown as { kv: unknown }).kv = (a.payload as unknown as { kv: unknown }).kv + await sendThroughRelay(a.payload, a.options, MESSAGE) + const old = (await readRelayStore(a.payload)).token! + expect(await rotateRelayToken(a.payload, a.options, { force: true })).toBe('rotated') + const fresh = (await readRelayStore(b.payload)).token + expect(fresh).not.toBe(old) + // a container that still held the old token asks too: already-rotated — the store has the newer one, nothing is lost + const late = await a.fake.handle(new Request(`${a.fake.url}/v1/rotate`, { headers: { authorization: `Bearer ${old}` }, method: 'POST' })) + expect(((await late.json()) as { code: string }).code).toBe('already-rotated') + expect((await sendThroughRelay(b.payload, a.options, { ...MESSAGE, subject: 'From B' })).sent).toBe(true) + expect((await readRelayStore(a.payload)).token).toBe(fresh) + }) + + test('already-rotated with no newer token in the store: the token is dropped and the next send enrols at once', async () => { + const { fake, options, payload } = relaySite({ fake: { allow: [HOST] } }) + await sendThroughRelay(payload, options, MESSAGE) + const old = (await readRelayStore(payload)).token! + // another process rotated and its answer was lost: the store still has the old token + await fake.handle(new Request(`${fake.url}/v1/rotate`, { headers: { authorization: `Bearer ${old}` }, method: 'POST' })) + expect(await rotateRelayToken(payload, options, { force: true })).toBe('failed') + expect((await readRelayStore(payload)).token).toBeUndefined() + expect((await sendThroughRelay(payload, options, { ...MESSAGE, subject: 'Healed' })).sent).toBe(true) + expect((await readRelayStore(payload)).token).not.toBe(old) + }) + + test('"Disconnect" gives the token up and stops the site from enrolling by itself; "Connect again" brings it back', async () => { + const { fake, options, payload } = relaySite({ fake: { allow: [HOST] } }) + await sendThroughRelay(payload, options, MESSAGE) + const old = (await readRelayStore(payload)).token! + await disconnectRelay(payload, options) + expect(await readRelayStore(payload)).toEqual({ disconnected: true, v: 1 }) + const refusedByService = await fake.handle(new Request(`${fake.url}/v1/status`, { headers: { authorization: `Bearer ${old}` } })) + expect(refusedByService.status).toBe(401) + const before = fake.requests.length + expect(await sendThroughRelay(payload, options, MESSAGE)).toMatchObject({ code: 'relay-disconnected', sent: false }) + expect(fake.requests.length).toBe(before) + expect((await enrolRelay(payload, options, { force: true })).ok).toBe(true) + expect((await sendThroughRelay(payload, options, MESSAGE)).sent).toBe(true) + }) + + 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 }) + expect(manual.fake.requests).toEqual([]) + await expect(setRelayToken(manual.payload, 'not-a-token')).rejects.toThrow() + await setRelayToken(manual.payload, manual.fake.issueToken(HOST)) + expect((await sendThroughRelay(manual.payload, manual.options, MESSAGE)).sent).toBe(true) + expect(manual.fake.requests.map((r) => r.path)).not.toContain('/v1/enrol') + expect((await getRelayStatus(manual.payload, manual.options)).tokenSource).toBe('manual') + + // a relay of one's own with a token from the deployment: nothing stored, nothing enrolled + const own = relaySite() + const token = own.fake.issueToken(HOST) + const options = { ...own.options, enrol: false as const, token: () => token } + expect((await sendThroughRelay(own.payload, options, MESSAGE)).sent).toBe(true) + expect((await readRelayStore(own.payload)).token).toBeUndefined() + expect((await getRelayStatus(own.payload, options)).tokenSource).toBe('option') + expect(await sendThroughRelay(own.payload, { ...own.options, token: () => undefined }, MESSAGE)).toMatchObject({ code: 'relay-refused', sent: false }) + }) +}) + +describe('the adapter on its own, and the deprecated Graph line', () => { + test('relayAdapter() is a whole e-mail adapter', async () => { + const { fake, payload } = relaySite({ fake: { allow: [HOST] }, integrations: { smtpFromName: 'Kancelaria Example' } }) + const adapter = adapterOf(relayAdapter({ fetchImpl: fake.fetch, url: fake.url }), payload) + expect(adapter).toMatchObject({ name: 'iapl-relay', defaultFromAddress: 'notification@webservices.intecion.net' }) + expect(((await adapter.sendEmail(MESSAGE)) as { sent: boolean }).sent).toBe(true) + expect(fake.outbox[0].fromName).toBe('Kancelaria Example') + }) + + test('a site on Microsoft Graph is told once per process that the transport is deprecated, and can silence it', async () => { + for (const name of GRAPH_ENV) {vi.stubEnv(name, 'x')} + const fetchImpl = (async () => Response.json({ access_token: 'a.b.c', expires_in: 3600 })) as unknown as typeof fetch + const loud = relaySite({ integrations: { emailTransport: 'graph', smtpFromAddress: 'biuro@example.com' } }) + const adapter = adapterOf(mailAdapter({ graph: { fetchImpl }, relay: loud.options }), loud.payload) + await adapter.sendEmail(MESSAGE) + await adapter.sendEmail(MESSAGE) + const warnings = loud.logger.warn.mock.calls.map((c) => String(c[0])).filter((m) => m.includes('deprecated')) + expect(warnings).toHaveLength(1) + expect(warnings[0]).toContain('removed in 2.0') + expect(loud.fake.requests).toEqual([]) // Graph in use: the service is not contacted + + resetGraphDeprecationWarning() + const quiet = relaySite({ custom: { iapl: { mail: { graphDeprecationWarning: false, relay: {} } } }, integrations: { emailTransport: 'graph' } }) + await adapterOf(mailAdapter({ graph: { fetchImpl } }), quiet.payload).sendEmail(MESSAGE) + expect(quiet.logger.warn.mock.calls.map((c) => String(c[0])).filter((m) => m.includes('deprecated'))).toEqual([]) + }) +}) diff --git a/test/mailRelay/helpers.ts b/test/mailRelay/helpers.ts new file mode 100644 index 0000000..cfa1141 --- /dev/null +++ b/test/mailRelay/helpers.ts @@ -0,0 +1,68 @@ +import type { BasePayload } from 'payload' + +import { readdirSync, readFileSync } from 'node:fs' +import path from 'node:path' +import { vi } from 'vitest' + +import type { FakeRelayOptions } from '../../src/modules/email/relay/fake.js' +import type { RelayOptions, ResolvedRelayOptions } from '../../src/modules/email/relay/options.js' + +import { relayConfirmEndpoint } from '../../src/modules/email/relay/confirm.js' +import { createFakeRelay } from '../../src/modules/email/relay/fake.js' +import { resolveRelayOptions } from '../../src/modules/email/relay/options.js' + +export const CONTRACT_DIR = path.resolve(import.meta.dirname, '../../contracts/mail-relay') + +export type ContractExample = { + client?: { reEnrol?: boolean; retry?: boolean; status?: null | string } + direction?: string + given?: Record + id: string + request: { body?: unknown; headers?: Record; method: string; path: string; schema?: string } + response: { body?: Record; schema?: string; status: number } + then?: { mail?: Record; mails?: number } +} + +export const contractExamples = (): ContractExample[] => + readdirSync(path.join(CONTRACT_DIR, 'examples')) + .filter((f) => f.endsWith('.json')) + .sort() + .map((f) => JSON.parse(readFileSync(path.join(CONTRACT_DIR, 'examples', f), 'utf8')) as ContractExample) + +/** The slice of Payload the relay client touches: the key-value store, the config, the logger, the two globals. */ +export function relayPayload({ custom, integrations = {}, serverURL = 'https://example.com', siteName = '' }: { custom?: object; integrations?: Record; serverURL?: string; siteName?: string } = {}) { + const store = new Map() + const logger = { error: vi.fn(), info: vi.fn(), warn: vi.fn() } + const settings = { ...integrations } + const payload = { + config: { custom: custom ?? {}, globals: [{ slug: 'site-integrations' }, { slug: 'site-settings' }], routes: { api: '/api' }, serverURL }, + findGlobal: vi.fn(async ({ slug }: { slug: string }) => (slug === 'site-settings' ? { siteName } : settings)), + kv: { + delete: async (key: string) => void store.delete(key), + get: async (key: string) => (store.has(key) ? structuredClone(store.get(key)) : null), + set: async (key: string, value: object) => void store.set(key, structuredClone(value)), + }, + logger, + updateGlobal: vi.fn(async ({ data }: { data: Record }) => Object.assign(settings, data)), + } + return { logger, payload: payload as unknown as BasePayload, settings, store } +} + +/** How the fake service reaches this site's confirm route: straight into the endpoint's handler. */ +export function callConfirmRoute(payload: BasePayload) { + const endpoint = relayConfirmEndpoint() + return async (url: string, init: { body: string; headers: Record }): Promise => { + const target = new URL(url) + if (target.pathname !== '/api/iapl/mail-relay/confirm') {return new Response(null, { status: 404 })} + const req = { headers: new Headers({ ...init.headers, 'x-forwarded-for': '198.51.100.7' }), payload, text: async () => init.body, url } + return (await endpoint.handler(req as never)) + } +} + +/** A site (the payload double) and a fake service that can call it back. */ +export function relaySite({ fake: fakeOptions, options: own, ...site }: { fake?: FakeRelayOptions; options?: RelayOptions } & Parameters[0] = {}) { + const made = relayPayload(site) + const fake = createFakeRelay({ callSite: callConfirmRoute(made.payload), ...fakeOptions }) + const options = resolveRelayOptions(made.payload, { fetchImpl: fake.fetch, retryBackoffMs: 1, url: fake.url, ...own }) as ResolvedRelayOptions + return { ...made, fake, options } +} diff --git a/test/mailRelayContract.test.ts b/test/mailRelayContract.test.ts new file mode 100644 index 0000000..c3b2643 --- /dev/null +++ b/test/mailRelayContract.test.ts @@ -0,0 +1,273 @@ +/** + * The plugin's copy of the wire contract of the Intecion Notifications Webservice (contracts/mail-relay, + * copied from the IWDL repository), and both sides of it as the plugin has them: + * - the copy is unedited (checksums) and is the version the client says it speaks; + * - the fake service (createFakeRelay) passes every example, through the contract's own runner; + * - the client does with each canned answer what the example's `client` block says: retry or not, + * enrol again or not, and the site status it reports; + * - the site's confirm route answers the call-back examples. + */ +import { execFileSync } from 'node:child_process' +import { randomBytes } from 'node:crypto' +import { readFileSync } from 'node:fs' +import path from 'node:path' +import { describe, expect, test, vi } from 'vitest' + +import { RELAY_BASE_URL, RELAY_CONFIRM_PATH, RELAY_CONTRACT_VERSION, RELAY_STATUS_CODES } from '../src/modules/email/relay/constants.js' +import { createFakeRelay } from '../src/modules/email/relay/fake.js' +import { sendThroughRelay } from '../src/modules/email/relay/send.js' +import { enrolRelay, refreshRelayStatus } from '../src/modules/email/relay/session.js' +import { holdNonce, readRelayCandidate, updateRelayStore } from '../src/modules/email/relay/store.js' +// the contract's runner is plain JavaScript, copied as it is +import { CONTRACT_VERSION, expand, runCallbackExample, runExample } from '../contracts/mail-relay/runner.mjs' +import { callConfirmRoute, CONTRACT_DIR, contractExamples, relayPayload, relaySite } from './mailRelay/helpers.js' + +vi.mock('server-only', () => ({})) + +const schema = JSON.parse(readFileSync(path.join(CONTRACT_DIR, 'schema.json'), 'utf8')) as { $defs: Record } +type Schema = { [key: string]: unknown } + +/** The part of JSON Schema 2020-12 the contract uses. Returns the problems found. */ +function validate(node: Schema, value: unknown, at = 'value'): string[] { + const out: string[] = [] + if (typeof node.$ref === 'string') {return validate(schema.$defs[node.$ref.replace('#/$defs/', '')], value, at)} + if ('const' in node && value !== node.const) {out.push(`${at}: not ${JSON.stringify(node.const)}`)} + if (Array.isArray(node.enum) && !node.enum.includes(value)) {out.push(`${at}: not one of ${node.enum.join(', ')}`)} + const type = node.type as string | undefined + const actual = Array.isArray(value) ? 'array' : value === null ? 'null' : Number.isInteger(value) ? 'integer' : typeof value + if (type && type !== actual && !(type === 'number' && actual === 'integer')) {return [...out, `${at}: ${actual}, expected ${type}`]} + if (typeof value === 'string') { + if (typeof node.minLength === 'number' && [...value].length < node.minLength) {out.push(`${at}: too short`)} + if (typeof node.maxLength === 'number' && [...value].length > node.maxLength) {out.push(`${at}: too long`)} + if (typeof node.pattern === 'string' && !new RegExp(node.pattern, 'u').test(value)) {out.push(`${at}: does not match ${node.pattern}`)} + } + if (typeof value === 'number' && typeof node.minimum === 'number' && value < node.minimum) {out.push(`${at}: below ${node.minimum}`)} + if (Array.isArray(value)) { + if (typeof node.minItems === 'number' && value.length < node.minItems) {out.push(`${at}: too few items`)} + if (typeof node.maxItems === 'number' && value.length > node.maxItems) {out.push(`${at}: too many items`)} + if (node.items) {value.forEach((item, i) => out.push(...validate(node.items as Schema, item, `${at}[${i}]`)))} + } + if (value && typeof value === 'object' && !Array.isArray(value)) { + const object = value as Record + const properties = (node.properties ?? {}) as Record + for (const name of (node.required ?? []) as string[]) { + if (!(name in object)) {out.push(`${at}: ${name} is missing`)} + } + for (const [name, child] of Object.entries(properties)) { + if (name in object) {out.push(...validate(child, object[name], `${at}.${name}`))} + } + if (node.additionalProperties === false) { + for (const name of Object.keys(object)) { + if (!(name in properties)) {out.push(`${at}: unknown field ${name}`)} + } + } + } + for (const part of (node.allOf ?? []) as Schema[]) {out.push(...validate(part, value, at))} + if (Array.isArray(node.anyOf) && !(node.anyOf as Schema[]).some((part) => validate(part, value, at).length === 0)) {out.push(`${at}: matches none of anyOf`)} + if (node.not && validate(node.not as Schema, value, at).length === 0) {out.push(`${at}: matches what it must not`)} + if (node.if) { + const branch = validate(node.if as Schema, value, at).length === 0 ? node.then : node.else + if (branch) {out.push(...validate(branch as Schema, value, at))} + } + return out +} + +const examples = contractExamples() +const toService = examples.filter((e) => e.direction !== 'service-to-site') +const HOST = 'example.com' +const RECIPIENT = 'office@example.com' +const ALERTS = 'alerts@intecion.example' +const sha = async (text: string) => Buffer.from(await crypto.subtle.digest('SHA-256', new TextEncoder().encode(text))).toString('hex') + +describe('the copied contract', () => { + test('is unedited: every file matches CHECKSUMS', () => { + const out = execFileSync('node', [path.join(CONTRACT_DIR, 'checksums.mjs'), '--check'], { encoding: 'utf8' }) + expect(out).toMatch(/files match CHECKSUMS/) + }) + + test('is the version the client says it speaks, with the client\'s constants', () => { + const version = readFileSync(path.join(CONTRACT_DIR, 'VERSION'), 'utf8').trim() + expect(RELAY_CONTRACT_VERSION).toBe(version) + expect(CONTRACT_VERSION).toBe(version) + const readme = readFileSync(path.join(CONTRACT_DIR, 'README.md'), 'utf8') + expect(readme).toContain(`**Base address: \`${RELAY_BASE_URL}\`**`) + // the confirm path the service calls for this product, under Payload's default API route + expect(readme).toContain(`| \`iapl\` | \`POST https:///api${RELAY_CONFIRM_PATH}\` |`) + expect(examples.find((e) => e.id === 'callback-confirm')?.request.path).toBe(`/api${RELAY_CONFIRM_PATH}`) + }) + + test('has the examples this file expects', () => { + expect(examples.length).toBeGreaterThanOrEqual(55) + expect(toService.length).toBeGreaterThanOrEqual(52) + }) +}) + +describe('the fake service speaks the contract (the contract\'s runner, every example)', () => { + for (const example of toService) { + test(example.id, async () => { + const given = example.given ?? {} + const calls = { confirm: 0 } + const fake = createFakeRelay({ + alertRecipient: ALERTS, + callSite: async (_url, init) => { + calls.confirm += 1 + const { nonce, token } = JSON.parse(init.body) as { nonce: string; token: string } + switch (given.callback) { + case 'no-content': + return new Response(null, { status: 204 }) + case 'not-found': + return new Response(null, { status: 404 }) + case 'redirect': + return new Response(null, { headers: { location: 'https://www.example.com/' }, status: 301 }) + case 'wrong-confirmation': + return Response.json({ confirmation: await sha(`${token}.${nonce}`) }) + default: + return Response.json({ confirmation: await sha(`${nonce}.${token}`) }) + } + }, + }) + let outboxStart = 0 + const driver = { + arrange: async () => { + let token = `ims_${'x'.repeat(43)}` + if (given.listed === true) {fake.allow(HOST)} + if (given.site && given.site !== 'none') { + token = fake.setSite(HOST, given.site as 'active') + if (given.token === 'previous') { + // the token in {{token}} was replaced a moment ago + const rotated = await fake.handle(new Request(`${fake.url}/v1/rotate`, { headers: { authorization: `Bearer ${token}` }, method: 'POST' })) + expect(rotated.status).toBe(200) + } + if (given.token === 'unknown') {token = `ims_${'u'.repeat(43)}`} + } + const site = fake.site(HOST) + if (site && given.quota === 'hour-exhausted') {site.hourOther = fake.limits.messagesPerHour} + if (site && given.quota === 'day-exhausted') {site.dayOther = fake.limits.messagesPerDay} + if (site && given.quota === 'hour-share-used') {site.hourOther = Math.floor((fake.limits.messagesPerHour * 4) / 5)} + if (site && given.quota === 'recipient-exhausted') {site.confirmations.set(RECIPIENT, fake.limits.perRecipientPerDay)} + if (given.backend) {fake.backend = given.backend as 'failure'} + const vars = { alertRecipient: ALERTS, host: HOST, idempotencyKey: randomBytes(18).toString('base64url'), nonce: randomBytes(32).toString('base64url'), recipient: RECIPIENT, senderAddress: 'notification@webservices.intecion.net', token } + if (given.idempotency === 'sent-same' || given.idempotency === 'sent-other') { + const body = expand(example.request.body, vars, example.id) as Record + const first = await fake.handle(new Request(`${fake.url}/v1/send`, { + body: JSON.stringify(given.idempotency === 'sent-same' ? body : { ...body, subject: 'Another message' }), + headers: { authorization: `Bearer ${token}`, 'content-type': 'application/json', 'idempotency-key': vars.idempotencyKey }, + method: 'POST', + })) + expect(first.status).toBe(200) + } + outboxStart = fake.outbox.length + return vars + }, + mails: async () => fake.outbox.slice(outboxStart), + request: async ({ body, headers, method, path: route }: { body?: unknown; headers: Record; method: string; path: string }) => { + const response = await fake.handle(new Request(`${fake.url}${route}`, { + body: body === undefined ? undefined : JSON.stringify(body), + headers: { ...headers, ...(given.address === 'unknown' ? { 'x-fake-client-address': '198.51.100.99' } : {}) }, + method, + })) + return { body: (await response.json().catch(() => null)) as unknown, headers: Object.fromEntries(response.headers), status: response.status } + }, + validate: (name: string, value: unknown) => validate(schema.$defs[name], value), + } + await runExample(example, driver) + // a suspended site is not called back; a refused request never reaches the site either + if (example.response.status === 403 || example.response.status === 400) {expect(calls.confirm).toBe(0)} + }) + } +}) + +describe('the client acts on each answer as the example says (canned answers)', () => { + const KNOWN = new Set(RELAY_STATUS_CODES) + + for (const example of toService.filter((e) => e.client)) { + test(example.id, async () => { + const client = example.client! + const route = example.request.path + const canned: Record = { message: 'canned', retryable: client.retry === true, ...example.response.body } + // /v1/send answers `ok: true` in full when the example only states part of it + const full: Record = canned.ok === true && route === '/v1/send' ? { id: 'm1', quota: {}, replayed: false, senderName: HOST, warnings: [], ...canned } : canned + const seen: string[] = [] + const { options, payload } = relaySite({ + options: { + fetchImpl: (async (input: Request | string | URL) => { + const target = String(input instanceof Request ? input.url : input) + const called = target.slice(target.indexOf('/mail') + 5) + seen.push(called) + // the answer under test comes from the example's own route; an enrolment on the way is refused, so it shows + if (called === route) {return Response.json(full, { status: example.response.status })} + return Response.json({ code: 'enrolment-closed', message: 'closed', ok: false, retryable: false }, { status: 403 }) + }) as typeof fetch, + }, + }) + if (route !== '/v1/enrol') {await updateRelayStore(payload, (c) => ({ ...c, host: HOST, state: 'active', token: `ims_${'t'.repeat(43)}` }))} + + let status: null | string = null + if (route === '/v1/send') { + const result = await sendThroughRelay(payload, options, { html: '

Hello.

', subject: 'New enquiry', to: RECIPIENT }) + status = result.sent ? (result.warnings.includes('sender-name-replaced') ? 'relay-name-replaced' : null) : result.code + expect(result.sent).toBe(full.ok === true) + // retried with the same request exactly when the example says so — three attempts in all, never more + expect(seen.filter((p) => p === '/v1/send').length).toBe(client.retry ? 3 : 1) + } else if (route === '/v1/enrol') { + const result = await enrolRelay(payload, options) + // the canned `200` carries no call-back, so no token arrived: only the refusals say something here + status = full.ok === true ? (full.state === 'pending' ? 'relay-pending' : null) : result.ok ? null : result.status + expect(seen.filter((p) => p === '/v1/enrol').length).toBe(1) + } else if (route === '/v1/status') { + const { error, stored } = await refreshRelayStatus(payload, options) + status = error ? null : stored.state === 'pending' ? 'relay-pending' : null + } else { + return // rotate, revoke: nothing a site reports + } + // enrols again exactly when the example says so + if (route !== '/v1/enrol') {expect(seen.includes('/v1/enrol')).toBe(client.reEnrol === true)} + if (client.status) { + expect(status).toBe(client.status) + // every status the contract suggests has a text of its own in the panel, or is the name warning + expect(KNOWN.has(client.status)).toBe(true) + } else if (full.ok !== true && !client.reEnrol && route === '/v1/send') { + // "report a bug" answers: not sent, and said so + expect(status).toBe('relay-error') + } + }) + } +}) + +describe('the site\'s confirm route answers the call-back examples', () => { + const ours = examples.filter((e) => e.direction === 'service-to-site' && e.request.path === `/api${RELAY_CONFIRM_PATH}`) + + test('both IAPL examples are here', () => { + expect(ours.map((e) => e.id).sort()).toEqual(['callback-confirm', 'callback-unknown-nonce']) + }) + + for (const example of ours) { + test(example.id, async () => { + const { payload } = relayPayload() + const confirm = callConfirmRoute(payload) + let raw = '' + const response = await runCallbackExample(example, { + confirm: async (request: { body: unknown; headers: Record; path: string }) => { + const answer = await confirm(`https://${HOST}${request.path}`, { body: JSON.stringify(request.body), headers: request.headers }) + raw = await answer.text() + return { body: raw ? (JSON.parse(raw) as unknown) : null, status: answer.status } + }, + prepare: async (body: { held: boolean; nonce: string }) => { + if (body.held) {await holdNonce(payload, body.nonce, 60_000)} + }, + }) + const sent = example.request.body as { nonce: string; token: string } + if (response.status === 200) { + // exactly this object and nothing else + expect(raw).toBe(JSON.stringify(example.response.body)) + expect(validate(schema.$defs.CallbackResponse, JSON.parse(raw))).toEqual([]) + expect((await readRelayCandidate(payload))?.token).toBe(sent.token) + // single use: the same call again is a 404 and changes nothing + expect((await confirm(`https://${HOST}/api${RELAY_CONFIRM_PATH}`, { body: JSON.stringify(sent), headers: {} })).status).toBe(404) + } else { + expect(raw).toBe('') + expect(await readRelayCandidate(payload)).toBeNull() + } + }) + } +})