From 9a648b049824eff116353f38f6a4e3c78f5f79b8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rados=C5=82aw=20Smoli=C5=84ski?= Date: Wed, 25 Nov 2026 01:04:14 +0100 Subject: [PATCH 1/7] The plugin's version is a constant: no package.json among a site's public assets pluginVersion() named package.json relative to its own module. A bundler takes such a file for an asset: a Turbopack build of a site copied the plugin's whole package.json (dependency lists, scripts, the registry and repository addresses; no secret) to /_next/static/media/package..json, served to anyone. Webpack kept it on the server side. The version now comes from src/version.ts (scripts/write-version.mjs, run by the `version` script; a test fails when it differs from package.json). A smoke test of the built site: nothing under .next/static is a package manifest. Co-Authored-By: Claude Fable 5.2 --- package.json | 3 ++- reference/e2e/smoke.spec.ts | 20 ++++++++++++++++++++ scripts/write-version.mjs | 13 +++++++++++++ src/modules/doctor/status.ts | 10 +++------- src/version.ts | 10 ++++++++++ test/version.test.ts | 32 ++++++++++++++++++++++++++++++++ 6 files changed, 80 insertions(+), 8 deletions(-) create mode 100644 scripts/write-version.mjs create mode 100644 src/version.ts create mode 100644 test/version.test.ts diff --git a/package.json b/package.json index 92d6950..89b8574 100644 --- a/package.json +++ b/package.json @@ -127,7 +127,8 @@ "test:e2e": "playwright test", "test:int": "vitest run", "test:watch": "vitest", - "typecheck": "tsc --noEmit -p . && tsc -p test" + "typecheck": "tsc --noEmit -p . && tsc -p test", + "version": "node scripts/write-version.mjs && git add src/version.ts" }, "dependencies": { "busboy": "1.6.0", diff --git a/reference/e2e/smoke.spec.ts b/reference/e2e/smoke.spec.ts index 32dee65..037d2de 100644 --- a/reference/e2e/smoke.spec.ts +++ b/reference/e2e/smoke.spec.ts @@ -1,4 +1,6 @@ import { expect, type Page, test } from '@playwright/test' +import { existsSync, readdirSync, readFileSync, statSync } from 'node:fs' +import path from 'node:path' import { attachmentOf, startSmtpSink } from './smtp-sink' import { totp } from './totp' @@ -176,6 +178,24 @@ test('SEO and GEO routes respond', async ({ request }) => { expect(await mcp.text()).toContain('get_page') }) +// A bundler turns a file that server code names relative to its own module into an ASSET. Turbopack published the +// plugin's whole package.json that way (dependency lists, scripts, the registry address) under /_next/static/media/. +test('no package.json is published: nothing under .next/static holds one, and the obvious addresses answer 404', async ({ request }) => { + const statics = path.resolve('.next/static') + const walk = (dir: string): string[] => (existsSync(dir) ? readdirSync(dir).flatMap((name) => { + const file = path.join(dir, name) + return statSync(file).isDirectory() ? walk(file) : [file] + }) : []) + const files = walk(statics) + expect(files.length, 'the built site\'s .next/static (run from the site folder)').toBeGreaterThan(0) + // by name, and by content (a manifest of a package: its dependency lists) + const manifests = files.filter((file) => /package[^/]*\.json$/.test(file) || (file.endsWith('.json') && /"(?:devDependencies|peerDependencies|publishConfig)"\s*:/.test(readFileSync(file, 'utf8')))) + expect(manifests.map((file) => path.relative(statics, file))).toEqual([]) + for (const address of ['/package.json', '/_next/package.json', '/_next/static/package.json', '/_next/static/media/package.json']) { + expect((await request.get(address)).status(), address).toBe(404) + } +}) + test('security headers: CSP enforced, no X-Powered-By', async ({ request }) => { const headers = (await request.get('/pl')).headers() expect(headers['content-security-policy']).toBeTruthy() diff --git a/scripts/write-version.mjs b/scripts/write-version.mjs new file mode 100644 index 0000000..571007d --- /dev/null +++ b/scripts/write-version.mjs @@ -0,0 +1,13 @@ +#!/usr/bin/env node +// Writes the version from package.json into src/version.ts (see the comment there). +// Runs as the `version` script of package.json; by hand: node scripts/write-version.mjs +import { readFileSync, writeFileSync } from 'node:fs' + +const root = new URL('../', import.meta.url) +const { version } = JSON.parse(readFileSync(new URL('package.json', root), 'utf8')) +const file = new URL('src/version.ts', root) +const before = readFileSync(file, 'utf8') +const after = before.replace(/export const PLUGIN_VERSION = '[^']*'/, `export const PLUGIN_VERSION = '${version}'`) +if (after === before && !before.includes(`'${version}'`)) {throw new Error('src/version.ts: the PLUGIN_VERSION line was not found')} +writeFileSync(file, after) +console.log(`src/version.ts → ${version}`) diff --git a/src/modules/doctor/status.ts b/src/modules/doctor/status.ts index b971e0b..a548ad3 100644 --- a/src/modules/doctor/status.ts +++ b/src/modules/doctor/status.ts @@ -1,10 +1,10 @@ import type { BasePayload, Endpoint, PayloadRequest } from 'payload' import { timingSafeEqual } from 'node:crypto' -import { readFileSync } from 'node:fs' import type { DoctorStatus } from './types.js' +import { PLUGIN_VERSION } from '../../version.js' import { openSignUpCollections, staffCollectionsOnOwnRoles, staffCollectionsOpenToOthers } from '../access/selfRegistration.js' import { countPendingCookies } from '../consent/scanner/approval.js' import { COOKIE_REVIEW_SLUG } from '../consent/scanner/collection.js' @@ -13,13 +13,9 @@ import { countAccountsWithoutTotp } from '../security/totp/setupRequired.js' import { clientIp, consumeRateLimit, tooManyRequests } from '../shared/rateLimit.js' import { turnstileSecretFromEnv } from '../turnstile/config.js' -/** The plugin's own version (package.json next to dist/ and src/). */ +/** The plugin's own version — a constant (src/version.ts), never a file read at run time. */ export function pluginVersion(): string { - try { - return (JSON.parse(readFileSync(new URL('../../../package.json', import.meta.url), 'utf8')) as { version: string }).version - } catch { - return 'unknown' - } + return PLUGIN_VERSION } type CollectionLike = { fields?: Array<{ name?: string }>; slug: string } diff --git a/src/version.ts b/src/version.ts new file mode 100644 index 0000000..b12905d --- /dev/null +++ b/src/version.ts @@ -0,0 +1,10 @@ +/** + * The plugin's own version, as a constant in the code. + * + * Not read from package.json at run time: naming that file relative to the module (a URL built + * from the module's own address) in server code makes a bundler treat the file as an ASSET — Turbopack copied the plugin's whole + * package.json (dependency lists, scripts, the registry address) into the site's public + * `/_next/static/media/`. Written by `node scripts/write-version.mjs` (the `version` script of + * package.json runs it on `pnpm version …`); test/version.test.ts fails when the two differ. + */ +export const PLUGIN_VERSION = '1.16.7' diff --git a/test/version.test.ts b/test/version.test.ts new file mode 100644 index 0000000..c18cc7e --- /dev/null +++ b/test/version.test.ts @@ -0,0 +1,32 @@ +import { readdirSync, readFileSync, statSync } from 'node:fs' +import path from 'node:path' +import { describe, expect, test } from 'vitest' + +import { pluginVersion } from '../src/modules/doctor/status.js' +import { PLUGIN_VERSION } from '../src/version.js' + +const root = path.resolve(import.meta.dirname, '..') +const walk = (dir: string): string[] => readdirSync(dir).flatMap((name) => { + const file = path.join(dir, name) + return statSync(file).isDirectory() ? walk(file) : [file] +}) + +describe('the plugin version', () => { + test('src/version.ts says what package.json says (node scripts/write-version.mjs after a bump)', () => { + const { version } = JSON.parse(readFileSync(path.join(root, 'package.json'), 'utf8')) as { version: string } + expect(PLUGIN_VERSION).toBe(version) + expect(pluginVersion()).toBe(version) + }) + + // A file named through `new URL(…, import.meta.url)` (or imported) in code a site bundles becomes an ASSET of + // that site: Turbopack put the plugin's whole package.json into the public /_next/static/media/. + test('no code a site bundles names package.json as a module-relative file', () => { + const cli = /^src\/modules\/(?:starter|doctor\/(?:cli|project|run|probe|rules))/ // run by the bin scripts, on the project's own disk + const offenders = walk(path.join(root, 'src')) + .filter((file) => /\.(?:ts|tsx|mjs|js)$/.test(file)) + .map((file) => ({ code: readFileSync(file, 'utf8'), rel: path.relative(root, file) })) + .filter(({ code, rel }) => (!cli.test(rel) && /new URL\([^)]*import\.meta\.url/.test(code)) || /(?:from|import\()\s*['"][^'"]*package\.json['"]/.test(code)) + .map(({ rel }) => rel) + expect(offenders).toEqual([]) + }) +}) From e77c607bca9e32d14039ee580437a0079c1eb429 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rados=C5=82aw=20Smoli=C5=84ski?= Date: Wed, 25 Nov 2026 01:18:03 +0100 Subject: [PATCH 2/7] R4-3: pnpm e2e:built (webpack and Turbopack); Playwright runs reset the test admins first The command builds the reference site with both bundlers, checks the public files for a package manifest and runs the late-staff spec and the published-files check against each built site. A global setup resets the test admins and their stored 2FA attempt counts before every run, so a spec no longer depends on what ran before it. Co-Authored-By: Claude Fable 5.2 --- package.json | 1 + reference/README.md | 15 +++++--- reference/e2e/global-setup.ts | 14 +++++++ reference/playwright.config.ts | 9 +++-- scripts/e2e-built.mjs | 70 ++++++++++++++++++++++++++++++++++ 5 files changed, 101 insertions(+), 8 deletions(-) create mode 100644 reference/e2e/global-setup.ts create mode 100644 scripts/e2e-built.mjs diff --git a/package.json b/package.json index 89b8574..b742111 100644 --- a/package.json +++ b/package.json @@ -112,6 +112,7 @@ "cookie-db:refresh": "node scripts/refresh-cookie-database.mjs", "copyfiles": "copyfiles -u 1 \"src/**/*.{html,css,scss,ttf,woff,woff2,eot,svg,jpg,png,json}\" dist/", "dev": "next dev dev --turbo", + "e2e:built": "node scripts/e2e-built.mjs", "dev:generate-importmap": "pnpm dev:payload generate:importmap", "dev:generate-types": "pnpm dev:payload generate:types", "dev:payload": "cross-env PAYLOAD_CONFIG_PATH=./dev/payload.config.ts payload", diff --git a/reference/README.md b/reference/README.md index 4d8a53b..2af9208 100644 --- a/reference/README.md +++ b/reference/README.md @@ -21,13 +21,18 @@ Production check: `pnpm build && pnpm payload run e2e/create-test-admin.ts && AL (Playwright starts the built site on port 3100 itself; another port: `E2E_BASE_URL=http://localhost:3200`, built with the same `NEXT_PUBLIC_SERVER_URL`; a server you started yourself: `E2E_REUSE_SERVER=1`). -Access rules on a built site, both bundlers (a staff collection that a plugin listed after ipalKit adds — unit tests -run unminified code and cannot see what a bundle renames): +Every Playwright run first resets the test admins and clears their stored 2FA attempt counts (`e2e/global-setup.ts`), +so a spec does not fail because of what ran before it. The fresh-site spec needs an EMPTY database: +`E2E_SKIP_ADMIN_SETUP=1 DATABASE_URI= pnpm exec playwright test two-factor-setup`. + +What only a built site shows, with both bundlers — from the plugin repository's root, part of the release gate: ```bash -E2E_LATE_STAFF=1 pnpm build && pnpm payload run e2e/create-test-admin.ts && E2E_LATE_STAFF=1 ALLOW_LOCAL_MEDIA=1 pnpm exec playwright test late-staff -E2E_LATE_STAFF=1 pnpm exec next build --turbopack && pnpm payload run e2e/create-test-admin.ts && E2E_LATE_STAFF=1 ALLOW_LOCAL_MEDIA=1 pnpm exec playwright test late-staff +pnpm e2e:built # webpack, then Turbopack: build with the late-staff fixture, check the public files, run the specs ``` -Without `E2E_LATE_STAFF=1` the fixture adds nothing and the spec is skipped. +It checks the account rules of a staff collection that a plugin listed after ipalKit adds or copies +(`e2e/late-staff-fixture.ts`, on only with `E2E_LATE_STAFF=1`; `e2e/late-staff.spec.ts`) and that no package manifest +is among the public files. Unit tests run unminified code and cannot see what a bundle renames or publishes. +Without `E2E_LATE_STAFF=1` the fixture adds nothing and the spec is skipped. Rebuild with `pnpm build` afterwards. ## What is where | Convention | Files | diff --git a/reference/e2e/global-setup.ts b/reference/e2e/global-setup.ts new file mode 100644 index 0000000..25b06ca --- /dev/null +++ b/reference/e2e/global-setup.ts @@ -0,0 +1,14 @@ +import { execFileSync } from 'node:child_process' + +/** + * Before every Playwright run: the test admins are made (or reset) and their stored 2FA attempt counts cleared + * (e2e/create-test-admin.ts). The count is kept in the database — 5 verify attempts per account in 10 minutes — + * so without this a second run within ten minutes, or one spec run after the whole suite, would find the test + * admin locked out: the result would depend on what ran before. Skipped when the test admin is not configured + * (the specs that need it skip themselves) or with E2E_SKIP_ADMIN_SETUP=1. + */ +export default function globalSetup(): void { + const { E2E_ADMIN_EMAIL, E2E_ADMIN_PASSWORD, E2E_SKIP_ADMIN_SETUP, E2E_TOTP_SECRET } = process.env + if (E2E_SKIP_ADMIN_SETUP === '1' || !E2E_ADMIN_EMAIL || !E2E_ADMIN_PASSWORD || !E2E_TOTP_SECRET) {return} + execFileSync('pnpm', ['payload', 'run', 'e2e/create-test-admin.ts'], { env: { ...process.env, NODE_ENV: 'development' }, stdio: 'inherit' }) +} diff --git a/reference/playwright.config.ts b/reference/playwright.config.ts index 392b003..bc93ea0 100644 --- a/reference/playwright.config.ts +++ b/reference/playwright.config.ts @@ -8,9 +8,10 @@ try { } /** - * Smoke tests against a built, seeded site: pnpm build && pnpm seed && pnpm payload run e2e/create-test-admin.ts. - * Run create-test-admin.ts again before repeating the tests within ten minutes: the 2FA verify limit (5 attempts per - * account in 10 minutes) is stored in the database, and that script clears the test admins' counts. + * Smoke tests against a built, seeded site: pnpm seed && pnpm build. + * The 2FA verify limit (5 attempts per account in 10 minutes) is stored in the database; the global setup resets the + * test admins and clears their counts before every run (e2e/global-setup.ts; E2E_SKIP_ADMIN_SETUP=1 for a run that + * needs an EMPTY database, the fresh-site spec). * E2E_BASE_URL picks the port (default 3100). Playwright starts its own server there and fails when the port is * taken, so another project's dev server is never tested by mistake; E2E_REUSE_SERVER=1 uses a server you started. */ @@ -18,6 +19,8 @@ const baseURL = process.env.E2E_BASE_URL ?? 'http://localhost:3100' export default defineConfig({ forbidOnly: !!process.env.CI, + // makes every run independent of the one before: test admins reset, stored 2FA attempt counts cleared + globalSetup: './e2e/global-setup.ts', projects: [{ name: 'chromium', use: { ...devices['Desktop Chrome'] } }], reporter: process.env.CI ? 'line' : 'list', retries: process.env.CI ? 1 : 0, diff --git a/scripts/e2e-built.mjs b/scripts/e2e-built.mjs new file mode 100644 index 0000000..aceb254 --- /dev/null +++ b/scripts/e2e-built.mjs @@ -0,0 +1,70 @@ +#!/usr/bin/env node +/** + * pnpm e2e:built — the checks that only a BUILT site can make, with BOTH bundlers. + * + * Unit tests run unminified code. A production bundle renames every function and decides what becomes a public + * asset; two defects of 1.16.7's review lived only there (a rule that told Payload's default by its name; the + * plugin's package.json among a Turbopack build's static files). So for the reference site, once with webpack and + * once with Turbopack: + * 1. production build with the late-staff fixture (E2E_LATE_STAFF=1, reference/e2e/late-staff-fixture.ts); + * 2. no package manifest under .next/static (checked on disk, before anything is started); + * 3. Playwright against `next start`: e2e/late-staff.spec.ts and the smoke test "no package.json is published". + * + * Needs what the reference site's "Production check" needs (reference/README.md): reference/.env with a local, + * seeded database and the E2E_* test admin. The test admins are reset by Playwright's global setup. + * Port: E2E_BASE_URL (default http://localhost:3100), the same value as NEXT_PUBLIC_SERVER_URL in reference/.env. + * Options: --only=webpack | --only=turbopack; --skip-plugin-build (dist and the injected copy are current). + */ +import { spawnSync } from 'node:child_process' +import { existsSync, readdirSync, readFileSync, statSync } from 'node:fs' +import path from 'node:path' +import { fileURLToPath } from 'node:url' + +const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..') +const site = path.join(root, 'reference') +const args = process.argv.slice(2) +const only = args.find((a) => a.startsWith('--only='))?.slice('--only='.length) +const bundlers = ['webpack', 'turbopack'].filter((b) => !only || b === only) +if (!bundlers.length) {throw new Error(`--only must be webpack or turbopack, got "${only}"`)} + +const run = (label, command, commandArgs, cwd, env = {}) => { + console.log(`\n[e2e:built] ${label}`) + const result = spawnSync(command, commandArgs, { cwd, env: { ...process.env, ...env }, stdio: 'inherit' }) + if (result.status !== 0) { + console.error(`\n[e2e:built] ✗ FAILED: ${label}`) + process.exit(result.status ?? 1) + } +} +const walk = (dir) => (existsSync(dir) ? readdirSync(dir).flatMap((name) => { + const file = path.join(dir, name) + return statSync(file).isDirectory() ? walk(file) : [file] +}) : []) + +if (!existsSync(path.join(site, '.env'))) { + console.error('[e2e:built] reference/.env is missing: cp reference/.env.example reference/.env, fill it (local database, E2E_* test admin), seed (reference/README.md).') + process.exit(1) +} +if (!args.includes('--skip-plugin-build')) { + run('build the plugin', 'pnpm', ['build'], root) + run('refresh the plugin copy in the reference site', 'pnpm', ['install', '--ignore-workspace'], site) +} +const fixture = { E2E_LATE_STAFF: '1', NODE_OPTIONS: `${process.env.NODE_OPTIONS ?? ''} --max-old-space-size=3072`.trim() } +const passed = [] +for (const bundler of bundlers) { + run(`${bundler}: production build with the late-staff fixture`, 'pnpm', ['exec', 'next', 'build', `--${bundler}`], site, fixture) + const statics = path.join(site, '.next', 'static') + const files = walk(statics) + if (!files.length) { + console.error(`[e2e:built] ✗ ${bundler}: .next/static is empty — the build did not produce a site`) + process.exit(1) + } + const manifests = files.filter((file) => /package[^/]*\.json$/.test(file) || (file.endsWith('.json') && /"(?:devDependencies|peerDependencies|publishConfig)"\s*:/.test(readFileSync(file, 'utf8')))) + if (manifests.length) { + console.error(`[e2e:built] ✗ ${bundler}: a package manifest is among the PUBLIC files of the build:\n${manifests.map((f) => ` /_next/static/${path.relative(statics, f)}`).join('\n')}`) + process.exit(1) + } + console.log(`[e2e:built] ✓ ${bundler}: no package manifest among ${files.length} public files`) + run(`${bundler}: the built site — late-staff spec and the published-files check`, 'pnpm', ['exec', 'playwright', 'test', 'late-staff', 'smoke', '--grep', 'late staff collection|no package.json is published'], site, { ALLOW_LOCAL_MEDIA: process.env.ALLOW_LOCAL_MEDIA ?? '1', E2E_LATE_STAFF: '1' }) + passed.push(bundler) +} +console.log(`\n[e2e:built] passed: ${passed.join(' and ')}. (The reference site's .next now holds the ${passed.at(-1)} build WITH the fixture: rebuild with \`pnpm build\` there before other checks.)`) From 01219b69d36d153d021d1c65cd19725922df027e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rados=C5=82aw=20Smoli=C5=84ski?= Date: Wed, 25 Nov 2026 01:53:46 +0100 Subject: [PATCH 3/7] F-3: pnpm e2e:built puts the reference site's generated files back, also on failure Co-Authored-By: Claude Fable 5.2 --- scripts/e2e-built.mjs | 18 +++++++++++++++++- 1 file changed, 17 insertions(+), 1 deletion(-) diff --git a/scripts/e2e-built.mjs b/scripts/e2e-built.mjs index aceb254..b97f953 100644 --- a/scripts/e2e-built.mjs +++ b/scripts/e2e-built.mjs @@ -13,10 +13,12 @@ * Needs what the reference site's "Production check" needs (reference/README.md): reference/.env with a local, * seeded database and the E2E_* test admin. The test admins are reset by Playwright's global setup. * Port: E2E_BASE_URL (default http://localhost:3100), the same value as NEXT_PUBLIC_SERVER_URL in reference/.env. + * The reference site's generated files (payload-types.ts, the import map) are put back as they were at the end, + * also when a step fails: the working tree is the same after the run. * Options: --only=webpack | --only=turbopack; --skip-plugin-build (dist and the injected copy are current). */ import { spawnSync } from 'node:child_process' -import { existsSync, readdirSync, readFileSync, statSync } from 'node:fs' +import { existsSync, readdirSync, readFileSync, statSync, writeFileSync } from 'node:fs' import path from 'node:path' import { fileURLToPath } from 'node:url' @@ -48,6 +50,20 @@ if (!args.includes('--skip-plugin-build')) { run('build the plugin', 'pnpm', ['build'], root) run('refresh the plugin copy in the reference site', 'pnpm', ['install', '--ignore-workspace'], site) } +// The run starts Payload with the fixture's collections, and Payload rewrites the site's generated types then. The +// tree must be as it was after a required release step: the file is put back at the end — also when a step fails. +const generated = ['src/payload-types.ts', 'src/app/(payload)/admin/importMap.js'].map((rel) => path.join(site, rel)).filter((file) => existsSync(file)).map((file) => ({ before: readFileSync(file), file })) +const restore = () => { + for (const { before, file } of generated) { + if (!existsSync(file) || !readFileSync(file).equals(before)) { + writeFileSync(file, before) + console.log(`[e2e:built] restored ${path.relative(root, file)} (rewritten with the fixture's collections during the run)`) + } + } +} +process.on('exit', restore) +for (const signal of ['SIGINT', 'SIGTERM']) {process.on(signal, () => process.exit(130))} + const fixture = { E2E_LATE_STAFF: '1', NODE_OPTIONS: `${process.env.NODE_OPTIONS ?? ''} --max-old-space-size=3072`.trim() } const passed = [] for (const bundler of bundlers) { From be2e6d52d9876a843c6d1956a97e050e0847a4f0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rados=C5=82aw=20Smoli=C5=84ski?= Date: Wed, 25 Nov 2026 02:59:44 +0100 Subject: [PATCH 4/7] A staff collection whose accounts can hold editor or admin gets the admin rules (H-2, J-3) In the released 1.16.7. The plugin's checks go by the value on the account, but a project's own staff collection without rules got the admin rules only when ALL its role values were the plugin's; otherwise 'an account of this collection' could create, change and delete accounts. Measured on bc0fa65 (SQLite; the first shape also on Postgres and MongoDB, 2FA off and on): with roles user/editor/admin/boss, with a text and with a json roles field, config-time and added by a later plugin, an account with the role user creates an admin (201) who reads Site integrations, changes another staff collection's roles and lists the panel's accounts (200 / 200 / 200), takes the admin over and deletes it; with viewer/editor a viewer creates an editor who gets past the access rule of Site settings. canHoldStaffRole(collection): a roles select with editor or admin among its values, or a roles field whose values cannot be listed. Then: create / delete / unlock an admin, update an admin or the account itself, roles only by an admin. A project's own rules win. A warning at start when no staff account is an admin and such a collection exists. The built-site fixture gets a config-time and a late collection of that kind; nothing here touches copied collections. Co-Authored-By: Claude Fable 5.2 --- reference/e2e/late-staff-fixture.ts | 14 +++ reference/e2e/late-staff.spec.ts | 31 +++++- reference/src/payload.config.ts | 7 +- src/index.ts | 2 + src/modules/access/selfRegistration.ts | 62 ++++++++++- src/plugin.ts | 13 ++- test/accountRulesAdminValue.test.ts | 9 ++ test/accountRulesAdminValue2fa.test.ts | 9 ++ test/accountRulesAdminValueSuite.ts | 141 +++++++++++++++++++++++++ test/accountRulesSuite.ts | 40 ++++++- 10 files changed, 318 insertions(+), 10 deletions(-) create mode 100644 test/accountRulesAdminValue.test.ts create mode 100644 test/accountRulesAdminValue2fa.test.ts create mode 100644 test/accountRulesAdminValueSuite.ts diff --git a/reference/e2e/late-staff-fixture.ts b/reference/e2e/late-staff-fixture.ts index 5d59ff5..e32d7c8 100644 --- a/reference/e2e/late-staff-fixture.ts +++ b/reference/e2e/late-staff-fixture.ts @@ -9,6 +9,18 @@ import type { Config, Plugin } from 'payload' */ export const E2E_LATE_STAFF = process.env.E2E_LATE_STAFF === '1' +/** Slugs the fixture names as staff (payload.config.ts → `access.staffCollections`). */ +export const E2E_STAFF_SLUGS = ['late-staff', 'e2e-crew', 'e2e-late-text'] + +/** + * Listed BEFORE ipalKit: a staff collection of the project's own, without rules, whose roles are the plugin's values + * PLUS one more. `admin` on an account of it makes a plugin admin, so its accounts must not hand that value out. + */ +export const e2eEarlyStaff: Plugin = (config: Config) => + E2E_LATE_STAFF + ? { ...config, collections: [...(config.collections ?? []), { slug: 'e2e-crew', auth: true, fields: [{ name: 'roles', type: 'select', hasMany: true, options: ['user', 'editor', 'admin', 'boss'], saveToJWT: true }] }] } + : config + export const e2eLateStaff: Plugin = (config: Config) => E2E_LATE_STAFF ? { @@ -17,6 +29,8 @@ export const e2eLateStaff: Plugin = (config: Config) => ...(config.collections ?? []), // no access rules at all: Payload's defaults ("any logged-in user") are what ipalKit must replace { slug: 'late-staff', auth: true, fields: [{ name: 'roles', type: 'select', hasMany: true, options: ['user', 'editor', 'admin'], saveToJWT: true }], versions: true }, + // a late staff collection whose `roles` is a text field: any value can be written there, `admin` included + { slug: 'e2e-late-text', auth: true, fields: [{ name: 'roles', type: 'text', hasMany: true }] }, { slug: 'e2e-visitors', access: { create: () => true }, auth: true, fields: [] }, ], } diff --git a/reference/e2e/late-staff.spec.ts b/reference/e2e/late-staff.spec.ts index 165f611..fe2e48b 100644 --- a/reference/e2e/late-staff.spec.ts +++ b/reference/e2e/late-staff.spec.ts @@ -1,7 +1,7 @@ import { type APIRequestContext, expect, test } from '@playwright/test' import { randomUUID } from 'node:crypto' -import { totp } from './totp' +import { secondTestAdmin, totp } from './totp' /** * The account rules on a BUILT site, for a staff collection that a plugin listed after ipalKit adds @@ -25,7 +25,8 @@ test.describe('a late staff collection on a built site', () => { const tag = randomUUID().slice(0, 8) // a fully signed-in admin of the panel's collection const admin = await context(playwright, baseURL!) - expect((await admin.post('/api/users/login', { data: { email, password } })).status()).toBe(200) + // (the second test admin: the smoke and back-link specs spend the first one's 2FA attempts) + expect((await admin.post('/api/users/login', { data: { email: secondTestAdmin(email!), password } })).status()).toBe(200) expect((await (await admin.post('/api/verify-totp', { data: { token: totp(secret!) } })).json()).ok).toBe(true) // anonymous: the first-user route of the (possibly empty) late collection, in two spellings @@ -69,6 +70,32 @@ test.describe('a late staff collection on a built site', () => { // a short password is refused there too (the password rule) expect((await admin.post('/api/late-staff', { data: { email: `s-${tag}@example.com`, password: 'tooshort', roles: ['user'] } })).status()).toBe(400) + // Staff collections whose accounts can hold `admin` although the roles are not just the plugin's — a select with + // one more value (in the config), a text field (added by a later plugin): the lowest account does not make an + // admin, take the collection's admin over, or delete it, and reaches nothing an admin reaches. + for (const slug of ['e2e-crew', 'e2e-late-text']) { + const itsAdmin = await admin.post(`/api/${slug}`, { data: { email: `a-${tag}@${slug}.example.com`, password: PASSWORD, roles: ['admin'] } }) + const itsUser = await admin.post(`/api/${slug}`, { data: { email: `u-${tag}@${slug}.example.com`, password: PASSWORD, roles: ['user'] } }) + expect([slug, itsAdmin.status(), itsUser.status()]).toEqual([slug, 201, 201]) + const itsAdminId = (await itsAdmin.json()).doc.id as string + const itsUserId = (await itsUser.json()).doc.id as string + const api = await context(playwright, baseURL!) + expect((await api.post(`/api/${slug}/login`, { data: { email: `u-${tag}@${slug}.example.com`, password: PASSWORD } })).status()).toBe(200) + expect([slug, { + create: (await api.post(`/api/${slug}`, { data: { email: `made-${tag}@${slug}.example.com`, password: PASSWORD, roles: ['admin'] } })).status(), + integrations: (await api.get('/api/globals/site-integrations')).status(), + patch: (await api.patch(`/api/${slug}/${itsAdminId}`, { data: { password: `taken-${PASSWORD}` } })).status(), + users: (await api.get('/api/users')).status(), + // last: it would remove the account the other calls are about + zDelete: (await api.delete(`/api/${slug}/${itsAdminId}`)).status(), + }]).toEqual([slug, { create: 403, integrations: 403, patch: 403, users: 403, zDelete: 403 }]) + await api.patch(`/api/${slug}/${itsUserId}`, { data: { roles: ['admin'] } }) + expect((await (await admin.get(`/api/${slug}/${itsUserId}`)).json()).roles, `${slug}: its own roles`).toEqual(['user']) + expect((await api.patch(`/api/${slug}/${itsUserId}`, { data: { password: `own-${PASSWORD}` } })).status(), `${slug}: its own password`).toBe(200) + for (const id of [itsAdminId, itsUserId]) {expect((await admin.delete(`/api/${slug}/${id}`)).status()).toBe(200)} + await api.dispose() + } + // an admin: everything, and it cleans up expect((await admin.get('/api/late-staff/versions')).status()).toBe(200) expect((await admin.post('/api/late-staff/unlock', { data: { email: `low-${tag}@example.com` } })).status()).toBe(200) diff --git a/reference/src/payload.config.ts b/reference/src/payload.config.ts index 1e4c019..8b05dd3 100644 --- a/reference/src/payload.config.ts +++ b/reference/src/payload.config.ts @@ -19,7 +19,7 @@ import { Pages } from './collections/Pages' import { Posts } from './collections/Posts' // @starter:endif // @starter:if demo -import { E2E_LATE_STAFF, e2eLateStaff } from '../e2e/late-staff-fixture' +import { E2E_LATE_STAFF, E2E_STAFF_SLUGS, e2eEarlyStaff, e2eLateStaff } from '../e2e/late-staff-fixture' // @starter:endif import { contentConfig } from './content.config' import { db } from './db' @@ -56,11 +56,14 @@ export default buildConfig({ sharp, typescript: { outputFile: path.resolve(dirname, 'payload-types.ts') }, plugins: [ + // @starter:if demo + e2eEarlyStaff, // a test fixture, a no-op without E2E_LATE_STAFF=1 (e2e/late-staff-fixture.ts) + // @starter:endif ipalKit({ i18n: i18nConfig, // @starter:if demo // (the staffCollections entry exists only for e2e/late-staff.spec.ts, with E2E_LATE_STAFF=1) - access: { authCollection: 'users', ...(E2E_LATE_STAFF ? { staffCollections: ['late-staff'] } : {}) }, + access: { authCollection: 'users', ...(E2E_LATE_STAFF ? { staffCollections: E2E_STAFF_SLUGS } : {}) }, // @starter:else //: access: { authCollection: 'users' }, // @starter:endif diff --git a/src/index.ts b/src/index.ts index bfb6cc4..e81001b 100644 --- a/src/index.ts +++ b/src/index.ts @@ -30,11 +30,13 @@ export { applyStaffAccountAccess, bothAllow, buildFirstUserEndpoint, + canHoldStaffRole, hasPluginRoles, openSignUpCollections, rolesByAdminOnly, rolesNotOwn, sameStaffCollectionAccess, + staffCollectionsNobodyManages, staffCollectionsOnOwnRoles, staffCollectionsOpenToOthers, staffCreateAccess, diff --git a/src/modules/access/selfRegistration.ts b/src/modules/access/selfRegistration.ts index 0ee6662..b19672a 100644 --- a/src/modules/access/selfRegistration.ts +++ b/src/modules/access/selfRegistration.ts @@ -96,11 +96,35 @@ function findRolesField(fields: FieldLike[] | undefined): FieldLike | undefined return undefined } +/** The values of the collection's `roles` select (at the top level of the data, also inside a row or an unnamed tab), or null when it has none. */ +const roleValues = (collection: Staffish): null | unknown[] => { + const field = findRolesField(collection.fields as FieldLike[]) as { options?: unknown[]; type?: string } | undefined + if (!field || field.type !== 'select' || !Array.isArray(field.options) || !field.options.length) {return null} + return field.options.map((option) => (typeof option === 'string' ? option : (option as { value?: unknown })?.value)) +} + /** True when the collection carries the plugin's roles: a `roles` select at the top level of the data (also inside a row or an unnamed tab) whose values are all the plugin's. */ export function hasPluginRoles(collection: Staffish): boolean { - const field = findRolesField(collection.fields as FieldLike[]) as { options?: unknown[]; type?: string } | undefined - if (!field || field.type !== 'select' || !Array.isArray(field.options) || !field.options.length) {return false} - return field.options.every((option) => ROLE_HIERARCHY.includes((typeof option === 'string' ? option : (option as { value?: unknown })?.value) as never)) + return roleValues(collection)?.every((value) => ROLE_HIERARCHY.includes(value as never)) ?? false +} + +/** + * True when an account of the collection can hold one of the plugin's roles that carry rights — `editor` or + * `admin` — whatever else its `roles` field offers. + * + * The plugin's predicates go by the VALUE on the account (`isAdmin`, `isEditor`, `userMeetsRole`): an account of + * a staff collection whose roles hold `admin` is a plugin admin, also when the select offers `boss` next to it; one + * that holds `editor` edits the site's settings. So the accounts of such a collection must not be able to hand + * those values out to each other, and the admin rules apply: + * - a `roles` select with `editor` or `admin` among its options (`user, editor, admin, boss`; `viewer, editor`); + * - a `roles` field whose values cannot be listed — a text or json field, a select without options: anything + * can be written there, `admin` included. + * False without a `roles` field, and for a select whose options hold neither value (`lead, member`). + */ +export function canHoldStaffRole(collection: Staffish): boolean { + if (!findRolesField(collection.fields as FieldLike[])) {return false} + const values = roleValues(collection) + return values === null || values.some((value) => value === 'editor' || value === 'admin') } /** What the plugin put on a staff collection (`custom.ipalAccountRules`) — for the doctor and for late collections. */ @@ -147,7 +171,8 @@ export type StaffAccountAccessOptions = { */ function ruleStaffCollection(collection: CollectionConfig, { create = true, pluginRoles = [], read = true, write = true }: StaffAccountAccessOptions, late = false): StaffAccountRules { const slug = collection.slug - const ours = pluginRoles.includes(slug) || hasPluginRoles(collection) + // the admin rules: where the roles are the plugin's, and wherever an account can hold `editor` or `admin` (canHoldStaffRole) + const ours = pluginRoles.includes(slug) || hasPluginRoles(collection) || canHoldStaffRole(collection) const other = sameStaffCollectionAccess(slug) const access = (collection.access ?? {}) as Record const applied: string[] = [] @@ -322,6 +347,35 @@ export function applyFirstUserRoute(config: Config, option: FirstUserRouteOption type LivePayload = { collections: Record; config?: unknown } +/** + * For the start-up line: staff collections that run on the plugin's ADMIN rules (other than `except`, the collection + * with the plugin's own roles) while NO account of any staff collection is a plugin admin — then nobody can create, + * delete or unlock accounts there. Returns their slugs; `[]` when an admin exists, when there is no such + * collection, or when the accounts cannot be counted (a `roles` field that cannot be queried). + */ +export async function staffCollectionsNobodyManages( + payload: { collections: Record; count: (args: { collection: string; overrideAccess: boolean; where?: unknown }) => Promise<{ totalDocs: number }> }, + staffSlugs: string[], + except?: string, +): Promise { + const staff = staffSlugs.map((slug) => payload.collections?.[slug]?.config).filter((c): c is CollectionConfig => Boolean(c?.auth)) + const ruled = staff.filter((c) => { + const rules = (c.custom as { ipalAccountRules?: StaffAccountRules } | undefined)?.ipalAccountRules + return c.slug !== except && rules && !rules.ownRoles && rules.applied.includes('create') && Boolean(findRolesField(c.fields as FieldLike[])) + }) + if (!ruled.length) {return []} + try { + for (const c of staff) { + // without a `roles` field every account of a staff collection is an admin to the plugin + const where = findRolesField(c.fields as FieldLike[]) ? { roles: { in: ['admin'] } } : undefined + if ((await payload.count({ collection: c.slug, overrideAccess: true, where })).totalDocs > 0) {return []} + } + } catch { + return [] // cannot tell: say nothing + } + return ruled.map((c) => c.slug).sort() +} + /** * Auth collections whose `create` rule lets an anonymous request through — open sign-up. * For the doctor (slugs only). A rule that throws, or needs more than `{ req }`, counts as closed. diff --git a/src/plugin.ts b/src/plugin.ts index 9ac799e..b386bf6 100644 --- a/src/plugin.ts +++ b/src/plugin.ts @@ -15,7 +15,7 @@ import { buildSiteSettings } from './globals/SiteSettings/index.js' import { adminOnly, adminOrSelfIn, injectRoles, registerStaffCollections, staffCollectionSlugs } from './modules/access/index.js' import { applyPanelRole, countBelowPanelRole, resolvePanelRole } from './modules/access/panelRole.js' import { applyPasswordRule, buildPasswordRuleHook, resolvePasswordRule } from './modules/access/passwordRule.js' -import { adoptLateAuthCollections, applyFirstUserRoute, applyStaffAccountAccess, markSeenAuthCollections, unknownStaffCollections } from './modules/access/selfRegistration.js' +import { adoptLateAuthCollections, applyFirstUserRoute, applyStaffAccountAccess, markSeenAuthCollections, staffCollectionsNobodyManages, unknownStaffCollections } from './modules/access/selfRegistration.js' import { ROLE_HIERARCHY } from './modules/access/types.js' import { applyAdminI18n } from './modules/admin-i18n/apply.js' import { buildAdminImageEndpoints } from './modules/branding/adminImages.js' @@ -935,6 +935,17 @@ export const ipalKit = (options: IpalOptions): Plugin => { 'Every account of the login collection can open the panel. To keep the lowest role out, set access.defaultRole to \'editor\' or drop access.firstUserAdmin: false (docs/access.md "Account rules").', ) } + // Staff collections on the admin rules while no staff account is an admin: nobody can manage their accounts. + if (accounts) { + const stuck = await staffCollectionsNobodyManages(payload as never, staffCollectionSlugs(payload), options.access?.authCollection) + if (stuck.length) { + payload.logger.warn( + `[ipal] No staff account holds the role "admin", so NOBODY can create, delete or unlock accounts in ${stuck.map((s) => `"${s}"`).join(', ')} ` + + "(only an admin does there: the collection's roles can hold \"editor\" or \"admin\"). Give one account the role with a script " + + '(payload.update, Local API), or write the collection\'s own access.create / update / delete rules (docs/access.md "Account rules").', + ) + } + } // The panel role: tell a site how many of its accounts the rule keeps out of the panel. if (panelRoleFor) { try { diff --git a/test/accountRulesAdminValue.test.ts b/test/accountRulesAdminValue.test.ts new file mode 100644 index 0000000..92db11f --- /dev/null +++ b/test/accountRulesAdminValue.test.ts @@ -0,0 +1,9 @@ +/** The plugin's role values plus one more on a staff collection, 2FA off — see accountRulesAdminValueSuite.ts. */ +import { vi } from 'vitest' + +import { adminValueSuite } from './accountRulesAdminValueSuite.js' + +vi.mock('server-only', () => ({})) +vi.mock('next/headers.js', async () => (await import('./http/server.js')).nextHeadersMock) + +adminValueSuite(false) diff --git a/test/accountRulesAdminValue2fa.test.ts b/test/accountRulesAdminValue2fa.test.ts new file mode 100644 index 0000000..03e825f --- /dev/null +++ b/test/accountRulesAdminValue2fa.test.ts @@ -0,0 +1,9 @@ +/** The plugin's role values plus one more on a staff collection, 2FA ON — see accountRulesAdminValueSuite.ts. */ +import { vi } from 'vitest' + +import { adminValueSuite } from './accountRulesAdminValueSuite.js' + +vi.mock('server-only', () => ({})) +vi.mock('next/headers.js', async () => (await import('./http/server.js')).nextHeadersMock) + +adminValueSuite(true) diff --git a/test/accountRulesAdminValueSuite.ts b/test/accountRulesAdminValueSuite.ts new file mode 100644 index 0000000..d0a241e --- /dev/null +++ b/test/accountRulesAdminValueSuite.ts @@ -0,0 +1,141 @@ +/** + * A project's own staff collection, without access rules of its own, whose accounts CAN hold one of the plugin's + * roles that carry rights — although its `roles` field is not the plugin's (in the released 1.16.7: H-2, J-3): + * - the plugin's values plus one more (`user, editor, admin, boss`); + * - `editor` among values of its own, no `admin` (`viewer, editor`); + * - a `roles` field whose values cannot be listed: text, json. + * The plugin's checks go by the value on the account, so such an account is a plugin admin / editor. Before, these + * collections counted as "roles of the project's own" and got "an account of this collection" for create / update / + * delete: an account with the lowest role created an `admin` there and was in everything. Now: the admin rules. + * Config-time and added by a later plugin. Real HTTP; SQLite, Postgres, MongoDB. + */ +import type { Config, Field, Payload, Plugin } 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 { ipalKit } 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 ROLES: Field = { name: 'roles', type: 'select', hasMany: true, options: ['user', 'editor', 'admin', 'boss'], saveToJWT: true } +const TEXT_ROLES: Field = { name: 'roles', type: 'text', hasMany: true } +const late: Plugin = (config: Config) => ({ + ...config, + collections: [...(config.collections ?? []), { slug: 'late-crew', auth: true, fields: [ROLES] }, { slug: 'late-text', auth: true, fields: [TEXT_ROLES] }], +}) +/** The shapes: the lowest role of the collection, and the plugin role an account of it must not be able to hand out. */ +const SHAPES: { low: string[]; other?: string[]; slug: string; top: 'admin' | 'editor' }[] = [ + { slug: 'crew', low: ['user'], other: ['boss'], top: 'admin' }, + { slug: 'late-crew', low: ['user'], other: ['boss'], top: 'admin' }, + { slug: 'viewers', low: ['viewer'], top: 'editor' }, + { slug: 'text-roles', low: ['user'], other: ['anything'], top: 'admin' }, + { slug: 'late-text', low: ['user'], top: 'admin' }, + { slug: 'json-roles', low: ['user'], top: 'admin' }, +] + +/** One Payload instance per test file: run from a file of its own for 2FA off and on. */ +export function adminValueSuite(twoFactor: boolean): void { + test(`a staff collection whose accounts can hold editor or admin: the admin rules (2FA on: ${twoFactor})`, async () => { + const config = buildTestConfig({ + admin: { user: 'users' }, + collections: [ + { slug: 'crew', auth: true, fields: [ROLES] }, + { slug: 'agents', auth: true, fields: [{ ...ROLES, options: ['user', 'editor', 'admin'] } as Field] }, + { slug: 'viewers', auth: true, fields: [{ ...ROLES, options: ['viewer', 'editor'] } as Field] }, + { slug: 'text-roles', auth: true, fields: [TEXT_ROLES] }, + { slug: 'json-roles', auth: true, fields: [{ name: 'roles', type: 'json' }] }, + // its own values with neither `editor` nor `admin`: the plugin cannot tell who its admins are — unchanged + { slug: 'team', auth: true, fields: [{ ...ROLES, options: ['lead', 'member'] } as Field] }, + { slug: 'customers', access: { create: () => true }, auth: true, fields: [] }, + { slug: 'media', fields: [], upload: { staticDir: path.join(os.tmpdir(), 'ipal-test-media') } }, + ], + db: testDatabase(twoFactor ? 'admin_value_2fa' : 'admin_value'), + editor: lexicalEditor(), + plugins: [ + ipalKit({ + access: { authCollection: 'users', staffCollections: ['crew', 'agents', 'team', 'late-crew', 'viewers', 'text-roles', 'json-roles', 'late-text'] }, + 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, + }) + const payload: Payload = await getPayload({ config }) + const server = await startPayloadServer(config) + type Session = Record + 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 = (collection: string, email: string, roles: string[]) => payload.create({ collection: collection as never, data: { email, password: PASSWORD, roles } as never }) + const login = async (collection: string, email: string, password = PASSWORD): Promise => { + const body = (await (await call('POST', `/${collection}/login`, {}, { email, password })).json()) as { token?: string } + return body.token ? { authorization: `JWT ${body.token}` } : null + } + const rolesOf = async (collection: string, id: unknown) => ((await payload.findByID({ id: id as never, collection: collection as never })) as { roles?: string[] }).roles + try { + const agent = await make('agents', 'one@agents.example.com', ['user']) + await make('agents', 'admin@agents.example.com', ['admin']) + // IPAL_TEST_SHAPE=: one shape only — for measuring an older tree, where the first open shape stops the run + for (const { slug, low, other, top } of SHAPES.filter((shape) => !process.env.IPAL_TEST_SHAPE || shape.slug === process.env.IPAL_TEST_SHAPE)) { + // the account the others must not take over: the collection's highest (an admin, or — `viewers` — an editor) + const target = await make(slug, `top@${slug}.example.com`, [top]) + const mine = await make(slug, `low@${slug}.example.com`, low) + if (other) {await make(slug, `other@${slug}.example.com`, other)} + for (const email of [`low@${slug}.example.com`, ...(other ? [`other@${slug}.example.com`] : [])]) { + const me = (await login(slug, email))! + const id = (await payload.find({ collection: slug as never, where: { email: { equals: email } } })).docs[0].id + const role = await rolesOf(slug, id) + // one object, so a failure shows everything that was open + const got = { + createTop: (await call('POST', `/${slug}`, me, { email: `made-by-${email}`, password: PASSWORD, roles: [top] })).status, + // …and as that account: the secrets global, another staff collection's roles, the panel's accounts, a settings global + madeReaches: await (async () => { + const made = await login(slug, `made-by-${email}`) + if (!made) {return 'no such account'} + return [(await call('GET', '/globals/site-integrations', made)).status, (await call('PATCH', `/agents/${agent.id}`, made, { roles: ['admin'] })).status, (await call('GET', '/users', made)).status, (await call('POST', '/globals/site-settings', made, {})).status] + })(), + ownRoles: await (async () => { + await call('PATCH', `/${slug}/${id}`, me, { roles: [top] }) + const after = await rolesOf(slug, id) + await payload.update({ id: id as never, collection: slug as never, data: { roles: role } as never }) + return after + })(), + takeOverTop: (await call('PATCH', `/${slug}/${target.id}`, me, { password: 'taken-over-password-1' })).status, + unlockTop: (await call('POST', `/${slug}/unlock`, me, { email: `top@${slug}.example.com` })).status, + // last: it removes the account the other calls are about + zDeleteTop: (await call('DELETE', `/${slug}/${target.id}`, me)).status, + } + expect([slug, email, got]).toEqual([slug, email, { createTop: 403, madeReaches: 'no such account', ownRoles: role, takeOverTop: 403, unlockTop: 403, zDeleteTop: 403 }]) + } + // what stays: its own password + const me = (await login(slug, `low@${slug}.example.com`))! + expect([slug, (await call('PATCH', `/${slug}/${mine.id}`, me, { password: 'my-own-new-password-1' })).status]).toEqual([slug, 200]) + // who manages the accounts: an admin of the collection where it has one, and an admin of another staff collection + const managers = [(await login('agents', 'admin@agents.example.com'))!, ...(top === 'admin' ? [(await login(slug, `top@${slug}.example.com`))!] : [])] + for (const [index, manager] of managers.entries()) { + expect([slug, index, (await call('POST', `/${slug}`, manager, { email: `by-manager-${index}@${slug}.example.com`, password: PASSWORD, roles: low })).status, (await call('PATCH', `/${slug}/${mine.id}`, manager, { roles: low })).status]).toEqual([slug, index, 201, 200]) + } + // an editor of such a collection is not an admin: it creates nobody (the `viewers` shape) + if (top === 'editor') { + const editor = (await login(slug, `top@${slug}.example.com`))! + expect([slug, (await call('POST', `/${slug}`, editor, { email: `by-editor@${slug}.example.com`, password: PASSWORD, roles: ['editor'] })).status]).toEqual([slug, 403]) + } + } + // role values with neither `editor` nor `admin`: as before — accounts of the collection manage it, never their own roles + await make('team', 'member@team.example.com', ['member']) + const member = (await login('team', 'member@team.example.com'))! + expect((await call('POST', '/team', member, { email: 'new@team.example.com', password: PASSWORD, roles: ['lead'] })).status).toBe(201) + } finally { + await server.close() + await payload.destroy?.() + } + }, 120_000) +} diff --git a/test/accountRulesSuite.ts b/test/accountRulesSuite.ts index d913ecf..5812f08 100644 --- a/test/accountRulesSuite.ts +++ b/test/accountRulesSuite.ts @@ -19,7 +19,7 @@ import type { I18nConfig } from '../src/modules/i18n/types.js' import { countBelowPanelRole, panelAccess, resolvePanelRole } from '../src/modules/access/panelRole.js' import { checkPassword, resolvePasswordRule } from '../src/modules/access/passwordRule.js' -import { adoptLateAuthCollections, bothAllow, hasPluginRoles, openSignUpCollections, rolesByAdminOnly, rolesNotOwn, sameStaffCollectionAccess, staffCollectionsOnOwnRoles, staffCollectionsOpenToOthers, staffCreateAccess, staffReadAccess, staffUpdateAccess, unknownStaffCollections } from '../src/modules/access/selfRegistration.js' +import { adoptLateAuthCollections, bothAllow, canHoldStaffRole, hasPluginRoles, openSignUpCollections, rolesByAdminOnly, rolesNotOwn, sameStaffCollectionAccess, staffCollectionsNobodyManages, staffCollectionsOnOwnRoles, staffCollectionsOpenToOthers, staffCreateAccess, staffReadAccess, staffUpdateAccess, unknownStaffCollections } from '../src/modules/access/selfRegistration.js' import { ipalKit } from '../src/plugin.js' import { buildTestConfig, withTotpParts } from './helpers.js' import { testDatabase } from './http/db.js' @@ -565,6 +565,19 @@ export function accountRulesSuite(twoFactor: boolean): void { 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 + expect(canHoldStaffRole({ slug: 'x', fields: [{ name: 'roles', type: 'text' }] } as never)).toBe(true) + expect(canHoldStaffRole({ slug: 'x', fields: [{ name: 'roles', type: 'json' }] } as never)).toBe(true) + expect(canHoldStaffRole(roles([]))).toBe(true) + expect(canHoldStaffRole({ slug: 'x', fields: [{ type: 'row', fields: [{ name: 'roles', type: 'text' }] }] } as never)).toBe(true) 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) @@ -731,6 +744,31 @@ export function accountRulesSuite(twoFactor: boolean): void { 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', 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']) } }, + 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']) } }, + } + const withAdmins = (admins: Record, fail = false) => ({ + collections, + count: async ({ collection }: { collection: string }) => { + if (fail) {throw new Error('cannot query')} + return { totalDocs: admins[collection] ?? 0 } + }, + }) + // nobody is an admin anywhere: the collections on the admin rules, without the plugin's own (it has its own warning) + expect(await staffCollectionsNobodyManages(withAdmins({}) as never, ['users', 'crew', 'team'], 'users')).toEqual(['crew']) + // an admin in the collection, or in another staff collection, manages it + expect(await staffCollectionsNobodyManages(withAdmins({ crew: 1 }) as never, ['users', 'crew', 'team'], 'users')).toEqual([]) + expect(await staffCollectionsNobodyManages(withAdmins({ users: 2 }) as never, ['users', 'crew', 'team'], 'users')).toEqual([]) + // nothing on the admin rules; or the accounts cannot be counted: nothing is said + expect(await staffCollectionsNobodyManages(withAdmins({}) as never, ['users', 'team'], 'users')).toEqual([]) + expect(await staffCollectionsNobodyManages(withAdmins({}, true) as never, ['users', 'crew'], 'users')).toEqual([]) + }) + test('openSignUpCollections: slugs of auth collections an anonymous request may create in', async () => { const collections = { customers: { config: { slug: 'customers', access: { create: () => true }, auth: true } }, From ccc6f859245bfdadaa84d545e7c72950a0275ba4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rados=C5=82aw=20Smoli=C5=84ski?= Date: Wed, 25 Nov 2026 02:59:44 +0100 Subject: [PATCH 5/7] Security follow-ups to 1.16.7: changelog, access guide, skills, API table, release gate, reference index Co-Authored-By: Claude Fable 5.2 --- docs/CHANGELOG.md | 67 +++++++++++++++++++ docs/access.md | 29 +++++++- docs/agent/AGENT.md | 2 +- docs/agent/reference-site/INDEX.md | 47 +++++++++++-- docs/agent/skills/ipal-debug/SKILL.md | 2 + .../skills/ipal-reference/resources/api.md | 4 +- docs/agent/skills/ipal-setup/SKILL.md | 2 +- docs/agent/skills/ipal-upgrade/SKILL.md | 8 ++- docs/dev/PROGRAMISTA.md | 20 +++++- docs/doctor.md | 2 +- reference/.agents/skills/ipal-debug/SKILL.md | 2 + .../skills/ipal-reference/resources/api.md | 4 +- reference/.agents/skills/ipal-setup/SKILL.md | 2 +- .../.agents/skills/ipal-upgrade/SKILL.md | 8 ++- scripts/reference-index.mjs | 5 +- 15 files changed, 183 insertions(+), 21 deletions(-) diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md index 080a8f0..0ebc86e 100644 --- a/docs/CHANGELOG.md +++ b/docs/CHANGELOG.md @@ -8,6 +8,73 @@ versions at once, go through every "Requires project changes" section in order, version you have. A new release = a new section at the top; we remove the oldest ones only once there are more than 20. +## Unreleased — security follow-ups to 1.16.7 (version to be set at release) + +> **Read before upgrading.** No option, schema, migration or import-map change. Two points: +> **What can stop people:** on a project's own staff collection **without access rules of its own** whose +> accounts can hold `editor` or `admin` although its roles are not just the plugin's — a `roles` select such as +> `user, editor, admin, boss` or `viewer, editor`, or a `roles` field that is text or json — an account that is +> not an admin can no longer create, delete or unlock accounts there, change another account, or change +> anybody's roles. If **no** staff account holds `admin`, nobody can (the start log says so; the way out is +> below). And a site **built with Turbopack** (`next build` without `--webpack`): see Security. + +### Security +- **A staff collection whose accounts can hold `editor` or `admin` gets the admin rules.** The plugin's checks go + by the value on the account: `admin` on an account of a staff collection makes a plugin admin, `editor` an + editor — whatever else the collection's `roles` field offers. But a project's own staff collection without + rules got the admin rules only when ALL its role values were the plugin's; otherwise "an account of this + collection" could create, change and delete accounts. So with roles `user, editor, admin, boss` an account + with the role `user` created an `admin` there (or set the admin's password) and then read Site integrations, + changed other staff collections' roles and listed the panel's accounts; with `viewer, editor` a `viewer` made + an `editor` who saves Site settings; the same with a `roles` field that is text or json. In 1.16.7 and, wider, + before it. Now such a collection — in the config or added by a later plugin — gets: create, delete, unlock — + an admin; update — an admin or the account itself; roles — only an admin. Not affected: `access.authCollection`, + collections with rules of their own, a `roles` select whose values hold neither `editor` nor `admin`. No known + site has such a collection ([access.md](./access.md) "Account rules"). +- **A Turbopack build of a site published the plugin's `package.json`.** The plugin read its own version from + that file by a path relative to its module, and a bundler takes such a file for an asset: Turbopack copied it + to `/_next/static/media/package..json`, where anyone could fetch it. It is the **plugin's** manifest, not + the project's: the plugin's name and version, its dependency lists with version ranges (also the development + ones), its script names, and the addresses of the package registry and the git repository it comes from. **No + secret, token or password**, and nothing of the project. The file name is a content hash and no page links to + it. A webpack build (`next build --webpack`, what the starter and the reference site use) kept the file on the + server side: not served. The version is now a constant in the code (`src/version.ts`); nothing is read from + disk at run time. + +### Added +- A start-log warning when staff collections run on the admin rules and no staff account holds `admin`. +- `pnpm e2e:built` (plugin repository): builds the reference site with webpack and with Turbopack and checks, + on each, the account rules on a built site and that no package manifest is among the public files. Part of + the release gate (PROGRAMISTA §8.1). The reference site's Playwright runs reset the test admins first + (`e2e/global-setup.ts`), so a spec no longer fails because of what ran before it. +- Exports: `canHoldStaffRole`, `staffCollectionsNobodyManages`. + +### Requires project changes +- **A staff collection of your own, without access rules, whose accounts can hold `editor` or `admin`** (a + `roles` select with one of them next to values of your own, or a text / json `roles` field): only an admin + creates, deletes and unlocks accounts there and changes roles; another account is changed by an admin or by + itself. If accounts with a role of your own (`boss`, `viewer`) managed accounts there, write that as the + collection's own rules (`access.create` / `update` / `delete`, field access on `roles`) — the plugin gives + your values no rights. In a collection where nobody can be an `admin` (`viewer, editor`), accounts are + managed by an admin of another staff collection (the panel's). +- **Read the start log after the upgrade.** `[ipal] No staff account holds the role "admin", so NOBODY can + create, delete or unlock accounts in "…"`: no account of any staff collection is an admin. Give one account + the role with a script (`payload.update({ collection, id, data: { roles: ['admin'] } })`, `pnpm payload run`), + or write the collection's own rules. To switch the default off for every staff collection: `accounts: { + adminOnlyCreate: false, adminOnlyWrite: false }` (that also takes the protection off). +- **A site built with Turbopack:** update and rebuild — the new build has no `package..json` under + `/_next/static/media/`. Check: `find .next/static -name 'package*.json'` prints nothing. Nothing to do for a + webpack build. +- `pnpm ipal:skills`. + +### Known limitations +- A staff collection **without a `roles` field** is unchanged: every account of it is an admin to the plugin. +- A `roles` select of your own whose values hold neither `editor` nor `admin` is unchanged: inside it every + account may create, change and delete accounts (`ipal-doctor --url` → `staff-own-roles`). +- The warning counts accounts whose `roles` hold `admin`; where a `roles` field cannot be queried it says nothing. +- **Not run for this change:** the starter built with Turbopack (it is generated from the reference site and uses + the same plugin code; the reference site was built with both bundlers). + ## 1.16.7 — hardening > **Read before upgrading.** Several defaults get stricter. Most sites change nothing, but check diff --git a/docs/access.md b/docs/access.md index e1577b6..8d731fa 100644 --- a/docs/access.md +++ b/docs/access.md @@ -290,11 +290,36 @@ list the staff accounts, and lift the lock after failed logins. | The collection | `create`, `delete`, `unlock` | `update` | the `roles` field (when it has no `access.update`) | `read`, `readVersions` | |---|---|---|---|---| -| carries **the plugin's roles**: it is `access.authCollection`, or has a `roles` select whose values are all `user` / `editor` / `admin` (`hasPluginRoles`) | an admin (`staffCreateAccess`) | an admin, or the account itself (`staffUpdateAccess(slug)`) | only an admin changes it (`rolesByAdminOnly`) | a staff account (`staffReadAccess`) | -| has **roles of its own** (`superadmin`, `writer`, …) or no `roles` field — the plugin cannot tell who its admins are | an account of that same collection, or a plugin admin of another staff collection (`sameStaffCollectionAccess(slug)`) | the same | an account never changes its **own** (`rolesNotOwn(slug)`) | a staff account | +| carries **the plugin's roles**: it is `access.authCollection`, or has a `roles` select whose values are all `user` / `editor` / `admin` (`hasPluginRoles`), **or one whose accounts can hold `editor` or `admin`**, whatever else its `roles` field offers (`canHoldStaffRole`, below) | an admin (`staffCreateAccess`) | an admin, or the account itself (`staffUpdateAccess(slug)`) | only an admin changes it (`rolesByAdminOnly`) | a staff account (`staffReadAccess`) | +| has **roles of its own that hold neither `editor` nor `admin`** (`superadmin`, `writer`, …) or no `roles` field — the plugin cannot tell who its admins are | an account of that same collection, or a plugin admin of another staff collection (`sameStaffCollectionAccess(slug)`) | the same | an account never changes its **own** (`rolesNotOwn(slug)`) | a staff account | Always "fully signed in": a session that still owes its second factor passes none of them. +**A `roles` field that can hold `editor` or `admin`.** The plugin's checks go by the **value on the account** +(`isAdmin`, `isEditor`): an account of a staff collection whose `roles` hold `admin` is a plugin admin, one that +holds `editor` edits the site's settings — whatever else the field offers. So wherever an account of the +collection **can** hold one of the two, the collection gets the admin rules (`canHoldStaffRole`): + +| The collection's `roles` field | Rules | +|---|---| +| a select with `editor` or `admin` among its values — `user, editor, admin, boss`; `viewer, editor` | the admin rules (first row above) | +| a field whose values cannot be listed — text, json, a select without options: anything can be written there | the admin rules | +| a select whose values are all your own and hold neither — `lead, member` | "an account of that same collection" (second row) | +| no `roles` field | second row; every account of it is an admin to the plugin (below) | + +Otherwise any account of such a collection could hand the value out: create an `admin` and be in Site +integrations and every other staff collection, or create an `editor` and change the site's settings. (Until this +change these collections got the second row, and an account with the lowest role could do exactly that.) +**What it means for your accounts:** a role the plugin does not know (`boss`, `viewer`) carries no rights of the +plugin's — such an account no longer creates, deletes or unlocks accounts there, changes another account or +anybody's roles. Give it what it needs with rules of your own (`access.create` / `update` / `delete`, field +access on `roles`), which win as always. In a collection where nobody can be an `admin` (`viewer, editor`) the +accounts are managed by an admin of another staff collection — the panel's. +**If no staff account holds `admin` at all**, nobody can create, delete or unlock accounts in such a collection. +The start log says so: `[ipal] No staff account holds the role "admin", so NOBODY can create, delete or unlock +accounts in "…"`. Way out: give one account the role with a script (`payload.update`, Local API), or write the +collection's own rules. + **Roles of your own — what the plugin does and does not hold.** It cannot rank `superadmin` against `writer`, so inside such a collection it enforces one thing only: an account does not change its own roles. Everything else that was allowed inside the collection stays allowed — **every account of it may still create an account diff --git a/docs/agent/AGENT.md b/docs/agent/AGENT.md index b63edc0..49f0e11 100644 --- a/docs/agent/AGENT.md +++ b/docs/agent/AGENT.md @@ -1172,7 +1172,7 @@ add missing hosts with flags / `extra`; (3) change `mode` to `'enforce'` in both | Stored secrets are write-only: `smtpPassword` and `turnstileSecretKey` come back as `'********'` over REST, GraphQL and in the panel; an empty save keeps the value, `'[[clear]]'` removes it; server code reads the real value with the Local API. **The panel is the source — never add an env variable for them** (`TURNSTILE_SECRET_KEY` is deprecated) | `secrets: { writeOnly: false }` | `writeOnlySecret(field)` / `writeOnlySecrets(fields, names)` for your own secret fields; with versions on the entity add `hooks.afterRead: [maskSecretsOnRestore]` | | The SMTP password stays with its server: a save in the panel or over the API that changes the server, port or user name without the password is refused (`400` "Enter the password again…"), whatever the transport says — otherwise an admin session points the server at its own machine and a test e-mail hands the password over. A change of the transport alone asks for nothing. Seeds and scripts (Local API, access control off) are not asked | `secrets: { reenterOnChange: false }` | `writeOnlySecret(field, { boundTo: [...] })`, `buildKeepSecret`, `SMTP_PASSWORD_BOUND_TO` | | The admin panel opens for `editor` and above; an account with only `user` sees "Unauthorized" (the API is not touched). First start logs how many accounts are below the role | `accounts: { panelRole: 'user' }` (or `false`) | `panelRole: 'admin'`; your own `access.admin`; `panelAccess(role)` | -| Nobody creates an account for themselves, or takes one over. A staff collection (also the project's own, also one a later plugin adds) without a `create` / `update` / `delete` / `unlock` / `read` / `readVersions` rule gets one (on a collection a later plugin adds the plugin's rule is put in front of its own and both must allow; `custom: { ipal: { accountRules: false } }` on it keeps its own): with the plugin's roles — create, delete, unlock: an admin; update: an admin or the account itself; the `roles` field: only an admin. With roles of its own, or none: an account of that same collection, or a plugin admin, and an account never changes its own roles — **the plugin cannot rank a project's own roles: write that collection's rules** (`ipal-doctor` → `staff-own-roles`). `read`: a staff account. Payload's first-user route answers only for the panel's login collection (the first account, which becomes admin), in any spelling of the URL. `access.firstUserAdmin: false` with a default role below the panel role: the default panel role is not applied (logged), an explicit one is refused at start. With a slug in `access.staffCollections` that is not an auth collection Payload does not start (`/api/health` 503) | `accounts: { adminOnlyCreate: false, adminOnlyWrite: false, staffOnlyRead: false, firstUserRoute: 'all' }` | your own rule wins; `firstUserRoute: ['users', 'partners']`; a collection with open sign-up keeps its routes; `staffCreateAccess`, `staffUpdateAccess(slug)`, `staffReadAccess`, `sameStaffCollectionAccess(slug)`, `rolesByAdminOnly`, `rolesNotOwn(slug)`, `hasPluginRoles`, `applyStaffAccountAccess`, `adoptLateAuthCollections`, `buildFirstUserEndpoint` | +| Nobody creates an account for themselves, or takes one over. A staff collection (also the project's own, also one a later plugin adds) without a `create` / `update` / `delete` / `unlock` / `read` / `readVersions` rule gets one (on a collection a later plugin adds the plugin's rule is put in front of its own and both must allow; `custom: { ipal: { accountRules: false } }` on it keeps its own): with the plugin's roles, or wherever an account of it can hold `editor` or `admin` (`user, editor, admin, boss`; `viewer, editor`; a `roles` field that is text or json — the value on the account makes a plugin admin or editor) — create, delete, unlock: an admin; update: an admin or the account itself; the `roles` field: only an admin. With roles of its own that hold neither `editor` nor `admin`, or none: an account of that same collection, or a plugin admin, and an account never changes its own roles — **the plugin cannot rank a project's own roles: write that collection's rules** (`ipal-doctor` → `staff-own-roles`). `read`: a staff account. Payload's first-user route answers only for the panel's login collection (the first account, which becomes admin), in any spelling of the URL. `access.firstUserAdmin: false` with a default role below the panel role: the default panel role is not applied (logged), an explicit one is refused at start. With a slug in `access.staffCollections` that is not an auth collection Payload does not start (`/api/health` 503) | `accounts: { adminOnlyCreate: false, adminOnlyWrite: false, staffOnlyRead: false, firstUserRoute: 'all' }` | your own rule wins; `firstUserRoute: ['users', 'partners']`; a collection with open sign-up keeps its routes; `staffCreateAccess`, `staffUpdateAccess(slug)`, `staffReadAccess`, `sameStaffCollectionAccess(slug)`, `rolesByAdminOnly`, `rolesNotOwn(slug)`, `hasPluginRoles`, `applyStaffAccountAccess`, `adoptLateAuthCollections`, `buildFirstUserEndpoint` | | A password set on a staff account has at least 12 characters and is not the e-mail address; existing passwords are not checked | `accounts: { password: false }` | `password: { minLength }`; `checkPassword`, `buildPasswordRuleHook` | | While Turnstile cannot check (wrong secret, Cloudflare down): a text form is accepted, a form with files is refused | `forms: { turnstileOnConfigError: 'allow' }` | `'reject'`, `{ text, files }`; `turnstileOnConfigError` at a call site wins | | Dashboard alerts by role: integration details for admins, a neutral line for editors, nothing for others; cookie alerts for editors and above. `'all'` checks nothing — no role, no second factor | `dashboardAlerts: { integrations: 'all', cookies: 'all' }` | `integrations: 'editor'`; the components' `details` / `audience` props | diff --git a/docs/agent/reference-site/INDEX.md b/docs/agent/reference-site/INDEX.md index e49b92e..d81e54a 100644 --- a/docs/agent/reference-site/INDEX.md +++ b/docs/agent/reference-site/INDEX.md @@ -93,9 +93,10 @@ try { } /** - * Smoke tests against a built, seeded site: pnpm build && pnpm seed && pnpm payload run e2e/create-test-admin.ts. - * Run create-test-admin.ts again before repeating the tests within ten minutes: the 2FA verify limit (5 attempts per - * account in 10 minutes) is stored in the database, and that script clears the test admins' counts. + * Smoke tests against a built, seeded site: pnpm seed && pnpm build. + * The 2FA verify limit (5 attempts per account in 10 minutes) is stored in the database; the global setup resets the + * test admins and clears their counts before every run (e2e/global-setup.ts; E2E_SKIP_ADMIN_SETUP=1 for a run that + * needs an EMPTY database, the fresh-site spec). * E2E_BASE_URL picks the port (default 3100). Playwright starts its own server there and fails when the port is * taken, so another project's dev server is never tested by mistake; E2E_REUSE_SERVER=1 uses a server you started. */ @@ -103,6 +104,8 @@ const baseURL = process.env.E2E_BASE_URL ?? 'http://localhost:3100' export default defineConfig({ forbidOnly: !!process.env.CI, + // makes every run independent of the one before: test admins reset, stored 2FA attempt counts cleared + globalSetup: './e2e/global-setup.ts', projects: [{ name: 'chromium', use: { ...devices['Desktop Chrome'] } }], reporter: process.env.CI ? 'line' : 'list', retries: process.env.CI ? 1 : 0, @@ -1160,14 +1163,34 @@ Rules: AGENT.md §8a. | File | What it shows | |---|---| | `e2e/create-test-admin.ts` | two test admins with a known TOTP secret (the specs share out the five 2FA verify attempts per account), their stored verify counts cleared, and e-mail sending pointed at the tests' mail sink (local / CI database only) | -| `e2e/late-staff-fixture.ts` | test fixture, on only with E2E_LATE_STAFF=1: a plugin listed after ipalKit that adds a staff collection without rules and a visitor collection with open sign-up (below) | -| `e2e/late-staff.spec.ts` | the account rules on a BUILT site for a staff collection a later plugin adds (run after a webpack and a Turbopack build): a visitor account gets nothing, nobody raises its own role | +| `e2e/global-setup.ts` | Playwright global setup: resets the test admins and clears their stored 2FA attempt counts before every run, so specs do not depend on run order (below) | +| `e2e/late-staff-fixture.ts` | test fixture, on only with E2E_LATE_STAFF=1: one plugin before ipalKit (a staff collection of the config whose roles are the plugin's values plus one more) and one after it (a staff collection without rules, one whose roles field is text, a visitor collection with open sign-up) (below) | +| `e2e/late-staff.spec.ts` | the account rules on a BUILT site (run by `pnpm e2e:built` after a webpack and a Turbopack build): a staff collection a later plugin adds, and staff collections whose accounts can hold `admin` — a visitor account gets nothing, nobody raises its own role or makes an admin | | `e2e/smoke.spec.ts` | the smoke tests every release must pass: pages, showcase, forms (also a file sent by e-mail), sitemap, SEO/GEO, headers, consent, 2FA | | `e2e/smtp-sink.ts` | a local mail sink for the smoke tests: reads what the site really sent (recipients, attachments) | | `e2e/totp.ts` | RFC 6238 code generator for the 2FA sign-in in the smoke test, and the address of the second test admin (below) | | `e2e/two-factor-back.spec.ts` | browser test of the 2FA screens' `back` link (twoFactor.safeBack): a prepared link — script or another host — ends on the admin root, an ordinary one is followed | | `e2e/two-factor-setup.spec.ts` | browser check of "2FA setup required": the first admin of a fresh site, a new editor, the administrator's reset on the account page | +### `e2e/global-setup.ts` + +```ts +import { execFileSync } from 'node:child_process' + +/** + * Before every Playwright run: the test admins are made (or reset) and their stored 2FA attempt counts cleared + * (e2e/create-test-admin.ts). The count is kept in the database — 5 verify attempts per account in 10 minutes — + * so without this a second run within ten minutes, or one spec run after the whole suite, would find the test + * admin locked out: the result would depend on what ran before. Skipped when the test admin is not configured + * (the specs that need it skip themselves) or with E2E_SKIP_ADMIN_SETUP=1. + */ +export default function globalSetup(): void { + const { E2E_ADMIN_EMAIL, E2E_ADMIN_PASSWORD, E2E_SKIP_ADMIN_SETUP, E2E_TOTP_SECRET } = process.env + if (E2E_SKIP_ADMIN_SETUP === '1' || !E2E_ADMIN_EMAIL || !E2E_ADMIN_PASSWORD || !E2E_TOTP_SECRET) {return} + execFileSync('pnpm', ['payload', 'run', 'e2e/create-test-admin.ts'], { env: { ...process.env, NODE_ENV: 'development' }, stdio: 'inherit' }) +} +``` + ### `e2e/late-staff-fixture.ts` ```ts @@ -1182,6 +1205,18 @@ import type { Config, Plugin } from 'payload' */ export const E2E_LATE_STAFF = process.env.E2E_LATE_STAFF === '1' +/** Slugs the fixture names as staff (payload.config.ts → `access.staffCollections`). */ +export const E2E_STAFF_SLUGS = ['late-staff', 'e2e-crew', 'e2e-late-text'] + +/** + * Listed BEFORE ipalKit: a staff collection of the project's own, without rules, whose roles are the plugin's values + * PLUS one more. `admin` on an account of it makes a plugin admin, so its accounts must not hand that value out. + */ +export const e2eEarlyStaff: Plugin = (config: Config) => + E2E_LATE_STAFF + ? { ...config, collections: [...(config.collections ?? []), { slug: 'e2e-crew', auth: true, fields: [{ name: 'roles', type: 'select', hasMany: true, options: ['user', 'editor', 'admin', 'boss'], saveToJWT: true }] }] } + : config + export const e2eLateStaff: Plugin = (config: Config) => E2E_LATE_STAFF ? { @@ -1190,6 +1225,8 @@ export const e2eLateStaff: Plugin = (config: Config) => ...(config.collections ?? []), // no access rules at all: Payload's defaults ("any logged-in user") are what ipalKit must replace { slug: 'late-staff', auth: true, fields: [{ name: 'roles', type: 'select', hasMany: true, options: ['user', 'editor', 'admin'], saveToJWT: true }], versions: true }, + // a late staff collection whose `roles` is a text field: any value can be written there, `admin` included + { slug: 'e2e-late-text', auth: true, fields: [{ name: 'roles', type: 'text', hasMany: true }] }, { slug: 'e2e-visitors', access: { create: () => true }, auth: true, fields: [] }, ], } diff --git a/docs/agent/skills/ipal-debug/SKILL.md b/docs/agent/skills/ipal-debug/SKILL.md index 81483c5..3b68f31 100644 --- a/docs/agent/skills/ipal-debug/SKILL.md +++ b/docs/agent/skills/ipal-debug/SKILL.md @@ -103,6 +103,8 @@ through this procedure. Ask only when you are missing something you cannot get y | an account logs in to `/admin` and sees "Unauthorized" (its API calls still work) | `accounts.panelRole`: the panel opens for `editor` and above; the account has only `user`, or no role | give it `editor` (an admin edits the account), or `accounts: { panelRole: 'user' }`; nobody can get in: a script with the Local API sets `roles: ['admin']`, or `accounts: { panelRole: false }` + redeploy | | `POST /api//first-register` answers `403` on an empty collection | `accounts.firstUserRoute`: only the panel's login collection may register its first account that way (the plugin's own endpoint sits in front of Payload's) | an admin creates the account; or the collection's own `create: () => true` (sign-up); or `accounts: { firstUserRoute: [''] }` | | an editor (or a script with its token) gets `403` creating an account in the project's own `users` | `accounts.adminOnlyCreate`: only admins create staff accounts where the roles are the plugin's | create as an admin; or write the collection's `create` rule; or `adminOnlyCreate: false` | +| log at start: `[ipal] No staff account holds the role "admin", so NOBODY can create, delete or unlock accounts in "…"` | a staff collection whose accounts can hold `editor` or `admin` runs on the admin rules, and no staff account is an admin | give one account `admin` with a script (`payload.update`, Local API); or write the collection's own `access.create` / `update` / `delete` | +| an account with a role of the project's own (`boss`, `viewer`) gets `403` creating or editing accounts in its staff collection (it worked on 1.16.7) | the collection's `roles` can hold `editor` or `admin` (a select with one of them, or a text / json field): the admin rules apply | do it as an admin; or write the collection's own rules for that role | | an account gets `403` changing or deleting ANOTHER account of a staff collection (it worked before) | `accounts.adminOnlyWrite`: an admin, or the account itself (update only); on a collection with roles of its own: accounts of that collection | do it as an admin; or write the collection's `update` / `delete` rule; or `adminOnlyWrite: false` | | an account saves its own profile and its `roles` do not change (no error) | `accounts.adminOnlyWrite`: nobody changes its own roles; with the plugin's roles only an admin changes roles | an admin changes the role; or give the `roles` field its own `access.update` | | a logged-in visitor (customer) gets `403` reading a staff collection — an author box went empty | `accounts.staffOnlyRead`: only staff accounts read a staff collection without a `read` rule | write that collection's `read` rule; or `staffOnlyRead: false` | diff --git a/docs/agent/skills/ipal-reference/resources/api.md b/docs/agent/skills/ipal-reference/resources/api.md index e61142e..dccc47d 100644 --- a/docs/agent/skills/ipal-reference/resources/api.md +++ b/docs/agent/skills/ipal-reference/resources/api.md @@ -67,8 +67,8 @@ Admin panel components from `@intecion/ipal-kit/admin` — the project does NOT | `isAdmin(user, source?)` | `@intecion/ipal-kit`; in client components `@intecion/ipal-kit/client` | Predicate → `boolean`: staff account with the `admin` role (see `hasMinimumRole`). In hooks and endpoints: `isAdmin(req.user, req.payload)`; in a client component: `isAdmin(user, config)` from `/client` — the main entry does not build there with webpack (`'server-only' cannot be imported…`). | | `isEditor(user, source?)` | `@intecion/ipal-kit`; in client components `@intecion/ipal-kit/client` | Predicate → `boolean`: staff account with `editor` or higher. | | `panelAccess(minimum?)`, `applyPanelRole(config, slug, role)`, `resolvePanelRole(option)`, `countBelowPanelRole(payload, slug, role)`, `DEFAULT_PANEL_ROLE` | `@intecion/ipal-kit` | `accounts.panelRole`: an `access.admin` function ("holds at least `minimum`", default `'editor'`; role only, not the second factor); the applier (skips a collection that has its own `access.admin`); the option → role or `null` when off; `{ all, below }` counts for the start-up line; `'editor'`. | -| `staffCreateAccess`, `staffUpdateAccess(slug)`, `staffReadAccess`, `sameStaffCollectionAccess(slug)`, `rolesByAdminOnly`, `rolesNotOwn(slug)`, `hasPluginRoles(collection)`, `applyStaffAccountAccess(config, staffSlugs, { create?, write?, read?, pluginRoles? })` | `@intecion/ipal-kit` | `accounts.adminOnlyCreate` / `adminOnlyWrite` / `staffOnlyRead`: the access functions — "an admin, fully signed in" (create, delete, unlock); "an admin, or the account itself" (update; self = an account of THAT collection); "a fully signed-in account of a staff collection" (read); "an account of this staff collection, or a plugin admin of another" (a collection whose roles are not the plugin's); the two field-access functions for a `roles` field (`update`: only an admin / never the account itself); whether a collection carries the plugin's roles (a `roles` select at the top level of the data with only `user` / `editor` / `admin`); the applier — puts the rules on the named staff collections for the operations that have none and closes the `roles` field where the plugin's `update` rule is in force, `pluginRoles` = slugs whose roles field is injected later. Run it before any plugin that wraps access (the 2FA package). | -| `buildFirstUserEndpoint(option?)`, `applyFirstUserRoute(config, option?)`, `adoptLateAuthCollections(config, staffSlugs, { access?, beforeOperation?, firstUserRoute? })`, `bothAllow(first, second)`, `unknownStaffCollections(config, staffSlugs)`, `openSignUpCollections(payload)`, `staffCollectionsOpenToOthers(payload)`, `staffCollectionsOnOwnRoles(payload)` | `@intecion/ipal-kit` | `accounts.firstUserRoute`: the plugin's own `POST /first-register` collection endpoint, matched before Payload's — `403` unless the collection is the panel's login collection (`'panel'`), is in the list, or its own `create` lets an anonymous request through; otherwise it calls Payload's handler (and sets `req.context.ipalFirstRegister`); the applier (every auth collection; `'all'` adds nothing; `endpoints: false` is left alone). For the doctor: slugs of auth collections with open sign-up; `':'` for every staff collection an account of a non-staff collection may create in, read, update, delete from or unlock; slugs of staff collections with role values of their own on the default rules. `adoptLateAuthCollections` takes the LIVE config (`payload.config`) and gives auth collections that a plugin listed after ipalKit added the same rules, in place (called by the plugin at start and on every dev reload; returns `LateAdoption[]` — per collection what was put). There the rules are combined with the collection's own by `bothAllow` (an access function that allows only when both do; two query constraints are joined with `and`), because in a sanitized config Payload's default cannot be told from a written rule — never by a function's name, which a production build changes. `custom.ipal.accountRules: false` on a late collection keeps its rules as they are. `unknownStaffCollections` lists staff slugs that are not auth collections (Payload does not start on any). | +| `staffCreateAccess`, `staffUpdateAccess(slug)`, `staffReadAccess`, `sameStaffCollectionAccess(slug)`, `rolesByAdminOnly`, `rolesNotOwn(slug)`, `hasPluginRoles(collection)`, `canHoldStaffRole(collection)`, `applyStaffAccountAccess(config, staffSlugs, { create?, write?, read?, pluginRoles? })` | `@intecion/ipal-kit` | `accounts.adminOnlyCreate` / `adminOnlyWrite` / `staffOnlyRead`: the access functions — "an admin, fully signed in" (create, delete, unlock); "an admin, or the account itself" (update; self = an account of THAT collection); "a fully signed-in account of a staff collection" (read); "an account of this staff collection, or a plugin admin of another" (a collection whose roles are not the plugin's); the two field-access functions for a `roles` field (`update`: only an admin / never the account itself); whether a collection carries the plugin's roles (a `roles` select at the top level of the data with only `user` / `editor` / `admin`); whether an account of it can hold `editor` or `admin` whatever else the field offers (a select with one of them among its values, or a `roles` field whose values cannot be listed — text, json) — then the admin rules apply too; the applier — puts the rules on the named staff collections for the operations that have none and closes the `roles` field where the plugin's `update` rule is in force, `pluginRoles` = slugs whose roles field is injected later. Run it before any plugin that wraps access (the 2FA package). | +| `buildFirstUserEndpoint(option?)`, `applyFirstUserRoute(config, option?)`, `adoptLateAuthCollections(config, staffSlugs, { access?, beforeOperation?, firstUserRoute? })`, `bothAllow(first, second)`, `unknownStaffCollections(config, staffSlugs)`, `openSignUpCollections(payload)`, `staffCollectionsOpenToOthers(payload)`, `staffCollectionsOnOwnRoles(payload)`, `staffCollectionsNobodyManages(payload, staffSlugs, except?)` | `@intecion/ipal-kit` | `accounts.firstUserRoute`: the plugin's own `POST /first-register` collection endpoint, matched before Payload's — `403` unless the collection is the panel's login collection (`'panel'`), is in the list, or its own `create` lets an anonymous request through; otherwise it calls Payload's handler (and sets `req.context.ipalFirstRegister`); the applier (every auth collection; `'all'` adds nothing; `endpoints: false` is left alone). For the doctor: slugs of auth collections with open sign-up; `':'` for every staff collection an account of a non-staff collection may create in, read, update, delete from or unlock; slugs of staff collections with role values of their own on the default rules. `adoptLateAuthCollections` takes the LIVE config (`payload.config`) and gives auth collections that a plugin listed after ipalKit added the same rules, in place (called by the plugin at start and on every dev reload; returns `LateAdoption[]` — per collection what was put). There the rules are combined with the collection's own by `bothAllow` (an access function that allows only when both do; two query constraints are joined with `and`), because in a sanitized config Payload's default cannot be told from a written rule — never by a function's name, which a production build changes. `custom.ipal.accountRules: false` on a late collection keeps its rules as they are. `unknownStaffCollections` lists staff slugs that are not auth collections (Payload does not start on any). | `staffCollectionsNobodyManages` (async): staff collections on the admin rules while no staff account is a plugin admin — nobody can create, delete or unlock accounts there (the plugin warns at start). | `checkPassword(password, { email?, minLength? })`, `buildPasswordRuleHook({ minLength? })`, `applyPasswordRule(config, slugs, rule)`, `resolvePasswordRule(option)`, `DEFAULT_PASSWORD_MIN_LENGTH` | `@intecion/ipal-kit` | `accounts.password`: `'short' \| 'email' \| null` for a new password (length in characters); the `beforeOperation` hook for `create` / `update` / `resetPassword` (throws Payload's `ValidationError` on `password`, text in the panel's language; the account's address is looked up by id, reset token or bulk query when the request carries none; a password that is not text is refused; login is never checked); the applier; the option → `{ minLength }` or `null`; `12`. | | `writeOnlySecret(field, options?)`, `writeOnlySecrets(fields, names, optionsByName?)`, `maskSecretAfterRead`, `keepSecretBeforeValidate`, `buildKeepSecret(options?)`, `SECRET_MASK`, `SECRET_CLEAR`, `isSecretMask(value)`, `INTEGRATION_SECRET_FIELDS`, `SMTP_PASSWORD_BOUND_TO` | `@intecion/ipal-kit` | Write-only secret fields (`secrets.writeOnly`): the wrapper for one field and for named fields anywhere in a tree (tabs, rows, groups); the two field hooks (reads through access control get `'********'`, the Local API with access control off gets the value; a save with nothing / empty / the mask keeps the stored value, `'[[clear]]'` removes it); the hook builder with options — `{ boundTo: ['siblingField'], appliesWhen?: (siblingData) => boolean }`: a save through access control that changes a bound sibling field without sending the secret throws a `ValidationError` on the secret (`secrets.reenterOnChange`); the two constants; the plugin's own secret field names (`smtpPassword`, `turnstileSecretKey`); the fields the SMTP password is bound to (`smtpHost`, `smtpPort`, `smtpUser` — not the transport: the mail adapter may fall back to SMTP). | | `maskSecretsOnRestore`, `maskWriteOnlySecrets(data, fields)` | `@intecion/ipal-kit` | Versions and write-only secrets: the `afterRead` hook for a global or a collection (a restore answers with the version document, fields under `version`, where field hooks do not run — it masks them there for reads through access control); the walker it uses (masks every write-only field in `data`, following tabs, rows, groups, arrays and blocks). On Site integrations by default; add the hook to your own entity that has both. | diff --git a/docs/agent/skills/ipal-setup/SKILL.md b/docs/agent/skills/ipal-setup/SKILL.md index 930bf7e..858bc1f 100644 --- a/docs/agent/skills/ipal-setup/SKILL.md +++ b/docs/agent/skills/ipal-setup/SKILL.md @@ -252,7 +252,7 @@ the panel shows Site settings, Site integrations, Cookies, Form messages, the Fo users at least `editor`); only an admin creates staff accounts, and an account is changed by an admin or by itself, nobody changes its own roles, and only staff accounts read staff accounts — also in the project's own staff collection and in one a later plugin adds (`adminOnlyCreate`, `adminOnlyWrite`, `staffOnlyRead`). **A - staff collection with role values of its own** (not `user` / `editor` / `admin`) gets only "an account of that + staff collection with role values of its own that hold neither `editor` nor `admin`** gets only "an account of that collection, or a plugin admin": the plugin cannot rank your roles, so inside it every account may create an account with any role — **write its `create` / `update` / `delete` rules and the field access of its `roles` field yourself** (`ipal-doctor --url` → `staff-own-roles`). Give every staff collection a `roles` field: without diff --git a/docs/agent/skills/ipal-upgrade/SKILL.md b/docs/agent/skills/ipal-upgrade/SKILL.md index 8adba70..dee04a5 100644 --- a/docs/agent/skills/ipal-upgrade/SKILL.md +++ b/docs/agent/skills/ipal-upgrade/SKILL.md @@ -459,7 +459,13 @@ account → "Two-step verification: Set up." and the reset button; delete the ac `editor` / `admin`): create, delete, unlock — an admin; update — an admin or the account itself; its `roles` field — only an admin (when the field has no `access.update` of its own). **Check:** does a non-admin create or edit other accounts, or change roles, there today? Then write the rule you want; - - the collection has **role values of its own** (`superadmin`, …) or no roles: accounts of that collection + - an account of the collection **can hold `editor` or `admin`** although its roles are not just the plugin's + (`user, editor, admin, boss`; `viewer, editor`; a `roles` field that is text or json): the admin rules too, + since the release after 1.16.7 (the value on the account makes a plugin admin or editor). **Check:** do + accounts with one of your own roles (`boss`, `viewer`) manage accounts there? Then write that as the + collection's own rules. Read the start log: `No staff account holds the role "admin", so NOBODY can create, + delete or unlock accounts in "…"` — give one account `admin` with a script, or write the rules; + - the collection has **role values of its own that hold neither** (`superadmin`, …) or no roles: accounts of that collection keep working as before, except that an account no longer changes its **own** roles; accounts of other collections are refused. **Write your own rules** — the plugin does not know your roles, and inside the collection every account can still create an account with any role (`ipal-doctor --url` → diff --git a/docs/dev/PROGRAMISTA.md b/docs/dev/PROGRAMISTA.md index 97e85f5..9f06a24 100644 --- a/docs/dev/PROGRAMISTA.md +++ b/docs/dev/PROGRAMISTA.md @@ -754,7 +754,8 @@ dev is running. pnpm build:starter && pnpm test:int && pnpm starter:gate` before every `npm publish`, so you cannot release a stale dist, a version with red tests or a starter that does not produce a working site (docs/project-starter.md; `pnpm clean && pnpm build` above is only a grep check before the commit). `prepare` (`pnpm build`) builds the package on install from git and on `pnpm install` in the repo. -`typecheck` and `lint` are **not** in `prepublishOnly` — before a commit: `pnpm typecheck && pnpm lint && +`pnpm e2e:built` is **not** in `prepublishOnly` either (it needs the reference site's `.env` and database): it is a +required step of §8.1. `typecheck` and `lint` are **not** in `prepublishOnly` — before a commit: `pnpm typecheck && pnpm lint && pnpm test:int` (CI in `.gitea/workflows/ci.yml` runs typecheck, lint, test:int and build on push and PR). ### 8.1b The reference site (`reference/`) — part of every release @@ -769,7 +770,21 @@ done until the reference site uses it. Before `npm version`: - [ ] Local run green: `pnpm build` (plugin) → `pnpm --dir reference install --ignore-workspace` (refreshes the injected copy) → in `reference/`: `pnpm generate:types && pnpm generate:importmap` (no diff), `pnpm typecheck`, `pnpm seed` on a throwaway MongoDB, `pnpm build`, `ALLOW_LOCAL_MEDIA=1 PORT=3100 pnpm start`, - `pnpm payload run e2e/create-test-admin.ts`, `pnpm test:e2e`. + `pnpm test:e2e` (Playwright's global setup runs `e2e/create-test-admin.ts` first: test admins reset, stored 2FA + attempt counts cleared, so the result does not depend on what ran before; the fresh-site spec on an EMPTY + database: `E2E_SKIP_ADMIN_SETUP=1`). +- [ ] **`pnpm e2e:built` green — required, no release without it.** It builds the reference site with webpack AND with + Turbopack (with the late-staff fixture, `E2E_LATE_STAFF=1`) and runs, on each built site: the account rules of + staff collections the project or a later plugin adds (`e2e/late-staff.spec.ts`), and "no package manifest among + the public files". Unit tests run unminified code and cannot see what a bundle renames or publishes — two + defects of the 1.16.7 review lived only in a built site. Needs `reference/.env` (local seeded MongoDB, `E2E_*` + test admin); port from `E2E_BASE_URL`. Afterwards `git status` is clean (the command puts the reference site's + generated types and import map back, also when it fails); rebuild the reference site without the fixture + (`pnpm build` there) before other checks. +- [ ] `pnpm version ` or `npm version --no-git-tag-version` writes the version into `src/version.ts` + as well (the `version` script; by hand: `node scripts/write-version.mjs`). **Not `pnpm --ignore-workspace + version …`**: that runs the `version` script itself with the arguments and fails. `test/version.test.ts` fails + when the constant differs from package.json. - [ ] `pnpm reference:index` → `docs/agent/reference-site/INDEX.md` committed (`test/referenceIndex.test.ts` fails otherwise; a new file in `reference/` needs its line in `scripts/reference-index.mjs` → `DESCRIPTIONS`). - [ ] CI job `reference` green (`.gitea/workflows/ci.yml`), the starter check included once `ipal-kit create` ships. @@ -790,6 +805,7 @@ The site uses the plugin as `file:..` with `dependenciesMeta.injected`, so the p | package contract | `test/exports.test.ts` | every `@intecion/ipal-kit/…` path from the docs exists in `exports` | | docs ↔ code | `test/docsConsistency.test.ts` | names imported in the docs exist in the entry points / `lib/content`; every public export is described in the docs | | e2e | `pnpm test:e2e` (Playwright) | `pnpm test` = `test:int` + `test:e2e` | +| built site, both bundlers | `pnpm e2e:built` (`scripts/e2e-built.mjs`, the reference site) | what only a production bundle shows: nothing decided by a function's name, nothing private among the public files (§8.1) | Rules: **every fixed bug = a regression test** (check that it fails on the old code); no network (`vi.spyOn(globalThis, 'fetch')`); env through `vi.stubEnv` + `unstubAllEnvs`; diff --git a/docs/doctor.md b/docs/doctor.md index c0a8506..d856fc1 100644 --- a/docs/doctor.md +++ b/docs/doctor.md @@ -102,7 +102,7 @@ Turn off: `ipalKit({ doctor: false })`. Adapt: `ipalKit({ doctor: { tokenVar: 'M | | `access-missing` | warning | `ipalKit` has an `access` option — without it there are no roles and every panel account is an admin | | | `csrf-empty` | warning | the config sets `serverURL` or `csrf` — otherwise Payload accepts the login cookie from any origin | | | `open-signup` | info | (deep) auth collections whose `create` rule lets an anonymous request through: sign-up is open there (intended for a customer zone — silence with a reason) | -| | `staff-own-roles` | warning | (deep) a staff collection with role values of its own (not `user` / `editor` / `admin`) that runs on the plugin's default account rules: the plugin cannot rank those roles, so inside the collection every account may create an account with any role and change or delete another. Write the collection's own rules | +| | `staff-own-roles` | warning | (deep) a staff collection with role values of its own, neither `editor` nor `admin` among them, that runs on the plugin's default account rules: the plugin cannot rank those roles, so inside the collection every account may create an account with any role and change or delete another. Write the collection's own rules | | | `staff-accounts-open` | error (warning for `read`, `readVersions`) | (deep) a staff collection that an account of another, non-staff auth collection may create in, read (also its versions), update, delete from or unlock — it can make itself staff, change a staff password, list the accounts or lift a login lock. The account rules are off (`accounts: false`, `adminOnlyCreate` / `adminOnlyWrite` / `staffOnlyRead: false`) or the project's own rule is wider. Asked with a made-up outside account; a rule that throws counts as closed | | | `turnstile-degraded` | warning / error | (deep) Turnstile is checking forms; while it is not (wrong or missing secret, Cloudflare down) a warning, an error once it has lasted 24 hours (counted from the recorded start to now) | | | `turnstile-env-key` | warning | (deep) the Turnstile secret key is in the panel, not in the deprecated `TURNSTILE_SECRET_KEY` environment variable | diff --git a/reference/.agents/skills/ipal-debug/SKILL.md b/reference/.agents/skills/ipal-debug/SKILL.md index 81483c5..3b68f31 100644 --- a/reference/.agents/skills/ipal-debug/SKILL.md +++ b/reference/.agents/skills/ipal-debug/SKILL.md @@ -103,6 +103,8 @@ through this procedure. Ask only when you are missing something you cannot get y | an account logs in to `/admin` and sees "Unauthorized" (its API calls still work) | `accounts.panelRole`: the panel opens for `editor` and above; the account has only `user`, or no role | give it `editor` (an admin edits the account), or `accounts: { panelRole: 'user' }`; nobody can get in: a script with the Local API sets `roles: ['admin']`, or `accounts: { panelRole: false }` + redeploy | | `POST /api//first-register` answers `403` on an empty collection | `accounts.firstUserRoute`: only the panel's login collection may register its first account that way (the plugin's own endpoint sits in front of Payload's) | an admin creates the account; or the collection's own `create: () => true` (sign-up); or `accounts: { firstUserRoute: [''] }` | | an editor (or a script with its token) gets `403` creating an account in the project's own `users` | `accounts.adminOnlyCreate`: only admins create staff accounts where the roles are the plugin's | create as an admin; or write the collection's `create` rule; or `adminOnlyCreate: false` | +| log at start: `[ipal] No staff account holds the role "admin", so NOBODY can create, delete or unlock accounts in "…"` | a staff collection whose accounts can hold `editor` or `admin` runs on the admin rules, and no staff account is an admin | give one account `admin` with a script (`payload.update`, Local API); or write the collection's own `access.create` / `update` / `delete` | +| an account with a role of the project's own (`boss`, `viewer`) gets `403` creating or editing accounts in its staff collection (it worked on 1.16.7) | the collection's `roles` can hold `editor` or `admin` (a select with one of them, or a text / json field): the admin rules apply | do it as an admin; or write the collection's own rules for that role | | an account gets `403` changing or deleting ANOTHER account of a staff collection (it worked before) | `accounts.adminOnlyWrite`: an admin, or the account itself (update only); on a collection with roles of its own: accounts of that collection | do it as an admin; or write the collection's `update` / `delete` rule; or `adminOnlyWrite: false` | | an account saves its own profile and its `roles` do not change (no error) | `accounts.adminOnlyWrite`: nobody changes its own roles; with the plugin's roles only an admin changes roles | an admin changes the role; or give the `roles` field its own `access.update` | | a logged-in visitor (customer) gets `403` reading a staff collection — an author box went empty | `accounts.staffOnlyRead`: only staff accounts read a staff collection without a `read` rule | write that collection's `read` rule; or `staffOnlyRead: false` | diff --git a/reference/.agents/skills/ipal-reference/resources/api.md b/reference/.agents/skills/ipal-reference/resources/api.md index e61142e..dccc47d 100644 --- a/reference/.agents/skills/ipal-reference/resources/api.md +++ b/reference/.agents/skills/ipal-reference/resources/api.md @@ -67,8 +67,8 @@ Admin panel components from `@intecion/ipal-kit/admin` — the project does NOT | `isAdmin(user, source?)` | `@intecion/ipal-kit`; in client components `@intecion/ipal-kit/client` | Predicate → `boolean`: staff account with the `admin` role (see `hasMinimumRole`). In hooks and endpoints: `isAdmin(req.user, req.payload)`; in a client component: `isAdmin(user, config)` from `/client` — the main entry does not build there with webpack (`'server-only' cannot be imported…`). | | `isEditor(user, source?)` | `@intecion/ipal-kit`; in client components `@intecion/ipal-kit/client` | Predicate → `boolean`: staff account with `editor` or higher. | | `panelAccess(minimum?)`, `applyPanelRole(config, slug, role)`, `resolvePanelRole(option)`, `countBelowPanelRole(payload, slug, role)`, `DEFAULT_PANEL_ROLE` | `@intecion/ipal-kit` | `accounts.panelRole`: an `access.admin` function ("holds at least `minimum`", default `'editor'`; role only, not the second factor); the applier (skips a collection that has its own `access.admin`); the option → role or `null` when off; `{ all, below }` counts for the start-up line; `'editor'`. | -| `staffCreateAccess`, `staffUpdateAccess(slug)`, `staffReadAccess`, `sameStaffCollectionAccess(slug)`, `rolesByAdminOnly`, `rolesNotOwn(slug)`, `hasPluginRoles(collection)`, `applyStaffAccountAccess(config, staffSlugs, { create?, write?, read?, pluginRoles? })` | `@intecion/ipal-kit` | `accounts.adminOnlyCreate` / `adminOnlyWrite` / `staffOnlyRead`: the access functions — "an admin, fully signed in" (create, delete, unlock); "an admin, or the account itself" (update; self = an account of THAT collection); "a fully signed-in account of a staff collection" (read); "an account of this staff collection, or a plugin admin of another" (a collection whose roles are not the plugin's); the two field-access functions for a `roles` field (`update`: only an admin / never the account itself); whether a collection carries the plugin's roles (a `roles` select at the top level of the data with only `user` / `editor` / `admin`); the applier — puts the rules on the named staff collections for the operations that have none and closes the `roles` field where the plugin's `update` rule is in force, `pluginRoles` = slugs whose roles field is injected later. Run it before any plugin that wraps access (the 2FA package). | -| `buildFirstUserEndpoint(option?)`, `applyFirstUserRoute(config, option?)`, `adoptLateAuthCollections(config, staffSlugs, { access?, beforeOperation?, firstUserRoute? })`, `bothAllow(first, second)`, `unknownStaffCollections(config, staffSlugs)`, `openSignUpCollections(payload)`, `staffCollectionsOpenToOthers(payload)`, `staffCollectionsOnOwnRoles(payload)` | `@intecion/ipal-kit` | `accounts.firstUserRoute`: the plugin's own `POST /first-register` collection endpoint, matched before Payload's — `403` unless the collection is the panel's login collection (`'panel'`), is in the list, or its own `create` lets an anonymous request through; otherwise it calls Payload's handler (and sets `req.context.ipalFirstRegister`); the applier (every auth collection; `'all'` adds nothing; `endpoints: false` is left alone). For the doctor: slugs of auth collections with open sign-up; `':'` for every staff collection an account of a non-staff collection may create in, read, update, delete from or unlock; slugs of staff collections with role values of their own on the default rules. `adoptLateAuthCollections` takes the LIVE config (`payload.config`) and gives auth collections that a plugin listed after ipalKit added the same rules, in place (called by the plugin at start and on every dev reload; returns `LateAdoption[]` — per collection what was put). There the rules are combined with the collection's own by `bothAllow` (an access function that allows only when both do; two query constraints are joined with `and`), because in a sanitized config Payload's default cannot be told from a written rule — never by a function's name, which a production build changes. `custom.ipal.accountRules: false` on a late collection keeps its rules as they are. `unknownStaffCollections` lists staff slugs that are not auth collections (Payload does not start on any). | +| `staffCreateAccess`, `staffUpdateAccess(slug)`, `staffReadAccess`, `sameStaffCollectionAccess(slug)`, `rolesByAdminOnly`, `rolesNotOwn(slug)`, `hasPluginRoles(collection)`, `canHoldStaffRole(collection)`, `applyStaffAccountAccess(config, staffSlugs, { create?, write?, read?, pluginRoles? })` | `@intecion/ipal-kit` | `accounts.adminOnlyCreate` / `adminOnlyWrite` / `staffOnlyRead`: the access functions — "an admin, fully signed in" (create, delete, unlock); "an admin, or the account itself" (update; self = an account of THAT collection); "a fully signed-in account of a staff collection" (read); "an account of this staff collection, or a plugin admin of another" (a collection whose roles are not the plugin's); the two field-access functions for a `roles` field (`update`: only an admin / never the account itself); whether a collection carries the plugin's roles (a `roles` select at the top level of the data with only `user` / `editor` / `admin`); whether an account of it can hold `editor` or `admin` whatever else the field offers (a select with one of them among its values, or a `roles` field whose values cannot be listed — text, json) — then the admin rules apply too; the applier — puts the rules on the named staff collections for the operations that have none and closes the `roles` field where the plugin's `update` rule is in force, `pluginRoles` = slugs whose roles field is injected later. Run it before any plugin that wraps access (the 2FA package). | +| `buildFirstUserEndpoint(option?)`, `applyFirstUserRoute(config, option?)`, `adoptLateAuthCollections(config, staffSlugs, { access?, beforeOperation?, firstUserRoute? })`, `bothAllow(first, second)`, `unknownStaffCollections(config, staffSlugs)`, `openSignUpCollections(payload)`, `staffCollectionsOpenToOthers(payload)`, `staffCollectionsOnOwnRoles(payload)`, `staffCollectionsNobodyManages(payload, staffSlugs, except?)` | `@intecion/ipal-kit` | `accounts.firstUserRoute`: the plugin's own `POST /first-register` collection endpoint, matched before Payload's — `403` unless the collection is the panel's login collection (`'panel'`), is in the list, or its own `create` lets an anonymous request through; otherwise it calls Payload's handler (and sets `req.context.ipalFirstRegister`); the applier (every auth collection; `'all'` adds nothing; `endpoints: false` is left alone). For the doctor: slugs of auth collections with open sign-up; `':'` for every staff collection an account of a non-staff collection may create in, read, update, delete from or unlock; slugs of staff collections with role values of their own on the default rules. `adoptLateAuthCollections` takes the LIVE config (`payload.config`) and gives auth collections that a plugin listed after ipalKit added the same rules, in place (called by the plugin at start and on every dev reload; returns `LateAdoption[]` — per collection what was put). There the rules are combined with the collection's own by `bothAllow` (an access function that allows only when both do; two query constraints are joined with `and`), because in a sanitized config Payload's default cannot be told from a written rule — never by a function's name, which a production build changes. `custom.ipal.accountRules: false` on a late collection keeps its rules as they are. `unknownStaffCollections` lists staff slugs that are not auth collections (Payload does not start on any). | `staffCollectionsNobodyManages` (async): staff collections on the admin rules while no staff account is a plugin admin — nobody can create, delete or unlock accounts there (the plugin warns at start). | `checkPassword(password, { email?, minLength? })`, `buildPasswordRuleHook({ minLength? })`, `applyPasswordRule(config, slugs, rule)`, `resolvePasswordRule(option)`, `DEFAULT_PASSWORD_MIN_LENGTH` | `@intecion/ipal-kit` | `accounts.password`: `'short' \| 'email' \| null` for a new password (length in characters); the `beforeOperation` hook for `create` / `update` / `resetPassword` (throws Payload's `ValidationError` on `password`, text in the panel's language; the account's address is looked up by id, reset token or bulk query when the request carries none; a password that is not text is refused; login is never checked); the applier; the option → `{ minLength }` or `null`; `12`. | | `writeOnlySecret(field, options?)`, `writeOnlySecrets(fields, names, optionsByName?)`, `maskSecretAfterRead`, `keepSecretBeforeValidate`, `buildKeepSecret(options?)`, `SECRET_MASK`, `SECRET_CLEAR`, `isSecretMask(value)`, `INTEGRATION_SECRET_FIELDS`, `SMTP_PASSWORD_BOUND_TO` | `@intecion/ipal-kit` | Write-only secret fields (`secrets.writeOnly`): the wrapper for one field and for named fields anywhere in a tree (tabs, rows, groups); the two field hooks (reads through access control get `'********'`, the Local API with access control off gets the value; a save with nothing / empty / the mask keeps the stored value, `'[[clear]]'` removes it); the hook builder with options — `{ boundTo: ['siblingField'], appliesWhen?: (siblingData) => boolean }`: a save through access control that changes a bound sibling field without sending the secret throws a `ValidationError` on the secret (`secrets.reenterOnChange`); the two constants; the plugin's own secret field names (`smtpPassword`, `turnstileSecretKey`); the fields the SMTP password is bound to (`smtpHost`, `smtpPort`, `smtpUser` — not the transport: the mail adapter may fall back to SMTP). | | `maskSecretsOnRestore`, `maskWriteOnlySecrets(data, fields)` | `@intecion/ipal-kit` | Versions and write-only secrets: the `afterRead` hook for a global or a collection (a restore answers with the version document, fields under `version`, where field hooks do not run — it masks them there for reads through access control); the walker it uses (masks every write-only field in `data`, following tabs, rows, groups, arrays and blocks). On Site integrations by default; add the hook to your own entity that has both. | diff --git a/reference/.agents/skills/ipal-setup/SKILL.md b/reference/.agents/skills/ipal-setup/SKILL.md index 930bf7e..858bc1f 100644 --- a/reference/.agents/skills/ipal-setup/SKILL.md +++ b/reference/.agents/skills/ipal-setup/SKILL.md @@ -252,7 +252,7 @@ the panel shows Site settings, Site integrations, Cookies, Form messages, the Fo users at least `editor`); only an admin creates staff accounts, and an account is changed by an admin or by itself, nobody changes its own roles, and only staff accounts read staff accounts — also in the project's own staff collection and in one a later plugin adds (`adminOnlyCreate`, `adminOnlyWrite`, `staffOnlyRead`). **A - staff collection with role values of its own** (not `user` / `editor` / `admin`) gets only "an account of that + staff collection with role values of its own that hold neither `editor` nor `admin`** gets only "an account of that collection, or a plugin admin": the plugin cannot rank your roles, so inside it every account may create an account with any role — **write its `create` / `update` / `delete` rules and the field access of its `roles` field yourself** (`ipal-doctor --url` → `staff-own-roles`). Give every staff collection a `roles` field: without diff --git a/reference/.agents/skills/ipal-upgrade/SKILL.md b/reference/.agents/skills/ipal-upgrade/SKILL.md index 8adba70..dee04a5 100644 --- a/reference/.agents/skills/ipal-upgrade/SKILL.md +++ b/reference/.agents/skills/ipal-upgrade/SKILL.md @@ -459,7 +459,13 @@ account → "Two-step verification: Set up." and the reset button; delete the ac `editor` / `admin`): create, delete, unlock — an admin; update — an admin or the account itself; its `roles` field — only an admin (when the field has no `access.update` of its own). **Check:** does a non-admin create or edit other accounts, or change roles, there today? Then write the rule you want; - - the collection has **role values of its own** (`superadmin`, …) or no roles: accounts of that collection + - an account of the collection **can hold `editor` or `admin`** although its roles are not just the plugin's + (`user, editor, admin, boss`; `viewer, editor`; a `roles` field that is text or json): the admin rules too, + since the release after 1.16.7 (the value on the account makes a plugin admin or editor). **Check:** do + accounts with one of your own roles (`boss`, `viewer`) manage accounts there? Then write that as the + collection's own rules. Read the start log: `No staff account holds the role "admin", so NOBODY can create, + delete or unlock accounts in "…"` — give one account `admin` with a script, or write the rules; + - the collection has **role values of its own that hold neither** (`superadmin`, …) or no roles: accounts of that collection keep working as before, except that an account no longer changes its **own** roles; accounts of other collections are refused. **Write your own rules** — the plugin does not know your roles, and inside the collection every account can still create an account with any role (`ipal-doctor --url` → diff --git a/scripts/reference-index.mjs b/scripts/reference-index.mjs index feb6d5f..fa64395 100644 --- a/scripts/reference-index.mjs +++ b/scripts/reference-index.mjs @@ -60,8 +60,9 @@ export const DESCRIPTIONS = { 'README.md': 'how to run the reference site and what is where', 'docs/DEPLOY.md': 'the Coolify runbook: local check, app settings, MongoDB resource, env, targeted seeds, DNS, rollback', 'e2e/create-test-admin.ts': 'two test admins with a known TOTP secret (the specs share out the five 2FA verify attempts per account), their stored verify counts cleared, and e-mail sending pointed at the tests\' mail sink (local / CI database only)', - 'e2e/late-staff-fixture.ts': 'test fixture, on only with E2E_LATE_STAFF=1: a plugin listed after ipalKit that adds a staff collection without rules and a visitor collection with open sign-up', - 'e2e/late-staff.spec.ts': 'the account rules on a BUILT site for a staff collection a later plugin adds (run after a webpack and a Turbopack build): a visitor account gets nothing, nobody raises its own role', + 'e2e/late-staff-fixture.ts': 'test fixture, on only with E2E_LATE_STAFF=1: one plugin before ipalKit (a staff collection of the config whose roles are the plugin\'s values plus one more) and one after it (a staff collection without rules, one whose roles field is text, a visitor collection with open sign-up)', + 'e2e/late-staff.spec.ts': 'the account rules on a BUILT site (run by `pnpm e2e:built` after a webpack and a Turbopack build): a staff collection a later plugin adds, and staff collections whose accounts can hold `admin` — a visitor account gets nothing, nobody raises its own role or makes an admin', + 'e2e/global-setup.ts': 'Playwright global setup: resets the test admins and clears their stored 2FA attempt counts before every run, so specs do not depend on run order', 'e2e/two-factor-setup.spec.ts': 'browser check of "2FA setup required": the first admin of a fresh site, a new editor, the administrator\'s reset on the account page', 'e2e/smoke.spec.ts': 'the smoke tests every release must pass: pages, showcase, forms (also a file sent by e-mail), sitemap, SEO/GEO, headers, consent, 2FA', 'e2e/smtp-sink.ts': 'a local mail sink for the smoke tests: reads what the site really sent (recipients, attachments)', From c3d95988e1652d1cd674ec1ed7a80f62653e32a9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rados=C5=82aw=20Smoli=C5=84ski?= Date: Wed, 25 Nov 2026 03:44:25 +0100 Subject: [PATCH 6/7] K-1, K-2: only a roles field that holds a LIST counts; the start-up check asks each collection its own way MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit K-1 the plugin counts roles only from an array (getRoles). A single-valued roles field — a select, text or relationship without hasMany, a radio — never makes a plugin admin, yet canHoldStaffRole said true: on a project's own login collection with a single role select nobody could create, change, delete or unlock accounts, the account holding admin included. rolesAreAList(collection) is now a precondition of the admin rules. The same for hasPluginRoles: a single select whose values are all the plugin's had the admin rules already in 1.16.7 and gets 'an account of this collection' now — its accounts manage each other again; the value still grants nothing. A relationship with hasMany counts (ids that are text). K-2 staffCollectionsNobodyManages returns { stuck, unchecked } and checks collection by collection: no query where the field cannot hold admin; a count for a select with hasMany; for text / json / relationship the accounts are read and the plugin's own test is applied. Where it cannot check it says so and claims nothing. Tests: the reviewer's shapes over HTTP and the warning's table against a running Payload, 2FA off and on. Co-Authored-By: Claude Fable 5.2 --- src/index.ts | 1 + src/modules/access/selfRegistration.ts | 109 +++++++++++++++++----- src/plugin.ts | 7 +- test/accountRulesAdminValueSuite.ts | 56 +++++++++-- test/accountRulesNobodyManages.test.ts | 9 ++ test/accountRulesNobodyManages2fa.test.ts | 9 ++ test/accountRulesNobodyManagesSuite.ts | 96 +++++++++++++++++++ test/accountRulesSingleLogin.test.ts | 9 ++ test/accountRulesSingleLogin2fa.test.ts | 9 ++ test/accountRulesSingleLoginSuite.ts | 89 ++++++++++++++++++ test/accountRulesSuite.ts | 59 +++++++++--- 11 files changed, 406 insertions(+), 47 deletions(-) create mode 100644 test/accountRulesNobodyManages.test.ts create mode 100644 test/accountRulesNobodyManages2fa.test.ts create mode 100644 test/accountRulesNobodyManagesSuite.ts create mode 100644 test/accountRulesSingleLogin.test.ts create mode 100644 test/accountRulesSingleLogin2fa.test.ts create mode 100644 test/accountRulesSingleLoginSuite.ts diff --git a/src/index.ts b/src/index.ts index e81001b..c567a78 100644 --- a/src/index.ts +++ b/src/index.ts @@ -33,6 +33,7 @@ export { canHoldStaffRole, hasPluginRoles, openSignUpCollections, + rolesAreAList, rolesByAdminOnly, rolesNotOwn, sameStaffCollectionAccess, diff --git a/src/modules/access/selfRegistration.ts b/src/modules/access/selfRegistration.ts index b19672a..96dd767 100644 --- a/src/modules/access/selfRegistration.ts +++ b/src/modules/access/selfRegistration.ts @@ -103,9 +103,32 @@ const roleValues = (collection: Staffish): null | unknown[] => { return field.options.map((option) => (typeof option === 'string' ? option : (option as { value?: unknown })?.value)) } -/** True when the collection carries the plugin's roles: a `roles` select at the top level of the data (also inside a row or an unnamed tab) whose values are all the plugin's. */ +/** Field types that hold ONE value unless `hasMany` says otherwise, and those that never hold a list of role names. */ +const SINGLE_UNLESS_MANY = ['select', 'text', 'relationship', 'upload'] +const NEVER_A_ROLE_LIST = ['radio', 'number', 'date', 'checkbox', 'email', 'textarea', 'code', 'point'] + +/** + * True when the collection's `roles` field can put an ARRAY on the account. The plugin's predicates count roles + * only from an array (`getRoles` in predicates.ts): an account whose `roles` is the single value `'admin'` — a + * select or text without `hasMany`, a radio — is nobody to the plugin, so there is nothing of the plugin's to + * protect in such a collection, and its accounts keep managing each other as Payload's default lets them. + * An array: a select, text or relationship with `hasMany` (a relationship to documents with text ids holds those + * ids), json, and any type the plugin does not know. + */ +export function rolesAreAList(collection: Staffish): boolean { + const field = findRolesField(collection.fields as FieldLike[]) as { hasMany?: boolean; type?: string } | undefined + if (!field) {return false} + if (SINGLE_UNLESS_MANY.includes(field.type ?? '')) {return field.hasMany === true} + return !NEVER_A_ROLE_LIST.includes(field.type ?? '') +} + +/** + * True when the collection carries the plugin's roles: a `roles` select (at the top level of the data, also inside + * a row or an unnamed tab) with `hasMany` whose values are all the plugin's. Without `hasMany` the value never + * counts as a role (`rolesAreAList`). + */ export function hasPluginRoles(collection: Staffish): boolean { - return roleValues(collection)?.every((value) => ROLE_HIERARCHY.includes(value as never)) ?? false + return rolesAreAList(collection) && (roleValues(collection)?.every((value) => ROLE_HIERARCHY.includes(value as never)) ?? false) } /** @@ -115,14 +138,16 @@ export function hasPluginRoles(collection: Staffish): boolean { * The plugin's predicates go by the VALUE on the account (`isAdmin`, `isEditor`, `userMeetsRole`): an account of * a staff collection whose roles hold `admin` is a plugin admin, also when the select offers `boss` next to it; one * that holds `editor` edits the site's settings. So the accounts of such a collection must not be able to hand - * those values out to each other, and the admin rules apply: + * those values out to each other, and the admin rules apply. The field must be able to hold a LIST + * (`rolesAreAList`), and then: * - a `roles` select with `editor` or `admin` among its options (`user, editor, admin, boss`; `viewer, editor`); - * - a `roles` field whose values cannot be listed — a text or json field, a select without options: anything - * can be written there, `admin` included. - * False without a `roles` field, and for a select whose options hold neither value (`lead, member`). + * - a `roles` field whose values cannot be listed — text, json, a relationship (to documents whose ids are text), + * a select without options: anything can be written there, `admin` included. + * False without a `roles` field, for a single-valued one, and for a select whose options hold neither value + * (`lead, member`). */ export function canHoldStaffRole(collection: Staffish): boolean { - if (!findRolesField(collection.fields as FieldLike[])) {return false} + if (!rolesAreAList(collection)) {return false} const values = roleValues(collection) return values === null || values.some((value) => value === 'editor' || value === 'admin') } @@ -347,33 +372,67 @@ export function applyFirstUserRoute(config: Config, option: FirstUserRouteOption type LivePayload = { collections: Record; config?: unknown } +type CountingPayload = { + collections: Record + count: (args: { collection: string; overrideAccess: boolean; where?: unknown }) => Promise<{ totalDocs: number }> + find: (args: { collection: string; depth: number; limit: number; overrideAccess: boolean; pagination: boolean }) => Promise<{ docs: unknown[]; hasNextPage?: boolean; totalDocs?: number }> +} +/** How many accounts are read to look for an admin where the database cannot be asked. */ +const ADMIN_SCAN_LIMIT = 1000 + +/** + * Whether a staff collection has an account that is a plugin admin: `true`, `false`, or `null` — could not check. + * Asked the way that is right for the field, never guessed: + * - no `roles` field: every account is an admin → is there an account; + * - a `roles` field that cannot hold a list, or a select whose options do not offer `admin`: none, without a query; + * - a select with `hasMany`: a count in the database; + * - anything else (text, json, a relationship): the accounts are READ and the plugin's own test is applied to the + * value (an array that holds `'admin'`) — a query on such a field answers differently on every database. + */ +async function collectionHasAdmin(payload: CountingPayload, collection: CollectionConfig): Promise { + const field = findRolesField(collection.fields as FieldLike[]) as { type?: string } | undefined + try { + if (!field) {return (await payload.count({ collection: collection.slug, overrideAccess: true })).totalDocs > 0} + if (!rolesAreAList(collection)) {return false} + const values = roleValues(collection) + if (values && !values.includes('admin')) {return false} + if (values) { + try { + return (await payload.count({ collection: collection.slug, overrideAccess: true, where: { roles: { in: ['admin'] } } })).totalDocs > 0 + } catch { + // asked in a way this database does not take: read instead + } + } + const { docs, hasNextPage } = await payload.find({ collection: collection.slug, depth: 0, limit: ADMIN_SCAN_LIMIT, overrideAccess: true, pagination: true }) + if (docs.some((doc) => Array.isArray((doc as { roles?: unknown }).roles) && ((doc as { roles: unknown[] }).roles).includes('admin'))) {return true} + return hasNextPage ? null : false // more accounts than were read: not known + } catch { + return null + } +} + /** * For the start-up line: staff collections that run on the plugin's ADMIN rules (other than `except`, the collection * with the plugin's own roles) while NO account of any staff collection is a plugin admin — then nobody can create, - * delete or unlock accounts there. Returns their slugs; `[]` when an admin exists, when there is no such - * collection, or when the accounts cannot be counted (a `roles` field that cannot be queried). + * delete or unlock accounts there. Counted collection by collection: + * - `stuck`: those collections, when every staff collection could be checked and none has an admin; + * - `unchecked`: staff collections whose accounts could not be checked — then nothing is claimed (`stuck` is empty) + * unless an admin was found elsewhere, in which case both are empty. */ -export async function staffCollectionsNobodyManages( - payload: { collections: Record; count: (args: { collection: string; overrideAccess: boolean; where?: unknown }) => Promise<{ totalDocs: number }> }, - staffSlugs: string[], - except?: string, -): Promise { +export async function staffCollectionsNobodyManages(payload: CountingPayload, staffSlugs: string[], except?: string): Promise<{ stuck: string[]; unchecked: string[] }> { const staff = staffSlugs.map((slug) => payload.collections?.[slug]?.config).filter((c): c is CollectionConfig => Boolean(c?.auth)) const ruled = staff.filter((c) => { const rules = (c.custom as { ipalAccountRules?: StaffAccountRules } | undefined)?.ipalAccountRules - return c.slug !== except && rules && !rules.ownRoles && rules.applied.includes('create') && Boolean(findRolesField(c.fields as FieldLike[])) + return c.slug !== except && rules && !rules.ownRoles && rules.applied.includes('create') && rolesAreAList(c) }) - if (!ruled.length) {return []} - try { - for (const c of staff) { - // without a `roles` field every account of a staff collection is an admin to the plugin - const where = findRolesField(c.fields as FieldLike[]) ? { roles: { in: ['admin'] } } : undefined - if ((await payload.count({ collection: c.slug, overrideAccess: true, where })).totalDocs > 0) {return []} - } - } catch { - return [] // cannot tell: say nothing + if (!ruled.length) {return { stuck: [], unchecked: [] }} + const unchecked: string[] = [] + for (const c of staff) { + const has = await collectionHasAdmin(payload, c) + if (has) {return { stuck: [], unchecked: [] }} + if (has === null) {unchecked.push(c.slug)} } - return ruled.map((c) => c.slug).sort() + return unchecked.length ? { stuck: [], unchecked: unchecked.sort() } : { stuck: ruled.map((c) => c.slug).sort(), unchecked: [] } } /** diff --git a/src/plugin.ts b/src/plugin.ts index b386bf6..ed49d04 100644 --- a/src/plugin.ts +++ b/src/plugin.ts @@ -937,13 +937,18 @@ export const ipalKit = (options: IpalOptions): Plugin => { } // Staff collections on the admin rules while no staff account is an admin: nobody can manage their accounts. if (accounts) { - const stuck = await staffCollectionsNobodyManages(payload as never, staffCollectionSlugs(payload), options.access?.authCollection) + const { stuck, unchecked } = await staffCollectionsNobodyManages(payload as never, staffCollectionSlugs(payload), options.access?.authCollection) if (stuck.length) { payload.logger.warn( `[ipal] No staff account holds the role "admin", so NOBODY can create, delete or unlock accounts in ${stuck.map((s) => `"${s}"`).join(', ')} ` + "(only an admin does there: the collection's roles can hold \"editor\" or \"admin\"). Give one account the role with a script " + '(payload.update, Local API), or write the collection\'s own access.create / update / delete rules (docs/access.md "Account rules").', ) + } else if (unchecked.length) { + payload.logger.warn( + `[ipal] Could not check whether an account of ${unchecked.map((s) => `"${s}"`).join(', ')} holds the role "admin" (no other staff account does). ` + + 'If none does, nobody can create, delete or unlock accounts in the staff collections that are managed by admins only (docs/access.md "Account rules").', + ) } } // The panel role: tell a site how many of its accounts the rule keeps out of the panel. diff --git a/test/accountRulesAdminValueSuite.ts b/test/accountRulesAdminValueSuite.ts index d0a241e..7c025e2 100644 --- a/test/accountRulesAdminValueSuite.ts +++ b/test/accountRulesAdminValueSuite.ts @@ -26,10 +26,6 @@ import { startPayloadServer } from './http/server.js' const PASSWORD = 'a-long-test-password-1' const ROLES: Field = { name: 'roles', type: 'select', hasMany: true, options: ['user', 'editor', 'admin', 'boss'], saveToJWT: true } const TEXT_ROLES: Field = { name: 'roles', type: 'text', hasMany: true } -const late: Plugin = (config: Config) => ({ - ...config, - collections: [...(config.collections ?? []), { slug: 'late-crew', auth: true, fields: [ROLES] }, { slug: 'late-text', auth: true, fields: [TEXT_ROLES] }], -}) /** The shapes: the lowest role of the collection, and the plugin role an account of it must not be able to hand out. */ const SHAPES: { low: string[]; other?: string[]; slug: string; top: 'admin' | 'editor' }[] = [ { slug: 'crew', low: ['user'], other: ['boss'], top: 'admin' }, @@ -38,8 +34,29 @@ const SHAPES: { low: string[]; other?: string[]; slug: string; top: 'admin' | 'e { slug: 'text-roles', low: ['user'], other: ['anything'], top: 'admin' }, { slug: 'late-text', low: ['user'], top: 'admin' }, { slug: 'json-roles', low: ['user'], top: 'admin' }, + // a relationship with hasMany to documents whose ids are text: at depth 0 the account's `roles` is ['admin'] + { slug: 'rel-roles', low: ['user'], other: ['boss'], top: 'admin' }, ] +/** + * Review of branch A (K-1): `roles` fields that hold ONE value. The plugin counts roles only from an array, so + * an account whose `roles` is `'admin'` there is nobody to the plugin: nothing to protect, and the collection's + * accounts keep managing each other exactly as on 1.16.7 (Payload's default for its own accounts). + */ +const SINGLE: { field: Field; low: unknown; slug: string; top: unknown }[] = [ + { slug: 'single', field: { name: 'roles', type: 'select', options: ['user', 'editor', 'admin', 'boss'] }, low: 'user', top: 'admin' }, + { slug: 'single-plugin', field: { name: 'roles', type: 'select', options: ['user', 'editor', 'admin'] }, low: 'user', top: 'admin' }, // all the plugin's values: admin rules on 1.16.7 + { slug: 'single-late', field: { name: 'roles', type: 'select', options: ['user', 'editor', 'admin', 'boss'] }, low: 'user', top: 'admin' }, + { slug: 'radio', field: { name: 'roles', type: 'radio', options: ['user', 'admin'] }, low: 'user', top: 'admin' }, + { slug: 'text-one', field: { name: 'roles', type: 'text' }, low: 'user', top: 'admin' }, + { slug: 'rel-one', field: { name: 'roles', type: 'relationship', relationTo: 'role-names' }, low: 'user', top: 'admin' }, +] + +const late: Plugin = (config: Config) => ({ + ...config, + collections: [...(config.collections ?? []), { slug: 'late-crew', auth: true, fields: [ROLES] }, { slug: 'late-text', auth: true, fields: [TEXT_ROLES] }, { slug: 'single-late', auth: true, fields: [SINGLE.find((x) => x.slug === 'single-late')!.field] }], +}) + /** One Payload instance per test file: run from a file of its own for 2FA off and on. */ export function adminValueSuite(twoFactor: boolean): void { test(`a staff collection whose accounts can hold editor or admin: the admin rules (2FA on: ${twoFactor})`, async () => { @@ -51,6 +68,9 @@ export function adminValueSuite(twoFactor: boolean): void { { slug: 'viewers', auth: true, fields: [{ ...ROLES, options: ['viewer', 'editor'] } as Field] }, { slug: 'text-roles', auth: true, fields: [TEXT_ROLES] }, { slug: 'json-roles', auth: true, fields: [{ name: 'roles', type: 'json' }] }, + { slug: 'role-names', fields: [{ name: 'id', type: 'text' }] }, // role documents with text ids + { slug: 'rel-roles', auth: true, fields: [{ name: 'roles', type: 'relationship', hasMany: true, relationTo: 'role-names' }] }, + ...SINGLE.filter((x) => x.slug !== 'single-late').map((x) => ({ slug: x.slug, auth: true as const, fields: [x.field] })), // its own values with neither `editor` nor `admin`: the plugin cannot tell who its admins are — unchanged { slug: 'team', auth: true, fields: [{ ...ROLES, options: ['lead', 'member'] } as Field] }, { slug: 'customers', access: { create: () => true }, auth: true, fields: [] }, @@ -60,7 +80,7 @@ export function adminValueSuite(twoFactor: boolean): void { editor: lexicalEditor(), plugins: [ ipalKit({ - access: { authCollection: 'users', staffCollections: ['crew', 'agents', 'team', 'late-crew', 'viewers', 'text-roles', 'json-roles', 'late-text'] }, + access: { authCollection: 'users', staffCollections: ['crew', 'agents', 'team', 'late-crew', 'viewers', 'text-roles', 'json-roles', 'late-text', 'rel-roles', ...SINGLE.map((x) => x.slug)] }, i18n: { defaultLocale: 'en', locales: [{ code: 'en', label: 'English' }] }, twoFactor: twoFactor ? { issuer: 'Example', plugin: payloadTotp, verifyLimit: false } : false, }), @@ -74,7 +94,7 @@ export function adminValueSuite(twoFactor: boolean): void { type Session = Record 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 = (collection: string, email: string, roles: string[]) => payload.create({ collection: collection as never, data: { email, password: PASSWORD, roles } as never }) + const make = (collection: string, email: string, roles: unknown) => payload.create({ collection: collection as never, data: { email, password: PASSWORD, roles } as never }) const login = async (collection: string, email: string, password = PASSWORD): Promise => { const body = (await (await call('POST', `/${collection}/login`, {}, { email, password })).json()) as { token?: string } return body.token ? { authorization: `JWT ${body.token}` } : null @@ -82,7 +102,9 @@ export function adminValueSuite(twoFactor: boolean): void { const rolesOf = async (collection: string, id: unknown) => ((await payload.findByID({ id: id as never, collection: collection as never })) as { roles?: string[] }).roles try { const agent = await make('agents', 'one@agents.example.com', ['user']) + await call('POST', '/customers', {}, { email: 'visitor@example.com', password: PASSWORD }) await make('agents', 'admin@agents.example.com', ['admin']) + for (const id of ['user', 'admin', 'boss', 'editor']) {await payload.create({ collection: 'role-names' as never, data: { id } as never })} // IPAL_TEST_SHAPE=: one shape only — for measuring an older tree, where the first open shape stops the run for (const { slug, low, other, top } of SHAPES.filter((shape) => !process.env.IPAL_TEST_SHAPE || shape.slug === process.env.IPAL_TEST_SHAPE)) { // the account the others must not take over: the collection's highest (an admin, or — `viewers` — an editor) @@ -119,7 +141,7 @@ export function adminValueSuite(twoFactor: boolean): void { const me = (await login(slug, `low@${slug}.example.com`))! expect([slug, (await call('PATCH', `/${slug}/${mine.id}`, me, { password: 'my-own-new-password-1' })).status]).toEqual([slug, 200]) // who manages the accounts: an admin of the collection where it has one, and an admin of another staff collection - const managers = [(await login('agents', 'admin@agents.example.com'))!, ...(top === 'admin' ? [(await login(slug, `top@${slug}.example.com`))!] : [])] + const managers = [(await login('agents', 'admin@agents.example.com'))!, ...(top === 'admin' && slug !== 'rel-roles' ? [(await login(slug, `top@${slug}.example.com`))!] : [])] // (over REST a related role arrives as a document, not as 'admin': that account is no admin there) for (const [index, manager] of managers.entries()) { expect([slug, index, (await call('POST', `/${slug}`, manager, { email: `by-manager-${index}@${slug}.example.com`, password: PASSWORD, roles: low })).status, (await call('PATCH', `/${slug}/${mine.id}`, manager, { roles: low })).status]).toEqual([slug, index, 201, 200]) } @@ -129,6 +151,26 @@ export function adminValueSuite(twoFactor: boolean): void { expect([slug, (await call('POST', `/${slug}`, editor, { email: `by-editor@${slug}.example.com`, password: PASSWORD, roles: ['editor'] })).status]).toEqual([slug, 403]) } } + // ── K-1: single-valued `roles` — as on 1.16.7. The value grants nothing, so nothing is closed. ── + for (const { slug, low, top } of SINGLE.filter((shape) => !process.env.IPAL_TEST_SHAPE || shape.slug === process.env.IPAL_TEST_SHAPE)) { + const boss = await make(slug, `top@${slug}.example.com`, top) + const mine = await make(slug, `low@${slug}.example.com`, low) + const victim = await make(slug, `victim@${slug}.example.com`, low) + const me = (await login(slug, `low@${slug}.example.com`))! + const holder = (await login(slug, `top@${slug}.example.com`))! + expect([slug, { + // an account that holds 'admin' in a single-valued field is not a plugin admin: it opens nothing + adminValueReaches: [(await call('GET', '/globals/site-integrations', holder)).status, (await call('PATCH', `/agents/${agent.id}`, holder, { roles: ['admin'] })).status, (await call('GET', '/users', holder)).status], + // the collection's accounts manage each other, the lowest and the one holding 'admin' alike + create: [(await call('POST', `/${slug}`, me, { email: `by-low@${slug}.example.com`, password: PASSWORD, roles: top })).status, (await call('POST', `/${slug}`, holder, { email: `by-top@${slug}.example.com`, password: PASSWORD, roles: low })).status], + patchOther: [(await call('PATCH', `/${slug}/${victim.id}`, me, { password: 'another-long-password-1' })).status, (await call('PATCH', `/${slug}/${victim.id}`, holder, { password: 'another-long-password-2' })).status], + zDelete: (await call('DELETE', `/${slug}/${victim.id}`, holder)).status, + }]).toEqual([slug, { adminValueReaches: [403, 403, 403], create: [201, 201], patchOther: [200, 200], zDelete: 200 }]) + // an account of ANOTHER collection still gets nothing there + const outsider = (await login('customers', 'visitor@example.com'))! + expect([slug, (await call('POST', `/${slug}`, outsider, { email: `by-visitor@${slug}.example.com`, password: PASSWORD, roles: top })).status, (await call('PATCH', `/${slug}/${boss.id}`, outsider, { password: 'taken-over-password-1' })).status, (await call('GET', `/${slug}`, outsider)).status]).toEqual([slug, 403, 403, 403]) + expect(mine.id).toBeDefined() + } // role values with neither `editor` nor `admin`: as before — accounts of the collection manage it, never their own roles await make('team', 'member@team.example.com', ['member']) const member = (await login('team', 'member@team.example.com'))! diff --git a/test/accountRulesNobodyManages.test.ts b/test/accountRulesNobodyManages.test.ts new file mode 100644 index 0000000..85e38a9 --- /dev/null +++ b/test/accountRulesNobodyManages.test.ts @@ -0,0 +1,9 @@ +/** The start-up check for staff collections without an admin, 2FA off — see accountRulesNobodyManagesSuite.ts. */ +import { vi } from 'vitest' + +import { nobodyManagesSuite } from './accountRulesNobodyManagesSuite.js' + +vi.mock('server-only', () => ({})) +vi.mock('next/headers.js', async () => (await import('./http/server.js')).nextHeadersMock) + +nobodyManagesSuite(false) diff --git a/test/accountRulesNobodyManages2fa.test.ts b/test/accountRulesNobodyManages2fa.test.ts new file mode 100644 index 0000000..6bf616a --- /dev/null +++ b/test/accountRulesNobodyManages2fa.test.ts @@ -0,0 +1,9 @@ +/** The start-up check for staff collections without an admin, 2FA ON — see accountRulesNobodyManagesSuite.ts. */ +import { vi } from 'vitest' + +import { nobodyManagesSuite } from './accountRulesNobodyManagesSuite.js' + +vi.mock('server-only', () => ({})) +vi.mock('next/headers.js', async () => (await import('./http/server.js')).nextHeadersMock) + +nobodyManagesSuite(true) diff --git a/test/accountRulesNobodyManagesSuite.ts b/test/accountRulesNobodyManagesSuite.ts new file mode 100644 index 0000000..8a619f5 --- /dev/null +++ b/test/accountRulesNobodyManagesSuite.ts @@ -0,0 +1,96 @@ +/** + * The start-up warning "no staff account holds admin" against a RUNNING Payload (review of branch A, K-2): + * `staffCollectionsNobodyManages` for each shape of `roles` field, in three states — the collection empty, with a + * lowest account, with its top account — and what it must say. It was silent or wrong where a query answers + * differently per database (a value outside a Postgres enum, json on SQL, a relationship). Now each collection is + * checked in the way that is right for its field. SQLite, Postgres, MongoDB. + */ +import type { CollectionConfig, Field, 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 { staffCollectionsNobodyManages } from '../src/modules/access/selfRegistration.js' +import { ipalKit } from '../src/plugin.js' +import { buildTestConfig } from './helpers.js' +import { testDatabase } from './http/db.js' + +const PASSWORD = 'a-long-test-password-1' +const select = (options: string[], hasMany = true): Field => ({ name: 'roles', type: 'select', hasMany, options }) as Field +/** `adminTop`: its top account IS a plugin admin; `ruled`: the collection runs on the admin rules. */ +const SHAPES: { adminTop: boolean; fields: Field[]; low: unknown; ruled: boolean; slug: string; top: unknown }[] = [ + { slug: 'crew', adminTop: true, fields: [select(['user', 'editor', 'admin', 'boss'])], low: ['user'], ruled: true, top: ['admin'] }, + { slug: 'in-tabs', adminTop: true, fields: [{ type: 'tabs', tabs: [{ fields: [select(['user', 'editor', 'admin'])], label: 'Account' }] }], low: ['user'], ruled: true, top: ['admin'] }, + { slug: 'text-many', adminTop: true, fields: [{ name: 'roles', type: 'text', hasMany: true }], low: ['user'], ruled: true, top: ['admin'] }, + // no `admin` among the values: nobody in it can be one — the editor is not + { slug: 'viewers', adminTop: false, fields: [select(['viewer', 'editor'])], low: ['viewer'], ruled: true, top: ['editor'] }, + { slug: 'json-roles', adminTop: true, fields: [{ name: 'roles', type: 'json' }], low: ['user'], ruled: true, top: ['admin'] }, + { slug: 'rel-roles', adminTop: true, fields: [{ name: 'roles', type: 'relationship', hasMany: true, relationTo: 'role-names' }], low: ['user'], ruled: true, top: ['admin'] }, + // single-valued: the value never counts, the collection is not on the admin rules, its 'admin' is not an admin + { slug: 'single', adminTop: false, fields: [select(['user', 'editor', 'admin'], false)], low: 'user', ruled: false, top: 'admin' }, + // roles of its own, and a collection with rules of its own: not on the admin rules + { slug: 'team', adminTop: false, fields: [select(['lead', 'member'])], low: ['member'], ruled: false, top: ['lead'] }, +] + +/** One Payload instance per test file: run from a file of its own for 2FA off and on. */ +export function nobodyManagesSuite(twoFactor: boolean): void { + test(`the start-up check says who has no admin — per collection, on this database (2FA on: ${twoFactor})`, async () => { + const config = buildTestConfig({ + admin: { user: 'users' }, + collections: [ + ...SHAPES.map(({ slug, fields }): CollectionConfig => ({ slug, auth: true, fields })), + { slug: 'own-rules', access: { create: () => false, delete: () => false, update: () => false }, auth: true, fields: [select(['user', 'editor', 'admin', 'boss'])] }, + { slug: 'role-names', fields: [{ name: 'id', type: 'text' }] }, + { slug: 'media', fields: [], upload: { staticDir: path.join(os.tmpdir(), 'ipal-test-media') } }, + ], + db: testDatabase(twoFactor ? 'nobody_2fa' : 'nobody'), + editor: lexicalEditor(), + plugins: [ + ipalKit({ + access: { authCollection: 'users', staffCollections: [...SHAPES.map((shape) => shape.slug), 'own-rules'] }, + 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 ask = (staff: string[]) => staffCollectionsNobodyManages(payload as never, staff, 'users') + const make = (collection: string, email: string, roles?: unknown) => payload.create({ collection: collection as never, data: { email, password: PASSWORD, ...(roles === undefined ? {} : { roles }) } as never }) + try { + for (const id of ['user', 'admin', 'editor']) {await payload.create({ collection: 'role-names' as never, data: { id } as never })} + const said: Record = {} + const should: Record = {} + for (const { slug, adminTop, low, ruled, top } of SHAPES) { + const nobody = { stuck: ruled ? [slug] : [], unchecked: [] } + const states: unknown[] = [await ask(['users', slug])] // empty + await make(slug, `low@${slug}.example.com`, low) + states.push(await ask(['users', slug])) // a lowest account + await make(slug, `top@${slug}.example.com`, top) + states.push(await ask(['users', slug])) // its top account + said[slug] = states + // with the top account: silent where that account is a plugin admin; still "nobody" where it is not + should[slug] = [nobody, nobody, adminTop ? { stuck: [], unchecked: [] } : nobody] + } + expect(said).toEqual(should) + // several collections in one start: each is checked on its own — one that the database cannot be asked about + // does not silence the others, and an admin anywhere answers for all + await payload.delete({ collection: 'crew' as never, where: { email: { equals: 'top@crew.example.com' } } }) + for (const slug of ['in-tabs', 'text-many', 'json-roles', 'rel-roles']) {await payload.delete({ collection: slug as never, where: { email: { equals: `top@${slug}.example.com` } } })} + const all = ['users', ...SHAPES.map((shape) => shape.slug), 'own-rules'] + expect(await ask(all)).toEqual({ stuck: SHAPES.filter((shape) => shape.ruled).map((shape) => shape.slug).sort(), unchecked: [] }) + // a collection with rules of its own is not on the admin rules: it is never named + expect((await ask(['users', 'own-rules'])).stuck).toEqual([]) + // an admin of the panel's collection: silent everywhere + await make('users', 'admin@example.com', ['admin']) + expect(await ask(all)).toEqual({ stuck: [], unchecked: [] }) + } finally { + await payload.destroy?.() + } + }, 120_000) +} diff --git a/test/accountRulesSingleLogin.test.ts b/test/accountRulesSingleLogin.test.ts new file mode 100644 index 0000000..7066fcf --- /dev/null +++ b/test/accountRulesSingleLogin.test.ts @@ -0,0 +1,9 @@ +/** A login collection with a single-valued role select, 2FA off — see accountRulesSingleLoginSuite.ts. */ +import { vi } from 'vitest' + +import { singleLoginSuite } from './accountRulesSingleLoginSuite.js' + +vi.mock('server-only', () => ({})) +vi.mock('next/headers.js', async () => (await import('./http/server.js')).nextHeadersMock) + +singleLoginSuite(false) diff --git a/test/accountRulesSingleLogin2fa.test.ts b/test/accountRulesSingleLogin2fa.test.ts new file mode 100644 index 0000000..231659b --- /dev/null +++ b/test/accountRulesSingleLogin2fa.test.ts @@ -0,0 +1,9 @@ +/** A login collection with a single-valued role select, 2FA ON — see accountRulesSingleLoginSuite.ts. */ +import { vi } from 'vitest' + +import { singleLoginSuite } from './accountRulesSingleLoginSuite.js' + +vi.mock('server-only', () => ({})) +vi.mock('next/headers.js', async () => (await import('./http/server.js')).nextHeadersMock) + +singleLoginSuite(true) diff --git a/test/accountRulesSingleLoginSuite.ts b/test/accountRulesSingleLoginSuite.ts new file mode 100644 index 0000000..bbcbd05 --- /dev/null +++ b/test/accountRulesSingleLoginSuite.ts @@ -0,0 +1,89 @@ +/** + * 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 { ipalKit } 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: [ipalKit({ 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 + 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 => { + 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('victim@example.com', 'user') + await make('low@example.com', 'user') + await make('boss@example.com', 'boss') + await make('admin@example.com', 'admin') + const got: Record = {} + 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: 'victim@example.com' })).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', 'admin@example.com'))).status).toBe(200) + // what is still closed: an account of another collection, and nobody + expect((await call('POST', '/customers', {}, { email: 'visitor@example.com', password: PASSWORD })).status).toBe(201) + const visitor = await login('customers', 'visitor@example.com') + 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) +} diff --git a/test/accountRulesSuite.ts b/test/accountRulesSuite.ts index 5812f08..322b16b 100644 --- a/test/accountRulesSuite.ts +++ b/test/accountRulesSuite.ts @@ -19,7 +19,7 @@ import type { I18nConfig } from '../src/modules/i18n/types.js' import { countBelowPanelRole, panelAccess, resolvePanelRole } from '../src/modules/access/panelRole.js' import { checkPassword, resolvePasswordRule } from '../src/modules/access/passwordRule.js' -import { adoptLateAuthCollections, bothAllow, canHoldStaffRole, hasPluginRoles, openSignUpCollections, rolesByAdminOnly, rolesNotOwn, sameStaffCollectionAccess, staffCollectionsNobodyManages, staffCollectionsOnOwnRoles, staffCollectionsOpenToOthers, staffCreateAccess, staffReadAccess, staffUpdateAccess, unknownStaffCollections } from '../src/modules/access/selfRegistration.js' +import { adoptLateAuthCollections, bothAllow, canHoldStaffRole, hasPluginRoles, openSignUpCollections, rolesAreAList, rolesByAdminOnly, rolesNotOwn, sameStaffCollectionAccess, staffCollectionsNobodyManages, staffCollectionsOnOwnRoles, staffCollectionsOpenToOthers, staffCreateAccess, staffReadAccess, staffUpdateAccess, unknownStaffCollections } from '../src/modules/access/selfRegistration.js' import { ipalKit } from '../src/plugin.js' import { buildTestConfig, withTotpParts } from './helpers.js' import { testDatabase } from './http/db.js' @@ -574,10 +574,19 @@ export function accountRulesSuite(twoFactor: boolean): void { 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 - expect(canHoldStaffRole({ slug: 'x', fields: [{ name: 'roles', type: 'text' }] } as never)).toBe(true) - expect(canHoldStaffRole({ slug: 'x', fields: [{ name: 'roles', type: 'json' }] } as never)).toBe(true) + const field = (f: Record) => ({ 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' }] }] } as never)).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) @@ -668,7 +677,7 @@ export function accountRulesSuite(twoFactor: boolean): void { const narrow = () => false const where = () => ({ team: { equals: 'a' } }) const hook = () => undefined - 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: {}, options: ['user', 'admin'] }] } + 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: 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: [] } @@ -745,28 +754,50 @@ export function accountRulesSuite(twoFactor: boolean): void { }) test('staffCollectionsNobodyManages: the admin rules without any admin — for the start-up warning', async () => { - const roles = (options: string[]) => [{ name: 'roles', type: 'select', options }] + 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 withAdmins = (admins: Record, fail = false) => ({ + const asked: string[] = [] + const site = ({ admins = {}, docs = {}, failCount = [], failFind = [], many = [] }: { admins?: Record; docs?: Record; failCount?: string[]; failFind?: string[]; many?: string[] }) => ({ collections, count: async ({ collection }: { collection: string }) => { - if (fail) {throw new Error('cannot query')} + 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[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 staffCollectionsNobodyManages(withAdmins({}) as never, ['users', 'crew', 'team'], 'users')).toEqual(['crew']) + expect(await ask({}, ['users', 'crew', 'team'])).toEqual({ stuck: ['crew'], unchecked: [] }) // an admin in the collection, or in another staff collection, manages it - expect(await staffCollectionsNobodyManages(withAdmins({ crew: 1 }) as never, ['users', 'crew', 'team'], 'users')).toEqual([]) - expect(await staffCollectionsNobodyManages(withAdmins({ users: 2 }) as never, ['users', 'crew', 'team'], 'users')).toEqual([]) - // nothing on the admin rules; or the accounts cannot be counted: nothing is said - expect(await staffCollectionsNobodyManages(withAdmins({}) as never, ['users', 'team'], 'users')).toEqual([]) - expect(await staffCollectionsNobodyManages(withAdmins({}, true) as never, ['users', 'crew'], 'users')).toEqual([]) + 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 () => { From 4c7b722aed8dda15adebb933c2c5373308021e47 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rados=C5=82aw=20Smoli=C5=84ski?= Date: Wed, 25 Nov 2026 03:44:25 +0100 Subject: [PATCH 7/7] =?UTF-8?q?K-3:=20docs=20=E2=80=94=20fields=20that=20h?= =?UTF-8?q?old=20a=20list,=20a=20relationship=20counts,=20a=20rule=20of=20?= =?UTF-8?q?your=20own=20replaces=20the=20protection,=20known=20limitations?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Fable 5.2 --- docs/CHANGELOG.md | 38 +++++++++++++++---- docs/access.md | 27 +++++++++---- docs/agent/AGENT.md | 2 +- docs/agent/skills/ipal-debug/SKILL.md | 3 +- .../skills/ipal-reference/resources/api.md | 4 +- docs/agent/skills/ipal-upgrade/SKILL.md | 3 +- reference/.agents/skills/ipal-debug/SKILL.md | 3 +- .../skills/ipal-reference/resources/api.md | 4 +- .../.agents/skills/ipal-upgrade/SKILL.md | 3 +- 9 files changed, 62 insertions(+), 25 deletions(-) diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md index 0ebc86e..533e103 100644 --- a/docs/CHANGELOG.md +++ b/docs/CHANGELOG.md @@ -13,7 +13,8 @@ once there are more than 20. > **Read before upgrading.** No option, schema, migration or import-map change. Two points: > **What can stop people:** on a project's own staff collection **without access rules of its own** whose > accounts can hold `editor` or `admin` although its roles are not just the plugin's — a `roles` select such as -> `user, editor, admin, boss` or `viewer, editor`, or a `roles` field that is text or json — an account that is +> `user, editor, admin, boss` or `viewer, editor`, or a `roles` field that is text, json or a relationship (all +> with `hasMany`, i.e. holding a list; a single-valued field is not affected) — an account that is > not an admin can no longer create, delete or unlock accounts there, change another account, or change > anybody's roles. If **no** staff account holds `admin`, nobody can (the start log says so; the way out is > below). And a site **built with Turbopack** (`next build` without `--webpack`): see Security. @@ -26,7 +27,8 @@ once there are more than 20. collection" could create, change and delete accounts. So with roles `user, editor, admin, boss` an account with the role `user` created an `admin` there (or set the admin's password) and then read Site integrations, changed other staff collections' roles and listed the panel's accounts; with `viewer, editor` a `viewer` made - an `editor` who saves Site settings; the same with a `roles` field that is text or json. In 1.16.7 and, wider, + an `editor` who saves Site settings; the same with a `roles` field that is text or a relationship with + `hasMany`, or json (a relationship to documents with text ids holds those ids). In 1.16.7 and, wider, before it. Now such a collection — in the config or added by a later plugin — gets: create, delete, unlock — an admin; update — an admin or the account itself; roles — only an admin. Not affected: `access.authCollection`, collections with rules of their own, a `roles` select whose values hold neither `editor` nor `admin`. No known @@ -42,16 +44,18 @@ once there are more than 20. disk at run time. ### Added -- A start-log warning when staff collections run on the admin rules and no staff account holds `admin`. +- A start-log warning when staff collections run on the admin rules and no staff account holds `admin` + (checked collection by collection; "could not check" where it cannot tell). - `pnpm e2e:built` (plugin repository): builds the reference site with webpack and with Turbopack and checks, on each, the account rules on a built site and that no package manifest is among the public files. Part of the release gate (PROGRAMISTA §8.1). The reference site's Playwright runs reset the test admins first (`e2e/global-setup.ts`), so a spec no longer fails because of what ran before it. -- Exports: `canHoldStaffRole`, `staffCollectionsNobodyManages`. +- Exports: `canHoldStaffRole`, `rolesAreAList`, `staffCollectionsNobodyManages`. ### Requires project changes - **A staff collection of your own, without access rules, whose accounts can hold `editor` or `admin`** (a - `roles` select with one of them next to values of your own, or a text / json `roles` field): only an admin + `roles` select with `hasMany` and one of them next to values of your own, or a `roles` field that is text or a + relationship with `hasMany`, or json): only an admin creates, deletes and unlocks accounts there and changes roles; another account is changed by an admin or by itself. If accounts with a role of your own (`boss`, `viewer`) managed accounts there, write that as the collection's own rules (`access.create` / `update` / `delete`, field access on `roles`) — the plugin gives @@ -67,13 +71,31 @@ once there are more than 20. webpack build. - `pnpm ipal:skills`. +### Changed +- **A single-valued `roles` field no longer brings the admin rules.** The plugin counts roles only from an array, + so an account whose `roles` is one value (`'admin'` in a select without `hasMany`, a radio) was never a plugin + admin. Yet in 1.16.7 a project's own staff collection whose single select offered only `user` / `editor` / + `admin` got the admin rules — and then nobody in it could create, delete or unlock accounts, unless a plugin + admin existed in another staff collection. Such a collection now gets "an account of this collection", like any + collection whose roles are not the plugin's: its accounts manage each other again. Nothing of the plugin's opens: + the value still grants nothing. + ### Known limitations +- **Copied staff collections behave as in 1.16.7**: a plugin listed after ipalKit that spreads a staff collection + into a new slug (`{ ...staff, slug: 'copy' }`) keeps the rules written for the original, so with numeric ids + (Postgres, SQLite) the original's account with the same id can change the copy's account. Not changed in this + release; no known site copies a staff collection. - A staff collection **without a `roles` field** is unchanged: every account of it is an admin to the plugin. - A `roles` select of your own whose values hold neither `editor` nor `admin` is unchanged: inside it every account may create, change and delete accounts (`ipal-doctor --url` → `staff-own-roles`). -- The warning counts accounts whose `roles` hold `admin`; where a `roles` field cannot be queried it says nothing. -- **Not run for this change:** the starter built with Turbopack (it is generated from the reference site and uses - the same plugin code; the reference site was built with both bundlers). +- The plugin judges a collection by its declared `roles` field. A value that a hook of the project's own puts + into `roles` is not seen, and a rule of the project's own (`access.create`, field access on `roles`) replaces + the protection for that operation. +- A relationship `roles` field makes a plugin admin only where the related documents' ids are the role names; over + REST such an account's roles arrive as documents and do not count, over GraphQL and the Local API at depth 0 + they do. The admin rules apply to the collection either way. +- The start-log check reads up to 1000 accounts of a collection whose `roles` field the database cannot be asked + about; with more it says "could not check" for that collection. ## 1.16.7 — hardening diff --git a/docs/access.md b/docs/access.md index 8d731fa..d666d25 100644 --- a/docs/access.md +++ b/docs/access.md @@ -290,21 +290,22 @@ list the staff accounts, and lift the lock after failed logins. | The collection | `create`, `delete`, `unlock` | `update` | the `roles` field (when it has no `access.update`) | `read`, `readVersions` | |---|---|---|---|---| -| carries **the plugin's roles**: it is `access.authCollection`, or has a `roles` select whose values are all `user` / `editor` / `admin` (`hasPluginRoles`), **or one whose accounts can hold `editor` or `admin`**, whatever else its `roles` field offers (`canHoldStaffRole`, below) | an admin (`staffCreateAccess`) | an admin, or the account itself (`staffUpdateAccess(slug)`) | only an admin changes it (`rolesByAdminOnly`) | a staff account (`staffReadAccess`) | +| carries **the plugin's roles**: it is `access.authCollection`, or has a `roles` select **with `hasMany`** whose values are all `user` / `editor` / `admin` (`hasPluginRoles`), **or one whose accounts can hold `editor` or `admin`**, whatever else its `roles` field offers (`canHoldStaffRole`, below) | an admin (`staffCreateAccess`) | an admin, or the account itself (`staffUpdateAccess(slug)`) | only an admin changes it (`rolesByAdminOnly`) | a staff account (`staffReadAccess`) | | has **roles of its own that hold neither `editor` nor `admin`** (`superadmin`, `writer`, …) or no `roles` field — the plugin cannot tell who its admins are | an account of that same collection, or a plugin admin of another staff collection (`sameStaffCollectionAccess(slug)`) | the same | an account never changes its **own** (`rolesNotOwn(slug)`) | a staff account | Always "fully signed in": a session that still owes its second factor passes none of them. **A `roles` field that can hold `editor` or `admin`.** The plugin's checks go by the **value on the account** -(`isAdmin`, `isEditor`): an account of a staff collection whose `roles` hold `admin` is a plugin admin, one that -holds `editor` edits the site's settings — whatever else the field offers. So wherever an account of the -collection **can** hold one of the two, the collection gets the admin rules (`canHoldStaffRole`): +(`isAdmin`, `isEditor`): an account of a staff collection whose `roles` — an **array** — holds `admin` is a plugin +admin, one that holds `editor` edits the site's settings, whatever else the field offers. So wherever an account +of the collection **can** hold one of the two, the collection gets the admin rules (`canHoldStaffRole`): | The collection's `roles` field | Rules | |---|---| -| a select with `editor` or `admin` among its values — `user, editor, admin, boss`; `viewer, editor` | the admin rules (first row above) | -| a field whose values cannot be listed — text, json, a select without options: anything can be written there | the admin rules | -| a select whose values are all your own and hold neither — `lead, member` | "an account of that same collection" (second row) | +| a select **with `hasMany`** and `editor` or `admin` among its values — `user, editor, admin, boss`; `viewer, editor` | the admin rules (first row above) | +| a field that holds a list whose values cannot be listed — text with `hasMany`, json, a relationship with `hasMany` (to documents whose ids are text, the ids are the roles), a select without options, a type the plugin does not know: anything can be written there | the admin rules | +| a select with `hasMany` whose values are all your own and hold neither — `lead, member` | "an account of that same collection" (second row) | +| a field that holds **one** value — a select, text or relationship without `hasMany`, a radio, a number (`rolesAreAList` is false) | second row. The plugin counts roles only from an array: an account whose `roles` is the single value `admin` is **not** a plugin admin, so there is nothing of the plugin's to protect and the collection's accounts keep managing each other | | no `roles` field | second row; every account of it is an admin to the plugin (below) | Otherwise any account of such a collection could hand the value out: create an `admin` and be in Site @@ -315,10 +316,20 @@ plugin's — such an account no longer creates, deletes or unlocks accounts ther anybody's roles. Give it what it needs with rules of your own (`access.create` / `update` / `delete`, field access on `roles`), which win as always. In a collection where nobody can be an `admin` (`viewer, editor`) the accounts are managed by an admin of another staff collection — the panel's. + +**A rule of your own replaces the protection for that operation.** The plugin fills only what you left open: with +your own `create: ({ req }) => Boolean(req.user)` any account still creates an `admin` there; with your own +`access.update: () => true` on the `roles` field an account still raises itself. And the plugin sees the field's +declared values, not your code: a value that a hook of yours puts into `roles` (an `afterRead` that returns +`['admin']` from a checkbox, a virtual field) is not seen — such a collection is judged by its declared field. + **If no staff account holds `admin` at all**, nobody can create, delete or unlock accounts in such a collection. The start log says so: `[ipal] No staff account holds the role "admin", so NOBODY can create, delete or unlock accounts in "…"`. Way out: give one account the role with a script (`payload.update`, Local API), or write the -collection's own rules. +collection's own rules. The check asks each staff collection in the way its field allows (a count for a select, +reading the accounts for text / json / relationship fields, up to 1000 of them); where it cannot check a +collection it says `[ipal] Could not check whether an account of "…" holds the role "admin"` instead and claims +nothing. **Roles of your own — what the plugin does and does not hold.** It cannot rank `superadmin` against `writer`, so inside such a collection it enforces one thing only: an account does not change its own roles. Everything diff --git a/docs/agent/AGENT.md b/docs/agent/AGENT.md index 49f0e11..437d281 100644 --- a/docs/agent/AGENT.md +++ b/docs/agent/AGENT.md @@ -1172,7 +1172,7 @@ add missing hosts with flags / `extra`; (3) change `mode` to `'enforce'` in both | Stored secrets are write-only: `smtpPassword` and `turnstileSecretKey` come back as `'********'` over REST, GraphQL and in the panel; an empty save keeps the value, `'[[clear]]'` removes it; server code reads the real value with the Local API. **The panel is the source — never add an env variable for them** (`TURNSTILE_SECRET_KEY` is deprecated) | `secrets: { writeOnly: false }` | `writeOnlySecret(field)` / `writeOnlySecrets(fields, names)` for your own secret fields; with versions on the entity add `hooks.afterRead: [maskSecretsOnRestore]` | | The SMTP password stays with its server: a save in the panel or over the API that changes the server, port or user name without the password is refused (`400` "Enter the password again…"), whatever the transport says — otherwise an admin session points the server at its own machine and a test e-mail hands the password over. A change of the transport alone asks for nothing. Seeds and scripts (Local API, access control off) are not asked | `secrets: { reenterOnChange: false }` | `writeOnlySecret(field, { boundTo: [...] })`, `buildKeepSecret`, `SMTP_PASSWORD_BOUND_TO` | | The admin panel opens for `editor` and above; an account with only `user` sees "Unauthorized" (the API is not touched). First start logs how many accounts are below the role | `accounts: { panelRole: 'user' }` (or `false`) | `panelRole: 'admin'`; your own `access.admin`; `panelAccess(role)` | -| Nobody creates an account for themselves, or takes one over. A staff collection (also the project's own, also one a later plugin adds) without a `create` / `update` / `delete` / `unlock` / `read` / `readVersions` rule gets one (on a collection a later plugin adds the plugin's rule is put in front of its own and both must allow; `custom: { ipal: { accountRules: false } }` on it keeps its own): with the plugin's roles, or wherever an account of it can hold `editor` or `admin` (`user, editor, admin, boss`; `viewer, editor`; a `roles` field that is text or json — the value on the account makes a plugin admin or editor) — create, delete, unlock: an admin; update: an admin or the account itself; the `roles` field: only an admin. With roles of its own that hold neither `editor` nor `admin`, or none: an account of that same collection, or a plugin admin, and an account never changes its own roles — **the plugin cannot rank a project's own roles: write that collection's rules** (`ipal-doctor` → `staff-own-roles`). `read`: a staff account. Payload's first-user route answers only for the panel's login collection (the first account, which becomes admin), in any spelling of the URL. `access.firstUserAdmin: false` with a default role below the panel role: the default panel role is not applied (logged), an explicit one is refused at start. With a slug in `access.staffCollections` that is not an auth collection Payload does not start (`/api/health` 503) | `accounts: { adminOnlyCreate: false, adminOnlyWrite: false, staffOnlyRead: false, firstUserRoute: 'all' }` | your own rule wins; `firstUserRoute: ['users', 'partners']`; a collection with open sign-up keeps its routes; `staffCreateAccess`, `staffUpdateAccess(slug)`, `staffReadAccess`, `sameStaffCollectionAccess(slug)`, `rolesByAdminOnly`, `rolesNotOwn(slug)`, `hasPluginRoles`, `applyStaffAccountAccess`, `adoptLateAuthCollections`, `buildFirstUserEndpoint` | +| Nobody creates an account for themselves, or takes one over. A staff collection (also the project's own, also one a later plugin adds) without a `create` / `update` / `delete` / `unlock` / `read` / `readVersions` rule gets one (on a collection a later plugin adds the plugin's rule is put in front of its own and both must allow; `custom: { ipal: { accountRules: false } }` on it keeps its own): with the plugin's roles, or wherever an account of it can hold `editor` or `admin` (`user, editor, admin, boss`; `viewer, editor`; a `roles` field that is text, json or a relationship holding a list — the value in the account's `roles` array makes a plugin admin or editor; a single-valued `roles` field is not affected: its value never counts) — create, delete, unlock: an admin; update: an admin or the account itself; the `roles` field: only an admin. With roles of its own that hold neither `editor` nor `admin`, or none: an account of that same collection, or a plugin admin, and an account never changes its own roles — **the plugin cannot rank a project's own roles: write that collection's rules** (`ipal-doctor` → `staff-own-roles`). `read`: a staff account. Payload's first-user route answers only for the panel's login collection (the first account, which becomes admin), in any spelling of the URL. `access.firstUserAdmin: false` with a default role below the panel role: the default panel role is not applied (logged), an explicit one is refused at start. With a slug in `access.staffCollections` that is not an auth collection Payload does not start (`/api/health` 503) | `accounts: { adminOnlyCreate: false, adminOnlyWrite: false, staffOnlyRead: false, firstUserRoute: 'all' }` | your own rule wins; `firstUserRoute: ['users', 'partners']`; a collection with open sign-up keeps its routes; `staffCreateAccess`, `staffUpdateAccess(slug)`, `staffReadAccess`, `sameStaffCollectionAccess(slug)`, `rolesByAdminOnly`, `rolesNotOwn(slug)`, `hasPluginRoles`, `applyStaffAccountAccess`, `adoptLateAuthCollections`, `buildFirstUserEndpoint` | | A password set on a staff account has at least 12 characters and is not the e-mail address; existing passwords are not checked | `accounts: { password: false }` | `password: { minLength }`; `checkPassword`, `buildPasswordRuleHook` | | While Turnstile cannot check (wrong secret, Cloudflare down): a text form is accepted, a form with files is refused | `forms: { turnstileOnConfigError: 'allow' }` | `'reject'`, `{ text, files }`; `turnstileOnConfigError` at a call site wins | | Dashboard alerts by role: integration details for admins, a neutral line for editors, nothing for others; cookie alerts for editors and above. `'all'` checks nothing — no role, no second factor | `dashboardAlerts: { integrations: 'all', cookies: 'all' }` | `integrations: 'editor'`; the components' `details` / `audience` props | diff --git a/docs/agent/skills/ipal-debug/SKILL.md b/docs/agent/skills/ipal-debug/SKILL.md index 3b68f31..c0268f2 100644 --- a/docs/agent/skills/ipal-debug/SKILL.md +++ b/docs/agent/skills/ipal-debug/SKILL.md @@ -104,7 +104,8 @@ through this procedure. Ask only when you are missing something you cannot get y | `POST /api//first-register` answers `403` on an empty collection | `accounts.firstUserRoute`: only the panel's login collection may register its first account that way (the plugin's own endpoint sits in front of Payload's) | an admin creates the account; or the collection's own `create: () => true` (sign-up); or `accounts: { firstUserRoute: [''] }` | | an editor (or a script with its token) gets `403` creating an account in the project's own `users` | `accounts.adminOnlyCreate`: only admins create staff accounts where the roles are the plugin's | create as an admin; or write the collection's `create` rule; or `adminOnlyCreate: false` | | log at start: `[ipal] No staff account holds the role "admin", so NOBODY can create, delete or unlock accounts in "…"` | a staff collection whose accounts can hold `editor` or `admin` runs on the admin rules, and no staff account is an admin | give one account `admin` with a script (`payload.update`, Local API); or write the collection's own `access.create` / `update` / `delete` | -| an account with a role of the project's own (`boss`, `viewer`) gets `403` creating or editing accounts in its staff collection (it worked on 1.16.7) | the collection's `roles` can hold `editor` or `admin` (a select with one of them, or a text / json field): the admin rules apply | do it as an admin; or write the collection's own rules for that role | +| an account with a role of the project's own (`boss`, `viewer`) gets `403` creating or editing accounts in its staff collection (it worked on 1.16.7) | the collection's `roles` can hold `editor` or `admin` (a select with `hasMany` and one of them, or a text / relationship field with `hasMany`, or json; a single-valued field is not affected): the admin rules apply | do it as an admin; or write the collection's own rules for that role | +| log at start: `[ipal] Could not check whether an account of "…" holds the role "admin"` | the accounts of that staff collection could not be read or are more than 1000, and no other staff account is an admin | make sure one account holds `admin`; nothing is wrong if one does | | an account gets `403` changing or deleting ANOTHER account of a staff collection (it worked before) | `accounts.adminOnlyWrite`: an admin, or the account itself (update only); on a collection with roles of its own: accounts of that collection | do it as an admin; or write the collection's `update` / `delete` rule; or `adminOnlyWrite: false` | | an account saves its own profile and its `roles` do not change (no error) | `accounts.adminOnlyWrite`: nobody changes its own roles; with the plugin's roles only an admin changes roles | an admin changes the role; or give the `roles` field its own `access.update` | | a logged-in visitor (customer) gets `403` reading a staff collection — an author box went empty | `accounts.staffOnlyRead`: only staff accounts read a staff collection without a `read` rule | write that collection's `read` rule; or `staffOnlyRead: false` | diff --git a/docs/agent/skills/ipal-reference/resources/api.md b/docs/agent/skills/ipal-reference/resources/api.md index dccc47d..ada3950 100644 --- a/docs/agent/skills/ipal-reference/resources/api.md +++ b/docs/agent/skills/ipal-reference/resources/api.md @@ -67,8 +67,8 @@ Admin panel components from `@intecion/ipal-kit/admin` — the project does NOT | `isAdmin(user, source?)` | `@intecion/ipal-kit`; in client components `@intecion/ipal-kit/client` | Predicate → `boolean`: staff account with the `admin` role (see `hasMinimumRole`). In hooks and endpoints: `isAdmin(req.user, req.payload)`; in a client component: `isAdmin(user, config)` from `/client` — the main entry does not build there with webpack (`'server-only' cannot be imported…`). | | `isEditor(user, source?)` | `@intecion/ipal-kit`; in client components `@intecion/ipal-kit/client` | Predicate → `boolean`: staff account with `editor` or higher. | | `panelAccess(minimum?)`, `applyPanelRole(config, slug, role)`, `resolvePanelRole(option)`, `countBelowPanelRole(payload, slug, role)`, `DEFAULT_PANEL_ROLE` | `@intecion/ipal-kit` | `accounts.panelRole`: an `access.admin` function ("holds at least `minimum`", default `'editor'`; role only, not the second factor); the applier (skips a collection that has its own `access.admin`); the option → role or `null` when off; `{ all, below }` counts for the start-up line; `'editor'`. | -| `staffCreateAccess`, `staffUpdateAccess(slug)`, `staffReadAccess`, `sameStaffCollectionAccess(slug)`, `rolesByAdminOnly`, `rolesNotOwn(slug)`, `hasPluginRoles(collection)`, `canHoldStaffRole(collection)`, `applyStaffAccountAccess(config, staffSlugs, { create?, write?, read?, pluginRoles? })` | `@intecion/ipal-kit` | `accounts.adminOnlyCreate` / `adminOnlyWrite` / `staffOnlyRead`: the access functions — "an admin, fully signed in" (create, delete, unlock); "an admin, or the account itself" (update; self = an account of THAT collection); "a fully signed-in account of a staff collection" (read); "an account of this staff collection, or a plugin admin of another" (a collection whose roles are not the plugin's); the two field-access functions for a `roles` field (`update`: only an admin / never the account itself); whether a collection carries the plugin's roles (a `roles` select at the top level of the data with only `user` / `editor` / `admin`); whether an account of it can hold `editor` or `admin` whatever else the field offers (a select with one of them among its values, or a `roles` field whose values cannot be listed — text, json) — then the admin rules apply too; the applier — puts the rules on the named staff collections for the operations that have none and closes the `roles` field where the plugin's `update` rule is in force, `pluginRoles` = slugs whose roles field is injected later. Run it before any plugin that wraps access (the 2FA package). | -| `buildFirstUserEndpoint(option?)`, `applyFirstUserRoute(config, option?)`, `adoptLateAuthCollections(config, staffSlugs, { access?, beforeOperation?, firstUserRoute? })`, `bothAllow(first, second)`, `unknownStaffCollections(config, staffSlugs)`, `openSignUpCollections(payload)`, `staffCollectionsOpenToOthers(payload)`, `staffCollectionsOnOwnRoles(payload)`, `staffCollectionsNobodyManages(payload, staffSlugs, except?)` | `@intecion/ipal-kit` | `accounts.firstUserRoute`: the plugin's own `POST /first-register` collection endpoint, matched before Payload's — `403` unless the collection is the panel's login collection (`'panel'`), is in the list, or its own `create` lets an anonymous request through; otherwise it calls Payload's handler (and sets `req.context.ipalFirstRegister`); the applier (every auth collection; `'all'` adds nothing; `endpoints: false` is left alone). For the doctor: slugs of auth collections with open sign-up; `':'` for every staff collection an account of a non-staff collection may create in, read, update, delete from or unlock; slugs of staff collections with role values of their own on the default rules. `adoptLateAuthCollections` takes the LIVE config (`payload.config`) and gives auth collections that a plugin listed after ipalKit added the same rules, in place (called by the plugin at start and on every dev reload; returns `LateAdoption[]` — per collection what was put). There the rules are combined with the collection's own by `bothAllow` (an access function that allows only when both do; two query constraints are joined with `and`), because in a sanitized config Payload's default cannot be told from a written rule — never by a function's name, which a production build changes. `custom.ipal.accountRules: false` on a late collection keeps its rules as they are. `unknownStaffCollections` lists staff slugs that are not auth collections (Payload does not start on any). | `staffCollectionsNobodyManages` (async): staff collections on the admin rules while no staff account is a plugin admin — nobody can create, delete or unlock accounts there (the plugin warns at start). +| `staffCreateAccess`, `staffUpdateAccess(slug)`, `staffReadAccess`, `sameStaffCollectionAccess(slug)`, `rolesByAdminOnly`, `rolesNotOwn(slug)`, `hasPluginRoles(collection)`, `canHoldStaffRole(collection)`, `rolesAreAList(collection)`, `applyStaffAccountAccess(config, staffSlugs, { create?, write?, read?, pluginRoles? })` | `@intecion/ipal-kit` | `accounts.adminOnlyCreate` / `adminOnlyWrite` / `staffOnlyRead`: the access functions — "an admin, fully signed in" (create, delete, unlock); "an admin, or the account itself" (update; self = an account of THAT collection); "a fully signed-in account of a staff collection" (read); "an account of this staff collection, or a plugin admin of another" (a collection whose roles are not the plugin's); the two field-access functions for a `roles` field (`update`: only an admin / never the account itself); whether a collection carries the plugin's roles (a `roles` select with `hasMany` at the top level of the data with only `user` / `editor` / `admin`); whether an account of it can hold `editor` or `admin` whatever else the field offers (a select with one of them among its values, or a `roles` field whose values cannot be listed — text, json, a relationship) — then the admin rules apply too; whether the `roles` field can put an ARRAY on the account at all (select / text / relationship need `hasMany`; radio, number, date, checkbox never do) — the plugin counts roles only from an array, so a single-valued field brings no admin rules; the applier — puts the rules on the named staff collections for the operations that have none and closes the `roles` field where the plugin's `update` rule is in force, `pluginRoles` = slugs whose roles field is injected later. Run it before any plugin that wraps access (the 2FA package). | +| `buildFirstUserEndpoint(option?)`, `applyFirstUserRoute(config, option?)`, `adoptLateAuthCollections(config, staffSlugs, { access?, beforeOperation?, firstUserRoute? })`, `bothAllow(first, second)`, `unknownStaffCollections(config, staffSlugs)`, `openSignUpCollections(payload)`, `staffCollectionsOpenToOthers(payload)`, `staffCollectionsOnOwnRoles(payload)`, `staffCollectionsNobodyManages(payload, staffSlugs, except?)` | `@intecion/ipal-kit` | `accounts.firstUserRoute`: the plugin's own `POST /first-register` collection endpoint, matched before Payload's — `403` unless the collection is the panel's login collection (`'panel'`), is in the list, or its own `create` lets an anonymous request through; otherwise it calls Payload's handler (and sets `req.context.ipalFirstRegister`); the applier (every auth collection; `'all'` adds nothing; `endpoints: false` is left alone). For the doctor: slugs of auth collections with open sign-up; `':'` for every staff collection an account of a non-staff collection may create in, read, update, delete from or unlock; slugs of staff collections with role values of their own on the default rules. `adoptLateAuthCollections` takes the LIVE config (`payload.config`) and gives auth collections that a plugin listed after ipalKit added the same rules, in place (called by the plugin at start and on every dev reload; returns `LateAdoption[]` — per collection what was put). There the rules are combined with the collection's own by `bothAllow` (an access function that allows only when both do; two query constraints are joined with `and`), because in a sanitized config Payload's default cannot be told from a written rule — never by a function's name, which a production build changes. `custom.ipal.accountRules: false` on a late collection keeps its rules as they are. `unknownStaffCollections` lists staff slugs that are not auth collections (Payload does not start on any). | `staffCollectionsNobodyManages` (async) → `{ stuck, unchecked }`: `stuck` — staff collections on the admin rules while no staff account is a plugin admin (nobody can create, delete or unlock accounts there; the plugin warns at start); `unchecked` — staff collections whose accounts could not be checked, in which case nothing is claimed. Each collection is asked in the way its field allows. | `checkPassword(password, { email?, minLength? })`, `buildPasswordRuleHook({ minLength? })`, `applyPasswordRule(config, slugs, rule)`, `resolvePasswordRule(option)`, `DEFAULT_PASSWORD_MIN_LENGTH` | `@intecion/ipal-kit` | `accounts.password`: `'short' \| 'email' \| null` for a new password (length in characters); the `beforeOperation` hook for `create` / `update` / `resetPassword` (throws Payload's `ValidationError` on `password`, text in the panel's language; the account's address is looked up by id, reset token or bulk query when the request carries none; a password that is not text is refused; login is never checked); the applier; the option → `{ minLength }` or `null`; `12`. | | `writeOnlySecret(field, options?)`, `writeOnlySecrets(fields, names, optionsByName?)`, `maskSecretAfterRead`, `keepSecretBeforeValidate`, `buildKeepSecret(options?)`, `SECRET_MASK`, `SECRET_CLEAR`, `isSecretMask(value)`, `INTEGRATION_SECRET_FIELDS`, `SMTP_PASSWORD_BOUND_TO` | `@intecion/ipal-kit` | Write-only secret fields (`secrets.writeOnly`): the wrapper for one field and for named fields anywhere in a tree (tabs, rows, groups); the two field hooks (reads through access control get `'********'`, the Local API with access control off gets the value; a save with nothing / empty / the mask keeps the stored value, `'[[clear]]'` removes it); the hook builder with options — `{ boundTo: ['siblingField'], appliesWhen?: (siblingData) => boolean }`: a save through access control that changes a bound sibling field without sending the secret throws a `ValidationError` on the secret (`secrets.reenterOnChange`); the two constants; the plugin's own secret field names (`smtpPassword`, `turnstileSecretKey`); the fields the SMTP password is bound to (`smtpHost`, `smtpPort`, `smtpUser` — not the transport: the mail adapter may fall back to SMTP). | | `maskSecretsOnRestore`, `maskWriteOnlySecrets(data, fields)` | `@intecion/ipal-kit` | Versions and write-only secrets: the `afterRead` hook for a global or a collection (a restore answers with the version document, fields under `version`, where field hooks do not run — it masks them there for reads through access control); the walker it uses (masks every write-only field in `data`, following tabs, rows, groups, arrays and blocks). On Site integrations by default; add the hook to your own entity that has both. | diff --git a/docs/agent/skills/ipal-upgrade/SKILL.md b/docs/agent/skills/ipal-upgrade/SKILL.md index dee04a5..3966a74 100644 --- a/docs/agent/skills/ipal-upgrade/SKILL.md +++ b/docs/agent/skills/ipal-upgrade/SKILL.md @@ -460,7 +460,8 @@ account → "Two-step verification: Set up." and the reset button; delete the ac `roles` field — only an admin (when the field has no `access.update` of its own). **Check:** does a non-admin create or edit other accounts, or change roles, there today? Then write the rule you want; - an account of the collection **can hold `editor` or `admin`** although its roles are not just the plugin's - (`user, editor, admin, boss`; `viewer, editor`; a `roles` field that is text or json): the admin rules too, + (`user, editor, admin, boss`; `viewer, editor`; a `roles` field that is text, json or a relationship) — the + field must hold a LIST (`hasMany`; a single-valued `roles` is not affected, its value never counts): the admin rules too, since the release after 1.16.7 (the value on the account makes a plugin admin or editor). **Check:** do accounts with one of your own roles (`boss`, `viewer`) manage accounts there? Then write that as the collection's own rules. Read the start log: `No staff account holds the role "admin", so NOBODY can create, diff --git a/reference/.agents/skills/ipal-debug/SKILL.md b/reference/.agents/skills/ipal-debug/SKILL.md index 3b68f31..c0268f2 100644 --- a/reference/.agents/skills/ipal-debug/SKILL.md +++ b/reference/.agents/skills/ipal-debug/SKILL.md @@ -104,7 +104,8 @@ through this procedure. Ask only when you are missing something you cannot get y | `POST /api//first-register` answers `403` on an empty collection | `accounts.firstUserRoute`: only the panel's login collection may register its first account that way (the plugin's own endpoint sits in front of Payload's) | an admin creates the account; or the collection's own `create: () => true` (sign-up); or `accounts: { firstUserRoute: [''] }` | | an editor (or a script with its token) gets `403` creating an account in the project's own `users` | `accounts.adminOnlyCreate`: only admins create staff accounts where the roles are the plugin's | create as an admin; or write the collection's `create` rule; or `adminOnlyCreate: false` | | log at start: `[ipal] No staff account holds the role "admin", so NOBODY can create, delete or unlock accounts in "…"` | a staff collection whose accounts can hold `editor` or `admin` runs on the admin rules, and no staff account is an admin | give one account `admin` with a script (`payload.update`, Local API); or write the collection's own `access.create` / `update` / `delete` | -| an account with a role of the project's own (`boss`, `viewer`) gets `403` creating or editing accounts in its staff collection (it worked on 1.16.7) | the collection's `roles` can hold `editor` or `admin` (a select with one of them, or a text / json field): the admin rules apply | do it as an admin; or write the collection's own rules for that role | +| an account with a role of the project's own (`boss`, `viewer`) gets `403` creating or editing accounts in its staff collection (it worked on 1.16.7) | the collection's `roles` can hold `editor` or `admin` (a select with `hasMany` and one of them, or a text / relationship field with `hasMany`, or json; a single-valued field is not affected): the admin rules apply | do it as an admin; or write the collection's own rules for that role | +| log at start: `[ipal] Could not check whether an account of "…" holds the role "admin"` | the accounts of that staff collection could not be read or are more than 1000, and no other staff account is an admin | make sure one account holds `admin`; nothing is wrong if one does | | an account gets `403` changing or deleting ANOTHER account of a staff collection (it worked before) | `accounts.adminOnlyWrite`: an admin, or the account itself (update only); on a collection with roles of its own: accounts of that collection | do it as an admin; or write the collection's `update` / `delete` rule; or `adminOnlyWrite: false` | | an account saves its own profile and its `roles` do not change (no error) | `accounts.adminOnlyWrite`: nobody changes its own roles; with the plugin's roles only an admin changes roles | an admin changes the role; or give the `roles` field its own `access.update` | | a logged-in visitor (customer) gets `403` reading a staff collection — an author box went empty | `accounts.staffOnlyRead`: only staff accounts read a staff collection without a `read` rule | write that collection's `read` rule; or `staffOnlyRead: false` | diff --git a/reference/.agents/skills/ipal-reference/resources/api.md b/reference/.agents/skills/ipal-reference/resources/api.md index dccc47d..ada3950 100644 --- a/reference/.agents/skills/ipal-reference/resources/api.md +++ b/reference/.agents/skills/ipal-reference/resources/api.md @@ -67,8 +67,8 @@ Admin panel components from `@intecion/ipal-kit/admin` — the project does NOT | `isAdmin(user, source?)` | `@intecion/ipal-kit`; in client components `@intecion/ipal-kit/client` | Predicate → `boolean`: staff account with the `admin` role (see `hasMinimumRole`). In hooks and endpoints: `isAdmin(req.user, req.payload)`; in a client component: `isAdmin(user, config)` from `/client` — the main entry does not build there with webpack (`'server-only' cannot be imported…`). | | `isEditor(user, source?)` | `@intecion/ipal-kit`; in client components `@intecion/ipal-kit/client` | Predicate → `boolean`: staff account with `editor` or higher. | | `panelAccess(minimum?)`, `applyPanelRole(config, slug, role)`, `resolvePanelRole(option)`, `countBelowPanelRole(payload, slug, role)`, `DEFAULT_PANEL_ROLE` | `@intecion/ipal-kit` | `accounts.panelRole`: an `access.admin` function ("holds at least `minimum`", default `'editor'`; role only, not the second factor); the applier (skips a collection that has its own `access.admin`); the option → role or `null` when off; `{ all, below }` counts for the start-up line; `'editor'`. | -| `staffCreateAccess`, `staffUpdateAccess(slug)`, `staffReadAccess`, `sameStaffCollectionAccess(slug)`, `rolesByAdminOnly`, `rolesNotOwn(slug)`, `hasPluginRoles(collection)`, `canHoldStaffRole(collection)`, `applyStaffAccountAccess(config, staffSlugs, { create?, write?, read?, pluginRoles? })` | `@intecion/ipal-kit` | `accounts.adminOnlyCreate` / `adminOnlyWrite` / `staffOnlyRead`: the access functions — "an admin, fully signed in" (create, delete, unlock); "an admin, or the account itself" (update; self = an account of THAT collection); "a fully signed-in account of a staff collection" (read); "an account of this staff collection, or a plugin admin of another" (a collection whose roles are not the plugin's); the two field-access functions for a `roles` field (`update`: only an admin / never the account itself); whether a collection carries the plugin's roles (a `roles` select at the top level of the data with only `user` / `editor` / `admin`); whether an account of it can hold `editor` or `admin` whatever else the field offers (a select with one of them among its values, or a `roles` field whose values cannot be listed — text, json) — then the admin rules apply too; the applier — puts the rules on the named staff collections for the operations that have none and closes the `roles` field where the plugin's `update` rule is in force, `pluginRoles` = slugs whose roles field is injected later. Run it before any plugin that wraps access (the 2FA package). | -| `buildFirstUserEndpoint(option?)`, `applyFirstUserRoute(config, option?)`, `adoptLateAuthCollections(config, staffSlugs, { access?, beforeOperation?, firstUserRoute? })`, `bothAllow(first, second)`, `unknownStaffCollections(config, staffSlugs)`, `openSignUpCollections(payload)`, `staffCollectionsOpenToOthers(payload)`, `staffCollectionsOnOwnRoles(payload)`, `staffCollectionsNobodyManages(payload, staffSlugs, except?)` | `@intecion/ipal-kit` | `accounts.firstUserRoute`: the plugin's own `POST /first-register` collection endpoint, matched before Payload's — `403` unless the collection is the panel's login collection (`'panel'`), is in the list, or its own `create` lets an anonymous request through; otherwise it calls Payload's handler (and sets `req.context.ipalFirstRegister`); the applier (every auth collection; `'all'` adds nothing; `endpoints: false` is left alone). For the doctor: slugs of auth collections with open sign-up; `':'` for every staff collection an account of a non-staff collection may create in, read, update, delete from or unlock; slugs of staff collections with role values of their own on the default rules. `adoptLateAuthCollections` takes the LIVE config (`payload.config`) and gives auth collections that a plugin listed after ipalKit added the same rules, in place (called by the plugin at start and on every dev reload; returns `LateAdoption[]` — per collection what was put). There the rules are combined with the collection's own by `bothAllow` (an access function that allows only when both do; two query constraints are joined with `and`), because in a sanitized config Payload's default cannot be told from a written rule — never by a function's name, which a production build changes. `custom.ipal.accountRules: false` on a late collection keeps its rules as they are. `unknownStaffCollections` lists staff slugs that are not auth collections (Payload does not start on any). | `staffCollectionsNobodyManages` (async): staff collections on the admin rules while no staff account is a plugin admin — nobody can create, delete or unlock accounts there (the plugin warns at start). +| `staffCreateAccess`, `staffUpdateAccess(slug)`, `staffReadAccess`, `sameStaffCollectionAccess(slug)`, `rolesByAdminOnly`, `rolesNotOwn(slug)`, `hasPluginRoles(collection)`, `canHoldStaffRole(collection)`, `rolesAreAList(collection)`, `applyStaffAccountAccess(config, staffSlugs, { create?, write?, read?, pluginRoles? })` | `@intecion/ipal-kit` | `accounts.adminOnlyCreate` / `adminOnlyWrite` / `staffOnlyRead`: the access functions — "an admin, fully signed in" (create, delete, unlock); "an admin, or the account itself" (update; self = an account of THAT collection); "a fully signed-in account of a staff collection" (read); "an account of this staff collection, or a plugin admin of another" (a collection whose roles are not the plugin's); the two field-access functions for a `roles` field (`update`: only an admin / never the account itself); whether a collection carries the plugin's roles (a `roles` select with `hasMany` at the top level of the data with only `user` / `editor` / `admin`); whether an account of it can hold `editor` or `admin` whatever else the field offers (a select with one of them among its values, or a `roles` field whose values cannot be listed — text, json, a relationship) — then the admin rules apply too; whether the `roles` field can put an ARRAY on the account at all (select / text / relationship need `hasMany`; radio, number, date, checkbox never do) — the plugin counts roles only from an array, so a single-valued field brings no admin rules; the applier — puts the rules on the named staff collections for the operations that have none and closes the `roles` field where the plugin's `update` rule is in force, `pluginRoles` = slugs whose roles field is injected later. Run it before any plugin that wraps access (the 2FA package). | +| `buildFirstUserEndpoint(option?)`, `applyFirstUserRoute(config, option?)`, `adoptLateAuthCollections(config, staffSlugs, { access?, beforeOperation?, firstUserRoute? })`, `bothAllow(first, second)`, `unknownStaffCollections(config, staffSlugs)`, `openSignUpCollections(payload)`, `staffCollectionsOpenToOthers(payload)`, `staffCollectionsOnOwnRoles(payload)`, `staffCollectionsNobodyManages(payload, staffSlugs, except?)` | `@intecion/ipal-kit` | `accounts.firstUserRoute`: the plugin's own `POST /first-register` collection endpoint, matched before Payload's — `403` unless the collection is the panel's login collection (`'panel'`), is in the list, or its own `create` lets an anonymous request through; otherwise it calls Payload's handler (and sets `req.context.ipalFirstRegister`); the applier (every auth collection; `'all'` adds nothing; `endpoints: false` is left alone). For the doctor: slugs of auth collections with open sign-up; `':'` for every staff collection an account of a non-staff collection may create in, read, update, delete from or unlock; slugs of staff collections with role values of their own on the default rules. `adoptLateAuthCollections` takes the LIVE config (`payload.config`) and gives auth collections that a plugin listed after ipalKit added the same rules, in place (called by the plugin at start and on every dev reload; returns `LateAdoption[]` — per collection what was put). There the rules are combined with the collection's own by `bothAllow` (an access function that allows only when both do; two query constraints are joined with `and`), because in a sanitized config Payload's default cannot be told from a written rule — never by a function's name, which a production build changes. `custom.ipal.accountRules: false` on a late collection keeps its rules as they are. `unknownStaffCollections` lists staff slugs that are not auth collections (Payload does not start on any). | `staffCollectionsNobodyManages` (async) → `{ stuck, unchecked }`: `stuck` — staff collections on the admin rules while no staff account is a plugin admin (nobody can create, delete or unlock accounts there; the plugin warns at start); `unchecked` — staff collections whose accounts could not be checked, in which case nothing is claimed. Each collection is asked in the way its field allows. | `checkPassword(password, { email?, minLength? })`, `buildPasswordRuleHook({ minLength? })`, `applyPasswordRule(config, slugs, rule)`, `resolvePasswordRule(option)`, `DEFAULT_PASSWORD_MIN_LENGTH` | `@intecion/ipal-kit` | `accounts.password`: `'short' \| 'email' \| null` for a new password (length in characters); the `beforeOperation` hook for `create` / `update` / `resetPassword` (throws Payload's `ValidationError` on `password`, text in the panel's language; the account's address is looked up by id, reset token or bulk query when the request carries none; a password that is not text is refused; login is never checked); the applier; the option → `{ minLength }` or `null`; `12`. | | `writeOnlySecret(field, options?)`, `writeOnlySecrets(fields, names, optionsByName?)`, `maskSecretAfterRead`, `keepSecretBeforeValidate`, `buildKeepSecret(options?)`, `SECRET_MASK`, `SECRET_CLEAR`, `isSecretMask(value)`, `INTEGRATION_SECRET_FIELDS`, `SMTP_PASSWORD_BOUND_TO` | `@intecion/ipal-kit` | Write-only secret fields (`secrets.writeOnly`): the wrapper for one field and for named fields anywhere in a tree (tabs, rows, groups); the two field hooks (reads through access control get `'********'`, the Local API with access control off gets the value; a save with nothing / empty / the mask keeps the stored value, `'[[clear]]'` removes it); the hook builder with options — `{ boundTo: ['siblingField'], appliesWhen?: (siblingData) => boolean }`: a save through access control that changes a bound sibling field without sending the secret throws a `ValidationError` on the secret (`secrets.reenterOnChange`); the two constants; the plugin's own secret field names (`smtpPassword`, `turnstileSecretKey`); the fields the SMTP password is bound to (`smtpHost`, `smtpPort`, `smtpUser` — not the transport: the mail adapter may fall back to SMTP). | | `maskSecretsOnRestore`, `maskWriteOnlySecrets(data, fields)` | `@intecion/ipal-kit` | Versions and write-only secrets: the `afterRead` hook for a global or a collection (a restore answers with the version document, fields under `version`, where field hooks do not run — it masks them there for reads through access control); the walker it uses (masks every write-only field in `data`, following tabs, rows, groups, arrays and blocks). On Site integrations by default; add the hook to your own entity that has both. | diff --git a/reference/.agents/skills/ipal-upgrade/SKILL.md b/reference/.agents/skills/ipal-upgrade/SKILL.md index dee04a5..3966a74 100644 --- a/reference/.agents/skills/ipal-upgrade/SKILL.md +++ b/reference/.agents/skills/ipal-upgrade/SKILL.md @@ -460,7 +460,8 @@ account → "Two-step verification: Set up." and the reset button; delete the ac `roles` field — only an admin (when the field has no `access.update` of its own). **Check:** does a non-admin create or edit other accounts, or change roles, there today? Then write the rule you want; - an account of the collection **can hold `editor` or `admin`** although its roles are not just the plugin's - (`user, editor, admin, boss`; `viewer, editor`; a `roles` field that is text or json): the admin rules too, + (`user, editor, admin, boss`; `viewer, editor`; a `roles` field that is text, json or a relationship) — the + field must hold a LIST (`hasMany`; a single-valued `roles` is not affected, its value never counts): the admin rules too, since the release after 1.16.7 (the value on the account makes a plugin admin or editor). **Check:** do accounts with one of your own roles (`boss`, `viewer`) manage accounts there? Then write that as the collection's own rules. Read the start log: `No staff account holds the role "admin", so NOBODY can create,