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 = { /** * 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 example * `['*.dev.example-agency.pl']`. A site on such a host is treated as a non-public copy for `otherHosts`, * exactly like a site with `IAPL_NOINDEX=1`. Nothing is built in: name the agency's own pattern here. */ 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 (`IAPL_NOINDEX=1`, or a host in `developmentHosts`) 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 | 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 /** * 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 = { ownUrl: boolean; url: string } & Omit 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): 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, 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, options: Pick): 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 '' } }