Files
outline/server/middlewares/csrf.ts
T
Tom MoorandClaude Opus 5 ac07b97a85 fix: Align CSRF cookie resolution between attach and verify paths (#13426)
* fix: Align CSRF cookie resolution between attach and verify paths

The middleware that attaches the token picked one cookie name based on
whether the request was secure, while the verifier accepted either name.
Resolve the name through a single helper so both paths always agree, and
warn at startup when proxy headers are untrusted on an https install.

* Remove excessive tests

* fix: Describe the request scheme on the MCP-derived API context

Helpers shared between the MCP tools and the HTTP routes read the scheme
from the context, which the MCP stub did not provide.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* fix: Do not warn about proxy headers when the app terminates TLS itself

The socket is already encrypted in that case, so the request scheme is
known without X-Forwarded-Proto. Extract the certificate check that main
was doing inline so both call sites stay in step.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* simplify

---------

Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-14 17:56:39 -04:00

113 lines
3.3 KiB
TypeScript

import type { Next } from "koa";
import { Scope } from "@shared/types";
import env from "@server/env";
import AuthenticationHelper from "@shared/helpers/AuthenticationHelper";
import type { AppContext } from "@server/types";
import {
generateRawToken,
bundleToken,
unbundleToken,
getCookieName,
getTokenFromCookie,
} from "@server/utils/csrf";
import { CSRF } from "@shared/constants";
import { CSRFError } from "@server/errors";
import { parseAuthentication } from "./authentication";
/**
* Middleware that generates and attaches CSRF tokens for safe methods
*/
export function attachCSRFToken() {
return async function attachCSRFTokenMiddleware(ctx: AppContext, next: Next) {
// Only attach tokens for safe methods that don't mutate state
if (["GET", "HEAD", "OPTIONS"].includes(ctx.method)) {
const raw = generateRawToken(16);
const bundled = bundleToken(raw, env.SECRET_KEY);
// Set cookie that JavaScript can read (not HttpOnly). Unlike the UI hint
// cookies, this one is deliberately host-only and never scoped to the
// base domain
ctx.cookies.set(getCookieName(ctx), bundled, {
httpOnly: false,
sameSite: "lax",
secure: ctx.request.secure,
});
}
await next();
};
}
/**
* Middleware that verifies CSRF tokens for mutating requests
*/
export function verifyCSRFToken() {
/**
* Determines if a request requires CSRF protection
*/
const shouldProtectRequest = (ctx: AppContext): boolean => {
// Skip if not a potentially mutating method
if (["GET", "HEAD", "OPTIONS"].includes(ctx.method)) {
return false;
}
// If not using cookie-based auth, skip CSRF protection
const { transport } = parseAuthentication(ctx);
if (transport !== "cookie") {
return false;
}
// For API routes, use AuthenticationHelper to determine if the operation is read-only
if (ctx.originalUrl.startsWith("/api/")) {
const canAccessWithReadOnly = AuthenticationHelper.canAccess(ctx.path, [
Scope.Read,
]);
// If it can be accessed with read-only scope, it doesn't need CSRF protection
if (canAccessWithReadOnly) {
return false;
}
}
// Protect all other mutating requests
return true;
};
return async function verifyCSRFTokenMiddleware(ctx: AppContext, next: Next) {
if (!shouldProtectRequest(ctx)) {
await next();
return;
}
// Get token from cookie
const cookieVal = getTokenFromCookie(ctx);
if (!cookieVal) {
throw CSRFError("CSRF token missing from cookie");
}
// Get token from header or form field depending on type
// Access the already-parsed body from koa-body middleware
const inputVal =
ctx.get(CSRF.headerName) || ctx.request.body?.[CSRF.fieldName];
if (!inputVal) {
throw CSRFError("CSRF token missing from request");
}
// Verify both tokens are valid HMAC-signed tokens
const { valid: cookieValid } = unbundleToken(cookieVal, env.SECRET_KEY);
const { valid: inputValid } = unbundleToken(inputVal, env.SECRET_KEY);
if (!cookieValid || !inputValid) {
throw CSRFError("CSRF token invalid or malformed");
}
// Verify tokens match (double-submit check)
if (cookieVal !== inputVal) {
throw CSRFError("CSRF token mismatch");
}
await next();
};
}