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:
Radosław Smoliński
2026-11-26 00:46:16 +01:00
co-authored by Claude Fable 5.2
parent acfcf72c03
commit 49927205bb
30 changed files with 443 additions and 119 deletions
+10 -1
View File
@@ -690,7 +690,16 @@ describe('e-mail: transport, the mail service, Graph, the confirm route', () =>
const copy = await doctor(project({ ...base(), 'src/payload.config.ts': 'iapl({ forms: {} })' }), ids, { deepStatus: { mail: mail({ relay: relay({ connected: false, reason: 'client.pl', refusal: 'client-other-host', state: undefined }) }) } })
expect(rules(copy)).toEqual(['mail-relay-state:warning'])
expect(copy.findings[0].message).toContain('client.pl')
expect(copy.findings[0].fix).toContain('otherHosts')
expect(copy.findings[0].fix).toContain('Connect again')
// the same for a copy that has a token of its own (production's data copied back onto the development address)
expect(await run(mail({ nonPublic: true, relay: relay({ reason: 'client.pl', refusal: 'client-other-host' }) }))).toEqual(['mail-relay-state:warning'])
// a PUBLIC site whose database knows another host: the site after its launch — or a copy that forgot IAPL_NOINDEX
const launched = await doctor(project({ ...base(), 'src/payload.config.ts': 'iapl({ forms: {} })' }), ids, { deepStatus: { mail: mail({ otherHostEntries: true }) } })
expect(rules(launched)).toEqual(['mail-relay-state:info'])
expect(launched.findings[0].message).toContain('copy')
expect(launched.findings[0].fix).toContain('IAPL_NOINDEX=1')
expect(launched.findings[0].fix).toContain('otherHosts')
expect(await run(mail({ nonPublic: true, otherHostEntries: true }))).toEqual([])
expect(await run(mail({ relay: relay({ nameReplaced: true }) }))).toEqual(['mail-relay-state:warning'])
})
+157 -29
View File
@@ -15,13 +15,14 @@ import { withAccountMailMark } from '../src/modules/email/relay/accountMail.js'
import { relayAdapter, relayAttachmentLimit } from '../src/modules/email/relay/adapter.js'
import { relayRequest } from '../src/modules/email/relay/client.js'
import { RELAY_DEFAULTS, RELAY_SHORT_NAME } from '../src/modules/email/relay/constants.js'
import { createFakeRelay } from '../src/modules/email/relay/fake.js'
import { dropExpectedMail, expectMailTo, takeExpectedMail, withMailKind } from '../src/modules/email/relay/kinds.js'
import { bareAddresses, buildRelayMessage, cleanSubject } from '../src/modules/email/relay/message.js'
import { isPublicHost, relayHost, resolveRelayOptions } from '../src/modules/email/relay/options.js'
import { mailPanelState } from '../src/modules/email/relay/panel.js'
import { clearUnconfirmedRelayMessages, sendThroughRelay } from '../src/modules/email/relay/send.js'
import { disconnectRelay, enrolRelay, getRelayStatus, provesToken, refreshRelayStatus, rotateRelayToken, setRelayToken } from '../src/modules/email/relay/session.js'
import { holdNonce, readRelayCandidate, readRelayStore, updateRelayStore } from '../src/modules/email/relay/store.js'
import { disconnectRelay, enrolRelay, forgetOtherHosts, getRelayStatus, provesToken, refreshRelayStatus, rotateRelayToken, setRelayToken, siteIsNonPublic } from '../src/modules/email/relay/session.js'
import { holdNonce, otherRelayHosts, readRelayCandidate, readRelayStore, updateRelayStore } from '../src/modules/email/relay/store.js'
import { NOTIFICATION_FALLBACK, NOTIFICATION_FALLBACK_PL } from '../src/modules/notifications/defaults.js'
import { resolveFormMessage } from '../src/modules/notifications/resolveFormMessage.js'
import { setRateLimitStore } from '../src/modules/shared/rateLimit.js'
@@ -56,6 +57,8 @@ beforeEach(() => {
clearRateLimits()
resetGraphDeprecationWarning()
for (const name of GRAPH_ENV) {vi.stubEnv(name, '')}
// every site is public unless a test says otherwise
for (const name of ['IAPL_NOINDEX', 'IPAL_NOINDEX']) {vi.stubEnv(name, '')}
})
afterEach(() => {
vi.unstubAllEnvs()
@@ -707,31 +710,117 @@ describe('the token over time', () => {
expect([...apex.store.keys()].filter((k) => k.includes(':site:')).sort()).toEqual(['iapl:mail-relay:site:client.pl', 'iapl:mail-relay:site:www.client.pl'])
})
test('a copy of production\'s database on a staging host does not enrol by itself — and uses, changes and revokes nothing of production\'s', async () => {
// The owner's sites: built and enrolled on a development address, then launched on the real domain. A
// development or staging site says so itself (IAPL_NOINDEX=1, or a host in mail.relay.developmentHosts).
const DEV = 'acme.dev.agency-example.com'
const DEV_HOSTS = { developmentHosts: ['*.dev.agency-example.com'] }
test('before launch: the site on its development address, with an empty store, enrols and sends by itself', async () => {
const dev = shared({ options: DEV_HOSTS, serverURL: `https://${DEV}` })
expect(siteIsNonPublic(dev.payload, dev.options)).toBe(true)
expect((await sendThroughRelay(dev.payload, dev.options, MESSAGE)).sent).toBe(true)
expect(dev.fake.outbox[0].host).toBe(DEV)
// the same with the switch such a site already has, and no option at all
vi.stubEnv('IAPL_NOINDEX', '1')
const noindex = relaySite({ fake: { allow: [HOST] } })
expect(siteIsNonPublic(noindex.payload, noindex.options)).toBe(true)
expect((await sendThroughRelay(noindex.payload, noindex.options, MESSAGE)).sent).toBe(true)
})
test('launch day: the real domain finds the development address\'s entry and enrols by itself — no click; the development site on its own database sends on', async () => {
const dev = shared({ options: DEV_HOSTS, serverURL: `https://${DEV}` })
await sendThroughRelay(dev.payload, dev.options, MESSAGE) // the test mail before launch
// launch: the same data, now served at the real domain (public: no noindex, not a development host)
const live = dev.another('https://client.pl', DEV_HOSTS)
expect(siteIsNonPublic(live.payload, live.options)).toBe(false)
const first = await sendThroughRelay(live.payload, live.options, { ...MESSAGE, subject: 'First mail after launch' })
expect(first).toMatchObject({ sent: true })
expect(dev.fake.outbox.at(-1)).toMatchObject({ host: 'client.pl', subject: 'First mail after launch' })
expect(dev.fake.requests.filter((r) => r.path === '/v1/enrol')).toHaveLength(2)
expect((await mailPanelState({ payload: live.payload }, live.options)).relay?.refusal).toBeUndefined()
// the doctor can still say that the database knows another host (information, for the case that this is a copy)
expect(await mailPanelState({ payload: live.payload }, live.options)).toMatchObject({ otherHostEntries: true })
expect((await mailPanelState({ payload: live.payload }, { ...live.options, otherHosts: [DEV] })).otherHostEntries).toBeUndefined()
// the development site keeps running beside it on its OWN database: nothing changes for it
const apart = relaySite({ fake: { allow: ['*'] }, options: DEV_HOSTS, serverURL: `https://${DEV}` })
await sendThroughRelay(apart.payload, apart.options, MESSAGE)
expect((await sendThroughRelay(apart.payload, apart.options, { ...MESSAGE, subject: 'Dev, later' })).sent).toBe(true)
// …but a development site that still runs ON the launched database now holds the live site's data: it stops by itself
forgetOtherHosts(dev.payload)
const before = dev.fake.requests.length
expect(await sendThroughRelay(dev.payload, dev.options, { ...MESSAGE, to: '[email protected]' })).toMatchObject({ cause: 'client-other-host', code: 'relay-refused', sent: false })
expect(dev.fake.requests).toHaveLength(before)
})
test('production\'s database copied BACK to the development address: the copy has a token of its own, and still mails nobody by itself', async () => {
// one service, two sites, each with a database of its own
const sites: Record<string, ReturnType<typeof callConfirmRoute>> = {}
const service = createFakeRelay({ allow: ['*'], callSite: (url, init) => sites[new URL(url).host](url, init) })
const site = (serverURL: string) => {
const made = relayPayload({ serverURL })
sites[new URL(serverURL).host] = callConfirmRoute(made.payload)
return { ...made, options: resolveRelayOptions(made.payload, { ...DEV_HOSTS, fetchImpl: service.fetch, retryBackoffMs: 1, url: service.url })! }
}
const copy = (from: Map<string, unknown>, to: Map<string, unknown>) => {
to.clear()
for (const [key, value] of from) {to.set(key, structuredClone(value))}
}
const dev = site(`https://${DEV}`)
expect((await sendThroughRelay(dev.payload, dev.options, MESSAGE)).sent).toBe(true)
// launch: the live site starts from the development site's data, and enrols by itself
const live = site('https://client.pl')
const liveOptions = live.options
copy(dev.store, live.store)
expect((await sendThroughRelay(live.payload, liveOptions, { ...MESSAGE, subject: 'Live' })).sent).toBe(true)
const liveToken = (await readRelayStore(live.payload)).token!
// months later: production's data is copied back onto the development address, to work on a bug
copy(live.store, dev.store)
forgetOtherHosts(dev.payload)
expect((await readRelayStore(dev.payload)).token).toMatch(/^ims_/) // its own old entry came back with the copy
const requests = service.requests.length
const held = await sendThroughRelay(dev.payload, dev.options, { ...MESSAGE, to: '[email protected]' })
expect(held).toMatchObject({ cause: 'client-other-host', code: 'relay-refused', confirmed: true, sent: false })
expect(service.requests).toHaveLength(requests)
expect(await mailPanelState({ payload: dev.payload }, dev.options)).toMatchObject({ nonPublic: true, relay: { connected: true, refusal: { code: 'client-other-host', reason: 'client.pl' } } })
// a developer decides that this copy sends: "Connect again", once
expect((await enrolRelay(dev.payload, dev.options, { force: true })).ok).toBe(true)
expect((await sendThroughRelay(dev.payload, dev.options, { ...MESSAGE, subject: 'On purpose' })).sent).toBe(true)
expect(service.outbox.at(-1)).toMatchObject({ host: DEV, subject: 'On purpose' })
expect((await mailPanelState({ payload: dev.payload }, dev.options)).relay?.refusal).toBeUndefined()
// the next fresh copy is held again: the consent was this database's, and the copy replaced it
copy(live.store, dev.store)
forgetOtherHosts(dev.payload)
expect(await sendThroughRelay(dev.payload, dev.options, MESSAGE)).toMatchObject({ cause: 'client-other-host', sent: false })
// production never noticed any of it
expect((await readRelayStore(live.payload)).token).toBe(liveToken)
expect(service.requests.map((r) => r.path)).not.toContain('/v1/revoke')
expect((await sendThroughRelay(live.payload, liveOptions, { ...MESSAGE, subject: 'Live, still' })).sent).toBe(true)
})
test('a staging copy of production\'s data that says it is not public (IAPL_NOINDEX) does not enrol — and uses, changes and revokes nothing of production\'s', async () => {
const production = shared({ integrations: { smtpFromName: 'Example' } })
await sendThroughRelay(production.payload, production.options, MESSAGE)
const token = (await readRelayStore(production.payload)).token!
const before = everything(production.store)
const entry = JSON.stringify(production.store.get(`iapl:mail-relay:site:${HOST}`))
const staging = production.another('https://staging.example.com')
const seen: string[] = []
// what the copy's requests carry (production's own later request is not the copy's)
production.fake.intercept = (request) => void (request.headers.get('x-intecion-site') !== HOST && seen.push(request.headers.get('authorization') ?? ''))
// a form on the copy, with production's data in it: nothing is sent, nothing is asked
vi.stubEnv('IAPL_NOINDEX', '1') // the staging process
const requests = production.fake.requests.length
const held = await sendThroughRelay(staging.payload, staging.options, { ...MESSAGE, to: '[email protected]' })
expect(held).toMatchObject({ cause: 'client-other-host', code: 'relay-refused', confirmed: true, sent: false })
expect(held.sent === false && held.detail).toContain('example.com')
expect(production.fake.requests).toHaveLength(requests)
expect(production.fake.outbox).toHaveLength(1)
// the panel and the doctor say why, before and after that send
expect(await mailPanelState({ payload: staging.payload }, staging.options)).toMatchObject({ relay: { connected: false, host: 'staging.example.com', refusal: { code: 'client-other-host', reason: HOST } } })
const untouched = production.another('https://staging-2.example.com')
expect((await mailPanelState({ payload: untouched.payload }, untouched.options)).relay?.refusal).toMatchObject({ code: 'client-other-host', reason: HOST })
expect(await mailPanelState({ payload: staging.payload }, staging.options)).toMatchObject({ nonPublic: true, relay: { connected: false, host: 'staging.example.com', refusal: { code: 'client-other-host', reason: HOST } } })
// "Disconnect" on the copy revokes nothing of production's
await disconnectRelay(untouched.payload, untouched.options)
await disconnectRelay(staging.payload, staging.options)
expect(production.fake.requests.filter((r) => r.path === '/v1/revoke')).toEqual([])
expect((await readRelayStore(production.payload)).token).toBe(token)
expect(JSON.stringify(production.store.get(`iapl:mail-relay:site:${HOST}`))).toBe(entry)
// an admin decides that the copy sends: "Connect again", once — then it is a site of its own and heals by itself
expect(await enrolRelay(staging.payload, staging.options, { force: true })).toEqual({ ok: true, state: 'active' })
@@ -741,7 +830,7 @@ describe('the token over time', () => {
expect(own).not.toBe(token)
await production.fake.handle(new Request(`${production.fake.url}/v1/revoke`, { headers: { authorization: `Bearer ${own}`, 'x-intecion-site': 'staging.example.com' }, method: 'POST' }))
expect((await sendThroughRelay(staging.payload, staging.options, { ...MESSAGE, subject: 'Healed' })).sent).toBe(true)
// also when its token is gone altogether (another container rotated it away): it has been connected, so it enrols
// also when its token is gone altogether (another container rotated it away)
await updateRelayStore(staging.payload, (c) => ({ ...c, token: undefined }))
expect((await sendThroughRelay(staging.payload, staging.options, { ...MESSAGE, subject: 'Healed again' })).sent).toBe(true)
// a token the service delivers for ONE host waits beside that host's token only: the other host never tries it
@@ -750,36 +839,75 @@ describe('the token over time', () => {
await callConfirmRoute(staging.payload)('https://staging.example.com/api/iapl/mail-relay/confirm', { body: JSON.stringify({ nonce, state: 'active', token: `ims_${'s'.repeat(43)}` }), headers: {} })
expect((await readRelayCandidate(staging.payload))?.token).toBe(`ims_${'s'.repeat(43)}`)
expect(await readRelayCandidate(production.payload)).toBeNull()
vi.stubEnv('IAPL_NOINDEX', '') // production's process
const sends = production.fake.requests.length
expect((await sendThroughRelay(production.payload, production.options, { ...MESSAGE, subject: 'Its own token' })).sent).toBe(true)
expect(production.fake.requests.slice(sends).map((r) => r.path)).toEqual(['/v1/send'])
expect(seen.every((header) => !header.includes(token))).toBe(true)
expect(JSON.stringify([staging.logger.warn.mock.calls, staging.logger.error.mock.calls])).not.toContain('ims_')
// production's entry is byte for byte what it was, and production sends on
expect((await readRelayStore(production.payload)).token).toBe(token)
expect(JSON.parse(before).find(([key]: [string]) => key === `iapl:mail-relay:site:${HOST}`)).toEqual([`iapl:mail-relay:site:${HOST}`, production.store.get(`iapl:mail-relay:site:${HOST}`)])
production.fake.intercept = undefined
expect((await sendThroughRelay(production.payload, production.options, { ...MESSAGE, subject: 'From production' })).sent).toBe(true)
})
test('a moved domain, a second domain, or a project that wants copies to enrol: `otherHosts`', async () => {
test('`www` and the bare domain are one site, also for a non-public one: neither holds the other', async () => {
const apex = shared({ options: DEV_HOSTS, serverURL: `https://${DEV}` })
const www = apex.another(`https://www.${DEV}`, DEV_HOSTS)
expect(siteIsNonPublic(www.payload, www.options)).toBe(true)
for (const site of [apex, www, apex, www]) {expect((await sendThroughRelay(site.payload, site.options, MESSAGE)).sent).toBe(true)}
expect(apex.fake.requests.filter((r) => r.path === '/v1/enrol')).toHaveLength(2)
expect((await mailPanelState({ payload: www.payload }, www.options)).otherHostEntries).toBeUndefined()
// the launched site names the development address once, with or without `www.`: both forms count
const live = apex.another('https://www.client.pl', { otherHosts: [`www.${DEV}`] })
expect((await sendThroughRelay(live.payload, live.options, MESSAGE)).sent).toBe(true)
expect((await mailPanelState({ payload: live.payload }, live.options)).otherHostEntries).toBeUndefined()
})
test('what remains possible: a staging copy that forgot to say it is not public enrols and sends like a launch — the panel state and the doctor name it', async () => {
const production = shared()
await sendThroughRelay(production.payload, production.options, MESSAGE)
const staging = production.another('https://staging.example.com') // no IAPL_NOINDEX, no development host
const sent = await sendThroughRelay(staging.payload, staging.options, { ...MESSAGE, to: '[email protected]' })
expect(sent).toMatchObject({ sent: true }) // the plugin cannot tell this from launch day
expect(await mailPanelState({ payload: staging.payload }, staging.options)).toMatchObject({ otherHostEntries: true, relay: { connected: true } })
expect((await mailPanelState({ payload: staging.payload }, staging.options)).nonPublic).toBeUndefined()
// the same site once it says so: held from the next e-mail on, although it has a token by now
vi.stubEnv('IAPL_NOINDEX', '1')
forgetOtherHosts(staging.payload)
expect(await sendThroughRelay(staging.payload, staging.options, MESSAGE)).toMatchObject({ cause: 'client-other-host', sent: false })
})
test('a domain move needs nobody; `otherHosts` — \'wait\', \'enrol\', the site\'s own hosts; the rule ends when its reason does', async () => {
const old = shared()
await sendThroughRelay(old.payload, old.options, MESSAGE)
// the same data under a new domain: waits by default …
// the same data under a new, public host: enrols by itself
const moved = old.another('https://example.org')
expect(await sendThroughRelay(moved.payload, moved.options, MESSAGE)).toMatchObject({ cause: 'client-other-host', sent: false })
// … named as the site's own old host, it enrols by itself
const named = old.another('https://example.net', { otherHosts: ['example.com'] })
expect((await sendThroughRelay(named.payload, named.options, MESSAGE)).sent).toBe(true)
// (the list names hosts: a third one in the way still stops it — example.net is now there too)
const third = old.another('https://example.info', { otherHosts: ['example.com'] })
expect(await sendThroughRelay(third.payload, third.options, MESSAGE)).toMatchObject({ cause: 'client-other-host' })
const any = old.another('https://copy.example.dev', { otherHosts: 'enrol' })
expect((await sendThroughRelay(moved.payload, moved.options, MESSAGE)).sent).toBe(true)
expect(old.fake.outbox.at(-1)?.host).toBe('example.org')
// 'wait': the rule of the first cut — a public site without a connection of its own waits too
const waiting = old.another('https://example.net', { otherHosts: 'wait' })
expect(await sendThroughRelay(waiting.payload, waiting.options, MESSAGE)).toMatchObject({ cause: 'client-other-host', sent: false })
// ('wait' holds a site WITHOUT a connection: the old domain, connected long ago, sends on beside the new hosts)
expect((await sendThroughRelay(old.payload, { ...old.options, otherHosts: 'wait' }, MESSAGE)).sent).toBe(true)
// …and the wait ends at once when the project names the other hosts as the site's own (no cool-down in the way)
const named = { ...waiting.options, otherHosts: ['example.com', 'www.example.org'] }
expect((await sendThroughRelay(waiting.payload, named, MESSAGE)).sent).toBe(true)
expect((await readRelayStore(waiting.payload, 'example.net')).refusal).toBeFalsy()
// a non-public copy with 'enrol': the project took the rule away
const any = old.another('https://copy.dev.agency-example.com', { ...DEV_HOSTS, otherHosts: 'enrol' })
expect((await sendThroughRelay(any.payload, any.options, MESSAGE)).sent).toBe(true)
// a site before launch — an empty store — enrols by itself, as ever
const fresh = relaySite({ fake: { allow: [HOST] } })
expect((await sendThroughRelay(fresh.payload, fresh.options, MESSAGE)).sent).toBe(true)
// a non-public copy that names SOME hosts as its own still stops for the others
const partly = old.another('https://two.dev.agency-example.com', { ...DEV_HOSTS, otherHosts: ['example.com'] })
expect(await sendThroughRelay(partly.payload, partly.options, MESSAGE)).toMatchObject({ cause: 'client-other-host', sent: false })
// …the panel shows that refusal from the store, and drops it the moment its reason is gone (no send needed)
expect((await mailPanelState({ payload: partly.payload }, partly.options)).relay?.refusal).toMatchObject({ code: 'client-other-host' })
expect((await readRelayStore(partly.payload, 'two.dev.agency-example.com')).refusal).toMatchObject({ code: 'client-other-host' })
expect((await mailPanelState({ payload: partly.payload }, { ...partly.options, otherHosts: 'enrol' })).relay?.refusal).toBeUndefined()
// …and one that names ALL of them (with or without `www.`) sends by itself
const others = (await otherRelayHosts(partly.payload, 'two.dev.agency-example.com')).map((h) => (h === 'example.com' ? 'www.example.com' : h))
expect(others.length).toBeGreaterThan(2)
expect((await sendThroughRelay(partly.payload, { ...partly.options, otherHosts: others }, MESSAGE)).sent).toBe(true)
expect(siteIsNonPublic(partly.payload, { developmentHosts: ['*.dev.other.example', 'two.dev.agency-exam*'], host: undefined })).toBe(true)
expect(siteIsNonPublic(partly.payload, { developmentHosts: ['dev.agency-example.com', '*.agency-example'], host: undefined })).toBe(false)
})
})