Files
ipal-kit/test/accountRulesSingleLoginSuite.ts
T
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

90 lines
5.5 KiB
TypeScript

/**
* The project's own LOGIN collection with a single-valued role select and no rules (review of branch A, K-1):
* `admin.user: 'people'`, no `access` option, `roles` = select `user, editor, admin, boss` WITHOUT hasMany.
* The plugin counts roles only from an array, so nobody there is a plugin admin whatever the field says; on such a
* collection the admin rules would mean that NOBODY can create, change, delete or unlock accounts — the account
* holding `admin` included. It keeps "an account of this collection", as on 1.16.7.
* Real HTTP; SQLite by default, Postgres / MongoDB with the usual variables; 2FA off and on (one file each).
*/
import type { Payload } 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 { cookiesOf, startPayloadServer } from './http/server.js'
import { totp } from './http/totp.js'
const PASSWORD = 'a-long-test-password-1'
const TOTP_SECRET = 'JBSWY3DPEHPK3PXP'
/** One Payload instance per test file: run from a file of its own for 2FA off and on. */
export function singleLoginSuite(twoFactor: boolean): void {
test(`a login collection with a single role select: its accounts keep managing each other (2FA on: ${twoFactor})`, async () => {
const config = buildTestConfig({
admin: { user: 'people' },
collections: [
{ slug: 'people', auth: true, fields: [{ name: 'roles', type: 'select', options: ['user', 'editor', 'admin', 'boss'] }] },
{ slug: 'customers', access: { create: () => true }, auth: true, fields: [] },
{ slug: 'media', fields: [], upload: { staticDir: path.join(os.tmpdir(), 'ipal-test-media') } },
],
db: testDatabase(twoFactor ? 'single_login_2fa' : 'single_login'),
editor: lexicalEditor(),
plugins: [iapl({ i18n: { defaultLocale: 'en', locales: [{ code: 'en', label: 'English' }] }, twoFactor: twoFactor ? { issuer: 'Example', plugin: payloadTotp, verifyLimit: false } : false })],
secret: 'integration-test-secret-0123456789',
telemetry: false,
})
const payload: Payload = await getPayload({ config })
const server = await startPayloadServer(config)
type Session = Record<string, string>
const call = (method: string, pathname: string, session: Session = {}, body?: unknown) =>
fetch(`${server.url}/api${pathname}`, { body: body === undefined ? undefined : JSON.stringify(body), headers: { 'content-type': 'application/json', ...session }, method })
const make = (email: string, role: string) => payload.create({ collection: 'people' as never, data: { email, password: PASSWORD, roles: role, ...(twoFactor ? { totpSecret: TOTP_SECRET } : {}) } as never })
/** A full login: with 2FA on, the code too. */
const login = async (collection: string, email: string): Promise<Session> => {
const res = await call('POST', `/${collection}/login`, {}, { email, password: PASSWORD })
const body = (await res.json()) as { token?: string }
if (!body.token) {throw new Error(`login failed for ${email}`)}
if (!twoFactor || collection !== 'people') {return { authorization: `JWT ${body.token}` }}
const cookies = cookiesOf(res)
const verify = await fetch(`${server.url}/api/verify-totp`, { body: JSON.stringify({ token: totp(TOTP_SECRET) }), headers: { 'content-type': 'application/json', cookie: cookies.join('; ') }, method: 'POST' })
expect(((await verify.json()) as { ok?: boolean }).ok).toBe(true)
return { cookie: [...cookies, ...cookiesOf(verify)].join('; ') }
}
try {
const victim = await make('[email protected]', 'user')
await make('[email protected]', 'user')
await make('[email protected]', 'boss')
await make('[email protected]', 'admin')
const got: Record<string, unknown> = {}
for (const who of ['low', 'boss', 'admin']) {
const session = await login('people', `${who}@example.com`)
got[who] = {
create: (await call('POST', '/people', session, { email: `by-${who}@example.com`, password: PASSWORD, roles: 'user' })).status,
patch: (await call('PATCH', `/people/${victim.id}`, session, { password: `changed-by-${who}-123456` })).status,
unlock: (await call('POST', '/people/unlock', session, { email: '[email protected]' })).status,
}
}
// as on 1.16.7: every account of the login collection, the one holding `admin` included
const yes = { create: 201, patch: 200, unlock: 200 }
expect(got).toEqual({ admin: yes, boss: yes, low: yes })
expect((await call('DELETE', `/people/${victim.id}`, await login('people', '[email protected]'))).status).toBe(200)
// what is still closed: an account of another collection, and nobody
expect((await call('POST', '/customers', {}, { email: '[email protected]', password: PASSWORD })).status).toBe(201)
const visitor = await login('customers', '[email protected]')
for (const [name, session] of [['a visitor account', visitor], ['nobody', {}]] as [string, Session][]) {
expect([name, (await call('POST', '/people', session, { email: `x-${name.length}@example.com`, password: PASSWORD, roles: 'admin' })).status, (await call('GET', '/people', session)).status]).toEqual([name, 403, 403])
}
} finally {
await server.close()
await payload.destroy?.()
}
}, 120_000)
}