From 52710021ef2043c6d6981bc7fe68b95d6530f9f0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rados=C5=82aw=20Smoli=C5=84ski?= Date: Tue, 1 Dec 2026 11:12:40 +0100 Subject: [PATCH] Staff sign-in rules: failures per IP and address, own origin, current password for own changes (1.18.0) Q2 (IAWL idea 16): Payload locks a staff account after 5 wrong passwords from anybody, so a stranger kept the owner out without a password. Failed sign-ins are now counted per client IP and typed address (folded: NFKC, lower case, trim): 5 in 15 min, then 429 for that IP and address only; only failures count (a place taken before the compare, given back on success or refusal; "try again in a moment" while others are being checked). Payload's own lock stays as the net at 50 failures for an hour where the project set none. The mail service's account-mail limit now counts per address per visitor (5) with 20 per address in all, so one stranger no longer blocks the owner's own reset mail. Q3 (idea 7): staff login, forgot and reset password refuse a request a browser marks as coming from another origin (403 before anything is counted or sent); visitor collections untouched. Q5 (idea 29): an account that changes its own e-mail, username or password must send its current password (panel field on the account page via the plugin's MaskedField, no import-map change; REST and GraphQL). Admins changing others, server code and API keys are not asked; wrong ones count like failed sign-ins. Options accounts.signInLimit / signInSameOrigin / confirmOwnChanges, all validated at start. Tests: 15 HTTP tests (2FA on/off, all off), fail before on 1.17.1; built-site spec own-account.spec.ts in e2e:built. Co-Authored-By: Claude Opus 5.5 --- docs/access.md | 70 +++++- docs/agent/AGENT.md | 3 + docs/agent/reference-site/INDEX.md | 1 + docs/agent/skills/iapl-debug/SKILL.md | 3 + docs/agent/skills/iapl-reference/SKILL.md | 3 + .../skills/iapl-reference/resources/api.md | 5 +- docs/agent/skills/iapl-upgrade/SKILL.md | 14 ++ docs/email.md | 10 +- docs/security.md | 4 +- reference/e2e/own-account.spec.ts | 84 +++++++ scripts/e2e-built.mjs | 6 +- scripts/reference-index.mjs | 1 + src/index.ts | 14 +- src/modules/access/signInRules.ts | 236 ++++++++++++++++++ src/modules/access/types.ts | 22 ++ src/modules/admin-i18n/texts/security.ts | 12 + src/modules/email/relay/constants.ts | 2 +- src/modules/email/relay/options.ts | 6 +- src/modules/email/relay/send.ts | 15 +- src/modules/security/totp/sameOrigin.ts | 18 +- src/modules/shared/rateLimit.ts | 22 ++ src/modules/shared/switches.ts | 23 ++ src/plugin.ts | 7 + test/mailRelay.test.ts | 20 ++ test/signInRules.test.ts | 121 +++++++++ test/signInRules2faOff.test.ts | 21 ++ test/signInRulesOff.test.ts | 31 +++ test/signInRulesSuite.ts | 86 +++++++ 28 files changed, 839 insertions(+), 21 deletions(-) create mode 100644 reference/e2e/own-account.spec.ts create mode 100644 src/modules/access/signInRules.ts create mode 100644 test/signInRules.test.ts create mode 100644 test/signInRules2faOff.test.ts create mode 100644 test/signInRulesOff.test.ts create mode 100644 test/signInRulesSuite.ts diff --git a/docs/access.md b/docs/access.md index 17a9752..8fc04e9 100644 --- a/docs/access.md +++ b/docs/access.md @@ -250,6 +250,9 @@ 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: { signInLimit: { perAddress: 10, windowMinutes: 15 } }, // or signInLimit: false (Payload's lock as before) + // accounts: { signInSameOrigin: { origins: ['https://panel.example.com'] } }, // or signInSameOrigin: false + // accounts: { confirmOwnChanges: false }, // own e-mail / password without the current password (as before) // accounts: false, // none of the rules }) ``` @@ -477,10 +480,75 @@ 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 stranger cannot lock a staff account out (`accounts.signInLimit`, 1.18.0) + +Payload locks an account after `maxLoginAttempts` wrong passwords (5) for `lockTime` (10 minutes) — wrong passwords +from **anybody**: five posts with no password at all kept the owner out, again and again. Now failed sign-ins to a +staff collection are counted **per client IP and typed address**: after **5 failures in 15 minutes** from one IP for +one address, that IP gets `429` ("Too many failed sign-ins to this address from here. Try again in N min.") for that +address; the owner, from anywhere else, signs in. Payload's own per-account lock stays as the net against a spray +from many IPs, at **50 failures, locked for an hour** — set only where the project did not set +`auth.maxLoginAttempts` / `auth.lockTime` itself (a value you wrote stays; no schema change). + +- **Only failures count.** A sign-in takes its place before the password is compared (a burst cannot slip under the + limit) and gives it back when it worked, or when it was refused without a compare. Several correct sign-ins at once + from one place may hear "try again in a moment" — nothing is locked. +- **One count for every spelling** of an address: the typed address is folded like the database that folds the most + (case, full-width and compatibility forms — NFKC — and spaces), so `OWNER@…`, `owner@…` and `owner@…` share it. + The "too many" answer is the same for a real and an invented address. +- **The client IP** is `clientIp()` — pin `IAPL_IP_HEADER` in production ([forms.md](./forms.md)). Requests without + an address share one bucket at 20× the limit (`setUnknownIpFactor`). Server code (the Local API) is never limited. +- **Options:** `signInLimit: { perAddress, windowMinutes, accountLock: { maxLoginAttempts, lockTime } }`; + `accountLock: false` = Payload's lock (5, 10 min) beside the per-IP count; `signInLimit: false` = no per-IP count + and Payload's lock as before. Values that make no sense (`0`, `'false'`) stop the start. +- **Check:** five wrong passwords for an editor with `X-Forwarded-For: 198.51.100.1` (behind one proxy, with + `IAPL_IP_HEADER=x-forwarded-for`), then the right one from there → `429`; from `203.0.113.1` → `200`. +- A staff collection a plugin listed after `iapl` adds is not covered (its config is built after these rules). + +### Staff sign-in only from the site's own origin (`accounts.signInSameOrigin`, 1.18.0) + +Login, "forgot password" and "reset password" of a staff collection refuse (`403`, before anything is counted or sent) +a request a browser marks as coming from another origin (`Origin`, else `Sec-Fetch-Site`) — over REST and GraphQL. +A foreign page could otherwise sign a visitor's browser into an account of the attacker's choosing (login CSRF), or +make visitors' browsers ask for reset mails. Own origins: the request's host (`Host`, `X-Forwarded-Host`), +`serverURL`, Payload's `csrf` and `cors` lists, and `signInSameOrigin.origins`. A request with neither header (a +script, `curl`, a server) passes. Visitor collections (not staff) are not touched — a shop front end on another +domain keeps signing its customers in. The first refusal of each origin is logged with the ways to allow it. + +- **A panel or front end that signs staff in from another origin:** `signInSameOrigin: { origins: ['https://…'] }`. + **Behind a proxy that rewrites `Host`** without `serverURL`: set `serverURL` (or the site's own sign-in is refused). +- **Off:** `signInSameOrigin: false`. +- **Check:** `curl -X POST /api/users/login -H 'Origin: https://other.example' -H 'Content-Type: application/json' + -d '{"email":"a@b.c","password":"x"}'` → `403`. + +### Changing one's own e-mail or password asks for the current password (`accounts.confirmOwnChanges`, 1.18.0) + +A stolen session alone could take an account over: change the e-mail, then "forgot password". Now an account that +changes its **own** e-mail address, username or password must send its current password — in the panel a +**Current password** field on the account's own page (the plugin's `MaskedField`, already in every site's import +map: no `generate:importmap`), over REST / GraphQL `currentPassword` in the body / `data`. Without it: `400` on the +`currentPassword` field ("Enter your current password…"); wrong: `400` ("The current password is not right."). Wrong +current passwords count like failed sign-ins (`signInLimit`). The field is virtual: never stored, never read back. + +- **Not asked:** an administrator changing **another** account; other fields of one's own account; server code + (`overrideAccess`); a request with an API key; "forgot password" / "reset password" (the token is the proof). +- **Scripts that change their own password** add `"currentPassword": ""` to the body. +- **Off:** `confirmOwnChanges: false`. A project with its own `currentPassword` field keeps its field and its value (the + rule reads the value from it and does not take it out of the save). +- The check uses Payload's stored hash formats (PBKDF2-SHA256 at 600,000 / 100,000 iterations, and the older + 25,000-iteration hashes); a hash format a later Payload adds is refused until IAPL knows it (fail closed — the + user then changes the password through "forgot password"). +- **Check:** as an editor, `PATCH /api/users/` with `{ "email": "new@…" }` → `400`; with `"currentPassword"` + → `200`. In the panel: Account → the new e-mail and "Current password" → saved. +- **Building blocks** of the three rules: `applySignInRules(collection, accounts)`, `buildSignInBeforeOperation`, + `releaseSignInPlace` (`afterLogin`), `settleFailedSignIn` (config `afterError`), `buildCurrentPasswordField`, + `resolveSignInRules`, `foldSignInName`, `passwordMatches`, `CURRENT_PASSWORD_FIELD`; `releaseRateLimit` (gives a + place of `consumeRateLimit` back — for limiters that count failures only). + ## Turn off, override, extend - **Account rules:** `accounts: false`, or one by one — `panelRole`, `adminOnlyCreate`, `adminOnlyWrite`, - `staffOnlyRead`, `firstUserRoute`, `password` (above). + `staffOnlyRead`, `firstUserRoute`, `password`, `signInLimit`, `signInSameOrigin`, `confirmOwnChanges` (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), diff --git a/docs/agent/AGENT.md b/docs/agent/AGENT.md index e40944c..a8a2a9d 100644 --- a/docs/agent/AGENT.md +++ b/docs/agent/AGENT.md @@ -1232,6 +1232,9 @@ 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` | +| Failed staff sign-ins counted per client IP and typed address (folded: case, width, NFKC): 5 in 15 min, then `429` for that IP and address; only failures count; Payload's per-account lock raised to 50 failures / 1 hour where the project did not set `maxLoginAttempts` / `lockTime` (1.18.0). Pin `IAPL_IP_HEADER`. **Verify:** 5 wrong passwords with `X-Forwarded-For: 198.51.100.1`, then the right one from there → `429`, from another address → `200` | `accounts: { signInLimit: false }` | `signInLimit: { perAddress, windowMinutes, accountLock: { maxLoginAttempts, lockTime } \| false }`; `applySignInRules`, `releaseRateLimit` | +| Staff login, forgot password and reset password refuse a request a browser marks as coming from another origin (`403`, REST and GraphQL; 1.18.0); visitor collections untouched. **Verify:** `curl -X POST /api/users/login -H 'Origin: https://other.example' …` → `403` | `accounts: { signInSameOrigin: false }` | `signInSameOrigin: { origins: [...] }` | +| Changing one's OWN e-mail, username or password needs the current password: panel field "Current password" on the account page (`MaskedField`, no import-map change), `currentPassword` over REST / GraphQL; admins changing others, server code and API keys are not asked; wrong ones count like failed sign-ins (1.18.0). **Verify:** `PATCH /api/users/ {"email":"…"}` → `400`, with `"currentPassword"` → `200` | `accounts: { confirmOwnChanges: false }` | `buildCurrentPasswordField`, `passwordMatches`, `CURRENT_PASSWORD_FIELD` (access.md) | | 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 | diff --git a/docs/agent/reference-site/INDEX.md b/docs/agent/reference-site/INDEX.md index 4b5895c..a3207f4 100644 --- a/docs/agent/reference-site/INDEX.md +++ b/docs/agent/reference-site/INDEX.md @@ -1173,6 +1173,7 @@ Rules: AGENT.md §8a. | `e2e/mail-relay-fixture.ts` | test fixture, on only with E2E_MAIL_RELAY_URL: points the mail service's client at the stand-in the spec starts; never in a real site (a real site names no address) (below) | | `e2e/mail-relay-setup.ts` | for the mail-service spec: empties the SMTP fields and the stored token, so the next e-mail enrols and goes through the mail service (local database only) (below) | | `e2e/mail-relay.spec.ts` | the mail service on a built site: the state block in the panel, the first e-mail through the public confirm route, no token in anything the browser receives | +| `e2e/own-account.spec.ts` | built-site test (pnpm e2e:built, 1.18.0): the account page asks for the current password before a new e-mail is saved (accounts.confirmOwnChanges); five failed staff sign-ins from one place answer 429 there, not elsewhere (accounts.signInLimit); a staff sign-in from another origin gets 403 (accounts.signInSameOrigin) | | `e2e/routes.snapshot.json` | every public route of the site (REST, GraphQL, Next route files) with one line saying who may use it and why — the judged list `routes:check` compares with | | `e2e/routes.ts` | `routes:check`: the site's public routes against e2e/routes.snapshot.json (`pnpm payload run e2e/routes.ts [update]`; from the repository `pnpm routes:check`) (below) | | `e2e/sign-in-look.spec.ts` | browser test of the sign-in look (whiteLabel.signIn): the panel comes with the form, sits above it on a phone in both themes, is on forgot / reset / logout too, the language links work, the 2FA code screen keeps its boxes (now named) | diff --git a/docs/agent/skills/iapl-debug/SKILL.md b/docs/agent/skills/iapl-debug/SKILL.md index bcec0df..ca59cba 100644 --- a/docs/agent/skills/iapl-debug/SKILL.md +++ b/docs/agent/skills/iapl-debug/SKILL.md @@ -34,6 +34,9 @@ through this procedure. Ask only when you are missing something you cannot get y ### Build / TypeScript | Symptom | Cause | Fix | |---|---|---| +| a sign-in answers `429` "Too many failed sign-ins to this address from here" | 5 failed sign-ins for that address from that client IP in 15 minutes (`accounts.signInLimit`, 1.18.0); everybody behind one IP shares it (an office NAT); without `IAPL_IP_HEADER` everybody may share the no-IP bucket | wait the minutes it names, or sign in from elsewhere; pin `IAPL_IP_HEADER`; more room: `signInLimit: { perAddress: 10 }` | +| staff login / "forgot password" answers `403` and the log says `[iapl] a staff sign-in from origin "…" was refused` | the request came from another origin (`accounts.signInSameOrigin`, 1.18.0): a front end on another domain, or a proxy that rewrites `Host` without `serverURL` | set `serverURL`, or `signInSameOrigin: { origins: ['https://…'] }` | +| saving one's own account answers "Enter your current password to change your e-mail address or password." | `accounts.confirmOwnChanges` (1.18.0): own e-mail / username / password changes need the current password | type it in "Current password" on the account page; scripts send `currentPassword`; off: `confirmOwnChanges: false` | | 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'] })` | diff --git a/docs/agent/skills/iapl-reference/SKILL.md b/docs/agent/skills/iapl-reference/SKILL.md index 878dad2..88fc780 100644 --- a/docs/agent/skills/iapl-reference/SKILL.md +++ b/docs/agent/skills/iapl-reference/SKILL.md @@ -38,6 +38,9 @@ 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//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.signInLimit` | `{ perAddress: 5, windowMinutes: 15, accountLock: { maxLoginAttempts: 50, lockTime: 3_600_000 } }` (1.18.0) | failed staff sign-ins per client IP + typed address (folded): over the limit `429` for that IP and address only; only failures count; Payload's per-account lock raised where the project set none | `{ perAddress, windowMinutes, accountLock }`; `accountLock: false` = Payload's lock; `false` = as before 1.18 | +| `accounts.signInSameOrigin` | on (1.18.0) | staff login / forgot / reset password: `403` for a request a browser marks as coming from another origin | `{ origins: [...] }`; `false` | +| `accounts.confirmOwnChanges` | on (1.18.0) | own e-mail / username / password change needs `currentPassword` (panel field, REST, GraphQL) | `false` | | `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 | diff --git a/docs/agent/skills/iapl-reference/resources/api.md b/docs/agent/skills/iapl-reference/resources/api.md index d6c9082..d720d0d 100644 --- a/docs/agent/skills/iapl-reference/resources/api.md +++ b/docs/agent/skills/iapl-reference/resources/api.md @@ -85,7 +85,10 @@ 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`). +| `applySignInRules(collection, accounts?)`, `buildSignInBeforeOperation(slug, rules)`, `releaseSignInPlace`, `settleFailedSignIn`, `buildCurrentPasswordField()`, `resolveSignInRules(accounts?)`, `foldSignInName(value)`, `passwordMatches({ hash, salt }, password)`, `CURRENT_PASSWORD_FIELD`; types `SignInRulesOptions`, `SignInLimitOptions`, `SignInSameOriginOptions` | `@intecion/ipal-kit` | 1.18.0, `accounts.signInLimit` / `signInSameOrigin` / `confirmOwnChanges`: the three rules on one staff collection (hooks, field, Payload lock defaults); the `beforeOperation` hook; the `afterLogin` hook that gives a sign-in's place back; the config `afterError` hook that ends a failed one; the virtual "Current password" field; the options with defaults; the address folding (NFKC, lower case, trim); Payload's stored-hash check (unknown formats refused). | +| `releaseRateLimit({ key, scope, max?, windowMs?, cost? })` | `@intecion/ipal-kit` | Gives back a place `consumeRateLimit` took (memory: never below 0; a store: `hit(id, -cost)`) — for a limiter that counts failures only. | + +**Types:** `AccountsOptions` (`accounts`: `panelRole`, `adminOnlyCreate`, `adminOnlyWrite`, `staffOnlyRead`, `firstUserRoute`, `password`, `signInLimit`, `signInSameOrigin`, `confirmOwnChanges`), `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` diff --git a/docs/agent/skills/iapl-upgrade/SKILL.md b/docs/agent/skills/iapl-upgrade/SKILL.md index 4ab83b2..b3fd674 100644 --- a/docs/agent/skills/iapl-upgrade/SKILL.md +++ b/docs/agent/skills/iapl-upgrade/SKILL.md @@ -25,6 +25,20 @@ the MANDATORY SET (GEO: llms-full, Markdown, MCP; R2; Turnstile through `getTurnstileConfig`…). Wire each one according to PROGRAMISTA §2 — it is part of the update, not an extra. Skip one only with a client decision in `AGENTS.md` (`iapl-audit-skip:`). +**→ 1.18.0, sign-in (CHANGELOG 1.18.0; access.md "A stranger cannot lock a staff account out", "Staff sign-in only +from the site's own origin", "Changing one's own e-mail or password asks for the current password") — no schema change, +no migration, no import-map change; read before deploying:** +1. `IAPL_IP_HEADER` must be pinned in production (`x-forwarded-for` behind Coolify/Traefik): failed staff sign-ins are + counted per client IP and address. Without it every visitor shares one bucket (20× the limit). +2. A staff collection with its own `auth.maxLoginAttempts` / `lockTime` keeps them; otherwise Payload's lock is now 50 + failures for an hour (beside 5 per IP and address in 15 minutes). Payload's behaviour back: `accounts: { signInLimit: false }`. +3. A panel or front end that signs **staff** in from another domain: `accounts: { signInSameOrigin: { origins: ['https://…'] } }` + (or `false`). A proxy that rewrites `Host`: set `serverURL`. Customer / visitor logins are not affected. +4. Scripts or integrations that change their OWN e-mail or password over the API send `currentPassword`; editors + see "Current password" on their account page. Off: `accounts: { confirmOwnChanges: false }`. +**Check:** five wrong passwords for an editor from one address → `429` there, `200` from another; the account page +shows "Current password"; `curl -X POST /api/users/login -H 'Origin: https://other.example' …` → `403`. + **→ 1.17.1:** (1) `src/proxy.ts`: replace the matcher literal with `['/((?!(?:api|admin|_next)(?:/|$)|.*\\..*).*)']` (i18n.md "Next matcher"; `iapl-doctor` rule `proxy-matcher`). The old one skipped every page whose first segment only starts with `api`, `admin` or `_next` (`/administracja`): diff --git a/docs/email.md b/docs/email.md index 6fad267..885d2cf 100644 --- a/docs/email.md +++ b/docs/email.md @@ -191,9 +191,11 @@ is read — and is renewed after a send, once an hour; until the site has enroll plugin has no number of its own). **Account mail is limited by the site itself.** "Forgot password" is a visitor's lever like a form, and the -service lets account mail use the whole hour. So the relay transport holds back more than **5 account e-mails to -one address** and more than **10 asked for by one visitor** within an hour (`mail.relay.accountMail`: -`{ perAddress, perVisitor, windowMinutes }`, or `false`). A held-back message is reported as `relay-quota` in the +service lets account mail use the whole hour. So the relay transport holds back, within an hour, more than **5 account +e-mails to one address asked for by one visitor**, more than **20 to one address from everybody** and more than **10 +asked for by one visitor** (`mail.relay.accountMail`: `{ perAddress, perAddressTotal, perVisitor, windowMinutes }`, or +`false`). Since 1.18.0 `perAddress` counts per visitor (the requesting IP): before, five requests from anybody used +the address's hour up, and its owner's own reset mail was held back too. A held-back message is reported as `relay-quota` in the log and the panel; the visitor is told nothing. Pin the address header for it: `IAPL_IP_HEADER` ([security.md](./security.md)). @@ -466,7 +468,7 @@ message); "Connect again" asks at once. Other causes: `host-not-allowed` (not a | `token` | — | a token from elsewhere (`string` or a function): the stored token is not used and the site does not enrol | | `senderName` | panel, then site name | a fixed name, or a function | | `kind` | — | the kind of a message nobody marked | -| `accountMail` | `{ perAddress: 5, perVisitor: 10, windowMinutes: 60 }` | the site's own limit on account mail; `false` = none | +| `accountMail` | `{ perAddress: 5, perAddressTotal: 20, perVisitor: 10, windowMinutes: 60 }` | the site's own limit on account mail: per address and visitor, per address from everybody (1.18.0), per visitor; `false` = none | | `confirmRateLimit` | `{ max: 10, windowMs: 60000 }` | calls to the public confirm route per address | | `totalTimeoutMs` | `10000`; `30000` with files | everything one message may take — enrolment, attempts and waits together. Somebody waits for the request that sends the mail; after it the message is reported ("not confirmed" when an attempt was cut off). A number, or `{ plain, files }` | | `timeoutMs` | `30000` | one attempt of a send; never more than what is left of `totalTimeoutMs` | diff --git a/docs/security.md b/docs/security.md index 188c088..da00aad 100644 --- a/docs/security.md +++ b/docs/security.md @@ -412,7 +412,9 @@ Changing the path makes automated scans harder, but it is NOT a safeguard. Real panel protection: - **2FA** for every user (enforced by the plugin — section below) - Strong passwords -- Rate limiting on login +- Rate limiting on login — failed staff sign-ins per IP and address (`accounts.signInLimit`, 1.18.0), staff sign-in + only from the site's own origin (`accounts.signInSameOrigin`), the current password for one's own e-mail / password + change (`accounts.confirmOwnChanges`) — [access.md](./access.md) - IP allowlist (if the panel is for the team only) - buildSecurityHeaders (headers) diff --git a/reference/e2e/own-account.spec.ts b/reference/e2e/own-account.spec.ts new file mode 100644 index 0000000..82648b2 --- /dev/null +++ b/reference/e2e/own-account.spec.ts @@ -0,0 +1,84 @@ +import { expect, test } from '@playwright/test' +import { randomUUID } from 'node:crypto' + +import { totp } from './totp' + +/** + * On the BUILT site (pnpm e2e:built, webpack and Turbopack), what 1.18.0 changed for one's own account and the + * sign-in of staff: + * - the account page has a "Current password" field; saving a new e-mail without it is refused on that field, + * with it the e-mail changes (accounts.confirmOwnChanges); + * - five failed sign-ins from one place for an address answer 429 there, the owner elsewhere still signs in + * (accounts.signInLimit); a staff sign-in from another origin gets 403 (accounts.signInSameOrigin). + * The accounts are fresh ones made here (the test admins are never touched). Needs the E2E_* test admin. + */ +const { E2E_ADMIN_EMAIL: adminEmail, E2E_ADMIN_PASSWORD: adminPassword, E2E_TOTP_SECRET: secret } = process.env +const SECRET = 'JPURUZNWYTZX2L42MT4SS7736WWNQWBM' + +test('own account: a new e-mail needs the current password, in the panel', async ({ baseURL, browser, playwright }) => { + test.skip(!adminEmail || !adminPassword || !secret, 'E2E_* test admin not configured') + test.setTimeout(120_000) + const email = `own-${randomUUID().slice(0, 8)}@example.com` + const password = `O-${randomUUID()}` + // made by the test admin; its TOTP set up over the API with a secret of our own + const admin = await playwright.request.newContext({ baseURL, extraHTTPHeaders: { origin: baseURL! } }) + expect((await admin.post('/api/users/login', { data: { email: adminEmail, password: adminPassword } })).status()).toBe(200) + expect((await (await admin.post('/api/verify-totp', { data: { token: totp(secret!) } })).json()).ok).toBe(true) + expect((await admin.post('/api/users', { data: { email, password, roles: ['editor'] } })).status()).toBe(201) + await admin.dispose() + const own = await playwright.request.newContext({ baseURL, extraHTTPHeaders: { origin: baseURL! } }) + expect((await own.post('/api/users/login', { data: { email, password } })).status()).toBe(200) + expect((await (await own.post('/api/setup-totp', { data: { secret: SECRET, token: totp(SECRET) } })).json()).ok).toBe(true) + await own.dispose() + + const context = await browser.newContext({ baseURL }) + const page = await context.newPage() + await page.goto('/admin/login') + await page.fill('#field-email', email) + await page.fill('#field-password', password) + await page.click('.form-submit button') + await page.waitForURL(/verify-totp/, { waitUntil: 'commit' }) + await page.getByRole('textbox').first().click() + await page.keyboard.type(totp(SECRET)) + await expect(page).toHaveTitle(/Dashboard|Pulpit/, { timeout: 20_000 }) + + await page.goto('/admin/account') + const current = page.locator('#field-currentPassword') + await expect(current).toBeVisible({ timeout: 20_000 }) + await expect(current).toHaveAttribute('type', 'password') + const renamed = `renamed-${randomUUID().slice(0, 8)}@example.com` + await page.fill('#field-email', renamed) + await page.click('#action-save') + await expect(page.getByText(/Enter your current password|Wpisz obecne hasło/).first()).toBeVisible({ timeout: 20_000 }) + await current.fill(password) + await page.click('#action-save') + await expect.poll(async () => { + const check = await playwright.request.newContext({ baseURL }) + const status = (await check.post('/api/users/login', { data: { email: renamed, password } })).status() + await check.dispose() + return status + }, { timeout: 20_000 }).toBe(200) + await context.close() +}) + +test('staff sign-in: five failures from one place answer 429 there, not elsewhere; another origin gets 403', async ({ baseURL, playwright }) => { + test.skip(!adminEmail || !adminPassword || !secret, 'E2E_* test admin not configured') + const email = `limit-${randomUUID().slice(0, 8)}@example.com` + const password = `S-${randomUUID()}` + const admin = await playwright.request.newContext({ baseURL, extraHTTPHeaders: { origin: baseURL! } }) + expect((await admin.post('/api/users/login', { data: { email: adminEmail, password: adminPassword } })).status()).toBe(200) + expect((await (await admin.post('/api/verify-totp', { data: { token: totp(secret!) } })).json()).ok).toBe(true) + expect((await admin.post('/api/users', { data: { email, password, roles: ['editor'] } })).status()).toBe(201) + await admin.dispose() + // the site reads the client address from IAPL_IP_HEADER (reference/.env: x-forwarded-for, one proxy) + const from = async (ip: string) => playwright.request.newContext({ baseURL, extraHTTPHeaders: { 'x-forwarded-for': ip } }) + const stranger = await from('198.51.100.123') + for (let i = 0; i < 5; i++) {expect((await stranger.post('/api/users/login', { data: { email, password: 'a-wrong-password' } })).status()).toBe(401)} + expect((await stranger.post('/api/users/login', { data: { email, password } })).status()).toBe(429) + const owner = await from('203.0.113.123') + expect((await owner.post('/api/users/login', { data: { email, password } })).status()).toBe(200) + const foreign = await owner.post('/api/users/login', { data: { email, password }, headers: { origin: 'https://blog.example.test', 'sec-fetch-site': 'same-site' } }) + expect(foreign.status()).toBe(403) + await stranger.dispose() + await owner.dispose() +}) diff --git a/scripts/e2e-built.mjs b/scripts/e2e-built.mjs index c614f0b..486bf73 100644 --- a/scripts/e2e-built.mjs +++ b/scripts/e2e-built.mjs @@ -14,7 +14,9 @@ * route under Next, the state block in the panel's production bundle) and the smoke tests "no package.json is published", * "client hints" (Payload's colour-scheme headers on the admin only; a public page is requested once), every * "consent" test (banner at first paint, Global Privacy Control, equal prominence, withdrawal, the consent log) - * and e2e/sign-in-look.spec.ts (the sign-in panel in the first HTML, on a phone, the language links, the 2FA screen). + * and e2e/sign-in-look.spec.ts (the sign-in panel in the first HTML, on a phone, the language links, the 2FA screen), + * e2e/own-account.spec.ts (1.18.0: the account page asks for the current password; staff sign-in failures per place; + * staff sign-in from another origin refused). * * Needs what the reference site's "Production check" needs (reference/README.md): reference/.env with a local, * seeded database and the E2E_* test admin. The test admins are reset by Playwright's global setup. @@ -89,7 +91,7 @@ for (const bundler of bundlers) { process.exit(1) } console.log(`[e2e:built] ✓ ${bundler}: no package manifest among ${files.length} public files`) - run(`${bundler}: the built site — late-staff spec, the mail service, closed doors, the published-files check, the client hints, consent and the sign-in look`, 'pnpm', ['exec', 'playwright', 'test', 'late-staff', 'mail-relay', 'closed-doors', 'smoke', 'sign-in-look', '--grep', 'late staff collection|the mail service|closed doors|no package.json is published|client hints|consent|sign-in look'], site, { ALLOW_LOCAL_MEDIA: process.env.ALLOW_LOCAL_MEDIA ?? '1', E2E_LATE_STAFF: '1' }) + run(`${bundler}: the built site — late-staff spec, the mail service, closed doors, the published-files check, the client hints, consent and the sign-in look`, 'pnpm', ['exec', 'playwright', 'test', 'late-staff', 'mail-relay', 'closed-doors', 'smoke', 'sign-in-look', 'own-account', '--grep', 'late staff collection|the mail service|closed doors|no package.json is published|client hints|consent|sign-in look|own account|staff sign-in'], site, { ALLOW_LOCAL_MEDIA: process.env.ALLOW_LOCAL_MEDIA ?? '1', E2E_LATE_STAFF: '1' }) passed.push(bundler) } console.log(`\n[e2e:built] passed: ${passed.join(' and ')}. (The reference site's .next now holds the ${passed.at(-1)} build WITH the fixture: rebuild with \`pnpm build\` there before other checks.)`) diff --git a/scripts/reference-index.mjs b/scripts/reference-index.mjs index 67cb639..1c73077 100644 --- a/scripts/reference-index.mjs +++ b/scripts/reference-index.mjs @@ -71,6 +71,7 @@ export const DESCRIPTIONS = { 'e2e/mail-relay-setup.ts': 'for the mail-service spec: empties the SMTP fields and the stored token, so the next e-mail enrols and goes through the mail service (local database only)', 'e2e/mail-relay.spec.ts': 'the mail service on a built site: the state block in the panel, the first e-mail through the public confirm route, no token in anything the browser receives', 'e2e/smtp-sink.ts': 'a local mail sink for the smoke tests: reads what the site really sent (recipients, attachments)', + 'e2e/own-account.spec.ts': 'built-site test (pnpm e2e:built, 1.18.0): the account page asks for the current password before a new e-mail is saved (accounts.confirmOwnChanges); five failed staff sign-ins from one place answer 429 there, not elsewhere (accounts.signInLimit); a staff sign-in from another origin gets 403 (accounts.signInSameOrigin)', 'e2e/sign-in-look.spec.ts': 'browser test of the sign-in look (whiteLabel.signIn): the panel comes with the form, sits above it on a phone in both themes, is on forgot / reset / logout too, the language links work, the 2FA code screen keeps its boxes (now named)', 'e2e/two-factor-back.spec.ts': 'browser test of the 2FA screens\' `back` link (twoFactor.safeBack): a prepared link — script or another host — ends on the admin root, an ordinary one is followed', 'e2e/routes.snapshot.json': 'every public route of the site (REST, GraphQL, Next route files) with one line saying who may use it and why — the judged list `routes:check` compares with', diff --git a/src/index.ts b/src/index.ts index e014373..2377f47 100644 --- a/src/index.ts +++ b/src/index.ts @@ -50,6 +50,18 @@ export { } from './modules/access/selfRegistration.js' export type { AccountsMarker, LateAdoption, StaffAccountAccessOptions, StaffAccountRules } from './modules/access/selfRegistration.js' export type { FirstUserRouteOption } from './modules/access/selfRegistration.js' +export { + applySignInRules, + buildCurrentPasswordField, + buildSignInBeforeOperation, + CURRENT_PASSWORD_FIELD, + foldSignInName, + passwordMatches, + releaseSignInPlace, + resolveSignInRules, + settleFailedSignIn, +} from './modules/access/signInRules.js' +export type { SignInLimitOptions, SignInRulesOptions, SignInSameOriginOptions } from './modules/access/signInRules.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). @@ -568,7 +580,7 @@ export { applyCollectionOverride } from './modules/shared/collectionOverride.js' export type { CollectionOverride } from './modules/shared/collectionOverride.js' // Development addresses by pattern (no env): the built-in list and the matcher behind `developmentHosts`. export { assertDevelopmentHosts, DEFAULT_DEVELOPMENT_HOSTS, isDevelopmentHost, matchDevelopmentHost } from './modules/shared/developmentHosts.js' -export { clientIp, setRateLimitStore, setUnknownIpFactor, UNKNOWN_IP_FACTOR } from './modules/shared/rateLimit.js' +export { clientIp, releaseRateLimit, setRateLimitStore, setUnknownIpFactor, UNKNOWN_IP_FACTOR } from './modules/shared/rateLimit.js' export type { ClientIpOptions, RateLimitStore } from './modules/shared/rateLimit.js' export { buildSlugField, toSlug } from './modules/slug/index.js' export { STATS_SLUG } from './modules/stats/index.js' diff --git a/src/modules/access/signInRules.ts b/src/modules/access/signInRules.ts new file mode 100644 index 0000000..2283e0b --- /dev/null +++ b/src/modules/access/signInRules.ts @@ -0,0 +1,236 @@ +import type { CollectionAfterLoginHook, CollectionBeforeOperationHook, CollectionConfig, Field, PayloadRequest } from 'payload' + +import { pbkdf2, timingSafeEqual } from 'node:crypto' +import { APIError, Forbidden, ValidationError } from 'payload' + +import { serverText } from '../integrations/texts.js' +import { reportRefusedOrigin, requestFromOwnOrigin } from '../security/totp/sameOrigin.js' +import { clientIp, consumeRateLimit, releaseRateLimit } from '../shared/rateLimit.js' +import { userMeetsRole } from './predicates.js' + +/** + * Sign-in rules of the staff collections (1.18.0; IAWL ideas 16, 7 and 29 — the owner's Q2, Q3 and Q5). + * + * 1. **A stranger cannot lock a staff account out** (`accounts.signInLimit`). Payload locks an account after + * `maxLoginAttempts` wrong passwords (5) for `lockTime` (10 min) — wrong passwords from ANYBODY, no password + * needed: five posts kept the owner out, again and again. Now failures are counted per client IP and typed + * address (`perAddress`, default 5 in `windowMinutes`, 15): the sixth try of one IP for one address gets `429`, + * everybody else is untouched. Payload's own per-account lock stays as the net against a spray from many IPs, + * at a much higher count (`accountLock`: 50 failures, locked for an hour) — set only where the project did not + * set `maxLoginAttempts` / `lockTime` itself. The typed address is folded like a database that folds the most + * (case, width, compatibility forms: NFKC + lower case), so spellings of one address share one count. Only + * failures stay counted: a place is taken before the password is compared (a burst cannot slip under) and given + * back when the sign-in worked or was refused without a compare; a refusal caused only by sign-ins still being + * checked says "try again in a moment". The answer for "too many" is the same for a real and an invented address. + * 2. **Staff sign-in only from the site's own origin** (`accounts.signInSameOrigin`). Login, "forgot password" and + * "reset password" of a staff collection refuse (`403`, before anything is counted or sent) a request a browser + * marks as coming from another origin — a foreign page could otherwise sign a visitor's browser into an account + * of the attacker's choosing, or have visitors' browsers request reset mails. The rule of the 2FA endpoints + * (sameOrigin.ts); a request with neither `Origin` nor `Sec-Fetch-Site` (a script, `curl`) passes. + * 3. **Changing one's own e-mail or password asks for the current password** (`accounts.confirmOwnChanges`), in the + * panel and over REST / GraphQL: a stolen session alone can no longer take the account over (new e-mail, then + * "forgot password"). The panel gets a "Current password" field on the account's own page (the plugin's + * `MaskedField`, already in every site's import map). An administrator changing ANOTHER account is not asked; + * server code (`overrideAccess`) and API keys are not asked. Wrong current passwords count like failed sign-ins. + * + * Server code (the Local API) is never limited or checked here. + */ +export type SignInLimitOptions = { + /** Payload's per-account lock for staff collections that do not set their own. Default `{ maxLoginAttempts: 50, lockTime: 3_600_000 }`; `false` = Payload's defaults (5, 10 min). */ + accountLock?: { lockTime?: number; maxLoginAttempts?: number } | false + /** Failed sign-ins per client IP and typed address in the window. Default 5. */ + perAddress?: number + /** The window, in minutes. Default 15. */ + windowMinutes?: number +} +export type SignInSameOriginOptions = { origins?: string[] } + +export type SignInRulesOptions = { + confirmOwnChanges?: false + signInLimit?: false | SignInLimitOptions + signInSameOrigin?: false | SignInSameOriginOptions +} + +/** The name of the panel's "Current password" field (and the body key over REST / GraphQL). */ +export const CURRENT_PASSWORD_FIELD = 'currentPassword' +const SCOPE = 'iapl-signin' + +/** A typed address folded like the database that folds the most: case, width and compatibility forms, spaces. */ +export const foldSignInName = (value: unknown): string => (typeof value === 'string' ? value.normalize('NFKC').toLowerCase().trim() : '') + +const isLocal = (req: PayloadRequest | undefined) => !req || (req as { payloadAPI?: string }).payloadAPI === 'local' || !req.headers + +/** Places taken by sign-ins of one IP + address still being checked (this instance). */ +const inFlight = new Map() +const flightKey = (scope: string, ip: string) => `${scope}|${ip}` +const flight = (key: string, by: number) => { + const next = Math.max(0, (inFlight.get(key) ?? 0) + by) + if (next) {inFlight.set(key, next)} else {inFlight.delete(key)} +} +/** For tests. */ +export const clearSignInFlights = (): void => inFlight.clear() + +type Place = { ip: string; max: number; scope: string; windowMs: number } +const PLACE = Symbol.for('iapl.signInPlace') +type WithPlace = { [PLACE]?: Place } + +/** Takes a place for one sign-in (or current-password check). Throws 429 when the IP + address has used its failures. */ +async function takePlace(req: PayloadRequest, name: string, limit: Required>): Promise { + const ip = clientIp(req.headers) + const scope = `${SCOPE}:${name}` + const windowMs = limit.windowMinutes * 60_000 + const place: Place = { ip, max: limit.perAddress, scope, windowMs } + const busy = inFlight.get(flightKey(scope, ip)) ?? 0 + const { ok, retryAfter } = await consumeRateLimit({ key: ip, max: limit.perAddress, scope, windowMs }) + if (!ok) { + // refused without a compare: the place goes back at once + await releaseRateLimit({ key: ip, max: limit.perAddress, scope, windowMs }) + const i18n = req.i18n as never + if (busy > 0) {throw new APIError(serverText(i18n, 'signInBusy'), 429, null, true)} + throw new APIError(serverText(i18n, 'signInTooMany', { minutes: Math.max(1, Math.ceil(retryAfter / 60)) }), 429, null, true) + } + flight(flightKey(scope, ip), 1) + return place +} + +async function givePlaceBack(place: Place | undefined, kept: boolean): Promise { + if (!place) {return} + flight(flightKey(place.scope, place.ip), -1) + if (!kept) {await releaseRateLimit({ key: place.ip, max: place.max, scope: place.scope, windowMs: place.windowMs })} +} + +/** Payload's own check of a stored password hash (auth/strategies/local), for the current-password rule. */ +const HASH_PREFIXES: Record = { 'pbkdf2-sha256-100k-v1:': 100_000, 'pbkdf2-sha256-v1:': 600_000 } +export async function passwordMatches(stored: { hash?: unknown; salt?: unknown }, password: string): Promise { + const { hash, salt } = stored + if (typeof hash !== 'string' || typeof salt !== 'string' || !password) {return false} + const prefix = Object.keys(HASH_PREFIXES).find((p) => hash.startsWith(p)) + // a hash with a prefix of a later Payload this code does not know: refused (fail closed), never accepted + if (!prefix && /^[a-z0-9-]+:/i.test(hash)) {return false} + const [hex, iterations, keyLength] = prefix ? [hash.slice(prefix.length), HASH_PREFIXES[prefix], 32] : [hash, 25_000, 512] + const derived = await new Promise((resolve, reject) => pbkdf2(password, salt, iterations, keyLength, 'sha256', (err, key) => (err ? reject(err) : resolve(key)))) + const expected = Buffer.from(hex, 'hex') + return expected.length === derived.length && timingSafeEqual(expected, derived) +} + +type Resolved = { confirm: boolean; limit: false | Required>; origins: false | string[]; /** the field is the plugin's (virtual): its value is taken out of the save */ stripField?: boolean } + +const signInOriginOk = (req: PayloadRequest, origins: string[]): boolean => { + if (requestFromOwnOrigin(req as never, origins)) {return true} + reportRefusedOrigin(req as never, origins, { + docs: 'docs/access.md "Staff sign-in only from the site\'s own origin"', + option: 'iapl({ accounts: { signInSameOrigin', + what: 'a staff sign-in', + }) + return false +} + +/** `beforeOperation` for a staff collection: the origin rule, the failure count and the current-password rule. */ +export function buildSignInBeforeOperation(slug: string, rules: Resolved): CollectionBeforeOperationHook { + return async ({ args, operation, req }) => { + if (isLocal(req)) {return args} + const data = ((args as { data?: Record }).data ?? {}) + if (operation === 'login' || operation === 'forgotPassword' || operation === 'resetPassword') { + if (rules.origins && !signInOriginOk(req, rules.origins)) {throw new Forbidden(req.t)} + if (operation === 'login' && rules.limit) { + const name = foldSignInName(data.email ?? data.username) + ;(req as WithPlace)[PLACE] = await takePlace(req, name, rules.limit) + } + return args + } + if (operation === 'update' && rules.confirm) {await confirmOwnChange(slug, args as never, req, rules)} + return args + } +} + +/** `afterLogin`: the sign-in worked, its place goes back. */ +export const releaseSignInPlace: CollectionAfterLoginHook = async ({ req }) => { + const place = (req as WithPlace)[PLACE] + delete (req as WithPlace)[PLACE] + await givePlaceBack(place, false) +} + +/** An `afterError` (config level): a sign-in that failed keeps its place but is no longer "being checked". */ +export const settleFailedSignIn = ({ req }: { req?: PayloadRequest }): void => { + const place = req ? (req as WithPlace)[PLACE] : undefined + if (!place || !req) {return} + delete (req as WithPlace)[PLACE] + flight(flightKey(place.scope, place.ip), -1) +} + +async function confirmOwnChange(slug: string, args: { data?: Record; id?: number | string; overrideAccess?: boolean }, req: PayloadRequest, rules: Resolved): Promise { + const data = args.data + if (!data || args.overrideAccess === true) {return} + const typed = data[CURRENT_PASSWORD_FIELD] + if (rules.stripField !== false) {delete data[CURRENT_PASSWORD_FIELD]} + const user = req.user as ({ _strategy?: string; collection?: string; email?: string; id: number | string; username?: string } & Record) | null + if (!user || user.collection !== slug || user._strategy === 'api-key') {return} + const own = args.id !== undefined ? String(args.id) === String(user.id) : !userMeetsRole(req, 'admin') + if (!own) {return} + const changesEmail = typeof data.email === 'string' && foldSignInName(data.email) !== foldSignInName(user.email) + const changesName = typeof data.username === 'string' && foldSignInName(data.username) !== foldSignInName(user.username) + const changesPassword = typeof data.password === 'string' && data.password !== '' + if (!changesEmail && !changesName && !changesPassword) {return} + const i18n = req.i18n as never + const fail = (key: 'currentPasswordRequired' | 'currentPasswordWrong') => + new ValidationError({ collection: slug, errors: [{ message: serverText(i18n, key), path: CURRENT_PASSWORD_FIELD }] }, req.t) + if (typeof typed !== 'string' || typed === '') {throw fail('currentPasswordRequired')} + const place = rules.limit ? await takePlace(req, foldSignInName(user.email ?? user.username ?? String(user.id)), rules.limit) : undefined + let right = false + try { + const stored = await (req.payload).db.findOne({ collection: slug, req, where: { id: { equals: user.id } } }) + right = await passwordMatches((stored ?? {}) as { hash?: unknown; salt?: unknown }, typed) + } finally { + await givePlaceBack(place, !right) + } + if (!right) {throw fail('currentPasswordWrong')} +} + +/** The panel's "Current password" field: virtual, never stored, never read back, shown only on one's own account. */ +export function buildCurrentPasswordField(): Field { + return { + name: CURRENT_PASSWORD_FIELD, + type: 'text', + admin: { + components: { Field: '@intecion/ipal-kit/admin#MaskedField' }, + condition: (data, _sibling, ctx) => { + 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'), + }, + hooks: { afterRead: [() => undefined] }, + label: ({ t }) => serverText({ language: (t as unknown as { i18n?: { language?: string } })?.i18n?.language } as never, 'currentPasswordLabel'), + virtual: true, + } as Field +} + +/** Resolves the three options (with their defaults). */ +export function resolveSignInRules(options: SignInRulesOptions = {}): Resolved { + const limit = options.signInLimit === false ? false : { perAddress: options.signInLimit?.perAddress ?? 5, windowMinutes: options.signInLimit?.windowMinutes ?? 15 } + const origins = options.signInSameOrigin === false ? false : (options.signInSameOrigin?.origins ?? []) + return { confirm: options.confirmOwnChanges !== false, limit, origins } +} + +/** Puts the rules on one staff collection of a (not yet sanitized) config. A project's own `maxLoginAttempts` / `lockTime` stay. */ +export function applySignInRules(collection: CollectionConfig, options: SignInRulesOptions = {}): CollectionConfig { + if (!collection.auth) {return collection} + const rules = resolveSignInRules(options) + const auth = typeof collection.auth === 'object' ? collection.auth : {} + const lock = options.signInLimit === false || options.signInLimit?.accountLock === false ? null : { lockTime: options.signInLimit?.accountLock?.lockTime ?? 3_600_000, maxLoginAttempts: options.signInLimit?.accountLock?.maxLoginAttempts ?? 50 } + const ownField = (collection.fields ?? []).some((f) => (f as { name?: string }).name === CURRENT_PASSWORD_FIELD) + return { + ...collection, + auth: { + ...auth, + ...(lock && auth.maxLoginAttempts === undefined ? { maxLoginAttempts: lock.maxLoginAttempts } : {}), + ...(lock && auth.lockTime === undefined ? { lockTime: lock.lockTime } : {}), + }, + fields: rules.confirm && !ownField ? [...(collection.fields ?? []), buildCurrentPasswordField()] : collection.fields, + hooks: { + ...collection.hooks, + afterLogin: [...(collection.hooks?.afterLogin ?? []), releaseSignInPlace], + beforeOperation: [buildSignInBeforeOperation(collection.slug, { ...rules, stripField: !ownField }), ...(collection.hooks?.beforeOperation ?? [])], + }, + } +} diff --git a/src/modules/access/types.ts b/src/modules/access/types.ts index 156e191..35ad7ef 100644 --- a/src/modules/access/types.ts +++ b/src/modules/access/types.ts @@ -1,6 +1,7 @@ import type { CollectionConfig } from 'payload' import type { PasswordRuleOptions } from './passwordRule.js' +import type { SignInLimitOptions, SignInSameOriginOptions } from './signInRules.js' /** * Role hierarchy, lowest to highest privilege. @@ -40,6 +41,13 @@ export type AccountsOptions = { * `false` = Payload's default on collections without a rule, as before. */ adminOnlyWrite?: false + /** + * Changing one's OWN e-mail address, username or password asks for the current password — in the panel (a + * "Current password" field on the account's own page) and over REST / GraphQL (`currentPassword` in the body). + * An administrator changing another account, server code and API keys are not asked (1.18.0). + * `false` = no question, as before. + */ + confirmOwnChanges?: false /** * Which auth collections Payload's first-user route * (`POST /api//first-register`) answers for while they are empty. @@ -67,6 +75,20 @@ export type AccountsOptions = { * logging in. `false` = Payload's own rule (3 characters). */ password?: false | PasswordRuleOptions + /** + * Failed sign-ins to a staff collection are counted per client IP and typed address: the sixth failure of one + * IP for one address in 15 minutes gets `429`; nobody else is affected — a stranger can no longer lock the owner + * out. Payload's per-account lock stays as the net against many IPs, at 50 failures for an hour (where the + * project did not set `auth.maxLoginAttempts` / `lockTime` itself). Only failures count (1.18.0). + * `false` = Payload's lock as it was (5 failures from anywhere, 10 minutes) and no per-IP count. + */ + signInLimit?: false | SignInLimitOptions + /** + * Login, "forgot password" and "reset password" of a staff collection refuse (`403`) a request a browser marks as + * coming from another origin (1.18.0). `origins` adds origins (a panel front end on another domain). + * `false` = no check, as before. + */ + signInSameOrigin?: false | SignInSameOriginOptions /** * `read` on a staff collection without a `read` rule: a fully signed-in * account of a staff collection. Payload's default let any logged-in diff --git a/src/modules/admin-i18n/texts/security.ts b/src/modules/admin-i18n/texts/security.ts index 922929d..c84f7f5 100644 --- a/src/modules/admin-i18n/texts/security.ts +++ b/src/modules/admin-i18n/texts/security.ts @@ -3,8 +3,14 @@ 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.', passwordTooShort: 'The password must have at least {{min}} characters.', + signInBusy: 'Another sign-in to this account from here is being checked right now. Try again in a moment.', + signInTooMany: 'Too many failed sign-ins to this address from here. Try again in {{minutes}} min.', 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.', @@ -29,8 +35,14 @@ 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.', passwordTooShort: 'Hasło musi mieć co najmniej {{min}} znaków.', + signInBusy: 'Właśnie sprawdzamy inne logowanie na to konto z tego miejsca. Spróbuj ponownie za chwilę.', + signInTooMany: 'Zbyt wiele nieudanych logowań na ten adres z tego miejsca. Spróbuj ponownie za {{minutes}} min.', 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/modules/email/relay/constants.ts b/src/modules/email/relay/constants.ts index f5d56f8..3326fce 100644 --- a/src/modules/email/relay/constants.ts +++ b/src/modules/email/relay/constants.ts @@ -25,7 +25,7 @@ export const RELAY_KV_KEY = 'iapl:mail-relay' export const RELAY_DEFAULTS = { /** A visitor's lever: "forgot password" mail per address and per visitor in the window (accountMail option). */ - accountMail: { perAddress: 5, perVisitor: 10, windowMinutes: 60 }, + accountMail: { perAddress: 5, perAddressTotal: 20, perVisitor: 10, windowMinutes: 60 }, /** Requests for one message, the same key and bytes each time. */ attempts: 3, /** One attempt, from sending the request to the end of the answer. */ diff --git a/src/modules/email/relay/options.ts b/src/modules/email/relay/options.ts index 4db6762..ea38d86 100644 --- a/src/modules/email/relay/options.ts +++ b/src/modules/email/relay/options.ts @@ -20,9 +20,11 @@ export type RelayOptions = { /** * "Forgot password" is a visitor's lever like a form: the service lets `account` mail use the site's * whole hour. So the plugin limits it itself, per address and per visitor (the request's address). - * Default 5 per address and 10 per visitor an hour; `false` = no limit of the plugin's. + * Default an hour: 5 to one address from one visitor (`perAddress`), 20 to one address from everybody + * (`perAddressTotal`, 1.18.0 — before, 5 from anybody filled it for the owner too), 10 from one visitor; + * `false` = no limit of the plugin's. */ - accountMail?: { perAddress?: number; perVisitor?: number; windowMinutes?: number } | false + accountMail?: { perAddress?: number; perAddressTotal?: number; perVisitor?: number; windowMinutes?: number } | false /** Calls to the public confirm route per address. Default 10 a minute. */ confirmRateLimit?: { max?: number; windowMs?: number } /** diff --git a/src/modules/email/relay/send.ts b/src/modules/email/relay/send.ts index fb8dfbb..d02ac05 100644 --- a/src/modules/email/relay/send.ts +++ b/src/modules/email/relay/send.ts @@ -137,12 +137,21 @@ export async function sendThroughRelay(payload: BasePayload, options: ResolvedRe const perAddress = own.perAddress ?? RELAY_DEFAULTS.accountMail.perAddress const checks = [ ...(marked?.visitor ? [{ key: `visitor:${marked.visitor}`, max: own.perVisitor ?? RELAY_DEFAULTS.accountMail.perVisitor }] : []), - ...[...(request.to ?? []), ...(request.cc ?? []), ...(request.bcc ?? [])].map((address) => ({ key: `to:${sha256Hex(address.toLowerCase())}`, max: perAddress })), + // 1.18.0: one visitor (IP) gets `perAddress` mails to an address; the address gets `perAddressTotal` from everybody — + // a stranger who fills an address's count from one IP no longer stops its owner's own reset mail (IAWL idea 16). + ...[...(request.to ?? []), ...(request.cc ?? []), ...(request.bcc ?? [])].flatMap((address) => { + const to = `to:${sha256Hex(address.toLowerCase())}` + return [ + // no visitor known (server code, no IP header): all such requests are one visitor + { key: marked?.visitor || 'no-visitor', max: perAddress, scope: `mail-relay-account:${to}` }, + { key: to, max: own.perAddressTotal ?? RELAY_DEFAULTS.accountMail.perAddressTotal }, + ] + }), ] for (const check of checks) { - const { ok } = await consumeRateLimit({ ...check, scope: 'mail-relay-account', windowMs }) + const { ok } = await consumeRateLimit({ scope: 'mail-relay-account', ...check, windowMs }) if (!ok) { - payload.logger.warn(`[iapl] mail service: an account e-mail was held back (more than ${check.max} ${check.key.startsWith('visitor:') ? 'from one visitor' : 'to one address'} in the window; mail.relay.accountMail).`) + payload.logger.warn(`[iapl] mail service: an account e-mail was held back (more than ${check.max} ${check.key.startsWith('visitor:') ? 'from one visitor' : 'scope' in check ? 'to one address from one visitor' : 'to one address'} in the window; mail.relay.accountMail).`) return failure('relay-quota', 'client-account-mail-limit', 'Too many account e-mails to one address or from one visitor; held back by the site (mail.relay.accountMail).') } } diff --git a/src/modules/security/totp/sameOrigin.ts b/src/modules/security/totp/sameOrigin.ts index e427a3b..da54e65 100644 --- a/src/modules/security/totp/sameOrigin.ts +++ b/src/modules/security/totp/sameOrigin.ts @@ -89,21 +89,29 @@ const MAX_REPORTED = 50 * that origin. Without it a site behind a proxy that hides its address has a panel nobody can * enter and a silent log. Returns true when a line was written. */ -export function reportRefusedOrigin(req: RequestLike, extra: string[] = []): boolean { +/** What a refusal line names: the request, the option that allows an origin, and the doc section. Default: 2FA. */ +export type RefusalContext = { docs: string; option: string; what: string } +const TWO_FACTOR_REFUSAL: RefusalContext = { + docs: 'docs/security.md "Verify and setup attempts only from the site\'s own origin"', + option: 'twoFactor: { sameOrigin', + what: '2FA: a code', +} + +export function reportRefusedOrigin(req: RequestLike, extra: string[] = [], context: RefusalContext = TWO_FACTOR_REFUSAL): boolean { const origin = req.headers?.get('origin') - const key = origin ? (originOf(origin) ?? 'null') : `sec-fetch-site: ${req.headers?.get('sec-fetch-site') ?? 'none'}` + const key = `${context.option}|${origin ? (originOf(origin) ?? 'null') : `sec-fetch-site: ${req.headers?.get('sec-fetch-site') ?? 'none'}`}` if (reported.has(key) || reported.size >= MAX_REPORTED) {return false} reported.add(key) const { hosts, origins } = ownOrigins(req, extra) const known = [...origins, ...[...hosts].map((h) => `host ${h}`)].join(', ') || 'none' const how = originOf(origin) ? `If "${originOf(origin)}" is this site's own address (a reverse proxy that rewrites Host and sends no X-Forwarded-Host), set serverURL to it in the Payload config, ` + - `or pass twoFactor: { sameOrigin: { origins: ['${originOf(origin)}'] } }, or make the proxy send X-Forwarded-Host. ` + `or pass ${context.option}: { origins: ['${originOf(origin)}'] } }, or make the proxy send X-Forwarded-Host. ` : 'The browser did not name an origin this site knows. ' req.payload?.logger?.warn( - `[iapl] 2FA: a code from ${origin ? `origin "${origin}"` : `a ${key} request`} was refused and not counted — it is not one of this site's own origins (${known}). ` + + `[iapl] ${context.what} from ${origin ? `origin "${origin}"` : `a ${key.split('|')[1]} request`} was refused${context === TWO_FACTOR_REFUSAL ? ' and not counted' : ''} — it is not one of this site's own origins (${known}). ` + how + - 'If it is a foreign page, this is the protection working. twoFactor: { sameOrigin: false } turns the check off (docs/security.md "Verify and setup attempts only from the site\'s own origin"). Said once per origin.', + `If it is a foreign page, this is the protection working. ${context.option}: false } turns the check off (${context.docs}). Said once per origin.`, ) return true } diff --git a/src/modules/shared/rateLimit.ts b/src/modules/shared/rateLimit.ts index 46b0839..4fa4f26 100644 --- a/src/modules/shared/rateLimit.ts +++ b/src/modules/shared/rateLimit.ts @@ -166,6 +166,28 @@ export async function consumeRateLimit({ return { ok: bucket.count <= max, retryAfter } } +/** + * Gives back one place that `consumeRateLimit` took (`cost` 1) — for a limiter that counts only failures: it takes + * a place before it compares (a burst cannot slip under the limit) and gives it back when the attempt was right. + * Never below zero in memory; with a shared store, `hit(id, -cost)` (a store that cannot take a negative cost + * simply keeps the place: fewer attempts, never more). + */ +export async function releaseRateLimit({ cost = 1, key: rawKey, max: rawMax = 5, scope = 'form', windowMs = 60_000 }: CheckArgs): Promise { + const resolved = resolveKey(rawKey, rawMax) + if (!resolved) {return} + const id = `${scope}:${resolved.key}` + if (store) { + try { + await store.hit(id, -cost, windowMs) + } catch { + // the place stays taken until the window ends + } + return + } + const bucket = buckets.get(id) + if (bucket && bucket.resetAt > Date.now()) {bucket.count = Math.max(0, bucket.count - cost)} +} + /** Seconds until the key's IN-MEMORY window resets — for a Retry-After header. */ export function retryAfterSeconds(key: string, scope = 'form'): number { const bucket = buckets.get(`${scope}:${key}`) diff --git a/src/modules/shared/switches.ts b/src/modules/shared/switches.ts index 3d59555..823a9ae 100644 --- a/src/modules/shared/switches.ts +++ b/src/modules/shared/switches.ts @@ -50,6 +50,28 @@ export function assertPluginSwitches(options: Record): 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.18.0: the sign-in rules. `signInLimit: 0` / `'false'` must not read as off; a limit of 0 never refuses. + const accounts = bag(options.accounts) + if (accounts) { + assertBooleanSwitch('accounts.confirmOwnChanges', accounts.confirmOwnChanges) + assertSwitchOrObject('accounts.signInLimit', accounts.signInLimit, { allowTrue: false }) + const limit = bag(accounts.signInLimit) + if (limit) { + assertNumberSwitch('accounts.signInLimit.perAddress', limit.perAddress, { min: 1 }) + assertNumberSwitch('accounts.signInLimit.windowMinutes', limit.windowMinutes, { exclusive: true, min: 0 }) + assertSwitchOrObject('accounts.signInLimit.accountLock', limit.accountLock, { allowTrue: false }) + const lock = bag(limit.accountLock) + if (lock) { + assertNumberSwitch('accounts.signInLimit.accountLock.maxLoginAttempts', lock.maxLoginAttempts, { min: 1 }) + assertNumberSwitch('accounts.signInLimit.accountLock.lockTime', lock.lockTime, { exclusive: true, min: 0 }) + } + } + assertSwitchOrObject('accounts.signInSameOrigin', accounts.signInSameOrigin, { allowTrue: false }) + const same = bag(accounts.signInSameOrigin) + if (same && same.origins !== undefined && !(Array.isArray(same.origins) && same.origins.every((o) => typeof o === 'string'))) { + throw new Error(`${where('accounts.signInSameOrigin.origins')} must be a list of origins such as ['https://panel.example.com'] (received ${JSON.stringify(same.origins)}).`) + } + } // 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) { @@ -106,6 +128,7 @@ export function assertPluginSwitches(options: Record): void { if (!limits) {throw new Error(`${where('mail.relay.accountMail')} must be false or an object (received ${JSON.stringify(accountMail)}).`)} assertNumberSwitch('mail.relay.accountMail.windowMinutes', limits.windowMinutes, { exclusive: true, min: 0 }) assertNumberSwitch('mail.relay.accountMail.perAddress', limits.perAddress, { min: 1 }) + assertNumberSwitch('mail.relay.accountMail.perAddressTotal', limits.perAddressTotal, { min: 1 }) assertNumberSwitch('mail.relay.accountMail.perVisitor', limits.perVisitor, { min: 1 }) } const confirm = bag(relay.confirmRateLimit) diff --git a/src/plugin.ts b/src/plugin.ts index 6445f7c..7a2ba93 100644 --- a/src/plugin.ts +++ b/src/plugin.ts @@ -16,6 +16,7 @@ import { adminOnly, adminOrSelfIn, injectRoles, registerStaffCollections, staffC 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' +import { applySignInRules, settleFailedSignIn } from './modules/access/signInRules.js' import { ROLE_HIERARCHY } from './modules/access/types.js' import { applyAdminI18n } from './modules/admin-i18n/apply.js' import { buildAdminImageEndpoints } from './modules/branding/adminImages.js' @@ -258,6 +259,12 @@ 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] : [] }) + // Sign-in rules of the staff collections: failures per IP + address, own origin, current password (1.18.0). + config = { + ...config, + collections: (config.collections ?? []).map((c) => (staffSlugs.includes(c.slug) ? applySignInRules(c, accounts) : c)), + hooks: { ...config.hooks, afterError: [...(config.hooks?.afterError ?? []), settleFailedSignIn as never] }, + } } if (options.twoFactor !== false) { const tf = options.twoFactor diff --git a/test/mailRelay.test.ts b/test/mailRelay.test.ts index 3968fc5..0d50056 100644 --- a/test/mailRelay.test.ts +++ b/test/mailRelay.test.ts @@ -1397,3 +1397,23 @@ describe('the adapter on its own, and the deprecated Graph line', () => { expect(quiet.logger.warn.mock.calls.map((c) => String(c[0])).filter((m) => m.includes('deprecated'))).toEqual([]) }) }) + +describe('account mail per address is counted per visitor too (1.18.0)', () => { + test('a stranger who uses up an address from one IP does not stop the owner\'s own reset mail; all visitors together stop at perAddressTotal', async () => { + const { fake, options, payload } = relaySite({ fake: { allow: [HOST], limits: { messagesPerHour: 100 } } }) + const send = (visitor: string, subject: string) => { + expectMailTo('owner@example.org', 'account', { visitor }) + // as Payload's "forgot password" goes: marked as account mail for this address, with the requesting visitor + return sendThroughRelay(payload, options, { html: 'reset', subject, to: 'owner@example.org' }) + } + for (let i = 0; i < 5; i++) {expect((await send('203.0.113.9', `Reset ${i}`)).sent).toBe(true)} + expect(await send('203.0.113.9', 'Reset 5')).toMatchObject({ cause: 'client-account-mail-limit', sent: false }) + // the owner, from another address + expect(await send('198.51.100.20', 'Reset owner')).toMatchObject({ sent: true }) + // many visitors together: perAddressTotal (20) for the address + let sent = 6 + for (let i = 1; sent < 20; i++) {if ((await send(`192.0.2.${i}`, `Reset v${i}`)).sent) {sent++}} + expect(await send('192.0.2.200', 'Reset over')).toMatchObject({ cause: 'client-account-mail-limit', sent: false }) + expect(fake.outbox.filter((m) => m.kind === 'account')).toHaveLength(20) + }) +}) diff --git a/test/signInRules.test.ts b/test/signInRules.test.ts new file mode 100644 index 0000000..8aafd3c --- /dev/null +++ b/test/signInRules.test.ts @@ -0,0 +1,121 @@ +/** Sign-in rules of the staff collections, 2FA on (signInRulesSuite.ts). */ +import { describe, expect, test, vi } from 'vitest' + +import { foldSignInName, passwordMatches } from '../src/modules/access/signInRules.js' +import { FOREIGN, PASSWORD, signInSite } from './signInRulesSuite.js' + +vi.mock('server-only', () => ({})) +vi.mock('next/headers.js', async () => (await import('./http/server.js')).nextHeadersMock) + +const { call, gqlLogin, idOf, login, session, state, stored } = signInSite() + +describe('accounts.signInLimit: a stranger cannot lock a staff account out', () => { + test('five wrong passwords from one IP: that IP gets 429 for the address; the owner, elsewhere, signs in', async () => { + for (let i = 0; i < 5; i++) {expect((await login('owner@example.com', 'a-wrong-password', '198.51.100.66')).status).toBe(401)} + const refused = await login('owner@example.com', PASSWORD, '198.51.100.66') + expect(refused.status).toBe(429) + expect(refused.body).toMatch(/Too many failed sign-ins/) + expect((await login('owner@example.com', PASSWORD, '203.0.113.7')).status).toBe(200) + expect((await stored('owner@example.com'))?.lockUntil ?? null).toBeNull() + }) + + test('the answer for "too many" is the same for a real and an invented address', async () => { + for (let i = 0; i < 5; i++) {await login('nobody@example.com', 'a-wrong-password', '198.51.100.67')} + for (let i = 0; i < 5; i++) {await login('editor2@example.com', 'a-wrong-password', '198.51.100.68')} + const invented = await login('nobody@example.com', 'a-wrong-password', '198.51.100.67') + const real = await login('editor2@example.com', 'a-wrong-password', '198.51.100.68') + expect(invented.status).toBe(429) + expect(real).toEqual(invented) + }) + + test('correct sign-ins never count; spellings of one address share one count (case, width)', async () => { + for (let i = 0; i < 8; i++) {expect((await login('office@example.com', PASSWORD, '198.51.100.69')).status).toBe(200)} + for (const spelling of ['FOLD@example.com', 'fold@example.com', ' fold@EXAMPLE.com', 'fold@example.com', 'Fold@Example.com']) { + await login(spelling, 'a-wrong-password', '198.51.100.70') + } + expect((await login('fold@example.com', PASSWORD, '198.51.100.70')).status).toBe(429) + expect(foldSignInName('fold@Example.COM ')).toBe('fold@example.com') + }) + + test('GraphQL counts and answers the same way', async () => { + for (let i = 0; i < 5; i++) {await gqlLogin('editor@example.com', 'a-wrong-password', '198.51.100.71')} + const refused = await gqlLogin('editor@example.com', PASSWORD, '198.51.100.71') + expect(refused.status).toBe(429) + expect(refused.message).toMatch(/Too many failed sign-ins/) + }) + + test("Payload's per-account lock stays as the net, at 50 failures for an hour", () => { + const auth = state.payload.collections['users' as never].config.auth as { lockTime: number; maxLoginAttempts: number } + expect([auth.maxLoginAttempts, auth.lockTime]).toEqual([50, 3_600_000]) + const customers = state.payload.collections['customers' as never].config.auth as { maxLoginAttempts: number } + expect(customers.maxLoginAttempts).toBe(5) // not staff: Payload's default + }) +}) + +describe('accounts.signInSameOrigin: staff sign-in only from the site\'s own origin', () => { + test('login, forgot password and reset password from a foreign page: 403, nothing counted or sent', async () => { + const before = state.mails.length + expect((await login('admin2@example.com', PASSWORD, '198.51.100.80', FOREIGN)).status).toBe(403) + expect((await call('/users/forgot-password', { email: 'admin2@example.com' }, { 'sec-fetch-site': 'cross-site' })).status).toBe(403) + expect((await call('/users/reset-password', { password: 'a-new-password-123', token: 'x'.repeat(40) }, FOREIGN)).status).toBe(403) + expect((await gqlLogin('admin2@example.com', PASSWORD, '198.51.100.80', FOREIGN)).status).toBe(403) + expect(state.mails.length).toBe(before) + // the site's own page and a script without browser headers go through + expect((await login('admin2@example.com', PASSWORD, '198.51.100.80', { origin: state.server.url, 'sec-fetch-site': 'same-origin' })).status).toBe(200) + expect((await login('admin2@example.com', PASSWORD, '198.51.100.80')).status).toBe(200) + expect((await call('/users/forgot-password', { email: 'admin2@example.com' })).status).toBe(200) + }) + + test('a visitor collection is not staff: its login from another origin is untouched', async () => { + expect((await call('/customers/login', { email: 'client@example.com', password: PASSWORD }, FOREIGN)).status).toBe(200) + }) +}) + +describe('accounts.confirmOwnChanges: one\'s own e-mail or password needs the current password', () => { + test('REST: without it 400, wrong 400, right 200; never read back', async () => { + const cookie = await session('editor@example.com', PASSWORD, '203.0.113.30') + const id = await idOf('editor@example.com') + const patch = (data: object) => call(`/users/${id}`, data, { cookie, 'x-real-ip': '203.0.113.30' }, 'PATCH') + const none = await patch({ email: 'editor-new@example.com' }) + expect([none.status, none.body]).toEqual([400, expect.stringMatching(/Enter your current password/)]) + const wrong = await patch({ currentPassword: 'not-my-password', email: 'editor-new@example.com' }) + expect([wrong.status, wrong.body]).toEqual([400, expect.stringMatching(/current password is not right/)]) + const right = await patch({ currentPassword: PASSWORD, email: 'editor-new@example.com' }) + expect(right.status).toBe(200) + expect(right.body).not.toMatch(/a-long-test-password/) + expect(await idOf('editor-new@example.com')).toBe(id) + // other fields of one's own account need nothing + expect((await call(`/users/${id}`, { roles: ['editor'] }, { cookie }, 'PATCH')).status).not.toBe(400) + }) + + test('GraphQL: the same rule; the password too', async () => { + const cookie = await session('editor-new@example.com', PASSWORD, '203.0.113.31') + const id = await idOf('editor-new@example.com') + const gql = async (data: string) => JSON.parse((await call('/graphql', { query: `mutation { updateUser(id: ${JSON.stringify(id)}, data: { ${data} }) { email } }` }, { cookie })).body) as { data?: { updateUser?: unknown }; errors?: { message: string }[] } + expect((await gql('password: "a-new-password-456"')).errors?.[0]?.message).toBeTruthy() + expect((await gql(`password: "a-new-password-456", currentPassword: "${PASSWORD}"`)).data?.updateUser).toBeTruthy() + expect((await login('editor-new@example.com', 'a-new-password-456', '203.0.113.31')).status).toBe(200) + }) + + test('an admin changing ANOTHER account is not asked', async () => { + const cookie = await session('owner@example.com', PASSWORD, '203.0.113.32') + const id = await idOf('editor2@example.com') + expect((await call(`/users/${id}`, { email: 'editor2-renamed@example.com' }, { cookie }, 'PATCH')).status).toBe(200) + }) + + test('wrong current passwords count like failed sign-ins (429 after five)', async () => { + const cookie = await session('office@example.com', PASSWORD, '203.0.113.33') + const id = await idOf('office@example.com') + for (let i = 0; i < 5; i++) { + expect((await call(`/users/${id}`, { currentPassword: `wrong-${i}`, password: 'another-password-1' }, { cookie, 'x-real-ip': '203.0.113.33' }, 'PATCH')).status).toBe(400) + } + expect((await call(`/users/${id}`, { currentPassword: PASSWORD, password: 'another-password-1' }, { cookie, 'x-real-ip': '203.0.113.33' }, 'PATCH')).status).toBe(429) + }) + + test("passwordMatches: Payload's hash formats; an unknown prefix is refused", async () => { + const doc = (await state.payload.db.findOne({ collection: 'users', where: { email: { equals: 'owner@example.com' } } })) as unknown as { hash: string; salt: string } + expect(await passwordMatches(doc, PASSWORD)).toBe(true) + expect(await passwordMatches(doc, 'nope')).toBe(false) + expect(await passwordMatches({ hash: `pbkdf2-sha512-v9:${doc.hash.split(':')[1]}`, salt: doc.salt }, PASSWORD)).toBe(false) + }) +}) diff --git a/test/signInRules2faOff.test.ts b/test/signInRules2faOff.test.ts new file mode 100644 index 0000000..2963aef --- /dev/null +++ b/test/signInRules2faOff.test.ts @@ -0,0 +1,21 @@ +/** Sign-in rules of the staff collections with twoFactor: false (signInRulesSuite.ts). */ +import { describe, expect, test, vi } from 'vitest' + +import { FOREIGN, PASSWORD, signInSite } from './signInRulesSuite.js' + +vi.mock('server-only', () => ({})) + +const { call, gqlLogin, idOf, login, session } = signInSite({ twoFactor: false }) + +describe('sign-in rules without 2FA', () => { + test('a stranger\'s five failures do not keep the owner out; foreign origin refused; own e-mail needs the current password', async () => { + for (let i = 0; i < 5; i++) {await login('owner@example.com', 'a-wrong-password', '198.51.100.90')} + expect((await login('owner@example.com', PASSWORD, '198.51.100.90')).status).toBe(429) + expect((await login('owner@example.com', PASSWORD, '203.0.113.90')).status).toBe(200) + expect((await gqlLogin('owner@example.com', PASSWORD, '203.0.113.91', FOREIGN)).status).toBe(403) + const cookie = await session('editor@example.com', PASSWORD, '203.0.113.92') + const id = await idOf('editor@example.com') + expect((await call(`/users/${id}`, { email: 'x@example.com' }, { cookie }, 'PATCH')).status).toBe(400) + expect((await call(`/users/${id}`, { currentPassword: PASSWORD, email: 'x@example.com' }, { cookie }, 'PATCH')).status).toBe(200) + }) +}) diff --git a/test/signInRulesOff.test.ts b/test/signInRulesOff.test.ts new file mode 100644 index 0000000..52d08a2 --- /dev/null +++ b/test/signInRulesOff.test.ts @@ -0,0 +1,31 @@ +/** accounts: { signInLimit: false, signInSameOrigin: false, confirmOwnChanges: false } — Payload's behaviour as before 1.18.0. */ +import { describe, expect, test, vi } from 'vitest' + +import { iapl } from '../src/plugin.js' +import { FOREIGN, PASSWORD, signInSite } from './signInRulesSuite.js' + +vi.mock('server-only', () => ({})) +vi.mock('next/headers.js', async () => (await import('./http/server.js')).nextHeadersMock) + +const { call, idOf, login, session, state } = signInSite({ off: true }) + +describe('the sign-in rules switched off', () => { + test("Payload's lock (5 from anywhere), foreign sign-in taken, own e-mail without a question", async () => { + expect((await login('admin2@example.com', PASSWORD, '203.0.113.1', FOREIGN)).status).toBe(200) + for (let i = 0; i < 5; i++) {await login('owner@example.com', 'a-wrong-password', '198.51.100.95')} + const locked = await login('owner@example.com', PASSWORD, '203.0.113.95') + expect(locked.status).toBe(401) + expect((state.payload.collections['users' as never].config.auth as { maxLoginAttempts: number }).maxLoginAttempts).toBe(5) + const cookie = await session('editor@example.com', PASSWORD, '203.0.113.96') + expect((await call(`/users/${await idOf('editor@example.com')}`, { email: 'y@example.com' }, { cookie }, 'PATCH')).status).toBe(200) + }) + + test('values nobody understands stop the start', async () => { + const i18n = { defaultLocale: 'en', locales: [{ code: 'en', label: 'English' }] } + const start = (accounts: unknown) => (async () => iapl({ accounts, i18n } as never)({ collections: [], secret: 'x' } as never))() + await expect(start({ signInLimit: 0 })).rejects.toThrow(/accounts\.signInLimit must be/) + await expect(start({ signInLimit: { perAddress: 0 } })).rejects.toThrow(/perAddress must be/) + await expect(start({ signInSameOrigin: 'false' })).rejects.toThrow(/signInSameOrigin must be/) + await expect(start({ confirmOwnChanges: 'no' })).rejects.toThrow(/confirmOwnChanges must be/) + }) +}) diff --git a/test/signInRulesSuite.ts b/test/signInRulesSuite.ts new file mode 100644 index 0000000..f2dc087 --- /dev/null +++ b/test/signInRulesSuite.ts @@ -0,0 +1,86 @@ +/** + * Sign-in rules of the staff collections (1.18.0, accounts.signInLimit / signInSameOrigin / confirmOwnChanges), through + * real HTTP requests against a running Payload. Shared by signInRules.test.ts (2FA on), signInRules2faOff.test.ts and + * signInRulesOff.test.ts (every rule switched off): 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 { cookiesOf, startPayloadServer, type TestServer } from './http/server.js' +import { totp } from './http/totp.js' + +export const SECRET = 'JBSWY3DPEHPK3PXP' +export const PASSWORD = 'a-long-test-password-1' +export const FOREIGN = { origin: 'https://blog.site.example', 'sec-fetch-site': 'same-site' } + +export type Answer = { body: string; status: number } + +export function signInSite({ off = false, twoFactor = true }: { off?: boolean; twoFactor?: boolean } = {}) { + const state = {} as { mails: string[]; payload: Payload; server: TestServer } + beforeAll(async () => { + state.mails = [] + const config = buildTestConfig({ + admin: { user: 'users' }, + collections: [ + { slug: 'customers', access: { create: () => true }, auth: true, fields: [] }, + { slug: 'media', fields: [], upload: { staticDir: '/tmp/iapl-sign-in-rules-media' } }, + ], + db: testDatabase('signinrules'), + editor: lexicalEditor(), + email: () => ({ name: 'count', defaultFromAddress: 'site@example.com', defaultFromName: 'Site', sendEmail: async (m: { to?: unknown }) => void state.mails.push(String(m.to)) }) as never, + plugins: [ + iapl({ + access: { authCollection: 'users' }, + ...(off ? { accounts: { confirmOwnChanges: false, signInLimit: false, signInSameOrigin: false } } : {}), + i18n: { defaultLocale: 'en', locales: [{ code: 'en', label: 'English' }] }, + mail: { relay: false }, + twoFactor: twoFactor ? { issuer: 'Example', plugin: payloadTotp } : false, + }), + ], + secret: 'integration-test-secret-0123456789', + telemetry: false, + }) + state.payload = await getPayload({ config }) + state.server = await startPayloadServer(config) + const make = (email: string, roles: string[]) => + state.payload.create({ collection: 'users' as never, data: { email, password: PASSWORD, roles, ...(twoFactor ? { totpSecret: SECRET } : {}) } as never }) + for (const [email, role] of [['owner@example.com', 'admin'], ['admin2@example.com', 'admin'], ['editor@example.com', 'editor'], ['editor2@example.com', 'editor'], ['office@example.com', 'editor'], ['fold@example.com', 'editor']] as const) { + await make(email, [role]) + } + await state.payload.create({ collection: 'customers' as never, data: { email: 'client@example.com', password: PASSWORD } as never }) + }, 120_000) + afterAll(async () => { + await state.server?.close() + await state.payload?.destroy?.() + }) + + const call = async (path: string, body: unknown, headers: Record = {}, method = 'POST'): Promise => { + const res = await fetch(`${state.server.url}/api${path}`, { body: JSON.stringify(body), headers: { 'content-type': 'application/json', ...headers }, method }) + return { body: await res.text(), status: res.status } + } + const login = (email: string, password: string, ip: string, extra: Record = {}) => call('/users/login', { email, password }, { 'x-real-ip': ip, ...extra }) + const gqlLogin = async (email: string, password: string, ip: string, extra: Record = {}) => { + const res = await call('/graphql', { query: `mutation { loginUser(email: ${JSON.stringify(email)}, password: ${JSON.stringify(password)}) { token } }` }, { 'x-real-ip': ip, ...extra }) + const error = (JSON.parse(res.body) as { errors?: { extensions?: { statusCode?: number }; message: string }[] }).errors?.[0] + return { message: error?.message, status: error?.extensions?.statusCode } + } + /** A fully signed-in session (password, then the code when 2FA is on): the cookie header. */ + const session = async (email: string, password = PASSWORD, ip = '203.0.113.200') => { + const res = await fetch(`${state.server.url}/api/users/login`, { body: JSON.stringify({ email, password }), headers: { 'content-type': 'application/json', 'x-real-ip': ip }, method: 'POST' }) + const first = cookiesOf(res) + if (!twoFactor) {return first.join('; ')} + const verify = await fetch(`${state.server.url}/api/verify-totp`, { body: JSON.stringify({ token: totp(SECRET) }), headers: { 'content-type': 'application/json', cookie: first.join('; ') }, method: 'POST' }) + return [...first, ...cookiesOf(verify)].join('; ') + } + const idOf = async (email: string) => ((await state.payload.find({ collection: 'users' as never, overrideAccess: true, where: { email: { equals: email } } })).docs[0] as { id: number | string }).id + const stored = async (email: string) => (await state.payload.find({ collection: 'users' as never, overrideAccess: true, showHiddenFields: true, where: { email: { equals: email } } })).docs[0] as { lockUntil?: null | string } | undefined + return { call, gqlLogin, idOf, login, session, state, stored } +}