Merge claude/iwsn-connect: "Połącz z IWSN" — the IAPL side of IWSN contract 1.8.0 (connect)
Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
@@ -1,5 +1,26 @@
|
||||
# Changelog of the wire contract
|
||||
|
||||
## 1.8.0 — 2026-12-01 (not released; no tag yet)
|
||||
|
||||
A site is confirmed by a person of Intecion on the service's own page (§2.1). Additive: a client of 1.7 keeps
|
||||
working — its sites enrol, are `pending`, and get `403 site-pending` until an operator confirms them by hand.
|
||||
**Client: to let its own administrator start the confirmation, add what is marked.**
|
||||
|
||||
- **New route `POST /v1/connect`** (token and `X-Intecion-Site`, no body). For a pending site it answers
|
||||
`{ ok, state: "pending", connectUrl, expiresAt }` — a link valid 15 minutes, for one confirmation, each call
|
||||
replacing the earlier link; for an active site `{ ok, state: "active" }`. **Client: a panel button that asks
|
||||
for the link from the server on the click and opens `connectUrl` in a new tab** (after checking that it
|
||||
begins with the service's base address and `/connect?`). Schema `ConnectResponse`.
|
||||
- **New code `503 connect-unavailable`** (not retryable): no confirmation page is set up. **Client: show "ask
|
||||
Intecion to confirm this site".**
|
||||
- **`/v1/status` of a pending site may carry `connectAvailable: true`.** **Client: show the button only then.**
|
||||
- **How a site learns that it was confirmed:** it asks `/v1/status` (at most every 5 seconds for at most 10
|
||||
minutes while the panel that opened the link is open, and on every panel load), or it simply sends. The
|
||||
service does not call the site. **Client: add the polling.**
|
||||
- `site-pending` now reads "not yet confirmed by Intecion"; its handling is unchanged.
|
||||
- Examples: `connect-pending`, `connect-active`, `connect-suspended`, `connect-unavailable`,
|
||||
`status-pending-connect`; `given.connect`.
|
||||
|
||||
## 1.7.1 — 2026-11-25 (not released; no tag yet)
|
||||
|
||||
Wording only; nothing for a client to change, and a copy of 1.7.0 need not be refreshed for it.
|
||||
|
||||
@@ -1,12 +1,16 @@
|
||||
3d5c4b7ed53fe6fe2c7c28826c0cf666f9c1d0b79f861b404503e7029728a61f README.md
|
||||
53da77d5dfff9948d68fca26b828563e21f83418245053d78b03a5aecac6c1d1 CHANGELOG.md
|
||||
249182a01164b81a5f7af87e5c5cdbd3344a80a7a66dfca624cecfb1501b2420 VERSION
|
||||
2ff0ad5b6a245365c0fa8733fa17b7bbd3ab91d4825981709d0fd02b762b939f schema.json
|
||||
9d8381d2e3465e97dc801a61f598fcf822e27e73a2c0729877744ec307097910 runner.mjs
|
||||
eabe3563e3ada8c4bb85ca03be33b259a38f80e49cc235603096e6efd74974a5 README.md
|
||||
af76187dbaf87e9ad8de8bf75f1066ec2f3120fb8d1de34feb2028d67f478f92 CHANGELOG.md
|
||||
3eb1ef94b5890ca727158b106142685c8733b0ace5bcb4cf3f0ac14f9f0643f4 VERSION
|
||||
9d1e429d266561d4b4baddee5fa8526c7fbce93dad0f16c32fe6e0999b5c9475 schema.json
|
||||
8a15b61b862fb01c8cb928ef202ba0bb14cf77cbce1fd1bfe32be6873d67989b runner.mjs
|
||||
7c46860adee597e570832c72bcdb418752a20b9f7d1b2d7a656ed065f9632b2a checksums.mjs
|
||||
df6015faf02a7cf7e9b5816b9e22b2e82968678ddd72a61c1f9665a8c0897ddf examples/callback-confirm-wordpress.json
|
||||
f5018ca4fb7d25794ee92168d715aaf47feeba3d907c0550651b16c10a691ceb examples/callback-confirm.json
|
||||
27bd95712cc36a71519cddc52c03d857b1009c2c384940dbc052022d86bc4231 examples/callback-unknown-nonce.json
|
||||
4008be4ec65e46d6a43221e400acf8682162cb14d54c5d8a4ab20b49e9985821 examples/connect-active.json
|
||||
9110ce20a6577b5884fa48a7ddb5d203f4671c863d56ef952a411907daaf45de examples/connect-pending.json
|
||||
6658a53ffec104a45e00fe962801bdc1a2b47a3f9cb10647d5405e0ed0355fa6 examples/connect-suspended.json
|
||||
394096063e2c135bb99622d4b37f65ad609cb276b610949fffdc26175cdb0dc9 examples/connect-unavailable.json
|
||||
de693b060c10c3d0f88fb8edfcd38c491cf141628d747328beee1b50c700c19b examples/enrol-address-literal.json
|
||||
7c4cf75eb9ab156a3031336ab2688e7c9dcd4cd266b7b7e5e4592285dcbd25ba examples/enrol-callback-no-content.json
|
||||
64466afc5bf0fecfa36f986d973cd987bbe1f64867e01cdf35e0de40838eb0d1 examples/enrol-callback-not-found.json
|
||||
@@ -60,5 +64,6 @@ ce4cbea2306f73bd5905249c10ab451a2599cb779e2386828971f40c97b8c591 examples/send-
|
||||
28e05f3c53cab6433b6af4d425511fa6655d0673df2e840af1fed9d25294a123 examples/send-unknown-token.json
|
||||
f105c38ab11ab5fc508ba0ed3f23f69108c318765c2670029b230b5b9a83912a examples/status-active.json
|
||||
89009ee9ab8f38e9ec290fb5412f206e1be28ad10fce6a7071d4406ac52dd4f0 examples/status-no-site-header.json
|
||||
28eeab5dc50c26f452e438f5cceddf99635ee7b3897e44dfe4255eb49123cc0f examples/status-pending-connect.json
|
||||
c9f49fa0dae1f0beacaacfe01660b467d06f990228c35a653307c8793f3c97a5 examples/status-pending.json
|
||||
afdb07ba8279479b6bbfdc4289efda657d4e5a9eccd94b8de165ec728b4a2386 examples/status-unknown-address.json
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
# Intecion Notifications Webservice — wire contract
|
||||
|
||||
Version: see [`VERSION`](VERSION) (this text describes **1.7.1**). Path prefix of this major version: `/v1`.
|
||||
Version: see [`VERSION`](VERSION) (this text describes **1.8.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
|
||||
@@ -63,7 +63,7 @@ Every refusal has the same body ([`Error`](schema.json)) — with one exception:
|
||||
| 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-pending` | Enrolled, not yet confirmed by Intecion (§2.1) | no | Keep the token; show "waiting for confirmation" with the connect button (§2.1) | `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` |
|
||||
@@ -85,6 +85,7 @@ Every refusal has the same body ([`Error`](schema.json)) — with one exception:
|
||||
| 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 |
|
||||
| 503 | `connect-unavailable` | `/v1/connect` only: the service has no confirmation page set up right now | no | Show "ask Intecion to confirm this site"; do not retry by itself | `relay-pending` |
|
||||
| 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
|
||||
@@ -240,6 +241,66 @@ Rules a client must know:
|
||||
site stores it the same way.
|
||||
- Use the token only from the site's server. Never print it, never send it to a browser.
|
||||
|
||||
### 2.1 Connecting a waiting site — `POST /v1/connect` (since 1.8.0)
|
||||
|
||||
An enrolment proves that a site is served at its host; it does not prove that the site is Intecion's. Under the
|
||||
service's `connect` policy every newly enrolled site is therefore **`pending`** and sends nothing
|
||||
(`403 site-pending`) until a person of Intecion confirms it on the service's own page, signed in with an
|
||||
`@intecion.com` address. The site's part is to hand that person the link:
|
||||
|
||||
1. **The site enrols as always** (§2). The answer says `"state": "pending"`; the token is stored as always.
|
||||
2. **An administrator of the site presses a button in the site's panel** ("Połącz z IWSN"). On that click — never
|
||||
on page load, never by itself — the site's **server** calls
|
||||
|
||||
```
|
||||
POST /v1/connect
|
||||
Authorization: Bearer ims_…
|
||||
X-Intecion-Site: example.com
|
||||
```
|
||||
|
||||
with no body (or `{}`). If the site holds no token yet it enrols first, as before any other call. The answer
|
||||
([`ConnectResponse`](schema.json)):
|
||||
|
||||
```json
|
||||
{ "ok": true, "state": "pending",
|
||||
"connectUrl": "https://webservices.intecion.net/mail/connect?ref=…",
|
||||
"expiresAt": "2026-12-01T10:15:00.000Z" }
|
||||
```
|
||||
|
||||
| Answer | Meaning | The panel |
|
||||
|---|---|---|
|
||||
| `200`, `state: "pending"`, `connectUrl`, `expiresAt` | A link for this host, valid **15 minutes**, usable for **one** confirmation. Each call makes a new link and the earlier one stops working | Opens `connectUrl` in a **new browser tab** |
|
||||
| `200`, `state: "active"` (no `connectUrl`) | The site is confirmed already | Shows "connected"; opens nothing |
|
||||
| `403 site-suspended` | Stopped by Intecion | As everywhere |
|
||||
| `503 connect-unavailable` | The service has no confirmation page right now | "Ask Intecion to confirm this site" (an operator can do it by hand) |
|
||||
| `429 rate-limited` | More than 10 links for this site within an hour | Wait `retryAfter` |
|
||||
| `401` / `403 host-mismatch` | As for every route with a token (§8) | Enrol again / forget the token, as there |
|
||||
|
||||
3. **The browser opens `connectUrl`** as a top-level navigation in a new tab
|
||||
(`target="_blank" rel="noopener noreferrer"`, or the equivalent after the click). The client
|
||||
- takes the address from the answer as it is and adds nothing to it;
|
||||
- opens it only if it begins with the service's base address followed by `/connect?` — anything else is a
|
||||
fault, shown as such;
|
||||
- never fetches it from the server, never puts it in a frame, never stores it and never writes it to a log.
|
||||
It is not a secret — it authorises nothing by itself, the person's sign-in does — but it is of use only
|
||||
for those fifteen minutes.
|
||||
4. **On the service's page** the person signs in (Cloudflare Access: a one-time code sent to their
|
||||
`@intecion.com` address), sees the host, and presses "Potwierdź". Nothing of this passes through the site.
|
||||
5. **The site learns that it is active by asking** — the service never calls the site for this:
|
||||
- `GET /v1/status` answers `"state": "active"`. While the panel that opened the link is open, the client
|
||||
asks **at most every 5 seconds, for at most 10 minutes**, then stops and shows "not confirmed yet" with
|
||||
the button again. It also asks whenever the panel is loaded.
|
||||
- Or simply by sending: the first `/v1/send` after the confirmation is accepted. Mail refused with
|
||||
`site-pending` before that was **not sent and is not kept by the service**; what a client does with it is
|
||||
what it does for any refusal that is not retryable.
|
||||
|
||||
**States a panel shows.** `pending` with `connectAvailable: true` in `/v1/status` (§4): "waiting for
|
||||
confirmation" and the button. `pending` without it: "waiting for approval by Intecion", no button. `active`:
|
||||
connected. `suspended`: stopped by Intecion.
|
||||
|
||||
A pending site that nobody confirms is forgotten 14 days after it first enrolled; it then enrols again by itself
|
||||
on its next send and is pending again.
|
||||
|
||||
## 3. Sending — `POST /v1/send`
|
||||
|
||||
Headers (`Bearer` in any case; one space; then the token exactly):
|
||||
@@ -360,7 +421,7 @@ not go out ([`StatusResponse`](schema.json)):
|
||||
|
||||
```json
|
||||
{ "ok": true, "state": "active", "host": "example.com", "product": "iapl",
|
||||
"service": { "name": "Intecion Notifications Webservice", "version": "1.0.0", "contract": "1.7.1" },
|
||||
"service": { "name": "Intecion Notifications Webservice", "version": "1.0.0", "contract": "1.8.0" },
|
||||
"sender": { "address": "[email protected]" },
|
||||
"limits": { "messagesPerHour": 30, "messagesPerDay": 200, "recipientsPerMessage": 10,
|
||||
"perRecipientPerDay": 10, "newRecipientsPerDay": 50,
|
||||
@@ -372,6 +433,9 @@ not go out ([`StatusResponse`](schema.json)):
|
||||
|
||||
A client takes its attachment limit from `limits.maxAttachmentBytes`, never from a constant of its own.
|
||||
|
||||
Since 1.8.0 the answer for a **pending** site may carry `"connectAvailable": true`: the site can be confirmed
|
||||
through `/v1/connect` (§2.1) and a panel shows the button. The field is left out otherwise.
|
||||
|
||||
## 5. Rotation — `POST /v1/rotate`
|
||||
|
||||
`Authorization: Bearer ims_…`, no body. When `token.rotateAfter` has passed (90 days after issue), the client
|
||||
@@ -474,6 +538,7 @@ Each file in `examples/` is one case:
|
||||
| `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 |
|
||||
| `connect` | `available`, `unavailable` | Whether the service's confirmation page is set up (§2.1). `available` when left out |
|
||||
|
||||
Variables: `{{host}}`, `{{token}}`, `{{nonce}}`, `{{idempotencyKey}}`, `{{recipient}}`, and — read from the
|
||||
service — `{{senderAddress}}`, `{{alertRecipient}}`.
|
||||
@@ -536,5 +601,8 @@ Checklist for a client:
|
||||
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`.
|
||||
8a. **Connect (§2.1):** a button for an administrator that asks `/v1/connect` from the server on the click and
|
||||
opens the answered `connectUrl` in a new tab after checking its beginning; `/v1/status` every 5 seconds for
|
||||
at most 10 minutes while that panel is open; the four states shown. No link is asked for on page load.
|
||||
9. Run the examples: the `client` block of each against canned answers, and the whole set against your local
|
||||
stand-in.
|
||||
|
||||
@@ -1 +1 @@
|
||||
1.7.1
|
||||
1.8.0
|
||||
|
||||
@@ -0,0 +1,31 @@
|
||||
{
|
||||
"id": "connect-active",
|
||||
"title": "A site that is confirmed already gets no link",
|
||||
"given": {
|
||||
"site": "active"
|
||||
},
|
||||
"request": {
|
||||
"method": "POST",
|
||||
"path": "/v1/connect",
|
||||
"headers": {
|
||||
"authorization": "Bearer {{token}}",
|
||||
"x-intecion-site": "{{host}}"
|
||||
}
|
||||
},
|
||||
"response": {
|
||||
"status": 200,
|
||||
"schema": "ConnectResponse",
|
||||
"body": {
|
||||
"ok": true,
|
||||
"state": "active"
|
||||
}
|
||||
},
|
||||
"client": {
|
||||
"retry": false,
|
||||
"reEnrol": false,
|
||||
"status": null
|
||||
},
|
||||
"then": {
|
||||
"mails": 0
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
{
|
||||
"id": "connect-pending",
|
||||
"title": "A waiting site asks for the link a person of Intecion confirms it with",
|
||||
"given": {
|
||||
"site": "pending"
|
||||
},
|
||||
"request": {
|
||||
"method": "POST",
|
||||
"path": "/v1/connect",
|
||||
"headers": {
|
||||
"authorization": "Bearer {{token}}",
|
||||
"x-intecion-site": "{{host}}"
|
||||
}
|
||||
},
|
||||
"response": {
|
||||
"status": 200,
|
||||
"schema": "ConnectResponse",
|
||||
"body": {
|
||||
"ok": true,
|
||||
"state": "pending"
|
||||
}
|
||||
},
|
||||
"client": {
|
||||
"retry": false,
|
||||
"reEnrol": false,
|
||||
"status": "relay-pending"
|
||||
},
|
||||
"then": {
|
||||
"mails": 0
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
{
|
||||
"id": "connect-suspended",
|
||||
"title": "A suspended site cannot be connected",
|
||||
"given": {
|
||||
"site": "suspended"
|
||||
},
|
||||
"request": {
|
||||
"method": "POST",
|
||||
"path": "/v1/connect",
|
||||
"headers": {
|
||||
"authorization": "Bearer {{token}}",
|
||||
"x-intecion-site": "{{host}}"
|
||||
}
|
||||
},
|
||||
"response": {
|
||||
"status": 403,
|
||||
"schema": "Error",
|
||||
"body": {
|
||||
"ok": false,
|
||||
"code": "site-suspended",
|
||||
"retryable": false
|
||||
}
|
||||
},
|
||||
"client": {
|
||||
"retry": false,
|
||||
"reEnrol": false,
|
||||
"status": "relay-suspended"
|
||||
},
|
||||
"then": {
|
||||
"mails": 0
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
{
|
||||
"id": "connect-unavailable",
|
||||
"title": "The service has no confirmation page set up: the site stays waiting and says whom to ask",
|
||||
"given": {
|
||||
"site": "pending",
|
||||
"connect": "unavailable"
|
||||
},
|
||||
"request": {
|
||||
"method": "POST",
|
||||
"path": "/v1/connect",
|
||||
"headers": {
|
||||
"authorization": "Bearer {{token}}",
|
||||
"x-intecion-site": "{{host}}"
|
||||
}
|
||||
},
|
||||
"response": {
|
||||
"status": 503,
|
||||
"schema": "Error",
|
||||
"body": {
|
||||
"ok": false,
|
||||
"code": "connect-unavailable",
|
||||
"retryable": false
|
||||
}
|
||||
},
|
||||
"client": {
|
||||
"retry": false,
|
||||
"reEnrol": false,
|
||||
"status": "relay-pending"
|
||||
},
|
||||
"then": {
|
||||
"mails": 0
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
{
|
||||
"id": "status-pending-connect",
|
||||
"title": "Status of a waiting site says that it can be confirmed through /v1/connect",
|
||||
"given": {
|
||||
"site": "pending"
|
||||
},
|
||||
"request": {
|
||||
"method": "GET",
|
||||
"path": "/v1/status",
|
||||
"headers": {
|
||||
"authorization": "Bearer {{token}}",
|
||||
"x-intecion-site": "{{host}}"
|
||||
}
|
||||
},
|
||||
"response": {
|
||||
"status": 200,
|
||||
"schema": "StatusResponse",
|
||||
"body": {
|
||||
"ok": true,
|
||||
"state": "pending",
|
||||
"connectAvailable": true
|
||||
}
|
||||
},
|
||||
"client": {
|
||||
"retry": false,
|
||||
"reEnrol": false,
|
||||
"status": "relay-pending"
|
||||
}
|
||||
}
|
||||
@@ -2,7 +2,7 @@
|
||||
// No dependency. Works in Node 20+ and in the Workers runtime (uses only WebCrypto, btoa and TextEncoder).
|
||||
// How to use it: README.md, "The examples and the runner".
|
||||
|
||||
export const CONTRACT_VERSION = '1.7.1'
|
||||
export const CONTRACT_VERSION = '1.8.0'
|
||||
|
||||
export class ContractError extends Error {
|
||||
constructor(exampleId, message) {
|
||||
|
||||
@@ -497,6 +497,10 @@
|
||||
"senderName": {
|
||||
"description": "The name the last mail left under, when there was one.",
|
||||
"type": "string"
|
||||
},
|
||||
"connectAvailable": {
|
||||
"description": "Only for a pending site, and only when true: the site can be confirmed through /v1/connect (contract 2.1).",
|
||||
"const": true
|
||||
}
|
||||
}
|
||||
},
|
||||
@@ -572,7 +576,8 @@
|
||||
"quota-exceeded",
|
||||
"backend-failed",
|
||||
"unavailable",
|
||||
"internal"
|
||||
"internal",
|
||||
"connect-unavailable"
|
||||
],
|
||||
"description": "The codes the service answers with today. The list grows with minor versions; that is why Error.code is an open string."
|
||||
},
|
||||
@@ -619,6 +624,63 @@
|
||||
"type": "string"
|
||||
}
|
||||
}
|
||||
},
|
||||
"ConnectResponse": {
|
||||
"description": "Answer of POST /v1/connect. For a pending site: a link for a person of Intecion, valid until expiresAt, usable for one confirmation. For an active site: no link.",
|
||||
"type": "object",
|
||||
"required": [
|
||||
"ok",
|
||||
"state"
|
||||
],
|
||||
"properties": {
|
||||
"ok": {
|
||||
"const": true
|
||||
},
|
||||
"state": {
|
||||
"enum": [
|
||||
"pending",
|
||||
"active"
|
||||
]
|
||||
},
|
||||
"connectUrl": {
|
||||
"type": "string",
|
||||
"pattern": "^https?://[^/?#\\s]+(/[A-Za-z0-9._~-]+)*/connect\\?ref=[A-Za-z0-9_-]{43}$",
|
||||
"description": "Opened by a person's browser as a top-level navigation. Never fetched by the site's server."
|
||||
},
|
||||
"expiresAt": {
|
||||
"type": "string",
|
||||
"format": "date-time"
|
||||
}
|
||||
},
|
||||
"if": {
|
||||
"properties": {
|
||||
"state": {
|
||||
"const": "pending"
|
||||
}
|
||||
}
|
||||
},
|
||||
"then": {
|
||||
"required": [
|
||||
"connectUrl",
|
||||
"expiresAt"
|
||||
]
|
||||
},
|
||||
"else": {
|
||||
"not": {
|
||||
"anyOf": [
|
||||
{
|
||||
"required": [
|
||||
"connectUrl"
|
||||
]
|
||||
},
|
||||
{
|
||||
"required": [
|
||||
"expiresAt"
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -14,6 +14,35 @@ once there are more than 20.
|
||||
This heading and the 1.17.2 section below (never released on its own) become one 1.18.0 entry at release. Read every
|
||||
"what changes for an existing site" list: the one here and the one in each subsection.
|
||||
|
||||
### IWSN: "Połącz z IWSN" — a person of Intecion connects the site (docs/email.md, contract 1.8.0)
|
||||
|
||||
> **What changes for an existing site:** nothing for a site whose "Sending method" is SMTP or Microsoft Graph, and
|
||||
> nothing for a site already active on IWSN. A site on IWSN that is new or still waits now shows **"Połącz z IWSN"**
|
||||
> on Site integrations → E-mail sending: pressing it opens the service's confirmation page in a new tab, where a
|
||||
> person of Intecion signs in with an `@intecion.com` address and presses "Potwierdź"; the panel then shows
|
||||
> "Connected to IWSN" by itself. Until then the site's e-mails are refused (`relay-pending`), the dashboard alert says
|
||||
> so, and `iapl-doctor --deep` reports an **error** (`mail-relay-connect`). No schema change, no import-map change.
|
||||
|
||||
- **The button** (state block on the e-mail tab, method IWSN): shown while the service offers the confirmation page
|
||||
(`connectAvailable` in `/v1/status`) or before the site has enrolled. A click asks the site's server for the link
|
||||
(`POST /api/iapl/mail-relay/connect-link`, admin only, enrolling first when there is no token); the server asks the
|
||||
service (`POST /v1/connect`), checks that the link begins with the service's own `{base}/connect?`, and hands it
|
||||
over without storing or logging it; the browser opens it with `noopener noreferrer`. The panel then asks
|
||||
`/v1/status` every 5 seconds for at most 10 minutes; every load of the panel asks too while the site waits.
|
||||
- **States shown:** "Waiting for confirmation" (with the button), "waiting for approval" (no button: no confirmation
|
||||
page), "Connected to IWSN", stopped. "The confirmation page is not available now" for `503 connect-unavailable`; a
|
||||
wait in minutes for more than 10 links an hour.
|
||||
- **Dashboard alert** for a waiting site (live, no call to the service); the text of `relay-pending` now speaks of
|
||||
confirmation.
|
||||
- **Doctor:** `mail-relay-connect` (error, deep) — the method is IWSN and the site is not connected or not confirmed.
|
||||
`mail-relay-state` no longer reports "waiting for approval" (warning) or "not enrolled yet" (info): both are this error.
|
||||
- **Opt-out:** `mail: { relay: { connectButton: false } }` — no button, no route.
|
||||
- **Building blocks:** `requestRelayConnectLink(payload, options?)` (`ConnectLinkResult`), `isRelayConnectUrl(url, base)`,
|
||||
`RELAY_CONNECT_LINK_PATH`, `RelayStatus.connectAvailable`; `relayPanelEndpoints(own, { connectLink })`. The stand-in:
|
||||
`createFakeRelay({ connect: 'available' | 'unavailable' })`, `relay.confirmConnect(connectUrl)`, `connectAvailable` in
|
||||
its `/v1/status`, `/v1/connect`.
|
||||
- The contract copy is 1.8.0 (`RELAY_CONTRACT_VERSION`); additive, every other route unchanged.
|
||||
|
||||
### Two-step verification: the first set-up is confirmed by e-mail (docs/security.md)
|
||||
|
||||
> **Read before upgrading — what changes for an existing site, most important first:**
|
||||
|
||||
+8
-2
@@ -1363,8 +1363,12 @@ reports `mail-method` info (nothing picked yet) or nothing (picked and usable).
|
||||
3. The server may call `https://webservices.intecion.net`.
|
||||
4. Site integrations → E-mail sending: "Sender name" (else the site name is used) and **"Sender address"** — with
|
||||
the mail service that is where replies go; the service's own address has no mailbox.
|
||||
5. Nothing to arrange with Intecion: a site that passes the call-back is active at once (`relay-pending`, held for
|
||||
approval, is the exception — the panel says so).
|
||||
5. **A person of Intecion connects the site** (contract 1.8.0): after its first e-mail (or the button) the site waits
|
||||
(`relay-pending`). Site integrations → E-mail sending → **"Połącz z IWSN"** opens the service's confirmation page in a
|
||||
new tab; a person of Intecion signs in with an `@intecion.com` address and presses "Potwierdź"; the block shows
|
||||
"Connected to IWSN" by itself (it asks every 5 s for 10 min, and on every load while the site waits). Tell the owner
|
||||
that step is theirs. Nothing to paste, no token. Opt-out: `mail: { relay: { connectButton: false } }` (no button, no
|
||||
route). **Verify:** `iapl-doctor --deep` has no `mail-relay-connect` error; a test e-mail answers "through IWSN".
|
||||
6. **Launch needs nobody:** a site enrolled on its development address and then served on the real domain (or moved
|
||||
to another domain) enrols by itself on its first e-mail. **A non-public copy does not send by itself:** a site
|
||||
whose host matches `iapl({ developmentHosts })` — default `['*.dev.netscale.pl']`, Intecion's development
|
||||
@@ -1414,6 +1418,7 @@ overrides per adapter; `resolveRelayOptions` reads what is in effect):
|
||||
| `otherHosts` | `'auto'` | a database holding another host's connection: a public site enrols by itself (launch, a move), a non-public one (`IAPL_NOINDEX=1` / `developmentHosts`) neither enrols nor sends until "Connect again"; a list of the site's own other hosts; `'wait'` (a public site without a connection waits too); `'enrol'` (no rule) |
|
||||
| `developmentHosts` | `iapl({ developmentHosts })`, default `DEFAULT_DEVELOPMENT_HOSTS` = `['*.dev.netscale.pl']` (`pluginDevelopmentHosts`) | host patterns (`*`) of development and staging addresses, for the mail service alone: a site there is non-public for `otherHosts` with no env (`siteIsNonPublic`, `siteNonPublicSignal` → `NonPublicSignal`, `matchDevelopmentHost`, `isDevelopmentHost`); `[]` = none. Checked when the config is built (`assertDevelopmentHosts`): not an array of non-empty host patterns, or a lone `*` → the site does not start; Unicode patterns are punycoded, a trailing dot and the port are ignored |
|
||||
| `enrol` | `'auto'` | `'manual'` (only "Connect again" / `enrolRelay`), `false` (token from `token` / `setRelayToken`) |
|
||||
| `connectButton` | `true` | `false`: no "Połącz z IWSN" and no `POST /api/iapl/mail-relay/connect-link`; confirm by an operator or with `requestRelayConnectLink` |
|
||||
| `accessKeyField` | `false` | `true`: admins get "Enter an access key" in the state block (a hand-issued token) |
|
||||
| `token` | — | a token from elsewhere; nothing is stored, the site does not enrol |
|
||||
| `senderName` | panel → site name (`relaySenderName`) | fixed name or function |
|
||||
@@ -1447,6 +1452,7 @@ needs more: Intecion raises the limits, or SMTP.
|
||||
|---|---|
|
||||
| The transport alone, no SMTP / Graph | `email: relayAdapter()` (`RelayAdapterArgs`) |
|
||||
| Enrol from a deploy script; state; rotate; disconnect; a token issued by hand | `enrolRelay` (`EnrolResult`), `getRelayStatus` (`RelayStatus`), `rotateRelayToken`, `disconnectRelay`, `setRelayToken` |
|
||||
| A button of your own for the confirmation by Intecion | `requestRelayConnectLink(payload)` (`ConnectLinkResult`: `{ state: 'pending', connectUrl, expiresAt }` / `{ state: 'active' }` / a refusal) on a person's click only; open `connectUrl` in a new tab with `noopener noreferrer`; never store, log or fetch it; `isRelayConnectUrl(url, base)`; the route `RELAY_CONNECT_LINK_PATH`; the stand-in `createFakeRelay({ connect })` + `relay.confirmConnect(url)` |
|
||||
| Your own state block or panel route | `mailPanelState` (`MailPanelState`), `relayPanelEndpoints`, `relayConfirmEndpoint`; the plugin's component is `MailRelayStatus` (`/admin`) |
|
||||
| One message with the retry rule; one HTTP call | `sendThroughRelay` (`RelaySendContext`, `RelaySendResult`), `relayRequest` (`RelayCall`, `RelayAnswer`, `RelayRefusal`) |
|
||||
| The request the service takes | `buildRelayMessage` (`BuildRelayMessageArgs`, `BuiltRelayMessage`, `RelaySendRequest`), `bareAddress`, `bareAddresses`, `cleanSubject` |
|
||||
|
||||
@@ -122,7 +122,7 @@ through this procedure. Ask only when you are missing something you cannot get y
|
||||
| a site sends nothing: "The data comes from another site (…), so this copy does not send e-mails by itself" / `relay-refused`, cause `client-other-host` | the site is non-public — its host matches `developmentHosts` (built in: `*.dev.netscale.pl`) or `IAPL_NOINDEX=1` is set; `iapl-doctor --deep` says which (`mail-non-public`) — and its database holds another host's connection: a staging copy of production, or production's data copied back onto the development address. Expected — a copy with production's data must not mail real people by itself | should it send: "Connect again" in the state block, once (until the data is replaced). A copy that must never send: `mail: { relay: false }` or SMTP to a catcher. **The production site itself says this:** `IAPL_NOINDEX` was left set after launch — remove it; or its host matches a development pattern — take it out of `iapl({ developmentHosts })` |
|
||||
| the site does not start: "[iapl] … developmentHosts must be an array of host patterns …" | the list is not an array of non-empty host patterns (a single string, `null`, `['']`), or holds a lone `*` | write it as `['*.dev.netscale.pl', 'staging.client.pl']`; `[]` = none; to change who waits use `mail.relay.otherHosts` |
|
||||
| a staging or test copy **does** send, to real addresses | its host matches no development pattern and it has no `IAPL_NOINDEX=1`, so it looks like a launch (a public site enrols by itself); the doctor's deep run notes "the database also holds the mail-service connection of another host" | name its host in `iapl({ developmentHosts: ['*.dev.netscale.pl', '<the copy's pattern>'] })`, or `IAPL_NOINDEX=1` on the copy; to be sure: `mail: { relay: false }` or SMTP to a catcher |
|
||||
| `relay-pending` / "waiting for approval" | while the service runs with enrolment "pending" (from its launch until Intecion switches to open enrolment), every new site waits for approval; after that, the exception (many new sites at once, or approval by hand) | Intecion approves it on the service; nothing to change on the site; the same token then works |
|
||||
| `relay-pending` / "Waiting for confirmation" / doctor `mail-relay-connect` | a new site waits until a person of Intecion confirms it (contract 1.8.0) | Site integrations → E-mail sending → "Połącz z IWSN"; the person signs in with an @intecion.com address on the page that opens and presses "Potwierdź"; the block turns "Connected" by itself. "Waiting for approval" with no button, or "the confirmation page is not available": Intecion confirms the host by hand. "Too many confirmation links": wait the minutes it says. The same token works afterwards |
|
||||
| `relay-suspended` | Intecion stopped the site (abuse, a flood from a form) | contact Intecion; fill in SMTP meanwhile |
|
||||
| `relay-disconnected` | an admin pressed "Disconnect" | "Connect again", or SMTP |
|
||||
| `relay-quota` | the site's hour or day is used up (30 / 200 by default), more than 10 recipients, more than 10 confirmations to one address a day, too many new addresses, or the site's own limit on account mail (`mail.relay.accountMail`) | the server log names the limit; look for a form being abused (Turnstile on? rate limit?); a site that really sends more: Intecion raises the limits, or SMTP |
|
||||
|
||||
@@ -669,7 +669,7 @@ scaling (5). `●` routes for pages need the database at build time (PROGRAMISTA
|
||||
6. **Notifications**: form messages in every language.
|
||||
7. **Site integrations → E-mail sending**: "Sender name" (the client's name; empty = the site name) and **"Sender
|
||||
address"** (the client's address: with the mail service replies go there). "Sending method" stays **IWSN (built-in)**; choose **Own SMTP server** and fill in its fields **only** when the client asked
|
||||
for its own server — what is chosen is what is used, an incomplete SMTP server sends nothing. A new site sends through IWSN with nothing picked; picking another option and saving stores it (the panel warns before the save when its settings are incomplete). On the production domain: the block "How e-mails are sent" must say "Connected to IWSN" ("waiting for approval": while the service runs with enrolment "pending" (from its launch until Intecion switches to open enrolment), every new site waits for approval — ask Intecion to approve the host; under open enrolment it is the exception; the real domain enrols by itself at launch although the site was connected on its development address — nothing to press; "The data comes from another site" = the site is non-public (its host matches `developmentHosts`, built in `*.dev.netscale.pl`, or `IAPL_NOINDEX=1`) and holds a copy of another site's data: press "Connect again" only if the copy should send — on the production domain it means `IAPL_NOINDEX` was left set. A development address under `*.dev.netscale.pl` needs nothing; a staging or test copy on any other host must have its host in `iapl({ developmentHosts: […] })` (an array of host patterns: a single string, an empty entry or a lone `*` stops the start) or `IAPL_NOINDEX=1`, or it mails the real addresses in its data), then **Send test e-mail** → "through IWSN". Turnstile (for testing site
|
||||
for its own server — what is chosen is what is used, an incomplete SMTP server sends nothing. A new site sends through IWSN with nothing picked; picking another option and saving stores it (the panel warns before the save when its settings are incomplete). On the production domain: the block "How e-mails are sent" must say "Connected to IWSN" ("Waiting for confirmation": press "Połącz z IWSN" and have a person of Intecion confirm the site on the page that opens — the owner's step, @intecion.com sign-in; "waiting for approval" with no button: ask Intecion; the real domain enrols by itself at launch although the site was connected on its development address — nothing to press; "The data comes from another site" = the site is non-public (its host matches `developmentHosts`, built in `*.dev.netscale.pl`, or `IAPL_NOINDEX=1`) and holds a copy of another site's data: press "Connect again" only if the copy should send — on the production domain it means `IAPL_NOINDEX` was left set. A development address under `*.dev.netscale.pl` needs nothing; a staging or test copy on any other host must have its host in `iapl({ developmentHosts: […] })` (an array of host patterns: a single string, an empty entry or a lone `*` stops the start) or `IAPL_NOINDEX=1`, or it mails the real addresses in its data), then **Send test e-mail** → "through IWSN". Turnstile (for testing site
|
||||
`1x00000000000000000000AA`, secret `1x0000000000000000000000000000000AA`; production keys from the client), analytics/pixel
|
||||
IDs, IndexNow → generate key. Mail/Turnstile errors show up as a dashboard alert.
|
||||
8. **Forms**: check the addresses in the Emails tab of the seeded forms.
|
||||
|
||||
@@ -714,7 +714,7 @@ PROGRAMISTA §6, items 73–75; email.md; AGENT.md §7.2) — nothing to run; re
|
||||
3. **For a site that will use the mail service:** `serverURL` is the public address the site answers on without a
|
||||
redirect; no proxy or WAF rule blocks `/api/iapl/mail-relay/confirm`; `trailingSlash: true` or another `routes.api` →
|
||||
Intecion sets the site's confirm address first; "Sender address" is filled in (replies go there); the client's
|
||||
processing agreement names the service. Tell Intecion the host: while the service runs with enrolment "pending" (from its launch until Intecion switches to open enrolment), every new site waits for approval (the panel says "waiting for approval"); under open enrolment a site is active as soon as it enrols.
|
||||
processing agreement names the service. A new site waits until a person of Intecion confirms it: "Połącz z IWSN" in the panel (contract 1.8.0).
|
||||
**Launch and a domain move need nothing:** the real domain enrols by itself although the database holds the
|
||||
development address's connection. **A staging or test copy of the database** neither enrols nor sends by itself
|
||||
**when it is non-public**: its host matches `iapl({ developmentHosts })` — built in `*.dev.netscale.pl`, so the
|
||||
@@ -736,7 +736,16 @@ PROGRAMISTA §6, items 73–75; email.md; AGENT.md §7.2) — nothing to run; re
|
||||
**Check:** `pnpm exec iapl-doctor --deep --url <site>` → no `mail-transport` / `mail-relay-state` / `mail-reply-address` /
|
||||
`mail-relay-route` finding (or only `mail-graph-deprecated` on a Graph site); Site integrations → E-mail sending →
|
||||
**Send test e-mail** names the transport you expect; a form submission arrives. **The service is live at
|
||||
`https://webservices.intecion.net/mail`; while the service runs with enrolment "pending" (from its launch until Intecion switches to open enrolment), every new site waits for approval — keep SMTP until it is approved, or `relay: false`.**
|
||||
`https://webservices.intecion.net/mail`; a new site waits until a person of Intecion confirms it ("Połącz z IWSN") — keep SMTP until then, or `relay: false`.**
|
||||
|
||||
**→ 1.18.0, IWSN is connected by a person of Intecion (CHANGELOG "Unreleased (for 1.18.0)" → "IWSN: Połącz z IWSN"; email.md "The mail service"; AGENT.md §7.2 point 5) — nothing to run:**
|
||||
1. No schema change, no migration, no import-map change. Sites whose "Sending method" is SMTP or Microsoft Graph see no
|
||||
change at all.
|
||||
2. A site on IWSN that is already active stays active. A site that waits (`relay-pending`, or doctor `mail-relay-connect`
|
||||
error after the upgrade): Site integrations → E-mail sending → **"Połącz z IWSN"** → a person of Intecion confirms
|
||||
it on the page that opens (an @intecion.com sign-in — the owner's step, tell them) → the block says "Connected to
|
||||
IWSN" by itself. Then send a test e-mail.
|
||||
3. A project that does not want the button: `mail: { relay: { connectButton: false } }` (no button, no route).
|
||||
|
||||
**→ 1.17.1, e-mail (CHANGELOG 1.17.1 point 5; PROGRAMISTA §6, item 82; email.md "Which transport a send takes"; AGENT.md §7.2) — nothing to run, one check:**
|
||||
1. **MongoDB: no migration. Postgres / SQLite: `pnpm payload migrate:create`** (the new field `emailMethod` is a column),
|
||||
|
||||
+2
-1
@@ -131,7 +131,8 @@ Turn off: `iapl({ doctor: false })`. Adapt: `iapl({ doctor: { tokenVar: 'MY_TOKE
|
||||
| mail | `mail-method` | error / info | (deep) the chosen "Sending method" can be used — "Own SMTP server" with server, user name and password, "Microsoft Graph" with the `GRAPH_*` variables; otherwise e-mails are not sent and nothing is sent another way (error). On Postgres / SQLite: the column of `emailMethod` exists — the 1.17.1 migration has run (error). Nobody has chosen yet: the site picks a method from what is filled in until Site integrations is saved (info) |
|
||||
| | `mail-transport` | error / warning | (deep) an e-mail transport is in effect (not: the mail service switched off and no SMTP server); the last sends worked — failing: warning, error once it has lasted 24 hours |
|
||||
| | `mail-non-public` | info | (deep) on the mail service: says which signal makes the site a non-public copy — its host matches a development pattern (`developmentHosts`, named in the finding) or `IAPL_NOINDEX` is set — and what to change if the site is in fact the public one |
|
||||
| | `mail-relay-state` | error / warning / info | (deep) on the Intecion mail service: not disconnected and not stopped (error), not waiting for approval, not refused at enrolment, not a non-public copy of another site's database that waits for "Connect again" (`client-other-host`), the sender name not replaced (warning); not enrolled yet, and a public site whose database also holds another host's connection — its own past after a launch or a move, or a copy that forgot `IAPL_NOINDEX=1` (info) |
|
||||
| | `mail-relay-connect` | error | (deep) the sending method is IWSN and the site is connected and confirmed — not "not enrolled yet", not waiting for confirmation by Intecion (contract 1.8.0). The fix names "Połącz z IWSN", or Intecion when the service offers no confirmation page |
|
||||
| | `mail-relay-state` | error / warning / info | (deep) on the Intecion mail service: not disconnected and not stopped (error), not refused at enrolment, not a non-public copy of another site's database that waits for "Connect again" (`client-other-host`), the sender name not replaced (warning); a public site whose database also holds another host's connection — its own past after a launch or a move, or a copy that forgot `IAPL_NOINDEX=1` (info) |
|
||||
| | `mail-reply-address` | warning | (deep) on the mail service, "Sender address" is filled in: replies go there |
|
||||
| | `mail-graph-deprecated` | warning | Microsoft Graph is not in use: no `GRAPH_*` variables on the site (deep), no `graphAdapter` / `emailGraph: true` in the config — deprecated, removed in 2.0 |
|
||||
| | `mail-relay-route` | warning | nothing keeps the mail service from confirming the site: no `trailingSlash: true`, `routes.api` is `/api` (else Intecion sets the site's confirm address); live, on the mail service: `/api/iapl/mail-relay/confirm` answers without a redirect, a block or a server error. Skipped with `relay: false` |
|
||||
|
||||
+36
-12
@@ -136,10 +136,28 @@ What the site needs for it:
|
||||
443, **without a redirect** — the service follows none. No basic auth, no firewall rule, no maintenance page in
|
||||
front of it. (Coolify: nothing to set; the route is part of Payload's API.)
|
||||
- **Outbound HTTPS** from the server to `webservices.intecion.net`.
|
||||
- **A site that passes the call-back is active at once.** Waiting for approval is the exception: the service
|
||||
holds a new site back when many new sites appear at once (more than a few a day from one address or domain, or
|
||||
more than its daily number in all), or when Intecion has set it to approve by hand. Mail is then not sent until
|
||||
Intecion approves the site; the same token works afterwards, and the panel says so.
|
||||
- **A new site is connected by a person of Intecion** (contract 1.8.0 §2.1, the service's `connect` policy). It
|
||||
enrols as before, then **waits** (`pending`): its mail is refused with `site-pending` (status `relay-pending`), not
|
||||
sent and not kept. On Site integrations → E-mail sending, with "IWSN (built-in)" as the method, an administrator
|
||||
presses **"Połącz z IWSN"** ("Connect to IWSN"). The site's **server** asks the service for a link
|
||||
(`POST /v1/connect`) and the panel opens it **in a new tab** (`noopener noreferrer`). A person of Intecion signs
|
||||
in there with an `@intecion.com` address (Cloudflare Access) and presses "Potwierdź". The panel asks the service
|
||||
every 5 seconds for at most 10 minutes and shows "Connected to IWSN" by itself; every load of the panel asks too
|
||||
while the site waits. Mail sent after that leaves; mail refused before it is not sent again.
|
||||
- The link is valid 15 minutes, for one confirmation; each press makes a new one. It is opened only when it begins
|
||||
with the service's own `{base}/connect?` (the plugin checks it on the server and in the browser), and it is
|
||||
never stored, logged or fetched by the server.
|
||||
- What the block says: **"Waiting for confirmation"** with the button (the service offers the page:
|
||||
`connectAvailable`); **"waiting for approval"** with no button (no confirmation page — an operator confirms the
|
||||
site); **"Connected to IWSN"**; **stopped** (suspended). A site that has not enrolled yet shows the button too:
|
||||
pressing it enrols first.
|
||||
- When the service has no confirmation page right now (`503 connect-unavailable`) the panel says "ask your
|
||||
administrator to have the site confirmed"; more than 10 links an hour (`429`) says when to try again.
|
||||
- The dashboard alert shows a waiting site; `iapl-doctor --deep` reports it as an **error** (`mail-relay-connect`).
|
||||
- No token or paste field is involved. Sites on SMTP or Microsoft Graph see nothing of this.
|
||||
- **Opt-out:** `mail: { relay: { connectButton: false } }` — no button and no route; the site is then confirmed by
|
||||
an operator, or by the project's own button with `requestRelayConnectLink(payload)` (open the answered
|
||||
`connectUrl` in a new tab; `isRelayConnectUrl(url, base)` checks it).
|
||||
|
||||
A site on `localhost`, on a private address or without `serverURL` is refused **by the plugin itself**, before any
|
||||
call leaves the server — development machines do not contact the service. To test mail locally use SMTP (a local
|
||||
@@ -392,18 +410,19 @@ await runWithMailKind('account', () => sendWelcomeMails(payload, user))
|
||||
|
||||
Site integrations → E-mail sending starts with "How e-mails are sent" (component `MailRelayStatus` from `/admin`,
|
||||
rendered by the tab's status banner — **no import-map entry of its own, so nothing to regenerate**): the
|
||||
transport in effect; for the mail service the state (connected, waiting for approval, stopped, not connected and
|
||||
why), the address mail leaves from, where replies go, what is left of the hour and the day, and a sender name the
|
||||
transport in effect; for the mail service the state (connected, waiting for confirmation — with "Połącz z IWSN" —,
|
||||
waiting for approval, stopped, not connected and why), the address mail leaves from, where replies go, what is left of the hour and the day, and a sender name the
|
||||
service replaced. Buttons: **Check now**, **Connect again**, **Disconnect** — and **Enter an access key** only
|
||||
with `mail.relay.accessKeyField: true` ("The token" above).
|
||||
|
||||
Routes (all three need the `admin` role: not logged in → 401, other role → 403; none ever answers with a token):
|
||||
Routes (all four need the `admin` role: not logged in → 401, other role → 403; none ever answers with a token):
|
||||
|
||||
| Route | What |
|
||||
|---|---|
|
||||
| `GET /api/iapl/mail-relay/status` | the transport and the stored state; `?refresh=1` asks the service |
|
||||
| `POST /api/iapl/mail-relay/connect` | enrol now; with `{ token }` store a token issued by hand — only with `accessKeyField: true`, otherwise `403` |
|
||||
| `POST /api/iapl/mail-relay/disconnect` | give the token up |
|
||||
| `POST /api/iapl/mail-relay/connect-link` | "Połącz z IWSN": asks the service for the confirmation link (`POST /v1/connect`, enrolling first when there is no token) and answers it as `connectUrl` + `expiresAt`, `Cache-Control: no-store`; nothing is stored. Absent with `connectButton: false` (`RELAY_CONNECT_LINK_PATH`) |
|
||||
| `POST /api/iapl/mail-relay/confirm` | **public** — the service's call-back. `404` and no change unless the site itself started an enrolment in the last 5 minutes; **refused** calls are rate-limited (10 a minute per address, `mail.relay.confirmRateLimit`) — a call that carries the nonce is never turned away by the limit, so junk from the same address cannot keep the site from enrolling |
|
||||
|
||||
These are the first routes under `/api/iapl/`; the others stay under `/api/ipal/` until 2.0. The confirm path is
|
||||
@@ -419,7 +438,7 @@ the service), each with a text in the editor's language:
|
||||
|
||||
| Code | Meaning | What to do |
|
||||
|---|---|---|
|
||||
| `relay-pending` | enrolled, but held for approval by Intecion — the rule while the service runs with enrolment "pending" (from its launch until Intecion switches to open enrolment), every new site waits for approval; after that the exception (many new sites at once, or approval by hand) | Intecion approves the host; nothing to do on the site |
|
||||
| `relay-pending` | enrolled, waiting for confirmation by a person of Intecion (contract 1.8.0) | "Połącz z IWSN" in the panel and the confirmation on the page that opens; without the button (no confirmation page), Intecion confirms the host |
|
||||
| `relay-suspended` | stopped by Intecion | contact Intecion; SMTP in the panel sends meanwhile |
|
||||
| `relay-refused` | the site could not enrol; or a token issued by hand stopped working (new server address, token no longer valid) | "When the site cannot be confirmed" below; hand-issued: ask Intecion for the address to be added or for a new token |
|
||||
| `relay-disconnected` | an admin pressed "Disconnect" | "Connect again", or fill in SMTP |
|
||||
@@ -464,6 +483,7 @@ message); "Connect again" asks at once. Other causes: `host-not-allowed` (not a
|
||||
| `otherHosts` | `'auto'` | a database that holds another host's connection. `'auto'`: a public site enrols by itself (launch, a domain move); a non-public one (`IAPL_NOINDEX=1` or `developmentHosts`) neither enrols nor sends until "Connect again". A list = those hosts are this site's own. `'wait'` = a public site without a connection of its own waits too. `'enrol'` = no rule |
|
||||
| `developmentHosts` | the plugin's list: `iapl({ developmentHosts })`, default `['*.dev.netscale.pl']` (`pluginDevelopmentHosts(payload)`) | host patterns (`*` = any characters) of development, staging and preview addresses, for the mail service alone: a site on such a host is non-public for `otherHosts`, like one with `IAPL_NOINDEX=1`, with no environment variable (`siteIsNonPublic`, `siteNonPublicSignal`, `matchDevelopmentHost`, `isDevelopmentHost`). `[]` = none |
|
||||
| `enrol` | `'auto'` | `'manual'`: only "Connect again" or `enrolRelay()` enrols. `false`: never (the token comes from `token` or `setRelayToken`) |
|
||||
| `connectButton` | `true` | `false`: no "Połącz z IWSN" in the state block and no `connect-link` route; the site is confirmed by an operator or by the project's own code (`requestRelayConnectLink`) |
|
||||
| `accessKeyField` | `false` | `true` shows "Enter an access key" in the state block and lets its route store a hand-issued token an admin pastes |
|
||||
| `token` | — | a token from elsewhere (`string` or a function): the stored token is not used and the site does not enrol |
|
||||
| `senderName` | panel, then site name | a fixed name, or a function |
|
||||
@@ -516,7 +536,9 @@ await payload.sendEmail({ to: '[email protected]', subject: 'Hi', html: '<p>Hi</p>'
|
||||
expect(relay.outbox[0]).toMatchObject({ kind: 'system', to: ['a@example.org'] })
|
||||
```
|
||||
|
||||
- `allow` / `relay.allow(host)`: hosts that are active at once; others wait for approval. `relay.setSite(host, state)`,
|
||||
- `allow` / `relay.allow(host)`: hosts that are active at once; others wait (`pending`). `connect: 'unavailable'` makes
|
||||
`/v1/connect` answer `503 connect-unavailable`; `relay.confirmConnect(connectUrl)` stands in for the person who
|
||||
confirms a link (true when it was the site's current one, not expired). `relay.setSite(host, state)`,
|
||||
`relay.issueToken(host)`, `relay.backend = 'failure'`, `relay.intercept`, `relay.limits`, `relay.clientAddress`
|
||||
arrange what a test needs; `relay.listen(port)` serves it over HTTP for a site in another process
|
||||
(`allowLocalHosts: true` lets it call back `http://localhost:<port>`).
|
||||
@@ -647,7 +669,8 @@ Works on any `text` field. After wiring it in a project you may need
|
||||
To the mail service (when the owner says so):
|
||||
|
||||
1. Upgrade; check that `serverURL` is the site's public address.
|
||||
2. Tell Intecion the host: while the service runs with enrolment "pending" (from its launch until Intecion switches to open enrolment), every new site waits for approval; the panel says so. Under open enrolment the site is active as soon as it enrols.
|
||||
2. After the first e-mail the site waits for confirmation: press "Połącz z IWSN" in Site integrations → E-mail
|
||||
sending and have a person of Intecion confirm it on the page that opens (keep Graph until then).
|
||||
3. Site integrations → E-mail sending → "Sending method": choose **IWSN (built-in)** and save. Then remove the four
|
||||
`GRAPH_*` variables in Coolify and redeploy.
|
||||
4. Site integrations → E-mail sending → send a test e-mail: the answer says "through IWSN".
|
||||
@@ -829,8 +852,9 @@ send (e.g. **Send test e-mail**) the current one appears.
|
||||
|
||||
## Doctor
|
||||
|
||||
`iapl-doctor` ([doctor.md](./doctor.md)): `mail-transport` (nothing set up; sending is failing), `mail-relay-state`
|
||||
(waiting for approval, stopped, refused, disconnected, a replaced sender name), `mail-reply-address`,
|
||||
`iapl-doctor` ([doctor.md](./doctor.md)): `mail-transport` (nothing set up; sending is failing), `mail-relay-connect`
|
||||
(error: the method is IWSN and the site is not connected or not confirmed), `mail-relay-state` (stopped, refused,
|
||||
disconnected, a held copy, a replaced sender name), `mail-reply-address`,
|
||||
`mail-graph-deprecated`, `mail-relay-route` (trailing slashes, another API route, a redirect or a block in front of
|
||||
the confirm route on the live site).
|
||||
|
||||
|
||||
@@ -122,7 +122,7 @@ through this procedure. Ask only when you are missing something you cannot get y
|
||||
| a site sends nothing: "The data comes from another site (…), so this copy does not send e-mails by itself" / `relay-refused`, cause `client-other-host` | the site is non-public — its host matches `developmentHosts` (built in: `*.dev.netscale.pl`) or `IAPL_NOINDEX=1` is set; `iapl-doctor --deep` says which (`mail-non-public`) — and its database holds another host's connection: a staging copy of production, or production's data copied back onto the development address. Expected — a copy with production's data must not mail real people by itself | should it send: "Connect again" in the state block, once (until the data is replaced). A copy that must never send: `mail: { relay: false }` or SMTP to a catcher. **The production site itself says this:** `IAPL_NOINDEX` was left set after launch — remove it; or its host matches a development pattern — take it out of `iapl({ developmentHosts })` |
|
||||
| the site does not start: "[iapl] … developmentHosts must be an array of host patterns …" | the list is not an array of non-empty host patterns (a single string, `null`, `['']`), or holds a lone `*` | write it as `['*.dev.netscale.pl', 'staging.client.pl']`; `[]` = none; to change who waits use `mail.relay.otherHosts` |
|
||||
| a staging or test copy **does** send, to real addresses | its host matches no development pattern and it has no `IAPL_NOINDEX=1`, so it looks like a launch (a public site enrols by itself); the doctor's deep run notes "the database also holds the mail-service connection of another host" | name its host in `iapl({ developmentHosts: ['*.dev.netscale.pl', '<the copy's pattern>'] })`, or `IAPL_NOINDEX=1` on the copy; to be sure: `mail: { relay: false }` or SMTP to a catcher |
|
||||
| `relay-pending` / "waiting for approval" | while the service runs with enrolment "pending" (from its launch until Intecion switches to open enrolment), every new site waits for approval; after that, the exception (many new sites at once, or approval by hand) | Intecion approves it on the service; nothing to change on the site; the same token then works |
|
||||
| `relay-pending` / "Waiting for confirmation" / doctor `mail-relay-connect` | a new site waits until a person of Intecion confirms it (contract 1.8.0) | Site integrations → E-mail sending → "Połącz z IWSN"; the person signs in with an @intecion.com address on the page that opens and presses "Potwierdź"; the block turns "Connected" by itself. "Waiting for approval" with no button, or "the confirmation page is not available": Intecion confirms the host by hand. "Too many confirmation links": wait the minutes it says. The same token works afterwards |
|
||||
| `relay-suspended` | Intecion stopped the site (abuse, a flood from a form) | contact Intecion; fill in SMTP meanwhile |
|
||||
| `relay-disconnected` | an admin pressed "Disconnect" | "Connect again", or SMTP |
|
||||
| `relay-quota` | the site's hour or day is used up (30 / 200 by default), more than 10 recipients, more than 10 confirmations to one address a day, too many new addresses, or the site's own limit on account mail (`mail.relay.accountMail`) | the server log names the limit; look for a form being abused (Turnstile on? rate limit?); a site that really sends more: Intecion raises the limits, or SMTP |
|
||||
|
||||
@@ -669,7 +669,7 @@ scaling (5). `●` routes for pages need the database at build time (PROGRAMISTA
|
||||
6. **Notifications**: form messages in every language.
|
||||
7. **Site integrations → E-mail sending**: "Sender name" (the client's name; empty = the site name) and **"Sender
|
||||
address"** (the client's address: with the mail service replies go there). "Sending method" stays **IWSN (built-in)**; choose **Own SMTP server** and fill in its fields **only** when the client asked
|
||||
for its own server — what is chosen is what is used, an incomplete SMTP server sends nothing. A new site sends through IWSN with nothing picked; picking another option and saving stores it (the panel warns before the save when its settings are incomplete). On the production domain: the block "How e-mails are sent" must say "Connected to IWSN" ("waiting for approval": while the service runs with enrolment "pending" (from its launch until Intecion switches to open enrolment), every new site waits for approval — ask Intecion to approve the host; under open enrolment it is the exception; the real domain enrols by itself at launch although the site was connected on its development address — nothing to press; "The data comes from another site" = the site is non-public (its host matches `developmentHosts`, built in `*.dev.netscale.pl`, or `IAPL_NOINDEX=1`) and holds a copy of another site's data: press "Connect again" only if the copy should send — on the production domain it means `IAPL_NOINDEX` was left set. A development address under `*.dev.netscale.pl` needs nothing; a staging or test copy on any other host must have its host in `iapl({ developmentHosts: […] })` (an array of host patterns: a single string, an empty entry or a lone `*` stops the start) or `IAPL_NOINDEX=1`, or it mails the real addresses in its data), then **Send test e-mail** → "through IWSN". Turnstile (for testing site
|
||||
for its own server — what is chosen is what is used, an incomplete SMTP server sends nothing. A new site sends through IWSN with nothing picked; picking another option and saving stores it (the panel warns before the save when its settings are incomplete). On the production domain: the block "How e-mails are sent" must say "Connected to IWSN" ("Waiting for confirmation": press "Połącz z IWSN" and have a person of Intecion confirm the site on the page that opens — the owner's step, @intecion.com sign-in; "waiting for approval" with no button: ask Intecion; the real domain enrols by itself at launch although the site was connected on its development address — nothing to press; "The data comes from another site" = the site is non-public (its host matches `developmentHosts`, built in `*.dev.netscale.pl`, or `IAPL_NOINDEX=1`) and holds a copy of another site's data: press "Connect again" only if the copy should send — on the production domain it means `IAPL_NOINDEX` was left set. A development address under `*.dev.netscale.pl` needs nothing; a staging or test copy on any other host must have its host in `iapl({ developmentHosts: […] })` (an array of host patterns: a single string, an empty entry or a lone `*` stops the start) or `IAPL_NOINDEX=1`, or it mails the real addresses in its data), then **Send test e-mail** → "through IWSN". Turnstile (for testing site
|
||||
`1x00000000000000000000AA`, secret `1x0000000000000000000000000000000AA`; production keys from the client), analytics/pixel
|
||||
IDs, IndexNow → generate key. Mail/Turnstile errors show up as a dashboard alert.
|
||||
8. **Forms**: check the addresses in the Emails tab of the seeded forms.
|
||||
|
||||
@@ -714,7 +714,7 @@ PROGRAMISTA §6, items 73–75; email.md; AGENT.md §7.2) — nothing to run; re
|
||||
3. **For a site that will use the mail service:** `serverURL` is the public address the site answers on without a
|
||||
redirect; no proxy or WAF rule blocks `/api/iapl/mail-relay/confirm`; `trailingSlash: true` or another `routes.api` →
|
||||
Intecion sets the site's confirm address first; "Sender address" is filled in (replies go there); the client's
|
||||
processing agreement names the service. Tell Intecion the host: while the service runs with enrolment "pending" (from its launch until Intecion switches to open enrolment), every new site waits for approval (the panel says "waiting for approval"); under open enrolment a site is active as soon as it enrols.
|
||||
processing agreement names the service. A new site waits until a person of Intecion confirms it: "Połącz z IWSN" in the panel (contract 1.8.0).
|
||||
**Launch and a domain move need nothing:** the real domain enrols by itself although the database holds the
|
||||
development address's connection. **A staging or test copy of the database** neither enrols nor sends by itself
|
||||
**when it is non-public**: its host matches `iapl({ developmentHosts })` — built in `*.dev.netscale.pl`, so the
|
||||
@@ -736,7 +736,16 @@ PROGRAMISTA §6, items 73–75; email.md; AGENT.md §7.2) — nothing to run; re
|
||||
**Check:** `pnpm exec iapl-doctor --deep --url <site>` → no `mail-transport` / `mail-relay-state` / `mail-reply-address` /
|
||||
`mail-relay-route` finding (or only `mail-graph-deprecated` on a Graph site); Site integrations → E-mail sending →
|
||||
**Send test e-mail** names the transport you expect; a form submission arrives. **The service is live at
|
||||
`https://webservices.intecion.net/mail`; while the service runs with enrolment "pending" (from its launch until Intecion switches to open enrolment), every new site waits for approval — keep SMTP until it is approved, or `relay: false`.**
|
||||
`https://webservices.intecion.net/mail`; a new site waits until a person of Intecion confirms it ("Połącz z IWSN") — keep SMTP until then, or `relay: false`.**
|
||||
|
||||
**→ 1.18.0, IWSN is connected by a person of Intecion (CHANGELOG "Unreleased (for 1.18.0)" → "IWSN: Połącz z IWSN"; email.md "The mail service"; AGENT.md §7.2 point 5) — nothing to run:**
|
||||
1. No schema change, no migration, no import-map change. Sites whose "Sending method" is SMTP or Microsoft Graph see no
|
||||
change at all.
|
||||
2. A site on IWSN that is already active stays active. A site that waits (`relay-pending`, or doctor `mail-relay-connect`
|
||||
error after the upgrade): Site integrations → E-mail sending → **"Połącz z IWSN"** → a person of Intecion confirms
|
||||
it on the page that opens (an @intecion.com sign-in — the owner's step, tell them) → the block says "Connected to
|
||||
IWSN" by itself. Then send a test e-mail.
|
||||
3. A project that does not want the button: `mail: { relay: { connectButton: false } }` (no button, no route).
|
||||
|
||||
**→ 1.17.1, e-mail (CHANGELOG 1.17.1 point 5; PROGRAMISTA §6, item 82; email.md "Which transport a send takes"; AGENT.md §7.2) — nothing to run, one check:**
|
||||
1. **MongoDB: no migration. Postgres / SQLite: `pnpm payload migrate:create`** (the new field `emailMethod` is a column),
|
||||
|
||||
@@ -104,4 +104,39 @@ test.describe('the mail service', () => {
|
||||
await page.waitForLoadState('networkidle')
|
||||
for (const body of [await page.content(), await status.text(), ...seen]) {expect(body).not.toContain('ims_')}
|
||||
})
|
||||
|
||||
test('"Connect to IWSN" (contract 1.8.0 §2.1): the link opens in a new tab, the person confirms, the block sees it by itself', async ({ page }) => {
|
||||
// the site enrolled above; the service now holds it for confirmation by a person of Intecion
|
||||
relay.site(site)!.state = 'pending'
|
||||
await page.goto('/admin/login')
|
||||
await page.fill('#field-email', email!)
|
||||
await page.fill('#field-password', password!)
|
||||
await page.click('.form-submit button')
|
||||
await page.waitForURL(/verify-totp|\/admin(\?|$)/, { waitUntil: 'commit' })
|
||||
if (page.url().includes('verify-totp')) {
|
||||
await page.getByRole('textbox').first().click()
|
||||
await page.keyboard.type(totp(secret!))
|
||||
}
|
||||
await expect(page).toHaveTitle(/Dashboard|Pulpit/, { timeout: 20_000 })
|
||||
await page.goto('/admin/globals/site-integrations')
|
||||
await page.getByRole('tab', { name: /E-mail sending|Wysyłka e-mail/ }).or(page.getByRole('button', { name: /E-mail sending|Wysyłka e-mail/ })).first().click()
|
||||
const block = page.locator('[data-mail-transport]')
|
||||
await block.getByRole('button', { name: /Check now|Sprawdź teraz/ }).click()
|
||||
const connect = block.locator('[data-mail-relay-connect]')
|
||||
await expect(connect).toBeVisible({ timeout: 20_000 })
|
||||
await expect(block).toContainText(/Waiting for confirmation|Oczekuje na potwierdzenie/)
|
||||
// no link was asked for by the page itself
|
||||
expect(relay.requests.filter((r) => r.path === '/v1/connect')).toEqual([])
|
||||
|
||||
const [tab] = await Promise.all([page.waitForEvent('popup'), connect.click()])
|
||||
const url = tab.url()
|
||||
expect(url.startsWith(`${server.url}/connect?ref=`)).toBe(true)
|
||||
expect(await tab.evaluate(() => window.opener)).toBeNull()
|
||||
// the person of Intecion signs in and presses "Potwierdź" on the service's page (the stand-in does it here)
|
||||
expect(relay.confirmConnect(url)).toBe(true)
|
||||
await tab.close()
|
||||
// the block asks every 5 s and shows the result without a reload
|
||||
await expect(block).toContainText(/Connected to IWSN|Połączono z IWSN/, { timeout: 20_000 })
|
||||
await expect(connect).toHaveCount(0)
|
||||
})
|
||||
})
|
||||
|
||||
@@ -197,6 +197,7 @@
|
||||
"POST /api/globals/site-settings/versions/:id": "restore a version: editor+",
|
||||
"POST /api/iapl/mail-relay/confirm": "public by design: the mail service's call-back; 404 unless it carries a nonce this site made in the last 5 min (single use)",
|
||||
"POST /api/iapl/mail-relay/connect": "mail service, connect with a pasted token: admin",
|
||||
"POST /api/iapl/mail-relay/connect-link": "mail service, \"Połącz z IWSN\": admin; asks the service for the confirmation link on the click, never stores or logs it; absent with mail.relay.connectButton: false",
|
||||
"POST /api/iapl/mail-relay/disconnect": "mail service, disconnect: admin",
|
||||
"POST /api/iapl/two-factor/confirm": "public by design: the link's button; own origin, the single-use 30-min token AND the enrolling browser's cookie; turns the factor on, ends the account's sessions, signs nobody in",
|
||||
"POST /api/iapl/two-factor/confirm-pending": "2FA: an admin signed in with the second factor confirms another account's waiting set-up (mail not working); own origin",
|
||||
|
||||
@@ -4,12 +4,14 @@ import { useConfig, useFormFields, useTranslation } from '@payloadcms/ui'
|
||||
import { useCallback, useEffect, useState } from 'react'
|
||||
|
||||
import { formatDateTime, iaplT } from '../../../modules/admin-i18n/t.js'
|
||||
import { RELAY_CONNECT_PATH, RELAY_DISCONNECT_PATH, RELAY_STATUS_PATH } from '../../../modules/email/relay/constants.js'
|
||||
import { RELAY_CONNECT_LINK_PATH, RELAY_CONNECT_PATH, RELAY_DISCONNECT_PATH, RELAY_STATUS_PATH } from '../../../modules/email/relay/constants.js'
|
||||
import { SECRET_CLEAR } from '../../../modules/secrets/constants.js'
|
||||
|
||||
type Window = { limit: number; remaining: number }
|
||||
type State = {
|
||||
accessKeyField?: boolean
|
||||
/** `mail.relay.connectButton` is on: "Połącz z IWSN" may be shown. */
|
||||
connectButton?: boolean
|
||||
error?: string
|
||||
graphReady?: boolean
|
||||
message?: string
|
||||
@@ -18,6 +20,7 @@ type State = {
|
||||
ok?: boolean
|
||||
refusalText?: string
|
||||
relay?: {
|
||||
connectAvailable?: boolean
|
||||
connected?: boolean
|
||||
disconnected?: boolean
|
||||
lastFailure?: { at: string; code: string }
|
||||
@@ -36,6 +39,11 @@ type State = {
|
||||
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
|
||||
/** Contract §2.1: while the panel that opened the link is open, ask at most every 5 s, for at most 10 min. */
|
||||
const POLL_EVERY_MS = 5_000
|
||||
const POLL_FOR_MS = 10 * 60_000
|
||||
/** The shape of the service's link (the server checked that it begins with the service's own address). */
|
||||
const CONNECT_URL = /^https?:\/\/[^/?#\s]+(?:\/[\w.~-]+)*\/connect\?ref=[\w-]{43}$/
|
||||
|
||||
/**
|
||||
* Admin UI: the state block at the top of Site integrations → E-mail sending. Says which transport is
|
||||
@@ -52,7 +60,7 @@ export const MailRelayStatus = () => {
|
||||
const { i18n, t } = useTranslation()
|
||||
const { config } = useConfig()
|
||||
const api = config.routes?.api ?? '/api'
|
||||
const text = (key: Parameters<typeof iaplT>[1], vars?: Record<string, unknown>) => iaplT(t as never, key, vars)
|
||||
const text = useCallback((key: Parameters<typeof iaplT>[1], vars?: Record<string, unknown>) => iaplT(t as never, key, vars), [t])
|
||||
const [state, setState] = useState<null | State>(null)
|
||||
const [busy, setBusy] = useState(false)
|
||||
const [note, setNote] = useState<{ kind: 'error' | 'ok'; msg: string } | null>(null)
|
||||
@@ -85,12 +93,70 @@ export const MailRelayStatus = () => {
|
||||
// (a stored password arrives as the mask: set; "Remove the stored value" is SECRET_CLEAR: not set)
|
||||
const formPassword = useFormFields(([f]) => f.smtpPassword?.value) as string | undefined
|
||||
const savedAt = useFormFields(([f]) => f.updatedAt?.value) as string | undefined
|
||||
// "Połącz z IWSN": the link lives in this component only — never stored, never logged — until it expires
|
||||
const [link, setLink] = useState<{ until: number; url: string } | null>(null)
|
||||
const [pollingSince, setPollingSince] = useState<null | number>(null)
|
||||
|
||||
// on load, and again after every save of the page: the state block says what the saved settings do
|
||||
useEffect(() => {
|
||||
void call(RELAY_STATUS_PATH)
|
||||
}, [call, savedAt])
|
||||
|
||||
const connectIwsn = async () => {
|
||||
setBusy(true)
|
||||
try {
|
||||
const res = await fetch(`${api}${RELAY_CONNECT_LINK_PATH}`, { credentials: 'include', method: 'POST' })
|
||||
const data = (await res.json()) as { connectUrl?: string; error?: string; expiresAt?: string; message?: string } & State
|
||||
if (data.transport) {setState(data)}
|
||||
if (!data.ok) {
|
||||
setNote({ kind: 'error', msg: data.error ?? iaplT(t as never, 'mailRelayLoadFailed') })
|
||||
return
|
||||
}
|
||||
if (data.connectUrl) {
|
||||
if (!CONNECT_URL.test(data.connectUrl)) {
|
||||
setNote({ kind: 'error', msg: text('mailRelayConnectBadLink') })
|
||||
return
|
||||
}
|
||||
// a top-level navigation in a new tab, with no way back to this page (contract §2.1)
|
||||
window.open(data.connectUrl, '_blank', 'noopener,noreferrer')
|
||||
setLink({ until: data.expiresAt ? Date.parse(data.expiresAt) : Date.now() + 15 * 60_000, url: data.connectUrl })
|
||||
setPollingSince(Date.now())
|
||||
}
|
||||
setNote(data.message ? { kind: 'ok', msg: data.message } : null)
|
||||
} catch {
|
||||
setNote({ kind: 'error', msg: iaplT(t as never, 'mailRelayLoadFailed') })
|
||||
} finally {
|
||||
setBusy(false)
|
||||
}
|
||||
}
|
||||
|
||||
// after the link was opened: is the site confirmed yet? Every 5 s, for 10 min at most, while this panel is open
|
||||
const waiting = pollingSince !== null && state?.relay?.state === 'pending'
|
||||
useEffect(() => {
|
||||
if (pollingSince === null) {return}
|
||||
if (state?.relay?.state && state.relay.state !== 'pending') {
|
||||
setPollingSince(null)
|
||||
setLink(null)
|
||||
if (state.relay.state === 'active') {setNote({ kind: 'ok', msg: text('mailRelayConnectDone') })}
|
||||
return
|
||||
}
|
||||
const timer = window.setTimeout(() => {
|
||||
if (Date.now() - pollingSince >= POLL_FOR_MS) {
|
||||
setPollingSince(null)
|
||||
setLink(null)
|
||||
setNote({ kind: 'error', msg: text('mailRelayConnectNotYet') })
|
||||
return
|
||||
}
|
||||
void fetch(`${api}${RELAY_STATUS_PATH}?refresh=1`, { credentials: 'include' })
|
||||
.then(async (res) => (await res.json()) as State)
|
||||
.then((data) => {
|
||||
if (data.transport) {setState(data)}
|
||||
})
|
||||
.catch(() => undefined)
|
||||
}, POLL_EVERY_MS)
|
||||
return () => window.clearTimeout(timer)
|
||||
}, [api, pollingSince, state, text])
|
||||
|
||||
const post = (path: string, body?: object) =>
|
||||
call(path, { body: body ? JSON.stringify(body) : undefined, headers: body ? { 'Content-Type': 'application/json' } : undefined, method: 'POST' }, true)
|
||||
|
||||
@@ -103,7 +169,7 @@ export const MailRelayStatus = () => {
|
||||
// why the service does not take this site: a refused enrolment, or a hand-issued token that stopped working
|
||||
: state.refusalText ? state.refusalText
|
||||
: !relay.connected ? text('mailRelayStateNotConnected')
|
||||
: relay.state === 'pending' ? text('mailRelayStatePending')
|
||||
: relay.state === 'pending' ? text(relay.connectAvailable && state.connectButton ? 'mailRelayStateAwaitingConnect' : 'mailRelayStatePending')
|
||||
: relay.state === 'suspended' ? text('mailRelayStateSuspended')
|
||||
: text('mailRelayStateActive')
|
||||
const attention = Boolean(relay && onRelay && (relay.disconnected || relay.state === 'pending' || relay.state === 'suspended' || state.refusalText))
|
||||
@@ -137,6 +203,17 @@ export const MailRelayStatus = () => {
|
||||
{relay.quota?.hour && relay.quota.day ? (
|
||||
<p style={{ ...line, fontSize: '0.85rem', opacity: 0.75 }}>{text('mailRelayQuota', { day: relay.quota.day.remaining, hour: relay.quota.hour.remaining })}</p>
|
||||
) : null}
|
||||
{state.connectButton && !relay.disconnected && relay.state !== 'suspended' && (relay.state === 'pending' ? relay.connectAvailable : !relay.connected) ? (
|
||||
<div style={{ alignItems: 'center', display: 'flex', flexWrap: 'wrap', gap: '.5rem', marginTop: '.75rem' }}>
|
||||
<button className="btn btn--style-primary btn--size-small" data-mail-relay-connect="" disabled={busy} onClick={() => void connectIwsn()} style={{ margin: 0 }} type="button">
|
||||
{busy ? text('mailRelayWorking') : text('mailRelayConnectButton')}
|
||||
</button>
|
||||
{link && link.until > Date.now() ? (
|
||||
<a href={link.url} rel="noopener noreferrer" target="_blank">{text('mailRelayConnectOpenLink')}</a>
|
||||
) : null}
|
||||
{waiting ? <span style={{ fontSize: '0.85rem', opacity: 0.75 }}>{text('mailRelayConnectWaiting')}</span> : null}
|
||||
</div>
|
||||
) : null}
|
||||
{relay.tokenSource === 'option' ? null : (
|
||||
<div style={{ alignItems: 'center', display: 'flex', flexWrap: 'wrap', gap: '.5rem', marginTop: '.75rem' }}>
|
||||
<button className="btn btn--style-secondary btn--size-small" disabled={busy} onClick={() => void call(`${RELAY_STATUS_PATH}?refresh=1`)} style={{ margin: 0 }} type="button">
|
||||
|
||||
@@ -302,12 +302,14 @@ export {
|
||||
expectMailTo,
|
||||
getRelayStatus,
|
||||
isPublicHost,
|
||||
isRelayConnectUrl,
|
||||
MAIL_KIND,
|
||||
MAIL_KINDS,
|
||||
mailKindOf,
|
||||
pluginDevelopmentHosts,
|
||||
RELAY_BASE_URL,
|
||||
RELAY_CONFIRM_PATH,
|
||||
RELAY_CONNECT_LINK_PATH,
|
||||
RELAY_CONTRACT_VERSION,
|
||||
RELAY_DEFAULTS,
|
||||
RELAY_KV_KEY,
|
||||
@@ -323,6 +325,7 @@ export {
|
||||
relayRequest,
|
||||
relaySenderName,
|
||||
relayStatusFor,
|
||||
requestRelayConnectLink,
|
||||
resolveRelayOptions,
|
||||
rotateRelayToken,
|
||||
runWithMailKind,
|
||||
@@ -335,6 +338,7 @@ export {
|
||||
export type {
|
||||
BuildRelayMessageArgs,
|
||||
BuiltRelayMessage,
|
||||
ConnectLinkResult,
|
||||
EnrolResult,
|
||||
MailKind,
|
||||
NonPublicSignal,
|
||||
|
||||
@@ -18,8 +18,18 @@ export const integrationsTexts = defineTexts({
|
||||
mailMethodSmtpIncompleteForm: 'Fill in server, user name and password below. If you save without them, e-mails will not be sent.',
|
||||
mailRelayCheck: 'Check now',
|
||||
mailRelayConnect: 'Connect again',
|
||||
mailRelayConnectBadLink: `${IWSN} answered a confirmation link that is not its own, so it was not opened. Tell your administrator.`,
|
||||
mailRelayConnectButton: `Connect to ${IWSN}`,
|
||||
mailRelayConnectDone: 'The site is confirmed. E-mails are sent from now on.',
|
||||
mailRelayConnected: `The site is connected to ${IWSN}.`,
|
||||
mailRelayConnectFailed: 'The site could not be connected. {{reason}}',
|
||||
mailRelayConnectNotYet: `Not confirmed yet. Press "Connect to ${IWSN}" again for a new link.`,
|
||||
mailRelayConnectOff: 'Connecting from the panel is switched off for this site. Ask your administrator.',
|
||||
mailRelayConnectOpened: 'The confirmation page opened in a new tab. This block updates by itself once the site is confirmed.',
|
||||
mailRelayConnectOpenLink: 'Open the confirmation page',
|
||||
mailRelayConnectRateLimited: 'Too many confirmation links were asked for. Try again in {{minutes}} min.',
|
||||
mailRelayConnectUnavailable: 'The confirmation page is not available now. Ask your administrator to have the site confirmed.',
|
||||
mailRelayConnectWaiting: 'Waiting for the confirmation…',
|
||||
mailRelayDisconnect: 'Disconnect',
|
||||
mailRelayDisconnectConfirm: `Disconnect the site from ${IWSN}? E-mails will not be sent until you connect again or fill in an SMTP server.`,
|
||||
mailRelayDisconnected: `The site is disconnected from ${IWSN}.`,
|
||||
@@ -45,6 +55,7 @@ export const integrationsTexts = defineTexts({
|
||||
mailRelayRepliesTo: 'Replies go to {{address}}.',
|
||||
mailRelaySmtpIncomplete: `The SMTP settings below are incomplete, so e-mails go through ${IWSN}. Fill in server, user name and password, or empty them.`,
|
||||
mailRelayStateActive: `Connected to ${IWSN}.`,
|
||||
mailRelayStateAwaitingConnect: `Waiting for confirmation. Press "Connect to ${IWSN}" and confirm the site on the page that opens.`,
|
||||
mailRelayStateDisconnected: 'Disconnected. E-mails are not sent until you connect again or fill in an SMTP server.',
|
||||
mailRelayStateNotConnected: 'Not connected yet. The site connects by itself when it sends its first e-mail.',
|
||||
mailRelayStatePending: 'The site is waiting for approval, so e-mails are not sent yet. Ask your administrator.',
|
||||
@@ -95,7 +106,7 @@ export const integrationsTexts = defineTexts({
|
||||
statusEmailRelayDisconnected: `The site is disconnected from ${IWSN}, so e-mails are not sent. Connect again, or fill in an SMTP server.`,
|
||||
statusEmailRelayError: `${IWSN} refused the e-mail. Tell your administrator.`,
|
||||
statusEmailRelayNotConfirmed: `${IWSN} did not confirm the last e-mail. It may have been sent.`,
|
||||
statusEmailRelayPending: 'The site is waiting for approval, so e-mails are not sent yet. Ask your administrator.',
|
||||
statusEmailRelayPending: 'The site is waiting for confirmation, so e-mails are not sent yet. Open the e-mail settings to connect it.',
|
||||
statusEmailRelayQuota: `The site reached a sending limit of ${IWSN}. The e-mail was not sent.`,
|
||||
statusEmailRelayRecipientSuppressed: `${IWSN} refuses one of the recipients, because earlier e-mails to that address came back. Nothing was sent.`,
|
||||
statusEmailRelayRefused: `${IWSN} did not connect this site. See the state above, or fill in an SMTP server.`,
|
||||
@@ -146,8 +157,18 @@ export const integrationsTexts = defineTexts({
|
||||
mailMethodSmtpIncompleteForm: 'Uzupełnij poniżej serwer, nazwę użytkownika i hasło. Jeśli zapiszesz bez nich, e-maile nie będą wysyłane.',
|
||||
mailRelayCheck: 'Sprawdź teraz',
|
||||
mailRelayConnect: 'Połącz ponownie',
|
||||
mailRelayConnectBadLink: `${IWSN} podał link potwierdzenia spoza swojego adresu, więc go nie otwarto. Powiadom administratora.`,
|
||||
mailRelayConnectButton: `Połącz z ${IWSN}`,
|
||||
mailRelayConnectDone: 'Witryna jest potwierdzona. Od teraz e-maile są wysyłane.',
|
||||
mailRelayConnected: `Witryna jest połączona z ${IWSN}.`,
|
||||
mailRelayConnectFailed: 'Nie udało się połączyć witryny. {{reason}}',
|
||||
mailRelayConnectNotYet: `Jeszcze nie potwierdzono. Naciśnij ponownie „Połącz z ${IWSN}”, aby dostać nowy link.`,
|
||||
mailRelayConnectOff: 'Łączenie z panelu jest wyłączone na tej witrynie. Zapytaj administratora.',
|
||||
mailRelayConnectOpened: 'Strona potwierdzenia otworzyła się w nowej karcie. Ten blok odświeży się sam po potwierdzeniu witryny.',
|
||||
mailRelayConnectOpenLink: 'Otwórz stronę potwierdzenia',
|
||||
mailRelayConnectRateLimited: 'Poproszono o zbyt wiele linków potwierdzenia. Spróbuj ponownie za {{minutes}} min.',
|
||||
mailRelayConnectUnavailable: 'Strona potwierdzenia jest teraz niedostępna. Poproś administratora o potwierdzenie witryny.',
|
||||
mailRelayConnectWaiting: 'Czekam na potwierdzenie…',
|
||||
mailRelayDisconnect: 'Rozłącz',
|
||||
mailRelayDisconnectConfirm: `Rozłączyć witrynę z ${IWSN}? E-maile nie będą wysyłane, dopóki nie połączysz jej ponownie albo nie uzupełnisz serwera SMTP.`,
|
||||
mailRelayDisconnected: `Witryna jest rozłączona z ${IWSN}.`,
|
||||
@@ -173,6 +194,7 @@ export const integrationsTexts = defineTexts({
|
||||
mailRelayRepliesTo: 'Odpowiedzi trafiają na adres {{address}}.',
|
||||
mailRelaySmtpIncomplete: `Ustawienia SMTP poniżej są niepełne, więc e-maile idą przez ${IWSN}. Uzupełnij serwer, nazwę użytkownika i hasło albo je wyczyść.`,
|
||||
mailRelayStateActive: `Połączono z ${IWSN}.`,
|
||||
mailRelayStateAwaitingConnect: `Oczekuje na potwierdzenie. Naciśnij „Połącz z ${IWSN}” i potwierdź witrynę na stronie, która się otworzy.`,
|
||||
mailRelayStateDisconnected: 'Rozłączono. E-maile nie są wysyłane, dopóki nie połączysz witryny ponownie albo nie uzupełnisz serwera SMTP.',
|
||||
mailRelayStateNotConnected: 'Jeszcze nie połączono. Witryna połączy się sama, gdy wyśle pierwszy e-mail.',
|
||||
mailRelayStatePending: 'Witryna czeka na zatwierdzenie, więc e-maile nie są jeszcze wysyłane. Zapytaj administratora.',
|
||||
@@ -220,7 +242,7 @@ export const integrationsTexts = defineTexts({
|
||||
statusEmailRelayDisconnected: `Witryna jest rozłączona z ${IWSN}, więc e-maile nie są wysyłane. Połącz ją ponownie albo uzupełnij serwer SMTP.`,
|
||||
statusEmailRelayError: `${IWSN} odrzucił e-mail. Powiadom administratora.`,
|
||||
statusEmailRelayNotConfirmed: `${IWSN} nie potwierdził ostatniego e-maila. Mógł zostać wysłany.`,
|
||||
statusEmailRelayPending: 'Witryna czeka na zatwierdzenie, więc e-maile nie są jeszcze wysyłane. Zapytaj administratora.',
|
||||
statusEmailRelayPending: 'Witryna czeka na potwierdzenie, więc e-maile nie są jeszcze wysyłane. Otwórz ustawienia e-mail, aby ją połączyć.',
|
||||
statusEmailRelayQuota: `Witryna osiągnęła limit wysyłki w ${IWSN}. E-mail nie został wysłany.`,
|
||||
statusEmailRelayRecipientSuppressed: `${IWSN} odrzuca jednego z odbiorców, bo wcześniejsze e-maile na ten adres wróciły. Nic nie zostało wysłane.`,
|
||||
statusEmailRelayRefused: `${IWSN} nie połączył tej witryny. Zobacz stan powyżej albo uzupełnij serwer SMTP.`,
|
||||
|
||||
@@ -77,6 +77,30 @@ export const mailRules: DoctorRule[] = [
|
||||
group: 'mail',
|
||||
source: 'deep',
|
||||
},
|
||||
{
|
||||
// IWSN is the method in effect, and the site is not connected: nothing it sends leaves (contract §2.1).
|
||||
id: 'mail-relay-connect',
|
||||
check: (ctx) => {
|
||||
const mail = ctx.deep?.mail
|
||||
const relay = mail?.relay
|
||||
if (!mail || mail.transport !== 'relay' || !relay || relay.disconnected || relay.state === 'suspended') {return []}
|
||||
// a refused enrolment and a held copy have findings of their own (mail-relay-state)
|
||||
if (relay.refusal && !relay.connected) {return []}
|
||||
if (relay.connected && relay.state !== 'pending') {return []}
|
||||
return [{
|
||||
fix: relay.connectAvailable || !relay.connected
|
||||
? 'Site integrations → E-mail sending → "Połącz z IWSN" (Connect to IWSN), then confirm the site on the page that opens (an @intecion.com sign-in). Or choose another sending method'
|
||||
: 'the confirmation page is not offered for this site: ask Intecion to confirm it (`ims approve <host>`), or choose another sending method',
|
||||
message: relay.connected
|
||||
? 'the sending method is IWSN, but the site is not confirmed yet: e-mails are not sent'
|
||||
: 'the sending method is IWSN, but the site is not connected yet: e-mails are not sent until it is connected and confirmed',
|
||||
severity: 'error',
|
||||
}]
|
||||
},
|
||||
docs: 'docs/email.md',
|
||||
group: 'mail',
|
||||
source: 'deep',
|
||||
},
|
||||
{
|
||||
// Which signal makes the site a non-public copy for the mail service — said plainly, because that signal
|
||||
// decides whether a copy of another site's data mails real people.
|
||||
@@ -108,8 +132,6 @@ export const mailRules: DoctorRule[] = [
|
||||
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 <host>`); 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.refusal === 'client-other-host') {
|
||||
out.push({
|
||||
fix: 'expected for a copy that must not mail real people. If this copy should send e-mails: Site integrations → E-mail sending → "Connect again" (once). To keep it silent for good: mail: { relay: false } or SMTP to a catcher. If this is NOT a copy but the site itself, it is wrongly marked non-public: remove IAPL_NOINDEX, or take the host out of iapl({ developmentHosts })',
|
||||
@@ -123,8 +145,6 @@ export const mailRules: DoctorRule[] = [
|
||||
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 (mail.otherHostEntries && !mail.nonPublic) {
|
||||
// Right after a launch or a domain move this is the site's own past. On a COPY that forgot to say it is not
|
||||
|
||||
@@ -123,6 +123,7 @@ export async function collectDoctorStatus(payload: BasePayload): Promise<DoctorS
|
||||
relay: state.relay
|
||||
? {
|
||||
connected: state.relay.connected,
|
||||
...(state.relay.connectAvailable ? { connectAvailable: true } : {}),
|
||||
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 } : {}) } : {}),
|
||||
|
||||
@@ -87,6 +87,8 @@ export type DoctorStatus = {
|
||||
otherHostEntries?: boolean
|
||||
/** null = the mail service is switched off in the project. */
|
||||
relay: {
|
||||
/** A waiting site the service can confirm through `/v1/connect` ("Połącz z IWSN" is shown). */
|
||||
connectAvailable?: boolean
|
||||
connected: boolean
|
||||
disconnected: boolean
|
||||
nameReplaced: boolean
|
||||
|
||||
@@ -7,7 +7,7 @@
|
||||
/** 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.7.1'
|
||||
export const RELAY_CONTRACT_VERSION = '1.8.0'
|
||||
/** The `product` value of this plugin. */
|
||||
export const RELAY_PRODUCT = 'iapl'
|
||||
/** The service's name, for docs, logs and the doctor. */
|
||||
@@ -19,6 +19,8 @@ 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'
|
||||
/** Admin-only: asks the service for the link a person of Intecion confirms this site with ("Połącz z IWSN", contract §2.1). */
|
||||
export const RELAY_CONNECT_LINK_PATH = '/iapl/mail-relay/connect-link'
|
||||
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'
|
||||
|
||||
@@ -52,6 +52,9 @@ type Site = {
|
||||
bindOnUse: boolean
|
||||
callbackPath?: string
|
||||
confirmations: Map<string, number>
|
||||
/** The link of `/v1/connect` that works now (contract §2.1): its `ref`, until when, and the links asked for this hour. */
|
||||
connect?: { expiresAt: number; ref: string }
|
||||
connectAsked: number[]
|
||||
dayAccount: number
|
||||
dayOther: number
|
||||
host: string
|
||||
@@ -77,6 +80,8 @@ export type FakeRelayOptions = {
|
||||
callSite?: (url: string, init: { body: string; headers: Record<string, string>; method: 'POST' }) => Promise<Response>
|
||||
/** The address requests come from when the request carries no `x-fake-client-address` header. */
|
||||
clientAddress?: string
|
||||
/** Whether the confirmation page of `/v1/connect` is set up (contract §2.1, `given.connect`). Default `'available'`. */
|
||||
connect?: 'available' | 'unavailable'
|
||||
limits?: Partial<FakeRelayLimits>
|
||||
now?: () => number
|
||||
senderAddress?: string
|
||||
@@ -148,6 +153,14 @@ export type FakeRelay = {
|
||||
backend: 'failure' | 'ok' | 'recipient-suppressed'
|
||||
/** The address the next requests come from (a request's own `x-fake-client-address` header wins). */
|
||||
clientAddress: string
|
||||
/**
|
||||
* What a person of Intecion does on the service's page: signs in and presses "Potwierdź" on the link a site
|
||||
* was given. True when the link was the site's current one and not expired (the site is then active); false
|
||||
* otherwise. The test stands in for the person's browser; a site never calls this.
|
||||
*/
|
||||
confirmConnect: (connectUrl: string) => boolean
|
||||
/** `'available'` (default) or `'unavailable'`: whether `/v1/connect` hands out links (contract §2.1). */
|
||||
connect: 'available' | 'unavailable'
|
||||
/** `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`, …))`. */
|
||||
@@ -185,12 +198,14 @@ export function createFakeRelay(options: FakeRelayOptions = {}): FakeRelay {
|
||||
const sites = new Map<string, Site>()
|
||||
const tokens = new Map<string, string>() // sha256(token) → host
|
||||
const url = 'https://fake-relay.invalid/mail'
|
||||
/** The address the fake answers at once `listen()` started it: the links of `/v1/connect` begin with it then. */
|
||||
let publicUrl: string | undefined
|
||||
const seenRecipients = new Map<string, Set<string>>()
|
||||
|
||||
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',
|
||||
addresses: [], alerts: 0, bindOnUse: false, confirmations: new Map(), connectAsked: [], 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()
|
||||
@@ -209,6 +224,19 @@ export function createFakeRelay(options: FakeRelayOptions = {}): FakeRelay {
|
||||
},
|
||||
backend: 'ok',
|
||||
clientAddress: options.clientAddress ?? '203.0.113.10',
|
||||
confirmConnect: (connectUrl) => {
|
||||
const ref = new URL(connectUrl).searchParams.get('ref')
|
||||
if (![url, publicUrl].some((base) => base && connectUrl.startsWith(`${base}/connect?`)) || !ref) {return false}
|
||||
for (const site of sites.values()) {
|
||||
if (site.connect?.ref !== ref) {continue}
|
||||
if (site.connect.expiresAt <= now() || site.state !== 'pending') {return false}
|
||||
site.connect = undefined // one confirmation per link
|
||||
site.state = 'active'
|
||||
return true
|
||||
}
|
||||
return false
|
||||
},
|
||||
connect: options.connect ?? 'available',
|
||||
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)}
|
||||
@@ -257,7 +285,8 @@ export function createFakeRelay(options: FakeRelayOptions = {}): FakeRelay {
|
||||
await new Promise<void>((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<void>((resolve) => server.close(() => resolve())), url: `http://127.0.0.1:${listening}${new URL(url).pathname}` }
|
||||
publicUrl = `http://127.0.0.1:${listening}${new URL(url).pathname}`
|
||||
return { close: () => new Promise<void>((resolve) => server.close(() => resolve())), url: publicUrl }
|
||||
},
|
||||
outbox: [],
|
||||
requests: [],
|
||||
@@ -543,11 +572,29 @@ export function createFakeRelay(options: FakeRelayOptions = {}): FakeRelay {
|
||||
sender: { address: senderAddress },
|
||||
...(site.lastSenderName ? { senderName: site.lastSenderName } : {}),
|
||||
service: { name: RELAY_SERVICE_NAME, contract: RELAY_CONTRACT_VERSION, version: '0.0.0-fake' },
|
||||
...(site.state === 'pending' && relay.connect === 'available' ? { connectAvailable: true } : {}),
|
||||
state: site.state,
|
||||
token: { issuedAt: new Date(site.issuedAt).toISOString(), rotateAfter: new Date(site.issuedAt + 90 * DAY).toISOString() },
|
||||
})
|
||||
}
|
||||
|
||||
/** POST /v1/connect (contract §2.1): a link for a person of Intecion, for a site that waits. */
|
||||
function connect(request: Request, address: string): Response {
|
||||
const { site } = authenticate(request, address)
|
||||
if (site.state === 'suspended') {throw new Refusal(403, 'site-suspended', 'The site was stopped by Intecion.')}
|
||||
if (site.state === 'active') {return json(200, { ok: true, state: 'active' })}
|
||||
if (relay.connect === 'unavailable') {throw new Refusal(503, 'connect-unavailable', 'No confirmation page is set up. Ask Intecion to confirm the site.', { retryable: false })}
|
||||
const hourAgo = now() - 60 * 60_000
|
||||
site.connectAsked = site.connectAsked.filter((at) => at > hourAgo)
|
||||
if (site.connectAsked.length >= 10) {
|
||||
throw new Refusal(429, 'rate-limited', 'More than 10 links for this site within an hour.', { retryable: false, retryAfter: Math.ceil((site.connectAsked[0] + 60 * 60_000 - now()) / 1000) })
|
||||
}
|
||||
site.connectAsked.push(now())
|
||||
// each call makes a new link; the earlier one stops working
|
||||
site.connect = { expiresAt: now() + 15 * 60_000, ref: randomBytes(32).toString('base64url') }
|
||||
return json(200, { connectUrl: `${publicUrl ?? url}/connect?ref=${site.connect.ref}`, expiresAt: new Date(site.connect.expiresAt).toISOString(), ok: true, state: 'pending' })
|
||||
}
|
||||
|
||||
async function handle(request: Request): Promise<Response> {
|
||||
const path = new URL(request.url).pathname.slice(new URL(url).pathname.length) || '/'
|
||||
const address = request.headers.get('x-fake-client-address') ?? relay.clientAddress
|
||||
@@ -557,6 +604,7 @@ export function createFakeRelay(options: FakeRelayOptions = {}): FakeRelay {
|
||||
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<string, [string, () => Promise<Response> | Response]> = {
|
||||
'/health': ['GET', () => json(200, { ok: true })],
|
||||
'/v1/connect': ['POST', () => connect(request, address)],
|
||||
'/v1/enrol': ['POST', () => enrol(request, address)],
|
||||
'/v1/revoke': ['POST', () => {
|
||||
const { site } = authenticate(request, address)
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import type { BasePayload } from 'payload'
|
||||
|
||||
import { type RelayOptions, resolveRelayOptions } from './options.js'
|
||||
import { disconnectRelay as disconnect, enrolRelay as enrol, type EnrolResult, siteIsNonPublic as nonPublic, type NonPublicSignal, siteNonPublicSignal as nonPublicSignal, type RelayStatus, rotateRelayToken as rotate, getRelayStatus as status } from './session.js'
|
||||
import { requestRelayConnectLink as connectLink, type ConnectLinkResult, disconnectRelay as disconnect, enrolRelay as enrol, type EnrolResult, siteIsNonPublic as nonPublic, type NonPublicSignal, siteNonPublicSignal as nonPublicSignal, 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'
|
||||
@@ -11,6 +11,7 @@ export { relayConfirmEndpoint } from './confirm.js'
|
||||
export {
|
||||
RELAY_BASE_URL,
|
||||
RELAY_CONFIRM_PATH,
|
||||
RELAY_CONNECT_LINK_PATH,
|
||||
RELAY_CONTRACT_VERSION,
|
||||
RELAY_DEFAULTS,
|
||||
RELAY_KV_KEY,
|
||||
@@ -30,7 +31,8 @@ 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, NonPublicSignal, RelayStatus } from './session.js'
|
||||
export { isRelayConnectUrl } from './session.js'
|
||||
export type { ConnectLinkResult, EnrolResult, NonPublicSignal, RelayStatus } from './session.js'
|
||||
|
||||
const DISABLED = 'The mail service is switched off for this project (mail: { relay: false }).'
|
||||
|
||||
@@ -77,3 +79,10 @@ export const siteIsNonPublic = (payload: BasePayload, options?: RelayOptions): b
|
||||
/** Which signal says so — `{ by: 'development-host', pattern }` or `{ by: 'noindex' }` — or null for a public site. */
|
||||
export const siteNonPublicSignal = (payload: BasePayload, options?: RelayOptions): NonPublicSignal | null =>
|
||||
nonPublicSignal(payload, resolveRelayOptions(payload, options) || (options ?? {}))
|
||||
|
||||
/**
|
||||
* Asks the service for the link a person of Intecion confirms this waiting site with (contract 1.8.0 §2.1) — what
|
||||
* the panel's "Połącz z IWSN" does; for a project's own button. Call it on a person's click only, never by itself;
|
||||
* open the answered `connectUrl` in a new tab (`noopener noreferrer`); never store, log or fetch it.
|
||||
*/
|
||||
export const requestRelayConnectLink = (payload: BasePayload, options?: RelayOptions): Promise<ConnectLinkResult> => connectLink(payload, resolved(payload, options))
|
||||
|
||||
@@ -27,6 +27,13 @@ export type RelayOptions = {
|
||||
accountMail?: { perAddress?: number; perAddressTotal?: number; perVisitor?: number; windowMinutes?: number } | false
|
||||
/** Calls to the public confirm route per address. Default 10 a minute. */
|
||||
confirmRateLimit?: { max?: number; windowMs?: number }
|
||||
/**
|
||||
* The button "Połącz z IWSN" on Site integrations → E-mail sending, and the admin-only route behind it
|
||||
* (`POST /api/iapl/mail-relay/connect-link`): a waiting site asks the service for the link a person of Intecion
|
||||
* confirms it with (contract §2.1). Default on. `false`: no button and no route — a site is then confirmed by an
|
||||
* operator, or by the project's own code (`requestRelayConnectLink`).
|
||||
*/
|
||||
connectButton?: boolean
|
||||
/**
|
||||
* Host patterns of development and preview addresses (`*` = any characters), for the mail service only.
|
||||
* Default: the plugin's list — `iapl({ developmentHosts })`, which itself defaults to
|
||||
|
||||
@@ -10,9 +10,9 @@ import { graphAvailable, type MailMethodProblem, type MailTransport, resolveMail
|
||||
import { isMailMethod, readMailSettings } from '../method.js'
|
||||
import { RELAY_SENDER_ADDRESS } from './adapter.js'
|
||||
import { relayRequest } from './client.js'
|
||||
import { RELAY_CONFIRM_PATH, RELAY_CONNECT_PATH, RELAY_DISCONNECT_PATH, RELAY_STATUS_PATH } from './constants.js'
|
||||
import { RELAY_CONFIRM_PATH, RELAY_CONNECT_LINK_PATH, RELAY_CONNECT_PATH, RELAY_DISCONNECT_PATH, RELAY_STATUS_PATH } from './constants.js'
|
||||
import { isPublicHost, relayHost, resolveRelayOptions } from './options.js'
|
||||
import { disconnectRelay, enrolRelay, type EnrolResult, getRelayStatus, LOCAL_CODES, type NonPublicSignal, otherHostsInTheWay, readSiteStore, type RelayStatus, setRelayToken, siteNonPublicSignal } from './session.js'
|
||||
import { disconnectRelay, enrolRelay, type EnrolResult, getRelayStatus, LOCAL_CODES, type NonPublicSignal, otherHostsInTheWay, readSiteStore, type RelayStatus, requestRelayConnectLink, setRelayToken, siteNonPublicSignal } from './session.js'
|
||||
import { otherRelayHosts } from './store.js'
|
||||
|
||||
type Settings = {
|
||||
@@ -31,6 +31,8 @@ export type MailPanelState = {
|
||||
accessKeyField?: boolean
|
||||
/** The address the service calls this site back at. */
|
||||
confirmUrl?: string
|
||||
/** `mail.relay.connectButton` is not `false`: the panel may show "Połącz z IWSN" for a waiting site. */
|
||||
connectButton?: boolean
|
||||
/** The four `GRAPH_*` variables are set on this server (whether "Microsoft Graph" could send). */
|
||||
graphReady: boolean
|
||||
/**
|
||||
@@ -101,6 +103,7 @@ export async function mailPanelState(req: Pick<PayloadRequest, 'payload'>, own:
|
||||
const api = payload.config.routes?.api ?? '/api'
|
||||
return {
|
||||
...(options?.accessKeyField === true ? { accessKeyField: true } : {}),
|
||||
...(options && options.connectButton !== false ? { connectButton: true } : {}),
|
||||
...(status?.host ? { confirmUrl: `https://${status.host}${api}${RELAY_CONFIRM_PATH}` } : {}),
|
||||
graphReady: graphAvailable(),
|
||||
methodChosen: method.explicit,
|
||||
@@ -152,20 +155,28 @@ async function answer(req: PayloadRequest, own: false | RelayOptions | undefined
|
||||
}
|
||||
|
||||
/**
|
||||
* The three admin-only routes behind the state block on Site integrations → E-mail sending:
|
||||
* The 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 }` and `mail.relay.accessKeyField: true`,
|
||||
* store a token Intecion issued by hand (refused otherwise)
|
||||
* POST /api/iapl/mail-relay/disconnect give the token up; nothing is sent through the service until "Connect again"
|
||||
* POST /api/iapl/mail-relay/connect-link the link a person of Intecion confirms a waiting site with ("Połącz z IWSN";
|
||||
* off with `mail.relay.connectButton: false`)
|
||||
* None of them ever answers with a token.
|
||||
*/
|
||||
export function relayPanelEndpoints(own?: false | RelayOptions): Endpoint[] {
|
||||
export function relayPanelEndpoints(own?: false | RelayOptions, { connectLink = true }: { connectLink?: boolean } = {}): 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')
|
||||
const asked = new URL(req.url ?? 'http://x').searchParams.get('refresh') === '1'
|
||||
if (asked) {return answer(req, own, {}, true)}
|
||||
// a site that waits for confirmation is asked about on every load of the panel (contract §2.1): the
|
||||
// confirmation happens on the service's page, and nothing tells the site
|
||||
const stored = await mailPanelState(req, own)
|
||||
const waits = stored.transport === 'relay' && stored.relay?.connected === true && stored.relay.state === 'pending'
|
||||
return answer(req, own, {}, waits)
|
||||
},
|
||||
method: 'get',
|
||||
path: RELAY_STATUS_PATH,
|
||||
@@ -231,5 +242,39 @@ export function relayPanelEndpoints(own?: false | RelayOptions): Endpoint[] {
|
||||
method: 'post',
|
||||
path: RELAY_DISCONNECT_PATH,
|
||||
},
|
||||
// (`mail.relay.connectButton: false` leaves the route out; iapl() passes it, a project's own wiring passes its own)
|
||||
...(connectLink && !(own && own.connectButton === false) ? [connectLinkEndpoint(own)] : []),
|
||||
]
|
||||
}
|
||||
|
||||
/**
|
||||
* `POST /api/iapl/mail-relay/connect-link` — admin only, on the click of "Połącz z IWSN": asks the service for the
|
||||
* link a person of Intecion confirms this site with (contract §2.1) and hands it to the panel, which opens it in a
|
||||
* new tab. The link is checked (it must begin with the service's `{base}/connect?`), never stored, never logged.
|
||||
*/
|
||||
function connectLinkEndpoint(own?: false | RelayOptions): Endpoint {
|
||||
return {
|
||||
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)}
|
||||
if (options.connectButton === false) {return json({ error: serverText(i18n, 'mailRelayConnectOff'), ok: false }, 404)}
|
||||
const result = await requestRelayConnectLink(req.payload, options)
|
||||
if (result.ok && result.state === 'pending') {
|
||||
return answer(req, own, { connectUrl: result.connectUrl, expiresAt: result.expiresAt, message: serverText(i18n, 'mailRelayConnectOpened') })
|
||||
}
|
||||
if (result.ok) {return answer(req, own, { message: serverText(i18n, 'mailRelayConnectDone') }, true)}
|
||||
const error =
|
||||
result.code === 'connect-unavailable' ? serverText(i18n, 'mailRelayConnectUnavailable')
|
||||
: result.code === 'rate-limited' ? serverText(i18n, 'mailRelayConnectRateLimited', { minutes: Math.max(1, Math.ceil((result.retryAfter ?? 60) / 60)) })
|
||||
: result.code === 'site-suspended' ? serverText(i18n, 'mailRelayStateSuspended')
|
||||
: result.code === LOCAL_CODES.badConnectUrl ? serverText(i18n, 'mailRelayConnectBadLink')
|
||||
: serverText(i18n, 'mailRelayConnectFailed', { reason: enrolRefusalText(i18n, result, await mailPanelState(req, own)) })
|
||||
return json({ ...(await mailPanelState(req, own)), code: result.code, error, ok: false }, result.code === 'rate-limited' ? 429 : 502)
|
||||
},
|
||||
method: 'post',
|
||||
path: RELAY_CONNECT_LINK_PATH,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -33,6 +33,8 @@ const refusal = (code: string, message: string, extra: Partial<RelayRefusal> = {
|
||||
|
||||
/** Codes this client makes up for what never reached the service. */
|
||||
export const LOCAL_CODES = {
|
||||
/** `/v1/connect` answered a link that does not begin with the service's own `{base}/connect?`: not opened. */
|
||||
badConnectUrl: 'client-bad-connect-url',
|
||||
disconnected: 'client-disconnected',
|
||||
/** A token that belongs to another site (the service says which host it is for). */
|
||||
foreignToken: 'client-foreign-token',
|
||||
@@ -358,6 +360,8 @@ export async function withRelayToken<T>(
|
||||
}
|
||||
|
||||
type StatusBody = {
|
||||
/** Since contract 1.8.0, only for a pending site: it can be confirmed through `/v1/connect`. */
|
||||
connectAvailable?: boolean
|
||||
host?: string
|
||||
limits?: NonNullable<RelayStored['service']>['limits']
|
||||
quota?: NonNullable<RelayStored['service']>['quota']
|
||||
@@ -398,6 +402,7 @@ export async function refreshRelayStatus(payload: BasePayload, options: Resolved
|
||||
hostChecked: true,
|
||||
service: {
|
||||
name: body.service?.name,
|
||||
...(body.connectAvailable === true ? { connectAvailable: true } : {}),
|
||||
contract: body.service?.contract,
|
||||
fetchedAt: new Date().toISOString(),
|
||||
limits: body.limits,
|
||||
@@ -410,6 +415,54 @@ export async function refreshRelayStatus(payload: BasePayload, options: Resolved
|
||||
return { stored }
|
||||
}
|
||||
|
||||
/** What "Połącz z IWSN" gets from the service (contract §2.1). Never logged, never stored. */
|
||||
export type ConnectLinkResult =
|
||||
| { connectUrl: string; expiresAt: string; ok: true; state: 'pending' }
|
||||
| { ok: true; state: 'active' }
|
||||
| RelayRefusal
|
||||
|
||||
/**
|
||||
* True when `connectUrl` is a link of the service this site uses: it begins with `{base}/connect?` and carries
|
||||
* the one `ref` the contract describes, nothing else. Anything else is a fault and is not opened.
|
||||
*/
|
||||
export function isRelayConnectUrl(connectUrl: unknown, base: string): connectUrl is string {
|
||||
if (typeof connectUrl !== 'string') {return false}
|
||||
const prefix = `${base.replace(/\/+$/, '')}/connect?`
|
||||
if (!connectUrl.startsWith(prefix)) {return false}
|
||||
return /^ref=[\w-]{43}$/.test(connectUrl.slice(prefix.length))
|
||||
}
|
||||
|
||||
/**
|
||||
* Asks the service for the link a person of Intecion confirms this waiting site with (contract §2.1,
|
||||
* `POST /v1/connect`) — only on an administrator's click, never by itself. A site without a token enrols first.
|
||||
* The link is returned to the caller as it came, after checking its beginning; it is not stored and not logged.
|
||||
* `active`: the site is confirmed already (the stored state says so from now on).
|
||||
*/
|
||||
export async function requestRelayConnectLink(payload: BasePayload, options: ResolvedRelayOptions): Promise<ConnectLinkResult> {
|
||||
const host = relayHost(payload, options)
|
||||
const answer = await withRelayToken<{ connectUrl?: unknown; expiresAt?: unknown; state?: unknown }>(
|
||||
payload,
|
||||
options,
|
||||
(token) => relayRequest({ fetchImpl: options.fetchImpl, method: 'POST', path: '/v1/connect', site: host, timeoutMs: options.timeoutMs, token, url: options.url }),
|
||||
{},
|
||||
// a click is a person asking: enrol first even when this site enrols by hand only
|
||||
{ enrol: options.enrol !== false },
|
||||
)
|
||||
if (!answer.ok) {
|
||||
if (answer.code === 'site-suspended') {await updateRelayStore(payload, options, (current) => ({ ...current, state: 'suspended' }))}
|
||||
return answer
|
||||
}
|
||||
if (answer.body.state === 'active') {
|
||||
await updateRelayStore(payload, options, (current) => ({ ...current, service: current.service ? { ...current.service, connectAvailable: undefined } : current.service, state: 'active' }))
|
||||
return { ok: true, state: 'active' }
|
||||
}
|
||||
if (answer.body.state === 'pending' && isRelayConnectUrl(answer.body.connectUrl, options.url) && typeof answer.body.expiresAt === 'string') {
|
||||
return { connectUrl: answer.body.connectUrl, expiresAt: answer.body.expiresAt, ok: true, state: 'pending' }
|
||||
}
|
||||
// (the link itself is not written anywhere: not in the message, not in the log)
|
||||
return refusal(LOCAL_CODES.badConnectUrl, 'The mail service answered a confirmation link that is not its own. It was not opened.')
|
||||
}
|
||||
|
||||
/**
|
||||
* 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
|
||||
@@ -496,6 +549,8 @@ export async function setRelayToken(payload: BasePayload, token: string, options
|
||||
|
||||
/** What the panel and the doctor may know: never the token. */
|
||||
export type RelayStatus = {
|
||||
/** The service can confirm this waiting site through `/v1/connect` ("Połącz z IWSN"); from the last `/v1/status`. */
|
||||
connectAvailable?: boolean
|
||||
connected: boolean
|
||||
disconnected: boolean
|
||||
host: string
|
||||
@@ -518,6 +573,7 @@ export function describeRelayStore(payload: BasePayload, options: ResolvedRelayO
|
||||
return {
|
||||
connected: fromOption || (Boolean(stored.token) && !stored.disconnected),
|
||||
disconnected: Boolean(stored.disconnected),
|
||||
...(stored.state === 'pending' && stored.service?.connectAvailable ? { connectAvailable: true } : {}),
|
||||
...(stored.lastFailure ? { lastFailure: stored.lastFailure } : {}),
|
||||
...(stored.revokePending ? { revokePending: true } : {}),
|
||||
host: relayHost(payload, options) || stored.host || '',
|
||||
|
||||
@@ -60,6 +60,8 @@ export type RelayStored = {
|
||||
revokePending?: boolean
|
||||
/** What `/v1/status` last said. */
|
||||
service?: {
|
||||
/** `/v1/status` said `connectAvailable: true` (a pending site that can be confirmed through `/v1/connect`). */
|
||||
connectAvailable?: boolean
|
||||
contract?: string
|
||||
fetchedAt: string
|
||||
limits?: RelayLimits
|
||||
|
||||
@@ -3,6 +3,7 @@ import type { Payload } from 'payload'
|
||||
import type { IntegrationStatus } from './status.js'
|
||||
|
||||
import { userMeetsRole } from '../access/predicates.js'
|
||||
import { mailPanelState } from '../email/relay/panel.js'
|
||||
import { turnstileMissingKey } from '../turnstile/config.js'
|
||||
import { type IntegrationLabel, resolveLabel, serverText, STATUS_CODE_TEXTS } from './texts.js'
|
||||
|
||||
@@ -72,6 +73,18 @@ export async function IntegrationAlerts({ adminRoute = '/admin', checks = DEFAUL
|
||||
message: serverText(i18nLike, missing === 'secret' ? 'statusTurnstileNoSecretKey' : 'statusTurnstileNoSiteKey'),
|
||||
})
|
||||
}
|
||||
// IWSN in effect and the site waits for confirmation (contract §2.1): nothing it sends leaves, and no send may have
|
||||
// recorded it yet — checked live from what the site knows (no call to the service)
|
||||
if ('emailStatus' in checks && !failing.some((f) => f.field === 'emailStatus')) {
|
||||
try {
|
||||
const mail = await mailPanelState({ payload }, undefined)
|
||||
if (mail.transport === 'relay' && mail.relay?.connected && !mail.relay.disconnected && mail.relay.state === 'pending') {
|
||||
failing.push({ field: 'emailStatus', label: resolveLabel(checks.emailStatus, language), message: serverText(i18nLike, 'statusEmailRelayPending') })
|
||||
}
|
||||
} catch {
|
||||
// the mail state cannot be read (no database yet): the alert says nothing about it
|
||||
}
|
||||
}
|
||||
if (!failing.length) {return null}
|
||||
|
||||
// Not allowed the detail: that something needs attention, and whom to ask — nothing of what or why.
|
||||
|
||||
+1
-1
@@ -870,7 +870,7 @@ export const iapl = (options: IaplOptions): Plugin => {
|
||||
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()]
|
||||
config.endpoints = [...config.endpoints, relayConfirmEndpoint(relay ?? {}), ...relayPanelEndpoints(undefined, { connectLink: !(relay && relay.connectButton === false) })]
|
||||
// "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))
|
||||
}
|
||||
|
||||
+20
-3
@@ -728,7 +728,7 @@ describe('iapl-doctor: first-seen dates', () => {
|
||||
})
|
||||
|
||||
describe('e-mail: transport, the mail service, Graph, the confirm route', () => {
|
||||
const ids = ['mail-transport', 'mail-method', 'mail-non-public', 'mail-relay-state', 'mail-reply-address', 'mail-graph-deprecated', 'mail-relay-route']
|
||||
const ids = ['mail-transport', 'mail-method', 'mail-non-public', 'mail-relay-connect', 'mail-relay-state', 'mail-reply-address', 'mail-graph-deprecated', 'mail-relay-route']
|
||||
const relay = (extra: object = {}) => ({ connected: true, disconnected: false, nameReplaced: false, state: 'active', ...extra })
|
||||
const mail = (extra: object = {}) => ({ graphEnv: false, relay: relay(), replyAddress: true, status: null, transport: 'relay', ...extra })
|
||||
const run = async (deep: null | object, files: Record<string, string> = {}) =>
|
||||
@@ -747,12 +747,29 @@ describe('e-mail: transport, the mail service, Graph, the confirm route', () =>
|
||||
expect(await run(failing('2026-10-27T09:00:00.000Z'))).toEqual(['mail-transport:error'])
|
||||
})
|
||||
|
||||
test('mail-relay-connect: the method is IWSN and the site is not connected — an error, and the fix names the button or Intecion', async () => {
|
||||
const find = async (deep: object) => (await doctor(project({ ...base(), 'src/payload.config.ts': 'iapl({ forms: {} })' }), ids, { deepStatus: { mail: mail(deep) } })).findings.filter((f) => f.rule === 'mail-relay-connect')
|
||||
const button = await find({ relay: relay({ connectAvailable: true, state: 'pending' }) })
|
||||
expect(button.map((f) => f.severity)).toEqual(['error'])
|
||||
expect(button[0].message).toContain('not confirmed yet')
|
||||
expect(button[0].fix).toContain('Połącz z IWSN')
|
||||
const noButton = await find({ relay: relay({ state: 'pending' }) })
|
||||
expect(noButton[0].fix).toContain('ask Intecion')
|
||||
const never = await find({ relay: relay({ connected: false, state: undefined }) })
|
||||
expect(never[0].message).toContain('not connected yet')
|
||||
expect(never[0].fix).toContain('Połącz z IWSN')
|
||||
// nothing for: connected and active, suspended, disconnected, a refused enrolment, another method
|
||||
for (const deep of [{}, { relay: relay({ state: 'suspended' }) }, { relay: relay({ connected: false, disconnected: true }) }, { relay: relay({ connected: false, refusal: 'callback-failed', state: undefined }) }, { relay: relay({ connectAvailable: true, state: 'pending' }), transport: 'smtp' }]) {
|
||||
expect(await find(deep), JSON.stringify(deep)).toEqual([])
|
||||
}
|
||||
})
|
||||
|
||||
test('mail-relay-state: disconnected, suspended, pending, refused, not enrolled yet, a replaced sender name', async () => {
|
||||
expect(await run(mail({ relay: relay({ connected: false, disconnected: true }) }))).toEqual(['mail-relay-state:error'])
|
||||
expect(await run(mail({ relay: relay({ state: 'suspended' }) }))).toEqual(['mail-relay-state:error'])
|
||||
expect(await run(mail({ relay: relay({ state: 'pending' }) }))).toEqual(['mail-relay-state:warning'])
|
||||
expect(await run(mail({ relay: relay({ state: 'pending' }) }))).toEqual(['mail-relay-connect:error'])
|
||||
expect(await run(mail({ relay: relay({ connected: false, reason: 'redirect', refusal: 'callback-failed', state: undefined }) }))).toEqual(['mail-relay-state:warning'])
|
||||
expect(await run(mail({ relay: relay({ connected: false, state: undefined }) }))).toEqual(['mail-relay-state:info'])
|
||||
expect(await run(mail({ relay: relay({ connected: false, state: undefined }) }))).toEqual(['mail-relay-connect:error'])
|
||||
// a copy of another site's database: it does not connect by itself, and the finding says what to do
|
||||
const copy = await doctor(project({ ...base(), 'src/payload.config.ts': 'iapl({ forms: {} })' }), ids, { deepStatus: { mail: mail({ relay: relay({ connected: false, reason: 'client.pl', refusal: 'client-other-host', state: undefined }) }) } })
|
||||
expect(rules(copy)).toEqual(['mail-relay-state:warning'])
|
||||
|
||||
@@ -0,0 +1,150 @@
|
||||
/**
|
||||
* "Połącz z IWSN" — contract 1.8.0 §2.1, against the fake service (src/modules/email/relay/fake.ts), which the
|
||||
* contract's examples check (test/mailRelayContract.test.ts):
|
||||
* - a waiting site asks for the link on an admin's click (never by itself), gets it only when it begins with
|
||||
* the service's own `{base}/connect?`, never stores or logs it;
|
||||
* - a person's confirmation on the service's page makes the site active; the site learns it from /v1/status;
|
||||
* - the answers the contract lists: active, suspended, 503 connect-unavailable, 429, no token yet.
|
||||
*/
|
||||
import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest'
|
||||
|
||||
import { RELAY_BASE_URL } from '../src/modules/email/relay/constants.js'
|
||||
import { mailPanelState } from '../src/modules/email/relay/panel.js'
|
||||
import { sendThroughRelay } from '../src/modules/email/relay/send.js'
|
||||
import { getRelayStatus, isRelayConnectUrl, LOCAL_CODES, refreshRelayStatus, requestRelayConnectLink } from '../src/modules/email/relay/session.js'
|
||||
import { readRelayStore } from '../src/modules/email/relay/store.js'
|
||||
import { setRateLimitStore } from '../src/modules/shared/rateLimit.js'
|
||||
import { relaySite } from './mailRelay/helpers.js'
|
||||
|
||||
const MESSAGE = { html: '<p>Hello.</p>', subject: 'New enquiry', to: '[email protected]' }
|
||||
const HOST = 'example.com'
|
||||
const logged = (logger: Record<string, { mock: { calls: unknown[][] } }>) => JSON.stringify(Object.values(logger).flatMap((fn) => fn.mock.calls))
|
||||
|
||||
beforeEach(() => {
|
||||
setRateLimitStore(null)
|
||||
for (const name of ['GRAPH_TENANT_ID', 'GRAPH_CLIENT_ID', 'GRAPH_CLIENT_SECRET', 'GRAPH_SENDER', 'IAPL_NOINDEX', 'IPAL_NOINDEX']) {vi.stubEnv(name, '')}
|
||||
})
|
||||
afterEach(() => vi.unstubAllEnvs())
|
||||
|
||||
/** A site under the service's `connect` policy: every new site waits (nothing is listed). */
|
||||
const waitingSite = () => relaySite({ fake: { allow: [] }, integrations: { smtpFromAddress: '[email protected]' } })
|
||||
|
||||
describe('the link', () => {
|
||||
test('isRelayConnectUrl: the service\'s own `{base}/connect?ref=<43>` and nothing else', () => {
|
||||
const ref = 'a'.repeat(43)
|
||||
expect(isRelayConnectUrl(`${RELAY_BASE_URL}/connect?ref=${ref}`, RELAY_BASE_URL)).toBe(true)
|
||||
expect(isRelayConnectUrl(`${RELAY_BASE_URL}/connect?ref=${ref}`, `${RELAY_BASE_URL}/`)).toBe(true)
|
||||
for (const bad of [
|
||||
`https://evil.example/mail/connect?ref=${ref}`,
|
||||
`${RELAY_BASE_URL}.evil.example/connect?ref=${ref}`,
|
||||
`${RELAY_BASE_URL}/connect?ref=${ref}&next=https://evil.example`,
|
||||
`${RELAY_BASE_URL}/connect?ref=${'a'.repeat(42)}`,
|
||||
`${RELAY_BASE_URL}/other?ref=${ref}`,
|
||||
`${RELAY_BASE_URL}/connect#ref=${ref}`,
|
||||
`javascript:alert(1)//${RELAY_BASE_URL}/connect?ref=${ref}`,
|
||||
42,
|
||||
undefined,
|
||||
]) {expect(isRelayConnectUrl(bad, RELAY_BASE_URL), String(bad)).toBe(false)}
|
||||
})
|
||||
})
|
||||
|
||||
describe('a waiting site is connected by a person of Intecion', () => {
|
||||
test('enrol (pending) → the click asks for a link → the person confirms → /v1/status says active → mail leaves', async () => {
|
||||
const { fake, logger, options, payload } = waitingSite()
|
||||
// the site enrols on its first e-mail and waits: the mail is refused, the panel shows the button
|
||||
expect(await sendThroughRelay(payload, options, MESSAGE)).toMatchObject({ cause: 'site-pending', sent: false })
|
||||
await refreshRelayStatus(payload, options)
|
||||
expect(await getRelayStatus(payload, options)).toMatchObject({ connectAvailable: true, connected: true, state: 'pending' })
|
||||
expect(await mailPanelState({ payload }, options)).toMatchObject({ connectButton: true, relay: { connectAvailable: true, state: 'pending' } })
|
||||
// nothing asked for a link by itself
|
||||
expect(fake.requests.filter((r) => r.path === '/v1/connect')).toEqual([])
|
||||
|
||||
const link = await requestRelayConnectLink(payload, options)
|
||||
expect(link).toMatchObject({ ok: true, state: 'pending' })
|
||||
if (!link.ok || link.state !== 'pending') {throw new Error('no link')}
|
||||
expect(link.connectUrl.startsWith(`${fake.url}/connect?ref=`)).toBe(true)
|
||||
expect(Date.parse(link.expiresAt) - Date.now()).toBeGreaterThan(14 * 60_000)
|
||||
// never stored, never logged
|
||||
expect(JSON.stringify(await readRelayStore(payload))).not.toContain(link.connectUrl.split('ref=')[1])
|
||||
expect(logged(logger)).not.toContain(link.connectUrl.split('ref=')[1])
|
||||
|
||||
// the person signs in on the service's page and presses "Potwierdź"
|
||||
expect(fake.confirmConnect(link.connectUrl)).toBe(true)
|
||||
expect(fake.confirmConnect(link.connectUrl)).toBe(false) // one confirmation per link
|
||||
// the site asks (the panel does it every 5 s); then it is active and sends
|
||||
await refreshRelayStatus(payload, options)
|
||||
expect(await getRelayStatus(payload, options)).toMatchObject({ connected: true, state: 'active' })
|
||||
expect((await getRelayStatus(payload, options)).connectAvailable).toBeUndefined()
|
||||
expect(await sendThroughRelay(payload, options, MESSAGE)).toMatchObject({ sent: true })
|
||||
// and the button now answers "connected", with no link
|
||||
expect(await requestRelayConnectLink(payload, options)).toEqual({ ok: true, state: 'active' })
|
||||
})
|
||||
|
||||
test('each click makes a new link and the earlier one stops working; a link expires after 15 minutes', async () => {
|
||||
let clock = Date.parse('2026-12-01T10:00:00Z')
|
||||
const { fake, options, payload } = relaySite({ fake: { allow: [], now: () => clock } })
|
||||
await sendThroughRelay(payload, options, MESSAGE)
|
||||
const first = await requestRelayConnectLink(payload, options)
|
||||
const second = await requestRelayConnectLink(payload, options)
|
||||
if (!first.ok || first.state !== 'pending' || !second.ok || second.state !== 'pending') {throw new Error('no link')}
|
||||
expect(second.connectUrl).not.toBe(first.connectUrl)
|
||||
expect(fake.confirmConnect(first.connectUrl)).toBe(false)
|
||||
clock += 15 * 60_000 + 1
|
||||
expect(fake.confirmConnect(second.connectUrl)).toBe(false)
|
||||
expect(fake.site(HOST)?.state).toBe('pending')
|
||||
})
|
||||
|
||||
test('no token yet: the click enrols first, then asks for the link — also on a site that enrols by hand only', async () => {
|
||||
for (const enrol of ['auto', 'manual'] as const) {
|
||||
const { fake, options, payload } = relaySite({ fake: { allow: [] }, options: { enrol } })
|
||||
const link = await requestRelayConnectLink(payload, options)
|
||||
expect(link).toMatchObject({ ok: true, state: 'pending' })
|
||||
expect(fake.requests.map((r) => r.path)).toEqual(['/v1/enrol', '/v1/connect'])
|
||||
}
|
||||
// `enrol: false` (a token from elsewhere only): nothing to connect
|
||||
const off = relaySite({ fake: { allow: [] }, options: { enrol: false } })
|
||||
expect(await requestRelayConnectLink(off.payload, off.options)).toMatchObject({ ok: false })
|
||||
expect(off.fake.requests).toEqual([])
|
||||
})
|
||||
|
||||
test('the answers the contract lists: suspended, 503 connect-unavailable, 429 after ten links an hour', async () => {
|
||||
const suspended = waitingSite()
|
||||
await sendThroughRelay(suspended.payload, suspended.options, MESSAGE)
|
||||
suspended.fake.setSite(HOST, 'suspended')
|
||||
expect(await requestRelayConnectLink(suspended.payload, suspended.options)).toMatchObject({ code: 'site-suspended', ok: false })
|
||||
expect((await readRelayStore(suspended.payload)).state).toBe('suspended')
|
||||
|
||||
const unavailable = relaySite({ fake: { allow: [], connect: 'unavailable' } })
|
||||
await sendThroughRelay(unavailable.payload, unavailable.options, MESSAGE)
|
||||
const requests = unavailable.fake.requests.length
|
||||
expect(await requestRelayConnectLink(unavailable.payload, unavailable.options)).toMatchObject({ code: 'connect-unavailable', ok: false, retryable: false })
|
||||
expect(unavailable.fake.requests).toHaveLength(requests + 1) // not retried
|
||||
await refreshRelayStatus(unavailable.payload, unavailable.options)
|
||||
expect((await getRelayStatus(unavailable.payload, unavailable.options)).connectAvailable).toBeUndefined() // no button
|
||||
|
||||
const many = waitingSite()
|
||||
await sendThroughRelay(many.payload, many.options, MESSAGE)
|
||||
for (let i = 0; i < 10; i++) {expect((await requestRelayConnectLink(many.payload, many.options)).ok).toBe(true)}
|
||||
const eleventh = await requestRelayConnectLink(many.payload, many.options)
|
||||
expect(eleventh).toMatchObject({ code: 'rate-limited', ok: false })
|
||||
expect(eleventh.ok === false && eleventh.retryAfter).toBeGreaterThan(0)
|
||||
})
|
||||
|
||||
test('a link that is not the service\'s own is refused, not returned, not logged', async () => {
|
||||
const { fake, logger, options, payload } = waitingSite()
|
||||
await sendThroughRelay(payload, options, MESSAGE)
|
||||
const evil = `https://evil.example/mail/connect?ref=${'e'.repeat(43)}`
|
||||
fake.intercept = (request) => (new URL(request.url).pathname.endsWith('/v1/connect') ? Response.json({ connectUrl: evil, expiresAt: new Date(Date.now() + 60_000).toISOString(), ok: true, state: 'pending' }) : undefined)
|
||||
const answer = await requestRelayConnectLink(payload, options)
|
||||
expect(answer).toMatchObject({ code: LOCAL_CODES.badConnectUrl, ok: false })
|
||||
expect(JSON.stringify(answer)).not.toContain('evil.example')
|
||||
expect(logged(logger)).not.toContain('evil.example')
|
||||
expect(JSON.stringify(await readRelayStore(payload))).not.toContain('evil.example')
|
||||
})
|
||||
|
||||
test('`mail.relay.connectButton: false`: the panel is not offered the button', async () => {
|
||||
const { options, payload } = waitingSite()
|
||||
await sendThroughRelay(payload, options, MESSAGE)
|
||||
expect((await mailPanelState({ payload }, { ...options, connectButton: false })).connectButton).toBeUndefined()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,155 @@
|
||||
/**
|
||||
* "Połącz z IWSN" on a running Payload (SQLite by default; MongoDB / Postgres through IPAL_TEST_MONGO_URI / IPAL_TEST_POSTGRES_URI), through
|
||||
* real HTTP requests: the admin-only route that hands the panel the link (contract 1.8.0 §2.1), the status route
|
||||
* that asks the service on load while the site waits, the dashboard alert, and the opt-out.
|
||||
*/
|
||||
import type { Payload } from 'payload'
|
||||
|
||||
import { lexicalEditor } from '@payloadcms/richtext-lexical'
|
||||
import os from 'os'
|
||||
import path from 'path'
|
||||
import { getPayload } from 'payload'
|
||||
import { renderToStaticMarkup } from 'react-dom/server'
|
||||
import { afterAll, beforeAll, describe, expect, test, vi } from 'vitest'
|
||||
|
||||
import { mailAdapter } from '../src/modules/email/mailAdapter.js'
|
||||
import { RELAY_CONNECT_LINK_PATH, RELAY_STATUS_PATH } from '../src/modules/email/relay/constants.js'
|
||||
import { createFakeRelay } from '../src/modules/email/relay/fake.js'
|
||||
import { IntegrationAlerts } from '../src/modules/integrations/IntegrationAlerts.js'
|
||||
import { iapl } from '../src/plugin.js'
|
||||
import { buildTestConfig } from './helpers.js'
|
||||
import { testDatabase } from './http/db.js'
|
||||
import { startPayloadServer, type TestServer } from './http/server.js'
|
||||
|
||||
vi.mock('server-only', () => ({}))
|
||||
vi.mock('next/headers.js', async () => (await import('./http/server.js')).nextHeadersMock)
|
||||
|
||||
const PASSWORD = 'a-long-test-password-1'
|
||||
const HOST = 'example.com'
|
||||
let server: TestServer
|
||||
let payload: Payload
|
||||
let admin: Record<string, string>
|
||||
let editor: Record<string, string>
|
||||
|
||||
// the service's `connect` policy: nothing is listed, every new site waits
|
||||
const fake = createFakeRelay({ allow: [], callSite: async (url, init) => fetch(`${server.url}${new URL(url).pathname}`, { ...init, redirect: 'manual' }) })
|
||||
|
||||
const makeConfig = (relay: object, name: string) =>
|
||||
buildTestConfig({
|
||||
admin: { user: 'users' },
|
||||
collections: [{ slug: 'media', fields: [], upload: { staticDir: path.join(os.tmpdir(), 'iapl-connect-media') } }],
|
||||
db: testDatabase(name),
|
||||
editor: lexicalEditor(),
|
||||
email: mailAdapter(),
|
||||
plugins: [iapl({ access: { authCollection: 'users' }, i18n: { defaultLocale: 'pl', locales: [{ code: 'pl', label: 'Polski' }] }, mail: { relay: { fetchImpl: fake.fetch, url: fake.url, ...relay } }, twoFactor: false })],
|
||||
secret: 'integration-test-secret-0123456789',
|
||||
serverURL: `https://${HOST}`,
|
||||
telemetry: false,
|
||||
})
|
||||
|
||||
const login = async (email: string) => {
|
||||
const res = await fetch(`${server.url}/api/users/login`, { body: JSON.stringify({ email, password: PASSWORD }), headers: { 'content-type': 'application/json' }, method: 'POST' })
|
||||
return { authorization: `JWT ${((await res.json()) as { token: string }).token}` }
|
||||
}
|
||||
const api = (pathname: string, headers: Record<string, string>, init: RequestInit = {}) => fetch(`${server.url}/api${pathname}`, { ...init, headers: { 'content-type': 'application/json', ...headers } })
|
||||
const alert = async () => {
|
||||
const out = await IntegrationAlerts({ payload, user: (await payload.find({ collection: 'users' as never, where: { email: { equals: '[email protected]' } } })).docs[0] as never })
|
||||
return out ? renderToStaticMarkup(out) : ''
|
||||
}
|
||||
|
||||
beforeAll(async () => {
|
||||
const config = makeConfig({}, 'relayconnect')
|
||||
payload = await getPayload({ config })
|
||||
server = await startPayloadServer(config)
|
||||
await payload.updateGlobal({ slug: 'site-integrations' as never, data: { smtpFromAddress: '[email protected]', smtpFromName: 'Kancelaria Example' } as never })
|
||||
await payload.create({ collection: 'users' as never, data: { email: '[email protected]', password: PASSWORD, roles: ['admin'] } as never })
|
||||
await payload.create({ collection: 'users' as never, data: { email: '[email protected]', password: PASSWORD, roles: ['editor'] } as never })
|
||||
admin = await login('[email protected]')
|
||||
editor = await login('[email protected]')
|
||||
}, 120_000)
|
||||
|
||||
afterAll(async () => {
|
||||
await server?.close()
|
||||
await payload?.destroy?.()
|
||||
})
|
||||
|
||||
describe('the panel side of contract 1.8.0 §2.1', () => {
|
||||
test('a waiting site: the alert, the status on load asks the service, the button\'s route hands the link to an admin only', async () => {
|
||||
// nothing enrolled yet: no alert (nothing waits yet), the button would enrol first
|
||||
expect(await alert()).toBe('')
|
||||
// the first e-mail enrols, the site waits, the mail is not sent
|
||||
expect(await payload.sendEmail({ html: '<p>Hello.</p>', subject: 'First', to: '[email protected]' })).toMatchObject({ sent: false })
|
||||
expect(fake.site(HOST)?.state).toBe('pending')
|
||||
// the dashboard alert says so, live, to an admin
|
||||
expect(await alert()).toMatch(/czeka na potwierdzenie|waiting for confirmation/i)
|
||||
|
||||
// a panel load of a waiting site asks the service (contract §2.1: "on every panel load")
|
||||
const before = fake.requests.filter((r) => r.path === '/v1/status').length
|
||||
const loaded = (await (await api(RELAY_STATUS_PATH, admin)).json()) as { connectButton?: boolean; relay: { connectAvailable?: boolean; state: string } }
|
||||
expect(fake.requests.filter((r) => r.path === '/v1/status').length).toBe(before + 1)
|
||||
expect(loaded).toMatchObject({ connectButton: true, relay: { connectAvailable: true, state: 'pending' } })
|
||||
|
||||
// nobody but an admin gets a link, and a load never asks for one
|
||||
expect(fake.requests.filter((r) => r.path === '/v1/connect')).toEqual([])
|
||||
expect((await fetch(`${server.url}/api${RELAY_CONNECT_LINK_PATH}`, { method: 'POST' })).status).toBe(401)
|
||||
expect((await api(RELAY_CONNECT_LINK_PATH, editor, { method: 'POST' })).status).toBe(403)
|
||||
expect(fake.requests.filter((r) => r.path === '/v1/connect')).toEqual([])
|
||||
|
||||
const res = await api(RELAY_CONNECT_LINK_PATH, admin, { method: 'POST' })
|
||||
expect(res.status).toBe(200)
|
||||
expect(res.headers.get('cache-control')).toContain('no-store')
|
||||
const body = (await res.json()) as { connectUrl: string; expiresAt: string; ok: boolean }
|
||||
expect(body.ok).toBe(true)
|
||||
expect(body.connectUrl.startsWith(`${fake.url}/connect?ref=`)).toBe(true)
|
||||
// the token is not in the answer
|
||||
expect(JSON.stringify(body)).not.toContain('ims_')
|
||||
|
||||
// the person confirms; the next status read (the panel polls it) says active, the alert is gone, mail leaves
|
||||
expect(fake.confirmConnect(body.connectUrl)).toBe(true)
|
||||
const after = (await (await api(`${RELAY_STATUS_PATH}?refresh=1`, admin)).json()) as { relay: { connectAvailable?: boolean; state: string } }
|
||||
expect(after.relay.state).toBe('active')
|
||||
expect(after.relay.connectAvailable).toBeUndefined()
|
||||
expect(await payload.sendEmail({ html: '<p>Hello.</p>', subject: 'Second', to: '[email protected]' })).toMatchObject({ transport: 'relay' })
|
||||
// (the first send's refusal stays recorded until a send works: then the alert is gone)
|
||||
expect(await alert()).toBe('')
|
||||
// an active site's load does not ask the service
|
||||
const quiet = fake.requests.length
|
||||
await api(RELAY_STATUS_PATH, admin)
|
||||
expect(fake.requests).toHaveLength(quiet)
|
||||
// the button on an active site answers "connected", no link
|
||||
const again = (await (await api(RELAY_CONNECT_LINK_PATH, admin, { method: 'POST' })).json()) as { connectUrl?: string; ok: boolean }
|
||||
expect(again).toMatchObject({ ok: true })
|
||||
expect(again.connectUrl).toBeUndefined()
|
||||
|
||||
// a site that waits without any send having recorded it (the status says "ok"): the alert reads it live
|
||||
fake.site(HOST)!.state = 'pending'
|
||||
await api(`${RELAY_STATUS_PATH}?refresh=1`, admin)
|
||||
expect(await alert()).toMatch(/czeka na potwierdzenie|waiting for confirmation/i)
|
||||
fake.site(HOST)!.state = 'active'
|
||||
await api(`${RELAY_STATUS_PATH}?refresh=1`, admin)
|
||||
expect(await alert()).toBe('')
|
||||
})
|
||||
|
||||
test('the service has no confirmation page: the route says whom to ask, with no link', async () => {
|
||||
fake.site(HOST)!.state = 'pending'
|
||||
fake.connect = 'unavailable'
|
||||
try {
|
||||
const res = await api(RELAY_CONNECT_LINK_PATH, admin, { method: 'POST' })
|
||||
expect(res.status).toBe(502)
|
||||
const body = (await res.json()) as { code: string; connectUrl?: string; error: string; ok: boolean }
|
||||
expect(body).toMatchObject({ code: 'connect-unavailable', ok: false })
|
||||
expect(body.error).toMatch(/administratora|administrator/)
|
||||
expect(body.connectUrl).toBeUndefined()
|
||||
} finally {
|
||||
fake.connect = 'available'
|
||||
fake.site(HOST)!.state = 'active'
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
test('`mail.relay.connectButton: false`: no route, and the panel is not offered the button', async () => {
|
||||
const config = await makeConfig({ connectButton: false }, 'relayconnectoff')
|
||||
expect((config.endpoints ?? []).map((e) => e.path)).not.toContain(RELAY_CONNECT_LINK_PATH)
|
||||
const on = await makeConfig({}, 'relayconnecton')
|
||||
expect((on.endpoints ?? []).map((e) => e.path)).toContain(RELAY_CONNECT_LINK_PATH)
|
||||
})
|
||||
@@ -146,6 +146,7 @@ describe('the fake service speaks the contract (the contract\'s runner, every ex
|
||||
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'}
|
||||
if (given.connect) {fake.connect = given.connect as 'unavailable'}
|
||||
const vars = { alertRecipient: ALERTS, host: HOST, idempotencyKey: randomBytes(18).toString('base64url'), nonce: randomBytes(32).toString('base64url'), recipient: RECIPIENT, senderAddress: '[email protected]', token }
|
||||
if (given.idempotency === 'sent-same' || given.idempotency === 'sent-other') {
|
||||
const body = expand(example.request.body, vars, example.id) as Record<string, unknown>
|
||||
|
||||
@@ -5,7 +5,7 @@
|
||||
*
|
||||
* Skipped unless the stand-in is named — nothing here can reach the deployed service:
|
||||
* cd <IWDL>/services/mail-relay
|
||||
* npm run dev:migrate && npm run ims -- allow localhost:3987 && npm run dev
|
||||
* npm run dev:migrate && npm run dev (policy `connect`: the site waits; the test confirms it on the stand-in's page)
|
||||
* npm run ims -- limits localhost:3987 --hour 2000 --day 20000 # after the first run: a run sends about ten messages,
|
||||
* # and the default hour (24 for mail that is not account mail) lasts three runs
|
||||
* IAPL_TEST_RELAY_URL=http://127.0.0.1:8787/mail pnpm vitest run test/mailRelayService.test.ts
|
||||
@@ -27,7 +27,7 @@ import { RELAY_CONTRACT_VERSION } from '../src/modules/email/relay/constants.js'
|
||||
import { withMailKind } from '../src/modules/email/relay/kinds.js'
|
||||
import { resolveRelayOptions } from '../src/modules/email/relay/options.js'
|
||||
import { sendThroughRelay } from '../src/modules/email/relay/send.js'
|
||||
import { disconnectRelay, enrolRelay, getRelayStatus, rotateRelayToken } from '../src/modules/email/relay/session.js'
|
||||
import { disconnectRelay, enrolRelay, getRelayStatus, requestRelayConnectLink, rotateRelayToken } from '../src/modules/email/relay/session.js'
|
||||
import { readRelayStore } from '../src/modules/email/relay/store.js'
|
||||
import { iapl } from '../src/plugin.js'
|
||||
import { buildTestConfig } from './helpers.js'
|
||||
@@ -80,14 +80,39 @@ describe.skipIf(!SERVICE || !local)('against the real service code, run locally'
|
||||
expect(await (await fetch(`${SERVICE}/health`)).json()).toEqual({ ok: true })
|
||||
})
|
||||
|
||||
test('the first e-mail: the service calls the site\'s confirm route over HTTP, then takes the message', async () => {
|
||||
test('the first e-mail: the service calls the site\'s confirm route, and the site waits for confirmation (contract 1.8.0, policy `connect`)', async () => {
|
||||
const result = (await payload.sendEmail(withMailKind(MESSAGE, 'form-notification'))) as Record<string, unknown>
|
||||
expect(result, JSON.stringify(result)).toMatchObject({ cause: 'site-pending', sent: false })
|
||||
const stored = await readRelayStore(payload)
|
||||
expect(stored).toMatchObject({ host: HOST, source: 'enrolment', state: 'pending' })
|
||||
expect(stored.token).toMatch(/^ims_[\w-]{43}$/)
|
||||
expect(await outbox()).toHaveLength(0)
|
||||
expect(await getRelayStatus(payload, options, { refresh: true })).toMatchObject({ connectAvailable: true, state: 'pending' })
|
||||
})
|
||||
|
||||
test('"Połącz z IWSN": the link, a person confirms it on the service\'s page, the site is active and sends', async () => {
|
||||
const link = await requestRelayConnectLink(payload, options)
|
||||
expect(link, JSON.stringify(link)).toMatchObject({ ok: true, state: 'pending' })
|
||||
if (!link.ok || link.state !== 'pending') {throw new Error('no link')}
|
||||
expect(link.connectUrl.startsWith(`${SERVICE}/connect?ref=`)).toBe(true)
|
||||
// the person's browser: the page (on a developer's machine the stand-in takes the person as signed in), then
|
||||
// its own form, sent from the page's own origin
|
||||
const page = await fetch(link.connectUrl)
|
||||
expect(page.status).toBe(200)
|
||||
const html = await page.text()
|
||||
const field = (name: string) => new RegExp(`name="${name}" value="([^"]+)"`).exec(html)?.[1] ?? ''
|
||||
expect(field('form')).not.toBe('')
|
||||
const origin = new URL(link.connectUrl).origin
|
||||
const confirmed = await fetch(link.connectUrl, { body: new URLSearchParams({ form: field('form'), ref: field('ref') }).toString(), headers: { 'content-type': 'application/x-www-form-urlencoded', origin, 'sec-fetch-site': 'same-origin' }, method: 'POST', redirect: 'manual' })
|
||||
expect(confirmed.status, await confirmed.clone().text()).toBeLessThan(400)
|
||||
// the site learns it by asking
|
||||
expect(await getRelayStatus(payload, options, { refresh: true })).toMatchObject({ connected: true, state: 'active' })
|
||||
expect(await requestRelayConnectLink(payload, options)).toEqual({ ok: true, state: 'active' })
|
||||
const result = (await payload.sendEmail(withMailKind(MESSAGE, 'form-notification'))) as Record<string, unknown>
|
||||
expect(result, JSON.stringify(result)).toMatchObject({ replayed: false, senderName: 'Kancelaria Example', sent: true, transport: 'relay', warnings: [] })
|
||||
const stored = await readRelayStore(payload)
|
||||
expect(stored).toMatchObject({ host: HOST, source: 'enrolment', state: 'active' })
|
||||
expect(stored.token).toMatch(/^ims_[\w-]{43}$/)
|
||||
const mails = await outbox()
|
||||
expect(mails).toHaveLength(1)
|
||||
// the site's own mail (the service may also have sent its own notice of the confirmation to Intecion)
|
||||
const mails = (await outbox()).filter((m) => JSON.stringify(m.to).includes('[email protected]'))
|
||||
expect(mails, JSON.stringify((await outbox()).map((m) => [m.to, m.subject]))).toHaveLength(1)
|
||||
expect(JSON.stringify(mails[0])).toContain('Kancelaria Example')
|
||||
expect(JSON.stringify(mails[0])).toContain('[email protected]')
|
||||
expect(JSON.stringify(mails[0])).toContain(HOST)
|
||||
|
||||
Reference in New Issue
Block a user