Mail relay: review round 2 — the store is keyed by host, a copied database does not enrol by itself
- Q-1 one entry per host (iapl:mail-relay:site:<host>); a read never deletes or writes; another host's
entry is neither used nor touched (a developer's process on the live database, www and apex, a copy)
- a database that holds another host's connection and none of this site's does not enrol by itself:
"Connect again" does, once; mail.relay.otherHosts ('wait' | 'enrol' | the site's own other hosts);
panel text and doctor finding; a site with an empty store enrols by itself as before
- Q-2 the file limit answers from what is stored and never asks the service
- Q-3 a file whose mail was not confirmed is not reported as a wrong file, and no notice mail follows
- Q-4 its own text when the access-key field is off
- D-1 docs for open enrolment; staging, copies and several hosts
Co-Authored-By: Claude Fable 5.2 <[email protected]>
This commit is contained in:
co-authored by
Claude Fable 5.2
parent
edee3a321f
commit
85ed92bb89
@@ -7,23 +7,24 @@ import type { ResolvedRelayOptions } from './options.js'
|
||||
import { PLUGIN_VERSION } from '../../../version.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, relayHost } from './options.js'
|
||||
import {
|
||||
clearRelayStore,
|
||||
dropRelayCandidate,
|
||||
holdNonce,
|
||||
readOwnRelayStore,
|
||||
readRelayCandidate,
|
||||
readRelayStore,
|
||||
type RelaySiteState,
|
||||
type RelayStored,
|
||||
releaseNonce,
|
||||
sha256Hex,
|
||||
updateRelayStore,
|
||||
} from './store.js'
|
||||
import { isPublicHost, pluginMailOptions, relayHost } from './options.js'
|
||||
import * as store from './store.js'
|
||||
import { otherRelayHosts, type RelaySiteState, type RelayStored, releaseNonce, sha256Hex } from './store.js'
|
||||
|
||||
/** The stored entry of this site — never one made on another host (store.ts). */
|
||||
export const readSiteStore = (payload: BasePayload, options: Pick<ResolvedRelayOptions, 'host'>) => readOwnRelayStore(payload, relayHost(payload, options))
|
||||
type HostOptions = Pick<ResolvedRelayOptions, 'host'>
|
||||
|
||||
// The store is keyed by host: everything here reads and writes the entry of THIS site's host
|
||||
// (`relay.host`, else the host of `serverURL`) and never another host's.
|
||||
const readRelayStore = (payload: BasePayload, options: HostOptions) => store.readRelayStore(payload, relayHost(payload, options))
|
||||
const updateRelayStore = (payload: BasePayload, options: HostOptions, change: (current: RelayStored) => RelayStored) => store.updateRelayStore(payload, change, relayHost(payload, options))
|
||||
const clearRelayStore = (payload: BasePayload, options: HostOptions, keep: Pick<RelayStored, 'disconnected'> = {}) => store.clearRelayStore(payload, keep, relayHost(payload, options))
|
||||
const readRelayCandidate = (payload: BasePayload, options: HostOptions) => store.readRelayCandidate(payload, relayHost(payload, options))
|
||||
const dropRelayCandidate = (payload: BasePayload, options: HostOptions) => store.dropRelayCandidate(payload, relayHost(payload, options))
|
||||
|
||||
/** The stored entry of this site — never one made on another host (store.ts). A read changes nothing. */
|
||||
export const readSiteStore = readRelayStore
|
||||
/** Changes the stored entry of this site. */
|
||||
export const updateSiteStore = updateRelayStore
|
||||
|
||||
const sleep = (ms: number) => new Promise<void>((resolve) => setTimeout(resolve, ms))
|
||||
const refusal = (code: string, message: string, extra: Partial<RelayRefusal> = {}): RelayRefusal => ({ code, message, noAnswer: false, ok: false, retryable: false, status: 0, ...extra })
|
||||
@@ -33,6 +34,8 @@ export const LOCAL_CODES = {
|
||||
disconnected: 'client-disconnected',
|
||||
/** A token that belongs to another site (the service says which host it is for). */
|
||||
foreignToken: 'client-foreign-token',
|
||||
/** The database holds another host's connection and none of this site's: a copy does not enrol by itself. */
|
||||
otherHost: 'client-other-host',
|
||||
/** This config has no confirm route, so the service could not call the site back. */
|
||||
noHost: 'client-no-host',
|
||||
noRoute: 'client-no-route',
|
||||
@@ -51,7 +54,7 @@ const enrolFailure = (answer: RelayRefusal): { ok: false } & EnrolResult => ({
|
||||
retryable: answer.retryable,
|
||||
status:
|
||||
answer.code === LOCAL_CODES.disconnected ? 'relay-disconnected'
|
||||
: ([LOCAL_CODES.foreignToken, LOCAL_CODES.noHost, LOCAL_CODES.noRoute, LOCAL_CODES.noToken] as string[]).includes(answer.code) ? 'relay-refused'
|
||||
: ([LOCAL_CODES.foreignToken, LOCAL_CODES.noHost, LOCAL_CODES.noRoute, LOCAL_CODES.noToken, LOCAL_CODES.otherHost] as string[]).includes(answer.code) ? 'relay-refused'
|
||||
: relayStatusFor(answer.code, answer.retryable),
|
||||
})
|
||||
|
||||
@@ -72,6 +75,16 @@ 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\./, '')))
|
||||
}
|
||||
|
||||
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.'))}
|
||||
@@ -92,11 +105,23 @@ 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.
|
||||
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() } }))
|
||||
return enrolFailure(refusal(LOCAL_CODES.otherHost, message, { reason: foreign[0] }))
|
||||
}
|
||||
|
||||
let answer: RelayAnswer<{ state?: string }> | undefined
|
||||
let nonce = ''
|
||||
for (let attempt = 0; attempt < 2; attempt++) {
|
||||
nonce = randomBytes(32).toString('base64url')
|
||||
const nonceHash = await holdNonce(payload, nonce, RELAY_DEFAULTS.nonceTtlMs)
|
||||
const nonceHash = await store.holdNonce(payload, nonce, RELAY_DEFAULTS.nonceTtlMs, host)
|
||||
answer = await relayRequest<{ state?: string }>({
|
||||
body: Buffer.from(JSON.stringify({ host, nonce, product: RELAY_PRODUCT, productVersion: PLUGIN_VERSION })),
|
||||
fetchImpl: options.fetchImpl,
|
||||
@@ -106,13 +131,13 @@ async function enrolOnce(payload: BasePayload, options: ResolvedRelayOptions, fo
|
||||
url: options.url,
|
||||
})
|
||||
if (answer.ok) {
|
||||
const candidate = await readRelayCandidate(payload)
|
||||
const candidate = await readRelayCandidate(payload, options)
|
||||
if (!candidate || candidate.nonceHash !== nonceHash) {
|
||||
// The service says yes, but the token did not reach this store (another instance with a store of its own?).
|
||||
return enrolFailure(refusal('callback-failed', 'The mail service confirmed the enrolment, but its token did not reach this site\'s store.', { reason: 'store' }))
|
||||
}
|
||||
const state: RelaySiteState = answer.body.state === 'pending' || answer.body.state === 'suspended' ? answer.body.state : 'active'
|
||||
await updateRelayStore(payload, (current) => ({
|
||||
await updateRelayStore(payload, options, (current) => ({
|
||||
...current,
|
||||
disconnected: false,
|
||||
enrolledAt: new Date().toISOString(),
|
||||
@@ -125,7 +150,7 @@ async function enrolOnce(payload: BasePayload, options: ResolvedRelayOptions, fo
|
||||
state,
|
||||
token: candidate.token,
|
||||
}))
|
||||
await dropRelayCandidate(payload)
|
||||
await dropRelayCandidate(payload, options)
|
||||
return { ok: true, state }
|
||||
}
|
||||
// Used or not, this nonce is over. A token the call-back did deliver stays beside the one in use.
|
||||
@@ -133,15 +158,15 @@ async function enrolOnce(payload: BasePayload, options: ResolvedRelayOptions, fo
|
||||
if (answer.code !== 'enrolment-in-progress' || attempt > 0) {break}
|
||||
// Another process of this site is enrolling: wait, then look whether the token is here by now.
|
||||
await sleep(Math.min((answer.retryAfter ?? 2) * 1000, 5000))
|
||||
const now = await readRelayStore(payload)
|
||||
if ((now.token && now.token !== stored.token) || (await readRelayCandidate(payload))) {return { ok: true, state: now.state ?? 'active' }}
|
||||
const now = await readRelayStore(payload, options)
|
||||
if ((now.token && now.token !== stored.token) || (await readRelayCandidate(payload, options))) {return { ok: true, state: now.state ?? 'active' }}
|
||||
}
|
||||
|
||||
const failed = answer as RelayRefusal
|
||||
if (!failed.retryable) {
|
||||
// Asking again at once would give the same answer (and a call-back that times out costs 8 seconds a time).
|
||||
const now = Date.now()
|
||||
await updateRelayStore(payload, (current) => ({
|
||||
await updateRelayStore(payload, options, (current) => ({
|
||||
...current,
|
||||
refusal: { at: new Date(now).toISOString(), code: failed.code, message: failed.message, ...(failed.reason ? { reason: failed.reason } : {}), until: new Date(now + RELAY_DEFAULTS.refusalCooldownMs).toISOString() },
|
||||
...(failed.code === 'site-suspended' ? { state: 'suspended' as const } : {}),
|
||||
@@ -159,9 +184,9 @@ const HAND_ISSUED = {
|
||||
* A site with a token issued by hand cannot be called back, so "enrol again" is not open to it
|
||||
* (contract §2): it stops, says what to ask Intecion for, and keeps the token.
|
||||
*/
|
||||
async function handIssued(payload: BasePayload, code: keyof typeof HAND_ISSUED): Promise<RelayRefusal> {
|
||||
async function handIssued(payload: BasePayload, options: HostOptions, code: keyof typeof HAND_ISSUED): Promise<RelayRefusal> {
|
||||
const now = new Date().toISOString()
|
||||
await updateRelayStore(payload, (current) => (current.refusal?.code === code ? current : { ...current, refusal: { at: now, code, message: HAND_ISSUED[code], until: now } }))
|
||||
await updateRelayStore(payload, options, (current) => (current.refusal?.code === code ? current : { ...current, refusal: { at: now, code, message: HAND_ISSUED[code], until: now } }))
|
||||
return refusal(code, HAND_ISSUED[code])
|
||||
}
|
||||
|
||||
@@ -216,7 +241,7 @@ export async function withRelayToken<T>(
|
||||
for (let round = 0; round < 4; round++) {
|
||||
const stored = await readSiteStore(payload, options)
|
||||
if (stored.disconnected) {return refusal(LOCAL_CODES.disconnected, 'The site was disconnected from the mail service in the panel.')}
|
||||
const candidate = await readRelayCandidate(payload)
|
||||
const candidate = await readRelayCandidate(payload, options)
|
||||
const token = candidate?.token ?? stored.token
|
||||
|
||||
const enrolNow = async (): Promise<null | RelayRefusal> => {
|
||||
@@ -228,7 +253,7 @@ export async function withRelayToken<T>(
|
||||
if (use.enrolment.ok) {return null}
|
||||
// The enrolment has no good answer, but the call-back may have delivered a token all the same (the
|
||||
// service's answer was lost): try it — the service says at once whether it made that token valid.
|
||||
if (round < 3 && (await readRelayCandidate(payload))) {return null}
|
||||
if (round < 3 && (await readRelayCandidate(payload, options))) {return null}
|
||||
return failed()
|
||||
}
|
||||
|
||||
@@ -243,10 +268,10 @@ export async function withRelayToken<T>(
|
||||
if (!answer.ok && answer.code === 'invalid-token') {
|
||||
if (candidate) {
|
||||
// The service never made this token valid: back to the earlier one.
|
||||
await dropRelayCandidate(payload)
|
||||
await dropRelayCandidate(payload, options)
|
||||
continue
|
||||
}
|
||||
if (stored.manual) {return handIssued(payload, 'invalid-token')}
|
||||
if (stored.manual) {return handIssued(payload, options, 'invalid-token')}
|
||||
const failed = await enrolNow()
|
||||
if (failed) {return use.enrolment && !use.enrolment.ok ? failed : answer}
|
||||
continue
|
||||
@@ -257,8 +282,8 @@ export async function withRelayToken<T>(
|
||||
// revoked — and the site enrols as itself; a site that cannot be called back is told to ask for its own.
|
||||
const message = `The token belongs to another site, not to "${relayHost(payload, options)}": it is not used. Ask Intecion for a token for this site.`
|
||||
const now = new Date().toISOString()
|
||||
await dropRelayCandidate(payload)
|
||||
await updateRelayStore(payload, (current) => ({ ...current, hostChecked: false, manual: false, service: null, source: undefined, state: undefined, token: undefined, ...(stored.manual ? { refusal: { at: now, code: LOCAL_CODES.foreignToken, message, until: now } } : {}) }))
|
||||
await dropRelayCandidate(payload, options)
|
||||
await updateRelayStore(payload, options, (current) => ({ ...current, hostChecked: false, manual: false, service: null, source: undefined, state: undefined, token: undefined, ...(stored.manual ? { refusal: { at: now, code: LOCAL_CODES.foreignToken, message, until: now } } : {}) }))
|
||||
if (stored.manual) {return refusal(LOCAL_CODES.foreignToken, message)}
|
||||
const failed = await enrolNow()
|
||||
if (failed) {return use.enrolment && !use.enrolment.ok ? failed : answer}
|
||||
@@ -267,11 +292,11 @@ export async function withRelayToken<T>(
|
||||
if (candidate && !provesToken(answer)) {return answer} // says nothing about the token: both stay as they are
|
||||
if (candidate) {
|
||||
// Seen accepted: this is the token now.
|
||||
await updateRelayStore(payload, (current) => ({ ...current, enrolledAt: candidate.at, host: relayHost(payload, options) || current.host, hostChecked: true, manual: false, source: 'enrolment', state: candidate.state, token: candidate.token }))
|
||||
await dropRelayCandidate(payload)
|
||||
await updateRelayStore(payload, options, (current) => ({ ...current, enrolledAt: candidate.at, host: relayHost(payload, options) || current.host, hostChecked: true, manual: false, source: 'enrolment', state: candidate.state, token: candidate.token }))
|
||||
await dropRelayCandidate(payload, options)
|
||||
}
|
||||
if (!answer.ok && answer.code === 'reverify') {
|
||||
if (stored.manual) {return handIssued(payload, 'reverify')}
|
||||
if (stored.manual) {return handIssued(payload, options, 'reverify')}
|
||||
const failed = await enrolNow()
|
||||
if (failed) {return use.enrolment && !use.enrolment.ok ? failed : answer}
|
||||
continue
|
||||
@@ -313,11 +338,11 @@ export async function refreshRelayStatus(payload: BasePayload, options: Resolved
|
||||
if (own && typeof body.host === 'string' && body.host && body.host !== own && options.token === undefined) {
|
||||
const now = new Date().toISOString()
|
||||
const message = `The token belongs to "${body.host}", not to this site ("${own}"): it is not used. Ask Intecion for a token for this site.`
|
||||
await dropRelayCandidate(payload)
|
||||
const stored = await updateRelayStore(payload, (current) => ({ ...current, hostChecked: false, manual: false, refusal: { at: now, code: LOCAL_CODES.foreignToken, message, until: now }, service: null, source: undefined, state: undefined, token: undefined }))
|
||||
await dropRelayCandidate(payload, options)
|
||||
const stored = await updateRelayStore(payload, options, (current) => ({ ...current, hostChecked: false, manual: false, refusal: { at: now, code: LOCAL_CODES.foreignToken, message, until: now }, service: null, source: undefined, state: undefined, token: undefined }))
|
||||
return { error: refusal(LOCAL_CODES.foreignToken, message), stored }
|
||||
}
|
||||
const stored = await updateRelayStore(payload, (current) => ({
|
||||
const stored = await updateRelayStore(payload, options, (current) => ({
|
||||
...current,
|
||||
hostChecked: true,
|
||||
service: {
|
||||
@@ -349,7 +374,7 @@ export async function rotateRelayToken(payload: BasePayload, options: ResolvedRe
|
||||
const answer = await relayRequest<{ token?: string }>({ fetchImpl: options.fetchImpl, method: 'POST', path: '/v1/rotate', site: relayHost(payload, options), timeoutMs, token: used, url: options.url })
|
||||
if (answer.ok && typeof answer.body.token === 'string' && answer.body.token) {
|
||||
const fresh = answer.body.token
|
||||
await updateRelayStore(payload, (current) => ({
|
||||
await updateRelayStore(payload, options, (current) => ({
|
||||
...current,
|
||||
enrolledAt: new Date().toISOString(),
|
||||
service: current.service ? { ...current.service, rotateAfter: undefined } : current.service,
|
||||
@@ -359,13 +384,13 @@ export async function rotateRelayToken(payload: BasePayload, options: ResolvedRe
|
||||
return 'rotated'
|
||||
}
|
||||
if (!answer.ok && answer.code === 'already-rotated') {
|
||||
const now = await readRelayStore(payload)
|
||||
const now = await readRelayStore(payload, options)
|
||||
// No newer token here: this one is on its way out. Forget it, so the next send enrols at once.
|
||||
if (now.token === used) {await updateRelayStore(payload, (current) => ({ ...current, service: null, token: undefined }))}
|
||||
if (now.token === used) {await updateRelayStore(payload, options, (current) => ({ ...current, service: null, token: undefined }))}
|
||||
return 'failed'
|
||||
}
|
||||
// Asked once; not again before the status has been read anew.
|
||||
await updateRelayStore(payload, (current) => ({ ...current, service: current.service ? { ...current.service, rotateAfter: undefined } : current.service }))
|
||||
await updateRelayStore(payload, options, (current) => ({ ...current, service: current.service ? { ...current.service, rotateAfter: undefined } : current.service }))
|
||||
return 'failed'
|
||||
}
|
||||
|
||||
@@ -383,11 +408,11 @@ export async function disconnectRelay(payload: BasePayload, options: ResolvedRel
|
||||
if (!answer.ok && !(answer.code === 'invalid-token' && !answer.noAnswer)) {
|
||||
// Not confirmed: the site stops using the token now, but it still works at the service. It is kept so
|
||||
// that "Disconnect" can be pressed again.
|
||||
await updateRelayStore(payload, (current) => ({ ...current, disconnected: true, revokePending: true }))
|
||||
await updateRelayStore(payload, options, (current) => ({ ...current, disconnected: true, revokePending: true }))
|
||||
return { revoked: false }
|
||||
}
|
||||
}
|
||||
await clearRelayStore(payload, { disconnected: true })
|
||||
await clearRelayStore(payload, options, { disconnected: true })
|
||||
return { revoked: true }
|
||||
}
|
||||
|
||||
@@ -397,12 +422,14 @@ export async function disconnectRelay(payload: BasePayload, options: ResolvedRel
|
||||
*/
|
||||
export async function setRelayToken(payload: BasePayload, token: string, options: { host?: string } = {}): Promise<void> {
|
||||
if (!/^ims_[\w-]{43}$/.test(token)) {throw new Error('Not a token of the mail service (ims_ and 43 characters).')}
|
||||
await dropRelayCandidate(payload)
|
||||
await updateRelayStore(payload, (current) => ({
|
||||
// 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 }
|
||||
await dropRelayCandidate(payload, options)
|
||||
await updateRelayStore(payload, options, (current) => ({
|
||||
...current,
|
||||
disconnected: false,
|
||||
enrolledAt: new Date().toISOString(),
|
||||
...(options.host ? { host: options.host } : {}),
|
||||
host: relayHost(payload, options) || undefined,
|
||||
hostChecked: false,
|
||||
manual: true,
|
||||
refusal: null,
|
||||
|
||||
Reference in New Issue
Block a user