diff --git a/docs/agent/AGENT.md b/docs/agent/AGENT.md index 22450ce..e1a0eb2 100644 --- a/docs/agent/AGENT.md +++ b/docs/agent/AGENT.md @@ -1218,9 +1218,9 @@ add missing hosts with flags / `extra`; (3) change `mode` to `'enforce'` in both | Injected `users`: admin manages everyone, others only themselves | — | `access.authAccess` (your keys win); your own `users` collection wins whole | | First registered account = admin | `access.firstUserAdmin: false` | `buildRolesField(defaultRole, { firstUserAdmin })` | | 2FA on the panel's login collection, mismatch = startup error; redirect to the 2FA screens by `TotpRedirectProvider` | `twoFactor: false` (discouraged) | `twoFactor.collectionSlug`, `allowCollectionMismatch: true`, `twoFactor.provider` (own component, or `false` for the package's) | -| 2FA setup required: an account without TOTP reaches only the setup screen; 72 h window from creation / admin reset, then blocked; status and "Reopen setup" on the account page, notice on the dashboard, `POST /api/ipal/two-factor/reset` | `twoFactor.requireSetup: false`; parts: `requireSetup: { dashboardNotice: false, statusField: false, setupNotice: false }` | `requireSetup: { windowHours, exempt }` (`exempt` returns exactly `true`, never `async`), `twoFactor.resetAccess` (default: an admin who entered its own code; the reset ends the account's sessions), texts `twoFactor*`; `twoFactorSetupState(req)`, `buildSetupFields`, `backfillSetupFrom`, `buildTwoFactorResetEndpoint`. **Postgres/SQLite: migration for `totp_setup_from` applied when the new container starts (`prodMigrations` or `pnpm payload migrate && pnpm start`; never a pre-deployment command — deployment.md §4.3), or every login answers 500** | +| 2FA setup required: an account without TOTP reaches only the setup screen; 72 h window from creation / admin reset, then blocked; status and "Reopen setup" on the account page, notice on the dashboard, `POST /api/ipal/two-factor/reset` | `twoFactor.requireSetup: false`; parts: `requireSetup: { dashboardNotice: false, statusField: false, setupNotice: false }` | `requireSetup: { windowHours, exempt }` (`exempt` returns exactly `true`, never `async`; decide it from a field only admins write, e.g. a `serviceAccount` checkbox with `adminOnlyField` — never from the e-mail, which every account may change itself; security.md "Decide `exempt` from a field only an administrator can write"), `twoFactor.resetAccess` (default: an admin who entered its own code; the reset ends the account's sessions), texts `twoFactor*`; `twoFactorSetupState(req)`, `buildSetupFields`, `backfillSetupFrom`, `buildTwoFactorResetEndpoint`. **Postgres/SQLite: migration for `totp_setup_from` applied when the new container starts (`prodMigrations` or `pnpm payload migrate && pnpm start`; never a pre-deployment command — deployment.md §4.3), or every login answers 500** | | The second factor on every collection and global, whichever plugin added it, and on the plugin's endpoints; an unrecognised 2FA package = startup error | per entity: `custom.ipal.secondFactor: false` or `{ read: false }` (or the package's `custom.totp.disableAccessWrapper`); everywhere: `twoFactor.guard: false` (not recommended) | `requireSecondFactor` / `secondFactorPassed` in your own access functions and endpoints | -| At most 5 verify attempts per account in 10 minutes (`POST /api/verify-totp` → `429`); the count is kept in memory and in the database (`payload.kv`), so a restart or a second instance does not reset it | `twoFactor.verifyLimit: false` | `verifyLimit: { max, windowMinutes, store: 'memory' }` | +| At most 5 **wrong** verify codes per account in 10 minutes (`POST /api/verify-totp` → `429`); a right code gives its place back (1.17.1), so correct logins are never refused; an attempt held out only by others still being checked gets `429` + `Retry-After: 2` ("try again in a moment"); the count is kept in memory and in the database (`payload.kv`), so a restart or a second instance does not reset it. **Verify:** log in correctly 7 times in a row → all in; 5 wrong codes → the next gets `429` with a long `Retry-After` | `twoFactor.verifyLimit: false` | `verifyLimit: { max, windowMinutes, store: 'memory' }`; own wiring: `buildVerifyLimit(...)` + `limit.settle(req, correct)` | | 2FA verify and setup attempts only from the site's own origin: a request a browser marks as coming from elsewhere (`Origin`, `Sec-Fetch-Site`) gets `403` and is not counted. **Set `serverURL`**: behind a proxy that rewrites `Host` and sends no `X-Forwarded-Host` the site's own page is refused without it (logged once per origin: `[iapl] 2FA: a code from origin … was refused`) | `twoFactor.sameOrigin: false` | `sameOrigin: { origins: ['https://app.example.com'] }`; `requestFromOwnOrigin`, `reportRefusedOrigin` | | Stored secrets are write-only: `smtpPassword` and `turnstileSecretKey` come back as `'********'` over REST, GraphQL and in the panel; an empty save keeps the value, `'[[clear]]'` removes it; server code reads the real value with the Local API. **The panel is the source — never add an env variable for them** (`TURNSTILE_SECRET_KEY` is deprecated) | `secrets: { writeOnly: false }` | `writeOnlySecret(field)` / `writeOnlySecrets(fields, names)` for your own secret fields; with versions on the entity add `hooks.afterRead: [maskSecretsOnRestore]` | | 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` | diff --git a/docs/agent/skills/iapl-debug/SKILL.md b/docs/agent/skills/iapl-debug/SKILL.md index 064c5f3..0ae5243 100644 --- a/docs/agent/skills/iapl-debug/SKILL.md +++ b/docs/agent/skills/iapl-debug/SKILL.md @@ -34,7 +34,7 @@ through this procedure. Ask only when you are missing something you cannot get y ### Build / TypeScript | Symptom | Cause | Fix | |---|---|---| -| the 2FA code screen answers "Too many codes were tried…" (`429` from `/api/verify-totp`) | more than 5 verify attempts for that account in 10 minutes (`twoFactor.verifyLimit`); 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 | +| 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'] })` | | `next build --webpack`: `'server-only' cannot be imported from a Client Component module … caused by importing '@intecion/ipal-kit/dist/index.js'` | a `'use client'` file imports the main entry (Turbopack lets it pass) | import from `@intecion/ipal-kit/client` (role predicates are there since 1.16.7; types: `import type` from the main entry is fine); data the browser needs → a prop from a server component | diff --git a/docs/agent/skills/iapl-reference/SKILL.md b/docs/agent/skills/iapl-reference/SKILL.md index 6351c4b..fc29a78 100644 --- a/docs/agent/skills/iapl-reference/SKILL.md +++ b/docs/agent/skills/iapl-reference/SKILL.md @@ -51,7 +51,7 @@ description: Complete map of everything @intecion/ipal-kit provides — every ia | `twoFactor.importMapCheck` | on | production only: at start searches the `importMap.js` on disk (where Payload looks for it) for `@intecion/ipal-kit/admin#SafeTotpView`; when not found, logs `[iapl] The admin import map may be out of date …` and IAPL's `TotpRedirectProvider` puts the notice "Two-step verification may not be available" above the 2FA screens (never instead of them). A hint only — the map in the build can differ from the file on disk (Dockerfile runner stage, re-exporting map); a file that is not found is not reported | `false` = no file read, log line or notice | | `twoFactor.texts` | IAPL's en/pl texts (`TOTP_TEXTS`) over the package's; 2FA screens titled "Two-step verification" / "Weryfikacja dwuetapowa" (site's language) | `false` = the package's texts; one text: `i18n.translations..totpPlugin.` (security.md) | | `twoFactor.guard` | on | IAPL's own second-factor check on every collection and global (also the plugin's own and those of plugins listed after iapl) and in `userMeetsRole`; startup fails with `[iapl] twoFactor: the injected 2FA plugin did not add …` when the 2FA package lacks the `totp` strategy / `hasTotp` / `totpSecret` | per entity: `custom.ipal.secondFactor: false` / `{ read: false }` or the package's `custom.totp.disableAccessWrapper.`; `false` = the package's wrapper only (the plugin's own data then opens to a password without the code; not recommended). The package's endpoints stay limited to accounts of the 2FA collection either way | -| `twoFactor.verifyLimit` | `{ max: 5, windowMinutes: 10, store: 'database' }` | attempts per account on `POST /api/verify-totp` (the 2FA package counts none): the sixth in the window, right or wrong, gets `429` + `Retry-After`. Counted in memory and in the database (`payload.kv`, the `payload-kv` collection Payload adds), so a restart or a second instance does not reset it; a failing store never opens the gate | `{ max, windowMinutes }`; `{ store: 'memory' }` = this instance only; `false` = no limit | +| `twoFactor.verifyLimit` | `{ max: 5, windowMinutes: 10, store: 'database' }` | wrong codes per account on `POST /api/verify-totp` (the 2FA package counts none): after five wrong ones in the window the next attempt, right or wrong, gets `429` + `Retry-After`; a right code gives its place back (1.17.1); an attempt held out only by others still being checked gets `429` + `Retry-After: 2`. Counted in memory and in the database (`payload.kv`, the `payload-kv` collection Payload adds), so a restart or a second instance does not reset it; a failing store never opens the gate | `{ max, windowMinutes }`; `{ store: 'memory' }` = this instance only; `false` = no limit | | `twoFactor.sameOrigin` | on | `POST /api/verify-totp` and `/api/setup-totp` refuse (`403`, not counted) a request a browser marks as coming from another origin (`Origin`, else `Sec-Fetch-Site`). Own origins: the request's host (`Host`, `X-Forwarded-Host`, a default port written out is ignored), `serverURL`, Payload's `csrf` / `cors`. Requests without those headers pass. A refusal is logged once per origin with how to allow it — behind a proxy that hides the address set `serverURL` | `{ origins: ['https://app.example.com'] }` adds origins; `false` = off | | `twoFactor.requireSetup` | on, `{ windowHours: 72 }` | an account without TOTP reaches nothing but the setup screen and `/api/setup-totp` (REST, GraphQL and the panel's data answer 403); it has `windowHours` from its creation or from an admin's reset, then it is blocked until an admin reopens setup. Adds the field `totpSetupStatus` (panel) to the 2FA collection, a dashboard notice and `POST /api/ipal/two-factor/reset`; the date field `totpSetupFrom` is there whenever 2FA is on (also with `requireSetup: false` / `guard: false`). Existing accounts get their window at the first start after the upgrade, written once. **Postgres/SQLite: the migration must be applied when the new container starts — `prodMigrations` or `pnpm payload migrate && pnpm start`, not a pre-deployment command (deployment.md §4.3) — or every login answers 500**; `generate:importmap`. `exempt` must return exactly `true` at once (an `async` one, or a `windowHours` that is not a number / `false`, stops the start) | `false` = the package's rule (API open until setup); `{ windowHours: 24 }`, `{ windowHours: false }` (no limit), `{ exempt: ({ user }) => … }` (a service account) | | `twoFactor.requireSetup.dashboardNotice` / `.statusField` / `.setupNotice` | on | the administrators' notice on the dashboard; the status and reset control on the account page; the notice on the setup screen | `false` each (the lock and the reset endpoint stay) | diff --git a/docs/agent/skills/iapl-reference/resources/api.md b/docs/agent/skills/iapl-reference/resources/api.md index 1791160..ce9d5e2 100644 --- a/docs/agent/skills/iapl-reference/resources/api.md +++ b/docs/agent/skills/iapl-reference/resources/api.md @@ -75,7 +75,7 @@ Admin panel components from `@intecion/ipal-kit/admin` — the project does NOT | `writeOnlySecret(field, options?)`, `writeOnlySecrets(fields, names, optionsByName?)`, `maskSecretAfterRead`, `keepSecretBeforeValidate`, `buildKeepSecret(options?)`, `SECRET_MASK`, `SECRET_CLEAR`, `isSecretMask(value)`, `INTEGRATION_SECRET_FIELDS`, `SMTP_PASSWORD_BOUND_TO` | `@intecion/ipal-kit` | Write-only secret fields (`secrets.writeOnly`): the wrapper for one field and for named fields anywhere in a tree (tabs, rows, groups); the two field hooks (reads through access control get `'********'`, the Local API with access control off gets the value; a save with nothing / empty / the mask keeps the stored value, `'[[clear]]'` removes it); the hook builder with options — `{ boundTo: ['siblingField'], appliesWhen?: (siblingData) => boolean }`: a save through access control that changes a bound sibling field without sending the secret throws a `ValidationError` on the secret (`secrets.reenterOnChange`); the two constants; the plugin's own secret field names (`smtpPassword`, `turnstileSecretKey`); the fields the SMTP password is bound to (`smtpHost`, `smtpPort`, `smtpUser` — not the transport: the mail adapter may fall back to SMTP). | | `maskSecretsOnRestore`, `maskWriteOnlySecrets(data, fields)` | `@intecion/ipal-kit` | Versions and write-only secrets: the `afterRead` hook for a global or a collection (a restore answers with the version document, fields under `version`, where field hooks do not run — it masks them there for reads through access control); the walker it uses (masks every write-only field in `data`, following tabs, rows, groups, arrays and blocks). On Site integrations by default; add the hook to your own entity that has both. | | `requestFromOwnOrigin(req, extraOrigins?)`, `ownOrigins(req, extraOrigins?)`, `reportRefusedOrigin(req, extraOrigins?)` | `@intecion/ipal-kit` | `twoFactor.sameOrigin`: `false` when a browser marks the request as coming from another origin (`Origin` not among the request's host, `serverURL`, `csrf`, `cors`, the extras; a default port written out on the host is ignored; else `Sec-Fetch-Site` not `same-origin` / `none`); `true` without those headers. `ownOrigins` → `{ hosts, origins }`. `reportRefusedOrigin` writes one log line per refused origin and process (at most 50) with the ways to allow it, and returns whether it wrote. For your own state-changing endpoint. | -| `buildVerifyLimit(collection, { max?, windowMinutes?, store?, keyPrefix? })`, `verifyLimitKey(collection, id, keyPrefix?)`, `clearVerifyLimits()` | `@intecion/ipal-kit` | `twoFactor.verifyLimit`: `async (req) => Response \| null` — counts an attempt of `req.user` in memory and, unless `store: 'memory'`, in `payload.kv`; a `429` with `Retry-After` past `max`. The kv key of an account's count; emptying the in-memory counts (tests). | +| `buildVerifyLimit(collection, { max?, windowMinutes?, store?, keyPrefix? })`, `verifyLimitKey(collection, id, keyPrefix?)`, `clearVerifyLimits()` | `@intecion/ipal-kit` | `twoFactor.verifyLimit`: `async (req) => Response \| null` — takes a place for an attempt of `req.user` in memory and, unless `store: 'memory'`, in `payload.kv`; a `429` with `Retry-After` past `max` (`Retry-After: 2` when only attempts still being checked hold it). `limit.settle(req, correct)` after the check: a right code gives its place back (unsettled = wrong). The kv key of an account's count; emptying the in-memory counts (tests). | | `turnstileSecretFromEnv(integrations)`, `TURNSTILE_SECRET_ENV` | `@intecion/ipal-kit` | `true` when the Turnstile secret in use comes from the environment because the panel field is empty (**deprecated** path; the doctor's `turnstile-env-key`); the variable's name, `'TURNSTILE_SECRET_KEY'`. | | `userMeetsRole(req, minimum)` | `@intecion/ipal-kit` | Predicate → `boolean` with `req` (`{ payload, user }`), in this order: the account belongs to a **staff collection** (`admin.user`, `access.authCollection`, `access.staffCollections`); with 2FA on it has passed the second factor (`secondFactorPassed`); it has a role ≥ `minimum`, **or** its collection has no `roles` field (the project omitted `access`). An account of any other auth collection never passes, whatever fields it has. The plugin's staff features (Site integrations, settings globals, form submissions, consent records, stats, cookie scanner, the e-mail test) use it; use it in your own endpoints. | | `staffCollectionSlugs(source?)` | `@intecion/ipal-kit` | `string[]`: the staff collections — `admin.user`, `access.authCollection` and `access.staffCollections` — from `req.payload`, a config or `{ staffCollections }`; without an argument what the configs built in this process agree on (`[]` when there is none). Roles and staff checks count only for accounts of these. | diff --git a/docs/agent/skills/iapl-setup/SKILL.md b/docs/agent/skills/iapl-setup/SKILL.md index 6e48a13..0d19ced 100644 --- a/docs/agent/skills/iapl-setup/SKILL.md +++ b/docs/agent/skills/iapl-setup/SKILL.md @@ -228,7 +228,7 @@ the panel shows Site settings, Site integrations, Cookies, Form messages, the Fo `[iapl] twoFactor…` unless `allowCollectionMismatch: true`. The second factor covers every collection and global (the plugin's own, and those of plugins listed after `iapl`) and the plugin's endpoints; guard your own endpoints with `secondFactorPassed(req)` or `userMeetsRole(req, role)` (security.md "What the second factor covers"). - Verify attempts: 5 per account in 10 minutes (`twoFactor.verifyLimit`). + Verify attempts: 5 wrong codes per account in 10 minutes (`twoFactor.verifyLimit`); right codes do not count. The `back` link of the setup and verify screens is checked on the server (`twoFactor.safeBack`, on by default: only a path inside the admin route is kept; `false` turns it off, a function replaces the rule). It needs the import map entry `@intecion/ipal-kit/admin#SafeTotpView` — run `pnpm payload generate:importmap` and commit @@ -246,7 +246,9 @@ the panel shows Site settings, Site integrations, Cookies, Form messages, the Fo (column `totp_setup_from`, there whenever 2FA is on) — without it every login answers 500; `pnpm payload generate:importmap` (`TwoFactorStatusField`, `TwoFactorAlert`). A service account that logs in with a password: `requireSetup: { exempt }` (a plain function - returning exactly `true`; never `async`); an API key needs nothing. Parts to switch off: `requireSetup: + returning exactly `true`; never `async`), deciding from a field only an admin can write (`serviceAccount` + checkbox with `adminOnlyField`; security.md "Decide `exempt` from a field only an administrator can write"), + never from the e-mail — every account may change its own e-mail; an API key needs nothing. Parts to switch off: `requireSetup: { dashboardNotice: false, statusField: false, setupNotice: false }`. An admin's reset ends the account's sessions and needs the admin's own TOTP code (`twoFactor.resetAccess` changes who). Have two administrators with 2FA: when all are blocked, only a script or a redeploy helps (security.md "Every administrator is diff --git a/docs/agent/skills/iapl-upgrade/SKILL.md b/docs/agent/skills/iapl-upgrade/SKILL.md index 0e52b53..8e2e432 100644 --- a/docs/agent/skills/iapl-upgrade/SKILL.md +++ b/docs/agent/skills/iapl-upgrade/SKILL.md @@ -405,7 +405,10 @@ site without steps 1–3 and a deploy day agreed with the owner. Steps 2, 3 and `[iapl] 2FA: the column for "totpSetupFrom" is missing … NOBODY CAN LOG IN`. `pnpm exec iapl-doctor` reports it before the deploy. MongoDB: nothing. 4. An integration that logs in with a password and has no TOTP: give it an API key, or - `twoFactor.requireSetup: { exempt: ({ user }) => user.email === '…' }`. `grep -rn "overrideAccess: false" src`: + `twoFactor.requireSetup: { exempt: ({ user }) => user.serviceAccount === true }` with a checkbox only admins can + write (`access: { create: adminOnlyField, update: adminOnlyField }`) — not by e-mail: every account may change its + own e-mail (security.md "Decide `exempt` from a field only an administrator can write"). A project already on an + e-mail list (1.17.1): move to the field, or make `email` admin-only. `grep -rn "overrideAccess: false" src`: a `user` fetched by id is refused for every account now — take it from `payload.auth({ headers })`. 5. `rm -rf .next`, build, redeploy on Coolify. Read the first lines of the log: `[iapl] 2FA: N existing account(s) without two-step verification…` — pass that number to the owner. The line appears on that first start only. diff --git a/docs/security.md b/docs/security.md index 05e6a40..5660932 100644 --- a/docs/security.md +++ b/docs/security.md @@ -523,7 +523,7 @@ twoFactor: { plugin: payloadTotp, // requireSetup: { windowHours: 24 }, // another window // requireSetup: { windowHours: false }, // no time limit (0 works too): locked until set up, never blocked - // requireSetup: { exempt: ({ user }) => user.email === 'integration@example.com' }, // a service account that logs in with a password, on purpose + // requireSetup: { exempt: ({ user }) => user.serviceAccount === true }, // a service account that logs in with a password, on purpose (the field: below) // requireSetup: { dashboardNotice: false, statusField: false, setupNotice: false }, // each panel part can be switched off; the lock stays // requireSetup: false, // the 2FA package's rule: redirect in the panel, API open until setup // who may reset / reopen. Default: a staff admin whose session entered its own TOTP code. Your function replaces @@ -547,6 +547,24 @@ twoFactor: { `async` function stops the site at start with a clear error; any answer other than exactly `true` (a Promise, a string, an error) exempts nobody and is logged once. Decide from the fields on `user`. An exempt account works on its password alone, so give it the lowest role that does its job. +- **Decide `exempt` from a field only an administrator can write — not from the e-mail address.** Every account + may change its own e-mail (REST, GraphQL and the account page, with no password asked), so an e-mail list + (`user.email === 'it@example.com'`, a list of addresses) lets an editor rename itself into it, and an admin's + later reset of that account's TOTP would leave it on its password alone. An account also cannot be told apart + from an address that does not exist yet. A checkbox that only admins can set: + + ```ts + import { adminOnlyField } from '@intecion/ipal-kit' + // in the 2FA collection's fields: + { name: 'serviceAccount', type: 'checkbox', defaultValue: false, access: { create: adminOnlyField, update: adminOnlyField } }, + // twoFactor.requireSetup: + { exempt: ({ user }) => user.serviceAccount === true } + ``` + + On Postgres / SQLite the new field is a column: a migration in the same deploy. A project that keeps an e-mail + list makes the e-mail field admin-only too (`access: { update: adminOnlyField }` on `email`) — then no account + changes its own address. **Check:** as an editor, `PATCH /api/users/` with `{ "serviceAccount": true }` + → the value stays `false`. - **`windowHours`** must be a number (0 or more) or `false`; anything else (`'24'`, `-1`) stops the site at start. - **Import map.** The status field and the dashboard notice are admin components: `pnpm payload generate:importmap` after upgrading (`TwoFactorStatusField`, `TwoFactorAlert`); `iapl-doctor` reports a map @@ -589,8 +607,14 @@ the panel. As an administrator open the account → "Two-step verification: Set **Verify attempts are limited** (`twoFactor.verifyLimit`). The package checks the code and never counts tries; a six-digit code has about three right answers in a million, so whoever held the password could guess. iapl -counts attempts per account on `POST /api/verify-totp`: by default the **sixth attempt within 10 minutes** — -right or wrong — is refused with `429` and `Retry-After`, and a line goes to the log. Only a session that already +counts **wrong codes** per account on `POST /api/verify-totp`: by default, after **five wrong codes within 10 +minutes** the next attempt — right or wrong — is refused with `429` and `Retry-After`, and a line goes to the log. +An attempt takes its place before the code is compared, so a burst of parallel guesses cannot slip under the limit, +and a right code gives its place back: an account that logs in correctly many times (an office sharing one login, +several devices) is never refused (since 1.17.1; before, every attempt counted, right or wrong, so the sixth correct +login in the window was refused). While other attempts of the same account are still being checked, a new one that +only they hold out gets `429` with `Retry-After: 2` and "try again in a moment" instead of the long wait; an attempt +that never ends counts as wrong. Only a session that already passed the password reaches the endpoint, so nobody without the password can lock an account's owner out; someone who has the password can delay the owner's login by ten minutes at a time (and that shows in the log). Counted in memory per server instance **and in the database** (Payload's key-value store, `payload.kv` — the `payload-kv` @@ -1084,7 +1108,9 @@ the full text, as before. The components take the same as props `writeOnlySecrets` (with `boundTo`), `maskSecretsOnRestore` for your own fields. - **2FA attempts from another origin:** `twoFactor.sameOrigin: false`, or `{ origins: [...] }`; `requestFromOwnOrigin`, `ownOrigins` are exported. **Verify count:** `verifyLimit: { store: 'memory' }`; `buildVerifyLimit`, - `verifyLimitKey`, `clearVerifyLimits` (tests) are exported. + `verifyLimitKey`, `clearVerifyLimits` (tests) are exported. A project that wires `buildVerifyLimit` into an + endpoint of its own calls `limit.settle(req, correct)` after its check (a right code gives its place back; + without it every attempt stays counted, as before 1.17.1). - **Dashboard alerts:** `dashboardAlerts: { integrations, cookies }`. - **The mail service:** `mail: { relay: false }`; `mail.relay: { enrol: 'manual' | false, token, accountMail, confirmRateLimit }`; `relayConfirmEndpoint`, `enrolRelay`, `disconnectRelay`, `rotateRelayToken`, `setRelayToken` diff --git a/src/modules/admin-i18n/texts/security.ts b/src/modules/admin-i18n/texts/security.ts index a7411fd..b5812af 100644 --- a/src/modules/admin-i18n/texts/security.ts +++ b/src/modules/admin-i18n/texts/security.ts @@ -9,6 +9,7 @@ export const securityTexts = defineTexts({ twoFactorAlertLink: 'Open the user list', twoFactorAlertPending: 'Accounts without two-step verification: {{count}}. Until it is set up, such an account cannot use the panel.', twoFactorAlertTitle: 'Two-step verification', + twoFactorBusy: 'Another code for this account is being checked right now. Try again in a moment.', twoFactorReopen: 'Reopen setup', twoFactorReset: 'Reset two-step verification', twoFactorResetConfirm: 'This account will have to set up two-step verification again before it can use the panel. Continue?', @@ -33,6 +34,7 @@ export const securityTexts = defineTexts({ 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.', twoFactorAlertTitle: 'Weryfikacja dwuetapowa', + twoFactorBusy: 'Właśnie sprawdzamy inny kod dla tego konta. Spróbuj ponownie za chwilę.', twoFactorReopen: 'Otwórz konfigurację ponownie', twoFactorReset: 'Zresetuj weryfikację dwuetapową', twoFactorResetConfirm: 'To konto będzie musiało ponownie ustawić weryfikację dwuetapową, zanim skorzysta z panelu. Kontynuować?', diff --git a/src/modules/security/totp/secondFactor.ts b/src/modules/security/totp/secondFactor.ts index e1cdfcf..83bc03f 100644 --- a/src/modules/security/totp/secondFactor.ts +++ b/src/modules/security/totp/secondFactor.ts @@ -382,6 +382,11 @@ export type TotpEndpointGuards = { * it. Return a Response to refuse (too many attempts), null to let it through. */ limitVerify?: (req: never) => null | Promise | Response + /** + * Called after a verify attempt that `limitVerify` let through: `correct` is true when the package + * answered `{ ok: true }`. The plugin's limit gives a right code's place back (buildVerifyLimit `settle`). + */ + settleVerify?: (req: never, correct: boolean) => Promise | void /** The answer for an account whose setup window has passed (in the caller's language). Default: a plain 403. */ onSetupClosed?: (req: never) => Response /** @@ -413,6 +418,16 @@ export function guardTotpEndpoint(endpoint: T, collectio if (user && endpoint.path === '/verify-totp' && guards.limitVerify) { const limited = await guards.limitVerify(req as never) if (limited) {return limited} + if (guards.settleVerify) { + let correct = false + try { + const res = await handler(req) + correct = res.status === 200 && ((await res.clone().json().catch(() => null)) as { ok?: unknown } | null)?.ok === true + return res + } finally { + await guards.settleVerify(req as never, correct) + } + } } return handler(req) }) as unknown as T['handler'], diff --git a/src/modules/security/totp/verifyLimit.ts b/src/modules/security/totp/verifyLimit.ts index d4b8547..d921f47 100644 --- a/src/modules/security/totp/verifyLimit.ts +++ b/src/modules/security/totp/verifyLimit.ts @@ -8,10 +8,16 @@ import { serverText } from '../../integrations/texts.js' * answers in a million, so whoever holds the password could simply try. * * Counted per ACCOUNT, not per IP (an attacker changes addresses; the account - * is what is being guessed). Every attempt counts, right or wrong — nobody - * needs more than a handful of logins in the window. Only a session that - * already passed the password reaches the endpoint, so someone without the - * password cannot use the limit to lock an account's owner out. + * is what is being guessed). An attempt takes its place BEFORE the code is + * compared (a burst of parallel guesses cannot slip under the limit), and gives + * it back when the code was right (`settle`): only wrong codes stay counted. + * Since 1.17.1 — before, every attempt stayed counted, so the sixth correct + * login of one account in the window (an office sharing a login, several devices) + * was refused. A place taken by an attempt still being checked refuses a new one + * with "try again in a moment" (`Retry-After: 2`), not with the long wait; an + * attempt never settled counts as wrong. Only a session that already passed the + * password reaches the endpoint, so someone without the password cannot use the + * limit to lock an account's owner out. * * Counted twice, and the higher count decides: * - **in memory**, per server instance — exact also for a burst of parallel requests @@ -44,10 +50,31 @@ export type VerifyLimitOptions = { type Bucket = { count: number; resetAt: number } const buckets = new Map() +/** Attempts let through and not settled yet, per bucket key: when each started. Older than IN_FLIGHT_MS = wrong. */ +const inFlight = new Map() +/** An attempt that has not said how it ended after this long counts as a wrong code. */ +const IN_FLIGHT_MS = 30_000 +/** Who took which place, so that `settle` gives back exactly that one. */ +type Place = { collection: string; id: string; key: string; keyPrefix: string; startedAt: number; stored: boolean } +const pending = new WeakMap() /** For tests. */ export function clearVerifyLimits(): void { buckets.clear() + inFlight.clear() +} + +const youngInFlight = (key: string, now: number): number[] => { + const kept = (inFlight.get(key) ?? []).filter((at) => now - at < IN_FLIGHT_MS) + if (kept.length) {inFlight.set(key, kept)} else {inFlight.delete(key)} + return kept +} +const dropInFlight = (key: string, startedAt: number): void => { + const list = inFlight.get(key) + if (!list) {return} + const i = list.indexOf(startedAt) + if (i >= 0) {list.splice(i, 1)} + if (!list.length) {inFlight.delete(key)} } type KV = { get: (key: string) => Promise; set: (key: string, value: object) => Promise } @@ -75,13 +102,47 @@ async function hitStored(payload: { kv?: unknown; logger?: { warn: (m: string) = } } -export function buildVerifyLimit(collection: string, options: VerifyLimitOptions = {}) { +/** Takes one counted attempt back, in memory and in the database (a right code, or an attempt that was refused without a compare). */ +async function giveBack(payload: { kv?: unknown }, place: Place, now: number): Promise { + const bucket = buckets.get(place.key) + if (bucket && bucket.resetAt > now && bucket.count > 0) {bucket.count -= 1} + if (!place.stored) {return} + const kv = payload.kv as KV | undefined + if (typeof kv?.get !== 'function' || typeof kv?.set !== 'function') {return} + try { + const key = verifyLimitKey(place.collection, place.id, place.keyPrefix) + const current = (await kv.get(key)) as Bucket | null + if (current && typeof current.count === 'number' && typeof current.resetAt === 'number' && current.resetAt > now && current.count > 0) { + await kv.set(key, { count: current.count - 1, resetAt: current.resetAt }) + } + } catch { + // the place stays taken until the window ends: never more attempts than the limit, only fewer + } +} + +/** + * Says how a verify attempt that the limit let through ended. `correct: true` gives its place back + * (only wrong codes stay counted); `false` keeps it. An attempt never settled counts as wrong. + * `guardTotpEndpoint` calls it with the package's answer (`{ ok: true }`); a project that calls + * `buildVerifyLimit` itself calls `limit.settle(req, correct)` after its own check. + */ +export type SettleVerifyAttempt = (req: PayloadRequest, correct: boolean) => Promise + +export function buildVerifyLimit(collection: string, options: VerifyLimitOptions = {}): ((req: PayloadRequest) => Promise) & { settle: SettleVerifyAttempt } { const max = Number.isFinite(options.max) && options.max! > 0 ? Math.floor(options.max!) : 5 const windowMs = (Number.isFinite(options.windowMinutes) && options.windowMinutes! > 0 ? options.windowMinutes! : 10) * 60_000 const stored = options.store !== 'memory' const keyPrefix = typeof options.keyPrefix === 'string' && options.keyPrefix.trim() ? options.keyPrefix.trim() : 'ipal' - return async (req: PayloadRequest): Promise => { + const settle: SettleVerifyAttempt = async (req, correct) => { + const place = pending.get(req as object) + if (!place) {return} + pending.delete(req as object) + dropInFlight(place.key, place.startedAt) + if (correct) {await giveBack(req.payload as never, place, Date.now())} + } + + const limit = async (req: PayloadRequest): Promise => { // No session: the package refuses by itself, and there is no account to count against. if (!req.user) {return null} // Whatever the id looks like, it is one bucket per value — never "no limit". @@ -95,6 +156,8 @@ export function buildVerifyLimit(collection: string, options: VerifyLimitOptions } } const key = `${collection}:${id}` + // attempts of this account being checked right now (taken before this one's own place) + const busy = youngInFlight(key, now).length const current = buckets.get(key) const bucket = current && current.resetAt > now ? current : { count: 0, resetAt: now + windowMs } bucket.count += 1 @@ -104,7 +167,21 @@ export function buildVerifyLimit(collection: string, options: VerifyLimitOptions // …and in the database, so a restart or another instance does not start from zero. The higher count decides. const kept = stored ? await hitStored(req.payload as never, verifyLimitKey(collection, id, keyPrefix), windowMs, now) : null const worst = kept && kept.count > mine.count ? kept : mine - if (worst.count <= max) {return null} + const place: Place = { id, collection, key, keyPrefix, startedAt: now, stored: stored && kept !== null } + if (worst.count <= max) { + pending.set(req as object, place) + inFlight.set(key, [...(inFlight.get(key) ?? []), now]) + return null + } + // Refused without a compare: this attempt gives its place back at once. + await giveBack(req.payload as never, place, now) + // Full only because of attempts still being checked (six right codes at the same moment): "try again", no long wait. + if (busy > 0 && worst.count - 1 - busy < max) { + return Response.json( + { message: serverText(req.i18n as never, 'twoFactorBusy'), ok: false }, + { headers: { 'Retry-After': '2' }, status: 429 }, + ) + } const retryAfter = Math.max(1, Math.ceil((worst.resetAt - now) / 1000)) req.payload.logger.warn(`[iapl] 2FA: too many verify attempts for ${collection} ${id}; refused for ${retryAfter} s.`) return Response.json( @@ -112,4 +189,5 @@ export function buildVerifyLimit(collection: string, options: VerifyLimitOptions { headers: { 'Retry-After': String(retryAfter) }, status: 429 }, ) } + return Object.assign(limit, { settle }) } diff --git a/src/plugin.ts b/src/plugin.ts index 8e44c9b..22cf24b 100644 --- a/src/plugin.ts +++ b/src/plugin.ts @@ -320,7 +320,7 @@ export const iapl = (options: IaplOptions): Plugin => { const limitVerify = tf.verifyLimit === false ? undefined : buildVerifyLimit(target, { ...tf.verifyLimit, keyPrefix: (typeof tf.verifyLimit?.keyPrefix === 'string' && tf.verifyLimit.keyPrefix.trim()) || (options.storageNames === 'iapl' ? 'iapl' : 'ipal') }) const extraOrigins = typeof tf.sameOrigin === 'object' ? (tf.sameOrigin.origins ?? []) : [] const guards = { - ...(limitVerify ? { limitVerify: (req: PayloadRequest) => limitVerify(req) } : {}), + ...(limitVerify ? { limitVerify: (req: PayloadRequest) => limitVerify(req), settleVerify: (req: PayloadRequest, correct: boolean) => limitVerify.settle(req, correct) } : {}), ...(tf.sameOrigin === false ? {} : { diff --git a/test/exemptByField.test.ts b/test/exemptByField.test.ts new file mode 100644 index 0000000..f593ab7 --- /dev/null +++ b/test/exemptByField.test.ts @@ -0,0 +1,85 @@ +/** + * The documented way to exempt a service account from 2FA setup (security.md "Decide `exempt` from a field only an + * administrator can write"), checked through real HTTP requests: an editor can rename itself to any e-mail, so an + * e-mail list is no boundary; an admin-only checkbox is — the editor's own save leaves it as it is (REST and GraphQL). + * 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, describe, expect, test, vi } from 'vitest' + +import { adminOnlyField } from '../src/index.js' +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' + +vi.mock('server-only', () => ({})) +vi.mock('next/headers.js', async () => (await import('./http/server.js')).nextHeadersMock) + +const SECRET = 'JBSWY3DPEHPK3PXP' +const PASSWORD = 'a-long-test-password-1' +let server: TestServer +let payload: Payload +let editorId: number | string +let cookie: string + +const call = (p: string, init: RequestInit = {}) => + fetch(`${server.url}/api${p}`, { ...init, headers: { 'content-type': 'application/json', cookie, ...(init.headers as Record) } }) + +beforeAll(async () => { + const config = buildTestConfig({ + admin: { user: 'users' }, + collections: [ + { slug: 'users', auth: true, fields: [{ name: 'serviceAccount', type: 'checkbox', access: { create: adminOnlyField, update: adminOnlyField }, defaultValue: false }] }, + { slug: 'media', fields: [], upload: { staticDir: '/tmp/iapl-exempt-media' } }, + ], + db: testDatabase('exemptfield'), + editor: lexicalEditor(), + plugins: [ + iapl({ + access: { authCollection: 'users' }, + i18n: { defaultLocale: 'en', locales: [{ code: 'en', label: 'English' }] }, + twoFactor: { issuer: 'Example', plugin: payloadTotp, requireSetup: { exempt: ({ user }) => user.serviceAccount === true } }, + }), + ], + secret: 'integration-test-secret-0123456789', + telemetry: false, + }) + payload = await getPayload({ config }) + server = await startPayloadServer(config) + const editor = await payload.create({ collection: 'users' as never, data: { email: 'editor@example.com', password: PASSWORD, roles: ['editor'], totpSecret: SECRET } as never }) + editorId = (editor as { id: number | string }).id + const login = await fetch(`${server.url}/api/users/login`, { body: JSON.stringify({ email: 'editor@example.com', password: PASSWORD }), headers: { 'content-type': 'application/json' }, method: 'POST' }) + const first = cookiesOf(login) + cookie = first.join('; ') + const verify = await call('/verify-totp', { body: JSON.stringify({ token: totp(SECRET) }), method: 'POST' }) + expect(((await verify.json()) as { ok?: boolean }).ok).toBe(true) + cookie = [...first, ...cookiesOf(verify)].join('; ') +}, 120_000) + +afterAll(async () => { + await server?.close() + await payload?.destroy?.() +}) + +describe('exempt from 2FA setup: by an admin-only field, not by e-mail', () => { + test('an editor cannot set the field on itself (REST and GraphQL); the value stays false', async () => { + const rest = await call(`/users/${editorId}`, { body: JSON.stringify({ serviceAccount: true }), method: 'PATCH' }) + expect(rest.status).toBe(200) + await call('/graphql', { body: JSON.stringify({ query: `mutation { updateUser(id: ${JSON.stringify(editorId)}, data: { serviceAccount: true }) { id } }` }), method: 'POST' }) + const stored = (await payload.findByID({ id: editorId, collection: 'users' as never, overrideAccess: true })) as { serviceAccount?: boolean } + expect(stored.serviceAccount).toBe(false) + }) + + test('…while the same editor can change its own e-mail to anything: an e-mail list is no boundary', async () => { + const res = await call(`/users/${editorId}`, { body: JSON.stringify({ email: 'it@example.com' }), method: 'PATCH' }) + expect(res.status).toBe(200) + const stored = (await payload.findByID({ id: editorId, collection: 'users' as never, overrideAccess: true })) as { email: string } + expect(stored.email).toBe('it@example.com') + }) +}) diff --git a/test/legacyNames.test.ts b/test/legacyNames.test.ts index 1f3d884..eb01b7c 100644 --- a/test/legacyNames.test.ts +++ b/test/legacyNames.test.ts @@ -391,7 +391,7 @@ describe('stored names', () => { expect(await limit(req())).toBeNull() expect((await limit(req()))?.status).toBe(429) expect([...data.keys()]).toEqual(['iapl:2fa-verify:users:1']) - expect(data.get('iapl:2fa-verify:users:1')).toMatchObject({ count: 3 }) + expect(data.get('iapl:2fa-verify:users:1')).toMatchObject({ count: 2 }) // the refused third gave its place back (1.17.1) // an empty or undefined prefix is "not given", never a third key for (const keyPrefix of [undefined, '', ' ']) { data.clear() diff --git a/test/secondFactorGuard.test.ts b/test/secondFactorGuard.test.ts index d30c0ff..9207aaf 100644 --- a/test/secondFactorGuard.test.ts +++ b/test/secondFactorGuard.test.ts @@ -316,8 +316,12 @@ describe('iapl and the 2FA plugin', () => { test('verify attempts are limited per account, and the limit can be changed or switched off', async () => { clearVerifyLimits() const req = (id: unknown) => ({ i18n: undefined, payload: { logger: { warn: () => {} } }, user: { id, collection: 'users' } }) as never - const limit = buildVerifyLimit('users') // 5 in 10 minutes - for (let i = 0; i < 5; i++) {expect(await limit(req(1))).toBeNull()} + const limit = buildVerifyLimit('users') // 5 wrong codes in 10 minutes + for (let i = 0; i < 5; i++) { + const attempt = req(1) + expect(await limit(attempt)).toBeNull() + await limit.settle(attempt, false) // a wrong code (1.17.1: a right one gives its place back) + } const refused = (await limit(req(1)))! expect(refused.status).toBe(429) expect(Number(refused.headers.get('retry-after'))).toBeGreaterThan(0) @@ -360,7 +364,8 @@ describe('iapl and the 2FA plugin', () => { expect(await limit(req(kv))).toBeNull() // 4th expect(await limit(req(kv))).toBeNull() // 5th expect((await limit(req(kv)))!.status).toBe(429) - expect(kv.data.get(verifyLimitKey('users', '1'))).toMatchObject({ count: 6 }) + // five attempts; the refused sixth compared nothing and gave its place back (1.17.1) + expect(kv.data.get(verifyLimitKey('users', '1'))).toMatchObject({ count: 5 }) // and a restart while refused keeps refusing, with the stored window's Retry-After clearVerifyLimits() const again = (await limit(req(kv)))! @@ -468,7 +473,7 @@ describe('iapl and the 2FA plugin', () => { }) test('wired by default on verify and setup, before the limit; not on other endpoints; sameOrigin: false turns it off', async () => { - const handler = vi.fn(() => Response.json({ ok: true })) + const handler = vi.fn(() => Response.json({ ok: false })) // wrong codes: they stay counted (a right one gives its place back) const warn = vi.fn() clearReportedOrigins() const withEndpoints = (o: { collection: string }) => (c: Config) => ({ diff --git a/test/verifyLimitCorrectCodes.test.ts b/test/verifyLimitCorrectCodes.test.ts new file mode 100644 index 0000000..37ace8b --- /dev/null +++ b/test/verifyLimitCorrectCodes.test.ts @@ -0,0 +1,143 @@ +/** + * The 2FA verify limit counts wrong codes only (1.17.1, IAWL idea 27: "a limiter that reserves a place before it + * compares must not lock on reservations"). Through real HTTP requests against a running Payload with the 2FA + * package: an account that logs in correctly six times in the window is not refused; wrong codes still lock; + * an attempt still being checked answers "try again in a moment", not the long wait. + * 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, describe, expect, test, vi } from 'vitest' + +import { buildVerifyLimit, clearVerifyLimits, verifyLimitKey } from '../src/modules/security/totp/verifyLimit.js' +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' + +vi.mock('server-only', () => ({})) +vi.mock('next/headers.js', async () => (await import('./http/server.js')).nextHeadersMock) + +const SECRET = 'JBSWY3DPEHPK3PXP' +const PASSWORD = 'a-long-test-password-1' +let server: TestServer +let payload: Payload + +const post = (p: string, body: unknown, cookie = '') => + fetch(`${server.url}/api${p}`, { body: JSON.stringify(body), headers: { 'content-type': 'application/json', ...(cookie ? { cookie } : {}) }, method: 'POST' }) +const passwordStep = async (email: string) => cookiesOf(await post('/users/login', { email, password: PASSWORD })).join('; ') +/** A code that is surely wrong now (not the current one, nor one step either side). */ +const wrongCode = () => { + const near = new Set([-30_000, 0, 30_000].map((d) => totp(SECRET, Date.now() + d))) + let n = 123456 + while (near.has(String(n))) {n++} + return String(n) +} + +beforeAll(async () => { + clearVerifyLimits() + const config = buildTestConfig({ + admin: { user: 'users' }, + collections: [{ slug: 'media', fields: [], upload: { staticDir: '/tmp/iapl-verify-limit-media' } }], + db: testDatabase('verifylimit'), + editor: lexicalEditor(), + plugins: [iapl({ access: { authCollection: 'users' }, i18n: { defaultLocale: 'en', locales: [{ code: 'en', label: 'English' }] }, twoFactor: { issuer: 'Example', plugin: payloadTotp } })], + secret: 'integration-test-secret-0123456789', + telemetry: false, + }) + payload = await getPayload({ config }) + server = await startPayloadServer(config) + for (const email of ['office@example.com', 'guess@example.com', 'burst@example.com']) { + await payload.create({ collection: 'users' as never, data: { email, password: PASSWORD, roles: ['editor'], totpSecret: SECRET } as never }) + } +}, 120_000) + +afterAll(async () => { + await server?.close() + await payload?.destroy?.() +}) + +describe('the 2FA verify limit counts wrong codes, not right ones', () => { + test('an account that logs in correctly seven times in the window is never refused', async () => { + const answers: unknown[] = [] + for (let i = 0; i < 7; i++) { + const res = await post('/verify-totp', { token: totp(SECRET) }, await passwordStep('office@example.com')) + answers.push([res.status, ((await res.json()) as { ok?: boolean }).ok]) + } + expect(answers).toEqual(Array.from({ length: 7 }, () => [200, true])) + }) + + test('six correct codes at the same moment: the account is not locked, a retry gets in', async () => { + const cookies: string[] = [] + for (let i = 0; i < 6; i++) {cookies.push(await passwordStep('burst@example.com'))} + const statuses = await Promise.all(cookies.map(async (cookie) => (await post('/verify-totp', { token: totp(SECRET) }, cookie)).status)) + // all in, or one told to try again in a moment — never the long wait + expect(statuses.filter((s) => s === 200).length).toBeGreaterThanOrEqual(5) + const retry = await post('/verify-totp', { token: totp(SECRET) }, await passwordStep('burst@example.com')) + expect([retry.status, ((await retry.json()) as { ok?: boolean }).ok]).toEqual([200, true]) + }) + + test('five wrong codes still lock the account, also for the right code; a right code does not undo wrong ones', async () => { + const cookie = await passwordStep('guess@example.com') + expect(((await (await post('/verify-totp', { token: totp(SECRET) }, cookie)).json()) as { ok?: boolean }).ok).toBe(true) + for (let i = 0; i < 5; i++) { + const res = await post('/verify-totp', { token: wrongCode() }, await passwordStep('guess@example.com')) + expect([res.status, ((await res.json()) as { ok?: boolean }).ok]).toEqual([200, false]) + } + const locked = await post('/verify-totp', { token: totp(SECRET) }, await passwordStep('guess@example.com')) + expect(locked.status).toBe(429) + expect(Number(locked.headers.get('retry-after'))).toBeGreaterThan(60) + expect(((await locked.json()) as { message: string }).message).toMatch(/Too many codes/) + // the stored count is the five wrong codes: the right one before them and the refused one gave their places back + const user = (await payload.find({ collection: 'users' as never, overrideAccess: true, where: { email: { equals: 'guess@example.com' } } })).docs[0] as { id: number | string } + expect(await payload.kv.get(verifyLimitKey('users', String(user.id)))).toMatchObject({ count: 5 }) + }) +}) + +describe('buildVerifyLimit: places, settle and "try again"', () => { + const req = (id = 1) => ({ i18n: undefined, payload: { logger: { warn: () => {} } }, user: { id, collection: 'users' } }) as never + + test('attempts still being checked fill the limit with "try again in a moment"; settled right codes free it', async () => { + clearVerifyLimits() + const limit = buildVerifyLimit('users', { store: 'memory' }) + const running = Array.from({ length: 5 }, () => req()) + for (const r of running) {expect(await limit(r)).toBeNull()} + const busy = (await limit(req()))! + expect(busy.status).toBe(429) + expect(busy.headers.get('retry-after')).toBe('2') + expect(((await busy.json()) as { message: string }).message).toMatch(/being checked right now/) + for (const r of running) {await limit.settle(r, true)} + const next = req() + expect(await limit(next)).toBeNull() + await limit.settle(next, true) + }) + + test('wrong codes stay counted; the sixth attempt gets the long wait', async () => { + clearVerifyLimits() + const limit = buildVerifyLimit('users', { store: 'memory' }) + for (let i = 0; i < 5; i++) { + const r = req() + expect(await limit(r)).toBeNull() + await limit.settle(r, false) + } + const refused = (await limit(req()))! + expect(refused.status).toBe(429) + expect(Number(refused.headers.get('retry-after'))).toBeGreaterThan(60) + expect(((await refused.json()) as { message: string }).message).toMatch(/Too many codes/) + }) + + test('settle for a request the limit never saw, or twice, changes nothing', async () => { + clearVerifyLimits() + const limit = buildVerifyLimit('users', { max: 1, store: 'memory' }) + await limit.settle(req(), true) + const r = req() + expect(await limit(r)).toBeNull() + await limit.settle(r, false) + await limit.settle(r, true) // already settled: the wrong code stays counted + expect((await limit(req()))?.status).toBe(429) + }) +})