/** * Sign-in rules of the staff collections (1.18.0, accounts.signInLimit / signInSameOrigin / confirmOwnChanges), through * real HTTP requests against a running Payload. Shared by signInRules.test.ts (2FA on), signInRules2faOff.test.ts and * signInRulesOff.test.ts (every rule switched off): one Payload per file. * Database: SQLite in memory, or IPAL_TEST_POSTGRES_URI / IPAL_TEST_MONGO_URI (test/http/db.ts). */ import type { Payload } from 'payload' import { payloadTotp } from '@clocklimited/payload-2fa' import { lexicalEditor } from '@payloadcms/richtext-lexical' import { getPayload } from 'payload' import { afterAll, beforeAll } from 'vitest' import { iapl } from '../src/plugin.js' import { buildTestConfig } from './helpers.js' import { testDatabase } from './http/db.js' import { cookiesOf, startPayloadServer, type TestServer } from './http/server.js' import { totp } from './http/totp.js' export const SECRET = 'JBSWY3DPEHPK3PXP' export const PASSWORD = 'a-long-test-password-1' export const FOREIGN = { origin: 'https://blog.site.example', 'sec-fetch-site': 'same-site' } export type Answer = { body: string; status: number } export function signInSite({ off = false, twoFactor = true }: { off?: boolean; twoFactor?: boolean } = {}) { const state = {} as { mails: string[]; payload: Payload; server: TestServer } beforeAll(async () => { state.mails = [] const config = buildTestConfig({ admin: { user: 'users' }, collections: [ { slug: 'customers', access: { create: () => true }, auth: true, fields: [] }, { slug: 'media', fields: [], upload: { staticDir: '/tmp/iapl-sign-in-rules-media' } }, ], db: testDatabase('signinrules'), editor: lexicalEditor(), email: () => ({ name: 'count', defaultFromAddress: 'site@example.com', defaultFromName: 'Site', sendEmail: async (m: { to?: unknown }) => void state.mails.push(String(m.to)) }) as never, plugins: [ iapl({ access: { authCollection: 'users' }, ...(off ? { accounts: { confirmOwnChanges: false, signInLimit: false, signInSameOrigin: false } } : {}), i18n: { defaultLocale: 'en', locales: [{ code: 'en', label: 'English' }] }, mail: { relay: false }, twoFactor: twoFactor ? { issuer: 'Example', plugin: payloadTotp } : false, }), ], secret: 'integration-test-secret-0123456789', telemetry: false, }) state.payload = await getPayload({ config }) state.server = await startPayloadServer(config) const make = (email: string, roles: string[]) => state.payload.create({ collection: 'users' as never, data: { email, password: PASSWORD, roles, ...(twoFactor ? { totpSecret: SECRET } : {}) } as never }) for (const [email, role] of [['owner@example.com', 'admin'], ['admin2@example.com', 'admin'], ['editor@example.com', 'editor'], ['editor2@example.com', 'editor'], ['office@example.com', 'editor'], ['fold@example.com', 'editor']] as const) { await make(email, [role]) } await state.payload.create({ collection: 'customers' as never, data: { email: 'client@example.com', password: PASSWORD } as never }) }, 120_000) afterAll(async () => { await state.server?.close() await state.payload?.destroy?.() }) const call = async (path: string, body: unknown, headers: Record = {}, method = 'POST'): Promise => { const res = await fetch(`${state.server.url}/api${path}`, { body: JSON.stringify(body), headers: { 'content-type': 'application/json', ...headers }, method }) return { body: await res.text(), status: res.status } } const login = (email: string, password: string, ip: string, extra: Record = {}) => call('/users/login', { email, password }, { 'x-real-ip': ip, ...extra }) const gqlLogin = async (email: string, password: string, ip: string, extra: Record = {}) => { const res = await call('/graphql', { query: `mutation { loginUser(email: ${JSON.stringify(email)}, password: ${JSON.stringify(password)}) { token } }` }, { 'x-real-ip': ip, ...extra }) const error = (JSON.parse(res.body) as { errors?: { extensions?: { statusCode?: number }; message: string }[] }).errors?.[0] return { message: error?.message, status: error?.extensions?.statusCode } } /** A fully signed-in session (password, then the code when 2FA is on): the cookie header. */ const session = async (email: string, password = PASSWORD, ip = '203.0.113.200') => { const res = await fetch(`${state.server.url}/api/users/login`, { body: JSON.stringify({ email, password }), headers: { 'content-type': 'application/json', 'x-real-ip': ip }, method: 'POST' }) const first = cookiesOf(res) if (!twoFactor) {return first.join('; ')} const verify = await fetch(`${state.server.url}/api/verify-totp`, { body: JSON.stringify({ token: totp(SECRET) }), headers: { 'content-type': 'application/json', cookie: first.join('; ') }, method: 'POST' }) return [...first, ...cookiesOf(verify)].join('; ') } const idOf = async (email: string) => ((await state.payload.find({ collection: 'users' as never, overrideAccess: true, where: { email: { equals: email } } })).docs[0] as { id: number | string }).id const stored = async (email: string) => (await state.payload.find({ collection: 'users' as never, overrideAccess: true, showHiddenFields: true, where: { email: { equals: email } } })).docs[0] as { lockUntil?: null | string } | undefined return { call, gqlLogin, idOf, login, session, state, stored } }