- contracts/mail-relay refreshed from IWDL 83af8c6 (1.6.0) - an answer that is not the service's JSON is 'not confirmed' unless its status is 400 to 499 - a site with a token issued by hand does not enrol to heal: it stops and says what to ask Intecion for - a store made on another host (a database copied to staging) is not used: the copy enrols as itself, nothing is revoked - the panel calls the service IWSN (RELAY_SHORT_NAME); docs, logs and the doctor keep the full name Co-Authored-By: Claude Fable 5.2 <[email protected]>
159 lines
7.8 KiB
TypeScript
159 lines
7.8 KiB
TypeScript
import type { Endpoint, PayloadRequest } from 'payload'
|
|
|
|
import type { IntegrationStatus } from '../../integrations/status.js'
|
|
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 { RELAY_SENDER_ADDRESS } from './adapter.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'
|
|
|
|
type Settings = {
|
|
emailStatus?: IntegrationStatus | null
|
|
emailTransport?: 'graph' | 'smtp' | null
|
|
smtpFromAddress?: null | string
|
|
smtpHost?: null | string
|
|
smtpPassword?: null | string
|
|
smtpUser?: null | string
|
|
}
|
|
|
|
/** What the state block on the e-mail tab shows. Never a token, never a password. */
|
|
export type MailPanelState = {
|
|
/** The address the service calls this site back at. */
|
|
confirmUrl?: string
|
|
/** Enabled in the project (`mail.relay` is not `false`). */
|
|
relay: ({ senderAddress: string } & RelayStatus) | null
|
|
replyAddress: null | string
|
|
transport: MailTransport
|
|
}
|
|
|
|
type I18n = Parameters<typeof serverText>[0]
|
|
|
|
const json = (body: unknown, status = 200) => Response.json(body, { headers: { 'cache-control': 'no-store' }, status })
|
|
|
|
function refuse(req: PayloadRequest): null | Response {
|
|
const i18n = req.i18n as I18n
|
|
if (!req.user) {return json({ error: serverText(i18n, 'mailRelayLoggedOut'), ok: false }, 401)}
|
|
if (!userMeetsRole(req, 'admin')) {return json({ error: serverText(i18n, 'mailRelayForbidden'), ok: false }, 403)}
|
|
return null
|
|
}
|
|
|
|
/** The transport in effect and the site's state with the service, for the panel and the doctor. */
|
|
export async function mailPanelState(req: Pick<PayloadRequest, 'payload'>, own: false | RelayOptions | undefined, { refresh = false }: { refresh?: boolean } = {}): Promise<MailPanelState> {
|
|
const { payload } = req
|
|
const settings = await getSiteIntegrations<Settings>(payload)
|
|
const options = resolveRelayOptions(payload, own)
|
|
const transport = resolveMailTransport(settings, { graphEnv: graphAvailable(), relay: Boolean(options) })
|
|
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}` } : {}),
|
|
relay: status ? { ...status, senderAddress: status.senderAddress ?? RELAY_SENDER_ADDRESS } : null,
|
|
replyAddress: typeof settings.smtpFromAddress === 'string' && settings.smtpFromAddress.trim() ? settings.smtpFromAddress.trim() : null,
|
|
transport,
|
|
}
|
|
}
|
|
|
|
/** Why an enrolment was refused, in the admin's language. */
|
|
export function enrolRefusalText(i18n: I18n, refusal: { code: string; message?: string; reason?: string }, state: Pick<MailPanelState, 'confirmUrl' | 'relay'>): string {
|
|
switch (refusal.code) {
|
|
case 'callback-failed':
|
|
return serverText(i18n, 'mailRelayRefusedCallback', { reason: refusal.reason ?? '', url: state.confirmUrl ?? '' })
|
|
case 'enrolment-closed':
|
|
return serverText(i18n, 'mailRelayRefusedClosed')
|
|
case 'host-not-allowed':
|
|
return serverText(i18n, 'mailRelayRefusedHost', { host: state.relay?.host ?? '' })
|
|
// a token issued by hand that stopped working: the site cannot heal by itself
|
|
case 'invalid-token':
|
|
return serverText(i18n, 'mailRelayRefusedToken')
|
|
case LOCAL_CODES.noHost:
|
|
return serverText(i18n, 'mailRelayRefusedNoHost')
|
|
case 'reverify':
|
|
return serverText(i18n, 'mailRelayRefusedAddress')
|
|
case 'site-suspended':
|
|
return serverText(i18n, 'mailRelayStateSuspended')
|
|
default:
|
|
return serverText(i18n, 'mailRelayRefusedOther', { message: refusal.message ?? refusal.code })
|
|
}
|
|
}
|
|
|
|
async function answer(req: PayloadRequest, own: false | RelayOptions | undefined, extra: Record<string, unknown> = {}, refresh = false): Promise<Response> {
|
|
const state = await mailPanelState(req, own, { refresh })
|
|
const refusal = state.relay?.refusal
|
|
return json({ ok: true, ...state, ...(refusal ? { refusalText: enrolRefusalText(req.i18n as I18n, refusal, state) } : {}), ...extra })
|
|
}
|
|
|
|
/**
|
|
* The three admin-only routes behind the state block on Site integrations → E-mail sending:
|
|
* GET /api/iapl/mail-relay/status the transport in effect and the site's state (`?refresh=1` asks the service)
|
|
* POST /api/iapl/mail-relay/connect enrol now — or, with `{ token }`, store a token Intecion issued by hand
|
|
* POST /api/iapl/mail-relay/disconnect give the token up; nothing is sent through the service until "Connect again"
|
|
* None of them ever answers with a token.
|
|
*/
|
|
export function relayPanelEndpoints(own?: false | RelayOptions): Endpoint[] {
|
|
return [
|
|
{
|
|
handler: async (req) => {
|
|
const refused = refuse(req)
|
|
if (refused) {return refused}
|
|
return answer(req, own, {}, new URL(req.url ?? 'http://x').searchParams.get('refresh') === '1')
|
|
},
|
|
method: 'get',
|
|
path: RELAY_STATUS_PATH,
|
|
},
|
|
{
|
|
handler: async (req) => {
|
|
const refused = refuse(req)
|
|
if (refused) {return refused}
|
|
const i18n = req.i18n as I18n
|
|
const options = resolveRelayOptions(req.payload, own)
|
|
if (!options) {return json({ error: serverText(i18n, 'mailRelayOff'), ok: false }, 409)}
|
|
let body: { token?: unknown } = {}
|
|
try {
|
|
body = ((await req.json?.()) ?? {}) as { token?: unknown }
|
|
} catch {
|
|
/* 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)
|
|
}
|
|
return answer(req, own, { message: serverText(i18n, 'mailRelayConnected') }, true)
|
|
}
|
|
const result: EnrolResult = await enrolRelay(req.payload, options, { force: true })
|
|
if (!result.ok) {
|
|
const state = await mailPanelState(req, own)
|
|
return json({ ...state, error: serverText(i18n, 'mailRelayConnectFailed', { reason: enrolRefusalText(i18n, result, state) }), ok: false }, 502)
|
|
}
|
|
return answer(req, own, { message: serverText(i18n, result.state === 'pending' ? 'mailRelayStatePending' : 'mailRelayConnected') }, true)
|
|
},
|
|
method: 'post',
|
|
path: RELAY_CONNECT_PATH,
|
|
},
|
|
{
|
|
handler: async (req) => {
|
|
const refused = refuse(req)
|
|
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)
|
|
return answer(req, own, { message: serverText(req.i18n as I18n, 'mailRelayDisconnected') })
|
|
},
|
|
method: 'post',
|
|
path: RELAY_DISCONNECT_PATH,
|
|
},
|
|
]
|
|
}
|