diff --git a/docs/agent/AGENT.md b/docs/agent/AGENT.md index e1a0eb2..6d979a5 100644 --- a/docs/agent/AGENT.md +++ b/docs/agent/AGENT.md @@ -1221,7 +1221,7 @@ 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)` | -| 2FA verify and setup attempts only from the site's own origin: a request a browser marks as coming from elsewhere (`Origin`, `Sec-Fetch-Site`) gets `403` and is not counted. **Set `serverURL`**: behind a proxy that rewrites `Host` and sends no `X-Forwarded-Host` the site's own page is refused without it (logged once per origin: `[iapl] 2FA: a code from origin … was refused`) | `twoFactor.sameOrigin: false` | `sameOrigin: { origins: ['https://app.example.com'] }`; `requestFromOwnOrigin`, `reportRefusedOrigin` | +| 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 /api/ipal/two-factor/reset -H 'Origin: https://other.example' -H 'Content-Type: text/plain' -b -d '{"userId":1}'` → `403`; the panel's button still works. **Set `serverURL`**: behind a proxy that rewrites `Host` and sends no `X-Forwarded-Host` the site's own page is refused without it (logged once per origin: `[iapl] 2FA: a code from origin … was refused`) | `twoFactor.sameOrigin: false` | `sameOrigin: { origins: ['https://app.example.com'] }`; `requestFromOwnOrigin`, `reportRefusedOrigin` | | Stored secrets are write-only: `smtpPassword` and `turnstileSecretKey` come back as `'********'` over REST, GraphQL and in the panel; an empty save keeps the value, `'[[clear]]'` removes it; server code reads the real value with the Local API. **The panel is the source — never add an env variable for them** (`TURNSTILE_SECRET_KEY` is deprecated) | `secrets: { writeOnly: false }` | `writeOnlySecret(field)` / `writeOnlySecrets(fields, names)` for your own secret fields; with versions on the entity add `hooks.afterRead: [maskSecretsOnRestore]` | | The SMTP password stays with its server: a save in the panel or over the API that changes the server, port or user name without the password is refused (`400` "Enter the password again…"), whatever the transport says — otherwise an admin session points the server at its own machine and a test e-mail hands the password over. A change of the transport alone asks for nothing. Seeds and scripts (Local API, access control off) are not asked | `secrets: { reenterOnChange: false }` | `writeOnlySecret(field, { boundTo: [...] })`, `buildKeepSecret`, `SMTP_PASSWORD_BOUND_TO` | | The admin panel opens for `editor` and above; an account with only `user` sees "Unauthorized" (the API is not touched). First start logs how many accounts are below the role | `accounts: { panelRole: 'user' }` (or `false`) | `panelRole: 'admin'`; your own `access.admin`; `panelAccess(role)` | diff --git a/docs/agent/skills/iapl-reference/SKILL.md b/docs/agent/skills/iapl-reference/SKILL.md index fc29a78..e31bb2f 100644 --- a/docs/agent/skills/iapl-reference/SKILL.md +++ b/docs/agent/skills/iapl-reference/SKILL.md @@ -52,7 +52,7 @@ description: Complete map of everything @intecion/ipal-kit provides — every ia | `twoFactor.texts` | IAPL's en/pl texts (`TOTP_TEXTS`) over the package's; 2FA screens titled "Two-step verification" / "Weryfikacja dwuetapowa" (site's language) | `false` = the package's texts; one text: `i18n.translations..totpPlugin.` (security.md) | | `twoFactor.guard` | on | IAPL's own second-factor check on every collection and global (also the plugin's own and those of plugins listed after iapl) and in `userMeetsRole`; startup fails with `[iapl] twoFactor: the injected 2FA plugin did not add …` when the 2FA package lacks the `totp` strategy / `hasTotp` / `totpSecret` | per entity: `custom.ipal.secondFactor: false` / `{ read: false }` or the package's `custom.totp.disableAccessWrapper.`; `false` = the package's wrapper only (the plugin's own data then opens to a password without the code; not recommended). The package's endpoints stay limited to accounts of the 2FA collection either way | | `twoFactor.verifyLimit` | `{ max: 5, windowMinutes: 10, store: 'database' }` | wrong codes per account on `POST /api/verify-totp` (the 2FA package counts none): after five wrong ones in the window the next attempt, right or wrong, gets `429` + `Retry-After`; a right code gives its place back (1.17.1); an attempt held out only by others still being checked gets `429` + `Retry-After: 2`. Counted in memory and in the database (`payload.kv`, the `payload-kv` collection Payload adds), so a restart or a second instance does not reset it; a failing store never opens the gate | `{ max, windowMinutes }`; `{ store: 'memory' }` = this instance only; `false` = no limit | -| `twoFactor.sameOrigin` | on | `POST /api/verify-totp` and `/api/setup-totp` refuse (`403`, not counted) a request a browser marks as coming from another origin (`Origin`, else `Sec-Fetch-Site`). Own origins: the request's host (`Host`, `X-Forwarded-Host`, a default port written out is ignored), `serverURL`, Payload's `csrf` / `cors`. Requests without those headers pass. A refusal is logged once per origin with how to allow it — behind a proxy that hides the address set `serverURL` | `{ origins: ['https://app.example.com'] }` adds origins; `false` = off | +| `twoFactor.sameOrigin` | on | `POST /api/verify-totp`, `/api/setup-totp` and (1.17.1) the admin's `/api/ipal/two-factor/reset` refuse (`403`, not counted) a request a browser marks as coming from another origin (`Origin`, else `Sec-Fetch-Site`). Own origins: the request's host (`Host`, `X-Forwarded-Host`, a default port written out is ignored), `serverURL`, Payload's `csrf` / `cors`. Requests without those headers pass. A refusal is logged once per origin with how to allow it — behind a proxy that hides the address set `serverURL` | `{ origins: ['https://app.example.com'] }` adds origins; `false` = off | | `twoFactor.requireSetup` | on, `{ windowHours: 72 }` | an account without TOTP reaches nothing but the setup screen and `/api/setup-totp` (REST, GraphQL and the panel's data answer 403); it has `windowHours` from its creation or from an admin's reset, then it is blocked until an admin reopens setup. Adds the field `totpSetupStatus` (panel) to the 2FA collection, a dashboard notice and `POST /api/ipal/two-factor/reset`; the date field `totpSetupFrom` is there whenever 2FA is on (also with `requireSetup: false` / `guard: false`). Existing accounts get their window at the first start after the upgrade, written once. **Postgres/SQLite: the migration must be applied when the new container starts — `prodMigrations` or `pnpm payload migrate && pnpm start`, not a pre-deployment command (deployment.md §4.3) — or every login answers 500**; `generate:importmap`. `exempt` must return exactly `true` at once (an `async` one, or a `windowHours` that is not a number / `false`, stops the start) | `false` = the package's rule (API open until setup); `{ windowHours: 24 }`, `{ windowHours: false }` (no limit), `{ exempt: ({ user }) => … }` (a service account) | | `twoFactor.requireSetup.dashboardNotice` / `.statusField` / `.setupNotice` | on | the administrators' notice on the dashboard; the status and reset control on the account page; the notice on the setup screen | `false` each (the lock and the reset endpoint stay) | | `twoFactor.resetAccess` (the endpoint exists with `twoFactor.guard` on; `guard: false` = no endpoint, 404) | a staff admin whose session entered its own TOTP code (not an API key, not an `exempt` account) | who may reset another account's TOTP / reopen its setup (the button on the account page, `POST /api/ipal/two-factor/reset`). The reset clears the secret and the account's sessions. A session that still owes its code is always refused | `({ req }) => boolean` — replaces the rule, so keep `req.user?._strategy === 'totp' &&` in it unless API-key / exempt admins should reset; only `true` allows; `req.user._strategy` tells `'totp'`, `'api-key'`, `'local-jwt'` apart | diff --git a/docs/agent/skills/iapl-reference/resources/api.md b/docs/agent/skills/iapl-reference/resources/api.md index ce9d5e2..aa08390 100644 --- a/docs/agent/skills/iapl-reference/resources/api.md +++ b/docs/agent/skills/iapl-reference/resources/api.md @@ -619,7 +619,7 @@ Server only (`pnpm payload run`); never import it from client code, the Payload | `SAFE_TOTP_VIEW` / `totpViewImportKey(component)` | `@intecion/ipal-kit` | `'@intecion/ipal-kit/admin#SafeTotpView'`, the wrapper's import-map path (the default `wrapper` of `wrapTotpViews`); and the import-map key (`path#export`) of a component given as a string or `{ path, exportName }`. | | `findImportMapFile(config, cwd?)` / `missingImportMapEntries(config, entries, cwd?)` | `@intecion/ipal-kit` | Where the project's `importMap.js` is on disk (`admin.importMap.importMapFile`, else `app/(payload)/` or `src/app/…` under `admin.importMap.baseDir` / the working directory; `null` when not found), and which of `entries` its text does not contain (`{ file, missing }`). A hint from the file on disk, not the map in the build: warn on it, never block on it. Behind `twoFactor.importMapCheck`. | | `buildSetupFields({ statusField? })`, `stampSetupFrom`, `backfillSetupFrom(payload, collection)` | `@intecion/ipal-kit` | The parts of "2FA setup required" for a project that wires them itself: the fields for the 2FA collection (`totpSetupFrom`, and the panel's `totpSetupStatus` unless `statusField: false`), the `beforeChange` hook that stamps the window start (on create, and when an account loses its TOTP secret), and the start-up step that gives accounts without TOTP and without a start their window (returns how many; once per account). | -| `buildTwoFactorResetEndpoint(collection, { access? })`, `TWO_FACTOR_RESET_PATH` | `@intecion/ipal-kit` | `POST /api/ipal/two-factor/reset` `{ userId }`: clears the account's TOTP secret and sessions and starts a new window. Default: a staff admin whose session entered its own TOTP code; `access` replaces that (only `true` allows; a session that owes its code is always refused). `iapl` registers it only with `twoFactor.guard` on. | +| `buildTwoFactorResetEndpoint(collection, { access?, ownOrigin? })`, `TWO_FACTOR_RESET_PATH` | `@intecion/ipal-kit` | `POST /api/ipal/two-factor/reset` `{ userId }`: clears the account's TOTP secret and sessions and starts a new window. `ownOrigin(req)` false → `403` before anything changes (the plugin passes the `twoFactor.sameOrigin` rule; wire `requestFromOwnOrigin` when you build it yourself). Default: a staff admin whose session entered its own TOTP code; `access` replaces that (only `true` allows; a session that owes its code is always refused). `iapl` registers it only with `twoFactor.guard` on. | | `countAccountsWithoutTotp(payload, collection, setupWindowMs?)` | `@intecion/ipal-kit` | `{ without, blocked }` — accounts of the 2FA collection without TOTP, and how many are past their window. | | `resolveRequireSetup(option)`, `strictExempt(fn)`, `SETUP_FROM_FIELD`, `DEFAULT_SETUP_WINDOW_HOURS` | `@intecion/ipal-kit` | `twoFactor.requireSetup` → `{ requireSetup, setupWindowMs, exempt? }` as the guard reads it (throws on a `windowHours` that is not a number ≥ 0 or `false`, and on an `async` `exempt`); the wrapper that makes an `exempt` function answer `true` only for exactly `true`; the field name `'totpSetupFrom'`; `72`. | | `fetchPublicImage(url, base)`, `publicImageDataUri(url, base)`, `rasterImageType(bytes)`, `siteOrigin(serverURL)`, `PUBLIC_IMAGE_MAX_BYTES` | `@intecion/ipal-kit` | An image fetched the way an anonymous visitor gets it (no cookies; http(s) only; `image/*`; at most 512 KB, reading stops at the limit) as `{ bytes, type }` or a `data:` address, else `null`. Used for the logo and icon on the 2FA screens. `rasterImageType(bytes)` → the media type of a bitmap by its first bytes (PNG, JPEG, GIF, WebP, ICO, AVIF) or `null` — never trust a claimed type before answering a file's bytes from the site's origin; an SVG gives `null`. | diff --git a/docs/security.md b/docs/security.md index 5660932..5a09063 100644 --- a/docs/security.md +++ b/docs/security.md @@ -636,7 +636,11 @@ request came in on (`Host`, `X-Forwarded-Host`), `serverURL`, Payload's `csrf` a `twoFactor: { …, sameOrigin: { origins: ['https://app.example.com'] } }` for a front end on another domain. A request with neither header (a script, `curl`, a server) passes: it cannot ride on somebody's cookie. A default port written out (`X-Forwarded-Host: site.example:443`) is the same host. -`sameOrigin: false` turns it off. +**The admin's reset** (`POST /api/ipal/two-factor/reset`, "Reset two-step verification" / "Reopen setup") follows +the same rule since 1.17.1: it reads a `text/plain` body, which a foreign page can send without a CORS preflight, +so before a page on a sibling subdomain could reset any account's TOTP and end its sessions with an admin's +cookie. The panel's own button is on the site's origin and is not affected. +`sameOrigin: false` turns it off (verify, setup and the reset). **Behind a reverse proxy that hides the site's address** — it rewrites `Host` and sends no `X-Forwarded-Host` (nginx's plain `proxy_pass`; Traefik and Coolify keep `Host`) — and without `serverURL`, the server cannot know diff --git a/src/modules/security/totp/setupRequired.ts b/src/modules/security/totp/setupRequired.ts index 22e455d..2aefe21 100644 --- a/src/modules/security/totp/setupRequired.ts +++ b/src/modules/security/totp/setupRequired.ts @@ -240,6 +240,14 @@ export type TwoFactorResetOptions = { * if you return true for it (`req.user._strategy` tells them apart). */ access?: (args: { req: PayloadRequest }) => boolean | Promise + /** + * Whether the request may come from where the browser says it comes from (sameOrigin.ts). False = + * refused (403) before anything is read or changed. The plugin passes the `twoFactor.sameOrigin` rule + * (on by default; `sameOrigin: false` leaves it out). Without it the endpoint takes a cross-origin + * `text/plain` POST — no CORS preflight — so a page on a sibling subdomain, which the browser sends the + * admin's `SameSite=Lax` cookie to, could reset any account's TOTP and end its sessions. + */ + ownOrigin?: (req: PayloadRequest) => boolean } /** @@ -267,6 +275,7 @@ export function buildTwoFactorResetEndpoint(collection: string, options: TwoFact ? (await options.access({ req })) === true : (req.user as { _strategy?: unknown })._strategy === 'totp' && userMeetsRole(req, 'admin')) if (!allowed) {return Response.json({ message: serverText(i18n, 'twoFactorResetForbidden'), ok: false }, { status: 403 })} + if (options.ownOrigin && !options.ownOrigin(req)) {return Response.json({ message: 'Not allowed from this origin.', ok: false }, { status: 403 })} let body: unknown try { body = await req.json?.() diff --git a/src/plugin.ts b/src/plugin.ts index 22cf24b..e947ca6 100644 --- a/src/plugin.ts +++ b/src/plugin.ts @@ -394,7 +394,7 @@ export const iapl = (options: IaplOptions): Plugin => { } } // An admin resets an account's TOTP (lost phone) / reopens its setup window. - config.endpoints = [...(config.endpoints ?? []), buildTwoFactorResetEndpoint(target, { access: tf.resetAccess })] + config.endpoints = [...(config.endpoints ?? []), buildTwoFactorResetEndpoint(target, { access: tf.resetAccess, ...(guards.ownOrigin ? { ownOrigin: guards.ownOrigin } : {}) })] // Called by Payload on every request before any access function: guards whatever // the live config has that was added after iapl (start, dev hot reload). const sweep = buildGuardStrategy(adoptConfig) diff --git a/test/twoFactorResetOrigin.test.ts b/test/twoFactorResetOrigin.test.ts new file mode 100644 index 0000000..d052677 --- /dev/null +++ b/test/twoFactorResetOrigin.test.ts @@ -0,0 +1,22 @@ +/** POST /api/ipal/two-factor/reset only from the own origin (1.17.1): twoFactorResetOriginSuite.ts. */ +import { describe, expect, test, vi } from 'vitest' + +import { clearReportedOrigins } from '../src/modules/security/totp/sameOrigin.js' +import { SECRET_VALUE, SIBLING, site } from './twoFactorResetOriginSuite.js' + +vi.mock('server-only', () => ({})) +vi.mock('next/headers.js', async () => (await import('./http/server.js')).nextHeadersMock) + +describe('the 2FA reset endpoint and the origin of the request', () => { + test('a page on a sibling subdomain is refused and nothing changes; the site itself still resets', async () => { + clearReportedOrigins() + const { reset, secretOf, server } = await site() + expect((await reset(SIBLING)).status).toBe(403) + expect(await secretOf()).toBe(SECRET_VALUE) + expect((await reset({ 'sec-fetch-site': 'cross-site' })).status).toBe(403) + expect(await secretOf()).toBe(SECRET_VALUE) + const own = await reset({ origin: server.url, 'sec-fetch-site': 'same-origin' }) + expect([own.status, ((await own.json()) as { ok?: boolean }).ok]).toEqual([200, true]) + expect(await secretOf()).toBeNull() + }) +}) diff --git a/test/twoFactorResetOriginOff.test.ts b/test/twoFactorResetOriginOff.test.ts new file mode 100644 index 0000000..fadce97 --- /dev/null +++ b/test/twoFactorResetOriginOff.test.ts @@ -0,0 +1,15 @@ +/** twoFactor.sameOrigin: false leaves the origin check of the 2FA reset endpoint out (twoFactorResetOriginSuite.ts). */ +import { describe, expect, test, vi } from 'vitest' + +import { SIBLING, site } from './twoFactorResetOriginSuite.js' + +vi.mock('server-only', () => ({})) +vi.mock('next/headers.js', async () => (await import('./http/server.js')).nextHeadersMock) + +describe('the 2FA reset endpoint with sameOrigin: false', () => { + test('a request from a sibling subdomain is taken, as before 1.17.1', async () => { + const { reset, secretOf } = await site(false) + expect((await reset(SIBLING)).status).toBe(200) + expect(await secretOf()).toBeNull() + }) +}) diff --git a/test/twoFactorResetOriginSuite.ts b/test/twoFactorResetOriginSuite.ts new file mode 100644 index 0000000..8ed6d07 --- /dev/null +++ b/test/twoFactorResetOriginSuite.ts @@ -0,0 +1,67 @@ +/** + * POST /api/ipal/two-factor/reset only from the site's own origin (1.17.1). The endpoint reads a `text/plain` body + * as JSON, and such a cross-origin POST needs no CORS preflight; a page on a sibling subdomain is "same site", so the + * browser sends the admin's `SameSite=Lax` cookie, and Payload's CSRF list is empty without `serverURL` / `csrf`. + * Before, that page could reset any account's TOTP and end its sessions. Through real HTTP requests. + * Shared by twoFactorResetOrigin.test.ts and twoFactorResetOriginOff.test.ts (one Payload per file). + * Database: SQLite in memory, or IPAL_TEST_POSTGRES_URI / IPAL_TEST_MONGO_URI (test/http/db.ts). + */ +import type { Payload } from 'payload' + +import { payloadTotp } from '@clocklimited/payload-2fa' +import { lexicalEditor } from '@payloadcms/richtext-lexical' +import { getPayload } from 'payload' +import { afterAll } from 'vitest' + +import { clearReportedOrigins } from '../src/modules/security/totp/sameOrigin.js' +import { iapl } from '../src/plugin.js' +import { buildTestConfig } from './helpers.js' +import { testDatabase } from './http/db.js' +import { cookiesOf, startPayloadServer, type TestServer } from './http/server.js' +import { totp } from './http/totp.js' + +const SECRET = 'JBSWY3DPEHPK3PXP' +const PASSWORD = 'a-long-test-password-1' +export const SIBLING = { origin: 'https://blog.site.example', 'sec-fetch-site': 'same-site' } +const opened: Array<{ payload: Payload; server: TestServer }> = [] + +export async function site(sameOrigin?: false) { + const config = buildTestConfig({ + admin: { user: 'users' }, + collections: [{ slug: 'media', fields: [], upload: { staticDir: '/tmp/iapl-reset-origin-media' } }], + db: testDatabase(`resetorigin${sameOrigin === false ? 'off' : ''}`), + editor: lexicalEditor(), + plugins: [ + iapl({ + access: { authCollection: 'users' }, + i18n: { defaultLocale: 'en', locales: [{ code: 'en', label: 'English' }] }, + twoFactor: { issuer: 'Example', plugin: payloadTotp, ...(sameOrigin === false ? { sameOrigin } : {}) }, + }), + ], + secret: 'integration-test-secret-0123456789', + telemetry: false, + }) + const payload = await getPayload({ config }) + const server = await startPayloadServer(config) + opened.push({ payload, server }) + await payload.create({ collection: 'users' as never, data: { email: 'admin@example.com', password: PASSWORD, roles: ['admin'], totpSecret: SECRET } as never }) + const target = (await payload.create({ collection: 'users' as never, data: { email: 'editor@example.com', password: PASSWORD, roles: ['editor'], totpSecret: SECRET } as never })) as { id: number | string } + const login = await fetch(`${server.url}/api/users/login`, { body: JSON.stringify({ email: 'admin@example.com', password: PASSWORD }), headers: { 'content-type': 'application/json' }, method: 'POST' }) + const first = cookiesOf(login) + const verify = await fetch(`${server.url}/api/verify-totp`, { body: JSON.stringify({ token: totp(SECRET) }), headers: { 'content-type': 'application/json', cookie: first.join('; ') }, method: 'POST' }) + const cookie = [...first, ...cookiesOf(verify)].join('; ') + // what a foreign page can send without a preflight: text/plain + const reset = (headers: Record) => + fetch(`${server.url}/api/ipal/two-factor/reset`, { body: JSON.stringify({ userId: target.id }), headers: { 'content-type': 'text/plain', cookie, ...headers }, method: 'POST' }) + const secretOf = async () => + ((await payload.findByID({ id: target.id, collection: 'users' as never, overrideAccess: true, showHiddenFields: true })) as { totpSecret?: null | string }).totpSecret ?? null + return { reset, secretOf, server } +} + +export const SECRET_VALUE = SECRET +afterAll(async () => { + for (const { payload, server } of opened) { + await server.close() + await payload.destroy?.() + } +})