From a988dc37e1a7dc9caaddb190e2997ebfcbe4557b Mon Sep 17 00:00:00 2001 From: Octo8080X <64694349+Octo8080X@users.noreply.github.com> Date: Fri, 25 Jul 2025 22:55:33 +0900 Subject: [PATCH] feat: add CSRF middleware (#3018) Co-authored-by: Marvin Hagemeister --- src/middlewares/csrf.ts | 113 +++++++++++++++++++++++++++++++++++ src/middlewares/csrf_test.ts | 101 +++++++++++++++++++++++++++++++ src/mod.ts | 1 + 3 files changed, 215 insertions(+) create mode 100644 src/middlewares/csrf.ts create mode 100644 src/middlewares/csrf_test.ts diff --git a/src/middlewares/csrf.ts b/src/middlewares/csrf.ts new file mode 100644 index 00000000..5d080cfa --- /dev/null +++ b/src/middlewares/csrf.ts @@ -0,0 +1,113 @@ +import type { Context } from "../context.ts"; +import { HttpError } from "../error.ts"; +import type { Middleware } from "./mod.ts"; + +/** Options for {@linkcode csrf}. **/ +// deno-lint-ignore no-explicit-any +export interface CsrfOptions { + /** + * origin - Specifies the allowed origin(s) for requests. + * - string: A single allowed origin. + * - string[]: static allowed origins. + * - function: A function to determine if an origin is allowed. + */ + origin?: + | string + | string[] + | ((origin: string, context: Context) => boolean); +} + +/** + * CSRF Protection Middleware for Fresh. + * + * @param options Options for the CSRF protection middleware. + * @returns The middleware handler function. + * + * @example Basic usage (with defaults) + * ```ts + * const app = new App() + * + * app.use(csrf()) + * ``` + * + * @example Specifying static origins + * ```ts + * app.use(csrf({ origin: 'https://myapp.example.com' })) + * + * // string[] + * app.use( + * csrf({ + * origin: ['https://myapp.example.com', 'http://development.myapp.example.com'], + * }) + * ) + * ``` + * + * @example Specifying more complex origins + * ```ts + * app.use( + * '*', + * csrf({ + * origin: (origin) => ['https://myapp.example.com', 'http://development.myapp.example.com'].includes(origin), + * }) + * ) + * ``` + */ +export function csrf( + options?: CsrfOptions, +): Middleware { + const isAllowedOrigin = ( + origin: string | null, + ctx: Context, + ) => { + if (origin === null) { + return false; + } + + const optsOrigin = options?.origin; + + if (!optsOrigin) { + return origin === ctx.url.origin; + } + if (typeof optsOrigin === "string") { + return origin === optsOrigin; + } + if (typeof optsOrigin === "function") { + return optsOrigin(origin, ctx); + } + return Array.isArray(optsOrigin) && optsOrigin.includes(origin); + }; + + return async (ctx) => { + const { method, headers } = ctx.req; + + // Safe methods + if (method === "GET" || method === "HEAD" || method === "OPTIONS") { + return await ctx.next(); + } + + const secFetchSite = headers.get("Sec-Fetch-Site"); + const origin = headers.get("origin"); + + if (secFetchSite !== null) { + if ( + secFetchSite === "same-origin" || secFetchSite === "none" || + isAllowedOrigin(origin, ctx) + ) { + return await ctx.next(); + } + + throw new HttpError(403); + } + + // Neither `Sec-Fetch-Site` or `Origin` is set + if (origin === null) { + return await ctx.next(); + } + + if (isAllowedOrigin(origin, ctx)) { + return await ctx.next(); + } + + throw new HttpError(403); + }; +} diff --git a/src/middlewares/csrf_test.ts b/src/middlewares/csrf_test.ts new file mode 100644 index 00000000..c9d51ca5 --- /dev/null +++ b/src/middlewares/csrf_test.ts @@ -0,0 +1,101 @@ +import { App } from "../app.ts"; +import type { Method } from "../router.ts"; +import { csrf, type CsrfOptions } from "./csrf.ts"; +import { expect } from "@std/expect"; + +function testHandler( + options?: CsrfOptions, +): (request: Request) => Promise { + return new App() + .use(csrf(options)) + .all("/", () => new Response("hello")) + .handler(); +} + +function createTests(trusted: CsrfOptions["origin"]) { + return async function runTest( + method: Method, + expected: 200 | 403, + test: { + secFetchSite?: "cross-site" | "same-origin" | "same-site" | "none"; + origin?: string; + } = {}, + ) { + const handler = testHandler({ origin: trusted }); + + const headers = new Headers(); + if (test.secFetchSite) headers.append("Sec-Fetch-Site", test.secFetchSite); + if (test.origin) { + headers.append("Origin", test.origin); + } + + const res = await handler( + new Request("https://example.com", { method, headers }), + ); + await res.body?.cancel(); + expect(res.status).toEqual(expected); + }; +} + +Deno.test("CSRF - allow GET/HEAD/OPTIONS", async () => { + const runTest = createTests("https://example.com"); + + await runTest("GET", 200); + await runTest("HEAD", 200); + await runTest("OPTIONS", 200); +}); + +Deno.test("CSRF - Sec-Fetch-Site", async () => { + const runTest = createTests("https://example.com"); + + await runTest("POST", 200, { secFetchSite: "same-origin" }); + await runTest("POST", 200, { secFetchSite: "none" }); + await runTest("POST", 403, { secFetchSite: "cross-site" }); + await runTest("POST", 403, { secFetchSite: "same-site" }); + + await runTest("POST", 200); + await runTest("POST", 200, { origin: "https://example.com" }); + await runTest("POST", 403, { origin: "https://attacker.example.com" }); + await runTest("POST", 403, { origin: "null" }); + + await runTest("GET", 200, { secFetchSite: "cross-site" }); + await runTest("HEAD", 200, { secFetchSite: "cross-site" }); + await runTest("OPTIONS", 200, { secFetchSite: "cross-site" }); + await runTest("PUT", 403, { secFetchSite: "cross-site" }); +}); + +Deno.test("CSRF - cross origin", async () => { + const runTest = createTests("https://trusted.example.com"); + + await runTest("POST", 200, { origin: "https://trusted.example.com" }); + await runTest("POST", 200, { + origin: "https://trusted.example.com", + secFetchSite: "cross-site", + }); + + await runTest("POST", 403, { origin: "https://attacker.example.com" }); + await runTest("POST", 403, { + origin: "https://attacker.example.com", + secFetchSite: "cross-site", + }); +}); + +Deno.test("CSRF - array origin", async () => { + const runTest = createTests( + ["https://example.com", "https://trusted.example.com"], + ); + + await runTest("POST", 200, { origin: "https://trusted.example.com" }); + await runTest("POST", 200, { origin: "https://example.com" }); + await runTest("POST", 403, { origin: "https://foo.example.com" }); +}); + +Deno.test("CSRF - function origin", async () => { + const runTest = createTests( + (origin) => origin === "https://example.com", + ); + + await runTest("POST", 200, { origin: "https://example.com" }); + await runTest("POST", 403, { origin: "https://trusted.example.com" }); + await runTest("POST", 403, { origin: "https://foo.example.com" }); +}); diff --git a/src/mod.ts b/src/mod.ts index 092bcdd2..a6cd6be0 100644 --- a/src/mod.ts +++ b/src/mod.ts @@ -11,6 +11,7 @@ export { export type { LayoutConfig, Lazy, MaybeLazy, RouteConfig } from "./types.ts"; export type { Middleware, MiddlewareFn } from "./middlewares/mod.ts"; export { staticFiles } from "./middlewares/static_files.ts"; +export { csrf, type CsrfOptions } from "./middlewares/csrf.ts"; export { cors, type CORSOptions } from "./middlewares/cors.ts"; export type { FreshConfig, ResolvedFreshConfig } from "./config.ts"; export type { Context, FreshContext, Island } from "./context.ts";