Files
ipal-kit/test/accountRulesReloadSuite.ts
Radosław SmolińskiandClaude Fable 5.2 0a4f001797 IAPL rename, scripted: preferred names in src, bin, scripts, services, tests; bin files and skill folders moved
Replaced by an explicit list of forms only (ten exported names, runtime env names, project file
names and marks, commands, skill names, the log prefix, the brand in prose). Package name, import
paths, routes, CSS tokens, data attributes, custom keys, context flags, the cookie and kv keys are
not touched. package.json keeps the five old bin names beside the five new ones.
The old names stop working in this commit and come back as aliases in the next; docs follow.

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

97 lines
5.9 KiB
TypeScript

/**
* A dev reload (review round 3, R3-2): Payload swaps `payload.config` and runs no onInit. A staff collection that a
* plugin listed after iapl adds must keep the account rules on the new config — with 2FA off and on.
* Real HTTP; SQLite by default, Postgres / MongoDB with IPAL_TEST_POSTGRES_URI / IPAL_TEST_MONGO_URI.
*/
import type { Config, Payload, Plugin, SanitizedConfig } from 'payload'
import { payloadTotp } from '@clocklimited/payload-2fa'
import { lexicalEditor } from '@payloadcms/richtext-lexical'
import os from 'os'
import path from 'path'
import { getPayload } from 'payload'
import { expect, test } from 'vitest'
import { iapl } from '../src/plugin.js'
import { buildTestConfig } from './helpers.js'
import { testDatabase } from './http/db.js'
import { startPayloadServer } from './http/server.js'
const PASSWORD = 'a-long-test-password-1'
const late: Plugin = (config: Config) => ({
...config,
collections: [...(config.collections ?? []), { slug: 'late-staff', auth: true, fields: [{ name: 'roles', type: 'select', hasMany: true, options: ['user', 'editor', 'admin'] }], versions: true }],
})
const makeConfig = (twoFactor: boolean) =>
buildTestConfig({
admin: { user: 'users' },
collections: [
{ slug: 'customers', access: { create: () => true }, auth: true, fields: [] },
{ slug: 'media', fields: [], upload: { staticDir: path.join(os.tmpdir(), 'ipal-test-media') } },
],
db: testDatabase(twoFactor ? 'reload_2fa' : 'reload'),
editor: lexicalEditor(),
plugins: [
iapl({ access: { authCollection: 'users', staffCollections: ['late-staff'] }, i18n: { defaultLocale: 'en', locales: [{ code: 'en', label: 'English' }] }, twoFactor: twoFactor ? { issuer: 'Example', plugin: payloadTotp, verifyLimit: false } : false }),
late,
],
secret: 'integration-test-secret-0123456789',
telemetry: false,
})
/** One Payload instance per test file (Payload caches it): run from a file of its own for 2FA off and on. */
export function reloadSuite(twoFactor: boolean): void {
test(`a late staff collection keeps its rules over a dev reload (2FA on: ${twoFactor})`, async () => {
const config = makeConfig(twoFactor)
const payload: Payload = await getPayload({ config })
const server = await startPayloadServer(config)
const call = (method: string, pathname: string, body?: unknown, headers: Record<string, string> = {}) =>
fetch(`${server.url}/api${pathname}`, { body: body === undefined ? undefined : JSON.stringify(body), headers: { 'content-type': 'application/json', ...headers }, method })
const round = async (when: string) => {
const tag = `${when.replace(/\W+/g, "-")}-${Math.random().toString(36).slice(2)}`
// an EMPTY late staff collection: its first-user route, in two spellings
const before = (await payload.count({ collection: 'late-staff' as never })).totalDocs
for (const spelling of ['/first-register', '/First-Register']) {
expect([when, spelling, (await call('POST', `/late-staff${spelling}`, { email: `first-${tag}@example.com`, password: PASSWORD, roles: ['admin'] })).status]).toEqual([when, spelling, 403])
}
expect([when, (await payload.count({ collection: 'late-staff' as never })).totalDocs]).toEqual([when, before])
// a visitor account
expect((await call('POST', '/customers', { email: `c-${tag}@example.com`, password: PASSWORD })).status).toBe(201)
const token = ((await (await call('POST', '/customers/login', { email: `c-${tag}@example.com`, password: PASSWORD })).json()) as { token: string }).token
const visitor = { authorization: `JWT ${token}` }
const victim = await payload.create({ collection: 'late-staff' as never, data: { email: `v-${tag}@example.com`, password: PASSWORD, roles: ['user'] } as never })
const got = {
create: (await call('POST', '/late-staff', { email: `x-${tag}@example.com`, password: PASSWORD, roles: ['admin'] }, visitor)).status,
delete: (await call('DELETE', `/late-staff/${victim.id}`, undefined, visitor)).status,
patch: (await call('PATCH', `/late-staff/${victim.id}`, { password: 'taken-over-password-1' }, visitor)).status,
read: (await call('GET', '/late-staff', undefined, visitor)).status,
unlock: (await call('POST', '/late-staff/unlock', { email: `v-${tag}@example.com` }, visitor)).status,
versions: (await call('GET', '/late-staff/versions', undefined, visitor)).status,
}
expect([when, got]).toEqual([when, { create: 403, delete: 403, patch: 403, read: 403, unlock: 403, versions: 403 }])
// the password rule is on the collection too
await expect(payload.create({ collection: 'late-staff' as never, data: { email: `s-${tag}@example.com`, password: 'tooshort', roles: ['user'] } as never })).rejects.toThrow()
await payload.delete({ collection: 'late-staff' as never, where: { email: { contains: tag } } })
}
try {
await round('start')
// what Payload's dev `reload()` does: a NEW sanitized config is assigned first, the collections after it
const next = await makeConfig(twoFactor)
const live = payload as unknown as { collections: Record<string, { config: unknown; customIDType?: unknown }>; config: SanitizedConfig; globals: { config: unknown } }
live.config = next
live.collections = Object.fromEntries(next.collections.map((c) => [c.slug, { config: c, customIDType: live.collections[c.slug]?.customIDType }]))
live.globals = { config: next.globals }
await round('after the reload')
// and once more: a second reload meets a fresh config again
const third = await makeConfig(twoFactor)
live.config = third
live.collections = Object.fromEntries(third.collections.map((c) => [c.slug, { config: c, customIDType: live.collections[c.slug]?.customIDType }]))
live.globals = { config: third.globals }
await round('after a second reload')
} finally {
await server.close()
await payload.destroy?.()
}
}, 120_000)
}