From 420fe404423a2039014da2a03a8c23d236061d22 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rados=C5=82aw=20Smoli=C5=84ski?= Date: Tue, 1 Dec 2026 11:18:21 +0100 Subject: [PATCH] Sign-in rules: tests that change their own password send the current one; field labels en/pl; the hook carries a mark Tests and the late-staff built-site spec that change an account's OWN password now send currentPassword (the 1.18.0 rule). The Current password field's label and description are plain { en, pl } (house style checked by the wording test). The beforeOperation hook carries SIGN_IN_RULES_MARK so the password-rule hook counts stay what they measure. The injected users collection carries Payload's lock defaults (50, 1 h). Co-Authored-By: Claude Opus 5.5 --- reference/e2e/late-staff.spec.ts | 3 ++- src/index.ts | 1 + src/modules/access/signInRules.ts | 10 +++++++--- src/modules/admin-i18n/texts/security.ts | 4 ---- test/accountRulesAdminValueSuite.ts | 2 +- test/accountRulesSuite.ts | 9 +++++---- test/exemptByField.test.ts | 3 ++- test/plugin.test.ts | 3 ++- 8 files changed, 20 insertions(+), 15 deletions(-) diff --git a/reference/e2e/late-staff.spec.ts b/reference/e2e/late-staff.spec.ts index 3e8c23b..90e6cec 100644 --- a/reference/e2e/late-staff.spec.ts +++ b/reference/e2e/late-staff.spec.ts @@ -91,7 +91,8 @@ test.describe('a late staff collection on a built site', () => { }]).toEqual([slug, { create: 403, integrations: 403, patch: 403, users: 403, zDelete: 403 }]) await api.patch(`/api/${slug}/${itsUserId}`, { data: { roles: ['admin'] } }) expect((await (await admin.get(`/api/${slug}/${itsUserId}`)).json()).roles, `${slug}: its own roles`).toEqual(['user']) - expect((await api.patch(`/api/${slug}/${itsUserId}`, { data: { password: `own-${PASSWORD}` } })).status(), `${slug}: its own password`).toBe(200) + // 1.18.0: with the current password (accounts.confirmOwnChanges) + expect((await api.patch(`/api/${slug}/${itsUserId}`, { data: { currentPassword: PASSWORD, password: `own-${PASSWORD}` } })).status(), `${slug}: its own password`).toBe(200) for (const id of [itsAdminId, itsUserId]) {expect((await admin.delete(`/api/${slug}/${id}`)).status()).toBe(200)} await api.dispose() } diff --git a/src/index.ts b/src/index.ts index 2377f47..5451a4b 100644 --- a/src/index.ts +++ b/src/index.ts @@ -60,6 +60,7 @@ export { releaseSignInPlace, resolveSignInRules, settleFailedSignIn, + SIGN_IN_RULES_MARK, } from './modules/access/signInRules.js' export type { SignInLimitOptions, SignInRulesOptions, SignInSameOriginOptions } from './modules/access/signInRules.js' export type { AccountsOptions } from './modules/access/types.js' diff --git a/src/modules/access/signInRules.ts b/src/modules/access/signInRules.ts index 2283e0b..3a52d93 100644 --- a/src/modules/access/signInRules.ts +++ b/src/modules/access/signInRules.ts @@ -126,8 +126,11 @@ const signInOriginOk = (req: PayloadRequest, origins: string[]): boolean => { } /** `beforeOperation` for a staff collection: the origin rule, the failure count and the current-password rule. */ +/** Mark on the sign-in rules' `beforeOperation` hook (tells it apart from the account rules' password hook). */ +export const SIGN_IN_RULES_MARK = Symbol.for('iapl.signInRules') + export function buildSignInBeforeOperation(slug: string, rules: Resolved): CollectionBeforeOperationHook { - return async ({ args, operation, req }) => { + const hook: CollectionBeforeOperationHook = async ({ args, operation, req }) => { if (isLocal(req)) {return args} const data = ((args as { data?: Record }).data ?? {}) if (operation === 'login' || operation === 'forgotPassword' || operation === 'resetPassword') { @@ -141,6 +144,7 @@ export function buildSignInBeforeOperation(slug: string, rules: Resolved): Colle if (operation === 'update' && rules.confirm) {await confirmOwnChange(slug, args as never, req, rules)} return args } + return Object.assign(hook, { [SIGN_IN_RULES_MARK]: true }) } /** `afterLogin`: the sign-in worked, its place goes back. */ @@ -197,10 +201,10 @@ export function buildCurrentPasswordField(): Field { const user = (ctx as { user?: { id?: unknown } | null } | undefined)?.user return Boolean(user && data?.id !== undefined && String(user.id) === String(data.id)) }, - description: ({ t }) => serverText({ language: (t as unknown as { i18n?: { language?: string } })?.i18n?.language } as never, 'currentPasswordDescription'), + description: { en: 'Needed only to change your own e-mail address or password.', pl: 'Potrzebne tylko do zmiany własnego adresu e-mail lub hasła.' }, }, hooks: { afterRead: [() => undefined] }, - label: ({ t }) => serverText({ language: (t as unknown as { i18n?: { language?: string } })?.i18n?.language } as never, 'currentPasswordLabel'), + label: { en: 'Current password', pl: 'Obecne hasło' }, virtual: true, } as Field } diff --git a/src/modules/admin-i18n/texts/security.ts b/src/modules/admin-i18n/texts/security.ts index c84f7f5..9d4336d 100644 --- a/src/modules/admin-i18n/texts/security.ts +++ b/src/modules/admin-i18n/texts/security.ts @@ -3,8 +3,6 @@ import { defineTexts } from '../define.js' /** Admin component texts — two-step verification (2FA). Placeholders use Payload's {{name}} syntax. */ export const securityTexts = defineTexts({ en: { - currentPasswordDescription: 'Needed only to change your own e-mail address or password.', - currentPasswordLabel: 'Current password', currentPasswordRequired: 'Enter your current password to change your e-mail address or password.', currentPasswordWrong: 'The current password is not right.', passwordIsEmail: 'The password cannot be the same as the e-mail address.', @@ -35,8 +33,6 @@ 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: { - currentPasswordDescription: 'Potrzebne tylko do zmiany własnego adresu e-mail lub hasła.', - currentPasswordLabel: 'Obecne hasło', currentPasswordRequired: 'Wpisz obecne hasło, aby zmienić adres e-mail lub hasło.', currentPasswordWrong: 'Obecne hasło jest nieprawidłowe.', passwordIsEmail: 'Hasło nie może być takie samo jak adres e-mail.', diff --git a/test/accountRulesAdminValueSuite.ts b/test/accountRulesAdminValueSuite.ts index fdde1bb..6522e2f 100644 --- a/test/accountRulesAdminValueSuite.ts +++ b/test/accountRulesAdminValueSuite.ts @@ -139,7 +139,7 @@ export function adminValueSuite(twoFactor: boolean): void { } // what stays: its own password const me = (await login(slug, `low@${slug}.example.com`))! - expect([slug, (await call('PATCH', `/${slug}/${mine.id}`, me, { password: 'my-own-new-password-1' })).status]).toEqual([slug, 200]) + expect([slug, (await call('PATCH', `/${slug}/${mine.id}`, me, { currentPassword: PASSWORD, password: 'my-own-new-password-1' })).status]).toEqual([slug, 200]) // who manages the accounts: an admin of the collection where it has one, and an admin of another staff collection const managers = [(await login('agents', 'admin@agents.example.com'))!, ...(top === 'admin' && slug !== 'rel-roles' ? [(await login(slug, `top@${slug}.example.com`))!] : [])] // (over REST a related role arrives as a document, not as 'admin': that account is no admin there) for (const [index, manager] of managers.entries()) { diff --git a/test/accountRulesSuite.ts b/test/accountRulesSuite.ts index a431c3c..081deec 100644 --- a/test/accountRulesSuite.ts +++ b/test/accountRulesSuite.ts @@ -33,8 +33,8 @@ import { totp } from './http/totp.js' * A `beforeOperation` hook of the account rules. Every auth collection also carries the mark that tells the mail * service what Payload's own account mail is (modules/email/relay/accountMail.ts): that one is not counted here. */ -// the account-mail hooks (the relay's kind mark, the after-commit hold) are not account rules -const ruleHook = (hook: unknown) => !(hook as Record)[Symbol.for('iapl.accountMailMark')] && !(hook as Record)[Symbol.for('iapl.accountMailAfterCommit')] +// the account-mail hooks (the relay's kind mark, the after-commit hold) and the sign-in rules (1.18.0) are not the password rule +const ruleHook = (hook: unknown) => !(hook as Record)[Symbol.for('iapl.accountMailMark')] && !(hook as Record)[Symbol.for('iapl.accountMailAfterCommit')] && !(hook as Record)[Symbol.for('iapl.signInRules')] const TOTP_SECRET = 'JBSWY3DPEHPK3PXP' @@ -254,7 +254,8 @@ export function accountRulesSuite(twoFactor: boolean): void { } expect(await canLogIn('agents', 'agent@example.com', NEW)).toBe(false) // its own account: yes — and never a delete - expect((await patch(`/agents/${own}`, { password: 'my-own-new-password-1' }, agentEditor)).status).toBe(200) + // 1.18.0: one's own password needs the current one (accounts.confirmOwnChanges) + expect((await patch(`/agents/${own}`, { currentPassword: PASSWORD, password: 'my-own-new-password-1' }, agentEditor)).status).toBe(200) expect(await canLogIn('agents', 'agent-editor@example.com', 'my-own-new-password-1')).toBe(true) expect((await remove(`/agents/${own}`, agentEditor)).status).toBe(403) // the injected collection: the same, and the roles field is the admin's @@ -289,7 +290,7 @@ export function accountRulesSuite(twoFactor: boolean): void { const low = await login('agents', 'low@agents.example.com') const id = await idOf('agents', 'low@agents.example.com') const rolesOf = async (collection: string, of: unknown) => ((await payload.findByID({ id: of as never, collection: collection as never })) as { roles?: string[] }).roles - for (const body of [{ roles: ['admin'] }, { roles: 'admin' }, { password: 'another-long-password-1', roles: ['admin', 'user'] }]) { + for (const body of [{ roles: ['admin'] }, { roles: 'admin' }, { currentPassword: PASSWORD, password: 'another-long-password-1', roles: ['admin', 'user'] }]) { await patch(`/agents/${id}`, body, low) expect(await rolesOf('agents', id)).toEqual(['user']) } diff --git a/test/exemptByField.test.ts b/test/exemptByField.test.ts index e092aed..1d91b19 100644 --- a/test/exemptByField.test.ts +++ b/test/exemptByField.test.ts @@ -77,7 +77,8 @@ describe('exempt from 2FA setup: by an admin-only field, not by e-mail', () => { }) test('…while the same editor can change its own e-mail to anything: an e-mail list is no boundary', async () => { - const res = await call(`/users/${editorId}`, { body: JSON.stringify({ email: 'it@example.com' }), method: 'PATCH' }) + // (1.18.0: with its current password — accounts.confirmOwnChanges) + const res = await call(`/users/${editorId}`, { body: JSON.stringify({ currentPassword: PASSWORD, email: 'it@example.com' }), method: 'PATCH' }) expect(res.status).toBe(200) const stored = (await payload.findByID({ id: editorId, collection: 'users' as never, overrideAccess: true })) as unknown as { email: string } expect(stored.email).toBe('it@example.com') diff --git a/test/plugin.test.ts b/test/plugin.test.ts index 47b98f4..cef9ee5 100644 --- a/test/plugin.test.ts +++ b/test/plugin.test.ts @@ -91,7 +91,8 @@ describe('iapl — auth collection', () => { } as unknown as Config) const users = config.collections?.find((c) => c.slug === 'users') // an auth collection with Payload's defaults; the plugin only wraps the reset mail's subject (mail.accountMailAfterCommit) - expect(users?.auth).toEqual({ forgotPassword: { generateEmailSubject: expect.any(Function) } }) + // 1.18.0: Payload's per-account lock at 50 failures for an hour (accounts.signInLimit), beside the per-IP count + expect(users?.auth).toEqual({ forgotPassword: { generateEmailSubject: expect.any(Function) }, lockTime: 3_600_000, maxLoginAttempts: 50 }) expect(users?.fields.some((f) => 'name' in f && f.name === 'roles')).toBe(true) })