From d01599a2b44decd9d751126d0e6e31b33a8c4727 Mon Sep 17 00:00:00 2001 From: Huang Xin Date: Tue, 28 Oct 2025 11:28:48 +0800 Subject: [PATCH] feat(security): sanitize XHTML safely to prevent XSS when scripts are disabled, closes #2316 (#2342) --- apps/readest-app/package.json | 1 + .../src/app/library/hooks/useBooksSync.ts | 1 - .../app/reader/components/FoliateViewer.tsx | 2 +- .../src/services/transformers/index.ts | 2 + .../src/services/transformers/sanitizer.ts | 35 ++++++++ apps/readest-app/src/utils/diff.ts | 90 +++++++++++++++++++ pnpm-lock.yaml | 10 +++ 7 files changed, 139 insertions(+), 2 deletions(-) create mode 100644 apps/readest-app/src/services/transformers/sanitizer.ts create mode 100644 apps/readest-app/src/utils/diff.ts diff --git a/apps/readest-app/package.json b/apps/readest-app/package.json index 8307c92e..e1625fd8 100644 --- a/apps/readest-app/package.json +++ b/apps/readest-app/package.json @@ -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", diff --git a/apps/readest-app/src/app/library/hooks/useBooksSync.ts b/apps/readest-app/src/app/library/hooks/useBooksSync.ts index 0fe918b5..47318f4b 100644 --- a/apps/readest-app/src/app/library/hooks/useBooksSync.ts +++ b/apps/readest-app/src/app/library/hooks/useBooksSync.ts @@ -58,7 +58,6 @@ export const useBooksSync = () => { useEffect(() => { if (!user) return; if (isPullingRef.current) { - console.log('Pull already in progress, skipping...'); return; } handleAutoSync(); diff --git a/apps/readest-app/src/app/reader/components/FoliateViewer.tsx b/apps/readest-app/src/app/reader/components/FoliateViewer.tsx index fa014ea0..99572027 100644 --- a/apps/readest-app/src/app/reader/components/FoliateViewer.tsx +++ b/apps/readest-app/src/app/reader/components/FoliateViewer.tsx @@ -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)); } diff --git a/apps/readest-app/src/services/transformers/index.ts b/apps/readest-app/src/services/transformers/index.ts index a4a6bf91..c5e4a9c9 100644 --- a/apps/readest-app/src/services/transformers/index.ts +++ b/apps/readest-app/src/services/transformers/index.ts @@ -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 ]; diff --git a/apps/readest-app/src/services/transformers/sanitizer.ts b/apps/readest-app/src/services/transformers/sanitizer.ts new file mode 100644 index 00000000..bef4811a --- /dev/null +++ b/apps/readest-app/src/services/transformers/sanitizer.ts @@ -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 = '' + sanitized; + + // console.log(`Sanitizer diff:\n${diff(result, sanitized)}`); + + return sanitized; + }, +}; diff --git a/apps/readest-app/src/utils/diff.ts b/apps/readest-app/src/utils/diff.ts new file mode 100644 index 00000000..e8dc1bb3 --- /dev/null +++ b/apps/readest-app/src/utils/diff.ts @@ -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; +} diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 964aa391..561c9c80 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -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