Mail relay: state block without an import-map entry, e2e on the reference site, sharper failure reports

- the state block is rendered by IntegrationStatusBanner (no new admin component: generate:importmap gives no diff)
- reference site: e2e/mail-relay.spec.ts with a fixture and setup script; e2e:built runs it with both bundlers
- a failed enrolment is reported as what it was; the service's own refusal after a fresh enrolment
- a message keeps its key after any failure that is not final
- a local site is shown as refused in the panel before any e-mail

Co-Authored-By: Claude Fable 5.2 <[email protected]>
This commit is contained in:
Radosław Smoliński
2026-11-25 21:14:47 +01:00
co-authored by Claude Fable 5.2
parent dd3792cbc7
commit 2cceceffd0
29 changed files with 1461 additions and 65 deletions
+8 -2
View File
@@ -9,7 +9,7 @@ import { getSiteIntegrations } from '../../payload/index.js'
import { graphAvailable, type MailTransport, resolveMailTransport } from '../mailAdapter.js'
import { RELAY_SENDER_ADDRESS } from './adapter.js'
import { RELAY_CONFIRM_PATH, RELAY_CONNECT_PATH, RELAY_DISCONNECT_PATH, RELAY_STATUS_PATH } from './constants.js'
import { resolveRelayOptions } from './options.js'
import { isPublicHost, resolveRelayOptions } from './options.js'
import { disconnectRelay, enrolRelay, type EnrolResult, getRelayStatus, LOCAL_CODES, type RelayStatus, setRelayToken } from './session.js'
type Settings = {
@@ -48,7 +48,13 @@ export async function mailPanelState(req: Pick<PayloadRequest, 'payload'>, own:
const settings = await getSiteIntegrations<Settings>(payload)
const options = resolveRelayOptions(payload, own)
const transport = resolveMailTransport(settings, { graphEnv: graphAvailable(), relay: Boolean(options) })
const status = options ? await getRelayStatus(payload, options, { refresh: refresh && transport === 'relay' }) : null
let status = options ? await getRelayStatus(payload, options, { refresh: refresh && transport === 'relay' }) : null
// A site the service could never call back (it runs locally, or does not know its address) is refused by the
// plugin before any call: say so now, not only after the first failed e-mail.
if (status && options && !status.connected && !status.refusal && !options.ownUrl && options.enrol !== false && options.token === undefined) {
const code = !status.host ? LOCAL_CODES.noHost : !isPublicHost(status.host) ? 'host-not-allowed' : null
if (code) {status = { ...status, refusal: { at: new Date().toISOString(), code } }}
}
const api = payload.config.routes?.api ?? '/api'
return {
...(status?.host ? { confirmUrl: `https://${status.host}${api}${RELAY_CONFIRM_PATH}` } : {}),
+11 -5
View File
@@ -48,9 +48,11 @@ type SendBody = { id?: string; messageId?: string; replayed?: boolean; senderNam
const sleep = (ms: number) => new Promise<void>((resolve) => setTimeout(resolve, ms))
/**
* Messages whose outcome the service never confirmed, by the hash of their bytes: sent again within
* 24 hours they go out under the SAME key, so the service answers with what happened to the first
* attempt instead of sending a second mail. Per process; a message of a new content always gets a new key.
* Messages the service gave no final answer for (no answer at all, a retryable failure, an error page
* of the network in front), by the hash of their bytes: sent again within 24 hours they go out under
* the SAME key, so the service answers with what happened to the first attempt instead of sending a
* second mail. Per process (there is no stored outbox): after a restart, or from another instance of
* the site, the same message gets a new key. A message of a new content always gets a new key.
*/
const unconfirmed = new Map<string, { at: number; key: string }>()
const DAY = 24 * 60 * 60_000
@@ -180,6 +182,8 @@ export async function sendThroughRelay(payload: BasePayload, options: ResolvedRe
use,
)
if (answer.ok || !answer.retryable || attempts >= RELAY_DEFAULTS.attempts) {break}
// The site could not enrol: the message was never handed over, and asking again would not change that.
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}
@@ -228,8 +232,10 @@ export async function sendThroughRelay(payload: BasePayload, options: ResolvedRe
}
const result = describeRefusal(answer)
// Not confirmed, or failed in a way the back end does not explain: the same key if this message is tried again.
if (!result.confirmed || result.detail.startsWith('Probably not sent')) {unconfirmed.set(hash, { at: Date.now(), key: idempotencyKey })}
// Whenever the service did not give a final "no" (no answer, a failure it calls retryable, an answer that was
// not its own): the same key if this message is tried again. Reusing a key is always safe — the service either
// answers with what happened to the first attempt or sends the message now; a new key could send it twice.
if (answer.noAnswer || answer.retryable) {unconfirmed.set(hash, { at: Date.now(), key: idempotencyKey })}
else {unconfirmed.delete(hash)}
if (answer.code === 'site-pending' || answer.code === 'site-suspended') {
const state = answer.code === 'site-pending' ? 'pending' : 'suspended'
+10 -4
View File
@@ -170,10 +170,16 @@ export async function withRelayToken<T>(
const token = candidate?.token ?? stored.token
const enrolNow = async (): Promise<null | RelayRefusal> => {
if (!enrol || use.enrolled) {return refusal(LOCAL_CODES.noToken, 'The site is not connected to the mail service.')}
// 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)
return use.enrolment.ok ? null : refusal(use.enrolment.code, use.enrolment.message, { reason: use.enrolment.reason, retryable: use.enrolment.retryable })
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))) {return null}
return failed()
}
if (!token) {
@@ -191,7 +197,7 @@ export async function withRelayToken<T>(
continue
}
const failed = await enrolNow()
if (failed) {return use.enrolment ? failed : answer}
if (failed) {return use.enrolment && !use.enrolment.ok ? failed : answer}
continue
}
if (candidate) {
@@ -201,7 +207,7 @@ export async function withRelayToken<T>(
}
if (!answer.ok && answer.code === 'reverify') {
const failed = await enrolNow()
if (failed) {return use.enrolment ? failed : answer}
if (failed) {return use.enrolment && !use.enrolment.ok ? failed : answer}
continue
}
return answer
@@ -3,12 +3,15 @@ import { useFormFields, useTranslation } from '@payloadcms/ui'
import type { IntegrationBannerTexts } from './status.js'
import { MailRelayStatus } from '../../globals/SiteIntegrations/components/MailRelayStatus.js'
import { formatDateTime, iaplT } from '../admin-i18n/t.js'
import { type IntegrationLabel, resolveLabel, STATUS_CODE_TEXTS } from './texts.js'
type Props = {
/** Integration name shown in the banner, e.g. { en: 'Spam protection', pl: 'Ochrona przed spamem' }. */
label: IntegrationLabel
/** The e-mail tab: show the block "How e-mails are sent" (transport, the mail service's state) above the banner. */
mailRelay?: boolean
/** Name of the hidden status group (buildIntegrationStatusField). */
statusField: string
/** Texts keys for this integration's failing heading and hint. */
@@ -20,7 +23,17 @@ type Props = {
* the integration has been used once; a red box while it's failing; a short
* green line once it works again. Wording comes from the integration (`texts`).
*/
export function IntegrationStatusBanner({ label, statusField, texts = {} }: Props) {
export function IntegrationStatusBanner({ mailRelay, ...props }: Props) {
if (!mailRelay) {return <StatusBanner {...props} />}
return (
<>
<MailRelayStatus />
<StatusBanner {...props} />
</>
)
}
function StatusBanner({ label, statusField, texts = {} }: Omit<Props, 'mailRelay'>) {
const { i18n, t } = useTranslation()
const state = useFormFields(([f]) => f[`${statusField}.state`]?.value) as string | undefined
const message = useFormFields(([f]) => f[`${statusField}.message`]?.value) as string | undefined
+6 -1
View File
@@ -66,6 +66,11 @@ export function buildIntegrationStatusBanner(
statusField: string,
label: IntegrationLabel,
texts: IntegrationBannerTexts = {},
/**
* `mailRelay`: the e-mail tab's block "How e-mails are sent" (MailRelayStatus) above the banner. It
* rides on this component so that no site has to regenerate its import map for it.
*/
extra: { mailRelay?: boolean } = {},
): Field {
return {
name: `${statusField}Banner`,
@@ -73,7 +78,7 @@ export function buildIntegrationStatusBanner(
admin: {
components: {
Field: {
clientProps: { label, statusField, texts },
clientProps: { label, statusField, texts, ...(extra.mailRelay ? { mailRelay: true } : {}) },
path: '@intecion/ipal-kit/admin#IntegrationStatusBanner',
},
},