Build your own AI office with Univer Office SDK. Bring editing, calculation, collaboration, and file processing into your product for people and AI agents. Built on an extensible open-source core.
TypeScript boardcollaborationdocdocxexceloffce365officepdfpptpptxpresentationsdksheetslidesspreadsheetuniverwordwordprocessorworkspacexlsx
fix(ui): sanitize legacy clipboard html copy and share base html sanitizer (#6739)
白熱4982cfd12f78
diff --git a/packages/sheets-ui/src/services/clipboard/html-to-usm/utils.ts b/packages/sheets-ui/src/services/clipboard/html-to-usm/utils.tsindex b5376fe04f..82009b3d40 100644--- a/packages/sheets-ui/src/services/clipboard/html-to-usm/utils.ts+++ b/packages/sheets-ui/src/services/clipboard/html-to-usm/utils.ts@@ -18,8 +18,7 @@ import type { IParagraph, IParagraphStyle, ITextRun, Nullable } from '@univerjs/import type { ICellDataWithSpanInfo } from '../type';import { DataStreamTreeTokenType, Tools } from '@univerjs/core';import { ptToPixel } from '@univerjs/engine-render';--const STRIPPED_HTML_SELECTOR = 'script, iframe, object, embed';+import { sanitizeParsedHtml } from '@univerjs/ui';function cleanTextNodes(node: Node) {if (node.nodeType === Node.TEXT_NODE) {@@ -38,17 +37,6 @@ function cleanTextNodes(node: Node) {node.childNodes.forEach(cleanTextNodes);}-function sanitizeParsedHtml(root: ParentNode) {- root.querySelectorAll(STRIPPED_HTML_SELECTOR).forEach((element) => element.remove());- root.querySelectorAll<HTMLElement>('*').forEach((element) => {- for (const { name } of Array.from(element.attributes)) {- if (name.startsWith('on')) {- element.removeAttribute(name);- }- }- });-}-export default function parseToDom(rawHtml: string) {const doc = document.implementation.createHTMLDocument('');const range = doc.createRange();@@ -56,7 +44,9 @@ export default function parseToDom(rawHtml: string) {const fragment = range.createContextualFragment(rawHtml);- sanitizeParsedHtml(fragment);+ sanitizeParsedHtml(fragment, {+ strippedSelector: 'script, iframe, object, embed',+ });cleanTextNodes(fragment);doc.body.append(fragment);diff --git a/packages/ui/src/services/clipboard/__tests__/clipboard-interface.service.spec.ts b/packages/ui/src/services/clipboard/__tests__/clipboard-interface.service.spec.tsindex 691bf7993c..3bd9fd0c4c 100644--- a/packages/ui/src/services/clipboard/__tests__/clipboard-interface.service.spec.ts+++ b/packages/ui/src/services/clipboard/__tests__/clipboard-interface.service.spec.ts@@ -98,6 +98,37 @@ describe('BrowserClipboardService', () => {expect(document.execCommand).toHaveBeenCalledWith('copy');});+ it('should sanitize html before legacy copy', async () => {+ vi.mocked(supportClipboardAPI).mockReturnValue(false);+ const { service } = createService();+ let copiedHtml = '';++ vi.mocked(document.execCommand).mockImplementation(() => {+ copiedHtml = document.body.lastElementChild?.innerHTML ?? '';+ return true;+ });++ await service.write(+ 'legacy',+ '<div data-copy-id="copy-id" onclick="alert(1)"><a href="javascript:alert(1)">unsafe</a><img src="data:image/png;base64,ZmFrZQ==" onerror="alert(1)" /><span style="color: red; background-image: url(javascript:alert(1))">safe</span><script>alert(1)</script></div>'+ );++ const copiedDocument = new DOMParser().parseFromString(copiedHtml, 'text/html');+ const wrapper = copiedDocument.body.firstElementChild as HTMLDivElement | null;+ const link = copiedDocument.querySelector('a');+ const image = copiedDocument.querySelector('img');+ const span = copiedDocument.querySelector('span');++ expect(wrapper?.getAttribute('data-copy-id')).toBe('copy-id');+ expect(wrapper?.hasAttribute('onclick')).toBe(false);+ expect(copiedDocument.querySelector('script')).toBeNull();+ expect(link?.hasAttribute('href')).toBe(false);+ expect(image?.getAttribute('src')).toBe('data:image/png;base64,ZmFrZQ==');+ expect(image?.hasAttribute('onerror')).toBe(false);+ expect(span?.getAttribute('style')).toContain('color: red');+ expect(span?.getAttribute('style')).not.toContain('url(');+ });+it('should show notification when write/writeText fails', async () => {const { service, logService, notificationService } = createService();vi.mocked(navigator.clipboard.writeText).mockRejectedValueOnce(new Error('writeText failed'));diff --git a/packages/ui/src/services/clipboard/clipboard-interface.service.ts b/packages/ui/src/services/clipboard/clipboard-interface.service.tsindex 24fc12fe39..920f6f21cc 100644--- a/packages/ui/src/services/clipboard/clipboard-interface.service.ts+++ b/packages/ui/src/services/clipboard/clipboard-interface.service.ts@@ -15,7 +15,7 @@*/import { createIdentifier, Disposable, ILogService, Inject, LocaleService, Optional } from '@univerjs/core';-+import { sanitizeParsedHtml } from '../../utils/html';import { INotificationService } from '../notification/notification.service';import { supportClipboardAPI } from './clipboard-utils';@@ -34,6 +34,105 @@ export const imageMimeTypeSet = new Set([FILE_PNG_CLIPBOARD_MIME_TYPE,]);+const DROP_CONTENT_TAGS = new Set([+ 'base',+ 'button',+ 'embed',+ 'form',+ 'frame',+ 'frameset',+ 'head',+ 'iframe',+ 'input',+ 'link',+ 'meta',+ 'object',+ 'script',+ 'select',+ 'style',+ 'template',+ 'textarea',+]);++const ALLOWED_HTML_TAGS = new Set([+ 'a',+ 'b',+ 'blockquote',+ 'br',+ 'caption',+ 'code',+ 'col',+ 'colgroup',+ 'dd',+ 'div',+ 'dl',+ 'dt',+ 'em',+ 'font',+ 'h1',+ 'h2',+ 'h3',+ 'h4',+ 'h5',+ 'h6',+ 'hr',+ 'i',+ 'img',+ 'li',+ 'ol',+ 'p',+ 'pre',+ 's',+ 'span',+ 'strike',+ 'strong',+ 'sub',+ 'sup',+ 'table',+ 'tbody',+ 'td',+ 'tfoot',+ 'th',+ 'thead',+ 'tr',+ 'u',+ 'ul',+]);++const ALLOWED_HTML_ATTRIBUTES = new Set([+ 'align',+ 'alt',+ 'aria-colindex',+ 'aria-colspan',+ 'aria-label',+ 'aria-labelledby',+ 'aria-rowindex',+ 'aria-rowspan',+ 'bgcolor',+ 'border',+ 'cellpadding',+ 'cellspacing',+ 'class',+ 'colspan',+ 'color',+ 'dir',+ 'face',+ 'headers',+ 'height',+ 'href',+ 'lang',+ 'rel',+ 'role',+ 'rowspan',+ 'size',+ 'src',+ 'style',+ 'target',+ 'title',+ 'valign',+ 'width',+]);+/*** This interface provides an interface to access system's clipboard.*/@@ -150,7 +249,7 @@ export class BrowserClipboardService extends Disposable implements IClipboardIntconst activeElement = document.activeElement;const container = createCopyHtmlContainer();document.body.appendChild(container);- container.innerHTML = html; // TODO: wzhudev: sanitize html+ container.replaceChildren(sanitizeHtmlForClipboard(html));try {select(container);@@ -212,6 +311,159 @@ function createCopyHtmlContainer() {return div;}+function sanitizeHtmlForClipboard(html: string): DocumentFragment {+ const parser = new DOMParser();+ const doc = parser.parseFromString(html, HTML_CLIPBOARD_MIME_TYPE);+ sanitizeParsedHtml(doc, {+ strippedSelector: 'script, iframe, object, embed',+ });+ const fragment = document.createDocumentFragment();++ Array.from(doc.body.childNodes).forEach((node) => {+ const sanitizedNode = sanitizeHtmlNode(node);++ if (sanitizedNode) {+ fragment.appendChild(sanitizedNode);+ }+ });++ return fragment;+}++function sanitizeHtmlNode(node: Node): Node | null {+ if (node.nodeType === Node.TEXT_NODE) {+ return document.createTextNode(node.textContent ?? '');+ }++ if (node.nodeType !== Node.ELEMENT_NODE) {+ return null;+ }++ const sourceElement = node as HTMLElement;+ const tagName = sourceElement.tagName.toLowerCase();++ if (DROP_CONTENT_TAGS.has(tagName)) {+ return null;+ }++ if (!ALLOWED_HTML_TAGS.has(tagName)) {+ const fragment = document.createDocumentFragment();++ Array.from(sourceElement.childNodes).forEach((childNode) => {+ const sanitizedChildNode = sanitizeHtmlNode(childNode);++ if (sanitizedChildNode) {+ fragment.appendChild(sanitizedChildNode);+ }+ });++ return fragment;+ }++ const sanitizedElement = document.createElement(tagName);+ copySanitizedAttributes(sourceElement, sanitizedElement);++ Array.from(sourceElement.childNodes).forEach((childNode) => {+ const sanitizedChildNode = sanitizeHtmlNode(childNode);++ if (sanitizedChildNode) {+ sanitizedElement.appendChild(sanitizedChildNode);+ }+ });++ return sanitizedElement;+}++function copySanitizedAttributes(sourceElement: HTMLElement, targetElement: HTMLElement) {+ Array.from(sourceElement.attributes).forEach((attribute) => {+ const attributeName = attribute.name.toLowerCase();++ if (attributeName.startsWith('on')) {+ return;+ }++ if (attributeName.startsWith('data-') || attributeName.startsWith('aria-')) {+ targetElement.setAttribute(attribute.name, attribute.value);+ return;+ }++ if (!ALLOWED_HTML_ATTRIBUTES.has(attributeName)) {+ return;+ }++ if (attributeName === 'href' || attributeName === 'src') {+ const sanitizedUrl = sanitizeHtmlUrl(attribute.value, attributeName === 'src');++ if (sanitizedUrl) {+ targetElement.setAttribute(attribute.name, sanitizedUrl);+ }++ return;+ }++ if (attributeName === 'style') {+ const sanitizedStyle = sanitizeInlineStyle(attribute.value);++ if (sanitizedStyle) {+ targetElement.setAttribute(attribute.name, sanitizedStyle);+ }++ return;+ }++ targetElement.setAttribute(attribute.name, attribute.value);+ });+}++function sanitizeHtmlUrl(value: string, allowDataImage: boolean): string | null {+ const trimmedValue = value.trim();++ if (!trimmedValue) {+ return null;+ }++ if (trimmedValue.startsWith('#')) {+ return trimmedValue;+ }++ if (/^(?:https?:|mailto:|tel:)/i.test(trimmedValue)) {+ return trimmedValue;+ }++ if (allowDataImage && /^data:image\/[a-z0-9.+-]+;base64,/i.test(trimmedValue)) {+ return trimmedValue;+ }++ if (/^(?:\/|\.\/|\.\.\/)/.test(trimmedValue)) {+ return trimmedValue;+ }++ return null;+}++function sanitizeInlineStyle(styleText: string): string {+ const probe = document.createElement('div');+ probe.style.cssText = styleText;++ const sanitizedDeclarations: string[] = [];++ Array.from(probe.style).forEach((propertyName) => {+ const propertyValue = probe.style.getPropertyValue(propertyName).trim();++ if (!propertyValue || isUnsafeStyleValue(propertyValue)) {+ return;+ }++ sanitizedDeclarations.push(`${propertyName}: ${propertyValue}`);+ });++ return sanitizedDeclarations.join('; ');+}++function isUnsafeStyleValue(styleValue: string): boolean {+ return /(expression\s*\(|url\s*\(|javascript:|vbscript:|mocha:|-moz-binding|behavior\s*:|@import)/i.test(styleValue);+}+function select(element: HTMLTextAreaElement | HTMLDivElement): string {if (element instanceof HTMLTextAreaElement) {const isReadOnly = element.hasAttribute('readonly');diff --git a/packages/ui/src/utils/cell.ts b/packages/ui/src/utils/cell.tsindex 5edb9caf54..36f065c9d4 100644--- a/packages/ui/src/utils/cell.ts+++ b/packages/ui/src/utils/cell.ts@@ -27,37 +27,13 @@ import type {import { BaselineOffset, BorderStyleTypes, ColorKit, generateRandomId, getBorderStyleType, Tools } from '@univerjs/core';import { ptToPx } from '@univerjs/engine-render';+import { parseHtmlDocument, parseHtmlFragment } from './html';import { textTrim } from './util';const PX_TO_PT_RATIO = 0.75;const MAX_FONT_SIZE = 78;const MIN_FONT_SIZE = 9;-const STRIPPED_HTML_SELECTOR = 'script, iframe, object, embed';--function sanitizeParsedHtml(root: ParentNode) {- root.querySelectorAll(STRIPPED_HTML_SELECTOR).forEach((element) => element.remove());- root.querySelectorAll<HTMLElement>('*').forEach((element) => {- for (const { name } of Array.from(element.attributes)) {- if (name.startsWith('on')) {- element.removeAttribute(name);- }- }- });-}--function parseHtmlFragment(html: string) {- const parser = new DOMParser();- const doc = parser.parseFromString(html, 'text/html');- sanitizeParsedHtml(doc);- return doc.body;-}--function parseHtmlDocument(html: string) {- const parser = new DOMParser();- const doc = parser.parseFromString(html, 'text/html');- sanitizeParsedHtml(doc);- return doc;-}+const HTML_SANITIZE_OPTIONS = { strippedSelector: 'script, iframe, object, embed' };// TODO: move to Utils/**@@ -632,7 +608,7 @@ export function splitSpanText(text: string) {}export function handleTableColgroup(table: string) {- const content = parseHtmlFragment(table);+ const content = parseHtmlFragment(table, HTML_SANITIZE_OPTIONS);const data: any[] = [];const colgroup = content.querySelectorAll('table col');if (!colgroup.length) return [];@@ -666,7 +642,7 @@ function getTdHeight(height: string | null, defaultHeight: number) {}export function handleTableRowGroup(table: string) {- const content = parseHtmlFragment(table);+ const content = parseHtmlFragment(table, HTML_SANITIZE_OPTIONS);const data: any[] = [];const rowGroup = content.querySelectorAll('table tr');if (!rowGroup.length) return [];@@ -696,7 +672,7 @@ export function handleTableRowGroup(table: string) {// Convert table data into sheet dataexport function handelTableToJson(table: string) {let data: any[] = [];- const content = parseHtmlFragment(table);+ const content = parseHtmlFragment(table, HTML_SANITIZE_OPTIONS);data = new Array(content.querySelectorAll('table tr').length);if (!data.length) return [];let colLen = 0;@@ -840,7 +816,7 @@ export function handleTableMergeData(data: any[], selection?: IRange) {export function handelExcelToJson(html: string) {let data: any[] = [];- const content = parseHtmlDocument(html);+ const content = parseHtmlDocument(html, HTML_SANITIZE_OPTIONS);const styleText = content.querySelector('style')?.innerText;if (!styleText) return;const excelStyle = getStyles(styleText);diff --git a/packages/ui/src/utils/html.ts b/packages/ui/src/utils/html.tsnew file mode 100644index 0000000000..593a7b9554--- /dev/null+++ b/packages/ui/src/utils/html.ts@@ -0,0 +1,45 @@+/**+ * Copyright 2023-present DreamNum Co., Ltd.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++export interface ISanitizeParsedHtmlOptions {+ strippedSelector: string;+}++export function sanitizeParsedHtml(root: ParentNode, options: ISanitizeParsedHtmlOptions) {+ root.querySelectorAll(options.strippedSelector).forEach((element) => element.remove());++ root.querySelectorAll<HTMLElement>('*').forEach((element) => {+ for (const { name } of Array.from(element.attributes)) {+ if (name.startsWith('on')) {+ element.removeAttribute(name);+ }+ }+ });+}++export function parseHtmlFragment(html: string, options: ISanitizeParsedHtmlOptions) {+ const parser = new DOMParser();+ const doc = parser.parseFromString(html, 'text/html');+ sanitizeParsedHtml(doc, options);+ return doc.body;+}++export function parseHtmlDocument(html: string, options: ISanitizeParsedHtmlOptions) {+ const parser = new DOMParser();+ const doc = parser.parseFromString(html, 'text/html');+ sanitizeParsedHtml(doc, options);+ return doc;+}diff --git a/packages/ui/src/utils/index.ts b/packages/ui/src/utils/index.tsindex 3f64859294..b9d6ed71e6 100644--- a/packages/ui/src/utils/index.ts+++ b/packages/ui/src/utils/index.ts@@ -16,4 +16,5 @@export * from './cell';export * from './di';+export * from './html';export * from './util';