Mail relay: review of 7d766b6 — R-1 to R-12, four mutations, two sentences
- R-1 a delivered token becomes the one in use only on 200 or a refusal given after authentication - R-2 a token of another site is refused by what /v1/status says (access-key field, scripts); docs for staging - R-3 the confirm route looks the nonce up first and counts only refused calls - R-4 one budget of time per message (10 s, 30 s with files), enrolment and retries included - R-5 'Disconnect' without the service's answer is not confirmed and keeps the token to try again - R-6 no enrolment without the confirm route in the config - R-7 half an SMTP set-up: one log line and a hint in the panel - R-8 to R-10, R-12 docs; R-11 the last failure stays in the state block - tests for redirect: manual, the candidate's nonce, the expectation taken back, one recipient only Co-Authored-By: Claude Fable 5.2 <[email protected]>
This commit is contained in:
co-authored by
Claude Fable 5.2
parent
0ee74ab2a4
commit
a2b07b1dc1
@@ -18,8 +18,10 @@ export const integrationsTexts = defineTexts({
|
||||
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}.`,
|
||||
mailRelayDisconnectUnconfirmed: `${IWSN} could not be reached, so the disconnection is not confirmed. E-mails are no longer sent; press Disconnect again later.`,
|
||||
mailRelayForbidden: 'Only an administrator can do this.',
|
||||
mailRelayHeading: 'How e-mails are sent',
|
||||
mailRelayLastFailure: 'An e-mail was not sent on {{date}}. Code: {{code}}.',
|
||||
mailRelayLoadFailed: 'The state could not be read. Try again.',
|
||||
mailRelayLoggedOut: 'Your session has ended. Log in again.',
|
||||
mailRelayNameReplaced: `${IWSN} did not accept the sender name "{{asked}}", so e-mails leave as "{{used}}". Choose another name below.`,
|
||||
@@ -32,14 +34,17 @@ export const integrationsTexts = defineTexts({
|
||||
mailRelayRefusedHost: `This site has no public address yet ({{host}}). ${IWSN} works once the site runs on its domain.`,
|
||||
mailRelayRefusedNoHost: 'The site does not know its own address. Ask your administrator.',
|
||||
mailRelayRefusedOther: `${IWSN} answered: {{message}}`,
|
||||
mailRelayRefusedSetup: `${IWSN} is not fully set up on this site. Ask your administrator.`,
|
||||
mailRelayRefusedToken: `The access key of this site is no longer valid. Ask your administrator for a new one.`,
|
||||
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}.`,
|
||||
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.',
|
||||
mailRelayStateSuspended: 'E-mail sending was stopped for this site. Ask your administrator.',
|
||||
mailRelayToken: 'Enter an access key',
|
||||
mailRelayTokenForeign: 'This access key belongs to another site, so it was not saved. Ask your administrator for a key for this site.',
|
||||
mailRelayTokenHint: 'Only when your administrator gave you a key for this site. It is stored and never shown again.',
|
||||
mailRelayTokenInvalid: `This is not an access key of ${IWSN}.`,
|
||||
mailRelayTokenSave: 'Save the key',
|
||||
@@ -131,8 +136,10 @@ export const integrationsTexts = defineTexts({
|
||||
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}.`,
|
||||
mailRelayDisconnectUnconfirmed: `Nie udało się połączyć z ${IWSN}, więc rozłączenie nie jest potwierdzone. E-maile nie są już wysyłane; kliknij Rozłącz ponownie później.`,
|
||||
mailRelayForbidden: 'Tylko administrator może to zrobić.',
|
||||
mailRelayHeading: 'Jak wysyłane są e-maile',
|
||||
mailRelayLastFailure: 'E-mail nie został wysłany {{date}}. Kod: {{code}}.',
|
||||
mailRelayLoadFailed: 'Nie udało się odczytać stanu. Spróbuj ponownie.',
|
||||
mailRelayLoggedOut: 'Sesja wygasła. Zaloguj się ponownie.',
|
||||
mailRelayNameReplaced: `${IWSN} nie przyjął nazwy nadawcy „{{asked}}”, więc e-maile wychodzą jako „{{used}}”. Wybierz inną nazwę poniżej.`,
|
||||
@@ -145,14 +152,17 @@ export const integrationsTexts = defineTexts({
|
||||
mailRelayRefusedHost: `Witryna nie ma jeszcze publicznego adresu ({{host}}). ${IWSN} zadziała, gdy witryna będzie dostępna pod swoją domeną.`,
|
||||
mailRelayRefusedNoHost: 'Witryna nie zna własnego adresu. Zapytaj administratora.',
|
||||
mailRelayRefusedOther: `${IWSN} odpowiedział: {{message}}`,
|
||||
mailRelayRefusedSetup: `${IWSN} nie jest w pełni skonfigurowany w tej witrynie. Zapytaj administratora.`,
|
||||
mailRelayRefusedToken: `Klucz dostępu tej witryny stracił ważność. Poproś administratora o nowy.`,
|
||||
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}.`,
|
||||
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.',
|
||||
mailRelayStateSuspended: 'Wysyłka e-maili z tej witryny została wstrzymana. Zapytaj administratora.',
|
||||
mailRelayToken: 'Wpisz klucz dostępu',
|
||||
mailRelayTokenForeign: 'Ten klucz dostępu należy do innej witryny, więc nie został zapisany. Poproś administratora o klucz dla tej witryny.',
|
||||
mailRelayTokenHint: 'Tylko jeśli administrator przekazał Ci klucz dla tej witryny. Klucz zostanie zapisany i nie będzie więcej pokazywany.',
|
||||
mailRelayTokenInvalid: `To nie jest klucz dostępu ${IWSN}.`,
|
||||
mailRelayTokenSave: 'Zapisz klucz',
|
||||
|
||||
@@ -20,6 +20,9 @@ type TransportIntegrations = {
|
||||
}
|
||||
|
||||
const smtpConfigured = (s: TransportIntegrations) => Boolean(s.smtpHost && s.smtpUser && s.smtpPassword)
|
||||
/** Some of server, user name and password are filled in, but not all: the SMTP server cannot be used. */
|
||||
export const smtpIncomplete = (s: TransportIntegrations) => !smtpConfigured(s) && Boolean(s.smtpHost || s.smtpUser || s.smtpPassword)
|
||||
let warnedSmtpIncomplete = false
|
||||
|
||||
/** Which transport a send takes. `none`: nothing is set up and the relay is switched off. */
|
||||
export type MailTransport = 'graph' | 'none' | 'relay' | 'smtp'
|
||||
@@ -156,7 +159,14 @@ export const mailAdapter =
|
||||
const chosen = transportOf(settings)
|
||||
|
||||
// No SMTP server in the panel and no Graph: the Intecion Notifications Webservice.
|
||||
if (chosen === 'relay') {return sendRelayWithPanel(payload, relayOptions()!, message, settings)}
|
||||
if (chosen === 'relay') {
|
||||
// Half an SMTP set-up was "not configured" before 1.17.0; now the mail leaves another way: say so once.
|
||||
if (smtpIncomplete(settings) && !warnedSmtpIncomplete) {
|
||||
warnedSmtpIncomplete = true
|
||||
payload.logger.warn('[iapl] The SMTP settings in Site integrations are incomplete (server, user name and password are all needed), so e-mails go through the Intecion Notifications Webservice. Complete them to use the SMTP server, or empty them.')
|
||||
}
|
||||
return sendRelayWithPanel(payload, relayOptions()!, message, settings)
|
||||
}
|
||||
|
||||
const useGraph = chosen === 'graph'
|
||||
// "Graph" in the panel without its variables is reported only while SMTP carries the mail instead.
|
||||
|
||||
@@ -36,7 +36,8 @@ export type RelayCall = {
|
||||
url: string
|
||||
}
|
||||
|
||||
const firstLine = (text: string) => text.split('\n')[0].slice(0, 300)
|
||||
/** One line of the service's own words for a log or the panel: no control or invisible characters, capped. */
|
||||
const firstLine = (text: string) => text.split('\n')[0].replace(/[\p{Cc}\p{Cf}\p{Zl}\p{Zp}]/gu, ' ').slice(0, 200)
|
||||
|
||||
/**
|
||||
* One request to the service. Never throws. An answer that is not the contract's JSON — an error page
|
||||
|
||||
@@ -36,7 +36,8 @@ async function readBody(req: PayloadRequest): Promise<unknown> {
|
||||
* replaced by one the service has not accepted — and answers `200` with exactly
|
||||
* `{ "confirmation": hex(SHA-256(nonce + "." + token)) }`, which only an endpoint that holds the
|
||||
* nonce and has read the token can compute;
|
||||
* - it is rate-limited per address.
|
||||
* - refused calls are rate-limited per address; a call that carries a nonce the site holds is never
|
||||
* turned away by the limit.
|
||||
* The path is fixed for this product by the service's contract; a project cannot move it (a site with
|
||||
* another API route asks Intecion to set its confirm address).
|
||||
*/
|
||||
@@ -45,17 +46,22 @@ export function relayConfirmEndpoint(options: Pick<RelayOptions, 'confirmRateLim
|
||||
const windowMs = options.confirmRateLimit?.windowMs ?? RELAY_DEFAULTS.confirmRateLimit.windowMs
|
||||
return {
|
||||
handler: async (req: PayloadRequest) => {
|
||||
const limit = await consumeRateLimit({ key: clientIp(req.headers), max, scope: 'mail-relay-confirm', windowMs })
|
||||
if (!limit.ok) {return tooManyRequests(limit.retryAfter, { error: 'Too many requests.' })}
|
||||
|
||||
// Only calls that are REFUSED count against the limit, and the nonce is looked up first: the address the
|
||||
// service calls from is shared (every Cloudflare Worker reaches a site behind Cloudflare from the same
|
||||
// one), so a stranger who fills a per-address bucket must not keep the site's own enrolment out.
|
||||
const refuse = async () => {
|
||||
const limit = await consumeRateLimit({ key: clientIp(req.headers), max, scope: 'mail-relay-confirm', windowMs })
|
||||
return limit.ok ? notFound() : tooManyRequests(limit.retryAfter, { error: 'Too many requests.' })
|
||||
}
|
||||
const body = (await readBody(req)) as { nonce?: unknown; state?: unknown; token?: unknown } | null
|
||||
if (!body || typeof body !== 'object') {return notFound()}
|
||||
if (!body || typeof body !== 'object') {return refuse()}
|
||||
const { nonce, state, token } = body
|
||||
if (typeof nonce !== 'string' || !NONCE.test(nonce) || typeof token !== 'string' || !TOKEN.test(token) || typeof state !== 'string' || !STATES.has(state)) {
|
||||
return notFound()
|
||||
return refuse()
|
||||
}
|
||||
try {
|
||||
if (!(await takeNonce(req.payload, nonce))) {return notFound()}
|
||||
// one read of the key-value store for a well-formed call; a wrong nonce is refused and counted
|
||||
if (!(await takeNonce(req.payload, nonce))) {return refuse()}
|
||||
await writeRelayCandidate(req.payload, { at: new Date().toISOString(), nonceHash: sha256Hex(nonce), state: state as 'active' | 'pending' | 'suspended', token })
|
||||
} catch (err) {
|
||||
req.payload.logger.error(`[iapl] mail service: the confirm route could not use the store: ${err instanceof Error ? err.message.split('\n')[0] : String(err)}`)
|
||||
|
||||
@@ -40,6 +40,13 @@ export const RELAY_DEFAULTS = {
|
||||
refusalCooldownMs: 15 * 60_000,
|
||||
/** How long the limits read from `/v1/status` are used before they are read again. */
|
||||
statusTtlMs: 60 * 60_000,
|
||||
/**
|
||||
* Everything a send may take, enrolment and retries included: somebody waits for the request that sends
|
||||
* the mail (a form's visitor). After it the message is reported and nothing more is tried.
|
||||
*/
|
||||
totalTimeoutMs: 10_000,
|
||||
/** The same for a message with files: a 10 MB upload has to fit. */
|
||||
totalTimeoutWithFilesMs: 30_000,
|
||||
/** Other calls (status, rotate, revoke). */
|
||||
timeoutMs: 10_000,
|
||||
/** Waiting between the attempts for one message, in all. Wins over `retryAfter`. */
|
||||
|
||||
@@ -56,8 +56,12 @@ export const getRelayStatus = (payload: BasePayload, options?: { refresh?: boole
|
||||
return status(payload, resolved(payload, Object.keys(own).length ? own : undefined), { refresh })
|
||||
}
|
||||
|
||||
/**
|
||||
* `revoked: false` = the service could not be asked: the site stops using the token, but it still works there
|
||||
* until this is called again and answered.
|
||||
*/
|
||||
/** Gives the site's token up on the service and forgets it; the site sends nothing through the service until it is connected again. */
|
||||
export const disconnectRelay = (payload: BasePayload, options?: RelayOptions): Promise<void> => disconnect(payload, resolved(payload, options))
|
||||
export const disconnectRelay = (payload: BasePayload, options?: RelayOptions): Promise<{ revoked: boolean }> => disconnect(payload, resolved(payload, options))
|
||||
|
||||
/** Asks for a new token now (the adapter does it by itself when the service says the token is due). */
|
||||
export const rotateRelayToken = (payload: BasePayload, options?: RelayOptions) => rotate(payload, resolved(payload, options), { force: true })
|
||||
|
||||
@@ -39,13 +39,20 @@ export type RelayOptions = {
|
||||
retryBackoffMs?: number
|
||||
/** The display name of outgoing mail. Default: the panel's "Sender name", else the site name. */
|
||||
senderName?: ((args: { payload: BasePayload }) => null | Promise<null | string | undefined> | string | undefined) | string
|
||||
/** One attempt of a send, in ms. Default 30 000 (a 10 MB attachment has to fit). */
|
||||
/** One attempt of a send, in ms. Default 30 000 (a 10 MB attachment has to fit); never more than what is left of `totalTimeoutMs`. */
|
||||
timeoutMs?: number
|
||||
/**
|
||||
* A token from elsewhere (a relay of your own, or a secret of your deployment). When set, the stored
|
||||
* token is not used and the site does not enrol.
|
||||
*/
|
||||
token?: (() => Promise<string | undefined> | string | undefined) | string
|
||||
/**
|
||||
* Everything one message may take, in ms — enrolment, attempts and waits together. Default 10 000, and
|
||||
* 30 000 for a message with files. A form's visitor waits for the mail, so a service that hangs must not
|
||||
* hold the request for the sum of the attempts. After it the message is reported ("not confirmed" when an
|
||||
* attempt was cut off). `{ plain, files }` sets the two apart; a job that nobody waits for may raise it.
|
||||
*/
|
||||
totalTimeoutMs?: { files?: number; plain?: number } | number
|
||||
/** Base address of the service. Default `https://webservices.intecion.net/mail`. A relay of your own speaks the same contract. */
|
||||
url?: string
|
||||
}
|
||||
|
||||
@@ -6,8 +6,9 @@ import type { RelayOptions } from './options.js'
|
||||
import { userMeetsRole } from '../../access/predicates.js'
|
||||
import { serverText } from '../../integrations/texts.js'
|
||||
import { getSiteIntegrations } from '../../payload/index.js'
|
||||
import { graphAvailable, type MailTransport, resolveMailTransport } from '../mailAdapter.js'
|
||||
import { graphAvailable, type MailTransport, resolveMailTransport, smtpIncomplete } from '../mailAdapter.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 { isPublicHost, relayHost, resolveRelayOptions } from './options.js'
|
||||
import { disconnectRelay, enrolRelay, type EnrolResult, getRelayStatus, LOCAL_CODES, type RelayStatus, setRelayToken } from './session.js'
|
||||
@@ -28,6 +29,8 @@ export type MailPanelState = {
|
||||
/** Enabled in the project (`mail.relay` is not `false`). */
|
||||
relay: ({ senderAddress: string } & RelayStatus) | null
|
||||
replyAddress: null | string
|
||||
/** Server, user name or password is filled in, but not all three: the SMTP server is not used. */
|
||||
smtpIncomplete?: boolean
|
||||
transport: MailTransport
|
||||
}
|
||||
|
||||
@@ -60,6 +63,7 @@ export async function mailPanelState(req: Pick<PayloadRequest, 'payload'>, own:
|
||||
...(status?.host ? { confirmUrl: `https://${status.host}${api}${RELAY_CONFIRM_PATH}` } : {}),
|
||||
relay: status ? { ...status, senderAddress: status.senderAddress ?? RELAY_SENDER_ADDRESS } : null,
|
||||
replyAddress: typeof settings.smtpFromAddress === 'string' && settings.smtpFromAddress.trim() ? settings.smtpFromAddress.trim() : null,
|
||||
...(smtpIncomplete(settings) ? { smtpIncomplete: true } : {}),
|
||||
transport,
|
||||
}
|
||||
}
|
||||
@@ -76,8 +80,12 @@ export function enrolRefusalText(i18n: I18n, refusal: { code: string; message?:
|
||||
// a token issued by hand that stopped working: the site cannot heal by itself
|
||||
case 'invalid-token':
|
||||
return serverText(i18n, 'mailRelayRefusedToken')
|
||||
case LOCAL_CODES.foreignToken:
|
||||
return serverText(i18n, 'mailRelayTokenForeign')
|
||||
case LOCAL_CODES.noHost:
|
||||
return serverText(i18n, 'mailRelayRefusedNoHost')
|
||||
case LOCAL_CODES.noRoute:
|
||||
return serverText(i18n, 'mailRelayRefusedSetup')
|
||||
case 'reverify':
|
||||
return serverText(i18n, 'mailRelayRefusedAddress')
|
||||
case 'site-suspended':
|
||||
@@ -125,12 +133,22 @@ export function relayPanelEndpoints(own?: false | RelayOptions): Endpoint[] {
|
||||
/* no body: plain "connect again" */
|
||||
}
|
||||
if (typeof body.token === 'string' && body.token.trim()) {
|
||||
try {
|
||||
await setRelayToken(req.payload, body.token.trim(), { host: relayHost(req.payload, options) || undefined })
|
||||
} catch {
|
||||
return json({ error: serverText(i18n, 'mailRelayTokenInvalid'), ok: false }, 400)
|
||||
const pasted = body.token.trim()
|
||||
if (!/^ims_[\w-]{43}$/.test(pasted)) {return json({ error: serverText(i18n, 'mailRelayTokenInvalid'), ok: false }, 400)}
|
||||
// Ask the service whose token this is BEFORE it replaces anything: a token of another site, or one the
|
||||
// service does not know, is refused and the site's present connection stays as it is.
|
||||
const ownHost = relayHost(req.payload, options)
|
||||
const asked = await relayRequest<{ host?: string }>({ fetchImpl: options.fetchImpl, method: 'GET', path: '/v1/status', token: pasted, url: options.url })
|
||||
if (asked.ok && ownHost && asked.body.host && asked.body.host !== ownHost) {return json({ error: serverText(i18n, 'mailRelayTokenForeign'), ok: false }, 400)}
|
||||
if (!asked.ok && asked.code === 'invalid-token' && !asked.noAnswer) {return json({ error: serverText(i18n, 'mailRelayTokenInvalid'), ok: false }, 400)}
|
||||
if (!asked.ok && asked.code !== 'reverify') {return json({ error: serverText(i18n, 'mailRelayLoadFailed'), ok: false }, 502)}
|
||||
await setRelayToken(req.payload, pasted, { host: ownHost || undefined })
|
||||
// the service says which host the token is for: another site's is refused and forgotten
|
||||
const checked = await mailPanelState(req, own, { refresh: true })
|
||||
if (checked.relay?.refusal?.code === LOCAL_CODES.foreignToken) {
|
||||
return json({ ...checked, error: serverText(i18n, 'mailRelayTokenForeign'), ok: false, refusalText: serverText(i18n, 'mailRelayTokenForeign') }, 400)
|
||||
}
|
||||
return answer(req, own, { message: serverText(i18n, 'mailRelayConnected') }, true)
|
||||
return answer(req, own, { message: serverText(i18n, 'mailRelayConnected') })
|
||||
}
|
||||
const result: EnrolResult = await enrolRelay(req.payload, options, { force: true })
|
||||
if (!result.ok) {
|
||||
@@ -148,7 +166,11 @@ export function relayPanelEndpoints(own?: false | RelayOptions): Endpoint[] {
|
||||
if (refused) {return refused}
|
||||
const options = resolveRelayOptions(req.payload, own)
|
||||
if (!options) {return json({ error: serverText(req.i18n as I18n, 'mailRelayOff'), ok: false }, 409)}
|
||||
await disconnectRelay(req.payload, options)
|
||||
const { revoked } = await disconnectRelay(req.payload, options)
|
||||
if (!revoked) {
|
||||
// the site stopped using the token, but the service has not confirmed that it gave it up
|
||||
return json({ ...(await mailPanelState(req, own)), error: serverText(req.i18n as I18n, 'mailRelayDisconnectUnconfirmed'), ok: false }, 502)
|
||||
}
|
||||
return answer(req, own, { message: serverText(req.i18n as I18n, 'mailRelayDisconnected') })
|
||||
},
|
||||
method: 'post',
|
||||
|
||||
@@ -84,7 +84,7 @@ function describeRefusal(answer: RelayRefusal): { sent: false } & RelaySendResul
|
||||
const extra = [answer.limit ? `limit: ${answer.limit}` : '', answer.reason ? `reason: ${answer.reason}` : '', answer.field ? `field: ${answer.field}` : ''].filter(Boolean).join(', ')
|
||||
const said = `${answer.code}${extra ? ` (${extra})` : ''}: ${answer.message}`
|
||||
if (answer.code === LOCAL_CODES.disconnected) {return failure('relay-disconnected', answer.code, answer.message)}
|
||||
if (answer.code === LOCAL_CODES.noToken || answer.code === LOCAL_CODES.noHost) {return failure('relay-refused', answer.code, answer.message)}
|
||||
if (([LOCAL_CODES.foreignToken, LOCAL_CODES.noHost, LOCAL_CODES.noRoute, LOCAL_CODES.noToken] as string[]).includes(answer.code)) {return failure('relay-refused', answer.code, answer.message)}
|
||||
// No answer at all, or a send the service cannot report on yet: it may be out.
|
||||
if (answer.noAnswer || answer.code === 'in-progress') {return failure('relay-not-confirmed', answer.code, `Not confirmed — the message may have been sent. ${said}`, false)}
|
||||
if (answer.code === 'callback-failed' && answer.reason === 'status') {
|
||||
@@ -113,6 +113,9 @@ export type RelaySendContext = {
|
||||
* `Idempotency-Key`: at most three attempts, 30 seconds each, at most ten seconds of waiting between
|
||||
* them in all (which win over the service's `retryAfter`), and only after an answer that says
|
||||
* `retryable` or after no answer. An enrolment made on the way is not one of the three.
|
||||
*
|
||||
* All of it shares one budget (`totalTimeoutMs`: 10 seconds, 30 with files): the request that sends the
|
||||
* mail has somebody waiting. An attempt cut off by it counts as no answer — "not confirmed".
|
||||
*/
|
||||
export async function sendThroughRelay(payload: BasePayload, options: ResolvedRelayOptions, message: SendEmailOptions, context: RelaySendContext = {}): Promise<RelaySendResult> {
|
||||
// What the message is: its own mark; else what an auth operation said about a message to this address
|
||||
@@ -158,26 +161,51 @@ export async function sendThroughRelay(payload: BasePayload, options: ResolvedRe
|
||||
}
|
||||
}
|
||||
|
||||
// Somebody waits for this request (a form's visitor): everything from here on — a check, an enrolment, the
|
||||
// attempts and the waits between them — shares one budget. A service that hangs costs that much, not the
|
||||
// sum of the attempts' time-outs.
|
||||
const total = options.totalTimeoutMs
|
||||
const hasFiles = Boolean(request.attachments?.length)
|
||||
const budgetMs =
|
||||
typeof total === 'number' ? total
|
||||
: hasFiles ? (total?.files ?? RELAY_DEFAULTS.totalTimeoutWithFilesMs)
|
||||
: (total?.plain ?? RELAY_DEFAULTS.totalTimeoutMs)
|
||||
const deadline = Date.now() + Math.max(1, budgetMs)
|
||||
const left = () => deadline - Date.now()
|
||||
|
||||
// A token stored by hand is used only once the service has said that it is this host's (a token of another
|
||||
// site, pasted in or copied, must not send as that site).
|
||||
if (stored.token && stored.manual && !stored.hostChecked && options.token === undefined) {
|
||||
const checked = await refreshRelayStatus(payload, options, { timeoutMs: Math.max(1, left()) })
|
||||
if (checked.error && checked.error.code !== 'reverify' && checked.error.code !== 'invalid-token') {
|
||||
// nothing was sent: the check itself did not get through, or the token is another site's
|
||||
return checked.error.code === LOCAL_CODES.foreignToken
|
||||
? failure('relay-refused', checked.error.code, checked.error.message)
|
||||
: failure('relay-unreachable', checked.error.code, `The token stored by hand could not be checked with the mail service, so nothing was sent. ${checked.error.message}`)
|
||||
}
|
||||
}
|
||||
|
||||
if (stored.service?.rotateAfter && Date.parse(stored.service.rotateAfter) <= Date.now()) {
|
||||
await rotateRelayToken(payload, options).catch(() => undefined)
|
||||
await rotateRelayToken(payload, options, { timeoutMs: Math.max(1, left()) }).catch(() => undefined)
|
||||
}
|
||||
|
||||
const body = Buffer.from(JSON.stringify(request), 'utf8')
|
||||
const hash = createHash('sha256').update(body).digest('hex')
|
||||
const idempotencyKey = keyFor(hash)
|
||||
const use: TokenUse = {}
|
||||
const use: TokenUse = { deadline }
|
||||
const budget = RELAY_DEFAULTS.waitBudgetMs
|
||||
let attempts = 0
|
||||
let waited = 0
|
||||
let answer: RelayAnswer<SendBody> = { code: 'unavailable', message: 'not tried', noAnswer: false, ok: false, retryable: false, status: 0 }
|
||||
|
||||
while (attempts < RELAY_DEFAULTS.attempts) {
|
||||
if (left() <= 0) {break} // the time is up: report what the last attempt said
|
||||
answer = await withRelayToken<SendBody>(
|
||||
payload,
|
||||
options,
|
||||
(token) => {
|
||||
attempts += 1
|
||||
return relayRequest<SendBody>({ body, fetchImpl: options.fetchImpl, idempotencyKey, method: 'POST', path: '/v1/send', timeoutMs: options.timeoutMs ?? RELAY_DEFAULTS.attemptTimeoutMs, token, url: options.url })
|
||||
return relayRequest<SendBody>({ body, fetchImpl: options.fetchImpl, idempotencyKey, method: 'POST', path: '/v1/send', timeoutMs: Math.max(1, Math.min(options.timeoutMs ?? RELAY_DEFAULTS.attemptTimeoutMs, left())), token, url: options.url })
|
||||
},
|
||||
use,
|
||||
)
|
||||
@@ -186,7 +214,7 @@ export async function sendThroughRelay(payload: BasePayload, options: ResolvedRe
|
||||
if (use.enrolment && !use.enrolment.ok) {break}
|
||||
const wait = answer.retryAfter !== undefined ? answer.retryAfter * 1000 : attempts * (options.retryBackoffMs ?? 1000)
|
||||
// The ten seconds win over retryAfter: stop at once and report.
|
||||
if (waited + wait > budget) {break}
|
||||
if (waited + wait > budget || wait >= left()) {break}
|
||||
await sleep(wait)
|
||||
waited += wait
|
||||
}
|
||||
@@ -214,7 +242,7 @@ export async function sendThroughRelay(payload: BasePayload, options: ResolvedRe
|
||||
// Limits, quota and the day to rotate: read again once they are an hour old. Awaited (one short GET an
|
||||
// hour): a write to the store that lands after the request has ended could undo a "Disconnect" or a rotation.
|
||||
if (!now.service || Date.now() - Date.parse(now.service.fetchedAt) > RELAY_DEFAULTS.statusTtlMs) {
|
||||
await refreshRelayStatus(payload, options)
|
||||
await refreshRelayStatus(payload, options, { timeoutMs: Math.max(2000, left()) })
|
||||
}
|
||||
} catch {
|
||||
/* bookkeeping must not turn a sent mail into a failed one */
|
||||
@@ -241,6 +269,17 @@ export async function sendThroughRelay(payload: BasePayload, options: ResolvedRe
|
||||
const state = answer.code === 'site-pending' ? 'pending' : 'suspended'
|
||||
if (stored.state !== state) {await updateRelayStore(payload, (current) => ({ ...current, state })).catch(() => undefined)}
|
||||
}
|
||||
// The panel's status is the LAST send's; a later good mail must not hide this one: kept with its time
|
||||
// (written when the code changes, or every ten minutes while it lasts).
|
||||
try {
|
||||
const now = await readRelayStore(payload)
|
||||
const last = now.lastFailure
|
||||
if (!last || last.code !== result.code || Date.now() - Date.parse(last.at) > 10 * 60_000) {
|
||||
await updateRelayStore(payload, (current) => ({ ...current, lastFailure: { at: new Date().toISOString(), code: result.code, kind } }))
|
||||
}
|
||||
} catch {
|
||||
/* bookkeeping only */
|
||||
}
|
||||
payload.logger.error(`[iapl] mail service: e-mail ${result.confirmed ? 'not sent' : 'not confirmed'} (${result.code}; ${answer.code}${answer.limit ? `, ${answer.limit}` : ''}${answer.reason ? `, ${answer.reason}` : ''}).`)
|
||||
return result
|
||||
}
|
||||
|
||||
@@ -6,7 +6,7 @@ import type { ResolvedRelayOptions } from './options.js'
|
||||
|
||||
import { PLUGIN_VERSION } from '../../../version.js'
|
||||
import { type RelayAnswer, type RelayRefusal, relayRequest } from './client.js'
|
||||
import { RELAY_DEFAULTS, RELAY_PRODUCT, type RelayStatusCode, relayStatusFor } from './constants.js'
|
||||
import { RELAY_CONFIRM_PATH, RELAY_DEFAULTS, RELAY_PRODUCT, type RelayStatusCode, relayStatusFor } from './constants.js'
|
||||
import { isPublicHost, relayHost } from './options.js'
|
||||
import {
|
||||
clearRelayStore,
|
||||
@@ -31,7 +31,11 @@ const refusal = (code: string, message: string, extra: Partial<RelayRefusal> = {
|
||||
/** Codes this client makes up for what never reached the service. */
|
||||
export const LOCAL_CODES = {
|
||||
disconnected: 'client-disconnected',
|
||||
/** A token that belongs to another site (the service says which host it is for). */
|
||||
foreignToken: 'client-foreign-token',
|
||||
/** 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
|
||||
|
||||
@@ -47,7 +51,7 @@ const enrolFailure = (answer: RelayRefusal): { ok: false } & EnrolResult => ({
|
||||
retryable: answer.retryable,
|
||||
status:
|
||||
answer.code === LOCAL_CODES.disconnected ? 'relay-disconnected'
|
||||
: answer.code === LOCAL_CODES.noHost || answer.code === LOCAL_CODES.noToken ? 'relay-refused'
|
||||
: ([LOCAL_CODES.foreignToken, LOCAL_CODES.noHost, LOCAL_CODES.noRoute, LOCAL_CODES.noToken] as string[]).includes(answer.code) ? 'relay-refused'
|
||||
: relayStatusFor(answer.code, answer.retryable),
|
||||
})
|
||||
|
||||
@@ -60,15 +64,15 @@ const inFlight = new WeakMap<object, Promise<EnrolResult>>()
|
||||
*
|
||||
* `force`: also when an earlier enrolment was refused a moment ago, or the site was disconnected.
|
||||
*/
|
||||
export function enrolRelay(payload: BasePayload, options: ResolvedRelayOptions, { force = false }: { force?: boolean } = {}): Promise<EnrolResult> {
|
||||
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).finally(() => inFlight.delete(payload))
|
||||
const run = enrolOnce(payload, options, force, deadline).finally(() => inFlight.delete(payload))
|
||||
inFlight.set(payload, run)
|
||||
return run
|
||||
}
|
||||
|
||||
async function enrolOnce(payload: BasePayload, options: ResolvedRelayOptions, force: boolean): Promise<EnrolResult> {
|
||||
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.'))}
|
||||
if (!force && stored.refusal && Date.parse(stored.refusal.until) > Date.now()) {
|
||||
@@ -78,6 +82,11 @@ async function enrolOnce(payload: BasePayload, options: ResolvedRelayOptions, fo
|
||||
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.`))
|
||||
@@ -93,7 +102,7 @@ async function enrolOnce(payload: BasePayload, options: ResolvedRelayOptions, fo
|
||||
fetchImpl: options.fetchImpl,
|
||||
method: 'POST',
|
||||
path: '/v1/enrol',
|
||||
timeoutMs: RELAY_DEFAULTS.enrolTimeoutMs,
|
||||
timeoutMs: deadline === undefined ? RELAY_DEFAULTS.enrolTimeoutMs : Math.max(1, Math.min(RELAY_DEFAULTS.enrolTimeoutMs, deadline - Date.now())),
|
||||
url: options.url,
|
||||
})
|
||||
if (answer.ok) {
|
||||
@@ -108,8 +117,10 @@ async function enrolOnce(payload: BasePayload, options: ResolvedRelayOptions, fo
|
||||
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,
|
||||
@@ -154,6 +165,16 @@ async function handIssued(payload: BasePayload, code: keyof typeof HAND_ISSUED):
|
||||
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', '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}
|
||||
@@ -162,7 +183,12 @@ async function optionToken(options: ResolvedRelayOptions): Promise<string | unde
|
||||
}
|
||||
|
||||
/** Kept across the retries of one message: a site enrols at most once per message. */
|
||||
export type TokenUse = { enrolled?: boolean; enrolment?: EnrolResult }
|
||||
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:
|
||||
@@ -170,7 +196,10 @@ export type TokenUse = { enrolled?: boolean; enrolment?: EnrolResult }
|
||||
* - a token the call-back delivered but `/v1/enrol` never confirmed is tried first; on
|
||||
* `401 invalid-token` it is dropped and the earlier token is used again;
|
||||
* - `401 invalid-token` or `401 reverify` → enrol again once, then call again.
|
||||
* Any answer but `invalid-token` proves the token: a candidate then becomes the token in use.
|
||||
* 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,
|
||||
@@ -194,7 +223,7 @@ export async function withRelayToken<T>(
|
||||
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)
|
||||
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.
|
||||
@@ -221,9 +250,10 @@ export async function withRelayToken<T>(
|
||||
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, (current) => ({ ...current, enrolledAt: candidate.at, host: relayHost(payload, options) || current.host, manual: false, source: 'enrolment', state: candidate.state, token: candidate.token }))
|
||||
await updateRelayStore(payload, (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)
|
||||
}
|
||||
if (!answer.ok && answer.code === 'reverify') {
|
||||
@@ -238,6 +268,7 @@ export async function withRelayToken<T>(
|
||||
}
|
||||
|
||||
type StatusBody = {
|
||||
host?: string
|
||||
limits?: NonNullable<RelayStored['service']>['limits']
|
||||
quota?: NonNullable<RelayStored['service']>['quota']
|
||||
sender?: { address?: string }
|
||||
@@ -252,18 +283,29 @@ type StatusBody = {
|
||||
* (`401 reverify`) enrols again, as on a send. Returns the stored entry as it is afterwards; `error`
|
||||
* when the service could not be asked.
|
||||
*/
|
||||
export async function refreshRelayStatus(payload: BasePayload, options: ResolvedRelayOptions): Promise<{ error?: RelayRefusal; stored: RelayStored }> {
|
||||
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', token, url: options.url }),
|
||||
{},
|
||||
(token) => relayRequest<StatusBody>({ fetchImpl: options.fetchImpl, method: 'GET', path: '/v1/status', 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)
|
||||
const stored = await updateRelayStore(payload, (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, (current) => ({
|
||||
...current,
|
||||
hostChecked: true,
|
||||
service: {
|
||||
name: body.service?.name,
|
||||
contract: body.service?.contract,
|
||||
@@ -284,13 +326,13 @@ export async function refreshRelayStatus(payload: BasePayload, options: Resolved
|
||||
* the site read the store again in time. `409 already-rotated` = another process won: nothing to do
|
||||
* when the store already holds a newer token, else the site enrols again on its next send.
|
||||
*/
|
||||
export async function rotateRelayToken(payload: BasePayload, options: ResolvedRelayOptions, { force = false }: { force?: boolean } = {}): Promise<'failed' | 'not-due' | 'rotated'> {
|
||||
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', token: used, url: options.url })
|
||||
const answer = await relayRequest<{ token?: string }>({ fetchImpl: options.fetchImpl, method: 'POST', path: '/v1/rotate', 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, (current) => ({
|
||||
@@ -313,14 +355,26 @@ export async function rotateRelayToken(payload: BasePayload, options: ResolvedRe
|
||||
return 'failed'
|
||||
}
|
||||
|
||||
/** Gives the token up on the service (every token of the site stops working) and forgets it here. */
|
||||
export async function disconnectRelay(payload: BasePayload, options: ResolvedRelayOptions): Promise<void> {
|
||||
/**
|
||||
* 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) {
|
||||
await relayRequest({ fetchImpl: options.fetchImpl, method: 'POST', path: '/v1/revoke', token: stored.token, url: options.url })
|
||||
const answer = await relayRequest({ fetchImpl: options.fetchImpl, method: 'POST', path: '/v1/revoke', 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, (current) => ({ ...current, disconnected: true, revokePending: true }))
|
||||
return { revoked: false }
|
||||
}
|
||||
}
|
||||
await clearRelayStore(payload, { disconnected: true })
|
||||
return { revoked: true }
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -335,8 +389,10 @@ export async function setRelayToken(payload: BasePayload, token: string, options
|
||||
disconnected: false,
|
||||
enrolledAt: new Date().toISOString(),
|
||||
...(options.host ? { host: options.host } : {}),
|
||||
hostChecked: false,
|
||||
manual: true,
|
||||
refusal: null,
|
||||
revokePending: false,
|
||||
service: null,
|
||||
source: 'manual',
|
||||
state: current.state ?? 'active',
|
||||
@@ -349,10 +405,14 @@ export type RelayStatus = {
|
||||
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
|
||||
@@ -362,8 +422,10 @@ export type RelayStatus = {
|
||||
export function describeRelayStore(payload: BasePayload, options: ResolvedRelayOptions, stored: RelayStored): RelayStatus {
|
||||
const fromOption = options.token !== undefined
|
||||
return {
|
||||
connected: fromOption || Boolean(stored.token),
|
||||
connected: fromOption || (Boolean(stored.token) && !stored.disconnected),
|
||||
disconnected: Boolean(stored.disconnected),
|
||||
...(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 } : {}),
|
||||
|
||||
@@ -30,17 +30,26 @@ export type RelayLimits = {
|
||||
}
|
||||
|
||||
export type RelayStored = {
|
||||
/** An admin pressed "Disconnect": no send and no enrolment until "Connect again". */
|
||||
/**
|
||||
* An admin pressed "Disconnect": no send and no enrolment until "Connect again". The token is still here
|
||||
* only while the service has not confirmed that it gave it up (`revokePending`).
|
||||
*/
|
||||
disconnected?: boolean
|
||||
enrolledAt?: string
|
||||
/** The host the token was issued for. A store found on another host is not this site's (readOwnRelayStore). */
|
||||
host?: string
|
||||
/** The service itself said that the token is this host's (`/v1/status`). A hand-issued token is not used before that. */
|
||||
hostChecked?: boolean
|
||||
/** The last message that was not sent (or not confirmed): the next good one does not hide it. */
|
||||
lastFailure?: { at: string; code: string; kind?: string } | null
|
||||
/** The token was issued by hand: the site cannot be called back, so it never enrols by itself to heal. */
|
||||
manual?: boolean
|
||||
/** The last warning about the sender name: the name the mail left under instead. */
|
||||
nameReplaced?: { asked: string; at: string; used: string } | null
|
||||
/** The last refusal of an enrolment; no new enrolment by itself before `until`. */
|
||||
refusal?: { at: string; code: string; message?: string; reason?: string; until: string } | null
|
||||
/** "Disconnect" could not reach the service: the token still works there; pressing it again tries again. */
|
||||
revokePending?: boolean
|
||||
/** What `/v1/status` last said. */
|
||||
service?: {
|
||||
contract?: string
|
||||
|
||||
Reference in New Issue
Block a user