Files
WRNexusJS/packages/dev-server/test/rpc-csrf.test.ts
T

62 lines
1.6 KiB
TypeScript

import { expect, test } from "bun:test";
import { validateRpcCsrf } from "../src/index.ts";
function request(headers: Record<string, string> = {}): Request {
return new Request("https://app.example/__wrnexus/rpc", {
method: "POST",
headers,
});
}
test("RPC CSRF rejects cross-site fetch metadata even with matching tokens", () => {
expect(
validateRpcCsrf(
request({
cookie: "wrn-csrf=token",
"x-csrf-token": "token",
"sec-fetch-site": "cross-site",
}),
),
).toBe(false);
});
test("RPC CSRF rejects malformed cookie encoding without throwing", () => {
for (const cookieName of ["wrn-csrf", "wrnexus_csrf"]) {
expect(
validateRpcCsrf(
request({
cookie: `${cookieName}=%E0%A4%A`,
"x-csrf-token": "%E0%A4%A",
}),
),
).toBe(false);
}
});
test("RPC CSRF requires a matching cookie and header from the same origin", () => {
expect(validateRpcCsrf(request())).toBe(false);
expect(validateRpcCsrf(request({ cookie: "wrn-csrf=token" }))).toBe(false);
expect(validateRpcCsrf(request({ "x-csrf-token": "token" }))).toBe(false);
expect(validateRpcCsrf(request({ cookie: "wrn-csrf=token", "x-csrf-token": "forged" }))).toBe(
false,
);
expect(
validateRpcCsrf(
request({
cookie: "wrn-csrf=token",
"x-csrf-token": "token",
origin: "https://evil.example",
}),
),
).toBe(false);
expect(
validateRpcCsrf(
request({
cookie: "wrn-csrf=encoded%20token",
"x-csrf-token": "encoded token",
origin: "https://app.example",
}),
),
).toBe(true);
});