Files
ipal-kit/src/modules/email/relay/session.ts
T
Radosław SmolińskiandClaude Opus 5.5 2c0262367d 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]>
2026-12-01 21:42:23 +01:00

602 lines
35 KiB
TypeScript

import type { BasePayload } from 'payload'
import { randomBytes } from 'node:crypto'
import type { RelayOptions, ResolvedRelayOptions } from './options.js'
import { PLUGIN_VERSION } from '../../../version.js'
import { isSiteNoindex } from '../../seo/siteNoindex.js'
import { matchDevelopmentHost } from '../../shared/developmentHosts.js'
import { type RelayAnswer, type RelayRefusal, relayRequest } from './client.js'
import { RELAY_CONFIRM_PATH, RELAY_DEFAULTS, RELAY_PRODUCT, type RelayStatusCode, relayStatusFor } from './constants.js'
import { isPublicHost, pluginDevelopmentHosts, pluginMailOptions, relayHost } from './options.js'
import * as store from './store.js'
import { otherRelayHosts, type RelaySiteState, type RelayStored, releaseNonce, sha256Hex } from './store.js'
type HostOptions = Pick<ResolvedRelayOptions, 'host'>
// The store is keyed by host: everything here reads and writes the entry of THIS site's host
// (`relay.host`, else the host of `serverURL`) and never another host's.
const readRelayStore = (payload: BasePayload, options: HostOptions) => store.readRelayStore(payload, relayHost(payload, options))
const updateRelayStore = (payload: BasePayload, options: HostOptions, change: (current: RelayStored) => RelayStored) => store.updateRelayStore(payload, change, relayHost(payload, options))
const clearRelayStore = (payload: BasePayload, options: HostOptions, keep: Pick<RelayStored, 'disconnected'> = {}) => store.clearRelayStore(payload, keep, relayHost(payload, options))
const readRelayCandidate = (payload: BasePayload, options: HostOptions) => store.readRelayCandidate(payload, relayHost(payload, options))
const dropRelayCandidate = (payload: BasePayload, options: HostOptions) => store.dropRelayCandidate(payload, relayHost(payload, options))
/** The stored entry of this site — never one made on another host (store.ts). A read changes nothing. */
export const readSiteStore = readRelayStore
/** Changes the stored entry of this site. */
export const updateSiteStore = updateRelayStore
const sleep = (ms: number) => new Promise<void>((resolve) => setTimeout(resolve, ms))
const refusal = (code: string, message: string, extra: Partial<RelayRefusal> = {}): RelayRefusal => ({ code, message, noAnswer: false, ok: false, retryable: false, status: 0, ...extra })
/** 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',
/** The database holds another host's connection and none of this site's: a copy does not enrol by itself. */
otherHost: 'client-other-host',
/** This config has no confirm route, so the service could not call the site back. */
noHost: 'client-no-host',
noRoute: 'client-no-route',
noToken: 'client-no-token',
} as const
export type EnrolResult =
| { code: string; message: string; ok: false; reason?: string; retryable: boolean; status: RelayStatusCode }
| { ok: true; state: RelaySiteState }
const enrolFailure = (answer: RelayRefusal): { ok: false } & EnrolResult => ({
code: answer.code,
message: answer.message,
ok: false,
...(answer.reason ? { reason: answer.reason } : {}),
retryable: answer.retryable,
status:
answer.code === LOCAL_CODES.disconnected ? 'relay-disconnected'
: ([LOCAL_CODES.foreignToken, LOCAL_CODES.noHost, LOCAL_CODES.noRoute, LOCAL_CODES.noToken, LOCAL_CODES.otherHost] as string[]).includes(answer.code) ? 'relay-refused'
: relayStatusFor(answer.code, answer.retryable),
})
const inFlight = new WeakMap<object, Promise<EnrolResult>>()
/**
* Enrols this site with the service: makes a nonce, asks, and the service calls the site's confirm
* route with the token before it answers (confirm.ts stores it beside the token in use). Only when the
* service answers `200` does that token become the one in use. One enrolment at a time per process.
*
* `force`: also when an earlier enrolment was refused a moment ago, or the site was disconnected.
*/
export function enrolRelay(payload: BasePayload, options: ResolvedRelayOptions, { deadline, force = false }: { deadline?: number; force?: boolean } = {}): Promise<EnrolResult> {
const running = inFlight.get(payload)
if (running) {return running}
const run = enrolOnce(payload, options, force, deadline).finally(() => inFlight.delete(payload))
inFlight.set(payload, run)
return run
}
const bare = (host: string) => host.trim().toLowerCase().replace(/^www\./, '')
/** Why a site counts as non-public: its host matches a development pattern, or `IAPL_NOINDEX` is set. */
export type NonPublicSignal = { by: 'development-host'; pattern: string } | { by: 'noindex' }
/**
* Which signal makes this site a non-public copy — a development, preview or staging address — or null for a
* public site. Either is enough: its host matches a development pattern (`mail.relay.developmentHosts`, else
* `iapl({ developmentHosts })`, else the built-in list — no environment variable needed), or `IAPL_NOINDEX=1`.
* The host is named first: it is the signal a site has without anybody setting anything.
*/
export function siteNonPublicSignal(payload: BasePayload, options: Pick<RelayOptions, 'developmentHosts' | 'host'>): NonPublicSignal | null {
const pattern = matchDevelopmentHost(relayHost(payload, options), options.developmentHosts ?? pluginDevelopmentHosts(payload))
if (pattern) {return { by: 'development-host', pattern }}
return isSiteNoindex() ? { by: 'noindex' } : null
}
/** Is this site a non-public copy (`siteNonPublicSignal` as a yes or no)? */
export function siteIsNonPublic(payload: BasePayload, options: Pick<RelayOptions, 'developmentHosts' | 'host'>): boolean {
return siteNonPublicSignal(payload, options) !== null
}
/**
* Other hosts' connections that keep this site from enrolling — and, for a non-public site, from sending —
* BY ITSELF (`mail.relay.otherHosts`). Decided by direction:
* - a public site is never held: the entry of its development address (launch) or of its old domain (a
* move) is simply its past;
* - a non-public site (noindex, or a development host) that finds the connection of a host it was never
* told about holds a copy of that site's data. Also when it has a token of its own: production's
* database copied BACK onto the development address brings the development site's old entry with it.
* Hosts the project named as its own, and hosts an admin accepted with "Connect again", do not count.
* Always read from the store now: a restored dump must stop the very next e-mail, not one half a minute later.
*/
export async function otherHostsInTheWay(
payload: BasePayload,
options: Pick<ResolvedRelayOptions, 'developmentHosts' | 'host' | 'otherHosts'>,
stored: RelayStored,
): Promise<string[]> {
const mode = options.otherHosts
if (mode === 'enrol') {return []}
const connected = Boolean(stored.token || stored.enrolledAt)
if (mode === 'wait' && connected) {return []}
if (mode !== 'wait' && !siteIsNonPublic(payload, options)) {return []}
const own = [...(Array.isArray(mode) ? mode : []), ...(stored.acceptedHosts ?? [])].map(bare)
return (await otherRelayHosts(payload, relayHost(payload, options))).filter((h) => !own.includes(bare(h)))
}
const otherHostMessage = (host: string, foreign: string[]) =>
`This database holds the mail-service connection of another site (${foreign.join(', ')}), and this site ("${host}") is a non-public copy (a development host, or IAPL_NOINDEX) or set to wait: it does not connect or send by itself. Press "Connect again" in Site integrations → E-mail sending if it should send e-mails (mail.relay.otherHosts).`
async function enrolOnce(payload: BasePayload, options: ResolvedRelayOptions, force: boolean, deadline?: number): Promise<EnrolResult> {
const stored = await readSiteStore(payload, options)
if (stored.disconnected && !force) {return enrolFailure(refusal(LOCAL_CODES.disconnected, 'The site was disconnected from the mail service in the panel.'))}
// (the copy rule is not a refusal of the service: it is asked again every time, so it ends when its reason does)
if (!force && stored.refusal && stored.refusal.code !== LOCAL_CODES.otherHost && Date.parse(stored.refusal.until) > Date.now()) {
return enrolFailure(refusal(stored.refusal.code, stored.refusal.message ?? stored.refusal.code, { reason: stored.refusal.reason }))
}
const host = relayHost(payload, options)
if (!host) {
return enrolFailure(refusal(LOCAL_CODES.noHost, 'The site does not know its public address: set serverURL in the Payload config, or mail.relay.host.'))
}
// Without the confirm route in this config the call-back can only fail: mailAdapter() without iapl(), or
// beside `mail: { relay: false }`. Nothing is asked of the service then.
if (!(payload.config.endpoints ?? []).some((e) => e.path === RELAY_CONFIRM_PATH && e.method === 'post')) {
return enrolFailure(refusal(LOCAL_CODES.noRoute, `This config has no route POST ${RELAY_CONFIRM_PATH}, so the mail service cannot confirm the site: use iapl() without mail: { relay: false }, or add relayConfirmEndpoint() to the endpoints.`))
}
// Intecion's service calls back public DNS names only; a relay of one's own (or the local stand-in) decides itself.
if (!options.ownUrl && !isPublicHost(host)) {
return enrolFailure(refusal('host-not-allowed', `"${host}" is not a public host name, so the mail service cannot call this site back.`))
}
// A copy of another site's database does not enrol BY ITSELF (otherHostsInTheWay): with that site's data it
// would mail real people. An admin's "Connect again" (`force`) does, and the hosts found then are accepted.
const others = force ? await otherRelayHosts(payload, host) : []
const foreign = force ? [] : await otherHostsInTheWay(payload, options, stored)
if (foreign.length) {
const message = otherHostMessage(host, foreign)
if (stored.refusal?.code !== LOCAL_CODES.otherHost || stored.refusal.reason !== foreign[0]) {
const now = new Date().toISOString()
await updateRelayStore(payload, options, (current) => ({ ...current, refusal: { at: now, code: LOCAL_CODES.otherHost, message, reason: foreign[0], until: now } }))
}
return enrolFailure(refusal(LOCAL_CODES.otherHost, message, { reason: foreign[0] }))
}
if (stored.refusal?.code === LOCAL_CODES.otherHost) {await updateRelayStore(payload, options, (current) => ({ ...current, refusal: null }))}
let answer: RelayAnswer<{ state?: string }> | undefined
let nonce = ''
for (let attempt = 0; attempt < 2; attempt++) {
nonce = randomBytes(32).toString('base64url')
const nonceHash = await store.holdNonce(payload, nonce, RELAY_DEFAULTS.nonceTtlMs, host)
answer = await relayRequest<{ state?: string }>({
body: Buffer.from(JSON.stringify({ host, nonce, product: RELAY_PRODUCT, productVersion: PLUGIN_VERSION })),
fetchImpl: options.fetchImpl,
method: 'POST',
path: '/v1/enrol',
timeoutMs: deadline === undefined ? RELAY_DEFAULTS.enrolTimeoutMs : Math.max(1, Math.min(RELAY_DEFAULTS.enrolTimeoutMs, deadline - Date.now())),
url: options.url,
})
if (answer.ok) {
const candidate = await readRelayCandidate(payload, options)
if (!candidate || candidate.nonceHash !== nonceHash) {
// The service says yes, but the token did not reach this store (another instance with a store of its own?).
return enrolFailure(refusal('callback-failed', 'The mail service confirmed the enrolment, but its token did not reach this site\'s store.', { reason: 'store' }))
}
const state: RelaySiteState = answer.body.state === 'pending' || answer.body.state === 'suspended' ? answer.body.state : 'active'
await updateRelayStore(payload, options, (current) => ({
...current,
...(force ? { acceptedHosts: [...new Set([...(current.acceptedHosts ?? []), ...others])] } : {}),
disconnected: false,
enrolledAt: new Date().toISOString(),
host,
hostChecked: true, // issued for this host a moment ago, through this host's own route
manual: false,
refusal: null,
revokePending: false,
source: 'enrolment',
state,
token: candidate.token,
}))
await dropRelayCandidate(payload, options)
return { ok: true, state }
}
// Used or not, this nonce is over. A token the call-back did deliver stays beside the one in use.
await releaseNonce(payload, nonce)
if (answer.code !== 'enrolment-in-progress' || attempt > 0) {break}
// Another process of this site is enrolling: wait, then look whether the token is here by now.
await sleep(Math.min((answer.retryAfter ?? 2) * 1000, 5000))
const now = await readRelayStore(payload, options)
if ((now.token && now.token !== stored.token) || (await readRelayCandidate(payload, options))) {return { ok: true, state: now.state ?? 'active' }}
}
const failed = answer as RelayRefusal
if (!failed.retryable) {
// Asking again at once would give the same answer (and a call-back that times out costs 8 seconds a time).
const now = Date.now()
await updateRelayStore(payload, options, (current) => ({
...current,
refusal: { at: new Date(now).toISOString(), code: failed.code, message: failed.message, ...(failed.reason ? { reason: failed.reason } : {}), until: new Date(now + RELAY_DEFAULTS.refusalCooldownMs).toISOString() },
...(failed.code === 'site-suspended' ? { state: 'suspended' as const } : {}),
}))
}
return enrolFailure(failed)
}
const HAND_ISSUED = {
'invalid-token': 'The token issued by hand for this site is no longer valid, and the site cannot enrol by itself: ask Intecion for a new token.',
reverify: 'The site sends from a server address the mail service does not know, and with a token issued by hand it cannot enrol by itself: ask Intecion to add this server\'s address.',
} as const
/**
* A site with a token issued by hand cannot be called back, so "enrol again" is not open to it
* (contract §2): it stops, says what to ask Intecion for, and keeps the token.
*/
async function handIssued(payload: BasePayload, options: HostOptions, code: keyof typeof HAND_ISSUED): Promise<RelayRefusal> {
const now = new Date().toISOString()
await updateRelayStore(payload, options, (current) => (current.refusal?.code === code ? current : { ...current, refusal: { at: now, code, message: HAND_ISSUED[code], until: now } }))
return refusal(code, HAND_ISSUED[code])
}
/**
* Refusals the service answers only after it has authenticated the token: such an answer proves the token.
* `rate-limited` is not among them (its per-address gate runs before the token is looked at), nor are
* `invalid-request`, `too-large`, `unavailable`, `internal` and the answers that are not the service's own.
*/
const TOKEN_SEEN = new Set(['already-rotated', 'attachment-refused', 'backend-failed', 'host-mismatch', 'idempotency-conflict', 'in-progress', 'quota-exceeded', 'recipient-suppressed', 'reverify', 'site-pending', 'site-suspended', 'too-many-recipients'])
/** Whether an answer shows that the service accepted the token it was sent with. */
export const provesToken = (answer: RelayAnswer<unknown>): boolean => answer.ok || (!answer.noAnswer && TOKEN_SEEN.has(answer.code))
/** A token from the `token` option (a relay of one's own, a deployment secret), when the project set one. */
async function optionToken(options: ResolvedRelayOptions): Promise<string | undefined> {
if (options.token === undefined) {return undefined}
const value = typeof options.token === 'function' ? await options.token() : options.token
return typeof value === 'string' && value.trim() ? value.trim() : undefined
}
/** Kept across the retries of one message: a site enrols at most once per message. */
export type TokenUse = {
/** When the message's whole time is up (ms since the epoch): an enrolment on the way ends by then too. */
deadline?: number
enrolled?: boolean
enrolment?: EnrolResult
}
/**
* Runs `call` with the site's token and deals with what the answer says about the token:
* - no token yet → enrol first (when `enrol` is `'auto'`), then call;
* - a token the call-back delivered but `/v1/enrol` never confirmed is tried first; on
* `401 invalid-token` it is dropped and the earlier token is used again;
* - `401 invalid-token` or `401 reverify` → enrol again once, then call again;
* - `403 host-mismatch` (the token is another site's) → forget it without revoking, enrol as this site.
* A candidate becomes the token in use only when the service has SEEN IT ACCEPTED: a `200`, or a refusal
* the service gives after it has checked the token (TOKEN_SEEN). No answer, an error page, the
* per-address `rate-limited` and `browser-not-allowed` say nothing about a token — the candidate then stays
* beside the working token, which is never thrown away for it.
*/
export async function withRelayToken<T>(
payload: BasePayload,
options: ResolvedRelayOptions,
call: (token: string) => Promise<RelayAnswer<T>>,
use: TokenUse = {},
{ enrol = options.enrol !== 'manual' && options.enrol !== false, first = true }: { enrol?: boolean; first?: boolean } = {},
): Promise<RelayAnswer<T>> {
const fixed = await optionToken(options)
if (fixed) {return call(fixed)}
if (options.token !== undefined) {return refusal(LOCAL_CODES.noToken, 'mail.relay.token returned no token.')}
for (let round = 0; round < 4; round++) {
const stored = await readSiteStore(payload, options)
if (stored.disconnected) {return refusal(LOCAL_CODES.disconnected, 'The site was disconnected from the mail service in the panel.')}
const candidate = await readRelayCandidate(payload, options)
const token = candidate?.token ?? stored.token
// A non-public copy holding another site's data does not SEND by itself either, token or not.
if (token && round === 0) {
const foreign = await otherHostsInTheWay(payload, options, stored)
if (foreign.length) {return refusal(LOCAL_CODES.otherHost, otherHostMessage(relayHost(payload, options), foreign), { reason: foreign[0] })}
}
const enrolNow = async (): Promise<null | RelayRefusal> => {
// once per message: a second request for it says again why the first enrolment failed
const failed = () => (use.enrolment && !use.enrolment.ok ? refusal(use.enrolment.code, use.enrolment.message, { reason: use.enrolment.reason, retryable: use.enrolment.retryable }) : null)
if (!enrol || use.enrolled) {return failed() ?? refusal(LOCAL_CODES.noToken, 'The site is not connected to the mail service.')}
use.enrolled = true
use.enrolment = await enrolRelay(payload, options, { deadline: use.deadline })
if (use.enrolment.ok) {return null}
// The enrolment has no good answer, but the call-back may have delivered a token all the same (the
// service's answer was lost): try it — the service says at once whether it made that token valid.
if (round < 3 && (await readRelayCandidate(payload, options))) {return null}
return failed()
}
if (!token) {
// `first: false` (a status read): a site that never enrolled does not start because somebody looked.
if (!first) {return refusal(LOCAL_CODES.noToken, 'The site is not connected to the mail service.')}
const failed = await enrolNow()
if (failed) {return failed}
continue
}
const answer = await call(token)
if (!answer.ok && answer.code === 'invalid-token') {
if (candidate) {
// The service never made this token valid: back to the earlier one.
await dropRelayCandidate(payload, options)
continue
}
if (stored.manual) {return handIssued(payload, options, 'invalid-token')}
const failed = await enrolNow()
if (failed) {return use.enrolment && !use.enrolment.ok ? failed : answer}
continue
}
if (!answer.ok && answer.code === 'host-mismatch') {
// The service knows this token as another site's (contract §8): a copied database or a token pasted into
// the wrong site that the comparison of the stored host did not catch. It is forgotten here — never
// revoked — and the site enrols as itself; a site that cannot be called back is told to ask for its own.
const message = `The token belongs to another site, not to "${relayHost(payload, options)}": it is not used. Ask Intecion for a token for this site.`
const now = new Date().toISOString()
await dropRelayCandidate(payload, options)
await updateRelayStore(payload, options, (current) => ({ ...current, hostChecked: false, manual: false, service: null, source: undefined, state: undefined, token: undefined, ...(stored.manual ? { refusal: { at: now, code: LOCAL_CODES.foreignToken, message, until: now } } : {}) }))
if (stored.manual) {return refusal(LOCAL_CODES.foreignToken, message)}
const failed = await enrolNow()
if (failed) {return use.enrolment && !use.enrolment.ok ? failed : answer}
continue
}
if (candidate && !provesToken(answer)) {return answer} // says nothing about the token: both stay as they are
if (candidate) {
// Seen accepted: this is the token now.
await updateRelayStore(payload, options, (current) => ({ ...current, enrolledAt: candidate.at, host: relayHost(payload, options) || current.host, hostChecked: true, manual: false, source: 'enrolment', state: candidate.state, token: candidate.token }))
await dropRelayCandidate(payload, options)
}
if (!answer.ok && answer.code === 'reverify') {
if (stored.manual) {return handIssued(payload, options, 'reverify')}
const failed = await enrolNow()
if (failed) {return use.enrolment && !use.enrolment.ok ? failed : answer}
continue
}
return answer
}
return refusal('invalid-token', 'The mail service keeps refusing this site\'s token.')
}
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']
sender?: { address?: string }
service?: { contract?: string; name?: string }
state?: RelaySiteState
token?: { rotateAfter?: string }
}
/**
* Reads `/v1/status` and keeps what it says (limits, quota, the sender address, when to rotate).
* A site without a token is not enrolled by this; a site whose server address is new to the service
* (`401 reverify`) enrols again, as on a send. Returns the stored entry as it is afterwards; `error`
* when the service could not be asked.
*/
export async function refreshRelayStatus(payload: BasePayload, options: ResolvedRelayOptions, { timeoutMs }: { timeoutMs?: number } = {}): Promise<{ error?: RelayRefusal; stored: RelayStored }> {
const answer = await withRelayToken<StatusBody>(
payload,
options,
(token) => relayRequest<StatusBody>({ fetchImpl: options.fetchImpl, method: 'GET', path: '/v1/status', site: relayHost(payload, options), timeoutMs, token, url: options.url }),
timeoutMs === undefined ? {} : { deadline: Date.now() + timeoutMs },
{ first: false },
)
if (!answer.ok) {return { error: answer, stored: await readSiteStore(payload, options) }}
const body = answer.body
// A token belongs to one host. One that the service knows as another site's (pasted into the access-key
// field, or stored by a script) is not this site's to use: forgotten here, never revoked there.
const own = relayHost(payload, options)
if (own && typeof body.host === 'string' && body.host && body.host !== own && options.token === undefined) {
const now = new Date().toISOString()
const message = `The token belongs to "${body.host}", not to this site ("${own}"): it is not used. Ask Intecion for a token for this site.`
await dropRelayCandidate(payload, options)
const stored = await updateRelayStore(payload, options, (current) => ({ ...current, hostChecked: false, manual: false, refusal: { at: now, code: LOCAL_CODES.foreignToken, message, until: now }, service: null, source: undefined, state: undefined, token: undefined }))
return { error: refusal(LOCAL_CODES.foreignToken, message), stored }
}
const stored = await updateRelayStore(payload, options, (current) => ({
...current,
hostChecked: true,
service: {
name: body.service?.name,
...(body.connectAvailable === true ? { connectAvailable: true } : {}),
contract: body.service?.contract,
fetchedAt: new Date().toISOString(),
limits: body.limits,
quota: body.quota,
rotateAfter: body.token?.rotateAfter,
senderAddress: body.sender?.address,
},
...(body.state ? { state: body.state } : {}),
}))
return { stored }
}
/** 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
* the site read the store again in time. `409 already-rotated` = another process won: nothing to do
* when the store already holds a newer token, else the site enrols again on its next send.
*/
export async function rotateRelayToken(payload: BasePayload, options: ResolvedRelayOptions, { force = false, timeoutMs }: { force?: boolean; timeoutMs?: number } = {}): Promise<'failed' | 'not-due' | 'rotated'> {
const stored = await readSiteStore(payload, options)
if (!stored.token || options.token !== undefined) {return 'not-due'}
const due = stored.service?.rotateAfter ? Date.parse(stored.service.rotateAfter) : Number.NaN
if (!force && !(due <= Date.now())) {return 'not-due'}
const used = stored.token
const answer = await relayRequest<{ token?: string }>({ fetchImpl: options.fetchImpl, method: 'POST', path: '/v1/rotate', site: relayHost(payload, options), timeoutMs, token: used, url: options.url })
if (answer.ok && typeof answer.body.token === 'string' && answer.body.token) {
const fresh = answer.body.token
await updateRelayStore(payload, options, (current) => ({
...current,
enrolledAt: new Date().toISOString(),
service: current.service ? { ...current.service, rotateAfter: undefined } : current.service,
source: 'rotation',
token: fresh,
}))
return 'rotated'
}
if (!answer.ok && answer.code === 'already-rotated') {
const now = await readRelayStore(payload, options)
// No newer token here: this one is on its way out. Forget it, so the next send enrols at once.
if (now.token === used) {await updateRelayStore(payload, options, (current) => ({ ...current, service: null, token: undefined }))}
return 'failed'
}
// Asked once; not again before the status has been read anew.
await updateRelayStore(payload, options, (current) => ({ ...current, service: current.service ? { ...current.service, rotateAfter: undefined } : current.service }))
return 'failed'
}
/**
* Gives the token up on the service (every token of the site stops working) and forgets it here.
* `revoked: false`: the service could not be asked — the site no longer uses the token, but it is still
* valid there until this is called again and answered.
*/
export async function disconnectRelay(payload: BasePayload, options: ResolvedRelayOptions): Promise<{ revoked: boolean }> {
// (a store copied from another host is dropped by this read: that site's token is never revoked from here)
const stored = await readSiteStore(payload, options)
if (stored.token && options.token === undefined) {
const answer = await relayRequest({ fetchImpl: options.fetchImpl, method: 'POST', path: '/v1/revoke', site: relayHost(payload, options), token: stored.token, url: options.url })
// Only the service's own word counts: "done", or "I do not know this token" (it is gone already).
if (!answer.ok && !(answer.code === 'invalid-token' && !answer.noAnswer)) {
// Not confirmed: the site stops using the token now, but it still works at the service. It is kept so
// that "Disconnect" can be pressed again.
await updateRelayStore(payload, options, (current) => ({ ...current, disconnected: true, revokePending: true }))
return { revoked: false }
}
}
await clearRelayStore(payload, options, { disconnected: true })
return { revoked: true }
}
/**
* Stores a token Intecion issued by hand (a site the service cannot call back: behind a firewall, on
* a private address). It is bound to the first server address that uses it.
*/
export async function setRelayToken(payload: BasePayload, token: string, options: { host?: string } = {}): Promise<void> {
if (!/^ims_[\w-]{43}$/.test(token)) {throw new Error('Not a token of the mail service (ims_ and 43 characters).')}
// the entry is this site's own: `options.host`, else `mail.relay.host`, else the host of serverURL
options = { host: options.host ?? (pluginMailOptions(payload).relay || {}).host }
const others = await otherRelayHosts(payload, relayHost(payload, options))
await dropRelayCandidate(payload, options)
await updateRelayStore(payload, options, (current) => ({
...current,
acceptedHosts: [...new Set([...(current.acceptedHosts ?? []), ...others])],
disconnected: false,
enrolledAt: new Date().toISOString(),
host: relayHost(payload, options) || undefined,
hostChecked: false,
manual: true,
refusal: null,
revokePending: false,
service: null,
source: 'manual',
state: current.state ?? 'active',
token,
}))
}
/** 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
/** The last message that was not sent or not confirmed, with its time and status code. */
lastFailure?: { at: string; code: string; kind?: string }
limits?: NonNullable<RelayStored['service']>['limits']
nameReplaced?: { asked: string; at: string; used: string }
quota?: NonNullable<RelayStored['service']>['quota']
refusal?: { at: string; code: string; message?: string; reason?: string }
/** "Disconnect" was not confirmed by the service: the token still works there. */
revokePending?: boolean
senderAddress?: string
serviceName?: string
state?: RelaySiteState
tokenSource?: 'enrolment' | 'manual' | 'option' | 'rotation'
}
export function describeRelayStore(payload: BasePayload, options: ResolvedRelayOptions, stored: RelayStored): RelayStatus {
const fromOption = options.token !== undefined
return {
connected: fromOption || (Boolean(stored.token) && !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 || '',
...(stored.service?.limits ? { limits: stored.service.limits } : {}),
...(stored.nameReplaced ? { nameReplaced: stored.nameReplaced } : {}),
...(stored.service?.quota ? { quota: stored.service.quota } : {}),
...(stored.refusal ? { refusal: { at: stored.refusal.at, code: stored.refusal.code, message: stored.refusal.message, reason: stored.refusal.reason } } : {}),
...(stored.service?.senderAddress ? { senderAddress: stored.service.senderAddress } : {}),
...(stored.service?.name ? { serviceName: stored.service.name } : {}),
...(stored.state ? { state: stored.state } : {}),
...(fromOption ? { tokenSource: 'option' as const } : stored.source ? { tokenSource: stored.source } : {}),
}
}
/**
* The site's state with the service, for a panel or a script. `refresh: true` asks the service
* (`/v1/status`); otherwise what was last stored is returned and nothing leaves the server.
*/
export async function getRelayStatus(payload: BasePayload, options: ResolvedRelayOptions, { refresh = false }: { refresh?: boolean } = {}): Promise<{ error?: string } & RelayStatus> {
if (!refresh) {return describeRelayStore(payload, options, await readSiteStore(payload, options))}
const { error, stored } = await refreshRelayStatus(payload, options)
return { ...describeRelayStore(payload, options, stored), ...(error && error.code !== LOCAL_CODES.noToken ? { error: error.code } : {}) }
}
export { sha256Hex }