diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md index 5d8b4ce..9155fc4 100644 --- a/docs/CHANGELOG.md +++ b/docs/CHANGELOG.md @@ -9,6 +9,39 @@ 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. +## 1.17.2 — DRAFT (security group C, round 2: the owner's Q1–Q3; not released) + +> Draft lines from session C (branch `claude/security-c-1172`); the integration session merges them with A's and B's. +> No schema, migration or import-map change. **Read the first two lines if the site has a customer login collection +> or uses Payload jobs over HTTP**; otherwise nothing changes for it. + +### Security +- **A customer account can no longer create submissions over REST.** `POST /api/form-submissions` (and GraphQL + `createFormSubmission`) needed only a signed-in account of any login collection, so a customer of a visitor + collection could skip the rate limit, Turnstile, the consent tick and the validation, and the form's e-mails went + out. Now: a staff account with its second factor. The site's own forms (`submitForm`, `createSubmitAction`, the file + endpoint) are not affected. Way back: `forms.formSubmissionOverrides.access.create`. +- **Payload's job queue over HTTP: only an admin or the cron secret.** When the project writes no + `jobs.access.run`, `/api/payload-jobs/run` and `/handle-schedules` now answer only an admin signed in with the second + factor (an admin's API key counts) or `Authorization: Bearer ` (16+ characters); before, any signed-in + account of any login collection. **A site whose cron calls the run route:** set `CRON_SECRET` in the app's + environment and send the header; the start log says so when it is missing. In-process runs (`jobs.autoRun`, + `payload jobs:run`) and a project's own rule are not affected; `iapl({ jobsRunAccess: false })` keeps Payload's + default (security.md "Payload's job queue"). + +### Added +- `iapl-doctor` deep rule **`visitor-writes`** (warning): on a site with a visitor login collection, every collection + and global whose write rule lets such an account in, Payload's default included. +- `jobsRunAccess`, `withJobsRunAccess`, `jobsRunNotice`, `cronSecretMatches`, `CRON_SECRET_ENV`, + `CRON_SECRET_MIN_LENGTH`; option `jobsRunAccess`; env `CRON_SECRET`. + +### Changed +- The reference site (and every new site from `iapl create`): `Pages`, `Posts`, `CaseStudies`, `Media` and the + `Header`, `Footer`, `Company` globals have their own write rules (`adminOrEditor`) instead of Payload's default. + Existing sites: nothing changes; the doctor's `visitor-writes` names what to add where it matters. +- Not built (owner's Q3 answer (a), planned for 2.0): a plugin-wide default for the project's own entities and for + Payload's `payload-locked-documents`. + ## 1.17.1 — security fixes from the IAWL review; the panel's sign-in look; the sending method is chosen > **Read before upgrading.** **MongoDB: no migration. Postgres / SQLite: one migration** — a new column for the diff --git a/docs/agent/AGENT.md b/docs/agent/AGENT.md index e40944c..a5c8c31 100644 --- a/docs/agent/AGENT.md +++ b/docs/agent/AGENT.md @@ -636,12 +636,18 @@ for visitors. Then, all four: `access.staffCollections` is for a second collection of STAFF (access.md → "Who is staff"). 3. In every auth collection use `adminOrSelfIn('')`, not `adminOrSelf`, for "only my own record". 4. Payload's default for a collection or global without `access` is "any logged-in account" — a customer too. - Give every collection and global explicit `access`. 2FA covers the panel's collection only. + Give every collection and global explicit `access` (writes: `adminOrEditor`, as the reference site's collections + and globals do since 1.17.2). Verify with `iapl-doctor --url …` (deep): no `visitor-writes` finding. 2FA covers + the panel's collection only. 5. Never let a sign-up write a field that grants rights (`roles`, `isAdmin`, …): give such a field `access: { create: adminOnlyField, update: adminOnlyField }`. 6. Check: log in as such an account (`POST /api/customers/login`), then `GET /api/globals/site-integrations`, `GET /api/form-submissions` and `GET /api/users` with its token must answer `403`, and so must - `POST /api/setup-totp`. + `POST /api/setup-totp`, `POST /api/form-submissions` and (a site with Payload jobs) `GET /api/payload-jobs/run` + (`401`). +7. Payload jobs run over HTTP: since 1.17.2 only an admin or `Authorization: Bearer ` (when the project + writes no `jobs.access.run`). A Coolify scheduled task that calls `/api/payload-jobs/run` sends that header; + `CRON_SECRET` goes into the app's environment (security.md "Payload's job queue"). **NEVER:** a second `media`, `daneFirmy`/`settings`/ `navigation`/`footer` as collections (they are globals), FAQ/hero/features as collections diff --git a/docs/agent/reference-site/INDEX.md b/docs/agent/reference-site/INDEX.md index 4b5895c..f5cc93b 100644 --- a/docs/agent/reference-site/INDEX.md +++ b/docs/agent/reference-site/INDEX.md @@ -279,7 +279,7 @@ Rules: AGENT.md §5, iapl-nav, iapl-collection. | `src/collections/Pages.ts` | Pages: slug, blocks layout, AI summary, noindex, slug history, revalidation, system-page delete guard (below) | | `src/collections/Posts.ts` | the blog collection (archive in System pages) (below) | | `src/collections/entryFields.ts` | shared fields of archive collections (names the entry card reads) (below) | -| `src/globals/Company.ts` | company data (PL market): footer, contact details, LocalBusiness JSON-LD (below) | +| `src/globals/Company.ts` | company data (PL market): footer, contact details, LocalBusiness JSON-LD | | `src/globals/Footer.ts` | footer navigation global (below) | | `src/globals/Header.ts` | header navigation global (below) | @@ -288,7 +288,7 @@ Rules: AGENT.md §5, iapl-nav, iapl-collection. ```ts import type { CollectionConfig } from 'payload' -import { buildRevalidateHook } from '@intecion/ipal-kit' +import { adminOrEditor, buildRevalidateHook } from '@intecion/ipal-kit' import { revalidatePath } from 'next/cache' import { i18nConfig } from '@/i18n.config' @@ -301,7 +301,8 @@ const revalidate = buildRevalidateHook({ config: i18nConfig, revalidatePath }) export const CaseStudies: CollectionConfig = { slug: 'caseStudies', admin: { defaultColumns: ['title', 'publishedAt', 'updatedAt'], useAsTitle: 'title' }, - access: { read: () => true }, + // write rules of its own: Payload's default is "any signed-in account" — a visitor login collection would reach it (security.md "Visitor accounts") + access: { create: adminOrEditor, delete: adminOrEditor, read: () => true, update: adminOrEditor }, defaultSort: '-publishedAt', fields: entryFields, hooks: { afterChange: [revalidate.afterChange], afterDelete: [revalidate.afterDelete] }, @@ -315,6 +316,7 @@ export const CaseStudies: CollectionConfig = { import type { CollectionConfig } from 'payload' import { + adminOrEditor, buildMediaPlaceholderField, buildMediaPlaceholderHook, buildOptimizeUploadField, @@ -325,7 +327,8 @@ import { /** media.md "Full collection", 1:1. */ export const Media: CollectionConfig = { slug: 'media', - access: { read: () => true }, // public files; media are served by the app (/api/media/file/…) + // write rules of its own: Payload's default is "any signed-in account" — a visitor login collection would reach it (security.md "Visitor accounts") + access: { create: adminOrEditor, delete: adminOrEditor, read: () => true, update: adminOrEditor }, // public files; media are served by the app (/api/media/file/…) upload: { focalPoint: true, mimeTypes: ['image/*', 'application/pdf', 'video/mp4', 'video/webm'] }, hooks: { beforeOperation: [normalizeFilenameHook, buildOptimizeUploadHook(), buildMediaPlaceholderHook()], @@ -344,6 +347,7 @@ export const Media: CollectionConfig = { import type { CollectionConfig } from 'payload' import { + adminOrEditor, buildNoindexField, buildPreventDeleteSystemPage, buildRevalidateHook, @@ -362,7 +366,8 @@ const revalidate = buildRevalidateHook({ config: i18nConfig, revalidatePath }) export const Pages: CollectionConfig = { slug: 'pages', admin: { defaultColumns: ['title', 'slug', 'updatedAt'], useAsTitle: 'title' }, - access: { read: () => true }, + // write rules of its own: Payload's default is "any signed-in account" — a visitor login collection would reach it (security.md "Visitor accounts") + access: { create: adminOrEditor, delete: adminOrEditor, read: () => true, update: adminOrEditor }, fields: [ { name: 'title', type: 'text', localized: true, required: true }, buildSlugField({ from: 'title' }), @@ -385,7 +390,7 @@ export const Pages: CollectionConfig = { ```ts import type { CollectionConfig } from 'payload' -import { buildRevalidateHook } from '@intecion/ipal-kit' +import { adminOrEditor, buildRevalidateHook } from '@intecion/ipal-kit' import { revalidatePath } from 'next/cache' import { i18nConfig } from '@/i18n.config' @@ -398,7 +403,8 @@ const revalidate = buildRevalidateHook({ config: i18nConfig, revalidatePath }) export const Posts: CollectionConfig = { slug: 'posts', admin: { defaultColumns: ['title', 'publishedAt', 'updatedAt'], useAsTitle: 'title' }, - access: { read: () => true }, + // write rules of its own: Payload's default is "any signed-in account" — a visitor login collection would reach it (security.md "Visitor accounts") + access: { create: adminOrEditor, delete: adminOrEditor, read: () => true, update: adminOrEditor }, defaultSort: '-publishedAt', fields: entryFields, hooks: { afterChange: [revalidate.afterChange], afterDelete: [revalidate.afterDelete] }, @@ -431,63 +437,19 @@ export const entryFields: Field[] = [ ] ``` -### `src/globals/Company.ts` - -```ts -import type { GlobalConfig } from 'payload' - -import { buildGlobalRevalidateHook, rowLabel } from '@intecion/ipal-kit' -import { revalidatePath } from 'next/cache' - -/** Company data for a PL market site: footer, contact block details, LocalBusiness JSON-LD. */ -export const Company: GlobalConfig = { - slug: 'company', - access: { read: () => true }, - fields: [ - { name: 'name', type: 'text', required: true }, - { name: 'legalName', type: 'text' }, - { name: 'taxId', type: 'text', label: 'NIP' }, - { name: 'taxIdLabel', type: 'text', admin: { description: 'Shown before the tax ID in the footer.' }, defaultValue: 'NIP', label: 'Tax ID label', localized: true }, - { - name: 'address', - type: 'group', - fields: [ - { name: 'street', type: 'text' }, - { name: 'postalCode', type: 'text' }, - { name: 'city', type: 'text' }, - { name: 'country', type: 'text', defaultValue: 'PL' }, - ], - }, - { name: 'phone', type: 'text' }, - { name: 'email', type: 'email' }, - { name: 'hours', type: 'text', localized: true, admin: { description: 'Shown next to the contact form, e.g. "Mon–Fri 9:00–17:00".' } }, - { - name: 'socials', - type: 'array', - admin: { components: rowLabel('label', 'Profile'), initCollapsed: true }, - labels: { plural: 'Profiles', singular: 'Profile' }, - fields: [ - { name: 'label', type: 'text', required: true }, - { name: 'url', type: 'text', required: true }, - ], - }, - ], - hooks: { afterChange: [buildGlobalRevalidateHook({ revalidatePath })] }, -} -``` - ### `src/globals/Footer.ts` ```ts import type { GlobalConfig } from 'payload' -import { buildGlobalRevalidateHook, buildLinkField, rowLabel } from '@intecion/ipal-kit' +import { adminOrEditor, buildGlobalRevalidateHook, buildLinkField, rowLabel } from '@intecion/ipal-kit' import { revalidatePath } from 'next/cache' /** iapl-nav: link columns and a note. Legal links come from System pages (getSystemLinks), not from here. */ export const Footer: GlobalConfig = { slug: 'footer', - access: { read: () => true }, + // write rules of its own: Payload's default is "any signed-in account" — a visitor login collection would reach it (security.md "Visitor accounts") + access: { read: () => true, update: adminOrEditor }, fields: [ { name: 'columns', @@ -517,13 +479,14 @@ export const Footer: GlobalConfig = { ```ts import type { GlobalConfig } from 'payload' -import { buildGlobalRevalidateHook, buildLinkField, buildLinksField, rowLabel } from '@intecion/ipal-kit' +import { adminOrEditor, buildGlobalRevalidateHook, buildLinkField, buildLinksField, rowLabel } from '@intecion/ipal-kit' import { revalidatePath } from 'next/cache' /** iapl-nav: menu with one submenu level, a CTA button, the mobile menu label. Logo comes from Site settings. */ export const Header: GlobalConfig = { slug: 'header', - access: { read: () => true }, + // write rules of its own: Payload's default is "any signed-in account" — a visitor login collection would reach it (security.md "Visitor accounts") + access: { read: () => true, update: adminOrEditor }, fields: [ { name: 'navItems', diff --git a/docs/agent/skills/iapl-audit/resources/closed-doors.spec.template.ts b/docs/agent/skills/iapl-audit/resources/closed-doors.spec.template.ts index 816abbf..f2e8d4c 100644 --- a/docs/agent/skills/iapl-audit/resources/closed-doors.spec.template.ts +++ b/docs/agent/skills/iapl-audit/resources/closed-doors.spec.template.ts @@ -46,12 +46,16 @@ const DOORS: Door[] = [ { closedFor: ALL, method: 'POST', name: 'the crawler\'s call-back without its token', path: '/api/ipal/cookie-crawl/results', body: { jobId: 'x', ok: true } }, { closedFor: OUTSIDERS, method: 'POST', name: 'a crawl without the schedule\'s token', path: '/api/ipal/cookie-crawl' }, { closedFor: OUTSIDERS, name: 'form submissions', path: '/api/form-submissions' }, + // IAPL 1.17.2: a staff account only; an open door answers 400 (validation) instead of 403 + { body: { form: NO_ID, submissionData: [] }, closedFor: OUTSIDERS, method: 'POST', name: 'a submission past submitForm', path: '/api/form-submissions', closed: status(403) }, { body: { email: 'door@example.com', password: 'Door-Password-1234', roles: ['admin'] }, closedFor: ALL, method: 'POST', name: 'nobody creates a staff account', path: '/api/users', closed: status(403) }, { body: { email: 'first@example.com', password: 'Door-Password-1234' }, closedFor: ALL, method: 'POST', name: 'the first-user route once an account exists', path: '/api/users/first-register', closed: status(403) }, { body: {}, closedFor: OUTSIDERS, method: 'POST', name: 'Site settings cannot be saved', path: '/api/globals/site-settings', closed: status(403) }, { closedFor: ALL, name: 'the GraphQL playground (production)', path: '/api/graphql-playground', closed: status(404) }, { closedFor: ALL, graphql: '{ __schema { queryType { name } } }', closed: ({ body }) => Boolean((body as { errors?: unknown[] })?.errors?.length), name: 'GraphQL introspection (production)' }, - { closedFor: ALL, name: 'Payload\'s job queue (a site without jobs)', path: '/api/payload-jobs/run', closed: status(404) }, + // a site without jobs: 404. A site WITH jobs (IAPL 1.17.2): refused (401) for everybody but an admin and + // `Authorization: Bearer ` — drop `closed: status(404)` there + { closedFor: ALL, name: 'Payload\'s job queue', path: '/api/payload-jobs/run', closed: status(404) }, // the project's own doors: add them here // { closedFor: OUTSIDERS, body: {}, method: 'PATCH', name: 'pages cannot be changed', path: `/api/pages/${NO_ID}`, closed: status(403) }, ] diff --git a/docs/agent/skills/iapl-reference/SKILL.md b/docs/agent/skills/iapl-reference/SKILL.md index 878dad2..a1b2eeb 100644 --- a/docs/agent/skills/iapl-reference/SKILL.md +++ b/docs/agent/skills/iapl-reference/SKILL.md @@ -93,7 +93,7 @@ description: Complete map of everything @intecion/ipal-kit provides — every ia | `forms.adminGroup` | `'Forms'` | sidebar group | `false` = Payload default; `admin.group` in overrides wins | | `forms.fields.*` | on: `checkbox`, `checkboxGroup`, `country`, `date`, `email`, `message`, `number`, `radio`, `select`, `state`, `step`, `text`, `textarea`, `time`; off: `payment` | block types in the builder (all with "Show only when") | `: false`; a block object replaces it; `payment: true` **does nothing** (filtered out) — pass a block object | | `forms.formOverrides` | Form/Forms labels, `emails` readable by logged-in users only | overrides the `forms` collection (`fields: ({ defaultFields }) => …`, `slug`, `admin`, `access`…) | any `CollectionConfig` | -| `forms.formSubmissionOverrides` | create: logged-in, read: editor+, delete: admin | overrides `form-submissions` | `access.create` etc. wins | +| `forms.formSubmissionOverrides` | create: a staff account with its second factor (since 1.17.2; before: any signed-in account), read: editor+, delete: admin | overrides `form-submissions` | `access.create` etc. wins | | `forms.redirectRelationships` | none | collections a form can redirect to | `['pages']` | | `forms.emailLayout` | `false` | `beforeEmail` with a layout (logo, colour, footer) + Site settings → **Emails** tab; `{{*:table}}` readable | `true` | | `forms.beforeEmail` | none | your own e-mail changes (after the layout) | form-builder function | @@ -102,6 +102,7 @@ description: Complete map of everything @intecion/ipal-kit provides — every ia | `forms.consentFieldName` | `'consent'` | name of the GDPR consent field `submitForm` requires (read from `config.custom.ipal`) | `createSubmitAction({ consentFieldName })` / `submitForm` argument wins | | `consentLog` | **on** (since 1.17.0) | `consent-records` collection + `POST /api/ipal/consent` (rate limit 20/min); Postgres / SQLite: a table, migration in the same deploy | `false` / `{ retentionDays }` (default 1095) | | `consentLog.collectionOverrides` | none | changes `consent-records`: an object merges `access` / `admin` / `hooks` key by key (your keys win), a function `(collection) => collection` takes over (keep the slug) | e.g. `{ access: { read: ({ req }) => req.user?.email === 'dpo@acme.pl' } }` — narrows who reads records in a project without roles | +| `jobsRunAccess` | on (since 1.17.2), only when the project writes no `jobs.access.run` | Payload's job queue over HTTP (`/api/payload-jobs/run`, `/handle-schedules`): an admin with the second factor (an admin API key counts) or `Authorization: Bearer ` (16+ chars); before: any signed-in account of any auth collection. In-process runs (`jobs.autoRun`, `payload jobs:run`) unaffected | `false` = Payload's default; `{ secretVar }` = another variable; your own `jobs.access.run` wins. Check: `curl -H "Authorization: Bearer $CRON_SECRET" $URL/api/payload-jobs/run` → 200, without it 401 (security.md "Payload's job queue") | | `doctor` | on (404 until `IAPL_DOCTOR_TOKEN` is set) | `GET /api/ipal/doctor` — read-only counts for `iapl-doctor --url` (users without TOTP, cookies waiting for approval, versions); Bearer token ≥ 32 characters, rate-limited, never names or values | `false` = no endpoint; `{ tokenVar, access }` (doctor.md) | | `cookieScanner` | off | `cookie-review` collection, "Scan cookies" box above its list (`CookieScanButton`), `GET`/`POST /api/ipal/cookie-scan`, and (unless `approval: false`) the *Approve cookies* view `/admin/cookie-approval` (`CookieApprovalView`) + `GET`/`POST /api/ipal/cookie-approval` + the dashboard reminder; a scan lists the cookies of the integrations switched on + names looked up in the bundled Open Cookie Database; one **Approve and add** puts the ticked cookies into Cookies → Cookie list (so `` and the detailed window); never deletes, never overwrites edited text, never duplicates, nothing reaches the banner before approval | `true` / object; after switching on: `pnpm generate:importmap` + `migrate:create`. Check: *Privacy → Cookie review* → **Scan cookies** → "Waiting for approval: N" → **Review and approve** → **Approve and add** → the cookies are in Cookies → Cookie list (cookie-scanner.md) | | `cookieScanner.adminLayout` | `'combined'` | one *Cookies* entry: *Review and approve* and (with `crawl`) *Site check* tabs on the `cookie-settings` global (`ui` fields, `CookieReviewTab` / `CookieSiteCheckTab`); `cookie-review` and `cookie-crawl` get `admin.group: false` (out of the nav, pages and API kept) | `'separate'`; no migration, `generate:importmap` | @@ -277,6 +278,7 @@ The plugin's own variables are `IAPL_`; a deploy that sets the spelling fr | `IAPL_IP_HEADER` | `ipHeader: true` + production | rate limit trusts any IP header (spoofing) + warning in prod | env: `cf-connecting-ip` (Cloudflare) / `x-forwarded-for` (Traefik/nginx) | | `IAPL_COOKIE_SCAN_URL`, `IAPL_COOKIE_SCAN_TOKEN` | `cookieScanner.crawl` (`iaplEnvRules({ cookieCrawl: true })` requires both in production; token ≥ 16 chars) | **Check site** disabled, the box names the missing variable | env; the token also goes into the scanner service's `IAPL_CRAWLER_SITES` as `host=token` | | `IAPL_DOCTOR_TOKEN` | no; ≥ 32 characters | `GET /api/ipal/doctor` answers 404; with it the endpoint answers a Bearer token, and `iapl-doctor --url` with the same variable reads the deep counts | env (Coolify) and the doctor's shell; also read by the doctor: `CI`, `NO_COLOR`, `PAYLOAD_CONFIG_PATH` (`--deep`), `IAPL_DOCTOR_IMPORT_MAP` (internal) — doctor.md | +| `CRON_SECRET` | no; ≥ 16 characters (name: `jobsRunAccess.secretVar`) | Payload's job queue runs over HTTP only for an admin; the start log says so when the queue is on | env (Coolify); the cron sends `Authorization: Bearer ` to `/api/payload-jobs/run` | | `IAPL_NOINDEX` | no; `1`/`true`/`yes` **staging/preview only** | — (when set: robots Disallow, meta noindex, `X-Robots-Tag`, IndexNow sends nothing) | staging env | | `NEXT_PHASE` | set by Next | only tells `next build` from runtime: during the build an unreachable database gives an empty sitemap; at runtime the sitemap throws (route → 503) | do not set by hand | | `NEXT_RUNTIME` | set by Next | `instrumentation.ts` checks for `nodejs`; missing (scripts, seed) → `buildRevalidateHook` does not revalidate | do not set by hand | diff --git a/docs/agent/skills/iapl-reference/resources/api.md b/docs/agent/skills/iapl-reference/resources/api.md index d6c9082..3c62922 100644 --- a/docs/agent/skills/iapl-reference/resources/api.md +++ b/docs/agent/skills/iapl-reference/resources/api.md @@ -872,6 +872,9 @@ Bin: `iapl-doctor` (`pnpm exec iapl-doctor [dir] [--json] [--md] [--strict] [--f | `runDeepProbe(ctx)` | `@intecion/ipal-kit/doctor` | `pnpm exec payload run …/dist/modules/doctor/probe.js` in the project → `DoctorStatus`. | | `collectDoctorStatus(payload)` | `@intecion/ipal-kit/doctor` | Read-only counts: `usersWithout2fa`, `pendingCookies`, `plugin`, `node`. | | `buildDoctorEndpoint({ tokenVar, access })` | `@intecion/ipal-kit/doctor` | `GET /ipal/doctor` (`/api/ipal/doctor`): 404 until the token variable (default `IAPL_DOCTOR_TOKEN`, ≥ 32 chars) is set, Bearer token or `access`, rate-limited. Added by `iapl` unless `doctor: false`. | +| `jobsRunAccess({ secretVar? })` | `@intecion/ipal-kit` | The rule iapl puts on `jobs.access.run` when the project writes none: `cronSecretMatches(req, process.env[secretVar])` or an admin with the second factor. Reuse it in your own rule: `run: (a) => jobsRunAccess()(a) \|\| myCheck(a)`. Type `JobsRunAccessOptions`. | +| `withJobsRunAccess(config, options \| false)` / `jobsRunNotice(config)` | `@intecion/ipal-kit` | The config with that rule (only when `jobs.access.run` is missing; marks `custom.iapl.jobsRunDefault`); the start-up line when the queue is on and the secret is missing (null otherwise). | +| `cronSecretMatches(req, secret)`, `CRON_SECRET_ENV`, `CRON_SECRET_MIN_LENGTH` | `@intecion/ipal-kit` | `Authorization: Bearer ` compared in constant time; an unset or shorter-than-16 secret never matches. Default variable `CRON_SECRET`. | | `runRouteCheck({ config, appDir?, snapshot?, update?, graphql?, cwd?, log? })` | `@intecion/ipal-kit/doctor` | `routes:check`: every public route (REST, GraphQL, Next route files) against the judged snapshot (default `e2e/routes.snapshot.json`); returns 1 on a route nobody judged or an entry without a reason; `update` writes new routes with an empty reason. Template: `iapl-audit/resources/routes.template.ts` (security.md "Routes nobody has judged"). Type `RunRouteCheckOptions`. | | `listPublicRoutes(config, { graphqlSchema?, routeFiles? })` | `@intecion/ipal-kit` | Stable ids of every door a built config opens: `GET /api/users/me`, `graphql mutation loginUser`, `next GET /sitemap.xml`. From the config only (same on every database). Types `RouteInventoryOptions`, `GraphqlSchemaLike` (`getQueryType` / `getMutationType`). | | `listNextRouteFiles(files, read)` | `@intecion/ipal-kit` | Next route handlers of an app directory (`route.ts` with the methods it exports, `robots.ts`, `sitemap.ts`, `manifest.ts`; route groups left out). | diff --git a/docs/agent/skills/iapl-upgrade/SKILL.md b/docs/agent/skills/iapl-upgrade/SKILL.md index 4ab83b2..97a3fd1 100644 --- a/docs/agent/skills/iapl-upgrade/SKILL.md +++ b/docs/agent/skills/iapl-upgrade/SKILL.md @@ -25,6 +25,15 @@ the MANDATORY SET (GEO: llms-full, Markdown, MCP; R2; Turnstile through `getTurnstileConfig`…). Wire each one according to PROGRAMISTA §2 — it is part of the update, not an extra. Skip one only with a client decision in `AGENTS.md` (`iapl-audit-skip:`). +**→ 1.17.2:** (1) Payload jobs: if the project has tasks or workflows and a cron calls `/api/payload-jobs/run` (or +`/handle-schedules`) without its own `jobs.access.run`, set `CRON_SECRET` (16+ characters) in the app's environment +and send `Authorization: Bearer ` from the cron; in-process runs (`jobs.autoRun`, `payload jobs:run`) +and an admin's API key need nothing (security.md "Payload's job queue"). Verify: the run route answers 401 without +the header, 200 with it. (2) A front end that posted to `/api/form-submissions` as a customer account (not through +`submitForm`): move it to `submitForm` / `createSubmitAction`, or set `forms.formSubmissionOverrides.access.create`. +(3) A site with a visitor login collection: `iapl-doctor --url …` lists `visitor-writes`; give each listed collection +and global its own write rule (`adminOrEditor`). (4) If the project has `tests/routes.ts`: `update`, judge, commit. + **→ 1.17.1:** (1) `src/proxy.ts`: replace the matcher literal with `['/((?!(?:api|admin|_next)(?:/|$)|.*\\..*).*)']` (i18n.md "Next matcher"; `iapl-doctor` rule `proxy-matcher`). The old one skipped every page whose first segment only starts with `api`, `admin` or `_next` (`/administracja`): diff --git a/docs/doctor.md b/docs/doctor.md index 83a6793..275d7eb 100644 --- a/docs/doctor.md +++ b/docs/doctor.md @@ -101,6 +101,7 @@ Turn off: `iapl({ doctor: false })`. Adapt: `iapl({ doctor: { tokenVar: 'MY_TOKE | | `env-live` | error | (deep) the project's env rules pass in the real environment | | security | `security-headers` | error | `buildSecurityHeaders`; live: HSTS, nosniff, Referrer-Policy, Permissions-Policy, frame protection | | | `powered-by` | error | `withSecurityConfig`; live: no `X-Powered-By` on `/` and the admin | +| | `visitor-writes` | warning | (deep) on a site with a visitor login collection (an auth collection that is not staff): every collection whose `create` / `update` / `delete`, or global whose `update`, lets such an account in — Payload's default "any signed-in account" included. Give it its own rule (`adminOrEditor`, …); asked by behaviour, never by a rule's name (1.17.2) | | | `proxy-matcher` | warning | `src/proxy.ts`: a matcher that skips `api`, `admin` or `_next` without ending them at "/" (`(?!api|admin|…)`) also skips every page whose first segment only starts with them (`/administracja`): no locale redirect, no proxy CSP. Fix: the literal in i18n.md (1.17.1) | | | `client-hints` | info | `withSecurityConfig` is the outer wrapper (`withSecurityConfig(withPayload(…))`), so Payload's colour-scheme client hints go to the admin only; live: `/` sends no `Critical-CH: Sec-CH-Prefers-Color-Scheme`. Not reported with `adminClientHints: false` | | | `csp` | warning / info | CSP on the site and the admin; report-only is info, a warning after 4 weeks (`seen`) | diff --git a/docs/env.md b/docs/env.md index bb9a75f..2d38697 100644 --- a/docs/env.md +++ b/docs/env.md @@ -113,7 +113,8 @@ finding the names it was written for. Both accept both spellings in the environm The plugin also reads (outside the preset — add your own rules if you want to validate them): `INDEXNOW_KEY` (seo.md), `IAPL_NOINDEX` (`1`/`true`/`yes` — staging, seo.md), `IAPL_DOCTOR_TOKEN` (≥ 32 characters — -turns `GET /api/ipal/doctor` on, doctor.md). Full table: +turns `GET /api/ipal/doctor` on, doctor.md), `CRON_SECRET` (≥ 16 characters — a cron runs Payload's job queue over +HTTP with `Authorization: Bearer `, security.md "Payload's job queue"). Full table: [deployment.md](./deployment.md). Extending with your own variables — spread: diff --git a/docs/forms.md b/docs/forms.md index 21787af..0e94ac9 100644 --- a/docs/forms.md +++ b/docs/forms.md @@ -547,7 +547,7 @@ then does it store. A flood dies before it touches the network or the database. **REST is closed.** By default the form-builder lets anyone create submissions through `POST /api/form-submissions` — skipping all the gates below. IAPL -sets `access.create` of the `form-submissions` collection to "logged-in users only"; the front end +sets `access.create` of the `form-submissions` collection to "a staff account with its second factor" (since 1.17.2; before: any signed-in account, a customer of a visitor login collection included); the front end submits through `submitForm` (server action → Local API), so this does not affect it. A deliberately public REST (e.g. an external app) → `forms: { formSubmissionOverrides: { access: { create: () => true } } }` — then @@ -861,7 +861,7 @@ filter it out on the client. - **Turn off:** without the `forms` option the plugin does not wire the form-builder (no Forms / Form Submissions collections). Single field types: `forms.fields.: false`. Files: `forms.attachments` is off unless you set it ("Files"). - **Override the collections:** `formOverrides` / `formSubmissionOverrides` — fields (the `fields` function), `labels`, - `admin`, `access`, `hooks`. The default submissions access (`create`: logged-in users, `read`: editor+, `delete`: admin) + `admin`, `access`, `hooks`. The default submissions access (`create`: a staff account with its second factor since 1.17.2, `read`: editor+, `delete`: admin) is overridden by keys in `formSubmissionOverrides.access`; forms access (`create`/`update`/`delete`: editor+, `read`: public) — in `formOverrides.access`. The Emails tab protection (`read`: editor+) is applied to the default fields **before** `formOverrides.fields`, so you change it there. diff --git a/docs/security.md b/docs/security.md index 188c088..3d8144d 100644 --- a/docs/security.md +++ b/docs/security.md @@ -1197,6 +1197,40 @@ a root endpoint to the config and the check names it as "not judged". **In the plugin repository:** `pnpm routes:check` (`--update` after a Payload upgrade) on the reference site, also the first step of `pnpm e2e:built`; the test fixtures are switched off for it. +## Payload's job queue (`jobsRunAccess`, 1.17.2) + +Payload runs its queue over HTTP at `GET /api/payload-jobs/run` and `/api/payload-jobs/handle-schedules`, checked by +`jobs.access.run`. Payload's default is **any signed-in account of any auth collection** — a shop's customer could +run the queue whenever they like. Since 1.17.2, when the project writes **no** `jobs.access.run`, iapl sets: an +**admin signed in with the second factor** (an admin's API key counts), or **`Authorization: Bearer `** +(16+ characters, compared in constant time). It is set even when the config has no `jobs` (Payload turns the queue on +by itself for scheduled publishing). A route that does not exist (no tasks, no workflows) stays 404. + +**A project with jobs keeps its cron working** — check which of these it uses: +- jobs run **in-process** (`jobs.autoRun`, `pnpm payload jobs:run`, `payload.jobs.run()` in code): nothing changes; +- a **Coolify scheduled task** (or any cron) that calls the run route: set `CRON_SECRET` in the app's environment and + in the task, and send the header — + `curl -fsS -H "Authorization: Bearer $CRON_SECRET" "$NEXT_PUBLIC_SERVER_URL/api/payload-jobs/run"`; +- a cron that signs in with an **admin's API key**: works as before; with a **non-admin** account's key: switch to + `CRON_SECRET`, or write your own rule; +- the project's **own** `jobs.access.run`: always wins, nothing changes. +At start, when the queue is on, the rule is iapl's and `CRON_SECRET` is missing or short, the log says so in one +line. Overrides: `iapl({ jobsRunAccess: false })` keeps Payload's default; `{ secretVar: 'MY_VAR' }` reads another +variable; `jobsRunAccess()` is exported to reuse in a rule of your own. Verify: without the header +`/api/payload-jobs/run` answers 401, with it 200 (the closed-doors spec does both on the built reference site). + +## Visitor accounts (customers, members) and Payload's default write rules + +Payload fills every missing access rule with **"any signed-in account"** — an account of a visitor login collection +included. The plugin narrows its own collections and globals and the staff accounts; **your** collections and +globals are yours to rule. On a site that has (or may get) a visitor login collection, give every collection +`create` / `update` / `delete` and every global `update` a rule of its own — the reference site and every new site +from `iapl create` do (`adminOrEditor`, since 1.17.2). `iapl-doctor --url` (deep) lists what such an account may +write (`visitor-writes`, warning), checked by behaviour: it asks every rule with a stand-in visitor account. Payload's +own `payload-locked-documents` (who edits which document) also runs on Payload's default and is listed there; a +plugin-wide default for it is planned for 2.0. Verify: the doctor shows no `visitor-writes` finding, and the +closed-doors spec's customer gets 403 on every write door. + ## Turn off, override, extend - **Stored secrets:** `secrets: { writeOnly: false }`, `secrets: { reenterOnChange: false }`; `writeOnlySecret` / diff --git a/reference/.agents/skills/iapl-audit/resources/closed-doors.spec.template.ts b/reference/.agents/skills/iapl-audit/resources/closed-doors.spec.template.ts index 816abbf..f2e8d4c 100644 --- a/reference/.agents/skills/iapl-audit/resources/closed-doors.spec.template.ts +++ b/reference/.agents/skills/iapl-audit/resources/closed-doors.spec.template.ts @@ -46,12 +46,16 @@ const DOORS: Door[] = [ { closedFor: ALL, method: 'POST', name: 'the crawler\'s call-back without its token', path: '/api/ipal/cookie-crawl/results', body: { jobId: 'x', ok: true } }, { closedFor: OUTSIDERS, method: 'POST', name: 'a crawl without the schedule\'s token', path: '/api/ipal/cookie-crawl' }, { closedFor: OUTSIDERS, name: 'form submissions', path: '/api/form-submissions' }, + // IAPL 1.17.2: a staff account only; an open door answers 400 (validation) instead of 403 + { body: { form: NO_ID, submissionData: [] }, closedFor: OUTSIDERS, method: 'POST', name: 'a submission past submitForm', path: '/api/form-submissions', closed: status(403) }, { body: { email: 'door@example.com', password: 'Door-Password-1234', roles: ['admin'] }, closedFor: ALL, method: 'POST', name: 'nobody creates a staff account', path: '/api/users', closed: status(403) }, { body: { email: 'first@example.com', password: 'Door-Password-1234' }, closedFor: ALL, method: 'POST', name: 'the first-user route once an account exists', path: '/api/users/first-register', closed: status(403) }, { body: {}, closedFor: OUTSIDERS, method: 'POST', name: 'Site settings cannot be saved', path: '/api/globals/site-settings', closed: status(403) }, { closedFor: ALL, name: 'the GraphQL playground (production)', path: '/api/graphql-playground', closed: status(404) }, { closedFor: ALL, graphql: '{ __schema { queryType { name } } }', closed: ({ body }) => Boolean((body as { errors?: unknown[] })?.errors?.length), name: 'GraphQL introspection (production)' }, - { closedFor: ALL, name: 'Payload\'s job queue (a site without jobs)', path: '/api/payload-jobs/run', closed: status(404) }, + // a site without jobs: 404. A site WITH jobs (IAPL 1.17.2): refused (401) for everybody but an admin and + // `Authorization: Bearer ` — drop `closed: status(404)` there + { closedFor: ALL, name: 'Payload\'s job queue', path: '/api/payload-jobs/run', closed: status(404) }, // the project's own doors: add them here // { closedFor: OUTSIDERS, body: {}, method: 'PATCH', name: 'pages cannot be changed', path: `/api/pages/${NO_ID}`, closed: status(403) }, ] diff --git a/reference/.agents/skills/iapl-reference/SKILL.md b/reference/.agents/skills/iapl-reference/SKILL.md index 878dad2..a1b2eeb 100644 --- a/reference/.agents/skills/iapl-reference/SKILL.md +++ b/reference/.agents/skills/iapl-reference/SKILL.md @@ -93,7 +93,7 @@ description: Complete map of everything @intecion/ipal-kit provides — every ia | `forms.adminGroup` | `'Forms'` | sidebar group | `false` = Payload default; `admin.group` in overrides wins | | `forms.fields.*` | on: `checkbox`, `checkboxGroup`, `country`, `date`, `email`, `message`, `number`, `radio`, `select`, `state`, `step`, `text`, `textarea`, `time`; off: `payment` | block types in the builder (all with "Show only when") | `: false`; a block object replaces it; `payment: true` **does nothing** (filtered out) — pass a block object | | `forms.formOverrides` | Form/Forms labels, `emails` readable by logged-in users only | overrides the `forms` collection (`fields: ({ defaultFields }) => …`, `slug`, `admin`, `access`…) | any `CollectionConfig` | -| `forms.formSubmissionOverrides` | create: logged-in, read: editor+, delete: admin | overrides `form-submissions` | `access.create` etc. wins | +| `forms.formSubmissionOverrides` | create: a staff account with its second factor (since 1.17.2; before: any signed-in account), read: editor+, delete: admin | overrides `form-submissions` | `access.create` etc. wins | | `forms.redirectRelationships` | none | collections a form can redirect to | `['pages']` | | `forms.emailLayout` | `false` | `beforeEmail` with a layout (logo, colour, footer) + Site settings → **Emails** tab; `{{*:table}}` readable | `true` | | `forms.beforeEmail` | none | your own e-mail changes (after the layout) | form-builder function | @@ -102,6 +102,7 @@ description: Complete map of everything @intecion/ipal-kit provides — every ia | `forms.consentFieldName` | `'consent'` | name of the GDPR consent field `submitForm` requires (read from `config.custom.ipal`) | `createSubmitAction({ consentFieldName })` / `submitForm` argument wins | | `consentLog` | **on** (since 1.17.0) | `consent-records` collection + `POST /api/ipal/consent` (rate limit 20/min); Postgres / SQLite: a table, migration in the same deploy | `false` / `{ retentionDays }` (default 1095) | | `consentLog.collectionOverrides` | none | changes `consent-records`: an object merges `access` / `admin` / `hooks` key by key (your keys win), a function `(collection) => collection` takes over (keep the slug) | e.g. `{ access: { read: ({ req }) => req.user?.email === 'dpo@acme.pl' } }` — narrows who reads records in a project without roles | +| `jobsRunAccess` | on (since 1.17.2), only when the project writes no `jobs.access.run` | Payload's job queue over HTTP (`/api/payload-jobs/run`, `/handle-schedules`): an admin with the second factor (an admin API key counts) or `Authorization: Bearer ` (16+ chars); before: any signed-in account of any auth collection. In-process runs (`jobs.autoRun`, `payload jobs:run`) unaffected | `false` = Payload's default; `{ secretVar }` = another variable; your own `jobs.access.run` wins. Check: `curl -H "Authorization: Bearer $CRON_SECRET" $URL/api/payload-jobs/run` → 200, without it 401 (security.md "Payload's job queue") | | `doctor` | on (404 until `IAPL_DOCTOR_TOKEN` is set) | `GET /api/ipal/doctor` — read-only counts for `iapl-doctor --url` (users without TOTP, cookies waiting for approval, versions); Bearer token ≥ 32 characters, rate-limited, never names or values | `false` = no endpoint; `{ tokenVar, access }` (doctor.md) | | `cookieScanner` | off | `cookie-review` collection, "Scan cookies" box above its list (`CookieScanButton`), `GET`/`POST /api/ipal/cookie-scan`, and (unless `approval: false`) the *Approve cookies* view `/admin/cookie-approval` (`CookieApprovalView`) + `GET`/`POST /api/ipal/cookie-approval` + the dashboard reminder; a scan lists the cookies of the integrations switched on + names looked up in the bundled Open Cookie Database; one **Approve and add** puts the ticked cookies into Cookies → Cookie list (so `` and the detailed window); never deletes, never overwrites edited text, never duplicates, nothing reaches the banner before approval | `true` / object; after switching on: `pnpm generate:importmap` + `migrate:create`. Check: *Privacy → Cookie review* → **Scan cookies** → "Waiting for approval: N" → **Review and approve** → **Approve and add** → the cookies are in Cookies → Cookie list (cookie-scanner.md) | | `cookieScanner.adminLayout` | `'combined'` | one *Cookies* entry: *Review and approve* and (with `crawl`) *Site check* tabs on the `cookie-settings` global (`ui` fields, `CookieReviewTab` / `CookieSiteCheckTab`); `cookie-review` and `cookie-crawl` get `admin.group: false` (out of the nav, pages and API kept) | `'separate'`; no migration, `generate:importmap` | @@ -277,6 +278,7 @@ The plugin's own variables are `IAPL_`; a deploy that sets the spelling fr | `IAPL_IP_HEADER` | `ipHeader: true` + production | rate limit trusts any IP header (spoofing) + warning in prod | env: `cf-connecting-ip` (Cloudflare) / `x-forwarded-for` (Traefik/nginx) | | `IAPL_COOKIE_SCAN_URL`, `IAPL_COOKIE_SCAN_TOKEN` | `cookieScanner.crawl` (`iaplEnvRules({ cookieCrawl: true })` requires both in production; token ≥ 16 chars) | **Check site** disabled, the box names the missing variable | env; the token also goes into the scanner service's `IAPL_CRAWLER_SITES` as `host=token` | | `IAPL_DOCTOR_TOKEN` | no; ≥ 32 characters | `GET /api/ipal/doctor` answers 404; with it the endpoint answers a Bearer token, and `iapl-doctor --url` with the same variable reads the deep counts | env (Coolify) and the doctor's shell; also read by the doctor: `CI`, `NO_COLOR`, `PAYLOAD_CONFIG_PATH` (`--deep`), `IAPL_DOCTOR_IMPORT_MAP` (internal) — doctor.md | +| `CRON_SECRET` | no; ≥ 16 characters (name: `jobsRunAccess.secretVar`) | Payload's job queue runs over HTTP only for an admin; the start log says so when the queue is on | env (Coolify); the cron sends `Authorization: Bearer ` to `/api/payload-jobs/run` | | `IAPL_NOINDEX` | no; `1`/`true`/`yes` **staging/preview only** | — (when set: robots Disallow, meta noindex, `X-Robots-Tag`, IndexNow sends nothing) | staging env | | `NEXT_PHASE` | set by Next | only tells `next build` from runtime: during the build an unreachable database gives an empty sitemap; at runtime the sitemap throws (route → 503) | do not set by hand | | `NEXT_RUNTIME` | set by Next | `instrumentation.ts` checks for `nodejs`; missing (scripts, seed) → `buildRevalidateHook` does not revalidate | do not set by hand | diff --git a/reference/.agents/skills/iapl-reference/resources/api.md b/reference/.agents/skills/iapl-reference/resources/api.md index d6c9082..3c62922 100644 --- a/reference/.agents/skills/iapl-reference/resources/api.md +++ b/reference/.agents/skills/iapl-reference/resources/api.md @@ -872,6 +872,9 @@ Bin: `iapl-doctor` (`pnpm exec iapl-doctor [dir] [--json] [--md] [--strict] [--f | `runDeepProbe(ctx)` | `@intecion/ipal-kit/doctor` | `pnpm exec payload run …/dist/modules/doctor/probe.js` in the project → `DoctorStatus`. | | `collectDoctorStatus(payload)` | `@intecion/ipal-kit/doctor` | Read-only counts: `usersWithout2fa`, `pendingCookies`, `plugin`, `node`. | | `buildDoctorEndpoint({ tokenVar, access })` | `@intecion/ipal-kit/doctor` | `GET /ipal/doctor` (`/api/ipal/doctor`): 404 until the token variable (default `IAPL_DOCTOR_TOKEN`, ≥ 32 chars) is set, Bearer token or `access`, rate-limited. Added by `iapl` unless `doctor: false`. | +| `jobsRunAccess({ secretVar? })` | `@intecion/ipal-kit` | The rule iapl puts on `jobs.access.run` when the project writes none: `cronSecretMatches(req, process.env[secretVar])` or an admin with the second factor. Reuse it in your own rule: `run: (a) => jobsRunAccess()(a) \|\| myCheck(a)`. Type `JobsRunAccessOptions`. | +| `withJobsRunAccess(config, options \| false)` / `jobsRunNotice(config)` | `@intecion/ipal-kit` | The config with that rule (only when `jobs.access.run` is missing; marks `custom.iapl.jobsRunDefault`); the start-up line when the queue is on and the secret is missing (null otherwise). | +| `cronSecretMatches(req, secret)`, `CRON_SECRET_ENV`, `CRON_SECRET_MIN_LENGTH` | `@intecion/ipal-kit` | `Authorization: Bearer ` compared in constant time; an unset or shorter-than-16 secret never matches. Default variable `CRON_SECRET`. | | `runRouteCheck({ config, appDir?, snapshot?, update?, graphql?, cwd?, log? })` | `@intecion/ipal-kit/doctor` | `routes:check`: every public route (REST, GraphQL, Next route files) against the judged snapshot (default `e2e/routes.snapshot.json`); returns 1 on a route nobody judged or an entry without a reason; `update` writes new routes with an empty reason. Template: `iapl-audit/resources/routes.template.ts` (security.md "Routes nobody has judged"). Type `RunRouteCheckOptions`. | | `listPublicRoutes(config, { graphqlSchema?, routeFiles? })` | `@intecion/ipal-kit` | Stable ids of every door a built config opens: `GET /api/users/me`, `graphql mutation loginUser`, `next GET /sitemap.xml`. From the config only (same on every database). Types `RouteInventoryOptions`, `GraphqlSchemaLike` (`getQueryType` / `getMutationType`). | | `listNextRouteFiles(files, read)` | `@intecion/ipal-kit` | Next route handlers of an app directory (`route.ts` with the methods it exports, `robots.ts`, `sitemap.ts`, `manifest.ts`; route groups left out). | diff --git a/reference/.agents/skills/iapl-upgrade/SKILL.md b/reference/.agents/skills/iapl-upgrade/SKILL.md index 4ab83b2..97a3fd1 100644 --- a/reference/.agents/skills/iapl-upgrade/SKILL.md +++ b/reference/.agents/skills/iapl-upgrade/SKILL.md @@ -25,6 +25,15 @@ the MANDATORY SET (GEO: llms-full, Markdown, MCP; R2; Turnstile through `getTurnstileConfig`…). Wire each one according to PROGRAMISTA §2 — it is part of the update, not an extra. Skip one only with a client decision in `AGENTS.md` (`iapl-audit-skip:`). +**→ 1.17.2:** (1) Payload jobs: if the project has tasks or workflows and a cron calls `/api/payload-jobs/run` (or +`/handle-schedules`) without its own `jobs.access.run`, set `CRON_SECRET` (16+ characters) in the app's environment +and send `Authorization: Bearer ` from the cron; in-process runs (`jobs.autoRun`, `payload jobs:run`) +and an admin's API key need nothing (security.md "Payload's job queue"). Verify: the run route answers 401 without +the header, 200 with it. (2) A front end that posted to `/api/form-submissions` as a customer account (not through +`submitForm`): move it to `submitForm` / `createSubmitAction`, or set `forms.formSubmissionOverrides.access.create`. +(3) A site with a visitor login collection: `iapl-doctor --url …` lists `visitor-writes`; give each listed collection +and global its own write rule (`adminOrEditor`). (4) If the project has `tests/routes.ts`: `update`, judge, commit. + **→ 1.17.1:** (1) `src/proxy.ts`: replace the matcher literal with `['/((?!(?:api|admin|_next)(?:/|$)|.*\\..*).*)']` (i18n.md "Next matcher"; `iapl-doctor` rule `proxy-matcher`). The old one skipped every page whose first segment only starts with `api`, `admin` or `_next` (`/administracja`): diff --git a/reference/e2e/closed-doors.spec.ts b/reference/e2e/closed-doors.spec.ts index 7a45c3a..9d39dcf 100644 --- a/reference/e2e/closed-doors.spec.ts +++ b/reference/e2e/closed-doors.spec.ts @@ -36,7 +36,7 @@ async function signIn(caller: Caller, baseURL: string, playwright: { request: { async function ask(api: APIRequestContext, door: (typeof DOORS)[number]): Promise { const res = door.graphql ? await api.post('/api/graphql', { data: { query: door.graphql } }) - : await api.fetch(door.path!, { data: door.body, maxRedirects: 0, method: door.method ?? 'GET' }) + : await api.fetch(door.path!, { data: door.body, headers: door.headers, maxRedirects: 0, method: door.method ?? 'GET' }) const text = await res.text() let body: unknown = text try { @@ -72,6 +72,16 @@ for (const caller of ['anonymous', 'customer', 'editor'] as const) { }) } +test.describe('closed doors: the cron secret opens the job queue (IAWL idea 35, 1.17.2)', () => { + test('Authorization: Bearer runs the queue; nothing else changes', async ({ baseURL, playwright }) => { + test.skip(lateStaff !== '1' || !process.env.CRON_SECRET, 'needs the fixture\'s job queue (E2E_LATE_STAFF=1) and CRON_SECRET (pnpm e2e:built sets both)') + const cron = await playwright.request.newContext({ baseURL, extraHTTPHeaders: { authorization: `Bearer ${process.env.CRON_SECRET}` } }) + const res = await cron.get('/api/payload-jobs/run?limit=1') + expect([res.status(), await res.text()]).toEqual([200, expect.any(String)]) + await cron.dispose() + }) +}) + test.describe('closed doors: the proxy skips /api, /admin and /_next as whole segments only (IAWL idea 36)', () => { test('the admin and the API are not sent to a locale; a page that only starts with those letters is', async ({ request }) => { for (const path of ['/admin', '/api/health']) { diff --git a/reference/e2e/closed-doors.ts b/reference/e2e/closed-doors.ts index 8a5b09f..13e3a0a 100644 --- a/reference/e2e/closed-doors.ts +++ b/reference/e2e/closed-doors.ts @@ -24,6 +24,8 @@ export type Door = { closed?: (answer: DoorAnswer, ctx: { email?: string }) => boolean closedFor: Caller[] graphql?: string + /** Extra request headers (e.g. a wrong bearer token). */ + headers?: Record method?: 'DELETE' | 'GET' | 'PATCH' | 'POST' name: string /** Open for these callers while the owner decides (the finding's question). */ @@ -56,7 +58,11 @@ export const DOORS: Door[] = [ { closedFor: ALL, name: 'the deep doctor status answers 404 without its token', path: '/api/ipal/doctor', closed: notFound }, // ---- jobs, schedules and call-backs (IAWL idea 35) --------------------------------------------------------- - { closedFor: ALL, name: 'Payload\'s job queue has no run route (no jobs on this site)', path: '/api/payload-jobs/run', closed: notFound }, + // the fixture's do-nothing task turns the queue on; since 1.17.2 (owner's Q2) only an admin or Bearer CRON_SECRET runs it + // (the "with the secret" case is its own test in closed-doors.spec.ts). Payload answers 401 when refused. + { closedFor: ALL, name: 'Payload\'s job queue cannot be run (only an admin or the cron secret)', path: '/api/payload-jobs/run' }, + { closedFor: ALL, name: 'Payload\'s job schedules cannot be handled (only an admin or the cron secret)', path: '/api/payload-jobs/handle-schedules' }, + { closedFor: ALL, name: 'a wrong cron secret runs nothing', path: '/api/payload-jobs/run', headers: { authorization: 'Bearer not-the-cron-secret-not-the-cron-secret' } }, { closedFor: ALL, method: 'POST', name: 'the crawler\'s call-back without its token', path: '/api/ipal/cookie-crawl/results', body: { jobId: 'x', ok: true } }, { closedFor: OUTSIDERS, method: 'POST', name: 'a crawl cannot be started without the schedule\'s token', path: '/api/ipal/cookie-crawl' }, { closedFor: OUTSIDERS, name: 'the crawl status', path: '/api/ipal/cookie-crawl' }, @@ -94,30 +100,21 @@ export const DOORS: Door[] = [ // ---- content and visitors' data -------------------------------------------------------------------------- { closedFor: OUTSIDERS, name: 'form submissions (visitors\' personal data)', path: '/api/form-submissions' }, { closedFor: OUTSIDERS, graphql: '{ FormSubmissions { docs { id } } }', closed: noData('FormSubmissions'), name: 'form submissions over GraphQL' }, - { - body: { form: NO_ID, submissionData: [] }, - closedFor: ['anonymous'], - method: 'POST', - name: 'a submission cannot be posted past submitForm (rate limit, Turnstile, consent, validation)', - openFor: { callers: ['customer'], question: 'Q1 (iawl-ideas-c-findings.md): any signed-in account may POST /api/form-submissions' }, - path: '/api/form-submissions', - closed: forbidden, - }, + // since 1.17.2 (owner's Q1): a staff account with its second factor only — an editor may (it reaches validation) + { body: { form: NO_ID, submissionData: [] }, closedFor: OUTSIDERS, method: 'POST', name: 'a submission cannot be posted past submitForm (rate limit, Turnstile, consent, validation)', path: '/api/form-submissions', closed: forbidden }, { body: {}, closedFor: OUTSIDERS, method: 'POST', name: 'Site settings cannot be saved', path: '/api/globals/site-settings', closed: forbidden }, { body: {}, closedFor: OUTSIDERS, method: 'POST', name: 'Cookie settings (legal texts) cannot be saved', path: '/api/globals/cookie-settings', closed: forbidden }, - { - body: {}, - closedFor: ['anonymous'], - method: 'PATCH', - name: 'pages cannot be changed', - openFor: { callers: ['customer'], question: 'Q3: collections without their own write rules run on Payload\'s default (any signed-in account)' }, - path: `/api/pages/${NO_ID}`, - closed: forbidden, - }, + // the reference site's content has write rules of its own since 1.17.2 (owner's Q3, answer (b)): editors and admins + { body: {}, closedFor: OUTSIDERS, method: 'PATCH', name: 'pages cannot be changed', path: `/api/pages/${NO_ID}`, closed: forbidden }, + { body: {}, closedFor: OUTSIDERS, method: 'PATCH', name: 'media cannot be changed', path: `/api/media/${NO_ID}`, closed: forbidden }, + { body: {}, closedFor: OUTSIDERS, method: 'POST', name: 'the header (navigation) cannot be saved', path: '/api/globals/header', closed: forbidden }, + { body: {}, closedFor: OUTSIDERS, method: 'POST', name: 'the company data cannot be saved', path: '/api/globals/company', closed: forbidden }, { closedFor: ['anonymous'], name: 'who edits what (Payload\'s document locks, with the editor\'s account)', - openFor: { callers: ['customer'], question: 'Q3: payload-locked-documents runs on Payload\'s default (any signed-in account)' }, + // Payload's own collection: the plugin-wide default for it is the owner's Q3 answer (a), recorded for 2.0; the doctor's + // `visitor-writes` rule lists it on a site with a visitor login collection + openFor: { callers: ['customer'], question: 'Q3 (a), 2.0: payload-locked-documents runs on Payload\'s default (any signed-in account)' }, path: '/api/payload-locked-documents', closed: forbidden, }, diff --git a/reference/e2e/late-staff-fixture.ts b/reference/e2e/late-staff-fixture.ts index 025bcf3..e6a835a 100644 --- a/reference/e2e/late-staff-fixture.ts +++ b/reference/e2e/late-staff-fixture.ts @@ -20,6 +20,9 @@ export const e2eEarlyStaff: Plugin = (config: Config) => E2E_LATE_STAFF ? { ...config, + // one do-nothing task turns Payload's job queue on, so the closed-doors spec can ask its run route + // (no `jobs.access.run` here: iapl's default applies — an admin with the second factor, or Bearer CRON_SECRET) + jobs: { ...config.jobs, tasks: [...(config.jobs?.tasks ?? []), { slug: 'e2eNoop', handler: () => ({ output: {} }) }] }, collections: [ ...(config.collections ?? []), { slug: 'e2e-crew', auth: true, fields: [{ name: 'roles', type: 'select', hasMany: true, options: ['user', 'editor', 'admin', 'boss'], saveToJWT: true }] }, diff --git a/reference/e2e/routes.snapshot.json b/reference/e2e/routes.snapshot.json index 5c2786a..a674b7f 100644 --- a/reference/e2e/routes.snapshot.json +++ b/reference/e2e/routes.snapshot.json @@ -1,29 +1,29 @@ { "$comment": "Every public door of this site: REST routes, GraphQL operations, Next route files. One line per entry: who may use it and why it is open (or that it is closed and to whom). A new route fails `routes:check` until somebody judges it here. `--update` adds new routes with an empty reason and drops gone ones. docs/security.md \"Routes nobody has judged\".", "routes": { - "DELETE /api/caseStudies": "delete: Payload default (any signed-in account; one login collection here, so staff only — a visitor collection would reach it: owner Q3)", - "DELETE /api/caseStudies/:id": "deleteByID: Payload default (any signed-in account; one login collection here, so staff only — a visitor collection would reach it: owner Q3)", + "DELETE /api/caseStudies": "delete: editor+ (adminOrEditor, the site's own rule since 1.17.2; Payload's default would let any signed-in account in)", + "DELETE /api/caseStudies/:id": "deleteByID: editor+ (adminOrEditor, the site's own rule since 1.17.2; Payload's default would let any signed-in account in)", "DELETE /api/consent-records": "delete: nobody over the API (create/update false); delete: admin; visitors write through POST /api/ipal/consent", "DELETE /api/consent-records/:id": "deleteByID: nobody over the API (create/update false); delete: admin; visitors write through POST /api/ipal/consent", "DELETE /api/cookie-review": "delete: create/update: editor+; delete: admin", "DELETE /api/cookie-review/:id": "deleteByID: create/update: editor+; delete: admin", - "DELETE /api/form-submissions": "delete: create: any signed-in account (owner Q1); update: Payload default; delete: admin", - "DELETE /api/form-submissions/:id": "deleteByID: create: any signed-in account (owner Q1); update: Payload default; delete: admin", + "DELETE /api/form-submissions": "delete: create: a staff account with its second factor (1.17.2; the site submits through submitForm); update: nobody (form-builder); delete: admin", + "DELETE /api/form-submissions/:id": "deleteByID: create: a staff account with its second factor (1.17.2; the site submits through submitForm); update: nobody (form-builder); delete: admin", "DELETE /api/forms": "delete: editor+ (staffAccess)", "DELETE /api/forms/:id": "deleteByID: editor+ (staffAccess)", - "DELETE /api/media": "delete: Payload default (any signed-in account; one login collection here, so staff only — a visitor collection would reach it: owner Q3)", - "DELETE /api/media/:id": "deleteByID: Payload default (any signed-in account; one login collection here, so staff only — a visitor collection would reach it: owner Q3)", - "DELETE /api/pages": "delete: Payload default (any signed-in account; one login collection here, so staff only — a visitor collection would reach it: owner Q3)", - "DELETE /api/pages/:id": "deleteByID: Payload default (any signed-in account; one login collection here, so staff only — a visitor collection would reach it: owner Q3)", + "DELETE /api/media": "delete: editor+ (adminOrEditor, the site's own rule since 1.17.2; Payload's default would let any signed-in account in)", + "DELETE /api/media/:id": "deleteByID: editor+ (adminOrEditor, the site's own rule since 1.17.2; Payload's default would let any signed-in account in)", + "DELETE /api/pages": "delete: editor+ (adminOrEditor, the site's own rule since 1.17.2; Payload's default would let any signed-in account in)", + "DELETE /api/pages/:id": "deleteByID: editor+ (adminOrEditor, the site's own rule since 1.17.2; Payload's default would let any signed-in account in)", "DELETE /api/payload-kv": "delete: nobody (every rule false)", "DELETE /api/payload-kv/:id": "deleteByID: nobody (every rule false)", - "DELETE /api/payload-locked-documents": "delete: Payload default: any signed-in account (owner Q3)", - "DELETE /api/payload-locked-documents/:id": "deleteByID: Payload default: any signed-in account (owner Q3)", + "DELETE /api/payload-locked-documents": "delete: Payload default: any signed-in account (the plugin-wide default is owner's Q3 (a), 2.0; the doctor's visitor-writes lists it)", + "DELETE /api/payload-locked-documents/:id": "deleteByID: Payload default: any signed-in account (the plugin-wide default is owner's Q3 (a), 2.0; the doctor's visitor-writes lists it)", "DELETE /api/payload-preferences": "delete: own preferences only (Payload)", "DELETE /api/payload-preferences/:id": "deleteByID: own preferences only (Payload)", "DELETE /api/payload-preferences/:key": "deleteByID: own preferences only (Payload)", - "DELETE /api/posts": "delete: Payload default (any signed-in account; one login collection here, so staff only — a visitor collection would reach it: owner Q3)", - "DELETE /api/posts/:id": "deleteByID: Payload default (any signed-in account; one login collection here, so staff only — a visitor collection would reach it: owner Q3)", + "DELETE /api/posts": "delete: editor+ (adminOrEditor, the site's own rule since 1.17.2; Payload's default would let any signed-in account in)", + "DELETE /api/posts/:id": "deleteByID: editor+ (adminOrEditor, the site's own rule since 1.17.2; Payload's default would let any signed-in account in)", "DELETE /api/users": "delete: create/delete/unlock: an admin with the second factor; update: admin or self; roles field: admin", "DELETE /api/users/:id": "deleteByID: create/delete/unlock: an admin with the second factor; update: admin or self; roles field: admin", "GET /api/access": "Payload: the signed-in account's permissions (what the panel may show); anonymous gets an empty map", @@ -101,11 +101,11 @@ "GET /api/payload-kv/count": "count: nobody (Payload: every rule false; the plugin keeps 2FA counts and the mail-service token here)", "GET /api/payload-kv/versions": "versions: readVersions = read (nobody (Payload: every rule false; the plugin keeps 2FA counts and the mail-service token here)); no version history kept here", "GET /api/payload-kv/versions/:id": "versionByID: readVersions = read (nobody (Payload: every rule false; the plugin keeps 2FA counts and the mail-service token here)); no version history kept here", - "GET /api/payload-locked-documents": "find: Payload default: any signed-in account (owner Q3)", - "GET /api/payload-locked-documents/:id": "findByID: Payload default: any signed-in account (owner Q3)", - "GET /api/payload-locked-documents/count": "count: Payload default: any signed-in account (owner Q3)", - "GET /api/payload-locked-documents/versions": "versions: readVersions = read (Payload default: any signed-in account (owner Q3)); no version history kept here", - "GET /api/payload-locked-documents/versions/:id": "versionByID: readVersions = read (Payload default: any signed-in account (owner Q3)); no version history kept here", + "GET /api/payload-locked-documents": "find: Payload default: any signed-in account (the plugin-wide default is owner's Q3 (a), 2.0; the doctor's visitor-writes lists it)", + "GET /api/payload-locked-documents/:id": "findByID: Payload default: any signed-in account (the plugin-wide default is owner's Q3 (a), 2.0; the doctor's visitor-writes lists it)", + "GET /api/payload-locked-documents/count": "count: Payload default: any signed-in account (the plugin-wide default is owner's Q3 (a), 2.0; the doctor's visitor-writes lists it)", + "GET /api/payload-locked-documents/versions": "versions: readVersions = read (Payload default: any signed-in account (the plugin-wide default is owner's Q3 (a), 2.0; the doctor's visitor-writes lists it)); no version history kept here", + "GET /api/payload-locked-documents/versions/:id": "versionByID: readVersions = read (Payload default: any signed-in account (the plugin-wide default is owner's Q3 (a), 2.0; the doctor's visitor-writes lists it)); no version history kept here", "GET /api/payload-preferences": "find: the signed-in account's own preferences only (Payload)", "GET /api/payload-preferences/:id": "findByID: the signed-in account's own preferences only (Payload)", "GET /api/payload-preferences/:key": "findByID: the signed-in account's own preferences only (Payload)", @@ -124,36 +124,36 @@ "GET /api/users/me": "Payload: the signed-in account itself, or null; no other account", "GET /api/users/versions": "versions: readVersions = read (an admin, or the account itself (adminOrSelfIn users)); no version history kept here", "GET /api/users/versions/:id": "versionByID: readVersions = read (an admin, or the account itself (adminOrSelfIn users)); no version history kept here", - "PATCH /api/caseStudies": "update: Payload default (any signed-in account; one login collection here, so staff only — a visitor collection would reach it: owner Q3)", - "PATCH /api/caseStudies/:id": "updateByID: Payload default (any signed-in account; one login collection here, so staff only — a visitor collection would reach it: owner Q3)", + "PATCH /api/caseStudies": "update: editor+ (adminOrEditor, the site's own rule since 1.17.2; Payload's default would let any signed-in account in)", + "PATCH /api/caseStudies/:id": "updateByID: editor+ (adminOrEditor, the site's own rule since 1.17.2; Payload's default would let any signed-in account in)", "PATCH /api/consent-records": "update: nobody over the API (create/update false); delete: admin; visitors write through POST /api/ipal/consent", "PATCH /api/consent-records/:id": "updateByID: nobody over the API (create/update false); delete: admin; visitors write through POST /api/ipal/consent", "PATCH /api/cookie-review": "update: create/update: editor+; delete: admin", "PATCH /api/cookie-review/:id": "updateByID: create/update: editor+; delete: admin", - "PATCH /api/form-submissions": "update: create: any signed-in account (owner Q1); update: Payload default; delete: admin", - "PATCH /api/form-submissions/:id": "updateByID: create: any signed-in account (owner Q1); update: Payload default; delete: admin", + "PATCH /api/form-submissions": "update: create: a staff account with its second factor (1.17.2; the site submits through submitForm); update: nobody (form-builder); delete: admin", + "PATCH /api/form-submissions/:id": "updateByID: create: a staff account with its second factor (1.17.2; the site submits through submitForm); update: nobody (form-builder); delete: admin", "PATCH /api/forms": "update: editor+ (staffAccess)", "PATCH /api/forms/:id": "updateByID: editor+ (staffAccess)", - "PATCH /api/media": "update: Payload default (any signed-in account; one login collection here, so staff only — a visitor collection would reach it: owner Q3)", - "PATCH /api/media/:id": "updateByID: Payload default (any signed-in account; one login collection here, so staff only — a visitor collection would reach it: owner Q3)", - "PATCH /api/pages": "update: Payload default (any signed-in account; one login collection here, so staff only — a visitor collection would reach it: owner Q3)", - "PATCH /api/pages/:id": "updateByID: Payload default (any signed-in account; one login collection here, so staff only — a visitor collection would reach it: owner Q3)", + "PATCH /api/media": "update: editor+ (adminOrEditor, the site's own rule since 1.17.2; Payload's default would let any signed-in account in)", + "PATCH /api/media/:id": "updateByID: editor+ (adminOrEditor, the site's own rule since 1.17.2; Payload's default would let any signed-in account in)", + "PATCH /api/pages": "update: editor+ (adminOrEditor, the site's own rule since 1.17.2; Payload's default would let any signed-in account in)", + "PATCH /api/pages/:id": "updateByID: editor+ (adminOrEditor, the site's own rule since 1.17.2; Payload's default would let any signed-in account in)", "PATCH /api/payload-kv": "update: nobody (every rule false)", "PATCH /api/payload-kv/:id": "updateByID: nobody (every rule false)", - "PATCH /api/payload-locked-documents": "update: Payload default: any signed-in account (owner Q3)", - "PATCH /api/payload-locked-documents/:id": "updateByID: Payload default: any signed-in account (owner Q3)", + "PATCH /api/payload-locked-documents": "update: Payload default: any signed-in account (the plugin-wide default is owner's Q3 (a), 2.0; the doctor's visitor-writes lists it)", + "PATCH /api/payload-locked-documents/:id": "updateByID: Payload default: any signed-in account (the plugin-wide default is owner's Q3 (a), 2.0; the doctor's visitor-writes lists it)", "PATCH /api/payload-preferences": "update: own preferences only (Payload)", "PATCH /api/payload-preferences/:id": "updateByID: own preferences only (Payload)", - "PATCH /api/posts": "update: Payload default (any signed-in account; one login collection here, so staff only — a visitor collection would reach it: owner Q3)", - "PATCH /api/posts/:id": "updateByID: Payload default (any signed-in account; one login collection here, so staff only — a visitor collection would reach it: owner Q3)", + "PATCH /api/posts": "update: editor+ (adminOrEditor, the site's own rule since 1.17.2; Payload's default would let any signed-in account in)", + "PATCH /api/posts/:id": "updateByID: editor+ (adminOrEditor, the site's own rule since 1.17.2; Payload's default would let any signed-in account in)", "PATCH /api/users": "update: create/delete/unlock: an admin with the second factor; update: admin or self; roles field: admin", "PATCH /api/users/:id": "updateByID: create/delete/unlock: an admin with the second factor; update: admin or self; roles field: admin", "POST /api/admin/remove-user-totp": "2FA: an admin removes another account's second factor", "POST /api/admin/reset-user-totp": "2FA: an admin resets another account's second factor", - "POST /api/caseStudies": "create: Payload default (any signed-in account; one login collection here, so staff only — a visitor collection would reach it: owner Q3)", - "POST /api/caseStudies/:id/duplicate": "duplicate: Payload default (any signed-in account; one login collection here, so staff only — a visitor collection would reach it: owner Q3)", + "POST /api/caseStudies": "create: editor+ (adminOrEditor, the site's own rule since 1.17.2; Payload's default would let any signed-in account in)", + "POST /api/caseStudies/:id/duplicate": "duplicate: editor+ (adminOrEditor, the site's own rule since 1.17.2; Payload's default would let any signed-in account in)", "POST /api/caseStudies/access/:id?": "the signed-in account's own permissions on caseStudies", - "POST /api/caseStudies/versions/:id": "restore a version: Payload default (any signed-in account; one login collection here, so staff only — a visitor collection would reach it: owner Q3)", + "POST /api/caseStudies/versions/:id": "restore a version: editor+ (adminOrEditor, the site's own rule since 1.17.2; Payload's default would let any signed-in account in)", "POST /api/consent-records": "create: nobody over the API (create/update false); delete: admin; visitors write through POST /api/ipal/consent", "POST /api/consent-records/:id/duplicate": "duplicate: nobody over the API (create/update false); delete: admin; visitors write through POST /api/ipal/consent", "POST /api/consent-records/access/:id?": "the signed-in account's own permissions on consent-records", @@ -162,29 +162,29 @@ "POST /api/cookie-review/:id/duplicate": "duplicate: create/update: editor+; delete: admin", "POST /api/cookie-review/access/:id?": "the signed-in account's own permissions on cookie-review", "POST /api/cookie-review/versions/:id": "restore a version: create/update: editor+; delete: admin", - "POST /api/form-submissions": "create: create: any signed-in account (owner Q1); update: Payload default; delete: admin", - "POST /api/form-submissions/:id/duplicate": "duplicate: create: any signed-in account (owner Q1); update: Payload default; delete: admin", + "POST /api/form-submissions": "create: a staff account with its second factor (1.17.2; the site submits through submitForm); update: nobody (form-builder); delete: admin", + "POST /api/form-submissions/:id/duplicate": "duplicate: create: a staff account with its second factor (1.17.2; the site submits through submitForm); update: nobody (form-builder); delete: admin", "POST /api/form-submissions/access/:id?": "the signed-in account's own permissions on form-submissions", - "POST /api/form-submissions/versions/:id": "restore a version: create: any signed-in account (owner Q1); update: Payload default; delete: admin", + "POST /api/form-submissions/versions/:id": "restore a version: create: a staff account with its second factor (1.17.2; the site submits through submitForm); update: nobody (form-builder); delete: admin", "POST /api/forms": "create: editor+ (staffAccess)", "POST /api/forms/:id/duplicate": "duplicate: editor+ (staffAccess)", "POST /api/forms/access/:id?": "the signed-in account's own permissions on forms", "POST /api/forms/versions/:id": "restore a version: editor+ (staffAccess)", - "POST /api/globals/company": "update: Payload default (any signed-in account; one login collection here, so staff only — a visitor collection would reach it: owner Q3)", + "POST /api/globals/company": "update: editor+ (adminOrEditor, the site's own rule since 1.17.2; Payload's default would let any signed-in account in)", "POST /api/globals/company/access": "the signed-in account's own permissions on globals/company", - "POST /api/globals/company/versions/:id": "restore a version: Payload default (any signed-in account; one login collection here, so staff only — a visitor collection would reach it: owner Q3)", + "POST /api/globals/company/versions/:id": "restore a version: editor+ (adminOrEditor, the site's own rule since 1.17.2; Payload's default would let any signed-in account in)", "POST /api/globals/cookie-crawl": "update: admin; the crawl endpoints write it after their own checks", "POST /api/globals/cookie-crawl/access": "the signed-in account's own permissions on globals/cookie-crawl", "POST /api/globals/cookie-crawl/versions/:id": "restore a version: admin; the crawl endpoints write it after their own checks", "POST /api/globals/cookie-settings": "update: editor+", "POST /api/globals/cookie-settings/access": "the signed-in account's own permissions on globals/cookie-settings", "POST /api/globals/cookie-settings/versions/:id": "restore a version: editor+", - "POST /api/globals/footer": "update: Payload default (any signed-in account; one login collection here, so staff only — a visitor collection would reach it: owner Q3)", + "POST /api/globals/footer": "update: editor+ (adminOrEditor, the site's own rule since 1.17.2; Payload's default would let any signed-in account in)", "POST /api/globals/footer/access": "the signed-in account's own permissions on globals/footer", - "POST /api/globals/footer/versions/:id": "restore a version: Payload default (any signed-in account; one login collection here, so staff only — a visitor collection would reach it: owner Q3)", - "POST /api/globals/header": "update: Payload default (any signed-in account; one login collection here, so staff only — a visitor collection would reach it: owner Q3)", + "POST /api/globals/footer/versions/:id": "restore a version: editor+ (adminOrEditor, the site's own rule since 1.17.2; Payload's default would let any signed-in account in)", + "POST /api/globals/header": "update: editor+ (adminOrEditor, the site's own rule since 1.17.2; Payload's default would let any signed-in account in)", "POST /api/globals/header/access": "the signed-in account's own permissions on globals/header", - "POST /api/globals/header/versions/:id": "restore a version: Payload default (any signed-in account; one login collection here, so staff only — a visitor collection would reach it: owner Q3)", + "POST /api/globals/header/versions/:id": "restore a version: editor+ (adminOrEditor, the site's own rule since 1.17.2; Payload's default would let any signed-in account in)", "POST /api/globals/notifications": "update: editor+", "POST /api/globals/notifications/access": "the signed-in account's own permissions on globals/notifications", "POST /api/globals/notifications/versions/:id": "restore a version: editor+", @@ -205,22 +205,22 @@ "POST /api/ipal/forms/submit": "public by design: a form with files; the submitForm pipeline (rate limit, Turnstile, consent, validation, file checks)", "POST /api/ipal/test-email": "send a test e-mail: admin", "POST /api/ipal/two-factor/reset": "reset another account's 2FA set-up window: admin signed in with the second factor", - "POST /api/media": "create: Payload default (any signed-in account; one login collection here, so staff only — a visitor collection would reach it: owner Q3)", - "POST /api/media/:id/duplicate": "duplicate: Payload default (any signed-in account; one login collection here, so staff only — a visitor collection would reach it: owner Q3)", + "POST /api/media": "create: editor+ (adminOrEditor, the site's own rule since 1.17.2; Payload's default would let any signed-in account in)", + "POST /api/media/:id/duplicate": "duplicate: editor+ (adminOrEditor, the site's own rule since 1.17.2; Payload's default would let any signed-in account in)", "POST /api/media/access/:id?": "the signed-in account's own permissions on media", - "POST /api/media/versions/:id": "restore a version: Payload default (any signed-in account; one login collection here, so staff only — a visitor collection would reach it: owner Q3)", - "POST /api/pages": "create: Payload default (any signed-in account; one login collection here, so staff only — a visitor collection would reach it: owner Q3)", - "POST /api/pages/:id/duplicate": "duplicate: Payload default (any signed-in account; one login collection here, so staff only — a visitor collection would reach it: owner Q3)", + "POST /api/media/versions/:id": "restore a version: editor+ (adminOrEditor, the site's own rule since 1.17.2; Payload's default would let any signed-in account in)", + "POST /api/pages": "create: editor+ (adminOrEditor, the site's own rule since 1.17.2; Payload's default would let any signed-in account in)", + "POST /api/pages/:id/duplicate": "duplicate: editor+ (adminOrEditor, the site's own rule since 1.17.2; Payload's default would let any signed-in account in)", "POST /api/pages/access/:id?": "the signed-in account's own permissions on pages", - "POST /api/pages/versions/:id": "restore a version: Payload default (any signed-in account; one login collection here, so staff only — a visitor collection would reach it: owner Q3)", + "POST /api/pages/versions/:id": "restore a version: editor+ (adminOrEditor, the site's own rule since 1.17.2; Payload's default would let any signed-in account in)", "POST /api/payload-kv": "create: nobody (every rule false)", "POST /api/payload-kv/:id/duplicate": "duplicate: nobody (every rule false)", "POST /api/payload-kv/access/:id?": "the signed-in account's own permissions on payload-kv", "POST /api/payload-kv/versions/:id": "restore a version: nobody (every rule false)", - "POST /api/payload-locked-documents": "create: Payload default: any signed-in account (owner Q3)", - "POST /api/payload-locked-documents/:id/duplicate": "duplicate: Payload default: any signed-in account (owner Q3)", + "POST /api/payload-locked-documents": "create: Payload default: any signed-in account (the plugin-wide default is owner's Q3 (a), 2.0; the doctor's visitor-writes lists it)", + "POST /api/payload-locked-documents/:id/duplicate": "duplicate: Payload default: any signed-in account (the plugin-wide default is owner's Q3 (a), 2.0; the doctor's visitor-writes lists it)", "POST /api/payload-locked-documents/access/:id?": "the signed-in account's own permissions on payload-locked-documents", - "POST /api/payload-locked-documents/versions/:id": "restore a version: Payload default: any signed-in account (owner Q3)", + "POST /api/payload-locked-documents/versions/:id": "restore a version: Payload default: any signed-in account (the plugin-wide default is owner's Q3 (a), 2.0; the doctor's visitor-writes lists it)", "POST /api/payload-preferences": "create: own preferences only (Payload)", "POST /api/payload-preferences/:id/duplicate": "duplicate: own preferences only (Payload)", "POST /api/payload-preferences/:key": "updateByID: own preferences only (Payload)", @@ -230,10 +230,10 @@ "POST /api/plugin-seo/generate-image": "SEO plugin (panel button): Payload default (signed-in account); nothing stored", "POST /api/plugin-seo/generate-title": "SEO plugin (panel button): Payload default (signed-in account); nothing stored", "POST /api/plugin-seo/generate-url": "SEO plugin (panel button): Payload default (signed-in account); nothing stored", - "POST /api/posts": "create: Payload default (any signed-in account; one login collection here, so staff only — a visitor collection would reach it: owner Q3)", - "POST /api/posts/:id/duplicate": "duplicate: Payload default (any signed-in account; one login collection here, so staff only — a visitor collection would reach it: owner Q3)", + "POST /api/posts": "create: editor+ (adminOrEditor, the site's own rule since 1.17.2; Payload's default would let any signed-in account in)", + "POST /api/posts/:id/duplicate": "duplicate: editor+ (adminOrEditor, the site's own rule since 1.17.2; Payload's default would let any signed-in account in)", "POST /api/posts/access/:id?": "the signed-in account's own permissions on posts", - "POST /api/posts/versions/:id": "restore a version: Payload default (any signed-in account; one login collection here, so staff only — a visitor collection would reach it: owner Q3)", + "POST /api/posts/versions/:id": "restore a version: editor+ (adminOrEditor, the site's own rule since 1.17.2; Payload's default would let any signed-in account in)", "POST /api/remove-totp": "2FA: the signed-in account's own second factor, fully signed in", "POST /api/setup-totp": "2FA: sets up the signed-in account's own authenticator; same-origin only", "POST /api/users": "create: create/delete/unlock: an admin with the second factor; update: admin or self; roles field: admin", @@ -248,64 +248,64 @@ "POST /api/users/verify/:id": "public by design: needs the e-mailed verification token (verify is off on users)", "POST /api/users/versions/:id": "restore a version: create/delete/unlock: an admin with the second factor; update: admin or self; roles field: admin", "POST /api/verify-totp": "2FA (payload-2fa): the signed-in account's own code; same-origin only, 5 tries per account in 10 min", - "graphql mutation createCaseStudy": "GraphQL create: Payload default (any signed-in account; one login collection here, so staff only — a visitor collection would reach it: owner Q3)", + "graphql mutation createCaseStudy": "GraphQL create: editor+ (adminOrEditor, the site's own rule since 1.17.2; Payload's default would let any signed-in account in)", "graphql mutation createConsentRecord": "GraphQL create: nobody over the API (create/update false); delete: admin; visitors write through POST /api/ipal/consent", "graphql mutation createCookieReview": "GraphQL create: create/update: editor+; delete: admin", "graphql mutation createForm": "GraphQL create: editor+ (staffAccess)", - "graphql mutation createFormSubmission": "GraphQL create: create: any signed-in account (owner Q1); update: Payload default; delete: admin", - "graphql mutation createMedia": "GraphQL create: Payload default (any signed-in account; one login collection here, so staff only — a visitor collection would reach it: owner Q3)", - "graphql mutation createPage": "GraphQL create: Payload default (any signed-in account; one login collection here, so staff only — a visitor collection would reach it: owner Q3)", + "graphql mutation createFormSubmission": "GraphQL create: a staff account with its second factor (1.17.2; the site submits through submitForm); update: nobody (form-builder); delete: admin", + "graphql mutation createMedia": "GraphQL create: editor+ (adminOrEditor, the site's own rule since 1.17.2; Payload's default would let any signed-in account in)", + "graphql mutation createPage": "GraphQL create: editor+ (adminOrEditor, the site's own rule since 1.17.2; Payload's default would let any signed-in account in)", "graphql mutation createPayloadKv": "GraphQL create: nobody (every rule false)", - "graphql mutation createPayloadLockedDocument": "GraphQL create: Payload default: any signed-in account (owner Q3)", + "graphql mutation createPayloadLockedDocument": "GraphQL create: Payload default: any signed-in account (the plugin-wide default is owner's Q3 (a), 2.0; the doctor's visitor-writes lists it)", "graphql mutation createPayloadPreference": "GraphQL create: own preferences only (Payload)", - "graphql mutation createPost": "GraphQL create: Payload default (any signed-in account; one login collection here, so staff only — a visitor collection would reach it: owner Q3)", + "graphql mutation createPost": "GraphQL create: editor+ (adminOrEditor, the site's own rule since 1.17.2; Payload's default would let any signed-in account in)", "graphql mutation createUser": "GraphQL create: create/delete/unlock: an admin with the second factor; update: admin or self; roles field: admin", - "graphql mutation deleteCaseStudy": "GraphQL delete: Payload default (any signed-in account; one login collection here, so staff only — a visitor collection would reach it: owner Q3)", + "graphql mutation deleteCaseStudy": "GraphQL delete: editor+ (adminOrEditor, the site's own rule since 1.17.2; Payload's default would let any signed-in account in)", "graphql mutation deleteConsentRecord": "GraphQL delete: nobody over the API (create/update false); delete: admin; visitors write through POST /api/ipal/consent", "graphql mutation deleteCookieReview": "GraphQL delete: create/update: editor+; delete: admin", "graphql mutation deleteForm": "GraphQL delete: editor+ (staffAccess)", - "graphql mutation deleteFormSubmission": "GraphQL delete: create: any signed-in account (owner Q1); update: Payload default; delete: admin", - "graphql mutation deleteMedia": "GraphQL delete: Payload default (any signed-in account; one login collection here, so staff only — a visitor collection would reach it: owner Q3)", - "graphql mutation deletePage": "GraphQL delete: Payload default (any signed-in account; one login collection here, so staff only — a visitor collection would reach it: owner Q3)", + "graphql mutation deleteFormSubmission": "GraphQL delete: create: a staff account with its second factor (1.17.2; the site submits through submitForm); update: nobody (form-builder); delete: admin", + "graphql mutation deleteMedia": "GraphQL delete: editor+ (adminOrEditor, the site's own rule since 1.17.2; Payload's default would let any signed-in account in)", + "graphql mutation deletePage": "GraphQL delete: editor+ (adminOrEditor, the site's own rule since 1.17.2; Payload's default would let any signed-in account in)", "graphql mutation deletePayloadKv": "GraphQL delete: nobody (every rule false)", - "graphql mutation deletePayloadLockedDocument": "GraphQL delete: Payload default: any signed-in account (owner Q3)", + "graphql mutation deletePayloadLockedDocument": "GraphQL delete: Payload default: any signed-in account (the plugin-wide default is owner's Q3 (a), 2.0; the doctor's visitor-writes lists it)", "graphql mutation deletePayloadPreference": "GraphQL delete: own preferences only (Payload)", - "graphql mutation deletePost": "GraphQL delete: Payload default (any signed-in account; one login collection here, so staff only — a visitor collection would reach it: owner Q3)", + "graphql mutation deletePost": "GraphQL delete: editor+ (adminOrEditor, the site's own rule since 1.17.2; Payload's default would let any signed-in account in)", "graphql mutation deleteUser": "GraphQL delete: create/delete/unlock: an admin with the second factor; update: admin or self; roles field: admin", - "graphql mutation duplicateCaseStudy": "GraphQL duplicate: Payload default (any signed-in account; one login collection here, so staff only — a visitor collection would reach it: owner Q3)", + "graphql mutation duplicateCaseStudy": "GraphQL duplicate: editor+ (adminOrEditor, the site's own rule since 1.17.2; Payload's default would let any signed-in account in)", "graphql mutation duplicateConsentRecord": "GraphQL duplicate: nobody over the API (create/update false); delete: admin; visitors write through POST /api/ipal/consent", "graphql mutation duplicateCookieReview": "GraphQL duplicate: create/update: editor+; delete: admin", "graphql mutation duplicateForm": "GraphQL duplicate: editor+ (staffAccess)", - "graphql mutation duplicateFormSubmission": "GraphQL duplicate: create: any signed-in account (owner Q1); update: Payload default; delete: admin", - "graphql mutation duplicateMedia": "GraphQL duplicate: Payload default (any signed-in account; one login collection here, so staff only — a visitor collection would reach it: owner Q3)", - "graphql mutation duplicatePage": "GraphQL duplicate: Payload default (any signed-in account; one login collection here, so staff only — a visitor collection would reach it: owner Q3)", + "graphql mutation duplicateFormSubmission": "GraphQL duplicate: create: a staff account with its second factor (1.17.2; the site submits through submitForm); update: nobody (form-builder); delete: admin", + "graphql mutation duplicateMedia": "GraphQL duplicate: editor+ (adminOrEditor, the site's own rule since 1.17.2; Payload's default would let any signed-in account in)", + "graphql mutation duplicatePage": "GraphQL duplicate: editor+ (adminOrEditor, the site's own rule since 1.17.2; Payload's default would let any signed-in account in)", "graphql mutation duplicatePayloadKv": "GraphQL duplicate: nobody (every rule false)", - "graphql mutation duplicatePayloadLockedDocument": "GraphQL duplicate: Payload default: any signed-in account (owner Q3)", + "graphql mutation duplicatePayloadLockedDocument": "GraphQL duplicate: Payload default: any signed-in account (the plugin-wide default is owner's Q3 (a), 2.0; the doctor's visitor-writes lists it)", "graphql mutation duplicatePayloadPreference": "GraphQL duplicate: own preferences only (Payload)", - "graphql mutation duplicatePost": "GraphQL duplicate: Payload default (any signed-in account; one login collection here, so staff only — a visitor collection would reach it: owner Q3)", + "graphql mutation duplicatePost": "GraphQL duplicate: editor+ (adminOrEditor, the site's own rule since 1.17.2; Payload's default would let any signed-in account in)", "graphql mutation forgotPasswordUser": "public by design: the same answer for a real and an invented address", "graphql mutation loginUser": "public by design: sign-in (as POST /api/users/login)", "graphql mutation logoutUser": "public by design: ends the caller's own session", "graphql mutation refreshTokenUser": "the signed-in account's own token only", "graphql mutation resetPasswordUser": "public by design: needs the e-mailed reset token", "graphql mutation unlockUser": "admin with the second factor (accounts.adminOnlyWrite)", - "graphql mutation updateCaseStudy": "GraphQL update: Payload default (any signed-in account; one login collection here, so staff only — a visitor collection would reach it: owner Q3)", - "graphql mutation updateCompany": "GraphQL update: Payload default (any signed-in account; one login collection here, so staff only — a visitor collection would reach it: owner Q3)", + "graphql mutation updateCaseStudy": "GraphQL update: editor+ (adminOrEditor, the site's own rule since 1.17.2; Payload's default would let any signed-in account in)", + "graphql mutation updateCompany": "GraphQL update: editor+ (adminOrEditor, the site's own rule since 1.17.2; Payload's default would let any signed-in account in)", "graphql mutation updateConsentRecord": "GraphQL update: nobody over the API (create/update false); delete: admin; visitors write through POST /api/ipal/consent", "graphql mutation updateCookieCrawl": "GraphQL update: admin; the crawl endpoints write it after their own checks", "graphql mutation updateCookieReview": "GraphQL update: create/update: editor+; delete: admin", "graphql mutation updateCookieSetting": "GraphQL update: editor+", - "graphql mutation updateFooter": "GraphQL update: Payload default (any signed-in account; one login collection here, so staff only — a visitor collection would reach it: owner Q3)", + "graphql mutation updateFooter": "GraphQL update: editor+ (adminOrEditor, the site's own rule since 1.17.2; Payload's default would let any signed-in account in)", "graphql mutation updateForm": "GraphQL update: editor+ (staffAccess)", - "graphql mutation updateFormSubmission": "GraphQL update: create: any signed-in account (owner Q1); update: Payload default; delete: admin", - "graphql mutation updateHeader": "GraphQL update: Payload default (any signed-in account; one login collection here, so staff only — a visitor collection would reach it: owner Q3)", - "graphql mutation updateMedia": "GraphQL update: Payload default (any signed-in account; one login collection here, so staff only — a visitor collection would reach it: owner Q3)", + "graphql mutation updateFormSubmission": "GraphQL update: create: a staff account with its second factor (1.17.2; the site submits through submitForm); update: nobody (form-builder); delete: admin", + "graphql mutation updateHeader": "GraphQL update: editor+ (adminOrEditor, the site's own rule since 1.17.2; Payload's default would let any signed-in account in)", + "graphql mutation updateMedia": "GraphQL update: editor+ (adminOrEditor, the site's own rule since 1.17.2; Payload's default would let any signed-in account in)", "graphql mutation updateNotification": "GraphQL update: editor+", - "graphql mutation updatePage": "GraphQL update: Payload default (any signed-in account; one login collection here, so staff only — a visitor collection would reach it: owner Q3)", + "graphql mutation updatePage": "GraphQL update: editor+ (adminOrEditor, the site's own rule since 1.17.2; Payload's default would let any signed-in account in)", "graphql mutation updatePayloadKv": "GraphQL update: nobody (every rule false)", - "graphql mutation updatePayloadLockedDocument": "GraphQL update: Payload default: any signed-in account (owner Q3)", + "graphql mutation updatePayloadLockedDocument": "GraphQL update: Payload default: any signed-in account (the plugin-wide default is owner's Q3 (a), 2.0; the doctor's visitor-writes lists it)", "graphql mutation updatePayloadPreference": "GraphQL update: own preferences only (Payload)", - "graphql mutation updatePost": "GraphQL update: Payload default (any signed-in account; one login collection here, so staff only — a visitor collection would reach it: owner Q3)", + "graphql mutation updatePost": "GraphQL update: editor+ (adminOrEditor, the site's own rule since 1.17.2; Payload's default would let any signed-in account in)", "graphql mutation updateSiteIntegration": "GraphQL update: admin; secrets write-only", "graphql mutation updateSiteSetting": "GraphQL update: editor+", "graphql mutation updateUser": "GraphQL update: create/delete/unlock: an admin with the second factor; update: admin or self; roles field: admin", @@ -332,8 +332,8 @@ "graphql query Pages": "GraphQL find: anyone (published content, no drafts)", "graphql query PayloadKv": "GraphQL find: nobody (Payload: every rule false; the plugin keeps 2FA counts and the mail-service token here)", "graphql query PayloadKvs": "GraphQL find: nobody (Payload: every rule false; the plugin keeps 2FA counts and the mail-service token here)", - "graphql query PayloadLockedDocument": "GraphQL find: Payload default: any signed-in account (owner Q3)", - "graphql query PayloadLockedDocuments": "GraphQL find: Payload default: any signed-in account (owner Q3)", + "graphql query PayloadLockedDocument": "GraphQL find: Payload default: any signed-in account (the plugin-wide default is owner's Q3 (a), 2.0; the doctor's visitor-writes lists it)", + "graphql query PayloadLockedDocuments": "GraphQL find: Payload default: any signed-in account (the plugin-wide default is owner's Q3 (a), 2.0; the doctor's visitor-writes lists it)", "graphql query PayloadPreference": "GraphQL find: the signed-in account's own preferences only (Payload)", "graphql query PayloadPreferences": "GraphQL find: the signed-in account's own preferences only (Payload)", "graphql query Post": "GraphQL find: anyone (published content, no drafts)", @@ -350,7 +350,7 @@ "graphql query countForms": "GraphQL count: anyone (the form renders from it; the Emails tab is staff-only by field access)", "graphql query countPages": "GraphQL count: anyone (published content, no drafts)", "graphql query countPayloadKvs": "GraphQL count: nobody (Payload: every rule false; the plugin keeps 2FA counts and the mail-service token here)", - "graphql query countPayloadLockedDocuments": "GraphQL count: Payload default: any signed-in account (owner Q3)", + "graphql query countPayloadLockedDocuments": "GraphQL count: Payload default: any signed-in account (the plugin-wide default is owner's Q3 (a), 2.0; the doctor's visitor-writes lists it)", "graphql query countPayloadPreferences": "GraphQL count: the signed-in account's own preferences only (Payload)", "graphql query countPosts": "GraphQL count: anyone (published content, no drafts)", "graphql query countUsers": "GraphQL count: an admin, or the account itself (adminOrSelfIn users)", diff --git a/reference/src/collections/CaseStudies.ts b/reference/src/collections/CaseStudies.ts index 4d9ee4f..27ea21e 100644 --- a/reference/src/collections/CaseStudies.ts +++ b/reference/src/collections/CaseStudies.ts @@ -1,6 +1,6 @@ import type { CollectionConfig } from 'payload' -import { buildRevalidateHook } from '@intecion/ipal-kit' +import { adminOrEditor, buildRevalidateHook } from '@intecion/ipal-kit' import { revalidatePath } from 'next/cache' import { i18nConfig } from '@/i18n.config' @@ -13,7 +13,8 @@ const revalidate = buildRevalidateHook({ config: i18nConfig, revalidatePath }) export const CaseStudies: CollectionConfig = { slug: 'caseStudies', admin: { defaultColumns: ['title', 'publishedAt', 'updatedAt'], useAsTitle: 'title' }, - access: { read: () => true }, + // write rules of its own: Payload's default is "any signed-in account" — a visitor login collection would reach it (security.md "Visitor accounts") + access: { create: adminOrEditor, delete: adminOrEditor, read: () => true, update: adminOrEditor }, defaultSort: '-publishedAt', fields: entryFields, hooks: { afterChange: [revalidate.afterChange], afterDelete: [revalidate.afterDelete] }, diff --git a/reference/src/collections/Media.ts b/reference/src/collections/Media.ts index d63c288..56e1695 100644 --- a/reference/src/collections/Media.ts +++ b/reference/src/collections/Media.ts @@ -1,6 +1,7 @@ import type { CollectionConfig } from 'payload' import { + adminOrEditor, buildMediaPlaceholderField, buildMediaPlaceholderHook, buildOptimizeUploadField, @@ -11,7 +12,8 @@ import { /** media.md "Full collection", 1:1. */ export const Media: CollectionConfig = { slug: 'media', - access: { read: () => true }, // public files; media are served by the app (/api/media/file/…) + // write rules of its own: Payload's default is "any signed-in account" — a visitor login collection would reach it (security.md "Visitor accounts") + access: { create: adminOrEditor, delete: adminOrEditor, read: () => true, update: adminOrEditor }, // public files; media are served by the app (/api/media/file/…) upload: { focalPoint: true, mimeTypes: ['image/*', 'application/pdf', 'video/mp4', 'video/webm'] }, hooks: { beforeOperation: [normalizeFilenameHook, buildOptimizeUploadHook(), buildMediaPlaceholderHook()], diff --git a/reference/src/collections/Pages.ts b/reference/src/collections/Pages.ts index eaa4e04..b9b4201 100644 --- a/reference/src/collections/Pages.ts +++ b/reference/src/collections/Pages.ts @@ -1,6 +1,7 @@ import type { CollectionConfig } from 'payload' import { + adminOrEditor, buildNoindexField, buildPreventDeleteSystemPage, buildRevalidateHook, @@ -19,7 +20,8 @@ const revalidate = buildRevalidateHook({ config: i18nConfig, revalidatePath }) export const Pages: CollectionConfig = { slug: 'pages', admin: { defaultColumns: ['title', 'slug', 'updatedAt'], useAsTitle: 'title' }, - access: { read: () => true }, + // write rules of its own: Payload's default is "any signed-in account" — a visitor login collection would reach it (security.md "Visitor accounts") + access: { create: adminOrEditor, delete: adminOrEditor, read: () => true, update: adminOrEditor }, fields: [ { name: 'title', type: 'text', localized: true, required: true }, buildSlugField({ from: 'title' }), diff --git a/reference/src/collections/Posts.ts b/reference/src/collections/Posts.ts index 3954cae..c6e602c 100644 --- a/reference/src/collections/Posts.ts +++ b/reference/src/collections/Posts.ts @@ -1,6 +1,6 @@ import type { CollectionConfig } from 'payload' -import { buildRevalidateHook } from '@intecion/ipal-kit' +import { adminOrEditor, buildRevalidateHook } from '@intecion/ipal-kit' import { revalidatePath } from 'next/cache' import { i18nConfig } from '@/i18n.config' @@ -13,7 +13,8 @@ const revalidate = buildRevalidateHook({ config: i18nConfig, revalidatePath }) export const Posts: CollectionConfig = { slug: 'posts', admin: { defaultColumns: ['title', 'publishedAt', 'updatedAt'], useAsTitle: 'title' }, - access: { read: () => true }, + // write rules of its own: Payload's default is "any signed-in account" — a visitor login collection would reach it (security.md "Visitor accounts") + access: { create: adminOrEditor, delete: adminOrEditor, read: () => true, update: adminOrEditor }, defaultSort: '-publishedAt', fields: entryFields, hooks: { afterChange: [revalidate.afterChange], afterDelete: [revalidate.afterDelete] }, diff --git a/reference/src/globals/Company.ts b/reference/src/globals/Company.ts index 59f22a5..0846158 100644 --- a/reference/src/globals/Company.ts +++ b/reference/src/globals/Company.ts @@ -1,12 +1,13 @@ import type { GlobalConfig } from 'payload' -import { buildGlobalRevalidateHook, rowLabel } from '@intecion/ipal-kit' +import { adminOrEditor, buildGlobalRevalidateHook, rowLabel } from '@intecion/ipal-kit' import { revalidatePath } from 'next/cache' /** Company data for a PL market site: footer, contact block details, LocalBusiness JSON-LD. */ export const Company: GlobalConfig = { slug: 'company', - access: { read: () => true }, + // write rules of its own: Payload's default is "any signed-in account" — a visitor login collection would reach it (security.md "Visitor accounts") + access: { read: () => true, update: adminOrEditor }, fields: [ { name: 'name', type: 'text', required: true }, { name: 'legalName', type: 'text' }, diff --git a/reference/src/globals/Footer.ts b/reference/src/globals/Footer.ts index 3900a68..d3c786e 100644 --- a/reference/src/globals/Footer.ts +++ b/reference/src/globals/Footer.ts @@ -1,12 +1,13 @@ import type { GlobalConfig } from 'payload' -import { buildGlobalRevalidateHook, buildLinkField, rowLabel } from '@intecion/ipal-kit' +import { adminOrEditor, buildGlobalRevalidateHook, buildLinkField, rowLabel } from '@intecion/ipal-kit' import { revalidatePath } from 'next/cache' /** iapl-nav: link columns and a note. Legal links come from System pages (getSystemLinks), not from here. */ export const Footer: GlobalConfig = { slug: 'footer', - access: { read: () => true }, + // write rules of its own: Payload's default is "any signed-in account" — a visitor login collection would reach it (security.md "Visitor accounts") + access: { read: () => true, update: adminOrEditor }, fields: [ { name: 'columns', diff --git a/reference/src/globals/Header.ts b/reference/src/globals/Header.ts index 863fc16..6bd2a3c 100644 --- a/reference/src/globals/Header.ts +++ b/reference/src/globals/Header.ts @@ -1,12 +1,13 @@ import type { GlobalConfig } from 'payload' -import { buildGlobalRevalidateHook, buildLinkField, buildLinksField, rowLabel } from '@intecion/ipal-kit' +import { adminOrEditor, buildGlobalRevalidateHook, buildLinkField, buildLinksField, rowLabel } from '@intecion/ipal-kit' import { revalidatePath } from 'next/cache' /** iapl-nav: menu with one submenu level, a CTA button, the mobile menu label. Logo comes from Site settings. */ export const Header: GlobalConfig = { slug: 'header', - access: { read: () => true }, + // write rules of its own: Payload's default is "any signed-in account" — a visitor login collection would reach it (security.md "Visitor accounts") + access: { read: () => true, update: adminOrEditor }, fields: [ { name: 'navItems', diff --git a/scripts/e2e-built.mjs b/scripts/e2e-built.mjs index c614f0b..82a75f3 100644 --- a/scripts/e2e-built.mjs +++ b/scripts/e2e-built.mjs @@ -24,6 +24,7 @@ * Options: --only=webpack | --only=turbopack; --skip-plugin-build (dist and the injected copy are current). */ import { spawnSync } from 'node:child_process' +import { randomBytes } from 'node:crypto' import { existsSync, readdirSync, readFileSync, statSync, writeFileSync } from 'node:fs' import path from 'node:path' import { fileURLToPath } from 'node:url' @@ -73,6 +74,8 @@ const restore = () => { process.on('exit', restore) for (const signal of ['SIGINT', 'SIGTERM']) {process.on(signal, () => process.exit(130))} +// the fixture's job queue is run by the closed-doors spec with this secret (a fresh one per run) +const cronSecret = randomBytes(24).toString('base64url') 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) { @@ -89,7 +92,7 @@ for (const bundler of bundlers) { process.exit(1) } console.log(`[e2e:built] ✓ ${bundler}: no package manifest among ${files.length} public files`) - run(`${bundler}: the built site — late-staff spec, the mail service, closed doors, the published-files check, the client hints, consent and the sign-in look`, 'pnpm', ['exec', 'playwright', 'test', 'late-staff', 'mail-relay', 'closed-doors', 'smoke', 'sign-in-look', '--grep', 'late staff collection|the mail service|closed doors|no package.json is published|client hints|consent|sign-in look'], site, { ALLOW_LOCAL_MEDIA: process.env.ALLOW_LOCAL_MEDIA ?? '1', E2E_LATE_STAFF: '1' }) + run(`${bundler}: the built site — late-staff spec, the mail service, closed doors, the published-files check, the client hints, consent and the sign-in look`, 'pnpm', ['exec', 'playwright', 'test', 'late-staff', 'mail-relay', 'closed-doors', 'smoke', 'sign-in-look', '--grep', 'late staff collection|the mail service|closed doors|no package.json is published|client hints|consent|sign-in look'], site, { ALLOW_LOCAL_MEDIA: process.env.ALLOW_LOCAL_MEDIA ?? '1', CRON_SECRET: cronSecret, 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.)`) diff --git a/src/index.ts b/src/index.ts index e014373..5bc1395 100644 --- a/src/index.ts +++ b/src/index.ts @@ -489,6 +489,9 @@ export type { } from './modules/security/index.js' export type { BuildSecurityHeadersArgs, SecurityHeader } from './modules/security/index.js' +// Payload's job queue over HTTP: an admin with the second factor or Bearer CRON_SECRET (security.md "Payload's job queue") +export { CRON_SECRET_ENV, CRON_SECRET_MIN_LENGTH, cronSecretMatches, jobsRunAccess, jobsRunNotice, withJobsRunAccess } from './modules/security/jobsAccess.js' +export type { JobsRunAccessOptions } from './modules/security/jobsAccess.js' // The doors a built config opens (REST, GraphQL, Next route files) and the judged snapshot they are checked against. export { compareRouteSnapshot, listNextRouteFiles, listPublicRoutes, updateRouteSnapshot } from './modules/security/routeInventory.js' export type { GraphqlSchemaLike, RouteInventoryOptions, RouteSnapshot, RouteSnapshotDiff } from './modules/security/routeInventory.js' diff --git a/src/modules/doctor/rules/security.ts b/src/modules/doctor/rules/security.ts index 358e874..0f1aeef 100644 --- a/src/modules/doctor/rules/security.ts +++ b/src/modules/doctor/rules/security.ts @@ -225,6 +225,30 @@ export const securityRules: DoctorRule[] = [ group: 'security', source: 'deep', }, + { + // An account of a visitor login collection (customers, members) may write content or settings: Payload fills a + // missing rule with "any signed-in account", and the plugin narrows only its own entities (owner's Q3, 1.17.2). + id: 'visitor-writes', + check: (ctx) => { + const byEntity = new Map() + for (const entry of ctx.deep?.visitorWrites ?? []) { + const at = entry.lastIndexOf(':') + byEntity.set(entry.slice(0, at), [...(byEntity.get(entry.slice(0, at)) ?? []), entry.slice(at + 1)]) + } + return [...byEntity].map(([entity, operations]) => { + const global = entity.startsWith('globals/') + const slug = global ? entity.slice('globals/'.length) : entity + return { + fix: `give ${global ? 'the global' : 'the collection'} "${slug}" its own ${operations.map((o) => `access.${o}`).join(' / ')} (adminOrEditor, requireRole('editor'), …) — Payload's default lets every signed-in account in (access.md "Who is staff")`, + message: `an account of a visitor login collection may ${operations.join(', ')} ${global ? 'the global' : 'in'} "${slug}"`, + severity: 'warning' as const, + } + }) + }, + docs: 'docs/access.md', + group: 'security', + source: 'deep', + }, { // A staff collection that an account of another auth collection (a customer, a member) may write to: // it can create a staff account, or change a staff account's password. The plugin's default rules close diff --git a/src/modules/doctor/status.ts b/src/modules/doctor/status.ts index e70e5b6..87c759e 100644 --- a/src/modules/doctor/status.ts +++ b/src/modules/doctor/status.ts @@ -15,6 +15,7 @@ import { countAccountsWithoutTotp } from '../security/totp/setupRequired.js' import { readEnv } from '../shared/envName.js' import { clientIp, consumeRateLimit, tooManyRequests } from '../shared/rateLimit.js' import { turnstileSecretFromEnv } from '../turnstile/config.js' +import { visitorWritableEntities } from './visitorWrites.js' /** The plugin's own version — a constant (src/version.ts), never a file read at run time. */ export function pluginVersion(): string { @@ -111,7 +112,13 @@ export async function collectDoctorStatus(payload: BasePayload): Promise unknown) | undefined +type LiveEntity = { access?: Record; auth?: unknown; slug: string } +type LivePayload = { + collections?: Record + config?: { globals?: LiveEntity[] } +} + +/** + * What an account of a visitor login collection (a shop's customers, a member zone — an auth collection that is not + * staff) may WRITE: every collection `create` / `update` / `delete` and global `update` whose rule answers a plain + * `true` for such an account, as `pages:create` or `globals/header:update`. For the doctor's `visitor-writes` rule + * (IAWL idea 35, the owner's Q3). Empty when the site has no visitor login collection. + * + * Asked by behaviour, never by the rule's name (a production build renames every function): Payload's default + * ("any signed-in account") and a project's own rule that is as wide both answer `true`. A rule that answers a query + * (e.g. "its own document") is not counted, nor one that throws. Staff collections are left to `staff-accounts-open`. + */ +export async function visitorWritableEntities(payload: LivePayload): Promise { + const staff = staffCollectionSlugs(payload as never) + const collections = Object.values(payload.collections ?? {}).map(({ config }) => config) + const visitors = collections.filter((c) => c.auth && !staff.includes(c.slug)).map((c) => c.slug) + if (!visitors.length) {return []} + const open = new Set() + const ask = async (rule: Rule, key: string) => { + for (const collection of visitors) { + const user = { id: '__iapl-visitor__', collection, email: 'visitor@example.invalid' } + try { + // no rule = Payload's default: any signed-in account + if (!rule || (await rule({ id: '__iapl-other__', req: { context: {}, headers: new Headers(), payload, user } } as never)) === true) { + open.add(key) + return + } + } catch { + /* closed */ + } + } + } + for (const config of collections) { + if (staff.includes(config.slug)) {continue} + for (const operation of ['create', 'update', 'delete'] as const) {await ask(config.access?.[operation], `${config.slug}:${operation}`)} + } + for (const global of payload.config?.globals ?? []) {await ask(global.access?.update, `globals/${global.slug}:update`)} + return [...open].sort() +} diff --git a/src/modules/forms/formsPluginConfig.ts b/src/modules/forms/formsPluginConfig.ts index 4b3021b..6299ec4 100644 --- a/src/modules/forms/formsPluginConfig.ts +++ b/src/modules/forms/formsPluginConfig.ts @@ -162,8 +162,13 @@ const builtin = (key: 'checkbox' | 'date' | 'email' | 'message' | 'number' | 'ra /** Text-like built-ins also get a localized "Placeholder" (select already has one). */ const withHint = (key: 'email' | 'number' | 'text' | 'textarea') => withShowWhen(withPlaceholder(builtinBlocks[key] as Block)) -/** REST/GraphQL: only logged-in users. Local API (submitForm) is unaffected. */ -const submissionsCreateAccess = ({ req }: AccessArgs) => Boolean(req.user) +/** + * REST/GraphQL: a staff account (any role) with its second factor. Local API (submitForm) is unaffected. Before + * 1.17.2 any signed-in account was enough — a customer of a visitor login collection could POST + * /api/form-submissions past the rate limit, Turnstile, consent and validation, and the form's e-mails went out. + * `formSubmissionOverrides.access.create` is the way back. + */ +const submissionsCreateAccess = ({ req }: AccessArgs) => userMeetsRole(req, 'user') /** * Submissions are visitors' personal data: editors and admins only. The * form-builder default lets ANY account of the admin collection read them — @@ -205,7 +210,7 @@ function hideEmails(fields: Field[]): Field[] { * SECURITY: form-builder defaults form-submissions to `create: () => true`, i.e. * anyone can POST /api/form-submissions and skip everything submitForm enforces * (rate limit, Turnstile, GDPR consent, schema validation). Here REST/GraphQL - * creation is limited to logged-in users; the site submits through submitForm + * creation is limited to staff accounts with their second factor; the site submits through submitForm * (server action → Local API, which bypasses access by design). A project that * really needs public REST submissions can override `formSubmissionOverrides.access.create`. */ diff --git a/src/modules/security/jobsAccess.ts b/src/modules/security/jobsAccess.ts new file mode 100644 index 0000000..cbb0524 --- /dev/null +++ b/src/modules/security/jobsAccess.ts @@ -0,0 +1,78 @@ +import type { Config, PayloadRequest } from 'payload' + +import { createHash, timingSafeEqual } from 'node:crypto' + +import { userMeetsRole } from '../access/predicates.js' + +/** + * Who may run Payload's job queue over HTTP (`GET /api/payload-jobs/run`, `/api/payload-jobs/handle-schedules`, + * both checked by `jobs.access.run`). Payload's own default is any signed-in account of ANY auth collection — a + * customer of a shop included (IAWL idea 35: a route open to the web is a visitor, not the system). Since 1.17.2, + * when the project writes no `jobs.access.run`, iapl sets: an admin signed in with the second factor (an admin's API + * key counts), or `Authorization: Bearer `. A project's own rule always wins; `jobsRunAccess: false` + * keeps Payload's default. Jobs run in-process (`jobs.autoRun`, `payload jobs:run`, `payload.jobs.run()`) never + * pass through this rule. + */ +export type JobsRunAccessOptions = { + /** The variable holding the cron secret. Default `CRON_SECRET`. Shorter than 16 characters = not used. */ + secretVar?: string +} + +export const CRON_SECRET_ENV = 'CRON_SECRET' +/** The secret's minimum length: a short one would be guessable over the run route. */ +export const CRON_SECRET_MIN_LENGTH = 16 + +const sha = (value: string) => createHash('sha256').update(value).digest() + +/** True when the request carries `Authorization: Bearer ` (constant-time; an unset or short secret never matches). */ +export function cronSecretMatches(req: Pick, secret: string | undefined): boolean { + const expected = secret?.trim() ?? '' + if (expected.length < CRON_SECRET_MIN_LENGTH) {return false} + const header = req.headers?.get?.('authorization') ?? '' + if (!/^Bearer\s+/i.test(header)) {return false} + return timingSafeEqual(sha(header.replace(/^Bearer\s+/i, '').trim()), sha(expected)) +} + +/** + * The rule iapl puts on `jobs.access.run` (exported for a project that writes its own and wants to keep this part): + * jobs: { access: { run: (args) => jobsRunAccess()(args) || myOwnCheck(args) } } + */ +export function jobsRunAccess({ secretVar = CRON_SECRET_ENV }: JobsRunAccessOptions = {}) { + return ({ req }: { req: PayloadRequest }): boolean => + cronSecretMatches(req, process.env[secretVar]) || userMeetsRole(req, 'admin') +} + +/** + * The config with iapl's `jobs.access.run`, only when the project wrote none (checked before Payload fills its + * default in, so a project's rule is never mistaken for Payload's). Also when the config has no `jobs` at all: + * Payload turns the queue on by itself for collections with scheduled publishing. Marks the config + * (`custom.iapl.jobsRunDefault`) so the start-up note knows the rule is iapl's. + */ +export function withJobsRunAccess(config: Config, options: false | JobsRunAccessOptions = {}): Config { + if (options === false || config.jobs?.access?.run) {return config} + const custom = (config.custom ?? {}) as Record + const iapl = (custom.iapl ?? {}) as Record + return { + ...config, + custom: { ...custom, iapl: { ...iapl, jobsRunDefault: { secretVar: options.secretVar ?? CRON_SECRET_ENV } } }, + jobs: { ...config.jobs, access: { ...config.jobs?.access, run: jobsRunAccess(options) } } as Config['jobs'], + } +} + +/** + * The one line said at start when the queue is on and the rule is iapl's: how a cron reaches the run route. + * Null when there is nothing to say. + */ +export function jobsRunNotice(config: { custom?: unknown; jobs?: { enabled?: boolean } }): null | string { + const own = ((config.custom as { iapl?: { jobsRunDefault?: { secretVar?: string } } } | undefined)?.iapl)?.jobsRunDefault + if (!own || !config.jobs?.enabled) {return null} + const secretVar = own.secretVar ?? CRON_SECRET_ENV + const secret = process.env[secretVar]?.trim() ?? '' + if (secret.length >= CRON_SECRET_MIN_LENGTH) {return null} + return ( + `[iapl] Payload's job queue runs over HTTP (/api/payload-jobs/run, /handle-schedules) only for an admin signed in with the second factor ` + + `or with "Authorization: Bearer <${secretVar}>" (1.17.2), and ${secretVar} is ${secret ? `shorter than ${CRON_SECRET_MIN_LENGTH} characters` : 'not set'}. ` + + `A cron that calls the run route: set ${secretVar} and send the header. In-process runs (jobs.autoRun, payload jobs:run) are not affected. ` + + 'Your own jobs.access.run wins; iapl({ jobsRunAccess: false }) keeps Payload\'s default (docs/security.md "Payload\'s job queue").' + ) +} diff --git a/src/plugin.ts b/src/plugin.ts index 6445f7c..ff86536 100644 --- a/src/plugin.ts +++ b/src/plugin.ts @@ -49,6 +49,7 @@ import { withFillLocales } from './modules/hooks/fillEmptyLocales.js' import { buildLocalizationConfig, validateI18nConfig } from './modules/i18n/index.js' import { serverText } from './modules/integrations/texts.js' import { buildSystemPagesFields } from './modules/pages/index.js' +import { jobsRunNotice, withJobsRunAccess } from './modules/security/jobsAccess.js' import { missingImportMapEntries } from './modules/security/totp/importMapCheck.js' import { changedViewKeys, copyViews, SAFE_TOTP_VIEW, wrapTotpViews } from './modules/security/totp/safeBack.js' import { reportRefusedOrigin, requestFromOwnOrigin } from './modules/security/totp/sameOrigin.js' @@ -981,6 +982,9 @@ export const iapl = (options: IaplOptions): Plugin => { }, } + // --- Payload's job queue over HTTP: an admin or the cron secret, unless the project wrote its own rule + config = withJobsRunAccess(config, options.jobsRunAccess ?? {}) + // --- second factor on everything in the config by now: the project's // collections (wrapped by the package already; twice is harmless), the // plugin's globals and collections, the form builder's. @@ -1010,6 +1014,9 @@ export const iapl = (options: IaplOptions): Plugin => { watchTransactions(payload, options.connectionReserve === false ? false : (options.connectionReserve ?? defaultConnectionReserve(poolSize(payload) ?? 10))) // Microsoft Graph is deprecated (removed in 2.0): one warning per start while its variables are set. if (graphAvailable() && options.mail?.graphDeprecationWarning !== false) {payload.logger.warn(GRAPH_DEPRECATION_NOTICE)} + // The queue is on and the run route is iapl's: say how a cron reaches it, when the secret is missing. + const jobsNotice = jobsRunNotice(payload.config as never) + if (jobsNotice) {payload.logger.warn(jobsNotice)} // Payload's dev reload swaps `payload.config` and runs no onInit: adopt the new config at once. watchPayloadConfig(payload, adoptConfig) if (staleSignInLook) { diff --git a/src/types.ts b/src/types.ts index bae1832..c3bcf65 100644 --- a/src/types.ts +++ b/src/types.ts @@ -26,6 +26,7 @@ import type { FormsOption } from './modules/forms/types.js' import type { RevalidatePathFn } from './modules/hooks/buildRevalidateHook.js' import type { I18nConfig } from './modules/i18n/types.js' import type { PagesOption } from './modules/pages/types.js' +import type { JobsRunAccessOptions } from './modules/security/jobsAccess.js' import type { SafeBackRule } from './modules/security/totp/safeBack.js' import type { RequireSetupOptions } from './modules/security/totp/setupRequired.js' import type { VerifyLimitOptions } from './modules/security/totp/verifyLimit.js' @@ -200,6 +201,16 @@ export type IaplOptions = { /** Additional fields injected into SiteIntegrations global */ integrationsFields?: Field[] + /** + * Who may run Payload's job queue over HTTP (`/api/payload-jobs/run`, `/handle-schedules`) when the project + * writes no `jobs.access.run` of its own: an admin signed in with the second factor (an admin's API key counts), or + * `Authorization: Bearer ` (16+ characters). Default on since 1.17.2; `secretVar` names another + * variable; `false` keeps Payload's default (any signed-in account of any auth collection). A project's own + * `jobs.access.run` always wins. In-process runs (`jobs.autoRun`, `payload jobs:run`) are not affected. + * docs/security.md "Payload's job queue". + */ + jobsRunAccess?: false | JobsRunAccessOptions + /** * Image lightbox labels in the Notifications global (a "Lightbox" group: * close, previous, next, counter, dialog name, trigger name), localized per diff --git a/test/accessControl.test.ts b/test/accessControl.test.ts index b5fceeb..76da3e5 100644 --- a/test/accessControl.test.ts +++ b/test/accessControl.test.ts @@ -159,6 +159,30 @@ describe('forms collection: public read, editor+ write, Emails hidden from plain }) }) +describe('form submissions over REST / GraphQL: staff only (1.17.2)', () => { + const build = async (forms: object = {}) => { + const config = await iapl({ access: { authCollection: 'users' }, forms, i18n, twoFactor: false })( + empty({ collections: [{ slug: 'customers', auth: true, fields: [] }] }), + ) + return config.collections?.find((c) => c.slug === 'form-submissions') as CollectionConfig + } + // the staff check reads the panel's collection from the request's Payload, as in a request + const runAs = (fn: Access | undefined, u: unknown) => + (fn as Access)({ req: { payload: { config: { admin: { user: 'users' } } }, user: u } } as never) + + test('a customer account, or nobody, cannot create a submission; any staff role can', async () => { + const { access = {} } = await build() + expect(runAs(access.create, null)).toBe(false) + expect(runAs(access.create, { id: 9, collection: 'customers' })).toBe(false) + for (const staff of [user, editor, admin]) {expect(runAs(access.create, staff)).toBe(true)} + }) + + test('formSubmissionOverrides.access.create is the way back', async () => { + const { access = {} } = await build({ formSubmissionOverrides: { access: { create: () => true } } }) + expect(runAs(access.create, { id: 9, collection: 'customers' })).toBe(true) + }) +}) + describe('roles field: the first-register account becomes admin', () => { const hook = async (totalDocs: number, value: string[], pathname = '/api/users/first-register') => { const config = await iapl({ access: { authCollection: 'users' }, i18n, twoFactor: false })(empty()) diff --git a/test/doctor.test.ts b/test/doctor.test.ts index 7e83166..58b93ef 100644 --- a/test/doctor.test.ts +++ b/test/doctor.test.ts @@ -203,6 +203,18 @@ describe('M1 rules: access-missing, turnstile-degraded, turnstile-env-key', () = expect(await run(cfg, ['open-signup'])).toEqual([]) }) + test('visitor-writes: one warning per entity a visitor account may write, its operations named', async () => { + const cfg = "iapl({ access: { authCollection: 'users' } })" + const report = await doctor(project({ ...base(), 'src/payload.config.ts': cfg }), ['visitor-writes'], { deepStatus: { visitorWrites: ['globals/header:update', 'pages:create', 'pages:delete', 'pages:update'] } }) + expect(report.findings.map((f) => `${f.severity}: ${f.message}`)).toEqual([ + 'warning: an account of a visitor login collection may update the global "header"', + 'warning: an account of a visitor login collection may create, delete, update in "pages"', + ]) + expect(await run(cfg, ['visitor-writes'], { visitorWrites: [] })).toEqual([]) + expect(await run(cfg, ['visitor-writes'], { visitorWrites: null })).toEqual([]) + expect(await run(cfg, ['visitor-writes'])).toEqual([]) + }) + test('staff-accounts-open: a staff collection an account of another collection may write to is an error', async () => { const cfg = "iapl({ access: { authCollection: 'users' } })" expect(await run(cfg, ['staff-accounts-open'], { staffOpenToOthers: ['agents:delete', 'agents:update', 'users:create'] })).toEqual(['staff-accounts-open:error', 'staff-accounts-open:error', 'staff-accounts-open:error']) @@ -529,7 +541,7 @@ describe('security and deep status', () => { } const status = await collectDoctorStatus(payload as never) expect(status).toMatchObject({ pendingCookies: 4, usersWithout2fa: 2 }) - expect(Object.keys(status).sort()).toEqual(['mail', 'node', 'openSignUp', 'pendingCookies', 'plugin', 'staffOnOwnRoles', 'staffOpenToOthers', 'turnstile', 'turnstileSecretFromEnv', 'usersSetupClosed', 'usersWithout2fa']) + expect(Object.keys(status).sort()).toEqual(['mail', 'node', 'openSignUp', 'pendingCookies', 'plugin', 'staffOnOwnRoles', 'staffOpenToOthers', 'turnstile', 'turnstileSecretFromEnv', 'usersSetupClosed', 'usersWithout2fa', 'visitorWrites']) expect(status.usersSetupClosed).toBeNull() // no setup window in this config expect(status.mail).toBeNull() // no Site integrations global in this config }) diff --git a/test/jobsAccess.test.ts b/test/jobsAccess.test.ts new file mode 100644 index 0000000..7b3bdf8 --- /dev/null +++ b/test/jobsAccess.test.ts @@ -0,0 +1,95 @@ +/** + * Payload's job queue over HTTP (1.17.2, IAWL idea 35, owner's Q2): when the project writes no `jobs.access.run`, + * only an admin signed in with the second factor, or `Authorization: Bearer `, may run it. Payload's + * default let any signed-in account of any auth collection run the queue — a customer included. + */ +import type { Config, SanitizedConfig } from 'payload' + +import { sqliteAdapter } from '@payloadcms/db-sqlite' +import { afterEach, describe, expect, test, vi } from 'vitest' + +import { jobsRunNotice, withJobsRunAccess } from '../src/modules/security/jobsAccess.js' +import { iapl } from '../src/plugin.js' +import { buildTestConfig } from './helpers.js' + +vi.mock('server-only', () => ({})) + +const SECRET = 'a-cron-secret-of-32-characters!!' +const i18n = { defaultLocale: 'en', locales: [{ code: 'en', label: 'English' }] } + +const project = (jobs?: Config['jobs']): Config => + ({ + collections: [{ slug: 'customers', auth: true, fields: [] }, { slug: 'media', fields: [], upload: true }], + db: sqliteAdapter({ client: { url: 'file::memory:' } }), + jobs: { ...jobs, tasks: [{ slug: 'noop', handler: () => ({ output: {} }) }] }, + secret: 'jobs-access-test', + telemetry: false, + }) as unknown as Config + +const build = (jobs?: Config['jobs'], options: object = {}) => + buildTestConfig({ ...project(jobs), plugins: [iapl({ access: { authCollection: 'users' }, i18n, twoFactor: false, ...options } as never)] }) + +/** Calls the sanitized run rule the way Payload's run endpoint does. */ +const runAs = async (config: SanitizedConfig, user: unknown, authorization?: string) => { + const req = { headers: new Headers(authorization ? { authorization } : {}), payload: { config }, user } + return Boolean(await (config.jobs.access!.run as (a: { req: unknown }) => unknown)({ req })) +} + +const admin = { id: 1, collection: 'users', roles: ['admin'] } +const editor = { id: 2, collection: 'users', roles: ['editor'] } +const customer = { id: 3, collection: 'customers' } + +afterEach(() => { + vi.unstubAllEnvs() +}) + +describe('jobs.access.run when the project writes none', () => { + test('an admin, or the cron secret; not an editor, a customer or nobody', async () => { + vi.stubEnv('CRON_SECRET', SECRET) + const config = await build() + expect(await runAs(config, admin)).toBe(true) + expect(await runAs(config, null, `Bearer ${SECRET}`)).toBe(true) + expect(await runAs(config, null)).toBe(false) + expect(await runAs(config, customer)).toBe(false) + expect(await runAs(config, editor)).toBe(false) + expect(await runAs(config, null, 'Bearer wrong-secret-wrong-secret')).toBe(false) + expect(await runAs(config, customer, SECRET)).toBe(false) // without "Bearer " + }, 30_000) + + test('a missing or short secret never matches', async () => { + vi.stubEnv('CRON_SECRET', 'short') + const config = await build() + expect(await runAs(config, null, 'Bearer short')).toBe(false) + vi.stubEnv('CRON_SECRET', '') + expect(await runAs(config, null, 'Bearer ')).toBe(false) + }, 30_000) + + test('secretVar names another variable', async () => { + vi.stubEnv('MY_JOBS_SECRET', SECRET) + const config = await build(undefined, { jobsRunAccess: { secretVar: 'MY_JOBS_SECRET' } }) + expect(await runAs(config, null, `Bearer ${SECRET}`)).toBe(true) + }, 30_000) + + test('the project\'s own rule wins; jobsRunAccess: false keeps Payload\'s default', async () => { + const own = await build({ access: { run: () => true } }) + expect(await runAs(own, null)).toBe(true) + const payloadDefault = await build(undefined, { jobsRunAccess: false }) + expect(await runAs(payloadDefault, customer)).toBe(true) // Payload: any signed-in account + }, 30_000) + + test('a config without jobs gets the rule too (Payload turns the queue on for scheduled publishing)', () => { + const config = withJobsRunAccess({ secret: 'x' } as Config) + expect(typeof config.jobs?.access?.run).toBe('function') + expect(withJobsRunAccess({ secret: 'x' } as Config, false).jobs).toBeUndefined() + }) + + test('at start: a note when the queue is on, the rule is iapl\'s and the secret is missing', () => { + const custom = { iapl: { jobsRunDefault: { secretVar: 'CRON_SECRET' } } } + vi.stubEnv('CRON_SECRET', '') + expect(jobsRunNotice({ custom, jobs: { enabled: true } })).toMatch(/Authorization: Bearer .*not set/) + expect(jobsRunNotice({ custom, jobs: { enabled: false } })).toBeNull() + expect(jobsRunNotice({ custom: {}, jobs: { enabled: true } })).toBeNull() + vi.stubEnv('CRON_SECRET', SECRET) + expect(jobsRunNotice({ custom, jobs: { enabled: true } })).toBeNull() + }) +}) diff --git a/test/visitorWrites.test.ts b/test/visitorWrites.test.ts new file mode 100644 index 0000000..c6a9157 --- /dev/null +++ b/test/visitorWrites.test.ts @@ -0,0 +1,56 @@ +/** + * The doctor's `visitor-writes` probe (1.17.2, the owner's Q3 answer (b)): on a site with a visitor login collection, + * every collection and global whose write rule lets such an account in — Payload's default "any signed-in account" + * included — is listed. Asked by behaviour on the built config, never by a rule's name. + */ +import type { Config, SanitizedConfig } from 'payload' + +import { sqliteAdapter } from '@payloadcms/db-sqlite' +import { lexicalEditor } from '@payloadcms/richtext-lexical' +import { describe, expect, test, vi } from 'vitest' + +import { adminOrEditor } from '../src/modules/access/access.js' +import { visitorWritableEntities } from '../src/modules/doctor/visitorWrites.js' +import { iapl } from '../src/plugin.js' +import { buildTestConfig } from './helpers.js' + +vi.mock('server-only', () => ({})) + +const i18n = { defaultLocale: 'en', locales: [{ code: 'en', label: 'English' }] } +const build = (collections: Config['collections'], globals: Config['globals'] = []) => + buildTestConfig({ + admin: { user: 'users' }, + collections: [{ slug: 'media', fields: [], upload: true }, ...(collections ?? [])], + db: sqliteAdapter({ client: { url: 'file::memory:' } }), + editor: lexicalEditor(), + globals, + plugins: [iapl({ access: { authCollection: 'users' }, forms: {}, i18n, twoFactor: false } as never)], + secret: 'visitor-writes-test', + telemetry: false, + } as unknown as Config) +/** The live shape the probe reads (`payload.collections`, `payload.config`), from a built config. */ +const live = (config: SanitizedConfig) => ({ collections: Object.fromEntries(config.collections.map((c) => [c.slug, { config: c }])), config }) as never + +describe('visitorWritableEntities', () => { + test('with a visitor login collection: Payload\'s defaults are listed, explicit staff rules and the plugin\'s own are not', async () => { + const config = await build( + [ + { slug: 'customers', access: { create: () => true, delete: () => false, update: ({ req }) => ({ id: { equals: req.user?.id } }) }, auth: true, fields: [] }, + { slug: 'pages', access: { read: () => true }, fields: [{ name: 'title', type: 'text' }] }, + { slug: 'posts', access: { create: adminOrEditor, delete: adminOrEditor, read: () => true, update: adminOrEditor }, fields: [{ name: 'title', type: 'text' }] }, + ], + [{ slug: 'header', access: { read: () => true }, fields: [{ name: 'title', type: 'text' }] }], + ) + const open = await visitorWritableEntities(live(config)) + expect(open).toEqual(expect.arrayContaining(['customers:create', 'globals/header:update', 'media:create', 'media:delete', 'media:update', 'pages:create', 'pages:delete', 'pages:update', 'payload-locked-documents:create'])) + // explicit staff rules, a rule that answers a query, "nobody", the plugin's own entities + for (const closed of ['posts:create', 'posts:update', 'posts:delete', 'customers:update', 'customers:delete', 'form-submissions:create', 'forms:create', 'globals/site-settings:update', 'globals/site-integrations:update', 'payload-kv:create']) { + expect(open).not.toContain(closed) + } + }, 30_000) + + test('a site with only the staff login collection: nothing to report', async () => { + const config = await build([{ slug: 'pages', access: { read: () => true }, fields: [{ name: 'title', type: 'text' }] }]) + expect(await visitorWritableEntities(live(config))).toEqual([]) + }, 30_000) +})