M1 (7): a password rule for staff accounts (accounts.password)

When a password is set on a staff collection — a new account, the first-user
screen, a change, a reset by e-mail; panel, API and Local API alike — it must
have at least 12 characters and not be the account's own e-mail address.
Existing passwords are never checked: a shorter one keeps logging in and meets
the rule when it is next changed. accounts.password: { minLength } | false.
No breached-password lookup; checkPassword and the hook are exported.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
This commit is contained in:
Radosław Smoliński
2026-11-25 00:39:12 +01:00
co-authored by Claude Fable 5.2
parent c6fc0d21fe
commit 5d35b2c3f4
8 changed files with 204 additions and 15 deletions
+6 -4
View File
@@ -1,10 +1,6 @@
export { lightboxNotificationFields } from './globals/Notifications/fields.js'
export { applyGlobalOverrides } from './globals/overrides.js'
export type { GlobalOverride, GlobalOverrides, IpalGlobalSlug } from './globals/overrides.js'
export { applyPanelRole, countBelowPanelRole, DEFAULT_PANEL_ROLE, panelAccess, resolvePanelRole } from './modules/access/panelRole.js'
export { applyAdminOnlyCreate, applyFirstUserRoute, buildFirstUserGuard, openSignUpCollections, staffCreateAccess } from './modules/access/selfRegistration.js'
export type { FirstUserRouteOption } from './modules/access/selfRegistration.js'
export type { AccountsOptions } from './modules/access/types.js'
export type { AccessOption, Role } from './modules/access/index.js'
export {
adminOnly,
@@ -25,6 +21,12 @@ export {
staffCollectionSlugs,
userMeetsRole,
} from './modules/access/index.js'
export { applyPanelRole, countBelowPanelRole, DEFAULT_PANEL_ROLE, panelAccess, resolvePanelRole } from './modules/access/panelRole.js'
export { applyPasswordRule, buildPasswordRuleHook, checkPassword, DEFAULT_PASSWORD_MIN_LENGTH, resolvePasswordRule } from './modules/access/passwordRule.js'
export type { PasswordRuleOptions } from './modules/access/passwordRule.js'
export { applyAdminOnlyCreate, applyFirstUserRoute, buildFirstUserGuard, openSignUpCollections, staffCreateAccess } from './modules/access/selfRegistration.js'
export type { FirstUserRouteOption } from './modules/access/selfRegistration.js'
export type { AccountsOptions } from './modules/access/types.js'
// Concrete files, not module barrels: a barrel that also re-exports 'use client'
// components would load React UI into payload.config / the CLI (test/entryGraph).
export { A11Y_COOKIE, A11Y_DEFAULT, a11yAttributes, parseA11y, serializeA11y } from './modules/accessibility/state.js'
+86
View File
@@ -0,0 +1,86 @@
import type { CollectionBeforeOperationHook, Config } from 'payload'
import { ValidationError } from 'payload'
import { serverText } from '../integrations/texts.js'
/**
* A password rule for staff accounts.
*
* Payload's own rule is a minimum of three characters. Default here: twelve, and not the
* account's own e-mail address (`accounts.password`). It is checked when a password is SET —
* creating an account, the first-user screen, changing a password, a reset by e-mail — in the
* panel, over the API and through the Local API alike. **A password that already exists is
* never checked:** an account with a shorter one keeps logging in, and is held to the rule the
* next time its password is changed.
*
* No breached-password lookup: that would send (part of a hash of) every new password to an
* outside service, and is left to a project that wants it — `checkPassword` and the hook are
* exported to build on.
*/
export const DEFAULT_PASSWORD_MIN_LENGTH = 12
export type PasswordRuleOptions = {
/** Shortest password accepted when one is set. Default 12. */
minLength?: number
}
/** `accounts.password` → the rule, or null when it is off (`false`). Throws on a value that is not a whole number ≥ 1. */
export function resolvePasswordRule(option: false | PasswordRuleOptions | undefined): null | Required<PasswordRuleOptions> {
if (option === false) {return null}
const minLength = option?.minLength ?? DEFAULT_PASSWORD_MIN_LENGTH
if (typeof minLength !== 'number' || !Number.isInteger(minLength) || minLength < 1) {
throw new Error(`[ipal] accounts.password.minLength must be a whole number of 1 or more, got ${JSON.stringify(option?.minLength) ?? String(option?.minLength)}. Use accounts: { password: false } to turn the rule off.`)
}
return { minLength }
}
/** What is wrong with a new password, or null. Length is counted in characters, not bytes. */
export function checkPassword(password: string, { email, minLength = DEFAULT_PASSWORD_MIN_LENGTH }: { email?: null | string; minLength?: number } = {}): 'email' | 'short' | null {
if ([...password].length < minLength) {return 'short'}
if (email && password.trim().toLowerCase() === email.trim().toLowerCase()) {return 'email'}
return null
}
/**
* `beforeOperation` hook for an auth collection: validates a password that is being set
* (`create`, `update`, `resetPassword`). Login, refresh and every other operation pass untouched.
*/
export function buildPasswordRuleHook({ minLength = DEFAULT_PASSWORD_MIN_LENGTH }: PasswordRuleOptions = {}): CollectionBeforeOperationHook {
return async ({ args, collection, operation, req }) => {
if (operation !== 'create' && operation !== 'update' && operation !== 'resetPassword') {return args}
const data = (args as { data?: { email?: unknown; password?: unknown } }).data
const password = data?.password
if (typeof password !== 'string' || password === '') {return args} // no password in this request: nothing is being set
let email = typeof data?.email === 'string' ? data.email : null
const id = (args as { id?: number | string }).id
if (!email && operation === 'update' && id !== undefined && req?.payload) {
try {
const doc = (await req.payload.findByID({ id, collection: collection.slug as never, depth: 0, overrideAccess: true, req })) as { email?: unknown }
email = typeof doc?.email === 'string' ? doc.email : null
} catch {
email = null
}
}
const problem = checkPassword(password, { email, minLength })
if (problem) {
const i18n = req?.i18n as Parameters<typeof serverText>[0]
const message = problem === 'short' ? serverText(i18n, 'passwordTooShort', { min: minLength }) : serverText(i18n, 'passwordIsEmail')
throw new ValidationError({ collection: collection.slug, errors: [{ message, path: 'password' }] }, req?.t)
}
return args
}
}
/** Adds the rule to the named auth collections that log in with a password. */
export function applyPasswordRule(config: Config, slugs: string[], rule: Required<PasswordRuleOptions>): Config {
const hook = buildPasswordRuleHook(rule)
return {
...config,
collections: (config.collections ?? []).map((collection) => {
const auth = collection.auth
const local = Boolean(auth) && !(typeof auth === 'object' && auth.disableLocalStrategy === true)
return local && slugs.includes(collection.slug) ? { ...collection, hooks: { ...collection.hooks, beforeOperation: [...(collection.hooks?.beforeOperation ?? []), hook] } } : collection
}),
}
}
+10
View File
@@ -1,5 +1,7 @@
import type { CollectionConfig } from 'payload'
import type { PasswordRuleOptions } from './passwordRule.js'
/**
* Role hierarchy, lowest to highest privilege.
* A higher role satisfies any requirement met by a lower one.
@@ -40,6 +42,14 @@ export type AccountsOptions = {
* collection (or `access.authAccess.admin`) wins. docs/access.md.
*/
panelRole?: false | Role
/**
* Rule for a password of a staff account when one is SET (a new account,
* the first-user screen, a change, a reset by e-mail): at least
* `minLength` characters (default 12) and not the account's own e-mail
* address. Existing passwords are never checked — a shorter one keeps
* logging in. `false` = Payload's own rule (3 characters).
*/
password?: false | PasswordRuleOptions
}
/**
+4
View File
@@ -3,6 +3,8 @@ import { defineTexts } from '../define.js'
/** Admin component texts — two-step verification (2FA). Placeholders use Payload's {{name}} syntax. */
export const securityTexts = defineTexts({
en: {
passwordIsEmail: 'The password cannot be the same as the e-mail address.',
passwordTooShort: 'The password must have at least {{min}} characters.',
twoFactorAlertBlocked: 'Blocked because the time for setup has passed: {{count}}. Open the account in the user list and choose "Reopen setup".',
twoFactorAlertLink: 'Open the user list',
twoFactorAlertPending: 'Accounts without two-step verification: {{count}}. Until it is set up, such an account cannot use the panel.',
@@ -25,6 +27,8 @@ export const securityTexts = defineTexts({
twoFactorTooManyAttempts: 'Too many codes were tried for this account. Wait {{minutes}} min, then enter the current code from your app.',
},
pl: {
passwordIsEmail: 'Hasło nie może być takie samo jak adres e-mail.',
passwordTooShort: 'Hasło musi mieć co najmniej {{min}} znaków.',
twoFactorAlertBlocked: 'Zablokowane, bo minął czas na konfigurację: {{count}}. Otwórz konto na liście użytkowników i wybierz „Otwórz konfigurację ponownie”.',
twoFactorAlertLink: 'Otwórz listę użytkowników',
twoFactorAlertPending: 'Konta bez weryfikacji dwuetapowej: {{count}}. Dopóki nie zostanie ustawiona, takie konto nie może korzystać z panelu.',
+3
View File
@@ -14,6 +14,7 @@ import { buildSiteIntegrations } from './globals/SiteIntegrations/index.js'
import { buildSiteSettings } from './globals/SiteSettings/index.js'
import { adminOnly, adminOrSelfIn, injectRoles, registerStaffCollections, staffCollectionSlugs } from './modules/access/index.js'
import { applyPanelRole, countBelowPanelRole, resolvePanelRole } from './modules/access/panelRole.js'
import { applyPasswordRule, resolvePasswordRule } from './modules/access/passwordRule.js'
import { applyAdminOnlyCreate, applyFirstUserRoute } from './modules/access/selfRegistration.js'
import { applyAdminI18n } from './modules/admin-i18n/apply.js'
import { buildAdminImageEndpoints } from './modules/branding/adminImages.js'
@@ -572,6 +573,8 @@ export const ipalKit = (options: IpalOptions): Plugin => {
const staffSlugs = [...new Set([panelSlug, options.access?.authCollection, ...(options.access?.staffCollections ?? [])].filter((s): s is string => Boolean(s)))]
if (accounts.adminOnlyCreate !== false) {config = applyAdminOnlyCreate(config, staffSlugs)}
config = applyFirstUserRoute(config, accounts.firstUserRoute)
const passwordRule = resolvePasswordRule(accounts.password)
if (passwordRule) {config = applyPasswordRule(config, staffSlugs, passwordRule)}
}
// For predicates called without `req.payload` (isAdmin(req.user) in a hook): what this config
// says now, under a token; the Payload instance takes the entry over when the config goes live
+5 -5
View File
@@ -34,16 +34,16 @@ import type { StatsOptions } from './modules/stats/collection.js'
* Passed by the client project in payload.config.ts.
*/
export type IpalOptions = {
/**
* Rules for the accounts of the staff collection: who may open the panel
* (`panelRole`). `false` = none of them. docs/access.md "Account rules".
*/
accounts?: AccountsOptions | false
/**
* Role-based access control. Injects a fixed `roles` field
* (admin > editor > user) into the client's auth collection.
*/
access?: AccessOption
/**
* Rules for the accounts of the staff collection: who may open the panel
* (`panelRole`). `false` = none of them. docs/access.md "Account rules".
*/
accounts?: AccountsOptions | false
/**
* Admin panel <head> for link previews and search engines (default on):