IWSN: "Połącz z IWSN" — a person of Intecion connects the site (contract 1.8.0)

- the state block on the e-mail tab (method IWSN): the button while the service offers the confirmation page
  (connectAvailable) or before the site has enrolled; a click asks the site's server for the link
  (POST /api/iapl/mail-relay/connect-link, admin only), which asks the service (POST /v1/connect, enrolling first),
  checks that it begins with the service's own {base}/connect?, and hands it over without storing or logging it;
  the browser opens it in a new tab with noopener noreferrer; the block asks /v1/status every 5 s for 10 min
- states: waiting for confirmation (button), waiting for approval (no page), connected, stopped; 503
  connect-unavailable and 429 said in the admin's language; a load of the panel asks the service while the site waits
- dashboard alert for a waiting site (live); doctor mail-relay-connect (error) — replaces the pending warning and the
  "not enrolled yet" note of mail-relay-state
- opt-out mail.relay.connectButton: false (no button, no route); building blocks requestRelayConnectLink,
  isRelayConnectUrl, RELAY_CONNECT_LINK_PATH; the fake service implements /v1/connect, connectAvailable and
  confirmConnect
- contract copy 1.8.0 (IWDL working tree, checksums match); docs, AGENT.md, setup / upgrade / debug skills, changelog

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
Radosław Smoliński
2026-12-01 21:42:23 +01:00
co-authored by Claude Opus 5.5
parent 347e3bafa1
commit 2c0262367d
41 changed files with 1113 additions and 57 deletions
+20 -3
View File
@@ -728,7 +728,7 @@ describe('iapl-doctor: first-seen dates', () => {
})
describe('e-mail: transport, the mail service, Graph, the confirm route', () => {
const ids = ['mail-transport', 'mail-method', 'mail-non-public', 'mail-relay-state', 'mail-reply-address', 'mail-graph-deprecated', 'mail-relay-route']
const ids = ['mail-transport', 'mail-method', 'mail-non-public', 'mail-relay-connect', 'mail-relay-state', 'mail-reply-address', 'mail-graph-deprecated', 'mail-relay-route']
const relay = (extra: object = {}) => ({ connected: true, disconnected: false, nameReplaced: false, state: 'active', ...extra })
const mail = (extra: object = {}) => ({ graphEnv: false, relay: relay(), replyAddress: true, status: null, transport: 'relay', ...extra })
const run = async (deep: null | object, files: Record<string, string> = {}) =>
@@ -747,12 +747,29 @@ describe('e-mail: transport, the mail service, Graph, the confirm route', () =>
expect(await run(failing('2026-10-27T09:00:00.000Z'))).toEqual(['mail-transport:error'])
})
test('mail-relay-connect: the method is IWSN and the site is not connected — an error, and the fix names the button or Intecion', async () => {
const find = async (deep: object) => (await doctor(project({ ...base(), 'src/payload.config.ts': 'iapl({ forms: {} })' }), ids, { deepStatus: { mail: mail(deep) } })).findings.filter((f) => f.rule === 'mail-relay-connect')
const button = await find({ relay: relay({ connectAvailable: true, state: 'pending' }) })
expect(button.map((f) => f.severity)).toEqual(['error'])
expect(button[0].message).toContain('not confirmed yet')
expect(button[0].fix).toContain('Połącz z IWSN')
const noButton = await find({ relay: relay({ state: 'pending' }) })
expect(noButton[0].fix).toContain('ask Intecion')
const never = await find({ relay: relay({ connected: false, state: undefined }) })
expect(never[0].message).toContain('not connected yet')
expect(never[0].fix).toContain('Połącz z IWSN')
// nothing for: connected and active, suspended, disconnected, a refused enrolment, another method
for (const deep of [{}, { relay: relay({ state: 'suspended' }) }, { relay: relay({ connected: false, disconnected: true }) }, { relay: relay({ connected: false, refusal: 'callback-failed', state: undefined }) }, { relay: relay({ connectAvailable: true, state: 'pending' }), transport: 'smtp' }]) {
expect(await find(deep), JSON.stringify(deep)).toEqual([])
}
})
test('mail-relay-state: disconnected, suspended, pending, refused, not enrolled yet, a replaced sender name', async () => {
expect(await run(mail({ relay: relay({ connected: false, disconnected: true }) }))).toEqual(['mail-relay-state:error'])
expect(await run(mail({ relay: relay({ state: 'suspended' }) }))).toEqual(['mail-relay-state:error'])
expect(await run(mail({ relay: relay({ state: 'pending' }) }))).toEqual(['mail-relay-state:warning'])
expect(await run(mail({ relay: relay({ state: 'pending' }) }))).toEqual(['mail-relay-connect:error'])
expect(await run(mail({ relay: relay({ connected: false, reason: 'redirect', refusal: 'callback-failed', state: undefined }) }))).toEqual(['mail-relay-state:warning'])
expect(await run(mail({ relay: relay({ connected: false, state: undefined }) }))).toEqual(['mail-relay-state:info'])
expect(await run(mail({ relay: relay({ connected: false, state: undefined }) }))).toEqual(['mail-relay-connect:error'])
// a copy of another site's database: it does not connect by itself, and the finding says what to do
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'])
+150
View File
@@ -0,0 +1,150 @@
/**
* "Połącz z IWSN" — contract 1.8.0 §2.1, against the fake service (src/modules/email/relay/fake.ts), which the
* contract's examples check (test/mailRelayContract.test.ts):
* - a waiting site asks for the link on an admin's click (never by itself), gets it only when it begins with
* the service's own `{base}/connect?`, never stores or logs it;
* - a person's confirmation on the service's page makes the site active; the site learns it from /v1/status;
* - the answers the contract lists: active, suspended, 503 connect-unavailable, 429, no token yet.
*/
import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest'
import { RELAY_BASE_URL } from '../src/modules/email/relay/constants.js'
import { mailPanelState } from '../src/modules/email/relay/panel.js'
import { sendThroughRelay } from '../src/modules/email/relay/send.js'
import { getRelayStatus, isRelayConnectUrl, LOCAL_CODES, refreshRelayStatus, requestRelayConnectLink } from '../src/modules/email/relay/session.js'
import { readRelayStore } from '../src/modules/email/relay/store.js'
import { setRateLimitStore } from '../src/modules/shared/rateLimit.js'
import { relaySite } from './mailRelay/helpers.js'
const MESSAGE = { html: '<p>Hello.</p>', subject: 'New enquiry', to: '[email protected]' }
const HOST = 'example.com'
const logged = (logger: Record<string, { mock: { calls: unknown[][] } }>) => JSON.stringify(Object.values(logger).flatMap((fn) => fn.mock.calls))
beforeEach(() => {
setRateLimitStore(null)
for (const name of ['GRAPH_TENANT_ID', 'GRAPH_CLIENT_ID', 'GRAPH_CLIENT_SECRET', 'GRAPH_SENDER', 'IAPL_NOINDEX', 'IPAL_NOINDEX']) {vi.stubEnv(name, '')}
})
afterEach(() => vi.unstubAllEnvs())
/** A site under the service's `connect` policy: every new site waits (nothing is listed). */
const waitingSite = () => relaySite({ fake: { allow: [] }, integrations: { smtpFromAddress: '[email protected]' } })
describe('the link', () => {
test('isRelayConnectUrl: the service\'s own `{base}/connect?ref=<43>` and nothing else', () => {
const ref = 'a'.repeat(43)
expect(isRelayConnectUrl(`${RELAY_BASE_URL}/connect?ref=${ref}`, RELAY_BASE_URL)).toBe(true)
expect(isRelayConnectUrl(`${RELAY_BASE_URL}/connect?ref=${ref}`, `${RELAY_BASE_URL}/`)).toBe(true)
for (const bad of [
`https://evil.example/mail/connect?ref=${ref}`,
`${RELAY_BASE_URL}.evil.example/connect?ref=${ref}`,
`${RELAY_BASE_URL}/connect?ref=${ref}&next=https://evil.example`,
`${RELAY_BASE_URL}/connect?ref=${'a'.repeat(42)}`,
`${RELAY_BASE_URL}/other?ref=${ref}`,
`${RELAY_BASE_URL}/connect#ref=${ref}`,
`javascript:alert(1)//${RELAY_BASE_URL}/connect?ref=${ref}`,
42,
undefined,
]) {expect(isRelayConnectUrl(bad, RELAY_BASE_URL), String(bad)).toBe(false)}
})
})
describe('a waiting site is connected by a person of Intecion', () => {
test('enrol (pending) → the click asks for a link → the person confirms → /v1/status says active → mail leaves', async () => {
const { fake, logger, options, payload } = waitingSite()
// the site enrols on its first e-mail and waits: the mail is refused, the panel shows the button
expect(await sendThroughRelay(payload, options, MESSAGE)).toMatchObject({ cause: 'site-pending', sent: false })
await refreshRelayStatus(payload, options)
expect(await getRelayStatus(payload, options)).toMatchObject({ connectAvailable: true, connected: true, state: 'pending' })
expect(await mailPanelState({ payload }, options)).toMatchObject({ connectButton: true, relay: { connectAvailable: true, state: 'pending' } })
// nothing asked for a link by itself
expect(fake.requests.filter((r) => r.path === '/v1/connect')).toEqual([])
const link = await requestRelayConnectLink(payload, options)
expect(link).toMatchObject({ ok: true, state: 'pending' })
if (!link.ok || link.state !== 'pending') {throw new Error('no link')}
expect(link.connectUrl.startsWith(`${fake.url}/connect?ref=`)).toBe(true)
expect(Date.parse(link.expiresAt) - Date.now()).toBeGreaterThan(14 * 60_000)
// never stored, never logged
expect(JSON.stringify(await readRelayStore(payload))).not.toContain(link.connectUrl.split('ref=')[1])
expect(logged(logger)).not.toContain(link.connectUrl.split('ref=')[1])
// the person signs in on the service's page and presses "Potwierdź"
expect(fake.confirmConnect(link.connectUrl)).toBe(true)
expect(fake.confirmConnect(link.connectUrl)).toBe(false) // one confirmation per link
// the site asks (the panel does it every 5 s); then it is active and sends
await refreshRelayStatus(payload, options)
expect(await getRelayStatus(payload, options)).toMatchObject({ connected: true, state: 'active' })
expect((await getRelayStatus(payload, options)).connectAvailable).toBeUndefined()
expect(await sendThroughRelay(payload, options, MESSAGE)).toMatchObject({ sent: true })
// and the button now answers "connected", with no link
expect(await requestRelayConnectLink(payload, options)).toEqual({ ok: true, state: 'active' })
})
test('each click makes a new link and the earlier one stops working; a link expires after 15 minutes', async () => {
let clock = Date.parse('2026-12-01T10:00:00Z')
const { fake, options, payload } = relaySite({ fake: { allow: [], now: () => clock } })
await sendThroughRelay(payload, options, MESSAGE)
const first = await requestRelayConnectLink(payload, options)
const second = await requestRelayConnectLink(payload, options)
if (!first.ok || first.state !== 'pending' || !second.ok || second.state !== 'pending') {throw new Error('no link')}
expect(second.connectUrl).not.toBe(first.connectUrl)
expect(fake.confirmConnect(first.connectUrl)).toBe(false)
clock += 15 * 60_000 + 1
expect(fake.confirmConnect(second.connectUrl)).toBe(false)
expect(fake.site(HOST)?.state).toBe('pending')
})
test('no token yet: the click enrols first, then asks for the link — also on a site that enrols by hand only', async () => {
for (const enrol of ['auto', 'manual'] as const) {
const { fake, options, payload } = relaySite({ fake: { allow: [] }, options: { enrol } })
const link = await requestRelayConnectLink(payload, options)
expect(link).toMatchObject({ ok: true, state: 'pending' })
expect(fake.requests.map((r) => r.path)).toEqual(['/v1/enrol', '/v1/connect'])
}
// `enrol: false` (a token from elsewhere only): nothing to connect
const off = relaySite({ fake: { allow: [] }, options: { enrol: false } })
expect(await requestRelayConnectLink(off.payload, off.options)).toMatchObject({ ok: false })
expect(off.fake.requests).toEqual([])
})
test('the answers the contract lists: suspended, 503 connect-unavailable, 429 after ten links an hour', async () => {
const suspended = waitingSite()
await sendThroughRelay(suspended.payload, suspended.options, MESSAGE)
suspended.fake.setSite(HOST, 'suspended')
expect(await requestRelayConnectLink(suspended.payload, suspended.options)).toMatchObject({ code: 'site-suspended', ok: false })
expect((await readRelayStore(suspended.payload)).state).toBe('suspended')
const unavailable = relaySite({ fake: { allow: [], connect: 'unavailable' } })
await sendThroughRelay(unavailable.payload, unavailable.options, MESSAGE)
const requests = unavailable.fake.requests.length
expect(await requestRelayConnectLink(unavailable.payload, unavailable.options)).toMatchObject({ code: 'connect-unavailable', ok: false, retryable: false })
expect(unavailable.fake.requests).toHaveLength(requests + 1) // not retried
await refreshRelayStatus(unavailable.payload, unavailable.options)
expect((await getRelayStatus(unavailable.payload, unavailable.options)).connectAvailable).toBeUndefined() // no button
const many = waitingSite()
await sendThroughRelay(many.payload, many.options, MESSAGE)
for (let i = 0; i < 10; i++) {expect((await requestRelayConnectLink(many.payload, many.options)).ok).toBe(true)}
const eleventh = await requestRelayConnectLink(many.payload, many.options)
expect(eleventh).toMatchObject({ code: 'rate-limited', ok: false })
expect(eleventh.ok === false && eleventh.retryAfter).toBeGreaterThan(0)
})
test('a link that is not the service\'s own is refused, not returned, not logged', async () => {
const { fake, logger, options, payload } = waitingSite()
await sendThroughRelay(payload, options, MESSAGE)
const evil = `https://evil.example/mail/connect?ref=${'e'.repeat(43)}`
fake.intercept = (request) => (new URL(request.url).pathname.endsWith('/v1/connect') ? Response.json({ connectUrl: evil, expiresAt: new Date(Date.now() + 60_000).toISOString(), ok: true, state: 'pending' }) : undefined)
const answer = await requestRelayConnectLink(payload, options)
expect(answer).toMatchObject({ code: LOCAL_CODES.badConnectUrl, ok: false })
expect(JSON.stringify(answer)).not.toContain('evil.example')
expect(logged(logger)).not.toContain('evil.example')
expect(JSON.stringify(await readRelayStore(payload))).not.toContain('evil.example')
})
test('`mail.relay.connectButton: false`: the panel is not offered the button', async () => {
const { options, payload } = waitingSite()
await sendThroughRelay(payload, options, MESSAGE)
expect((await mailPanelState({ payload }, { ...options, connectButton: false })).connectButton).toBeUndefined()
})
})
+155
View File
@@ -0,0 +1,155 @@
/**
* "Połącz z IWSN" on a running Payload (SQLite by default; MongoDB / Postgres through IPAL_TEST_*_URI), through
* real HTTP requests: the admin-only route that hands the panel the link (contract 1.8.0 §2.1), the status route
* that asks the service on load while the site waits, the dashboard alert, and the opt-out.
*/
import type { Payload } from 'payload'
import { lexicalEditor } from '@payloadcms/richtext-lexical'
import os from 'os'
import path from 'path'
import { getPayload } from 'payload'
import { renderToStaticMarkup } from 'react-dom/server'
import { afterAll, beforeAll, describe, expect, test, vi } from 'vitest'
import { mailAdapter } from '../src/modules/email/mailAdapter.js'
import { RELAY_CONNECT_LINK_PATH, RELAY_STATUS_PATH } from '../src/modules/email/relay/constants.js'
import { createFakeRelay } from '../src/modules/email/relay/fake.js'
import { IntegrationAlerts } from '../src/modules/integrations/IntegrationAlerts.js'
import { iapl } from '../src/plugin.js'
import { buildTestConfig } from './helpers.js'
import { testDatabase } from './http/db.js'
import { startPayloadServer, type TestServer } from './http/server.js'
vi.mock('server-only', () => ({}))
vi.mock('next/headers.js', async () => (await import('./http/server.js')).nextHeadersMock)
const PASSWORD = 'a-long-test-password-1'
const HOST = 'example.com'
let server: TestServer
let payload: Payload
let admin: Record<string, string>
let editor: Record<string, string>
// the service's `connect` policy: nothing is listed, every new site waits
const fake = createFakeRelay({ allow: [], callSite: async (url, init) => fetch(`${server.url}${new URL(url).pathname}`, { ...init, redirect: 'manual' }) })
const makeConfig = (relay: object, name: string) =>
buildTestConfig({
admin: { user: 'users' },
collections: [{ slug: 'media', fields: [], upload: { staticDir: path.join(os.tmpdir(), 'iapl-connect-media') } }],
db: testDatabase(name),
editor: lexicalEditor(),
email: mailAdapter(),
plugins: [iapl({ access: { authCollection: 'users' }, i18n: { defaultLocale: 'pl', locales: [{ code: 'pl', label: 'Polski' }] }, mail: { relay: { fetchImpl: fake.fetch, url: fake.url, ...relay } }, twoFactor: false })],
secret: 'integration-test-secret-0123456789',
serverURL: `https://${HOST}`,
telemetry: false,
})
const login = async (email: string) => {
const res = await fetch(`${server.url}/api/users/login`, { body: JSON.stringify({ email, password: PASSWORD }), headers: { 'content-type': 'application/json' }, method: 'POST' })
return { authorization: `JWT ${((await res.json()) as { token: string }).token}` }
}
const api = (pathname: string, headers: Record<string, string>, init: RequestInit = {}) => fetch(`${server.url}/api${pathname}`, { ...init, headers: { 'content-type': 'application/json', ...headers } })
const alert = async () => {
const out = await IntegrationAlerts({ payload, user: (await payload.find({ collection: 'users' as never, where: { email: { equals: '[email protected]' } } })).docs[0] as never })
return out ? renderToStaticMarkup(out) : ''
}
beforeAll(async () => {
const config = makeConfig({}, 'relayconnect')
payload = await getPayload({ config })
server = await startPayloadServer(config)
await payload.updateGlobal({ slug: 'site-integrations' as never, data: { smtpFromAddress: '[email protected]', smtpFromName: 'Kancelaria Example' } as never })
await payload.create({ collection: 'users' as never, data: { email: '[email protected]', password: PASSWORD, roles: ['admin'] } as never })
await payload.create({ collection: 'users' as never, data: { email: '[email protected]', password: PASSWORD, roles: ['editor'] } as never })
admin = await login('[email protected]')
editor = await login('[email protected]')
}, 120_000)
afterAll(async () => {
await server?.close()
await payload?.destroy?.()
})
describe('the panel side of contract 1.8.0 §2.1', () => {
test('a waiting site: the alert, the status on load asks the service, the button\'s route hands the link to an admin only', async () => {
// nothing enrolled yet: no alert (nothing waits yet), the button would enrol first
expect(await alert()).toBe('')
// the first e-mail enrols, the site waits, the mail is not sent
expect(await payload.sendEmail({ html: '<p>Hello.</p>', subject: 'First', to: '[email protected]' })).toMatchObject({ sent: false })
expect(fake.site(HOST)?.state).toBe('pending')
// the dashboard alert says so, live, to an admin
expect(await alert()).toMatch(/czeka na potwierdzenie|waiting for confirmation/i)
// a panel load of a waiting site asks the service (contract §2.1: "on every panel load")
const before = fake.requests.filter((r) => r.path === '/v1/status').length
const loaded = (await (await api(RELAY_STATUS_PATH, admin)).json()) as { connectButton?: boolean; relay: { connectAvailable?: boolean; state: string } }
expect(fake.requests.filter((r) => r.path === '/v1/status').length).toBe(before + 1)
expect(loaded).toMatchObject({ connectButton: true, relay: { connectAvailable: true, state: 'pending' } })
// nobody but an admin gets a link, and a load never asks for one
expect(fake.requests.filter((r) => r.path === '/v1/connect')).toEqual([])
expect((await fetch(`${server.url}/api${RELAY_CONNECT_LINK_PATH}`, { method: 'POST' })).status).toBe(401)
expect((await api(RELAY_CONNECT_LINK_PATH, editor, { method: 'POST' })).status).toBe(403)
expect(fake.requests.filter((r) => r.path === '/v1/connect')).toEqual([])
const res = await api(RELAY_CONNECT_LINK_PATH, admin, { method: 'POST' })
expect(res.status).toBe(200)
expect(res.headers.get('cache-control')).toContain('no-store')
const body = (await res.json()) as { connectUrl: string; expiresAt: string; ok: boolean }
expect(body.ok).toBe(true)
expect(body.connectUrl.startsWith(`${fake.url}/connect?ref=`)).toBe(true)
// the token is not in the answer
expect(JSON.stringify(body)).not.toContain('ims_')
// the person confirms; the next status read (the panel polls it) says active, the alert is gone, mail leaves
expect(fake.confirmConnect(body.connectUrl)).toBe(true)
const after = (await (await api(`${RELAY_STATUS_PATH}?refresh=1`, admin)).json()) as { relay: { connectAvailable?: boolean; state: string } }
expect(after.relay.state).toBe('active')
expect(after.relay.connectAvailable).toBeUndefined()
expect(await payload.sendEmail({ html: '<p>Hello.</p>', subject: 'Second', to: '[email protected]' })).toMatchObject({ transport: 'relay' })
// (the first send's refusal stays recorded until a send works: then the alert is gone)
expect(await alert()).toBe('')
// an active site's load does not ask the service
const quiet = fake.requests.length
await api(RELAY_STATUS_PATH, admin)
expect(fake.requests).toHaveLength(quiet)
// the button on an active site answers "connected", no link
const again = (await (await api(RELAY_CONNECT_LINK_PATH, admin, { method: 'POST' })).json()) as { connectUrl?: string; ok: boolean }
expect(again).toMatchObject({ ok: true })
expect(again.connectUrl).toBeUndefined()
// a site that waits without any send having recorded it (the status says "ok"): the alert reads it live
fake.site(HOST)!.state = 'pending'
await api(`${RELAY_STATUS_PATH}?refresh=1`, admin)
expect(await alert()).toMatch(/czeka na potwierdzenie|waiting for confirmation/i)
fake.site(HOST)!.state = 'active'
await api(`${RELAY_STATUS_PATH}?refresh=1`, admin)
expect(await alert()).toBe('')
})
test('the service has no confirmation page: the route says whom to ask, with no link', async () => {
fake.site(HOST)!.state = 'pending'
fake.connect = 'unavailable'
try {
const res = await api(RELAY_CONNECT_LINK_PATH, admin, { method: 'POST' })
expect(res.status).toBe(502)
const body = (await res.json()) as { code: string; connectUrl?: string; error: string; ok: boolean }
expect(body).toMatchObject({ code: 'connect-unavailable', ok: false })
expect(body.error).toMatch(/administratora|administrator/)
expect(body.connectUrl).toBeUndefined()
} finally {
fake.connect = 'available'
fake.site(HOST)!.state = 'active'
}
})
})
test('`mail.relay.connectButton: false`: no route, and the panel is not offered the button', async () => {
const config = await makeConfig({ connectButton: false }, 'relayconnectoff')
expect((config.endpoints ?? []).map((e) => e.path)).not.toContain(RELAY_CONNECT_LINK_PATH)
const on = await makeConfig({}, 'relayconnecton')
expect((on.endpoints ?? []).map((e) => e.path)).toContain(RELAY_CONNECT_LINK_PATH)
})
+1
View File
@@ -146,6 +146,7 @@ describe('the fake service speaks the contract (the contract\'s runner, every ex
if (site && given.quota === 'hour-share-used') {site.hourOther = Math.floor((fake.limits.messagesPerHour * 4) / 5)}
if (site && given.quota === 'recipient-exhausted') {site.confirmations.set(RECIPIENT, fake.limits.perRecipientPerDay)}
if (given.backend) {fake.backend = given.backend as 'failure'}
if (given.connect) {fake.connect = given.connect as 'unavailable'}
const vars = { alertRecipient: ALERTS, host: HOST, idempotencyKey: randomBytes(18).toString('base64url'), nonce: randomBytes(32).toString('base64url'), recipient: RECIPIENT, senderAddress: '[email protected]', token }
if (given.idempotency === 'sent-same' || given.idempotency === 'sent-other') {
const body = expand(example.request.body, vars, example.id) as Record<string, unknown>