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
@@ -34,7 +34,7 @@ export const integrationsTexts = defineTexts({
|
||||
mailRelayRefusedHost: `This site has no public address yet ({{host}}). ${IWSN} works once the site runs on its domain.`,
|
||||
mailRelayRefusedNoHost: 'The site does not know its own address. Ask your administrator.',
|
||||
mailRelayRefusedOther: `${IWSN} answered: {{message}}`,
|
||||
mailRelayRefusedOtherHost: 'The data comes from another site ({{host}}), so this site did not connect by itself. Press "Connect again" if it should send e-mails.',
|
||||
mailRelayRefusedOtherHost: 'The data comes from another site ({{host}}), so this copy does not send e-mails by itself. Press "Connect again" if it should.',
|
||||
mailRelayRefusedSetup: `${IWSN} is not fully set up on this site. Ask your administrator.`,
|
||||
mailRelayRefusedToken: `The access key of this site is no longer valid. Ask your administrator for a new one.`,
|
||||
mailRelayRepliesTo: 'Replies go to {{address}}.',
|
||||
@@ -154,7 +154,7 @@ export const integrationsTexts = defineTexts({
|
||||
mailRelayRefusedHost: `Witryna nie ma jeszcze publicznego adresu ({{host}}). ${IWSN} zadziała, gdy witryna będzie dostępna pod swoją domeną.`,
|
||||
mailRelayRefusedNoHost: 'Witryna nie zna własnego adresu. Zapytaj administratora.',
|
||||
mailRelayRefusedOther: `${IWSN} odpowiedział: {{message}}`,
|
||||
mailRelayRefusedOtherHost: 'Dane pochodzą z innej witryny ({{host}}), więc ta witryna nie połączyła się sama. Kliknij „Połącz ponownie”, jeśli ma wysyłać e-maile.',
|
||||
mailRelayRefusedOtherHost: 'Dane pochodzą z innej witryny ({{host}}), więc ta kopia nie wysyła e-maili sama. Kliknij „Połącz ponownie”, jeśli ma je wysyłać.',
|
||||
mailRelayRefusedSetup: `${IWSN} nie jest w pełni skonfigurowany w tej witrynie. Zapytaj administratora.`,
|
||||
mailRelayRefusedToken: `Klucz dostępu tej witryny stracił ważność. Poproś administratora o nowy.`,
|
||||
mailRelayRepliesTo: 'Odpowiedzi trafiają na adres {{address}}.',
|
||||
|
||||
@@ -59,10 +59,10 @@ export const mailRules: DoctorRule[] = [
|
||||
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 === 'client-other-host') {
|
||||
} else if (relay.refusal === 'client-other-host') {
|
||||
out.push({
|
||||
fix: 'if this site should send e-mails: Site integrations → E-mail sending → "Connect again" (once); a moved domain or a second domain of the same site: mail: { relay: { otherHosts: [\'old-domain.example\'] } }; a staging copy that must not send: mail: { relay: false } or SMTP to a catcher',
|
||||
message: `the database holds the mail-service connection of another site (${relay.reason ?? 'another host'}) and none of this one — a copied database or a new domain: the site does not connect by itself, e-mails are not sent`,
|
||||
fix: 'expected for a copy that must not mail real people. If this copy should send e-mails: Site integrations → E-mail sending → "Connect again" (once). To keep it silent for good: mail: { relay: false } or SMTP to a catcher. If this is NOT a copy but the site itself, it is wrongly marked non-public: remove IAPL_NOINDEX / the host from mail.relay.developmentHosts',
|
||||
message: `this site is non-public (IAPL_NOINDEX or a development host) and its database holds the mail-service connection of another site (${relay.reason ?? 'another host'}) — a copy of that site's data: it does not connect or send by itself, e-mails are not sent`,
|
||||
severity: 'warning',
|
||||
})
|
||||
} else if (!relay.connected && relay.refusal) {
|
||||
@@ -75,6 +75,15 @@ export const mailRules: DoctorRule[] = [
|
||||
} 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 (mail.otherHostEntries && !mail.nonPublic) {
|
||||
// Right after a launch or a domain move this is the site's own past. On a COPY that forgot to say it is not
|
||||
// public it is the last warning before real people get its mail.
|
||||
out.push({
|
||||
fix: 'the site itself after a launch or a move: nothing to do — name the old host to silence this: mail: { relay: { otherHosts: [\'<old host>\'] } }. A staging or test COPY of that site: set IAPL_NOINDEX=1 there (it then waits for "Connect again"), or mail: { relay: false } / SMTP to a catcher',
|
||||
message: 'the database also holds the mail-service connection of another host, and this site is public: if it is a copy of that site, it sends e-mails to the real addresses in its data',
|
||||
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' })
|
||||
}
|
||||
|
||||
@@ -71,6 +71,8 @@ export async function collectDoctorStatus(payload: BasePayload): Promise<DoctorS
|
||||
}
|
||||
mail = {
|
||||
graphEnv: graphAvailable(),
|
||||
...(state.nonPublic ? { nonPublic: true } : {}),
|
||||
...(state.otherHostEntries ? { otherHostEntries: true } : {}),
|
||||
relay: state.relay
|
||||
? {
|
||||
connected: state.relay.connected,
|
||||
|
||||
@@ -67,6 +67,10 @@ export type DoctorStatus = {
|
||||
mail?: {
|
||||
/** The four GRAPH_* variables are set (Microsoft Graph: deprecated). */
|
||||
graphEnv: boolean
|
||||
/** The site says it is not public (`IAPL_NOINDEX`, or a development host): a copy of another site's data does not mail by itself. */
|
||||
nonPublic?: boolean
|
||||
/** The database also holds the mail-service connection of another host that this site did not name as its own. */
|
||||
otherHostEntries?: boolean
|
||||
/** null = the mail service is switched off in the project. */
|
||||
relay: {
|
||||
connected: boolean
|
||||
|
||||
@@ -7,7 +7,7 @@
|
||||
/** 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.7.0'
|
||||
export const RELAY_CONTRACT_VERSION = '1.7.1'
|
||||
/** The `product` value of this plugin. */
|
||||
export const RELAY_PRODUCT = 'iapl'
|
||||
/** The service's name, for docs, logs and the doctor. */
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
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'
|
||||
import { disconnectRelay as disconnect, enrolRelay as enrol, type EnrolResult, siteIsNonPublic as nonPublic, 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'
|
||||
@@ -65,3 +65,10 @@ export const disconnectRelay = (payload: BasePayload, options?: RelayOptions): P
|
||||
|
||||
/** 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 })
|
||||
|
||||
/**
|
||||
* Whether this site counts as a non-public copy for `mail.relay.otherHosts`: `IAPL_NOINDEX=1`, or its host is
|
||||
* matched by `mail.relay.developmentHosts`. Such a site neither enrols nor sends by itself while its database
|
||||
* holds another host's connection (docs/email.md "Staging, copies and several hosts").
|
||||
*/
|
||||
export const siteIsNonPublic = (payload: BasePayload, options?: RelayOptions): boolean => nonPublic(payload, resolveRelayOptions(payload, options) || (options ?? {}))
|
||||
|
||||
@@ -24,6 +24,12 @@ export type RelayOptions = {
|
||||
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.
|
||||
@@ -40,14 +46,19 @@ export type RelayOptions = {
|
||||
/** 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 already holds the connection of ANOTHER host and none of its own —
|
||||
* the sign of a copied database (staging made from production), of a moved domain, or of two sites on one
|
||||
* database. Default `'wait'`: the site does not enrol by itself (a copy with production's data would start
|
||||
* mailing real people); an admin presses "Connect again", once. `'enrol'`: enrol by itself all the same.
|
||||
* A list: these hosts are this site's own (its old domain, its second domain) — beside them it enrols by
|
||||
* itself, beside any other it waits. `www.` and the bare domain are always one site.
|
||||
* 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?: 'enrol' | 'wait' | string[]
|
||||
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.
|
||||
|
||||
@@ -11,7 +11,8 @@ import { RELAY_SENDER_ADDRESS } from './adapter.js'
|
||||
import { relayRequest } from './client.js'
|
||||
import { RELAY_CONFIRM_PATH, RELAY_CONNECT_PATH, RELAY_DISCONNECT_PATH, RELAY_STATUS_PATH } from './constants.js'
|
||||
import { isPublicHost, relayHost, resolveRelayOptions } from './options.js'
|
||||
import { disconnectRelay, enrolRelay, type EnrolResult, getRelayStatus, LOCAL_CODES, otherHostsInTheWay, readSiteStore, type RelayStatus, setRelayToken } from './session.js'
|
||||
import { disconnectRelay, enrolRelay, type EnrolResult, getRelayStatus, LOCAL_CODES, otherHostsInTheWay, readSiteStore, type RelayStatus, setRelayToken, siteIsNonPublic } from './session.js'
|
||||
import { otherRelayHosts } from './store.js'
|
||||
|
||||
type Settings = {
|
||||
emailStatus?: IntegrationStatus | null
|
||||
@@ -28,6 +29,10 @@ export type MailPanelState = {
|
||||
accessKeyField?: boolean
|
||||
/** The address the service calls this site back at. */
|
||||
confirmUrl?: string
|
||||
/** The site says it is not public (`IAPL_NOINDEX`, or a host in `mail.relay.developmentHosts`). */
|
||||
nonPublic?: boolean
|
||||
/** The database also holds the connection of a host this site did not name as its own, and the site is not held for it. */
|
||||
otherHostEntries?: boolean
|
||||
/** Enabled in the project (`mail.relay` is not `false`). */
|
||||
relay: ({ senderAddress: string } & RelayStatus) | null
|
||||
replyAddress: null | string
|
||||
@@ -60,10 +65,21 @@ export async function mailPanelState(req: Pick<PayloadRequest, 'payload'>, own:
|
||||
const code = !status.host ? LOCAL_CODES.noHost : !isPublicHost(status.host) ? 'host-not-allowed' : null
|
||||
if (code) {status = { ...status, refusal: { at: new Date().toISOString(), code } }}
|
||||
}
|
||||
// …and so is a copy of another site's database: it waits for an admin's "Connect again".
|
||||
if (status && options && !status.connected && !status.disconnected && !status.refusal && options.enrol !== false && options.token === undefined) {
|
||||
const foreign = await otherHostsInTheWay(payload, options, await readSiteStore(payload, options))
|
||||
if (foreign.length) {status = { ...status, refusal: { at: new Date().toISOString(), code: LOCAL_CODES.otherHost, reason: foreign[0] } }}
|
||||
// …and so is a non-public copy of another site's database: it waits for an admin's "Connect again", with or
|
||||
// without a token of its own. Asked now, not read from what a past send left: the rule ends with its reason.
|
||||
let nonPublic = false
|
||||
let otherHostEntries = false
|
||||
if (status && options && options.token === undefined) {
|
||||
nonPublic = siteIsNonPublic(payload, options)
|
||||
const stored = await readSiteStore(payload, options)
|
||||
const foreign = status.disconnected ? [] : await otherHostsInTheWay(payload, options, stored)
|
||||
const known = status.refusal?.code === LOCAL_CODES.otherHost
|
||||
if (foreign.length && (!status.refusal || known)) {status = { ...status, refusal: { at: status.refusal?.at ?? new Date().toISOString(), code: LOCAL_CODES.otherHost, reason: foreign[0] } }}
|
||||
else if (known) {status = { ...status, refusal: undefined }}
|
||||
// other hosts' entries a PUBLIC site did not name as its own: its development address after launch — or the
|
||||
// sign that this is a copy which forgot to say that it is not public
|
||||
const named = [...(Array.isArray(options.otherHosts) ? options.otherHosts : []), ...(stored.acceptedHosts ?? [])].map((h) => h.trim().toLowerCase().replace(/^www\./, ''))
|
||||
otherHostEntries = !foreign.length && (await otherRelayHosts(payload, status.host)).some((h) => !named.includes(h.replace(/^www\./, '')))
|
||||
}
|
||||
const api = payload.config.routes?.api ?? '/api'
|
||||
return {
|
||||
@@ -71,6 +87,8 @@ export async function mailPanelState(req: Pick<PayloadRequest, 'payload'>, own:
|
||||
...(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,
|
||||
...(nonPublic ? { nonPublic: true } : {}),
|
||||
...(otherHostEntries ? { otherHostEntries: true } : {}),
|
||||
...(smtpIncomplete(settings) ? { smtpIncomplete: true } : {}),
|
||||
transport,
|
||||
}
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -32,6 +32,12 @@ export type RelayLimits = {
|
||||
}
|
||||
|
||||
export type RelayStored = {
|
||||
/**
|
||||
* Other hosts whose connection was in this database when a person connected this site ("Connect again",
|
||||
* `setRelayToken`): a copy that was told to send does not stop for them again. A host that appears LATER
|
||||
* — production's entry arriving with a fresh copy of its database — is not among them.
|
||||
*/
|
||||
acceptedHosts?: string[]
|
||||
/**
|
||||
* An admin pressed "Disconnect": no send and no enrolment until "Connect again". The token is still here
|
||||
* only while the service has not confirmed that it gave it up (`revokePending`).
|
||||
|
||||
Reference in New Issue
Block a user