Files
ipal-kit/test/mailRelayConnect.test.ts
T
Radosław SmolińskiandClaude Opus 5.5 2c0262367d 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]>
2026-12-01 21:42:23 +01:00

151 lines
9.3 KiB
TypeScript

/**
* "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()
})
})