Mail relay: the built-in client for the Intecion Notifications Webservice
Transport, enrolment with the confirm route, token and state in payload-kv, rotation, the panel's state block, doctor rules, the fake service and the copied contract 1.5.0. Tests against the contract's runner and the fake. Docs and HTTP tests follow. Co-Authored-By: Claude Fable 5.2 <[email protected]>
This commit is contained in:
co-authored by
Claude Fable 5.2
parent
9efd86a06f
commit
ea9703f8e3
@@ -5,6 +5,7 @@
|
||||
* banners). Separate export so Payload's importMap can resolve them by a stable path, and so
|
||||
* nothing importing @payloadcms/ui ends up in /client — that entry ships to every site visitor.
|
||||
*/
|
||||
export { MailRelayStatus } from '../globals/SiteIntegrations/components/MailRelayStatus.js'
|
||||
export { MaskedField } from '../globals/SiteIntegrations/components/MaskedField.js'
|
||||
export { TestEmailButton } from '../globals/SiteIntegrations/components/TestEmailButton.js'
|
||||
export { DocumentTitle } from '../modules/admin-i18n/DocumentTitle.js'
|
||||
|
||||
@@ -0,0 +1,163 @@
|
||||
'use client'
|
||||
|
||||
import { useConfig, useTranslation } from '@payloadcms/ui'
|
||||
import { useCallback, useEffect, useState } from 'react'
|
||||
|
||||
import { iaplT } from '../../../modules/admin-i18n/t.js'
|
||||
import { RELAY_CONNECT_PATH, RELAY_DISCONNECT_PATH, RELAY_STATUS_PATH } from '../../../modules/email/relay/constants.js'
|
||||
|
||||
type Window = { limit: number; remaining: number }
|
||||
type State = {
|
||||
error?: string
|
||||
message?: string
|
||||
ok?: boolean
|
||||
refusalText?: string
|
||||
relay?: {
|
||||
connected?: boolean
|
||||
disconnected?: boolean
|
||||
nameReplaced?: { asked: string; used: string }
|
||||
quota?: { day?: Window; hour?: Window }
|
||||
senderAddress?: string
|
||||
state?: 'active' | 'pending' | 'suspended'
|
||||
tokenSource?: string
|
||||
} | null
|
||||
replyAddress?: null | string
|
||||
transport?: 'graph' | 'none' | 'relay' | 'smtp'
|
||||
}
|
||||
|
||||
const box = { border: '1px solid var(--theme-elevation-150)', borderRadius: 4, marginBottom: '1.5rem', padding: '0.9rem 1rem' } as const
|
||||
const line = { margin: '0.35rem 0 0' } as const
|
||||
const warn = { ...line, color: 'var(--theme-warning-600, #b45309)' } as const
|
||||
|
||||
/**
|
||||
* Admin UI: the state block at the top of Site integrations → E-mail sending. Says which transport is
|
||||
* in effect (the Intecion mail service, the site's SMTP server, Microsoft Graph), and for the mail
|
||||
* service: the state, the address mail leaves from, where replies go, what is left of the limits, and
|
||||
* a sender name the service did not accept. "Check now" asks the service; "Connect again" and
|
||||
* "Disconnect" act on the site's connection. No token is ever shown or sent to this component.
|
||||
*
|
||||
* Assigned via a `ui` field's admin.components.Field. Texts: `mailRelay*` keys.
|
||||
*/
|
||||
export const MailRelayStatus = () => {
|
||||
const { t } = useTranslation()
|
||||
const { config } = useConfig()
|
||||
const api = config.routes?.api ?? '/api'
|
||||
const text = (key: Parameters<typeof iaplT>[1], vars?: Record<string, unknown>) => iaplT(t as never, key, vars)
|
||||
const [state, setState] = useState<null | State>(null)
|
||||
const [busy, setBusy] = useState(false)
|
||||
const [note, setNote] = useState<{ kind: 'error' | 'ok'; msg: string } | null>(null)
|
||||
const [token, setToken] = useState('')
|
||||
const [showToken, setShowToken] = useState(false)
|
||||
|
||||
const call = useCallback(
|
||||
async (path: string, init?: RequestInit, announce = false) => {
|
||||
setBusy(true)
|
||||
try {
|
||||
const res = await fetch(`${api}${path}`, { credentials: 'include', ...init })
|
||||
const data = (await res.json()) as State
|
||||
if (data.transport) {setState(data)}
|
||||
if (!data.ok) {setNote({ kind: 'error', msg: data.error ?? iaplT(t as never, 'mailRelayLoadFailed') })}
|
||||
else if (announce && data.message) {setNote({ kind: 'ok', msg: data.message })}
|
||||
else {setNote(null)}
|
||||
} catch {
|
||||
setNote({ kind: 'error', msg: iaplT(t as never, 'mailRelayLoadFailed') })
|
||||
} finally {
|
||||
setBusy(false)
|
||||
}
|
||||
},
|
||||
[api, t],
|
||||
)
|
||||
|
||||
useEffect(() => {
|
||||
void call(RELAY_STATUS_PATH)
|
||||
}, [call])
|
||||
|
||||
const post = (path: string, body?: object) =>
|
||||
call(path, { body: body ? JSON.stringify(body) : undefined, headers: body ? { 'Content-Type': 'application/json' } : undefined, method: 'POST' }, true)
|
||||
|
||||
if (!state?.transport) {
|
||||
return note ? <div role="alert" style={{ ...box, borderColor: 'var(--theme-error-400, #e5484d)' }}>{note.msg}</div> : null
|
||||
}
|
||||
const relay = state.relay
|
||||
const onRelay = state.transport === 'relay'
|
||||
const relayState = !relay ? '' : relay.disconnected ? text('mailRelayStateDisconnected')
|
||||
: !relay.connected ? (state.refusalText ?? text('mailRelayStateNotConnected'))
|
||||
: relay.state === 'pending' ? text('mailRelayStatePending')
|
||||
: relay.state === 'suspended' ? text('mailRelayStateSuspended')
|
||||
: text('mailRelayStateActive')
|
||||
const attention = Boolean(relay && onRelay && (relay.disconnected || relay.state === 'pending' || relay.state === 'suspended' || (!relay.connected && state.refusalText)))
|
||||
|
||||
return (
|
||||
<div data-mail-transport={state.transport} style={box}>
|
||||
<strong>{text('mailRelayHeading')}</strong>
|
||||
<p style={line}>
|
||||
{state.transport === 'relay' ? text('mailRelayTransportRelay', { address: relay?.senderAddress ?? '' })
|
||||
: state.transport === 'smtp' ? text('mailRelayTransportSmtp')
|
||||
: state.transport === 'graph' ? text('mailRelayTransportGraph')
|
||||
: text(relay ? 'mailRelayTransportNone' : 'mailRelayOff')}
|
||||
</p>
|
||||
{onRelay && relay ? (
|
||||
<>
|
||||
<p role={attention ? 'alert' : undefined} style={attention ? warn : line}>{relayState}</p>
|
||||
<p style={state.replyAddress ? line : warn}>{state.replyAddress ? text('mailRelayRepliesTo', { address: state.replyAddress }) : text('mailRelayNoReplyAddress')}</p>
|
||||
{relay.nameReplaced ? <p style={warn}>{text('mailRelayNameReplaced', { asked: relay.nameReplaced.asked, used: relay.nameReplaced.used })}</p> : null}
|
||||
{relay.quota?.hour && relay.quota.day ? (
|
||||
<p style={{ ...line, fontSize: '0.85rem', opacity: 0.75 }}>{text('mailRelayQuota', { day: relay.quota.day.remaining, hour: relay.quota.hour.remaining })}</p>
|
||||
) : null}
|
||||
{relay.tokenSource === 'option' ? null : (
|
||||
<div style={{ alignItems: 'center', display: 'flex', flexWrap: 'wrap', gap: '.5rem', marginTop: '.75rem' }}>
|
||||
<button className="btn btn--style-secondary btn--size-small" disabled={busy} onClick={() => void call(`${RELAY_STATUS_PATH}?refresh=1`)} style={{ margin: 0 }} type="button">
|
||||
{busy ? text('mailRelayWorking') : text('mailRelayCheck')}
|
||||
</button>
|
||||
<button className="btn btn--style-secondary btn--size-small" disabled={busy} onClick={() => void post(RELAY_CONNECT_PATH)} style={{ margin: 0 }} type="button">
|
||||
{text('mailRelayConnect')}
|
||||
</button>
|
||||
{relay.connected ? (
|
||||
<button
|
||||
className="btn btn--style-secondary btn--size-small"
|
||||
disabled={busy}
|
||||
onClick={() => {
|
||||
if (window.confirm(text('mailRelayDisconnectConfirm'))) {void post(RELAY_DISCONNECT_PATH)}
|
||||
}}
|
||||
style={{ margin: 0 }}
|
||||
type="button"
|
||||
>
|
||||
{text('mailRelayDisconnect')}
|
||||
</button>
|
||||
) : null}
|
||||
<button className="btn btn--style-none btn--size-small" onClick={() => setShowToken((v) => !v)} style={{ margin: 0, textDecoration: 'underline' }} type="button">
|
||||
{text('mailRelayToken')}
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
{showToken ? (
|
||||
<div style={{ marginTop: '.75rem' }}>
|
||||
<p style={{ fontSize: '.85rem', margin: 0, opacity: 0.75 }}>{text('mailRelayTokenHint')}</p>
|
||||
<div style={{ display: 'flex', flexWrap: 'wrap', gap: '.5rem', marginTop: '.35rem' }}>
|
||||
<input aria-label={text('mailRelayToken')} autoComplete="off" onChange={(e) => setToken(e.target.value)} style={{ flex: 1, minWidth: '220px' }} type="password" value={token} />
|
||||
<button
|
||||
className="btn btn--style-secondary btn--size-small"
|
||||
disabled={busy || !token.trim()}
|
||||
onClick={() => {
|
||||
void post(RELAY_CONNECT_PATH, { token: token.trim() }).then(() => setToken(''))
|
||||
}}
|
||||
style={{ margin: 0 }}
|
||||
type="button"
|
||||
>
|
||||
{text('mailRelayTokenSave')}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
) : null}
|
||||
</>
|
||||
) : null}
|
||||
{note ? (
|
||||
<p role={note.kind === 'error' ? 'alert' : 'status'} style={{ ...line, color: note.kind === 'error' ? 'var(--theme-error-500, crimson)' : 'var(--theme-success-500, green)' }}>
|
||||
{note.msg}
|
||||
</p>
|
||||
) : null}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export default MailRelayStatus
|
||||
@@ -3,7 +3,9 @@ import type { Condition, Field } from 'payload'
|
||||
import { buildIntegrationStatusBanner, buildIntegrationStatusField } from '../../../modules/integrations/status.js'
|
||||
|
||||
/**
|
||||
* E-mail sending settings (SMTP, or Microsoft Graph set up on the server).
|
||||
* E-mail sending settings. No field is needed for mail to work: a site with no SMTP server here
|
||||
* sends through the Intecion Notifications Webservice (modules/email/relay). The SMTP fields are
|
||||
* for a client who wants its own mail server; Microsoft Graph (set up on the server) is deprecated.
|
||||
*
|
||||
* Protected at the global level (SiteIntegrations requires an authenticated
|
||||
* user), so all fields — including the password — stay editable in the admin
|
||||
@@ -13,7 +15,16 @@ import { buildIntegrationStatusBanner, buildIntegrationStatusField } from '../..
|
||||
// SMTP fields only matter with the SMTP transport — hidden while Graph is selected.
|
||||
const usesSmtp: Condition = (_, siblingData) => siblingData?.emailTransport !== 'graph'
|
||||
|
||||
export const smtpFields: Field[] = [
|
||||
/**
|
||||
* The fields of the "E-mail sending" tab. `relay: false` (the project switched the Intecion mail
|
||||
* service off): no state block, and the wording of 1.16 — SMTP is then the way to send.
|
||||
* No stored field differs between the two: labels, descriptions and one `ui` block only.
|
||||
*/
|
||||
export const buildSmtpFields = ({ relay = true }: { relay?: boolean } = {}): Field[] => [
|
||||
// Which transport is in effect, and the site's state with the Intecion mail service.
|
||||
...(relay
|
||||
? [{ name: 'mailRelayStatus', type: 'ui' as const, admin: { components: { Field: '@intecion/ipal-kit/admin#MailRelayStatus' } } }]
|
||||
: []),
|
||||
// Status written by mailAdapter on every send (throttled) — banner on this tab.
|
||||
buildIntegrationStatusBanner(
|
||||
'emailStatus',
|
||||
@@ -24,10 +35,15 @@ export const smtpFields: Field[] = [
|
||||
name: 'emailTransport',
|
||||
type: 'select',
|
||||
admin: {
|
||||
description: {
|
||||
en: 'Microsoft Graph works only when your administrator has set it up on the server.',
|
||||
pl: 'Microsoft Graph działa tylko wtedy, gdy administrator skonfiguruje go na serwerze.',
|
||||
},
|
||||
description: relay
|
||||
? {
|
||||
en: 'Automatic: e-mails go through your SMTP server when one is filled in below, otherwise through the Intecion mail service. Microsoft Graph works only when your administrator has set it up on the server; it will be removed in version 2.0.',
|
||||
pl: 'Automatycznie: e-maile idą przez Twój serwer SMTP, jeśli jest uzupełniony poniżej, a w przeciwnym razie przez usługę pocztową Intecion. Microsoft Graph działa tylko wtedy, gdy administrator skonfiguruje go na serwerze; zostanie usunięty w wersji 2.0.',
|
||||
}
|
||||
: {
|
||||
en: 'Microsoft Graph works only when your administrator has set it up on the server. It will be removed in version 2.0.',
|
||||
pl: 'Microsoft Graph działa tylko wtedy, gdy administrator skonfiguruje go na serwerze. Zostanie usunięty w wersji 2.0.',
|
||||
},
|
||||
// The Graph option only makes sense when agency credentials exist in env.
|
||||
// We can't read process.env in the admin UI directly, so a client project
|
||||
// that hasn't set up Graph should filter this option via integrationsFields
|
||||
@@ -37,8 +53,9 @@ export const smtpFields: Field[] = [
|
||||
defaultValue: 'smtp',
|
||||
label: { en: 'Sending method', pl: 'Sposób wysyłki' },
|
||||
options: [
|
||||
{ label: { en: 'SMTP server', pl: 'Serwer SMTP' }, value: 'smtp' },
|
||||
{ label: { en: 'Microsoft Graph (Exchange)', pl: 'Microsoft Graph (Exchange)' }, value: 'graph' },
|
||||
// Labels only: the two stored values stay (a new value would change the Postgres enum).
|
||||
{ label: relay ? { en: 'Automatic (Intecion mail service, or your SMTP server)', pl: 'Automatycznie (usługa pocztowa Intecion albo Twój serwer SMTP)' } : { en: 'SMTP server', pl: 'Serwer SMTP' }, value: 'smtp' },
|
||||
{ label: { en: 'Microsoft Graph (deprecated)', pl: 'Microsoft Graph (wycofywany)' }, value: 'graph' },
|
||||
],
|
||||
},
|
||||
{
|
||||
@@ -48,10 +65,15 @@ export const smtpFields: Field[] = [
|
||||
name: 'smtpFromAddress',
|
||||
type: 'email',
|
||||
admin: {
|
||||
description: {
|
||||
en: 'E-mails are sent from this address; with Microsoft Graph, replies go to it.',
|
||||
pl: 'Z tego adresu wychodzą e-maile; przy Microsoft Graph trafiają na niego odpowiedzi.',
|
||||
},
|
||||
description: relay
|
||||
? {
|
||||
en: 'With your SMTP server, e-mails are sent from this address. With the Intecion mail service (and Microsoft Graph), replies go to it.',
|
||||
pl: 'Przy Twoim serwerze SMTP z tego adresu wychodzą e-maile. Przy usłudze pocztowej Intecion (i Microsoft Graph) trafiają na niego odpowiedzi.',
|
||||
}
|
||||
: {
|
||||
en: 'E-mails are sent from this address; with Microsoft Graph, replies go to it.',
|
||||
pl: 'Z tego adresu wychodzą e-maile; przy Microsoft Graph trafiają na niego odpowiedzi.',
|
||||
},
|
||||
placeholder: '[email protected]',
|
||||
width: '50%',
|
||||
},
|
||||
@@ -61,10 +83,15 @@ export const smtpFields: Field[] = [
|
||||
name: 'smtpFromName',
|
||||
type: 'text',
|
||||
admin: {
|
||||
description: {
|
||||
en: 'The name recipients see, e.g. the company name.',
|
||||
pl: 'Nazwa widoczna dla odbiorcy, np. nazwa firmy.',
|
||||
},
|
||||
description: relay
|
||||
? {
|
||||
en: 'The name recipients see, e.g. the company name. Empty: the site name.',
|
||||
pl: 'Nazwa widoczna dla odbiorcy, np. nazwa firmy. Puste: nazwa witryny.',
|
||||
}
|
||||
: {
|
||||
en: 'The name recipients see, e.g. the company name.',
|
||||
pl: 'Nazwa widoczna dla odbiorcy, np. nazwa firmy.',
|
||||
},
|
||||
width: '50%',
|
||||
},
|
||||
label: { en: 'Sender name', pl: 'Nazwa nadawcy' },
|
||||
@@ -78,8 +105,19 @@ export const smtpFields: Field[] = [
|
||||
{
|
||||
name: 'smtpHost',
|
||||
type: 'text',
|
||||
admin: { placeholder: 'smtp.example.com', width: '70%' },
|
||||
label: { en: 'Server', pl: 'Serwer' },
|
||||
admin: {
|
||||
...(relay
|
||||
? {
|
||||
description: {
|
||||
en: 'Fill in only when the site should send through your own mail server. Leave empty to use the Intecion mail service.',
|
||||
pl: 'Uzupełnij tylko wtedy, gdy witryna ma wysyłać przez Twój własny serwer pocztowy. Zostaw puste, aby korzystać z usługi pocztowej Intecion.',
|
||||
},
|
||||
}
|
||||
: {}),
|
||||
placeholder: 'smtp.example.com',
|
||||
width: '70%',
|
||||
},
|
||||
label: relay ? { en: 'Own SMTP server (optional)', pl: 'Własny serwer SMTP (opcjonalnie)' } : { en: 'Server', pl: 'Serwer' },
|
||||
},
|
||||
{
|
||||
name: 'smtpPort',
|
||||
@@ -122,3 +160,6 @@ export const smtpFields: Field[] = [
|
||||
},
|
||||
buildIntegrationStatusField('emailStatus'),
|
||||
]
|
||||
|
||||
/** The fields with the Intecion mail service enabled (the default). */
|
||||
export const smtpFields: Field[] = buildSmtpFields()
|
||||
|
||||
@@ -4,12 +4,17 @@ import { userMeetsRole } from '../../modules/access/index.js'
|
||||
import { INTEGRATION_SECRET_FIELDS, maskSecretsOnRestore, SMTP_PASSWORD_BOUND_TO, writeOnlySecrets } from '../../modules/secrets/writeOnly.js'
|
||||
import { indexNowFields } from '../../modules/seo/indexNow.js'
|
||||
import { analyticsFields } from './fields/analytics.js'
|
||||
import { smtpFields } from './fields/smtp.js'
|
||||
import { buildSmtpFields } from './fields/smtp.js'
|
||||
import { turnstileFields } from './fields/turnstile.js'
|
||||
|
||||
type BuildSiteIntegrationsArgs = {
|
||||
/** Extra fields injected by the client project */
|
||||
additionalFields?: Field[]
|
||||
/**
|
||||
* The Intecion mail service is enabled in the project (`mail.relay` is not `false`): the e-mail
|
||||
* tab shows its state block and says that SMTP is optional. Default true.
|
||||
*/
|
||||
mailRelay?: boolean
|
||||
/**
|
||||
* A save through access control that changes the SMTP server, port or user name must send the
|
||||
* password again (or remove it), whatever the transport. Default true; needs write-only
|
||||
@@ -38,6 +43,7 @@ type BuildSiteIntegrationsArgs = {
|
||||
*/
|
||||
export function buildSiteIntegrations({
|
||||
additionalFields,
|
||||
mailRelay = true,
|
||||
reenterSecretOnChange = true,
|
||||
writeOnlySecrets: writeOnly = true,
|
||||
}: BuildSiteIntegrationsArgs = {}): GlobalConfig {
|
||||
@@ -68,7 +74,7 @@ export function buildSiteIntegrations({
|
||||
fields: secret(turnstileFields),
|
||||
label: { en: 'Spam protection', pl: 'Ochrona przed spamem' },
|
||||
},
|
||||
{ fields: secret(smtpFields), label: { en: 'E-mail sending', pl: 'Wysyłka e-mail' } },
|
||||
{ fields: secret(buildSmtpFields({ relay: mailRelay })), label: { en: 'E-mail sending', pl: 'Wysyłka e-mail' } },
|
||||
{ fields: indexNowFields, label: { en: 'IndexNow', pl: 'IndexNow' } },
|
||||
...(additionalFields?.length
|
||||
? [{ fields: additionalFields, label: { en: 'More', pl: 'Więcej' } }]
|
||||
|
||||
+63
-3
@@ -210,17 +210,77 @@ export type { SearchResult } from './modules/content/index.js'
|
||||
export { mailAttachmentLimit } from './modules/email/attachmentLimit.js'
|
||||
export { graphAdapter } from './modules/email/graphAdapter.js'
|
||||
export type { GraphAdapterArgs } from './modules/email/graphAdapter.js'
|
||||
export { mailAdapter } from './modules/email/mailAdapter.js'
|
||||
export type { MailAdapterArgs } from './modules/email/mailAdapter.js'
|
||||
export { GRAPH_DEPRECATION_NOTICE, mailAdapter, resolveMailTransport } from './modules/email/mailAdapter.js'
|
||||
export type { MailAdapterArgs, MailTransport } from './modules/email/mailAdapter.js'
|
||||
// Imported straight from the file, NOT from ./modules/email/index.js — that
|
||||
// barrel re-exports sendEmail, which imports 'server-only' and would crash when
|
||||
// Payload loads the config (or runs generate:importmap) as a plain Node script.
|
||||
export { panelSmtpAdapter } from './modules/email/panelSmtpAdapter.js'
|
||||
export type { PanelSmtpAdapterArgs } from './modules/email/panelSmtpAdapter.js'
|
||||
// The Intecion Notifications Webservice (docs/email.md): the transport of a site with no SMTP server.
|
||||
// Every piece is exported, so a project can use the transport alone, enrol from a script, mark its own
|
||||
// mail, build its own panel, or test against the fake service.
|
||||
export { createFakeRelay } from './modules/email/relay/fake.js'
|
||||
export type { FakeRelay, FakeRelayLimits, FakeRelayMail, FakeRelayOptions } from './modules/email/relay/fake.js'
|
||||
export {
|
||||
bareAddress,
|
||||
bareAddresses,
|
||||
buildRelayMessage,
|
||||
cleanSubject,
|
||||
disconnectRelay,
|
||||
enrolRelay,
|
||||
getRelayStatus,
|
||||
isPublicHost,
|
||||
MAIL_KIND,
|
||||
MAIL_KINDS,
|
||||
mailKindOf,
|
||||
markNextMail,
|
||||
RELAY_BASE_URL,
|
||||
RELAY_CONFIRM_PATH,
|
||||
RELAY_CONTRACT_VERSION,
|
||||
RELAY_DEFAULTS,
|
||||
RELAY_KV_KEY,
|
||||
RELAY_PRODUCT,
|
||||
RELAY_SENDER_ADDRESS,
|
||||
RELAY_SERVICE_NAME,
|
||||
RELAY_STATUS_CODES,
|
||||
relayAdapter,
|
||||
relayAttachmentLimit,
|
||||
relayConfirmEndpoint,
|
||||
relayHost,
|
||||
relayRequest,
|
||||
relaySenderName,
|
||||
relayStatusFor,
|
||||
resolveRelayOptions,
|
||||
rotateRelayToken,
|
||||
runWithMailKind,
|
||||
sendThroughRelay,
|
||||
setRelayToken,
|
||||
withMailKind,
|
||||
} from './modules/email/relay/index.js'
|
||||
export type {
|
||||
BuildRelayMessageArgs,
|
||||
BuiltRelayMessage,
|
||||
EnrolResult,
|
||||
MailKind,
|
||||
RelayAdapterArgs,
|
||||
RelayAnswer,
|
||||
RelayCall,
|
||||
RelayOptions,
|
||||
RelayRefusal,
|
||||
RelaySendContext,
|
||||
RelaySendRequest,
|
||||
RelaySendResult,
|
||||
RelayStatus,
|
||||
RelayStatusCode,
|
||||
} from './modules/email/relay/index.js'
|
||||
export { mailPanelState, relayPanelEndpoints } from './modules/email/relay/panel.js'
|
||||
export type { MailPanelState } from './modules/email/relay/panel.js'
|
||||
// Boot-time environment validation (fail fast on misconfigured deploys).
|
||||
export { assertEnv, checkDatabaseName, databaseNameFromUri, databaseNamesFor, iaplEnvRules, ipalEnvRules, legacyEnvName, readEnv } from './modules/env/index.js'
|
||||
export type { AssertEnvOptions, EnvKind, EnvRule, IaplEnvFeatures, IpalEnvFeatures } from './modules/env/index.js'
|
||||
export type { FormAttachmentsOption, FormFileScanInput, FormFileScanResult, FormSubmitEndpointOptions } from './modules/forms/attachments/config.js'
|
||||
export { buildFormMailKindHook } from './modules/forms/attachments/delivery.js'
|
||||
export { buildFileBlock, fileBlock } from './modules/forms/attachments/fileBlock.js'
|
||||
export { FORM_FILE_TYPES, formatFileSize, RISKY_FILE_EXTENSIONS } from './modules/forms/attachments/fileTypes.js'
|
||||
export type { FormFileDetect, FormFileType } from './modules/forms/attachments/fileTypes.js'
|
||||
@@ -468,4 +528,4 @@ export type { IaplTokenName, IpalTokenName, TokensInput } from './modules/tokens
|
||||
export { getTurnstileConfig, TURNSTILE_SECRET_ENV, turnstileSecretFromEnv } from './modules/turnstile/config.js'
|
||||
export type { TurnstileConfig } from './modules/turnstile/config.js'
|
||||
export { iapl, ipalKit } from './plugin.js'
|
||||
export type { IaplOptions, IpalOptions, ThemeOptions } from './types.js'
|
||||
export type { IaplOptions, IpalOptions, MailOptions, ThemeOptions } from './types.js'
|
||||
|
||||
@@ -9,6 +9,43 @@ export const integrationsTexts = defineTexts({
|
||||
alertsLink: 'Go to Site integrations',
|
||||
alertsUnknownError: 'Unknown error.',
|
||||
|
||||
// Intecion mail service: the state block on the e-mail tab (MailRelayStatus) and its routes
|
||||
mailRelayCheck: 'Check now',
|
||||
mailRelayConnect: 'Connect again',
|
||||
mailRelayConnected: 'The site is connected to the Intecion mail service.',
|
||||
mailRelayConnectFailed: 'The site could not be connected: {{reason}}',
|
||||
mailRelayDisconnect: 'Disconnect',
|
||||
mailRelayDisconnectConfirm: 'Disconnect this site from the Intecion mail service? E-mails will not be sent until you connect again or fill in an SMTP server.',
|
||||
mailRelayDisconnected: 'The site is disconnected from the Intecion mail service.',
|
||||
mailRelayForbidden: 'Only an administrator can do this.',
|
||||
mailRelayHeading: 'How e-mails are sent',
|
||||
mailRelayLoadFailed: 'The state could not be read. Try again.',
|
||||
mailRelayLoggedOut: 'Your session has ended. Log in again.',
|
||||
mailRelayNameReplaced: 'The mail service did not accept the sender name "{{asked}}", so e-mails leave as "{{used}}". Choose another name below.',
|
||||
mailRelayNoReplyAddress: 'No reply address is set. Fill in "Sender address" below, or replies to these e-mails will be lost.',
|
||||
mailRelayOff: 'The Intecion mail service is switched off for this project.',
|
||||
mailRelayQuota: 'Left this hour: {{hour}}. Left today: {{day}}.',
|
||||
mailRelayRefusedCallback: 'The mail service could not confirm this site at {{url}} ({{reason}}). The site must answer there from the internet, without a redirect. If the site serves its API at another address, ask Intecion to set this site\'s confirm address.',
|
||||
mailRelayRefusedClosed: 'The mail service does not take new sites at the moment. Contact Intecion.',
|
||||
mailRelayRefusedHost: 'This site has no public address the mail service could call back ({{host}}). It works once the site runs on its domain.',
|
||||
mailRelayRefusedNoHost: 'The site does not know its own address. An administrator must set serverURL in the Payload config.',
|
||||
mailRelayRefusedOther: 'The mail service answered: {{message}}',
|
||||
mailRelayRepliesTo: 'Replies go to {{address}}.',
|
||||
mailRelayStateActive: 'Connected to the Intecion mail service.',
|
||||
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: 'Waiting for approval by Intecion. E-mails are not sent yet.',
|
||||
mailRelayStateSuspended: 'Intecion has stopped e-mail sending for this site. Contact Intecion.',
|
||||
mailRelayToken: 'Token issued by Intecion',
|
||||
mailRelayTokenHint: 'Only for a site the mail service cannot call back. The token is stored and never shown again.',
|
||||
mailRelayTokenInvalid: 'This is not a token of the mail service.',
|
||||
mailRelayTokenSave: 'Save the token',
|
||||
mailRelayTransportGraph: 'E-mails go through Microsoft Graph. This method is deprecated and will be removed in version 2.0.',
|
||||
mailRelayTransportNone: 'No sending method is set up. E-mails are not sent.',
|
||||
mailRelayTransportRelay: 'E-mails go through the Intecion mail service, from {{address}}.',
|
||||
mailRelayTransportSmtp: 'E-mails go through your SMTP server.',
|
||||
mailRelayWorking: 'Working…',
|
||||
|
||||
// Masked secret field
|
||||
maskedHide: 'Hide',
|
||||
maskedKeep: 'Keep the stored value',
|
||||
@@ -37,6 +74,17 @@ export const integrationsTexts = defineTexts({
|
||||
'Microsoft Graph cannot send files of 3 MB and more here, so larger form files are limited or go over SMTP. Ask your administrator.',
|
||||
statusEmailGraphUnavailable:
|
||||
'Microsoft Graph is selected but not set up on the server, so e-mails go over SMTP. Ask your administrator.',
|
||||
statusEmailRelayAttachmentRefused: 'The Intecion mail service does not carry this type of file. The e-mail was not sent.',
|
||||
statusEmailRelayDisconnected: 'The site is disconnected from the Intecion mail service, so e-mails are not sent. Connect again, or fill in an SMTP server.',
|
||||
statusEmailRelayError: 'The Intecion mail service refused the e-mail. Tell your administrator.',
|
||||
statusEmailRelayNotConfirmed: 'The Intecion mail service did not confirm the last e-mail. It may have been sent.',
|
||||
statusEmailRelayPending: 'The site is waiting for approval by Intecion. E-mails are not sent yet.',
|
||||
statusEmailRelayQuota: 'The site reached a sending limit of the Intecion mail service. The e-mail was not sent.',
|
||||
statusEmailRelayRecipientSuppressed: 'The mail service refuses one of the recipients, because earlier e-mails to that address came back. Nothing was sent. Contact Intecion.',
|
||||
statusEmailRelayRefused: 'The Intecion mail service did not connect this site. See the state above, or fill in an SMTP server.',
|
||||
statusEmailRelaySuspended: 'Intecion has stopped e-mail sending for this site. Contact Intecion.',
|
||||
statusEmailRelayTooLarge: 'The e-mail or its files are larger than the Intecion mail service carries. The e-mail was not sent.',
|
||||
statusEmailRelayUnreachable: 'The Intecion mail service could not be reached or failed. The e-mail was probably not sent.',
|
||||
statusTurnstileBadResponse: 'Cloudflare sent an unexpected response.',
|
||||
statusTurnstileInternalError: 'Cloudflare reported an internal error. It usually passes on its own.',
|
||||
statusTurnstileInvalidSecret: 'Cloudflare rejected the secret key. Both keys must come from the same widget.',
|
||||
@@ -56,10 +104,13 @@ export const integrationsTexts = defineTexts({
|
||||
testEmailLoggedOut: 'Your session has ended. Log in again.',
|
||||
testEmailNoConnection: 'Could not reach the server. Check your connection and try again.',
|
||||
testEmailNotConfigured: 'Fill in the server, user name and password, then save.',
|
||||
testEmailNotConfirmed: 'The mail service did not confirm the test e-mail. It may have been sent; check the mailbox before trying again.',
|
||||
testEmailRecipient: 'Recipient address',
|
||||
testEmailSend: 'Send test e-mail',
|
||||
testEmailSending: 'Sending…',
|
||||
testEmailSent: 'Test e-mail sent to {{to}}.',
|
||||
testEmailSentRelay: 'Test e-mail sent to {{to}} through the Intecion mail service, as "{{name}}".',
|
||||
testEmailSentSmtp: 'Test e-mail sent to {{to}} through your SMTP server.',
|
||||
testEmailSubject: 'Test e-mail from {{site}}',
|
||||
testEmailSubjectGeneric: 'Test e-mail from your website',
|
||||
testEmailWithFile: 'Attach a 10 MB test file',
|
||||
@@ -70,6 +121,42 @@ export const integrationsTexts = defineTexts({
|
||||
alertsLink: 'Przejdź do integracji',
|
||||
alertsUnknownError: 'Nieznany błąd.',
|
||||
|
||||
mailRelayCheck: 'Sprawdź teraz',
|
||||
mailRelayConnect: 'Połącz ponownie',
|
||||
mailRelayConnected: 'Witryna jest połączona z usługą pocztową Intecion.',
|
||||
mailRelayConnectFailed: 'Nie udało się połączyć witryny: {{reason}}',
|
||||
mailRelayDisconnect: 'Rozłącz',
|
||||
mailRelayDisconnectConfirm: 'Rozłączyć witrynę z usługą pocztową Intecion? 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 usługą pocztową Intecion.',
|
||||
mailRelayForbidden: 'Tylko administrator może to zrobić.',
|
||||
mailRelayHeading: 'Jak wysyłane są e-maile',
|
||||
mailRelayLoadFailed: 'Nie udało się odczytać stanu. Spróbuj ponownie.',
|
||||
mailRelayLoggedOut: 'Sesja wygasła. Zaloguj się ponownie.',
|
||||
mailRelayNameReplaced: 'Usługa pocztowa nie przyjęła nazwy nadawcy „{{asked}}”, więc e-maile wychodzą jako „{{used}}”. Wybierz inną nazwę poniżej.',
|
||||
mailRelayNoReplyAddress: 'Nie ustawiono adresu do odpowiedzi. Uzupełnij „Adres nadawcy” poniżej, inaczej odpowiedzi na te e-maile przepadną.',
|
||||
mailRelayOff: 'Usługa pocztowa Intecion jest wyłączona w tym projekcie.',
|
||||
mailRelayQuota: 'Pozostało w tej godzinie: {{hour}}. Pozostało dziś: {{day}}.',
|
||||
mailRelayRefusedCallback: 'Usługa pocztowa nie mogła potwierdzić witryny pod adresem {{url}} ({{reason}}). Witryna musi odpowiadać tam z internetu, bez przekierowania. Jeśli witryna udostępnia API pod innym adresem, poproś Intecion o ustawienie adresu potwierdzenia dla tej witryny.',
|
||||
mailRelayRefusedClosed: 'Usługa pocztowa nie przyjmuje teraz nowych witryn. Skontaktuj się z Intecion.',
|
||||
mailRelayRefusedHost: 'Witryna nie ma publicznego adresu, pod który usługa pocztowa mogłaby się odezwać ({{host}}). Zadziała, gdy witryna będzie dostępna pod swoją domeną.',
|
||||
mailRelayRefusedNoHost: 'Witryna nie zna własnego adresu. Administrator musi ustawić serverURL w konfiguracji Payload.',
|
||||
mailRelayRefusedOther: 'Usługa pocztowa odpowiedziała: {{message}}',
|
||||
mailRelayRepliesTo: 'Odpowiedzi trafiają na adres {{address}}.',
|
||||
mailRelayStateActive: 'Połączono z usługą pocztową Intecion.',
|
||||
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 przez Intecion. E-maile nie są jeszcze wysyłane.',
|
||||
mailRelayStateSuspended: 'Intecion wstrzymał wysyłkę e-maili z tej witryny. Skontaktuj się z Intecion.',
|
||||
mailRelayToken: 'Token wydany przez Intecion',
|
||||
mailRelayTokenHint: 'Tylko dla witryny, do której usługa pocztowa nie może się odezwać. Token zostanie zapisany i nie będzie więcej pokazywany.',
|
||||
mailRelayTokenInvalid: 'To nie jest token usługi pocztowej.',
|
||||
mailRelayTokenSave: 'Zapisz token',
|
||||
mailRelayTransportGraph: 'E-maile idą przez Microsoft Graph. Ten sposób jest wycofywany i zostanie usunięty w wersji 2.0.',
|
||||
mailRelayTransportNone: 'Nie ustawiono żadnego sposobu wysyłki. E-maile nie są wysyłane.',
|
||||
mailRelayTransportRelay: 'E-maile idą przez usługę pocztową Intecion, z adresu {{address}}.',
|
||||
mailRelayTransportSmtp: 'E-maile idą przez Twój serwer SMTP.',
|
||||
mailRelayWorking: 'Trwa…',
|
||||
|
||||
maskedHide: 'Ukryj',
|
||||
maskedKeep: 'Zostaw zapisaną wartość',
|
||||
maskedRemove: 'Usuń zapisaną wartość',
|
||||
@@ -95,6 +182,17 @@ export const integrationsTexts = defineTexts({
|
||||
'Microsoft Graph nie może tu wysyłać plików od 3 MB, więc większe pliki z formularzy są ograniczone lub idą przez SMTP. Zapytaj administratora.',
|
||||
statusEmailGraphUnavailable:
|
||||
'Wybrano Microsoft Graph, ale nie jest on skonfigurowany na serwerze, więc e-maile idą przez SMTP. Zapytaj administratora.',
|
||||
statusEmailRelayAttachmentRefused: 'Usługa pocztowa Intecion nie przesyła plików tego typu. E-mail nie został wysłany.',
|
||||
statusEmailRelayDisconnected: 'Witryna jest rozłączona z usługą pocztową Intecion, więc e-maile nie są wysyłane. Połącz ją ponownie albo uzupełnij serwer SMTP.',
|
||||
statusEmailRelayError: 'Usługa pocztowa Intecion odrzuciła e-mail. Powiadom administratora.',
|
||||
statusEmailRelayNotConfirmed: 'Usługa pocztowa Intecion nie potwierdziła ostatniego e-maila. Mógł zostać wysłany.',
|
||||
statusEmailRelayPending: 'Witryna czeka na zatwierdzenie przez Intecion. E-maile nie są jeszcze wysyłane.',
|
||||
statusEmailRelayQuota: 'Witryna osiągnęła limit wysyłki w usłudze pocztowej Intecion. E-mail nie został wysłany.',
|
||||
statusEmailRelayRecipientSuppressed: 'Usługa pocztowa odrzuca jednego z odbiorców, bo wcześniejsze e-maile na ten adres wróciły. Nic nie zostało wysłane. Skontaktuj się z Intecion.',
|
||||
statusEmailRelayRefused: 'Usługa pocztowa Intecion nie połączyła tej witryny. Zobacz stan powyżej albo uzupełnij serwer SMTP.',
|
||||
statusEmailRelaySuspended: 'Intecion wstrzymał wysyłkę e-maili z tej witryny. Skontaktuj się z Intecion.',
|
||||
statusEmailRelayTooLarge: 'E-mail lub jego pliki są większe, niż przesyła usługa pocztowa Intecion. E-mail nie został wysłany.',
|
||||
statusEmailRelayUnreachable: 'Usługa pocztowa Intecion była nieosiągalna albo zawiodła. E-mail prawdopodobnie nie został wysłany.',
|
||||
statusTurnstileBadResponse: 'Cloudflare zwrócił nieoczekiwaną odpowiedź.',
|
||||
statusTurnstileInternalError: 'Cloudflare zgłosił błąd wewnętrzny. Zwykle ustępuje samoczynnie.',
|
||||
statusTurnstileInvalidSecret: 'Cloudflare odrzucił klucz tajny. Oba klucze muszą pochodzić z tego samego widżetu.',
|
||||
@@ -113,10 +211,13 @@ export const integrationsTexts = defineTexts({
|
||||
testEmailLoggedOut: 'Sesja wygasła. Zaloguj się ponownie.',
|
||||
testEmailNoConnection: 'Brak połączenia z serwerem. Sprawdź połączenie i spróbuj ponownie.',
|
||||
testEmailNotConfigured: 'Uzupełnij serwer, nazwę użytkownika i hasło, a następnie zapisz.',
|
||||
testEmailNotConfirmed: 'Usługa pocztowa nie potwierdziła testowego e-maila. Mógł zostać wysłany; sprawdź skrzynkę, zanim spróbujesz ponownie.',
|
||||
testEmailRecipient: 'Adres odbiorcy',
|
||||
testEmailSend: 'Wyślij testowy e-mail',
|
||||
testEmailSending: 'Wysyłanie…',
|
||||
testEmailSent: 'Testowy e-mail wysłano na adres {{to}}.',
|
||||
testEmailSentRelay: 'Testowy e-mail wysłano na adres {{to}} przez usługę pocztową Intecion, jako „{{name}}”.',
|
||||
testEmailSentSmtp: 'Testowy e-mail wysłano na adres {{to}} przez Twój serwer SMTP.',
|
||||
testEmailSubject: 'Testowy e-mail z witryny {{site}}',
|
||||
testEmailSubjectGeneric: 'Testowy e-mail z witryny',
|
||||
testEmailWithFile: 'Dołącz plik testowy 10 MB',
|
||||
|
||||
@@ -0,0 +1,141 @@
|
||||
import type { DoctorContext } from '../project.js'
|
||||
import type { DoctorRule, RuleFinding } from '../types.js'
|
||||
|
||||
import { configFile, nextConfigFile } from '../project.js'
|
||||
import { stripComments } from '../util.js'
|
||||
|
||||
const CONFIRM = '/iapl/mail-relay/confirm'
|
||||
const cfg = (ctx: DoctorContext) => stripComments(ctx.read(configFile(ctx) ?? ''))
|
||||
const next = (ctx: DoctorContext) => stripComments(ctx.read(nextConfigFile(ctx) ?? ''))
|
||||
const relayOff = (code: string) => /\brelay\s*:\s*false\b/.test(code)
|
||||
const since = (iso?: null | string) => (iso ? `, since ${iso.slice(0, 16).replace('T', ' ')}` : '')
|
||||
|
||||
/**
|
||||
* E-mail (docs/email.md): which transport is in effect and whether it works, the site's state with the
|
||||
* Intecion Notifications Webservice, the deprecated Graph transport, the reply address, and whether
|
||||
* the service can reach the site's confirm route. Ids carry no brand, like `agents-md`.
|
||||
*/
|
||||
export const mailRules: DoctorRule[] = [
|
||||
{
|
||||
// Which transport a send takes right now, and whether the last sends worked.
|
||||
id: 'mail-transport',
|
||||
check: (ctx) => {
|
||||
const mail = ctx.deep?.mail
|
||||
if (!mail) {return []}
|
||||
const out: RuleFinding[] = []
|
||||
if (mail.transport === 'none') {
|
||||
out.push({
|
||||
fix: 'remove `mail: { relay: false }` to send through the Intecion mail service, or fill in an SMTP server in Site integrations → E-mail sending',
|
||||
message: 'no e-mail transport is set up: the Intecion mail service is switched off and the panel has no SMTP server — e-mails are not sent',
|
||||
severity: 'error',
|
||||
})
|
||||
}
|
||||
if (mail.status?.state === 'degraded') {
|
||||
const now = ctx.today === new Date().toISOString().slice(0, 10) ? Date.now() : Date.parse(`${ctx.today}T12:00:00Z`)
|
||||
const hours = mail.status.since ? Math.floor((now - Date.parse(mail.status.since)) / 3_600_000) : null
|
||||
out.push({
|
||||
fix: 'Site integrations → E-mail sending: read the state block, then send a test e-mail (iapl-debug, "E-mail")',
|
||||
message: `e-mail sending is failing (${mail.status.code ?? 'unknown'}, transport: ${mail.transport})${since(mail.status.since)}`,
|
||||
severity: hours !== null && hours >= 24 ? 'error' : 'warning',
|
||||
})
|
||||
}
|
||||
return out
|
||||
},
|
||||
docs: 'docs/email.md',
|
||||
group: 'mail',
|
||||
source: 'deep',
|
||||
},
|
||||
{
|
||||
// The site's state with the Intecion mail service, when that is how it sends.
|
||||
id: 'mail-relay-state',
|
||||
check: (ctx) => {
|
||||
const mail = ctx.deep?.mail
|
||||
const relay = mail?.relay
|
||||
if (!mail || mail.transport !== 'relay' || !relay) {return []}
|
||||
const out: RuleFinding[] = []
|
||||
if (relay.disconnected) {
|
||||
out.push({ fix: 'Site integrations → E-mail sending → "Connect again", or fill in an SMTP server', message: 'the site was disconnected from the Intecion mail service in the panel: e-mails are not sent', severity: 'error' })
|
||||
} else if (relay.state === 'suspended') {
|
||||
out.push({ fix: 'contact Intecion; meanwhile an SMTP server in the panel sends the site\'s mail', message: 'Intecion has stopped e-mail sending for this site (suspended)', severity: 'error' })
|
||||
} else if (relay.state === 'pending') {
|
||||
out.push({ fix: 'Intecion approves the host on the service (`ims approve <host>`); the same token then works', message: 'the site is enrolled with the Intecion mail service but waits for approval: e-mails are not sent yet', severity: 'warning' })
|
||||
} else if (!relay.connected && relay.refusal) {
|
||||
const path = relay.refusal === 'callback-failed' ? ` (${relay.reason ?? 'unknown'}): the service could not confirm the site at its public address` : ''
|
||||
out.push({
|
||||
fix: relay.refusal === 'callback-failed' ? 'the site must answer POST /api/iapl/mail-relay/confirm from the internet without a redirect (email.md, "When the site cannot be confirmed"), then "Connect again"' : 'email.md, "When the site cannot be confirmed"; then Site integrations → E-mail sending → "Connect again"',
|
||||
message: `the Intecion mail service did not connect this site: ${relay.refusal}${path}`,
|
||||
severity: 'warning',
|
||||
})
|
||||
} else if (!relay.connected) {
|
||||
out.push({ fix: 'send a test e-mail from Site integrations → E-mail sending', message: 'the site has not enrolled with the Intecion mail service yet (it does so on its first e-mail)', severity: 'info' })
|
||||
}
|
||||
if (relay.nameReplaced) {
|
||||
out.push({ fix: 'Site integrations → E-mail sending → Sender name: a name that is the client\'s own (no address, no other company\'s name)', message: 'the mail service did not accept the sender name, so e-mails leave under the site\'s host', severity: 'warning' })
|
||||
}
|
||||
return out
|
||||
},
|
||||
docs: 'docs/email.md',
|
||||
group: 'mail',
|
||||
source: 'deep',
|
||||
},
|
||||
{
|
||||
// The sender address of the service has no mailbox: without a reply address, answers are lost.
|
||||
id: 'mail-reply-address',
|
||||
check: (ctx) => {
|
||||
const mail = ctx.deep?.mail
|
||||
return mail?.transport === 'relay' && !mail.replyAddress
|
||||
? [{ fix: 'Site integrations → E-mail sending → Sender address: the client\'s own address', message: 'no reply address is set: replies to the site\'s e-mails (other than forms that set their own) go to an address without a mailbox', severity: 'warning' }]
|
||||
: []
|
||||
},
|
||||
docs: 'docs/email.md',
|
||||
group: 'mail',
|
||||
source: 'deep',
|
||||
},
|
||||
{
|
||||
// Microsoft Graph as the transport: deprecated in 1.17.0, removed in 2.0.
|
||||
id: 'mail-graph-deprecated',
|
||||
check: (ctx) => {
|
||||
const mail = ctx.deep?.mail
|
||||
const inCode = /\bgraphAdapter\s*\(|\bemailGraph\s*:\s*true\b/.test(cfg(ctx))
|
||||
if (!mail?.graphEnv && mail?.transport !== 'graph' && !inCode) {return []}
|
||||
return [{
|
||||
fix: 'remove the four GRAPH_* variables (Coolify) and send a test e-mail — the site then uses the Intecion mail service — or fill in an SMTP server (email.md, "Moving off Microsoft Graph")',
|
||||
message: mail?.transport === 'graph' ? 'e-mails go through Microsoft Graph, which is deprecated and will be removed in 2.0' : 'Microsoft Graph is still set up for this site (GRAPH_* variables or graphAdapter); it is deprecated and will be removed in 2.0',
|
||||
severity: 'warning',
|
||||
}]
|
||||
},
|
||||
docs: 'docs/email.md',
|
||||
group: 'mail',
|
||||
source: 'static',
|
||||
},
|
||||
{
|
||||
// The service calls exactly https://<host>/api/iapl/mail-relay/confirm and follows no redirect.
|
||||
id: 'mail-relay-route',
|
||||
check: async (ctx) => {
|
||||
const code = cfg(ctx)
|
||||
if (relayOff(code)) {return []}
|
||||
const out: RuleFinding[] = []
|
||||
const ask = 'ask Intecion to set this site\'s confirm address (`ims callback-path <host> <path>`), or change the site to answer at /api/iapl/mail-relay/confirm'
|
||||
if (/\btrailingSlash\s*:\s*true\b/.test(next(ctx))) {
|
||||
out.push({ file: nextConfigFile(ctx) ?? 'next.config.ts', fix: `${ask} — with trailing slashes the path ends in /confirm/`, message: 'trailingSlash: true redirects the mail service\'s call-back, and the service follows no redirect: the site cannot enrol', severity: 'warning' })
|
||||
}
|
||||
const api = /\broutes\s*:\s*\{[^}]*\bapi\s*:\s*['"`]([^'"`]+)['"`]/.exec(code)?.[1]
|
||||
if (api && api !== '/api') {
|
||||
out.push({ file: configFile(ctx) ?? 'src/payload.config.ts', fix: ask, message: `the API is served at ${api}, not /api: the mail service calls /api${CONFIRM} unless Intecion set another address for this host`, severity: 'warning' })
|
||||
}
|
||||
if (ctx.live && ctx.deep?.mail?.transport === 'relay') {
|
||||
const res = await ctx.live.fetch(`${api ?? '/api'}${CONFIRM}`, { redirect: 'manual' })
|
||||
// A GET finds no route there (the route is POST): 404 or 405 means the address is reached as it is.
|
||||
if (res.status >= 300 && res.status < 400) {
|
||||
out.push({ fix: `enrol the host the site really answers on (mail.relay.host), or ${ask}`, message: `live ${api ?? '/api'}${CONFIRM} redirects (${res.status} → ${res.headers.get('location') ?? '?'}); the mail service follows no redirect`, severity: 'warning' })
|
||||
} else if (res.status === 401 || res.status === 403 || res.status === 0 || res.status >= 500) {
|
||||
out.push({ fix: 'the confirm route must be reachable from the internet: no basic auth, no firewall rule, no maintenance page in front of it', message: `live ${api ?? '/api'}${CONFIRM} → ${res.status || res.error}: the mail service cannot call the site back`, severity: 'warning' })
|
||||
}
|
||||
}
|
||||
return out
|
||||
},
|
||||
docs: 'docs/email.md',
|
||||
group: 'mail',
|
||||
source: 'static',
|
||||
},
|
||||
]
|
||||
@@ -12,6 +12,7 @@ import { envRules } from './rules/env.js'
|
||||
import { layoutRules } from './rules/layout.js'
|
||||
import { legacyRules } from './rules/legacy.js'
|
||||
import { createLiveFetcher, liveRules } from './rules/live.js'
|
||||
import { mailRules } from './rules/mail.js'
|
||||
import { securityRules } from './rules/security.js'
|
||||
import { seedRules } from './rules/seeds.js'
|
||||
import { toolingRules } from './rules/tooling.js'
|
||||
@@ -33,6 +34,7 @@ export const doctorRules: DoctorRule[] = [
|
||||
...layoutRules,
|
||||
...envRules,
|
||||
...securityRules,
|
||||
...mailRules,
|
||||
...agentRules,
|
||||
...legacyRules,
|
||||
...seedRules,
|
||||
|
||||
@@ -8,6 +8,8 @@ import { PLUGIN_VERSION } from '../../version.js'
|
||||
import { openSignUpCollections, staffCollectionsOnOwnRoles, staffCollectionsOpenToOthers } from '../access/selfRegistration.js'
|
||||
import { countPendingCookies } from '../consent/scanner/approval.js'
|
||||
import { COOKIE_REVIEW_SLUG } from '../consent/scanner/collection.js'
|
||||
import { graphAvailable } from '../email/mailAdapter.js'
|
||||
import { mailPanelState } from '../email/relay/panel.js'
|
||||
import { secondFactorPassed, SETUP_FROM_FIELD } from '../security/totp/secondFactor.js'
|
||||
import { countAccountsWithoutTotp } from '../security/totp/setupRequired.js'
|
||||
import { readEnv } from '../shared/envName.js'
|
||||
@@ -59,6 +61,33 @@ export async function collectDoctorStatus(payload: BasePayload): Promise<DoctorS
|
||||
/* the global cannot be read: unknown */
|
||||
}
|
||||
}
|
||||
// E-mail: the transport in effect and the state with the mail service — read from the store, nothing is asked.
|
||||
let mail: DoctorStatus['mail'] = null
|
||||
if ((payload.config.globals ?? []).some((g) => g.slug === 'site-integrations')) {
|
||||
try {
|
||||
const state = await mailPanelState({ payload }, undefined)
|
||||
const integrations = (await payload.findGlobal({ slug: 'site-integrations' as never, depth: 0, overrideAccess: true })) as unknown as {
|
||||
emailStatus?: { code?: null | string; since?: null | string; state?: null | string } | null
|
||||
}
|
||||
mail = {
|
||||
graphEnv: graphAvailable(),
|
||||
relay: state.relay
|
||||
? {
|
||||
connected: state.relay.connected,
|
||||
disconnected: state.relay.disconnected,
|
||||
nameReplaced: Boolean(state.relay.nameReplaced),
|
||||
...(state.relay.refusal ? { refusal: state.relay.refusal.code, ...(state.relay.refusal.reason ? { reason: state.relay.refusal.reason } : {}) } : {}),
|
||||
...(state.relay.state ? { state: state.relay.state } : {}),
|
||||
}
|
||||
: null,
|
||||
replyAddress: Boolean(state.replyAddress),
|
||||
status: integrations.emailStatus?.state ? { code: integrations.emailStatus.code ?? null, since: integrations.emailStatus.since ?? null, state: integrations.emailStatus.state } : null,
|
||||
transport: state.transport,
|
||||
}
|
||||
} catch {
|
||||
/* the global cannot be read: unknown */
|
||||
}
|
||||
}
|
||||
let openSignUp: null | string[] = null
|
||||
try {
|
||||
openSignUp = await openSignUpCollections(payload as never)
|
||||
@@ -77,7 +106,7 @@ export async function collectDoctorStatus(payload: BasePayload): Promise<DoctorS
|
||||
} catch {
|
||||
staffOnOwnRoles = null
|
||||
}
|
||||
return { node: process.version, openSignUp, pendingCookies, plugin: pluginVersion(), staffOnOwnRoles, staffOpenToOthers, turnstile, turnstileSecretFromEnv: secretFromEnv, usersSetupClosed, usersWithout2fa }
|
||||
return { mail, node: process.version, openSignUp, pendingCookies, plugin: pluginVersion(), staffOnOwnRoles, staffOpenToOthers, turnstile, turnstileSecretFromEnv: secretFromEnv, usersSetupClosed, usersWithout2fa }
|
||||
}
|
||||
|
||||
export type DoctorEndpointOptions = {
|
||||
|
||||
@@ -60,6 +60,29 @@ export type DoctorStatus = {
|
||||
error?: string
|
||||
/** null = not compared (the endpoint cannot read files). */
|
||||
importMapCurrent?: boolean | null
|
||||
/**
|
||||
* E-mail: the transport in effect, the recorded state of sending, and the site's state with the
|
||||
* Intecion mail service. States and codes only — never a token, a password or an address.
|
||||
*/
|
||||
mail?: {
|
||||
/** The four GRAPH_* variables are set (Microsoft Graph: deprecated). */
|
||||
graphEnv: boolean
|
||||
/** null = the mail service is switched off in the project. */
|
||||
relay: {
|
||||
connected: boolean
|
||||
disconnected: boolean
|
||||
nameReplaced: boolean
|
||||
/** With `callback-failed`: why (`unreachable`, `timeout`, `redirect`, `status`, `confirmation`). */
|
||||
reason?: string
|
||||
/** The code of a refused enrolment. */
|
||||
refusal?: string
|
||||
state?: string
|
||||
} | null
|
||||
/** "Sender address" is filled in (with the mail service: where replies go). */
|
||||
replyAddress: boolean
|
||||
status?: { code?: null | string; since?: null | string; state?: null | string } | null
|
||||
transport: 'graph' | 'none' | 'relay' | 'smtp'
|
||||
} | null
|
||||
node?: string
|
||||
/** Auth collections whose `create` rule lets an anonymous request through (slugs only). */
|
||||
openSignUp?: null | string[]
|
||||
|
||||
@@ -5,11 +5,15 @@ import { getSiteIntegrations } from '../payload/index.js'
|
||||
import { graphAdapter, type GraphAdapterArgs, graphLargeAttachmentSupport } from './graphAdapter.js'
|
||||
import { attachmentBytes, GRAPH_INLINE_MAX_BYTES, toGraphAttachments } from './graphAttachments.js'
|
||||
import { panelSmtpAdapter, type PanelSmtpAdapterArgs } from './panelSmtpAdapter.js'
|
||||
import { relayAttachmentLimit, sendRelayWithPanel } from './relay/adapter.js'
|
||||
import { pluginMailOptions, type RelayOptions, resolveRelayOptions } from './relay/options.js'
|
||||
|
||||
type TransportIntegrations = {
|
||||
emailStatus?: IntegrationStatus | null
|
||||
/** 'smtp' | 'graph' — chosen by the editor in SiteIntegrations. */
|
||||
emailTransport?: 'graph' | 'smtp' | null
|
||||
smtpFromAddress?: null | string
|
||||
smtpFromName?: null | string
|
||||
smtpHost?: null | string
|
||||
smtpPassword?: null | string
|
||||
smtpUser?: null | string
|
||||
@@ -17,9 +21,33 @@ type TransportIntegrations = {
|
||||
|
||||
const smtpConfigured = (s: TransportIntegrations) => Boolean(s.smtpHost && s.smtpUser && s.smtpPassword)
|
||||
|
||||
/** Which transport a send takes. `none`: nothing is set up and the relay is switched off. */
|
||||
export type MailTransport = 'graph' | 'none' | 'relay' | 'smtp'
|
||||
|
||||
/**
|
||||
* The transport in effect for the present settings, decided on every send (no stored value):
|
||||
* 1. "Sending method" is Microsoft Graph and the GRAPH_* variables are complete → Graph, as before
|
||||
* (deprecated; removed in 2.0);
|
||||
* 2. the panel has an SMTP server (server, user name, password) → SMTP — on the client's request;
|
||||
* 3. the GRAPH_* variables are complete → Graph (deprecated), until they are removed;
|
||||
* 4. otherwise → the Intecion Notifications Webservice, unless it is switched off (`mail: { relay: false }`);
|
||||
* 5. otherwise nothing is configured.
|
||||
* A site with SMTP filled in never contacts the service.
|
||||
*/
|
||||
export function resolveMailTransport(settings: TransportIntegrations, state: { graphEnv: boolean; relay: boolean }): MailTransport {
|
||||
if ((settings.emailTransport ?? 'smtp') === 'graph' && state.graphEnv) {return 'graph'}
|
||||
if (smtpConfigured(settings)) {return 'smtp'}
|
||||
if (state.graphEnv) {return 'graph'}
|
||||
return state.relay ? 'relay' : 'none'
|
||||
}
|
||||
|
||||
/** Graph result codes that mean "Graph cannot carry an attachment this large" — SMTP may. */
|
||||
const GRAPH_TOO_LARGE = new Set(['graph-large-off', 'graph-permission'])
|
||||
|
||||
/** The one warning a site on Microsoft Graph gets per process (silence: `mail: { graphDeprecationWarning: false }`). */
|
||||
export const GRAPH_DEPRECATION_NOTICE =
|
||||
'[iapl] Microsoft Graph as the e-mail transport is deprecated and will be removed in 2.0. Remove the GRAPH_* variables to send through the Intecion Notifications Webservice, or fill in an SMTP server in Site integrations (docs/email.md, "Moving off Microsoft Graph").'
|
||||
|
||||
const STATUS_FIELD = 'emailStatus'
|
||||
/** Error text for the panel: first line, no stack, capped — SMTP errors don't carry the password. */
|
||||
const describe = (err: unknown) =>
|
||||
@@ -28,12 +56,27 @@ const describe = (err: unknown) =>
|
||||
export type MailAdapterArgs = {
|
||||
fallbackFromAddress?: string
|
||||
fallbackFromName?: string
|
||||
/** @deprecated Microsoft Graph is deprecated since 1.17.0 and removed in 2.0 (docs/email.md, "Moving off Microsoft Graph"). */
|
||||
graph?: GraphAdapterArgs
|
||||
/**
|
||||
* The Intecion Notifications Webservice — the transport of a site with no SMTP server in the panel.
|
||||
* `false` switches it off for this adapter; an object overrides `iapl({ mail: { relay } })`.
|
||||
*/
|
||||
relay?: false | RelayOptions
|
||||
smtp?: PanelSmtpAdapterArgs
|
||||
}
|
||||
|
||||
let warnedGraphDeprecated = false
|
||||
/** iapl() left its options in the config: it has already warned at start (plugin.ts, onInit). */
|
||||
const pluginWarnsAtStart = (payload: { config?: { custom?: unknown } }) => Boolean((payload.config?.custom as { iapl?: { mail?: unknown } } | undefined)?.iapl?.mail)
|
||||
|
||||
/** For tests. */
|
||||
export function resetGraphDeprecationWarning(): void {
|
||||
warnedGraphDeprecated = false
|
||||
}
|
||||
|
||||
/** True when the agency Graph credentials are present in the environment. */
|
||||
function graphAvailable(): boolean {
|
||||
export function graphAvailable(): boolean {
|
||||
return Boolean(
|
||||
process.env.GRAPH_TENANT_ID &&
|
||||
process.env.GRAPH_CLIENT_ID &&
|
||||
@@ -44,7 +87,9 @@ function graphAvailable(): boolean {
|
||||
|
||||
/**
|
||||
* Dispatcher email adapter: wired into the config ONCE, but picks the transport
|
||||
* (SMTP or Graph) per send by reading `emailTransport` from SiteIntegrations.
|
||||
* per send from Site integrations (resolveMailTransport): the panel's SMTP server
|
||||
* when one is filled in, Microsoft Graph while its variables last (deprecated),
|
||||
* otherwise the Intecion Notifications Webservice (relay/).
|
||||
* This is what makes the choice switchable in the panel — Payload builds the
|
||||
* email adapter at boot and can't swap it at runtime, so instead of choosing
|
||||
* between two adapters at boot we install one that delegates on every send.
|
||||
@@ -84,9 +129,15 @@ export const mailAdapter =
|
||||
* promises more than can be sent: on Graph without the large-file path and
|
||||
* without SMTP settings the ceiling is GRAPH_INLINE_MAX_BYTES.
|
||||
*/
|
||||
const relayOptions = () => resolveRelayOptions(payload, args.relay)
|
||||
const transportOf = (settings: TransportIntegrations) => resolveMailTransport(settings, { graphEnv: graphAvailable(), relay: Boolean(relayOptions()) })
|
||||
|
||||
const attachmentLimit = async (): Promise<null | number> => {
|
||||
const settings = await getSiteIntegrations<TransportIntegrations>(payload)
|
||||
if ((settings.emailTransport ?? 'smtp') !== 'graph' || !graphAvailable()) {return null}
|
||||
const transport = transportOf(settings)
|
||||
// The service says what it carries for this site (10 MB unless Intecion set another number).
|
||||
if (transport === 'relay') {return relayAttachmentLimit(payload, relayOptions()!).catch(() => null)}
|
||||
if (transport !== 'graph') {return null}
|
||||
const support = await graphLargeAttachmentSupport(args.graph)
|
||||
if (support === 'ok' || support === 'unavailable' || smtpConfigured(settings)) {return null}
|
||||
return GRAPH_INLINE_MAX_BYTES - 1
|
||||
@@ -102,7 +153,13 @@ export const mailAdapter =
|
||||
const settings = await getSiteIntegrations<TransportIntegrations>(payload)
|
||||
const choice = settings.emailTransport ?? 'smtp'
|
||||
const previous = settings[STATUS_FIELD]
|
||||
const useGraph = choice === 'graph' && graphAvailable()
|
||||
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)}
|
||||
|
||||
const useGraph = chosen === 'graph'
|
||||
// "Graph" in the panel without its variables is reported only while SMTP carries the mail instead.
|
||||
const graphFallback = choice === 'graph' && !useGraph
|
||||
|
||||
if (graphFallback) {
|
||||
@@ -112,6 +169,11 @@ export const mailAdapter =
|
||||
'[iapl] Transport set to Graph but GRAPH_* env vars are missing; falling back to SMTP.',
|
||||
)
|
||||
}
|
||||
// A project that uses mailAdapter() without iapl()'s start warning still hears it once.
|
||||
if (useGraph && !warnedGraphDeprecated && !pluginWarnsAtStart(payload) && pluginMailOptions(payload).graphDeprecationWarning !== false) {
|
||||
warnedGraphDeprecated = true
|
||||
payload.logger.warn(GRAPH_DEPRECATION_NOTICE)
|
||||
}
|
||||
|
||||
// A large attachment Graph cannot carry (switched off, or the app lacks
|
||||
// Mail.ReadWrite) goes over SMTP when the panel has SMTP settings.
|
||||
@@ -168,7 +230,8 @@ export const mailAdapter =
|
||||
}
|
||||
: { state: 'ok' },
|
||||
)
|
||||
return result
|
||||
// which transport carried it — the test e-mail says so in the panel
|
||||
return result && typeof result === 'object' ? { ...result, transport: viaGraph ? 'graph' : 'smtp' } : result
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,31 @@
|
||||
import type { CollectionConfig } from 'payload'
|
||||
|
||||
import { clientIp } from '../../shared/rateLimit.js'
|
||||
import { markNextMail } from './kinds.js'
|
||||
|
||||
const MARK = Symbol.for('iapl.accountMailMark')
|
||||
|
||||
/**
|
||||
* Payload composes and sends "forgot password" and "verify your e-mail" by itself, through
|
||||
* `payload.sendEmail`, with nothing on the message that says what it is. This hook on an auth
|
||||
* collection says it for the NEXT message of the request (kinds.ts): kind `account`, with the
|
||||
* visitor's address so the relay transport can limit what one visitor makes the site send
|
||||
* (`mail.relay.accountMail`). Other transports ignore the mark; nothing else changes.
|
||||
*
|
||||
* Marks `forgotPassword` always, and `create` only where the collection verifies e-mail addresses.
|
||||
*/
|
||||
export function withAccountMailMark(collection: CollectionConfig): CollectionConfig {
|
||||
const hooks = collection.hooks?.beforeOperation ?? []
|
||||
if (hooks.some((h) => (h as { [MARK]?: boolean })[MARK])) {return collection}
|
||||
const verifies = typeof collection.auth === 'object' && Boolean(collection.auth.verify)
|
||||
// NOT async: the mark has to be set in the operation's own synchronous run (markNextMail).
|
||||
const mark = ((args: { args?: { req?: { headers?: Headers } }; operation: string; req?: { headers?: Headers } }) => {
|
||||
if (args.operation === 'forgotPassword' || (verifies && args.operation === 'create')) {
|
||||
const headers = args.req?.headers ?? args.args?.req?.headers
|
||||
markNextMail('account', { visitor: headers ? clientIp(headers) || undefined : undefined })
|
||||
}
|
||||
return args.args
|
||||
}) as unknown as { [MARK]?: boolean } & NonNullable<NonNullable<CollectionConfig['hooks']>['beforeOperation']>[number]
|
||||
mark[MARK] = true
|
||||
return { ...collection, hooks: { ...collection.hooks, beforeOperation: [...hooks, mark] } }
|
||||
}
|
||||
@@ -0,0 +1,99 @@
|
||||
import type { BasePayload, PayloadEmailAdapter, SendEmailOptions } from 'payload'
|
||||
|
||||
import type { RelayOptions, ResolvedRelayOptions } from './options.js'
|
||||
|
||||
import { type IntegrationStatus, recordIntegrationStatus } from '../../integrations/status.js'
|
||||
import { getSiteIntegrations } from '../../payload/index.js'
|
||||
import { RELAY_DEFAULTS, RELAY_SERVICE_NAME } from './constants.js'
|
||||
import { resolveRelayOptions } from './options.js'
|
||||
import { type RelaySendResult, sendThroughRelay } from './send.js'
|
||||
import { refreshRelayStatus } from './session.js'
|
||||
import { readRelayStore } from './store.js'
|
||||
|
||||
/** The address mail leaves from until the service has been asked (`/v1/status` reports the real one). */
|
||||
export const RELAY_SENDER_ADDRESS = '[email protected]'
|
||||
|
||||
type PanelSender = { emailStatus?: IntegrationStatus | null; smtpFromAddress?: null | string; smtpFromName?: null | string }
|
||||
|
||||
const firstLine = (text: string) => text.split('\n')[0].slice(0, 200)
|
||||
|
||||
/** The site name from Site settings (default locale), or '' — the sender name when the panel field is empty. */
|
||||
async function siteName(payload: BasePayload): Promise<string> {
|
||||
try {
|
||||
if (!(payload.config.globals ?? []).some((g) => g.slug === 'site-settings')) {return ''}
|
||||
const doc = (await payload.findGlobal({ slug: 'site-settings' as never, depth: 0, overrideAccess: true })) as { siteName?: unknown }
|
||||
return typeof doc?.siteName === 'string' ? doc.siteName.trim() : ''
|
||||
} catch {
|
||||
return ''
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The display name of the site's mail: `relay.senderName`, else the panel's "Sender name", else the
|
||||
* site name from Site settings. Empty = the service uses the site's host.
|
||||
*/
|
||||
export async function relaySenderName(payload: BasePayload, options: Pick<RelayOptions, 'senderName'>, panelName?: null | string): Promise<string> {
|
||||
const own = typeof options.senderName === 'function' ? await options.senderName({ payload }) : options.senderName
|
||||
if (typeof own === 'string' && own.trim()) {return own.trim()}
|
||||
if (typeof panelName === 'string' && panelName.trim()) {return panelName.trim()}
|
||||
return siteName(payload)
|
||||
}
|
||||
|
||||
/** One send through the service with the panel's sender name and reply address, and `emailStatus` kept. */
|
||||
export async function sendRelayWithPanel(payload: BasePayload, options: ResolvedRelayOptions, message: SendEmailOptions, settings: PanelSender): Promise<RelaySendResult> {
|
||||
const result = await sendThroughRelay(payload, options, message, {
|
||||
replyTo: settings.smtpFromAddress,
|
||||
senderName: await relaySenderName(payload, options, settings.smtpFromName),
|
||||
})
|
||||
await recordIntegrationStatus(
|
||||
payload,
|
||||
'emailStatus',
|
||||
settings.emailStatus,
|
||||
result.sent ? { state: 'ok' } : { code: result.code, message: `${RELAY_SERVICE_NAME}: ${firstLine(result.detail)}`, state: 'degraded' },
|
||||
)
|
||||
return result
|
||||
}
|
||||
|
||||
/**
|
||||
* The largest total attachment size the service carries for this site, as it last reported
|
||||
* (`limits.maxAttachmentBytes` of `/v1/status`) — read again when older than an hour. `null` until
|
||||
* the site has enrolled: the plugin has no constant of its own for it.
|
||||
*/
|
||||
export async function relayAttachmentLimit(payload: BasePayload, options: ResolvedRelayOptions): Promise<null | number> {
|
||||
let stored = await readRelayStore(payload)
|
||||
const stale = !stored.service || Date.now() - Date.parse(stored.service.fetchedAt) > RELAY_DEFAULTS.statusTtlMs
|
||||
if (stale && (stored.token || options.token !== undefined) && !stored.disconnected) {
|
||||
stored = (await refreshRelayStatus(payload, options)).stored
|
||||
}
|
||||
const limit = stored.service?.limits?.maxAttachmentBytes
|
||||
return typeof limit === 'number' && limit >= 0 ? limit : null
|
||||
}
|
||||
|
||||
export type RelayAdapterArgs = {
|
||||
/** Payload wants a from-address at start; the service fixes the real one. */
|
||||
fallbackFromAddress?: string
|
||||
fallbackFromName?: string
|
||||
} & RelayOptions
|
||||
|
||||
/**
|
||||
* The Intecion Notifications Webservice as a Payload e-mail adapter of its own — for a project that
|
||||
* wants this transport and nothing else:
|
||||
* email: relayAdapter()
|
||||
* `mailAdapter()` already uses it when the panel has no SMTP server; most projects need only that.
|
||||
* Reads the sender name and the reply address from Site integrations when that global exists.
|
||||
*/
|
||||
export const relayAdapter =
|
||||
(args: RelayAdapterArgs = {}): PayloadEmailAdapter =>
|
||||
({ payload }) => {
|
||||
const { fallbackFromAddress, fallbackFromName, ...own } = args
|
||||
const options = () => resolveRelayOptions(payload, own) as ResolvedRelayOptions
|
||||
const panel = async (): Promise<PanelSender> =>
|
||||
(payload.config.globals ?? []).some((g) => g.slug === 'site-integrations') ? getSiteIntegrations<PanelSender>(payload) : {}
|
||||
return {
|
||||
name: 'iapl-relay',
|
||||
attachmentLimit: () => relayAttachmentLimit(payload, options()),
|
||||
defaultFromAddress: fallbackFromAddress ?? RELAY_SENDER_ADDRESS,
|
||||
defaultFromName: fallbackFromName ?? 'Website',
|
||||
sendEmail: async (message: SendEmailOptions) => sendRelayWithPanel(payload, options(), message, await panel()),
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,101 @@
|
||||
import { PLUGIN_VERSION } from '../../../version.js'
|
||||
import { RELAY_DEFAULTS, RELAY_PRODUCT } from './constants.js'
|
||||
|
||||
/** A refusal of the service (contracts/mail-relay/schema.json, `Error`), or what stands in for one. */
|
||||
export type RelayRefusal = {
|
||||
code: string
|
||||
field?: string
|
||||
limit?: string
|
||||
message: string
|
||||
/** No usable answer came at all (time-out, connection lost): the request may have been carried out. */
|
||||
noAnswer: boolean
|
||||
ok: false
|
||||
reason?: string
|
||||
retryable: boolean
|
||||
/** Seconds. */
|
||||
retryAfter?: number
|
||||
status: number
|
||||
}
|
||||
|
||||
export type RelayAnswer<T = Record<string, unknown>> = { body: T; ok: true; status: number } | RelayRefusal
|
||||
|
||||
export type RelayCall = {
|
||||
/** The request body, already encoded. A send keeps these bytes for every retry. */
|
||||
body?: Uint8Array
|
||||
fetchImpl?: typeof fetch
|
||||
idempotencyKey?: string
|
||||
method: 'GET' | 'POST'
|
||||
/** Relative to the base address: `/v1/send`. */
|
||||
path: string
|
||||
timeoutMs?: number
|
||||
token?: string
|
||||
/** Base address, host and path prefix together; joined with `path` as text. */
|
||||
url: string
|
||||
}
|
||||
|
||||
const firstLine = (text: string) => text.split('\n')[0].slice(0, 300)
|
||||
|
||||
/**
|
||||
* One request to the service. Never throws. An answer that is not the contract's JSON — an error page
|
||||
* of the network in front, an empty or cut-off body, a redirect — is `503 unavailable`, retryable; a
|
||||
* request that got no answer at all is the same with `noAnswer: true`.
|
||||
*/
|
||||
export async function relayRequest<T = Record<string, unknown>>(call: RelayCall): Promise<RelayAnswer<T>> {
|
||||
const controller = new AbortController()
|
||||
const timer = setTimeout(() => controller.abort(), call.timeoutMs ?? RELAY_DEFAULTS.timeoutMs)
|
||||
let status = 0
|
||||
try {
|
||||
const response = await (call.fetchImpl ?? fetch)(`${call.url.replace(/\/+$/, '')}${call.path}`, {
|
||||
body: call.body as BodyInit | undefined,
|
||||
headers: {
|
||||
accept: 'application/json',
|
||||
'user-agent': `${RELAY_PRODUCT}/${PLUGIN_VERSION}`,
|
||||
...(call.body ? { 'content-type': 'application/json' } : {}),
|
||||
...(call.token ? { authorization: `Bearer ${call.token}` } : {}),
|
||||
...(call.idempotencyKey ? { 'idempotency-key': call.idempotencyKey } : {}),
|
||||
},
|
||||
method: call.method,
|
||||
// the token goes to the configured address and nowhere else
|
||||
redirect: 'manual',
|
||||
signal: controller.signal,
|
||||
})
|
||||
status = response.status
|
||||
const text = await response.text()
|
||||
let parsed: unknown
|
||||
try {
|
||||
parsed = JSON.parse(text)
|
||||
} catch {
|
||||
parsed = null
|
||||
}
|
||||
const body = parsed && typeof parsed === 'object' && !Array.isArray(parsed) ? (parsed as Record<string, unknown>) : null
|
||||
if (body?.ok === true && status === 200) {return { body: body as T, ok: true, status }}
|
||||
if (body?.ok === false && typeof body.code === 'string' && body.code) {
|
||||
return {
|
||||
code: body.code,
|
||||
message: typeof body.message === 'string' ? firstLine(body.message) : body.code,
|
||||
noAnswer: false,
|
||||
ok: false,
|
||||
retryable: body.retryable === true,
|
||||
status,
|
||||
...(typeof body.retryAfter === 'number' && body.retryAfter >= 0 ? { retryAfter: body.retryAfter } : {}),
|
||||
...(typeof body.field === 'string' ? { field: body.field } : {}),
|
||||
...(typeof body.limit === 'string' ? { limit: body.limit } : {}),
|
||||
...(typeof body.reason === 'string' ? { reason: body.reason } : {}),
|
||||
}
|
||||
}
|
||||
return { code: 'unavailable', message: `The mail service answered ${status} without a usable body.`, noAnswer: false, ok: false, retryable: true, status }
|
||||
} catch (err) {
|
||||
const aborted = controller.signal.aborted
|
||||
return {
|
||||
code: 'unavailable',
|
||||
message: aborted ? 'The mail service did not answer in time.' : `The mail service could not be reached: ${firstLine(err instanceof Error ? err.message : String(err))}`,
|
||||
// an attempt that timed out is "no answer"; a body that broke off by itself is an answer that is not JSON
|
||||
noAnswer: aborted || status === 0,
|
||||
ok: false,
|
||||
retryable: true,
|
||||
status,
|
||||
}
|
||||
} finally {
|
||||
clearTimeout(timer)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
import type { Endpoint, PayloadRequest } from 'payload'
|
||||
|
||||
import type { RelayOptions } from './options.js'
|
||||
|
||||
import { clientIp, consumeRateLimit, tooManyRequests } from '../../shared/rateLimit.js'
|
||||
import { RELAY_CONFIRM_PATH, RELAY_DEFAULTS } from './constants.js'
|
||||
import { sha256Hex, takeNonce, writeRelayCandidate } from './store.js'
|
||||
|
||||
const NONCE = /^[\w-]{32,128}$/
|
||||
const TOKEN = /^ims_[\w-]{43}$/
|
||||
const STATES = new Set(['active', 'pending', 'suspended'])
|
||||
const MAX_BODY = 2048
|
||||
|
||||
const notFound = () => new Response(null, { headers: { 'cache-control': 'no-store' }, status: 404 })
|
||||
|
||||
async function readBody(req: PayloadRequest): Promise<unknown> {
|
||||
const length = Number(req.headers.get('content-length') ?? 0)
|
||||
if (length > MAX_BODY) {return null}
|
||||
try {
|
||||
const read = (req as { text?: () => Promise<string> }).text
|
||||
if (typeof read !== 'function') {return (await req.json?.()) as unknown}
|
||||
const text = await read.call(req)
|
||||
return text.length <= MAX_BODY ? (JSON.parse(text) as unknown) : null
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* `POST /api/iapl/mail-relay/confirm` — where the Intecion Notifications Webservice calls a site back
|
||||
* during an enrolment the SITE started. Public, and useless to anybody else:
|
||||
*
|
||||
* - it answers `404` and changes nothing unless the body carries a nonce this site made in the last
|
||||
* five minutes (kept as a hash, compared in constant time, single use);
|
||||
* - then it stores the delivered token BESIDE the one in use (store.ts) — a working token is never
|
||||
* 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.
|
||||
* 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).
|
||||
*/
|
||||
export function relayConfirmEndpoint(options: Pick<RelayOptions, 'confirmRateLimit'> = {}): Endpoint {
|
||||
const max = options.confirmRateLimit?.max ?? RELAY_DEFAULTS.confirmRateLimit.max
|
||||
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.' })}
|
||||
|
||||
const body = (await readBody(req)) as { nonce?: unknown; state?: unknown; token?: unknown } | null
|
||||
if (!body || typeof body !== 'object') {return notFound()}
|
||||
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()
|
||||
}
|
||||
try {
|
||||
if (!(await takeNonce(req.payload, nonce))) {return notFound()}
|
||||
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)}`)
|
||||
return notFound()
|
||||
}
|
||||
// Exactly this object and nothing else: the service reads at most 1024 bytes and checks the hash.
|
||||
return new Response(JSON.stringify({ confirmation: sha256Hex(`${nonce}.${token}`) }), {
|
||||
headers: { 'cache-control': 'no-store', 'content-type': 'application/json' },
|
||||
status: 200,
|
||||
})
|
||||
},
|
||||
method: 'post',
|
||||
path: RELAY_CONFIRM_PATH,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,92 @@
|
||||
/**
|
||||
* The Intecion Notifications Webservice, as the plugin knows it. No secret is here and none is in the
|
||||
* package: a site gets its own token by enrolling (enrol.ts). The wire contract these values come from
|
||||
* is copied in `contracts/mail-relay/` (test/mailRelayContract.test.ts fails on a hand-edited copy).
|
||||
*/
|
||||
|
||||
/** Base address: host and path together, joined with a path as text. Override: `mail: { relay: { url } }`. */
|
||||
export const RELAY_BASE_URL = 'https://webservices.intecion.net/mail'
|
||||
/** The version of the copied contract this client speaks (`contracts/mail-relay/VERSION`). */
|
||||
export const RELAY_CONTRACT_VERSION = '1.5.0'
|
||||
/** The `product` value of this plugin. */
|
||||
export const RELAY_PRODUCT = 'iapl'
|
||||
/** The service's name, for texts. */
|
||||
export const RELAY_SERVICE_NAME = 'Intecion Notifications Webservice'
|
||||
/** Where the service calls a site of this product back, under Payload's API route. Fixed by the contract. */
|
||||
export const RELAY_CONFIRM_PATH = '/iapl/mail-relay/confirm'
|
||||
/** Admin-only routes of the panel's status block. */
|
||||
export const RELAY_STATUS_PATH = '/iapl/mail-relay/status'
|
||||
export const RELAY_CONNECT_PATH = '/iapl/mail-relay/connect'
|
||||
export const RELAY_DISCONNECT_PATH = '/iapl/mail-relay/disconnect'
|
||||
/** Key of the site's token and state in `payload.kv`; the candidate token and the nonces hang off it. */
|
||||
export const RELAY_KV_KEY = 'iapl:mail-relay'
|
||||
|
||||
export const RELAY_DEFAULTS = {
|
||||
/** A visitor's lever: "forgot password" mail per address and per visitor in the window (accountMail option). */
|
||||
accountMail: { perAddress: 5, perVisitor: 10, windowMinutes: 60 },
|
||||
/** Requests for one message, the same key and bytes each time. */
|
||||
attempts: 3,
|
||||
/** One attempt, from sending the request to the end of the answer. */
|
||||
attemptTimeoutMs: 30_000,
|
||||
/** Calls to the confirm route per address a minute. */
|
||||
confirmRateLimit: { max: 10, windowMs: 60_000 },
|
||||
/** The enrolment call: the service's call-back has 8 seconds of it. */
|
||||
enrolTimeoutMs: 15_000,
|
||||
/** How long a site keeps the nonce of an enrolment it started. */
|
||||
nonceTtlMs: 5 * 60_000,
|
||||
/** After a refused enrolment the site does not ask again by itself for this long ("Connect again" does). */
|
||||
refusalCooldownMs: 15 * 60_000,
|
||||
/** How long the limits read from `/v1/status` are used before they are read again. */
|
||||
statusTtlMs: 60 * 60_000,
|
||||
/** Other calls (status, rotate, revoke). */
|
||||
timeoutMs: 10_000,
|
||||
/** Waiting between the attempts for one message, in all. Wins over `retryAfter`. */
|
||||
waitBudgetMs: 10_000,
|
||||
} as const
|
||||
|
||||
/**
|
||||
* What a send through the service can leave in `emailStatus.code` (Site integrations), each with a
|
||||
* text in the editor's language. `relay-name-replaced` is a warning shown in the status block: the
|
||||
* mail went out.
|
||||
*/
|
||||
export const RELAY_STATUS_CODES = [
|
||||
'relay-pending',
|
||||
'relay-suspended',
|
||||
'relay-refused',
|
||||
'relay-quota',
|
||||
'relay-too-large',
|
||||
'relay-attachment-refused',
|
||||
'relay-recipient-suppressed',
|
||||
'relay-unreachable',
|
||||
'relay-not-confirmed',
|
||||
'relay-disconnected',
|
||||
'relay-error',
|
||||
'relay-name-replaced',
|
||||
] as const
|
||||
export type RelayStatusCode = (typeof RELAY_STATUS_CODES)[number]
|
||||
|
||||
/** The site status for a code of the service (contract §1, "suggested site status"). */
|
||||
export function relayStatusFor(code: string, retryable: boolean): RelayStatusCode {
|
||||
switch (code) {
|
||||
case 'attachment-refused':
|
||||
return 'relay-attachment-refused'
|
||||
case 'callback-failed':
|
||||
case 'enrolment-closed':
|
||||
case 'host-not-allowed':
|
||||
return 'relay-refused'
|
||||
case 'quota-exceeded':
|
||||
case 'too-many-recipients':
|
||||
return 'relay-quota'
|
||||
case 'recipient-suppressed':
|
||||
return 'relay-recipient-suppressed'
|
||||
case 'site-pending':
|
||||
return 'relay-pending'
|
||||
case 'site-suspended':
|
||||
return 'relay-suspended'
|
||||
case 'too-large':
|
||||
return 'relay-too-large'
|
||||
default:
|
||||
// A code this client does not know is acted on by `retryable` (contract §1).
|
||||
return retryable ? 'relay-unreachable' : 'relay-error'
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,586 @@
|
||||
import { createHash, randomBytes } from 'node:crypto'
|
||||
|
||||
import { RELAY_CONTRACT_VERSION, RELAY_SERVICE_NAME } from './constants.js'
|
||||
import { MAIL_KINDS, type MailKind } from './kinds.js'
|
||||
|
||||
/**
|
||||
* A stand-in for the Intecion Notifications Webservice, in memory, for tests — the plugin's own and
|
||||
* a project's. It speaks the wire contract (`contracts/mail-relay/`): every example there runs against
|
||||
* it (test/mailRelayContract.test.ts). Nothing is sent: accepted mail is recorded in `outbox`.
|
||||
*
|
||||
* const relay = createFakeRelay({ allow: ['example.com'] })
|
||||
* iapl({ mail: { relay: { url: relay.url, fetchImpl: relay.fetch } } })
|
||||
*
|
||||
* It is NOT the service: its sender-name guard and its limits are simplified (the real lists and
|
||||
* windows are the service's own), and it keeps no log. Use it to test what a site does with each
|
||||
* answer, not to learn what the service will accept.
|
||||
*/
|
||||
|
||||
export type FakeRelayMail = {
|
||||
attachments: { bytes: number; contentType: string; filename: string }[]
|
||||
bcc: string[]
|
||||
cc: string[]
|
||||
from: string
|
||||
fromName: string
|
||||
headers: Record<string, string>
|
||||
host: string
|
||||
html?: string
|
||||
kind: MailKind
|
||||
replyTo?: string
|
||||
subject: string
|
||||
text?: string
|
||||
to: string[]
|
||||
}
|
||||
|
||||
export type FakeRelayLimits = {
|
||||
maxAttachmentBytes: number
|
||||
maxAttachments: number
|
||||
maxBodyBytes: number
|
||||
messagesPerDay: number
|
||||
messagesPerHour: number
|
||||
newRecipientsPerDay: number
|
||||
perRecipientPerDay: number
|
||||
recipientsPerMessage: number
|
||||
securityAlertsPerDay: number
|
||||
serverAddresses: number
|
||||
}
|
||||
|
||||
type Site = {
|
||||
addresses: string[]
|
||||
alerts: number
|
||||
/** A token issued by hand binds to the first address that uses it. */
|
||||
bindOnUse: boolean
|
||||
callbackPath?: string
|
||||
confirmations: Map<string, number>
|
||||
dayAccount: number
|
||||
dayOther: number
|
||||
host: string
|
||||
hourAccount: number
|
||||
hourOther: number
|
||||
issuedAt: number
|
||||
keys: Map<string, { answer: Record<string, unknown>; hash: string }>
|
||||
lastSenderName?: string
|
||||
previous?: { token: string; until: number }
|
||||
product: string
|
||||
state: 'active' | 'pending' | 'suspended'
|
||||
token?: string
|
||||
}
|
||||
|
||||
export type FakeRelayOptions = {
|
||||
/** Where the service's own notices and every `security-alert` go. */
|
||||
alertRecipient?: string
|
||||
/** Hosts that are active as soon as they enrol; others wait for approval (`'*'` = every host). */
|
||||
allow?: string[]
|
||||
/** Also enrol hosts that are not public DNS names (`localhost:3000`), and call them back over http. For a site on this machine. */
|
||||
allowLocalHosts?: boolean
|
||||
/** How the service reaches a site's confirm route. Default: `fetch`, no redirect followed. */
|
||||
callSite?: (url: string, init: { body: string; headers: Record<string, string>; method: 'POST' }) => Promise<Response>
|
||||
/** The address requests come from when the request carries no `x-fake-client-address` header. */
|
||||
clientAddress?: string
|
||||
limits?: Partial<FakeRelayLimits>
|
||||
now?: () => number
|
||||
senderAddress?: string
|
||||
}
|
||||
|
||||
const DEFAULT_LIMITS: FakeRelayLimits = {
|
||||
maxAttachmentBytes: 10 * 1024 * 1024,
|
||||
maxAttachments: 20,
|
||||
maxBodyBytes: 512_000,
|
||||
messagesPerDay: 200,
|
||||
messagesPerHour: 30,
|
||||
newRecipientsPerDay: 50,
|
||||
perRecipientPerDay: 10,
|
||||
recipientsPerMessage: 10,
|
||||
securityAlertsPerDay: 20,
|
||||
serverAddresses: 8,
|
||||
}
|
||||
|
||||
const DAY = 24 * 60 * 60_000
|
||||
const HOST = /^(?=.{4,253}$)(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z][a-z0-9-]{0,61}[a-z0-9]$/
|
||||
const LOCAL_HOST = /^[a-z0-9](?:[a-z0-9.-]{0,251}[a-z0-9])?(?::\d{1,5})?$/
|
||||
const PRIVATE = ['localhost', 'local', 'localdomain', 'internal', 'intranet', 'private', 'lan', 'home', 'corp', 'test', 'invalid', 'example', 'onion', 'arpa']
|
||||
const ADDRESS = /^[\w!#$%&'*+/=?^`{|}~-]+(?:\.[\w!#$%&'*+/=?^`{|}~-]+)*@(?:[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?\.)+[A-Z][A-Z0-9-]{0,61}[A-Z0-9]$/i
|
||||
const NONCE = /^[\w-]{32,128}$/
|
||||
const KEY = /^[\w-]{16,128}$/
|
||||
const VERSION = /^[0-9A-Z][\w.+-]*$/i
|
||||
const CONTENT_TYPE = /^[A-Z0-9][\w!#$&^.+-]*\/[A-Z0-9][\w!#$&^.+-]*$/i
|
||||
// three single code points on purpose (ZWNJ, ZWJ, soft hyphen), not a joined sequence
|
||||
// eslint-disable-next-line no-misleading-character-class
|
||||
const UNSAFE_SUBJECT = /[\p{Cc}\p{Zl}\p{Zp}\p{Co}\p{Cs}]|(?![\u200C\u200D\u00AD])\p{Cf}/u
|
||||
const UNSAFE_NAME = /[\p{Cc}\p{Zl}\p{Zp}\p{Co}\p{Cs}\p{Cf}]/u
|
||||
const EXECUTABLE = new Set(['apk', 'app', 'bat', 'cmd', 'com', 'cpl', 'dll', 'dmg', 'exe', 'hta', 'jar', 'js', 'jse', 'lnk', 'msi', 'ps1', 'scr', 'sh', 'vbs', 'wsf'])
|
||||
const SEND_FIELDS = new Set(['attachments', 'bcc', 'cc', 'html', 'kind', 'product', 'productVersion', 'replyTo', 'senderName', 'subject', 'text', 'to'])
|
||||
const NEVER_A_CLIENT = /\b(?:admin|administrator|amazon|apple|bank|gmail|google|intecion|microsoft|no-?reply|outlook|paypal|security|support)\b/i
|
||||
|
||||
const sha256 = (value: string | Uint8Array) => createHash('sha256').update(value).digest('hex')
|
||||
|
||||
class Refusal extends Error {
|
||||
constructor(
|
||||
readonly status: number,
|
||||
readonly code: string,
|
||||
message: string,
|
||||
readonly extra: { field?: string; limit?: string; reason?: string; retryable?: boolean; retryAfter?: number } = {},
|
||||
) {
|
||||
super(message)
|
||||
}
|
||||
}
|
||||
const invalid = (field: string, message: string) => new Refusal(400, 'invalid-request', message, { field })
|
||||
|
||||
function isPublicHost(host: string): boolean {
|
||||
return HOST.test(host) && !PRIVATE.some((s) => host === s || host.endsWith(`.${s}`))
|
||||
}
|
||||
|
||||
/** The simplified sender-name guard: the name, or null when the mail leaves under the host instead. */
|
||||
function guardName(name: string, host: string): null | string {
|
||||
const clean = name.replace(/\s+/g, ' ').trim()
|
||||
if (!clean || [...clean].length > 64) {return null}
|
||||
if (/[@<>"\\]/.test(clean) || !/^[\p{L}\p{N} .,&'’()/-]+$/u.test(clean)) {return null}
|
||||
if (/\b[\w-]+\.[a-z]{2,}\b/i.test(clean) && !clean.toLowerCase().includes(host)) {return null}
|
||||
if (NEVER_A_CLIENT.test(clean)) {return null}
|
||||
const scripts = ['Latin', 'Cyrillic', 'Greek'].filter((s) => new RegExp(`\\p{Script=${s}}`, 'u').test(clean))
|
||||
return scripts.length > 1 ? null : clean
|
||||
}
|
||||
|
||||
export type FakeRelay = {
|
||||
/** Lists a host: it is active as soon as it enrols (and at once when it is waiting). */
|
||||
allow: (host: string) => void
|
||||
/** How the mail back end answers the next sends. */
|
||||
backend: 'failure' | 'ok' | 'recipient-suppressed'
|
||||
/** The address the next requests come from (a request's own `x-fake-client-address` header wins). */
|
||||
clientAddress: string
|
||||
/** `fetch` for requests under `url`; anything else goes to the real `fetch`. */
|
||||
fetch: typeof fetch
|
||||
/** One request to the service: `handle(new Request(`${url}/v1/send`, …))`. */
|
||||
handle: (request: Request) => Promise<Response>
|
||||
/**
|
||||
* Looked at before every request: return a `Response` to answer in the service's place, `'drop'` to
|
||||
* make the request fail like a lost connection, or nothing to let it through.
|
||||
*/
|
||||
intercept?: (request: Request) => 'drop' | Promise<'drop' | Response | undefined> | Response | undefined
|
||||
/** A token for a site the service cannot call back; it binds to the first address that uses it. */
|
||||
issueToken: (host: string, product?: string) => string
|
||||
limits: FakeRelayLimits
|
||||
/** Starts an HTTP server for the fake (a site in another process, an end-to-end test). */
|
||||
listen: (port?: number) => Promise<{ close: () => Promise<void>; url: string }>
|
||||
/** Every message the back end accepted, oldest first. */
|
||||
outbox: FakeRelayMail[]
|
||||
/** Every request that reached the service: method, path and the caller's address — never a token. */
|
||||
requests: { address: string; method: string; path: string }[]
|
||||
/** Forgets every site, message and counter. */
|
||||
reset: () => void
|
||||
/** Sets the confirm address of one host (a site that serves its API somewhere else). */
|
||||
setCallbackPath: (host: string, path: string) => void
|
||||
/** Puts a site into a state without an enrolment; returns its token. */
|
||||
setSite: (host: string, state: 'active' | 'pending' | 'suspended', options?: { product?: string }) => string
|
||||
/** For tests of limits: the counters of one site. */
|
||||
site: (host: string) => Site | undefined
|
||||
url: string
|
||||
}
|
||||
|
||||
export function createFakeRelay(options: FakeRelayOptions = {}): FakeRelay {
|
||||
const now = options.now ?? (() => Date.now())
|
||||
const senderAddress = options.senderAddress ?? '[email protected]'
|
||||
const alertRecipient = options.alertRecipient ?? '[email protected]'
|
||||
const listed = new Set(options.allow ?? [])
|
||||
const sites = new Map<string, Site>()
|
||||
const tokens = new Map<string, string>() // sha256(token) → host
|
||||
const url = 'https://fake-relay.invalid/mail'
|
||||
const seenRecipients = new Map<string, Set<string>>()
|
||||
|
||||
const isListed = (host: string) => listed.has('*') || listed.has(host)
|
||||
const newToken = () => `ims_${randomBytes(32).toString('base64url')}`
|
||||
const blank = (host: string, product: string): Site => ({
|
||||
addresses: [], alerts: 0, bindOnUse: false, confirmations: new Map(), dayAccount: 0, dayOther: 0, host, hourAccount: 0, hourOther: 0, issuedAt: now(), keys: new Map(), product, state: 'pending',
|
||||
})
|
||||
const giveToken = (site: Site): string => {
|
||||
const token = newToken()
|
||||
if (site.token) {site.previous = { token: site.token, until: now() + DAY }}
|
||||
site.token = token
|
||||
site.issuedAt = now()
|
||||
tokens.set(sha256(token), site.host)
|
||||
return token
|
||||
}
|
||||
|
||||
const relay: FakeRelay = {
|
||||
allow: (host) => {
|
||||
listed.add(host)
|
||||
const site = sites.get(host)
|
||||
if (site?.state === 'pending') {site.state = 'active'}
|
||||
},
|
||||
backend: 'ok',
|
||||
clientAddress: options.clientAddress ?? '203.0.113.10',
|
||||
fetch: ((input: Request | string | URL, init?: RequestInit) => {
|
||||
const target = typeof input === 'string' ? input : input instanceof URL ? input.href : input.url
|
||||
if (!target.startsWith(url)) {return fetch(input, init)}
|
||||
return relay.handle(new Request(input, init))
|
||||
}) as typeof fetch,
|
||||
handle: async (request) => {
|
||||
const held = await relay.intercept?.(request.clone())
|
||||
if (held === 'drop') {throw new TypeError('fetch failed')}
|
||||
if (held) {return held}
|
||||
return handle(request)
|
||||
},
|
||||
issueToken: (host, product = 'iapl') => {
|
||||
const site = sites.get(host) ?? blank(host, product)
|
||||
sites.set(host, site)
|
||||
site.state = site.state === 'suspended' ? 'suspended' : 'active'
|
||||
site.bindOnUse = true
|
||||
site.addresses = []
|
||||
return giveToken(site)
|
||||
},
|
||||
limits: { ...DEFAULT_LIMITS, ...options.limits },
|
||||
listen: async (port = 0) => {
|
||||
const { createServer } = await import('node:http')
|
||||
const server = createServer((req, res) => {
|
||||
const chunks: Buffer[] = []
|
||||
req.on('data', (c: Buffer) => chunks.push(c))
|
||||
req.on('end', () => {
|
||||
void (async () => {
|
||||
const headers = new Headers()
|
||||
for (const [k, v] of Object.entries(req.headers)) {
|
||||
if (typeof v === 'string') {headers.set(k, v)}
|
||||
}
|
||||
const method = (req.method ?? 'GET').toUpperCase()
|
||||
const prefix = new URL(url).pathname
|
||||
const path = (req.url ?? '/').startsWith(prefix) ? (req.url ?? '/').slice(prefix.length) : `/__outside${req.url ?? '/'}`
|
||||
try {
|
||||
const response = await relay.handle(new Request(`${url}${path}`, { body: method === 'GET' || method === 'HEAD' ? undefined : Buffer.concat(chunks), headers, method }))
|
||||
response.headers.forEach((value, key) => res.setHeader(key, value))
|
||||
res.statusCode = response.status
|
||||
res.end(Buffer.from(await response.arrayBuffer()))
|
||||
} catch {
|
||||
req.socket.destroy()
|
||||
}
|
||||
})()
|
||||
})
|
||||
})
|
||||
await new Promise<void>((resolve) => server.listen(port, '127.0.0.1', resolve))
|
||||
const address = server.address()
|
||||
const listening = typeof address === 'object' && address ? address.port : port
|
||||
return { close: () => new Promise<void>((resolve) => server.close(() => resolve())), url: `http://127.0.0.1:${listening}${new URL(url).pathname}` }
|
||||
},
|
||||
outbox: [],
|
||||
requests: [],
|
||||
reset: () => {
|
||||
sites.clear()
|
||||
tokens.clear()
|
||||
seenRecipients.clear()
|
||||
relay.outbox.length = 0
|
||||
relay.requests.length = 0
|
||||
relay.backend = 'ok'
|
||||
relay.intercept = undefined
|
||||
},
|
||||
setCallbackPath: (host, path) => {
|
||||
const site = sites.get(host) ?? blank(host, 'iapl')
|
||||
sites.set(host, site)
|
||||
site.callbackPath = path
|
||||
},
|
||||
setSite: (host, state, { product = 'iapl' } = {}) => {
|
||||
const site = sites.get(host) ?? blank(host, product)
|
||||
sites.set(host, site)
|
||||
site.state = state
|
||||
if (!site.addresses.includes(relay.clientAddress)) {site.addresses.push(relay.clientAddress)}
|
||||
return site.token ?? giveToken(site)
|
||||
},
|
||||
site: (host) => sites.get(host),
|
||||
url,
|
||||
}
|
||||
|
||||
const json = (status: number, body: Record<string, unknown>, headers: Record<string, string> = {}) =>
|
||||
new Response(JSON.stringify(body), { headers: { 'cache-control': 'no-store', 'content-type': 'application/json', ...headers }, status })
|
||||
|
||||
const refused = (r: Refusal) =>
|
||||
json(
|
||||
r.status,
|
||||
{ code: r.code, message: r.message, ok: false, retryable: r.extra.retryable ?? false, ...(r.extra.field ? { field: r.extra.field } : {}), ...(r.extra.limit ? { limit: r.extra.limit } : {}), ...(r.extra.reason ? { reason: r.extra.reason } : {}), ...(r.extra.retryAfter !== undefined ? { retryAfter: r.extra.retryAfter } : {}) },
|
||||
r.extra.retryAfter !== undefined ? { 'retry-after': String(r.extra.retryAfter) } : {},
|
||||
)
|
||||
|
||||
async function readJson(request: Request): Promise<{ bytes: Uint8Array; value: Record<string, unknown> }> {
|
||||
if (!(request.headers.get('content-type') ?? '').toLowerCase().startsWith('application/json')) {
|
||||
throw new Refusal(415, 'unsupported-media-type', 'The body must be application/json.')
|
||||
}
|
||||
const bytes = new Uint8Array(await request.arrayBuffer())
|
||||
let value: unknown
|
||||
try {
|
||||
value = JSON.parse(new TextDecoder().decode(bytes))
|
||||
} catch {
|
||||
throw invalid('body', 'The body is not JSON.')
|
||||
}
|
||||
if (!value || typeof value !== 'object' || Array.isArray(value)) {throw invalid('body', 'The body must be an object.')}
|
||||
return { bytes, value: value as Record<string, unknown> }
|
||||
}
|
||||
|
||||
function authenticate(request: Request, address: string): { current: boolean; site: Site } {
|
||||
const match = /^bearer (\S+)$/i.exec(request.headers.get('authorization') ?? '')
|
||||
const host = match ? tokens.get(sha256(match[1])) : undefined
|
||||
const site = host ? sites.get(host) : undefined
|
||||
const current = Boolean(site && match && site.token === match[1])
|
||||
const previous = Boolean(site && match && site.previous?.token === match[1] && site.previous.until > now())
|
||||
if (!site || (!current && !previous)) {throw new Refusal(401, 'invalid-token', 'No token, or one the service does not know.')}
|
||||
if (site.bindOnUse && site.addresses.length === 0) {site.addresses.push(address)}
|
||||
if (!site.addresses.includes(address)) {throw new Refusal(401, 'reverify', 'The token is good, but this server address is new for the site. Enrol again.')}
|
||||
// used most recently last: beyond the limit the address used longest ago is dropped
|
||||
site.addresses = [...site.addresses.filter((a) => a !== address), address]
|
||||
return { current, site }
|
||||
}
|
||||
|
||||
async function enrol(request: Request, address: string): Promise<Response> {
|
||||
const { value } = await readJson(request)
|
||||
for (const key of Object.keys(value)) {
|
||||
if (!['host', 'nonce', 'product', 'productVersion'].includes(key)) {throw invalid(key, `Unknown field "${key}".`)}
|
||||
}
|
||||
const { host, nonce, product, productVersion } = value
|
||||
if (typeof host !== 'string') {throw invalid('host', 'host is required.')}
|
||||
if (typeof nonce !== 'string' || !NONCE.test(nonce)) {throw invalid('nonce', 'nonce must be 32 to 128 characters of A-Z a-z 0-9 _ -.')}
|
||||
if (product !== 'iapl' && product !== 'iawl') {throw invalid('product', 'Unknown product.')}
|
||||
if (typeof productVersion !== 'string' || !VERSION.test(productVersion) || productVersion.length > 32) {throw invalid('productVersion', 'productVersion is required.')}
|
||||
const local = Boolean(options.allowLocalHosts) && LOCAL_HOST.test(host)
|
||||
if (!isPublicHost(host) && !local) {throw new Refusal(403, 'host-not-allowed', 'The host is not a public DNS name.')}
|
||||
|
||||
const existing = sites.get(host)
|
||||
if (existing?.state === 'suspended') {throw new Refusal(403, 'site-suspended', 'The site was stopped by Intecion.')}
|
||||
const site = existing ?? blank(host, product)
|
||||
const state = existing?.state === 'active' || isListed(host) ? 'active' : 'pending'
|
||||
const token = newToken()
|
||||
const path = site.callbackPath ?? (product === 'iawl' ? '/?rest_route=/iawl/v1/mail-relay/confirm' : '/api/iapl/mail-relay/confirm')
|
||||
const target = `${local && !isPublicHost(host) ? 'http' : 'https'}://${host}${path}`
|
||||
const body = JSON.stringify({ nonce, state, token })
|
||||
const fail = (reason: string) => new Refusal(422, 'callback-failed', `The site's confirm endpoint did not confirm (${reason}).`, { reason })
|
||||
let answer: Response
|
||||
try {
|
||||
const call = options.callSite ?? ((u, init) => fetch(u, { ...init, redirect: 'manual', signal: AbortSignal.timeout(8000) }))
|
||||
answer = await call(target, { body, headers: { 'content-type': 'application/json' }, method: 'POST' })
|
||||
} catch (err) {
|
||||
throw fail(err instanceof Error && err.name === 'TimeoutError' ? 'timeout' : 'unreachable')
|
||||
}
|
||||
if (answer.status >= 300 && answer.status < 400) {throw fail('redirect')}
|
||||
if (answer.status !== 200) {throw fail('status')}
|
||||
let confirmation: unknown
|
||||
try {
|
||||
const text = await answer.text()
|
||||
confirmation = text.length <= 1024 ? (JSON.parse(text) as { confirmation?: unknown }).confirmation : undefined
|
||||
} catch {
|
||||
confirmation = undefined
|
||||
}
|
||||
if (confirmation !== sha256(`${nonce}.${token}`)) {throw fail('confirmation')}
|
||||
|
||||
sites.set(host, site)
|
||||
site.state = state
|
||||
site.product = product
|
||||
if (site.token) {site.previous = { token: site.token, until: now() + DAY }}
|
||||
site.token = token
|
||||
site.issuedAt = now()
|
||||
site.bindOnUse = false
|
||||
tokens.set(sha256(token), host)
|
||||
site.addresses = [...site.addresses.filter((a) => a !== address), address].slice(-relay.limits.serverAddresses)
|
||||
return json(200, { ok: true, state })
|
||||
}
|
||||
|
||||
function validateSend(value: Record<string, unknown>, site: Site) {
|
||||
for (const key of Object.keys(value)) {
|
||||
if (!SEND_FIELDS.has(key)) {throw invalid(key, `Unknown field "${key}".`)}
|
||||
}
|
||||
const kind = value.kind as MailKind
|
||||
if (value.product !== 'iapl' && value.product !== 'iawl') {throw invalid('product', 'Unknown product.')}
|
||||
if (typeof value.productVersion !== 'string' || !VERSION.test(value.productVersion)) {throw invalid('productVersion', 'productVersion is required.')}
|
||||
if (!(MAIL_KINDS as readonly string[]).includes(kind)) {throw invalid('kind', 'Unknown kind.')}
|
||||
const list = (field: 'bcc' | 'cc' | 'to'): string[] => {
|
||||
const raw = value[field]
|
||||
if (raw === undefined) {return []}
|
||||
if (!Array.isArray(raw) || raw.some((a) => typeof a !== 'string' || a.length > 254 || !ADDRESS.test(a))) {throw invalid(field, `${field} must be a list of bare addresses.`)}
|
||||
return raw as string[]
|
||||
}
|
||||
let to = list('to')
|
||||
let cc = list('cc')
|
||||
let bcc = list('bcc')
|
||||
if (kind === 'security-alert') {
|
||||
to = [alertRecipient]
|
||||
cc = []
|
||||
bcc = []
|
||||
} else if (to.length === 0) {throw invalid('to', 'At least one recipient.')}
|
||||
if (to.length + cc.length + bcc.length > relay.limits.recipientsPerMessage) {
|
||||
throw new Refusal(422, 'too-many-recipients', `At most ${relay.limits.recipientsPerMessage} recipients a message.`)
|
||||
}
|
||||
const replyTo = value.replyTo
|
||||
if (replyTo !== undefined && (typeof replyTo !== 'string' || !ADDRESS.test(replyTo))) {throw invalid('replyTo', 'replyTo must be one bare address.')}
|
||||
const senderName = value.senderName
|
||||
if (senderName !== undefined && (typeof senderName !== 'string' || [...senderName].length > 256)) {throw invalid('senderName', 'senderName must be at most 256 characters.')}
|
||||
const subject = value.subject
|
||||
if (typeof subject !== 'string' || subject.length === 0 || [...subject].length > 300) {throw invalid('subject', 'subject must be 1 to 300 characters.')}
|
||||
if (UNSAFE_SUBJECT.test(subject)) {throw invalid('subject', 'subject must not contain line breaks, control or invisible characters.')}
|
||||
if (subject.replace(/\s+/g, '').toLowerCase().startsWith(`[${RELAY_SERVICE_NAME.replace(/ /g, '').toLowerCase()}`)) {
|
||||
throw invalid('subject', 'The subject must not start with the name of the mail service in brackets.')
|
||||
}
|
||||
const { html, text } = value
|
||||
if (text !== undefined && (typeof text !== 'string' || !text)) {throw invalid('text', 'text must be a non-empty string.')}
|
||||
if (html !== undefined && (typeof html !== 'string' || !html)) {throw invalid('html', 'html must be a non-empty string.')}
|
||||
if (text === undefined && html === undefined) {throw invalid('text', 'text or html is required.')}
|
||||
if (Buffer.byteLength(`${(text) ?? ''}${(html) ?? ''}`) > relay.limits.maxBodyBytes) {
|
||||
throw new Refusal(413, 'too-large', 'The body is too large.', { limit: 'body' })
|
||||
}
|
||||
const attachments: FakeRelayMail['attachments'] = []
|
||||
if (value.attachments !== undefined) {
|
||||
if (!Array.isArray(value.attachments) || value.attachments.length > relay.limits.maxAttachments) {throw invalid('attachments', 'Too many attachments.')}
|
||||
let total = 0
|
||||
value.attachments.forEach((raw: unknown, index: number) => {
|
||||
const a = raw as { content?: unknown; contentType?: unknown; filename?: unknown }
|
||||
if (!a || typeof a !== 'object' || Object.keys(a).some((k) => !['content', 'contentType', 'filename'].includes(k))) {throw invalid('attachments', 'Unknown field in an attachment.')}
|
||||
if (typeof a.filename !== 'string' || !a.filename || a.filename.length > 255) {throw invalid('attachments', 'An attachment needs a filename.')}
|
||||
if (typeof a.contentType !== 'string' || !CONTENT_TYPE.test(a.contentType)) {throw invalid('attachments', 'An attachment needs a content type.')}
|
||||
if (typeof a.content !== 'string' || a.content.length < 4 || a.content.length % 4 !== 0 || !/^[A-Z0-9+/]+={0,2}$/i.test(a.content)) {throw invalid('attachments', 'content must be padded base64.')}
|
||||
const refusedFile = new Refusal(422, 'attachment-refused', 'A file the service never carries, or a bad file name.', { field: `attachments[${index}]` })
|
||||
if (UNSAFE_NAME.test(a.filename) || /[/\\"<>|:*?]/.test(a.filename) || a.filename.startsWith('.')) {throw refusedFile}
|
||||
if (a.filename.toLowerCase().split('.').slice(1).some((e) => EXECUTABLE.has(e))) {throw refusedFile}
|
||||
const bytes = (a.content.length * 3) / 4 - (a.content.endsWith('==') ? 2 : a.content.endsWith('=') ? 1 : 0)
|
||||
total += bytes
|
||||
attachments.push({ bytes, contentType: a.contentType, filename: a.filename })
|
||||
})
|
||||
if (total > relay.limits.maxAttachmentBytes) {throw new Refusal(413, 'too-large', 'The attachments are too large.', { limit: 'attachments' })}
|
||||
}
|
||||
const asked = typeof senderName === 'string' ? senderName : ''
|
||||
const accepted = asked ? guardName(asked, site.host) : null
|
||||
const marked = [...bcc, ...cc, ...to].includes(alertRecipient)
|
||||
return {
|
||||
attachments, bcc, cc, html, kind, replaced: Boolean(asked) && !accepted,
|
||||
replyTo, senderName: accepted ?? site.host, subject: marked ? `[${site.host}] ${subject}` : subject, text, to,
|
||||
}
|
||||
}
|
||||
|
||||
/** The limits of contract §3.3, counted simply (no sliding window: `reset()` or the site's counters start them again). */
|
||||
function checkQuota(site: Site, kind: MailKind, recipients: string[]): { apply: () => void; left: { day: number; hour: number } } {
|
||||
const { messagesPerDay: day, messagesPerHour: hour, newRecipientsPerDay, perRecipientPerDay, securityAlertsPerDay } = relay.limits
|
||||
const over = (limit: string) => new Refusal(429, 'quota-exceeded', `The site reached its limit (${limit}).`, { limit })
|
||||
if (kind === 'security-alert') {
|
||||
if (site.alerts >= securityAlertsPerDay) {throw over('alerts')}
|
||||
return { apply: () => void (site.alerts += 1), left: { day: securityAlertsPerDay - site.alerts - 1, hour: securityAlertsPerDay - site.alerts - 1 } }
|
||||
}
|
||||
const share = (limit: number) => (kind === 'account' || limit < 5 ? limit : Math.floor((limit * 4) / 5))
|
||||
const usedHour = kind === 'account' ? site.hourAccount + site.hourOther : site.hourOther
|
||||
const usedDay = kind === 'account' ? site.dayAccount + site.dayOther : site.dayOther
|
||||
if (usedHour >= share(hour) || site.hourAccount + site.hourOther >= hour) {throw over('hour')}
|
||||
if (usedDay >= share(day) || site.dayAccount + site.dayOther >= day) {throw over('day')}
|
||||
if (kind === 'form-confirmation' && recipients.some((r) => (site.confirmations.get(r.toLowerCase()) ?? 0) >= perRecipientPerDay)) {throw over('recipient')}
|
||||
const seen = seenRecipients.get(site.host) ?? new Set<string>()
|
||||
seenRecipients.set(site.host, seen)
|
||||
const fresh = kind === 'account' ? [] : recipients.filter((r) => !seen.has(r.toLowerCase()))
|
||||
const newToday = [...seen].filter((r) => r.startsWith('new:')).length
|
||||
const newLimit = kind === 'form-confirmation' && newRecipientsPerDay >= 5 ? Math.floor((newRecipientsPerDay * 4) / 5) : newRecipientsPerDay
|
||||
if (fresh.length && newToday + fresh.length > newLimit) {throw over('new-recipients')}
|
||||
return {
|
||||
apply: () => {
|
||||
if (kind === 'account') {
|
||||
site.hourAccount += 1
|
||||
site.dayAccount += 1
|
||||
} else {
|
||||
site.hourOther += 1
|
||||
site.dayOther += 1
|
||||
}
|
||||
if (kind === 'form-confirmation') {
|
||||
for (const r of recipients) {site.confirmations.set(r.toLowerCase(), (site.confirmations.get(r.toLowerCase()) ?? 0) + 1)}
|
||||
}
|
||||
for (const r of fresh) {
|
||||
seen.add(r.toLowerCase())
|
||||
seen.add(`new:${r.toLowerCase()}`)
|
||||
}
|
||||
},
|
||||
left: { day: Math.max(0, Math.min(share(day) - usedDay, day - site.dayAccount - site.dayOther) - 1), hour: Math.max(0, Math.min(share(hour) - usedHour, hour - site.hourAccount - site.hourOther) - 1) },
|
||||
}
|
||||
}
|
||||
|
||||
async function send(request: Request, address: string): Promise<Response> {
|
||||
const { site } = authenticate(request, address)
|
||||
if (site.state === 'pending') {throw new Refusal(403, 'site-pending', 'The site is waiting for approval by Intecion.')}
|
||||
if (site.state === 'suspended') {throw new Refusal(403, 'site-suspended', 'The site was stopped by Intecion.')}
|
||||
const key = request.headers.get('idempotency-key') ?? ''
|
||||
if (!KEY.test(key)) {throw invalid('Idempotency-Key', 'Idempotency-Key must be 16 to 128 characters of A-Z a-z 0-9 _ -.')}
|
||||
const { bytes, value } = await readJson(request)
|
||||
const hash = sha256(bytes)
|
||||
const known = site.keys.get(key)
|
||||
if (known) {
|
||||
if (known.hash !== hash) {throw new Refusal(409, 'idempotency-conflict', 'This Idempotency-Key was used for a different message.')}
|
||||
return json(200, { ...known.answer, replayed: true })
|
||||
}
|
||||
const mail = validateSend(value, site)
|
||||
const quota = checkQuota(site, mail.kind, [...mail.to, ...mail.cc, ...mail.bcc])
|
||||
if (relay.backend === 'failure') {throw new Refusal(502, 'backend-failed', 'The mail back end failed.', { retryable: true })}
|
||||
if (relay.backend === 'recipient-suppressed') {throw new Refusal(422, 'recipient-suppressed', 'The mail back end refuses one of the recipients. Nothing was sent.')}
|
||||
quota.apply()
|
||||
site.lastSenderName = mail.senderName
|
||||
relay.outbox.push({
|
||||
attachments: mail.attachments, bcc: mail.bcc, cc: mail.cc, from: senderAddress, fromName: mail.senderName,
|
||||
headers: { 'X-Intecion-Product': String(value.product), 'X-Intecion-Site': site.host }, host: site.host,
|
||||
...(mail.html ? { html: mail.html } : {}), kind: mail.kind, ...(mail.replyTo ? { replyTo: mail.replyTo } : {}), subject: mail.subject, ...(mail.text ? { text: mail.text } : {}), to: mail.to,
|
||||
})
|
||||
const { messagesPerDay, messagesPerHour } = relay.limits
|
||||
const answer = {
|
||||
id: `fake-${relay.outbox.length}`,
|
||||
messageId: `<fake-${relay.outbox.length}@${senderAddress.split('@')[1]}>`,
|
||||
ok: true,
|
||||
quota: { day: { limit: messagesPerDay, remaining: quota.left.day }, hour: { limit: messagesPerHour, remaining: quota.left.hour } },
|
||||
replayed: false,
|
||||
senderName: mail.senderName,
|
||||
warnings: mail.replaced ? ['sender-name-replaced'] : [],
|
||||
}
|
||||
site.keys.set(key, { answer, hash })
|
||||
return json(200, answer)
|
||||
}
|
||||
|
||||
function status(request: Request, address: string): Response {
|
||||
const { site } = authenticate(request, address)
|
||||
const { messagesPerDay, messagesPerHour } = relay.limits
|
||||
return json(200, {
|
||||
host: site.host,
|
||||
kinds: [...MAIL_KINDS],
|
||||
limits: relay.limits,
|
||||
ok: true,
|
||||
product: site.product,
|
||||
quota: { day: { limit: messagesPerDay, remaining: Math.max(0, messagesPerDay - site.dayAccount - site.dayOther) }, hour: { limit: messagesPerHour, remaining: Math.max(0, messagesPerHour - site.hourAccount - site.hourOther) } },
|
||||
sender: { address: senderAddress },
|
||||
...(site.lastSenderName ? { senderName: site.lastSenderName } : {}),
|
||||
service: { name: RELAY_SERVICE_NAME, contract: RELAY_CONTRACT_VERSION, version: '0.0.0-fake' },
|
||||
state: site.state,
|
||||
token: { issuedAt: new Date(site.issuedAt).toISOString(), rotateAfter: new Date(site.issuedAt + 90 * DAY).toISOString() },
|
||||
})
|
||||
}
|
||||
|
||||
async function handle(request: Request): Promise<Response> {
|
||||
const path = new URL(request.url).pathname.slice(new URL(url).pathname.length) || '/'
|
||||
const address = request.headers.get('x-fake-client-address') ?? relay.clientAddress
|
||||
relay.requests.push({ address, method: request.method, path })
|
||||
try {
|
||||
const fetchSite = request.headers.get('sec-fetch-site')
|
||||
if (request.headers.has('origin') || (fetchSite !== null && fetchSite !== 'none')) {throw new Refusal(403, 'browser-not-allowed', 'The service is for servers, not browsers.')}
|
||||
const routes: Record<string, [string, () => Promise<Response> | Response]> = {
|
||||
'/health': ['GET', () => json(200, { ok: true })],
|
||||
'/v1/enrol': ['POST', () => enrol(request, address)],
|
||||
'/v1/revoke': ['POST', () => {
|
||||
const { site } = authenticate(request, address)
|
||||
for (const [hash, host] of tokens) {
|
||||
if (host === site.host) {tokens.delete(hash)}
|
||||
}
|
||||
site.token = undefined
|
||||
site.previous = undefined
|
||||
return json(200, { ok: true })
|
||||
}],
|
||||
'/v1/rotate': ['POST', () => {
|
||||
const { current, site } = authenticate(request, address)
|
||||
if (!current) {throw new Refusal(409, 'already-rotated', 'Only the current token can rotate.')}
|
||||
const token = giveToken(site)
|
||||
return json(200, { ok: true, previousValidUntil: new Date(now() + DAY).toISOString(), token })
|
||||
}],
|
||||
'/v1/send': ['POST', () => send(request, address)],
|
||||
'/v1/status': ['GET', () => status(request, address)],
|
||||
}
|
||||
const route = routes[path]
|
||||
if (!route) {throw new Refusal(404, 'not-found', 'No such route.')}
|
||||
if (route[0] !== request.method) {throw new Refusal(405, 'method-not-allowed', 'Wrong method.')}
|
||||
return await route[1]()
|
||||
} catch (err) {
|
||||
if (err instanceof Refusal) {return refused(err)}
|
||||
return refused(new Refusal(500, 'internal', 'A fault in the fake service.', { retryable: true }))
|
||||
}
|
||||
}
|
||||
|
||||
return relay
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
import type { BasePayload } from 'payload'
|
||||
|
||||
import { type RelayOptions, resolveRelayOptions } from './options.js'
|
||||
import { disconnectRelay as disconnect, enrolRelay as enrol, type EnrolResult, type RelayStatus, rotateRelayToken as rotate, getRelayStatus as status } from './session.js'
|
||||
|
||||
export { RELAY_SENDER_ADDRESS, relayAdapter, relayAttachmentLimit, relaySenderName } from './adapter.js'
|
||||
export type { RelayAdapterArgs } from './adapter.js'
|
||||
export { relayRequest } from './client.js'
|
||||
export type { RelayAnswer, RelayCall, RelayRefusal } from './client.js'
|
||||
export { relayConfirmEndpoint } from './confirm.js'
|
||||
export {
|
||||
RELAY_BASE_URL,
|
||||
RELAY_CONFIRM_PATH,
|
||||
RELAY_CONTRACT_VERSION,
|
||||
RELAY_DEFAULTS,
|
||||
RELAY_KV_KEY,
|
||||
RELAY_PRODUCT,
|
||||
RELAY_SERVICE_NAME,
|
||||
RELAY_STATUS_CODES,
|
||||
relayStatusFor,
|
||||
} from './constants.js'
|
||||
export type { RelayStatusCode } from './constants.js'
|
||||
export { MAIL_KIND, MAIL_KINDS, mailKindOf, markNextMail, runWithMailKind, withMailKind } from './kinds.js'
|
||||
export type { MailKind } from './kinds.js'
|
||||
export { bareAddress, bareAddresses, buildRelayMessage, cleanSubject } from './message.js'
|
||||
export type { BuildRelayMessageArgs, BuiltRelayMessage, RelaySendRequest } from './message.js'
|
||||
export { isPublicHost, relayHost, resolveRelayOptions } from './options.js'
|
||||
export type { RelayOptions } from './options.js'
|
||||
export { sendThroughRelay } from './send.js'
|
||||
export type { RelaySendContext, RelaySendResult } from './send.js'
|
||||
export { setRelayToken } from './session.js'
|
||||
export type { EnrolResult, RelayStatus } from './session.js'
|
||||
|
||||
const DISABLED = 'The mail service is switched off for this project (mail: { relay: false }).'
|
||||
|
||||
function resolved(payload: BasePayload, options?: RelayOptions) {
|
||||
const out = resolveRelayOptions(payload, options)
|
||||
if (!out) {throw new Error(DISABLED)}
|
||||
return out
|
||||
}
|
||||
|
||||
/**
|
||||
* Enrols the site with the Intecion Notifications Webservice now (a deploy script, a "Connect" button
|
||||
* of your own). `mailAdapter()` does this by itself on the first send. `force` also after a refusal a
|
||||
* moment ago, or after "Disconnect".
|
||||
*/
|
||||
export const enrolRelay = (payload: BasePayload, options?: { force?: boolean } & RelayOptions): Promise<EnrolResult> => {
|
||||
const { force, ...own } = options ?? {}
|
||||
return enrol(payload, resolved(payload, Object.keys(own).length ? own : undefined), { force })
|
||||
}
|
||||
|
||||
/** The site's state with the service — never the token. `refresh: true` asks the service; otherwise the stored state. */
|
||||
export const getRelayStatus = (payload: BasePayload, options?: { refresh?: boolean } & RelayOptions): Promise<{ error?: string } & RelayStatus> => {
|
||||
const { refresh, ...own } = options ?? {}
|
||||
return status(payload, resolved(payload, Object.keys(own).length ? own : undefined), { refresh })
|
||||
}
|
||||
|
||||
/** 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))
|
||||
|
||||
/** 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 })
|
||||
@@ -0,0 +1,58 @@
|
||||
import { AsyncLocalStorage } from 'node:async_hooks'
|
||||
|
||||
/**
|
||||
* What a message is for. The Intecion Notifications Webservice applies different limits per kind, so
|
||||
* the kind has to be true: `account` only for mail to an account holder (password reset, invitation),
|
||||
* `form-confirmation` for mail to an address a visitor typed, `form-notification` for a form's mail to
|
||||
* the addresses written in the panel. Mail whose purpose is not known is `system`.
|
||||
*/
|
||||
export const MAIL_KINDS = ['form-notification', 'form-confirmation', 'account', 'security-alert', 'system', 'test'] as const
|
||||
export type MailKind = (typeof MAIL_KINDS)[number]
|
||||
|
||||
/** The key of the kind on a message. A symbol: no mail library reads it, JSON leaves it out, a spread keeps it. */
|
||||
export const MAIL_KIND = Symbol.for('iapl.mailKind')
|
||||
|
||||
const isKind = (value: unknown): value is MailKind => typeof value === 'string' && (MAIL_KINDS as readonly string[]).includes(value)
|
||||
|
||||
/**
|
||||
* Marks a message for `payload.sendEmail`:
|
||||
* await payload.sendEmail(withMailKind({ to, subject, html }, 'account'))
|
||||
* Other transports (SMTP, Graph, a project's own adapter) ignore the mark.
|
||||
*/
|
||||
export function withMailKind<T extends object>(message: T, kind: MailKind): T {
|
||||
return { ...message, [MAIL_KIND]: kind }
|
||||
}
|
||||
|
||||
/** The kind a message was marked with, if any. */
|
||||
export function mailKindOf(message: unknown): MailKind | undefined {
|
||||
const kind = message && typeof message === 'object' ? (message as Record<symbol, unknown>)[MAIL_KIND] : undefined
|
||||
return isKind(kind) ? kind : undefined
|
||||
}
|
||||
|
||||
/**
|
||||
* For mail the plugin does not compose itself (Payload's "forgot password" and "verify your e-mail"):
|
||||
* the operation's hook says what the NEXT message of this request is, and the adapter takes it once.
|
||||
*/
|
||||
type MailContext = { kind: MailKind; sticky?: boolean; taken?: boolean; visitor?: string }
|
||||
const context = new AsyncLocalStorage<MailContext>()
|
||||
|
||||
/**
|
||||
* Says that the next message sent in this request is of `kind`. Call it synchronously at the start of
|
||||
* a hook (before the first `await`), so the operation that called the hook runs on in this context.
|
||||
*/
|
||||
export function markNextMail(kind: MailKind, extra: { visitor?: string } = {}): void {
|
||||
context.enterWith({ kind, ...extra })
|
||||
}
|
||||
|
||||
/** Runs `fn` with every message sent inside it marked as `kind` (a message's own mark still wins). */
|
||||
export function runWithMailKind<T>(kind: MailKind, fn: () => T): T {
|
||||
return context.run({ kind, sticky: true }, fn)
|
||||
}
|
||||
|
||||
/** The context of the message being sent now; a one-shot mark is used up by this call. */
|
||||
export function takeMailContext(): { kind: MailKind; visitor?: string } | undefined {
|
||||
const current = context.getStore()
|
||||
if (!current || current.taken) {return undefined}
|
||||
if (!current.sticky) {current.taken = true}
|
||||
return { kind: current.kind, visitor: current.visitor }
|
||||
}
|
||||
@@ -0,0 +1,161 @@
|
||||
import type { SendEmailOptions } from 'payload'
|
||||
|
||||
import { domainToASCII } from 'node:url'
|
||||
|
||||
import type { MailKind } from './kinds.js'
|
||||
|
||||
import { PLUGIN_VERSION } from '../../../version.js'
|
||||
import { toGraphAttachments } from '../graphAttachments.js'
|
||||
import { RELAY_PRODUCT, RELAY_SERVICE_NAME } from './constants.js'
|
||||
|
||||
/** The body of `POST /v1/send` (contracts/mail-relay/schema.json, `SendRequest`). Closed: no other field exists. */
|
||||
export type RelaySendRequest = {
|
||||
attachments?: { content: string; contentType: string; filename: string }[]
|
||||
bcc?: string[]
|
||||
cc?: string[]
|
||||
html?: string
|
||||
kind: MailKind
|
||||
product: string
|
||||
productVersion: string
|
||||
replyTo?: string
|
||||
senderName?: string
|
||||
subject: string
|
||||
text?: string
|
||||
to?: string[]
|
||||
}
|
||||
|
||||
const ADDRESS = /^[\w!#$%&'*+/=?^`{|}~-]+(?:\.[\w!#$%&'*+/=?^`{|}~-]+)*@(?:[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?\.)+[A-Z][A-Z0-9-]{0,61}[A-Z0-9]$/i
|
||||
const CONTENT_TYPE = /^[A-Z0-9][\w!#$&^.+-]*\/[A-Z0-9][\w!#$&^.+-]*$/i
|
||||
/** What a subject may not contain (contract §3): control and invisible characters, except ZWJ, ZWNJ and the soft hyphen. */
|
||||
// three single code points on purpose (ZWNJ, ZWJ, soft hyphen), not a joined sequence
|
||||
// eslint-disable-next-line no-misleading-character-class
|
||||
const UNSAFE = /[\p{Cc}\p{Zl}\p{Zp}\p{Co}\p{Cs}]|(?![\u200C\u200D\u00AD])\p{Cf}/gu
|
||||
const UNSAFE_STRICT = /[\p{Cc}\p{Zl}\p{Zp}\p{Co}\p{Cs}\p{Cf}]/gu
|
||||
|
||||
/** One bare address (`name@domain`, ASCII; an international domain as punycode), or null. */
|
||||
export function bareAddress(value: unknown): null | string {
|
||||
const raw = typeof value === 'string' ? value : value && typeof value === 'object' ? (value as { address?: unknown }).address : ''
|
||||
if (typeof raw !== 'string') {return null}
|
||||
const text = (raw.match(/<([^<>]+)>\s*$/)?.[1] ?? raw).trim()
|
||||
const at = text.lastIndexOf('@')
|
||||
if (at < 1) {return null}
|
||||
const domain = /^[\x21-\x7e]+$/.test(text.slice(at + 1)) ? text.slice(at + 1) : domainToASCII(text.slice(at + 1))
|
||||
const address = `${text.slice(0, at)}@${domain}`
|
||||
return address.length >= 6 && address.length <= 254 && ADDRESS.test(address) ? address : null
|
||||
}
|
||||
|
||||
/**
|
||||
* Every address of a To / CC / BCC value as nodemailer takes it — a string ("Anna <[email protected]>, [email protected]"),
|
||||
* an object, or a list of either — as bare addresses. `dropped` counts what was not an address.
|
||||
*/
|
||||
export function bareAddresses(value: unknown): { addresses: string[]; dropped: number } {
|
||||
const parts: unknown[] = []
|
||||
for (const item of Array.isArray(value) ? value : value === undefined || value === null || value === '' ? [] : [value]) {
|
||||
if (typeof item === 'string') {
|
||||
// commas and semicolons separate addresses, except inside a quoted display name
|
||||
parts.push(...(item.match(/(?:"[^"]*"|[^,;])+/g) ?? []).map((p) => p.trim()).filter(Boolean))
|
||||
} else {parts.push(item)}
|
||||
}
|
||||
const addresses: string[] = []
|
||||
let dropped = 0
|
||||
for (const part of parts) {
|
||||
const address = bareAddress(part)
|
||||
if (!address) {dropped += 1}
|
||||
else if (!addresses.some((a) => a.toLowerCase() === address.toLowerCase())) {addresses.push(address)}
|
||||
}
|
||||
return { addresses, dropped }
|
||||
}
|
||||
|
||||
const codePoints = (text: string, max: number) => {
|
||||
const points = [...text]
|
||||
return points.length > max ? points.slice(0, max).join('') : text
|
||||
}
|
||||
|
||||
/**
|
||||
* A subject the service accepts. It refuses, it does not repair — and a subject is often a visitor's
|
||||
* own words — so line breaks become spaces, control and invisible characters go, the length is cut to
|
||||
* 300 characters, and a subject that would start like the service's own notices loses its bracket.
|
||||
*/
|
||||
export function cleanSubject(subject: unknown): string {
|
||||
let text = typeof subject === 'string' ? subject : ''
|
||||
text = text.replace(/[\r\n\t\u2028\u2029]+/g, ' ').replace(UNSAFE, '').replace(/ {2,}/g, ' ').trim()
|
||||
if (text.replace(/\s+/g, '').toLowerCase().startsWith(`[${RELAY_SERVICE_NAME.replace(/ /g, '').toLowerCase()}`)) {text = text.replace(/^\s*\[\s*/, '')}
|
||||
return codePoints(text, 300) || '(no subject)'
|
||||
}
|
||||
|
||||
/** A file name the service accepts: no path, no quotes, nothing invisible. */
|
||||
export function cleanFilename(name: unknown): string {
|
||||
const base = (typeof name === 'string' ? name : '').split(/[/\\]/).pop() ?? ''
|
||||
const clean = base.replace(UNSAFE_STRICT, '').replace(/["<>|:*?]/g, '_').replace(/^\.+/, '').trim()
|
||||
return codePoints(clean, 255) || 'attachment'
|
||||
}
|
||||
|
||||
const bodyText = (value: unknown): string | undefined =>
|
||||
typeof value === 'string' ? value || undefined : Buffer.isBuffer(value) ? value.toString('utf8') || undefined : undefined
|
||||
|
||||
export type BuildRelayMessageArgs = {
|
||||
/** What the message is for. Default `system`. */
|
||||
kind?: MailKind
|
||||
product?: string
|
||||
productVersion?: string
|
||||
/** Used when the message names no reply address of its own (the panel's "Sender address"). */
|
||||
replyTo?: null | string
|
||||
/** The display name (the panel's "Sender name", else the site name). Without one the mail leaves under the site's host. */
|
||||
senderName?: null | string
|
||||
}
|
||||
|
||||
export type BuiltRelayMessage =
|
||||
| { dropped: number; ok: true; request: RelaySendRequest }
|
||||
| { ok: false; problem: string }
|
||||
|
||||
/**
|
||||
* A Payload / nodemailer message as the request the service takes. `from` and free headers are left
|
||||
* out: the service fixes the sender address, and there is no field for either.
|
||||
*/
|
||||
export function buildRelayMessage(message: SendEmailOptions, args: BuildRelayMessageArgs = {}): BuiltRelayMessage {
|
||||
const m = message as Record<string, unknown>
|
||||
const kind = args.kind ?? 'system'
|
||||
const to = bareAddresses(m.to)
|
||||
const cc = bareAddresses(m.cc)
|
||||
const bcc = bareAddresses(m.bcc)
|
||||
if (kind !== 'security-alert' && to.addresses.length === 0) {return { ok: false, problem: 'The message has no valid recipient address.' }}
|
||||
|
||||
const text = bodyText(m.text)
|
||||
const html = bodyText(m.html)
|
||||
if (!text && !html) {return { ok: false, problem: 'The message has no text and no HTML body.' }}
|
||||
|
||||
const all = toGraphAttachments(message)
|
||||
if (all === null) {return { ok: false, problem: 'An attachment has content the mail service cannot carry (pass a Buffer or a string).' }}
|
||||
// an empty file cannot be written in the request (base64 of at least one byte) and carries nothing
|
||||
const files = all.filter((file) => file.content.length > 0)
|
||||
|
||||
const replyTo = bareAddresses(m.replyTo).addresses[0] ?? bareAddress(args.replyTo ?? '') ?? undefined
|
||||
const senderName = typeof args.senderName === 'string' ? codePoints(args.senderName.replace(UNSAFE_STRICT, ' ').replace(/ {2,}/g, ' ').trim(), 256) : ''
|
||||
|
||||
const request: RelaySendRequest = {
|
||||
kind,
|
||||
product: args.product ?? RELAY_PRODUCT,
|
||||
productVersion: args.productVersion ?? PLUGIN_VERSION,
|
||||
...(kind === 'security-alert' && !to.addresses.length ? {} : { to: to.addresses }),
|
||||
...(cc.addresses.length ? { cc: cc.addresses } : {}),
|
||||
...(bcc.addresses.length ? { bcc: bcc.addresses } : {}),
|
||||
...(replyTo ? { replyTo } : {}),
|
||||
...(senderName ? { senderName } : {}),
|
||||
subject: cleanSubject(m.subject),
|
||||
...(text ? { text } : {}),
|
||||
...(html ? { html } : {}),
|
||||
...(files.length
|
||||
? {
|
||||
attachments: files.map((file) => {
|
||||
const type = file.contentType.split(';')[0].trim()
|
||||
return {
|
||||
content: file.content.toString('base64'),
|
||||
contentType: CONTENT_TYPE.test(type) && type.length <= 127 ? type : 'application/octet-stream',
|
||||
filename: cleanFilename(file.name),
|
||||
}
|
||||
}),
|
||||
}
|
||||
: {}),
|
||||
}
|
||||
return { dropped: to.dropped + cc.dropped + bcc.dropped, ok: true, request }
|
||||
}
|
||||
@@ -0,0 +1,97 @@
|
||||
import type { BasePayload, SendEmailOptions } from 'payload'
|
||||
|
||||
import type { MailKind } from './kinds.js'
|
||||
|
||||
import { RELAY_BASE_URL } from './constants.js'
|
||||
|
||||
/**
|
||||
* `iapl({ mail: { relay } })` and `mailAdapter({ relay })`. Every key is optional; `relay: false`
|
||||
* switches the transport, the enrolment and the confirm route off.
|
||||
*/
|
||||
export type RelayOptions = {
|
||||
/**
|
||||
* "Forgot password" is a visitor's lever like a form: the service lets `account` mail use the site's
|
||||
* whole hour. So the plugin limits it itself, per address and per visitor (the request's address).
|
||||
* Default 5 per address and 10 per visitor an hour; `false` = no limit of the plugin's.
|
||||
*/
|
||||
accountMail?: { perAddress?: number; perVisitor?: number; windowMinutes?: number } | false
|
||||
/** Calls to the public confirm route per address. Default 10 a minute. */
|
||||
confirmRateLimit?: { max?: number; windowMs?: number }
|
||||
/**
|
||||
* `'auto'` (default): the site enrols by itself on the first send without a token, and again after
|
||||
* the service asks for it. `'manual'`: only "Connect" in the panel or `enrolRelay()` enrols.
|
||||
* `false`: never — the token comes from `token` or `setRelayToken()`.
|
||||
*/
|
||||
enrol?: 'auto' | 'manual' | false
|
||||
/** For tests and special networks: the `fetch` the service is called with. */
|
||||
fetchImpl?: typeof fetch
|
||||
/**
|
||||
* The site's public host, as the service calls it back (`example.com`). Default: the host of
|
||||
* `serverURL`. Enrol the host the site really answers on (no redirect is followed).
|
||||
*/
|
||||
host?: string
|
||||
/** The kind of a message that carries no mark of its own; return undefined to keep the default (`system`). */
|
||||
kind?: (message: SendEmailOptions) => MailKind | undefined
|
||||
/**
|
||||
* The wait before the next attempt when the service names none, in ms, multiplied by the attempt's
|
||||
* number. Default 1000. The ten seconds of waiting in all are not changed by it. Mostly for tests.
|
||||
*/
|
||||
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). */
|
||||
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
|
||||
/** Base address of the service. Default `https://webservices.intecion.net/mail`. A relay of your own speaks the same contract. */
|
||||
url?: string
|
||||
}
|
||||
|
||||
export type ResolvedRelayOptions = { ownUrl: boolean; url: string } & Omit<RelayOptions, 'url'>
|
||||
|
||||
type PluginMail = { graphDeprecationWarning?: boolean; relay?: false | RelayOptions }
|
||||
|
||||
/** What `iapl({ mail })` left in the config for the adapter (`config.custom.iapl.mail`). */
|
||||
export function pluginMailOptions(payload: Pick<BasePayload, 'config'>): PluginMail {
|
||||
return ((payload.config?.custom as { iapl?: { mail?: PluginMail } } | undefined)?.iapl?.mail ?? {})
|
||||
}
|
||||
|
||||
/**
|
||||
* The options in effect: the adapter's own `relay` argument over the plugin option. `null` = the relay
|
||||
* is switched off.
|
||||
*/
|
||||
export function resolveRelayOptions(payload: Pick<BasePayload, 'config'>, own?: false | RelayOptions): null | ResolvedRelayOptions {
|
||||
const fromPlugin = pluginMailOptions(payload).relay
|
||||
if (own === false || (own === undefined && fromPlugin === false)) {return null}
|
||||
const merged: RelayOptions = { ...(fromPlugin || {}), ...(own || {}) }
|
||||
const url = (merged.url ?? RELAY_BASE_URL).replace(/\/+$/, '')
|
||||
return { ...merged, ownUrl: url !== RELAY_BASE_URL, url }
|
||||
}
|
||||
|
||||
const LABEL = /^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/
|
||||
const PRIVATE_SUFFIXES = ['localhost', 'local', 'localdomain', 'internal', 'intranet', 'private', 'lan', 'home', 'corp', 'test', 'invalid', 'example', 'onion', 'arpa']
|
||||
|
||||
/** A public DNS name the service can call back: no address literal, no port, no single label, no private suffix. */
|
||||
export function isPublicHost(host: string): boolean {
|
||||
if (host.length < 4 || host.length > 253) {return false}
|
||||
const labels = host.split('.')
|
||||
if (labels.length < 2 || !labels.every((l) => LABEL.test(l)) || !/^[a-z]/.test(labels[labels.length - 1])) {return false}
|
||||
return !PRIVATE_SUFFIXES.some((s) => host === s || host.endsWith(`.${s}`))
|
||||
}
|
||||
|
||||
/**
|
||||
* The host this site enrols as: `relay.host`, else the host of `serverURL` — lowercase, punycode,
|
||||
* without scheme, path or the default port. Empty when neither is set.
|
||||
*/
|
||||
export function relayHost(payload: Pick<BasePayload, 'config'>, options: Pick<RelayOptions, 'host'>): string {
|
||||
const raw = (options.host ?? payload.config?.serverURL ?? '').trim()
|
||||
if (!raw) {return ''}
|
||||
try {
|
||||
return new URL(/^[a-z][a-z0-9+.-]*:\/\//i.test(raw) ? raw : `https://${raw}`).host.toLowerCase()
|
||||
} catch {
|
||||
return ''
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,147 @@
|
||||
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 { 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) })
|
||||
const status = options ? await getRelayStatus(payload, options, { refresh: refresh && transport === 'relay' }) : null
|
||||
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 ?? '' })
|
||||
case LOCAL_CODES.noHost:
|
||||
return serverText(i18n, 'mailRelayRefusedNoHost')
|
||||
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())
|
||||
} 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,
|
||||
},
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,237 @@
|
||||
import type { BasePayload, SendEmailOptions } from 'payload'
|
||||
|
||||
import { createHash, randomBytes } from 'node:crypto'
|
||||
|
||||
import type { ResolvedRelayOptions } from './options.js'
|
||||
|
||||
import { consumeRateLimit } from '../../shared/rateLimit.js'
|
||||
import { type RelayAnswer, type RelayRefusal, relayRequest } from './client.js'
|
||||
import { RELAY_DEFAULTS, type RelayStatusCode, relayStatusFor } from './constants.js'
|
||||
import { type MailKind, mailKindOf, takeMailContext } from './kinds.js'
|
||||
import { buildRelayMessage, type RelaySendRequest } from './message.js'
|
||||
import { LOCAL_CODES, refreshRelayStatus, rotateRelayToken, type TokenUse, withRelayToken } from './session.js'
|
||||
import { readRelayStore, sha256Hex, updateRelayStore } from './store.js'
|
||||
|
||||
export type RelaySendResult =
|
||||
| {
|
||||
/** The service's code, or one of this client's (`client-…`). */
|
||||
cause: string
|
||||
/** A status code for `emailStatus` (RELAY_STATUS_CODES). */
|
||||
code: RelayStatusCode
|
||||
/**
|
||||
* `false`: the message MAY have been sent — the service gave no answer, or cannot say yet. Send
|
||||
* the same message again and this client uses the same key and bytes, so no second mail can go out.
|
||||
*/
|
||||
confirmed: boolean
|
||||
/** For the panel status and the log. English; never shown to a visitor. */
|
||||
detail: string
|
||||
error: string
|
||||
sent: false
|
||||
transport: 'relay'
|
||||
}
|
||||
| {
|
||||
/** The service's id of the message in its log. */
|
||||
id: string
|
||||
kind: MailKind
|
||||
messageId?: string
|
||||
/** true: this message had been sent before (same key and bytes); no second mail went out. */
|
||||
replayed: boolean
|
||||
/** The name the mail left under. */
|
||||
senderName: string
|
||||
sent: true
|
||||
transport: 'relay'
|
||||
warnings: string[]
|
||||
}
|
||||
|
||||
type SendBody = { id?: string; messageId?: string; replayed?: boolean; senderName?: string; warnings?: unknown }
|
||||
|
||||
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.
|
||||
*/
|
||||
const unconfirmed = new Map<string, { at: number; key: string }>()
|
||||
const DAY = 24 * 60 * 60_000
|
||||
|
||||
function keyFor(hash: string): string {
|
||||
const now = Date.now()
|
||||
for (const [h, entry] of unconfirmed) {
|
||||
if (now - entry.at > DAY) {unconfirmed.delete(h)}
|
||||
}
|
||||
return unconfirmed.get(hash)?.key ?? randomBytes(24).toString('base64url')
|
||||
}
|
||||
|
||||
/** For tests. */
|
||||
export function clearUnconfirmedRelayMessages(): void {
|
||||
unconfirmed.clear()
|
||||
}
|
||||
|
||||
const failure = (code: RelayStatusCode, cause: string, detail: string, confirmed = true): { sent: false } & RelaySendResult => ({
|
||||
cause,
|
||||
code,
|
||||
confirmed,
|
||||
detail,
|
||||
error: confirmed ? 'The e-mail was not sent.' : 'The e-mail may not have been sent: the mail service did not confirm it.',
|
||||
sent: false,
|
||||
transport: 'relay',
|
||||
})
|
||||
|
||||
function describeRefusal(answer: RelayRefusal): { sent: false } & RelaySendResult {
|
||||
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)}
|
||||
// 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') {
|
||||
return failure('relay-refused', answer.code, `${said} If the site serves its API at another path, ask Intecion to set this site's confirm address.`)
|
||||
}
|
||||
if (answer.code === 'invalid-token' || answer.code === 'reverify') {return failure('relay-refused', answer.code, said)}
|
||||
const status = relayStatusFor(answer.code, answer.retryable)
|
||||
// The mail back end failed without saying whether the message can still go out.
|
||||
if (status === 'relay-unreachable' && !['enrolment-in-progress', 'rate-limited', 'unavailable'].includes(answer.code)) {
|
||||
return failure(status, answer.code, `Probably not sent. ${said}`)
|
||||
}
|
||||
return failure(status, answer.code, said)
|
||||
}
|
||||
|
||||
export type RelaySendContext = {
|
||||
/** The panel's "Sender address": where replies go when the message names no reply address. */
|
||||
replyTo?: null | string
|
||||
/** The panel's "Sender name", else the site name. */
|
||||
senderName?: null | string
|
||||
}
|
||||
|
||||
/**
|
||||
* One message through the service. Never throws.
|
||||
*
|
||||
* The message is encoded ONCE and exactly those bytes go out on every attempt, under one
|
||||
* `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.
|
||||
*/
|
||||
export async function sendThroughRelay(payload: BasePayload, options: ResolvedRelayOptions, message: SendEmailOptions, context: RelaySendContext = {}): Promise<RelaySendResult> {
|
||||
const marked = takeMailContext()
|
||||
const kind = mailKindOf(message) ?? marked?.kind ?? options.kind?.(message) ?? 'system'
|
||||
|
||||
const built = buildRelayMessage(message, { kind, replyTo: context.replyTo, senderName: context.senderName })
|
||||
if (!built.ok) {return failure('relay-error', 'client-invalid-message', built.problem)}
|
||||
const request: RelaySendRequest = built.request
|
||||
if (built.dropped) {payload.logger.warn(`[iapl] mail service: ${built.dropped} recipient value(s) were not e-mail addresses and were left out.`)}
|
||||
|
||||
// A visitor can ask for account mail as often as they like; the service does not limit it per address.
|
||||
if (kind === 'account' && options.accountMail !== false) {
|
||||
const own = options.accountMail ?? {}
|
||||
const windowMs = (own.windowMinutes ?? RELAY_DEFAULTS.accountMail.windowMinutes) * 60_000
|
||||
const perAddress = own.perAddress ?? RELAY_DEFAULTS.accountMail.perAddress
|
||||
const checks = [
|
||||
...(marked?.visitor ? [{ key: `visitor:${marked.visitor}`, max: own.perVisitor ?? RELAY_DEFAULTS.accountMail.perVisitor }] : []),
|
||||
...[...(request.to ?? []), ...(request.cc ?? []), ...(request.bcc ?? [])].map((address) => ({ key: `to:${sha256Hex(address.toLowerCase())}`, max: perAddress })),
|
||||
]
|
||||
for (const check of checks) {
|
||||
const { ok } = await consumeRateLimit({ ...check, scope: 'mail-relay-account', windowMs })
|
||||
if (!ok) {
|
||||
payload.logger.warn(`[iapl] mail service: an account e-mail was held back (more than ${check.max} ${check.key.startsWith('visitor:') ? 'from one visitor' : 'to one address'} in the window; mail.relay.accountMail).`)
|
||||
return failure('relay-quota', 'client-account-mail-limit', 'Too many account e-mails to one address or from one visitor; held back by the site (mail.relay.accountMail).')
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const stored = await readRelayStore(payload)
|
||||
const limits = stored.service && Date.now() - Date.parse(stored.service.fetchedAt) < RELAY_DEFAULTS.statusTtlMs ? stored.service.limits : undefined
|
||||
if (limits) {
|
||||
// What the service said within the last hour: no need to upload 10 MB to hear it again.
|
||||
const bytes = (request.attachments ?? []).reduce((sum, a) => sum + Math.floor((a.content.length * 3) / 4) - (a.content.endsWith('==') ? 2 : a.content.endsWith('=') ? 1 : 0), 0)
|
||||
if (typeof limits.maxAttachmentBytes === 'number' && bytes > limits.maxAttachmentBytes) {
|
||||
return failure('relay-too-large', 'too-large', `too-large (limit: attachments): the files are ${bytes} bytes, the mail service carries ${limits.maxAttachmentBytes}.`)
|
||||
}
|
||||
const recipients = (request.to?.length ?? 0) + (request.cc?.length ?? 0) + (request.bcc?.length ?? 0)
|
||||
if (typeof limits.recipientsPerMessage === 'number' && recipients > limits.recipientsPerMessage) {
|
||||
return failure('relay-quota', 'too-many-recipients', `too-many-recipients: ${recipients} recipients, the mail service allows ${limits.recipientsPerMessage} a message.`)
|
||||
}
|
||||
}
|
||||
|
||||
if (stored.service?.rotateAfter && Date.parse(stored.service.rotateAfter) <= Date.now()) {
|
||||
await rotateRelayToken(payload, options).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 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) {
|
||||
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 })
|
||||
},
|
||||
use,
|
||||
)
|
||||
if (answer.ok || !answer.retryable || attempts >= RELAY_DEFAULTS.attempts) {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}
|
||||
await sleep(wait)
|
||||
waited += wait
|
||||
}
|
||||
|
||||
if (answer.ok) {
|
||||
unconfirmed.delete(hash)
|
||||
const warnings = Array.isArray(answer.body.warnings) ? answer.body.warnings.filter((w): w is string => typeof w === 'string') : []
|
||||
const used = typeof answer.body.senderName === 'string' ? answer.body.senderName : ''
|
||||
const replaced = warnings.includes('sender-name-replaced')
|
||||
try {
|
||||
const now = await readRelayStore(payload)
|
||||
const known = now.nameReplaced
|
||||
const nameChanged = replaced ? known?.used !== used || known?.asked !== (request.senderName ?? '') : Boolean(known)
|
||||
if (nameChanged || now.state !== 'active' || now.refusal) {
|
||||
await updateRelayStore(payload, (current) => ({
|
||||
...current,
|
||||
nameReplaced: replaced ? { asked: request.senderName ?? '', at: new Date().toISOString(), used } : null,
|
||||
refusal: null,
|
||||
state: 'active',
|
||||
}))
|
||||
}
|
||||
if (replaced && nameChanged) {
|
||||
payload.logger.warn(`[iapl] mail service: the sender name was not accepted; the e-mail left under "${used}". Choose another name in Site integrations → E-mail sending.`)
|
||||
}
|
||||
// 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)
|
||||
}
|
||||
} catch {
|
||||
/* bookkeeping must not turn a sent mail into a failed one */
|
||||
}
|
||||
return {
|
||||
id: typeof answer.body.id === 'string' ? answer.body.id : '',
|
||||
kind,
|
||||
...(typeof answer.body.messageId === 'string' ? { messageId: answer.body.messageId } : {}),
|
||||
replayed: answer.body.replayed === true,
|
||||
senderName: used,
|
||||
sent: true,
|
||||
transport: 'relay',
|
||||
warnings,
|
||||
}
|
||||
}
|
||||
|
||||
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 })}
|
||||
else {unconfirmed.delete(hash)}
|
||||
if (answer.code === 'site-pending' || answer.code === 'site-suspended') {
|
||||
const state = answer.code === 'site-pending' ? 'pending' : 'suspended'
|
||||
if (stored.state !== state) {await updateRelayStore(payload, (current) => ({ ...current, state })).catch(() => undefined)}
|
||||
}
|
||||
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
|
||||
}
|
||||
@@ -0,0 +1,359 @@
|
||||
import type { BasePayload } from 'payload'
|
||||
|
||||
import { randomBytes } from 'node:crypto'
|
||||
|
||||
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 { isPublicHost, relayHost } from './options.js'
|
||||
import {
|
||||
clearRelayStore,
|
||||
dropRelayCandidate,
|
||||
holdNonce,
|
||||
readRelayCandidate,
|
||||
readRelayStore,
|
||||
type RelaySiteState,
|
||||
type RelayStored,
|
||||
releaseNonce,
|
||||
sha256Hex,
|
||||
updateRelayStore,
|
||||
} from './store.js'
|
||||
|
||||
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 = {
|
||||
disconnected: 'client-disconnected',
|
||||
noHost: 'client-no-host',
|
||||
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'
|
||||
: answer.code === LOCAL_CODES.noHost || answer.code === LOCAL_CODES.noToken ? '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, { force = false }: { force?: boolean } = {}): Promise<EnrolResult> {
|
||||
const running = inFlight.get(payload)
|
||||
if (running) {return running}
|
||||
const run = enrolOnce(payload, options, force).finally(() => inFlight.delete(payload))
|
||||
inFlight.set(payload, run)
|
||||
return run
|
||||
}
|
||||
|
||||
async function enrolOnce(payload: BasePayload, options: ResolvedRelayOptions, force: boolean): Promise<EnrolResult> {
|
||||
const stored = await readRelayStore(payload)
|
||||
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()) {
|
||||
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.'))
|
||||
}
|
||||
// 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.`))
|
||||
}
|
||||
|
||||
let answer: RelayAnswer<{ state?: string }> | undefined
|
||||
let nonce = ''
|
||||
for (let attempt = 0; attempt < 2; attempt++) {
|
||||
nonce = randomBytes(32).toString('base64url')
|
||||
const nonceHash = await holdNonce(payload, nonce, RELAY_DEFAULTS.nonceTtlMs)
|
||||
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: RELAY_DEFAULTS.enrolTimeoutMs,
|
||||
url: options.url,
|
||||
})
|
||||
if (answer.ok) {
|
||||
const candidate = await readRelayCandidate(payload)
|
||||
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, (current) => ({
|
||||
...current,
|
||||
disconnected: false,
|
||||
enrolledAt: new Date().toISOString(),
|
||||
host,
|
||||
refusal: null,
|
||||
source: 'enrolment',
|
||||
state,
|
||||
token: candidate.token,
|
||||
}))
|
||||
await dropRelayCandidate(payload)
|
||||
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)
|
||||
if ((now.token && now.token !== stored.token) || (await readRelayCandidate(payload))) {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, (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)
|
||||
}
|
||||
|
||||
/** 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 = { 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.
|
||||
* Any answer but `invalid-token` proves the token: a candidate then becomes the token in use.
|
||||
*/
|
||||
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 readRelayStore(payload)
|
||||
if (stored.disconnected) {return refusal(LOCAL_CODES.disconnected, 'The site was disconnected from the mail service in the panel.')}
|
||||
const candidate = await readRelayCandidate(payload)
|
||||
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.')}
|
||||
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 (!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)
|
||||
continue
|
||||
}
|
||||
const failed = await enrolNow()
|
||||
if (failed) {return use.enrolment ? failed : answer}
|
||||
continue
|
||||
}
|
||||
if (candidate) {
|
||||
// Seen accepted: this is the token now.
|
||||
await updateRelayStore(payload, (current) => ({ ...current, enrolledAt: candidate.at, host: relayHost(payload, options) || current.host, source: 'enrolment', state: candidate.state, token: candidate.token }))
|
||||
await dropRelayCandidate(payload)
|
||||
}
|
||||
if (!answer.ok && answer.code === 'reverify') {
|
||||
const failed = await enrolNow()
|
||||
if (failed) {return use.enrolment ? failed : answer}
|
||||
continue
|
||||
}
|
||||
return answer
|
||||
}
|
||||
return refusal('invalid-token', 'The mail service keeps refusing this site\'s token.')
|
||||
}
|
||||
|
||||
type StatusBody = {
|
||||
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): 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 }),
|
||||
{},
|
||||
{ first: false },
|
||||
)
|
||||
if (!answer.ok) {return { error: answer, stored: await readRelayStore(payload) }}
|
||||
const body = answer.body
|
||||
const stored = await updateRelayStore(payload, (current) => ({
|
||||
...current,
|
||||
service: {
|
||||
name: body.service?.name,
|
||||
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 }
|
||||
}
|
||||
|
||||
/**
|
||||
* 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 }: { force?: boolean } = {}): Promise<'failed' | 'not-due' | 'rotated'> {
|
||||
const stored = await readRelayStore(payload)
|
||||
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 })
|
||||
if (answer.ok && typeof answer.body.token === 'string' && answer.body.token) {
|
||||
const fresh = answer.body.token
|
||||
await updateRelayStore(payload, (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)
|
||||
// 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, (current) => ({ ...current, service: null, token: undefined }))}
|
||||
return 'failed'
|
||||
}
|
||||
// Asked once; not again before the status has been read anew.
|
||||
await updateRelayStore(payload, (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. */
|
||||
export async function disconnectRelay(payload: BasePayload, options: ResolvedRelayOptions): Promise<void> {
|
||||
const stored = await readRelayStore(payload)
|
||||
if (stored.token && options.token === undefined) {
|
||||
await relayRequest({ fetchImpl: options.fetchImpl, method: 'POST', path: '/v1/revoke', token: stored.token, url: options.url })
|
||||
}
|
||||
await clearRelayStore(payload, { disconnected: 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).')}
|
||||
await dropRelayCandidate(payload)
|
||||
await updateRelayStore(payload, (current) => ({
|
||||
...current,
|
||||
disconnected: false,
|
||||
enrolledAt: new Date().toISOString(),
|
||||
...(options.host ? { host: options.host } : {}),
|
||||
refusal: null,
|
||||
service: null,
|
||||
source: 'manual',
|
||||
state: current.state ?? 'active',
|
||||
token,
|
||||
}))
|
||||
}
|
||||
|
||||
/** What the panel and the doctor may know: never the token. */
|
||||
export type RelayStatus = {
|
||||
connected: boolean
|
||||
disconnected: boolean
|
||||
host: 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 }
|
||||
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),
|
||||
disconnected: Boolean(stored.disconnected),
|
||||
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 readRelayStore(payload))}
|
||||
const { error, stored } = await refreshRelayStatus(payload, options)
|
||||
return { ...describeRelayStore(payload, options, stored), ...(error && error.code !== LOCAL_CODES.noToken ? { error: error.code } : {}) }
|
||||
}
|
||||
|
||||
export { sha256Hex }
|
||||
@@ -0,0 +1,140 @@
|
||||
import type { BasePayload } from 'payload'
|
||||
|
||||
import { createHash, timingSafeEqual } from 'node:crypto'
|
||||
|
||||
import { RELAY_KV_KEY } from './constants.js'
|
||||
|
||||
/**
|
||||
* Where the site keeps its token: Payload's key-value store (`payload.kv`, the `payload-kv` collection
|
||||
* Payload itself adds — no field, no column, no migration of ours). That collection refuses every
|
||||
* operation through access control and is hidden in the panel, so the token cannot be read over REST
|
||||
* or GraphQL (test/mailRelayHttp.test.ts proves it). The token is never logged and never sent to a browser.
|
||||
*
|
||||
* Three entries:
|
||||
* - `iapl:mail-relay` the token in use, the site's state, what the service last reported;
|
||||
* - `iapl:mail-relay:candidate` a token the service delivered that has not been seen accepted yet;
|
||||
* - `iapl:mail-relay:nonce:<hash>` an enrolment this site started (5 minutes, single use).
|
||||
* The confirm route writes only the candidate and deletes only its nonce, so it can never overwrite a
|
||||
* working token.
|
||||
*/
|
||||
|
||||
export type RelaySiteState = 'active' | 'pending' | 'suspended'
|
||||
|
||||
export type RelayLimits = {
|
||||
maxAttachmentBytes?: number
|
||||
maxAttachments?: number
|
||||
maxBodyBytes?: number
|
||||
messagesPerDay?: number
|
||||
messagesPerHour?: number
|
||||
recipientsPerMessage?: number
|
||||
}
|
||||
|
||||
export type RelayStored = {
|
||||
/** An admin pressed "Disconnect": no send and no enrolment until "Connect again". */
|
||||
disconnected?: boolean
|
||||
enrolledAt?: string
|
||||
/** The host the token was issued for. */
|
||||
host?: string
|
||||
/** 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
|
||||
/** What `/v1/status` last said. */
|
||||
service?: {
|
||||
contract?: string
|
||||
fetchedAt: string
|
||||
limits?: RelayLimits
|
||||
name?: string
|
||||
quota?: { day?: { limit: number; remaining: number }; hour?: { limit: number; remaining: number } }
|
||||
rotateAfter?: string
|
||||
senderAddress?: string
|
||||
} | null
|
||||
/** `enrolment`: by the call-back. `manual`: issued by Intecion and stored by hand. `rotation`: from /v1/rotate. */
|
||||
source?: 'enrolment' | 'manual' | 'rotation'
|
||||
state?: RelaySiteState
|
||||
token?: string
|
||||
v: 1
|
||||
}
|
||||
|
||||
export type RelayCandidate = { at: string; nonceHash: string; state: RelaySiteState; token: string }
|
||||
|
||||
type KV = { delete: (key: string) => Promise<void>; get: (key: string) => Promise<unknown>; set: (key: string, value: object) => Promise<void> }
|
||||
|
||||
/** Without `payload.kv` (a Payload older than the store, or a test double): this process only. */
|
||||
const memory = new WeakMap<object, Map<string, unknown>>()
|
||||
let warnedNoStore = false
|
||||
|
||||
function kvOf(payload: BasePayload): KV {
|
||||
const kv = (payload as { kv?: Partial<KV> }).kv
|
||||
if (typeof kv?.get === 'function' && typeof kv?.set === 'function' && typeof kv?.delete === 'function') {return kv as KV}
|
||||
if (!warnedNoStore) {
|
||||
warnedNoStore = true
|
||||
payload.logger?.warn?.('[iapl] mail service: this Payload has no key-value store (payload.kv); the token is kept in memory and is lost on restart.')
|
||||
}
|
||||
let map = memory.get(payload)
|
||||
if (!map) {
|
||||
map = new Map()
|
||||
memory.set(payload, map)
|
||||
}
|
||||
const held = map
|
||||
return {
|
||||
delete: (key) => Promise.resolve(void held.delete(key)),
|
||||
get: (key) => Promise.resolve(held.get(key) ?? null),
|
||||
set: (key, value) => Promise.resolve(void held.set(key, structuredClone(value))),
|
||||
}
|
||||
}
|
||||
|
||||
export const sha256Hex = (text: string) => createHash('sha256').update(text, 'utf8').digest('hex')
|
||||
|
||||
const CANDIDATE_KEY = `${RELAY_KV_KEY}:candidate`
|
||||
const nonceKey = (nonceHash: string) => `${RELAY_KV_KEY}:nonce:${nonceHash}`
|
||||
|
||||
export async function readRelayStore(payload: BasePayload): Promise<RelayStored> {
|
||||
const value = (await kvOf(payload).get(RELAY_KV_KEY)) as null | RelayStored
|
||||
return value && typeof value === 'object' ? { ...value, v: 1 } : { v: 1 }
|
||||
}
|
||||
|
||||
/** Reads the entry again, applies `change` and writes it: the smallest window for two writers. */
|
||||
export async function updateRelayStore(payload: BasePayload, change: (current: RelayStored) => RelayStored): Promise<RelayStored> {
|
||||
const next = change(await readRelayStore(payload))
|
||||
await kvOf(payload).set(RELAY_KV_KEY, next)
|
||||
return next
|
||||
}
|
||||
|
||||
/** Forgets the token and everything known about the service (keeps nothing). */
|
||||
export async function clearRelayStore(payload: BasePayload, keep: Pick<RelayStored, 'disconnected'> = {}): Promise<void> {
|
||||
const kv = kvOf(payload)
|
||||
await kv.delete(CANDIDATE_KEY)
|
||||
if (keep.disconnected) {await kv.set(RELAY_KV_KEY, { disconnected: true, v: 1 } satisfies RelayStored)}
|
||||
else {await kv.delete(RELAY_KV_KEY)}
|
||||
}
|
||||
|
||||
export async function readRelayCandidate(payload: BasePayload): Promise<null | RelayCandidate> {
|
||||
const value = (await kvOf(payload).get(CANDIDATE_KEY)) as null | RelayCandidate
|
||||
return value && typeof value.token === 'string' ? value : null
|
||||
}
|
||||
|
||||
export const writeRelayCandidate = (payload: BasePayload, candidate: RelayCandidate) => kvOf(payload).set(CANDIDATE_KEY, candidate)
|
||||
export const dropRelayCandidate = (payload: BasePayload) => kvOf(payload).delete(CANDIDATE_KEY)
|
||||
|
||||
/** Remembers that this site started an enrolment with `nonce`. Only its hash is stored. */
|
||||
export async function holdNonce(payload: BasePayload, nonce: string, ttlMs: number): Promise<string> {
|
||||
const nonceHash = sha256Hex(nonce)
|
||||
await kvOf(payload).set(nonceKey(nonceHash), { expiresAt: Date.now() + ttlMs, hash: nonceHash })
|
||||
return nonceHash
|
||||
}
|
||||
|
||||
/** True when this site holds `nonce` and it has not expired. Single use: the entry is gone afterwards. */
|
||||
export async function takeNonce(payload: BasePayload, nonce: string): Promise<boolean> {
|
||||
const kv = kvOf(payload)
|
||||
const nonceHash = sha256Hex(nonce)
|
||||
const key = nonceKey(nonceHash)
|
||||
// Found by the hash of the nonce (a look-up tells nothing about the nonce itself), then compared in constant time.
|
||||
const held = (await kv.get(key)) as { expiresAt?: number; hash?: string } | null
|
||||
if (!held || typeof held.hash !== 'string' || held.hash.length !== nonceHash.length) {return false}
|
||||
if (!timingSafeEqual(Buffer.from(held.hash), Buffer.from(nonceHash))) {return false}
|
||||
await kv.delete(key)
|
||||
return typeof held.expiresAt === 'number' && held.expiresAt > Date.now()
|
||||
}
|
||||
|
||||
export const releaseNonce = (payload: BasePayload, nonce: string) => kvOf(payload).delete(nonceKey(sha256Hex(nonce)))
|
||||
@@ -3,7 +3,8 @@ import type { Endpoint, PayloadRequest } from 'payload'
|
||||
import { addDataAndFileToRequest } from 'payload'
|
||||
|
||||
import { userMeetsRole } from '../../access/predicates.js'
|
||||
import { serverText } from '../../integrations/texts.js'
|
||||
import { serverText, STATUS_CODE_TEXTS } from '../../integrations/texts.js'
|
||||
import { withMailKind } from '../relay/kinds.js'
|
||||
|
||||
/**
|
||||
* Custom endpoint: send a test email to a given address through whatever
|
||||
@@ -64,7 +65,7 @@ export const testEmailEndpoint: Endpoint = {
|
||||
const text = site ? serverText(i18n, 'testEmailBody', { site }) : serverText(i18n, 'testEmailBodyGeneric')
|
||||
|
||||
try {
|
||||
const info = await req.payload.sendEmail({
|
||||
const info = await req.payload.sendEmail(withMailKind({
|
||||
...(attachmentMB
|
||||
? { attachments: [{ content: Buffer.alloc(attachmentMB * 1024 * 1024, 'IAPL test file\n'), contentType: 'text/plain', filename: `test-${attachmentMB}MB.txt` }] }
|
||||
: {}),
|
||||
@@ -72,7 +73,7 @@ export const testEmailEndpoint: Endpoint = {
|
||||
subject,
|
||||
text,
|
||||
to,
|
||||
})
|
||||
}, 'test'))
|
||||
|
||||
// Payload's sendEmail resolves with the adapter's result. Our adapters
|
||||
// return { sent: boolean, error?: string, code?: string }; nodemailer
|
||||
@@ -83,16 +84,28 @@ export const testEmailEndpoint: Endpoint = {
|
||||
: true
|
||||
|
||||
if (!sent) {
|
||||
const failed = info as { code?: string; detail?: string; error?: string }
|
||||
const failed = info as { code?: string; confirmed?: boolean; detail?: string; error?: string }
|
||||
req.payload.logger.error(`[iapl] Test email not sent: ${failed?.detail ?? failed?.error ?? 'unknown reason'}`)
|
||||
const relayText = failed?.code ? STATUS_CODE_TEXTS[failed.code] : undefined
|
||||
const error =
|
||||
failed?.code === 'not-configured'
|
||||
? serverText(i18n, 'testEmailNotConfigured')
|
||||
: serverText(i18n, 'testEmailFailed')
|
||||
return Response.json({ error, ok: false }, { status: 502 })
|
||||
: failed?.confirmed === false
|
||||
? serverText(i18n, 'testEmailNotConfirmed')
|
||||
// the mail service's refusal in the admin's language (waiting for approval, a limit, too large …)
|
||||
: failed?.code?.startsWith('relay-') && relayText
|
||||
? serverText(i18n, relayText)
|
||||
: serverText(i18n, 'testEmailFailed')
|
||||
return Response.json({ code: failed?.code, error, ok: false }, { status: 502 })
|
||||
}
|
||||
|
||||
return Response.json({ message: serverText(i18n, 'testEmailSent', { to }), ok: true })
|
||||
// The answer names the transport that carried it.
|
||||
const sentBy = info as { senderName?: string; transport?: string } | null
|
||||
const message =
|
||||
sentBy?.transport === 'relay' ? serverText(i18n, 'testEmailSentRelay', { name: sentBy.senderName ?? '', to })
|
||||
: sentBy?.transport === 'smtp' ? serverText(i18n, 'testEmailSentSmtp', { to })
|
||||
: serverText(i18n, 'testEmailSent', { to })
|
||||
return Response.json({ message, ok: true, ...(sentBy?.transport ? { transport: sentBy.transport } : {}) })
|
||||
} catch (err) {
|
||||
const message = err instanceof Error ? err.message : String(err)
|
||||
req.payload.logger.error(`[iapl] Test email failed: ${message}`)
|
||||
|
||||
@@ -4,6 +4,7 @@ import type { BasePayload } from 'payload'
|
||||
import type { FormAttachmentsOption } from './config.js'
|
||||
import type { AcceptedFormFile } from './fileGate.js'
|
||||
|
||||
import { mailKindOf, withMailKind } from '../../email/relay/kinds.js'
|
||||
import { formatFileSize } from './fileTypes.js'
|
||||
|
||||
/**
|
||||
@@ -121,6 +122,25 @@ export function buildFileNoticeHook({ formsSlug = 'forms', notice }: { formsSlug
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Says what each e-mail of a form is, for a transport that asks (the Intecion mail service limits the
|
||||
* two kinds differently): `form-notification` when EVERY recipient is an address written in the
|
||||
* panel, `form-confirmation` otherwise — it goes to an address a visitor typed. An e-mail the
|
||||
* project's own `beforeEmail` already marked keeps its mark; when the form cannot be read the purpose
|
||||
* is not known (`system`). Other transports ignore the mark.
|
||||
*/
|
||||
export function buildFormMailKindHook({ formsSlug = 'forms' }: { formsSlug?: string } = {}): BeforeEmail {
|
||||
return async (emails, args) => {
|
||||
let fixed: null | Set<string> = null
|
||||
try {
|
||||
fixed = await loadFixed(args, formsSlug)
|
||||
} catch {
|
||||
/* unknown purpose below */
|
||||
}
|
||||
return emails.map((email) => (mailKindOf(email) ? email : withMailKind(email, !fixed ? 'system' : mayCarryFiles(email, fixed) ? 'form-notification' : 'form-confirmation')))
|
||||
}
|
||||
}
|
||||
|
||||
type SendOutcome = { detail?: string; ok: boolean }
|
||||
|
||||
/** One send through the project's adapter. mailAdapter reports failure as `{ sent: false }`; others throw. */
|
||||
|
||||
@@ -8,7 +8,7 @@ import type { FormsOption } from './types.js'
|
||||
|
||||
import { userMeetsRole } from '../access/predicates.js'
|
||||
import { resolveFormAttachments } from './attachments/config.js'
|
||||
import { buildFileDeliveryHook, buildFileNoticeHook } from './attachments/delivery.js'
|
||||
import { buildFileDeliveryHook, buildFileNoticeHook, buildFormMailKindHook } from './attachments/delivery.js'
|
||||
import { buildFormSubmitEndpoint } from './attachments/endpoint.js'
|
||||
import { buildFileBlock } from './attachments/fileBlock.js'
|
||||
import { buildFormFilesAfterRead, buildFormFilesBeforeValidate, submissionFileFields } from './attachments/formHooks.js'
|
||||
@@ -218,19 +218,20 @@ export function buildFormsPlugin(forms: FormsOption): Plugin {
|
||||
const attachments = forms.attachments ? resolveFormAttachments(forms.attachments) : null
|
||||
const fileNotice = attachments ? buildFileNoticeHook({ formsSlug, notice: attachments.notice }) : undefined
|
||||
const fileDelivery = attachments ? buildFileDeliveryHook({ formsSlug }) : undefined
|
||||
const beforeEmail: BeforeEmail | undefined =
|
||||
layout || forms.beforeEmail || attachments
|
||||
? async (emails, args) => {
|
||||
const noticed = fileNotice ? await fileNotice(emails, args) : emails
|
||||
const laidOut = layout ? await layout(noticed, args) : noticed
|
||||
const changed = forms.beforeEmail ? await Promise.resolve(forms.beforeEmail(laidOut, args)) : laidOut
|
||||
return fileDelivery ? fileDelivery(changed, args) : changed
|
||||
}
|
||||
: undefined
|
||||
// Every e-mail of a form says what it is (notification to the addresses written in the panel, or
|
||||
// confirmation to an address the visitor typed): the Intecion mail service limits the two differently.
|
||||
const markKinds = buildFormMailKindHook({ formsSlug })
|
||||
const beforeEmail: BeforeEmail = async (emails, args) => {
|
||||
const noticed = fileNotice ? await fileNotice(emails, args) : emails
|
||||
const laidOut = layout ? await layout(noticed, args) : noticed
|
||||
const changed = forms.beforeEmail ? await Promise.resolve(forms.beforeEmail(laidOut, args)) : laidOut
|
||||
const marked = await markKinds(changed, args)
|
||||
return fileDelivery ? fileDelivery(marked, args) : marked
|
||||
}
|
||||
const fileBlockOption = forms.fields?.file
|
||||
const formHooks = forms.formOverrides?.hooks
|
||||
const builder = formBuilderPlugin({
|
||||
...(beforeEmail ? { beforeEmail } : {}),
|
||||
beforeEmail,
|
||||
// Built-in types + ipal's `step`, `checkboxGroup` and `time` (builderBlocks). All are
|
||||
// panel choices only — a form uses what the editor adds, nothing changes on
|
||||
// existing forms. Switch any off with forms.fields.<type>: false.
|
||||
|
||||
@@ -24,6 +24,17 @@ export const STATUS_CODE_TEXTS: Record<string, AdminTextKey> = {
|
||||
'missing-input-secret': 'statusTurnstileMissingSecret',
|
||||
'missing-secret': 'statusTurnstileMissingSecret',
|
||||
'network-error': 'statusTurnstileNetworkError',
|
||||
'relay-attachment-refused': 'statusEmailRelayAttachmentRefused',
|
||||
'relay-disconnected': 'statusEmailRelayDisconnected',
|
||||
'relay-error': 'statusEmailRelayError',
|
||||
'relay-not-confirmed': 'statusEmailRelayNotConfirmed',
|
||||
'relay-pending': 'statusEmailRelayPending',
|
||||
'relay-quota': 'statusEmailRelayQuota',
|
||||
'relay-recipient-suppressed': 'statusEmailRelayRecipientSuppressed',
|
||||
'relay-refused': 'statusEmailRelayRefused',
|
||||
'relay-suspended': 'statusEmailRelaySuspended',
|
||||
'relay-too-large': 'statusEmailRelayTooLarge',
|
||||
'relay-unreachable': 'statusEmailRelayUnreachable',
|
||||
}
|
||||
|
||||
type I18nLike = { language?: string; t?: (key: never, vars?: Record<string, unknown>) => string } | undefined
|
||||
|
||||
@@ -31,6 +31,10 @@ import { mergeCookieScanLabels } from './modules/consent/scanner/labels.js'
|
||||
import { buildConstructionFields } from './modules/construction/fields.js'
|
||||
import { buildArchiveFields } from './modules/content/index.js'
|
||||
import { buildDoctorEndpoint } from './modules/doctor/status.js'
|
||||
import { GRAPH_DEPRECATION_NOTICE, graphAvailable } from './modules/email/mailAdapter.js'
|
||||
import { withAccountMailMark } from './modules/email/relay/accountMail.js'
|
||||
import { relayConfirmEndpoint } from './modules/email/relay/confirm.js'
|
||||
import { relayPanelEndpoints } from './modules/email/relay/panel.js'
|
||||
import { testEmailEndpoint } from './modules/email/test/testEmailEndpoint.js'
|
||||
import { emailSettingsFields } from './modules/forms/emailLayout.js'
|
||||
import { buildFormsPlugin } from './modules/forms/formsPluginConfig.js'
|
||||
@@ -705,6 +709,7 @@ export const iapl = (options: IaplOptions): Plugin => {
|
||||
}),
|
||||
buildSiteIntegrations({
|
||||
additionalFields: options.integrationsFields,
|
||||
mailRelay: options.mail?.relay !== false,
|
||||
reenterSecretOnChange: options.secrets?.reenterOnChange !== false,
|
||||
writeOnlySecrets: options.secrets?.writeOnly !== false,
|
||||
}),
|
||||
@@ -743,6 +748,22 @@ export const iapl = (options: IaplOptions): Plugin => {
|
||||
|
||||
config.endpoints = [...(config.endpoints ?? []), testEmailEndpoint]
|
||||
|
||||
// --- e-mail: the Intecion Notifications Webservice (docs/email.md; off with mail: { relay: false }) ---
|
||||
// What mailAdapter() reads at send time; born under the new name (`custom.iapl`).
|
||||
const relay = options.mail?.relay
|
||||
const iaplCustom = (config.custom?.iapl ?? {}) as object
|
||||
config.custom = {
|
||||
...config.custom,
|
||||
iapl: { ...iaplCustom, mail: { ...(options.mail?.graphDeprecationWarning === false ? { graphDeprecationWarning: false } : {}), relay: relay === false ? false : (relay ?? {}) } },
|
||||
}
|
||||
if (relay !== false) {
|
||||
// The public route the service calls a site back at (404 unless this site just started an
|
||||
// enrolment), and the admin-only routes of the state block on the e-mail tab.
|
||||
config.endpoints = [...config.endpoints, relayConfirmEndpoint(relay ?? {}), ...relayPanelEndpoints()]
|
||||
// "Forgot password" and "verify your e-mail" are Payload's own mail: say what they are.
|
||||
config.collections = (config.collections ?? []).map((c) => (c.auth ? withAccountMailMark(c) : c))
|
||||
}
|
||||
|
||||
// --- iapl-doctor status (404 until IAPL_DOCTOR_TOKEN is set; docs/doctor.md) ---
|
||||
if (options.doctor !== false) {
|
||||
config.endpoints = [...(config.endpoints ?? []), buildDoctorEndpoint(options.doctor ?? {})]
|
||||
@@ -918,6 +939,8 @@ export const iapl = (options: IaplOptions): Plugin => {
|
||||
)
|
||||
}
|
||||
adoptConfig(payload)
|
||||
// Microsoft Graph is deprecated (removed in 2.0): one warning per start while its variables are set.
|
||||
if (graphAvailable() && options.mail?.graphDeprecationWarning !== false) {payload.logger.warn(GRAPH_DEPRECATION_NOTICE)}
|
||||
// Payload's dev reload swaps `payload.config` and runs no onInit: adopt the new config at once.
|
||||
watchPayloadConfig(payload, adoptConfig)
|
||||
if (staleImportMap) {
|
||||
|
||||
+25
-1
@@ -19,6 +19,7 @@ import type { ConsentLogOptions } from './modules/consent/consentLog.js'
|
||||
import type { CookieScannerOptions } from './modules/consent/scanner/types.js'
|
||||
import type { ContentOption } from './modules/content/types.js'
|
||||
import type { DoctorEndpointOptions } from './modules/doctor/status.js'
|
||||
import type { RelayOptions } from './modules/email/relay/options.js'
|
||||
import type { FormsOption } from './modules/forms/types.js'
|
||||
import type { RevalidatePathFn } from './modules/hooks/buildRevalidateHook.js'
|
||||
import type { I18nConfig } from './modules/i18n/types.js'
|
||||
@@ -178,6 +179,22 @@ export type IaplOptions = {
|
||||
*/
|
||||
lightbox?: boolean
|
||||
|
||||
/**
|
||||
* E-mail (docs/email.md). A site with no SMTP server in Site integrations sends through the
|
||||
* Intecion Notifications Webservice: it enrols by itself on its first send (an outbound call with
|
||||
* the site's host and the plugin version) and gets its own token through the public route
|
||||
* `POST /api/iapl/mail-relay/confirm`. A site with SMTP filled in never contacts the service.
|
||||
*
|
||||
* - `relay: false` — no enrolment, no outbound call, no confirm route, no state block in the
|
||||
* panel: SMTP (or Graph) only, as before 1.17.0.
|
||||
* - `relay: { … }` — the service's address (a relay of your own), the site's host, manual
|
||||
* enrolment, a token from elsewhere, the sender name, the limit on account e-mails.
|
||||
* - `graphDeprecationWarning: false` — no start-log warning while the site still uses the
|
||||
* deprecated Microsoft Graph transport.
|
||||
* `mailAdapter({ relay })` overrides `relay` for that adapter.
|
||||
*/
|
||||
mail?: MailOptions
|
||||
|
||||
/**
|
||||
* System-page assignments (homepage, privacy, cookies) in SiteSettings.
|
||||
* Provide the slug of the client's Pages collection to enable.
|
||||
@@ -200,7 +217,6 @@ export type IaplOptions = {
|
||||
* over `seo.searchSettings`.
|
||||
*/
|
||||
searchSettings?: ((defaults: Field[]) => Field[]) | false
|
||||
|
||||
/**
|
||||
* SEO — adds meta fields to chosen collections (via @payloadcms/plugin-seo)
|
||||
* and enables locale-aware metadata helpers.
|
||||
@@ -222,6 +238,7 @@ export type IaplOptions = {
|
||||
* follows the new server. docs/security.md "Stored secrets".
|
||||
*/
|
||||
secrets?: { reenterOnChange?: false; writeOnly?: false }
|
||||
|
||||
seo?: SeoOption
|
||||
|
||||
/** Additional fields injected into SiteSettings global */
|
||||
@@ -437,3 +454,10 @@ export type ThemeOptions = {
|
||||
|
||||
/** @deprecated The name before 1.17.0; the same type as `IaplOptions`. Removed in 2.0. */
|
||||
export type IpalOptions = IaplOptions
|
||||
|
||||
export type MailOptions = {
|
||||
/** `false` silences the one warning per process start of a site on Microsoft Graph (deprecated, removed in 2.0). */
|
||||
graphDeprecationWarning?: boolean
|
||||
/** The Intecion Notifications Webservice. Default on; `false` switches it off. */
|
||||
relay?: false | RelayOptions
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user