Files
ipal-kit/test/m1Turnstile.test.ts
T
Radosław SmolińskiandClaude Fable 5.2 0a4f001797 IAPL rename, scripted: preferred names in src, bin, scripts, services, tests; bin files and skill folders moved
Replaced by an explicit list of forms only (ten exported names, runtime env names, project file
names and marks, commands, skill names, the log prefix, the brand in prose). Package name, import
paths, routes, CSS tokens, data attributes, custom keys, context flags, the cookie and kv keys are
not touched. package.json keeps the five old bin names beside the five new ones.
The old names stop working in this commit and come back as aliases in the next; docs follow.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
2026-11-25 17:24:21 +01:00

109 lines
6.0 KiB
TypeScript

/**
* M1: what a form does while Turnstile cannot check (forms.turnstileOnConfigError).
* Cloudflare is the mocked `fetch`; the rest is the real gate code.
*/
import { afterEach, describe, expect, test, vi } from 'vitest'
import { passTurnstile, resolveTurnstileOnConfigError, TURNSTILE_ON_CONFIG_ERROR_DEFAULT } from '../src/modules/forms/submitForm.js'
import { iapl } from '../src/plugin.js'
vi.mock('server-only', () => ({}))
type Option = 'allow' | 'reject' | { files?: 'allow' | 'reject'; text?: 'allow' | 'reject' } | undefined
const payloadWith = (integrations: Record<string, unknown>, option?: Option) => ({
config: { custom: { ipal: { forms: option ? { turnstileOnConfigError: option } : {} } }, globals: [{ slug: 'site-integrations' }] },
findGlobal: async () => integrations,
logger: { error: () => undefined, info: () => undefined, warn: () => undefined },
updateGlobal: async () => ({}),
})
const KEYS = { turnstileSecretKey: 'secret', turnstileSiteKey: 'site' }
const cloudflare = (body: unknown, status = 200) => vi.stubGlobal('fetch', vi.fn(async () => new Response(JSON.stringify(body), { status })))
const gate = (kind: 'files' | 'text' | undefined, option?: Option, explicit?: 'allow' | 'reject', integrations: Record<string, unknown> = KEYS, token: string | undefined = 'token') =>
passTurnstile({ ip: '1.2.3.4', payload: payloadWith(integrations, option) as never, turnstileKind: kind, turnstileOnConfigError: explicit, turnstileToken: token })
const REFUSED = { reason: 'turnstile', success: false }
afterEach(() => {
vi.unstubAllGlobals()
vi.unstubAllEnvs()
vi.restoreAllMocks()
})
describe('forms.turnstileOnConfigError', () => {
test('the policy: call site, then the plugin option, then the default for the kind', () => {
expect(TURNSTILE_ON_CONFIG_ERROR_DEFAULT).toEqual({ files: 'reject', text: 'allow' })
const p = (option?: Option) => payloadWith(KEYS, option)
expect(resolveTurnstileOnConfigError(p(), 'text')).toBe('allow')
expect(resolveTurnstileOnConfigError(p(), 'files')).toBe('reject')
expect(resolveTurnstileOnConfigError(p(), undefined)).toBe('allow') // a caller that says nothing is a text form, as before
expect(resolveTurnstileOnConfigError(p('reject'), 'text')).toBe('reject')
expect(resolveTurnstileOnConfigError(p('allow'), 'files')).toBe('allow')
expect(resolveTurnstileOnConfigError(p({ files: 'allow' }), 'files')).toBe('allow')
expect(resolveTurnstileOnConfigError(p({ files: 'allow' }), 'text')).toBe('allow')
expect(resolveTurnstileOnConfigError(p({ text: 'reject' }), 'files')).toBe('reject')
expect(resolveTurnstileOnConfigError(p('reject'), 'text', 'allow')).toBe('allow') // the call site wins
expect(resolveTurnstileOnConfigError(p('allow'), 'files', 'reject')).toBe('reject')
expect(resolveTurnstileOnConfigError(p('nonsense' as never), 'files')).toBe('reject') // an unknown value never loosens
expect(resolveTurnstileOnConfigError(null, 'files')).toBe('reject')
})
test.each([
['Cloudflare rejects the secret', { 'error-codes': ['invalid-input-secret'], success: false }, 200],
['Cloudflare answers 500', {}, 500],
['an answer nobody understands', { hello: 1 }, 200],
])('%s: a text form is accepted, a form with files is refused', async (_name, body, status) => {
vi.spyOn(console, 'warn').mockImplementation(() => undefined)
cloudflare(body, status)
expect(await gate('text')).toBeNull()
expect(await gate(undefined)).toBeNull()
expect(await gate('files')).toEqual(REFUSED)
})
test('the network fails: the same', async () => {
vi.spyOn(console, 'warn').mockImplementation(() => undefined)
vi.stubGlobal('fetch', vi.fn(async () => { throw new Error('ECONNRESET') }))
expect(await gate('text')).toBeNull()
expect(await gate('files')).toEqual(REFUSED)
})
test('the plugin option and the call site change it, each way', async () => {
vi.spyOn(console, 'warn').mockImplementation(() => undefined)
cloudflare({ 'error-codes': ['invalid-input-secret'], success: false })
expect(await gate('text', 'reject')).toEqual(REFUSED)
expect(await gate('files', 'allow')).toBeNull()
expect(await gate('files', { files: 'allow' })).toBeNull()
expect(await gate('text', { files: 'allow' })).toBeNull()
expect(await gate('files', undefined, 'allow')).toBeNull()
expect(await gate('text', 'allow', 'reject')).toEqual(REFUSED)
})
test('not touched by the policy: a valid token passes, a bad token and a missing token are refused, for both kinds', async () => {
vi.spyOn(console, 'warn').mockImplementation(() => undefined)
cloudflare({ success: true })
expect(await gate('text')).toBeNull()
expect(await gate('files')).toBeNull()
cloudflare({ 'error-codes': ['invalid-input-response'], success: false })
expect(await gate('text', 'allow')).toEqual(REFUSED)
expect(await gate('files', 'allow')).toEqual(REFUSED)
expect(await gate('files', 'allow', undefined, KEYS, undefined)).toEqual(REFUSED)
})
test('Turnstile off (no keys): nothing is checked, forms with files included', async () => {
const fetchMock = vi.fn()
vi.stubGlobal('fetch', fetchMock)
vi.stubEnv('TURNSTILE_SECRET_KEY', '')
vi.stubEnv('NEXT_PUBLIC_TURNSTILE_SITE_KEY', '')
expect(await gate('files', undefined, undefined, {}, undefined)).toBeNull()
expect(await gate('text', 'reject', undefined, {}, undefined)).toBeNull()
expect(fetchMock).not.toHaveBeenCalled()
})
test('iapl carries the option to where the gate reads it', async () => {
const i18n = { defaultLocale: 'en', locales: [{ code: 'en', label: 'English' }] }
const build = async (forms: Record<string, unknown>) =>
((await iapl({ forms, i18n, twoFactor: false } as never)({ collections: [], secret: 'x' } as never)).custom as { ipal?: { forms?: { turnstileOnConfigError?: unknown } } }).ipal?.forms?.turnstileOnConfigError
expect(await build({})).toBeUndefined()
expect(await build({ turnstileOnConfigError: 'reject' })).toBe('reject')
expect(await build({ turnstileOnConfigError: { files: 'allow' } })).toEqual({ files: 'allow' })
})
})