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]>
This commit is contained in:
Radosław Smoliński
2026-11-26 10:57:32 +01:00
co-authored by Claude Fable 5.2
parent 99c73ed0ff
commit 6c4e244094
18 changed files with 135 additions and 46 deletions
+1 -1
View File
@@ -519,7 +519,7 @@ export type { SitemapRouteOptions, SitemapStyleOptions } from './modules/seo/ind
export { applyCollectionOverride } from './modules/shared/collectionOverride.js'
export type { CollectionOverride } from './modules/shared/collectionOverride.js'
// Development addresses by pattern (no env): the built-in list and the matcher behind `developmentHosts`.
export { DEFAULT_DEVELOPMENT_HOSTS, isDevelopmentHost, matchDevelopmentHost } from './modules/shared/developmentHosts.js'
export { assertDevelopmentHosts, DEFAULT_DEVELOPMENT_HOSTS, isDevelopmentHost, matchDevelopmentHost } from './modules/shared/developmentHosts.js'
export { clientIp, setRateLimitStore, setUnknownIpFactor, UNKNOWN_IP_FACTOR } from './modules/shared/rateLimit.js'
export type { ClientIpOptions, RateLimitStore } from './modules/shared/rateLimit.js'
export { buildSlugField, toSlug } from './modules/slug/index.js'
+3
View File
@@ -2,6 +2,7 @@ import type { PayloadEmailAdapter, SendEmailOptions } from 'payload'
import { type IntegrationStatus, recordIntegrationStatus } from '../integrations/status.js'
import { getSiteIntegrations } from '../payload/index.js'
import { assertDevelopmentHosts } from '../shared/developmentHosts.js'
import { sendAccountMailAfterCommit } from './accountMailAfterCommit.js'
import { graphAdapter, type GraphAdapterArgs, graphLargeAttachmentSupport } from './graphAdapter.js'
import { attachmentBytes, GRAPH_INLINE_MAX_BYTES, toGraphAttachments } from './graphAttachments.js'
@@ -112,6 +113,8 @@ export function graphAvailable(): boolean {
export const mailAdapter =
(args: MailAdapterArgs = {}): PayloadEmailAdapter =>
(deps) => {
// a malformed list must stop the start, not be found at the first e-mail of a copy
if (args.relay && args.relay.developmentHosts !== undefined) {assertDevelopmentHosts(args.relay.developmentHosts, 'mailAdapter({ relay: { developmentHosts } })')}
// Build both delegates once; each still resolves its own config per send.
const smtp = panelSmtpAdapter({
fallbackFromAddress: args.fallbackFromAddress,
+4 -2
View File
@@ -2,7 +2,7 @@ import type { BasePayload, SendEmailOptions } from 'payload'
import type { MailKind } from './kinds.js'
import { DEFAULT_DEVELOPMENT_HOSTS } from '../../shared/developmentHosts.js'
import { assertDevelopmentHosts, DEFAULT_DEVELOPMENT_HOSTS } from '../../shared/developmentHosts.js'
import { RELAY_BASE_URL } from './constants.js'
/**
@@ -102,7 +102,8 @@ export function pluginMailOptions(payload: Pick<BasePayload, 'config'>): PluginM
*/
export function pluginDevelopmentHosts(payload: Pick<BasePayload, 'config'>): string[] {
const own = (payload.config?.custom as { iapl?: { developmentHosts?: unknown } } | undefined)?.iapl?.developmentHosts
return Array.isArray(own) ? own.filter((p): p is string => typeof p === 'string') : [...DEFAULT_DEVELOPMENT_HOSTS]
// (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')
}
/**
@@ -113,6 +114,7 @@ export function resolveRelayOptions(payload: Pick<BasePayload, 'config'>, own?:
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 }
}
+4 -24
View File
@@ -77,23 +77,6 @@ export function enrolRelay(payload: BasePayload, options: ResolvedRelayOptions,
return run
}
/** Short memory of which other hosts have an entry: a non-public site asks on every send. Per Payload instance. */
const otherHostsSeen = new WeakMap<object, { at: number; host: string; hosts: string[] }>()
const OTHER_HOSTS_TTL_MS = 30_000
/** For tests, and after this site's own connection changed. */
export function forgetOtherHosts(payload?: object): void {
if (payload) {otherHostsSeen.delete(payload)}
}
async function otherHostsNow(payload: BasePayload, host: string, fresh: boolean): Promise<string[]> {
const seen = otherHostsSeen.get(payload)
if (!fresh && seen && seen.host === host && Date.now() - seen.at < OTHER_HOSTS_TTL_MS) {return seen.hosts}
const hosts = await otherRelayHosts(payload, host)
otherHostsSeen.set(payload, { at: Date.now(), host, hosts })
return hosts
}
const bare = (host: string) => host.trim().toLowerCase().replace(/^www\./, '')
/** Why a site counts as non-public: its host matches a development pattern, or `IAPL_NOINDEX` is set. */
@@ -125,13 +108,12 @@ export function siteIsNonPublic(payload: BasePayload, options: Pick<RelayOptions
* told about holds a copy of that site's data. Also when it has a token of its own: production's
* database copied BACK onto the development address brings the development site's old entry with it.
* Hosts the project named as its own, and hosts an admin accepted with "Connect again", do not count.
* `fresh`: read the store now (an enrolment); otherwise what was seen in the last half minute.
* Always read from the store now: a restored dump must stop the very next e-mail, not one half a minute later.
*/
export async function otherHostsInTheWay(
payload: BasePayload,
options: Pick<ResolvedRelayOptions, 'developmentHosts' | 'host' | 'otherHosts'>,
stored: RelayStored,
{ fresh = true }: { fresh?: boolean } = {},
): Promise<string[]> {
const mode = options.otherHosts
if (mode === 'enrol') {return []}
@@ -139,7 +121,7 @@ export async function otherHostsInTheWay(
if (mode === 'wait' && connected) {return []}
if (mode !== 'wait' && !siteIsNonPublic(payload, options)) {return []}
const own = [...(Array.isArray(mode) ? mode : []), ...(stored.acceptedHosts ?? [])].map(bare)
return (await otherHostsNow(payload, relayHost(payload, options), fresh)).filter((h) => !own.includes(bare(h)))
return (await otherRelayHosts(payload, relayHost(payload, options))).filter((h) => !own.includes(bare(h)))
}
const otherHostMessage = (host: string, foreign: string[]) =>
@@ -168,7 +150,7 @@ async function enrolOnce(payload: BasePayload, options: ResolvedRelayOptions, fo
// A copy of another site's database does not enrol BY ITSELF (otherHostsInTheWay): with that site's data it
// would mail real people. An admin's "Connect again" (`force`) does, and the hosts found then are accepted.
const others = force ? await otherHostsNow(payload, host, true) : []
const others = force ? await otherRelayHosts(payload, host) : []
const foreign = force ? [] : await otherHostsInTheWay(payload, options, stored)
if (foreign.length) {
const message = otherHostMessage(host, foreign)
@@ -215,7 +197,6 @@ async function enrolOnce(payload: BasePayload, options: ResolvedRelayOptions, fo
token: candidate.token,
}))
await dropRelayCandidate(payload, options)
forgetOtherHosts(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.
@@ -310,7 +291,7 @@ export async function withRelayToken<T>(
const token = candidate?.token ?? stored.token
// A non-public copy holding another site's data does not SEND by itself either, token or not.
if (token && round === 0) {
const foreign = await otherHostsInTheWay(payload, options, stored, { fresh: false })
const foreign = await otherHostsInTheWay(payload, options, stored)
if (foreign.length) {return refusal(LOCAL_CODES.otherHost, otherHostMessage(relayHost(payload, options), foreign), { reason: foreign[0] })}
}
@@ -495,7 +476,6 @@ export async function setRelayToken(payload: BasePayload, token: string, options
// the entry is this site's own: `options.host`, else `mail.relay.host`, else the host of serverURL
options = { host: options.host ?? (pluginMailOptions(payload).relay || {}).host }
const others = await otherRelayHosts(payload, relayHost(payload, options))
forgetOtherHosts(payload)
await dropRelayCandidate(payload, options)
await updateRelayStore(payload, options, (current) => ({
...current,
+51 -2
View File
@@ -19,7 +19,8 @@ export function hostOf(value: null | string | undefined): string {
const raw = (value ?? '').trim()
if (!raw) {return ''}
try {
return new URL(/^[a-z][a-z0-9+.-]*:\/\//i.test(raw) ? raw : `https://${raw}`).host.toLowerCase()
// (a fully qualified name may end in a dot — `acme.dev.example.pl.` is the same host)
return new URL(/^[a-z][a-z0-9+.-]*:\/\//i.test(raw) ? raw : `https://${raw}`).host.toLowerCase().replace(/\.(?=:\d+$|$)/, '')
} catch {
return ''
}
@@ -33,12 +34,60 @@ export function matchDevelopmentHost(host: null | string | undefined, patterns:
const name = hostOf(host).replace(/:\d+$/, '')
if (!name) {return null}
for (const pattern of patterns) {
const source = pattern.trim().toLowerCase().split('*').map((part) => part.replace(/[.+?^${}()|[\]\\]/g, '\\$&')).join('.*')
// a pattern is compared the way hosts are written on the wire: lowercase, punycode, no trailing dot
const written = typeof pattern === 'string' ? (asciiPattern(pattern) ?? pattern.trim().toLowerCase()) : ''
const source = written.split('*').map((part) => part.replace(/[.+?^${}()|[\]\\]/g, '\\$&')).join('.*')
if (source && new RegExp(`^${source}$`).test(name)) {return pattern}
}
return null
}
const STAR = 'zq9star9qz'
/**
* A pattern as hosts are written: lowercase, punycode (`*.dev.zażółć.pl` → `*.dev.xn--za-….pl`), no trailing
* dot, no port. null when it is not a host pattern at all (empty, a space inside, a `*` in a label with
* non-ASCII letters, …).
*/
function asciiPattern(pattern: string): null | string {
const raw = pattern.trim().toLowerCase().replace(/\.$/, '')
if (!raw || /[\s/@?#\\]/.test(raw)) {return null}
const stars = raw.split('*').length - 1
try {
const host = new URL(`https://${raw.replaceAll('*', STAR)}`).hostname
// (a `*` inside a punycoded label would stand for nothing a person could mean)
if (host.split(STAR).length - 1 !== stars || host.split('.').some((label) => label.startsWith('xn--') && label.includes(STAR))) {return null}
return host.replaceAll(STAR, '*')
} catch {
return null
}
}
/**
* Checks a `developmentHosts` value when the project's config is built, and returns the list as given.
* Throws — the site does not start — on anything but an array of host patterns, because a list that is
* silently ignored or silently empty means a copy of production's data mails real people:
* - not an array (a single string, `null`, an object);
* - an entry that is not a non-empty string, or not a host pattern;
* - a pattern made of `*` alone (with or without dots): it would make EVERY host a development address,
* the public site included. To switch the mail rule's waiting off or on for all hosts use
* `mail.relay.otherHosts` instead.
* `[]` is valid: no host is a development address. `undefined` is not checked here (the default applies).
*/
export function assertDevelopmentHosts(value: unknown, option = 'developmentHosts'): string[] {
const fail = (why: string): never => {
throw new Error(`[iapl] ${option} must be an array of host patterns such as ['*.dev.netscale.pl'] ([] = none): ${why}. Got ${JSON.stringify(value)}.`)
}
if (!Array.isArray(value)) {return fail('it is not an array')}
value.forEach((entry, index) => {
if (typeof entry !== 'string' || !entry.trim()) {fail(`entry ${index} is not a non-empty string`)}
const written = asciiPattern(entry as string)
if (!written) {fail(`entry ${index} ("${entry}") is not a host pattern — a host name with \`*\` for any characters, no scheme, no path`)}
if (!/[^*.]/.test(written as string)) {fail(`entry ${index} ("${entry}") matches every host, so the public site would count as a development address`)}
})
return value as string[]
}
/** Is `host` a development address (`matchDevelopmentHost` as a yes or no)? */
export const isDevelopmentHost = (host: null | string | undefined, patterns: readonly string[] = DEFAULT_DEVELOPMENT_HOSTS): boolean =>
matchDevelopmentHost(host, patterns) !== null
+3 -1
View File
@@ -66,6 +66,7 @@ import { buildIndexNowHook } from './modules/seo/indexNow.js'
import { searchSettingsFields } from './modules/seo/searchSettings.js'
import { migrateTitleSeparator } from './modules/seo/titleSeparator.js'
import { applyCollectionOverride } from './modules/shared/collectionOverride.js'
import { assertDevelopmentHosts } from './modules/shared/developmentHosts.js'
import { buildStatsCollection, buildStatsEndpoint } from './modules/stats/index.js'
import { visitorCookieFor } from './modules/stats/visitorCookie.js'
@@ -753,10 +754,11 @@ export const iapl = (options: IaplOptions): Plugin => {
// --- 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
if (relay && relay.developmentHosts !== undefined) {assertDevelopmentHosts(relay.developmentHosts, 'iapl({ mail: { relay: { developmentHosts } } })')}
const iaplCustom = (config.custom?.iapl ?? {}) as object
config.custom = {
...config.custom,
iapl: { ...iaplCustom, ...(Array.isArray(options.developmentHosts) ? { developmentHosts: [...options.developmentHosts] } : {}), mail: { ...(options.mail?.graphDeprecationWarning === false ? { graphDeprecationWarning: false } : {}), relay: relay === false ? false : (relay ?? {}) } },
iapl: { ...iaplCustom, ...(options.developmentHosts !== undefined ? { developmentHosts: [...assertDevelopmentHosts(options.developmentHosts, 'iapl({ developmentHosts })')] } : {}), mail: { ...(options.mail?.graphDeprecationWarning === false ? { graphDeprecationWarning: false } : {}), relay: relay === false ? false : (relay ?? {}) } },
}
// "Forgot password" and "verify your e-mail" through mailAdapter(): sent right after their transaction
// commits, not inside it (mail.accountMailAfterCommit; docs/deployment.md §4.3a).
+3 -1
View File
@@ -140,7 +140,9 @@ export type IaplOptions = {
* matches is "non-public" with no environment variable: when its database holds the mail-service
* connection of another host (a copy of production's data), it does not mail real people by itself
* (docs/email.md "Staging, copies and several hosts"). Replace the list with your own patterns, or
* pass `[]` so that no host is a development address. Mail only: the option does not make a
* pass `[]` so that no host is a development address. Anything but an array of non-empty host
* patterns, and a pattern of `*` alone, stops the start (`assertDevelopmentHosts`); a pattern may
* be written in Unicode (it is punycoded), a trailing dot and the port are ignored. Mail only: the option does not make a
* development host noindex (that is the hosting's business, or `IAPL_NOINDEX=1`). `mail.relay.developmentHosts` overrides it
* for the mail service alone.
*/