A locked staff account answers its login like a wrong password (accounts.lockedAnswer)
Payload checks the lock before the password, so after five wrong passwords
a staff address answered "This user is locked…" to any password while an
address with no account always answered "The email or password provided is
incorrect.": anybody could find out which addresses have a staff account
(IAWL idea 6, owner's Q1). A config-level afterError hook now answers
LockedAuth on a staff collection's login exactly like AuthenticationError:
REST status and body, GraphQL message and extensions.name. The lock is
unchanged; visitor collections keep Payload's answer.
accounts: { lockedAnswer: 'payload' } keeps Payload's message; any other
value stops the start. Building blocks lockedLooksWrong, withLockedAnswer,
graphqlLoginName.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
co-authored by
Claude Opus 5.5
parent
fc70a34f3e
commit
15b5c6258d
+21
-1
@@ -250,6 +250,7 @@ iapl({
|
||||
// accounts: { firstUserRoute: 'all' }, // Payload's first-user route for every empty auth collection
|
||||
// accounts: { firstUserRoute: ['users', 'partners'] },
|
||||
// accounts: { password: { minLength: 16 } }, // or password: false
|
||||
// accounts: { lockedAnswer: 'payload' }, // a locked staff account is told it is locked (Payload's answer)
|
||||
// accounts: false, // none of the rules
|
||||
})
|
||||
```
|
||||
@@ -477,10 +478,29 @@ characters."; texts `passwordTooShort`, `passwordIsEmail` in `i18n.translations.
|
||||
`DEFAULT_PASSWORD_MIN_LENGTH`.
|
||||
- **Check:** create an account with an 11-character password → "The password must have at least 12 characters.".
|
||||
|
||||
### A locked staff account answers like a wrong password (`accounts.lockedAnswer`, 1.17.2)
|
||||
|
||||
Payload locks an account after `maxLoginAttempts` wrong passwords (5 by default) for `lockTime` (10 minutes), and
|
||||
it checks the lock **before** the password: the locked account then gets `401 "This user is locked due to having too
|
||||
many failed login attempts."` for any password, while an address with no account always gets `401 "The email or
|
||||
password provided is incorrect."`. Five wrong guesses told anybody, without a password, whether an address has a
|
||||
staff account. Now a staff collection's login answers a locked account exactly like a wrong password — the same
|
||||
status, body and GraphQL `extensions.name` (`AuthenticationError`) — over REST, GraphQL and the panel's sign-in
|
||||
form. The lock itself is unchanged: the owner's correct password is still refused until it ends, and the owner is
|
||||
then told "wrong e-mail or password" (an administrator sees `lockUntil` on the account and can unlock it). Visitor
|
||||
collections (not staff) keep Payload's answer.
|
||||
|
||||
- **Turn off:** `accounts: { lockedAnswer: 'payload' }` (Payload's message), or `accounts: false`. Any other value
|
||||
stops the start.
|
||||
- **Building blocks:** `lockedLooksWrong` (the config-level `afterError` hook), `withLockedAnswer(config)`,
|
||||
`graphqlLoginName(collection)` (`login<SingularName>`, as GraphQL names the mutation).
|
||||
- **Check:** five wrong passwords for an admin's address, then `POST /api/users/login` with the right one → the same
|
||||
`401` body as for `nobody@example.com`; GraphQL `loginUser` → `extensions.name: "AuthenticationError"`.
|
||||
|
||||
## Turn off, override, extend
|
||||
|
||||
- **Account rules:** `accounts: false`, or one by one — `panelRole`, `adminOnlyCreate`, `adminOnlyWrite`,
|
||||
`staffOnlyRead`, `firstUserRoute`, `password` (above).
|
||||
`staffOnlyRead`, `firstUserRoute`, `password`, `lockedAnswer` (above).
|
||||
- **Turn off:** leave out `access` — no `roles` field, the auth collection keeps Payload's rules
|
||||
(or yours). `access.firstUserAdmin: false` stops giving admin to the first account.
|
||||
- **Override:** `access.staffCollections` (who is staff), `access.authAccess` (injected collection), your own auth collection (wins whole),
|
||||
|
||||
@@ -1232,6 +1232,7 @@ add missing hosts with flags / `extra`; (3) change `mode` to `'enforce'` in both
|
||||
| The SMTP password stays with its server: a save in the panel or over the API that changes the server, port or user name without the password is refused (`400` "Enter the password again…"), whatever the transport says — otherwise an admin session points the server at its own machine and a test e-mail hands the password over. A change of the transport alone asks for nothing. Seeds and scripts (Local API, access control off) are not asked | `secrets: { reenterOnChange: false }` | `writeOnlySecret(field, { boundTo: [...] })`, `buildKeepSecret`, `SMTP_PASSWORD_BOUND_TO` |
|
||||
| The admin panel opens for `editor` and above; an account with only `user` sees "Unauthorized" (the API is not touched). First start logs how many accounts are below the role | `accounts: { panelRole: 'user' }` (or `false`) | `panelRole: 'admin'`; your own `access.admin`; `panelAccess(role)` |
|
||||
| Nobody creates an account for themselves, or takes one over. A staff collection (also the project's own, also one a later plugin adds) without a `create` / `update` / `delete` / `unlock` / `read` / `readVersions` rule gets one (on a collection a later plugin adds the plugin's rule is put in front of its own and both must allow; `custom: { ipal: { accountRules: false } }` on it keeps its own): with the plugin's roles, or wherever an account of it can hold `editor` or `admin` (`user, editor, admin, boss`; `viewer, editor`; a `roles` field that is text, json or a relationship holding a list — the value in the account's `roles` array makes a plugin admin or editor; a single-valued `roles` field is not affected: its value never counts) — create, delete, unlock: an admin; update: an admin or the account itself; the `roles` field: only an admin. With roles of its own that hold neither `editor` nor `admin`, or none: an account of that same collection, or a plugin admin, and an account never changes its own roles — **the plugin cannot rank a project's own roles: write that collection's rules** (`iapl-doctor` → `staff-own-roles`). `read`: a staff account. Payload's first-user route answers only for the panel's login collection (the first account, which becomes admin), in any spelling of the URL. `access.firstUserAdmin: false` with a default role below the panel role: the default panel role is not applied (logged), an explicit one is refused at start. With a slug in `access.staffCollections` that is not an auth collection Payload does not start (`/api/health` 503) | `accounts: { adminOnlyCreate: false, adminOnlyWrite: false, staffOnlyRead: false, firstUserRoute: 'all' }` | your own rule wins; `firstUserRoute: ['users', 'partners']`; a collection with open sign-up keeps its routes; `staffCreateAccess`, `staffUpdateAccess(slug)`, `staffReadAccess`, `sameStaffCollectionAccess(slug)`, `rolesByAdminOnly`, `rolesNotOwn(slug)`, `hasPluginRoles`, `applyStaffAccountAccess`, `adoptLateAuthCollections`, `buildFirstUserEndpoint` |
|
||||
| A locked staff account (Payload's `maxLoginAttempts`) answers its login exactly like a wrong password — REST body and status, GraphQL `extensions.name: AuthenticationError`, the panel's sign-in (1.17.2); visitor collections keep Payload's answer. **Verify:** 5 wrong passwords for an admin, then the right one → the same `401` body as for an unknown address | `accounts: { lockedAnswer: 'payload' }` | `lockedLooksWrong`, `withLockedAnswer(config)`, `graphqlLoginName` |
|
||||
| A password set on a staff account has at least 12 characters and is not the e-mail address; existing passwords are not checked | `accounts: { password: false }` | `password: { minLength }`; `checkPassword`, `buildPasswordRuleHook` |
|
||||
| While Turnstile cannot check (wrong secret, Cloudflare down): a text form is accepted, a form with files is refused | `forms: { turnstileOnConfigError: 'allow' }` | `'reject'`, `{ text, files }`; `turnstileOnConfigError` at a call site wins |
|
||||
| Dashboard alerts by role: integration details for admins, a neutral line for editors, nothing for others; cookie alerts for editors and above. `'all'` checks nothing — no role, no second factor | `dashboardAlerts: { integrations: 'all', cookies: 'all' }` | `integrations: 'editor'`; the components' `details` / `audience` props |
|
||||
|
||||
@@ -34,6 +34,7 @@ through this procedure. Ask only when you are missing something you cannot get y
|
||||
### Build / TypeScript
|
||||
| Symptom | Cause | Fix |
|
||||
|---|---|---|
|
||||
| a staff account's correct password gets "The email or password provided is incorrect." | the account is locked by Payload after `maxLoginAttempts` wrong passwords (5, for `lockTime`, 10 min); since 1.17.2 a locked staff account gets the wrong-password answer (`accounts.lockedAnswer`) | wait for the lock to end, or an admin unlocks it (the account in the panel, or `POST /api/users/unlock`); `lockUntil` on the account shows it. Payload's own message back: `accounts: { lockedAnswer: 'payload' }` |
|
||||
| the 2FA code screen answers "Too many codes were tried…" (`429` from `/api/verify-totp`) | more than 5 wrong codes for that account in 10 minutes (`twoFactor.verifyLimit`; right codes do not count since 1.17.1). "…being checked right now. Try again in a moment." (`Retry-After: 2`) = several attempts of one account at the same moment, nothing is locked; repeated lines `[iapl] 2FA: too many verify attempts` in the log without the owner trying = someone has the password | wait for the window, enter the current code once; unexplained attempts: change that account's password. Tests that log in often: `verifyLimit: { max: … }` for that environment |
|
||||
| `isAdmin(req.user)` says `false` for a real administrator on the server, in a process that loads two Payload configs (tests, a multi-site script) | a call without a source counts only collections that are staff in **every** config of the process | pass the source: `isAdmin(req.user, req.payload)` — with it each config gets its own answer |
|
||||
| `isAdmin(user)` / `isEditor(user)` is always `false` in a client component or in `proxy.ts` | the staff collections are not known there (no config in the browser bundle / middleware), and the predicates fail closed | `isAdmin(user, config)` with `useConfig()`, imported from `@intecion/ipal-kit/client`; in middleware `isAdmin(user, { staffCollections: ['users'] })` |
|
||||
|
||||
@@ -38,6 +38,7 @@ description: Complete map of everything @intecion/ipal-kit provides — every ia
|
||||
| `accounts.staffOnlyRead` | on | `read` and `readVersions` on a staff collection without those rules: a fully signed-in account of a staff collection (Payload's default let a visitor account list the staff accounts) | `false` = Payload's default; a `read` rule you wrote wins |
|
||||
| `accounts.firstUserRoute` | `'panel'` | which auth collections `POST /api/<slug>/first-register` answers for while they are empty: only the one the panel logs in with (the first account of a site → admin). Others get `403`, a second staff collection included, in any spelling of the URL (the plugin's own endpoint sits in front of Payload's); a collection whose own `create` allows an anonymous request keeps its route. With `access.firstUserAdmin: false` and a default role below the panel role, the default `panelRole` is not applied (logged) and an explicit one is refused at start | a list of slugs; `'all'` = Payload's behaviour |
|
||||
| `accounts.password` | `{ minLength: 12 }` | when a password is SET on a staff collection (create, first-user screen, change, reset by e-mail; panel, API and Local API): at least `minLength` characters, not the account's e-mail address. Existing passwords are never checked — a shorter one keeps logging in | `{ minLength }`; `false` = Payload's rule (3 characters) |
|
||||
| `accounts.lockedAnswer` | `'wrong'` (1.17.2) | a staff account Payload has locked (too many wrong passwords) gets exactly the wrong-password answer on login (REST, GraphQL, the panel): nobody tells which addresses have an account; the lock itself is unchanged | `'payload'` = Payload's "This user is locked…"; any other value stops the start |
|
||||
| `secrets.writeOnly` | on | `smtpPassword` and `turnstileSecretKey` (Site integrations) are never returned: REST, GraphQL and the panel get `'********'` when a value is stored; a save with nothing / empty / the mask keeps it, a new value replaces it, `'[[clear]]'` removes it; the Local API with access control off reads the real value. The panel is the source of these secrets — no env variable. A restore of a version is masked too | `false` = returned to whoever may read the global, as before |
|
||||
| "Sending method" (`emailMethod`; `getMailMethod` / `setMailMethod`) | nobody has chosen: the order of 1.17.0, shown as selected | `relay` (IWSN), `smtp`, `graph` (deprecated): what is chosen is what is used, no fallback; a stored field (Postgres / SQLite: one migration) |
|
||||
| `secrets.reenterOnChange` | on | a save through access control that changes `smtpHost`, `smtpPort` or `smtpUser` while a password is stored must send the password again or remove it (`400` on the field otherwise), whatever `emailTransport` says — so an admin session cannot send the stored password to a server of its own. A change of the transport alone, and the Local API with access control off, are not asked | `false` = the stored password follows the new server |
|
||||
|
||||
@@ -85,7 +85,9 @@ Admin panel components from `@intecion/ipal-kit/admin` — the project does NOT
|
||||
| `buildRolesField(defaultRole?, { firstUserAdmin? })` | `@intecion/ipal-kit` | The `roles` select field the plugin injects (only admins set roles; `firstUserAdmin` default `true` = the account made on "Create first user" gets `admin`). The plugin wires it itself — use it only for an auth collection the plugin does not manage. |
|
||||
| `injectRoles(config, accessOption)` | `@intecion/ipal-kit` | Adds `roles` to `accessOption.authCollection` in a config. The plugin calls it itself with `access` — do not call. |
|
||||
|
||||
**Types:** `AccountsOptions` (`accounts`: `panelRole`, `adminOnlyCreate`, `adminOnlyWrite`, `staffOnlyRead`, `firstUserRoute`, `password`), `StaffAccountAccessOptions` (`{ create?, write?, read?, pluginRoles? }`), `StaffRuleMark` (`{ slug, self }`), `AccountsMarker` (`{ slug, staff, own? }`, in `custom.ipalAccounts`; `own`: the operations that had a rule of the project's at config time, kept when the collection becomes staff later), `LateAdoption` (`{ slug, applied, kept, known, password, firstUser }`; `known`: in the config when iapl ran and staff only afterwards, `kept`: its operations whose own rule was left as written), `StaffAccountRules` (what the plugin put on a staff collection, in `custom.ipalAccountRules`: `{ applied, ownRoles }`), `WriteOnlySecretOptions` (`{ boundTo?, appliesWhen? }`), `PasswordRuleOptions` (`{ minLength? }`), `FirstUserRouteOption` (`'panel' \| 'all' \| string[]`), `TurnstileOnConfigError` / `TurnstileOnConfigErrorOption` / `TurnstileFormKind` (`@intecion/ipal-kit/server`), `VerifyLimitOptions` (`twoFactor.verifyLimit`: `{ max?, windowMinutes?, store? }`), `RequireSetupOptions` (`twoFactor.requireSetup`), `TwoFactorResetOptions`, `TwoFactorSetupState`, `SafeBackRule` / `SafeBackContext` (`twoFactor.safeBack` as a function: `(back, { adminRoute, origin? }) => string`), `TotpViewComponent` (a view component as registered: a path or `{ path, exportName?, clientProps?, serverProps? }`), `SafeTotpViewProps` (`@intecion/ipal-kit/admin`), `Role` (`'user' \| 'editor' \| 'admin'`), `AccessOption` (the plugin's `access` option: `authCollection`, `defaultRole`, `authAccess`, `firstUserAdmin`, `staffCollections`).
|
||||
| `lockedLooksWrong`, `withLockedAnswer(config)`, `graphqlLoginName(collection)` | `@intecion/ipal-kit` | `accounts.lockedAnswer` (1.17.2): the config-level `afterError` hook that answers Payload's `LockedAuth` on a staff collection's login (REST, GraphQL) exactly like `AuthenticationError`; adding it to a config (idempotent); the GraphQL login mutation's name of a collection. |
|
||||
|
||||
**Types:** `AccountsOptions` (`accounts`: `panelRole`, `adminOnlyCreate`, `adminOnlyWrite`, `staffOnlyRead`, `firstUserRoute`, `password`, `lockedAnswer`), `LockedAnswerOption`, `StaffAccountAccessOptions` (`{ create?, write?, read?, pluginRoles? }`), `StaffRuleMark` (`{ slug, self }`), `AccountsMarker` (`{ slug, staff, own? }`, in `custom.ipalAccounts`; `own`: the operations that had a rule of the project's at config time, kept when the collection becomes staff later), `LateAdoption` (`{ slug, applied, kept, known, password, firstUser }`; `known`: in the config when iapl ran and staff only afterwards, `kept`: its operations whose own rule was left as written), `StaffAccountRules` (what the plugin put on a staff collection, in `custom.ipalAccountRules`: `{ applied, ownRoles }`), `WriteOnlySecretOptions` (`{ boundTo?, appliesWhen? }`), `PasswordRuleOptions` (`{ minLength? }`), `FirstUserRouteOption` (`'panel' \| 'all' \| string[]`), `TurnstileOnConfigError` / `TurnstileOnConfigErrorOption` / `TurnstileFormKind` (`@intecion/ipal-kit/server`), `VerifyLimitOptions` (`twoFactor.verifyLimit`: `{ max?, windowMinutes?, store? }`), `RequireSetupOptions` (`twoFactor.requireSetup`), `TwoFactorResetOptions`, `TwoFactorSetupState`, `SafeBackRule` / `SafeBackContext` (`twoFactor.safeBack` as a function: `(back, { adminRoute, origin? }) => string`), `TotpViewComponent` (a view component as registered: a path or `{ path, exportName?, clientProps?, serverProps? }`), `SafeTotpViewProps` (`@intecion/ipal-kit/admin`), `Role` (`'user' \| 'editor' \| 'admin'`), `AccessOption` (the plugin's `access` option: `authCollection`, `defaultRole`, `authAccess`, `firstUserAdmin`, `staffCollections`).
|
||||
|
||||
## Accessibility — widget (`accessibility`) — details: `node_modules/@intecion/ipal-kit/docs/accessibility.md`
|
||||
|
||||
|
||||
@@ -27,6 +27,8 @@ export { applyPasswordRule, buildPasswordRuleHook, checkPassword, DEFAULT_PASSWO
|
||||
export type { PasswordRuleOptions } from './modules/access/passwordRule.js'
|
||||
export { isPasswordRuleHook, staffRuleOf } from './modules/access/ruleMark.js'
|
||||
export type { StaffRuleMark } from './modules/access/ruleMark.js'
|
||||
export { graphqlLoginName, lockedLooksWrong, withLockedAnswer } from './modules/access/lockedAnswer.js'
|
||||
export type { LockedAnswerOption } from './modules/access/lockedAnswer.js'
|
||||
export {
|
||||
adoptLateAuthCollections,
|
||||
applyFirstUserRoute,
|
||||
|
||||
@@ -0,0 +1,67 @@
|
||||
import type { AfterErrorHook, Config, SanitizedCollectionConfig } from 'payload'
|
||||
|
||||
import { AuthenticationError, formatNames, toWords } from 'payload'
|
||||
|
||||
import { staffCollectionSlugs } from './predicates.js'
|
||||
|
||||
/**
|
||||
* A locked staff account answers its login exactly like a wrong password (`accounts.lockedAnswer`, 1.17.2).
|
||||
*
|
||||
* Payload checks the lock BEFORE the password: after five wrong passwords for `owner@site` any password gets
|
||||
* `401 "This user is locked due to having too many failed login attempts."` (GraphQL: `LockedAuth`), while an
|
||||
* address that has no account always gets `401 "The email or password provided is incorrect."`. Anybody could
|
||||
* tell which addresses have a staff account with no password at all (IAWL idea 6). This hook turns Payload's
|
||||
* `LockedAuth` on a staff collection's login into the `AuthenticationError` answer — same status, same body, same
|
||||
* GraphQL `extensions.name`. The price: the owner, while locked, is told "wrong e-mail or password" too.
|
||||
*
|
||||
* The lock itself is not touched (it still holds for `lockTime`). `accounts: { lockedAnswer: 'payload' }` keeps
|
||||
* Payload's message. The error is recognised by its `name` (`'LockedAuth'`, a string Payload sets — not a function
|
||||
* name, so a minified bundle keeps it) and by the collection: a staff collection only.
|
||||
*/
|
||||
export type LockedAnswerOption = 'payload' | 'wrong'
|
||||
|
||||
const isLocked = (error: unknown): boolean => (error as { name?: unknown } | null)?.name === 'LockedAuth'
|
||||
|
||||
/** The GraphQL login mutation's name of a collection, as @payloadcms/graphql builds it (`login${singularName}`). */
|
||||
export function graphqlLoginName(collection: Pick<SanitizedCollectionConfig, 'graphQL' | 'slug'>): null | string {
|
||||
const graphQL = collection.graphQL as { singularName?: string } | false | undefined
|
||||
if (graphQL === false) {return null}
|
||||
const singular = graphQL?.singularName ? toWords(graphQL.singularName, true) : formatNames(collection.slug).singular
|
||||
return `login${singular}`
|
||||
}
|
||||
|
||||
type T = ConstructorParameters<typeof AuthenticationError>[0]
|
||||
|
||||
/** The config-level `afterError` hook (REST and GraphQL). */
|
||||
export const lockedLooksWrong: AfterErrorHook = (args) => {
|
||||
const { collection, error, req } = args as { error: unknown; graphqlResult?: Record<string, unknown> } & Parameters<AfterErrorHook>[0]
|
||||
const payload = req?.payload
|
||||
if (!payload) {return}
|
||||
const staff = staffCollectionSlugs(payload)
|
||||
const wrong = new AuthenticationError(req.t as T)
|
||||
// GraphQL: the error is wrapped (`originalError`), the collection only shows in the mutation's name.
|
||||
const graphqlResult = (args as { graphqlResult?: { extensions?: Record<string, unknown>; path?: unknown[] } }).graphqlResult
|
||||
if (graphqlResult) {
|
||||
const original = (error as { originalError?: unknown }).originalError
|
||||
if (!isLocked(original)) {return}
|
||||
const field = Array.isArray(graphqlResult.path) ? graphqlResult.path[0] : undefined
|
||||
const names = new Set((payload.config.collections ?? []).filter((c) => staff.includes(c.slug)).map(graphqlLoginName))
|
||||
if (typeof field !== 'string' || !names.has(field)) {return}
|
||||
return {
|
||||
graphqlResult: {
|
||||
...graphqlResult,
|
||||
extensions: { ...graphqlResult.extensions, name: wrong.name, statusCode: wrong.status },
|
||||
message: wrong.message,
|
||||
},
|
||||
} as never
|
||||
}
|
||||
if (!isLocked(error) || !collection || !staff.includes(collection.slug)) {return}
|
||||
return { response: { errors: [{ message: wrong.message }] }, status: wrong.status } as never
|
||||
}
|
||||
|
||||
/** Adds the hook to a config (idempotent). */
|
||||
export function withLockedAnswer(config: Config): Config {
|
||||
const own = config.hooks?.afterError ?? []
|
||||
if (own.includes(lockedLooksWrong)) {return config}
|
||||
return { ...config, hooks: { ...config.hooks, afterError: [...own, lockedLooksWrong] } }
|
||||
}
|
||||
@@ -49,6 +49,13 @@ export type AccountsOptions = {
|
||||
* whose own `create` rule allows an anonymous request keeps its route.
|
||||
*/
|
||||
firstUserRoute?: 'all' | 'panel' | string[]
|
||||
/**
|
||||
* What a staff account that Payload has locked (too many wrong passwords) is told when it logs in.
|
||||
* Default (1.17.2): exactly what a wrong password gets — same status, message and GraphQL error name — so
|
||||
* nobody can find out which addresses have a staff account by locking them. The lock itself is unchanged.
|
||||
* `'wrong'` = the default, said out loud. `'payload'` = Payload's own "This user is locked due to having too many failed login attempts."
|
||||
*/
|
||||
lockedAnswer?: 'payload' | 'wrong'
|
||||
/**
|
||||
* The lowest role that may open the admin panel. Default `'editor'`: an
|
||||
* account that holds only `user` (the default role of a new account) sees
|
||||
|
||||
@@ -50,6 +50,9 @@ export function assertPluginSwitches(options: Record<string, unknown>): void {
|
||||
// `accounts: 0` / `''` dropped every account rule (staff-only reads, admin-only writes, the panel role,
|
||||
// the password rule, the closed first-user route).
|
||||
assertSwitchOrObject('accounts', options.accounts, { allowTrue: false })
|
||||
// 1.17.2: only 'payload' brings Payload's "locked" answer back (it tells which addresses have an account).
|
||||
const accounts = bag(options.accounts)
|
||||
if (accounts) {assertOneOf('accounts.lockedAnswer', accounts.lockedAnswer, ['payload', 'wrong'])}
|
||||
|
||||
// Opt-in features that add public endpoints or outbound calls: `'false'` switched them ON.
|
||||
for (const name of ['cookieScanner', 'stats', 'consentLog', 'adminMeta', 'whiteLabel'] as const) {
|
||||
|
||||
@@ -13,6 +13,7 @@ import { applyGlobalOverrides } from './globals/overrides.js'
|
||||
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 { withLockedAnswer } from './modules/access/lockedAnswer.js'
|
||||
import { applyPanelRole, countBelowPanelRole, resolvePanelRole } from './modules/access/panelRole.js'
|
||||
import { applyPasswordRule, buildPasswordRuleHook, resolvePasswordRule } from './modules/access/passwordRule.js'
|
||||
import { adoptLateAuthCollections, applyFirstUserRoute, applyStaffAccountAccess, markSeenAuthCollections, markStaffRules, staffCollectionsNobodyManages, unknownStaffCollections } from './modules/access/selfRegistration.js'
|
||||
@@ -258,6 +259,8 @@ export const iapl = (options: IaplOptions): Plugin => {
|
||||
const panelSlug = config.admin?.user ?? (config.collections ?? []).find((c) => c.auth)?.slug
|
||||
const staffSlugs = [...new Set([panelSlug, options.access?.authCollection, ...(options.access?.staffCollections ?? [])].filter((s): s is string => Boolean(s)))]
|
||||
config = applyStaffAccountAccess(config, staffSlugs, { ...accountAccess, pluginRoles: options.access?.authCollection ? [options.access.authCollection] : [] })
|
||||
// A locked staff account answers like a wrong password (accounts.lockedAnswer).
|
||||
if (accounts.lockedAnswer !== 'payload') {config = withLockedAnswer(config)}
|
||||
}
|
||||
if (options.twoFactor !== false) {
|
||||
const tf = options.twoFactor
|
||||
|
||||
@@ -0,0 +1,35 @@
|
||||
/** A locked staff account answers like a wrong password, REST and GraphQL (lockedAnswerSuite.ts). 2FA on. */
|
||||
import { describe, expect, test, vi } from 'vitest'
|
||||
|
||||
import { lockedAnswerSite, PASSWORD } from './lockedAnswerSuite.js'
|
||||
|
||||
vi.mock('server-only', () => ({}))
|
||||
vi.mock('next/headers.js', async () => (await import('./http/server.js')).nextHeadersMock)
|
||||
|
||||
const { gqlLogin, lock, restLogin, state } = lockedAnswerSite()
|
||||
|
||||
describe('accounts.lockedAnswer (default): a locked staff account looks like a wrong password', () => {
|
||||
test('REST: the locked owner, with any password, gets exactly what an invented address gets', async () => {
|
||||
await lock('users', '[email protected]')
|
||||
const invented = await restLogin('users', '[email protected]', 'a-wrong-password')
|
||||
expect(invented.status).toBe(401)
|
||||
expect(await restLogin('users', '[email protected]', 'a-wrong-password')).toEqual(invented)
|
||||
expect(await restLogin('users', '[email protected]', PASSWORD)).toEqual(invented)
|
||||
expect(invented.body).not.toMatch(/locked/i)
|
||||
// the lock itself is still there
|
||||
const stored = (await state.payload.find({ collection: 'users' as never, overrideAccess: true, showHiddenFields: true, where: { email: { equals: '[email protected]' } } })).docs[0] as { lockUntil?: string }
|
||||
expect(new Date(String(stored.lockUntil)).getTime()).toBeGreaterThan(Date.now())
|
||||
})
|
||||
|
||||
test('GraphQL: the same message, status and error name', async () => {
|
||||
const invented = await gqlLogin('loginUser', '[email protected]', 'a-wrong-password')
|
||||
expect(invented.name).toBe('AuthenticationError')
|
||||
expect(await gqlLogin('loginUser', '[email protected]', PASSWORD)).toEqual(invented)
|
||||
})
|
||||
|
||||
test('a visitor collection keeps Payload\'s answer (not staff)', async () => {
|
||||
await lock('customers', '[email protected]', 3)
|
||||
expect((await restLogin('customers', '[email protected]', PASSWORD)).body).toMatch(/locked/i)
|
||||
expect((await gqlLogin('loginCustomer', '[email protected]', PASSWORD)).name).toBe('LockedAuth')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,16 @@
|
||||
/** A locked staff account answers like a wrong password with 2FA off too (lockedAnswerSuite.ts). */
|
||||
import { describe, expect, test, vi } from 'vitest'
|
||||
|
||||
import { lockedAnswerSite, PASSWORD } from './lockedAnswerSuite.js'
|
||||
|
||||
vi.mock('server-only', () => ({}))
|
||||
|
||||
const { gqlLogin, lock, restLogin } = lockedAnswerSite({ twoFactor: false })
|
||||
|
||||
describe('accounts.lockedAnswer with twoFactor: false', () => {
|
||||
test('REST and GraphQL answer the locked owner like an invented address', async () => {
|
||||
await lock('users', '[email protected]')
|
||||
expect(await restLogin('users', '[email protected]', PASSWORD)).toEqual(await restLogin('users', '[email protected]', 'x-wrong-password-1'))
|
||||
expect(await gqlLogin('loginUser', '[email protected]', PASSWORD)).toEqual(await gqlLogin('loginUser', '[email protected]', 'x-wrong-password-1'))
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,23 @@
|
||||
/** accounts.lockedAnswer: 'payload' keeps Payload's "locked" answer (lockedAnswerSuite.ts). */
|
||||
import { describe, expect, test, vi } from 'vitest'
|
||||
|
||||
import { iapl } from '../src/plugin.js'
|
||||
import { lockedAnswerSite, PASSWORD } from './lockedAnswerSuite.js'
|
||||
|
||||
vi.mock('server-only', () => ({}))
|
||||
vi.mock('next/headers.js', async () => (await import('./http/server.js')).nextHeadersMock)
|
||||
|
||||
const { gqlLogin, lock, restLogin } = lockedAnswerSite({ lockedAnswer: 'payload' })
|
||||
|
||||
describe("accounts.lockedAnswer: 'payload'", () => {
|
||||
test('the locked owner is told it is locked, REST and GraphQL', async () => {
|
||||
await lock('users', '[email protected]')
|
||||
expect((await restLogin('users', '[email protected]', PASSWORD)).body).toMatch(/locked/i)
|
||||
expect((await gqlLogin('loginUser', '[email protected]', PASSWORD)).name).toBe('LockedAuth')
|
||||
})
|
||||
|
||||
test('a value nobody understands stops the start', async () => {
|
||||
const config = { collections: [], secret: 'x' } as never
|
||||
await expect((async () => iapl({ accounts: { lockedAnswer: 'Payload' as never }, i18n: { defaultLocale: 'en', locales: [{ code: 'en', label: 'English' }] } } as never)(config))()).rejects.toThrow(/accounts\.lockedAnswer must be one of/)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,79 @@
|
||||
/**
|
||||
* A locked staff account answers its login exactly like a wrong password (accounts.lockedAnswer, 1.17.2; IAWL
|
||||
* idea 6). Shared by lockedAnswer.test.ts (default, 2FA on), lockedAnswer2fa-off.test.ts (2FA off) and
|
||||
* lockedAnswerPayload.test.ts (`lockedAnswer: 'payload'`): one Payload per file.
|
||||
* Database: SQLite in memory, or IPAL_TEST_POSTGRES_URI / IPAL_TEST_MONGO_URI (test/http/db.ts).
|
||||
*/
|
||||
import type { Payload } from 'payload'
|
||||
|
||||
import { payloadTotp } from '@clocklimited/payload-2fa'
|
||||
import { lexicalEditor } from '@payloadcms/richtext-lexical'
|
||||
import { getPayload } from 'payload'
|
||||
import { afterAll, beforeAll } from 'vitest'
|
||||
|
||||
import { iapl } from '../src/plugin.js'
|
||||
import { buildTestConfig } from './helpers.js'
|
||||
import { testDatabase } from './http/db.js'
|
||||
import { startPayloadServer, type TestServer } from './http/server.js'
|
||||
|
||||
export const PASSWORD = 'a-long-test-password-1'
|
||||
|
||||
export type Answer = { body: string; status: number }
|
||||
|
||||
export function lockedAnswerSite({ lockedAnswer, twoFactor = true }: { lockedAnswer?: 'payload'; twoFactor?: boolean } = {}) {
|
||||
const state = {} as { payload: Payload; server: TestServer }
|
||||
beforeAll(async () => {
|
||||
const config = buildTestConfig({
|
||||
admin: { user: 'users' },
|
||||
collections: [
|
||||
// a visitor collection with Payload's own lock: not staff, not changed
|
||||
{ slug: 'customers', access: { create: () => true }, auth: { maxLoginAttempts: 3 }, fields: [] },
|
||||
{ slug: 'media', fields: [], upload: { staticDir: '/tmp/iapl-locked-answer-media' } },
|
||||
],
|
||||
db: testDatabase('lockedanswer'),
|
||||
editor: lexicalEditor(),
|
||||
plugins: [
|
||||
iapl({
|
||||
access: { authCollection: 'users' },
|
||||
...(lockedAnswer ? { accounts: { lockedAnswer } } : {}),
|
||||
i18n: { defaultLocale: 'en', locales: [{ code: 'en', label: 'English' }] },
|
||||
twoFactor: twoFactor ? { issuer: 'Example', plugin: payloadTotp } : false,
|
||||
}),
|
||||
],
|
||||
secret: 'integration-test-secret-0123456789',
|
||||
telemetry: false,
|
||||
})
|
||||
state.payload = await getPayload({ config })
|
||||
state.server = await startPayloadServer(config)
|
||||
await state.payload.create({ collection: 'users' as never, data: { email: '[email protected]', password: PASSWORD, roles: ['admin'] } as never })
|
||||
await state.payload.create({ collection: 'customers' as never, data: { email: '[email protected]', password: PASSWORD } as never })
|
||||
}, 120_000)
|
||||
afterAll(async () => {
|
||||
await state.server?.close()
|
||||
await state.payload?.destroy?.()
|
||||
})
|
||||
|
||||
const restLogin = async (collection: string, email: string, password: string): Promise<Answer> => {
|
||||
const res = await fetch(`${state.server.url}/api/${collection}/login`, {
|
||||
body: JSON.stringify({ email, password }),
|
||||
headers: { 'content-type': 'application/json' },
|
||||
method: 'POST',
|
||||
})
|
||||
return { body: await res.text(), status: res.status }
|
||||
}
|
||||
const gqlLogin = async (mutation: string, email: string, password: string) => {
|
||||
const res = await fetch(`${state.server.url}/api/graphql`, {
|
||||
body: JSON.stringify({ query: `mutation { ${mutation}(email: ${JSON.stringify(email)}, password: ${JSON.stringify(password)}) { token } }` }),
|
||||
headers: { 'content-type': 'application/json' },
|
||||
method: 'POST',
|
||||
})
|
||||
const body = (await res.json()) as { errors?: { extensions?: { name?: string; statusCode?: number }; message: string }[] }
|
||||
const e = body.errors?.[0]
|
||||
return { name: e?.extensions?.name, message: e?.message, status: res.status, statusCode: e?.extensions?.statusCode }
|
||||
}
|
||||
/** Locks `email` with wrong passwords (Payload's default: 5). */
|
||||
const lock = async (collection: string, email: string, times = 5) => {
|
||||
for (let i = 0; i < times; i++) {await restLogin(collection, email, 'a-wrong-password')}
|
||||
}
|
||||
return { gqlLogin, lock, restLogin, state }
|
||||
}
|
||||
Reference in New Issue
Block a user