From b52193ae479e6a68ed20d50af5d5a730bda0e885 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rados=C5=82aw=20Smoli=C5=84ski?= Date: Tue, 24 Nov 2026 20:31:44 +0100 Subject: [PATCH] 2FA setup required: the missing-column log reads the error's cause chain MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit R3-1: the SQL adapters throw "Failed query: …" and put the database's own words ("column … does not exist", "no such column") in the error's cause, so the loud start-up line never appeared on a real Postgres or SQLite. The reason is now built from the whole cause chain; other failures (ECONNREFUSED, a locked database) still only warn. Tested with wrapped errors and against the real adapter with the column dropped. Docs and the doctor's fix text name how the migration is applied (deployment.md 4.3) wherever they said only "before the site serves". Co-Authored-By: Claude Fable 5.2 --- docs/agent/AGENT.md | 2 +- docs/agent/skills/ipal-reference/SKILL.md | 2 +- docs/agent/skills/ipal-setup/SKILL.md | 4 +- docs/dev/PROGRAMISTA.md | 2 +- .../.agents/skills/ipal-reference/SKILL.md | 2 +- reference/.agents/skills/ipal-setup/SKILL.md | 4 +- src/modules/doctor/rules/security.ts | 4 +- src/modules/security/totp/setupRequired.ts | 17 ++++- test/secondFactorGuard.test.ts | 33 +++++++++ test/setupColumnMissing.test.ts | 72 +++++++++++++++++++ 10 files changed, 133 insertions(+), 9 deletions(-) create mode 100644 test/setupColumnMissing.test.ts diff --git a/docs/agent/AGENT.md b/docs/agent/AGENT.md index 5666e7e..8c0a9f1 100644 --- a/docs/agent/AGENT.md +++ b/docs/agent/AGENT.md @@ -1165,7 +1165,7 @@ add missing hosts with flags / `extra`; (3) change `mode` to `'enforce'` in both | Injected `users`: admin manages everyone, others only themselves | — | `access.authAccess` (your keys win); your own `users` collection wins whole | | First registered account = admin | `access.firstUserAdmin: false` | `buildRolesField(defaultRole, { firstUserAdmin })` | | 2FA on the panel's login collection, mismatch = startup error; redirect to the 2FA screens by `TotpRedirectProvider` | `twoFactor: false` (discouraged) | `twoFactor.collectionSlug`, `allowCollectionMismatch: true`, `twoFactor.provider` (own component, or `false` for the package's) | -| 2FA setup required: an account without TOTP reaches only the setup screen; 72 h window from creation / admin reset, then blocked; status and "Reopen setup" on the account page, notice on the dashboard, `POST /api/ipal/two-factor/reset` | `twoFactor.requireSetup: false`; parts: `requireSetup: { dashboardNotice: false, statusField: false, setupNotice: false }` | `requireSetup: { windowHours, exempt }` (`exempt` returns exactly `true`, never `async`), `twoFactor.resetAccess` (default: an admin who entered its own code; the reset ends the account's sessions), texts `twoFactor*`; `twoFactorSetupState(req)`, `buildSetupFields`, `backfillSetupFrom`, `buildTwoFactorResetEndpoint`. **Postgres/SQLite: migration for `totp_setup_from` before the version serves, or every login answers 500** | +| 2FA setup required: an account without TOTP reaches only the setup screen; 72 h window from creation / admin reset, then blocked; status and "Reopen setup" on the account page, notice on the dashboard, `POST /api/ipal/two-factor/reset` | `twoFactor.requireSetup: false`; parts: `requireSetup: { dashboardNotice: false, statusField: false, setupNotice: false }` | `requireSetup: { windowHours, exempt }` (`exempt` returns exactly `true`, never `async`), `twoFactor.resetAccess` (default: an admin who entered its own code; the reset ends the account's sessions), texts `twoFactor*`; `twoFactorSetupState(req)`, `buildSetupFields`, `backfillSetupFrom`, `buildTwoFactorResetEndpoint`. **Postgres/SQLite: migration for `totp_setup_from` applied when the new container starts (`prodMigrations` or `pnpm payload migrate && pnpm start`; never a pre-deployment command — deployment.md §4.3), or every login answers 500** | | The second factor on every collection and global, whichever plugin added it, and on the plugin's endpoints; an unrecognised 2FA package = startup error | per entity: `custom.ipal.secondFactor: false` or `{ read: false }` (or the package's `custom.totp.disableAccessWrapper`); everywhere: `twoFactor.guard: false` (not recommended) | `requireSecondFactor` / `secondFactorPassed` in your own access functions and endpoints | | At most 5 verify attempts per account in 10 minutes (`POST /api/verify-totp` → `429`) | `twoFactor.verifyLimit: false` | `verifyLimit: { max, windowMinutes }` | | The `back` link of the 2FA setup and verify screens is checked on the server (`SafeTotpView` in front of the package's views): only a path on the site's origin inside the admin route is kept, anything else (`javascript:`, another host) becomes the admin root. Needs `generate:importmap` in the same deploy — with a stale map the 2FA screens have no code form and nobody can sign in (`ipal-doctor`, the start log and a notice above the screen report it; the notice is a hint from the file on disk and never replaces the screen; `twoFactor.importMapCheck: false` turns it off); check: password only → `/admin/verify-totp?back=https%3A%2F%2Fexample.com%2F` → code → lands on `/admin` | `twoFactor.safeBack: false` | `safeBack: (back, { adminRoute, origin }) => string`; `safeAdminBack`, `wrapTotpViews` (`@intecion/ipal-kit`), `SafeTotpView` (`@intecion/ipal-kit/admin`) for own views | diff --git a/docs/agent/skills/ipal-reference/SKILL.md b/docs/agent/skills/ipal-reference/SKILL.md index 7ce674b..217dacc 100644 --- a/docs/agent/skills/ipal-reference/SKILL.md +++ b/docs/agent/skills/ipal-reference/SKILL.md @@ -42,7 +42,7 @@ description: Complete map of everything @intecion/ipal-kit provides — every ip | `twoFactor.texts` | ipal-kit'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 | ipal-kit's own second-factor check on every collection and global (also the plugin's own and those of plugins listed after ipalKit) and in `userMeetsRole`; startup fails with `[ipal] 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 }` | attempts per account on `POST /api/verify-totp` (the 2FA package counts none): the sixth in the window, right or wrong, gets `429` + `Retry-After`; in memory per instance | `{ max, windowMinutes }`; `false` = no limit | -| `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 run before the version serves, 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` | 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 | | `whiteLabel.inlineImages` | on | on the 2FA screens the logo / icon is fetched by the server as an anonymous visitor gets it (max 512 KB) and inlined as `data:` — the session there is refused `media` | `false` = the browser tries the media URL | diff --git a/docs/agent/skills/ipal-setup/SKILL.md b/docs/agent/skills/ipal-setup/SKILL.md index df8ca1f..052fd52 100644 --- a/docs/agent/skills/ipal-setup/SKILL.md +++ b/docs/agent/skills/ipal-setup/SKILL.md @@ -237,7 +237,9 @@ the panel shows Site settings, Site integrations, Cookies, Form messages, the Fo **Setup required** (`twoFactor.requireSetup`, default): an account without TOTP reaches only the setup screen; it has 72 h from its creation (or an admin's "Reopen setup" on the account page), then it is blocked. So create an account, hand over the password and have the owner set 2FA up at once. **Postgres/SQLite: `pnpm payload - migrate:create` and run the migration before the site serves** (column `totp_setup_from`, there whenever 2FA is + migrate:create` and have the migration applied when the container starts, before the site serves** — `prodMigrations` + or the start command `pnpm payload migrate && pnpm start`, never a pre-deployment command (deployment.md §4.3) + (column `totp_setup_from`, there whenever 2FA is on) — without it every login answers 500; `pnpm payload generate:importmap` (`TwoFactorStatusField`, `TwoFactorAlert`). A service account that logs in with a password: `requireSetup: { exempt }` (a plain function returning exactly `true`; never `async`); an API key needs nothing. Parts to switch off: `requireSetup: diff --git a/docs/dev/PROGRAMISTA.md b/docs/dev/PROGRAMISTA.md index adef6a7..4bdd59b 100644 --- a/docs/dev/PROGRAMISTA.md +++ b/docs/dev/PROGRAMISTA.md @@ -675,7 +675,7 @@ Do one item at a time, build, check. Order by importance: | 65 | **1.16.4 — security** — with 2FA on, a login with the password only gets `200` from `/api/globals/site-integrations` or `/api/form-submissions`; or the project has a second auth collection (`customers`) | Upgrade and redeploy (no config change with one auth collection). With the owner: change the SMTP password and the Turnstile secret, review Site settings / Site integrations / each form's Emails tab for values nobody set. Second auth collection: `admin: { user }` in `buildConfig`, `adminOrSelfIn('')`, `access.staffCollections` only for a second STAFF collection. Every account must have 2FA set up (`ipal-doctor --url` → 0 without). Own endpoints: `secondFactorPassed(req)`; own `overrideAccess: false` calls: `user` from `payload.auth()`. `pnpm ipal:skills`; no migration | CHANGELOG 1.16.4, security.md "What the second factor covers", access.md "Who is staff" | | 66 | **1.16.4** — production `PAYLOAD_SECRET` shorter than 32 characters (the site would stop at `assertEnv`) | Before deploying 1.16.4, check the length in Coolify (`node -e 'console.log(process.env.PAYLOAD_SECRET.length)'`). Shorter: a random 32+ character secret (logs everyone out, asks for 2FA again, breaks stored API keys), or `ipalEnvRules({ secretMinLength: 0 })` for now | CHANGELOG 1.16.4, deployment.md "PAYLOAD_SECRET — length and changing it" | | 67 | **1.16.5 — security** — with 2FA on, `/admin/verify-totp?back=https%3A%2F%2Fexample.com%2F` sends the user to example.com after the code (and `back=javascript:…` runs script in the panel) | Upgrade and, **in ONE deploy**, `pnpm payload generate:importmap` (adds `@intecion/ipal-kit/admin#SafeTotpView`), commit `importMap.js`, `rm -rf .next`, redeploy on Coolify — with the old map the 2FA screens have no code form and nobody can sign in (run `pnpm exec ipal-doctor` before deploying; the start log says so too); check: the link above ends on `/admin`. `pnpm ipal:skills`. No option, env or migration; off / own rule: `twoFactor.safeBack` | CHANGELOG 1.16.5, security.md "The `back` link of the 2FA screens" | -| 68 | **Unreleased — 2FA setup required** — an account that has not set 2FA up still reads data over the API with its password; or after the upgrade an account "can do nothing" / is blocked | Before upgrading: `ipal-doctor --url` → accounts without 2FA set it up or are removed; one admin must have 2FA. Then: update, `generate:types`, `generate:importmap` (`TwoFactorStatusField`, `TwoFactorAlert`), **Postgres/SQLite: `migrate:create` and the migration applied in the same deploy (column `totp_setup_from`) — without it every login answers 500**, build, redeploy. Existing accounts get 72 h from the first start; blocked later → admin: account page → "Reopen setup". Password-login integrations: API key or `requireSetup.exempt`. `pnpm ipal:skills` | CHANGELOG "Unreleased — 2FA setup required", security.md "Setup required" | +| 68 | **Unreleased — 2FA setup required** — an account that has not set 2FA up still reads data over the API with its password; or after the upgrade an account "can do nothing" / is blocked | Before upgrading: `ipal-doctor --url` → accounts without 2FA set it up or are removed; one admin must have 2FA. Then: update, `generate:types`, `generate:importmap` (`TwoFactorStatusField`, `TwoFactorAlert`), **Postgres/SQLite: `migrate:create` and the migration applied in the same deploy when the new container starts — `prodMigrations` or `pnpm payload migrate && pnpm start`, never a pre-deployment command (deployment.md §4.3) — (column `totp_setup_from`); without it every login answers 500**, build, redeploy. Existing accounts get 72 h from the first start; blocked later → admin: account page → "Reopen setup". Password-login integrations: API key or `requireSetup.exempt`. `pnpm ipal:skills` | CHANGELOG "Unreleased — 2FA setup required", security.md "Setup required" | After updating the package: `pnpm ipal:skills` (new skill versions), `pnpm payload generate:importmap`, `rm -rf .next`, restart dev, grep for the new symbol in `node_modules/@intecion/ipal-kit/dist`. diff --git a/reference/.agents/skills/ipal-reference/SKILL.md b/reference/.agents/skills/ipal-reference/SKILL.md index 7ce674b..217dacc 100644 --- a/reference/.agents/skills/ipal-reference/SKILL.md +++ b/reference/.agents/skills/ipal-reference/SKILL.md @@ -42,7 +42,7 @@ description: Complete map of everything @intecion/ipal-kit provides — every ip | `twoFactor.texts` | ipal-kit'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 | ipal-kit's own second-factor check on every collection and global (also the plugin's own and those of plugins listed after ipalKit) and in `userMeetsRole`; startup fails with `[ipal] 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 }` | attempts per account on `POST /api/verify-totp` (the 2FA package counts none): the sixth in the window, right or wrong, gets `429` + `Retry-After`; in memory per instance | `{ max, windowMinutes }`; `false` = no limit | -| `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 run before the version serves, 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` | 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 | | `whiteLabel.inlineImages` | on | on the 2FA screens the logo / icon is fetched by the server as an anonymous visitor gets it (max 512 KB) and inlined as `data:` — the session there is refused `media` | `false` = the browser tries the media URL | diff --git a/reference/.agents/skills/ipal-setup/SKILL.md b/reference/.agents/skills/ipal-setup/SKILL.md index df8ca1f..052fd52 100644 --- a/reference/.agents/skills/ipal-setup/SKILL.md +++ b/reference/.agents/skills/ipal-setup/SKILL.md @@ -237,7 +237,9 @@ the panel shows Site settings, Site integrations, Cookies, Form messages, the Fo **Setup required** (`twoFactor.requireSetup`, default): an account without TOTP reaches only the setup screen; it has 72 h from its creation (or an admin's "Reopen setup" on the account page), then it is blocked. So create an account, hand over the password and have the owner set 2FA up at once. **Postgres/SQLite: `pnpm payload - migrate:create` and run the migration before the site serves** (column `totp_setup_from`, there whenever 2FA is + migrate:create` and have the migration applied when the container starts, before the site serves** — `prodMigrations` + or the start command `pnpm payload migrate && pnpm start`, never a pre-deployment command (deployment.md §4.3) + (column `totp_setup_from`, there whenever 2FA is on) — without it every login answers 500; `pnpm payload generate:importmap` (`TwoFactorStatusField`, `TwoFactorAlert`). A service account that logs in with a password: `requireSetup: { exempt }` (a plain function returning exactly `true`; never `async`); an API key needs nothing. Parts to switch off: `requireSetup: diff --git a/src/modules/doctor/rules/security.ts b/src/modules/doctor/rules/security.ts index 555bb7e..5347d50 100644 --- a/src/modules/doctor/rules/security.ts +++ b/src/modules/doctor/rules/security.ts @@ -117,10 +117,10 @@ export const securityRules: DoctorRule[] = [ const files = dirs.flatMap((dir) => ctx.list(dir).filter((name) => /\.(?:ts|js|mjs|sql|json)$/.test(name)).map((name) => `${dir}/${name}`)) if (!files.some((file) => /totp_setup_from|totpSetupFrom/.test(ctx.read(file)))) { out.push({ - fix: 'pnpm payload migrate:create, commit the migration, and run it (pnpm payload migrate) in the same deploy, before the new version serves requests', + fix: 'pnpm payload migrate:create, commit the migration, and have it applied when the new container starts — prodMigrations in the adapter, or the start command `pnpm payload migrate && pnpm start`; not a pre-deployment command (docs/deployment.md §4.3) — in the same deploy, before the new version serves requests', message: files.length ? 'no migration adds the 2FA column `totp_setup_from`: in production every login would answer 500 — nobody could sign in to the panel' - : 'a SQL database and no migrations folder: the 2FA column `totp_setup_from` must exist before this version runs in production (migrate:create), or nobody can sign in', + : 'a SQL database and no migrations folder: the 2FA column `totp_setup_from` must exist before this version runs in production (migrate:create; applied at container start — docs/deployment.md §4.3), or nobody can sign in', severity: files.length ? 'error' : 'warning', }) } diff --git a/src/modules/security/totp/setupRequired.ts b/src/modules/security/totp/setupRequired.ts index ba3f203..9e0eaf5 100644 --- a/src/modules/security/totp/setupRequired.ts +++ b/src/modules/security/totp/setupRequired.ts @@ -194,7 +194,9 @@ export async function backfillSetupFrom(payload: BasePayload, collection: string } return totalDocs } catch (err) { - const reason = err instanceof Error ? err.message : String(err) + // The whole chain: Drizzle's own message is "Failed query: …", and what the database said + // ("column … does not exist", "no such column") is in `cause`. + const reason = errorChain(err) // On Postgres / SQLite without the migration the column is missing — and then it is not only this step // that fails: every query on the collection selects the column, so EVERY login answers 500 until it exists. // Only the missing column gets this message — a database that cannot be reached is another problem. @@ -212,6 +214,19 @@ export async function backfillSetupFrom(payload: BasePayload, collection: string } } +/** The messages of an error and of everything in its `cause` chain, outermost first. */ +export function errorChain(err: unknown): string { + const parts: string[] = [] + const seen = new Set() + for (let current: unknown = err; current !== undefined && current !== null && !seen.has(current) && parts.length < 6; current = (current as { cause?: unknown }).cause) { + seen.add(current) + const message = current instanceof Error || typeof (current as { message?: unknown }).message === 'string' ? String((current as { message: unknown }).message) : typeof current === 'string' ? current : '' + if (message && !parts.includes(message)) {parts.push(message)} + if (typeof current !== 'object') {break} + } + return parts.join(' — ') || String(err) +} + export type TwoFactorResetOptions = { /** * Who may reset another account's TOTP. Default: a staff admin whose session has **entered its diff --git a/test/secondFactorGuard.test.ts b/test/secondFactorGuard.test.ts index 3b69abb..b1f9769 100644 --- a/test/secondFactorGuard.test.ts +++ b/test/secondFactorGuard.test.ts @@ -497,6 +497,39 @@ describe('ipalKit and the 2FA plugin', () => { expect(other.logger.warn).toHaveBeenCalledTimes(1) } expect(String(pg.logger.error.mock.calls[0]?.[0])).toMatch(/prodMigrations.*not in a pre-deployment command/s) + + // What the SQL adapters really throw: Drizzle's "Failed query: …" with the database's own words in `cause`. + const wrapped = (name: string, cause: unknown, message = 'Failed query: select count(*) from "users" where …') => { + const logger = { error: vi.fn(), warn: vi.fn() } + return { logger, payload: { count: async () => { throw Object.assign(new Error(message), { cause }) }, db: { name }, logger } } + } + for (const real of [ + wrapped('postgres', Object.assign(new Error('column users.totp_setup_from does not exist'), { code: '42703' })), + wrapped('sqlite', new Error('SQLITE_ERROR: no such column: users.totp_setup_from')), + wrapped('sqlite', { message: 'no such column: totp_setup_from' }), // a plain object as the cause + wrapped('postgres', Object.assign(new Error('driver'), { cause: new Error('column "totp_setup_from" does not exist') })), // two levels down + ]) { + await backfillSetupFrom(real.payload as never, 'users') + expect(real.logger.warn).not.toHaveBeenCalled() + expect(String(real.logger.error.mock.calls[0]?.[0])).toMatch(/NOBODY CAN LOG IN/) + expect(String(real.logger.error.mock.calls[0]?.[0])).toMatch(/totp_setup_from/) // the database's own words are in the line + } + for (const other of [ + wrapped('postgres', Object.assign(new Error('connect ECONNREFUSED 127.0.0.1:5432'), { code: 'ECONNREFUSED' })), + wrapped('sqlite', new Error('SQLITE_BUSY: database is locked')), + wrapped('postgres', new Error('relation "users" does not exist')), + ]) { + await backfillSetupFrom(other.payload as never, 'users') + expect(other.logger.error).not.toHaveBeenCalled() + expect(other.logger.warn).toHaveBeenCalledTimes(1) + } + // a cause that points at itself does not loop + const loop = new Error('Failed query') as { cause?: unknown } & Error + loop.cause = loop + const looping = { logger: { error: vi.fn(), warn: vi.fn() }, payload: {} as Record } + looping.payload = { count: async () => { throw loop }, db: { name: 'postgres' }, logger: looping.logger } + await backfillSetupFrom(looping.payload as never, 'users') + expect(looping.logger.warn).toHaveBeenCalledTimes(1) }) // The reset removes a second factor: by default only a session that entered its own TOTP code may do it. diff --git a/test/setupColumnMissing.test.ts b/test/setupColumnMissing.test.ts new file mode 100644 index 0000000..77c2ad5 --- /dev/null +++ b/test/setupColumnMissing.test.ts @@ -0,0 +1,72 @@ +/** + * Postgres / SQLite without the migration that adds the 2FA column, against the REAL adapter: the start-up step + * must log the loud line (the database's own words are in the error's `cause`, not in its message), and every + * query on the collection fails — which is why the docs call the migration a required step of the same deploy. + * SQLite in memory by default; `IPAL_TEST_POSTGRES_URI` runs it on Postgres. Not for MongoDB (no columns). + */ +import type { Payload } from 'payload' + +import { payloadTotp } from '@clocklimited/payload-2fa' +import { lexicalEditor } from '@payloadcms/richtext-lexical' +import os from 'os' +import path from 'path' +import { getPayload } from 'payload' +import { afterAll, beforeAll, expect, test, vi } from 'vitest' + +import { backfillSetupFrom } from '../src/modules/security/totp/setupRequired.js' +import { ipalKit } from '../src/plugin.js' +import { buildTestConfig } from './helpers.js' +import { testDatabase } from './http/db.js' + +vi.mock('server-only', () => ({})) +vi.mock('next/headers.js', async () => (await import('./http/server.js')).nextHeadersMock) + +const sql = !process.env.IPAL_TEST_MONGO_URI +let payload: Payload + +beforeAll(async () => { + if (!sql) {return} + const config = buildTestConfig({ + admin: { user: 'users' }, + collections: [{ slug: 'media', fields: [], upload: { staticDir: path.join(os.tmpdir(), 'ipal-test-media') } }], + db: testDatabase('setupcol'), + editor: lexicalEditor(), + plugins: [ipalKit({ access: { authCollection: 'users' }, i18n: { defaultLocale: 'en', locales: [{ code: 'en', label: 'English' }] }, twoFactor: { issuer: 'Example', plugin: payloadTotp as never } })], + secret: 'integration-test-secret-0123456789', + telemetry: false, + }) + payload = await getPayload({ config }) +}, 120_000) + +afterAll(async () => { + await payload?.destroy?.() +}) + +test.skipIf(!sql)('without the column: the loud log line, and every query on the collection fails; with it: the window starts', async () => { + await payload.create({ collection: 'users' as never, data: { email: 'before@example.com', password: 'a-long-test-password-1', roles: ['admin'] } as never }) + const db = payload.db as unknown as { client?: { execute: (q: string) => Promise }; name: string; pool?: { query: (q: string) => Promise }; schemaName?: string } + const run = (statement: string) => (db.pool ? db.pool.query(statement) : db.client!.execute(statement)) + const table = db.pool && db.schemaName ? `"${db.schemaName}"."users"` : '"users"' + // the schema as the previous version left it + await run(`ALTER TABLE ${table} DROP COLUMN "totp_setup_from"`) + + const error = vi.spyOn(payload.logger, 'error').mockImplementation(() => undefined as never) + const warn = vi.spyOn(payload.logger, 'warn').mockImplementation(() => undefined as never) + expect(await backfillSetupFrom(payload, 'users')).toBe(0) // does not throw: the public site must keep running + expect(error).toHaveBeenCalledTimes(1) + expect(String(error.mock.calls[0]?.[0])).toMatch(/the column for "totpSetupFrom" is missing.*NOBODY CAN LOG IN.*prodMigrations/s) + expect(warn).not.toHaveBeenCalled() + // what "nobody can log in" means: the account cannot even be read + await expect(payload.find({ collection: 'users' as never })).rejects.toThrow() + await expect(payload.login({ collection: 'users' as never, data: { email: 'before@example.com', password: 'a-long-test-password-1' } as never })).rejects.toThrow() + + // the migration: the column is there → the start-up step gives the existing account its window, once + await run(`ALTER TABLE ${table} ADD COLUMN "totp_setup_from" ${db.pool ? 'timestamp(3) with time zone' : 'text'}`) + error.mockClear() + expect(await backfillSetupFrom(payload, 'users')).toBe(1) + expect(await backfillSetupFrom(payload, 'users')).toBe(0) + expect(error).not.toHaveBeenCalled() + expect((await payload.login({ collection: 'users' as never, data: { email: 'before@example.com', password: 'a-long-test-password-1' } as never })).token).toBeTruthy() + error.mockRestore() + warn.mockRestore() +})