2FA: the first set-up is confirmed by e-mail (twoFactor.confirmByEmail, 1.18.0)
Security audit 2026-12, F0: inside an account's setup window its password alone enrolled an authenticator of the caller's choosing; the owner was locked out. - /setup-totp for an account without a factor: IAPL checks the code, keeps the secret pending (payload-kv), mails a single-use 30-min link to the account and ties it to the enrolling browser; the package's handler (and its -totp cookie) is never used for a first enrolment - GET /api/iapl/two-factor/confirm = a page with one button; POST confirms (own origin, same browser), ends the account's sessions, signs nobody in - notice mails on every enrolment, change, removal / reset (any path) - mail not working: link to the server log, admin confirms on the account page (POST /api/iapl/two-factor/confirm-pending), doctor rule 2fa-enrolment-mail - options and opt-out (confirmByEmail: false), building blocks exported - tests: HTTP suite on SQLite, MongoDB, Postgres; built-site spec in e2e:built; closed doors and judged routes; docs, AGENT.md, skills, changelog Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
co-authored by
Claude Opus 5.5
parent
84717804ae
commit
c9d1f4b340
+1
-1
@@ -554,7 +554,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', 'originKnown', 'pendingCookies', 'plugin', 'staffOnOwnRoles', 'staffOpenToOthers', 'turnstile', 'turnstileSecretFromEnv', 'usersSetupClosed', 'usersWithout2fa', 'visitorWrites'])
|
||||
expect(Object.keys(status).sort()).toEqual(['mail', 'node', 'openSignUp', 'originKnown', 'pendingCookies', 'plugin', 'staffOnOwnRoles', 'staffOpenToOthers', 'turnstile', 'turnstileSecretFromEnv', 'twoFactorConfirm', 'usersSetupClosed', 'usersWithout2fa', 'visitorWrites'])
|
||||
expect(status.usersSetupClosed).toBeNull() // no setup window in this config
|
||||
expect(status.mail).toBeNull() // no Site integrations global in this config
|
||||
})
|
||||
|
||||
@@ -0,0 +1,62 @@
|
||||
/**
|
||||
* twoFactor.confirmByEmail building blocks: the switch is read strictly, the code check agrees with the 2FA package's
|
||||
* own (RFC 6238 vectors; one period either side, like otpauth's window 1), addresses are masked, and the notice hooks see every transition. The HTTP flow is in
|
||||
* enrolmentConfirmHttp.test.ts.
|
||||
*/
|
||||
import { describe, expect, test } from 'vitest'
|
||||
|
||||
import { buildTotpNoticeHooks, maskAddress, resolveConfirmByEmail, verifyTotpCode } from '../src/modules/security/totp/enrolmentConfirm.js'
|
||||
|
||||
describe('confirmByEmail options', () => {
|
||||
test('on by default; false turns it off; nonsense stops the start', () => {
|
||||
expect(resolveConfirmByEmail(undefined)).toMatchObject({ adminConfirm: true, linkMinutes: 30, logLinkWhenMailFails: true, maxMailsPerHour: 5, notices: true, sameBrowser: true })
|
||||
expect(resolveConfirmByEmail(false)).toBeNull()
|
||||
expect(resolveConfirmByEmail({ linkMinutes: 10, sameBrowser: false })).toMatchObject({ linkMinutes: 10, sameBrowser: false })
|
||||
for (const bad of ['false', 0, [], { sameBrowser: 'false' }, { linkMinutes: 0 }, { linkMinutes: 2000 }, { maxMailsPerHour: 1.5 }]) {
|
||||
expect(() => resolveConfirmByEmail(bad), JSON.stringify(bad)).toThrow(/confirmByEmail/)
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
describe('the code check', () => {
|
||||
const secret = 'JBSWY3DPEHPK3PXPJBSWY3DPEHPK3PXP'
|
||||
test('RFC 6238 test vectors (SHA1, SHA256, SHA512; 8 digits) and one period either side, not two', () => {
|
||||
// RFC 6238 Appendix B: seeds "1234567890…" (20 / 32 / 64 bytes) in base32
|
||||
const sha1 = 'GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ'
|
||||
const sha256 = 'GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQGEZA'
|
||||
const sha512 = 'GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQGEZDGNA'
|
||||
const at = (s: number) => s * 1000
|
||||
expect(verifyTotpCode(sha1, '94287082', { digits: 8 }, at(59))).toBe(true)
|
||||
expect(verifyTotpCode(sha256, '46119246', { algorithm: 'SHA256', digits: 8 }, at(59))).toBe(true)
|
||||
expect(verifyTotpCode(sha512, '90693936', { algorithm: 'SHA512', digits: 8 }, at(59))).toBe(true)
|
||||
expect(verifyTotpCode(sha1, '07081804', { digits: 8 }, at(1111111109))).toBe(true)
|
||||
// the same code 30 s later still passes (window 1), 90 s later not
|
||||
expect(verifyTotpCode(sha1, '07081804', { digits: 8 }, at(1111111109 + 30))).toBe(true)
|
||||
expect(verifyTotpCode(sha1, '07081804', { digits: 8 }, at(1111111109 + 90))).toBe(false)
|
||||
expect(verifyTotpCode(sha1, '1234567', { digits: 8 }, at(59))).toBe(false)
|
||||
expect(verifyTotpCode('not base32!', '123456', {}, at(59))).toBe(false)
|
||||
expect(verifyTotpCode('ABCD', '123456', {}, at(59))).toBe(false) // too short a key
|
||||
void secret
|
||||
})
|
||||
test('addresses are masked on the screen', () => {
|
||||
expect(maskAddress('[email protected]')).toBe('j…@firma.pl')
|
||||
expect(maskAddress('nope')).toBe('…')
|
||||
})
|
||||
})
|
||||
|
||||
describe('notice hooks', () => {
|
||||
const { beforeChange } = buildTotpNoticeHooks('users', { notices: true })
|
||||
const change = (before: unknown, after: unknown, operation = 'update') => {
|
||||
const context: Record<string, unknown> = {}
|
||||
beforeChange({ context, data: { totpSecret: after }, operation, originalDoc: { totpSecret: before } } as never)
|
||||
return context.iaplTotpChange ?? null
|
||||
}
|
||||
test('on, off, changed; nothing for a write that does not touch the secret, or a create', () => {
|
||||
expect(change(null, 'A')).toBe('on')
|
||||
expect(change('A', null)).toBe('off')
|
||||
expect(change('A', 'B')).toBe('changed')
|
||||
expect(change('A', 'A')).toBeNull()
|
||||
expect(change(null, null)).toBeNull()
|
||||
expect(change(null, 'A', 'create')).toBeNull()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,290 @@
|
||||
/**
|
||||
* twoFactor.confirmByEmail (1.18.0; security audit 2026-12, finding F0): the first enrolment of a factor waits for a
|
||||
* link sent to the account's own e-mail and opened in the browser that scanned the code. Real HTTP (Payload's REST
|
||||
* and GraphQL handlers behind a server), a capturing mail transport, the 2FA package itself.
|
||||
*/
|
||||
import type { Payload } from 'payload'
|
||||
|
||||
import { payloadTotp } from '@clocklimited/payload-2fa'
|
||||
import { lexicalEditor } from '@payloadcms/richtext-lexical'
|
||||
import { createServer } from 'node:net'
|
||||
import os from 'os'
|
||||
import path from 'path'
|
||||
import { getPayload } from 'payload'
|
||||
import { afterAll, beforeAll, beforeEach, describe, expect, test, vi } from 'vitest'
|
||||
|
||||
import { pendingEnrolmentKey } from '../src/modules/security/totp/enrolmentConfirm.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'
|
||||
|
||||
vi.mock('server-only', () => ({}))
|
||||
vi.mock('next/headers.js', async () => (await import('./http/server.js')).nextHeadersMock)
|
||||
|
||||
const ADMIN_SECRET = 'GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ'
|
||||
const ATTACKER_SECRET = 'JBSWY3DPEHPK3PXPJBSWY3DPEHPK3PXP'
|
||||
const OWNER_SECRET = 'KRSXG5CTMVRXEZLUKRSXG5CTMVRXEZLU'
|
||||
const PASSWORD = 'a-long-test-password-1'
|
||||
|
||||
type Mail = { html?: string; subject?: string; text?: string; to?: string }
|
||||
const mails: Mail[] = []
|
||||
let mailBroken = false
|
||||
let server: TestServer
|
||||
let payload: Payload
|
||||
let base = ''
|
||||
|
||||
const freePort = () => new Promise<number>((resolve) => {
|
||||
const s = createServer().listen(0, '127.0.0.1', () => {
|
||||
const { port } = s.address() as { port: number }
|
||||
s.close(() => resolve(port))
|
||||
})
|
||||
})
|
||||
|
||||
beforeAll(async () => {
|
||||
const port = await freePort()
|
||||
base = `http://127.0.0.1:${port}`
|
||||
const config = buildTestConfig({
|
||||
collections: [{ slug: 'media', fields: [], upload: { staticDir: path.join(os.tmpdir(), 'ipal-test-media') } }],
|
||||
db: testDatabase('enrol_confirm'),
|
||||
editor: lexicalEditor(),
|
||||
email: () => ({
|
||||
name: 'capture',
|
||||
defaultFromAddress: '[email protected]',
|
||||
defaultFromName: 'Site',
|
||||
sendEmail: async (message: unknown) => {
|
||||
const m = message as Mail
|
||||
if (mailBroken) {throw new Error('SMTP down')}
|
||||
mails.push(m)
|
||||
return { sent: true }
|
||||
},
|
||||
}),
|
||||
plugins: [
|
||||
iapl({
|
||||
access: { authCollection: 'users' },
|
||||
forms: {},
|
||||
i18n: { defaultLocale: 'pl', locales: [{ code: 'pl', label: 'Polski' }] },
|
||||
twoFactor: { issuer: 'Example', plugin: payloadTotp },
|
||||
}),
|
||||
],
|
||||
secret: 'integration-test-secret-0123456789',
|
||||
serverURL: base,
|
||||
telemetry: false,
|
||||
})
|
||||
payload = await getPayload({ config })
|
||||
server = await startPayloadServer(config, port)
|
||||
// an administrator with a factor (made by a script, like a seed): for the admin's own actions
|
||||
await payload.create({ collection: 'users' as never, data: { email: '[email protected]', password: PASSWORD, roles: ['admin'], totpSecret: ADMIN_SECRET } as never })
|
||||
}, 120_000)
|
||||
|
||||
afterAll(async () => {
|
||||
await server?.close()
|
||||
await payload?.destroy?.()
|
||||
})
|
||||
|
||||
beforeEach(() => {
|
||||
mails.length = 0
|
||||
mailBroken = false
|
||||
})
|
||||
|
||||
const json = { 'content-type': 'application/json', origin: () => base }
|
||||
const headers = (cookie = '', extra: Record<string, string> = {}) => ({ 'content-type': 'application/json', cookie, origin: base, ...extra })
|
||||
let accounts = 0
|
||||
|
||||
/** A new editor account without a factor (inside its setup window). */
|
||||
async function newAccount(): Promise<{ email: string; id: number | string }> {
|
||||
const email = `person-${++accounts}-${Date.now()}@example.com`
|
||||
const doc = (await payload.create({ collection: 'users' as never, data: { email, password: PASSWORD, roles: ['editor'] } as never })) as unknown as { id: number | string }
|
||||
return { id: doc.id, email }
|
||||
}
|
||||
const signIn = async (email: string) => {
|
||||
const res = await fetch(`${base}/api/users/login`, { body: JSON.stringify({ email, password: PASSWORD }), headers: headers(), method: 'POST' })
|
||||
expect(res.status).toBe(200)
|
||||
return cookiesOf(res).join('; ')
|
||||
}
|
||||
const setup = (cookie: string, secret: string, token = totp(secret)) =>
|
||||
fetch(`${base}/api/setup-totp`, { body: JSON.stringify({ secret, token }), headers: headers(cookie), method: 'POST' })
|
||||
const storedSecret = async (id: number | string) =>
|
||||
((await payload.findByID({ id, collection: 'users' as never, overrideAccess: true, showHiddenFields: true })) as unknown as { totpSecret?: null | string }).totpSecret ?? null
|
||||
const linkIn = (mail: Mail | undefined) => {
|
||||
const m = (mail?.text ?? '').match(/https?:\/\/\S+\/two-factor\/confirm\?u=\S+/)
|
||||
return m ? new URL(m[0]) : null
|
||||
}
|
||||
const confirm = (link: URL, cookie = '', origin = base) =>
|
||||
fetch(`${base}/api/iapl/two-factor/confirm`, {
|
||||
body: new URLSearchParams({ t: link.searchParams.get('t')!, u: link.searchParams.get('u')! }).toString(),
|
||||
headers: { 'content-type': 'application/x-www-form-urlencoded', cookie, origin },
|
||||
method: 'POST',
|
||||
})
|
||||
void json
|
||||
|
||||
describe('F0: the password alone no longer enrols a factor', () => {
|
||||
test('an attacker with the password: the set-up waits, a link goes to the OWNER\'s mailbox, nothing opens, no -totp cookie', async () => {
|
||||
const victim = await newAccount()
|
||||
const attacker = await signIn(victim.email)
|
||||
const res = await setup(attacker, ATTACKER_SECRET)
|
||||
expect(res.status).toBe(202)
|
||||
const body = (await res.json()) as { mailed?: boolean; message?: string; ok?: boolean; pending?: boolean }
|
||||
expect(body).toMatchObject({ mailed: true, ok: false, pending: true })
|
||||
expect(body.message).toMatch(/p…@example\.com/)
|
||||
// no factor stored, and the package's cookie was never set (it would turn valid once any secret is confirmed)
|
||||
expect(await storedSecret(victim.id)).toBeNull()
|
||||
const set = res.headers.getSetCookie().join('\n')
|
||||
expect(set).not.toMatch(/payload-totp=/)
|
||||
expect(set).toMatch(/payload-iapl-enrol=[^;]+;.*HttpOnly/)
|
||||
// still nothing but setup
|
||||
for (const p of ['/globals/site-integrations', '/users', '/form-submissions']) {
|
||||
expect([p, (await fetch(`${base}/api${p}`, { headers: { cookie: attacker } })).status]).toEqual([p, 403])
|
||||
}
|
||||
// the mail: to the account, with the link, without the secret
|
||||
expect(mails).toHaveLength(1)
|
||||
expect(mails[0].to).toBe(victim.email)
|
||||
expect(`${mails[0].html}${mails[0].text}`).not.toContain(ATTACKER_SECRET)
|
||||
expect(linkIn(mails[0])?.origin).toBe(base)
|
||||
})
|
||||
|
||||
test('the owner opens the attacker\'s link in THEIR browser: refused, the attacker\'s factor is not turned on', async () => {
|
||||
const victim = await newAccount()
|
||||
const attacker = await signIn(victim.email)
|
||||
await setup(attacker, ATTACKER_SECRET)
|
||||
const link = linkIn(mails[0])!
|
||||
// opening the link (a mail scanner, a preview) changes nothing
|
||||
const page = await fetch(link)
|
||||
expect(page.status).toBe(200)
|
||||
expect(await page.text()).toContain('<form method="post"')
|
||||
expect(await storedSecret(victim.id)).toBeNull()
|
||||
// the owner's browser has no enrolment cookie
|
||||
const ownerSession = await signIn(victim.email)
|
||||
const res = await confirm(link, ownerSession)
|
||||
expect(res.status).toBe(403)
|
||||
expect(await storedSecret(victim.id)).toBeNull()
|
||||
})
|
||||
|
||||
test('the owner\'s own set-up replaces a waiting one; the older link stops working', async () => {
|
||||
const victim = await newAccount()
|
||||
const attacker = await signIn(victim.email)
|
||||
const a = await setup(attacker, ATTACKER_SECRET)
|
||||
const attackerLink = linkIn(mails[0])!
|
||||
const attackerCookie = cookiesOf(a).find((c) => c.startsWith('payload-iapl-enrol='))!
|
||||
const owner = await signIn(victim.email)
|
||||
await setup(owner, OWNER_SECRET)
|
||||
expect(mails).toHaveLength(2)
|
||||
expect((await confirm(attackerLink, `${attacker}; ${attackerCookie}`)).status).toBe(400)
|
||||
expect(await storedSecret(victim.id)).toBeNull()
|
||||
})
|
||||
})
|
||||
|
||||
describe('confirming', () => {
|
||||
test('the link in the same browser turns it on, ends every session, signs nobody in; then password + code open the panel', async () => {
|
||||
const person = await newAccount()
|
||||
const session = await signIn(person.email)
|
||||
const res = await setup(session, OWNER_SECRET)
|
||||
const enrolCookie = cookiesOf(res).find((c) => c.startsWith('payload-iapl-enrol='))!
|
||||
const link = linkIn(mails[0])!
|
||||
mails.length = 0
|
||||
const done = await confirm(link, `${session}; ${enrolCookie}`)
|
||||
expect(done.status).toBe(200)
|
||||
expect(await done.text()).toContain('/admin/login')
|
||||
expect(done.headers.getSetCookie().join('\n')).not.toMatch(/payload-token=[^;]|payload-totp=[^;]/)
|
||||
expect(await storedSecret(person.id)).toBe(OWNER_SECRET)
|
||||
// the old password-only session is gone
|
||||
const me = (await (await fetch(`${base}/api/users/me`, { headers: { cookie: session } })).json()) as { user: unknown }
|
||||
expect(me.user).toBeNull()
|
||||
// the notice "turned on"
|
||||
expect(mails.map((m) => [m.to, m.subject])).toEqual([[person.email, expect.stringMatching(/two-step|dwuetapow/i)]])
|
||||
expect(`${mails[0].html}${mails[0].text}`).not.toContain(OWNER_SECRET)
|
||||
// sign in again: password, then the code
|
||||
const again = await signIn(person.email)
|
||||
const verify = await fetch(`${base}/api/verify-totp`, { body: JSON.stringify({ token: totp(OWNER_SECRET) }), headers: headers(again), method: 'POST' })
|
||||
expect(((await verify.json()) as { ok: boolean }).ok).toBe(true)
|
||||
const full = [again, ...cookiesOf(verify)].join('; ')
|
||||
expect((await fetch(`${base}/api/globals/site-settings`, { headers: { cookie: full } })).status).toBe(200)
|
||||
// single use
|
||||
expect((await confirm(link, `${session}; ${enrolCookie}`)).status).toBe(400)
|
||||
})
|
||||
|
||||
test('a wrong code sends nothing; an expired link and a POST from another origin are refused', async () => {
|
||||
const person = await newAccount()
|
||||
const session = await signIn(person.email)
|
||||
const wrong = await setup(session, OWNER_SECRET, '000000')
|
||||
expect(wrong.status).toBe(400)
|
||||
expect(mails).toHaveLength(0)
|
||||
|
||||
const res = await setup(session, OWNER_SECRET)
|
||||
const enrolCookie = cookiesOf(res).find((c) => c.startsWith('payload-iapl-enrol='))!
|
||||
const link = linkIn(mails[0])!
|
||||
expect((await confirm(link, `${session}; ${enrolCookie}`, 'https://evil.example')).status).toBe(403)
|
||||
const key = pendingEnrolmentKey('users', person.id)
|
||||
const kv = (payload as unknown as { kv: { get: (k: string) => Promise<Record<string, unknown>>; set: (k: string, v: object) => Promise<void> } }).kv
|
||||
await kv.set(key, { ...(await kv.get(key)), expiresAt: Date.now() - 1 })
|
||||
expect((await confirm(link, `${session}; ${enrolCookie}`)).status).toBe(400)
|
||||
expect(await storedSecret(person.id)).toBeNull()
|
||||
})
|
||||
|
||||
test('at most five confirmation mails per account and hour', async () => {
|
||||
const person = await newAccount()
|
||||
const session = await signIn(person.email)
|
||||
for (let i = 0; i < 5; i++) {expect((await setup(session, OWNER_SECRET)).status).toBe(202)}
|
||||
expect((await setup(session, OWNER_SECRET)).status).toBe(429)
|
||||
expect(mails).toHaveLength(5)
|
||||
})
|
||||
})
|
||||
|
||||
describe('mail that does not work', () => {
|
||||
test('the link goes to the server log; the person is told to ask an administrator; the admin confirms it', async () => {
|
||||
const person = await newAccount()
|
||||
const session = await signIn(person.email)
|
||||
mailBroken = true
|
||||
const warn = vi.spyOn(payload.logger, 'warn')
|
||||
const res = await setup(session, OWNER_SECRET)
|
||||
const body = (await res.json()) as { mailed?: boolean; message?: string }
|
||||
expect(body.mailed).toBe(false)
|
||||
expect(body.message).toMatch(/administrator/i)
|
||||
const logged = warn.mock.calls.map(([line]) => String(line)).find((line) => line.includes('/two-factor/confirm?u='))
|
||||
warn.mockRestore()
|
||||
expect(logged).toContain(base)
|
||||
expect(await storedSecret(person.id)).toBeNull()
|
||||
|
||||
// the person themselves cannot use the admin action; an admin with the code can
|
||||
expect((await fetch(`${base}/api/iapl/two-factor/confirm-pending`, { body: JSON.stringify({ userId: person.id }), headers: headers(session), method: 'POST' })).status).toBe(403)
|
||||
const adminSession = await signIn('[email protected]')
|
||||
const passwordOnly = await fetch(`${base}/api/iapl/two-factor/confirm-pending`, { body: JSON.stringify({ userId: person.id }), headers: headers(adminSession), method: 'POST' })
|
||||
expect(passwordOnly.status).toBe(403)
|
||||
const verify = await fetch(`${base}/api/verify-totp`, { body: JSON.stringify({ token: totp(ADMIN_SECRET) }), headers: headers(adminSession), method: 'POST' })
|
||||
const admin = [adminSession, ...cookiesOf(verify)].join('; ')
|
||||
mailBroken = false
|
||||
const ok = await fetch(`${base}/api/iapl/two-factor/confirm-pending`, { body: JSON.stringify({ userId: person.id }), headers: headers(admin), method: 'POST' })
|
||||
expect(ok.status).toBe(200)
|
||||
expect(await storedSecret(person.id)).toBe(OWNER_SECRET)
|
||||
// nothing waits any more
|
||||
expect((await fetch(`${base}/api/iapl/two-factor/confirm-pending`, { body: JSON.stringify({ userId: person.id }), headers: headers(admin), method: 'POST' })).status).toBe(404)
|
||||
// the notice names who confirmed it
|
||||
expect(mails.at(-1)?.text).toContain('[email protected]')
|
||||
})
|
||||
})
|
||||
|
||||
describe('notices and the other ways to set or remove a factor', () => {
|
||||
test('an administrator\'s reset sends the account a notice; REST and GraphQL cannot write a secret', async () => {
|
||||
const person = await newAccount()
|
||||
await payload.update({ id: person.id, collection: 'users' as never, data: { totpSecret: OWNER_SECRET } as never, overrideAccess: true })
|
||||
mails.length = 0
|
||||
const adminSession = await signIn('[email protected]')
|
||||
const verify = await fetch(`${base}/api/verify-totp`, { body: JSON.stringify({ token: totp(ADMIN_SECRET) }), headers: headers(adminSession), method: 'POST' })
|
||||
const admin = [adminSession, ...cookiesOf(verify)].join('; ')
|
||||
|
||||
// REST and GraphQL: the field cannot be written, not even by an admin
|
||||
await fetch(`${base}/api/users/${person.id}`, { body: JSON.stringify({ totpSecret: ATTACKER_SECRET }), headers: headers(admin), method: 'PATCH' })
|
||||
expect(await storedSecret(person.id)).toBe(OWNER_SECRET)
|
||||
const gql = await fetch(`${base}/api/graphql`, { body: JSON.stringify({ query: `mutation { updateUser(id: ${JSON.stringify(person.id)}, data: { totpSecret: "${ATTACKER_SECRET}" }) { id } }` }), headers: headers(admin), method: 'POST' })
|
||||
expect(gql.status).toBeLessThan(500)
|
||||
expect(await storedSecret(person.id)).toBe(OWNER_SECRET)
|
||||
|
||||
const reset = await fetch(`${base}/api/ipal/two-factor/reset`, { body: JSON.stringify({ userId: person.id }), headers: headers(admin), method: 'POST' })
|
||||
expect(reset.status).toBe(200)
|
||||
expect(await storedSecret(person.id)).toBeNull()
|
||||
const notice = mails.find((m) => m.to === person.email)
|
||||
expect(notice?.subject).toMatch(/removed|usunięta/i)
|
||||
expect(notice?.text).toContain('[email protected]')
|
||||
})
|
||||
})
|
||||
@@ -21,7 +21,7 @@ import {
|
||||
twoFactorSetupState,
|
||||
watchPayloadConfig,
|
||||
} from '../src/modules/security/totp/secondFactor.js'
|
||||
import { buildTwoFactorResetEndpoint, resolveRequireSetup, strictExempt } from '../src/modules/security/totp/setupRequired.js'
|
||||
import { buildTwoFactorResetEndpoint, resolveRequireSetup, stampSetupFrom, strictExempt } from '../src/modules/security/totp/setupRequired.js'
|
||||
import { buildVerifyLimit, clearVerifyLimits, verifyLimitKey } from '../src/modules/security/totp/verifyLimit.js'
|
||||
import { iapl } from '../src/plugin.js'
|
||||
import { withTotpParts } from './helpers.js'
|
||||
@@ -480,7 +480,7 @@ describe('iapl and the 2FA plugin', () => {
|
||||
...withTotpParts(c, o.collection),
|
||||
endpoints: [...(c.endpoints ?? []), ...['/verify-totp', '/setup-totp', '/remove-totp'].map((path) => ({ handler, method: 'post' as const, path }))],
|
||||
})
|
||||
const build = (twoFactor: Record<string, unknown> = {}) => iapl({ i18n, twoFactor: { issuer: 'A', plugin: withEndpoints as never, ...twoFactor } as never })({ collections: [], endpoints: [], secret: 'x' } as unknown as Config)
|
||||
const build = (twoFactor: Record<string, unknown> = {}) => iapl({ i18n, twoFactor: { confirmByEmail: false, issuer: 'A', plugin: withEndpoints as never, ...twoFactor } as never })({ collections: [], endpoints: [], secret: 'x' } as unknown as Config)
|
||||
const call = async (config: Config, path: string, headers: Record<string, string>, user: Record<string, unknown>) =>
|
||||
(await config.endpoints!.find((e) => e.path === path)!.handler({ headers: new Headers(headers), i18n: undefined, payload: { config, logger: { warn } }, url: 'https://site.example/api' + path, user: { id: 5, collection: 'users', ...user } } as never)).status
|
||||
const elsewhere = { host: 'site.example', origin: 'https://blog.site.example' }
|
||||
@@ -538,7 +538,7 @@ describe('iapl and the 2FA plugin', () => {
|
||||
expect(guard(on)).toMatchObject({ collection: 'users', requireSetup: true, setupWindowMs: 72 * 3_600_000 })
|
||||
const users = on.collections!.find((c) => c.slug === 'users')!
|
||||
expect(users.fields.some((f) => 'name' in f && f.name === 'totpSetupFrom')).toBe(true)
|
||||
expect(users.hooks?.beforeChange?.length).toBe(1)
|
||||
expect(users.hooks?.beforeChange?.filter((h) => h === stampSetupFrom)).toHaveLength(1)
|
||||
expect(on.endpoints!.some((e) => e.path === '/ipal/two-factor/reset')).toBe(true)
|
||||
expect(JSON.stringify(on.admin?.components?.beforeDashboard)).toContain('TwoFactorAlert')
|
||||
|
||||
@@ -551,7 +551,7 @@ describe('iapl and the 2FA plugin', () => {
|
||||
const offUsers = off.collections!.find((c) => c.slug === 'users')!
|
||||
expect(offUsers.fields.some((f) => 'name' in f && f.name === 'totpSetupFrom')).toBe(true)
|
||||
expect(offUsers.fields.some((f) => 'name' in f && f.name === 'totpSetupStatus')).toBe(false)
|
||||
expect(offUsers.hooks?.beforeChange?.length ?? 0).toBe(0) // no stamping while the mode is off
|
||||
expect(offUsers.hooks?.beforeChange?.includes(stampSetupFrom) ?? false).toBe(false) // no stamping while the mode is off
|
||||
expect(JSON.stringify(off.admin?.components?.beforeDashboard ?? [])).not.toContain('TwoFactorAlert')
|
||||
const guardOff = await iapl({ i18n, twoFactor: { guard: false, issuer: 'A', plugin: fakeTotp as never } })(base())
|
||||
expect(guardOff.collections!.find((c) => c.slug === 'users')!.fields.some((f) => 'name' in f && f.name === 'totpSetupFrom')).toBe(true)
|
||||
|
||||
@@ -107,7 +107,8 @@ const makeConfig = () =>
|
||||
forms: {},
|
||||
i18n: { defaultLocale: 'pl', locales: [{ code: 'pl', label: 'Polski' }] },
|
||||
stats: true,
|
||||
twoFactor: { issuer: 'Example', plugin: payloadTotp },
|
||||
// the e-mail step of a first enrolment has its own suite (enrolmentConfirmHttp.test.ts); here the code alone turns it on
|
||||
twoFactor: { confirmByEmail: false, issuer: 'Example', plugin: payloadTotp },
|
||||
}),
|
||||
latePlugin,
|
||||
],
|
||||
|
||||
@@ -44,7 +44,8 @@ beforeAll(async () => {
|
||||
access: { authCollection: 'users' },
|
||||
forms: {},
|
||||
i18n: { defaultLocale: 'pl', locales: [{ code: 'pl', label: 'Polski' }] },
|
||||
twoFactor: { issuer: 'Example', plugin: payloadTotp as never },
|
||||
// the e-mail step of a first enrolment has its own suite (enrolmentConfirmHttp.test.ts); here the code alone turns it on
|
||||
twoFactor: { confirmByEmail: false, issuer: 'Example', plugin: payloadTotp as never },
|
||||
}),
|
||||
],
|
||||
secret: 'integration-test-secret-0123456789',
|
||||
|
||||
@@ -35,7 +35,8 @@ beforeAll(async () => {
|
||||
access: { authCollection: 'users' },
|
||||
forms: {},
|
||||
i18n: { defaultLocale: 'pl', locales: [{ code: 'pl', label: 'Polski' }] },
|
||||
twoFactor: { issuer: 'Example', plugin: payloadTotp },
|
||||
// the e-mail step of a first enrolment has its own suite (enrolmentConfirmHttp.test.ts); here the code alone turns it on
|
||||
twoFactor: { confirmByEmail: false, issuer: 'Example', plugin: payloadTotp },
|
||||
}),
|
||||
],
|
||||
secret: 'integration-test-secret-0123456789',
|
||||
|
||||
Reference in New Issue
Block a user