Merge claude/security-a-1172: a locked staff account answers like a wrong password, IPv6 counted per /64, panel actions only from the site's own origin

plugin.ts import conflict: withVersionReadRules (readPublished fix) and withLockedAnswer both kept.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
Radosław Smoliński
2026-12-01 11:06:15 +01:00
co-authored by Claude Opus 5.5
35 changed files with 882 additions and 31 deletions
+21 -1
View File
@@ -266,6 +266,7 @@ iapl({
// accounts: { firstUserRoute: 'all' }, // Payload's first-user route for every empty auth collection
// accounts: { firstUserRoute: ['users', 'partners'] },
// accounts: { password: { minLength: 16 } }, // or password: false
// accounts: { lockedAnswer: 'payload' }, // a locked staff account is told it is locked (Payload's answer)
// accounts: false, // none of the rules
})
```
@@ -493,10 +494,29 @@ characters."; texts `passwordTooShort`, `passwordIsEmail` in `i18n.translations.
`DEFAULT_PASSWORD_MIN_LENGTH`.
- **Check:** create an account with an 11-character password → "The password must have at least 12 characters.".
### A locked staff account answers like a wrong password (`accounts.lockedAnswer`, 1.17.2)
Payload locks an account after `maxLoginAttempts` wrong passwords (5 by default) for `lockTime` (10 minutes), and
it checks the lock **before** the password: the locked account then gets `401 "This user is locked due to having too
many failed login attempts."` for any password, while an address with no account always gets `401 "The email or
password provided is incorrect."`. Five wrong guesses told anybody, without a password, whether an address has a
staff account. Now a staff collection's login answers a locked account exactly like a wrong password — the same
status, body and GraphQL `extensions.name` (`AuthenticationError`) — over REST, GraphQL and the panel's sign-in
form. The lock itself is unchanged: the owner's correct password is still refused until it ends, and the owner is
then told "wrong e-mail or password" (an administrator sees `lockUntil` on the account and can unlock it). Visitor
collections (not staff) keep Payload's answer.
- **Turn off:** `accounts: { lockedAnswer: 'payload' }` (Payload's message), or `accounts: false`. Any other value
stops the start.
- **Building blocks:** `lockedLooksWrong` (the config-level `afterError` hook), `withLockedAnswer(config)`,
`graphqlLoginName(collection)` (`login<SingularName>`, as GraphQL names the mutation).
- **Check:** five wrong passwords for an admin's address, then `POST /api/users/login` with the right one → the same
`401` body as for `nobody@example.com`; GraphQL `loginUser` → `extensions.name: "AuthenticationError"`.
## Turn off, override, extend
- **Account rules:** `accounts: false`, or one by one — `panelRole`, `adminOnlyCreate`, `adminOnlyWrite`,
`staffOnlyRead`, `firstUserRoute`, `password` (above).
`staffOnlyRead`, `firstUserRoute`, `password`, `lockedAnswer` (above).
- **Turn off:** leave out `access` — no `roles` field, the auth collection keeps Payload's rules
(or yours). `access.firstUserAdmin: false` stops giving admin to the first account.
- **Override:** `access.staffCollections` (who is staff), `access.authAccess` (injected collection), your own auth collection (wins whole),
+3
View File
@@ -1227,11 +1227,13 @@ add missing hosts with flags / `extra`; (3) change `mode` to `'enforce'` in both
| 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 **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)` |
| The plugin's panel actions (`POST` mail service connect / disconnect, test e-mail, cookie scan / approval / crawl) refuse a request a browser marks as coming from another origin (`403`, before anything is read; 1.17.2). The panel's buttons are not affected; set `serverURL` (doctor `csrf-empty` warns without it). **Verify:** `curl -X POST <site>/api/ipal/test-email -H 'Origin: https://other.example' -H 'Content-Type: text/plain' -b <admin cookies> -d '{}'` → `403` | `adminSameOrigin: false` | `adminSameOrigin: { origins: [...] }`; `requireOwnOrigin(endpoint, origins?)` for your own endpoints |
| 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. A query cannot name a secret (1.17.1): `where` / `sort` on it — REST, GraphQL, versions — is refused (`secretReadAccess`, the field's `read` rule; verify: `GET /api/globals/site-integrations/versions?where[version.smtpPassword][exists]=true` as an admin → 400 `QueryError`, no `totalDocs`). **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)` |
| Nobody creates an account for themselves, or takes one over. A staff collection (also the project's own, also one a later plugin adds) without a `create` / `update` / `delete` / `unlock` / `read` / `readVersions` rule gets one (on a collection a later plugin adds the plugin's rule is put in front of its own and both must allow; `custom: { ipal: { accountRules: false } }` on it keeps its own): with the plugin's roles, or wherever an account of it can hold `editor` or `admin` (`user, editor, admin, boss`; `viewer, editor`; a `roles` field that is text, json or a relationship holding a list — the value in the account's `roles` array makes a plugin admin or editor; a single-valued `roles` field is not affected: its value never counts) — create, delete, unlock: an admin; update: an admin or the account itself; the `roles` field: only an admin. With roles of its own that hold neither `editor` nor `admin`, or none: an account of that same collection, or a plugin admin, and an account never changes its own roles — **the plugin cannot rank a project's own roles: write that collection's rules** (`iapl-doctor` → `staff-own-roles`). `read`: a staff account. Payload's first-user route answers only for the panel's login collection (the first account, which becomes admin), in any spelling of the URL. `access.firstUserAdmin: false` with a default role below the panel role: the default panel role is not applied (logged), an explicit one is refused at start. With a slug in `access.staffCollections` that is not an auth collection Payload does not start (`/api/health` 503) | `accounts: { adminOnlyCreate: false, adminOnlyWrite: false, staffOnlyRead: false, firstUserRoute: 'all' }` | your own rule wins; `firstUserRoute: ['users', 'partners']`; a collection with open sign-up keeps its routes; `staffCreateAccess`, `staffUpdateAccess(slug)`, `staffReadAccess`, `sameStaffCollectionAccess(slug)`, `rolesByAdminOnly`, `rolesNotOwn(slug)`, `hasPluginRoles`, `applyStaffAccountAccess`, `adoptLateAuthCollections`, `buildFirstUserEndpoint` |
| A locked staff account (Payload's `maxLoginAttempts`) answers its login exactly like a wrong password — REST body and status, GraphQL `extensions.name: AuthenticationError`, the panel's sign-in (1.17.2); visitor collections keep Payload's answer. **Verify:** 5 wrong passwords for an admin, then the right one → the same `401` body as for an unknown address | `accounts: { lockedAnswer: 'payload' }` | `lockedLooksWrong`, `withLockedAnswer(config)`, `graphqlLoginName` |
| A password set on a staff account has at least 12 characters and is not the e-mail address; existing passwords are not checked | `accounts: { password: false }` | `password: { minLength }`; `checkPassword`, `buildPasswordRuleHook` |
| While Turnstile cannot check (wrong secret, Cloudflare down): a text form is accepted, a form with files is refused | `forms: { turnstileOnConfigError: 'allow' }` | `'reject'`, `{ text, files }`; `turnstileOnConfigError` at a call site wins |
| Dashboard alerts by role: integration details for admins, a neutral line for editors, nothing for others; cookie alerts for editors and above. `'all'` checks nothing — no role, no second factor | `dashboardAlerts: { integrations: 'all', cookies: 'all' }` | `integrations: 'editor'`; the components' `details` / `audience` props |
@@ -1240,6 +1242,7 @@ add missing hosts with flags / `extra`; (3) change `mode` to `'enforce'` in both
| Roles count only for accounts of a staff collection, in every predicate and access function | — | `access.staffCollections` |
| `enabled: false` keeps the schema | — | — (no endpoints, `onInit` or admin components; no DROP TABLE in `migrate:create`) |
| No client IP = one shared `unknown-ip` bucket at 20× the limit | `setUnknownIpFactor(0)` (only with a limiter in front) | `setUnknownIpFactor(n)`; `UNKNOWN_IP_FACTOR` |
| IPv6 counted per /64 in every plugin limiter (1.17.2): one /64 = one client, `::ffff:a.b.c.d` = its IPv4; no /48 counter by default. **Verify:** 50 requests with `X-Real-IP: 2001:db8:1:1::<n>` → `429` after the limit | `setIpv6Grouping({ prefix: 128 })` (per address, as before) | `setIpv6Grouping({ prefix, wide: 48, wideFactor })`; `ipRateKey(ip)` for your own limiter (forms.md "IPv6 is counted per network") |
| Turnstile token domain not checked | (default) | `createSubmitAction({ turnstileHostnames })`, `verifyTurnstile({ hostnames })` — leave empty in dev |
| Consent Mode `advanced` | `consentMode: 'basic'` | your own `<Analytics>` props (`SiteProviders analytics={false}`) |
| Locale cookie: consent read under its own stored version | — | `createProxy(config, { policyVersion })` / `createLocaleMiddleware({ policyVersion })` |
+1
View File
@@ -1175,6 +1175,7 @@ Rules: AGENT.md §8a.
| `e2e/mail-relay.spec.ts` | the mail service on a built site: the state block in the panel, the first e-mail through the public confirm route, no token in anything the browser receives |
| `e2e/routes.snapshot.json` | every public route of the site (REST, GraphQL, Next route files) with one line saying who may use it and why — the judged list `routes:check` compares with |
| `e2e/routes.ts` | `routes:check`: the site's public routes against e2e/routes.snapshot.json (`pnpm payload run e2e/routes.ts [update]`; from the repository `pnpm routes:check`) (below) |
| `e2e/sign-in-answers.spec.ts` | built-site test (pnpm e2e:built, 1.17.2): a locked staff account gets the wrong-password answer over REST and GraphQL (accounts.lockedAnswer); the plugin's panel actions refuse another origin and take the site's own (adminSameOrigin) |
| `e2e/sign-in-look.spec.ts` | browser test of the sign-in look (whiteLabel.signIn): the panel comes with the form, sits above it on a phone in both themes, is on forgot / reset / logout too, the language links work, the 2FA code screen keeps its boxes (now named) |
| `e2e/smoke.spec.ts` | the smoke tests every release must pass: pages, showcase, forms (also a file sent by e-mail), sitemap, SEO/GEO, headers, consent, 2FA |
| `e2e/smtp-sink.ts` | a local mail sink for the smoke tests: reads what the site really sent (recipients, attachments) |
+2
View File
@@ -34,6 +34,8 @@ through this procedure. Ask only when you are missing something you cannot get y
### Build / TypeScript
| Symptom | Cause | Fix |
|---|---|---|
| a panel button (mail service Connect / Disconnect, Send test e-mail, cookie scan / approve / check site) answers `403` "Not allowed from this origin."; log `[iapl] a panel action from origin "…" was refused` | the request's origin is not one the site knows (1.17.2, `adminSameOrigin`): a reverse proxy that rewrites `Host` and sends no `X-Forwarded-Host`, and no `serverURL` | set `serverURL: process.env.NEXT_PUBLIC_SERVER_URL` in the Payload config, or make the proxy send `X-Forwarded-Host`, or `adminSameOrigin: { origins: ['https://…'] }`; `iapl-doctor` `csrf-empty` |
| a staff account's correct password gets "The email or password provided is incorrect." | the account is locked by Payload after `maxLoginAttempts` wrong passwords (5, for `lockTime`, 10 min); since 1.17.2 a locked staff account gets the wrong-password answer (`accounts.lockedAnswer`) | wait for the lock to end, or an admin unlocks it (the account in the panel, or `POST /api/users/unlock`); `lockUntil` on the account shows it. Payload's own message back: `accounts: { lockedAnswer: 'payload' }` |
| the 2FA code screen answers "Too many codes were tried…" (`429` from `/api/verify-totp`) | more than 5 wrong codes for that account in 10 minutes (`twoFactor.verifyLimit`; right codes do not count since 1.17.1). "…being checked right now. Try again in a moment." (`Retry-After: 2`) = several attempts of one account at the same moment, nothing is locked; repeated lines `[iapl] 2FA: too many verify attempts` in the log without the owner trying = someone has the password | wait for the window, enter the current code once; unexplained attempts: change that account's password. Tests that log in often: `verifyLimit: { max: … }` for that environment |
| `isAdmin(req.user)` says `false` for a real administrator on the server, in a process that loads two Payload configs (tests, a multi-site script) | a call without a source counts only collections that are staff in **every** config of the process | pass the source: `isAdmin(req.user, req.payload)` — with it each config gets its own answer |
| `isAdmin(user)` / `isEditor(user)` is always `false` in a client component or in `proxy.ts` | the staff collections are not known there (no config in the browser bundle / middleware), and the predicates fail closed | `isAdmin(user, config)` with `useConfig()`, imported from `@intecion/ipal-kit/client`; in middleware `isAdmin(user, { staffCollections: ['users'] })` |
@@ -38,10 +38,12 @@ description: Complete map of everything @intecion/ipal-kit provides — every ia
| `accounts.staffOnlyRead` | on | `read` and `readVersions` on a staff collection without those rules: a fully signed-in account of a staff collection (Payload's default let a visitor account list the staff accounts) | `false` = Payload's default; a `read` rule you wrote wins |
| `accounts.firstUserRoute` | `'panel'` | which auth collections `POST /api/<slug>/first-register` answers for while they are empty: only the one the panel logs in with (the first account of a site → admin). Others get `403`, a second staff collection included, in any spelling of the URL (the plugin's own endpoint sits in front of Payload's); a collection whose own `create` allows an anonymous request keeps its route. With `access.firstUserAdmin: false` and a default role below the panel role, the default `panelRole` is not applied (logged) and an explicit one is refused at start | a list of slugs; `'all'` = Payload's behaviour |
| `accounts.password` | `{ minLength: 12 }` | when a password is SET on a staff collection (create, first-user screen, change, reset by e-mail; panel, API and Local API): at least `minLength` characters, not the account's e-mail address. Existing passwords are never checked — a shorter one keeps logging in | `{ minLength }`; `false` = Payload's rule (3 characters) |
| `accounts.lockedAnswer` | `'wrong'` (1.17.2) | a staff account Payload has locked (too many wrong passwords) gets exactly the wrong-password answer on login (REST, GraphQL, the panel): nobody tells which addresses have an account; the lock itself is unchanged | `'payload'` = Payload's "This user is locked…"; any other value stops the start |
| `secrets.writeOnly` | on | `smtpPassword` and `turnstileSecretKey` (Site integrations) are never returned: REST, GraphQL and the panel get `'********'` when a value is stored; a save with nothing / empty / the mask keeps it, a new value replaces it, `'[[clear]]'` removes it; the Local API with access control off reads the real value. The panel is the source of these secrets — no env variable. A restore of a version is masked too | `false` = returned to whoever may read the global, as before |
| "Sending method" (`emailMethod`; `getMailMethod` / `setMailMethod`) | nobody has chosen: the order of 1.17.0, shown as selected | `relay` (IWSN), `smtp`, `graph` (deprecated): what is chosen is what is used, no fallback; a stored field (Postgres / SQLite: one migration) |
| `secrets.reenterOnChange` | on | a save through access control that changes `smtpHost`, `smtpPort` or `smtpUser` while a password is stored must send the password again or remove it (`400` on the field otherwise), whatever `emailTransport` says — so an admin session cannot send the stored password to a server of its own. A change of the transport alone, and the Local API with access control off, are not asked | `false` = the stored password follows the new server |
| `dashboardAlerts` | `{ integrations: 'admin', cookies: 'editor' }` | who sees the plugin's dashboard alerts: integration details (error text, link) for `integrations` and above, a neutral "ask an administrator" for editors below it, nothing for others; the cookie crawl / approval alert for `cookies` and above. With a role, a session that owes its second factor sees none | `integrations: 'editor' | 'all'`, `cookies: 'all'` (`'all'` = as before: no role and no second factor is checked) |
| `adminSameOrigin` | on (1.17.2) | `POST` mail service connect / disconnect, test e-mail, cookie scan / approval / crawl refuse (`403`) a request a browser marks as coming from another origin; own origins: the request's host, `serverURL`, `csrf`, `cors`, `origins` | `{ origins: [...] }` adds origins; `false` = no check; any other value stops the start |
| `adminRoute` | `'/admin'` | `config.routes.admin`; stats link and views, `IntegrationAlerts` | the project moves `app/(payload)/<route>/` itself and adds the route to the proxy matcher (security.md) |
| `twoFactor` | **none = error** | `@clocklimited/payload-2fa` with `forceSetup: true` (TOTP enforced, also checked in the API) | `twoFactor: false` (discouraged); omitting the option throws `[iapl] twoFactor.issuer is required` |
| `twoFactor.issuer` | — (required) | name in the authenticator app | — |
@@ -85,7 +85,10 @@ Admin panel components from `@intecion/ipal-kit/admin` — the project does NOT
| `buildRolesField(defaultRole?, { firstUserAdmin? })` | `@intecion/ipal-kit` | The `roles` select field the plugin injects (only admins set roles; `firstUserAdmin` default `true` = the account made on "Create first user" gets `admin`). The plugin wires it itself — use it only for an auth collection the plugin does not manage. |
| `injectRoles(config, accessOption)` | `@intecion/ipal-kit` | Adds `roles` to `accessOption.authCollection` in a config. The plugin calls it itself with `access` — do not call. |
**Types:** `AccountsOptions` (`accounts`: `panelRole`, `adminOnlyCreate`, `adminOnlyWrite`, `staffOnlyRead`, `firstUserRoute`, `password`), `StaffAccountAccessOptions` (`{ create?, write?, read?, pluginRoles? }`), `StaffRuleMark` (`{ slug, self }`), `AccountsMarker` (`{ slug, staff, own? }`, in `custom.ipalAccounts`; `own`: the operations that had a rule of the project's at config time, kept when the collection becomes staff later), `LateAdoption` (`{ slug, applied, kept, known, password, firstUser }`; `known`: in the config when iapl ran and staff only afterwards, `kept`: its operations whose own rule was left as written), `StaffAccountRules` (what the plugin put on a staff collection, in `custom.ipalAccountRules`: `{ applied, ownRoles }`), `WriteOnlySecretOptions` (`{ boundTo?, appliesWhen? }`), `PasswordRuleOptions` (`{ minLength? }`), `FirstUserRouteOption` (`'panel' \| 'all' \| string[]`), `TurnstileOnConfigError` / `TurnstileOnConfigErrorOption` / `TurnstileFormKind` (`@intecion/ipal-kit/server`), `VerifyLimitOptions` (`twoFactor.verifyLimit`: `{ max?, windowMinutes?, store? }`), `RequireSetupOptions` (`twoFactor.requireSetup`), `TwoFactorResetOptions`, `TwoFactorSetupState`, `SafeBackRule` / `SafeBackContext` (`twoFactor.safeBack` as a function: `(back, { adminRoute, origin? }) => string`), `TotpViewComponent` (a view component as registered: a path or `{ path, exportName?, clientProps?, serverProps? }`), `SafeTotpViewProps` (`@intecion/ipal-kit/admin`), `Role` (`'user' \| 'editor' \| 'admin'`), `AccessOption` (the plugin's `access` option: `authCollection`, `defaultRole`, `authAccess`, `firstUserAdmin`, `staffCollections`).
| `requireOwnOrigin(endpoint, origins?)`, `guardAdminEndpoints(config, projectEndpoints, option)`, `ADMIN_POST_ENDPOINTS`, type `AdminSameOriginOption` | `@intecion/ipal-kit` | `adminSameOrigin` (1.17.2): wraps an endpoint so a request a browser marks as coming from another origin gets `403` (logged once per origin); applies it to the plugin's panel actions it added; the list of `[method, path]` covered. `reportRefusedOrigin(req, origins?, { what, option, docs }?)` names your option in the log line. |
| `lockedLooksWrong`, `withLockedAnswer(config)`, `graphqlLoginName(collection)` | `@intecion/ipal-kit` | `accounts.lockedAnswer` (1.17.2): the config-level `afterError` hook that answers Payload's `LockedAuth` on a staff collection's login (REST, GraphQL) exactly like `AuthenticationError`; adding it to a config (idempotent); the GraphQL login mutation's name of a collection. |
**Types:** `AccountsOptions` (`accounts`: `panelRole`, `adminOnlyCreate`, `adminOnlyWrite`, `staffOnlyRead`, `firstUserRoute`, `password`, `lockedAnswer`), `LockedAnswerOption`, `StaffAccountAccessOptions` (`{ create?, write?, read?, pluginRoles? }`), `StaffRuleMark` (`{ slug, self }`), `AccountsMarker` (`{ slug, staff, own? }`, in `custom.ipalAccounts`; `own`: the operations that had a rule of the project's at config time, kept when the collection becomes staff later), `LateAdoption` (`{ slug, applied, kept, known, password, firstUser }`; `known`: in the config when iapl ran and staff only afterwards, `kept`: its operations whose own rule was left as written), `StaffAccountRules` (what the plugin put on a staff collection, in `custom.ipalAccountRules`: `{ applied, ownRoles }`), `WriteOnlySecretOptions` (`{ boundTo?, appliesWhen? }`), `PasswordRuleOptions` (`{ minLength? }`), `FirstUserRouteOption` (`'panel' \| 'all' \| string[]`), `TurnstileOnConfigError` / `TurnstileOnConfigErrorOption` / `TurnstileFormKind` (`@intecion/ipal-kit/server`), `VerifyLimitOptions` (`twoFactor.verifyLimit`: `{ max?, windowMinutes?, store? }`), `RequireSetupOptions` (`twoFactor.requireSetup`), `TwoFactorResetOptions`, `TwoFactorSetupState`, `SafeBackRule` / `SafeBackContext` (`twoFactor.safeBack` as a function: `(back, { adminRoute, origin? }) => string`), `TotpViewComponent` (a view component as registered: a path or `{ path, exportName?, clientProps?, serverProps? }`), `SafeTotpViewProps` (`@intecion/ipal-kit/admin`), `Role` (`'user' \| 'editor' \| 'admin'`), `AccessOption` (the plugin's `access` option: `authCollection`, `defaultRole`, `authAccess`, `firstUserAdmin`, `staffCollections`).
## Accessibility — widget (`accessibility`) — details: `node_modules/@intecion/ipal-kit/docs/accessibility.md`
@@ -744,6 +747,7 @@ Most routes and metadata are already ready in `createContentHelpers` (`generateP
| `setRateLimitStore(store \| null)` | `@intecion/ipal-kit` | Shared store (e.g. Redis) for all plugin limiters (forms, consents, MCP…); `null` = process memory. Call once at startup when several instances run. |
| `setUnknownIpFactor(n)` | `@intecion/ipal-kit` | Requests with no client IP share one `unknown-ip` bucket with `n` × the limit (every plugin limiter). Call once at startup; `0` = unlimited (only with a limiter in front, e.g. Cloudflare). |
| `UNKNOWN_IP_FACTOR` | `@intecion/ipal-kit` | `20` — the default factor of the no-IP bucket. |
| `setIpv6Grouping({ prefix?, wide?, wideFactor? })`, `ipRateKey(ip)`, type `Ipv6Grouping` | `@intecion/ipal-kit` | 1.17.2: how every plugin limiter counts IPv6 — default one client per /64 (`prefix: 64`), no wide counter; `wide: 48` adds a counter per /48 at `wideFactor` (10) × the limit; `prefix: 128` = per address. Out-of-range values throw. `ipRateKey`: an IPv4 as it is, `::ffff:a.b.c.d` as the IPv4, an IPv6 as its network (`2001:db8:1:2:0:0:0:0/64`), anything else unchanged. |
**Types:** `ClientIpOptions` — `clientIp` options; `RateLimitStore` — store contract (`hit(id, cost, windowMs)` → `{ count, resetAt }`).
+1 -1
View File
@@ -106,7 +106,7 @@ Turn off: `iapl({ doctor: false })`. Adapt: `iapl({ doctor: { tokenVar: 'MY_TOKE
| | `csp` | warning / info | CSP on the site and the admin; report-only is info, a warning after 4 weeks (`seen`) |
| | `2fa` | error | `twoFactor: { plugin: payloadTotp }` + the package; deep: 0 users without TOTP (the message says how many of them are blocked because their setup window has passed); error: a Postgres / SQLite project whose migrations do not mention the 2FA column `totp_setup_from` (every login would answer 500; a warning when there is no migrations folder — the doctor cannot see a schema that gets there another way); warning: `twoFactor.requireSetup: false`; info: no setup window (`windowHours: false`) |
| | `access-missing` | warning | `iapl` has an `access` option — without it there are no roles and every panel account is an admin |
| | `csrf-empty` | warning | the config sets `serverURL` or `csrf` — otherwise Payload accepts the login cookie from any origin |
| | `csrf-empty` | warning | the config sets `serverURL` or `csrf` — otherwise Payload accepts the login cookie from any origin, and behind a proxy that rewrites `Host` the plugin's own-origin checks (2FA, panel actions) refuse the site's own panel. With `--url` (deep) the running config decides (`originKnown` in the status), not the file |
| | `open-signup` | info | (deep) auth collections whose `create` rule lets an anonymous request through: sign-up is open there (intended for a customer zone — silence with a reason) |
| | `staff-own-roles` | warning | (deep) a staff collection with role values of its own, neither `editor` nor `admin` among them, that runs on the plugin's default account rules: the plugin cannot rank those roles, so inside the collection every account may create an account with any role and change or delete another. Write the collection's own rules |
| | `staff-accounts-open` | error (warning for `read`, `readVersions`) | (deep) a staff collection that an account of another, non-staff auth collection may create in, read (also its versions), update, delete from or unlock — it can make itself staff, change a staff password, list the accounts or lift a login lock. The account rules are off (`accounts: false`, `adminOnlyCreate` / `adminOnlyWrite` / `staffOnlyRead: false`) or the project's own rule is wider. Asked with a made-up outside account; a rule that throws counts as closed |
+12
View File
@@ -436,6 +436,18 @@ A missing IP (the proxy strips the header, a wrong `IAPL_IP_HEADER`) does **not*
share one `unknown-ip` bucket with a ×20 limit (`UNKNOWN_IP_FACTOR`) — real
visitors get through, a flood without the header does not. `setUnknownIpFactor(n)` (root, once at startup)
changes the multiplier; `setUnknownIpFactor(0)` = the old behaviour (no limit), when a limiter sits in front.
**IPv6 is counted per network (1.17.2).** A host with IPv6 holds a whole /64 — 2^64 addresses, every home
connection and every server — so counting per address gave one visitor as many budgets as it had addresses. Every
limiter of the plugin (forms, the file upload endpoint, search, MCP, the consent log, stats, the doctor status, the
mail service's confirm route and account-mail limit) counts a **/64 as one client**; an IPv4-mapped address
(`::ffff:1.2.3.4`) counts as its IPv4. One home network shares the budget, as an IPv4 home behind one router always
did. Change it once at start (root export): `setIpv6Grouping({ prefix: 128 })` = per address (as before);
`setIpv6Grouping({ prefix: 56 })` another network size; `setIpv6Grouping({ wide: 48, wideFactor: 10 })` adds a
second counter per /48 at 10× the limit (a hosting customer often holds a /48 — off by default, because a mobile
carrier can put many phones in one /48). A value out of range throws. `ipRateKey(ip)` gives the key a limiter of
your own should count by (`consumeRateLimit` already applies it to a key that is an IP address).
**Check:** fifty requests to a limited route with `X-Real-IP: 2001:db8:1:1::1` … `::32` → `429` after the limit.
Without a pinned header the order
`cf-connecting-ip` → `x-real-ip` → XFF stays (switching to XFF-only, from the right, would put every visitor
behind Cloudflare into the bucket of the edge node) — that is why `IAPL_IP_HEADER` is mandatory in production
+34
View File
@@ -419,6 +419,40 @@ Real panel protection:
`/admin → /its` is a layer (it filters out dumb bots), not a lock. Treat it as an
addition to real safeguards, not a replacement for them.
## Panel actions only from the site's own origin (`adminSameOrigin`, 1.17.2)
The plugin's panel actions act with the panel's login cookie and read their body whatever its `Content-Type`
says: `POST /api/iapl/mail-relay/connect` and `/disconnect` (the mail service), `/api/ipal/test-email`,
`/api/ipal/cookie-scan`, `/api/ipal/cookie-approval`, `/api/ipal/cookie-crawl`. A `text/plain` POST needs no CORS
preflight, a page on a sibling subdomain is "same site" (the browser sends the `SameSite=Lax` cookie), and
Payload's own CSRF list is empty unless `serverURL` or `csrf` is set. So before 1.17.2 such a page could make a
signed-in administrator disconnect the mail service, send test mails, run scans and crawls, or approve every
waiting cookie. Now each of them refuses (`403`, before anything is read) a request a browser marks as coming
from elsewhere — the same rule as the 2FA endpoints: the `Origin` header, else `Sec-Fetch-Site`. Own origins: the
host the request came in on (`Host`, `X-Forwarded-Host`), `serverURL`, Payload's `csrf` and `cors` lists, and
`adminSameOrigin.origins`. A request with neither header (a script, `curl`, a server) passes: it rides on nobody's
cookie. The panel's own buttons are on the site's origin and are not affected. A project's own endpoint on one of
these paths is left as it is. The 2FA endpoints keep their own switch (`twoFactor.sameOrigin`).
```ts
iapl({
// adminSameOrigin: { origins: ['https://panel.example.com'] }, // the panel served from another origin
// adminSameOrigin: false, // no check (as before 1.17.2)
})
```
- **Behind a proxy that rewrites `Host`** and sends no `X-Forwarded-Host`, without `serverURL`, the site's own
panel buttons are refused. It is not silent: the first refusal of each origin is logged
(`[iapl] a panel action from origin "…" was refused … pass iapl({ adminSameOrigin: { origins: [...] } })`), and
`iapl-doctor` warns when the running config has neither `serverURL` nor `csrf` (`csrf-empty`). Set
`serverURL: process.env.NEXT_PUBLIC_SERVER_URL`.
- **Any other value** than `true`, `false` or an object with `origins` (a list of strings) stops the start.
- **Building blocks:** `requireOwnOrigin(endpoint, origins?)` for an endpoint of your own,
`guardAdminEndpoints(config, projectEndpoints, option)`, `ADMIN_POST_ENDPOINTS` (the list), and the 2FA ones:
`requestFromOwnOrigin`, `ownOrigins`, `reportRefusedOrigin(req, origins?, { what, option, docs }?)`.
- **Check:** `curl -X POST <site>/api/ipal/test-email -H 'Origin: https://other.example' -H 'Content-Type: text/plain'
-b <admin cookies> -d '{"to":"a@example.com"}'` → `403`; "Send test e-mail" in the panel still works.
## 2FA (TOTP) — ENFORCED for every user
The plugin enforces two-factor authentication (TOTP) for ALL panel users —
+59
View File
@@ -0,0 +1,59 @@
import { type APIRequestContext, expect, test } from '@playwright/test'
import { randomUUID } from 'node:crypto'
import { totp } from './totp'
/**
* On the BUILT site (pnpm e2e:built, webpack and Turbopack), what 1.17.2 changed at the sign-in and in the panel:
* - a locked staff account answers its login exactly like a wrong password (accounts.lockedAnswer) — the hook
* recognises Payload's error by the name Payload gives it, which a minified bundle must keep;
* - the plugin's panel actions refuse a request from another origin (adminSameOrigin), the site's own still works.
* Needs the E2E_* test admin (e2e/create-test-admin.ts). The locked account is a fresh one made here, so the test
* admins are never locked.
*/
const { E2E_ADMIN_EMAIL: adminEmail, E2E_ADMIN_PASSWORD: password, E2E_TOTP_SECRET: secret } = process.env
let admin: APIRequestContext
test.beforeAll(async ({ baseURL, playwright }) => {
test.skip(!adminEmail || !password || !secret, 'E2E_ADMIN_* values are not set')
admin = await playwright.request.newContext({ baseURL, extraHTTPHeaders: { origin: baseURL! } })
expect((await admin.post('/api/users/login', { data: { email: adminEmail, password } })).status()).toBe(200)
expect((await (await admin.post('/api/verify-totp', { data: { token: totp(secret!) } })).json()).ok).toBe(true)
})
test.afterAll(async () => {
await admin?.dispose()
})
test('a locked staff account gets the wrong-password answer, REST and GraphQL', async ({ baseURL, playwright }) => {
const email = `locked-${randomUUID().slice(0, 8)}@example.com`
const own = `L-${randomUUID()}`
expect((await admin.post('/api/users', { data: { email, password: own, roles: ['editor'] } })).status()).toBe(201)
const anon = await playwright.request.newContext({ baseURL })
const login = async (address: string, pass: string) => {
const res = await anon.post('/api/users/login', { data: { email: address, password: pass } })
return { body: await res.text(), status: res.status() }
}
for (let i = 0; i < 5; i++) {await login(email, 'a-wrong-password-1')}
const invented = await login(`nobody-${randomUUID().slice(0, 8)}@example.com`, 'a-wrong-password-1')
expect(invented.status).toBe(401)
expect(await login(email, own)).toEqual(invented)
const gql = async (address: string, pass: string) => {
const res = await anon.post('/api/graphql', { data: { query: `mutation { loginUser(email: ${JSON.stringify(address)}, password: ${JSON.stringify(pass)}) { token } }` } })
const error = ((await res.json()) as { errors?: { extensions?: { name?: string }; message: string }[] }).errors?.[0]
return { message: error?.message, name: error?.extensions?.name }
}
expect(await gql(email, own)).toEqual(await gql(`nobody-${randomUUID().slice(0, 8)}@example.com`, 'x-wrong-password-1'))
await anon.dispose()
})
test('panel actions: another origin gets 403 with the admin cookie, the site itself goes through', async ({ baseURL }) => {
const foreign = await admin.fetch('/api/ipal/cookie-approval', {
data: '{"ids":[]}',
headers: { 'content-type': 'text/plain', origin: 'https://blog.example.test', 'sec-fetch-site': 'same-site' },
method: 'POST',
})
expect(foreign.status()).toBe(403)
const own = await admin.fetch('/api/ipal/cookie-approval', { data: '{"ids":[]}', headers: { 'content-type': 'text/plain', origin: baseURL! }, method: 'POST' })
expect(own.status()).toBe(200)
})
+4 -2
View File
@@ -14,7 +14,9 @@
* route under Next, the state block in the panel's production bundle) and the smoke tests "no package.json is published",
* "client hints" (Payload's colour-scheme headers on the admin only; a public page is requested once), every
* "consent" test (banner at first paint, Global Privacy Control, equal prominence, withdrawal, the consent log)
* and e2e/sign-in-look.spec.ts (the sign-in panel in the first HTML, on a phone, the language links, the 2FA screen).
* and e2e/sign-in-look.spec.ts (the sign-in panel in the first HTML, on a phone, the language links, the 2FA screen),
* e2e/sign-in-answers.spec.ts (1.17.2: a locked staff account answers like a wrong password; the panel actions refuse
* another origin).
*
* Needs what the reference site's "Production check" needs (reference/README.md): reference/.env with a local,
* seeded database and the E2E_* test admin. The test admins are reset by Playwright's global setup.
@@ -89,7 +91,7 @@ for (const bundler of bundlers) {
process.exit(1)
}
console.log(`[e2e:built] ✓ ${bundler}: no package manifest among ${files.length} public files`)
run(`${bundler}: the built site — late-staff spec, the mail service, closed doors, the published-files check, the client hints, consent and the sign-in look`, 'pnpm', ['exec', 'playwright', 'test', 'late-staff', 'mail-relay', 'closed-doors', 'smoke', 'sign-in-look', '--grep', 'late staff collection|the mail service|closed doors|no package.json is published|client hints|consent|sign-in look'], site, { ALLOW_LOCAL_MEDIA: process.env.ALLOW_LOCAL_MEDIA ?? '1', E2E_LATE_STAFF: '1' })
run(`${bundler}: the built site — late-staff spec, the mail service, closed doors, the published-files check, the client hints, consent, the sign-in look and the sign-in answers`, 'pnpm', ['exec', 'playwright', 'test', 'late-staff', 'mail-relay', 'closed-doors', 'smoke', 'sign-in-look', 'sign-in-answers', '--grep', 'late staff collection|the mail service|closed doors|no package.json is published|client hints|consent|sign-in look|locked staff account|panel actions'], site, { ALLOW_LOCAL_MEDIA: process.env.ALLOW_LOCAL_MEDIA ?? '1', E2E_LATE_STAFF: '1' })
passed.push(bundler)
}
console.log(`\n[e2e:built] passed: ${passed.join(' and ')}. (The reference site's .next now holds the ${passed.at(-1)} build WITH the fixture: rebuild with \`pnpm build\` there before other checks.)`)
+1
View File
@@ -71,6 +71,7 @@ export const DESCRIPTIONS = {
'e2e/mail-relay-setup.ts': 'for the mail-service spec: empties the SMTP fields and the stored token, so the next e-mail enrols and goes through the mail service (local database only)',
'e2e/mail-relay.spec.ts': 'the mail service on a built site: the state block in the panel, the first e-mail through the public confirm route, no token in anything the browser receives',
'e2e/smtp-sink.ts': 'a local mail sink for the smoke tests: reads what the site really sent (recipients, attachments)',
'e2e/sign-in-answers.spec.ts': 'built-site test (pnpm e2e:built, 1.17.2): a locked staff account gets the wrong-password answer over REST and GraphQL (accounts.lockedAnswer); the plugin\'s panel actions refuse another origin and take the site\'s own (adminSameOrigin)',
'e2e/sign-in-look.spec.ts': 'browser test of the sign-in look (whiteLabel.signIn): the panel comes with the form, sits above it on a phone in both themes, is on forgot / reset / logout too, the language links work, the 2FA code screen keeps its boxes (now named)',
'e2e/two-factor-back.spec.ts': 'browser test of the 2FA screens\' `back` link (twoFactor.safeBack): a prepared link — script or another host — ends on the admin root, an ordinary one is followed',
'e2e/routes.snapshot.json': 'every public route of the site (REST, GraphQL, Next route files) with one line saying who may use it and why — the judged list `routes:check` compares with',
+6 -1
View File
@@ -25,6 +25,8 @@ export {
userMeetsRole,
withVersionReadRules,
} from './modules/access/index.js'
export { graphqlLoginName, lockedLooksWrong, withLockedAnswer } from './modules/access/lockedAnswer.js'
export type { LockedAnswerOption } from './modules/access/lockedAnswer.js'
export { applyPanelRole, countBelowPanelRole, DEFAULT_PANEL_ROLE, panelAccess, resolvePanelRole } from './modules/access/panelRole.js'
export { applyPasswordRule, buildPasswordRuleHook, checkPassword, DEFAULT_PASSWORD_MIN_LENGTH, resolvePasswordRule } from './modules/access/passwordRule.js'
export type { PasswordRuleOptions } from './modules/access/passwordRule.js'
@@ -457,6 +459,8 @@ export {
writeOnlySecrets,
} from './modules/secrets/writeOnly.js'
export type { WriteOnlySecretOptions } from './modules/secrets/writeOnly.js'
export { ADMIN_POST_ENDPOINTS, guardAdminEndpoints, requireOwnOrigin } from './modules/security/adminSameOrigin.js'
export type { AdminSameOriginOption } from './modules/security/adminSameOrigin.js'
export {
adminClientHintSources,
buildAdminCsp,
@@ -571,7 +575,8 @@ export { applyCollectionOverride } from './modules/shared/collectionOverride.js'
export type { CollectionOverride } from './modules/shared/collectionOverride.js'
// Development addresses by pattern (no env): the built-in list and the matcher behind `developmentHosts`.
export { assertDevelopmentHosts, DEFAULT_DEVELOPMENT_HOSTS, isDevelopmentHost, matchDevelopmentHost } from './modules/shared/developmentHosts.js'
export { clientIp, setRateLimitStore, setUnknownIpFactor, UNKNOWN_IP_FACTOR } from './modules/shared/rateLimit.js'
export { clientIp, ipRateKey, setIpv6Grouping, setRateLimitStore, setUnknownIpFactor, UNKNOWN_IP_FACTOR } from './modules/shared/rateLimit.js'
export type { Ipv6Grouping } from './modules/shared/rateLimit.js'
export type { ClientIpOptions, RateLimitStore } from './modules/shared/rateLimit.js'
export { buildSlugField, toSlug } from './modules/slug/index.js'
export { STATS_SLUG } from './modules/stats/index.js'
+67
View File
@@ -0,0 +1,67 @@
import type { AfterErrorHook, Config, SanitizedCollectionConfig } from 'payload'
import { AuthenticationError, formatNames, toWords } from 'payload'
import { staffCollectionSlugs } from './predicates.js'
/**
* A locked staff account answers its login exactly like a wrong password (`accounts.lockedAnswer`, 1.17.2).
*
* Payload checks the lock BEFORE the password: after five wrong passwords for `owner@site` any password gets
* `401 "This user is locked due to having too many failed login attempts."` (GraphQL: `LockedAuth`), while an
* address that has no account always gets `401 "The email or password provided is incorrect."`. Anybody could
* tell which addresses have a staff account with no password at all (IAWL idea 6). This hook turns Payload's
* `LockedAuth` on a staff collection's login into the `AuthenticationError` answer — same status, same body, same
* GraphQL `extensions.name`. The price: the owner, while locked, is told "wrong e-mail or password" too.
*
* The lock itself is not touched (it still holds for `lockTime`). `accounts: { lockedAnswer: 'payload' }` keeps
* Payload's message. The error is recognised by its `name` (`'LockedAuth'`, a string Payload sets — not a function
* name, so a minified bundle keeps it) and by the collection: a staff collection only.
*/
export type LockedAnswerOption = 'payload' | 'wrong'
const isLocked = (error: unknown): boolean => (error as { name?: unknown } | null)?.name === 'LockedAuth'
/** The GraphQL login mutation's name of a collection, as @payloadcms/graphql builds it (`login${singularName}`). */
export function graphqlLoginName(collection: Pick<SanitizedCollectionConfig, 'graphQL' | 'slug'>): null | string {
const graphQL = collection.graphQL as { singularName?: string } | false | undefined
if (graphQL === false) {return null}
const singular = graphQL?.singularName ? toWords(graphQL.singularName, true) : formatNames(collection.slug).singular
return `login${singular}`
}
type T = ConstructorParameters<typeof AuthenticationError>[0]
/** The config-level `afterError` hook (REST and GraphQL). */
export const lockedLooksWrong: AfterErrorHook = (args) => {
const { collection, error, req } = args as { error: unknown; graphqlResult?: Record<string, unknown> } & Parameters<AfterErrorHook>[0]
const payload = req?.payload
if (!payload) {return}
const staff = staffCollectionSlugs(payload)
const wrong = new AuthenticationError(req.t as T)
// GraphQL: the error is wrapped (`originalError`), the collection only shows in the mutation's name.
const graphqlResult = (args as { graphqlResult?: { extensions?: Record<string, unknown>; path?: unknown[] } }).graphqlResult
if (graphqlResult) {
const original = (error as { originalError?: unknown }).originalError
if (!isLocked(original)) {return}
const field = Array.isArray(graphqlResult.path) ? graphqlResult.path[0] : undefined
const names = new Set((payload.config.collections ?? []).filter((c) => staff.includes(c.slug)).map(graphqlLoginName))
if (typeof field !== 'string' || !names.has(field)) {return}
return {
graphqlResult: {
...graphqlResult,
extensions: { ...graphqlResult.extensions, name: wrong.name, statusCode: wrong.status },
message: wrong.message,
},
} as never
}
if (!isLocked(error) || !collection || !staff.includes(collection.slug)) {return}
return { response: { errors: [{ message: wrong.message }] }, status: wrong.status } as never
}
/** Adds the hook to a config (idempotent). */
export function withLockedAnswer(config: Config): Config {
const own = config.hooks?.afterError ?? []
if (own.includes(lockedLooksWrong)) {return config}
return { ...config, hooks: { ...config.hooks, afterError: [...own, lockedLooksWrong] } }
}
+7
View File
@@ -49,6 +49,13 @@ export type AccountsOptions = {
* whose own `create` rule allows an anonymous request keeps its route.
*/
firstUserRoute?: 'all' | 'panel' | string[]
/**
* What a staff account that Payload has locked (too many wrong passwords) is told when it logs in.
* Default (1.17.2): exactly what a wrong password gets — same status, message and GraphQL error name — so
* nobody can find out which addresses have a staff account by locking them. The lock itself is unchanged.
* `'wrong'` = the default, said out loud. `'payload'` = Payload's own "This user is locked due to having too many failed login attempts."
*/
lockedAnswer?: 'payload' | 'wrong'
/**
* The lowest role that may open the admin panel. Default `'editor'`: an
* account that holds only `user` (the default role of a new account) sees
+9 -1
View File
@@ -202,11 +202,19 @@ export const securityRules: DoctorRule[] = [
{
// Payload accepts the login cookie from ANY origin while its `csrf` list is empty — and it is empty
// unless `csrf` or `serverURL` is set. A page on a sibling subdomain can then act with a panel user's cookie.
// The plugin's own-origin checks (2FA verify / setup / reset, the panel actions — 1.17.2) then know the site
// only from the request's Host: behind a proxy that rewrites it, the site's own panel would be refused.
id: 'csrf-empty',
check: (ctx) => {
const fix = "serverURL: process.env.NEXT_PUBLIC_SERVER_URL (Payload then trusts that origin only; the plugin's own-origin checks know the site's address), or csrf: ['https://<site>']"
const why = 'Payload accepts the login cookie from any origin (a risk when other applications share the domain), and behind a proxy that rewrites Host the plugin cannot tell the panel\'s own requests (2FA, panel actions) from foreign ones'
// deep (the running config) wins over reading the file: serverURL may come from a spread or a helper
if (ctx.deep && typeof ctx.deep.originKnown === 'boolean') {
return ctx.deep.originKnown ? [] : [{ fix, message: `the running config has neither \`serverURL\` nor \`csrf\`: ${why}`, severity: 'warning' }]
}
const code = cfg(ctx)
if (!/buildConfig\s*\(/.test(code) || /\bcsrf\s*:/.test(code) || /\bserverURL\s*:/.test(code)) {return []}
return [{ file: configFile(ctx) ?? 'payload.config.ts', fix: "serverURL: process.env.NEXT_PUBLIC_SERVER_URL (Payload then trusts that origin only), or csrf: ['https://<site>']", message: 'neither `serverURL` nor `csrf` is set: Payload accepts the login cookie from any origin (a risk when other applications share the domain)', severity: 'warning' }]
return [{ file: configFile(ctx) ?? 'payload.config.ts', fix, message: `neither \`serverURL\` nor \`csrf\` is set: ${why}`, severity: 'warning' }]
},
docs: 'docs/security.md',
group: 'security',
+3 -1
View File
@@ -111,7 +111,9 @@ export async function collectDoctorStatus(payload: BasePayload): Promise<DoctorS
} catch {
staffOnOwnRoles = null
}
return { mail, node: process.version, openSignUp, pendingCookies, plugin: pluginVersion(), staffOnOwnRoles, staffOpenToOthers, turnstile, turnstileSecretFromEnv: secretFromEnv, usersSetupClosed, usersWithout2fa }
const { csrf, serverURL } = payload.config as { csrf?: unknown; serverURL?: unknown }
const originKnown = (typeof serverURL === 'string' && serverURL.trim() !== '') || (Array.isArray(csrf) && csrf.some((o) => typeof o === 'string' && o.trim() !== ''))
return { mail, node: process.version, openSignUp, originKnown, pendingCookies, plugin: pluginVersion(), staffOnOwnRoles, staffOpenToOthers, turnstile, turnstileSecretFromEnv: secretFromEnv, usersSetupClosed, usersWithout2fa }
}
export type DoctorEndpointOptions = {
+5
View File
@@ -99,6 +99,11 @@ export type DoctorStatus = {
node?: string
/** Auth collections whose `create` rule lets an anonymous request through (slugs only). */
openSignUp?: null | string[]
/**
* The running config has a `serverURL` (1.17.2), or a non-empty `csrf` list. Without either Payload takes the
* login cookie from any origin, and the plugin's own-origin checks know the site only from the request's host.
*/
originKnown?: boolean
pendingCookies?: null | number
plugin?: string
/**
+2 -2
View File
@@ -4,7 +4,7 @@ import { createHash, randomBytes } from 'node:crypto'
import type { ResolvedRelayOptions } from './options.js'
import { consumeRateLimit } from '../../shared/rateLimit.js'
import { consumeRateLimit, ipRateKey } from '../../shared/rateLimit.js'
import { type RelayAnswer, type RelayRefusal, relayRequest } from './client.js'
import { RELAY_DEFAULTS, type RelayStatusCode, relayStatusFor } from './constants.js'
import { currentMailKind, type MailKind, mailKindOf, takeExpectedMail } from './kinds.js'
@@ -136,7 +136,7 @@ export async function sendThroughRelay(payload: BasePayload, options: ResolvedRe
const windowMs = (own.windowMinutes ?? RELAY_DEFAULTS.accountMail.windowMinutes) * 60_000
const perAddress = own.perAddress ?? RELAY_DEFAULTS.accountMail.perAddress
const checks = [
...(marked?.visitor ? [{ key: `visitor:${marked.visitor}`, max: own.perVisitor ?? RELAY_DEFAULTS.accountMail.perVisitor }] : []),
...(marked?.visitor ? [{ key: `visitor:${ipRateKey(marked.visitor)}`, max: own.perVisitor ?? RELAY_DEFAULTS.accountMail.perVisitor }] : []),
...[...(request.to ?? []), ...(request.cc ?? []), ...(request.bcc ?? [])].map((address) => ({ key: `to:${sha256Hex(address.toLowerCase())}`, max: perAddress })),
]
for (const check of checks) {
+3 -1
View File
@@ -3,9 +3,11 @@ export {
checkRateLimit,
clientIp,
consumeRateLimit,
ipRateKey,
retryAfterSeconds,
setIpv6Grouping,
setRateLimitStore,
setUnknownIpFactor,
tooManyRequests,
} from '../shared/rateLimit.js'
export type { ClientIpOptions, RateLimitArgs, RateLimitStore } from '../shared/rateLimit.js'
export type { ClientIpOptions, Ipv6Grouping, RateLimitArgs, RateLimitStore } from '../shared/rateLimit.js'
+71
View File
@@ -0,0 +1,71 @@
import type { Config, Endpoint, PayloadRequest } from 'payload'
import { COOKIE_APPROVAL_PATH } from '../consent/scanner/approval.js'
import { COOKIE_CRAWL_PATH } from '../consent/scanner/crawl/config.js'
import { COOKIE_SCAN_PATH } from '../consent/scanner/endpoint.js'
import { RELAY_CONNECT_PATH, RELAY_DISCONNECT_PATH } from '../email/relay/constants.js'
import { reportRefusedOrigin, requestFromOwnOrigin } from './totp/sameOrigin.js'
/**
* The plugin's panel actions only from the site's own origin (`adminSameOrigin`, 1.17.2; IAWL idea 7, owner's Q6).
*
* These endpoints act with the panel's login cookie and read a body whatever its `Content-Type` says — a
* `text/plain` POST, which another origin can send without a CORS preflight. A page on a sibling subdomain is
* "same site", so the browser sends the `SameSite=Lax` cookie along, and Payload's own CSRF list is empty unless
* `serverURL` or `csrf` is set. Such a page could make a signed-in administrator disconnect the mail service,
* connect it again, send test mails, run cookie scans and crawls, or approve every waiting cookie. The rule is the
* one 2FA verify / setup / reset use (sameOrigin.ts): a request the browser marks as coming from elsewhere
* (`Origin`, else `Sec-Fetch-Site`) gets `403` before anything is read; a request with neither header (a script,
* `curl`) passes — it rides on nobody's cookie. Refusals are logged once per origin with the ways to allow it.
*/
export type AdminSameOriginOption = {
/** More origins that may call these endpoints (a panel on another domain). */
origins?: string[]
} | boolean
/** The panel actions the rule covers: method and path (relative to the API route). */
export const ADMIN_POST_ENDPOINTS: ReadonlyArray<readonly ['post', string]> = [
['post', RELAY_CONNECT_PATH],
['post', RELAY_DISCONNECT_PATH],
['post', '/ipal/test-email'],
['post', COOKIE_SCAN_PATH],
['post', COOKIE_APPROVAL_PATH],
['post', COOKIE_CRAWL_PATH],
]
const ADMIN_REFUSAL = {
docs: 'docs/security.md "Panel actions only from the site\'s own origin"',
option: 'iapl({ adminSameOrigin',
what: 'a panel action',
}
const covered = (endpoint: Pick<Endpoint, 'method' | 'path'>): boolean =>
ADMIN_POST_ENDPOINTS.some(([method, path]) => endpoint.method === method && endpoint.path === path)
/** Wraps one endpoint: `403` for a request from another origin, the endpoint's own answer otherwise. */
export function requireOwnOrigin<T extends Pick<Endpoint, 'handler'>>(endpoint: T, origins: string[] = []): T {
const handler = endpoint.handler as (req: PayloadRequest) => Promise<Response> | Response
return {
...endpoint,
handler: (async (req: PayloadRequest) => {
if (!requestFromOwnOrigin(req as never, origins)) {
reportRefusedOrigin(req as never, origins, ADMIN_REFUSAL)
return Response.json({ message: 'Not allowed from this origin.', ok: false }, { status: 403 })
}
return handler(req)
}) as T['handler'],
}
}
/**
* Applies the rule to the covered endpoints the plugin added (`ownEndpoints`: those not in the project's config
* before iapl ran) — a project's own endpoint on the same path is left as it is.
*/
export function guardAdminEndpoints(config: Config, before: ReadonlySet<unknown>, option: AdminSameOriginOption | undefined): Config {
if (option === false) {return config}
const origins = typeof option === 'object' ? (option.origins ?? []) : []
return {
...config,
endpoints: (config.endpoints ?? []).map((e) => (!before.has(e) && covered(e) ? requireOwnOrigin(e, origins) : e)),
}
}
+13 -5
View File
@@ -89,21 +89,29 @@ const MAX_REPORTED = 50
* that origin. Without it a site behind a proxy that hides its address has a panel nobody can
* enter and a silent log. Returns true when a line was written.
*/
export function reportRefusedOrigin(req: RequestLike, extra: string[] = []): boolean {
/** What a refusal line names: the request, the option that allows an origin, and the doc section. Default: 2FA. */
export type RefusalContext = { docs: string; option: string; what: string }
const TWO_FACTOR_REFUSAL: RefusalContext = {
docs: 'docs/security.md "Verify and setup attempts only from the site\'s own origin"',
option: 'twoFactor: { sameOrigin',
what: '2FA: a code',
}
export function reportRefusedOrigin(req: RequestLike, extra: string[] = [], context: RefusalContext = TWO_FACTOR_REFUSAL): boolean {
const origin = req.headers?.get('origin')
const key = origin ? (originOf(origin) ?? 'null') : `sec-fetch-site: ${req.headers?.get('sec-fetch-site') ?? 'none'}`
const key = `${context.option}|${origin ? (originOf(origin) ?? 'null') : `sec-fetch-site: ${req.headers?.get('sec-fetch-site') ?? 'none'}`}`
if (reported.has(key) || reported.size >= MAX_REPORTED) {return false}
reported.add(key)
const { hosts, origins } = ownOrigins(req, extra)
const known = [...origins, ...[...hosts].map((h) => `host ${h}`)].join(', ') || 'none'
const how = originOf(origin)
? `If "${originOf(origin)}" is this site's own address (a reverse proxy that rewrites Host and sends no X-Forwarded-Host), set serverURL to it in the Payload config, ` +
`or pass twoFactor: { sameOrigin: { origins: ['${originOf(origin)}'] } }, or make the proxy send X-Forwarded-Host. `
`or pass ${context.option}: { origins: ['${originOf(origin)}'] } }, or make the proxy send X-Forwarded-Host. `
: 'The browser did not name an origin this site knows. '
req.payload?.logger?.warn(
`[iapl] 2FA: a code from ${origin ? `origin "${origin}"` : `a ${key} request`} was refused and not counted — it is not one of this site's own origins (${known}). ` +
`[iapl] ${context.what} from ${origin ? `origin "${origin}"` : `a ${key.split('|')[1]} request`} was refused${context === TWO_FACTOR_REFUSAL ? ' and not counted' : ''} — it is not one of this site's own origins (${known}). ` +
how +
'If it is a foreign page, this is the protection working. twoFactor: { sameOrigin: false } turns the check off (docs/security.md "Verify and setup attempts only from the site\'s own origin"). Said once per origin.',
`If it is a foreign page, this is the protection working. ${context.option}: false } turns the check off (${context.docs}). Said once per origin.`,
)
return true
}
+118 -13
View File
@@ -94,8 +94,103 @@ export function setUnknownIpFactor(factor: number): void {
unknownIpFactor = Math.max(0, factor)
}
/**
* IPv6 is counted per network, not per address (1.17.2, IAWL idea 9). A host with IPv6 gets a whole /64
* (2^64 addresses) — every home connection and every server does — so counting per address gave one visitor
* as many budgets as it has addresses. Every limiter of the plugin (forms, search, MCP, consent log, stats,
* doctor, the mail service's confirm route and account-mail limit) counts a /64 as one client. One home network
* shares the budget then, as an IPv4 home behind one router always did.
*
* Optionally a second, roomier counter per wider network (`wide: 48`, `wideFactor` × the limit): one hosting
* customer often holds a /48 (65,536 /64s). Off by default — mobile carriers can put many phones in one /48.
*/
export type Ipv6Grouping = {
/** Prefix length one client is counted by. Default 64; 128 = per address (as before 1.17.2). 1–128. */
prefix?: number
/** A second counter per this wider prefix (e.g. 48), at `wideFactor` × the limit. Default: none. */
wide?: false | number
/** Multiplier for the wide counter's limit. Default 10. */
wideFactor?: number
}
let ipv6 = { prefix: 64, wide: 0, wideFactor: 10 }
/** How every limiter of the plugin counts IPv6 clients (call once at start). `setIpv6Grouping({ prefix: 128 })` = per address. */
export function setIpv6Grouping(next: Ipv6Grouping = {}): void {
const prefix = next.prefix ?? 64
const wide = next.wide === false || next.wide === undefined ? 0 : next.wide
const wideFactor = next.wideFactor ?? 10
for (const [name, value, min] of [['prefix', prefix, 1], ['wide', wide, 0], ['wideFactor', wideFactor, 1]] as const) {
if (!Number.isInteger(value) || value < min || value > (name === 'wideFactor' ? 1e6 : 128)) {
throw new Error(`[iapl] setIpv6Grouping: ${name} must be a whole number from ${min}${name === 'wideFactor' ? '' : ' to 128'} (received ${JSON.stringify(value)}).`)
}
}
if (wide && wide >= prefix) {throw new Error(`[iapl] setIpv6Grouping: wide (${wide}) must be a shorter prefix than prefix (${prefix}).`)}
ipv6 = { prefix, wide, wideFactor }
}
/** A dotted IPv4 address (no `node:net`: this module also reaches bundles that are not Node's). */
function isIPv4(value: string): boolean {
const parts = value.split('.')
return parts.length === 4 && parts.every((p) => /^\d{1,3}$/.test(p) && Number(p) <= 255)
}
/** The 8 groups of an IPv6 address as numbers (brackets and a zone id allowed), or null when it is not one. */
function ipv6Groups(address: string): null | number[] {
let text = address.replace(/^\[|\]$/g, '').split('%')[0]
if (!text.includes(':') || !/^[0-9a-f:.]+$/i.test(text) || text.split('::').length > 2) {return null}
const v4 = /(?:^|:)(\d+\.\d+\.\d+\.\d+)$/.exec(text)
if (v4) {
if (!isIPv4(v4[1])) {return null}
const [a, b, c, d] = v4[1].split('.').map(Number)
text = text.slice(0, -v4[1].length) + `${((a << 8) | b).toString(16)}:${((c << 8) | d).toString(16)}`
} else if (text.includes('.')) {return null}
const compressed = text.includes('::')
const [head, tail = ''] = compressed ? text.split('::') : [text]
const left = head ? head.split(':') : []
const right = tail ? tail.split(':') : []
if ([...left, ...right].some((g) => !/^[0-9a-f]{1,4}$/i.test(g))) {return null}
const missing = 8 - left.length - right.length
if (compressed ? missing < 1 : missing !== 0) {return null}
return [...left, ...Array(compressed ? missing : 0).fill('0'), ...right].map((g) => parseInt(g, 16))
}
/** `2001:db8:1:2::/64` for any address of that network (`bits` = prefix length). */
function ipv6Network(groups: number[], bits: number): string {
const out = groups.map((g, i) => {
const start = i * 16
if (start >= bits) {return 0}
const keep = Math.min(16, bits - start)
return keep === 16 ? g : g & ((0xffff << (16 - keep)) & 0xffff)
})
return `${out.map((g) => g.toString(16)).join(':')}/${bits}`
}
/**
* The key one client is counted by: an IPv4 address as it is, an IPv4-mapped IPv6 address (`::ffff:1.2.3.4`) as
* its IPv4, an IPv6 address as its network (`setIpv6Grouping`, default /64). Anything else is returned unchanged.
* Use it for a limiter of your own keyed by `clientIp()`.
*/
export function ipRateKey(ip: string): string {
const value = ip.trim()
if (!value || isIPv4(value)) {return value}
const groups = ipv6Groups(value)
if (!groups) {return value}
const mapped = groups.slice(0, 5).every((g) => g === 0) && groups[5] === 0xffff
if (mapped) {return `${groups[6] >> 8}.${groups[6] & 0xff}.${groups[7] >> 8}.${groups[7] & 0xff}`}
return ipv6Network(groups, ipv6.prefix)
}
/** The wide network of an IPv6 key, when the wide counter is on; null otherwise. */
function wideKeyOf(ip: string): null | string {
if (!ipv6.wide) {return null}
const groups = ipv6Groups(ip.trim())
if (!groups || (groups.slice(0, 5).every((g) => g === 0) && groups[5] === 0xffff)) {return null}
return ipv6Network(groups, ipv6.wide)
}
function resolveKey(key: string, max: number): { key: string; max: number } | null {
if (key) {return { key, max }}
if (key) {return { key: ipRateKey(key), max }}
return unknownIpFactor > 0 ? { key: UNKNOWN_IP_KEY, max: max * unknownIpFactor } : null
}
@@ -125,10 +220,16 @@ export function checkRateLimit({ cost = 1, key: rawKey, max: rawMax = 5, scope =
if (!resolved) {return true}
const { key, max } = resolved
const id = `${scope}:${key}`
const current = buckets.get(id)
const used = current && current.resetAt > Date.now() ? current.count : 0
if (used + cost > max) {return false}
const wide = wideKeyOf(rawKey)
const wideId = wide ? `${scope}:${wide}` : null
const used = (bucketId: string) => {
const current = buckets.get(bucketId)
return current && current.resetAt > Date.now() ? current.count : 0
}
if (used(id) + cost > max) {return false}
if (wideId && used(wideId) + cost > max * ipv6.wideFactor) {return false}
hitMemory(id, cost, windowMs)
if (wideId) {hitMemory(wideId, cost, windowMs)}
return true
}
@@ -149,26 +250,30 @@ export async function consumeRateLimit({
if (!resolved) {return { ok: true, retryAfter: 0 }}
const { key, max } = resolved
const id = `${scope}:${key}`
const wide = wideKeyOf(rawKey)
let bucket: Bucket
if (store) {
const hit = async (bucketId: string): Promise<Bucket | null> => {
if (!store) {return hitMemory(bucketId, cost, windowMs)}
try {
bucket = await store.hit(id, cost, windowMs)
return await store.hit(bucketId, cost, windowMs)
} catch (err) {
console.warn('[iapl] rate limit store failed, allowing request:', err instanceof Error ? err.message : err)
return { ok: true, retryAfter: 0 }
return null
}
} else {
bucket = hitMemory(id, cost, windowMs)
}
const bucket = await hit(id)
if (!bucket) {return { ok: true, retryAfter: 0 }}
const wideBucket = wide ? await hit(`${scope}:${wide}`) : null
const retryAfter = Math.max(1, Math.ceil((bucket.resetAt - Date.now()) / 1000))
return { ok: bucket.count <= max, retryAfter }
const over = [bucket.count > max ? bucket : null, wideBucket && wideBucket.count > max * ipv6.wideFactor ? wideBucket : null].filter((b): b is Bucket => b !== null)
const later = over.reduce((at, b) => Math.max(at, b.resetAt), bucket.resetAt)
const retryAfter = Math.max(1, Math.ceil(((over.length ? later : bucket.resetAt) - Date.now()) / 1000))
return { ok: over.length === 0, retryAfter }
}
/** Seconds until the key's IN-MEMORY window resets — for a Retry-After header. */
export function retryAfterSeconds(key: string, scope = 'form'): number {
const bucket = buckets.get(`${scope}:${key}`)
const bucket = buckets.get(`${scope}:${key ? ipRateKey(key) : UNKNOWN_IP_KEY}`)
return bucket ? Math.max(1, Math.ceil((bucket.resetAt - Date.now()) / 1000)) : 1
}
+9
View File
@@ -50,12 +50,21 @@ export function assertPluginSwitches(options: Record<string, unknown>): void {
// `accounts: 0` / `''` dropped every account rule (staff-only reads, admin-only writes, the panel role,
// the password rule, the closed first-user route).
assertSwitchOrObject('accounts', options.accounts, { allowTrue: false })
// 1.17.2: only 'payload' brings Payload's "locked" answer back (it tells which addresses have an account).
const accounts = bag(options.accounts)
if (accounts) {assertOneOf('accounts.lockedAnswer', accounts.lockedAnswer, ['payload', 'wrong'])}
// Opt-in features that add public endpoints or outbound calls: `'false'` switched them ON.
for (const name of ['cookieScanner', 'stats', 'consentLog', 'adminMeta', 'whiteLabel'] as const) {
assertSwitchOrObject(name, options[name])
}
assertBooleanSwitch('indexNow', options.indexNow)
// 1.17.2: `adminSameOrigin: 0` / `'false'` must not read as off (it took the origin check off the panel actions)
assertSwitchOrObject('adminSameOrigin', options.adminSameOrigin)
const adminSameOrigin = bag(options.adminSameOrigin)
if (adminSameOrigin && adminSameOrigin.origins !== undefined && !(Array.isArray(adminSameOrigin.origins) && adminSameOrigin.origins.every((o) => typeof o === 'string'))) {
throw new Error(`${where('adminSameOrigin.origins')} must be a list of origins such as ['https://panel.example.com'] (received ${JSON.stringify(adminSameOrigin.origins)}).`)
}
// an unknown name ('IAPL') used to mean 'ipal': the scanner declared one visitor cookie while the site set another
assertOneOf('storageNames', options.storageNames, ['ipal', 'iapl'])
assertBooleanSwitch('lightbox', options.lightbox)
+9
View File
@@ -13,6 +13,7 @@ import { applyGlobalOverrides } from './globals/overrides.js'
import { buildSiteIntegrations } from './globals/SiteIntegrations/index.js'
import { buildSiteSettings } from './globals/SiteSettings/index.js'
import { adminOnly, adminOrSelfIn, injectRoles, registerStaffCollections, staffCollectionSlugs, withVersionReadRules } from './modules/access/index.js'
import { withLockedAnswer } from './modules/access/lockedAnswer.js'
import { applyPanelRole, countBelowPanelRole, resolvePanelRole } from './modules/access/panelRole.js'
import { applyPasswordRule, buildPasswordRuleHook, resolvePasswordRule } from './modules/access/passwordRule.js'
import { adoptLateAuthCollections, applyFirstUserRoute, applyStaffAccountAccess, markSeenAuthCollections, markStaffRules, staffCollectionsNobodyManages, unknownStaffCollections } from './modules/access/selfRegistration.js'
@@ -49,6 +50,7 @@ import { withFillLocales } from './modules/hooks/fillEmptyLocales.js'
import { buildLocalizationConfig, validateI18nConfig } from './modules/i18n/index.js'
import { serverText } from './modules/integrations/texts.js'
import { buildSystemPagesFields } from './modules/pages/index.js'
import { guardAdminEndpoints } from './modules/security/adminSameOrigin.js'
import { missingImportMapEntries } from './modules/security/totp/importMapCheck.js'
import { changedViewKeys, copyViews, SAFE_TOTP_VIEW, wrapTotpViews } from './modules/security/totp/safeBack.js'
import { reportRefusedOrigin, requestFromOwnOrigin } from './modules/security/totp/sameOrigin.js'
@@ -129,6 +131,8 @@ export const iapl = (options: IaplOptions): Plugin => {
async function transform(incomingConfig: Config): Promise<Config> {
let config = { ...incomingConfig }
/** The project's own endpoints: the panel-action origin rule (adminSameOrigin) is for the plugin's only. */
const projectEndpoints = new Set<unknown>(incomingConfig.endpoints ?? [])
// Text written in one language fills the empty languages of the same field (cookie list, cookie review).
const fillDefaults = { 'cookie-review': ['purpose', 'retention'], 'cookie-settings': ['cookies.purpose', 'cookies.duration'] }
@@ -258,6 +262,8 @@ export const iapl = (options: IaplOptions): Plugin => {
const panelSlug = config.admin?.user ?? (config.collections ?? []).find((c) => c.auth)?.slug
const staffSlugs = [...new Set([panelSlug, options.access?.authCollection, ...(options.access?.staffCollections ?? [])].filter((s): s is string => Boolean(s)))]
config = applyStaffAccountAccess(config, staffSlugs, { ...accountAccess, pluginRoles: options.access?.authCollection ? [options.access.authCollection] : [] })
// A locked staff account answers like a wrong password (accounts.lockedAnswer).
if (accounts.lockedAnswer !== 'payload') {config = withLockedAnswer(config)}
}
if (options.twoFactor !== false) {
const tf = options.twoFactor
@@ -1102,6 +1108,9 @@ export const iapl = (options: IaplOptions): Plugin => {
const panel = config.admin?.user ?? (config.collections ?? []).find((c) => c.auth)?.slug
config = markSeenAuthCollections(config, staffCollectionSlugs({ admin: { user: panel }, custom: config.custom }))
}
// The plugin's panel actions (mail service connect / disconnect, test e-mail, cookie scan / approval / crawl)
// only from the site's own origin (adminSameOrigin).
config = guardAdminEndpoints(config, projectEndpoints, options.adminSameOrigin)
return config
}
}
+10 -1
View File
@@ -26,6 +26,7 @@ import type { FormsOption } from './modules/forms/types.js'
import type { RevalidatePathFn } from './modules/hooks/buildRevalidateHook.js'
import type { I18nConfig } from './modules/i18n/types.js'
import type { PagesOption } from './modules/pages/types.js'
import type { AdminSameOriginOption } from './modules/security/adminSameOrigin.js'
import type { SafeBackRule } from './modules/security/totp/safeBack.js'
import type { RequireSetupOptions } from './modules/security/totp/setupRequired.js'
import type { VerifyLimitOptions } from './modules/security/totp/verifyLimit.js'
@@ -57,7 +58,6 @@ export type IaplOptions = {
* Keys the project sets in its own `admin.meta` always win. `false` = Payload's defaults.
*/
adminMeta?: AdminMetaOptions | false
/**
* Custom admin panel route, e.g. '/its' instead of the default '/admin'.
* The plugin sets config.routes.admin. IMPORTANT: this alone isn't enough —
@@ -70,6 +70,15 @@ export type IaplOptions = {
*/
adminRoute?: string
/**
* The plugin's panel actions — `POST` mail service connect / disconnect, test e-mail, cookie scan, cookie
* approval, cookie crawl — refuse (`403`) a request a browser marks as coming from another origin, before
* anything is read (1.17.2). Own origins: the request's host (`Host`, `X-Forwarded-Host`), `serverURL`,
* Payload's `csrf` and `cors` lists, and `origins` here. `false` = no check (as before 1.17.2).
* The 2FA endpoints follow `twoFactor.sameOrigin`. docs/security.md "Panel actions only from the site's own origin".
*/
adminSameOrigin?: AdminSameOriginOption
/**
* Who supports the technology, named in the admin credit, the panel's link
* description and its preview image. Default `{ name: 'Intecion.com', url: 'https://intecion.com' }`.
+38
View File
@@ -0,0 +1,38 @@
/** The plugin's panel actions refuse other origins (adminSameOriginSuite.ts). */
import { describe, expect, test, vi } from 'vitest'
import { guardAdminEndpoints } from '../src/modules/security/adminSameOrigin.js'
import { clearReportedOrigins } from '../src/modules/security/totp/sameOrigin.js'
import { ACTIONS, adminSite, SIBLING } from './adminSameOriginSuite.js'
vi.mock('server-only', () => ({}))
vi.mock('next/headers.js', async () => (await import('./http/server.js')).nextHeadersMock)
const { action, state } = adminSite()
describe('adminSameOrigin (default): panel actions only from the site\'s own origin', () => {
test('a page on a sibling subdomain, or a cross-site page, gets 403 on every panel action, with the admin cookie', async () => {
clearReportedOrigins()
for (const path of ACTIONS) {
expect([path, (await action(path, SIBLING)).status]).toEqual([path, 403])
expect([path, (await action(path, { 'sec-fetch-site': 'cross-site' })).status]).toEqual([path, 403])
}
// said in the log once per origin, naming this option
const lines = state.warn.filter((l) => l.includes('blog.site.example'))
expect(lines).toHaveLength(1)
expect(lines[0]).toMatch(/adminSameOrigin/)
})
test('the site\'s own page and a script without browser headers still reach them', async () => {
const own = await action('/ipal/cookie-approval', { origin: state.server.url, 'sec-fetch-site': 'same-origin' }, '{"ids":[]}')
expect(own.status).toBe(200)
const script = await action('/ipal/cookie-approval', {}, '{"ids":[]}')
expect(script.status).toBe(200)
})
test('a project\'s own endpoint on one of these paths is left as it is', () => {
const own = { handler: () => Response.json({ ok: true }), method: 'post' as const, path: '/ipal/test-email' }
const config = guardAdminEndpoints({ endpoints: [own] } as never, new Set([own]), undefined)
expect(config.endpoints?.[0]).toBe(own)
})
})
+22
View File
@@ -0,0 +1,22 @@
/** adminSameOrigin: false leaves the origin check out (adminSameOriginSuite.ts). */
import { describe, expect, test, vi } from 'vitest'
import { iapl } from '../src/plugin.js'
import { adminSite, SIBLING } from './adminSameOriginSuite.js'
vi.mock('server-only', () => ({}))
vi.mock('next/headers.js', async () => (await import('./http/server.js')).nextHeadersMock)
const { action } = adminSite(false)
describe('adminSameOrigin: false', () => {
test('a request from a sibling subdomain reaches the action, as before 1.17.2', async () => {
expect((await action('/ipal/cookie-approval', SIBLING, '{"ids":[]}')).status).toBe(200)
})
test('a value nobody understands stops the start', async () => {
const i18n = { defaultLocale: 'en', locales: [{ code: 'en', label: 'English' }] }
await expect((async () => iapl({ adminSameOrigin: 0 as never, i18n } as never)({ collections: [], secret: 'x' } as never))()).rejects.toThrow(/adminSameOrigin must be/)
await expect((async () => iapl({ adminSameOrigin: { origins: 'https://a.example' as never }, i18n } as never)({ collections: [], secret: 'x' } as never))()).rejects.toThrow(/adminSameOrigin\.origins must be a list/)
})
})
+70
View File
@@ -0,0 +1,70 @@
/**
* The plugin's panel actions only from the site's own origin (adminSameOrigin, 1.17.2). Shared by
* adminSameOrigin.test.ts (default) and adminSameOriginOff.test.ts (`adminSameOrigin: false`): one Payload per file.
* A signed-in administrator's cookie rides on a `text/plain` POST (no CORS preflight) from a page on a sibling
* subdomain. Database: SQLite in memory, or IPAL_TEST_POSTGRES_URI / IPAL_TEST_MONGO_URI (test/http/db.ts).
*/
import type { Payload } from 'payload'
import { payloadTotp } from '@clocklimited/payload-2fa'
import { lexicalEditor } from '@payloadcms/richtext-lexical'
import { getPayload } from 'payload'
import { afterAll, beforeAll } from 'vitest'
import { iapl } from '../src/plugin.js'
import { buildTestConfig } from './helpers.js'
import { testDatabase } from './http/db.js'
import { cookiesOf, startPayloadServer, type TestServer } from './http/server.js'
import { totp } from './http/totp.js'
const SECRET = 'JBSWY3DPEHPK3PXP'
const PASSWORD = 'a-long-test-password-1'
export const SIBLING = { origin: 'https://blog.site.example', 'sec-fetch-site': 'same-site' }
/** Every panel action the rule covers (path under /api). */
export const ACTIONS = ['/iapl/mail-relay/connect', '/iapl/mail-relay/disconnect', '/ipal/test-email', '/ipal/cookie-scan', '/ipal/cookie-approval', '/ipal/cookie-crawl']
export function adminSite(adminSameOrigin?: false) {
const state = {} as { cookie: string; payload: Payload; server: TestServer; warn: string[] }
beforeAll(async () => {
process.env.IAPL_COOKIE_SCAN_URL ??= 'http://127.0.0.1:9'
process.env.IAPL_COOKIE_SCAN_TOKEN ??= 'test-token-0123456789abcdef0123456789'
const config = buildTestConfig({
admin: { user: 'users' },
collections: [{ slug: 'media', fields: [], upload: { staticDir: '/tmp/iapl-admin-origin-media' } }],
db: testDatabase('adminorigin'),
editor: lexicalEditor(),
plugins: [
iapl({
access: { authCollection: 'users' },
...(adminSameOrigin === false ? { adminSameOrigin } : {}),
cookieScanner: { crawl: true },
i18n: { defaultLocale: 'en', locales: [{ code: 'en', label: 'English' }] },
twoFactor: { issuer: 'Example', plugin: payloadTotp },
}),
],
secret: 'integration-test-secret-0123456789',
telemetry: false,
})
state.payload = await getPayload({ config })
state.warn = []
const warn = state.payload.logger.warn.bind(state.payload.logger)
state.payload.logger.warn = ((msg: unknown, ...rest: unknown[]) => {
state.warn.push(String(msg))
return (warn as (...a: unknown[]) => void)(msg, ...rest)
}) as never
state.server = await startPayloadServer(config)
await state.payload.create({ collection: 'users' as never, data: { email: '[email protected]', password: PASSWORD, roles: ['admin'], totpSecret: SECRET } as never })
const login = await fetch(`${state.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(`${state.server.url}/api/verify-totp`, { body: JSON.stringify({ token: totp(SECRET) }), headers: { 'content-type': 'application/json', cookie: first.join('; ') }, method: 'POST' })
state.cookie = [...first, ...cookiesOf(verify)].join('; ')
}, 120_000)
afterAll(async () => {
await state.server?.close()
await state.payload?.destroy?.()
})
/** A POST as a foreign page can send it: text/plain, the admin's cookie. */
const action = (path: string, headers: Record<string, string>, body = '{"to":"[email protected]"}') =>
fetch(`${state.server.url}/api${path}`, { body, headers: { 'content-type': 'text/plain', cookie: state.cookie, ...headers }, method: 'POST', signal: AbortSignal.timeout(20_000) })
return { action, state }
}
+14 -1
View File
@@ -193,6 +193,9 @@ describe('M1 rules: access-missing, turnstile-degraded, turnstile-env-key', () =
expect(await run(build('{ serverURL: process.env.NEXT_PUBLIC_SERVER_URL, plugins: [] }'), ['csrf-empty'])).toEqual([])
expect(await run(build("{ csrf: ['https://site.example'], plugins: [] }"), ['csrf-empty'])).toEqual([])
expect(await run('// not a Payload config', ['csrf-empty'])).toEqual([])
// deep (the running config, 1.17.2): it wins over the file — serverURL may come from a spread or a helper
expect(await run(build('{ ...base, plugins: [] }'), ['csrf-empty'], { originKnown: false })).toEqual(['csrf-empty:warning'])
expect(await run(build("{ plugins: [iapl({ access: { authCollection: 'users' } })] }"), ['csrf-empty'], { originKnown: true })).toEqual([])
})
test('open-signup: an auth collection anyone can register in is said, as info', async () => {
@@ -230,6 +233,16 @@ describe('M1 rules: access-missing, turnstile-degraded, turnstile-env-key', () =
expect(fromEnv.turnstileSecretFromEnv).toBe(true)
expect(JSON.stringify(fromEnv)).not.toMatch(/secret-value/)
})
test('the deep status says whether the running config knows its own origin (serverURL or csrf), never the value', async () => {
const fake = (extra: object) => ({ config: { admin: { user: 'users' }, collections: [{ slug: 'users', fields: [] }], globals: [], ...extra } })
expect((await collectDoctorStatus(fake({}) as never)).originKnown).toBe(false)
expect((await collectDoctorStatus(fake({ serverURL: '' }) as never)).originKnown).toBe(false)
const known = await collectDoctorStatus(fake({ serverURL: 'https://secret-host.example' }) as never)
expect(known.originKnown).toBe(true)
expect(JSON.stringify(known)).not.toMatch(/secret-host/)
expect((await collectDoctorStatus(fake({ csrf: ['https://site.example'] }) as never)).originKnown).toBe(true)
})
})
describe('helpers', () => {
@@ -529,7 +542,7 @@ describe('security and deep status', () => {
}
const status = await collectDoctorStatus(payload as never)
expect(status).toMatchObject({ pendingCookies: 4, usersWithout2fa: 2 })
expect(Object.keys(status).sort()).toEqual(['mail', 'node', 'openSignUp', 'pendingCookies', 'plugin', 'staffOnOwnRoles', 'staffOpenToOthers', 'turnstile', 'turnstileSecretFromEnv', 'usersSetupClosed', 'usersWithout2fa'])
expect(Object.keys(status).sort()).toEqual(['mail', 'node', 'openSignUp', 'originKnown', 'pendingCookies', 'plugin', 'staffOnOwnRoles', 'staffOpenToOthers', 'turnstile', 'turnstileSecretFromEnv', 'usersSetupClosed', 'usersWithout2fa'])
expect(status.usersSetupClosed).toBeNull() // no setup window in this config
expect(status.mail).toBeNull() // no Site integrations global in this config
})
+35
View File
@@ -0,0 +1,35 @@
/** A locked staff account answers like a wrong password, REST and GraphQL (lockedAnswerSuite.ts). 2FA on. */
import { describe, expect, test, vi } from 'vitest'
import { lockedAnswerSite, PASSWORD } from './lockedAnswerSuite.js'
vi.mock('server-only', () => ({}))
vi.mock('next/headers.js', async () => (await import('./http/server.js')).nextHeadersMock)
const { gqlLogin, lock, restLogin, state } = lockedAnswerSite()
describe('accounts.lockedAnswer (default): a locked staff account looks like a wrong password', () => {
test('REST: the locked owner, with any password, gets exactly what an invented address gets', async () => {
await lock('users', '[email protected]')
const invented = await restLogin('users', '[email protected]', 'a-wrong-password')
expect(invented.status).toBe(401)
expect(await restLogin('users', '[email protected]', 'a-wrong-password')).toEqual(invented)
expect(await restLogin('users', '[email protected]', PASSWORD)).toEqual(invented)
expect(invented.body).not.toMatch(/locked/i)
// the lock itself is still there
const stored = (await state.payload.find({ collection: 'users' as never, overrideAccess: true, showHiddenFields: true, where: { email: { equals: '[email protected]' } } })).docs[0] as { lockUntil?: string }
expect(new Date(String(stored.lockUntil)).getTime()).toBeGreaterThan(Date.now())
})
test('GraphQL: the same message, status and error name', async () => {
const invented = await gqlLogin('loginUser', '[email protected]', 'a-wrong-password')
expect(invented.name).toBe('AuthenticationError')
expect(await gqlLogin('loginUser', '[email protected]', PASSWORD)).toEqual(invented)
})
test('a visitor collection keeps Payload\'s answer (not staff)', async () => {
await lock('customers', '[email protected]', 3)
expect((await restLogin('customers', '[email protected]', PASSWORD)).body).toMatch(/locked/i)
expect((await gqlLogin('loginCustomer', '[email protected]', PASSWORD)).name).toBe('LockedAuth')
})
})
+16
View File
@@ -0,0 +1,16 @@
/** A locked staff account answers like a wrong password with 2FA off too (lockedAnswerSuite.ts). */
import { describe, expect, test, vi } from 'vitest'
import { lockedAnswerSite, PASSWORD } from './lockedAnswerSuite.js'
vi.mock('server-only', () => ({}))
const { gqlLogin, lock, restLogin } = lockedAnswerSite({ twoFactor: false })
describe('accounts.lockedAnswer with twoFactor: false', () => {
test('REST and GraphQL answer the locked owner like an invented address', async () => {
await lock('users', '[email protected]')
expect(await restLogin('users', '[email protected]', PASSWORD)).toEqual(await restLogin('users', '[email protected]', 'x-wrong-password-1'))
expect(await gqlLogin('loginUser', '[email protected]', PASSWORD)).toEqual(await gqlLogin('loginUser', '[email protected]', 'x-wrong-password-1'))
})
})
+23
View File
@@ -0,0 +1,23 @@
/** accounts.lockedAnswer: 'payload' keeps Payload's "locked" answer (lockedAnswerSuite.ts). */
import { describe, expect, test, vi } from 'vitest'
import { iapl } from '../src/plugin.js'
import { lockedAnswerSite, PASSWORD } from './lockedAnswerSuite.js'
vi.mock('server-only', () => ({}))
vi.mock('next/headers.js', async () => (await import('./http/server.js')).nextHeadersMock)
const { gqlLogin, lock, restLogin } = lockedAnswerSite({ lockedAnswer: 'payload' })
describe("accounts.lockedAnswer: 'payload'", () => {
test('the locked owner is told it is locked, REST and GraphQL', async () => {
await lock('users', '[email protected]')
expect((await restLogin('users', '[email protected]', PASSWORD)).body).toMatch(/locked/i)
expect((await gqlLogin('loginUser', '[email protected]', PASSWORD)).name).toBe('LockedAuth')
})
test('a value nobody understands stops the start', async () => {
const config = { collections: [], secret: 'x' } as never
await expect((async () => iapl({ accounts: { lockedAnswer: 'Payload' as never }, i18n: { defaultLocale: 'en', locales: [{ code: 'en', label: 'English' }] } } as never)(config))()).rejects.toThrow(/accounts\.lockedAnswer must be one of/)
})
})
+79
View File
@@ -0,0 +1,79 @@
/**
* A locked staff account answers its login exactly like a wrong password (accounts.lockedAnswer, 1.17.2; IAWL
* idea 6). Shared by lockedAnswer.test.ts (default, 2FA on), lockedAnswer2fa-off.test.ts (2FA off) and
* lockedAnswerPayload.test.ts (`lockedAnswer: 'payload'`): one Payload per file.
* Database: SQLite in memory, or IPAL_TEST_POSTGRES_URI / IPAL_TEST_MONGO_URI (test/http/db.ts).
*/
import type { Payload } from 'payload'
import { payloadTotp } from '@clocklimited/payload-2fa'
import { lexicalEditor } from '@payloadcms/richtext-lexical'
import { getPayload } from 'payload'
import { afterAll, beforeAll } from 'vitest'
import { iapl } from '../src/plugin.js'
import { buildTestConfig } from './helpers.js'
import { testDatabase } from './http/db.js'
import { startPayloadServer, type TestServer } from './http/server.js'
export const PASSWORD = 'a-long-test-password-1'
export type Answer = { body: string; status: number }
export function lockedAnswerSite({ lockedAnswer, twoFactor = true }: { lockedAnswer?: 'payload'; twoFactor?: boolean } = {}) {
const state = {} as { payload: Payload; server: TestServer }
beforeAll(async () => {
const config = buildTestConfig({
admin: { user: 'users' },
collections: [
// a visitor collection with Payload's own lock: not staff, not changed
{ slug: 'customers', access: { create: () => true }, auth: { maxLoginAttempts: 3 }, fields: [] },
{ slug: 'media', fields: [], upload: { staticDir: '/tmp/iapl-locked-answer-media' } },
],
db: testDatabase('lockedanswer'),
editor: lexicalEditor(),
plugins: [
iapl({
access: { authCollection: 'users' },
...(lockedAnswer ? { accounts: { lockedAnswer } } : {}),
i18n: { defaultLocale: 'en', locales: [{ code: 'en', label: 'English' }] },
twoFactor: twoFactor ? { issuer: 'Example', plugin: payloadTotp } : false,
}),
],
secret: 'integration-test-secret-0123456789',
telemetry: false,
})
state.payload = await getPayload({ config })
state.server = await startPayloadServer(config)
await state.payload.create({ collection: 'users' as never, data: { email: '[email protected]', password: PASSWORD, roles: ['admin'] } as never })
await state.payload.create({ collection: 'customers' as never, data: { email: '[email protected]', password: PASSWORD } as never })
}, 120_000)
afterAll(async () => {
await state.server?.close()
await state.payload?.destroy?.()
})
const restLogin = async (collection: string, email: string, password: string): Promise<Answer> => {
const res = await fetch(`${state.server.url}/api/${collection}/login`, {
body: JSON.stringify({ email, password }),
headers: { 'content-type': 'application/json' },
method: 'POST',
})
return { body: await res.text(), status: res.status }
}
const gqlLogin = async (mutation: string, email: string, password: string) => {
const res = await fetch(`${state.server.url}/api/graphql`, {
body: JSON.stringify({ query: `mutation { ${mutation}(email: ${JSON.stringify(email)}, password: ${JSON.stringify(password)}) { token } }` }),
headers: { 'content-type': 'application/json' },
method: 'POST',
})
const body = (await res.json()) as { errors?: { extensions?: { name?: string; statusCode?: number }; message: string }[] }
const e = body.errors?.[0]
return { name: e?.extensions?.name, message: e?.message, status: res.status, statusCode: e?.extensions?.statusCode }
}
/** Locks `email` with wrong passwords (Payload's default: 5). */
const lock = async (collection: string, email: string, times = 5) => {
for (let i = 0; i < times; i++) {await restLogin(collection, email, 'a-wrong-password')}
}
return { gqlLogin, lock, restLogin, state }
}
+108
View File
@@ -0,0 +1,108 @@
/**
* IPv6 is counted per network (1.17.2, IAWL idea 9): a /64 is one client in every limiter of the plugin; a second
* counter per /48 when a project turns it on (`setIpv6Grouping({ wide: 48 })`).
*/
import { afterEach, describe, expect, test, vi } from 'vitest'
import { buildConsentLogEndpoint } from '../src/modules/consent/consentLog.js'
import { passRateLimit } from '../src/modules/forms/submitForm.js'
import { checkRateLimit, clientIp, consumeRateLimit, ipRateKey, setIpv6Grouping } from '../src/modules/shared/rateLimit.js'
vi.mock('server-only', () => ({}))
let scope = 0
const nextScope = () => `ipv6-test-${++scope}`
const hex = (n: number) => n.toString(16)
afterEach(() => setIpv6Grouping())
describe('ipRateKey', () => {
test('one key for every address of a /64, whatever the spelling', () => {
const key = ipRateKey('2001:db8:1:2::1')
expect(key).toBe('2001:db8:1:2:0:0:0:0/64')
for (const a of ['2001:db8:1:2:ffff:ffff:ffff:ffff', '2001:0DB8:0001:0002:0000:0000:0000:0042', '[2001:db8:1:2::9]', '2001:db8:1:2::9%eth0']) {
expect([a, ipRateKey(a)]).toEqual([a, key])
}
expect(ipRateKey('2001:db8:1:3::1')).not.toBe(key)
})
test('IPv4 as it is; an IPv4-mapped IPv6 address is its IPv4; anything else unchanged', () => {
expect(ipRateKey('198.51.100.7')).toBe('198.51.100.7')
expect(ipRateKey('::ffff:198.51.100.7')).toBe('198.51.100.7')
expect(ipRateKey('::ffff:c633:6407')).toBe('198.51.100.7')
expect(ipRateKey('')).toBe('')
expect(ipRateKey('not-an-ip')).toBe('not-an-ip')
for (const bad of ['1::2::3', '2001:db8:1:2:3:4:5:6:7', '12345::1', '::ffff:300.1.1.1', 'to:abcdef', 'a:b']) {expect([bad, ipRateKey(bad)]).toEqual([bad, bad])}
expect(ipRateKey('::')).toBe('0:0:0:0:0:0:0:0/64')
expect(ipRateKey('256.1.1.1')).toBe('256.1.1.1')
})
test('setIpv6Grouping: per address again, another prefix; nonsense is refused', () => {
setIpv6Grouping({ prefix: 128 })
expect(ipRateKey('2001:db8::1')).not.toBe(ipRateKey('2001:db8::2'))
setIpv6Grouping({ prefix: 56 })
expect(ipRateKey('2001:db8:0:ff::1')).toBe(ipRateKey('2001:db8:0:1::1'))
expect(() => setIpv6Grouping({ prefix: 0 })).toThrow(/prefix must be/)
expect(() => setIpv6Grouping({ prefix: '64' as never })).toThrow(/prefix must be/)
expect(() => setIpv6Grouping({ prefix: 48, wide: 56 })).toThrow(/shorter prefix/)
})
})
describe('the limiters count a /64 as one client', () => {
test('consumeRateLimit: fifty addresses of one /64 get five requests, not fifty', async () => {
const s = nextScope()
let allowed = 0
for (let i = 1; i <= 50; i++) {
if ((await consumeRateLimit({ key: clientIp(new Headers({ 'x-real-ip': `2001:db8:1:1::${hex(i)}` })), max: 5, scope: s })).ok) {allowed++}
}
expect(allowed).toBe(5)
// another /64 of the same /48 is another client (the wide counter is off by default)
expect((await consumeRateLimit({ key: '2001:db8:1:2::1', max: 5, scope: s })).ok).toBe(true)
})
test('checkRateLimit (the synchronous one) too', () => {
const s = nextScope()
const results = Array.from({ length: 8 }, (_, i) => checkRateLimit({ key: `2001:db8:9:9::${hex(i + 1)}`, max: 3, scope: s }))
expect(results.filter(Boolean)).toHaveLength(3)
})
test('the forms gate (passRateLimit)', async () => {
const results = []
for (let i = 1; i <= 8; i++) {results.push(await passRateLimit({ ip: `2001:db8:abcd:1::${hex(i)}`, maxPerMinute: 5 }))}
expect(results.filter((r) => r === null)).toHaveLength(5)
expect(results[7]).toMatchObject({ reason: 'rate_limited' })
})
test('a plugin endpoint (the consent log, 20 a minute): the 21st address of one /64 gets 429', async () => {
const { handler } = buildConsentLogEndpoint()
const statuses: number[] = []
for (let i = 1; i <= 21; i++) {
const req = { headers: new Headers({ 'x-real-ip': `2001:db8:feed:1::${hex(i)}` }), text: () => Promise.resolve('{') }
statuses.push((await (handler as (r: never) => Promise<Response>)(req as never)).status)
}
expect(statuses.slice(0, 20)).not.toContain(429)
expect(statuses[20]).toBe(429)
})
})
describe('the wide counter (setIpv6Grouping({ wide: 48 }))', () => {
test('three hundred /64s of one /48: at most wideFactor × max requests', async () => {
setIpv6Grouping({ wide: 48, wideFactor: 10 })
const s = nextScope()
let allowed = 0
for (let i = 1; i <= 300; i++) {
if ((await consumeRateLimit({ key: `2001:db8:7:${hex(i)}::1`, max: 5, scope: s })).ok) {allowed++}
}
expect(allowed).toBe(50)
// another /48 is untouched
expect((await consumeRateLimit({ key: '2001:db8:8:1::1', max: 5, scope: s })).ok).toBe(true)
})
test('IPv4 is not affected by it', async () => {
setIpv6Grouping({ wide: 48 })
const s = nextScope()
const ok = []
for (let i = 1; i <= 6; i++) {ok.push((await consumeRateLimit({ key: `198.51.100.${i}`, max: 1, scope: s })).ok)}
expect(ok).toEqual([true, true, true, true, true, true])
})
})