Skip to content

An open-source, privacy-first, self-hosted knowledge workspace where humans and AI agents work together 开源、隐私优先、自托管的知识工作空间,让人与智能体在此协作

:bug: Harden asset upload transaction boundaries https://github.com/siyuan-note/siyuan/issues/18878

Daniel057a31cb189e
diff --git a/app/src/menus/protyle.ts b/app/src/menus/protyle.ts
index 1f3921b078..de7a2c9f2e 100644
--- a/app/src/menus/protyle.ts
+++ b/app/src/menus/protyle.ts
@@ -64,7 +64,7 @@ import {popSearch} from "../mobile/menu/search";
import {showMessage} from "../dialog/message";
import {img3115} from "../boot/compatibleVersion";
import {hideTooltip} from "../dialog/tooltip";
-import {base64ToURL} from "../protyle/upload/base64";
+import {base64ToURL, showBase64ImageSizeLimit} from "../protyle/upload/base64";
import {setPosition} from "../util/setPosition";
import {setFold} from "../protyle/util/blockFold";
import {isEncryptedBox} from "../util/pathName";
@@ -1510,10 +1510,18 @@ export const imgMenu = (protyle: IProtyle, range: Range, assetElement: HTMLEleme
window.siyuan.menus.menu.removeCB = async () => {
const newSrc = textElements[0].value;
if (src !== newSrc && newSrc.startsWith("data:image/")) {
- const base64Src = await base64ToURL([newSrc], protyle, {
- source: "programmatic",
- target: "editor",
- });
+ let base64Src: Array<string | undefined>;
+ try {
+ base64Src = await base64ToURL([newSrc], protyle, {
+ source: "programmatic",
+ target: "editor",
+ });
+ } catch (error) {
+ if (showBase64ImageSizeLimit(error)) {
+ return;
+ }
+ throw error;
+ }
if (base64Src[0]) {
imgElement.setAttribute("src", base64Src[0]);
imgElement.setAttribute("data-src", base64Src[0]);
diff --git a/app/src/plugin/loader.ts b/app/src/plugin/loader.ts
index 9c940f9472..d05d6e8c5b 100644
--- a/app/src/plugin/loader.ts
+++ b/app/src/plugin/loader.ts
@@ -13,7 +13,7 @@ import {
import {API} from "./API";
import {getFrontend, isMobile, isWindow} from "../util/functions";
import {Constants} from "../constants";
-import {destroyPlugin} from "./uninstall";
+import {beginPluginTeardown, destroyPlugin} from "./uninstall";
import {setStorageVal} from "../protyle/util/compatibility";
import {getAllEditor} from "../layout/getAll";
import {getPluginDockEntryKey, refreshDockCatalog} from "../config/entryVisibility/catalog";
@@ -93,7 +93,10 @@ const getLifecycleManager = (app: App) => {
mount: (plugin) => mountPlugin(plugin),
shouldReloadOnDataChange: (plugin) => plugin.onDataChanged === Plugin.prototype.onDataChanged,
onDataChanged: (plugin) => plugin.onDataChanged(),
- onunload: (plugin) => plugin.onunload(),
+ onunload: (plugin) => {
+ beginPluginTeardown(plugin);
+ return plugin.onunload();
+ },
uninstall: (plugin) => plugin.uninstall(),
markDisposed: (plugin) => markPluginDisposed(plugin),
dispose: (plugin, isUninstall) => destroyPlugin(app, plugin, isUninstall),
diff --git a/app/src/plugin/uninstall.ts b/app/src/plugin/uninstall.ts
index 6558cc2c70..7c593761b0 100644
--- a/app/src/plugin/uninstall.ts
+++ b/app/src/plugin/uninstall.ts
@@ -31,8 +31,12 @@ const runCleanup = (plugin: Plugin, step: string, callback: () => unknown) => {
}
};
-export const destroyPlugin = (app: App, plugin: Plugin, isUninstall: boolean) => {
+export const beginPluginTeardown = (plugin: Plugin) => {
runCleanup(plugin, "asset upload", () => cancelAssetUploadsByPlugin(plugin));
+};
+
+export const destroyPlugin = (app: App, plugin: Plugin, isUninstall: boolean) => {
+ beginPluginTeardown(plugin);
runCleanup(plugin, "kernel", () => plugin.kernel.destroy());
runCleanup(plugin, "event bus", () => destroyEventBus(plugin.eventBus));
if (isUninstall) {
diff --git a/app/src/protyle/render/av/asset.ts b/app/src/protyle/render/av/asset.ts
index 1efe367fcb..700dd84ba0 100644
--- a/app/src/protyle/render/av/asset.ts
+++ b/app/src/protyle/render/av/asset.ts
@@ -22,7 +22,7 @@ import * as dayjs from "dayjs";
import {getColId} from "./col";
import {getFieldIdByCellElement} from "./row";
import {getCompressURL, removeCompressURL} from "../../../util/image";
-import {base64ToURL} from "../../upload/base64";
+import {base64ToURL, showBase64ImageSizeLimit} from "../../upload/base64";
import {isBrowserRenderableImagePath} from "../../../util/imageURL";
import {genNetworkImageAssetValue} from "./assetValue";
import {getAssetUploadSuccesses} from "../../upload/uploadResult";
@@ -248,10 +248,18 @@ export const editAssetItem = (options: {
return;
}
if (type === "image" && currentLink.startsWith("data:image/")) {
- const base64Src = await base64ToURL([currentLink], options.protyle, {
- source: "programmatic",
- target: "av-cell",
- });
+ let base64Src: Array<string | undefined>;
+ try {
+ base64Src = await base64ToURL([currentLink], options.protyle, {
+ source: "programmatic",
+ target: "av-cell",
+ });
+ } catch (error) {
+ if (showBase64ImageSizeLimit(error)) {
+ return;
+ }
+ throw error;
+ }
currentLink = base64Src[0] || currentLink;
}
diff --git a/app/src/protyle/upload/base64.ts b/app/src/protyle/upload/base64.ts
index 962817c9ee..bcf3ad2e09 100644
--- a/app/src/protyle/upload/base64.ts
+++ b/app/src/protyle/upload/base64.ts
@@ -1,11 +1,35 @@
import {type IUploadInsertOptions, uploadFiles} from "./index";
import {getAssetUploadPathsByInput} from "./uploadResult";
-import {createBase64ImageFile} from "./base64File";
+import {
+ addBase64ImageBatchSize,
+ assertBase64ImageItemSize,
+ createBase64ImageFile,
+ getBase64ImageDecodedSize,
+ isBase64ImageSizeLimitError,
+} from "./base64File";
+import {showMessage} from "../../dialog/message";
+
+export const showBase64ImageSizeLimit = (error: unknown) => {
+ if (!isBase64ImageSizeLimitError(error)) {
+ return false;
+ }
+ showMessage(`<ul><li>Base64 ${window.siyuan.languages.over} ${error.maxBytes / 1024 / 1024}M</li></ul>`);
+ return true;
+};
export const base64ToURL = async (base64SrcList: string[], protyle: IProtyle,
options?: IUploadInsertOptions) => {
const files: File[] = [];
const fileSourceIndices: number[] = [];
+ let totalBytes = 0;
+ base64SrcList.forEach(item => {
+ const size = getBase64ImageDecodedSize(item);
+ if (size === undefined) {
+ return;
+ }
+ assertBase64ImageItemSize(size, protyle.options.upload.max);
+ totalBytes = addBase64ImageBatchSize(totalBytes, size);
+ });
base64SrcList.forEach((item, sourceIndex) => {
const file = createBase64ImageFile(item, `base64image-${Lute.NewNodeID()}`, protyle.options.upload.max);
if (!file) {
diff --git a/app/src/protyle/upload/base64File.ts b/app/src/protyle/upload/base64File.ts
index 91614993e7..553f839c94 100644
--- a/app/src/protyle/upload/base64File.ts
+++ b/app/src/protyle/upload/base64File.ts
@@ -3,6 +3,38 @@ interface IBase64ImageFormat {
mime: string;
}
+export const BASE64_IMAGE_ITEM_MAX_BYTES = 32 * 1024 * 1024;
+export const BASE64_IMAGE_BATCH_MAX_BYTES = 64 * 1024 * 1024;
+
+export type TBase64ImageSizeLimitScope = "item" | "batch";
+
+export class Base64ImageSizeLimitError extends Error {
+ readonly code = "BASE64_IMAGE_SIZE_LIMIT";
+
+ constructor(readonly scope: TBase64ImageSizeLimitScope, readonly actualBytes: number, readonly maxBytes: number) {
+ super(`Base64 image ${scope} size ${actualBytes} exceeds ${maxBytes} bytes`);
+ this.name = "Base64ImageSizeLimitError";
+ }
+}
+
+export const isBase64ImageSizeLimitError = (error: unknown): error is Base64ImageSizeLimitError =>
+ error instanceof Base64ImageSizeLimitError;
+
+export const assertBase64ImageItemSize = (actualBytes: number, maxBytes?: number) => {
+ const itemMaxBytes = Math.min(maxBytes ?? BASE64_IMAGE_ITEM_MAX_BYTES, BASE64_IMAGE_ITEM_MAX_BYTES);
+ if (actualBytes > itemMaxBytes) {
+ throw new Base64ImageSizeLimitError("item", actualBytes, itemMaxBytes);
+ }
+};
+
+export const addBase64ImageBatchSize = (currentBytes: number, fileBytes: number) => {
+ const totalBytes = currentBytes + fileBytes;
+ if (totalBytes > BASE64_IMAGE_BATCH_MAX_BYTES) {
+ throw new Base64ImageSizeLimitError("batch", totalBytes, BASE64_IMAGE_BATCH_MAX_BYTES);
+ }
+ return totalBytes;
+};
+
const startsWith = (bytes: Uint8Array, signature: number[]) =>
signature.every((value, index) => bytes[index] === value);
@@ -24,31 +56,58 @@ const detectBase64ImageFormat = (bytes: Uint8Array): IBase64ImageFormat | undefi
startsWith(bytes.subarray(8), [0x57, 0x45, 0x42, 0x50])) {
return {extension: "webp", mime: "image/webp"};
}
- const text = new TextDecoder().decode(bytes.subarray(0, 4096)).replace(/^\uFEFF/, "").trimStart();
- if (/^(?:<\?xml[^>]*>\s*)?<svg(?:\s|>)/i.test(text)) {
+ const text = new TextDecoder().decode(bytes.subarray(0, 64 * 1024)).replace(/^\uFEFF/, "");
+ const root = text.replace(/^(?:(?:\s+)|(?:<\?xml[\s\S]*?\?>)|(?:<!--[\s\S]*?-->)|(?:<!DOCTYPE[\s\S]*?>))*/i, "");
+ if (/^<svg(?:\s|>)/i.test(root)) {
return {extension: "svg", mime: "image/svg+xml"};
}
};
-const getBase64DecodedSize = (base64: string) => {
- const padding = base64.endsWith("==") ? 2 : base64.endsWith("=") ? 1 : 0;
- return Math.floor(base64.length * 3 / 4) - padding;
+const getBase64Data = (source: string) => {
+ const separator = source.indexOf(",");
+ if (separator < 0 || !/^data:([^;,]+)(?:;[^,]*)?;base64$/i.test(source.substring(0, separator))) {
+ return;
+ }
+ return source.substring(separator + 1);
};
-export const createBase64ImageFile = (source: string, name: string, maxBytes?: number) => {
- const separator = source.indexOf(",");
- if (separator < 0) {
+export const getBase64ImageDecodedSize = (source: string) => {
+ const data = getBase64Data(source);
+ if (data === undefined) {
return;
}
- const mimeMatch = source.substring(0, separator).match(/^data:([^;,]+)(?:;[^,]*)?;base64$/i);
- if (!mimeMatch) {
+ let encodedLength = 0;
+ let lastCharacter = "";
+ let penultimateCharacter = "";
+ for (let index = 0; index < data.length; index++) {
+ const code = data.charCodeAt(index);
+ if (code === 0x25 && data[index + 1] === "0" && data[index + 2]?.toUpperCase() === "A") {
+ index += 2;
+ continue;
+ }
+ if (code === 0x09 || code === 0x0A || code === 0x0B || code === 0x0C || code === 0x0D || code === 0x20) {
+ continue;
+ }
+ encodedLength++;
+ penultimateCharacter = lastCharacter;
+ lastCharacter = data[index];
+ }
+ const padding = lastCharacter === "=" ? penultimateCharacter === "=" ? 2 : 1 : 0;
+ return Math.floor(encodedLength * 3 / 4) - padding;
+};
+
+export const createBase64ImageFile = (source: string, name: string, maxBytes?: number) => {
+ const base64Data = getBase64Data(source);
+ if (base64Data === undefined) {
return;
}
try {
- const base64 = source.substring(separator + 1).replace(/%0A/gi, "\n").replace(/\s/g, "");
- if (maxBytes !== undefined && getBase64DecodedSize(base64) > maxBytes) {
+ const decodedSize = getBase64ImageDecodedSize(source);
+ if (decodedSize === undefined) {
return;
}
+ assertBase64ImageItemSize(decodedSize, maxBytes);
+ const base64 = base64Data.replace(/%0A/gi, "\n").replace(/\s/g, "");
const binary = atob(base64);
const bytes = new Uint8Array(binary.length);
for (let index = 0; index < binary.length; index++) {
@@ -60,6 +119,9 @@ export const createBase64ImageFile = (source: string, name: string, maxBytes?: n
}
return new File([bytes], `${name}.${format.extension}`, {type: format.mime});
} catch (error) {
+ if (isBase64ImageSizeLimitError(error)) {
+ throw error;
+ }
console.error(error);
}
};
diff --git a/app/src/protyle/upload/htmlEmbeddedAssets.test.ts b/app/src/protyle/upload/htmlEmbeddedAssets.test.ts
index 74f3e30237..d0b106c1f7 100644
--- a/app/src/protyle/upload/htmlEmbeddedAssets.test.ts
+++ b/app/src/protyle/upload/htmlEmbeddedAssets.test.ts
@@ -1,12 +1,21 @@
import {describe, it} from "node:test";
import * as assert from "node:assert/strict";
-import {createBase64ImageFile} from "./base64File";
+import {
+ addBase64ImageBatchSize,
+ BASE64_IMAGE_BATCH_MAX_BYTES,
+ BASE64_IMAGE_ITEM_MAX_BYTES,
+ Base64ImageSizeLimitError,
+ assertBase64ImageItemSize,
+ createBase64ImageFile,
+ isBase64ImageSizeLimitError,
+} from "./base64File";
import {
applyHTMLEmbeddedAssetPaths,
collectHTMLEmbeddedAssets,
hasHTMLEmbeddedAssets,
type IHTMLEmbeddedAsset,
isHTMLBase64Image,
+ validateHTMLEmbeddedAssetSizes,
} from "./htmlEmbeddedAssets";
describe("HTML embedded assets", () => {
@@ -40,6 +49,14 @@ describe("HTML embedded assets", () => {
assert.equal(createBase64ImageFile("data:image/png;base64,PHN2Zz48L3N2Zz4=", "svg")?.type, "image/svg+xml");
});
+ it("recognizes SVG documents with comments and a doctype", () => {
+ const comment = "x".repeat(5000);
+ const svg = `<!--${comment}--><!DOCTYPE svg><svg xmlns="http://www.w3.org/2000/svg"></svg>`;
+ const source = `data:image/svg+xml;base64,${Buffer.from(svg).toString("base64")}`;
+
+ assert.equal(createBase64ImageFile(source, "svg")?.type, "image/svg+xml");
+ });
+
it("rejects unsupported and oversized Base64 images before decoding", () => {
assert.equal(createBase64ImageFile("data:image/png;base64,YQ==", "invalid"), undefined);
const originalAtob = globalThis.atob;
@@ -49,7 +66,9 @@ describe("HTML embedded assets", () => {
return originalAtob(value);
};
try {
- assert.equal(createBase64ImageFile("data:image/png;base64,iVBORw0KGgo=", "large", 7), undefined);
+ assert.throws(() => createBase64ImageFile("data:image/png;base64,iVBORw0KGgo=", "large", 7),
+ (error: unknown) => isBase64ImageSizeLimitError(error) && error.scope === "item" &&
+ error.actualBytes === 8 && error.maxBytes === 7);
} finally {
globalThis.atob = originalAtob;
}
@@ -57,6 +76,75 @@ describe("HTML embedded assets", () => {
assert.equal(createBase64ImageFile("data:image/png;base64,iVBORw0KGgo=", "image", 8)?.size, 8);
});
+ it("rejects a Base64 batch that exceeds the hard limit", () => {
+ assert.throws(() => assertBase64ImageItemSize(BASE64_IMAGE_ITEM_MAX_BYTES + 1, Number.MAX_SAFE_INTEGER),
+ (error: unknown) => error instanceof Base64ImageSizeLimitError && error.scope === "item" &&
+ error.maxBytes === BASE64_IMAGE_ITEM_MAX_BYTES);
+ assert.equal(addBase64ImageBatchSize(BASE64_IMAGE_BATCH_MAX_BYTES - 1, 1), BASE64_IMAGE_BATCH_MAX_BYTES);
+ assert.throws(() => addBase64ImageBatchSize(BASE64_IMAGE_BATCH_MAX_BYTES, 1),
+ (error: unknown) => error instanceof Base64ImageSizeLimitError && error.scope === "batch" &&
+ error.actualBytes === BASE64_IMAGE_BATCH_MAX_BYTES + 1 &&
+ error.maxBytes === BASE64_IMAGE_BATCH_MAX_BYTES);
+ });
+
+ it("validates HTML Base64 sizes without decoding", () => {
+ const root = {
+ querySelectorAll(selector: string) {
+ if (selector === "pre") {
+ return [];
+ }
+ return [{
+ getAttribute(attribute: string) {
+ return attribute === "src" ? "data:image/png;base64,iVBORw0KGgo=" : null;
+ },
+ }];
+ },
+ } as unknown as ParentNode;
+ const originalAtob = globalThis.atob;
+ let decoded = false;
+ globalThis.atob = () => {
+ decoded = true;
+ return "";
+ };
+ try {
+ assert.throws(() => validateHTMLEmbeddedAssetSizes(root, 7), isBase64ImageSizeLimitError);
+ } finally {
+ globalThis.atob = originalAtob;
+ }
+ assert.equal(decoded, false);
+ });
+
+ it("validates the complete HTML Base64 batch before creating files", () => {
+ const sources = [
+ "data:image/png;base64,iVBORw0KGgo=",
+ "data:image/png;base64,iVBORw0KGgoAA",
+ ];
+ const root = {
+ querySelectorAll(selector: string) {
+ if (selector === "pre") {
+ return [];
+ }
+ return sources.map(source => ({
+ getAttribute(attribute: string) {
+ return attribute === "src" ? source : null;
+ },
+ }));
+ },
+ } as unknown as ParentNode;
+ const originalAtob = globalThis.atob;
+ let decoded = false;
+ globalThis.atob = () => {
+ decoded = true;
+ return "";
+ };
+ try {
+ assert.throws(() => collectHTMLEmbeddedAssets(root, 8), isBase64ImageSizeLimitError);
+ } finally {
+ globalThis.atob = originalAtob;
+ }
+ assert.equal(decoded, false);
+ });
+
it("collects Base64 attributes and rewrites them after upload", () => {
const attributes = new Map([["src", "data:image/png;base64,iVBORw0KGgo="]]);
const element = {
diff --git a/app/src/protyle/upload/htmlEmbeddedAssets.ts b/app/src/protyle/upload/htmlEmbeddedAssets.ts
index f6c9c0db29..a4614201bb 100644
--- a/app/src/protyle/upload/htmlEmbeddedAssets.ts
+++ b/app/src/protyle/upload/htmlEmbeddedAssets.ts
@@ -1,4 +1,9 @@
-import {createBase64ImageFile} from "./base64File";
+import {
+ addBase64ImageBatchSize,
+ assertBase64ImageItemSize,
+ createBase64ImageFile,
+ getBase64ImageDecodedSize,
+} from "./base64File";
export interface IHTMLEmbeddedAsset {
file: File;
@@ -18,18 +23,38 @@ export const hasHTMLEmbeddedAssets = (root: ParentNode) => {
}));
};
-export const collectHTMLEmbeddedAssets = (root: ParentNode, maxBytes?: number) => {
- const assets: IHTMLEmbeddedAsset[] = [];
- const svgBlocks = new Set<Element>();
- root.querySelectorAll("pre").forEach(element => {
- if (!element.hasAttributes()) {
- return;
- }
- const svg = element.querySelector("svg");
- if (!svg) {
+const getInlineSVGBlocks = (root: ParentNode) => new Set(Array.from(root.querySelectorAll("pre")).filter(element =>
+ element.hasAttributes() && element.querySelector("svg")));
+
+export const validateHTMLEmbeddedAssetSizes = (root: ParentNode, maxBytes?: number) => {
+ const svgBlocks = getInlineSVGBlocks(root);
+ let totalBytes = 0;
+ root.querySelectorAll("[href], [src]").forEach(element => {
+ if (Array.from(svgBlocks).some(block => block.contains(element))) {
return;
}
- svgBlocks.add(element);
+ (["href", "src"] as const).forEach(attribute => {
+ const source = element.getAttribute(attribute);
+ if (!source || !isHTMLBase64Image(source)) {
+ return;
+ }
+ const size = getBase64ImageDecodedSize(source.trim());
+ if (size === undefined) {
+ return;
+ }
+ assertBase64ImageItemSize(size, maxBytes);
+ totalBytes = addBase64ImageBatchSize(totalBytes, size);
+ });
+ });
+};
+
+export const collectHTMLEmbeddedAssets = (root: ParentNode, maxBytes?: number) => {
+ validateHTMLEmbeddedAssetSizes(root, maxBytes);
+ const assets: IHTMLEmbeddedAsset[] = [];
+ let base64Bytes = 0;
+ const svgBlocks = getInlineSVGBlocks(root);
+ svgBlocks.forEach(element => {
+ const svg = element.querySelector("svg")!;
const file = new File([svg.outerHTML], `inline-svg-${assets.length}.svg`, {type: "image/svg+xml"});
assets.push({
file,
@@ -54,6 +79,7 @@ export const collectHTMLEmbeddedAssets = (root: ParentNode, maxBytes?: number) =
if (!file) {
return;
}
+ base64Bytes = addBase64ImageBatchSize(base64Bytes, file.size);
assets.push({
file,
apply(path) {
diff --git a/app/src/protyle/upload/insertPosition.test.ts b/app/src/protyle/upload/insertPosition.test.ts
index e05bf2727b..c16ff31db4 100644
--- a/app/src/protyle/upload/insertPosition.test.ts
+++ b/app/src/protyle/upload/insertPosition.test.ts
@@ -3,6 +3,7 @@ import * as assert from "node:assert/strict";
import {createUploadInsertPosition, isUploadInsertPositionAvailable} from "./insertPosition";
class TestElement {
+ public isConnected = true;
public parent?: TestElement;
public children: TestElement[] = [];
@@ -65,4 +66,13 @@ describe("upload insert position", () => {
assert.equal(isUploadInsertPositionAvailable(editor as unknown as Element, position), false);
});
+
+ it("rejects a position after the editor is detached", () => {
+ const target = new TestElement();
+ const editor = new TestElement().append(target);
+ const position = createUploadInsertPosition(createRange(target));
+ editor.isConnected = false;
+
+ assert.equal(isUploadInsertPositionAvailable(editor as unknown as Element, position), false);
+ });
});
diff --git a/app/src/protyle/upload/insertPosition.ts b/app/src/protyle/upload/insertPosition.ts
index 9705aec269..1a3882bfc0 100644
--- a/app/src/protyle/upload/insertPosition.ts
+++ b/app/src/protyle/upload/insertPosition.ts
@@ -16,9 +16,15 @@ export const createUploadInsertPosition = (range: Range, context?: Record<string
};
export const isUploadInsertPositionAvailable = (editorElement: Element, position?: IUploadInsertPosition) => {
- return !!position &&
+ return editorElement.isConnected && !!position &&
editorElement.contains(position.startContainer) &&
editorElement.contains(position.endContainer) &&
editorElement.contains(position.range.startContainer) &&
editorElement.contains(position.range.endContainer);
};
+
+export const getAvailableUploadInsertRange = (editorElement: Element, position?: IUploadInsertPosition) => {
+ if (isUploadInsertPositionAvailable(editorElement, position)) {
+ return position.range.cloneRange();
+ }
+};
diff --git a/app/src/protyle/upload/pluginEvent.test.ts b/app/src/protyle/upload/pluginEvent.test.ts
index 16087d4a62..baf1b3a3d1 100644
--- a/app/src/protyle/upload/pluginEvent.test.ts
+++ b/app/src/protyle/upload/pluginEvent.test.ts
@@ -85,6 +85,28 @@ describe("asset upload plugin event", () => {
assert.notEqual(prepared.task.input.files, input.files);
});
+ it("generates unique UUID request identifiers", async () => {
+ const plugin = createPlugin(() => undefined);
+ const first = await prepareAssetUpload({
+ plugins: [plugin],
+ protyle,
+ input: {kind: "files", files: [createFile("a.png")]},
+ context,
+ });
+ const second = await prepareAssetUpload({
+ plugins: [plugin],
+ protyle,
+ input: {kind: "files", files: [createFile("b.png")]},
+ context,
+ });
+
+ assert.match(first.task.requestId, /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i);
+ assert.match(second.task.requestId, /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i);
+ assert.notEqual(first.task.requestId, second.task.requestId);
+ first.task.complete({status: "canceled"});
+ second.task.complete({status: "canceled"});
+ });
+
it("isolates local file input from listener mutations", async () => {
const originalFile: ILocalFiles = {path: "a.png", size: 1};
const prepared = await prepareAssetUpload({
@@ -464,6 +486,25 @@ describe("asset upload plugin event", () => {
assert.equal(signal.aborted, true);
});
+ it("does not dispatch new uploads after the plugin starts unloading", async () => {
+ let pluginCalled = false;
+ const plugin = createPlugin(() => {
+ pluginCalled = true;
+ });
+ cancelAssetUploadsByPlugin(plugin);
+
+ const prepared = await prepareAssetUpload({
+ plugins: [plugin],
+ protyle,
+ input: {kind: "files", files: [createFile("a.png")]},
+ context,
+ });
+
+ assert.equal(prepared.state, "ready");
+ assert.equal(pluginCalled, false);
+ prepared.task.complete({status: "canceled"});
+ });
+
it("cancels pending processing when a queued plugin is unloaded", async () => {
const activePlugin = createPlugin(event => {
event.detail.respondWith(new Promise(() => undefined));
diff --git a/app/src/protyle/upload/pluginEvent.ts b/app/src/protyle/upload/pluginEvent.ts
index 0a6e981f1e..68322107a9 100644
--- a/app/src/protyle/upload/pluginEvent.ts
+++ b/app/src/protyle/upload/pluginEvent.ts
@@ -40,16 +40,13 @@ class AssetUploadTimeoutError extends Error {
export const ASSET_UPLOAD_PLUGIN_TIMEOUT = 120_000;
-let requestSequence = 0;
const waitingTasksByProtyle = new WeakMap<IProtyle, Set<AssetUploadTask>>();
const waitingTasksByPlugin = new WeakMap<IAssetUploadPlugin, Set<AssetUploadTask>>();
const activeTasksByProtyle = new WeakMap<IProtyle, Set<AssetUploadTask>>();
const completionTasksByPlugin = new WeakMap<IAssetUploadPlugin, Set<AssetUploadTask>>();
+const unloadingPlugins = new WeakSet<IAssetUploadPlugin>();
-const genRequestId = () => {
- requestSequence++;
- return `${Date.now()}-${requestSequence}`;
-};
+const genRequestId = () => crypto.randomUUID();
const cloneInput = (input: IAssetUploadInput): IAssetUploadInput => {
if (input.kind === "files") {
@@ -277,6 +274,7 @@ export const cancelAssetUploads = (protyle: IProtyle) => {
};
export const cancelAssetUploadsByPlugin = (plugin: IAssetUploadPlugin) => {
+ unloadingPlugins.add(plugin);
Array.from(completionTasksByPlugin.get(plugin) || []).forEach(task => task.removeCompleteCallbacks(plugin));
cancelWaitingTasks(waitingTasksByPlugin.get(plugin), `Plugin ${plugin.name || ""} was unloaded`.trim());
};
@@ -341,7 +339,8 @@ export const prepareAssetUpload = (options: {
if (!hasPluginSubscriber("before-upload-assets")) {
return {state: "ready", task};
}
- const plugins = Array.from(options.plugins).filter(plugin => eventBusHas(plugin.eventBus, "before-upload-assets"));
+ const plugins = Array.from(options.plugins).filter(plugin => !unloadingPlugins.has(plugin) &&
+ eventBusHas(plugin.eventBus, "before-upload-assets"));
if (plugins.length === 0) {
return {state: "ready", task};
}
@@ -355,6 +354,9 @@ export const prepareAssetUpload = (options: {
return {state: "ready", task};
}
const plugin = plugins[index];
+ if (unloadingPlugins.has(plugin)) {
+ return processPlugin(index + 1);
+ }
task.startWaiting(plugins.slice(index));
const pluginLabel = getPluginLabel(plugin, index);
let response: PromiseLike<IAssetUploadDecision> | undefined;
@@ -395,6 +397,9 @@ export const prepareAssetUpload = (options: {
console.error(new Error(`Plugin ${pluginLabel} must register onComplete synchronously`));
return;
}
+ if (unloadingPlugins.has(plugin)) {
+ return;
+ }
task.addCompleteCallback(plugin, callback);
},
});
diff --git a/app/src/protyle/util/paste.ts b/app/src/protyle/util/paste.ts
index c68a0f0ca6..efe158ef93 100644
--- a/app/src/protyle/util/paste.ts
+++ b/app/src/protyle/util/paste.ts
@@ -1,6 +1,11 @@
import {Constants} from "../../constants";
import {uploadFiles, uploadLocalFiles} from "../upload";
import type {IUploadInsertOptions} from "../upload";
+import {
+ createUploadInsertPosition,
+ getAvailableUploadInsertRange,
+ isUploadInsertPositionAvailable,
+} from "../upload/insertPosition";
import {processPasteCode, processRender} from "./processCode";
import {getLocalFiles, getTextSiyuanFromTextHTML, readText} from "./compatibility";
import {hasClosestBlock, hasClosestByAttribute, hasClosestByClassName} from "./hasClosest";
@@ -18,12 +23,14 @@ import {cellScrollIntoView, getCellText} from "../render/av/cell";
import {fixAdjacentTags, getCalloutInfo, getContenteditableElement} from "../wysiwyg/getBlock";
import {clearBlockElement} from "./clear";
import {removeZWJ} from "./normalizeText";
-import {base64ToURL} from "../upload/base64";
+import {base64ToURL, showBase64ImageSizeLimit} from "../upload/base64";
import {applyHTMLLocalAssetPaths, collectHTMLLocalAssets} from "../upload/htmlLocalAssets";
import {
applyHTMLEmbeddedAssetPaths,
collectHTMLEmbeddedAssets,
hasHTMLEmbeddedAssets,
+ type IHTMLEmbeddedAsset,
+ validateHTMLEmbeddedAssetSizes,
} from "../upload/htmlEmbeddedAssets";
import {getAssetUploadPathsByInput} from "../upload/uploadResult";
import {resolveLinkDest} from "../toolbar/util";
@@ -297,24 +304,58 @@ const readLocalFile = async (protyle: IProtyle, localFiles: ILocalFiles[], optio
if (!eventBusHas(plugin.eventBus, "paste")) {
continue;
}
- const response: { localFiles: ILocalFiles[] } = await new Promise((resolve) => {
+ const response = await new Promise<{ localFiles: ILocalFiles[] } | undefined |
+ typeof PASTE_PLUGIN_TIMED_OUT>((resolve, reject) => {
+ let settled = false;
+ const finish = (value: { localFiles: ILocalFiles[] } | undefined | typeof PASTE_PLUGIN_TIMED_OUT) => {
+ if (settled) {
+ return;
+ }
+ settled = true;
+ clearTimeout(timeoutId);
+ resolve(value);
+ };
+ const resolveResponse = (value: { localFiles: ILocalFiles[] } |
+ PromiseLike<{ localFiles: ILocalFiles[] } | undefined> | undefined) => {
+ void Promise.resolve(value).then(finish, error => {
+ if (!settled) {
+ settled = true;
+ clearTimeout(timeoutId);
+ reject(error);
+ }
+ });
+ };
+ const timeoutId = setTimeout(() => finish(PASTE_PLUGIN_TIMED_OUT), PASTE_PLUGIN_TIMEOUT);
const emitResult = plugin.eventBus.emit("paste", {
protyle,
- resolve,
+ resolve: resolveResponse,
textHTML: "",
textPlain: "",
siyuanHTML: "",
localFiles
});
if (emitResult) {
- resolve(undefined);
+ finish(undefined);
}
});
+ if (options?.insertPosition &&
+ !isUploadInsertPositionAvailable(protyle.wysiwyg.element, options.insertPosition)) {
+ return;
+ }
+ if (response === PASTE_PLUGIN_TIMED_OUT) {
+ console.error(new Error(`Plugin ${plugin.name || `#${i + 1}`} paste processing timed out`));
+ showMessage(window.siyuan.languages.uploadError);
+ return;
+ }
if (response?.localFiles) {
localFiles = response.localFiles;
}
}
}
+ if (options?.insertPosition &&
+ !isUploadInsertPositionAvailable(protyle.wysiwyg.element, options.insertPosition)) {
+ return;
+ }
uploadLocalFiles(localFiles, protyle, true, options);
};
@@ -520,8 +561,9 @@ const pasteCrossBlockRange = (protyle: IProtyle, tempElement: HTMLElement, range
return true;
};
-const insertConvertedBlockDOM = (protyle: IProtyle, dom: string) => {
- insertHTML(dom, protyle, false, false, true);
+const insertConvertedBlockDOM = (protyle: IProtyle, dom: string, range: Range) => {
+ protyle.toolbar.range = range;
+ insertHTML(dom, protyle, false, true, true);
protyle.wysiwyg.element.querySelectorAll('[data-type~="block-ref"]').forEach(item => {
if (item.textContent === "") {
fetchPost("/api/block/getRefText", {id: item.getAttribute("data-id")}, (response) => {
@@ -543,8 +585,20 @@ export const paste = async (protyle: IProtyle, event: (ClipboardEvent | DragEven
event.stopPropagation();
event.preventDefault();
}
+ const pasteInsertPosition = uploadOptions?.insertPosition ||
+ createUploadInsertPosition(getEditorRange(protyle.wysiwyg.element));
+ const isPasteInsertPositionAvailable = () =>
+ isUploadInsertPositionAvailable(protyle.wysiwyg.element, pasteInsertPosition);
+ const restorePasteInsertRange = () => {
+ return getAvailableUploadInsertRange(protyle.wysiwyg.element, pasteInsertPosition);
+ };
+ const insertAtPasteRange = (html: string, range: Range, isBlock = false, insertByCursor = false) => {
+ protyle.toolbar.range = range;
+ insertHTML(html, protyle, isBlock, true, insertByCursor);
+ };
const assetUploadOptions: IUploadInsertOptions = {
...uploadOptions,
+ insertPosition: pasteInsertPosition,
source: uploadOptions?.source || ("dataTransfer" in event ? "drop" : "paste"),
target: uploadOptions?.target || "editor",
position: uploadOptions?.position || ("dataTransfer" in event ? {x: event.clientX, y: event.clientY} : undefined),
@@ -613,9 +667,15 @@ export const paste = async (protyle: IProtyle, event: (ClipboardEvent | DragEven
text: textPlain,
}),
]);
+ if (!isPasteInsertPositionAvailable()) {
+ return;
+ }
}
if (!siyuanHTML && !textHTML && !textPlain && !wpsPresentation && ("clipboardData" in event)) {
const localFiles: ILocalFiles[] = await getLocalFiles();
+ if (!isPasteInsertPositionAvailable()) {
+ return;
+ }
if (localFiles.length > 0) {
readLocalFile(protyle, localFiles, assetUploadOptions);
return;
@@ -706,6 +766,10 @@ export const paste = async (protyle: IProtyle, event: (ClipboardEvent | DragEven
}
});
+ if (!isPasteInsertPositionAvailable()) {
+ return;
+ }
+
if (response === PASTE_PLUGIN_TIMED_OUT) {
console.error(new Error(`Plugin ${plugin.name || `#${i + 1}`} paste processing timed out`));
showMessage(window.siyuan.languages.uploadError);
@@ -747,8 +811,11 @@ export const paste = async (protyle: IProtyle, event: (ClipboardEvent | DragEven
originalTextHTML = extractCrossBlockPasteContext(originalTextHTML).html;
+ let range = restorePasteInsertRange();
+ if (!range) {
+ return;
+ }
let nodeElement = hasClosestBlock(event.target);
- const range = getEditorRange(protyle.wysiwyg.element);
if (!nodeElement) {
nodeElement = hasClosestBlock(range.startContainer);
}
@@ -767,42 +834,53 @@ export const paste = async (protyle: IProtyle, event: (ClipboardEvent | DragEven
if (nodeElement.getAttribute("data-type") === "NodeCodeBlock" ||
protyle.toolbar.getCurrentType(range).includes("code")) {
// https://github.com/siyuan-note/siyuan/issues/13552
- insertHTML(removeZWJ(textPlain).replace(/```/g, "\u200D```"), protyle);
+ insertAtPasteRange(removeZWJ(textPlain).replace(/```/g, "\u200D```"), range);
return;
} else if (siyuanHTML) {
async function streamInsert(container: HTMLElement, bigHtmlString: string) {
const iframe = document.createElement("iframe");
iframe.style.display = "none";
document.body.appendChild(iframe);
+ try {
+ const doc = iframe.contentWindow.document;
+ doc.open();
- const doc = iframe.contentWindow.document;
- doc.open();
+ const chunkSize = 102400;
+ let offset = 0;
+ while (offset < bigHtmlString.length) {
+ const chunk = bigHtmlString.substring(offset, offset + chunkSize);
+ doc.write(chunk);
+ offset += chunkSize;
+ await new Promise(resolve => setTimeout(resolve, 0));
+ if (!isPasteInsertPositionAvailable()) {
+ return false;
+ }
+ }
- const chunkSize = 102400;
- let offset = 0;
- while (offset < bigHtmlString.length) {
- const chunk = bigHtmlString.substring(offset, offset + chunkSize);
- doc.write(chunk);
- offset += chunkSize;
- await new Promise(resolve => setTimeout(resolve, 0));
- }
+ doc.close();
- doc.close();
+ const fragment = document.createDocumentFragment();
+ while (doc.body.firstChild) {
+ fragment.appendChild(doc.body.firstChild);
+ }
- const fragment = document.createDocumentFragment();
- while (doc.body.firstChild) {
- fragment.appendChild(doc.body.firstChild);
+ container.appendChild(fragment);
+ return true;
+ } finally {
+ iframe.remove();
}
-
- container.appendChild(fragment);
-
- document.body.removeChild(iframe);
}
// 编辑器内部粘贴
const tempElement = document.createElement("div");
if (1024 * 512 < siyuanHTML.length) {
- await streamInsert(tempElement, siyuanHTML);
+ if (!await streamInsert(tempElement, siyuanHTML)) {
+ return;
+ }
+ range = restorePasteInsertRange();
+ if (!range) {
+ return;
+ }
} else {
tempElement.innerHTML = siyuanHTML;
}
@@ -849,6 +927,7 @@ export const paste = async (protyle: IProtyle, event: (ClipboardEvent | DragEven
}
if (types.includes("block-ref")) {
+ protyle.toolbar.range = range;
const refElement = protyle.toolbar.setInlineMark(protyle, "block-ref", "range", {
type: "id",
color: `${linkElement.dataset.id}${Constants.ZWSP}s${Constants.ZWSP}${range.toString()}`
@@ -859,6 +938,7 @@ export const paste = async (protyle: IProtyle, event: (ClipboardEvent | DragEven
return;
}
if (types.includes("a")) {
+ protyle.toolbar.range = range;
protyle.toolbar.setInlineMark(protyle, "a", "range", {
type: "a",
color: `${linkElement.dataset.href}${Constants.ZWSP}${range.toString()}`
@@ -878,6 +958,10 @@ export const paste = async (protyle: IProtyle, event: (ClipboardEvent | DragEven
oldIds.push(e.getAttribute("data-node-id"));
});
const existResponse = await fetchSyncPost("/api/block/checkBlocksExist", {ids: oldIds});
+ range = restorePasteInsertRange();
+ if (!range) {
+ return;
+ }
pastedBlockElements.forEach((e) => {
const originalId = e.getAttribute("data-node-id");
const isCutPaste = existResponse.data[originalId] === false; // 剪切来的(原块已删)
@@ -919,15 +1003,15 @@ export const paste = async (protyle: IProtyle, event: (ClipboardEvent | DragEven
try {
const json = JSON.parse(tempInnerHTML);
if (json.length > 0 && json[0].length > 0 && json[0][0].id && json[0][0].type) {
- insertHTML(textPlain, protyle, isBlock);
+ insertAtPasteRange(textPlain, range, isBlock);
} else {
- insertHTML(tempInnerHTML, protyle, isBlock);
+ insertAtPasteRange(tempInnerHTML, range, isBlock);
}
} catch (e) {
- insertHTML(tempInnerHTML, protyle, isBlock);
+ insertAtPasteRange(tempInnerHTML, range, isBlock);
}
} else {
- insertHTML(tempInnerHTML, protyle, isBlock, false, true);
+ insertAtPasteRange(tempInnerHTML, range, isBlock, true);
}
blockRender(protyle, protyle.wysiwyg.element);
processRender(protyle.wysiwyg.element);
@@ -936,9 +1020,9 @@ export const paste = async (protyle: IProtyle, event: (ClipboardEvent | DragEven
} else if (code) {
if (!code.startsWith('<div data-type="NodeCodeBlock" class="code-block" data-node-id="')) {
// 原有代码在行内元素中粘贴会嵌套
- insertHTML(code, protyle);
+ insertAtPasteRange(code, range);
} else {
- insertHTML(code, protyle, true, false, true);
+ insertAtPasteRange(code, range, true, true);
highlightRender(protyle.wysiwyg.element);
}
hideElements(["hint"], protyle);
@@ -954,9 +1038,13 @@ export const paste = async (protyle: IProtyle, event: (ClipboardEvent | DragEven
} catch (e) {
// 内核不可用时继续使用剪贴板中的纯文本或图片
}
+ range = restorePasteInsertRange();
+ if (!range) {
+ return;
+ }
const result = response?.data as { converted?: unknown, dom?: unknown };
if (response?.code === 0 && result?.converted === true && typeof result.dom === "string" && result.dom.trim() !== "") {
- insertConvertedBlockDOM(protyle, result.dom);
+ insertConvertedBlockDOM(protyle, result.dom, range);
return;
}
const fallback = getWPSPresentationFallback(wpsPresentation.type, Boolean(files?.length));
@@ -1038,6 +1126,7 @@ export const paste = async (protyle: IProtyle, event: (ClipboardEvent | DragEven
}
if (linkElement) {
const selectText = range.toString();
+ protyle.toolbar.range = range;
const aElements = protyle.toolbar.setInlineMark(protyle, "a", "range", {
type: "a",
color: `${linkElement.getAttribute("href")}${Constants.ZWSP}${selectText || linkElement.textContent}`
@@ -1052,10 +1141,11 @@ export const paste = async (protyle: IProtyle, event: (ClipboardEvent | DragEven
return;
}
if (nodeElement.classList.contains("av") && tempElement.querySelector("table")) {
- insertHTML(tempElement.innerHTML, protyle, false, false, true);
+ insertAtPasteRange(tempElement.innerHTML, range, false, true);
return;
}
- const localAssets = collectHTMLLocalAssets(tempElement);
+ let localAssets = collectHTMLLocalAssets(tempElement);
+ let preparedHTML = false;
const conversionContext = {
text: textPlain,
mathML,
@@ -1064,25 +1154,58 @@ export const paste = async (protyle: IProtyle, event: (ClipboardEvent | DragEven
wps,
};
if (localAssets.length > 0 || hasHTMLEmbeddedAssets(tempElement)) {
+ try {
+ validateHTMLEmbeddedAssetSizes(tempElement, protyle.options.upload.max);
+ } catch (error) {
+ if (showBase64ImageSizeLimit(error)) {
+ return;
+ }
+ throw error;
+ }
let preflightResponse: IWebSocketData;
+ const controller = new AbortController();
+ const timeoutId = setTimeout(() => controller.abort(), PASTE_PLUGIN_TIMEOUT);
try {
preflightResponse = await fetchSyncPost("/api/lute/html2BlockDOM", {
...conversionContext,
dom: tempElement.innerHTML,
preflight: true,
- });
+ }, undefined, true, controller.signal);
} catch (error) {
+ console.error(error);
+ if (isPasteInsertPositionAvailable()) {
+ showMessage(window.siyuan.languages.uploadError);
+ }
+ return;
+ } finally {
+ clearTimeout(timeoutId);
+ }
+ range = restorePasteInsertRange();
+ if (!range) {
return;
}
- const preflight = preflightResponse?.data as {converted?: unknown, dom?: unknown, useHTML?: unknown};
+ const preflight = preflightResponse?.data as {
+ converted?: unknown,
+ dom?: unknown,
+ normalizedHTML?: unknown,
+ useHTML?: unknown,
+ };
if (preflightResponse?.code !== 0 || preflight?.converted !== true ||
typeof preflight.useHTML !== "boolean" || typeof preflight.dom !== "string") {
+ showMessage(window.siyuan.languages.uploadError);
return;
}
if (!preflight.useHTML) {
- insertConvertedBlockDOM(protyle, preflight.dom);
+ insertConvertedBlockDOM(protyle, preflight.dom, range);
+ return;
+ }
+ if (typeof preflight.normalizedHTML !== "string") {
+ showMessage(window.siyuan.languages.uploadError);
return;
}
+ tempElement.innerHTML = preflight.normalizedHTML;
+ localAssets = collectHTMLLocalAssets(tempElement);
+ preparedHTML = true;
}
if (localAssets.length > 0) {
await new Promise<void>(resolve => {
@@ -1095,8 +1218,20 @@ export const paste = async (protyle: IProtyle, event: (ClipboardEvent | DragEven
getAssetUploadPathsByInput(localAssets.length, result));
}, () => resolve());
});
+ range = restorePasteInsertRange();
+ if (!range) {
+ return;
+ }
+ }
+ let embeddedAssets: IHTMLEmbeddedAsset[];
+ try {
+ embeddedAssets = collectHTMLEmbeddedAssets(tempElement, protyle.options.upload.max);
+ } catch (error) {
+ if (showBase64ImageSizeLimit(error)) {
+ return;
+ }
+ throw error;
}
- const embeddedAssets = collectHTMLEmbeddedAssets(tempElement, protyle.options.upload.max);
if (embeddedAssets.length > 0) {
await new Promise<void>(resolve => {
uploadFiles(protyle, embeddedAssets.map(item => item.file), undefined, (_response, result) => {
@@ -1107,16 +1242,37 @@ export const paste = async (protyle: IProtyle, event: (ClipboardEvent | DragEven
requiredFileCount: embeddedAssets.length,
});
});
+ range = restorePasteInsertRange();
+ if (!range) {
+ return;
+ }
+ }
+ let conversionResponse: IWebSocketData;
+ try {
+ conversionResponse = await fetchSyncPost("/api/lute/html2BlockDOM", {
+ ...conversionContext,
+ dom: tempElement.innerHTML,
+ preparedHTML,
+ skipLocalAssets: localAssets.length > 0,
+ skipBase64Assets: true,
+ skipInlineSVGAssets: true,
+ });
+ } catch (error) {
+ console.error(error);
+ if (isPasteInsertPositionAvailable()) {
+ showMessage(window.siyuan.languages.uploadError);
+ }
+ return;
}
- fetchPost("/api/lute/html2BlockDOM", {
- ...conversionContext,
- dom: tempElement.innerHTML,
- skipLocalAssets: localAssets.length > 0,
- skipBase64Assets: true,
- skipInlineSVGAssets: true,
- }, (response) => {
- insertConvertedBlockDOM(protyle, response.data);
- });
+ range = restorePasteInsertRange();
+ if (!range) {
+ return;
+ }
+ if (conversionResponse?.code !== 0 || typeof conversionResponse?.data !== "string") {
+ showMessage(window.siyuan.languages.uploadError);
+ return;
+ }
+ insertConvertedBlockDOM(protyle, conversionResponse.data, range);
return;
} else if (files && files.length > 0) {
uploadFiles(protyle, files, undefined, undefined, undefined, assetUploadOptions);
@@ -1125,6 +1281,7 @@ export const paste = async (protyle: IProtyle, event: (ClipboardEvent | DragEven
if (range.toString() !== "") {
const firstLine = textPlain.split("\n")[0];
if (isDynamicRef(textPlain)) {
+ protyle.toolbar.range = range;
const refElement = protyle.toolbar.setInlineMark(protyle, "block-ref", "range", {
type: "id",
// range 不能 escape,否则 https://github.com/siyuan-note/siyuan/issues/8359
@@ -1135,6 +1292,7 @@ export const paste = async (protyle: IProtyle, event: (ClipboardEvent | DragEven
}
return;
} else if (isFileAnnotation(firstLine)) {
+ protyle.toolbar.range = range;
protyle.toolbar.setInlineMark(protyle, "file-annotation-ref", "range", {
type: "file-annotation-ref",
color: firstLine.substring(2).replace(/ ".+">>$/, "")
@@ -1144,6 +1302,7 @@ export const paste = async (protyle: IProtyle, event: (ClipboardEvent | DragEven
// https://github.com/siyuan-note/siyuan/issues/8475
const linkDest = resolveLinkDest(textPlain, protyle.lute);
if (linkDest) {
+ protyle.toolbar.range = range;
protyle.toolbar.setInlineMark(protyle, "a", "range", {
type: "a",
color: linkDest
@@ -1172,7 +1331,19 @@ export const paste = async (protyle: IProtyle, event: (ClipboardEvent | DragEven
imageElements.push(item);
}
});
- const base64SrcList = await base64ToURL(imgSrcList, protyle, assetUploadOptions);
+ let base64SrcList: Array<string | undefined>;
+ try {
+ base64SrcList = await base64ToURL(imgSrcList, protyle, assetUploadOptions);
+ } catch (error) {
+ if (showBase64ImageSizeLimit(error)) {
+ return;
+ }
+ throw error;
+ }
+ range = restorePasteInsertRange();
+ if (!range) {
+ return;
+ }
base64SrcList.forEach((item, index) => {
if (!item) {
return;
@@ -1183,7 +1354,7 @@ export const paste = async (protyle: IProtyle, event: (ClipboardEvent | DragEven
});
textPlainDom = tempElement.innerHTML;
}
- insertHTML(textPlainDom, protyle, false, false, true);
+ insertAtPasteRange(textPlainDom, range, false, true);
}
blockRender(protyle, protyle.wysiwyg.element);
processRender(protyle.wysiwyg.element);
diff --git a/app/src/util/fetch.ts b/app/src/util/fetch.ts
index 889cc94423..ce5985a0b2 100644
--- a/app/src/util/fetch.ts
+++ b/app/src/util/fetch.ts
@@ -121,9 +121,11 @@ export const fetchPost = (
});
};
-export const fetchSyncPost = async (url: string, data?: any, headers?: Record<string, string>, process = true) => {
+export const fetchSyncPost = async (url: string, data?: any, headers?: Record<string, string>, process = true,
+ signal?: AbortSignal) => {
const init: RequestInit = {
method: "POST",
+ signal,
};
if (headers) {
init.headers = headers;
diff --git a/kernel/api/lute.go b/kernel/api/lute.go
index 7515da7a58..9d04b16a19 100644
--- a/kernel/api/lute.go
+++ b/kernel/api/lute.go
@@ -39,6 +39,9 @@ import (
// maxSpinBlockDOMBytes 限制 spinBlockDOM 输入 DOM 的最大字节数。
const maxSpinBlockDOMBytes = 1024 * 1024
+// maxHTML2BlockDOMRequestBytes 限制 html2BlockDOM 请求体的最大字节数。
+const maxHTML2BlockDOMRequestBytes int64 = 128 * 1024 * 1024
+
func copyStdMarkdown(c *gin.Context) {
ret := gulu.Ret.NewResult()
defer c.JSON(http.StatusOK, ret)
@@ -91,6 +94,7 @@ func copyStdMarkdown(c *gin.Context) {
func html2BlockDOM(c *gin.Context) {
ret := gulu.Ret.NewResult()
defer c.JSON(http.StatusOK, ret)
+ limitHTML2BlockDOMRequestBody(c, maxHTML2BlockDOMRequestBytes)
arg, ok := util.JsonArg(c, ret)
if !ok {
@@ -122,11 +126,12 @@ func html2BlockDOM(c *gin.Context) {
skipBase64Assets, _ := arg["skipBase64Assets"].(bool)
skipInlineSVGAssets, _ := arg["skipInlineSVGAssets"].(bool)
preflight, _ := arg["preflight"].(bool)
+ preparedHTML, _ := arg["preparedHTML"].(bool)
luteEngine := util.NewLute()
luteEngine.SetHTMLTag2TextMark(true)
luteEngine.SetHTML2MarkdownAttrs([]string{"alias", "memo", "bookmark", "custom-*"})
- dom, useHTML := resolveHTMLClipboardContent(luteEngine, dom, mathML, office, officeMathHTML, wps,
- convertClipboardMath, convertOfficeHTMLClipboardMath)
+ dom, useHTML := prepareHTMLClipboardContent(luteEngine, dom, text, mathML, office, officeMathHTML, wps,
+ preparedHTML, convertClipboardMath, convertOfficeHTMLClipboardMath)
if !useHTML {
if preflight {
ret.Data = map[string]any{"converted": true, "dom": dom, "useHTML": false}
@@ -140,16 +145,14 @@ func html2BlockDOM(c *gin.Context) {
skipBase64Assets = true
skipInlineSVGAssets = true
}
- // 将 Word 和 WPS 批注转换为行级备注 https://github.com/siyuan-note/siyuan/issues/18748
- dom = normalizeWPSComments(dom, text, wps)
- dom = normalizeMSWordComments(dom)
+ normalizedHTML := dom
tree, _ := model.HTML2TreeWithOptions(dom, luteEngine, boxID, model.HTML2TreeOptions{
SkipBase64Assets: skipBase64Assets,
SkipInlineSVGAssets: skipInlineSVGAssets,
})
if nil == tree {
if preflight {
- ret.Data = map[string]any{"converted": false, "dom": "Failed to convert", "useHTML": true}
+ ret.Data = map[string]any{"converted": false, "dom": "Failed to convert", "normalizedHTML": normalizedHTML, "useHTML": true}
} else {
ret.Data = "Failed to convert"
}
@@ -269,7 +272,7 @@ func html2BlockDOM(c *gin.Context) {
md, err := lute.FormatNodeSync(tree.Root, luteEngine.ParseOptions, luteEngine.RenderOptions)
if nil != err {
if preflight {
- ret.Data = map[string]any{"converted": false, "dom": "Failed to convert", "useHTML": true}
+ ret.Data = map[string]any{"converted": false, "dom": "Failed to convert", "normalizedHTML": normalizedHTML, "useHTML": true}
} else {
ret.Data = "Failed to convert"
}
@@ -281,15 +284,35 @@ func html2BlockDOM(c *gin.Context) {
output := renderer.Render()
convertedDOM := gulu.Str.FromBytes(output)
if preflight {
- ret.Data = map[string]any{"converted": true, "dom": convertedDOM, "useHTML": true}
+ ret.Data = map[string]any{"converted": true, "dom": convertedDOM, "normalizedHTML": normalizedHTML, "useHTML": true}
} else {
ret.Data = convertedDOM
}
}
+func limitHTML2BlockDOMRequestBody(c *gin.Context, maxBytes int64) {
+ c.Request.Body = http.MaxBytesReader(c.Writer, c.Request.Body, maxBytes)
+}
+
type clipboardMathConverter func(mathML, office, wps string) (markdown string, converted bool)
type officeHTMLClipboardMathConverter func(officeMathHTML string) (markdown string, converted bool)
+func prepareHTMLClipboardContent(luteEngine *lute.Lute, dom, text, mathML, office, officeMathHTML, wps string,
+ preparedHTML bool, mathConverter clipboardMathConverter,
+ officeHTMLMathConverter officeHTMLClipboardMathConverter) (resolvedDOM string, useHTML bool) {
+ if preparedHTML {
+ return dom, true
+ }
+ resolvedDOM, useHTML = resolveHTMLClipboardContent(luteEngine, dom, mathML, office, officeMathHTML, wps,
+ mathConverter, officeHTMLMathConverter)
+ if !useHTML {
+ return resolvedDOM, false
+ }
+ // 将 Word 和 WPS 批注转换为行级备注 https://github.com/siyuan-note/siyuan/issues/18748
+ resolvedDOM = normalizeWPSComments(resolvedDOM, text, wps)
+ return normalizeMSWordComments(resolvedDOM), true
+}
+
func resolveHTMLClipboardContent(luteEngine *lute.Lute, dom, mathML, office, officeMathHTML, wps string,
mathConverter clipboardMathConverter, officeHTMLMathConverter officeHTMLClipboardMathConverter) (resolvedDOM string, useHTML bool) {
// 将 Word 和 WPS 公式转换为可编辑公式 https://github.com/siyuan-note/siyuan/issues/18747
diff --git a/kernel/api/lute_clipboard_math_test.go b/kernel/api/lute_clipboard_math_test.go
index 96fb779019..b039de3ed5 100644
--- a/kernel/api/lute_clipboard_math_test.go
+++ b/kernel/api/lute_clipboard_math_test.go
@@ -89,6 +89,30 @@ func TestResolveHTMLClipboardContentBeforeAssetProcessing(t *testing.T) {
}
}
+func TestPrepareHTMLClipboardContentFreezesNormalizedHTML(t *testing.T) {
+ htmlWithCommentImage := `<p>kept</p><div style="mso-element:comment-list"><p class="MsoCommentText">` +
+ `<img src="data:image/png;base64,removed"></p></div>`
+ noMath := func(string, string, string) (string, bool) { return "", false }
+ noOfficeMath := func(string) (string, bool) { return "", false }
+ normalizedHTML, useHTML := prepareHTMLClipboardContent(util.NewLute(), htmlWithCommentImage, "", "", "", "", "",
+ false, noMath, noOfficeMath)
+ if !useHTML || !strings.Contains(normalizedHTML, "kept") || strings.Contains(normalizedHTML, "data:image") {
+ t.Fatalf("unexpected normalized HTML: useHTML=%v dom=%q", useHTML, normalizedHTML)
+ }
+
+ preparedHTML, useHTML := prepareHTMLClipboardContent(util.NewLute(), normalizedHTML, "", "ignored", "", "", "",
+ true, func(string, string, string) (string, bool) {
+ t.Fatal("prepared HTML should not run clipboard math conversion")
+ return "", false
+ }, func(string) (string, bool) {
+ t.Fatal("prepared HTML should not run Office HTML math conversion")
+ return "", false
+ })
+ if !useHTML || preparedHTML != normalizedHTML {
+ t.Fatalf("prepared HTML changed: useHTML=%v dom=%q", useHTML, preparedHTML)
+ }
+}
+
func TestConvertClipboardMathMixedWPS(t *testing.T) {
wps := buildWPSClipboard(t, `<w:document xmlns:w="urn:w" xmlns:m="urn:m"><w:body><m:oMath/></w:body></w:document>`, "")
pandocJSON := `{"pandoc-api-version":[1,23,1,2],"meta":{},"blocks":[{"t":"Para","c":[{"t":"Str","c":"123"}]},{"t":"Para","c":[{"t":"Math","c":[{"t":"DisplayMath"},"\\frac{S}{N}"]}]},{"t":"Para","c":[{"t":"Str","c":"456"}]}]}`
diff --git a/kernel/api/lute_request_limit_test.go b/kernel/api/lute_request_limit_test.go
new file mode 100644
index 0000000000..0526a6ba4b
--- /dev/null
+++ b/kernel/api/lute_request_limit_test.go
@@ -0,0 +1,41 @@
+// SiYuan - From thought to insight, with agents
+// Copyright (c) 2020-present, b3log.org
+//
+// This program is free software: you can redistribute it and/or modify
+// it under the terms of the GNU Affero General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// This program is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU Affero General Public License for more details.
+//
+// You should have received a copy of the GNU Affero General Public License
+// along with this program. If not, see <https://www.gnu.org/licenses/>.
+
+package api
+
+import (
+ "errors"
+ "io"
+ "net/http"
+ "net/http/httptest"
+ "strings"
+ "testing"
+
+ "github.com/gin-gonic/gin"
+)
+
+func TestLimitHTML2BlockDOMRequestBody(t *testing.T) {
+ gin.SetMode(gin.TestMode)
+ context, _ := gin.CreateTestContext(httptest.NewRecorder())
+ context.Request = httptest.NewRequest(http.MethodPost, "/api/lute/html2BlockDOM", strings.NewReader("12345"))
+ limitHTML2BlockDOMRequestBody(context, 4)
+
+ _, err := io.ReadAll(context.Request.Body)
+ var limitError *http.MaxBytesError
+ if !errors.As(err, &limitError) || limitError.Limit != 4 {
+ t.Fatalf("unexpected request body limit error: %v", err)
+ }
+}