Skip to content

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

:bug: Harden HTML asset paste boundaries https://github.com/siyuan-note/siyuan/issues/18878

Daniel8d31ca36e1b9
diff --git a/app/src/protyle/upload/htmlEmbeddedAssets.test.ts b/app/src/protyle/upload/htmlEmbeddedAssets.test.ts
index d0b106c1f7..1a89fc6ed0 100644
--- a/app/src/protyle/upload/htmlEmbeddedAssets.test.ts
+++ b/app/src/protyle/upload/htmlEmbeddedAssets.test.ts
@@ -185,6 +185,29 @@ describe("HTML embedded assets", () => {
assert.equal(hasHTMLEmbeddedAssets(root), true);
});
+ it("counts inline SVG bytes against the item limit", () => {
+ const svgHTML = "<svg><text>inline image</text></svg>";
+ const block = {
+ hasAttributes() {
+ return true;
+ },
+ querySelector() {
+ return {outerHTML: svgHTML};
+ },
+ } as unknown as Element;
+ const root = {
+ querySelectorAll(selector: string) {
+ return selector === "pre" ? [block] : [];
+ },
+ } as unknown as ParentNode;
+ const size = new Blob([svgHTML]).size;
+
+ assert.throws(() => validateHTMLEmbeddedAssetSizes(root, size - 1),
+ (error: unknown) => isBase64ImageSizeLimitError(error) && error.scope === "item" &&
+ error.actualBytes === size && error.maxBytes === size - 1);
+ assert.doesNotThrow(() => validateHTMLEmbeddedAssetSizes(root, size));
+ });
+
it("collects inline SVG blocks and replaces them with uploaded images", () => {
const attributes = new Map<string, string>();
const image = {
diff --git a/app/src/protyle/upload/htmlEmbeddedAssets.ts b/app/src/protyle/upload/htmlEmbeddedAssets.ts
index a4614201bb..8923cf83d1 100644
--- a/app/src/protyle/upload/htmlEmbeddedAssets.ts
+++ b/app/src/protyle/upload/htmlEmbeddedAssets.ts
@@ -29,6 +29,12 @@ const getInlineSVGBlocks = (root: ParentNode) => new Set(Array.from(root.querySe
export const validateHTMLEmbeddedAssetSizes = (root: ParentNode, maxBytes?: number) => {
const svgBlocks = getInlineSVGBlocks(root);
let totalBytes = 0;
+ svgBlocks.forEach(element => {
+ const svg = element.querySelector("svg")!;
+ const size = new Blob([svg.outerHTML]).size;
+ assertBase64ImageItemSize(size, maxBytes);
+ totalBytes = addBase64ImageBatchSize(totalBytes, size);
+ });
root.querySelectorAll("[href], [src]").forEach(element => {
if (Array.from(svgBlocks).some(block => block.contains(element))) {
return;
diff --git a/app/src/protyle/upload/pluginEvent.test.ts b/app/src/protyle/upload/pluginEvent.test.ts
index baf1b3a3d1..d5f7d63061 100644
--- a/app/src/protyle/upload/pluginEvent.test.ts
+++ b/app/src/protyle/upload/pluginEvent.test.ts
@@ -107,6 +107,47 @@ describe("asset upload plugin event", () => {
second.task.complete({status: "canceled"});
});
+ it("generates a request identifier without crypto.randomUUID", () => {
+ const cryptoDescriptor = Object.getOwnPropertyDescriptor(globalThis, "crypto");
+ const windowDescriptor = Object.getOwnPropertyDescriptor(globalThis, "window");
+ const nativeCrypto = globalThis.crypto;
+ const insecureCrypto = {
+ getRandomValues: nativeCrypto.getRandomValues.bind(nativeCrypto),
+ } as unknown as Crypto;
+ try {
+ Object.defineProperty(globalThis, "crypto", {configurable: true, value: insecureCrypto});
+ Object.defineProperty(globalThis, "window", {
+ configurable: true,
+ value: {crypto: insecureCrypto},
+ });
+ const prepared = prepareAssetUpload({
+ plugins: [],
+ protyle,
+ input: {kind: "files", files: [createFile("a.png")]},
+ context,
+ });
+
+ if (prepared instanceof Promise) {
+ assert.fail("Expected plugin-free preparation to complete synchronously");
+ }
+ assert.equal(prepared.state, "ready");
+ assert.match(prepared.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);
+ prepared.task.complete({status: "canceled"});
+ } finally {
+ if (cryptoDescriptor) {
+ Object.defineProperty(globalThis, "crypto", cryptoDescriptor);
+ } else {
+ Reflect.deleteProperty(globalThis, "crypto");
+ }
+ if (windowDescriptor) {
+ Object.defineProperty(globalThis, "window", windowDescriptor);
+ } else {
+ Reflect.deleteProperty(globalThis, "window");
+ }
+ }
+ });
+
it("isolates local file input from listener mutations", async () => {
const originalFile: ILocalFiles = {path: "a.png", size: 1};
const prepared = await prepareAssetUpload({
diff --git a/app/src/protyle/upload/pluginEvent.ts b/app/src/protyle/upload/pluginEvent.ts
index 68322107a9..63910c4621 100644
--- a/app/src/protyle/upload/pluginEvent.ts
+++ b/app/src/protyle/upload/pluginEvent.ts
@@ -1,5 +1,6 @@
import type {EventBus, IEventBusSafeEmitResult} from "../../plugin/EventBusCore";
import {emitWithErrors, eventBusHas, hasPluginSubscriber} from "../../plugin/EventBusCore";
+import {genUUID} from "../../util/genID";
export interface IAssetUploadEventContext {
source: TAssetUploadSource;
@@ -46,7 +47,8 @@ const activeTasksByProtyle = new WeakMap<IProtyle, Set<AssetUploadTask>>();
const completionTasksByPlugin = new WeakMap<IAssetUploadPlugin, Set<AssetUploadTask>>();
const unloadingPlugins = new WeakSet<IAssetUploadPlugin>();
-const genRequestId = () => crypto.randomUUID();
+const genRequestId = () => typeof globalThis.crypto.randomUUID === "function" ?
+ globalThis.crypto.randomUUID() : genUUID();
const cloneInput = (input: IAssetUploadInput): IAssetUploadInput => {
if (input.kind === "files") {
diff --git a/app/src/protyle/util/paste.ts b/app/src/protyle/util/paste.ts
index efe158ef93..ba3be70870 100644
--- a/app/src/protyle/util/paste.ts
+++ b/app/src/protyle/util/paste.ts
@@ -1191,11 +1191,15 @@ export const paste = async (protyle: IProtyle, event: (ClipboardEvent | DragEven
useHTML?: unknown,
};
if (preflightResponse?.code !== 0 || preflight?.converted !== true ||
- typeof preflight.useHTML !== "boolean" || typeof preflight.dom !== "string") {
+ typeof preflight.useHTML !== "boolean") {
showMessage(window.siyuan.languages.uploadError);
return;
}
if (!preflight.useHTML) {
+ if (typeof preflight.dom !== "string") {
+ showMessage(window.siyuan.languages.uploadError);
+ return;
+ }
insertConvertedBlockDOM(protyle, preflight.dom, range);
return;
}
@@ -1248,6 +1252,8 @@ export const paste = async (protyle: IProtyle, event: (ClipboardEvent | DragEven
}
}
let conversionResponse: IWebSocketData;
+ const controller = new AbortController();
+ const timeoutId = setTimeout(() => controller.abort(), PASTE_PLUGIN_TIMEOUT);
try {
conversionResponse = await fetchSyncPost("/api/lute/html2BlockDOM", {
...conversionContext,
@@ -1256,13 +1262,15 @@ export const paste = async (protyle: IProtyle, event: (ClipboardEvent | DragEven
skipLocalAssets: localAssets.length > 0,
skipBase64Assets: true,
skipInlineSVGAssets: 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) {
diff --git a/kernel/api/lute.go b/kernel/api/lute.go
index 9d04b16a19..d8d91c038b 100644
--- a/kernel/api/lute.go
+++ b/kernel/api/lute.go
@@ -282,11 +282,10 @@ func html2BlockDOM(c *gin.Context) {
tree = parse.Parse("", []byte(md), luteEngine.ParseOptions)
renderer := render.NewProtyleRenderer(tree, luteEngine.RenderOptions, luteEngine.ParseOptions)
output := renderer.Render()
- convertedDOM := gulu.Str.FromBytes(output)
if preflight {
- ret.Data = map[string]any{"converted": true, "dom": convertedDOM, "normalizedHTML": normalizedHTML, "useHTML": true}
+ ret.Data = map[string]any{"converted": true, "normalizedHTML": normalizedHTML, "useHTML": true}
} else {
- ret.Data = convertedDOM
+ ret.Data = gulu.Str.FromBytes(output)
}
}
diff --git a/kernel/api/lute_request_limit_test.go b/kernel/api/lute_request_limit_test.go
index 0526a6ba4b..e1c699cf39 100644
--- a/kernel/api/lute_request_limit_test.go
+++ b/kernel/api/lute_request_limit_test.go
@@ -17,6 +17,7 @@
package api
import (
+ "encoding/json"
"errors"
"io"
"net/http"
@@ -25,6 +26,8 @@ import (
"testing"
"github.com/gin-gonic/gin"
+ "github.com/siyuan-note/siyuan/kernel/conf"
+ "github.com/siyuan-note/siyuan/kernel/model"
)
func TestLimitHTML2BlockDOMRequestBody(t *testing.T) {
@@ -39,3 +42,36 @@ func TestLimitHTML2BlockDOMRequestBody(t *testing.T) {
t.Fatalf("unexpected request body limit error: %v", err)
}
}
+
+func TestHTML2BlockDOMPreflightOmitsConvertedDOM(t *testing.T) {
+ originalConf := model.Conf
+ model.Conf = model.NewAppConf()
+ model.Conf.System = &conf.System{}
+ t.Cleanup(func() { model.Conf = originalConf })
+
+ gin.SetMode(gin.TestMode)
+ recorder := httptest.NewRecorder()
+ context, _ := gin.CreateTestContext(recorder)
+ context.Request = httptest.NewRequest(http.MethodPost, "/api/lute/html2BlockDOM",
+ strings.NewReader(`{"dom":"<p>kept</p>","preflight":true}`))
+ context.Request.Header.Set("Content-Type", "application/json")
+
+ html2BlockDOM(context)
+
+ response := struct {
+ Code int `json:"code"`
+ Data map[string]any `json:"data"`
+ }{}
+ if err := json.Unmarshal(recorder.Body.Bytes(), &response); err != nil {
+ t.Fatal(err)
+ }
+ if response.Code != 0 || response.Data["converted"] != true || response.Data["useHTML"] != true {
+ t.Fatalf("unexpected preflight response: %s", recorder.Body.String())
+ }
+ if response.Data["normalizedHTML"] != "<p>kept</p>" {
+ t.Fatalf("unexpected normalized HTML: %v", response.Data["normalizedHTML"])
+ }
+ if _, ok := response.Data["dom"]; ok {
+ t.Fatalf("preflight response contains converted DOM: %s", recorder.Body.String())
+ }
+}