diff --git a/docs/agent/AGENT.md b/docs/agent/AGENT.md index a9a3c92..bee897c 100644 --- a/docs/agent/AGENT.md +++ b/docs/agent/AGENT.md @@ -1227,6 +1227,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)` | +| 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 /api/ipal/test-email -H 'Origin: https://other.example' -H 'Content-Type: text/plain' -b -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 /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. 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` | diff --git a/docs/agent/skills/iapl-debug/SKILL.md b/docs/agent/skills/iapl-debug/SKILL.md index d747a6b..16e17c7 100644 --- a/docs/agent/skills/iapl-debug/SKILL.md +++ b/docs/agent/skills/iapl-debug/SKILL.md @@ -34,6 +34,7 @@ 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 | diff --git a/docs/agent/skills/iapl-reference/SKILL.md b/docs/agent/skills/iapl-reference/SKILL.md index 1375263..6262610 100644 --- a/docs/agent/skills/iapl-reference/SKILL.md +++ b/docs/agent/skills/iapl-reference/SKILL.md @@ -43,6 +43,7 @@ description: Complete map of everything @intecion/ipal-kit provides — every ia | "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)//` 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 | — | diff --git a/docs/agent/skills/iapl-reference/resources/api.md b/docs/agent/skills/iapl-reference/resources/api.md index 9f17bb8..2027fd3 100644 --- a/docs/agent/skills/iapl-reference/resources/api.md +++ b/docs/agent/skills/iapl-reference/resources/api.md @@ -85,6 +85,7 @@ 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. | +| `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`). diff --git a/docs/doctor.md b/docs/doctor.md index 83a6793..c95edac 100644 --- a/docs/doctor.md +++ b/docs/doctor.md @@ -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 | diff --git a/docs/security.md b/docs/security.md index 188c088..c5f6675 100644 --- a/docs/security.md +++ b/docs/security.md @@ -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 /api/ipal/test-email -H 'Origin: https://other.example' -H 'Content-Type: text/plain' + -b -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 — diff --git a/src/index.ts b/src/index.ts index 9c9b257..dd5b336 100644 --- a/src/index.ts +++ b/src/index.ts @@ -28,6 +28,8 @@ export type { PasswordRuleOptions } from './modules/access/passwordRule.js' export { isPasswordRuleHook, staffRuleOf } from './modules/access/ruleMark.js' export type { StaffRuleMark } from './modules/access/ruleMark.js' export { graphqlLoginName, lockedLooksWrong, withLockedAnswer } from './modules/access/lockedAnswer.js' +export { ADMIN_POST_ENDPOINTS, guardAdminEndpoints, requireOwnOrigin } from './modules/security/adminSameOrigin.js' +export type { AdminSameOriginOption } from './modules/security/adminSameOrigin.js' export type { LockedAnswerOption } from './modules/access/lockedAnswer.js' export { adoptLateAuthCollections, diff --git a/src/modules/doctor/rules/security.ts b/src/modules/doctor/rules/security.ts index 358e874..6facf5a 100644 --- a/src/modules/doctor/rules/security.ts +++ b/src/modules/doctor/rules/security.ts @@ -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://']" + 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://']", 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', diff --git a/src/modules/doctor/status.ts b/src/modules/doctor/status.ts index e70e5b6..a091aeb 100644 --- a/src/modules/doctor/status.ts +++ b/src/modules/doctor/status.ts @@ -111,7 +111,9 @@ export async function collectDoctorStatus(payload: BasePayload): Promise 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 = { diff --git a/src/modules/doctor/types.ts b/src/modules/doctor/types.ts index 2a716ff..4164185 100644 --- a/src/modules/doctor/types.ts +++ b/src/modules/doctor/types.ts @@ -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 /** diff --git a/src/modules/security/adminSameOrigin.ts b/src/modules/security/adminSameOrigin.ts new file mode 100644 index 0000000..17b79c3 --- /dev/null +++ b/src/modules/security/adminSameOrigin.ts @@ -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 = [ + ['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): 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>(endpoint: T, origins: string[] = []): T { + const handler = endpoint.handler as (req: PayloadRequest) => Promise | 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, 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)), + } +} diff --git a/src/modules/security/totp/sameOrigin.ts b/src/modules/security/totp/sameOrigin.ts index e427a3b..da54e65 100644 --- a/src/modules/security/totp/sameOrigin.ts +++ b/src/modules/security/totp/sameOrigin.ts @@ -89,21 +89,29 @@ const MAX_REPORTED = 50 * that origin. Without it a site behind a proxy that hides its address has a panel nobody can * enter and a silent log. Returns true when a line was written. */ -export function reportRefusedOrigin(req: RequestLike, extra: string[] = []): boolean { +/** What a refusal line names: the request, the option that allows an origin, and the doc section. Default: 2FA. */ +export type RefusalContext = { docs: string; option: string; what: string } +const TWO_FACTOR_REFUSAL: RefusalContext = { + docs: 'docs/security.md "Verify and setup attempts only from the site\'s own origin"', + option: 'twoFactor: { sameOrigin', + what: '2FA: a code', +} + +export function reportRefusedOrigin(req: RequestLike, extra: string[] = [], context: RefusalContext = TWO_FACTOR_REFUSAL): boolean { const origin = req.headers?.get('origin') - const key = origin ? (originOf(origin) ?? 'null') : `sec-fetch-site: ${req.headers?.get('sec-fetch-site') ?? 'none'}` + const key = `${context.option}|${origin ? (originOf(origin) ?? 'null') : `sec-fetch-site: ${req.headers?.get('sec-fetch-site') ?? 'none'}`}` if (reported.has(key) || reported.size >= MAX_REPORTED) {return false} reported.add(key) const { hosts, origins } = ownOrigins(req, extra) const known = [...origins, ...[...hosts].map((h) => `host ${h}`)].join(', ') || 'none' const how = originOf(origin) ? `If "${originOf(origin)}" is this site's own address (a reverse proxy that rewrites Host and sends no X-Forwarded-Host), set serverURL to it in the Payload config, ` + - `or pass twoFactor: { sameOrigin: { origins: ['${originOf(origin)}'] } }, or make the proxy send X-Forwarded-Host. ` + `or pass ${context.option}: { origins: ['${originOf(origin)}'] } }, or make the proxy send X-Forwarded-Host. ` : 'The browser did not name an origin this site knows. ' req.payload?.logger?.warn( - `[iapl] 2FA: a code from ${origin ? `origin "${origin}"` : `a ${key} request`} was refused and not counted — it is not one of this site's own origins (${known}). ` + + `[iapl] ${context.what} from ${origin ? `origin "${origin}"` : `a ${key.split('|')[1]} request`} was refused${context === TWO_FACTOR_REFUSAL ? ' and not counted' : ''} — it is not one of this site's own origins (${known}). ` + how + - 'If it is a foreign page, this is the protection working. twoFactor: { sameOrigin: false } turns the check off (docs/security.md "Verify and setup attempts only from the site\'s own origin"). Said once per origin.', + `If it is a foreign page, this is the protection working. ${context.option}: false } turns the check off (${context.docs}). Said once per origin.`, ) return true } diff --git a/src/modules/shared/switches.ts b/src/modules/shared/switches.ts index 68c6292..e938976 100644 --- a/src/modules/shared/switches.ts +++ b/src/modules/shared/switches.ts @@ -59,6 +59,12 @@ export function assertPluginSwitches(options: Record): void { 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) diff --git a/src/plugin.ts b/src/plugin.ts index ddae46e..9c4af88 100644 --- a/src/plugin.ts +++ b/src/plugin.ts @@ -50,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' @@ -130,6 +131,8 @@ export const iapl = (options: IaplOptions): Plugin => { async function transform(incomingConfig: Config): Promise { let config = { ...incomingConfig } + /** The project's own endpoints: the panel-action origin rule (adminSameOrigin) is for the plugin's only. */ + const projectEndpoints = new Set(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'] } @@ -1101,6 +1104,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 } } diff --git a/src/types.ts b/src/types.ts index bae1832..c60f2e1 100644 --- a/src/types.ts +++ b/src/types.ts @@ -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' }`. diff --git a/test/adminSameOrigin.test.ts b/test/adminSameOrigin.test.ts new file mode 100644 index 0000000..ac13ece --- /dev/null +++ b/test/adminSameOrigin.test.ts @@ -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) + }) +}) diff --git a/test/adminSameOriginOff.test.ts b/test/adminSameOriginOff.test.ts new file mode 100644 index 0000000..d743d17 --- /dev/null +++ b/test/adminSameOriginOff.test.ts @@ -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/) + }) +}) diff --git a/test/adminSameOriginSuite.ts b/test/adminSameOriginSuite.ts new file mode 100644 index 0000000..a02a300 --- /dev/null +++ b/test/adminSameOriginSuite.ts @@ -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: 'admin@example.com', password: PASSWORD, roles: ['admin'], totpSecret: SECRET } as never }) + const login = await fetch(`${state.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(`${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, body = '{"to":"someone@example.com"}') => + 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 } +} diff --git a/test/doctor.test.ts b/test/doctor.test.ts index 7e83166..f13f21a 100644 --- a/test/doctor.test.ts +++ b/test/doctor.test.ts @@ -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 })