diff --git a/src/index.ts b/src/index.ts index 85dfd06..4114530 100644 --- a/src/index.ts +++ b/src/index.ts @@ -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' diff --git a/src/modules/access/passwordRule.ts b/src/modules/access/passwordRule.ts new file mode 100644 index 0000000..ae25e87 --- /dev/null +++ b/src/modules/access/passwordRule.ts @@ -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 { + 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[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): 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 + }), + } +} diff --git a/src/modules/access/types.ts b/src/modules/access/types.ts index 4545fe0..c0e7ad0 100644 --- a/src/modules/access/types.ts +++ b/src/modules/access/types.ts @@ -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 } /** diff --git a/src/modules/admin-i18n/texts/security.ts b/src/modules/admin-i18n/texts/security.ts index 6f5cc5e..a7411fd 100644 --- a/src/modules/admin-i18n/texts/security.ts +++ b/src/modules/admin-i18n/texts/security.ts @@ -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.', diff --git a/src/plugin.ts b/src/plugin.ts index 2f74228..445a7ac 100644 --- a/src/plugin.ts +++ b/src/plugin.ts @@ -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 diff --git a/src/types.ts b/src/types.ts index e8d3754..baf97fc 100644 --- a/src/types.ts +++ b/src/types.ts @@ -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 for link previews and search engines (default on): diff --git a/test/accountRules.test.ts b/test/accountRules.test.ts index b87b9a2..72058e8 100644 --- a/test/accountRules.test.ts +++ b/test/accountRules.test.ts @@ -5,12 +5,16 @@ import type { Config, Payload } from 'payload' import { lexicalEditor } from '@payloadcms/richtext-lexical' +import { pbkdf2Sync, randomBytes } from 'node:crypto' import os from 'os' import path from 'path' import { getPayload } from 'payload' import { afterAll, beforeAll, describe, expect, test, vi } from 'vitest' +import type { I18nConfig } from '../src/modules/i18n/types.js' + import { countBelowPanelRole, panelAccess, resolvePanelRole } from '../src/modules/access/panelRole.js' +import { checkPassword, resolvePasswordRule } from '../src/modules/access/passwordRule.js' import { buildFirstUserGuard, openSignUpCollections, staffCreateAccess } from '../src/modules/access/selfRegistration.js' import { ipalKit } from '../src/plugin.js' import { buildTestConfig } from './helpers.js' @@ -19,7 +23,7 @@ import { startPayloadServer, type TestServer } from './http/server.js' vi.mock('server-only', () => ({})) -const i18n = { defaultLocale: 'en', locales: [{ code: 'en', label: 'English' }] } +const i18n: I18nConfig = { defaultLocale: 'en', locales: [{ code: 'en', label: 'English' }] } const PASSWORD = 'a-long-test-password-1' let server: TestServer let payload: Payload @@ -150,6 +154,85 @@ describe('the lowest role stays out of the admin panel (accounts.panelRole)', () }) }) +describe('the password rule (accounts.password): twelve characters when a password is set', () => { + let admin: Session + const messageOf = async (res: Response) => JSON.stringify(await res.json()) + + beforeAll(async () => { + admin = await login('users', 'first@example.com') + }) + + test('a new account: 11 characters refused with a clear message, 12 accepted', async () => { + const short = await post('/users', { email: 'short@example.com', password: 'abcdefghijk', roles: ['editor'] }, admin) + expect(short.status).toBe(400) + expect(await messageOf(short)).toMatch(/at least 12 characters/) + expect((await post('/users', { email: 'twelve@example.com', password: 'abcdefghijkl', roles: ['editor'] }, admin)).status).toBe(201) + // counted in characters, not bytes + expect((await post('/users', { email: 'unicode@example.com', password: 'zażółć gęślą', roles: ['editor'] }, admin)).status).toBe(201) + }) + + test('in Polish for a Polish panel', async () => { + const res = await post('/users', { email: 'pl@example.com', password: 'krotkie', roles: ['editor'] }, { ...admin, 'accept-language': 'pl' }) + expect(res.status).toBe(400) + expect(await messageOf(res)).toMatch(/co najmniej 12 znaków/) + }) + + test('not the account\'s own e-mail address', async () => { + const same = await post('/users', { email: 'same-as-password@example.com', password: 'Same-As-Password@example.com', roles: ['editor'] }, admin) + expect(same.status).toBe(400) + expect(await messageOf(same)).toMatch(/same as the e-mail/) + }) + + test('changing a password: checked; changing anything else: not', async () => { + const doc = (await payload.find({ collection: 'users' as never, where: { email: { equals: 'twelve@example.com' } } })).docs[0] + expect((await call(`/users/${doc.id}`, admin, { body: JSON.stringify({ password: 'tooshort' }), method: 'PATCH' })).status).toBe(400) + expect((await call(`/users/${doc.id}`, admin, { body: JSON.stringify({ password: 'twelve@example.com' }), method: 'PATCH' })).status).toBe(400) // its own address, looked up + expect((await call(`/users/${doc.id}`, admin, { body: JSON.stringify({ roles: ['user'] }), method: 'PATCH' })).status).toBe(200) + expect((await call(`/users/${doc.id}`, admin, { body: JSON.stringify({ password: 'a-new-long-password' }), method: 'PATCH' })).status).toBe(200) + await login('users', 'twelve@example.com', 'a-new-long-password') + }) + + test('an EXISTING shorter password keeps logging in — nothing is checked at login', async () => { + // an account as an earlier version left it: a 6-character password, stored the way Payload stored it then + const old = await make('users', { email: 'old-short@example.com', roles: ['editor'] }) + const salt = randomBytes(32).toString('hex') + const hash = pbkdf2Sync('short1', salt, 25000, 512, 'sha256').toString('hex') + await payload.db.updateOne({ id: old.id, collection: 'users' as never, data: { hash, salt } as never }) + const session = await login('users', 'old-short@example.com', 'short1') + expect(((await (await call('/users/me', session)).json()) as { user?: { email?: string } }).user?.email).toBe('old-short@example.com') + // the rule meets it the next time the password is changed + expect((await call(`/users/${old.id}`, session, { body: JSON.stringify({ password: 'short2' }), method: 'PATCH' })).status).toBe(400) + }) + + test('a reset by e-mail is held to the rule too', async () => { + const token = await payload.forgotPassword({ collection: 'users' as never, data: { email: 'twelve@example.com' }, disableEmail: true }) + const short = await post('/users/reset-password', { password: 'tooshort', token }) + expect(short.status).toBe(400) + expect(await messageOf(short)).toMatch(/at least 12 characters/) + expect((await post('/users/reset-password', { password: 'reset-to-a-long-one', token })).status).toBe(200) + }) + + test('visitor collections are not touched', async () => { + expect((await post('/customers', { email: 'short-pass@customers.example.com', password: 'abc123' })).status).toBe(201) + }) + + test('the option, the checker and the switch', async () => { + expect(resolvePasswordRule(undefined)).toEqual({ minLength: 12 }) + expect(resolvePasswordRule({ minLength: 16 })).toEqual({ minLength: 16 }) + expect(resolvePasswordRule(false)).toBeNull() + for (const bad of ['12', 0, -1, 1.5, Number.NaN]) {expect(() => resolvePasswordRule({ minLength: bad as never })).toThrow(/minLength must be/)} + expect(checkPassword('abcdefghijk')).toBe('short') + expect(checkPassword('abcdefghijkl')).toBeNull() + expect(checkPassword('abcd', { minLength: 4 })).toBeNull() + expect(checkPassword('Someone@Example.com ', { email: 'someone@example.com', minLength: 4 })).toBe('email') + const hooks = async (options: Record) => + (await ipalKit({ access: { authCollection: 'users' }, i18n, twoFactor: false, ...options } as never)({ admin: { user: 'users' }, collections: [{ slug: 'customers', auth: true, fields: [] }], secret: 'x' } as unknown as Config)).collections!.map((c) => [c.slug, c.hooks?.beforeOperation?.length ?? 0]) + expect(await hooks({})).toEqual([['customers', 1], ['users', 2]]) // customers: the first-user guard only + expect(await hooks({ accounts: { password: false } })).toEqual([['customers', 1], ['users', 1]]) + expect(await hooks({ accounts: false })).toEqual([['customers', 0], ['users', 0]]) + }) +}) + describe('accounts.panelRole: the config', () => { const build = (options: Record, incoming: Partial = {}) => ipalKit({ access: { authCollection: 'users' }, i18n, twoFactor: false, ...options } as never)({ collections: [], secret: 'x', ...incoming } as unknown as Config) @@ -219,8 +302,9 @@ describe('accounts.adminOnlyCreate / firstUserRoute: the config', () => { test('the switches', async () => { const guards = (config: Config, slug: string) => of(config, slug).hooks?.beforeOperation?.length ?? 0 const on = await build({}) - expect([guards(on, 'users'), guards(on, 'staff2'), guards(on, 'customers'), guards(on, 'pages')]).toEqual([1, 1, 1, 0]) - const payloadWay = await build({ accounts: { adminOnlyCreate: false, firstUserRoute: 'all' } }) + // staff collections: the first-user guard and the password rule; a visitor collection: the guard only + expect([guards(on, 'users'), guards(on, 'staff2'), guards(on, 'customers'), guards(on, 'pages')]).toEqual([2, 2, 1, 0]) + const payloadWay = await build({ accounts: { adminOnlyCreate: false, firstUserRoute: 'all', password: false } }) expect(of(payloadWay, 'staff2').access?.create).toBeUndefined() expect(guards(payloadWay, 'staff2')).toBe(0) const off = await build({ accounts: false }) diff --git a/test/integration.test.ts b/test/integration.test.ts index 82c6c97..a006e8d 100644 --- a/test/integration.test.ts +++ b/test/integration.test.ts @@ -167,7 +167,7 @@ describe('forms against a real Payload', () => { test('open sign-up cannot self-assign admin — roles fall back to the default', async () => { const user = (await payload.create({ collection: 'users', - data: { email: 'a@acme.pl', password: 'Passw0rd!x', roles: ['admin'] } as never, + data: { email: 'a@acme.pl', password: 'Passw0rd!x-long', roles: ['admin'] } as never, overrideAccess: false, })) as unknown as { roles: string[] } expect(user.roles).toEqual(['user']) @@ -176,7 +176,7 @@ describe('forms against a real Payload', () => { test('seed / Local API with overrideAccess can still create an admin', async () => { const admin = (await payload.create({ collection: 'users', - data: { email: 'root@acme.pl', password: 'Passw0rd!x', roles: ['admin'] } as never, + data: { email: 'root@acme.pl', password: 'Passw0rd!x-long', roles: ['admin'] } as never, })) as unknown as { roles: string[] } expect(admin.roles).toEqual(['admin']) }) @@ -401,7 +401,7 @@ describe('forms access', () => { const user = (await payload.create({ collection: 'users', - data: { email: 'plain@acme.pl', password: 'Passw0rd!x' } as never, + data: { email: 'plain@acme.pl', password: 'Passw0rd!x-long' } as never, })) as unknown as Record await expect( payload.find({ collection: 'form-submissions' as never, overrideAccess: false, user: { ...user, collection: 'users' } as never }),