import { test, expect } from "bun:test"; import { createContext, csrfToken, verifyCsrf, CSRF_COOKIE } from "../src/index.ts"; function ctx(method: string, cookie?: string, header?: string) { const headers: Record = {}; if (cookie) headers.cookie = `${CSRF_COOKIE}=${cookie}`; if (header) headers["x-csrf-token"] = header; const req = new Request("http://x/api", { method, headers }); return createContext(req, new URL(req.url)); } test("csrfToken issues a token", () => { const token = csrfToken(ctx("GET")); expect(token).toBeTruthy(); expect(token.length).toBeGreaterThan(16); }); test("verifyCsrf: safe methods always pass", () => { expect(verifyCsrf(ctx("GET"))).toBe(true); expect(verifyCsrf(ctx("HEAD"))).toBe(true); }); test("verifyCsrf: unsafe methods need matching cookie + header", () => { expect(verifyCsrf(ctx("POST", "abc", "abc"))).toBe(true); expect(verifyCsrf(ctx("POST", "abc", "xyz"))).toBe(false); // mismatch expect(verifyCsrf(ctx("POST", "abc"))).toBe(false); // no header expect(verifyCsrf(ctx("POST", undefined, "abc"))).toBe(false); // no cookie });