Role checks in client components: export them from /client, fix the docs

access.md and the 1.16.4 upgrade notes led projects to import isAdmin from
'@intecion/ipal-kit' in a client component; with `next build --webpack` that
fails ('server-only' cannot be imported from a Client Component module).
No existing entry had a client-safe one, so '@intecion/ipal-kit/client' now
exports hasMinimumRole, isAdmin, isEditor and the type Role; the main entry
keeps them for server code.

Docs: access.md (snippet with imports, server vs client, useConfig() carries
admin.user only), AGENT.md, ipal-debug, ipal-reference, ipal-upgrade, the
1.16.4 note, an Unreleased changelog entry. Tests: /client reaches no
server-only module, the predicates' answers with a client config, no
client-component example in the docs imports the main entry.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
Radosław Smoliński
2026-11-24 22:00:27 +01:00
co-authored by Claude Opus 5.5
parent 1270ebc3d1
commit de414a81a8
13 changed files with 117 additions and 19 deletions
+19 -2
View File
@@ -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
+19 -4
View File
@@ -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) ? <p>…</p> : 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.
+1 -1
View File
@@ -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**
+2 -1
View File
@@ -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` |
@@ -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`). |
+3 -1
View File
@@ -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 <site>` (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
+2 -1
View File
@@ -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` |
@@ -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`). |
@@ -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 <site>` (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
+4
View File
@@ -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'
+4 -2
View File
@@ -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}
+12
View File
@@ -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))
+42
View File
@@ -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<string>()
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)
})
})