import type { Config, TextField } from 'payload' import { payloadTotp } from '@clocklimited/payload-2fa' import { realpathSync } from 'node:fs' import { createRequire } from 'node:module' import { describe, expect, test } from 'vitest' import type { I18nConfig } from '../src/modules/i18n/types.js' import { iapl } from '../src/plugin.js' const i18n: I18nConfig = { defaultLocale: 'en', locales: [{ code: 'en', label: 'English' }] } const require = createRequire(import.meta.url) /** Real path of the `payload` entry that `fromFile` would load. */ const payloadSeenFrom = (fromFile: string) => realpathSync(createRequire(fromFile).resolve('payload')) describe('@clocklimited/payload-2fa with the real plugin', () => { test('uses the same payload as the project (peer dependency, no second copy)', () => { const twoFactorEntry = realpathSync(require.resolve('@clocklimited/payload-2fa')) expect(payloadSeenFrom(twoFactorEntry)).toBe(payloadSeenFrom(import.meta.url)) }) test('iapl wraps the auth collection with TOTP: secret field, strategy and setup view', async () => { const config = await iapl({ access: { authCollection: 'users' }, i18n, twoFactor: { issuer: 'Example', plugin: payloadTotp }, })({ collections: [], secret: 'x' } as unknown as Config) const users = config.collections?.find((c) => c.slug === 'users') const secret = users?.fields.find( (f): f is TextField => 'name' in f && f.name === 'totpSecret' && f.type === 'text', ) expect(secret).toBeDefined() expect(secret?.admin?.hidden).toBe(true) // The TOTP secret is never readable over the API. expect((secret?.access?.read as () => boolean)()).toBe(false) const auth = users?.auth expect(typeof auth === 'object' && auth.strategies?.length).toBeGreaterThan(0) expect(config.admin?.components?.views?.SetupTOTP).toBeDefined() expect(config.admin?.components?.views?.VerifyTOTP).toBeDefined() }) })