Files
ipal-kit/contracts/mail-relay/README.md
T
Radosław SmolińskiandClaude Fable 5.2 ea9703f8e3 Mail relay: the built-in client for the Intecion Notifications Webservice
Transport, enrolment with the confirm route, token and state in payload-kv, rotation,
the panel's state block, doctor rules, the fake service and the copied contract 1.5.0.
Tests against the contract's runner and the fake. Docs and HTTP tests follow.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
2026-11-25 20:29:46 +01:00

473 lines
33 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# 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: <product>/<version>` (not checked, used for the log).
- **An answer that is not JSON** — an error page of the network in front of the service, an empty body, a cut-off
answer — is treated exactly like `503 unavailable` with `retryable: true`, whatever its status.
### 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://<host><confirm path of the product>`, 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": "<lowercase hex SHA-256 of nonce + \".\" + token>" }
```
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://<host>/api/iapl/mail-relay/confirm` | Under Payload's default API route (`/api`) |
| `iawl` | `POST https://<host>/?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 <host> <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": ["[email protected]"],
"replyTo": "[email protected]",
"senderName": "Kancelaria Example",
"subject": "New enquiry",
"text": "…", "html": "…",
"attachments": [{ "filename": "cv.pdf", "contentType": "application/pdf", "content": "<base64>" }]
}
```
- **`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: <host>` and `X-Intecion-Product: <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": "[email protected]" },
"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/<name>; 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.