Files
ipal-kit/test/accountRulesSuite.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

981 lines
79 KiB
TypeScript

/**
* M1 account rules over real HTTP (SQLite by default; Postgres / MongoDB with IPAL_TEST_POSTGRES_URI /
* IPAL_TEST_MONGO_URI): who may open the panel, who may create, change or delete an account, what a
* password must be. One suite, run twice: with 2FA off (accountRules.test.ts) and with 2FA on
* (accountRules2fa.test.ts) — the 2FA package rewrites every collection's access, and a rule that
* holds without it may not hold with it.
*/
import type { Config, Payload, Plugin } from 'payload'
import { payloadTotp } from '@clocklimited/payload-2fa'
import { lexicalEditor } from '@payloadcms/richtext-lexical'
import { pbkdf2Sync, randomBytes } from 'node:crypto'
import os from 'os'
import path from 'path'
import { getPayload } from 'payload'
import { afterAll, beforeAll, describe, expect, test } from 'vitest'
import type { I18nConfig } from '../src/modules/i18n/types.js'
import { adminOrSelfIn } from '../src/modules/access/index.js'
import { countBelowPanelRole, panelAccess, resolvePanelRole } from '../src/modules/access/panelRole.js'
import { buildPasswordRuleHook, checkPassword, resolvePasswordRule } from '../src/modules/access/passwordRule.js'
import { isPasswordRuleHook, markedStaffRule, staffRuleOf } from '../src/modules/access/ruleMark.js'
import { adoptLateAuthCollections, bothAllow, canHoldStaffRole, hasPluginRoles, openSignUpCollections, rolesAreAList, rolesNotOwn, sameStaffCollectionAccess, staffCollectionsNobodyManages, staffCollectionsOnOwnRoles, staffCollectionsOpenToOthers, staffCreateAccess, staffReadAccess, staffUpdateAccess, unknownStaffCollections } from '../src/modules/access/selfRegistration.js'
import { requireSecondFactor } from '../src/modules/security/totp/secondFactor.js'
import { iapl } from '../src/plugin.js'
import { buildTestConfig, withTotpParts } from './helpers.js'
import { testDatabase } from './http/db.js'
import { cookiesOf, startPayloadServer, type TestServer } from './http/server.js'
import { totp } from './http/totp.js'
const TOTP_SECRET = 'JBSWY3DPEHPK3PXP'
/** A plugin the project lists AFTER iapl: its auth collections did not exist when iapl ran (review round 2, R2-3). */
const latePlugin: Plugin = (config: Config) => ({
...config,
collections: [
...(config.collections ?? []),
{ slug: 'late-staff', auth: true, fields: [{ name: 'roles', type: 'select', hasMany: true, options: ['user', 'editor', 'admin'], saveToJWT: true }], versions: true },
{ slug: 'late-members', auth: true, fields: [] },
],
})
/** The whole suite; `twoFactor` = run it with the 2FA package on. */
export function accountRulesSuite(twoFactor: boolean): void {
const i18n: I18nConfig = { defaultLocale: 'en', locales: [{ code: 'en', label: 'English' }] }
const PASSWORD = 'a-long-test-password-1'
let server: TestServer
let payload: Payload
type Session = Record<string, string>
const call = (pathname: string, session: Session = {}, init: RequestInit = {}) =>
fetch(`${server.url}/api${pathname}`, { ...init, headers: { 'content-type': 'application/json', ...session, ...(init.headers as Record<string, string> | undefined) } })
const post = (pathname: string, body: unknown, session: Session = {}) => call(pathname, session, { body: JSON.stringify(body), method: 'POST' })
const sessions = new Map<string, Session>()
/** A full login. With 2FA on, an account of the 2FA collection (`users`) also types its code. */
const login = async (collection: string, email: string, password = PASSWORD): Promise<Session> => {
const key = `${collection}|${email}|${password}`
const known = sessions.get(key)
if (known) {return known}
const res = await post(`/${collection}/login`, { email, password })
const body = (await res.json()) as { token?: string }
if (!body.token) {throw new Error(`login failed for ${email}: ${JSON.stringify(body)}`)}
let session: Session = { authorization: `JWT ${body.token}` }
if (twoFactor && collection === 'users') {
// accounts made over HTTP in a test have no secret yet: give them one, as their owner would on the setup screen
await payload.update({ collection: 'users' as never, data: { totpSecret: TOTP_SECRET } as never, where: { email: { equals: email } } })
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' })
const verified = (await verify.json()) as { ok?: boolean }
if (!verified.ok) {throw new Error(`2FA failed for ${email}: ${JSON.stringify(verified)}`)}
session = { cookie: [...cookies, ...cookiesOf(verify)].join('; ') }
}
sessions.set(key, session)
return session
}
/** Password only: with 2FA on, a `users` session that still owes its code. */
const passwordOnly = async (email: string): Promise<Session> => ({ authorization: `JWT ${((await (await post('/users/login', { email, password: PASSWORD })).json()) as { token: string }).token}` })
const make = (collection: string, data: Record<string, unknown>) =>
payload.create({ collection: collection as never, data: { password: PASSWORD, ...(twoFactor && collection === 'users' ? { totpSecret: TOTP_SECRET } : {}), ...data } as never })
const patch = (pathname: string, body: unknown, session: Session = {}) => call(pathname, session, { body: JSON.stringify(body), method: 'PATCH' })
const remove = (pathname: string, session: Session = {}) => call(pathname, session, { method: 'DELETE' })
const idOf = async (collection: string, email: string) => (await payload.find({ collection: collection as never, where: { email: { equals: email } } })).docs[0]?.id
const canLogIn = async (collection: string, email: string, password = PASSWORD) => (await post(`/${collection}/login`, { email, password })).status === 200
beforeAll(async () => {
const config = buildTestConfig({
admin: { user: 'users' },
collections: [
{ slug: 'customers', access: { create: () => true }, auth: true, fields: [] },
{ slug: 'members', auth: true, fields: [] },
{ slug: 'staff2', auth: true, fields: [] }, // a second staff collection, without roles and without rules
// a staff collection with the project's OWN role values and no rules: the plugin cannot tell who its admins are
{ slug: 'crew', auth: true, fields: [{ name: 'roles', type: 'select', hasMany: true, options: ['boss', 'worker'] }] },
// a staff collection with the plugin's role values, written by the project, no rules
{ slug: 'agents', auth: true, fields: [{ name: 'roles', type: 'select', hasMany: true, options: ['user', 'editor', 'admin'], saveToJWT: true }], versions: true },
{ slug: 'media', fields: [], upload: { staticDir: path.join(os.tmpdir(), 'ipal-test-media') } },
],
db: testDatabase(twoFactor ? 'accounts_2fa' : 'accounts'),
editor: lexicalEditor(),
plugins: [iapl({ access: { authCollection: 'users', staffCollections: ['staff2', 'crew', 'agents', 'late-staff'] }, i18n, twoFactor: twoFactor ? { issuer: 'Example', plugin: payloadTotp, verifyLimit: false } : false }), latePlugin],
secret: 'integration-test-secret-0123456789',
telemetry: false,
})
payload = await getPayload({ config })
server = await startPayloadServer(config)
}, 120_000)
afterAll(async () => {
await server?.close()
await payload?.destroy?.()
})
// The owner's rule: nobody creates an account for themselves; only the first account of a site, as admin.
describe('no self-registration (accounts.adminOnlyCreate, accounts.firstUserRoute)', () => {
const rolesOf = async (email: string) => ((await payload.find({ collection: 'users' as never, where: { email: { equals: email } } })).docs[0] as { roles?: string[] } | undefined)?.roles
const count = async (collection: string) => (await payload.count({ collection: collection as never })).totalDocs
test('an empty site: an anonymous request creates no staff account, over REST or GraphQL', async () => {
expect((await post('/users', { email: '[email protected]', password: PASSWORD })).status).toBe(403)
expect((await post('/users', { email: '[email protected]', password: PASSWORD, roles: ['admin'] })).status).toBe(403)
expect((await post('/staff2', { email: '[email protected]', password: PASSWORD })).status).toBe(403)
const gql = (await (await post('/graphql', { query: `mutation { createUser(data: { email: "[email protected]", password: "${PASSWORD}", roles: [admin] }) { id } }` })).json()) as { errors?: unknown[] }
expect(gql.errors?.length).toBeGreaterThan(0)
expect(await count('users')).toBe(0)
expect(await count('staff2')).toBe(0)
})
test("the first-user route of other empty auth collections is closed — a second STAFF collection included", async () => {
// before: 200 for each of them while empty; a first account in `staff2` would have been staff
expect((await post('/staff2/first-register', { email: '[email protected]', password: PASSWORD })).status).toBe(403)
expect((await post('/members/first-register', { email: '[email protected]', password: PASSWORD })).status).toBe(403)
expect(await count('staff2')).toBe(0)
expect(await count('members')).toBe(0)
})
test('…in every spelling Payload\'s router accepts or might: letter case, slashes, encoding, query', async () => {
// the first cut read the path and missed /First-Register: an anonymous visitor became a staff admin
const spellings = ['/first-register', '/first-register/', '/First-Register', '/FIRST-REGISTER', '/fIrSt-ReGiStEr', '/first-registe%72', '//first-register', '/first-register?x=1', '/first-register;x', '/First-Register/?x=1']
for (const collection of ['staff2', 'crew', 'agents', 'members', 'late-staff', 'late-members']) {
for (const spelling of spellings) {
const res = await post(`/${collection}${spelling}`, { email: `sp-${Math.random().toString(36).slice(2)}@example.com`, password: PASSWORD, roles: ['admin'] })
expect([collection, spelling, res.status === 200 || res.status === 201]).toEqual([collection, spelling, false])
}
expect([collection, await count(collection)]).toEqual([collection, 0])
}
})
test('a collection that allows sign-up keeps its routes', async () => {
expect((await post('/customers/first-register', { email: '[email protected]', password: PASSWORD })).status).toBe(200)
expect((await post('/customers', { email: '[email protected]', password: PASSWORD })).status).toBe(201)
expect((await post('/members', { email: '[email protected]', password: PASSWORD })).status).toBe(403)
})
test('the first account of the site registers through the first-user route and is an admin; the route then closes', async () => {
// in a spelling of its own: the account is still the first one, and still an admin
const first = await post('/users/First-Register', { email: '[email protected]', password: PASSWORD, roles: ['user'] })
expect(first.status).toBe(200)
expect(((await first.json()) as { token?: string }).token).toBeTypeOf('string')
expect(first.headers.getSetCookie().join(';')).toMatch(/payload-token=/)
expect(await rolesOf('[email protected]')).toEqual(['admin'])
for (const spelling of ['/first-register', '/First-Register', '/FIRST-REGISTER/']) {
expect((await post(`/users${spelling}`, { email: '[email protected]', password: PASSWORD })).status).toBe(403)
}
expect(await rolesOf('[email protected]')).toBeUndefined()
expect((await post('/users', { email: '[email protected]', password: PASSWORD })).status).toBe(403)
})
test('only an admin creates staff accounts — not an editor, not a plain user, not asking for a role', async () => {
await make('users', { email: '[email protected]', roles: ['editor'] })
await make('users', { email: '[email protected]', roles: ['user'] })
for (const who of ['[email protected]', '[email protected]']) {
const session = await login('users', who)
expect([who, (await post('/users', { email: `by-${who}`, password: PASSWORD, roles: ['admin'] }, session)).status]).toEqual([who, 403])
expect([who, (await post('/staff2', { email: `by-${who}`, password: PASSWORD }, session)).status]).toEqual([who, 403])
}
const admin = await login('users', '[email protected]')
expect((await post('/users', { email: '[email protected]', password: PASSWORD, roles: ['editor'] }, admin)).status).toBe(201)
expect(await rolesOf('[email protected]')).toEqual(['editor'])
// an admin of the panel's collection makes the first account of the second staff collection
expect((await post('/staff2', { email: '[email protected]', password: PASSWORD }, admin)).status).toBe(201)
// a visitor account is nobody here
const visitor = await login('customers', '[email protected]')
expect((await post('/users', { email: '[email protected]', password: PASSWORD }, visitor)).status).toBe(403)
expect((await post('/staff2', { email: '[email protected]', password: PASSWORD }, visitor)).status).toBe(403)
// GraphQL is the same rule
const gql = (await (await post('/graphql', { query: `mutation { createUser(data: { email: "[email protected]", password: "${PASSWORD}", roles: [admin] }) { id } }` }, visitor)).json()) as { errors?: unknown[] }
expect(gql.errors?.length).toBeGreaterThan(0)
expect(await idOf('users', '[email protected]')).toBeUndefined()
})
test('a session that still owes its second factor creates nothing', async () => {
if (!twoFactor) {return}
const half = await passwordOnly('[email protected]')
expect((await post('/users', { email: '[email protected]', password: PASSWORD }, half)).status).toBe(403)
expect((await post('/staff2', { email: '[email protected]', password: PASSWORD }, half)).status).toBe(403)
expect((await post('/crew', { email: '[email protected]', password: PASSWORD }, half)).status).toBe(403)
})
})
// Closing `create` alone is little help while Payload's default for `update` and `delete` is "any logged-in user".
describe('nobody takes an account over (accounts.adminOnlyWrite)', () => {
const NEW = 'taken-over-password-1'
let admin: Session
let visitor: Session
let editor: Session
let plain: Session
beforeAll(async () => {
admin = await login('users', '[email protected]')
visitor = await login('customers', '[email protected]')
await make('users', { email: '[email protected]', roles: ['editor'] })
await make('users', { email: '[email protected]', roles: ['user'] })
editor = await login('users', '[email protected]')
plain = await login('users', '[email protected]')
await make('agents', { email: '[email protected]', roles: ['admin'] })
await make('agents', { email: '[email protected]', roles: ['editor'] })
await make('staff2', { email: '[email protected]' })
await make('crew', { email: '[email protected]', roles: ['boss'] })
await make('crew', { email: '[email protected]', roles: ['worker'] })
})
test.each(['agents', 'staff2', 'crew'])('%s (the project\'s own staff collection, no rules): a visitor account and an anonymous request change and delete nothing', async (collection) => {
const email = { agents: '[email protected]', crew: '[email protected]', staff2: '[email protected]' }[collection]!
const id = await idOf(collection, email)
for (const [who, session] of [['visitor', visitor], ['anonymous', {}]] as [string, Session][]) {
// before: 200 for the visitor — a staff account's password and roles
expect([who, (await patch(`/${collection}/${id}`, { password: NEW, roles: ['admin'] }, session)).status]).toEqual([who, 403])
await patch(`/${collection}?where[email][equals]=${email}`, { password: NEW }, session) // bulk: whatever it answers…
expect([who, (await remove(`/${collection}/${id}`, session)).status]).toEqual([who, 403])
await remove(`/${collection}?where[email][equals]=${email}`, session)
}
// …nothing happened
expect(await idOf(collection, email)).toBe(id)
expect(await canLogIn(collection, email, NEW)).toBe(false)
expect(await canLogIn(collection, email)).toBe(true)
})
test('where the roles are the plugin\'s: an admin changes and deletes; anyone else only its own account, and not its roles', async () => {
const victim = await idOf('agents', '[email protected]')
const own = await idOf('agents', '[email protected]')
const agentEditor = await login('agents', '[email protected]')
// an editor of the same collection, and an editor / plain user of the panel's collection
for (const [who, session] of [['agent editor', agentEditor], ['editor', editor], ['plain', plain]] as [string, Session][]) {
expect([who, (await patch(`/agents/${victim}`, { password: NEW }, session)).status]).toEqual([who, 403])
expect([who, (await remove(`/agents/${victim}`, session)).status]).toEqual([who, 403])
}
expect(await canLogIn('agents', '[email protected]', NEW)).toBe(false)
// its own account: yes — and never a delete
expect((await patch(`/agents/${own}`, { password: 'my-own-new-password-1' }, agentEditor)).status).toBe(200)
expect(await canLogIn('agents', '[email protected]', 'my-own-new-password-1')).toBe(true)
expect((await remove(`/agents/${own}`, agentEditor)).status).toBe(403)
// the injected collection: the same, and the roles field is the admin's
const me = await idOf('users', '[email protected]')
await patch(`/users/${me}`, { roles: ['admin'] }, editor)
expect(((await payload.findByID({ id: me as never, collection: 'users' as never })) as { roles?: string[] }).roles).toEqual(['editor'])
expect((await patch(`/users/${await idOf('users', '[email protected]')}`, { password: NEW }, editor)).status).toBe(403)
// an admin: everything
const spare = await make('agents', { email: '[email protected]', roles: ['user'] })
expect((await patch(`/agents/${spare.id}`, { roles: ['editor'] }, admin)).status).toBe(200)
expect((await remove(`/agents/${spare.id}`, admin)).status).toBe(200)
})
test('where the roles are the project\'s own: accounts of that collection keep working as before; a plugin admin too; nobody else', async () => {
// the plugin cannot tell a `boss` from a `worker`: the project's own rules decide inside the collection
const boss = await login('crew', '[email protected]')
expect((await post('/crew', { email: '[email protected]', password: PASSWORD, roles: ['worker'] }, boss)).status).toBe(201)
const id = await idOf('crew', '[email protected]')
expect((await patch(`/crew/${id}`, { roles: ['boss'] }, boss)).status).toBe(200)
expect((await remove(`/crew/${id}`, boss)).status).toBe(200)
// an admin of the panel's collection
expect((await post('/crew', { email: '[email protected]', password: PASSWORD, roles: ['worker'] }, admin)).status).toBe(201)
// an editor of another staff collection, a visitor, nobody
for (const [who, session] of [['editor', editor], ['plain', plain], ['visitor', visitor], ['anonymous', {}]] as [string, Session][]) {
expect([who, (await post('/crew', { email: `by-${who}@crew.example.com`, password: PASSWORD, roles: ['boss'] }, session)).status]).toEqual([who, 403])
}
})
// Review round 2 (R2-2): the default "the account itself may update" must not reach the roles.
test('nobody raises its own role: a lowest-role account of a second staff collection stays what it is', async () => {
await make('agents', { email: '[email protected]', roles: ['user'] })
const low = await login('agents', '[email protected]')
const id = await idOf('agents', '[email protected]')
const rolesOf = async (collection: string, of: unknown) => ((await payload.findByID({ id: of as never, collection: collection as never })) as { roles?: string[] }).roles
for (const body of [{ roles: ['admin'] }, { roles: 'admin' }, { password: 'another-long-password-1', roles: ['admin', 'user'] }]) {
await patch(`/agents/${id}`, body, low)
expect(await rolesOf('agents', id)).toEqual(['user'])
}
await patch('/agents?where[email][equals][email protected]', { roles: ['admin'] }, low) // bulk
expect(await rolesOf('agents', id)).toEqual(['user'])
const gql = await post('/graphql', { query: `mutation { updateAgent(id: ${typeof id === 'number' ? id : `"${id}"`}, data: { roles: [admin] }) { id } }` }, low)
await gql.text()
expect(await rolesOf('agents', id)).toEqual(['user'])
// the rest of its own account is its own (the password above was changed)
expect(await canLogIn('agents', '[email protected]', 'another-long-password-1')).toBe(true)
// and it opens nothing an admin opens
expect((await call('/globals/site-integrations', low)).status).toBe(403)
// an admin gives roles
expect((await patch(`/agents/${id}`, { roles: ['editor'] }, admin)).status).toBe(200)
expect(await rolesOf('agents', id)).toEqual(['editor'])
// role values of the project's own: the plugin cannot rank them, but an account still never changes its own
const worker = await login('crew', '[email protected]')
const workerId = await idOf('crew', '[email protected]')
await patch(`/crew/${workerId}`, { roles: ['boss'] }, worker)
await patch('/crew?where[email][equals][email protected]', { roles: ['boss'] }, worker)
expect(await rolesOf('crew', workerId)).toEqual(['worker'])
// somebody else of the collection does (what the project's own rules must narrow — said by the doctor)
const boss = await login('crew', '[email protected]')
expect((await patch(`/crew/${workerId}`, { roles: ['boss'] }, boss)).status).toBe(200)
expect(await rolesOf('crew', workerId)).toEqual(['boss'])
await payload.update({ id: workerId as never, collection: 'crew' as never, data: { roles: ['worker'] } as never })
})
// Payload's defaults for `read` and `unlock` are "any logged-in user" too.
test('a visitor account does not list staff accounts or unlock them; staff does (accounts.staffOnlyRead)', async () => {
for (const collection of ['agents', 'staff2', 'crew', 'late-staff']) {
for (const [who, session] of [['visitor', visitor], ['anonymous', {}]] as [string, Session][]) {
expect([collection, who, (await call(`/${collection}`, session)).status]).toEqual([collection, who, 403])
expect([collection, who, (await post(`/${collection}/unlock`, { email: '[email protected]' }, session)).status]).toEqual([collection, who, 403])
}
expect([collection, (await call(`/${collection}`, editor)).status]).toEqual([collection, 200]) // staff reads staff
}
// versions hold what the accounts hold (review round 3, R3-3)
await payload.update({ collection: 'agents' as never, data: { roles: ['admin'] } as never, where: { email: { equals: '[email protected]' } } })
for (const collection of ['agents', 'late-staff']) {
for (const [who, session] of [['visitor', visitor], ['anonymous', {}]] as [string, Session][]) {
const res = await call(`/${collection}/versions`, session)
expect([collection, who, res.status]).toEqual([collection, who, 403])
expect(await res.text()).not.toContain('[email protected]')
}
expect([collection, (await call(`/${collection}/versions`, editor)).status]).toEqual([collection, 200])
}
const gql = (await (await post('/graphql', { query: '{ Agents { docs { email } } }' }, visitor)).json()) as { data?: unknown; errors?: unknown[] }
expect(JSON.stringify(gql)).not.toContain('[email protected]')
expect((await post('/agents/unlock', { email: '[email protected]' }, editor)).status).toBe(403)
expect((await post('/agents/unlock', { email: '[email protected]' }, admin)).status).toBe(200)
await make('late-staff', { email: '[email protected]', roles: ['user'] })
expect((await post('/late-staff/unlock', { email: '[email protected]' }, editor)).status).toBe(403) // a late collection: the same table
expect((await post('/late-staff/unlock', { email: '[email protected]' }, admin)).status).toBe(200)
})
// Review round 2 (R2-3): a staff collection a later plugin adds.
test('a staff collection added by a plugin listed after iapl has the same rules', async () => {
// (the first-user spellings above created nothing: counted there)
expect((await post('/late-staff', { email: '[email protected]', password: PASSWORD, roles: ['admin'] }, visitor)).status).toBe(403)
expect((await post('/late-staff', { email: '[email protected]', password: PASSWORD, roles: ['admin'] }, editor)).status).toBe(403)
// the password rule is there too
expect((await post('/late-staff', { email: '[email protected]', password: 'tooshort', roles: ['user'] }, admin)).status).toBe(400)
expect((await post('/late-staff', { email: '[email protected]', password: PASSWORD, roles: ['user'] }, admin)).status).toBe(201)
const id = await idOf('late-staff', '[email protected]')
expect((await patch(`/late-staff/${id}`, { password: NEW }, visitor)).status).toBe(403)
expect((await remove(`/late-staff/${id}`, visitor)).status).toBe(403)
const one = await login('late-staff', '[email protected]')
await patch(`/late-staff/${id}`, { roles: ['admin'] }, one)
expect(((await payload.findByID({ id: id as never, collection: 'late-staff' as never })) as { roles?: string[] }).roles).toEqual(['user'])
expect((await patch(`/late-staff/${id}`, { roles: ['editor'] }, admin)).status).toBe(200)
})
test('the doctor\'s check: no staff collection is open to an account of another collection', async () => {
expect(staffCollectionsOnOwnRoles(payload as never)).toEqual(['crew']) // `staff2` has no roles field: nothing to rank
expect(await staffCollectionsOpenToOthers(payload as never)).toEqual([])
expect(await openSignUpCollections(payload as never)).toEqual(['customers'])
})
})
describe('the lowest role stays out of the admin panel (accounts.panelRole)', () => {
const canAccessAdmin = async (session: Session) => Boolean(((await (await call('/access', session)).json()) as { canAccessAdmin?: boolean }).canAccessAdmin)
beforeAll(async () => {
await make('users', { email: '[email protected]', roles: ['admin'] })
await make('users', { email: '[email protected]', roles: ['editor'] })
await make('users', { email: '[email protected]', roles: ['user'] })
await make('customers', { email: '[email protected]' })
})
test('Payload reports panel access for an admin and an editor, not for a plain user or a visitor account', async () => {
expect(await canAccessAdmin(await login('users', '[email protected]'))).toBe(true)
expect(await canAccessAdmin(await login('users', '[email protected]'))).toBe(true)
expect(await canAccessAdmin(await login('users', '[email protected]'))).toBe(false)
expect(await canAccessAdmin(await login('customers', '[email protected]'))).toBe(false)
expect(await canAccessAdmin({})).toBe(false)
})
test('the API is not touched: the plain user still logs in and reads its own account', async () => {
const session = await login('users', '[email protected]')
const me = (await (await call('/users/me', session)).json()) as { user?: { email?: string } }
expect(me.user?.email).toBe('[email protected]')
})
test('the start-up count: how many accounts are below the panel role', async () => {
const all = (await payload.find({ collection: 'users' as never, limit: 100 })).docs as unknown as { roles?: string[] }[]
const has = (role: string) => all.filter((u) => u.roles?.includes(role)).length
expect(await countBelowPanelRole(payload, 'users', 'editor')).toEqual({ all: all.length, below: all.length - has('admin') - has('editor') })
expect(await countBelowPanelRole(payload, 'users', 'admin')).toEqual({ all: all.length, below: all.length - has('admin') })
expect(has('user')).toBeGreaterThan(0)
})
})
describe('the password rule (accounts.password): twelve characters when a password is set', () => {
let admin: Session
const messageOf = async (res: Response) => JSON.stringify(await res.json())
beforeAll(async () => {
admin = await login('users', '[email protected]')
})
test('a new account: 11 characters refused with a clear message, 12 accepted', async () => {
const short = await post('/users', { email: '[email protected]', password: 'abcdefghijk', roles: ['editor'] }, admin)
expect(short.status).toBe(400)
expect(await messageOf(short)).toMatch(/at least 12 characters/)
expect((await post('/users', { email: '[email protected]', password: 'abcdefghijkl', roles: ['editor'] }, admin)).status).toBe(201)
// counted in characters, not bytes
expect((await post('/users', { email: '[email protected]', password: 'zażółć gęślą', roles: ['editor'] }, admin)).status).toBe(201)
})
test('in Polish for a Polish panel', async () => {
const res = await post('/users', { email: '[email protected]', password: 'krotkie', roles: ['editor'] }, { ...admin, 'accept-language': 'pl' })
expect(res.status).toBe(400)
expect(await messageOf(res)).toMatch(/co najmniej 12 znaków/)
})
test('not the account\'s own e-mail address', async () => {
const same = await post('/users', { email: '[email protected]', password: '[email protected]', roles: ['editor'] }, admin)
expect(same.status).toBe(400)
expect(await messageOf(same)).toMatch(/same as the e-mail/)
})
test('changing a password: checked; changing anything else: not', async () => {
const doc = (await payload.find({ collection: 'users' as never, where: { email: { equals: '[email protected]' } } })).docs[0]
expect((await call(`/users/${doc.id}`, admin, { body: JSON.stringify({ password: 'tooshort' }), method: 'PATCH' })).status).toBe(400)
expect((await call(`/users/${doc.id}`, admin, { body: JSON.stringify({ password: '[email protected]' }), method: 'PATCH' })).status).toBe(400) // its own address, looked up
expect((await call(`/users/${doc.id}`, admin, { body: JSON.stringify({ roles: ['user'] }), method: 'PATCH' })).status).toBe(200)
expect((await call(`/users/${doc.id}`, admin, { body: JSON.stringify({ password: 'a-new-long-password' }), method: 'PATCH' })).status).toBe(200)
await login('users', '[email protected]', 'a-new-long-password')
})
test('an EXISTING shorter password keeps logging in — nothing is checked at login', async () => {
// an account as an earlier version left it: a 6-character password, stored the way Payload stored it then
const old = await make('users', { email: '[email protected]', roles: ['editor'] })
const salt = randomBytes(32).toString('hex')
const hash = pbkdf2Sync('short1', salt, 25000, 512, 'sha256').toString('hex')
await payload.db.updateOne({ id: old.id, collection: 'users' as never, data: { hash, salt } as never })
const session = await login('users', '[email protected]', 'short1')
expect(((await (await call('/users/me', session)).json()) as { user?: { email?: string } }).user?.email).toBe('[email protected]')
// the rule meets it the next time the password is changed
expect((await call(`/users/${old.id}`, session, { body: JSON.stringify({ password: 'short2' }), method: 'PATCH' })).status).toBe(400)
})
test('a reset by e-mail is held to the rule too', async () => {
const token = await payload.forgotPassword({ collection: 'users' as never, data: { email: '[email protected]' }, disableEmail: true })
const short = await post('/users/reset-password', { password: 'tooshort', token })
expect(short.status).toBe(400)
expect(await messageOf(short)).toMatch(/at least 12 characters/)
// not the account's own address either: there is no e-mail in a reset request, the account is found by its token
const own = await post('/users/reset-password', { password: '[email protected]', token })
expect(own.status).toBe(400)
expect(await messageOf(own)).toMatch(/same as the e-mail/)
expect((await post('/users/reset-password', { password: 'reset-to-a-long-one', token })).status).toBe(200)
})
test('a bulk update is checked against every account it matches; a password that is not text is refused, not a server error', async () => {
await make('users', { email: '[email protected]', roles: ['editor'] })
const bulk = await patch('/users?where[email][equals][email protected]', { password: '[email protected]' }, admin)
expect(JSON.stringify(await bulk.json())).toMatch(/same as the e-mail/)
expect(await canLogIn('users', '[email protected]', '[email protected]')).toBe(false)
for (const notText of [123456789012, ['a-long-enough-one'], { length: 20 }]) {
const res = await post('/users', { email: `nt-${Math.random().toString(36).slice(2)}@example.com`, password: notText, roles: ['editor'] }, admin)
expect([JSON.stringify(notText), res.status]).toEqual([JSON.stringify(notText), 400])
}
})
test('visitor collections are not touched', async () => {
expect((await post('/customers', { email: '[email protected]', password: 'abc123' })).status).toBe(201)
})
test('the option, the checker and the switch', async () => {
expect(resolvePasswordRule(undefined)).toEqual({ minLength: 12 })
expect(resolvePasswordRule({ minLength: 16 })).toEqual({ minLength: 16 })
expect(resolvePasswordRule(false)).toBeNull()
for (const bad of ['12', 0, -1, 1.5, Number.NaN]) {expect(() => resolvePasswordRule({ minLength: bad as never })).toThrow(/minLength must be/)}
expect(checkPassword('abcdefghijk')).toBe('short')
expect(checkPassword('abcdefghijkl')).toBeNull()
expect(checkPassword('abcd', { minLength: 4 })).toBeNull()
expect(checkPassword('[email protected] ', { email: '[email protected]', minLength: 4 })).toBe('email')
const hooks = async (options: Record<string, unknown>) =>
(await iapl({ access: { authCollection: 'users' }, i18n, twoFactor: false, ...options } as never)({ admin: { user: 'users' }, collections: [{ slug: 'customers', auth: true, fields: [] }], secret: 'x' } as unknown as Config)).collections!.map((c) => [c.slug, c.hooks?.beforeOperation?.length ?? 0])
expect(await hooks({})).toEqual([['customers', 0], ['users', 1]])
expect(await hooks({ accounts: { password: false } })).toEqual([['customers', 0], ['users', 0]])
expect(await hooks({ accounts: false })).toEqual([['customers', 0], ['users', 0]])
})
})
describe('accounts.panelRole: the config', () => {
const build = (options: Record<string, unknown>, incoming: Partial<Config> = {}) =>
iapl({ access: { authCollection: 'users' }, i18n, twoFactor: false, ...options } as never)({ collections: [], secret: 'x', ...incoming } as unknown as Config)
const adminRule = (config: Config) => config.collections!.find((c) => c.slug === 'users')!.access?.admin
test('on by default at editor; a role, false and accounts: false change it', async () => {
expect(resolvePanelRole(undefined)).toBe('editor')
expect(resolvePanelRole('admin')).toBe('admin')
expect(resolvePanelRole('user')).toBeNull() // the lowest role = everyone, as before
expect(resolvePanelRole(false)).toBeNull()
expect(() => resolvePanelRole('boss' as never)).toThrow(/panelRole must be one of/)
expect(adminRule(await build({}))).toBeTypeOf('function')
expect(adminRule(await build({ accounts: { panelRole: 'user' } }))).toBeUndefined()
expect(adminRule(await build({ accounts: { panelRole: false } }))).toBeUndefined()
expect(adminRule(await build({ accounts: false }))).toBeUndefined()
// without `access` there are no roles to ask about
expect(adminRule(await iapl({ i18n, twoFactor: false })({ collections: [], secret: 'x' } as unknown as Config))).toBeUndefined()
})
test("the project's own rule wins: on its own collection, and through access.authAccess", async () => {
const mine = () => true
const own = await build({}, { collections: [{ slug: 'users', access: { admin: mine }, auth: true, fields: [] }] } as never)
expect(adminRule(own)).toBe(mine)
const injected = await build({ access: { authAccess: { admin: mine }, authCollection: 'users' } })
expect(adminRule(injected)).toBe(mine)
// the project's own collection without a rule gets the plugin's
const plain = await build({}, { collections: [{ slug: 'users', auth: true, fields: [] }] } as never)
expect(adminRule(plain)).toBeTypeOf('function')
})
test('the rule looks at the role, not at the second factor, and only at staff accounts', () => {
const source = { staffCollections: ['users'] }
const ask = (user: unknown, minimum?: 'admin' | 'editor') => panelAccess(minimum)({ req: { payload: source, user } } as never)
expect(ask({ collection: 'users', roles: ['editor'] })).toBe(true)
expect(ask({ _strategy: 'local-jwt', collection: 'users', hasTotp: true, roles: ['admin'] })).toBe(true) // still owes its code: the 2FA screens are part of the panel
expect(ask({ collection: 'users', roles: ['user'] })).toBe(false)
expect(ask({ collection: 'users', roles: [] })).toBe(false)
expect(ask({ collection: 'users' })).toBe(false)
expect(ask({ collection: 'customers', roles: ['admin'] })).toBe(false)
expect(ask(null)).toBe(false)
expect(ask({ collection: 'users', roles: ['editor'] }, 'admin')).toBe(false)
})
})
describe('accounts.adminOnlyCreate / firstUserRoute: the config', () => {
const build = (options: Record<string, unknown>, incoming: Partial<Config> = {}) =>
iapl({ access: { authCollection: 'users', staffCollections: ['staff2'] }, i18n, twoFactor: false, ...options } as never)({
collections: [{ slug: 'staff2', auth: true, fields: [] }, { slug: 'customers', access: { create: () => true }, auth: true, fields: [] }, { slug: 'pages', fields: [] }],
secret: 'x',
...incoming,
} as unknown as Config)
const of = (config: Config, slug: string) => config.collections!.find((c) => c.slug === slug)!
test('staff collections without rules get them; a rule the project wrote stays; other collections are not touched', async () => {
const config = await build({})
expect(of(config, 'staff2').access?.create).toBeTypeOf('function')
expect(of(config, 'staff2').access?.update).toBeTypeOf('function')
expect(of(config, 'staff2').access?.delete).toBeTypeOf('function')
expect(of(config, 'users').access?.create).toBeTypeOf('function') // the injected collection had adminOnly already
expect(String(of(config, 'customers').access?.create)).toContain('true')
expect(of(config, 'customers').access?.update).toBeUndefined() // not a staff collection
expect(of(config, 'pages').access?.create).toBeUndefined()
const mine = () => true
const own = await build({}, { collections: [{ slug: 'users', access: { create: mine, delete: mine, update: mine }, auth: true, fields: [] }, { slug: 'staff2', auth: true, fields: [] }] } as never)
expect([of(own, 'users').access?.create, of(own, 'users').access?.update, of(own, 'users').access?.delete]).toEqual([mine, mine, mine])
// the collection that carries the plugin's roles: the admin rule, although the field is injected later
const ownNoRule = await build({}, { collections: [{ slug: 'users', auth: true, fields: [] }] } as never)
// (the plugin's rules carry its mark for the slug, on the function: that is how a copy of the collection is told later)
expect(['create', 'delete', 'update', 'unlock', 'read', 'readVersions'].map((op) => staffRuleOf((of(ownNoRule, 'users').access as Record<string, unknown>)[op])?.slug)).toEqual(Array(6).fill('users'))
expect(await (of(ownNoRule, 'users').access!.create as (a: unknown) => unknown)({ req: { payload: { staffCollections: ['users'] }, user: { id: 1, collection: 'users', roles: ['editor'] } } })).toBe(false)
expect(staffRuleOf(mine)).toBeUndefined() // a rule the project wrote is not marked
expect(staffRuleOf(staffCreateAccess)).toBeUndefined() // nor the exported rule itself: the mark is on a function of its own
})
test('whose roles: the plugin\'s rule only where the roles are the plugin\'s', () => {
const roles = (options: unknown[]) => ({ slug: 'x', fields: [{ name: 'roles', type: 'select', hasMany: true, options }] }) as never
expect(hasPluginRoles(roles(['user', 'editor', 'admin']))).toBe(true)
expect(hasPluginRoles(roles([{ label: 'Admin', value: 'admin' }, { label: 'Editor', value: 'editor' }]))).toBe(true)
expect(hasPluginRoles(roles(['superadmin', 'writer']))).toBe(false)
expect(hasPluginRoles(roles(['admin', 'writer']))).toBe(false) // one foreign value: the project's own roles
// …but an account that CAN hold `editor` or `admin` is the plugin's business: the admin rules apply (review H-2, J-3)
expect(canHoldStaffRole(roles(['admin', 'writer']))).toBe(true)
expect(canHoldStaffRole(roles(['user', 'editor', 'admin', 'boss']))).toBe(true)
expect(canHoldStaffRole(roles(['viewer', 'editor']))).toBe(true)
expect(canHoldStaffRole(roles([{ label: 'Admin', value: 'admin' }, { label: 'Boss', value: 'boss' }]))).toBe(true)
expect(canHoldStaffRole(roles(['superadmin', 'writer']))).toBe(false)
expect(canHoldStaffRole(roles(['Admin', 'administrator', 'user']))).toBe(false) // the values themselves, nothing like them
expect(canHoldStaffRole({ slug: 'x', fields: [] })).toBe(false) // no roles field: nothing to hand out (every account is an admin)
// a field whose values cannot be listed can hold anything
const field = (f: Record<string, unknown>) => ({ slug: 'x', fields: [{ name: 'roles', ...f }] }) as never
expect(canHoldStaffRole(field({ type: 'text', hasMany: true }))).toBe(true)
expect(canHoldStaffRole(field({ type: 'json' }))).toBe(true)
expect(canHoldStaffRole(field({ type: 'relationship', hasMany: true, relationTo: 'role-names' }))).toBe(true) // ids that are text
expect(canHoldStaffRole(field({ type: 'some-type-of-a-plugin' }))).toBe(true) // unknown: assume it can
expect(canHoldStaffRole(roles([]))).toBe(true)
expect(canHoldStaffRole({ slug: 'x', fields: [{ type: 'row', fields: [{ name: 'roles', type: 'text', hasMany: true }] }] } as never)).toBe(true)
// Review of branch A (K-1): the plugin counts roles only from an ARRAY. A single-valued field never makes a
// plugin admin, so there is nothing to protect — and the collection's accounts keep managing each other.
for (const single of [{ type: 'select', options: ['user', 'editor', 'admin', 'boss'] }, { type: 'select', hasMany: false, options: ['user', 'editor', 'admin'] }, { type: 'text' }, { type: 'radio', options: ['user', 'admin'] }, { type: 'number' }, { type: 'date' }, { type: 'checkbox' }, { type: 'relationship', relationTo: 'role-names' }, { type: 'upload', relationTo: 'media' }]) {
expect([JSON.stringify(single), rolesAreAList(field(single)), canHoldStaffRole(field(single)), hasPluginRoles(field(single))]).toEqual([JSON.stringify(single), false, false, false])
}
expect([rolesAreAList(field({ type: 'select', hasMany: true, options: ['lead'] })), rolesAreAList(field({ type: 'json' })), rolesAreAList({ slug: 'x', fields: [] })]).toEqual([true, true, false])
expect(hasPluginRoles(roles([]))).toBe(false)
expect(hasPluginRoles({ slug: 'x', fields: [] })).toBe(false)
expect(hasPluginRoles({ slug: 'x', fields: [{ name: 'roles', type: 'text' }] } as never)).toBe(false)
const staff = { staffCollections: ['users', 'agents', 'crew'] }
const ask = (rule: ReturnType<typeof staffUpdateAccess>, user: unknown) => rule({ req: { payload: staff, user } } as never)
const admin = { id: 1, collection: 'users', roles: ['admin'] }
const editor = { id: 2, collection: 'users', roles: ['editor'] }
const customer = { id: 2, collection: 'customers', roles: ['admin'] }
// the plugin's roles
expect(ask(staffCreateAccess, admin)).toBe(true)
expect(ask(staffCreateAccess, editor)).toBe(false)
expect(ask(staffUpdateAccess('users'), admin)).toBe(true)
expect(ask(staffUpdateAccess('users'), editor)).toEqual({ id: { equals: 2 } })
expect(ask(staffUpdateAccess('agents'), editor)).toBe(false) // "self" is an account of THAT collection: id 2 of another one is somebody else
expect(ask(staffUpdateAccess('users'), customer)).toBe(false)
expect(ask(staffUpdateAccess('users'), null)).toBe(false)
// the project's own roles
const crew = sameStaffCollectionAccess('crew')
expect(ask(crew, { id: 5, collection: 'crew', roles: ['worker'] })).toBe(true)
expect(ask(crew, admin)).toBe(true)
expect(ask(crew, editor)).toBe(false)
expect(ask(crew, customer)).toBe(false)
expect(ask(crew, null)).toBe(false)
expect(ask(sameStaffCollectionAccess('shop'), { id: 5, collection: 'shop' })).toBe(false) // not a staff collection: never by this rule
})
test('the switches', async () => {
const guards = (config: Config, slug: string) => of(config, slug).hooks?.beforeOperation?.length ?? 0
const firstUser = (config: Config, slug: string) => (of(config, slug).endpoints || []).filter((e) => e.path === '/first-register').length
const on = await build({})
// staff collections: the password rule; every auth collection: the first-user endpoint
expect([guards(on, 'users'), guards(on, 'staff2'), guards(on, 'customers'), guards(on, 'pages')]).toEqual([1, 1, 0, 0])
expect([firstUser(on, 'users'), firstUser(on, 'staff2'), firstUser(on, 'customers'), firstUser(on, 'pages')]).toEqual([1, 1, 1, 0])
const payloadWay = await build({ accounts: { adminOnlyCreate: false, adminOnlyWrite: false, firstUserRoute: 'all', password: false } })
expect(Object.keys(of(payloadWay, 'staff2').access ?? {}).sort()).toEqual(['read', 'readVersions'])
expect(of(await build({ accounts: { adminOnlyCreate: false, adminOnlyWrite: false, firstUserRoute: 'all', password: false, staffOnlyRead: false } }), 'staff2').access).toBeUndefined()
expect([guards(payloadWay, 'staff2'), firstUser(payloadWay, 'staff2')]).toEqual([0, 0])
// each switch on its own
const createOnly = await build({ accounts: { adminOnlyWrite: false } })
expect([typeof of(createOnly, 'staff2').access?.create, of(createOnly, 'staff2').access?.update, of(createOnly, 'staff2').access?.delete]).toEqual(['function', undefined, undefined])
const writeOnly = await build({ accounts: { adminOnlyCreate: false } })
expect([of(writeOnly, 'staff2').access?.create, typeof of(writeOnly, 'staff2').access?.update, typeof of(writeOnly, 'staff2').access?.delete]).toEqual([undefined, 'function', 'function'])
const off = await build({ accounts: false })
expect(of(off, 'staff2').access?.create).toBeUndefined()
expect(of(off, 'staff2').access?.update).toBeUndefined()
expect([guards(off, 'users'), firstUser(off, 'users')]).toEqual([0, 0])
await expect(build({ accounts: { firstUserRoute: 'everyone' } })).rejects.toThrow(/firstUserRoute must be/)
// a collection that turned its endpoints off keeps them off
const noEndpoints = await build({}, { collections: [{ slug: 'staff2', auth: true, endpoints: false, fields: [] }] } as never)
expect(of(noEndpoints, 'staff2').endpoints).toBe(false)
// without `access` the rules still apply to the panel's login collection — as "an account of this collection":
// without the plugin's roles nobody is an admin to it
const noAccess = await iapl({ i18n, twoFactor: false })({ collections: [{ slug: 'users', auth: true, fields: [] }], secret: 'x' } as unknown as Config)
expect(of(noAccess, 'users').access?.create).toBeTypeOf('function')
expect(await (of(noAccess, 'users').access!.create as (a: unknown) => unknown)({ req: { payload: { staffCollections: ['users'] }, user: { id: 1, collection: 'users' } } })).toBe(true)
})
test('the roles field: protected where the plugin\'s update rule is in force and the field has no access of its own', async () => {
const rolesField = (config: Config, slug: string) => of(config, slug).fields.find((f) => 'name' in f && f.name === 'roles') as { access?: { update?: unknown } }
const own = { name: 'roles', type: 'select', hasMany: true, options: ['user', 'editor', 'admin'] }
const collections = (extra: object = {}, field: object = own) => ({ collections: [{ slug: 'staff2', auth: true, fields: [{ type: 'row', fields: [field] }], ...extra }] }) as never
const inRow = (config: Config) => (of(config, 'staff2').fields[0] as unknown as { fields: { access?: { update?: unknown } }[] }).fields[0]
// the plugin's roles: only an admin; found inside a row too; the project's own field object is not changed
const fieldRule0 = inRow(await build({}, collections())).access?.update as (a: unknown) => boolean
expect(staffRuleOf(fieldRule0)?.slug).toBe('staff2')
expect(fieldRule0({ req: { payload: { staffCollections: ['staff2'] }, user: { id: 1, collection: 'staff2', roles: ['editor'] } } })).toBe(false)
expect(fieldRule0({ req: { payload: { staffCollections: ['staff2'] }, user: { id: 1, collection: 'staff2', roles: ['admin'] } } })).toBe(true)
expect((own as { access?: unknown }).access).toBeUndefined()
// roles of the project's own: never the account itself
const mine = inRow(await build({}, collections({}, { ...own, options: ['boss', 'worker'] }))).access?.update as (a: unknown) => boolean
expect(mine({ id: 5, req: { user: { id: 5, collection: 'staff2' } } })).toBe(false)
expect(mine({ id: '5', req: { user: { id: 5, collection: 'staff2' } } })).toBe(false)
expect(mine({ id: 6, req: { user: { id: 5, collection: 'staff2' } } })).toBe(true)
expect(mine({ id: 5, req: { user: { id: 5, collection: 'users' } } })).toBe(true) // id 5 of another collection is somebody else
expect(rolesNotOwn('x')({ id: undefined, req: { user: { id: 5, collection: 'x' } } } as never)).toBe(true) // a create
// left alone: a field with its own rule, a collection with its own update rule, the switch
const fieldRule = () => true
expect(inRow(await build({}, collections({}, { ...own, access: { update: fieldRule } }))).access?.update).toBe(fieldRule)
expect(inRow(await build({}, collections({ access: { update: () => true } }))).access).toBeUndefined()
expect(inRow(await build({ accounts: { adminOnlyWrite: false } }, collections())).access).toBeUndefined()
// the injected collection's field has the plugin's own access already
expect(rolesField(await build({}), 'users').access?.update).toBeTypeOf('function')
})
// Review round 3 (R3-1): nothing may depend on recognising Payload's default — a production build minifies
// its name away. The functions below have the names a bundler gives them: none that means anything.
// Review of the copy rules (L-2): a collection that WAS in the config and becomes staff later (a later plugin sets
// `admin.user`). The plugin noted at config time which operations had a rule; those stay as written.
test('a config collection that becomes staff later keeps the rules it had at config time', async () => {
const own = ({ req }: { req: { user: unknown } }) => Boolean(req.user)
const rolesField = () => ({ name: 'roles', type: 'select', hasMany: true, options: ['user', 'editor', 'admin'] })
const { iapl } = await import('../src/plugin.js')
const built = await iapl({ access: { authCollection: 'users' }, i18n, twoFactor: false } as never)({
admin: { user: 'users' },
collections: [
{ slug: 'users', auth: true, fields: [] },
{ slug: 'none', auth: true, fields: [rolesField()] },
{ slug: 'some', access: { create: own, update: own }, auth: true, fields: [rolesField()] },
{ slug: 'pages', fields: [] },
],
secret: 'x',
} as unknown as Config)
const of = (slug: string) => built.collections!.find((c) => c.slug === slug)!
expect(of('none').custom?.ipalAccounts).toEqual({ slug: 'none', own: [], staff: false })
expect(of('some').custom?.ipalAccounts).toEqual({ slug: 'some', own: ['create', 'update'], staff: false })
expect(of('users').custom?.ipalAccounts).toEqual({ slug: 'users', staff: true })
expect(of('pages').custom?.ipalAccounts).toBeUndefined()
// Payload sanitizes: every missing rule is a function now, none with a telling name
const filled = (slug: string) => {
const c = of(slug)
const access = Object.fromEntries(['create', 'update', 'delete', 'unlock', 'read', 'readVersions'].map((operation) => [operation, (c.access as Record<string, unknown>)?.[operation] ?? (({ req }: { req: { user: unknown } }) => Boolean(req.user))]))
return { ...c, access, endpoints: [] }
}
const none = filled('none')
const some = filled('some')
// a copy of it under a new slug brings the marker along: its `own` says nothing about the copy
const copy = { ...filled('some'), slug: 'copy' }
const config = { collections: [none, some, copy] } as never
expect(adoptLateAuthCollections(config, ['none', 'some', 'copy'], { access: {}, firstUserRoute: 'all' })).toEqual([
{ slug: 'none', applied: ['create', 'update', 'delete', 'unlock', 'read', 'readVersions', 'roles'], firstUser: false, kept: [], known: true, password: false },
{ slug: 'some', applied: ['delete', 'unlock', 'read', 'readVersions'], firstUser: false, kept: ['create', 'update'], known: true, password: false },
{ slug: 'copy', applied: ['create', 'update', 'delete', 'unlock', 'read', 'readVersions', 'roles'], firstUser: false, kept: [], known: false, password: false },
])
// the kept rules are the very functions the project wrote; the roles field is not guarded where its own `update` rule stays (as at config time)
expect([(some.access as Record<string, unknown>).create, (some.access as Record<string, unknown>).update]).toEqual([own, own])
expect((some.fields as { access?: unknown }[])[0].access).toBeUndefined()
expect(some.custom?.ipalAccounts).toEqual({ slug: 'some', own: ['create', 'update'], staff: true })
const visitor = { req: { payload: { config: { admin: { user: 'some' }, custom: { ipal: { staffCollections: ['none', 'some', 'copy'] } } } }, user: { id: 1, collection: 'customers' } } } as never
const answers = async (c: { access: Record<string, unknown> }) => Object.fromEntries(await Promise.all(Object.entries(c.access).map(async ([operation, rule]) => [operation, Boolean(await (rule as (a: never) => unknown)(visitor))])))
expect(await answers(none as never)).toEqual({ create: false, delete: false, read: false, readVersions: false, unlock: false, update: false })
expect(await answers(some as never)).toEqual({ create: true, delete: false, read: false, readVersions: false, unlock: false, update: true })
// handled: a second pass changes nothing
expect(adoptLateAuthCollections(config, ['none', 'some', 'copy'], { access: {}, firstUserRoute: 'all' })).toEqual([])
// the opt-out keeps everything; and a collection that never became staff is left alone
const asIs = { ...filled('some'), custom: { ...of('some').custom, ipal: { accountRules: false } } }
expect(adoptLateAuthCollections({ collections: [asIs, filled('none')] } as never, ['some'], { access: {}, firstUserRoute: 'all' })).toEqual([])
})
test('late collections: the plugin\'s rule goes in FRONT of whatever is there, whatever it is called', async () => {
const g = ({ req }: { req: { user: unknown } }) => Boolean(req.user) // Payload's default as a built site holds it: no telling name
const bw = ({ req }: { req: { user: unknown } }) => Boolean(req.user)
const narrow = () => false
const where = () => ({ team: { equals: 'a' } })
const hook = buildPasswordRuleHook() // a real one: the plugin knows its own hook by a mark on the function
const late = { slug: 'late', access: { create: g, delete: narrow, read: g, readVersions: g, unlock: bw, update: where }, auth: true, endpoints: [{ handler: () => undefined, method: 'post', path: '/first-register' }], fields: [{ name: 'roles', type: 'select', access: {}, hasMany: true, options: ['user', 'admin'] }] }
const seen = { slug: 'users', access: { create: g }, auth: true, custom: { ipalAccounts: { slug: 'users', staff: true } }, endpoints: [], fields: [] }
const visitors = { slug: 'visitors', access: { create: g }, auth: true, endpoints: [], fields: [] }
const asIs = { slug: 'as-is', access: { create: g }, auth: true, custom: { ipal: { accountRules: false } }, endpoints: [], fields: [] }
const pages = { slug: 'pages', access: {}, endpoints: [], fields: [] }
const config = { collections: [late, pages, seen, visitors, asIs] } as never
const staff = { staffCollections: ['users', 'late', 'as-is'] }
expect(adoptLateAuthCollections(config, ['users', 'late', 'as-is'], { beforeOperation: hook })).toEqual([
{ slug: 'late', applied: ['create', 'update', 'delete', 'unlock', 'read', 'readVersions', 'roles'], firstUser: true, kept: [], known: false, password: true },
{ slug: 'visitors', applied: [], firstUser: true, kept: [], known: false, password: false },
{ slug: 'as-is', applied: [], firstUser: true, kept: [], known: false, password: true }, // its own rules as they are: it said so
])
const ask = (operation: keyof typeof late.access, user: unknown) => (late.access[operation] as (a: unknown) => unknown)({ req: { payload: staff, user } })
const admin = { id: 1, collection: 'users', roles: ['admin'] }
const editor = { id: 2, collection: 'users', roles: ['editor'] }
const own = { id: 7, collection: 'late', roles: ['user'] }
const customer = { id: 9, collection: 'customers', roles: ['admin'] }
for (const operation of ['create', 'read', 'readVersions', 'update', 'delete', 'unlock'] as const) {
expect([operation, await ask(operation, customer)]).toEqual([operation, false])
expect([operation, await ask(operation, null)]).toEqual([operation, false])
}
expect(await ask('create', editor)).toBe(false)
expect(await ask('create', admin)).toBe(true)
expect(await ask('unlock', editor)).toBe(false) // an admin, as the table in the docs says
expect(await ask('unlock', admin)).toBe(true)
expect(await ask('read', editor)).toBe(true)
expect(await ask('readVersions', editor)).toBe(true)
// a rule of the collection's own is kept, and only ever narrows: both must allow
expect(await ask('delete', admin)).toBe(false)
expect(await ask('update', admin)).toEqual({ team: { equals: 'a' } })
expect(await ask('update', own)).toEqual({ and: [{ id: { equals: 7 } }, { team: { equals: 'a' } }] })
expect(staffRuleOf((late.fields[0] as { access?: { update?: unknown } }).access?.update)?.slug).toBe('late')
expect((late as { hooks?: { beforeOperation?: unknown[] } }).hooks?.beforeOperation).toEqual([hook])
expect((late.endpoints[0] as { custom?: { ipalFirstUser?: boolean } }).custom?.ipalFirstUser).toBe(true) // in FRONT of Payload's
// a late auth collection that is not staff: the first-user endpoint only
expect(visitors.access.create).toBe(g)
expect(asIs.access.create).toBe(g)
// what iapl saw at config time, and what is not an auth collection: untouched
expect(seen.access.create).toBe(g)
expect([seen.endpoints.length, pages.endpoints.length]).toEqual([0, 0])
// a second call (a request after the start) changes nothing
expect(adoptLateAuthCollections(config, ['users', 'late'], { beforeOperation: hook })).toEqual([])
expect(late.endpoints).toHaveLength(2)
// a staff slug without an auth collection
expect(unknownStaffCollections(config, ['users', 'late', 'pages', 'ghost'])).toEqual(['pages', 'ghost'])
// the combiner
expect(await bothAllow(() => true, undefined)({} as never)).toBe(true)
expect(await bothAllow(() => false, () => { throw new Error('not asked') })({} as never)).toBe(false)
})
// The copy rules ("a rule that cannot widen"): the HTTP proof is the table in accountCopyTableSuite.ts; here the parts.
test('the plugin\'s mark: on the function itself, never on a shared rule or through somebody\'s wrapper', async () => {
const marked = markedStaffRule(staffCreateAccess, 'agents')
expect(marked).not.toBe(staffCreateAccess)
expect(staffRuleOf(marked)).toEqual({ slug: 'agents', self: marked })
expect(staffRuleOf(staffCreateAccess)).toBeUndefined() // the exported rule is shared: a project may use it anywhere
expect(staffRuleOf(() => true)).toBeUndefined()
expect(staffRuleOf(undefined)).toBeUndefined()
expect(await marked({ req: { payload: { staffCollections: ['users'] }, user: { id: 1, collection: 'users', roles: ['admin'] } } } as never)).toBe(true)
// the plugin's own wrapper (its 2FA guard) gets a mark made for IT
const guarded = requireSecondFactor(marked)
expect(staffRuleOf(guarded)).toEqual({ slug: 'agents', self: guarded })
expect(staffRuleOf(requireSecondFactor(() => true))).toBeUndefined()
// wrappers that are not the plugin's answer with the same property — and are not the rule
const symbol = Symbol.for('ipal.staffRule')
for (const [name, fn] of [['a Proxy', new Proxy(marked, { apply: () => false })], ['the rule as prototype', Object.setPrototypeOf(() => false, marked)], ['copied descriptors', Object.defineProperties(() => false, Object.getOwnPropertyDescriptors(marked))]] as [string, unknown][]) {
expect([name, (fn as Record<symbol, unknown>)[symbol] !== undefined, staffRuleOf(fn)]).toEqual([name, true, undefined])
}
expect(staffRuleOf(marked.bind(null))).toBeUndefined()
// the password hook: marked the same way, so a copy has it once — also across module instances (a registered symbol)
const hook = buildPasswordRuleHook()
expect(isPasswordRuleHook(hook)).toBe(true)
expect((hook as unknown as Record<symbol, unknown>)[Symbol.for('ipal.passwordRule')]).toEqual({ self: hook })
expect([isPasswordRuleHook(() => undefined), isPasswordRuleHook(new Proxy(hook, {}))]).toEqual([false, false])
// with 2FA wiring that wraps every access function: the function that ENDS UP on the collection carries the mark…
const wrapping = ((o: { collection: string }) => (c: Config) => withTotpParts({ ...c, collections: (c.collections ?? []).map((col) => ({ ...col, access: Object.fromEntries(Object.entries(col.access ?? {}).map(([k, v]) => [k, (x: never) => (v as (x: never) => unknown)(x)])) })) } as Config, o.collection)) as never
const withFactory = await build({ twoFactor: { issuer: 'A', plugin: wrapping } })
expect(['create', 'update', 'delete', 'unlock', 'read', 'readVersions'].map((op) => staffRuleOf((of(withFactory, 'staff2').access as Record<string, unknown>)[op])?.slug)).toEqual(Array(6).fill('staff2'))
expect(staffRuleOf(of(withFactory, 'customers').access?.create)).toBeUndefined() // the project's own rule
// …and marking does not undo IAPL's 2FA guard: a plain 2FA config has nothing left to guard at start
const { ensurePayloadGuarded } = await import('../src/modules/security/totp/secondFactor.js')
const plain = await build({ twoFactor: { issuer: 'A', plugin: ((o: { collection: string }) => (c: Config) => withTotpParts(c, o.collection)) as never } })
expect([ensurePayloadGuarded({ config: plain } as never), ensurePayloadGuarded({ config: withFactory } as never)]).toEqual([[], []])
})
test('a copied collection: the plugin\'s rule for ITS slug goes in front of every rule it brought; nothing is replaced', async () => {
const mk = (slug: string, rule: unknown) => markedStaffRule(rule as () => unknown, slug)
const access = { create: mk('agents', staffCreateAccess), delete: mk('agents', staffCreateAccess), read: mk('agents', staffReadAccess), update: mk('agents', staffUpdateAccess('agents')) }
const pluginRoles = () => ({ name: 'roles', type: 'select', hasMany: true, options: ['user', 'editor', 'admin'] }) as { access?: { update?: (a: unknown) => unknown }; name: string; options: string[]; type: string }
const agents = { slug: 'agents', access, auth: true, custom: { ipalAccountRules: { slug: 'agents', applied: Object.keys(access), ownRoles: false }, ipalAccounts: { slug: 'agents', staff: true } }, endpoints: [], fields: [pluginRoles()], hooks: { beforeOperation: [buildPasswordRuleHook()] } }
const nobody = () => false
const copy = { ...agents, slug: 'copy', endpoints: [], fields: [pluginRoles()] }
const ownRule = { ...agents, slug: 'own-rule', access: { ...access, update: nobody }, endpoints: [], fields: [pluginRoles()] }
const optOut = { ...agents, slug: 'opt-out', custom: { ...agents.custom, ipal: { accountRules: false } }, endpoints: [], fields: [pluginRoles()] }
const notStaff = { ...agents, slug: 'not-staff', endpoints: [], fields: [pluginRoles()] }
const claims = { slug: 'claims', access: { create: mk('claims', () => true) }, auth: true, endpoints: [], fields: [] } // a mark that claims this very collection
const hook = buildPasswordRuleHook()
const adopted = adoptLateAuthCollections({ collections: [agents, copy, ownRule, optOut, notStaff, claims] } as never, ['agents', 'copy', 'own-rule', 'opt-out', 'claims'], { beforeOperation: hook })
expect(adopted.map((x) => [x.slug, x.applied, x.password])).toEqual([
['copy', ['create', 'update', 'delete', 'unlock', 'read', 'readVersions', 'roles'], false], // the hook came along: not put twice
['own-rule', ['create', 'update', 'delete', 'unlock', 'read', 'readVersions', 'roles'], false],
['opt-out', ['create', 'update', 'delete', 'read', 'roles'], false], // only in front of the rules the plugin wrote for `agents`, and the roles field
['not-staff', ['create', 'update', 'delete', 'read', 'roles'], false],
['claims', ['create', 'update', 'delete', 'unlock', 'read', 'readVersions'], true],
])
const staff = { staffCollections: ['users', 'agents', 'copy', 'own-rule', 'opt-out', 'claims'] }
const ask = (c: { access: Record<string, unknown> }, operation: string, user: unknown) => (c.access[operation] as (a: unknown) => unknown)({ req: { payload: staff, user } })
const admin = { id: 1, collection: 'users', roles: ['admin'] }
const namesake = { id: 7, collection: 'agents', roles: ['user'] }
for (const c of [copy, ownRule, optOut, notStaff]) {
const own = { id: 7, collection: c.slug, roles: ['user'] }
// the original's account with the same id is not "the account itself" here; nor does the copy's own account pass
// the rule that still says "an account of `agents`" — both rules must allow (the accepted cost: the copy writes its own update rule)
expect([c.slug, await ask(c, 'update', namesake), await ask(c, 'update', own), await ask(c, 'create', own), await ask(c, 'delete', own)]).toEqual([c.slug, false, false, false, false])
// the functions that came along are still inside: nothing was replaced
expect([c.slug, staffRuleOf(c.access.update)?.slug]).toEqual([c.slug, c.slug])
expect([c.slug, await ask(c, 'create', admin)]).toEqual([c.slug, true])
// the roles field of every copy is guarded, whatever the mode
const field = (c.fields[0]).access?.update
expect([c.slug, staffRuleOf(field)?.slug, await field?.({ id: 7, req: { payload: staff, user: own } })]).toEqual([c.slug, c.slug, false])
expect(c.fields[0]).not.toBe(agents.fields[0])
expect(c.access).not.toBe(agents.access)
}
expect(await ask(ownRule, 'update', admin)).toBe(false) // its own "nobody" still has to allow
expect(await ask(copy, 'update', admin)).toBe(true)
// the one line a copying plugin writes so that the copy's own accounts edit themselves (docs/access.md)
const fixed = { ...agents, slug: 'fixed', access: { ...access, update: adminOrSelfIn('fixed') }, endpoints: [], fields: [pluginRoles()] }
adoptLateAuthCollections({ collections: [fixed] } as never, ['agents', 'fixed'], { beforeOperation: hook })
const all = { staffCollections: ['users', 'agents', 'fixed'] }
const askFixed = (user: unknown) => (fixed.access.update as (a: unknown) => unknown)({ req: { payload: all, user } })
expect(await askFixed({ id: 7, collection: 'fixed', roles: ['user'] })).toEqual({ and: [{ id: { equals: 7 } }, { id: { equals: 7 } }] })
expect([await askFixed(namesake), await askFixed(admin)]).toEqual([false, true])
// a mark that claims the collection does not leave the function alone
expect([await ask(claims, 'create', { id: 9, collection: 'customers' }), await ask(claims, 'create', null), await ask(claims, 'create', admin)]).toEqual([false, false, true])
// the original is untouched
expect(await ask(agents, 'update', namesake)).toEqual({ id: { equals: 7 } })
expect(staffRuleOf(agents.access.update)?.slug).toBe('agents')
// R4-2: an object seen as NOT staff (a `next dev` edit names it as staff afterwards) is handled again; a second call changes nothing
const visitors = { slug: 'visitors', access: { create: () => true }, auth: true, endpoints: [], fields: [] }
expect(adoptLateAuthCollections({ collections: [visitors] } as never, [], { beforeOperation: hook }).map((x) => [x.slug, x.applied, x.firstUser])).toEqual([['visitors', [], true]])
expect(adoptLateAuthCollections({ collections: [visitors] } as never, ['visitors'], { beforeOperation: hook }).map((x) => [x.slug, x.applied.length > 0, x.password, x.firstUser])).toEqual([['visitors', true, true, false]])
expect(adoptLateAuthCollections({ collections: [visitors] } as never, ['visitors'], { beforeOperation: hook })).toEqual([])
expect(await (visitors.access.create as (a: unknown) => unknown)({ req: { payload: { staffCollections: ['visitors'] }, user: { id: 9, collection: 'customers' } } })).toBe(false)
})
test('the rules are on the collections BEFORE the 2FA package wraps them', async () => {
// the package gives every collection a create / update / delete of its own; afterwards "no rule" cannot be seen
const seen: Record<string, unknown> = {}
const factory = (o: { collection: string }) => (c: Config) => {
for (const col of c.collections ?? []) {seen[col.slug] = { ...col.access }}
return withTotpParts({ ...c, collections: (c.collections ?? []).map((col) => ({ ...col, access: { create: () => true, delete: () => true, update: () => true, ...col.access } })) }, o.collection)
}
await build({ twoFactor: { issuer: 'A', plugin: factory as never } })
expect(Object.keys(seen.staff2 as object).sort()).toEqual(['create', 'delete', 'read', 'readVersions', 'unlock', 'update'])
expect(seen.customers).toEqual({ create: expect.any(Function) })
})
test('access.firstUserAdmin: false and the panel role: the first account must be able to get in', async () => {
const adminRule = (config: Config) => of(config, 'users').access?.admin
// the default panel role steps aside (a line at start says so)…
expect(adminRule(await build({ access: { authCollection: 'users', firstUserAdmin: false } }))).toBeUndefined()
// …a role the project asked for is refused at start, with the ways out
await expect(build({ access: { authCollection: 'users', firstUserAdmin: false }, accounts: { panelRole: 'editor' } })).rejects.toThrow(/nobody who can open the panel[\s\S]*defaultRole/)
await expect(build({ access: { authCollection: 'users', defaultRole: 'editor', firstUserAdmin: false }, accounts: { panelRole: 'admin' } })).rejects.toThrow(/nobody who can open the panel/)
// a default role that reaches the panel is fine
expect(adminRule(await build({ access: { authCollection: 'users', defaultRole: 'editor', firstUserAdmin: false } }))).toBeTypeOf('function')
expect(adminRule(await build({ access: { authCollection: 'users', defaultRole: 'editor', firstUserAdmin: false }, accounts: { panelRole: 'editor' } }))).toBeTypeOf('function')
// and nothing to decide when the rule is off
expect(adminRule(await build({ access: { authCollection: 'users', firstUserAdmin: false }, accounts: { panelRole: false } }))).toBeUndefined()
})
test('staffCollectionsNobodyManages: the admin rules without any admin — for the start-up warning', async () => {
const roles = (options: string[]) => [{ name: 'roles', type: 'select', hasMany: true, options }]
const ruled = { applied: ['create', 'update', 'delete'], ownRoles: false }
const collections = {
crew: { config: { slug: 'crew', auth: true, custom: { ipalAccountRules: ruled }, fields: roles(['user', 'admin', 'boss']) } },
notes: { config: { slug: 'notes', auth: true, custom: { ipalAccountRules: ruled }, fields: [{ name: 'roles', type: 'json' }] } },
team: { config: { slug: 'team', auth: true, custom: { ipalAccountRules: { applied: ['create'], ownRoles: true } }, fields: roles(['lead', 'member']) } },
users: { config: { slug: 'users', auth: true, custom: { ipalAccountRules: ruled }, fields: roles(['user', 'editor', 'admin']) } },
viewers: { config: { slug: 'viewers', auth: true, custom: { ipalAccountRules: ruled }, fields: roles(['viewer', 'editor']) } },
}
const asked: string[] = []
const site = ({ admins = {}, docs = {}, failCount = [], failFind = [], many = [] }: { admins?: Record<string, number>; docs?: Record<string, unknown[]>; failCount?: string[]; failFind?: string[]; many?: string[] }) => ({
collections,
count: async ({ collection }: { collection: string }) => {
asked.push(`count ${collection}`)
if (failCount.includes(collection)) {throw new Error('the database does not take this query')}
return { totalDocs: admins[collection] ?? 0 }
},
find: async ({ collection }: { collection: string }) => {
asked.push(`find ${collection}`)
if (failFind.includes(collection)) {throw new Error('cannot read')}
return { docs: docs[collection] ?? [], hasNextPage: many.includes(collection) }
},
})
const ask = (state: Parameters<typeof site>[0], staff: string[]) => staffCollectionsNobodyManages(site(state) as never, staff, 'users')
// nobody is an admin anywhere: the collections on the admin rules, without the plugin's own (it has its own warning)
expect(await ask({}, ['users', 'crew', 'team'])).toEqual({ stuck: ['crew'], unchecked: [] })
// an admin in the collection, or in another staff collection, manages it
expect(await ask({ admins: { crew: 1 } }, ['users', 'crew', 'team'])).toEqual({ stuck: [], unchecked: [] })
expect(await ask({ admins: { users: 2 } }, ['users', 'crew', 'team'])).toEqual({ stuck: [], unchecked: [] })
// nothing on the admin rules: nothing is said
expect(await ask({}, ['users', 'team'])).toEqual({ stuck: [], unchecked: [] })
// a select that does not offer `admin` has none — without a query (on Postgres the query for a value outside the enum throws)
asked.length = 0
expect(await ask({ failCount: ['viewers'] }, ['users', 'viewers'])).toEqual({ stuck: ['viewers'], unchecked: [] })
expect(asked).toEqual(['count users'])
// a field the database cannot be asked about (json): the accounts are read and the plugin's own test is applied
expect(await ask({ docs: { notes: [{ roles: ['user'] }, { roles: 'admin' }, { roles: null }] } }, ['users', 'notes'])).toEqual({ stuck: ['notes'], unchecked: [] })
expect(await ask({ docs: { notes: [{ roles: ['user'] }, { roles: ['boss', 'admin'] }] } }, ['users', 'notes'])).toEqual({ stuck: [], unchecked: [] })
// a count that fails falls back to reading; what cannot be checked at all is named, and NOBODY is not claimed
expect(await ask({ docs: { crew: [{ roles: ['admin'] }] }, failCount: ['crew'] }, ['users', 'crew'])).toEqual({ stuck: [], unchecked: [] })
expect(await ask({ failFind: ['notes'] }, ['users', 'crew', 'notes'])).toEqual({ stuck: [], unchecked: ['notes'] })
expect(await ask({ many: ['notes'] }, ['users', 'crew', 'notes'])).toEqual({ stuck: [], unchecked: ['notes'] }) // more accounts than were read
// …but one collection that cannot be checked does not hide an admin found elsewhere
expect(await ask({ admins: { crew: 1 }, failFind: ['notes'] }, ['users', 'notes', 'crew'])).toEqual({ stuck: [], unchecked: [] })
})
test('openSignUpCollections: slugs of auth collections an anonymous request may create in', async () => {
const collections = {
customers: { config: { slug: 'customers', access: { create: () => true }, auth: true } },
members: { config: { slug: 'members', access: { create: ({ req }: { req: { user: unknown } }) => Boolean(req.user) }, auth: true } },
pages: { config: { slug: 'pages', access: { create: () => true } } },
weird: { config: { slug: 'weird', access: { create: () => { throw new Error('x') } }, auth: true } },
}
expect(await openSignUpCollections({ collections } as never)).toEqual(['customers'])
})
test('staffCollectionsOpenToOthers: staff collections an account of a non-staff collection may write to', async () => {
const anyone = ({ req }: { req: { user: unknown } }) => Boolean(req.user) // Payload's default
const collections = {
agents: { config: { slug: 'agents', access: { create: staffCreateAccess, delete: anyone, update: anyone }, auth: true } },
customers: { config: { slug: 'customers', access: { create: () => true, update: anyone }, auth: true } }, // not staff: not its business
users: { config: { slug: 'users', access: { create: staffCreateAccess, delete: staffCreateAccess, read: staffReadAccess, readVersions: staffReadAccess, unlock: staffCreateAccess, update: staffUpdateAccess('users') }, auth: true } },
weird: { config: { slug: 'weird', access: { update: () => { throw new Error('x') } }, auth: true } },
}
expect(await staffCollectionsOpenToOthers({ collections, config: { admin: { user: 'users' }, custom: { ipal: { staffCollections: ['agents', 'weird'] } } } } as never)).toEqual(['agents:delete', 'agents:read', 'agents:readVersions', 'agents:unlock', 'agents:update', 'weird:create', 'weird:delete', 'weird:read', 'weird:readVersions', 'weird:unlock']) // no rule = Payload's default, open; a rule that throws = closed
})
})
}