/** * "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: '

Hello.

', subject: 'New enquiry', to: 'office@example.org' } const HOST = 'example.com' const logged = (logger: Record) => 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: 'biuro@example.com' } }) 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() }) })