IWSN: "Połącz z IWSN" — a person of Intecion connects the site (contract 1.8.0)

- the state block on the e-mail tab (method IWSN): the button while the service offers the confirmation page
  (connectAvailable) 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), which asks the service (POST /v1/connect, enrolling first),
  checks that it begins with the service's own {base}/connect?, and hands it over without storing or logging it;
  the browser opens it in a new tab with noopener noreferrer; the block asks /v1/status every 5 s for 10 min
- states: waiting for confirmation (button), waiting for approval (no page), connected, stopped; 503
  connect-unavailable and 429 said in the admin's language; a load of the panel asks the service while the site waits
- dashboard alert for a waiting site (live); doctor mail-relay-connect (error) — replaces the pending warning and the
  "not enrolled yet" note of mail-relay-state
- opt-out mail.relay.connectButton: false (no button, no route); building blocks requestRelayConnectLink,
  isRelayConnectUrl, RELAY_CONNECT_LINK_PATH; the fake service implements /v1/connect, connectAvailable and
  confirmConnect
- contract copy 1.8.0 (IWDL working tree, checksums match); docs, AGENT.md, setup / upgrade / debug skills, changelog

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
Radosław Smoliński
2026-12-01 21:42:23 +01:00
co-authored by Claude Opus 5.5
parent 347e3bafa1
commit 2c0262367d
41 changed files with 1113 additions and 57 deletions
@@ -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">
+4
View File
@@ -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,
+24 -2
View File
@@ -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.`,
+24 -4
View File
@@ -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
+1
View File
@@ -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 } : {}) } : {}),
+2
View File
@@ -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
+3 -1
View File
@@ -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'
+50 -2
View File
@@ -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)
+11 -2
View File
@@ -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))
+7
View File
@@ -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
+50 -5
View File
@@ -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,
}
}
+56
View File
@@ -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 || '',
+2
View File
@@ -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
View File
@@ -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))
}