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:
co-authored by
Claude Fable 5.2
parent
c6fc0d21fe
commit
5d35b2c3f4
+6
-4
@@ -1,10 +1,6 @@
|
|||||||
export { lightboxNotificationFields } from './globals/Notifications/fields.js'
|
export { lightboxNotificationFields } from './globals/Notifications/fields.js'
|
||||||
export { applyGlobalOverrides } from './globals/overrides.js'
|
export { applyGlobalOverrides } from './globals/overrides.js'
|
||||||
export type { GlobalOverride, GlobalOverrides, IpalGlobalSlug } 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 type { AccessOption, Role } from './modules/access/index.js'
|
||||||
export {
|
export {
|
||||||
adminOnly,
|
adminOnly,
|
||||||
@@ -25,6 +21,12 @@ export {
|
|||||||
staffCollectionSlugs,
|
staffCollectionSlugs,
|
||||||
userMeetsRole,
|
userMeetsRole,
|
||||||
} from './modules/access/index.js'
|
} 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'
|
// 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).
|
// 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'
|
export { A11Y_COOKIE, A11Y_DEFAULT, a11yAttributes, parseA11y, serializeA11y } from './modules/accessibility/state.js'
|
||||||
|
|||||||
@@ -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
|
||||||
|
}),
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,5 +1,7 @@
|
|||||||
import type { CollectionConfig } from 'payload'
|
import type { CollectionConfig } from 'payload'
|
||||||
|
|
||||||
|
import type { PasswordRuleOptions } from './passwordRule.js'
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Role hierarchy, lowest to highest privilege.
|
* Role hierarchy, lowest to highest privilege.
|
||||||
* A higher role satisfies any requirement met by a lower one.
|
* 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.
|
* collection (or `access.authAccess.admin`) wins. docs/access.md.
|
||||||
*/
|
*/
|
||||||
panelRole?: false | Role
|
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
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|||||||
@@ -3,6 +3,8 @@ import { defineTexts } from '../define.js'
|
|||||||
/** Admin component texts — two-step verification (2FA). Placeholders use Payload's {{name}} syntax. */
|
/** Admin component texts — two-step verification (2FA). Placeholders use Payload's {{name}} syntax. */
|
||||||
export const securityTexts = defineTexts({
|
export const securityTexts = defineTexts({
|
||||||
en: {
|
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".',
|
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',
|
twoFactorAlertLink: 'Open the user list',
|
||||||
twoFactorAlertPending: 'Accounts without two-step verification: {{count}}. Until it is set up, such an account cannot use the panel.',
|
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.',
|
twoFactorTooManyAttempts: 'Too many codes were tried for this account. Wait {{minutes}} min, then enter the current code from your app.',
|
||||||
},
|
},
|
||||||
pl: {
|
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”.',
|
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',
|
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.',
|
twoFactorAlertPending: 'Konta bez weryfikacji dwuetapowej: {{count}}. Dopóki nie zostanie ustawiona, takie konto nie może korzystać z panelu.',
|
||||||
|
|||||||
@@ -14,6 +14,7 @@ import { buildSiteIntegrations } from './globals/SiteIntegrations/index.js'
|
|||||||
import { buildSiteSettings } from './globals/SiteSettings/index.js'
|
import { buildSiteSettings } from './globals/SiteSettings/index.js'
|
||||||
import { adminOnly, adminOrSelfIn, injectRoles, registerStaffCollections, staffCollectionSlugs } from './modules/access/index.js'
|
import { adminOnly, adminOrSelfIn, injectRoles, registerStaffCollections, staffCollectionSlugs } from './modules/access/index.js'
|
||||||
import { applyPanelRole, countBelowPanelRole, resolvePanelRole } from './modules/access/panelRole.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 { applyAdminOnlyCreate, applyFirstUserRoute } from './modules/access/selfRegistration.js'
|
||||||
import { applyAdminI18n } from './modules/admin-i18n/apply.js'
|
import { applyAdminI18n } from './modules/admin-i18n/apply.js'
|
||||||
import { buildAdminImageEndpoints } from './modules/branding/adminImages.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)))]
|
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)}
|
if (accounts.adminOnlyCreate !== false) {config = applyAdminOnlyCreate(config, staffSlugs)}
|
||||||
config = applyFirstUserRoute(config, accounts.firstUserRoute)
|
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
|
// 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
|
// says now, under a token; the Payload instance takes the entry over when the config goes live
|
||||||
|
|||||||
+5
-5
@@ -34,16 +34,16 @@ import type { StatsOptions } from './modules/stats/collection.js'
|
|||||||
* Passed by the client project in payload.config.ts.
|
* Passed by the client project in payload.config.ts.
|
||||||
*/
|
*/
|
||||||
export type IpalOptions = {
|
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
|
* Role-based access control. Injects a fixed `roles` field
|
||||||
* (admin > editor > user) into the client's auth collection.
|
* (admin > editor > user) into the client's auth collection.
|
||||||
*/
|
*/
|
||||||
access?: AccessOption
|
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):
|
* Admin panel <head> for link previews and search engines (default on):
|
||||||
|
|||||||
@@ -5,12 +5,16 @@
|
|||||||
import type { Config, Payload } from 'payload'
|
import type { Config, Payload } from 'payload'
|
||||||
|
|
||||||
import { lexicalEditor } from '@payloadcms/richtext-lexical'
|
import { lexicalEditor } from '@payloadcms/richtext-lexical'
|
||||||
|
import { pbkdf2Sync, randomBytes } from 'node:crypto'
|
||||||
import os from 'os'
|
import os from 'os'
|
||||||
import path from 'path'
|
import path from 'path'
|
||||||
import { getPayload } from 'payload'
|
import { getPayload } from 'payload'
|
||||||
import { afterAll, beforeAll, describe, expect, test, vi } from 'vitest'
|
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 { 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 { buildFirstUserGuard, openSignUpCollections, staffCreateAccess } from '../src/modules/access/selfRegistration.js'
|
||||||
import { ipalKit } from '../src/plugin.js'
|
import { ipalKit } from '../src/plugin.js'
|
||||||
import { buildTestConfig } from './helpers.js'
|
import { buildTestConfig } from './helpers.js'
|
||||||
@@ -19,7 +23,7 @@ import { startPayloadServer, type TestServer } from './http/server.js'
|
|||||||
|
|
||||||
vi.mock('server-only', () => ({}))
|
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'
|
const PASSWORD = 'a-long-test-password-1'
|
||||||
let server: TestServer
|
let server: TestServer
|
||||||
let payload: Payload
|
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', '[email protected]')
|
||||||
|
})
|
||||||
|
|
||||||
|
test('a new account: 11 characters refused with a clear message, 12 accepted', async () => {
|
||||||
|
const short = await post('/users', { email: '[email protected]', password: 'abcdefghijk', roles: ['editor'] }, admin)
|
||||||
|
expect(short.status).toBe(400)
|
||||||
|
expect(await messageOf(short)).toMatch(/at least 12 characters/)
|
||||||
|
expect((await post('/users', { email: '[email protected]', password: 'abcdefghijkl', roles: ['editor'] }, admin)).status).toBe(201)
|
||||||
|
// counted in characters, not bytes
|
||||||
|
expect((await post('/users', { email: '[email protected]', password: 'zażółć gęślą', roles: ['editor'] }, admin)).status).toBe(201)
|
||||||
|
})
|
||||||
|
|
||||||
|
test('in Polish for a Polish panel', async () => {
|
||||||
|
const res = await post('/users', { email: '[email protected]', 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: '[email protected]', password: '[email protected]', 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: '[email protected]' } } })).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: '[email protected]' }), 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', '[email protected]', '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: '[email protected]', 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', '[email protected]', 'short1')
|
||||||
|
expect(((await (await call('/users/me', session)).json()) as { user?: { email?: string } }).user?.email).toBe('[email protected]')
|
||||||
|
// 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: '[email protected]' }, 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: '[email protected]', 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('[email protected] ', { email: '[email protected]', minLength: 4 })).toBe('email')
|
||||||
|
const hooks = async (options: Record<string, unknown>) =>
|
||||||
|
(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', () => {
|
describe('accounts.panelRole: the config', () => {
|
||||||
const build = (options: Record<string, unknown>, incoming: Partial<Config> = {}) =>
|
const build = (options: Record<string, unknown>, incoming: Partial<Config> = {}) =>
|
||||||
ipalKit({ access: { authCollection: 'users' }, i18n, twoFactor: false, ...options } as never)({ collections: [], secret: 'x', ...incoming } as unknown as Config)
|
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 () => {
|
test('the switches', async () => {
|
||||||
const guards = (config: Config, slug: string) => of(config, slug).hooks?.beforeOperation?.length ?? 0
|
const guards = (config: Config, slug: string) => of(config, slug).hooks?.beforeOperation?.length ?? 0
|
||||||
const on = await build({})
|
const on = await build({})
|
||||||
expect([guards(on, 'users'), guards(on, 'staff2'), guards(on, 'customers'), guards(on, 'pages')]).toEqual([1, 1, 1, 0])
|
// staff collections: the first-user guard and the password rule; a visitor collection: the guard only
|
||||||
const payloadWay = await build({ accounts: { adminOnlyCreate: false, firstUserRoute: 'all' } })
|
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(of(payloadWay, 'staff2').access?.create).toBeUndefined()
|
||||||
expect(guards(payloadWay, 'staff2')).toBe(0)
|
expect(guards(payloadWay, 'staff2')).toBe(0)
|
||||||
const off = await build({ accounts: false })
|
const off = await build({ accounts: false })
|
||||||
|
|||||||
@@ -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 () => {
|
test('open sign-up cannot self-assign admin — roles fall back to the default', async () => {
|
||||||
const user = (await payload.create({
|
const user = (await payload.create({
|
||||||
collection: 'users',
|
collection: 'users',
|
||||||
data: { email: '[email protected]', password: 'Passw0rd!x', roles: ['admin'] } as never,
|
data: { email: '[email protected]', password: 'Passw0rd!x-long', roles: ['admin'] } as never,
|
||||||
overrideAccess: false,
|
overrideAccess: false,
|
||||||
})) as unknown as { roles: string[] }
|
})) as unknown as { roles: string[] }
|
||||||
expect(user.roles).toEqual(['user'])
|
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 () => {
|
test('seed / Local API with overrideAccess can still create an admin', async () => {
|
||||||
const admin = (await payload.create({
|
const admin = (await payload.create({
|
||||||
collection: 'users',
|
collection: 'users',
|
||||||
data: { email: '[email protected]', password: 'Passw0rd!x', roles: ['admin'] } as never,
|
data: { email: '[email protected]', password: 'Passw0rd!x-long', roles: ['admin'] } as never,
|
||||||
})) as unknown as { roles: string[] }
|
})) as unknown as { roles: string[] }
|
||||||
expect(admin.roles).toEqual(['admin'])
|
expect(admin.roles).toEqual(['admin'])
|
||||||
})
|
})
|
||||||
@@ -401,7 +401,7 @@ describe('forms access', () => {
|
|||||||
|
|
||||||
const user = (await payload.create({
|
const user = (await payload.create({
|
||||||
collection: 'users',
|
collection: 'users',
|
||||||
data: { email: '[email protected]', password: 'Passw0rd!x' } as never,
|
data: { email: '[email protected]', password: 'Passw0rd!x-long' } as never,
|
||||||
})) as unknown as Record<string, unknown>
|
})) as unknown as Record<string, unknown>
|
||||||
await expect(
|
await expect(
|
||||||
payload.find({ collection: 'form-submissions' as never, overrideAccess: false, user: { ...user, collection: 'users' } as never }),
|
payload.find({ collection: 'form-submissions' as never, overrideAccess: false, user: { ...user, collection: 'users' } as never }),
|
||||||
|
|||||||
Reference in New Issue
Block a user