Mail relay: launch and a domain move need no click; a non-public copy neither enrols nor sends by itself
The copy rule now goes by direction. A public site that finds another host's connection in its database (its development address after launch, its old domain after a move) enrols by itself. A site that says it is not public - IAPL_NOINDEX=1, or a host in the new mail.relay.developmentHosts - and holds another host's connection is a copy of that site's data: it neither enrols nor sends until "Connect again", also when it has a token of its own (production's database copied back onto the development address). The consent is stored with the copy (acceptedHosts), so the next fresh copy waits again. - mail.relay.otherHosts: 'auto' (default) | 'wait' | 'enrol' | list of the site's own hosts - mail.relay.developmentHosts, siteIsNonPublic() exported - the copy refusal ends when its reason does (no cool-down; the panel recomputes it on every read) - doctor: info for a public site whose database knows another host (the launched site, or a copy that forgot IAPL_NOINDEX) - contract copy 1.7.1 (wording only) - docs, AGENT.md, skills, changelog draft Co-Authored-By: Claude Fable 5.2 <[email protected]>
This commit is contained in:
co-authored by
Claude Fable 5.2
parent
acfcf72c03
commit
49927205bb
@@ -5,6 +5,7 @@ import { randomBytes } from 'node:crypto'
|
||||
import type { ResolvedRelayOptions } from './options.js'
|
||||
|
||||
import { PLUGIN_VERSION } from '../../../version.js'
|
||||
import { isSiteNoindex } from '../../seo/siteNoindex.js'
|
||||
import { type RelayAnswer, type RelayRefusal, relayRequest } from './client.js'
|
||||
import { RELAY_CONFIRM_PATH, RELAY_DEFAULTS, RELAY_PRODUCT, type RelayStatusCode, relayStatusFor } from './constants.js'
|
||||
import { isPublicHost, pluginMailOptions, relayHost } from './options.js'
|
||||
@@ -75,20 +76,72 @@ export function enrolRelay(payload: BasePayload, options: ResolvedRelayOptions,
|
||||
return run
|
||||
}
|
||||
|
||||
/**
|
||||
* Other hosts' connections that keep this site from enrolling by itself: none when the site has (or had) a
|
||||
* connection of its own, when the project said `otherHosts: 'enrol'`, or for hosts it named as its own.
|
||||
*/
|
||||
export async function otherHostsInTheWay(payload: BasePayload, options: Pick<ResolvedRelayOptions, 'host' | 'otherHosts'>, stored: RelayStored): Promise<string[]> {
|
||||
if (stored.token || stored.enrolledAt || options.otherHosts === 'enrol') {return []}
|
||||
const own = Array.isArray(options.otherHosts) ? options.otherHosts.map((h) => h.trim().toLowerCase().replace(/^www\./, '')) : []
|
||||
return (await otherRelayHosts(payload, relayHost(payload, options))).filter((h) => !own.includes(h.replace(/^www\./, '')))
|
||||
/** 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\./, '')
|
||||
|
||||
/**
|
||||
* Is this site a non-public copy — a development, preview or staging address? `IAPL_NOINDEX=1` (the switch
|
||||
* such a site already has), or a host that matches `mail.relay.developmentHosts`.
|
||||
*/
|
||||
export function siteIsNonPublic(payload: BasePayload, options: Pick<ResolvedRelayOptions, 'developmentHosts' | 'host'>): boolean {
|
||||
if (isSiteNoindex()) {return true}
|
||||
const host = relayHost(payload, options)
|
||||
return (options.developmentHosts ?? []).some((pattern) => {
|
||||
const source = pattern.trim().toLowerCase().split('*').map((part) => part.replace(/[.+?^${}()|[\]\\]/g, '\\$&')).join('.*')
|
||||
return Boolean(source) && new RegExp(`^${source}$`).test(host)
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* Other hosts' connections that keep this site from enrolling — and, for a non-public site, from sending —
|
||||
* BY ITSELF (`mail.relay.otherHosts`). Decided by direction:
|
||||
* - a public site is never held: the entry of its development address (launch) or of its old domain (a
|
||||
* move) is simply its past;
|
||||
* - a non-public site (noindex, or a development host) that finds the connection of a host it was never
|
||||
* 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.
|
||||
*/
|
||||
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 []}
|
||||
const connected = Boolean(stored.token || stored.enrolledAt)
|
||||
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)))
|
||||
}
|
||||
|
||||
const otherHostMessage = (host: string, foreign: string[]) =>
|
||||
`This database holds the mail-service connection of another site (${foreign.join(', ')}), and this site ("${host}") is a non-public copy (IAPL_NOINDEX, or a development host) or set to wait: it does not connect or send by itself. Press "Connect again" in Site integrations → E-mail sending if it should send e-mails (mail.relay.otherHosts).`
|
||||
|
||||
async function enrolOnce(payload: BasePayload, options: ResolvedRelayOptions, force: boolean, deadline?: number): Promise<EnrolResult> {
|
||||
const stored = await readSiteStore(payload, options)
|
||||
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()) {
|
||||
// (the copy rule is not a refusal of the service: it is asked again every time, so it ends when its reason does)
|
||||
if (!force && stored.refusal && stored.refusal.code !== LOCAL_CODES.otherHost && 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)
|
||||
@@ -105,17 +158,19 @@ async function enrolOnce(payload: BasePayload, options: ResolvedRelayOptions, fo
|
||||
return enrolFailure(refusal('host-not-allowed', `"${host}" is not a public host name, so the mail service cannot call this site back.`))
|
||||
}
|
||||
|
||||
// A copied database: another host's connection is here and this site has never had one. With production's
|
||||
// data a copy would mail real people as soon as it could send, so it does not enrol BY ITSELF — an admin's
|
||||
// "Connect again" (`force`) does, once; from then on the site has its own entry and heals like any other.
|
||||
// A site with an empty store (before launch) is not affected.
|
||||
// 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 foreign = force ? [] : await otherHostsInTheWay(payload, options, stored)
|
||||
if (foreign.length) {
|
||||
const now = Date.now()
|
||||
const message = `This database holds the mail-service connection of another site (${foreign.join(', ')}) and none of "${host}": a copied database, or a new domain. The site does not connect by itself; press "Connect again" in Site integrations → E-mail sending if it should send e-mails (or set mail.relay.otherHosts).`
|
||||
await updateRelayStore(payload, options, (current) => ({ ...current, refusal: { at: new Date(now).toISOString(), code: LOCAL_CODES.otherHost, message, reason: foreign[0], until: new Date(now + RELAY_DEFAULTS.refusalCooldownMs).toISOString() } }))
|
||||
const message = otherHostMessage(host, foreign)
|
||||
if (stored.refusal?.code !== LOCAL_CODES.otherHost || stored.refusal.reason !== foreign[0]) {
|
||||
const now = new Date().toISOString()
|
||||
await updateRelayStore(payload, options, (current) => ({ ...current, refusal: { at: now, code: LOCAL_CODES.otherHost, message, reason: foreign[0], until: now } }))
|
||||
}
|
||||
return enrolFailure(refusal(LOCAL_CODES.otherHost, message, { reason: foreign[0] }))
|
||||
}
|
||||
if (stored.refusal?.code === LOCAL_CODES.otherHost) {await updateRelayStore(payload, options, (current) => ({ ...current, refusal: null }))}
|
||||
|
||||
let answer: RelayAnswer<{ state?: string }> | undefined
|
||||
let nonce = ''
|
||||
@@ -139,6 +194,7 @@ async function enrolOnce(payload: BasePayload, options: ResolvedRelayOptions, fo
|
||||
const state: RelaySiteState = answer.body.state === 'pending' || answer.body.state === 'suspended' ? answer.body.state : 'active'
|
||||
await updateRelayStore(payload, options, (current) => ({
|
||||
...current,
|
||||
...(force ? { acceptedHosts: [...new Set([...(current.acceptedHosts ?? []), ...others])] } : {}),
|
||||
disconnected: false,
|
||||
enrolledAt: new Date().toISOString(),
|
||||
host,
|
||||
@@ -151,6 +207,7 @@ 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.
|
||||
@@ -243,6 +300,11 @@ export async function withRelayToken<T>(
|
||||
if (stored.disconnected) {return refusal(LOCAL_CODES.disconnected, 'The site was disconnected from the mail service in the panel.')}
|
||||
const candidate = await readRelayCandidate(payload, options)
|
||||
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 })
|
||||
if (foreign.length) {return refusal(LOCAL_CODES.otherHost, otherHostMessage(relayHost(payload, options), foreign), { reason: foreign[0] })}
|
||||
}
|
||||
|
||||
const enrolNow = async (): Promise<null | RelayRefusal> => {
|
||||
// once per message: a second request for it says again why the first enrolment failed
|
||||
@@ -424,9 +486,12 @@ export async function setRelayToken(payload: BasePayload, token: string, options
|
||||
if (!/^ims_[\w-]{43}$/.test(token)) {throw new Error('Not a token of the mail service (ims_ and 43 characters).')}
|
||||
// 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,
|
||||
acceptedHosts: [...new Set([...(current.acceptedHosts ?? []), ...others])],
|
||||
disconnected: false,
|
||||
enrolledAt: new Date().toISOString(),
|
||||
host: relayHost(payload, options) || undefined,
|
||||
|
||||
Reference in New Issue
Block a user