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 <[email protected]>
This commit is contained in:
co-authored by
Claude Opus 5.5
parent
14fd2c497f
commit
a87742621a
@@ -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<GlobalConfig>
|
||||
|
||||
export type GlobalOverrides = Partial<Record<IpalGlobalSlug, GlobalOverride>>
|
||||
|
||||
type Hooks = NonNullable<GlobalConfig['hooks']>
|
||||
|
||||
function mergeHooks(base: GlobalConfig['hooks'], extra: GlobalConfig['hooks']): GlobalConfig['hooks'] {
|
||||
if (!extra) {return base}
|
||||
const out: Record<string, unknown[]> = { ...(base as Record<string, unknown[]>) }
|
||||
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),
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -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'
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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
|
||||
}
|
||||
|
||||
@@ -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' },
|
||||
|
||||
+42
-14
@@ -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]
|
||||
|
||||
|
||||
+22
-1
@@ -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
|
||||
|
||||
Reference in New Issue
Block a user