Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .env.example
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,11 @@ JWT_SECRET=change-me-in-production
# For production: https://yourdomain.com
ORIGIN=http://localhost:8000

# Extra origins allowed to submit forms (comma-separated, full origin incl. scheme+port).
# Supports glob, e.g. http://*.ts.net:8003, or "*" to allow all (trusted networks only).
# Optional; when unset, only ORIGIN is allowed.
# TRUSTED_ORIGINS=

# ─── Database ─────────────────────────────────────────────
# Docker (default): /app/data/invio.db
# Local development: ./invio.db
Expand Down
5 changes: 5 additions & 0 deletions frontend/bun.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 3 additions & 1 deletion frontend/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -13,14 +13,16 @@
"check": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json",
"check:watch": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json --watch",
"lint": "prettier --check . && eslint .",
"format": "prettier --write ."
"format": "prettier --write .",
"test": "bun test"
},
"devDependencies": {
"@sveltejs/adapter-auto": "^7.0.0",
"@sveltejs/adapter-node": "^5.5.4",
"@sveltejs/kit": "^2.50.2",
"@sveltejs/vite-plugin-svelte": "^6.2.4",
"@tailwindcss/vite": "^4.1.18",
"@types/bun": "^1.4.0",
"@types/node": "^25.5.1",
"@typescript-eslint/parser": "^8.59.0",
"eslint": "^10.2.0",
Expand Down
35 changes: 34 additions & 1 deletion frontend/src/hooks.server.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,42 @@
import type { Handle } from "@sveltejs/kit";
import { dev } from "$app/environment";
import { error, type Handle } from "@sveltejs/kit";
import { env } from "$env/dynamic/private";
import { resolveLocalization, DEFAULT_LOCALIZATION } from "$lib/i18n/mod";
import { getAuthHeaderFromCookie } from "$lib/auth";
import { backendGet } from "$lib/backend";
import {
isMutatingFormRequest,
originAllowed,
originMatchesRequestHost,
parseAllowedOrigins,
} from "$lib/csrf";

function assertTrustedFormOrigin(event: Parameters<Handle>[0]["event"]): void {
if (!isMutatingFormRequest(event.request)) {
return;
}

const origin = event.request.headers.get("origin") ?? "";
const allowedOrigins = parseAllowedOrigins(env.ORIGIN, env.TRUSTED_ORIGINS);

const allowed =
allowedOrigins.length > 0
? originAllowed(origin, allowedOrigins)
: originMatchesRequestHost(origin, event.request.headers.get("host"));

if (!allowed) {
error(
403,
`Cross-site ${event.request.method} form submissions are forbidden`,
);
}
}

export const handle: Handle = async ({ event, resolve }) => {
if (!dev) {
assertTrustedFormOrigin(event);
}

const cookieString = event.request.headers.get("cookie");

// Auth
Expand Down
110 changes: 110 additions & 0 deletions frontend/src/lib/csrf.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,110 @@
import { describe, expect, test } from "bun:test";
import {
originAllowed,
originMatchesRequestHost,
parseAllowedOrigins,
isMutatingFormRequest,
} from "./csrf";

describe("originAllowed", () => {
test("exact match", () => {
expect(
originAllowed("http://localhost:8000", ["http://localhost:8000"]),
).toBe(true);
});

test("hostname mismatch is denied", () => {
expect(
originAllowed("http://127.0.0.1:8000", ["http://localhost:8000"]),
).toBe(false);
});

test("missing origin is denied", () => {
expect(originAllowed("", ["http://localhost:8000"])).toBe(false);
expect(originAllowed("", ["*"])).toBe(false);
});

test("wildcard allows any origin", () => {
expect(originAllowed("http://evil.example:8000", ["*"])).toBe(true);
});

test("glob matches Tailscale MagicDNS", () => {
expect(
originAllowed("http://umbrel-home.tailf2e95.ts.net:8003", [
"http://*.ts.net:8003",
]),
).toBe(true);
});

test("glob rejects other hosts and ports", () => {
expect(
originAllowed("http://evil.example:8003", ["http://*.ts.net:8003"]),
).toBe(false);
expect(
originAllowed("http://umbrel-home.tailf2e95.ts.net:8000", [
"http://*.ts.net:8003",
]),
).toBe(false);
});
});

describe("parseAllowedOrigins", () => {
test("ORIGIN only", () => {
expect(parseAllowedOrigins("http://umbrel.local:8003", undefined)).toEqual([
"http://umbrel.local:8003",
]);
});

test("ORIGIN plus TRUSTED_ORIGINS", () => {
expect(
parseAllowedOrigins(
"http://app.local:8000",
"http://tailscale.local:8000, http://*.ts.net:8003",
),
).toEqual([
"http://app.local:8000",
"http://tailscale.local:8000",
"http://*.ts.net:8003",
]);
});

test("both env vars empty yields empty list", () => {
expect(parseAllowedOrigins(undefined, undefined)).toEqual([]);
expect(parseAllowedOrigins("", "")).toEqual([]);
});
});

describe("originMatchesRequestHost", () => {
test("matches Host including port, ignoring http vs https", () => {
expect(
originMatchesRequestHost("http://app.local:18000", "app.local:18000"),
).toBe(true);
expect(
originMatchesRequestHost("https://app.local:18000", "app.local:18000"),
).toBe(true);
});

test("rejects a different hostname", () => {
expect(
originMatchesRequestHost(
"http://tailscale.local:18000",
"app.local:18000",
),
).toBe(false);
});
});

describe("isMutatingFormRequest", () => {
test("login form POST is checked", () => {
const request = new Request("http://localhost/login?/login", {
method: "POST",
headers: { "content-type": "application/x-www-form-urlencoded" },
});
expect(isMutatingFormRequest(request)).toBe(true);
});

test("GET is not checked", () => {
const request = new Request("http://localhost/login");
expect(isMutatingFormRequest(request)).toBe(false);
});
});
67 changes: 67 additions & 0 deletions frontend/src/lib/csrf.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
const FORM_CONTENT_TYPES = new Set([
"application/x-www-form-urlencoded",
"multipart/form-data",
"text/plain",
]);

const MUTATING_METHODS = new Set(["POST", "PUT", "PATCH", "DELETE"]);

export function isFormContentType(request: Request): boolean {
const type =
request.headers
.get("content-type")
?.split(";", 1)[0]
.trim()
.toLowerCase() ?? "";
return FORM_CONTENT_TYPES.has(type);
}

export function isMutatingFormRequest(request: Request): boolean {
return MUTATING_METHODS.has(request.method) && isFormContentType(request);
}

function escapeRegex(value: string): string {
return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
}

export function originAllowed(origin: string, patterns: string[]): boolean {
if (!origin) return false;
for (const pattern of patterns) {
if (pattern === "*") return true;
if (pattern === origin) return true;
if (pattern.includes("*")) {
const regex = new RegExp(
"^" + pattern.split("*").map(escapeRegex).join(".+") + "$",
);
if (regex.test(origin)) return true;
}
}
return false;
}

export function parseAllowedOrigins(
originEnv: string | undefined,
trustedOriginsEnv: string | undefined,
): string[] {
return [
...(originEnv?.trim() ? [originEnv.trim()] : []),
...(trustedOriginsEnv ?? "")
.split(",")
.map((value) => value.trim())
.filter(Boolean),
];
}

/** True when Origin's host[:port] matches the incoming Host header (scheme ignored). */
export function originMatchesRequestHost(
origin: string,
hostHeader: string | null | undefined,
): boolean {
if (!origin || !hostHeader) return false;
try {
const originUrl = new URL(origin);
return originUrl.host === hostHeader || originUrl.hostname === hostHeader;
} catch {
return false;
}
}
3 changes: 3 additions & 0 deletions frontend/svelte.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,9 @@ const config = {
adapter: adapter({
out: "build",
}),
csrf: {
trustedOrigins: ["*"],
},
},
vitePlugin: {
dynamicCompileOptions: ({ filename }) =>
Expand Down
Loading