diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md index cc8c1e0..25646b0 100644 --- a/docs/CHANGELOG.md +++ b/docs/CHANGELOG.md @@ -8,6 +8,21 @@ versions at once, go through every "Requires project changes" section in order, version you have. A new release = a new section at the top; we remove the oldest ones only once there are more than 20. +## Unreleased + +### Fixes +- **Role checks in a client component: import `isAdmin`, `isEditor` and `hasMinimumRole` (and the type `Role`) from + `@intecion/ipal-kit/client`.** The advice since 1.16.4 led to importing them from `@intecion/ipal-kit`, which reaches + `server-only` modules: `next build --webpack` fails with `'server-only' cannot be imported from a Client Component + module`. The main entry keeps exporting them for server code; its Turbopack behaviour is unchanged. access.md also + says now what `useConfig()` carries: `admin.user` only, so accounts of `access.staffCollections` need + `{ staffCollections: [...] }`. + +### Requires project changes (what projects must update) +- **Only if a `'use client'` file imports `isAdmin`, `isEditor` or `hasMinimumRole` from `@intecion/ipal-kit`:** + change the import to `@intecion/ipal-kit/client` and keep the second argument (`isAdmin(user, config)`). + `grep -rlE "^['\"]use client" src | xargs grep -nE "from '@intecion/ipal-kit'"` lists the files; `import type` may stay. + ## 1.16.6 > **Read before upgrading — this is not a routine patch.** It turns on a new default for every site with 2FA: an @@ -282,8 +297,10 @@ once there are more than 20. authenticator still works; if it does not, reset that account's 2FA and set it up again. - **`isAdmin` / `isEditor` / `hasMinimumRole` in a client component or in `proxy.ts` / middleware** return `false` unless they are told which collections are staff: `isAdmin(user, config)` with the config from `useConfig()`, or - `isAdmin(user, { staffCollections: ['users'] })`. On the server (`isAdmin(req.user)` in hooks, endpoints, access - functions) nothing changes; `isAdmin(req.user, req.payload)` is the explicit form. + `isAdmin(user, { staffCollections: ['users'] })`. A client component imports them from `@intecion/ipal-kit/client` + (corrected later: the main entry, which this note implied, does not build there with webpack; `/client` has them + in the version after 1.16.6). On the server (`isAdmin(req.user)` in hooks, endpoints, access functions) nothing + changes; `isAdmin(req.user, req.payload)` is the explicit form. - **A second staff collection (`access.staffCollections`) is not covered by 2FA** — the log says so at start. - **Own code that reads a plugin collection or global with `overrideAccess: false`** must pass a `user` from `payload.auth({ headers })`; a user fetched by id and passed by hand is refused when it has TOTP set up, and its diff --git a/docs/access.md b/docs/access.md index 827a07a..0219369 100644 --- a/docs/access.md +++ b/docs/access.md @@ -135,16 +135,31 @@ which collections are staff: | Where you call it | Pass | Without it | |---|---|---| | access functions, hooks, endpoints (server, the config is loaded) | `req.payload` | works: the staff collections of the config `ipalKit` built in this process. With two different configs in one process, only collections that are staff in **both** count — pass `req.payload` to get that config's own answer | -| client components | the config from `useConfig()` (it has `admin.user`), or `{ staffCollections: ['users', …] }` | **always `false`** — the browser bundle has no config | +| client components — import from **`@intecion/ipal-kit/client`** | the config from `useConfig()` (it has `admin.user`, the panel's login collection), or `{ staffCollections: ['users', …] }` | **always `false`** — the browser bundle has no config | | Next middleware / `proxy.ts`, the edge runtime | `{ staffCollections: ['users'] }` | **always `false`** — the config is not loaded there | ```tsx 'use client' -const { config } = useConfig() -const { user } = useAuth() -if (isAdmin(user, config)) { /* show the button — a hint only, the server decides */ } +import { isAdmin } from '@intecion/ipal-kit/client' // not '@intecion/ipal-kit' +import { useAuth, useConfig } from '@payloadcms/ui' + +export function AdminOnlyHint() { + const { config } = useConfig() + const { user } = useAuth() + // a hint only — the server decides + return isAdmin(user, config) ?

…

: null +} ``` +- **The import in a client component is `/client`** (`hasMinimumRole`, `isAdmin`, `isEditor`, the type `Role`). The main + entry reaches `server-only` modules: with `next build --webpack` it fails with `'server-only' cannot be imported from + a Client Component module` (Turbopack builds it, but the import does not belong there either). + In 1.16.4–1.16.6 `/client` does not have them — upgrade. +- **On the server** (config, hooks, access functions, endpoints, server components, `proxy.ts`) import from + `@intecion/ipal-kit`: `/client` is a `'use client'` entry, a server component that calls a function from it fails. +- `useConfig()` carries `admin.user` only (Payload strips `config.custom` from the client config). Accounts of + `access.staffCollections` need the list: `isAdmin(user, { staffCollections: ['users', 'partners'] })`. + They fail closed: where the staff collections are not known, nobody is staff, and an account without `collection` is nobody. `isAdmin` and the others do **not** check the second factor; `userMeetsRole` and every `access` function in the config do. diff --git a/docs/agent/AGENT.md b/docs/agent/AGENT.md index 8c0a9f1..5c8b594 100644 --- a/docs/agent/AGENT.md +++ b/docs/agent/AGENT.md @@ -1059,7 +1059,7 @@ project → **plugin gap**, not a copy. | ISR after save, old slug → 308, images across languages | `buildRevalidateHook`, `trackSlugHistoryHook`, `buildCrossLocaleFieldSync` | hooks.md | | ISR after a global is saved | plugin globals: `ipalKit({ revalidatePath })`; your own globals: `buildGlobalRevalidateHook({ revalidatePath })` | hooks.md | | Change a plugin global (access, hooks, fields) | `ipalKit({ globalOverrides })` | access.md | -| Roles and access | `adminOnly`, `adminOrEditor`, `adminOrSelf`, `adminOrSelfIn(slug)` (several auth collections), `authenticated`, `requireRole`, `hasMinimumRole` (+ `…Field`); staff checks: `userMeetsRole(req, role)`, `isAdmin(req.user, req.payload)` (roles count only for accounts of a staff collection; in a client component `isAdmin(user, config)` with `useConfig()`, in middleware `isAdmin(user, { staffCollections: ['users'] })` — without the last argument there it is always `false`), `staffCollectionSlugs(payload)`, `access.staffCollections`; second factor in your own code: `secondFactorPassed(req)`, `requireSecondFactor(access)`; injected `users`: `access.authAccess`, first user = admin (`access.firstUserAdmin`) | access.md, security.md | +| Roles and access | `adminOnly`, `adminOrEditor`, `adminOrSelf`, `adminOrSelfIn(slug)` (several auth collections), `authenticated`, `requireRole`, `hasMinimumRole` (+ `…Field`); staff checks: `userMeetsRole(req, role)`, `isAdmin(req.user, req.payload)` (roles count only for accounts of a staff collection; in a client component `isAdmin(user, config)` with `useConfig()`, imported from **`@intecion/ipal-kit/client`** (the main entry does not build there with webpack), in middleware `isAdmin(user, { staffCollections: ['users'] })` — without the last argument there it is always `false`), `staffCollectionSlugs(payload)`, `access.staffCollections`; second factor in your own code: `secondFactorPassed(req)`, `requireSecondFactor(access)`; injected `users`: `access.authAccess`, first user = admin (`access.firstUserAdmin`) | access.md, security.md | | Data from globals | `getGlobal`, `getSiteSettings`, `getSiteIntegrations` | payload-helpers.md | **Links and navigation** diff --git a/docs/agent/skills/ipal-debug/SKILL.md b/docs/agent/skills/ipal-debug/SKILL.md index f30051e..51f7e76 100644 --- a/docs/agent/skills/ipal-debug/SKILL.md +++ b/docs/agent/skills/ipal-debug/SKILL.md @@ -36,7 +36,8 @@ through this procedure. Ask only when you are missing something you cannot get y |---|---|---| | the 2FA code screen answers "Too many codes were tried…" (`429` from `/api/verify-totp`) | more than 5 verify attempts for that account in 10 minutes (`twoFactor.verifyLimit`); repeated lines `[ipal] 2FA: too many verify attempts` in the log without the owner trying = someone has the password | wait for the window, enter the current code once; unexplained attempts: change that account's password. Tests that log in often: `verifyLimit: { max: … }` for that environment | | `isAdmin(req.user)` says `false` for a real administrator on the server, in a process that loads two Payload configs (tests, a multi-site script) | a call without a source counts only collections that are staff in **every** config of the process | pass the source: `isAdmin(req.user, req.payload)` — with it each config gets its own answer | -| `isAdmin(user)` / `isEditor(user)` is always `false` in a client component or in `proxy.ts` | the staff collections are not known there (no config in the browser bundle / middleware), and the predicates fail closed | `isAdmin(user, config)` with `useConfig()`; in middleware `isAdmin(user, { staffCollections: ['users'] })` | +| `isAdmin(user)` / `isEditor(user)` is always `false` in a client component or in `proxy.ts` | the staff collections are not known there (no config in the browser bundle / middleware), and the predicates fail closed | `isAdmin(user, config)` with `useConfig()`, imported from `@intecion/ipal-kit/client`; in middleware `isAdmin(user, { staffCollections: ['users'] })` | +| `next build --webpack`: `'server-only' cannot be imported from a Client Component module … caused by importing '@intecion/ipal-kit/dist/index.js'` | a `'use client'` file imports the main entry (Turbopack lets it pass) | import from `@intecion/ipal-kit/client` (role predicates are there after 1.16.6; types: `import type` from the main entry is fine); data the browser needs → a prop from a server component | | an account logs in but every page and request answers 403 / the setup screen says "The time to set up two-step verification has passed" | 2FA setup required: the account did not set TOTP up within the window (72 h from its creation, an admin's reset, or the first start after the upgrade) | an administrator opens the account in the panel → Two-step verification → "Reopen setup" (or `POST /api/ipal/two-factor/reset` `{ userId }`); every administrator is blocked: security.md "Every administrator is blocked" — a script with the Local API, `payload.update({ collection: 'users', id, data: { totpSetupFrom: new Date().toISOString() } })` (`pnpm payload run`), then log in and set TOTP up; or `requireSetup: { windowHours: false }`, redeploy, set up, put it back | | a new account gets `403` from the API although its role allows the request | 2FA setup required: until TOTP is set up the account reaches only the setup screen | set TOTP up (log in to the panel); an integration: use an API key, or `twoFactor.requireSetup.exempt` | | after an upgrade EVERY panel login answers `500` (also `/api/users/init`), administrators with 2FA included; log: `[ipal] 2FA: the column for "totpSetupFrom" is missing … NOBODY CAN LOG IN` or `column users.totp_setup_from does not exist` | Postgres/SQLite: the migration that adds the 2FA column has not run (needed whenever 2FA is on) | `pnpm payload migrate:create` if no migration has it, commit, and redeploy with migrations run when the new container starts — `prodMigrations` in the adapter or the start command `pnpm payload migrate && pnpm start` (deployment.md §4.3; not Coolify's Pre-deployment command, which runs in the old container); nothing is lost. `ipal-doctor` reports a project whose migrations lack `totp_setup_from` | diff --git a/docs/agent/skills/ipal-reference/resources/api.md b/docs/agent/skills/ipal-reference/resources/api.md index 397bca1..fee8921 100644 --- a/docs/agent/skills/ipal-reference/resources/api.md +++ b/docs/agent/skills/ipal-reference/resources/api.md @@ -63,9 +63,9 @@ Admin panel components from `@intecion/ipal-kit/admin` — the project does NOT | `adminOnlyField` | `@intecion/ipal-kit` | `FieldAccess` (boolean only): field for admin only. In `field.access.read/update`. | | `adminOrEditorField` | `@intecion/ipal-kit` | `FieldAccess`: field for editor or admin. | | `requireRoleField(minimum)` | `@intecion/ipal-kit` | `FieldAccess` factory: at least the given role. | -| `hasMinimumRole(user, minimum, source?)` | `@intecion/ipal-kit` | Predicate → `boolean`: the user is an account of a **staff collection** and has a role ≥ `minimum` (reads `user.roles` and `user.collection` safely). A role on an account of another auth collection never counts. `source` says which collections are staff: `req.payload` on the server, the config from `useConfig()` in a client component, or `{ staffCollections: ['users'] }` (middleware). Without it: the staff collections of the config ipalKit built in this process (two different configs: only what both call staff) — and **`false` where there is none** (browser bundle, middleware, edge). Does not check the second factor. | -| `isAdmin(user, source?)` | `@intecion/ipal-kit` | Predicate → `boolean`: staff account with the `admin` role (see `hasMinimumRole`). In hooks and endpoints: `isAdmin(req.user, req.payload)`; in a client component: `isAdmin(user, config)`. | -| `isEditor(user, source?)` | `@intecion/ipal-kit` | Predicate → `boolean`: staff account with `editor` or higher. | +| `hasMinimumRole(user, minimum, source?)` | `@intecion/ipal-kit`; in client components `@intecion/ipal-kit/client` | Predicate → `boolean`: the user is an account of a **staff collection** and has a role ≥ `minimum` (reads `user.roles` and `user.collection` safely). A role on an account of another auth collection never counts. `source` says which collections are staff: `req.payload` on the server, the config from `useConfig()` in a client component (it has `admin.user` only; for `access.staffCollections` pass the list), or `{ staffCollections: ['users'] }` (middleware). Without it: the staff collections of the config ipalKit built in this process (two different configs: only what both call staff) — and **`false` where there is none** (browser bundle, middleware, edge). Does not check the second factor. | +| `isAdmin(user, source?)` | `@intecion/ipal-kit`; in client components `@intecion/ipal-kit/client` | Predicate → `boolean`: staff account with the `admin` role (see `hasMinimumRole`). In hooks and endpoints: `isAdmin(req.user, req.payload)`; in a client component: `isAdmin(user, config)` from `/client` — the main entry does not build there with webpack (`'server-only' cannot be imported…`). | +| `isEditor(user, source?)` | `@intecion/ipal-kit`; in client components `@intecion/ipal-kit/client` | Predicate → `boolean`: staff account with `editor` or higher. | | `userMeetsRole(req, minimum)` | `@intecion/ipal-kit` | Predicate → `boolean` with `req` (`{ payload, user }`), in this order: the account belongs to a **staff collection** (`admin.user`, `access.authCollection`, `access.staffCollections`); with 2FA on it has passed the second factor (`secondFactorPassed`); it has a role ≥ `minimum`, **or** its collection has no `roles` field (the project omitted `access`). An account of any other auth collection never passes, whatever fields it has. The plugin's staff features (Site integrations, settings globals, form submissions, consent records, stats, cookie scanner, the e-mail test) use it; use it in your own endpoints. | | `staffCollectionSlugs(source?)` | `@intecion/ipal-kit` | `string[]`: the staff collections — `admin.user`, `access.authCollection` and `access.staffCollections` — from `req.payload`, a config or `{ staffCollections }`; without an argument what the configs built in this process agree on (`[]` when there is none). Roles and staff checks count only for accounts of these. | | `ROLE_HIERARCHY` | `@intecion/ipal-kit` | Constant `['user', 'editor', 'admin']` (lowest first) — a higher role meets the requirements of a lower one. The plugin injects the `roles` field into the auth collection (`access.authCollection`). | diff --git a/docs/agent/skills/ipal-upgrade/SKILL.md b/docs/agent/skills/ipal-upgrade/SKILL.md index ed623c8..408d559 100644 --- a/docs/agent/skills/ipal-upgrade/SKILL.md +++ b/docs/agent/skills/ipal-upgrade/SKILL.md @@ -350,7 +350,9 @@ for every site:** `isAdmin(req.user)` keeps working on the server; prefer `isAdmin(req.user, req.payload)`. `grep -rnE "isAdmin\(|isEditor\(|hasMinimumRole\(" src` — a call in a **client component** or in `proxy.ts` / middleware now returns `false` without a source: `isAdmin(user, config)` (`useConfig()`), or - `isAdmin(user, { staffCollections: ['users'] })`. + `isAdmin(user, { staffCollections: ['users'] })`. A **client component imports them from + `@intecion/ipal-kit/client`** (not in 1.16.4–1.16.6: go to the next version); the main entry there fails with + `next build --webpack` (`'server-only' cannot be imported from a Client Component module`). 4. `pnpm exec ipal-doctor --url ` (with the doctor token) → accounts without 2FA must be 0. An account that has not set TOTP up opens everything with its password alone: have its owner set it up now, or remove it. 5. Tell the owner what the CHANGELOG entry says under "Requires project changes" and agree on it: new SMTP diff --git a/reference/.agents/skills/ipal-debug/SKILL.md b/reference/.agents/skills/ipal-debug/SKILL.md index f30051e..51f7e76 100644 --- a/reference/.agents/skills/ipal-debug/SKILL.md +++ b/reference/.agents/skills/ipal-debug/SKILL.md @@ -36,7 +36,8 @@ through this procedure. Ask only when you are missing something you cannot get y |---|---|---| | the 2FA code screen answers "Too many codes were tried…" (`429` from `/api/verify-totp`) | more than 5 verify attempts for that account in 10 minutes (`twoFactor.verifyLimit`); repeated lines `[ipal] 2FA: too many verify attempts` in the log without the owner trying = someone has the password | wait for the window, enter the current code once; unexplained attempts: change that account's password. Tests that log in often: `verifyLimit: { max: … }` for that environment | | `isAdmin(req.user)` says `false` for a real administrator on the server, in a process that loads two Payload configs (tests, a multi-site script) | a call without a source counts only collections that are staff in **every** config of the process | pass the source: `isAdmin(req.user, req.payload)` — with it each config gets its own answer | -| `isAdmin(user)` / `isEditor(user)` is always `false` in a client component or in `proxy.ts` | the staff collections are not known there (no config in the browser bundle / middleware), and the predicates fail closed | `isAdmin(user, config)` with `useConfig()`; in middleware `isAdmin(user, { staffCollections: ['users'] })` | +| `isAdmin(user)` / `isEditor(user)` is always `false` in a client component or in `proxy.ts` | the staff collections are not known there (no config in the browser bundle / middleware), and the predicates fail closed | `isAdmin(user, config)` with `useConfig()`, imported from `@intecion/ipal-kit/client`; in middleware `isAdmin(user, { staffCollections: ['users'] })` | +| `next build --webpack`: `'server-only' cannot be imported from a Client Component module … caused by importing '@intecion/ipal-kit/dist/index.js'` | a `'use client'` file imports the main entry (Turbopack lets it pass) | import from `@intecion/ipal-kit/client` (role predicates are there after 1.16.6; types: `import type` from the main entry is fine); data the browser needs → a prop from a server component | | an account logs in but every page and request answers 403 / the setup screen says "The time to set up two-step verification has passed" | 2FA setup required: the account did not set TOTP up within the window (72 h from its creation, an admin's reset, or the first start after the upgrade) | an administrator opens the account in the panel → Two-step verification → "Reopen setup" (or `POST /api/ipal/two-factor/reset` `{ userId }`); every administrator is blocked: security.md "Every administrator is blocked" — a script with the Local API, `payload.update({ collection: 'users', id, data: { totpSetupFrom: new Date().toISOString() } })` (`pnpm payload run`), then log in and set TOTP up; or `requireSetup: { windowHours: false }`, redeploy, set up, put it back | | a new account gets `403` from the API although its role allows the request | 2FA setup required: until TOTP is set up the account reaches only the setup screen | set TOTP up (log in to the panel); an integration: use an API key, or `twoFactor.requireSetup.exempt` | | after an upgrade EVERY panel login answers `500` (also `/api/users/init`), administrators with 2FA included; log: `[ipal] 2FA: the column for "totpSetupFrom" is missing … NOBODY CAN LOG IN` or `column users.totp_setup_from does not exist` | Postgres/SQLite: the migration that adds the 2FA column has not run (needed whenever 2FA is on) | `pnpm payload migrate:create` if no migration has it, commit, and redeploy with migrations run when the new container starts — `prodMigrations` in the adapter or the start command `pnpm payload migrate && pnpm start` (deployment.md §4.3; not Coolify's Pre-deployment command, which runs in the old container); nothing is lost. `ipal-doctor` reports a project whose migrations lack `totp_setup_from` | diff --git a/reference/.agents/skills/ipal-reference/resources/api.md b/reference/.agents/skills/ipal-reference/resources/api.md index 397bca1..fee8921 100644 --- a/reference/.agents/skills/ipal-reference/resources/api.md +++ b/reference/.agents/skills/ipal-reference/resources/api.md @@ -63,9 +63,9 @@ Admin panel components from `@intecion/ipal-kit/admin` — the project does NOT | `adminOnlyField` | `@intecion/ipal-kit` | `FieldAccess` (boolean only): field for admin only. In `field.access.read/update`. | | `adminOrEditorField` | `@intecion/ipal-kit` | `FieldAccess`: field for editor or admin. | | `requireRoleField(minimum)` | `@intecion/ipal-kit` | `FieldAccess` factory: at least the given role. | -| `hasMinimumRole(user, minimum, source?)` | `@intecion/ipal-kit` | Predicate → `boolean`: the user is an account of a **staff collection** and has a role ≥ `minimum` (reads `user.roles` and `user.collection` safely). A role on an account of another auth collection never counts. `source` says which collections are staff: `req.payload` on the server, the config from `useConfig()` in a client component, or `{ staffCollections: ['users'] }` (middleware). Without it: the staff collections of the config ipalKit built in this process (two different configs: only what both call staff) — and **`false` where there is none** (browser bundle, middleware, edge). Does not check the second factor. | -| `isAdmin(user, source?)` | `@intecion/ipal-kit` | Predicate → `boolean`: staff account with the `admin` role (see `hasMinimumRole`). In hooks and endpoints: `isAdmin(req.user, req.payload)`; in a client component: `isAdmin(user, config)`. | -| `isEditor(user, source?)` | `@intecion/ipal-kit` | Predicate → `boolean`: staff account with `editor` or higher. | +| `hasMinimumRole(user, minimum, source?)` | `@intecion/ipal-kit`; in client components `@intecion/ipal-kit/client` | Predicate → `boolean`: the user is an account of a **staff collection** and has a role ≥ `minimum` (reads `user.roles` and `user.collection` safely). A role on an account of another auth collection never counts. `source` says which collections are staff: `req.payload` on the server, the config from `useConfig()` in a client component (it has `admin.user` only; for `access.staffCollections` pass the list), or `{ staffCollections: ['users'] }` (middleware). Without it: the staff collections of the config ipalKit built in this process (two different configs: only what both call staff) — and **`false` where there is none** (browser bundle, middleware, edge). Does not check the second factor. | +| `isAdmin(user, source?)` | `@intecion/ipal-kit`; in client components `@intecion/ipal-kit/client` | Predicate → `boolean`: staff account with the `admin` role (see `hasMinimumRole`). In hooks and endpoints: `isAdmin(req.user, req.payload)`; in a client component: `isAdmin(user, config)` from `/client` — the main entry does not build there with webpack (`'server-only' cannot be imported…`). | +| `isEditor(user, source?)` | `@intecion/ipal-kit`; in client components `@intecion/ipal-kit/client` | Predicate → `boolean`: staff account with `editor` or higher. | | `userMeetsRole(req, minimum)` | `@intecion/ipal-kit` | Predicate → `boolean` with `req` (`{ payload, user }`), in this order: the account belongs to a **staff collection** (`admin.user`, `access.authCollection`, `access.staffCollections`); with 2FA on it has passed the second factor (`secondFactorPassed`); it has a role ≥ `minimum`, **or** its collection has no `roles` field (the project omitted `access`). An account of any other auth collection never passes, whatever fields it has. The plugin's staff features (Site integrations, settings globals, form submissions, consent records, stats, cookie scanner, the e-mail test) use it; use it in your own endpoints. | | `staffCollectionSlugs(source?)` | `@intecion/ipal-kit` | `string[]`: the staff collections — `admin.user`, `access.authCollection` and `access.staffCollections` — from `req.payload`, a config or `{ staffCollections }`; without an argument what the configs built in this process agree on (`[]` when there is none). Roles and staff checks count only for accounts of these. | | `ROLE_HIERARCHY` | `@intecion/ipal-kit` | Constant `['user', 'editor', 'admin']` (lowest first) — a higher role meets the requirements of a lower one. The plugin injects the `roles` field into the auth collection (`access.authCollection`). | diff --git a/reference/.agents/skills/ipal-upgrade/SKILL.md b/reference/.agents/skills/ipal-upgrade/SKILL.md index ed623c8..408d559 100644 --- a/reference/.agents/skills/ipal-upgrade/SKILL.md +++ b/reference/.agents/skills/ipal-upgrade/SKILL.md @@ -350,7 +350,9 @@ for every site:** `isAdmin(req.user)` keeps working on the server; prefer `isAdmin(req.user, req.payload)`. `grep -rnE "isAdmin\(|isEditor\(|hasMinimumRole\(" src` — a call in a **client component** or in `proxy.ts` / middleware now returns `false` without a source: `isAdmin(user, config)` (`useConfig()`), or - `isAdmin(user, { staffCollections: ['users'] })`. + `isAdmin(user, { staffCollections: ['users'] })`. A **client component imports them from + `@intecion/ipal-kit/client`** (not in 1.16.4–1.16.6: go to the next version); the main entry there fails with + `next build --webpack` (`'server-only' cannot be imported from a Client Component module`). 4. `pnpm exec ipal-doctor --url ` (with the doctor token) → accounts without 2FA must be 0. An account that has not set TOTP up opens everything with its password alone: have its owner set it up now, or remove it. 5. Tell the owner what the CHANGELOG entry says under "Requires project changes" and agree on it: new SMTP diff --git a/src/exports/client.ts b/src/exports/client.ts index 1395dda..3f0e0d8 100644 --- a/src/exports/client.ts +++ b/src/exports/client.ts @@ -1,4 +1,8 @@ 'use client' +// Role predicates for client components (the main entry reaches 'server-only' modules and does not build +// there with webpack). Concrete file, not the access barrel. On the server import them from the main entry. +export { hasMinimumRole, isAdmin, isEditor } from '../modules/access/predicates.js' +export type { Role } from '../modules/access/types.js' export { A11Y_DEFAULT_TEXTS, AccessibilityProvider, AccessibilityWidget, useAccessibility } from '../modules/accessibility/client.js' export type { A11yClassNames, A11yState, A11yTexts } from '../modules/accessibility/client.js' export { Analytics } from '../modules/analytics/client.js' diff --git a/src/modules/access/predicates.ts b/src/modules/access/predicates.ts index 3dfaa9a..e328599 100644 --- a/src/modules/access/predicates.ts +++ b/src/modules/access/predicates.ts @@ -86,7 +86,8 @@ export function staffCollectionSlugs(source?: MaybePayload): string[] { * - where the staff collections are not known — no source given and ipalKit * never ran in this bundle (client components, Next middleware, the edge * runtime) — nobody is staff. Pass the source there: `isAdmin(user, config)` - * with the config from `useConfig()`, or `isAdmin(user, { staffCollections: ['users'] })`. + * with the config from `useConfig()` (client components import from + * '@intecion/ipal-kit/client'), or `isAdmin(user, { staffCollections: ['users'] })`. */ function isStaffAccount(user: MaybeUser, source?: MaybePayload): boolean { if (!user || typeof user !== 'object') {return false} @@ -117,7 +118,8 @@ function highestRoleIndex(user: MaybeUser): number { * functions, hooks, endpoints); without it the staff collections of the * config ipalKit built in this process are used — and where there is none * (a browser bundle, middleware) the answer is false: pass the config from - * `useConfig()` or `{ staffCollections: ['users'] }` there. + * `useConfig()` or `{ staffCollections: ['users'] }` there. A client component + * imports it from '@intecion/ipal-kit/client': the main entry does not build there with webpack. */ export function hasMinimumRole(user: MaybeUser, minimum: Role, payload?: MaybePayload): boolean { if (!isStaffAccount(user, payload)) {return false} diff --git a/test/docsConsistency.test.ts b/test/docsConsistency.test.ts index a063321..43cf4cd 100644 --- a/test/docsConsistency.test.ts +++ b/test/docsConsistency.test.ts @@ -149,6 +149,18 @@ describe('docs ↔ code', () => { expect(broken).toEqual([]) }) + test('no client-component example imports the main entry', () => { + // '@intecion/ipal-kit' reaches server-only modules: a 'use client' file that imports it does not build with webpack. + const offending: string[] = [] + for (const file of docs) { + const blocks = file.endsWith('.md') ? [...read(file).matchAll(/```[a-z]*\n([\s\S]*?)```/g)].map((m) => m[1]) : [read(file)] + for (const block of blocks) { + if (/^['"]use client['"]/m.test(block) && /^import (?!type\b)[^'"]*?from ['"]@intecion\/ipal-kit['"]/m.test(block)) {offending.push(file)} + } + } + expect(offending).toEqual([]) + }) + test('every module page is listed in docs/README.md', () => { const index = read('docs/README.md') const pages = readdirSync(path.join(root, 'docs')).filter((n) => n.endsWith('.md') && !['CHANGELOG.md', 'README.md'].includes(n)) diff --git a/test/entryGraph.test.ts b/test/entryGraph.test.ts index e7d04e4..d4fc917 100644 --- a/test/entryGraph.test.ts +++ b/test/entryGraph.test.ts @@ -42,3 +42,45 @@ describe('server entries load no client modules', () => { expect(clientModulesReachable(entry)).toEqual([]) }) }) + +/** Modules importing 'server-only' reachable from `entry` — static and dynamic imports (a bundler follows both). */ +function serverOnlyReachable(entry: string): string[] { + const seen = new Set() + const hits: string[] = [] + const stack = [path.join(root, entry)] + while (stack.length) { + const file = stack.pop()! + if (seen.has(file)) {continue} + seen.add(file) + const src = readFileSync(file, 'utf8') + if (/^import ['"]server-only['"]/m.test(src)) {hits.push(path.relative(root, file))} + for (const m of src.matchAll(/^(?:import|export) (?!type\b)[^'"]*?from ['"]([^'"]+)['"]|\bimport\(\s*['"]([^'"]+)['"]/gm)) { + const next = resolve(file, m[1] ?? m[2]) + if (next) {stack.push(next)} + } + } + return hits.sort() +} + +describe('client components', () => { + test('/client reaches no server-only module', () => { + expect(serverOnlyReachable('src/exports/client.ts')).toEqual([]) + // why a client component must not import the main entry: webpack stops at these + expect(serverOnlyReachable('src/index.ts')).not.toEqual([]) + }) + + test('/client exports the role predicates, with the same fail-closed answers', async () => { + const { hasMinimumRole, isAdmin, isEditor } = await import('../src/modules/access/predicates.js') + const client = readFileSync(path.join(root, 'src/exports/client.ts'), 'utf8') + expect(client).toMatch(/export \{ hasMinimumRole, isAdmin, isEditor \} from '\.\.\/modules\/access\/predicates\.js'/) + const config = { admin: { user: 'users' } } // what useConfig() carries: `custom` is not in the client config + const admin = { collection: 'users', roles: ['admin'] } + const editor = { collection: 'users', roles: ['editor'] } + expect([isAdmin(admin, config), isAdmin(editor, config), isAdmin(null, config)]).toEqual([true, false, false]) + expect([isEditor(editor, config), hasMinimumRole(editor, 'user', config)]).toEqual([true, true]) + expect(isAdmin({ ...admin, collection: 'customers' }, config)).toBe(false) + // access.staffCollections is not in the client config: name the collections + expect(isAdmin({ ...admin, collection: 'partners' }, config)).toBe(false) + expect(isAdmin({ ...admin, collection: 'partners' }, { staffCollections: ['users', 'partners'] })).toBe(true) + }) +})