unit.test.ts 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372
  1. /**
  2. * Unit tests for the Worker. These don't hit Cloudflare's real siteverify —
  3. * see integration.test.ts for that.
  4. */
  5. import { describe, expect, it, vi, beforeEach, afterEach } from 'vitest';
  6. import worker from '../src/index.js';
  7. import type { Env } from '../src/types.js';
  8. const TEST_ENV: Env = {
  9. TURNSTILE_SECRET_KEY: 'test-secret-key',
  10. ALLOWED_ORIGIN: '*',
  11. };
  12. const SITEVERIFY_URL = 'https://challenges.cloudflare.com/turnstile/v0/siteverify';
  13. function mockFetchOnce(response: { status?: number; body: unknown }): void {
  14. vi.spyOn(globalThis, 'fetch').mockImplementationOnce(async () => {
  15. return new Response(JSON.stringify(response.body), {
  16. status: response.status ?? 200,
  17. headers: { 'Content-Type': 'application/json' },
  18. });
  19. });
  20. }
  21. describe('CORS', () => {
  22. beforeEach(() => vi.restoreAllMocks());
  23. afterEach(() => vi.restoreAllMocks());
  24. it('responds to OPTIONS preflight with CORS headers', async () => {
  25. const res = await worker.fetch(new Request('https://w/', { method: 'OPTIONS' }), TEST_ENV);
  26. expect(res.status).toBe(204);
  27. expect(res.headers.get('Access-Control-Allow-Origin')).toBe('*');
  28. expect(res.headers.get('Access-Control-Allow-Methods')).toContain('POST');
  29. });
  30. it('echoes ALLOWED_ORIGIN when set explicitly', async () => {
  31. const env = { ...TEST_ENV, ALLOWED_ORIGIN: 'https://example.com' };
  32. const res = await worker.fetch(new Request('https://w/', { method: 'OPTIONS' }), env);
  33. expect(res.headers.get('Access-Control-Allow-Origin')).toBe('https://example.com');
  34. });
  35. });
  36. describe('Health endpoints', () => {
  37. it('GET / returns {ok: true, version}', async () => {
  38. const res = await worker.fetch(new Request('https://w/'), TEST_ENV);
  39. expect(res.status).toBe(200);
  40. const body = (await res.json()) as { ok: boolean; version: string; service: string };
  41. expect(body.ok).toBe(true);
  42. expect(body.version).toMatch(/^\d+\.\d+\.\d+$/);
  43. expect(body.service).toBe('turnstile-siteverify');
  44. });
  45. it('GET /health returns the same shape', async () => {
  46. const res = await worker.fetch(new Request('https://w/health'), TEST_ENV);
  47. expect(res.status).toBe(200);
  48. const body = (await res.json()) as { ok: boolean; version: string };
  49. expect(body.ok).toBe(true);
  50. expect(typeof body.version).toBe('string');
  51. });
  52. it('GET /healthz still returns health (legacy alias)', async () => {
  53. const res = await worker.fetch(new Request('https://w/healthz'), TEST_ENV);
  54. expect(res.status).toBe(200);
  55. const body = (await res.json()) as { ok: boolean };
  56. expect(body.ok).toBe(true);
  57. });
  58. });
  59. describe('POST / (siteverify proxy) — JSON body', () => {
  60. beforeEach(() => vi.restoreAllMocks());
  61. afterEach(() => vi.restoreAllMocks());
  62. it('forwards a JSON token to siteverify and returns success', async () => {
  63. mockFetchOnce({
  64. body: {
  65. success: true,
  66. hostname: 'example.com',
  67. challenge_ts: '2026-05-22T12:00:00Z',
  68. 'error-codes': [],
  69. },
  70. });
  71. const res = await worker.fetch(
  72. new Request('https://w/', {
  73. method: 'POST',
  74. headers: { 'Content-Type': 'application/json' },
  75. body: JSON.stringify({ token: 'abc' }),
  76. }),
  77. TEST_ENV,
  78. );
  79. expect(res.status).toBe(200);
  80. const body = (await res.json()) as { success: boolean; _worker?: { worker_version: string } };
  81. expect(body.success).toBe(true);
  82. expect(body._worker?.worker_version).toMatch(/^\d+\.\d+\.\d+$/);
  83. // Verify it called the right upstream
  84. expect(globalThis.fetch).toHaveBeenCalledOnce();
  85. expect((globalThis.fetch as ReturnType<typeof vi.fn>).mock.calls[0]?.[0]).toBe(SITEVERIFY_URL);
  86. });
  87. it('passes through siteverify failure with success=false', async () => {
  88. mockFetchOnce({
  89. body: { success: false, 'error-codes': ['invalid-input-response'] },
  90. });
  91. const res = await worker.fetch(
  92. new Request('https://w/', {
  93. method: 'POST',
  94. headers: { 'Content-Type': 'application/json' },
  95. body: JSON.stringify({ token: 'bad' }),
  96. }),
  97. TEST_ENV,
  98. );
  99. expect(res.status).toBe(200);
  100. const body = (await res.json()) as { success: boolean; 'error-codes': string[] };
  101. expect(body.success).toBe(false);
  102. expect(body['error-codes']).toContain('invalid-input-response');
  103. });
  104. it('returns 400 when token is missing', async () => {
  105. const res = await worker.fetch(
  106. new Request('https://w/', {
  107. method: 'POST',
  108. headers: { 'Content-Type': 'application/json' },
  109. body: JSON.stringify({}),
  110. }),
  111. TEST_ENV,
  112. );
  113. expect(res.status).toBe(400);
  114. const body = (await res.json()) as { success: boolean; 'error-codes': string[] };
  115. expect(body.success).toBe(false);
  116. expect(body['error-codes']).toContain('missing-token');
  117. });
  118. it('returns 400 on malformed JSON', async () => {
  119. const res = await worker.fetch(
  120. new Request('https://w/', {
  121. method: 'POST',
  122. headers: { 'Content-Type': 'application/json' },
  123. body: '{not json',
  124. }),
  125. TEST_ENV,
  126. );
  127. expect(res.status).toBe(400);
  128. });
  129. it('accepts cf-turnstile-response as alias for token', async () => {
  130. mockFetchOnce({
  131. body: { success: true, 'error-codes': [] },
  132. });
  133. const res = await worker.fetch(
  134. new Request('https://w/', {
  135. method: 'POST',
  136. headers: { 'Content-Type': 'application/json' },
  137. body: JSON.stringify({ 'cf-turnstile-response': 'xyz' }),
  138. }),
  139. TEST_ENV,
  140. );
  141. expect(res.status).toBe(200);
  142. });
  143. });
  144. describe('POST / (siteverify proxy) — form body', () => {
  145. beforeEach(() => vi.restoreAllMocks());
  146. afterEach(() => vi.restoreAllMocks());
  147. it('accepts urlencoded body', async () => {
  148. mockFetchOnce({
  149. body: { success: true, 'error-codes': [] },
  150. });
  151. const res = await worker.fetch(
  152. new Request('https://w/', {
  153. method: 'POST',
  154. headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
  155. body: 'token=abc',
  156. }),
  157. TEST_ENV,
  158. );
  159. expect(res.status).toBe(200);
  160. const body = (await res.json()) as { success: boolean };
  161. expect(body.success).toBe(true);
  162. });
  163. it('accepts cf-turnstile-response from form body', async () => {
  164. mockFetchOnce({
  165. body: { success: true, 'error-codes': [] },
  166. });
  167. const res = await worker.fetch(
  168. new Request('https://w/', {
  169. method: 'POST',
  170. headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
  171. body: 'cf-turnstile-response=xyz',
  172. }),
  173. TEST_ENV,
  174. );
  175. expect(res.status).toBe(200);
  176. });
  177. });
  178. describe('Content-Type handling', () => {
  179. beforeEach(() => vi.restoreAllMocks());
  180. afterEach(() => vi.restoreAllMocks());
  181. it('returns 415 for unsupported content type', async () => {
  182. const res = await worker.fetch(
  183. new Request('https://w/', {
  184. method: 'POST',
  185. headers: { 'Content-Type': 'text/plain' },
  186. body: 'token=abc',
  187. }),
  188. TEST_ENV,
  189. );
  190. expect(res.status).toBe(415);
  191. const body = (await res.json()) as { 'error-codes': string[] };
  192. expect(body['error-codes']).toContain('invalid-content-type');
  193. });
  194. });
  195. describe('Path routing', () => {
  196. beforeEach(() => vi.restoreAllMocks());
  197. afterEach(() => vi.restoreAllMocks());
  198. it('accepts POST /siteverify as alias of POST /', async () => {
  199. mockFetchOnce({
  200. body: { success: true, 'error-codes': [] },
  201. });
  202. const res = await worker.fetch(
  203. new Request('https://w/siteverify', {
  204. method: 'POST',
  205. headers: { 'Content-Type': 'application/json' },
  206. body: JSON.stringify({ token: 'abc' }),
  207. }),
  208. TEST_ENV,
  209. );
  210. expect(res.status).toBe(200);
  211. });
  212. it('returns 404 for unknown paths', async () => {
  213. const res = await worker.fetch(new Request('https://w/random'), TEST_ENV);
  214. expect(res.status).toBe(404);
  215. });
  216. });
  217. describe('CF-Connecting-IP fallback', () => {
  218. beforeEach(() => vi.restoreAllMocks());
  219. afterEach(() => vi.restoreAllMocks());
  220. it('uses CF-Connecting-IP if customer did not pass remoteip', async () => {
  221. const fetchSpy = vi.spyOn(globalThis, 'fetch').mockImplementationOnce(async (_url, init) => {
  222. const form = init?.body as FormData;
  223. expect(form.get('remoteip')).toBe('1.2.3.4');
  224. return new Response(JSON.stringify({ success: true, 'error-codes': [] }), { status: 200 });
  225. });
  226. const res = await worker.fetch(
  227. new Request('https://w/', {
  228. method: 'POST',
  229. headers: {
  230. 'Content-Type': 'application/json',
  231. 'CF-Connecting-IP': '1.2.3.4',
  232. },
  233. body: JSON.stringify({ token: 'abc' }),
  234. }),
  235. TEST_ENV,
  236. );
  237. expect(res.status).toBe(200);
  238. expect(fetchSpy).toHaveBeenCalledOnce();
  239. });
  240. it('prefers explicit remoteip over CF-Connecting-IP', async () => {
  241. vi.spyOn(globalThis, 'fetch').mockImplementationOnce(async (_url, init) => {
  242. const form = init?.body as FormData;
  243. expect(form.get('remoteip')).toBe('9.9.9.9');
  244. return new Response(JSON.stringify({ success: true, 'error-codes': [] }), { status: 200 });
  245. });
  246. await worker.fetch(
  247. new Request('https://w/', {
  248. method: 'POST',
  249. headers: {
  250. 'Content-Type': 'application/json',
  251. 'CF-Connecting-IP': '1.2.3.4',
  252. },
  253. body: JSON.stringify({ token: 'abc', remoteip: '9.9.9.9' }),
  254. }),
  255. TEST_ENV,
  256. );
  257. });
  258. });
  259. describe('Hostname-mismatch defense', () => {
  260. beforeEach(() => vi.restoreAllMocks());
  261. afterEach(() => vi.restoreAllMocks());
  262. it('rejects success response when hostname does not match EXPECTED_HOSTNAME', async () => {
  263. mockFetchOnce({
  264. body: { success: true, hostname: 'attacker.com', 'error-codes': [] },
  265. });
  266. const env: Env = { ...TEST_ENV, EXPECTED_HOSTNAME: 'mysite.com' };
  267. const res = await worker.fetch(
  268. new Request('https://w/', {
  269. method: 'POST',
  270. headers: { 'Content-Type': 'application/json' },
  271. body: JSON.stringify({ token: 'abc' }),
  272. }),
  273. env,
  274. );
  275. expect(res.status).toBe(200);
  276. const body = (await res.json()) as { success: boolean; 'error-codes': string[] };
  277. expect(body.success).toBe(false);
  278. expect(body['error-codes']).toContain('hostname-mismatch');
  279. });
  280. it('accepts success response when hostname matches EXPECTED_HOSTNAME', async () => {
  281. mockFetchOnce({
  282. body: { success: true, hostname: 'mysite.com', 'error-codes': [] },
  283. });
  284. const env: Env = { ...TEST_ENV, EXPECTED_HOSTNAME: 'mysite.com' };
  285. const res = await worker.fetch(
  286. new Request('https://w/', {
  287. method: 'POST',
  288. headers: { 'Content-Type': 'application/json' },
  289. body: JSON.stringify({ token: 'abc' }),
  290. }),
  291. env,
  292. );
  293. const body = (await res.json()) as { success: boolean };
  294. expect(body.success).toBe(true);
  295. });
  296. it('does not apply hostname check when EXPECTED_HOSTNAME is unset', async () => {
  297. mockFetchOnce({
  298. body: { success: true, hostname: 'anywhere.com', 'error-codes': [] },
  299. });
  300. const res = await worker.fetch(
  301. new Request('https://w/', {
  302. method: 'POST',
  303. headers: { 'Content-Type': 'application/json' },
  304. body: JSON.stringify({ token: 'abc' }),
  305. }),
  306. TEST_ENV,
  307. );
  308. const body = (await res.json()) as { success: boolean };
  309. expect(body.success).toBe(true);
  310. });
  311. });
  312. describe('Missing secret', () => {
  313. beforeEach(() => vi.restoreAllMocks());
  314. afterEach(() => vi.restoreAllMocks());
  315. it('returns 500 with missing-input-secret when TURNSTILE_SECRET_KEY is empty', async () => {
  316. const env = { ...TEST_ENV, TURNSTILE_SECRET_KEY: '' };
  317. const res = await worker.fetch(
  318. new Request('https://w/', {
  319. method: 'POST',
  320. headers: { 'Content-Type': 'application/json' },
  321. body: JSON.stringify({ token: 'abc' }),
  322. }),
  323. env,
  324. );
  325. expect(res.status).toBe(500);
  326. const body = (await res.json()) as { 'error-codes': string[] };
  327. expect(body['error-codes']).toContain('missing-input-secret');
  328. });
  329. });