Files
ipal-kit/src/modules/email/relay/options.ts
T
Radosław SmolińskiandClaude Fable 5.2 6c4e244094 Development hosts, review V-1 to V-3: a malformed list stops the start, a trailing dot and Unicode patterns match, every send reads the store
- V-1: assertDevelopmentHosts - iapl({ developmentHosts }), mail.relay.developmentHosts and
  mailAdapter({ relay }) refuse anything but an array of non-empty host patterns, and a pattern of `*` alone
  (it would make the public site a development address). Nothing is ignored silently any more.
- V-2: one trailing dot of the host is stripped before matching; patterns are punycoded, so one written in
  Unicode matches; a `*` inside a non-ASCII label is refused.
- V-3: the 30-second memory of other hosts is gone. A dump restored into a running development site stops
  its very next e-mail.
- docs, AGENT.md, changelog draft, skills

Co-Authored-By: Claude Fable 5.2 <[email protected]>
2026-11-26 10:57:32 +01:00

146 lines
8.3 KiB
TypeScript

import type { BasePayload, SendEmailOptions } from 'payload'
import type { MailKind } from './kinds.js'
import { assertDevelopmentHosts, DEFAULT_DEVELOPMENT_HOSTS } from '../../shared/developmentHosts.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 = {
/**
* Show "Enter an access key" in the panel's state block, and let its route store a token an admin pastes.
* Default `false`: a token issued by hand (for a site the service cannot call back) is set by a developer —
* `setRelayToken(payload, token)` in a script, or `token` below. `true` gives admins the field. Either way a
* token of another site is refused.
*/
accessKeyField?: boolean
/**
* "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 }
/**
* Host patterns of development and preview addresses (`*` = any characters), for the mail service only.
* Default: the plugin's list — `iapl({ developmentHosts })`, which itself defaults to
* `DEFAULT_DEVELOPMENT_HOSTS` (`['*.dev.netscale.pl']`, Intecion's own development domain). A site on such a
* host is treated as a non-public copy for `otherHosts`, exactly like a site with `IAPL_NOINDEX=1`; no
* environment variable is needed. `[]` = no host is a development address.
*/
developmentHosts?: string[]
/**
* `'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
/**
* What a site does when its database holds the connection of ANOTHER host — a launch (the development
* address's entry is still there), a moved domain, or a copy of another site's database.
*
* Default (`'auto'`): by direction. A **public** site enrols by itself — launch day and a domain move need
* nobody. A **non-public** site (a host in `developmentHosts`, or `IAPL_NOINDEX=1`) that finds another
* host's connection it was never told about is a copy of that site's data: it does not enrol and does not
* send by itself (it would mail real people), until an admin presses "Connect again".
*
* `'wait'`: every site waits for "Connect again" when it has no connection of its own (the rule of the
* first cut). `'enrol'`: no rule at all. A list: these hosts are this site's own (never "another host").
* `www.` and the bare domain are always one site; a site with an empty store always enrols by itself.
*/
otherHosts?: 'auto' | 'enrol' | 'wait' | string[]
/**
* 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); never more than what is left of `totalTimeoutMs`. */
timeoutMs?: number
/**
* A token from elsewhere (a relay of your own, or a secret of your deployment). When set, the stored
* token is not used and the site does not enrol.
*/
token?: (() => Promise<string | undefined> | string | undefined) | string
/**
* Everything one message may take, in ms — enrolment, attempts and waits together. Default 10 000, and
* 30 000 for a message with files. A form's visitor waits for the mail, so a service that hangs must not
* hold the request for the sum of the attempts. After it the message is reported ("not confirmed" when an
* attempt was cut off). `{ plain, files }` sets the two apart; a job that nobody waits for may raise it.
*/
totalTimeoutMs?: { files?: number; plain?: number } | number
/** Base address of the service. Default `https://webservices.intecion.net/mail`. A relay of your own speaks the same contract. */
url?: string
}
export type ResolvedRelayOptions = { developmentHosts: string[]; ownUrl: boolean; url: string } & Omit<RelayOptions, 'developmentHosts' | '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 plugin's development-host patterns: `iapl({ developmentHosts })` as left in the config
* (`config.custom.iapl.developmentHosts`), else the built-in list.
*/
export function pluginDevelopmentHosts(payload: Pick<BasePayload, 'config'>): string[] {
const own = (payload.config?.custom as { iapl?: { developmentHosts?: unknown } } | undefined)?.iapl?.developmentHosts
// (written by iapl(), which refuses a malformed list; a value put here by hand is checked the same way)
return own === undefined ? [...DEFAULT_DEVELOPMENT_HOSTS] : assertDevelopmentHosts(own, 'config.custom.iapl.developmentHosts')
}
/**
* 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 || {}) }
if (merged.developmentHosts !== undefined) {assertDevelopmentHosts(merged.developmentHosts, 'mail.relay.developmentHosts')}
const url = (merged.url ?? RELAY_BASE_URL).replace(/\/+$/, '')
return { ...merged, developmentHosts: merged.developmentHosts ?? pluginDevelopmentHosts(payload), 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 ''
}
}