import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest' import { submitForm } from '../src/modules/forms/submitForm.js' import { localizedRules, minLength, required } from '../src/modules/forms/validators.js' import { notificationFallback } from '../src/modules/notifications/defaults.js' import { resolveFormMessage } from '../src/modules/notifications/resolveFormMessage.js' import { UNKNOWN_IP_FACTOR } from '../src/modules/shared/rateLimit.js' import { fakePayload } from './helpers.js' vi.mock('server-only', () => ({})) const forms = { contact: { fields: [ { name: 'name', blockType: 'text', required: true }, { name: 'consent', blockType: 'checkbox' }, { blockType: 'message' }, ], }, } const data = { name: 'Ala', consent: true } const keys = { turnstileSecretKey: 'secret', turnstileSiteKey: 'site' } let ipCounter = 0 const nextIp = () => `10.0.0.${++ipCounter}` function mockSiteverify(body: unknown, status = 200) { return vi.spyOn(globalThis, 'fetch').mockResolvedValue(Response.json(body, { status })) } describe('submitForm — Turnstile', () => { beforeEach(() => { vi.spyOn(console, 'warn').mockImplementation(() => {}) }) afterEach(() => { vi.restoreAllMocks() vi.unstubAllEnvs() }) test('not configured → no check, the submission is stored', async () => { const fetchSpy = vi.spyOn(globalThis, 'fetch') const { create, payload } = fakePayload({ forms }) const result = await submitForm({ data, formId: 'contact', ip: nextIp(), payload }) expect(result).toEqual({ submissionId: 'sub-1', success: true }) expect(create).toHaveBeenCalledOnce() expect(fetchSpy).not.toHaveBeenCalled() }) test('half-configured (site key only) counts as off', async () => { const { payload } = fakePayload({ forms, integrations: { turnstileSiteKey: 'site' } }) expect((await submitForm({ data, formId: 'contact', ip: nextIp(), payload })).success).toBe(true) }) test('configured → a MISSING token is rejected (no opting out by omission)', async () => { const fetchSpy = vi.spyOn(globalThis, 'fetch') const { create, payload } = fakePayload({ forms, integrations: keys }) const result = await submitForm({ data, formId: 'contact', ip: nextIp(), payload }) expect(result).toEqual({ reason: 'turnstile', success: false }) expect(create).not.toHaveBeenCalled() expect(fetchSpy).not.toHaveBeenCalled() }) test('configured from env vars counts too', async () => { vi.stubEnv('NEXT_PUBLIC_TURNSTILE_SITE_KEY', 'site') vi.stubEnv('TURNSTILE_SECRET_KEY', 'secret') const { payload } = fakePayload({ forms }) expect(await submitForm({ data, formId: 'contact', ip: nextIp(), payload })).toEqual({ reason: 'turnstile', success: false, }) }) test('configured + valid token → stored', async () => { mockSiteverify({ success: true }) const { create, payload } = fakePayload({ forms, integrations: keys }) const result = await submitForm({ data, formId: 'contact', ip: nextIp(), payload, turnstileToken: 'tok' }) expect(result.success).toBe(true) expect(create).toHaveBeenCalledOnce() }) test('configured + bad token → rejected', async () => { mockSiteverify({ 'error-codes': ['invalid-input-response'], success: false }) const { create, payload } = fakePayload({ forms, integrations: keys }) const result = await submitForm({ data, formId: 'contact', ip: nextIp(), payload, turnstileToken: 'bad' }) expect(result).toEqual({ reason: 'turnstile', success: false }) expect(create).not.toHaveBeenCalled() }) test('turnstileHostnames: a token solved on another host is rejected', async () => { mockSiteverify({ hostname: 'evil.example', success: true }) const { create, payload } = fakePayload({ forms, integrations: keys }) const base = { data, formId: 'contact', payload, turnstileToken: 'tok' } expect(await submitForm({ ...base, ip: nextIp(), turnstileHostnames: ['www.firma.pl'] })).toEqual({ reason: 'turnstile', success: false, }) expect(create).not.toHaveBeenCalled() mockSiteverify({ hostname: 'WWW.firma.pl', success: true }) expect((await submitForm({ ...base, ip: nextIp(), turnstileHostnames: ['www.firma.pl'] })).success).toBe(true) }) test('configured + Cloudflare rejects OUR secret → allowed by default, refused with reject', async () => { mockSiteverify({ 'error-codes': ['invalid-input-secret'], success: false }) const { payload } = fakePayload({ forms, integrations: keys }) const base = { data, formId: 'contact', payload, turnstileToken: 'tok' } expect((await submitForm({ ...base, ip: nextIp() })).success).toBe(true) expect(await submitForm({ ...base, ip: nextIp(), turnstileOnConfigError: 'reject' })).toEqual({ reason: 'turnstile', success: false, }) }) }) describe('submitForm — other gates', () => { afterEach(() => vi.restoreAllMocks()) test('no client IP is not a free pass — it shares one capped bucket', async () => { const { payload } = fakePayload({ forms }) let accepted = 0 for (let i = 0; i < 50; i++) { if ((await submitForm({ data, formId: 'contact', maxPerMinute: 1, payload })).success) {accepted++} } expect(accepted).toBe(UNKNOWN_IP_FACTOR) }) test('rate limit per IP', async () => { const { payload } = fakePayload({ forms }) const ip = nextIp() for (let i = 0; i < 2; i++) { expect((await submitForm({ data, formId: 'contact', ip, maxPerMinute: 2, payload })).success).toBe(true) } expect(await submitForm({ data, formId: 'contact', ip, maxPerMinute: 2, payload })).toEqual({ reason: 'rate_limited', success: false, }) }) test('ipalKit forms.consentFieldName (payload.config.custom) names the consent field', async () => { const { payload } = fakePayload({ forms: { f: { fields: [{ name: 'zgoda', blockType: 'checkbox' }] } } }) Object.assign(payload, { config: { custom: { ipal: { consentFieldName: 'zgoda' } } } }) expect(await submitForm({ data: { zgoda: false }, formId: 'f', ip: nextIp(), payload })).toEqual({ field: 'zgoda', reason: 'consent', success: false, }) // an explicit argument still wins expect((await submitForm({ consentFieldName: 'other', data: { zgoda: false }, formId: 'f', ip: nextIp(), payload })).success).toBe(true) }) test('consent must be checked', async () => { const { payload } = fakePayload({ forms }) expect(await submitForm({ data: { ...data, consent: false }, formId: 'contact', ip: nextIp(), payload })).toEqual({ field: 'consent', reason: 'consent', success: false, }) }) test('required field, unknown keys, unknown form', async () => { const { payload } = fakePayload({ forms }) const ip = nextIp() expect(await submitForm({ data: { consent: true }, formId: 'contact', ip, maxPerMinute: 0, payload })).toEqual({ field: 'name', kind: 'required', reason: 'validation', success: false, }) expect( await submitForm({ data: { ...data, admin: 1 }, formId: 'contact', ip, maxPerMinute: 0, payload }), ).toEqual({ kind: 'unknown_fields', reason: 'validation', success: false }) expect(await submitForm({ data, formId: 'nope', ip, maxPerMinute: 0, payload })).toEqual({ reason: 'not_found', success: false, }) }) test('a validation message names the field by its label, in the page language', async () => { const { payload } = fakePayload({ forms: { f: { fields: [{ name: 'email', blockType: 'email', label: 'Adres e-mail', required: true }] } } }) const result = await submitForm({ data: { email: 'nope' }, formId: 'f', ip: nextIp(), locale: 'pl', maxPerMinute: 0, payload }) expect(result).toEqual({ field: 'email', kind: 'invalid_format', label: 'Adres e-mail', reason: 'validation', success: false }) expect(resolveFormMessage(result, notificationFallback('pl').form)).toBe('Sprawdź pole „Adres e-mail”.') // no single field at fault → the generic error, never an empty {field} expect(resolveFormMessage({ kind: 'unknown_fields', reason: 'validation', success: false }, notificationFallback('en').form)).toBe(notificationFallback('en').form.error) }) test('validator messages: full sentences, Polish via localizedRules, own message wins', () => { expect(required()('', {})).toBe('Fill in this field.') expect(minLength(10)('abc', {})).toBe('Enter at least 10 characters.') const pl = localizedRules('pl-PL') expect(pl.required()('', {})).toBe('Uzupełnij to pole.') expect(pl.minLength(2)('a', {})).toBe('Wpisz co najmniej 2 znaki.') expect(pl.minLength(5)('a', {})).toBe('Wpisz co najmniej 5 znaków.') expect(pl.email('Mój tekst')('x', {})).toBe('Mój tekst') }) test('the captcha field injected by the widget is not an unknown key', async () => { const { create, payload } = fakePayload({ forms }) const result = await submitForm({ data: { ...data, 'cf-turnstile-response': 'x' }, formId: 'contact', ip: nextIp(), payload, }) expect(result.success).toBe(true) expect(create).toHaveBeenCalledWith( expect.objectContaining({ data: expect.objectContaining({ submissionData: [ { field: 'name', value: 'Ala' }, { field: 'consent', value: 'true' }, ], }), }), ) }) }) describe('turnstileKeyProblem', () => { afterEach(() => vi.unstubAllEnvs()) test('only flags a half-configured setup', async () => { const { turnstileKeyProblem } = await import('../src/modules/turnstile/config.js') expect(turnstileKeyProblem({})).toBeNull() expect(turnstileKeyProblem({ turnstileSecretKey: 's', turnstileSiteKey: 'k' })).toBeNull() expect(turnstileKeyProblem({ turnstileSiteKey: 'k' })).toMatch(/secret key is missing/) expect(turnstileKeyProblem({ turnstileSecretKey: 's' })).toMatch(/site key is missing/) vi.stubEnv('TURNSTILE_SECRET_KEY', 's') expect(turnstileKeyProblem({ turnstileSiteKey: 'k' })).toBeNull() }) })