Files
ipal-kit/test/http/server.ts
T
Radosław SmolińskiandClaude Fable 5.2 0c61ac231b Security: staff checks only for staff collections; 2FA covers what the plugin adds
Staff check (userMeetsRole): the 'no roles field = every account passes'
rule applied to the account's own collection, so an account of a second
auth collection (customers) passed every staff check. It now applies only
to staff collections: the panel's login collection plus the new
access.staffCollections. The injected auth collection uses the new
adminOrSelfIn(slug), so an account of another collection with the same
numeric id is not 'self'.

2FA: @clocklimited/payload-2fa wraps the collections and globals present
when it runs; ipalKit's own globals and collections were added later and
stayed unwrapped, so a password without the TOTP code opened them over
REST and GraphQL. ipal-kit now has its own second-factor check
(secondFactorPassed / requireSecondFactor): applied to every collection
and global at the end of ipalKit, again in onInit for entities added by
plugins listed after it, and inside userMeetsRole and the endpoints that
take a project access function. It fails closed: an unrecognised user
shape is refused, and startup stops when the injected 2FA plugin lacks
the parts the check reads (twoFactor.guard: false opts out).

Tests through real HTTP requests (REST and GraphQL) against Payload's
route handlers, plus the reference smoke test. Docs, agent guide, skills
and the reference skills copy updated; changelog entry without a version.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
2026-11-24 00:31:55 +01:00

90 lines
4.1 KiB
TypeScript

import type { SanitizedConfig } from 'payload'
import { GRAPHQL_POST, REST_DELETE, REST_GET, REST_PATCH, REST_POST } from '@payloadcms/next/routes'
import { AsyncLocalStorage } from 'node:async_hooks'
import { createServer, type Server } from 'node:http'
/**
* Payload's own REST and GraphQL route handlers (the ones a Next app mounts under /api) behind a real HTTP
* server, so a test sends real requests: login, cookies, `Authorization` headers.
*
* @clocklimited/payload-2fa reads and writes its cookie through `next/headers`, which only works inside a Next
* request. A test file that turns 2FA on mocks that module with `nextHeadersMock` below:
* vi.mock('next/headers.js', async () => (await import('./http/server.js')).nextHeadersMock)
*/
type CookieJar = { incoming: Map<string, string>; outgoing: string[] }
const jar = new AsyncLocalStorage<CookieJar>()
export const nextHeadersMock = {
cookies: () => {
const store = jar.getStore()
return Promise.resolve({
get: (name: string) => (store?.incoming.has(name) ? { name, value: store.incoming.get(name)! } : undefined),
set: (name: string, value: string) => {
store?.outgoing.push(`${name}=${value}; Path=/; HttpOnly`)
},
})
},
headers: () => Promise.resolve(new Headers()),
}
export type TestServer = { close: () => Promise<void>; url: string }
export async function startPayloadServer(config: Promise<SanitizedConfig>): Promise<TestServer> {
const rest = { DELETE: REST_DELETE(config), GET: REST_GET(config), PATCH: REST_PATCH(config), POST: REST_POST(config) }
const graphql = GRAPHQL_POST(config)
const server: Server = createServer((req, res) => {
const chunks: Buffer[] = []
req.on('data', (c: Buffer) => chunks.push(c))
req.on('end', () => {
void (async () => {
const url = new URL(req.url ?? '/', `http://${req.headers.host}`)
const headers = new Headers()
for (const [k, v] of Object.entries(req.headers)) {
if (typeof v === 'string') {headers.set(k, v)}
}
const method = (req.method ?? 'GET').toUpperCase()
const body = method === 'GET' || method === 'HEAD' ? undefined : Buffer.concat(chunks)
const request = new Request(url, { body, headers, method })
const incoming = new Map(
(req.headers.cookie ?? '').split(';').map((p) => p.trim()).filter(Boolean).map((p) => {
const i = p.indexOf('=')
return [p.slice(0, i), p.slice(i + 1)] as [string, string]
}),
)
const store: CookieJar = { incoming, outgoing: [] }
try {
const response = await jar.run(store, async () => {
if (url.pathname === '/api/graphql') {return graphql(request)}
const handler = rest[method as keyof typeof rest]
if (!handler) {return new Response('Method not allowed', { status: 405 })}
const slug = url.pathname.replace(/^\/api\/?/, '').split('/').filter(Boolean)
return handler(request, { params: Promise.resolve({ slug }) })
})
const setCookies = [...response.headers.getSetCookie(), ...store.outgoing]
response.headers.forEach((value, key) => {
if (key !== 'set-cookie') {res.setHeader(key, value)}
})
if (setCookies.length) {res.setHeader('set-cookie', setCookies)}
res.statusCode = response.status
res.end(Buffer.from(await response.arrayBuffer()))
} catch (err) {
res.statusCode = 500
res.end(err instanceof Error ? err.stack : String(err))
}
})()
})
})
await new Promise<void>((resolve) => server.listen(0, '127.0.0.1', resolve))
const address = server.address()
const port = typeof address === 'object' && address ? address.port : 0
return {
close: () => new Promise<void>((resolve) => server.close(() => resolve())),
url: `http://127.0.0.1:${port}`,
}
}
/** `name=value` pairs of a response's Set-Cookie headers, ready for a `cookie` request header. */
export const cookiesOf = (res: Response): string[] => res.headers.getSetCookie().map((c) => c.split(';')[0])