feat(security): sanitize XHTML safely to prevent XSS when scripts are disabled, closes #2316 (#2342)

This commit is contained in:
Huang Xin
2025-10-28 11:28:48 +08:00
committed by GitHub
parent e80a2268ac
commit d01599a2b4
7 changed files with 139 additions and 2 deletions
+1
View File
@@ -72,6 +72,7 @@
"clsx": "^2.1.1",
"cors": "^2.8.5",
"dayjs": "^1.11.13",
"dompurify": "^3.3.0",
"foliate-js": "workspace:*",
"franc-min": "^6.2.0",
"google-auth-library": "^10.4.1",
@@ -58,7 +58,6 @@ export const useBooksSync = () => {
useEffect(() => {
if (!user) return;
if (isPullingRef.current) {
console.log('Pull already in progress, skipping...');
return;
}
handleAutoSync();
@@ -132,7 +132,7 @@ const FoliateViewer: React.FC<{
viewSettings,
primaryLanguage: bookData.book?.primaryLanguage,
content: data,
transformers: ['punctuation', 'footnote', 'whitespace', 'language'],
transformers: ['punctuation', 'footnote', 'whitespace', 'language', 'sanitizer'],
} as TransformContext;
return Promise.resolve(transformContent(ctx));
}
@@ -3,11 +3,13 @@ import { footnoteTransformer } from './footnote';
import { languageTransformer } from './language';
import { punctuationTransformer } from './punctuation';
import { whitespaceTransformer } from './whitespace';
import { sanitizerTransformer } from './sanitizer';
export const availableTransformers: Transformer[] = [
punctuationTransformer,
footnoteTransformer,
languageTransformer,
whitespaceTransformer,
sanitizerTransformer,
// Add more transformers here
];
@@ -0,0 +1,35 @@
import DOMPurify from 'dompurify';
import type { Transformer } from './types';
export const sanitizerTransformer: Transformer = {
name: 'sanitizer',
transform: async (ctx) => {
const allowScript = ctx.viewSettings.allowScript;
if (allowScript) return ctx.content;
let result = ctx.content;
let sanitized = DOMPurify.sanitize(result, {
WHOLE_DOCUMENT: true,
FORBID_TAGS: ['script'],
ALLOWED_URI_REGEXP:
/^(?:(?:(?:f|ht)tps?|mailto|tel|callto|sms|cid|xmpp|blob|data):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i,
ADD_TAGS: ['link', 'meta'],
ADD_ATTR: (attributeName: string) => {
return (
['xmlns'].includes(attributeName) ||
attributeName.startsWith('xml:') ||
attributeName.startsWith('xmlns:') ||
attributeName.startsWith('epub:')
);
},
});
sanitized = '<?xml version="1.0" encoding="utf-8"?><!DOCTYPE html>' + sanitized;
// console.log(`Sanitizer diff:\n${diff(result, sanitized)}`);
return sanitized;
},
};
+90
View File
@@ -0,0 +1,90 @@
/**
* Diff function similar to Linux `diff`
* Usage: diff(str1, str2)
*/
export function diff(str1: string, str2: string) {
const lines1 = str1.split('\n');
const lines2 = str2.split('\n');
const lcs = longestCommonSubsequence(lines1, lines2);
let i = 0,
j = 0,
k = 0;
const result: string[] = [];
const addRange = (start: number, end: number) => (start === end ? `${start}` : `${start},${end}`);
while (i < lines1.length || j < lines2.length) {
if (k < lcs.length && i < lines1.length && lines1[i] === lcs[k]) {
// common line
i++;
j++;
k++;
} else {
let delStart = i,
addStart = j;
while (i < lines1.length && (k >= lcs.length || lines1[i] !== lcs[k])) i++;
while (j < lines2.length && (k >= lcs.length || lines2[j] !== lcs[k])) j++;
const delRange = addRange(delStart + 1, i);
const addRangeStr = addRange(addStart + 1, j);
if (delStart < i && addStart < j) {
// change
result.push(`${delRange}c${addRangeStr}`);
for (let m = delStart; m < i; m++) result.push(`< ${lines1[m]}`);
result.push('---');
for (let m = addStart; m < j; m++) result.push(`> ${lines2[m]}`);
} else if (delStart < i) {
// deletion
result.push(`${delRange}d${addStart}`);
for (let m = delStart; m < i; m++) result.push(`< ${lines1[m]}`);
} else if (addStart < j) {
// addition
result.push(`${delStart}a${addRangeStr}`);
for (let m = addStart; m < j; m++) result.push(`> ${lines2[m]}`);
}
}
}
return result.join('\n');
}
function longestCommonSubsequence(arr1: string[], arr2: string[]) {
const m = arr1.length;
const n = arr2.length;
const dp = Array(m + 1)
.fill(null)
.map(() => Array(n + 1).fill(0));
for (let i = 1; i <= m; i++) {
for (let j = 1; j <= n; j++) {
if (arr1[i - 1] === arr2[j - 1]) {
dp[i]![j] = dp[i - 1]![j - 1] + 1;
} else {
dp[i]![j] = Math.max(dp[i - 1]![j], dp[i]![j - 1]);
}
}
}
const lcs: string[] = [];
let i = m,
j = n;
while (i > 0 && j > 0) {
if (arr1[i - 1] === arr2[j - 1]) {
lcs.unshift(arr1[i - 1]!);
i--;
j--;
} else if (dp[i - 1]![j] > dp[i]![j - 1]) {
i--;
} else {
j--;
}
}
return lcs;
}
+10
View File
@@ -125,6 +125,9 @@ importers:
dayjs:
specifier: ^1.11.13
version: 1.11.13
dompurify:
specifier: ^3.3.0
version: 3.3.0
foliate-js:
specifier: workspace:*
version: link:../../packages/foliate-js
@@ -4047,6 +4050,9 @@ packages:
dom-accessibility-api@0.5.16:
resolution: {integrity: sha512-X7BJ2yElsnOJ30pZF4uIIDfBEVgF4XEBxL9Bxhy6dnrm5hkzqmsWHGTiHqRiITNhMyFLyAiWndIJP7Z1NTteDg==}
dompurify@3.3.0:
resolution: {integrity: sha512-r+f6MYR1gGN1eJv0TVQbhA7if/U7P87cdPl3HN5rikqaBSBxLiCb/b9O+2eG0cxz0ghyU+mU1QkbsOwERMYlWQ==}
dotenv-cli@7.4.4:
resolution: {integrity: sha512-XkBYCG0tPIes+YZr4SpfFv76SQrV/LeCE8CI7JSEMi3VR9MvTihCGTOtbIexD6i2mXF+6px7trb1imVCXSNMDw==}
hasBin: true
@@ -12151,6 +12157,10 @@ snapshots:
dom-accessibility-api@0.5.16: {}
dompurify@3.3.0:
optionalDependencies:
'@types/trusted-types': 2.0.7
dotenv-cli@7.4.4:
dependencies:
cross-spawn: 7.0.6