Skip to content

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.

fix(ui): fix memory leaks in before-close and ribbon services (#6991)

白熱d56b1f900747
diff --git a/packages/core/src/common/__tests__/url.spec.ts b/packages/core/src/common/__tests__/url.spec.ts
index 0fee2a53f5..3cbdb54489 100644
--- a/packages/core/src/common/__tests__/url.spec.ts
+++ b/packages/core/src/common/__tests__/url.spec.ts
@@ -15,7 +15,7 @@
*/
import { describe, expect, it } from 'vitest';
-import { isLegalUrl, normalizeUrl, resolveWithBasePath } from '../url';
+import { isLegalUrl, isSafeUrl, normalizeUrl, resolveWithBasePath } from '../url';
describe('Test url utils', () => {
it('should return true on legal url', () => {
@@ -37,6 +37,16 @@ describe('Test url utils', () => {
expect(normalizeUrl('[email protected]')).toEqual('mailto://[email protected]');
});
+ it('should allow safe url schemes and reject dangerous ones', () => {
+ expect(isSafeUrl('https://univer.ai')).toBe(true);
+ expect(isSafeUrl('http://localhost:3000')).toBe(true);
+ expect(isSafeUrl('mailto:[email protected]')).toBe(true);
+ expect(isSafeUrl('javascript:alert(1)')).toBe(false);
+ expect(isSafeUrl('data:text/html,<script>alert(1)</script>')).toBe(false);
+ expect(isSafeUrl('vbscript:msgbox(1)')).toBe(false);
+ expect(isSafeUrl('')).toBe(false);
+ });
+
it('should resolve url with base path', () => {
expect(resolveWithBasePath('/universer-api/strean/file/dowload?file_id-2008162633680711718', 'http://univer.examples.com.cn:9080/univer/')).toEqual(
'http://univer.examples.com.cn:9080/univer/universer-api/strean/file/dowload?file_id-2008162633680711718'
diff --git a/packages/core/src/common/url.ts b/packages/core/src/common/url.ts
index 838d8b887d..f00c7c517d 100644
--- a/packages/core/src/common/url.ts
+++ b/packages/core/src/common/url.ts
@@ -374,6 +374,19 @@ export function normalizeUrl(urlStr: string) {
* @param {string} baseURL - The base URL to use for resolution.
* @returns {string} - The resolved URL.
*/
+export function isSafeUrl(url: string): boolean {
+ if (!url || typeof url !== 'string') {
+ return false;
+ }
+ try {
+ const base = typeof window !== 'undefined' && window.location ? window.location.origin : 'http://localhost';
+ const parsed = new URL(url, base);
+ return ['http:', 'https:', 'mailto:'].includes(parsed.protocol);
+ } catch {
+ return false;
+ }
+}
+
export function resolveWithBasePath(url: string, baseURL: string): string {
try {
const base = new URL(baseURL);
diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts
index f1812a7805..ce71d4b365 100644
--- a/packages/core/src/index.ts
+++ b/packages/core/src/index.ts
@@ -55,7 +55,7 @@ export { requestImmediateMacroTask } from './common/request-immediate-macro-task
export { type ISequenceExecuteResult, sequence, sequenceAsync } from './common/sequence';
export { mergeSets } from './common/set';
export { UnitModel, UniverInstanceType } from './common/unit';
-export { resolveWithBasePath } from './common/url';
+export { isSafeUrl, normalizeUrl, resolveWithBasePath } from './common/url';
export * from './docs/data-model';
export { JSON1, JSONX } from './docs/data-model/json-x/json-x';
export type { JSONXActions, JSONXPath } from './docs/data-model/json-x/json-x';
diff --git a/packages/core/src/shared/__tests__/tools.spec.ts b/packages/core/src/shared/__tests__/tools.spec.ts
index e7801c2547..58d98a4b8c 100644
--- a/packages/core/src/shared/__tests__/tools.spec.ts
+++ b/packages/core/src/shared/__tests__/tools.spec.ts
@@ -100,6 +100,16 @@ describe('Tools extra coverage', () => {
expect(Tools.clamp(-1, 1, 10)).toBe(1);
});
+ it('should reject prototype pollution keys in deepMerge', () => {
+ const payload = JSON.parse('{"startIndex":0,"__proto__":{"isAdmin":true,"polluted":true}}');
+ expect(({} as any).isAdmin).toBeUndefined();
+
+ Tools.deepMerge({}, payload);
+
+ expect(({} as any).isAdmin).toBeUndefined();
+ expect(({} as any).polluted).toBeUndefined();
+ });
+
it('should read timing, ids and wildcard regex helpers', () => {
vi.spyOn(globalThis.performance, 'now').mockReturnValue(123.456);
diff --git a/packages/core/src/shared/tools.ts b/packages/core/src/shared/tools.ts
index c26f33c30c..ec5e790254 100644
--- a/packages/core/src/shared/tools.ts
+++ b/packages/core/src/shared/tools.ts
@@ -177,8 +177,15 @@ export class Tools {
static deepMerge(target: any, ...sources: any[]): any {
sources.forEach((item) => item && deepItem(item));
+ function isDangerousKey(key: string): boolean {
+ return key === '__proto__' || key === 'constructor' || key === 'prototype';
+ }
+
function deepArray(array: any[], to: any[]) {
array.forEach((value, key) => {
+ if (typeof key === 'string' && isDangerousKey(key)) {
+ return;
+ }
if (Tools.isArray(value)) {
const origin = to[key] ?? [];
to[key] = origin;
@@ -197,6 +204,9 @@ export class Tools {
function deepObject(object: any, to: any) {
Object.keys(object).forEach((key) => {
+ if (isDangerousKey(key)) {
+ return;
+ }
const value = object[key];
if (Tools.isObject(value)) {
const origin = to[key] ?? {};
@@ -216,6 +226,9 @@ export class Tools {
function deepItem(item: any) {
Object.keys(item).forEach((key) => {
+ if (isDangerousKey(key)) {
+ return;
+ }
const value = item[key];
if (Tools.isArray(value)) {
const origin = target[key] ?? [];
diff --git a/packages/docs-ui/src/services/clipboard/html-to-udm/converter.ts b/packages/docs-ui/src/services/clipboard/html-to-udm/converter.ts
index 8004640c71..b8d5367308 100644
--- a/packages/docs-ui/src/services/clipboard/html-to-udm/converter.ts
+++ b/packages/docs-ui/src/services/clipboard/html-to-udm/converter.ts
@@ -22,6 +22,7 @@ import {
DataStreamTreeTokenType,
DrawingTypeEnum,
generateRandomId,
+ isSafeUrl,
NamedStyleType,
ObjectRelativeFromH,
ObjectRelativeFromV,
@@ -933,15 +934,6 @@ function roundCssNumber(value: number): number {
return Math.round(value * 100) / 100;
}
-function isSafeUrl(url: string): boolean {
- try {
- const parsed = new URL(url, window.location.origin);
- return ['http:', 'https:', 'mailto:'].includes(parsed.protocol);
- } catch {
- return false;
- }
-}
-
function getStructuredBlockType(node: HTMLElement): string | null {
const docType = node.dataset.docType;
if (docType === 'quote') {
diff --git a/packages/sheets-hyper-link-ui/src/services/resolver.service.ts b/packages/sheets-hyper-link-ui/src/services/resolver.service.ts
index 4f55747eda..539b37e2dd 100644
--- a/packages/sheets-hyper-link-ui/src/services/resolver.service.ts
+++ b/packages/sheets-hyper-link-ui/src/services/resolver.service.ts
@@ -18,7 +18,7 @@ import type { IRange, Workbook, Worksheet } from '@univerjs/core';
import type { ISetSelectionsOperationParams } from '@univerjs/sheets';
import type { ISheetHyperLinkInfo, ISheetUrlParams } from '@univerjs/sheets-hyper-link';
import type { IUniverSheetsHyperLinkUIConfig } from '../config/config';
-import { ICommandService, IConfigService, Inject, isValidRange, IUniverInstanceService, LocaleService, RANGE_TYPE, Rectangle, UniverInstanceType } from '@univerjs/core';
+import { ICommandService, IConfigService, Inject, isSafeUrl, isValidRange, IUniverInstanceService, LocaleService, RANGE_TYPE, Rectangle, UniverInstanceType } from '@univerjs/core';
import { MessageType } from '@univerjs/design';
import { deserializeRangeWithSheet, IDefinedNamesService } from '@univerjs/engine-formula';
import { SetSelectionsOperation, SetWorksheetActiveOperation } from '@univerjs/sheets';
@@ -196,6 +196,10 @@ export class SheetsHyperLinkResolverService {
}
async navigateToOtherWebsite(url: string) {
+ if (!isSafeUrl(url)) {
+ return;
+ }
+
const config = this._configService.getConfig<IUniverSheetsHyperLinkUIConfig>(SHEETS_HYPER_LINK_UI_PLUGIN_CONFIG_KEY);
if (config?.urlHandler?.navigateToOtherWebsite) {
diff --git a/packages/sheets-ui/src/services/clipboard/html-to-usm/converter.ts b/packages/sheets-ui/src/services/clipboard/html-to-usm/converter.ts
index 5683f8ffc9..bbac68ff85 100644
--- a/packages/sheets-ui/src/services/clipboard/html-to-usm/converter.ts
+++ b/packages/sheets-ui/src/services/clipboard/html-to-usm/converter.ts
@@ -26,7 +26,7 @@ import type {
IUniverSheetCopyDataModel,
} from '../type';
import type { IAfterProcessRule, IPastePlugin } from './paste-plugins/type';
-import { CustomRangeType, DEFAULT_WORKSHEET_ROW_HEIGHT, generateRandomId, getNumfmtParseValueFilter, numfmt, ObjectMatrix, skipParseTagNames } from '@univerjs/core';
+import { CustomRangeType, DEFAULT_WORKSHEET_ROW_HEIGHT, generateRandomId, getNumfmtParseValueFilter, isSafeUrl, numfmt, ObjectMatrix, skipParseTagNames } from '@univerjs/core';
import { handleStringToStyle, textTrim } from '@univerjs/ui';
import { extractNodeStyle } from './parse-node-style';
import parseToDom, { convertToCellStyle, generateParagraphs } from './utils';
@@ -723,13 +723,17 @@ export class HtmlToUSMService {
const element = node as HTMLElement;
if (element.tagName.toUpperCase() === 'A') {
+ const href = (element as HTMLAnchorElement).href;
+ if (!isSafeUrl(href)) {
+ return;
+ }
body.customRanges = body.customRanges ?? [];
body.customRanges.push({
startIndex: start,
endIndex: body.dataStream.length - 1,
rangeId: element.dataset.rangeid ?? generateRandomId(),
rangeType: CustomRangeType.HYPERLINK,
- properties: { url: (element as HTMLAnchorElement).href },
+ properties: { url: href },
});
}
}
diff --git a/packages/ui/src/services/before-close/before-close.service.ts b/packages/ui/src/services/before-close/before-close.service.ts
index bc3320e600..8ef7d5908d 100644
--- a/packages/ui/src/services/before-close/before-close.service.ts
+++ b/packages/ui/src/services/before-close/before-close.service.ts
@@ -15,7 +15,7 @@
*/
import type { IDisposable } from '@univerjs/core';
-import { createIdentifier } from '@univerjs/core';
+import { createIdentifier, Disposable } from '@univerjs/core';
import { INotificationService } from '../notification/notification.service';
@@ -39,34 +39,16 @@ export interface IBeforeCloseService {
export const IBeforeCloseService = createIdentifier<IBeforeCloseService>('univer.ui.before-close-service');
-export class DesktopBeforeCloseService implements IBeforeCloseService {
+export class DesktopBeforeCloseService extends Disposable implements IBeforeCloseService {
private _beforeUnloadCallbacks: Array<() => string | undefined> = [];
private _onCloseCallbacks: Array<() => void> = [];
- constructor(@INotificationService private readonly _notificationService: INotificationService) {
- this._init();
- }
+ private readonly _beforeUnloadHandler: (event: BeforeUnloadEvent) => string | undefined;
+ private readonly _unloadHandler: () => void;
- registerBeforeClose(callback: () => string | undefined): IDisposable {
- this._beforeUnloadCallbacks.push(callback);
- return {
- dispose: () => {
- this._beforeUnloadCallbacks = this._beforeUnloadCallbacks.filter((cb) => cb !== callback);
- },
- };
- }
-
- registerOnClose(callback: () => void): IDisposable {
- this._onCloseCallbacks.push(callback);
- return {
- dispose: () => {
- this._onCloseCallbacks = this._onCloseCallbacks.filter((cb) => cb !== callback);
- },
- };
- }
-
- private _init(): void {
- window.addEventListener('beforeunload', (_event: BeforeUnloadEvent) => {
+ constructor(@INotificationService private readonly _notificationService: INotificationService) {
+ super();
+ this._beforeUnloadHandler = (_event: BeforeUnloadEvent) => {
let event = _event;
const message = this._beforeUnloadCallbacks
.map((callback) => callback())
@@ -87,10 +69,43 @@ export class DesktopBeforeCloseService implements IBeforeCloseService {
event.returnValue = message;
return message;
}
- });
+ };
- window.addEventListener('unload', () => {
+ this._unloadHandler = () => {
this._onCloseCallbacks.forEach((callback) => callback());
- });
+ };
+
+ this._init();
+ }
+
+ override dispose(): void {
+ window.removeEventListener('beforeunload', this._beforeUnloadHandler);
+ window.removeEventListener('unload', this._unloadHandler);
+ this._beforeUnloadCallbacks = [];
+ this._onCloseCallbacks = [];
+ super.dispose();
+ }
+
+ registerBeforeClose(callback: () => string | undefined): IDisposable {
+ this._beforeUnloadCallbacks.push(callback);
+ return {
+ dispose: () => {
+ this._beforeUnloadCallbacks = this._beforeUnloadCallbacks.filter((cb) => cb !== callback);
+ },
+ };
+ }
+
+ registerOnClose(callback: () => void): IDisposable {
+ this._onCloseCallbacks.push(callback);
+ return {
+ dispose: () => {
+ this._onCloseCallbacks = this._onCloseCallbacks.filter((cb) => cb !== callback);
+ },
+ };
+ }
+
+ private _init(): void {
+ window.addEventListener('beforeunload', this._beforeUnloadHandler);
+ window.addEventListener('unload', this._unloadHandler);
}
}
diff --git a/packages/ui/src/services/ribbon/ribbon.service.ts b/packages/ui/src/services/ribbon/ribbon.service.ts
index 4176008e13..c4f4d0e2ce 100644
--- a/packages/ui/src/services/ribbon/ribbon.service.ts
+++ b/packages/ui/src/services/ribbon/ribbon.service.ts
@@ -238,6 +238,11 @@ export class DesktopRibbonService extends Disposable implements IRibbonService {
override dispose(): void {
this._hiddenSubscription?.unsubscribe();
this._hiddenSubscription = null;
+ this._ribbon$.next([]);
+ this._ribbon$.complete();
+ this._activatedTab$.complete();
+ this._collapsedIds$.complete();
+ this._fakeToolbarVisible$.complete();
super.dispose();
}
}