From 31b825b183bfae702c8ceb2fa48b29a4b830cf73 Mon Sep 17 00:00:00 2001 From: Fuwn Date: Tue, 2 Jun 2026 00:25:29 +0000 Subject: fix(security): sanitize badge_wall_css server-side, render via textContent Custom badge-wall CSS was sanitised only client-side with a fragile regex and injected via innerHTML, while the stored value stayed raw. Sanitise at the write boundary instead (setCSS, covering both the REST and GraphQL paths) with a css-tree pass that parses leniently and drops @import, behavior/-moz-binding, expression()/javascript: values, and break-out attempts; render with textContent instead of innerHTML so break-out is impossible by construction (CSP already blocks inline script). css-tree stays server-only. A behaviour-gate test confirms ordinary CSS (backdrop-filter, content, url(), @media, @keyframes) is preserved while the dangerous constructs are removed. The previous regex also silently stripped all `content:` declarations; those now render correctly. --- package.json | 2 + pnpm-lock.yaml | 25 ++++++++++ src/lib/Database/SB/User/preferences.ts | 3 +- src/lib/Utility/sanitizeCss.test.ts | 76 ++++++++++++++++++++++++++++++ src/lib/Utility/sanitizeCss.ts | 57 ++++++++++++++++++++++ src/routes/user/[user]/badges/+page.svelte | 13 +---- 6 files changed, 163 insertions(+), 13 deletions(-) create mode 100644 src/lib/Utility/sanitizeCss.test.ts create mode 100644 src/lib/Utility/sanitizeCss.ts diff --git a/package.json b/package.json index ac44767c..c6f795a5 100644 --- a/package.json +++ b/package.json @@ -29,6 +29,7 @@ "@sveltejs/adapter-vercel": "5.0.0", "@sveltejs/kit": "2.5.27", "@sveltejs/vite-plugin-svelte": "^4.0.0", + "@types/css-tree": "^2.3.11", "@types/fast-levenshtein": "^0.0.4", "@types/jsdom": "^21.1.6", "@types/string-similarity": "^4.0.2", @@ -57,6 +58,7 @@ "@vercel/speed-insights": "^1.0.9", "botid": "^1.5.10", "caniuse-lite": "^1.0.30001655", + "css-tree": "^3.2.1", "dexie": "^4.0.1-alpha.25", "dompurify": "^3.4.7", "effect": "4.0.0-beta.25", diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index cc1644e5..d270e294 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -29,6 +29,9 @@ importers: caniuse-lite: specifier: ^1.0.30001655 version: 1.0.30001766 + css-tree: + specifier: ^3.2.1 + version: 3.2.1 dexie: specifier: ^4.0.1-alpha.25 version: 4.2.1 @@ -96,6 +99,9 @@ importers: '@sveltejs/vite-plugin-svelte': specifier: ^4.0.0 version: 4.0.4(svelte@5.48.0)(vite@5.4.21(@types/node@25.3.3)(sass@1.97.3)) + '@types/css-tree': + specifier: ^2.3.11 + version: 2.3.11 '@types/fast-levenshtein': specifier: ^0.0.4 version: 0.0.4 @@ -2072,6 +2078,9 @@ packages: '@types/cors@2.8.19': resolution: {integrity: sha512-mFNylyeyqN93lfe/9CSxOGREz8cpzAhH+E93xJ4xWQf62V8sQ/24reV2nyzUWM6H6Xji+GGHpkbLe7pVoUEskg==} + '@types/css-tree@2.3.11': + resolution: {integrity: sha512-aEokibJOI77uIlqoBOkVbaQGC9zII0A+JH1kcTNKW2CwyYWD8KM6qdo+4c77wD3wZOQfJuNWAr9M4hdk+YhDIg==} + '@types/deep-eql@4.0.2': resolution: {integrity: sha512-c9h9dVVMigMPc4bwTvC5dxqtqJZwQPePsWjPlpSOnojbor6pGqdk541lfA7AqFQr5pB1BRdq0juY9db81BwyFw==} @@ -2569,6 +2578,10 @@ packages: resolution: {integrity: sha512-6Fv1DV/TYw//QF5IzQdqsNDjx/wc8TrMBZsqjL9eW01tWb7R7k/mq+/VXfJCl7SoD5emsJop9cOByJZfs8hYIw==} engines: {node: ^10 || ^12.20.0 || ^14.13.0 || >=15.0.0} + css-tree@3.2.1: + resolution: {integrity: sha512-X7sjQzceUhu1u7Y/ylrRZFU2FS6LRiFVp6rKLPg23y3x3c3DOKAwuXGDp+PAGjh6CSnCjYeAul8pcT8bAl+lSA==} + engines: {node: ^10 || ^12.20.0 || ^14.13.0 || >=15.0.0} + cssstyle@4.6.0: resolution: {integrity: sha512-2z+rWdzbbSZv6/rhtvzvqeZQHrBaqgogqt85sqFNbabZOuFbCVFb8kPeEtZjiKkbrm395irpNKiYeFeLiQnFPg==} engines: {node: '>=18'} @@ -3404,6 +3417,9 @@ packages: mdn-data@2.0.30: resolution: {integrity: sha512-GaqWWShW4kv/G9IEucWScBx9G1/vsFZZJUO+tD26M8J8z3Kw5RDQjaoZe03YAClgeS/SWPOcb4nkFBTEi5DUEA==} + mdn-data@2.27.1: + resolution: {integrity: sha512-9Yubnt3e8A0OKwxYSXyhLymGW4sCufcLG6VdiDdUGVkPhpqLxlvP5vl1983gQjJl3tqbrM731mjaZaP68AgosQ==} + memfs@3.5.3: resolution: {integrity: sha512-UERzLsxzllchadvbPs5aolHh65ISpKpM+ccLbOJ8/vvpBKmAWf+la7dXFy7Mr0ySHbdHrFv5kGFCUHHe6GFEmw==} engines: {node: '>= 4.0.0'} @@ -6360,6 +6376,8 @@ snapshots: dependencies: '@types/node': 17.0.45 + '@types/css-tree@2.3.11': {} + '@types/deep-eql@4.0.2': {} '@types/estree@1.0.8': {} @@ -6839,6 +6857,11 @@ snapshots: mdn-data: 2.0.30 source-map-js: 1.2.1 + css-tree@3.2.1: + dependencies: + mdn-data: 2.27.1 + source-map-js: 1.2.1 + cssstyle@4.6.0: dependencies: '@asamuzakjp/css-color': 3.2.0 @@ -7948,6 +7971,8 @@ snapshots: mdn-data@2.0.30: {} + mdn-data@2.27.1: {} + memfs@3.5.3: dependencies: fs-monkey: 1.1.0 diff --git a/src/lib/Database/SB/User/preferences.ts b/src/lib/Database/SB/User/preferences.ts index d1f03ee8..755f21b2 100644 --- a/src/lib/Database/SB/User/preferences.ts +++ b/src/lib/Database/SB/User/preferences.ts @@ -1,3 +1,4 @@ +import { sanitizeBadgeWallCss } from "$lib/Utility/sanitizeCss"; import sb from "../../sb.server"; export interface UserPreferences { @@ -122,7 +123,7 @@ export const toggleHideAWCBadges = async (userId: number) => { export const setCSS = async (userId: number, css: string) => { return await setUserPreferences(userId, { updated_at: new Date().toISOString(), - badge_wall_css: css, + badge_wall_css: sanitizeBadgeWallCss(css), }); }; diff --git a/src/lib/Utility/sanitizeCss.test.ts b/src/lib/Utility/sanitizeCss.test.ts new file mode 100644 index 00000000..f6c22364 --- /dev/null +++ b/src/lib/Utility/sanitizeCss.test.ts @@ -0,0 +1,76 @@ +import { describe, expect, it } from "vitest"; +import { sanitizeBadgeWallCss } from "./sanitizeCss"; + +describe("sanitizeBadgeWallCss", () => { + // Behaviour gate: the CSS people actually write for their badge wall survives. + it("preserves ordinary rules, declarations and values", () => { + const out = sanitizeBadgeWallCss( + ".badge { color: red; opacity: 0.5; border-radius: 8px; }", + ); + + expect(out).toContain("color"); + expect(out).toContain("red"); + expect(out).toContain("border-radius"); + }); + + it("preserves backdrop-filter, content, url() and at-rules", () => { + expect( + sanitizeBadgeWallCss(".x { backdrop-filter: blur(4px); }"), + ).toContain("backdrop-filter"); + expect(sanitizeBadgeWallCss('.x::before { content: "★"; }')).toContain( + "content", + ); + expect( + sanitizeBadgeWallCss( + ".x { background: url(https://cdn.due.moe/a.png); }", + ), + ).toContain("url(https://cdn.due.moe/a.png)"); + expect( + sanitizeBadgeWallCss("@media (min-width: 1px) { .x { color: blue; } }"), + ).toContain("@media"); + expect( + sanitizeBadgeWallCss( + "@keyframes spin { from { transform: rotate(0); } to { transform: rotate(360deg); } }", + ), + ).toContain("@keyframes"); + }); + + it("returns empty string for nullish input", () => { + expect(sanitizeBadgeWallCss("")).toBe(""); + // @ts-expect-error exercising defensive nullish handling + expect(sanitizeBadgeWallCss(undefined)).toBe(""); + }); + + // The fix: dangerous constructs are removed while surrounding CSS is kept. + it("strips @import, behavior, -moz-binding, expression and js: urls", () => { + const imported = sanitizeBadgeWallCss( + "@import url(https://evil.example.com/x.css); .x { color: red; }", + ); + expect(imported).not.toContain("@import"); + expect(imported).toContain("color"); + + expect( + sanitizeBadgeWallCss(".x { behavior: url(evil.htc); color: red; }"), + ).not.toContain("behavior"); + expect( + sanitizeBadgeWallCss(".x { -moz-binding: url(evil.xml#x); }"), + ).not.toContain("-moz-binding"); + expect( + sanitizeBadgeWallCss(".x { width: expression(alert(1)); }"), + ).not.toContain("expression"); + expect( + sanitizeBadgeWallCss(".x { background: url(javascript:alert(1)); }"), + ).not.toContain("javascript:"); + }); + + it("drops .b { color: blue; }", + ); + + expect(out).not.toContain("` break-out attempts — and we additionally remove the few + * constructs that can load resources or (in legacy engines) run code: + * `@import`, `behavior`/`-moz-binding`, and `expression()`/`javascript:` values. + * + * This is defence in depth: rendering goes through `textContent` (no HTML + * parsing, so no break-out) and the CSP blocks inline script regardless. + */ +export const sanitizeBadgeWallCss = (css: string): string => { + if (!css) return ""; + + let ast: csstree.CssNode; + + try { + ast = csstree.parse(css, { onParseError: () => {} }); + } catch { + return ""; + } + + csstree.walk(ast, (node, item, list) => { + if (!list || !item) return; + + if (node.type === "Atrule" && node.name.toLowerCase() === "import") { + list.remove(item); + } else if ( + node.type === "Rule" && + csstree.generate(node.prelude).includes("<") + ) { + // css-tree keeps an unparseable selector as a Raw prelude, so a + // `