Files
ipal-kit/test/twoFactorResetOriginSuite.ts
T
Radosław SmolińskiandClaude Opus 5.5 6ca0730c08 2FA reset endpoint: only from the site's own origin (twoFactor.sameOrigin)
POST /api/ipal/two-factor/reset reads a text/plain body, which another
origin can send without a CORS preflight; 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. Such a page could reset any account's
TOTP and end its sessions (reproduced on SQLite, Postgres, MongoDB). Now the
endpoint takes the same origin rule as verify and setup, before it reads
or changes anything; twoFactor.sameOrigin: false leaves it out, and
buildTwoFactorResetEndpoint takes ownOrigin for own wiring.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-26 20:18:57 +01:00

68 lines
3.8 KiB
TypeScript

/**
* 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: '[email protected]', password: PASSWORD, roles: ['admin'], totpSecret: SECRET } as never })
const target = (await payload.create({ collection: 'users' as never, data: { email: '[email protected]', password: PASSWORD, roles: ['editor'], totpSecret: SECRET } as never })) as { id: number | string }
const login = await fetch(`${server.url}/api/users/login`, { body: JSON.stringify({ email: '[email protected]', password: PASSWORD }), headers: { 'content-type': 'application/json' }, method: 'POST' })
const first = cookiesOf(login)
const verify = await fetch(`${server.url}/api/verify-totp`, { body: JSON.stringify({ token: totp(SECRET) }), headers: { 'content-type': 'application/json', cookie: first.join('; ') }, method: 'POST' })
const cookie = [...first, ...cookiesOf(verify)].join('; ')
// what a foreign page can send without a preflight: text/plain
const reset = (headers: Record<string, string>) =>
fetch(`${server.url}/api/ipal/two-factor/reset`, { body: JSON.stringify({ userId: target.id }), headers: { 'content-type': 'text/plain', cookie, ...headers }, method: 'POST' })
const secretOf = async () =>
((await payload.findByID({ id: target.id, collection: 'users' as never, overrideAccess: true, showHiddenFields: true })) as { totpSecret?: null | string }).totpSecret ?? null
return { reset, secretOf, server }
}
export const SECRET_VALUE = SECRET
afterAll(async () => {
for (const { payload, server } of opened) {
await server.close()
await payload.destroy?.()
}
})