Files
poli0981andClaude Opus 5.5 2c2d990f33 feat(worker): Turnstile verification gate for the web app
Until a visitor passes a Cloudflare Turnstile check, app pages ("/" is
now Worker-first too) answer with a self-contained verification page and
/img covers with 403, so a browser loads nothing of the site before the
check. Passing sets an HttpOnly, host-only cookie (HMAC of its issue
time) good for BOT_GATE_TTL_HOURS (48). The page then reloads into the
link that was asked for, and the legal gate follows as before.

- /assets, /data (desktop/Android apps, CC BY reuse), robots, sitemap,
  og image, /api/* and /admin* stay ungated.
- Verified bots pass with the token a zone Transform Rule adds
  (x-fig-known-bot); clients that only claim to be a search crawler get
  a 503, never the noindex page.
- Fails open: it needs BOT_GATE="on", the Turnstile keys, GATE_SECRET
  and GATE_BOT_TOKEN; deleting GATE_SECRET switches it off at once.
- POST /api/verify: same-origin, RL_GATE (IPv4 / IPv6 /64), siteverify
  with action "gate". GET reports the pass for the page and the SPA.
- turnstile.ts: siteverify shared with Suggest, which now also checks
  the hostname and action (a token from one page can't be spent on the
  other) and answers 503 when Turnstile is unreachable.
- SPA: a tab whose pass ran out re-checks when shown again or when a
  cover fails, and reloads into the verification page.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-24 17:56:33 +07:00

81 lines
3.7 KiB
TypeScript

import { describe, expect, it, vi } from 'vitest'
import { isTestSecret, siteverify, type SiteverifyInput } from './turnstile'
const input: SiteverifyInput = {
secret: '0x4AAAAAAAreal-secret',
token: 'tok',
ip: '203.0.113.9',
action: 'gate',
hostname: 'freeitchgames.win',
}
const answer = (body: unknown) => vi.fn(async () => Response.json(body))
const run = (fetch: unknown, over: Partial<SiteverifyInput> = {}, timeoutMs?: number) =>
siteverify({ ...input, ...over }, fetch as typeof globalThis.fetch, timeoutMs)
describe('siteverify', () => {
it('accepts a token solved on our host for the same action', async () => {
const fetch = answer({ success: true, hostname: 'freeitchgames.win', action: 'gate' })
expect(await run(fetch)).toBe('ok')
const [url, init] = fetch.mock.calls[0] as unknown as [string, RequestInit]
expect(url).toBe('https://challenges.cloudflare.com/turnstile/v0/siteverify')
const form = init.body as FormData
expect([form.get('secret'), form.get('response'), form.get('remoteip')]).toEqual([input.secret, 'tok', '203.0.113.9'])
})
it('leaves remoteip out when the IP is unknown', async () => {
const fetch = answer({ success: true, hostname: 'freeitchgames.win', action: 'gate' })
await run(fetch, { ip: '' })
expect(((fetch.mock.calls[0] as unknown as [string, RequestInit])[1].body as FormData).has('remoteip')).toBe(false)
})
it.each([
['a failed challenge', { success: false, 'error-codes': ['invalid-input-response'] }],
['a spent token', { success: false, 'error-codes': ['timeout-or-duplicate'] }],
['a token from another host', { success: true, hostname: 'evil.example', action: 'gate' }],
['a token for another action', { success: true, hostname: 'freeitchgames.win', action: 'suggest' }],
['a token without an action', { success: true, hostname: 'freeitchgames.win' }],
['a token without a hostname', { success: true, action: 'gate' }],
['a malformed answer', null],
])('rejects %s', async (_name, body) => {
expect(await run(answer(body))).toBe('rejected')
})
it.each([
['a 5xx', () => new Response('bad gateway', { status: 502 })],
['a non-JSON body', () => new Response('<html>', { status: 200 })],
['a network error', () => Promise.reject(new TypeError('fetch failed'))],
['an internal error', () => Response.json({ success: false, 'error-codes': ['internal-error'] })],
['a refused secret key', () => Response.json({ success: false, 'error-codes': ['invalid-input-secret'] })],
])('reports %s as unavailable', async (_name, reply) => {
vi.spyOn(console, 'error').mockImplementation(() => {})
expect(await run(vi.fn(async () => reply()))).toBe('unavailable')
})
it('gives up after the timeout', async () => {
const fetch = vi.fn(
(_url: string, init: RequestInit) =>
new Promise<Response>((_resolve, reject) => init.signal?.addEventListener('abort', () => reject(init.signal?.reason))),
)
expect(await run(fetch, {}, 20)).toBe('unavailable')
})
it('skips the host and action checks for the test secrets', async () => {
const fetch = answer({ success: true, hostname: 'example.com', action: '' })
expect(await run(fetch, { secret: '1x0000000000000000000000000000000AA' })).toBe('ok')
expect(await run(answer({ success: false }), { secret: '2x0000000000000000000000000000000AA' })).toBe('rejected')
})
})
describe('isTestSecret', () => {
it.each([
['1x0000000000000000000000000000000AA', true],
['2x0000000000000000000000000000000AA', true],
['3x0000000000000000000000000000000AA', true],
['0x4AAAAAAAreal-secret', false],
['1x0000000000000000000000000000000AB', false],
])('%s → %s', (secret, expected) => {
expect(isTestSecret(secret)).toBe(expected)
})
})