156 lines
8.6 KiB
TypeScript
156 lines
8.6 KiB
TypeScript
/**
|
|
* "Połącz z IWSN" on a running Payload (SQLite by default; MongoDB / Postgres through IPAL_TEST_MONGO_URI / IPAL_TEST_POSTGRES_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)
|
|
})
|