Merge claude/security-a-signin-limits-80f95e: 2FA verify limit counts wrong codes only, exempt by an admin-only field, 2FA reset only from the site's own origin
Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
+3
-3
@@ -1218,10 +1218,10 @@ 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' }` |
|
||||
| 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` |
|
||||
| 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. The admin's reset `POST /api/ipal/two-factor/reset` follows the same rule (1.17.1). **Verify:** `curl -X POST <site>/api/ipal/two-factor/reset -H 'Origin: https://other.example' -H 'Content-Type: text/plain' -b <admin cookies> -d '{"userId":1}'` → `403`; the panel's button still works. **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` |
|
||||
| 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)` |
|
||||
|
||||
@@ -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 |
|
||||
|
||||
@@ -51,8 +51,8 @@ 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.<lang>.totpPlugin.<key>` (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.<op>`; `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.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.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`, `/api/setup-totp` and (1.17.1) the admin's `/api/ipal/two-factor/reset` 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) |
|
||||
| `twoFactor.resetAccess` (the endpoint exists with `twoFactor.guard` on; `guard: false` = no endpoint, 404) | a staff admin whose session entered its own TOTP code (not an API key, not an `exempt` account) | who may reset another account's TOTP / reopen its setup (the button on the account page, `POST /api/ipal/two-factor/reset`). The reset clears the secret and the account's sessions. A session that still owes its code is always refused | `({ req }) => boolean` — replaces the rule, so keep `req.user?._strategy === 'totp' &&` in it unless API-key / exempt admins should reset; only `true` allows; `req.user._strategy` tells `'totp'`, `'api-key'`, `'local-jwt'` apart |
|
||||
|
||||
@@ -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. |
|
||||
@@ -619,7 +619,7 @@ Server only (`pnpm payload run`); never import it from client code, the Payload
|
||||
| `SAFE_TOTP_VIEW` / `totpViewImportKey(component)` | `@intecion/ipal-kit` | `'@intecion/ipal-kit/admin#SafeTotpView'`, the wrapper's import-map path (the default `wrapper` of `wrapTotpViews`); and the import-map key (`path#export`) of a component given as a string or `{ path, exportName }`. |
|
||||
| `findImportMapFile(config, cwd?)` / `missingImportMapEntries(config, entries, cwd?)` | `@intecion/ipal-kit` | Where the project's `importMap.js` is on disk (`admin.importMap.importMapFile`, else `app/(payload)<admin route>/` or `src/app/…` under `admin.importMap.baseDir` / the working directory; `null` when not found), and which of `entries` its text does not contain (`{ file, missing }`). A hint from the file on disk, not the map in the build: warn on it, never block on it. Behind `twoFactor.importMapCheck`. |
|
||||
| `buildSetupFields({ statusField? })`, `stampSetupFrom`, `backfillSetupFrom(payload, collection)` | `@intecion/ipal-kit` | The parts of "2FA setup required" for a project that wires them itself: the fields for the 2FA collection (`totpSetupFrom`, and the panel's `totpSetupStatus` unless `statusField: false`), the `beforeChange` hook that stamps the window start (on create, and when an account loses its TOTP secret), and the start-up step that gives accounts without TOTP and without a start their window (returns how many; once per account). |
|
||||
| `buildTwoFactorResetEndpoint(collection, { access? })`, `TWO_FACTOR_RESET_PATH` | `@intecion/ipal-kit` | `POST /api/ipal/two-factor/reset` `{ userId }`: clears the account's TOTP secret and sessions and starts a new window. Default: a staff admin whose session entered its own TOTP code; `access` replaces that (only `true` allows; a session that owes its code is always refused). `iapl` registers it only with `twoFactor.guard` on. |
|
||||
| `buildTwoFactorResetEndpoint(collection, { access?, ownOrigin? })`, `TWO_FACTOR_RESET_PATH` | `@intecion/ipal-kit` | `POST /api/ipal/two-factor/reset` `{ userId }`: clears the account's TOTP secret and sessions and starts a new window. `ownOrigin(req)` false → `403` before anything changes (the plugin passes the `twoFactor.sameOrigin` rule; wire `requestFromOwnOrigin` when you build it yourself). Default: a staff admin whose session entered its own TOTP code; `access` replaces that (only `true` allows; a session that owes its code is always refused). `iapl` registers it only with `twoFactor.guard` on. |
|
||||
| `countAccountsWithoutTotp(payload, collection, setupWindowMs?)` | `@intecion/ipal-kit` | `{ without, blocked }` — accounts of the 2FA collection without TOTP, and how many are past their window. |
|
||||
| `resolveRequireSetup(option)`, `strictExempt(fn)`, `SETUP_FROM_FIELD`, `DEFAULT_SETUP_WINDOW_HOURS` | `@intecion/ipal-kit` | `twoFactor.requireSetup` → `{ requireSetup, setupWindowMs, exempt? }` as the guard reads it (throws on a `windowHours` that is not a number ≥ 0 or `false`, and on an `async` `exempt`); the wrapper that makes an `exempt` function answer `true` only for exactly `true`; the field name `'totpSetupFrom'`; `72`. |
|
||||
| `fetchPublicImage(url, base)`, `publicImageDataUri(url, base)`, `rasterImageType(bytes)`, `siteOrigin(serverURL)`, `PUBLIC_IMAGE_MAX_BYTES` | `@intecion/ipal-kit` | An image fetched the way an anonymous visitor gets it (no cookies; http(s) only; `image/*`; at most 512 KB, reading stops at the limit) as `{ bytes, type }` or a `data:` address, else `null`. Used for the logo and icon on the 2FA screens. `rasterImageType(bytes)` → the media type of a bitmap by its first bytes (PNG, JPEG, GIF, WebP, ICO, AVIF) or `null` — never trust a claimed type before answering a file's bytes from the site's origin; an SVG gives `null`. |
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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.
|
||||
|
||||
+35
-5
@@ -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 === '[email protected]'`, 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/<own id>` 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`
|
||||
@@ -612,7 +636,11 @@ request came in on (`Host`, `X-Forwarded-Host`), `serverURL`, Payload's `csrf` a
|
||||
`twoFactor: { …, sameOrigin: { origins: ['https://app.example.com'] } }` for a front end on another domain.
|
||||
A request with neither header (a script, `curl`, a server) passes: it cannot ride on somebody's cookie.
|
||||
A default port written out (`X-Forwarded-Host: site.example:443`) is the same host.
|
||||
`sameOrigin: false` turns it off.
|
||||
**The admin's reset** (`POST /api/ipal/two-factor/reset`, "Reset two-step verification" / "Reopen setup") follows
|
||||
the same rule since 1.17.1: it reads a `text/plain` body, which a foreign page can send without a CORS preflight,
|
||||
so before a page on a sibling subdomain could reset any account's TOTP and end its sessions with an admin's
|
||||
cookie. The panel's own button is on the site's origin and is not affected.
|
||||
`sameOrigin: false` turns it off (verify, setup and the reset).
|
||||
|
||||
**Behind a reverse proxy that hides the site's address** — it rewrites `Host` and sends no `X-Forwarded-Host`
|
||||
(nginx's plain `proxy_pass`; Traefik and Coolify keep `Host`) — and without `serverURL`, the server cannot know
|
||||
@@ -1084,7 +1112,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`
|
||||
|
||||
+1
-1
@@ -262,5 +262,5 @@ full control or have an unusual case. The provider is a convenience layer over i
|
||||
- **Access to the keys:** Site integrations is admin-only (read and update); change it with
|
||||
`iapl({ globalOverrides: { 'site-integrations': { access: … } } })` — keep `read` restricted, the secret lives there.
|
||||
- **Look:** `theme` on `<Turnstile>` / `<TurnstileWidget theme>`, `turnstileTheme` in `RenderForm` / `BuilderForm`.
|
||||
- **Your own integration:** `checkTurnstile` (full `pass` / `reject` / `degraded` classification),
|
||||
- **Your own integration:** limit first, then ask Cloudflare — `consumeRateLimit({ key: clientIp(req), scope: 'signup' })` before `checkTurnstile`, so a flood of posts does not become a flood of requests to Cloudflare (the plugin's forms do it in this order: `passRateLimit`, then `passTurnstile`). `checkTurnstile` (full `pass` / `reject` / `degraded` classification),
|
||||
`verifyTurnstile`, `getTurnstileConfig`, `<Turnstile>`, `useTurnstile` / `useOptionalTurnstile`.
|
||||
|
||||
@@ -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ć?',
|
||||
|
||||
@@ -389,6 +389,11 @@ export type TotpEndpointGuards = {
|
||||
* (sameOrigin.ts). False = refused, and NOT counted against the verify limit.
|
||||
*/
|
||||
ownOrigin?: (req: never) => boolean
|
||||
/**
|
||||
* 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> | void
|
||||
}
|
||||
|
||||
export function guardTotpEndpoint<T extends EndpointLike>(endpoint: T, collection: string, guards: TotpEndpointGuards = {}): T {
|
||||
@@ -413,6 +418,16 @@ export function guardTotpEndpoint<T extends EndpointLike>(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'],
|
||||
|
||||
@@ -240,6 +240,14 @@ export type TwoFactorResetOptions = {
|
||||
* if you return true for it (`req.user._strategy` tells them apart).
|
||||
*/
|
||||
access?: (args: { req: PayloadRequest }) => boolean | Promise<boolean>
|
||||
/**
|
||||
* Whether the request may come from where the browser says it comes from (sameOrigin.ts). False =
|
||||
* refused (403) before anything is read or changed. The plugin passes the `twoFactor.sameOrigin` rule
|
||||
* (on by default; `sameOrigin: false` leaves it out). Without it the endpoint takes a cross-origin
|
||||
* `text/plain` POST — no CORS preflight — so a page on a sibling subdomain, which the browser sends the
|
||||
* admin's `SameSite=Lax` cookie to, could reset any account's TOTP and end its sessions.
|
||||
*/
|
||||
ownOrigin?: (req: PayloadRequest) => boolean
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -267,6 +275,7 @@ export function buildTwoFactorResetEndpoint(collection: string, options: TwoFact
|
||||
? (await options.access({ req })) === true
|
||||
: (req.user as { _strategy?: unknown })._strategy === 'totp' && userMeetsRole(req, 'admin'))
|
||||
if (!allowed) {return Response.json({ message: serverText(i18n, 'twoFactorResetForbidden'), ok: false }, { status: 403 })}
|
||||
if (options.ownOrigin && !options.ownOrigin(req)) {return Response.json({ message: 'Not allowed from this origin.', ok: false }, { status: 403 })}
|
||||
let body: unknown
|
||||
try {
|
||||
body = await req.json?.()
|
||||
|
||||
@@ -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<string, Bucket>()
|
||||
/** Attempts let through and not settled yet, per bucket key: when each started. Older than IN_FLIGHT_MS = wrong. */
|
||||
const inFlight = new Map<string, number[]>()
|
||||
/** 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<object, Place>()
|
||||
|
||||
/** 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<unknown>; set: (key: string, value: object) => Promise<void> }
|
||||
@@ -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<void> {
|
||||
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<void>
|
||||
|
||||
export function buildVerifyLimit(collection: string, options: VerifyLimitOptions = {}): ((req: PayloadRequest) => Promise<null | Response>) & { 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<null | Response> => {
|
||||
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<null | Response> => {
|
||||
// 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 })
|
||||
}
|
||||
|
||||
+2
-2
@@ -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
|
||||
? {}
|
||||
: {
|
||||
@@ -394,7 +394,7 @@ export const iapl = (options: IaplOptions): Plugin => {
|
||||
}
|
||||
}
|
||||
// An admin resets an account's TOTP (lost phone) / reopens its setup window.
|
||||
config.endpoints = [...(config.endpoints ?? []), buildTwoFactorResetEndpoint(target, { access: tf.resetAccess })]
|
||||
config.endpoints = [...(config.endpoints ?? []), buildTwoFactorResetEndpoint(target, { access: tf.resetAccess, ...(guards.ownOrigin ? { ownOrigin: guards.ownOrigin } : {}) })]
|
||||
// Called by Payload on every request before any access function: guards whatever
|
||||
// the live config has that was added after iapl (start, dev hot reload).
|
||||
const sweep = buildGuardStrategy(adoptConfig)
|
||||
|
||||
@@ -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<string, string>) } })
|
||||
|
||||
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: '[email protected]', 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: '[email protected]', 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 unknown 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: '[email protected]' }), method: 'PATCH' })
|
||||
expect(res.status).toBe(200)
|
||||
const stored = (await payload.findByID({ id: editorId, collection: 'users' as never, overrideAccess: true })) as unknown as { email: string }
|
||||
expect(stored.email).toBe('[email protected]')
|
||||
})
|
||||
})
|
||||
@@ -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()
|
||||
|
||||
@@ -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) => ({
|
||||
|
||||
@@ -0,0 +1,22 @@
|
||||
/** POST /api/ipal/two-factor/reset only from the own origin (1.17.1): twoFactorResetOriginSuite.ts. */
|
||||
import { describe, expect, test, vi } from 'vitest'
|
||||
|
||||
import { clearReportedOrigins } from '../src/modules/security/totp/sameOrigin.js'
|
||||
import { SECRET_VALUE, SIBLING, site } from './twoFactorResetOriginSuite.js'
|
||||
|
||||
vi.mock('server-only', () => ({}))
|
||||
vi.mock('next/headers.js', async () => (await import('./http/server.js')).nextHeadersMock)
|
||||
|
||||
describe('the 2FA reset endpoint and the origin of the request', () => {
|
||||
test('a page on a sibling subdomain is refused and nothing changes; the site itself still resets', async () => {
|
||||
clearReportedOrigins()
|
||||
const { reset, secretOf, server } = await site()
|
||||
expect((await reset(SIBLING)).status).toBe(403)
|
||||
expect(await secretOf()).toBe(SECRET_VALUE)
|
||||
expect((await reset({ 'sec-fetch-site': 'cross-site' })).status).toBe(403)
|
||||
expect(await secretOf()).toBe(SECRET_VALUE)
|
||||
const own = await reset({ origin: server.url, 'sec-fetch-site': 'same-origin' })
|
||||
expect([own.status, ((await own.json()) as { ok?: boolean }).ok]).toEqual([200, true])
|
||||
expect(await secretOf()).toBeNull()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,15 @@
|
||||
/** twoFactor.sameOrigin: false leaves the origin check of the 2FA reset endpoint out (twoFactorResetOriginSuite.ts). */
|
||||
import { describe, expect, test, vi } from 'vitest'
|
||||
|
||||
import { SIBLING, site } from './twoFactorResetOriginSuite.js'
|
||||
|
||||
vi.mock('server-only', () => ({}))
|
||||
vi.mock('next/headers.js', async () => (await import('./http/server.js')).nextHeadersMock)
|
||||
|
||||
describe('the 2FA reset endpoint with sameOrigin: false', () => {
|
||||
test('a request from a sibling subdomain is taken, as before 1.17.1', async () => {
|
||||
const { reset, secretOf } = await site(false)
|
||||
expect((await reset(SIBLING)).status).toBe(200)
|
||||
expect(await secretOf()).toBeNull()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,66 @@
|
||||
/**
|
||||
* POST /api/ipal/two-factor/reset only from the site's own origin (1.17.1). The endpoint reads a `text/plain` body
|
||||
* as JSON, and such a cross-origin POST needs no CORS preflight; a page on a sibling subdomain is "same site", so the
|
||||
* browser sends the admin's `SameSite=Lax` cookie, and Payload's CSRF list is empty without `serverURL` / `csrf`.
|
||||
* Before, that page could reset any account's TOTP and end its sessions. Through real HTTP requests.
|
||||
* Shared by twoFactorResetOrigin.test.ts and twoFactorResetOriginOff.test.ts (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 } 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'
|
||||
|
||||
const SECRET = 'JBSWY3DPEHPK3PXP'
|
||||
const PASSWORD = 'a-long-test-password-1'
|
||||
export const SIBLING = { origin: 'https://blog.site.example', 'sec-fetch-site': 'same-site' }
|
||||
const opened: Array<{ payload: Payload; server: TestServer }> = []
|
||||
|
||||
export async function site(sameOrigin?: false) {
|
||||
const config = buildTestConfig({
|
||||
admin: { user: 'users' },
|
||||
collections: [{ slug: 'media', fields: [], upload: { staticDir: '/tmp/iapl-reset-origin-media' } }],
|
||||
db: testDatabase(`resetorigin${sameOrigin === false ? 'off' : ''}`),
|
||||
editor: lexicalEditor(),
|
||||
plugins: [
|
||||
iapl({
|
||||
access: { authCollection: 'users' },
|
||||
i18n: { defaultLocale: 'en', locales: [{ code: 'en', label: 'English' }] },
|
||||
twoFactor: { issuer: 'Example', plugin: payloadTotp, ...(sameOrigin === false ? { sameOrigin } : {}) },
|
||||
}),
|
||||
],
|
||||
secret: 'integration-test-secret-0123456789',
|
||||
telemetry: false,
|
||||
})
|
||||
const payload = await getPayload({ config })
|
||||
const server = await startPayloadServer(config)
|
||||
opened.push({ payload, server })
|
||||
await payload.create({ collection: 'users' as never, data: { email: '[email protected]', password: PASSWORD, roles: ['admin'], totpSecret: SECRET } as never })
|
||||
const target = (await payload.create({ collection: 'users' as never, data: { email: '[email protected]', password: PASSWORD, roles: ['editor'], totpSecret: SECRET } as never })) as { id: number | string }
|
||||
const login = await fetch(`${server.url}/api/users/login`, { body: JSON.stringify({ email: '[email protected]', password: PASSWORD }), headers: { 'content-type': 'application/json' }, method: 'POST' })
|
||||
const first = cookiesOf(login)
|
||||
const verify = await fetch(`${server.url}/api/verify-totp`, { body: JSON.stringify({ token: totp(SECRET) }), headers: { 'content-type': 'application/json', cookie: first.join('; ') }, method: 'POST' })
|
||||
const cookie = [...first, ...cookiesOf(verify)].join('; ')
|
||||
// what a foreign page can send without a preflight: text/plain
|
||||
const reset = (headers: Record<string, string>) =>
|
||||
fetch(`${server.url}/api/ipal/two-factor/reset`, { body: JSON.stringify({ userId: target.id }), headers: { 'content-type': 'text/plain', cookie, ...headers }, method: 'POST' })
|
||||
const secretOf = async () =>
|
||||
((await payload.findByID({ id: target.id, collection: 'users' as never, overrideAccess: true, showHiddenFields: true })) as { totpSecret?: null | string }).totpSecret ?? null
|
||||
return { reset, secretOf, server }
|
||||
}
|
||||
|
||||
export const SECRET_VALUE = SECRET
|
||||
afterAll(async () => {
|
||||
for (const { payload, server } of opened) {
|
||||
await server.close()
|
||||
await payload.destroy?.()
|
||||
}
|
||||
})
|
||||
@@ -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 ['[email protected]', '[email protected]', '[email protected]']) {
|
||||
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('[email protected]'))
|
||||
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('[email protected]'))}
|
||||
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('[email protected]'))
|
||||
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('[email protected]')
|
||||
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('[email protected]'))
|
||||
expect([res.status, ((await res.json()) as { ok?: boolean }).ok]).toEqual([200, false])
|
||||
}
|
||||
const locked = await post('/verify-totp', { token: totp(SECRET) }, await passwordStep('[email protected]'))
|
||||
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: '[email protected]' } } })).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)
|
||||
})
|
||||
})
|
||||
Reference in New Issue
Block a user