From a87742621adff978019ef380d133a67f20d737b3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rados=C5=82aw=20Smoli=C5=84ski?= Date: Thu, 22 Oct 2026 17:23:14 +0200 Subject: [PATCH] Access defaults overridable; unlock admin-only; 2FA target validated - access.authAccess merges over the injected auth collection's access; unlock is admin-only by default - access.firstUserAdmin (default true) makes the first-register promotion optional - globalOverrides: object merges access/admin/hooks, function takes over - form Emails protection is applied before formOverrides.fields, so a project can change it there - 2FA defaults to admin.user and fails at init when the target is not an auth collection or differs from admin.user (twoFactor.allowCollectionMismatch) - buildRolesField, injectRoles, applyGlobalOverrides exported Co-Authored-By: Claude Opus 5.5 --- docs/access.md | 102 +++++++++++++++++------- docs/security.md | 10 ++- src/globals/overrides.ts | 44 +++++++++++ src/index.ts | 4 + src/modules/access/injectRoles.ts | 2 +- src/modules/access/rolesField.ts | 27 ++++--- src/modules/access/types.ts | 16 ++++ src/modules/forms/formsPluginConfig.ts | 10 ++- src/plugin.ts | 56 +++++++++---- src/types.ts | 23 +++++- test/accessControl.test.ts | 105 +++++++++++++++++++++++-- 11 files changed, 334 insertions(+), 65 deletions(-) create mode 100644 src/globals/overrides.ts diff --git a/docs/access.md b/docs/access.md index ac066bb..64617ac 100644 --- a/docs/access.md +++ b/docs/access.md @@ -9,39 +9,63 @@ predykaty oraz gotowe funkcje dostępu (collection-level i field-level). ```ts ipalKit({ access: { - authCollection: 'users', // slug Twojej kolekcji auth - // defaultRole: 'user', // rola nowych użytkowników, domyślnie 'user' + authCollection: 'users', // slug Twojej kolekcji auth (wymagane) + // defaultRole: 'user', // rola nowych kont + // firstUserAdmin: true, // konto z „Create first user” → admin + // authAccess: { … }, // access wstrzykniętej kolekcji auth (Twoje klucze wygrywają) + }, + // globalOverrides: { … }, // access / admin / hooks / pola globali pluginu +}) +``` + +| Opcja | Domyślnie | Co robi | +|---|---|---| +| `access.authCollection` | — (wymagane) | kolekcja auth, do której trafia pole `roles` | +| `access.defaultRole` | `'user'` | rola nowego konta, gdy nie nadał jej admin | +| `access.firstUserAdmin` | `true` | konto z ekranu „Create first user” (`…/first-register` na pustej kolekcji) dostaje `['admin']`, nawet gdy formularz wybrał `user`; `false` = dostaje to, co wysłano | +| `access.authAccess` | patrz tabela niżej | `access` **wstrzykniętej** kolekcji auth, scalany z domyślnym (Twoje klucze wygrywają) | +| `globalOverrides` | — | zmiana globali pluginu: obiekt scala `access` / `admin` / `hooks` (Twoje klucze wygrywają), funkcja `(global) => global` przejmuje całość | + +Pole `roles` (select hasMany, wymagane, `saveToJWT`): odczyt bez ograniczeń, nadawanie i +zmiana tylko przez admina — także przy tworzeniu konta, więc otwarta rejestracja nie +przepuści `roles: ['admin']`. Ekran pierwszego użytkownika i Local API (seed) działają z +`overrideAccess`. Konto bez ról nie spełnia żadnego progu (nawet `'user'`); `authenticated` +sprawdza tylko zalogowanie. + +**Kolekcja auth, gdy projekt jej nie ma.** Plugin dokłada minimalną kolekcję (`auth: true`, +`admin.useAsTitle: 'email'`) o slugu `access.authCollection` (albo `twoFactor.collectionSlug`, +`admin.user`, `'users'`). Własna kolekcja projektu o tym slugu zawsze wygrywa w całości. + +## Co plugin zamyka sam + +| Zasób | Odczyt | Zapis | Jak zmienić | +|---|---|---|---| +| kolekcja auth **wstrzyknięta** przez plugin, z rolami | admin: wszyscy; inni: tylko siebie | `create` / `delete` / `unlock`: admin; `update`: admin albo siebie | `access.authAccess`, albo własna kolekcja | +| Site Settings, Cookie Settings, Notifications | publiczny | `editor+` | `globalOverrides` | +| Site Integrations | admin | admin | `globalOverrides` | +| Forms | publiczny (zakładka Emails tylko `editor+`) | `editor+` | `forms.formOverrides.access`, pole Emails w `formOverrides.fields` | +| Form submissions | `editor+` | REST `create`: zalogowani; `delete`: admin | `forms.formSubmissionOverrides.access` | + +```ts +import { authenticated } from '@intecion/ipal-kit' +ipalKit({ + access: { authCollection: 'users', authAccess: { read: authenticated } }, // edytorzy widzą listę kont + globalOverrides: { + notifications: { access: { update: authenticated } }, // każdy zalogowany edytuje teksty + 'site-settings': (g) => ({ ...g, admin: { ...g.admin, group: 'Ustawienia' } }), }, }) ``` -Wstrzykuje pole `roles` (select hasMany, `saveToJWT`, tylko admin może -nadawać i zmieniać role — także przy tworzeniu konta, więc otwarta rejestracja nie -przepuści `roles: ['admin']`; nie-admin dostaje `defaultRole`) do wskazanej kolekcji. -Ekran pierwszego użytkownika i Local API (seed) działają z `overrideAccess`, więc -pierwszego admina nadal da się utworzyć. **Konto z ekranu „Create first user” -(`…/first-register` na pustej kolekcji) zawsze dostaje `roles: ['admin']`** (hook pola), nawet gdy ekran -nie pokazuje pola ról. Otwarta rejestracja (zwykłe `create`) na pustej kolekcji dostaje `defaultRole`. Kolekcja należy do Ciebie -(create-payload-app) — plugin tylko dokłada pole. - -## Co plugin zamyka sam - -| Zasób | Odczyt | Zapis | -|---|---|---| -| kolekcja auth **wstrzyknięta** przez plugin (gdy projekt nie ma własnej) i z rolami | admin: wszyscy; inni: tylko siebie | `create`/`delete`: admin; `update`: admin albo siebie | -| Site Settings, Cookie Settings, Notifications | publiczny | `editor+` | -| Site Integrations | admin | admin | -| Forms | publiczny (bez zakładki Emails — ta tylko `editor+`) | `editor+` | -| Form submissions | `editor+` | REST `create`: zalogowani; `delete`: admin | - Własna kolekcja auth projektu zachowuje własne `access` — plugin dokłada tylko pole -`roles`. Ustaw jej co najmniej `update: adminOrSelf`, `delete: adminOnly`, `create: adminOnly`: -domyślny Payload pozwala każdemu zalogowanemu zmienić e-mail i hasło innego konta. -Kolekcja wstrzyknięta **bez** `access` (brak ról) zostaje przy domyślnych regułach Payloada — -bez ról wszystkie konta są równe. +`roles`. Ustaw jej co najmniej `update: adminOrSelf`, `delete: adminOnly`, `create: adminOnly`, +`unlock: adminOnly`: domyślny Payload pozwala każdemu zalogowanemu zmienić e-mail i hasło +innego konta i odblokować dowolne konto. Kolekcja wstrzyknięta **bez** `access` (brak ról) +zostaje przy domyślnych regułach Payloada — bez ról wszystkie konta są równe. -> Po dodaniu: zadbaj, by seed / pierwszy user miał `roles: ['admin']`, inaczej -> stracisz dostęp do zasobów admin-only (np. SiteIntegrations). +> **Bez `access` nie ma pola `roles`**, więc `isAdmin` zawsze zwraca `false`: global Site +> Integrations i endpoint `/api/ipal/test-email` działają wtedy tylko przez Local API +> (`overrideAccess`). Seed / pierwszy user musi mieć `roles: ['admin']`. ## Predykaty (front / hooki / access) @@ -98,3 +122,27 @@ import { adminOnlyField, adminOrEditorField, requireRoleField } from '@intecion/ import { ROLE_HIERARCHY } from '@intecion/ipal-kit' // ['user', 'editor', 'admin'] — wyższa rola spełnia wymóg niższej ``` + +## Klocki: buildRolesField, injectRoles, applyGlobalOverrides + +```ts +import { applyGlobalOverrides, buildRolesField, injectRoles } from '@intecion/ipal-kit' + +buildRolesField('user', { firstUserAdmin: true }) // samo pole roles — do własnej kolekcji +injectRoles(config, { authCollection: 'members' }) // dołóż pole do kolekcji w gotowym configu +applyGlobalOverrides(globals, { notifications: { … } }) // ta sama logika co opcja globalOverrides +``` + +Typy: `AccessOption`, `Role`, `GlobalOverride`, `GlobalOverrides`, `IpalGlobalSlug`. + +## Wyłączenie, nadpisanie, rozszerzenie + +- **Wyłączenie:** pomiń `access` — brak pola `roles`, kolekcja auth zostaje przy regułach Payloada + (albo Twoich). `access.firstUserAdmin: false` wyłącza nadawanie admina pierwszemu kontu. +- **Nadpisanie:** `access.authAccess` (kolekcja wstrzyknięta), własna kolekcja auth (wygrywa w całości), + `globalOverrides` (globale), `forms.formOverrides` / `formSubmissionOverrides` (formularze), + `defaultRole`. Hierarchia ról (`ROLE_HIERARCHY`) jest stała. +- **Rozszerzenie:** `requireRole` / `requireRoleField`, predykaty, `buildRolesField`, `injectRoles`, + `applyGlobalOverrides` we własnych kolekcjach i globalach. +- **Sprawdzenie:** zaloguj się kontem `user` → `PATCH /api/globals/site-settings` = 403, + `DELETE /api/users/` = 403; konto z „Create first user” ma rolę `admin`. diff --git a/docs/security.md b/docs/security.md index fc23772..2ae8e6b 100644 --- a/docs/security.md +++ b/docs/security.md @@ -274,7 +274,8 @@ ipalKit({ twoFactor: { issuer: 'Nazwa Firmy', // pokazywane w aplikacji authenticator plugin: payloadTotp, // ← WSTRZYKNIJ — patrz niżej dlaczego - // collectionSlug: 'users', // domyślnie kolekcja auth: access.authCollection → admin.user → 'users' + // collectionSlug: 'users', // domyślnie kolekcja logowania do panelu (admin.user, inaczej pierwsza kolekcja auth) + // allowCollectionMismatch: true, // tylko świadomie: 2FA na innej kolekcji niż admin.user }, }) ``` @@ -340,8 +341,11 @@ dostęp do danych, nie tylko UI. - Wstrzyknięta kolekcja auth z rolami: konto `user` czyta i edytuje tylko siebie, tworzy i usuwa tylko admin. Wcześniej każdy zalogowany mógł zmienić e-mail/hasło admina. -- 2FA bez `collectionSlug` wrapuje kolekcję, którą faktycznie się logujesz (`access.authCollection`, - potem `admin.user`), a nie literał `'users'` — inaczej TOTP po cichu nie działał. +- 2FA bez `collectionSlug` wrapuje kolekcję logowania do panelu (`admin.user`, inaczej pierwszą kolekcję + auth), a nie literał `'users'`. Start pluginu kończy się błędem `[ipal] twoFactor…`, gdy cel nie jest + kolekcją auth albo różni się od `admin.user` — świadomy wyjątek: `twoFactor.allowCollectionMismatch: true`. +- Kolekcja auth wstrzyknięta z rolami: także `unlock` tylko dla admina. Wszystko nadpiszesz: + `access.authAccess`, `access.firstUserAdmin: false`, `globalOverrides`, `forms.formOverrides`. - Site Settings, Cookie Settings, Notifications i kolekcja Forms: zapis tylko `editor+`; zakładka Emails formularza (odbiorcy, BCC) czytelna tylko dla `editor+`. - Pełna tabela: [access.md](./access.md#co-plugin-zamyka-sam). diff --git a/src/globals/overrides.ts b/src/globals/overrides.ts new file mode 100644 index 0000000..3e68d58 --- /dev/null +++ b/src/globals/overrides.ts @@ -0,0 +1,44 @@ +import type { GlobalConfig } from 'payload' + +/** Slugs of the globals the plugin adds. */ +export type IpalGlobalSlug = 'cookie-settings' | 'notifications' | 'site-integrations' | 'site-settings' + +/** + * A project's change to one plugin global: + * - an object is merged over the plugin's: `access`, `admin` and `hooks` key by + * key (your access rules win, your hooks run after the plugin's), anything + * else (label, fields, …) replaces the plugin's value; + * - a function gets the plugin's global and returns the one to use — full + * control, e.g. dropping a plugin hook or appending fields. + */ +export type GlobalOverride = ((global: GlobalConfig) => GlobalConfig) | Partial + +export type GlobalOverrides = Partial> + +type Hooks = NonNullable + +function mergeHooks(base: GlobalConfig['hooks'], extra: GlobalConfig['hooks']): GlobalConfig['hooks'] { + if (!extra) {return base} + const out: Record = { ...(base as Record) } + for (const [key, list] of Object.entries(extra)) { + out[key] = [...(out[key] ?? []), ...((list as unknown[]) ?? [])] + } + return out as Hooks +} + +/** Applies `globalOverrides` to the plugin's globals. */ +export function applyGlobalOverrides(globals: GlobalConfig[], overrides: GlobalOverrides | undefined): GlobalConfig[] { + if (!overrides) {return globals} + return globals.map((global) => { + const override = overrides[global.slug as IpalGlobalSlug] + if (!override) {return global} + if (typeof override === 'function') {return override(global)} + return { + ...global, + ...override, + access: { ...global.access, ...override.access }, + admin: { ...global.admin, ...override.admin }, + hooks: mergeHooks(global.hooks, override.hooks), + } + }) +} diff --git a/src/index.ts b/src/index.ts index 42b056c..0659f34 100644 --- a/src/index.ts +++ b/src/index.ts @@ -6,7 +6,9 @@ export { adminOrEditorField, adminOrSelf, authenticated, + buildRolesField, hasMinimumRole, + injectRoles, isAdmin, isEditor, requireRole, @@ -231,3 +233,5 @@ export { getTurnstileConfig } from './modules/turnstile/config.js' export type { TurnstileConfig } from './modules/turnstile/config.js' export { ipalKit } from './plugin.js' export type { IpalOptions } from './types.js' +export { applyGlobalOverrides } from './globals/overrides.js' +export type { GlobalOverride, GlobalOverrides, IpalGlobalSlug } from './globals/overrides.js' diff --git a/src/modules/access/injectRoles.ts b/src/modules/access/injectRoles.ts index 040588c..438564c 100644 --- a/src/modules/access/injectRoles.ts +++ b/src/modules/access/injectRoles.ts @@ -12,7 +12,7 @@ import { buildRolesField } from './rolesField.js' * stack, so no conflict handling is needed — the field is simply added. */ export function injectRoles(config: Config, access: AccessOption): Config { - const rolesField = buildRolesField(access.defaultRole) + const rolesField = buildRolesField(access.defaultRole, { firstUserAdmin: access.firstUserAdmin }) return { ...config, diff --git a/src/modules/access/rolesField.ts b/src/modules/access/rolesField.ts index d9621c1..fd58410 100644 --- a/src/modules/access/rolesField.ts +++ b/src/modules/access/rolesField.ts @@ -19,9 +19,10 @@ import { ROLE_HIERARCHY } from './types.js' * …/first-register on an empty collection) always becomes admin: that screen * may not show this field, and a site whose only account is a plain 'user' has * nobody who can manage users, integrations or roles. An open sign-up (plain - * create) on an empty collection still gets `defaultRole`. + * create) on an empty collection still gets `defaultRole`. `firstUserAdmin: + * false` turns this off. */ -export function buildRolesField(defaultRole: Role = 'user'): Field { +export function buildRolesField(defaultRole: Role = 'user', { firstUserAdmin = true }: { firstUserAdmin?: boolean } = {}): Field { return { name: 'roles', type: 'select', @@ -35,15 +36,19 @@ export function buildRolesField(defaultRole: Role = 'user'): Field { }, defaultValue: [defaultRole], hasMany: true, - hooks: { - beforeChange: [ - async ({ collection, operation, req, value }) => { - if (operation !== 'create' || !collection || !req.pathname?.endsWith('/first-register')) {return value} - const { totalDocs } = await req.payload.count({ collection: collection.slug, overrideAccess: true, req }) - return totalDocs === 0 ? ['admin'] : value - }, - ], - }, + ...(firstUserAdmin + ? { + hooks: { + beforeChange: [ + async ({ collection, operation, req, value }) => { + if (operation !== 'create' || !collection || !req.pathname?.endsWith('/first-register')) {return value} + const { totalDocs } = await req.payload.count({ collection: collection.slug, overrideAccess: true, req }) + return totalDocs === 0 ? ['admin'] : value + }, + ], + }, + } + : {}), options: ROLE_HIERARCHY.map((role) => ({ label: role.charAt(0).toUpperCase() + role.slice(1), value: role, diff --git a/src/modules/access/types.ts b/src/modules/access/types.ts index b78da05..ecba3b5 100644 --- a/src/modules/access/types.ts +++ b/src/modules/access/types.ts @@ -1,3 +1,5 @@ +import type { CollectionConfig } from 'payload' + /** * Role hierarchy, lowest to highest privilege. * A higher role satisfies any requirement met by a lower one. @@ -14,8 +16,22 @@ export type Role = (typeof ROLE_HIERARCHY)[number] * role definition belongs to the plugin. */ export type AccessOption = { + /** + * Access for the auth collection the plugin INJECTS when the project has none + * (a project's own collection keeps its own access untouched). Merged over the + * plugin's defaults — admin manages everyone, others only themselves: + * `{ create: adminOnly, delete: adminOnly, read: adminOrSelf, unlock: adminOnly, update: adminOrSelf }`. + * Your keys win, e.g. `{ read: authenticated }` to let editors list accounts. + */ + authAccess?: CollectionConfig['access'] /** Slug of the client's auth collection, e.g. 'users'. */ authCollection: string /** Role assigned to new users. Defaults to 'user'. */ defaultRole?: Role + /** + * The account made on Payload's "create first user" screen gets + * `roles: ['admin']`, whatever the form preselected. Default true; + * `false` = that account gets what was submitted (`defaultRole` by default). + */ + firstUserAdmin?: boolean } diff --git a/src/modules/forms/formsPluginConfig.ts b/src/modules/forms/formsPluginConfig.ts index eab94a4..7997c1a 100644 --- a/src/modules/forms/formsPluginConfig.ts +++ b/src/modules/forms/formsPluginConfig.ts @@ -35,7 +35,9 @@ const staffAccess = ({ req }: AccessArgs) => hasMinimumRole(req.user as never, ' /** * Forms stay publicly readable (their fields render the form), but the Emails * tab — recipient addresses, templates — is for editors and admins only, so - * GET /api/forms doesn't hand out the company's inboxes to spammers. + * GET /api/forms doesn't hand out the company's inboxes to spammers. Applied to + * the default fields BEFORE formOverrides.fields sees them, so a project can + * still change the rule there. */ function hideEmails(fields: Field[]): Field[] { return fields.map((field) => @@ -117,8 +119,10 @@ export function buildFormsPlugin(forms: FormsOption): Plugin { ...forms.formOverrides?.access, }, admin: { ...group, ...forms.formOverrides?.admin }, - fields: ({ defaultFields }) => - hideEmails(forms.formOverrides?.fields ? forms.formOverrides.fields({ defaultFields }) : defaultFields), + fields: ({ defaultFields }) => { + const protectedFields = hideEmails(defaultFields) + return forms.formOverrides?.fields ? forms.formOverrides.fields({ defaultFields: protectedFields }) : protectedFields + }, }, formSubmissionOverrides: { labels: { plural: 'Submissions', singular: 'Submission' }, diff --git a/src/plugin.ts b/src/plugin.ts index 3a10e71..036efce 100644 --- a/src/plugin.ts +++ b/src/plugin.ts @@ -8,6 +8,7 @@ import { buildNotifications } from './globals/Notifications/index.js' import { buildSiteIntegrations } from './globals/SiteIntegrations/index.js' import { buildSiteSettings } from './globals/SiteSettings/index.js' import { adminOnly, adminOrSelf, injectRoles } from './modules/access/index.js' +import { applyGlobalOverrides } from './globals/overrides.js' import { buildConsentLogCollection, buildConsentLogEndpoint } from './modules/consent/consentLog.js' import { buildConstructionFields } from './modules/construction/fields.js' import { buildArchiveFields } from './modules/content/index.js' @@ -68,8 +69,9 @@ export const ipalKit = (options: IpalOptions): Plugin => { 'users' // With roles on it (access.authCollection), the injected collection is // locked down: Payload's default lets ANY logged-in account read, edit - // (email, password) or delete every other account — a plain 'user' could - // take over an admin. Admins manage everyone; others only themselves. + // (email, password), unlock or delete every other account — a plain 'user' + // could take over an admin. Admins manage everyone; others only themselves. + // access.authAccess overrides any of it; a project's own collection wins whole. if (!(config.collections ?? []).some((c) => c.slug === authSlug)) { const hasRoles = options.access?.authCollection === authSlug config.collections = [ @@ -77,7 +79,16 @@ export const ipalKit = (options: IpalOptions): Plugin => { { slug: authSlug, ...(hasRoles - ? { access: { create: adminOnly, delete: adminOnly, read: adminOrSelf, update: adminOrSelf } } + ? { + access: { + create: adminOnly, + delete: adminOnly, + read: adminOrSelf, + unlock: adminOnly, + update: adminOrSelf, + ...options.access?.authAccess, + }, + } : {}), admin: { useAsTitle: 'email' }, auth: true, @@ -122,12 +133,30 @@ export const ipalKit = (options: IpalOptions): Plugin => { ) } - // Default to the resolved auth collection (access.authCollection / - // admin.user), not a literal 'users': wrapping a slug nobody logs in with - // leaves the real collection without TOTP fields, and the TOTP access - // wrapper lets users without those fields through — 2FA silently off. + // TOTP must wrap the collection people log in to the panel with + // (admin.user, else Payload's pick: the first auth collection). Wrapping + // another slug leaves the real one without TOTP fields, and the TOTP + // access wrapper lets users without those fields through — 2FA silently + // off. So: default to it, and refuse a target that isn't an auth + // collection, or differs from it unless allowCollectionMismatch says so. + const authSlugs = (config.collections ?? []).filter((c) => c.auth).map((c) => c.slug) + const adminSlug = config.admin?.user ?? authSlugs[0] ?? authSlug + const target = tf.collectionSlug ?? adminSlug + if (!authSlugs.includes(target)) { + throw new Error( + `[ipal] twoFactor: "${target}" is not an auth collection, so 2FA would protect nothing. ` + + `Auth collections: ${authSlugs.join(', ') || 'none'}. Fix twoFactor.collectionSlug.`, + ) + } + if (target !== adminSlug && !tf.allowCollectionMismatch) { + throw new Error( + `[ipal] twoFactor wraps "${target}" but the admin panel logs in with "${adminSlug}" ` + + '(admin.user) — those accounts would skip 2FA. Point twoFactor.collectionSlug at ' + + `"${adminSlug}", or pass twoFactor.allowCollectionMismatch: true if that is deliberate.`, + ) + } config = await totp({ - collection: tf.collectionSlug ?? authSlug, + collection: target, forceSetup: true, // ENFORCED — every user must set up TOTP; no opt-out totp: { issuer: tf.issuer }, })(config) @@ -243,12 +272,11 @@ export const ipalKit = (options: IpalOptions): Plugin => { ] // A global feeds every page's layout — revalidate the site on save. const revalidateGlobal = options.revalidatePath ? buildGlobalRevalidateHook({ revalidatePath: options.revalidatePath }) : null - config.globals = [ - ...(config.globals ?? []), - ...(revalidateGlobal - ? pluginGlobals.map((g) => ({ ...g, hooks: { ...g.hooks, afterChange: [...(g.hooks?.afterChange ?? []), revalidateGlobal] } })) - : pluginGlobals), - ] + const withRevalidate = revalidateGlobal + ? pluginGlobals.map((g) => ({ ...g, hooks: { ...g.hooks, afterChange: [...(g.hooks?.afterChange ?? []), revalidateGlobal] } })) + : pluginGlobals + // The project's globalOverrides win (access, admin, hooks merged; a function = full control). + config.globals = [...(config.globals ?? []), ...applyGlobalOverrides(withRevalidate, options.globalOverrides)] config.endpoints = [...(config.endpoints ?? []), testEmailEndpoint] diff --git a/src/types.ts b/src/types.ts index 5a48cae..4ec9941 100644 --- a/src/types.ts +++ b/src/types.ts @@ -12,6 +12,7 @@ export type TotpPluginFactory = (options: { forceSetup: boolean totp: { issuer: string } }) => Plugin +import type { GlobalOverrides } from './globals/overrides.js' import type { AccessOption } from './modules/access/types.js' import type { ContentOption } from './modules/content/types.js' import type { FormsOption } from './modules/forms/types.js' @@ -89,6 +90,15 @@ export type IpalOptions = { */ pages?: PagesOption + /** + * Change any of the plugin's globals (site-settings, site-integrations, + * cookie-settings, notifications): an object merges over the plugin's + * (`access` / `admin` / `hooks` key by key, your keys win), a function gets + * the global and returns the one to use. E.g. let any logged-in user edit + * Notifications: `{ notifications: { access: { update: authenticated } } }`. + */ + globalOverrides?: GlobalOverrides + /** * next/cache `revalidatePath`, INJECTED (the plugin never imports next/cache). * When given, saving any of the plugin's globals (Site Settings, Site @@ -129,7 +139,18 @@ export type IpalOptions = { */ twoFactor?: | { - /** Auth collection slug. Defaults to 'users'. */ + /** + * Let `collectionSlug` differ from the panel's login collection + * (admin.user). Off by default: a mismatch means panel users skip 2FA, + * so the plugin refuses to start. Set true only when you protect a + * second auth collection on purpose. + */ + allowCollectionMismatch?: boolean + /** + * Auth collection TOTP wraps. Default: the panel's login collection — + * admin.user, else the first auth collection (with the one the plugin + * injects). Must be an auth collection. + */ collectionSlug?: CollectionSlug /** Name shown in the authenticator app (e.g. company/site name). */ issuer: string diff --git a/test/accessControl.test.ts b/test/accessControl.test.ts index b348064..bf48848 100644 --- a/test/accessControl.test.ts +++ b/test/accessControl.test.ts @@ -70,14 +70,46 @@ describe('2FA wraps the auth collection people log in with', () => { expect(plugin).toHaveBeenCalledWith(expect.objectContaining({ collection: 'staff' })) }) - test('an explicit collectionSlug still wins', async () => { + const twoAuth = () => + empty({ + admin: { user: 'admins' }, + collections: [ + { slug: 'admins', auth: true, fields: [] }, + { slug: 'users', auth: true, fields: [] }, + { slug: 'pages', fields: [] }, + ], + } as Partial) + + test('admin.user wins over access.authCollection as the default target', async () => { + const plugin = totp() + await ipalKit({ access: { authCollection: 'users' }, i18n, twoFactor: { issuer: 'A', plugin: plugin as never } })(twoAuth()) + expect(plugin).toHaveBeenCalledWith(expect.objectContaining({ collection: 'admins' })) + }) + + test('a target other than the panel login collection fails at init…', async () => { + const plugin = totp() + await expect( + ipalKit({ i18n, twoFactor: { collectionSlug: 'users', issuer: 'A', plugin: plugin as never } })(twoAuth()), + ).rejects.toThrow(/admin panel logs in with "admins"/) + }) + + test('…unless allowCollectionMismatch says it is deliberate', async () => { const plugin = totp() await ipalKit({ - access: { authCollection: 'users' }, i18n, - twoFactor: { collectionSlug: 'admins', issuer: 'A', plugin: plugin as never }, - })(empty()) - expect(plugin).toHaveBeenCalledWith(expect.objectContaining({ collection: 'admins' })) + twoFactor: { allowCollectionMismatch: true, collectionSlug: 'users', issuer: 'A', plugin: plugin as never }, + })(twoAuth()) + expect(plugin).toHaveBeenCalledWith(expect.objectContaining({ collection: 'users' })) + }) + + test('a target that is not an auth collection always fails', async () => { + const plugin = totp() + await expect( + ipalKit({ + i18n, + twoFactor: { allowCollectionMismatch: true, collectionSlug: 'pages', issuer: 'A', plugin: plugin as never }, + })(twoAuth()), + ).rejects.toThrow(/"pages" is not an auth collection/) }) }) @@ -144,3 +176,66 @@ describe('roles field: the first-register account becomes admin', () => { expect(await hook(0, ['user'], '/api/users')).toEqual(['user']) }) }) + +describe('every access default can be overridden by the project', () => { + test('injected users: unlock is admin-only by default; access.authAccess keys win', async () => { + const base = await ipalKit({ access: { authCollection: 'users' }, i18n, twoFactor: false })(empty()) + const def = base.collections?.find((c) => c.slug === 'users')?.access ?? {} + expect(run(def.unlock, user)).toBe(false) + expect(run(def.unlock, admin)).toBe(true) + + const config = await ipalKit({ + access: { authAccess: { read: () => true }, authCollection: 'users' }, + i18n, + twoFactor: false, + })(empty()) + const access = config.collections?.find((c) => c.slug === 'users')?.access ?? {} + expect(run(access.read, user)).toBe(true) + expect(run(access.delete, user)).toBe(false) // the rest keeps the plugin default + }) + + test('access.firstUserAdmin: false keeps what the first-register form sent', async () => { + const config = await ipalKit({ access: { authCollection: 'users', firstUserAdmin: false }, i18n, twoFactor: false })(empty()) + const users = config.collections?.find((c) => c.slug === 'users') as CollectionConfig + const roles = users.fields.find((f) => 'name' in f && f.name === 'roles') as { hooks?: unknown } + expect(roles.hooks).toBeUndefined() + }) + + test('globalOverrides: an object merges access (project wins), a function takes over', async () => { + const config = await ipalKit({ + access: { authCollection: 'users' }, + globalOverrides: { + 'cookie-settings': (g) => ({ ...g, label: 'Cookies' }), + notifications: { access: { update: ({ req }) => Boolean(req.user) } }, + }, + i18n, + twoFactor: false, + })(empty()) + const notifications = config.globals?.find((g) => g.slug === 'notifications') as GlobalConfig + expect(run(notifications.access?.update, user)).toBe(true) + expect(run(notifications.access?.read, null)).toBe(true) + expect(config.globals?.find((g) => g.slug === 'cookie-settings')?.label).toBe('Cookies') + // untouched globals keep the secure default + expect(run((config.globals?.find((g) => g.slug === 'site-settings') as GlobalConfig).access?.update, user)).toBe(false) + }) + + test('forms: formOverrides.access wins; a read rule on the Emails field wins', async () => { + const config = await ipalKit({ + access: { authCollection: 'users' }, + forms: { + formOverrides: { + access: { update: () => true }, + fields: ({ defaultFields }) => + defaultFields.map((f) => ('name' in f && f.name === 'emails' ? ({ ...f, access: { read: () => true } } as Field) : f)), + }, + }, + i18n, + twoFactor: false, + })(empty()) + const forms = config.collections?.find((c) => c.slug === 'forms') as CollectionConfig + expect(run(forms.access?.update, user)).toBe(true) + expect(run(forms.access?.delete, user)).toBe(false) + const emails = forms.fields.find((f: Field) => 'name' in f && f.name === 'emails') as { access?: { read?: (a: unknown) => boolean } } + expect(emails.access?.read?.({ req: { user } })).toBe(true) + }) +})