🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
🐛 fix(file-viewer): skip embedded HTML chunks in docx preview (#22563)
Lobehub Coder7ec149b966d8
diff --git a/apps/desktop/src/main/const/protocol.ts b/apps/desktop/src/main/const/protocol.tsindex 683bb6662a5..fceff66fc0e 100644--- a/apps/desktop/src/main/const/protocol.ts+++ b/apps/desktop/src/main/const/protocol.ts@@ -1,6 +1,10 @@export const LOCAL_FILE_PROTOCOL_SCHEME = 'localfile';export const LOCAL_FILE_PROTOCOL_HOST = 'file';+/** Where the renderer is served from (`app://renderer`), in dev and prod alike. */+export const RENDERER_PROTOCOL_SCHEME = 'app';+export const RENDERER_PROTOCOL_HOST = 'renderer';+/*** Renderer pathnames that must be proxied to the remote LobeHub backend* instead of being served as static assets. Covers tRPC, webapi, NextAuth,diff --git a/apps/desktop/src/main/controllers/__tests__/BrowserSidebarCtr.test.ts b/apps/desktop/src/main/controllers/__tests__/BrowserSidebarCtr.test.tsindex b6d02cd99d1..5990155594b 100644--- a/apps/desktop/src/main/controllers/__tests__/BrowserSidebarCtr.test.ts+++ b/apps/desktop/src/main/controllers/__tests__/BrowserSidebarCtr.test.ts@@ -71,7 +71,11 @@ describe('BrowserSidebarCtr retained webview registration', () => {const invokeIpc = async <T>(channel: string, payload: unknown): Promise<T> => {const handler = ipcHandlers.get(channel);if (!handler) throw new Error(`IPC handler for ${channel} not found`);- return handler({ sender: {} }, payload) as Promise<T>;+ return handler(+ // IpcHandler only serves the renderer's top-level frame.+ { sender: {}, senderFrame: { parent: null, url: 'app://renderer/' } },+ payload,+ ) as Promise<T>;};beforeEach(() => {diff --git a/apps/desktop/src/main/controllers/__tests__/OpenInAppCtr.test.ts b/apps/desktop/src/main/controllers/__tests__/OpenInAppCtr.test.tsindex 050b34de32a..9edeb83ee94 100644--- a/apps/desktop/src/main/controllers/__tests__/OpenInAppCtr.test.ts+++ b/apps/desktop/src/main/controllers/__tests__/OpenInAppCtr.test.ts@@ -32,6 +32,8 @@ const invokeIpc = async <T = any>(const fakeEvent = {sender: context?.sender ?? ({ id: 'test' } as any),+ // IpcHandler only serves the renderer's top-level frame.+ senderFrame: { parent: null, url: 'app://renderer/' },};if (payload === undefined) {diff --git a/apps/desktop/src/main/controllers/__tests__/SystemCtr.test.ts b/apps/desktop/src/main/controllers/__tests__/SystemCtr.test.tsindex 7e38a9b8e2e..edbdb30c0bc 100644--- a/apps/desktop/src/main/controllers/__tests__/SystemCtr.test.ts+++ b/apps/desktop/src/main/controllers/__tests__/SystemCtr.test.ts@@ -41,6 +41,8 @@ const invokeIpc = async <T = any>(const fakeEvent = {sender: context?.sender ?? ({ id: 'test' } as any),+ // IpcHandler only serves the renderer's top-level frame.+ senderFrame: { parent: null, url: 'app://renderer/' },};if (payload === undefined) {diff --git a/apps/desktop/src/main/core/infrastructure/RendererProtocolManager.ts b/apps/desktop/src/main/core/infrastructure/RendererProtocolManager.tsindex 8cdefc38b91..19601a51b80 100644--- a/apps/desktop/src/main/core/infrastructure/RendererProtocolManager.ts+++ b/apps/desktop/src/main/core/infrastructure/RendererProtocolManager.ts@@ -4,6 +4,7 @@ import path from 'node:path';import { tryGetMimeType } from '@lobechat/utils/mimeType';import { app, protocol } from 'electron';+import { RENDERER_PROTOCOL_HOST, RENDERER_PROTOCOL_SCHEME } from '@/const/protocol';import { createLogger } from '@/utils/logger';export type RendererFile = { filePath: string; name: string };@@ -41,8 +42,6 @@ interface RendererProtocolManagerOptions {scheme?: string;}-const RENDERER_DIR = 'renderer';-export class RendererProtocolManager {private readonly scheme: string;private readonly host: string;@@ -51,8 +50,8 @@ export class RendererProtocolManager {private handlerRegistered = false;constructor(options: RendererProtocolManagerOptions) {- this.scheme = options.scheme ?? 'app';- this.host = options.host ?? RENDERER_DIR;+ this.scheme = options.scheme ?? RENDERER_PROTOCOL_SCHEME;+ this.host = options.host ?? RENDERER_PROTOCOL_HOST;this.fallback = options.fallback;}diff --git a/apps/desktop/src/main/utils/ipc/__tests__/base.test.ts b/apps/desktop/src/main/utils/ipc/__tests__/base.test.tsindex 4c90698b790..23ddc46555e 100644--- a/apps/desktop/src/main/utils/ipc/__tests__/base.test.ts+++ b/apps/desktop/src/main/utils/ipc/__tests__/base.test.ts@@ -1,7 +1,9 @@import { beforeEach, describe, expect, it, vi } from 'vitest';+import { isIpcErrorEnvelope } from '~common/ipcError';+import type { IpcContext } from '../base';-import { getIpcContext,IpcMethod, IpcService } from '../base';+import { getIpcContext, IpcMethod, IpcService } from '../base';const { ipcMainHandleMock } = vi.hoisted(() => ({ipcMainHandleMock: vi.fn(),@@ -13,6 +15,9 @@ vi.mock('electron', () => ({},}));+const rendererFrame = (url = 'app://renderer/chat', parent: unknown = null) =>+ ({ parent, url }) as any;+describe('ipc service base', () => {beforeEach(() => {ipcMainHandleMock.mockClear();@@ -37,7 +42,7 @@ describe('ipc service base', () => {const handler = ipcMainHandleMock.mock.calls[0][1];const fakeSender = { id: 1 } as any;- const fakeEvent = { sender: fakeSender } as any;+ const fakeEvent = { sender: fakeSender, senderFrame: rendererFrame() } as any;const result = await handler(fakeEvent, 'hello');@@ -67,4 +72,47 @@ describe('ipc service base', () => {expect(service.invokedWith).toBe('test');expect(ipcMainHandleMock).toHaveBeenCalledWith('direct.run', expect.any(Function));});+ describe('sender validation', () => {+ class GuardedService extends IpcService {+ static readonly groupName = 'guarded';+ public calls = 0;++ @IpcMethod()+ run() {+ this.calls += 1;+ return 'ran';+ }+ }++ // The handler registry is a process-wide singleton, so the channel is+ // registered once and the captured handler is reused across cases.+ const service = new GuardedService();+ const handler = ipcMainHandleMock.mock.calls.find(([channel]) => channel === 'guarded.run')![1];++ const invoke = (senderFrame: unknown) => {+ service.calls = 0;+ return { result: handler({ sender: { id: 1 }, senderFrame } as any), service };+ };++ it('runs the handler for the renderer top-level frame', async () => {+ const { result, service } = invoke(rendererFrame());++ await expect(result).resolves.toBe('ran');+ expect(service.calls).toBe(1);+ });++ it.each([+ ['a subframe of the renderer', rendererFrame('app://renderer/', rendererFrame())],+ ['a foreign origin', rendererFrame('https://evil.example/')],+ ['a local file page', rendererFrame('file:///tmp/index.html')],+ ['another app:// host', rendererFrame('app://other/')],+ ['an unparsable url', rendererFrame('')],+ ['a destroyed frame', null],+ ])('rejects %s without running the handler', async (_label, frame) => {+ const { result, service } = invoke(frame);++ expect(isIpcErrorEnvelope(await result)).toBe(true);+ expect(service.calls).toBe(0);+ });+ });});diff --git a/apps/desktop/src/main/utils/ipc/base.ts b/apps/desktop/src/main/utils/ipc/base.tsindex 954bd65b7b1..3929b66bf8b 100644--- a/apps/desktop/src/main/utils/ipc/base.ts+++ b/apps/desktop/src/main/utils/ipc/base.ts@@ -5,6 +5,8 @@ import { ipcMain } from 'electron';import { toIpcErrorEnvelope } from '~common/ipcError';+import { isTrustedIpcSender } from './sender';+// Base context for IPC methodsexport interface IpcContext {event: IpcMainInvokeEvent;@@ -59,6 +61,13 @@ export class IpcHandler {sender: event.sender,};+ if (!isTrustedIpcSender(event)) {+ console.warn(+ `Rejected IPC method ${channel} from untrusted frame: ${event.senderFrame?.url ?? '<gone>'}`,+ );+ return toIpcErrorEnvelope(new Error(`IPC method ${channel} rejected: untrusted sender`));+ }+return ipcContextStorage.run(context, async () => {try {const typedArgs = args as TArgs;diff --git a/apps/desktop/src/main/utils/ipc/sender.ts b/apps/desktop/src/main/utils/ipc/sender.tsnew file mode 100644index 00000000000..74000166e1e--- /dev/null+++ b/apps/desktop/src/main/utils/ipc/sender.ts@@ -0,0 +1,25 @@+import type { IpcMainInvokeEvent } from 'electron';++import { RENDERER_PROTOCOL_HOST, RENDERER_PROTOCOL_SCHEME } from '@/const/protocol';++/**+ * Whether an `invoke` came from a document the desktop APIs are meant for: the+ * top-level frame of a window showing the app's own renderer.+ *+ * The preload only runs in main frames, so a subframe or a page the window was+ * navigated to has no business reaching a controller. Checked in `IpcHandler`,+ * so every `@IpcMethod` handler inherits it.+ */+export const isTrustedIpcSender = (event: IpcMainInvokeEvent): boolean => {+ const frame = event.senderFrame;+ // Null once the frame navigated away or was destroyed mid-call.+ if (!frame || frame.parent) return false;++ try {+ const url = new URL(frame.url);+ // `URL.origin` is "null" for custom schemes in Node, so compare the parts.+ return url.protocol === `${RENDERER_PROTOCOL_SCHEME}:` && url.host === RENDERER_PROTOCOL_HOST;+ } catch {+ return false;+ }+};diff --git a/src/features/FileViewer/Renderer/Document/DocxPane.tsx b/src/features/FileViewer/Renderer/Document/DocxPane.tsxindex a9eda198a10..74bce948e1e 100644--- a/src/features/FileViewer/Renderer/Document/DocxPane.tsx+++ b/src/features/FileViewer/Renderer/Document/DocxPane.tsx@@ -5,6 +5,7 @@ import { memo, useCallback, useEffect, useRef, useState } from 'react';import Loading from '@/components/Loading/CircleLoading';+import { DOCX_RENDER_OPTIONS, sanitizeRenderedDocx } from './docxSafety';import { collectDocxSections, type DocxSection } from './docxSections';import PaneFooter from './PaneFooter';@@ -63,8 +64,10 @@ const DocxPane = memo<DocxPaneProps>(({ blob, onError }) => {try {const { renderAsync } = await import('docx-preview');if (disposed) return;- await renderAsync(blob, container);+ // The file is untrusted: see DOCX_RENDER_OPTIONS for why altChunks are off.+ await renderAsync(blob, container, undefined, DOCX_RENDER_OPTIONS);if (disposed) return;+ sanitizeRenderedDocx(container);setSections(collectDocxSections(container));setActiveSection(0);setLoading(false);diff --git a/src/features/FileViewer/Renderer/Document/docxSafety.test.ts b/src/features/FileViewer/Renderer/Document/docxSafety.test.tsnew file mode 100644index 00000000000..2a3a569eed4--- /dev/null+++ b/src/features/FileViewer/Renderer/Document/docxSafety.test.ts@@ -0,0 +1,106 @@+// @vitest-environment happy-dom+import { renderAsync } from 'docx-preview';+import { strToU8, zipSync } from 'fflate';+import { describe, expect, it } from 'vitest';++import { DOCX_RENDER_OPTIONS, sanitizeRenderedDocx } from './docxSafety';++const W = 'http://schemas.openxmlformats.org/wordprocessingml/2006/main';+const R = 'http://schemas.openxmlformats.org/officeDocument/2006/relationships';+const PKG = 'http://schemas.openxmlformats.org/package/2006/relationships';++const CHUNK_HTML =+ '<html><body><p>chunk</p><script>document.body.dataset.chunk = "1";</script></body></html>';++/**+ * A minimal .docx whose body holds an HTML altChunk carrying a script, a+ * `javascript:` hyperlink, an https hyperlink and a bookmark link.+ *+ * Word writes these attributes prefixed (`r:id`, `w:anchor`). happy-dom's XML+ * parser does not report the bare name as a prefixed attribute's localName,+ * while docx-preview matches attributes by localName only — so the fixture+ * uses bare names, which docx-preview reads the way a browser reads the+ * prefixed form.+ */+const buildDocx = (): Blob => {+ const files = {+ '[Content_Types].xml': `<?xml version="1.0" encoding="UTF-8"?>+<Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types">+ <Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/>+ <Default Extension="xml" ContentType="application/xml"/>+ <Default Extension="htm" ContentType="text/html"/>+ <Override PartName="/word/document.xml" ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml"/>+</Types>`,+ '_rels/.rels': `<?xml version="1.0" encoding="UTF-8"?>+<Relationships xmlns="${PKG}">+ <Relationship Id="rId1" Type="${R}/officeDocument" Target="word/document.xml"/>+</Relationships>`,+ 'word/_rels/document.xml.rels': `<?xml version="1.0" encoding="UTF-8"?>+<Relationships xmlns="${PKG}">+ <Relationship Id="rIdChunk" Type="${R}/aFChunk" Target="chunk.htm"/>+ <Relationship Id="rIdJs" Type="${R}/hyperlink" Target="javascript:alert(1)" TargetMode="External"/>+ <Relationship Id="rIdWeb" Type="${R}/hyperlink" Target="https://lobehub.com/" TargetMode="External"/>+</Relationships>`,+ 'word/chunk.htm': CHUNK_HTML,+ 'word/document.xml': `<?xml version="1.0" encoding="UTF-8"?>+<w:document xmlns:w="${W}" xmlns:r="${R}">+ <w:body>+ <w:p><w:r><w:t>Body text</w:t></w:r></w:p>+ <w:altChunk id="rIdChunk"/>+ <w:p><w:hyperlink id="rIdJs"><w:r><w:t>Script link</w:t></w:r></w:hyperlink></w:p>+ <w:p><w:hyperlink id="rIdWeb"><w:r><w:t>Web link</w:t></w:r></w:hyperlink></w:p>+ <w:p><w:hyperlink anchor="_Toc1"><w:r><w:t>Bookmark link</w:t></w:r></w:hyperlink></w:p>+ </w:body>+</w:document>`,+ };++ const zipped = zipSync(+ Object.fromEntries(Object.entries(files).map(([k, v]) => [k, strToU8(v)])),+ );+ return new Blob([zipped]);+};++const linkByText = (root: HTMLElement, text: string) =>+ [...root.querySelectorAll('a')].find((anchor) => anchor.textContent === text);++describe('docx preview safety', () => {+ it('default options embed the sample altChunk as an iframe', async () => {+ // Guards the fixture: if this stops producing the iframe, the test below+ // would pass without proving anything.+ const container = document.createElement('div');+ await renderAsync(buildDocx(), container);++ const iframe = container.querySelector('iframe');+ expect(iframe).not.toBeNull();+ expect(iframe!.srcdoc).toContain('<script>');+ });++ it('renders the document without altChunk iframes or script-scheme links', async () => {+ const container = document.createElement('div');+ await renderAsync(buildDocx(), container, undefined, DOCX_RENDER_OPTIONS);+ sanitizeRenderedDocx(container);++ expect(container.querySelector('iframe')).toBeNull();+ expect(container.textContent).toContain('Body text');+ expect(container.textContent).not.toContain('chunk');++ const scriptLink = linkByText(container, 'Script link');+ expect(scriptLink).toBeDefined();+ expect(scriptLink!.hasAttribute('href')).toBe(false);+ expect(linkByText(container, 'Web link')!.getAttribute('href')).toBe('https://lobehub.com/');+ expect(linkByText(container, 'Bookmark link')!.getAttribute('href')).toBe('#_Toc1');+ });++ it('removes active embeds regardless of how they were produced', () => {+ const root = document.createElement('div');+ root.innerHTML =+ '<p>text</p><iframe srcdoc="x"></iframe><object></object><embed><a href="vbscript:x">v</a><a href="data:text/html,x">d</a><a href="mailto:[email protected]">m</a>';++ sanitizeRenderedDocx(root);++ expect(root.querySelector('iframe, object, embed')).toBeNull();+ expect(linkByText(root, 'v')!.hasAttribute('href')).toBe(false);+ expect(linkByText(root, 'd')!.hasAttribute('href')).toBe(false);+ expect(linkByText(root, 'm')!.getAttribute('href')).toBe('mailto:[email protected]');+ });+});diff --git a/src/features/FileViewer/Renderer/Document/docxSafety.ts b/src/features/FileViewer/Renderer/Document/docxSafety.tsnew file mode 100644index 00000000000..3cbcac61a56--- /dev/null+++ b/src/features/FileViewer/Renderer/Document/docxSafety.ts@@ -0,0 +1,45 @@+import type { Options } from 'docx-preview';++/**+ * docx-preview options for rendering an uploaded file.+ *+ * `renderAltChunks` defaults to `true`, which embeds each `w:altChunk` (an+ * imported HTML/RTF part) as an iframe holding the part's raw markup. That+ * markup comes from the file, unfiltered, so altChunks are not rendered.+ */+export const DOCX_RENDER_OPTIONS: Partial<Options> = {+ renderAltChunks: false,+};++const SAFE_LINK_PROTOCOLS = new Set(['http:', 'https:', 'mailto:', 'tel:']);++// Nothing docx-preview should emit outside altChunks; removed in case a future+// version or another path starts producing them.+const ACTIVE_CONTENT_SELECTOR = 'iframe, frame, object, embed, script';++const isSafeHref = (href: string): boolean => {+ const value = href.trim();+ // In-document bookmark links (`#_Toc…`) stay clickable.+ if (value.startsWith('#')) return value.length > 1;++ try {+ return SAFE_LINK_PROTOCOLS.has(new URL(value).protocol);+ } catch {+ // Relative targets would navigate the app itself; there is nothing to+ // resolve them against in a standalone document.+ return false;+ }+};++/**+ * Strip what docx-preview copies verbatim from the file and the browser would+ * execute: active embeds, and hyperlink targets such as `javascript:` that run+ * on click. Hyperlinks keep their text; only the unsafe target is removed.+ */+export const sanitizeRenderedDocx = (root: HTMLElement): void => {+ for (const element of root.querySelectorAll(ACTIVE_CONTENT_SELECTOR)) element.remove();++ for (const anchor of root.querySelectorAll<HTMLAnchorElement>('a[href]')) {+ if (!isSafeHref(anchor.getAttribute('href') ?? '')) anchor.removeAttribute('href');+ }+};