Skip to content

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

:sparkles: Support embedding HTML files as IFrame blocks https://github.com/siyuan-note/siyuan/issues/18127

Daniel82ef7048823e
diff --git a/app/appearance/langs/ar.json b/app/appearance/langs/ar.json
index 0e5e6528dd..ad7b42da5f 100644
--- a/app/appearance/langs/ar.json
+++ b/app/appearance/langs/ar.json
@@ -1,4 +1,7 @@
{
+ "insertHTMLFile": "تضمين ملف HTML",
+ "dragHTMLFileToIframe": "تضمين ملفات HTML المسحوبة",
+ "dragHTMLFileToIframeTip": "تضمين ملفات HTML ككتل IFrame عند سحبها إلى المحرر",
"bazaarPackageInvalid": "غير صالح",
"bazaarPackageMissingManifest": "ملف بيان حزمة السوق مفقود",
"bazaarPackageInvalidManifest": "ملف بيان حزمة السوق غير صالح",
diff --git a/app/appearance/langs/de.json b/app/appearance/langs/de.json
index 26dc87a89e..91a151b775 100644
--- a/app/appearance/langs/de.json
+++ b/app/appearance/langs/de.json
@@ -1,4 +1,7 @@
{
+ "insertHTMLFile": "HTML-Datei einbetten",
+ "dragHTMLFileToIframe": "Gezogene HTML-Dateien einbetten",
+ "dragHTMLFileToIframeTip": "HTML-Dateien beim Ziehen in den Editor als IFrame-Blöcke einbetten",
"bazaarPackageInvalid": "Ungültig",
"bazaarPackageMissingManifest": "Die Manifestdatei des Marktplatzpakets fehlt",
"bazaarPackageInvalidManifest": "Die Manifestdatei des Marktplatzpakets ist ungültig",
diff --git a/app/appearance/langs/en.json b/app/appearance/langs/en.json
index 26e4bdbab6..6eb62ccebf 100644
--- a/app/appearance/langs/en.json
+++ b/app/appearance/langs/en.json
@@ -1,4 +1,7 @@
{
+ "insertHTMLFile": "Embed HTML file",
+ "dragHTMLFileToIframe": "Embed dragged HTML files",
+ "dragHTMLFileToIframeTip": "Embed HTML files as IFrame blocks when dragging them into the editor",
"bazaarPackageInvalid": "Invalid",
"bazaarPackageMissingManifest": "The marketplace package manifest is missing",
"bazaarPackageInvalidManifest": "The marketplace package manifest is invalid",
diff --git a/app/appearance/langs/es.json b/app/appearance/langs/es.json
index 44ecf669f1..9bb616e6a9 100644
--- a/app/appearance/langs/es.json
+++ b/app/appearance/langs/es.json
@@ -1,4 +1,7 @@
{
+ "insertHTMLFile": "Incrustar archivo HTML",
+ "dragHTMLFileToIframe": "Incrustar archivos HTML arrastrados",
+ "dragHTMLFileToIframeTip": "Incrustar archivos HTML como bloques IFrame al arrastrarlos al editor",
"bazaarPackageInvalid": "No válido",
"bazaarPackageMissingManifest": "Falta el archivo de manifiesto del paquete del mercado",
"bazaarPackageInvalidManifest": "El archivo de manifiesto del paquete del mercado no es válido",
diff --git a/app/appearance/langs/fr.json b/app/appearance/langs/fr.json
index e157aadf2d..32c2f01162 100644
--- a/app/appearance/langs/fr.json
+++ b/app/appearance/langs/fr.json
@@ -1,4 +1,7 @@
{
+ "insertHTMLFile": "Intégrer un fichier HTML",
+ "dragHTMLFileToIframe": "Intégrer les fichiers HTML déposés",
+ "dragHTMLFileToIframeTip": "Intégrer les fichiers HTML en tant que blocs IFrame lors de leur dépôt dans l’éditeur",
"bazaarPackageInvalid": "Non valide",
"bazaarPackageMissingManifest": "Le fichier manifeste du paquet de la place de marché est manquant",
"bazaarPackageInvalidManifest": "Le fichier manifeste du paquet de la place de marché n'est pas valide",
diff --git a/app/appearance/langs/he.json b/app/appearance/langs/he.json
index e7e8b16ec3..3ddbe0eeba 100644
--- a/app/appearance/langs/he.json
+++ b/app/appearance/langs/he.json
@@ -1,4 +1,7 @@
{
+ "insertHTMLFile": "הטמעת קובץ HTML",
+ "dragHTMLFileToIframe": "הטמעת קובצי HTML שנגררו",
+ "dragHTMLFileToIframeTip": "הטמעת קובצי HTML כבלוקי IFrame בעת גרירתם לעורך",
"bazaarPackageInvalid": "לא תקין",
"bazaarPackageMissingManifest": "קובץ המניפסט של חבילת השוק חסר",
"bazaarPackageInvalidManifest": "קובץ המניפסט של חבילת השוק אינו תקין",
diff --git a/app/appearance/langs/hi.json b/app/appearance/langs/hi.json
index ebf19aea6c..9dce9ca77f 100644
--- a/app/appearance/langs/hi.json
+++ b/app/appearance/langs/hi.json
@@ -1,4 +1,7 @@
{
+ "insertHTMLFile": "HTML फ़ाइल एम्बेड करें",
+ "dragHTMLFileToIframe": "खींची गई HTML फ़ाइलें एम्बेड करें",
+ "dragHTMLFileToIframeTip": "HTML फ़ाइलों को संपादक में खींचते समय IFrame ब्लॉक के रूप में एम्बेड करें",
"bazaarPackageInvalid": "अमान्य",
"bazaarPackageMissingManifest": "मार्केटप्लेस पैकेज की मैनिफेस्ट फ़ाइल मौजूद नहीं है",
"bazaarPackageInvalidManifest": "मार्केटप्लेस पैकेज की मैनिफेस्ट फ़ाइल अमान्य है",
diff --git a/app/appearance/langs/id.json b/app/appearance/langs/id.json
index 1849c150ef..1c5df9b07b 100644
--- a/app/appearance/langs/id.json
+++ b/app/appearance/langs/id.json
@@ -1,4 +1,7 @@
{
+ "insertHTMLFile": "Sematkan berkas HTML",
+ "dragHTMLFileToIframe": "Sematkan berkas HTML yang diseret",
+ "dragHTMLFileToIframeTip": "Sematkan berkas HTML sebagai blok IFrame saat diseret ke editor",
"bazaarPackageInvalid": "Tidak valid",
"bazaarPackageMissingManifest": "Berkas manifes paket marketplace tidak ditemukan",
"bazaarPackageInvalidManifest": "Berkas manifes paket marketplace tidak valid",
diff --git a/app/appearance/langs/it.json b/app/appearance/langs/it.json
index 4e34033e4b..b9ef45edd0 100644
--- a/app/appearance/langs/it.json
+++ b/app/appearance/langs/it.json
@@ -1,4 +1,7 @@
{
+ "insertHTMLFile": "Incorpora file HTML",
+ "dragHTMLFileToIframe": "Incorpora i file HTML trascinati",
+ "dragHTMLFileToIframeTip": "Incorpora i file HTML come blocchi IFrame quando vengono trascinati nell’editor",
"bazaarPackageInvalid": "Non valido",
"bazaarPackageMissingManifest": "Il file manifest del pacchetto del marketplace è mancante",
"bazaarPackageInvalidManifest": "Il file manifest del pacchetto del marketplace non è valido",
diff --git a/app/appearance/langs/ja.json b/app/appearance/langs/ja.json
index bba5d092cf..bec88bf9b0 100644
--- a/app/appearance/langs/ja.json
+++ b/app/appearance/langs/ja.json
@@ -1,4 +1,7 @@
{
+ "insertHTMLFile": "HTML ファイルを埋め込む",
+ "dragHTMLFileToIframe": "ドラッグした HTML ファイルを埋め込む",
+ "dragHTMLFileToIframeTip": "HTML ファイルをエディターにドラッグしたときに IFrame ブロックとして埋め込む",
"bazaarPackageInvalid": "異常",
"bazaarPackageMissingManifest": "マーケットプレイスパッケージのマニフェストファイルがありません",
"bazaarPackageInvalidManifest": "マーケットプレイスパッケージのマニフェストファイルが無効です",
diff --git a/app/appearance/langs/ko.json b/app/appearance/langs/ko.json
index 33680f255b..41c4a95765 100644
--- a/app/appearance/langs/ko.json
+++ b/app/appearance/langs/ko.json
@@ -1,4 +1,7 @@
{
+ "insertHTMLFile": "HTML 파일 임베드",
+ "dragHTMLFileToIframe": "드래그한 HTML 파일 임베드",
+ "dragHTMLFileToIframeTip": "HTML 파일을 편집기로 드래그할 때 IFrame 블록으로 임베드",
"bazaarPackageInvalid": "비정상",
"bazaarPackageMissingManifest": "마켓플레이스 패키지 매니페스트 파일이 없습니다",
"bazaarPackageInvalidManifest": "마켓플레이스 패키지 매니페스트 파일이 올바르지 않습니다",
diff --git a/app/appearance/langs/nl.json b/app/appearance/langs/nl.json
index d425c50b2d..eb3cd9f4a7 100644
--- a/app/appearance/langs/nl.json
+++ b/app/appearance/langs/nl.json
@@ -1,4 +1,7 @@
{
+ "insertHTMLFile": "HTML-bestand insluiten",
+ "dragHTMLFileToIframe": "Gesleepte HTML-bestanden insluiten",
+ "dragHTMLFileToIframeTip": "HTML-bestanden als IFrame-blokken insluiten wanneer ze naar de editor worden gesleept",
"bazaarPackageInvalid": "Ongeldig",
"bazaarPackageMissingManifest": "Het manifestbestand van het marktplaatspakket ontbreekt",
"bazaarPackageInvalidManifest": "Het manifestbestand van het marktplaatspakket is ongeldig",
diff --git a/app/appearance/langs/pl.json b/app/appearance/langs/pl.json
index 2c851f24f0..e1f19cb732 100644
--- a/app/appearance/langs/pl.json
+++ b/app/appearance/langs/pl.json
@@ -1,4 +1,7 @@
{
+ "insertHTMLFile": "Osadź plik HTML",
+ "dragHTMLFileToIframe": "Osadzaj przeciągane pliki HTML",
+ "dragHTMLFileToIframeTip": "Osadzaj pliki HTML jako bloki IFrame podczas przeciągania ich do edytora",
"bazaarPackageInvalid": "Nieprawidłowy",
"bazaarPackageMissingManifest": "Brakuje pliku manifestu pakietu z rynku",
"bazaarPackageInvalidManifest": "Plik manifestu pakietu z rynku jest nieprawidłowy",
diff --git a/app/appearance/langs/pt-BR.json b/app/appearance/langs/pt-BR.json
index 7229faf56c..d683353321 100644
--- a/app/appearance/langs/pt-BR.json
+++ b/app/appearance/langs/pt-BR.json
@@ -1,4 +1,7 @@
{
+ "insertHTMLFile": "Incorporar arquivo HTML",
+ "dragHTMLFileToIframe": "Incorporar arquivos HTML arrastados",
+ "dragHTMLFileToIframeTip": "Incorporar arquivos HTML como blocos IFrame ao arrastá-los para o editor",
"bazaarPackageInvalid": "Inválido",
"bazaarPackageMissingManifest": "O arquivo de manifesto do pacote do marketplace está ausente",
"bazaarPackageInvalidManifest": "O arquivo de manifesto do pacote do marketplace é inválido",
diff --git a/app/appearance/langs/ru.json b/app/appearance/langs/ru.json
index 99c8d11cfb..b5ab965700 100644
--- a/app/appearance/langs/ru.json
+++ b/app/appearance/langs/ru.json
@@ -1,4 +1,7 @@
{
+ "insertHTMLFile": "Встроить HTML-файл",
+ "dragHTMLFileToIframe": "Встраивать перетаскиваемые HTML-файлы",
+ "dragHTMLFileToIframeTip": "Встраивать HTML-файлы как блоки IFrame при перетаскивании в редактор",
"bazaarPackageInvalid": "Недопустимый",
"bazaarPackageMissingManifest": "Файл манифеста пакета торговой площадки отсутствует",
"bazaarPackageInvalidManifest": "Файл манифеста пакета торговой площадки недопустим",
diff --git a/app/appearance/langs/sk.json b/app/appearance/langs/sk.json
index 589a5aa46e..80ae36119a 100644
--- a/app/appearance/langs/sk.json
+++ b/app/appearance/langs/sk.json
@@ -1,4 +1,7 @@
{
+ "insertHTMLFile": "Vložiť súbor HTML",
+ "dragHTMLFileToIframe": "Vkladať presunuté súbory HTML",
+ "dragHTMLFileToIframeTip": "Vkladať súbory HTML ako bloky IFrame pri ich presunutí do editora",
"bazaarPackageInvalid": "Neplatný",
"bazaarPackageMissingManifest": "Súbor manifestu balíka trhoviska chýba",
"bazaarPackageInvalidManifest": "Súbor manifestu balíka trhoviska je neplatný",
diff --git a/app/appearance/langs/th.json b/app/appearance/langs/th.json
index b78dfc5f05..ec3ef7c7b5 100644
--- a/app/appearance/langs/th.json
+++ b/app/appearance/langs/th.json
@@ -1,4 +1,7 @@
{
+ "insertHTMLFile": "ฝังไฟล์ HTML",
+ "dragHTMLFileToIframe": "ฝังไฟล์ HTML ที่ลากมา",
+ "dragHTMLFileToIframeTip": "ฝังไฟล์ HTML เป็นบล็อก IFrame เมื่อลากไฟล์เข้าสู่ตัวแก้ไข",
"bazaarPackageInvalid": "ไม่ถูกต้อง",
"bazaarPackageMissingManifest": "ไม่พบไฟล์แมนิเฟสต์ของแพ็กเกจมาร์เก็ตเพลส",
"bazaarPackageInvalidManifest": "ไฟล์แมนิเฟสต์ของแพ็กเกจมาร์เก็ตเพลสไม่ถูกต้อง",
diff --git a/app/appearance/langs/tr.json b/app/appearance/langs/tr.json
index 9f40331776..ce4433a21d 100644
--- a/app/appearance/langs/tr.json
+++ b/app/appearance/langs/tr.json
@@ -1,4 +1,7 @@
{
+ "insertHTMLFile": "HTML dosyası göm",
+ "dragHTMLFileToIframe": "Sürüklenen HTML dosyalarını göm",
+ "dragHTMLFileToIframeTip": "HTML dosyalarını düzenleyiciye sürüklerken IFrame blokları olarak göm",
"bazaarPackageInvalid": "Geçersiz",
"bazaarPackageMissingManifest": "Pazar paketi bildirim dosyası eksik",
"bazaarPackageInvalidManifest": "Pazar paketi bildirim dosyası geçersiz",
diff --git a/app/appearance/langs/uk.json b/app/appearance/langs/uk.json
index f26e631ee1..93ff476c55 100644
--- a/app/appearance/langs/uk.json
+++ b/app/appearance/langs/uk.json
@@ -1,4 +1,7 @@
{
+ "insertHTMLFile": "Вбудувати HTML-файл",
+ "dragHTMLFileToIframe": "Вбудовувати перетягнуті HTML-файли",
+ "dragHTMLFileToIframeTip": "Вбудовувати HTML-файли як блоки IFrame під час перетягування до редактора",
"bazaarPackageInvalid": "Недійсний",
"bazaarPackageMissingManifest": "Файл маніфесту пакета торгового майданчика відсутній",
"bazaarPackageInvalidManifest": "Файл маніфесту пакета торгового майданчика недійсний",
diff --git a/app/appearance/langs/zh-CN.json b/app/appearance/langs/zh-CN.json
index 6dadd336f2..d1e0e21c6c 100644
--- a/app/appearance/langs/zh-CN.json
+++ b/app/appearance/langs/zh-CN.json
@@ -1,4 +1,7 @@
{
+ "insertHTMLFile": "嵌入 HTML 文件",
+ "dragHTMLFileToIframe": "嵌入拖拽的 HTML 文件",
+ "dragHTMLFileToIframeTip": "将拖拽到编辑器中的 HTML 文件嵌入为 IFrame 块",
"bazaarPackageInvalid": "异常",
"bazaarPackageMissingManifest": "集市包元数据文件缺失",
"bazaarPackageInvalidManifest": "集市包元数据文件无效",
diff --git a/app/appearance/langs/zh-TW.json b/app/appearance/langs/zh-TW.json
index 274d6e2c45..519147ea83 100644
--- a/app/appearance/langs/zh-TW.json
+++ b/app/appearance/langs/zh-TW.json
@@ -1,4 +1,7 @@
{
+ "insertHTMLFile": "嵌入 HTML 檔案",
+ "dragHTMLFileToIframe": "嵌入拖曳的 HTML 檔案",
+ "dragHTMLFileToIframeTip": "將拖曳到編輯器中的 HTML 檔案嵌入為 IFrame 區塊",
"bazaarPackageInvalid": "異常",
"bazaarPackageMissingManifest": "集市套件中繼資料檔案缺失",
"bazaarPackageInvalidManifest": "集市套件中繼資料檔案無效",
diff --git a/app/src/asset/html.test.ts b/app/src/asset/html.test.ts
new file mode 100644
index 0000000000..59d7fc53e3
--- /dev/null
+++ b/app/src/asset/html.test.ts
@@ -0,0 +1,18 @@
+import * as assert from "node:assert/strict";
+import test from "node:test";
+import {getHTMLAssetIFrameSrc, isHTMLFilePath} from "./html";
+
+test("recognizes supported HTML file paths", () => {
+ assert.equal(isHTMLFilePath("component.html"), true);
+ assert.equal(isHTMLFilePath("component.HTM?box=20260810000000-abcdefg"), true);
+ assert.equal(isHTMLFilePath("component.xhtml"), false);
+ assert.equal(isHTMLFilePath("component.js"), false);
+});
+
+test("adds the HTML IFrame query without losing existing parameters", () => {
+ assert.equal(getHTMLAssetIFrameSrc("assets/component.html"), "assets/component.html?iframe=true");
+ assert.equal(getHTMLAssetIFrameSrc("assets/component.html?box=20260810000000-abcdefg"),
+ "assets/component.html?box=20260810000000-abcdefg&iframe=true");
+ assert.equal(getHTMLAssetIFrameSrc("assets/component.html?iframe=false#preview"),
+ "assets/component.html?iframe=true#preview");
+});
diff --git a/app/src/asset/html.ts b/app/src/asset/html.ts
new file mode 100644
index 0000000000..ace9d4ac6c
--- /dev/null
+++ b/app/src/asset/html.ts
@@ -0,0 +1,15 @@
+export const isHTMLFilePath = (value: string) => {
+ const path = value.split(/[?#]/, 1)[0].toLowerCase();
+ return path.endsWith(".html") || path.endsWith(".htm");
+};
+
+export const getHTMLAssetIFrameSrc = (assetPath: string) => {
+ const hashIndex = assetPath.indexOf("#");
+ const hash = hashIndex > -1 ? assetPath.substring(hashIndex) : "";
+ const pathAndQuery = hashIndex > -1 ? assetPath.substring(0, hashIndex) : assetPath;
+ const queryIndex = pathAndQuery.indexOf("?");
+ const path = queryIndex > -1 ? pathAndQuery.substring(0, queryIndex) : pathAndQuery;
+ const params = new URLSearchParams(queryIndex > -1 ? pathAndQuery.substring(queryIndex + 1) : "");
+ params.set("iframe", "true");
+ return `${path}?${params.toString()}${hash}`;
+};
diff --git a/app/src/asset/renderAssets.ts b/app/src/asset/renderAssets.ts
index 3582feb225..1a96bc267d 100644
--- a/app/src/asset/renderAssets.ts
+++ b/app/src/asset/renderAssets.ts
@@ -4,6 +4,8 @@ import {getAllModels} from "../layout/getAll";
/// #endif
import {getAssetExtension} from "../util/pathName";
import * as dayjs from "dayjs";
+import {escapeAttr} from "../util/escape";
+import {getHTMLAssetIFrameSrc, isHTMLFilePath} from "./html";
export const renderAssetsPreview = (pathString: string) => {
if (!pathString) {
@@ -59,9 +61,12 @@ export const pdfResize = () => {
/// #endif
};
-export const genAssetHTML = (type: string, pathString: string, imgName: string, linkName: string) => {
+export const genAssetHTML = (type: string, pathString: string, imgName: string, linkName: string, htmlAsIframe = false) => {
let html = "";
- if (Constants.SIYUAN_ASSETS_AUDIO.includes(type)) {
+ if (htmlAsIframe && isHTMLFilePath(linkName)) {
+ const iframeSrc = escapeAttr(getHTMLAssetIFrameSrc(pathString));
+ html = `<div data-node-id="${Lute.NewNodeID()}" data-type="NodeIFrame" class="iframe" updated="${dayjs().format("YYYYMMDDHHmmss")}"><div class="iframe-content">${Constants.ZWSP}<iframe sandbox="allow-scripts" src="${iframeSrc}" border="0" frameborder="no" framespacing="0" allowfullscreen="true"></iframe><span class="protyle-action__drag" contenteditable="false"></span></div><div class="protyle-attr" contenteditable="false">${Constants.ZWSP}</div></div>`;
+ } else if (Constants.SIYUAN_ASSETS_AUDIO.includes(type)) {
html = `<div data-node-id="${Lute.NewNodeID()}" data-type="NodeAudio" class="iframe" updated="${dayjs().format("YYYYMMDDHHmmss")}"><div class="iframe-content"><audio controls="controls" src="${pathString}"></audio>${Constants.ZWSP}</div><div class="protyle-attr" contenteditable="false">${Constants.ZWSP}</div></div>`;
} else if (Constants.SIYUAN_ASSETS_IMAGE.includes(type)) {
let netHTML = "";
diff --git a/app/src/config/entryVisibility/catalog.test.ts b/app/src/config/entryVisibility/catalog.test.ts
index 096ecbc005..53f3fff233 100644
--- a/app/src/config/entryVisibility/catalog.test.ts
+++ b/app/src/config/entryVisibility/catalog.test.ts
@@ -134,6 +134,14 @@ test("document loading actions follow the document menu order", () => {
assert.equal(children[loadAllIndex + 2]?.key, "separator_1");
});
+test("HTML file insertion follows general asset insertion", () => {
+ const children = getEntryCatalogChildren("document.more");
+ const insertAssetIndex = children.findIndex((item) => item.key === "insertAsset");
+
+ assert.ok(0 <= insertAssetIndex);
+ assert.equal(children[insertAssetIndex + 1]?.key, "insertHTMLFile");
+});
+
test("simple profile follows the reviewed defaults", () => {
const shown = [
"document.title.copy.copyBlockEmbed",
diff --git a/app/src/config/entryVisibility/catalog.ts b/app/src/config/entryVisibility/catalog.ts
index d8291bc616..f0284de330 100644
--- a/app/src/config/entryVisibility/catalog.ts
+++ b/app/src/config/entryVisibility/catalog.ts
@@ -493,6 +493,7 @@ export const entryCatalog: IEntryCatalogSection[] = [
children: [
node("insertImage", lang("insertImage")),
node("insertAsset", lang("insertAsset")),
+ node("insertHTMLFile", lang("insertHTMLFile")),
node("startRecord", lang("startRecord"), false),
node("endRecord", lang("endRecord"), false),
node("netImg2LocalAsset", lang("netImg2LocalAsset")),
diff --git a/app/src/config/tabs/editorTab.ts b/app/src/config/tabs/editorTab.ts
index f8ccc7165b..68f2f9fdf5 100644
--- a/app/src/config/tabs/editorTab.ts
+++ b/app/src/config/tabs/editorTab.ts
@@ -332,6 +332,10 @@ const registerEditorAdvancedGroup = (tab: SettingTabBuilder) => {
desc: window.siyuan.languages.katexMacrosTip,
mode: "textarea",
});
+ group.switch("editor.dragHTMLFileToIframe", {
+ title: window.siyuan.languages.dragHTMLFileToIframe,
+ desc: window.siyuan.languages.dragHTMLFileToIframeTip,
+ });
group.switch("editor.allowSVGScript", {
title: window.siyuan.languages.allowSVGScript,
desc: window.siyuan.languages.allowSVGScriptTip,
diff --git a/app/src/protyle/breadcrumb/index.ts b/app/src/protyle/breadcrumb/index.ts
index 29221eb7ab..688d4bf259 100644
--- a/app/src/protyle/breadcrumb/index.ts
+++ b/app/src/protyle/breadcrumb/index.ts
@@ -687,6 +687,21 @@ ${padHTML}
window.siyuan.menus.menu.remove();
});
window.siyuan.menus.menu.append(uploadMenu);
+ const htmlUploadMenu = new MenuItem({
+ id: "insertHTMLFile",
+ icon: "iconHTML5",
+ label: `${window.siyuan.languages.insertHTMLFile}<input class="b3-form__upload" type="file" multiple="multiple" accept=".html,.htm">`,
+ }).element;
+ htmlUploadMenu.querySelector("input").addEventListener("change", (event: InputEvent & {
+ target: HTMLInputElement
+ }) => {
+ if (event.target.files.length === 0) {
+ return;
+ }
+ uploadFiles(protyle, event.target.files, event.target, undefined, undefined, {htmlAsIframe: true});
+ window.siyuan.menus.menu.remove();
+ });
+ window.siyuan.menus.menu.append(htmlUploadMenu);
window.siyuan.menus.menu.append(new MenuItem({
id: this.mediaRecorder?.isRecording ? "endRecord" : "startRecord",
current: this.mediaRecorder && this.mediaRecorder.isRecording,
diff --git a/app/src/protyle/hint/extend.ts b/app/src/protyle/hint/extend.ts
index ac95de7072..af9085f1c4 100644
--- a/app/src/protyle/hint/extend.ts
+++ b/app/src/protyle/hint/extend.ts
@@ -275,6 +275,12 @@ export const hintSlash = (key: string, protyle: IProtyle, sourceOrHideConfigured
value: Constants.ZWSP + 3,
html: `<div class="b3-list-item__first"><svg class="b3-list-item__graphic"><use xlink:href="#iconDownload"></use></svg><span class="b3-list-item__text">${window.siyuan.languages.insertAsset}</span>
<input class="b3-form__upload" type="file" multiple="multiple"${protyle.options.upload.accept ? ' accept="' + protyle.options.upload.accept + '"' : ""}></div>`,
+ }, {
+ filter: [window.siyuan.languages.insertHTMLFile, "embed html file", "iframe", "嵌入 html 文件", "qianruhtmlwenjian", "qrhtmlwj"],
+ id: "insertHTMLFile",
+ value: Constants.ZWSP + 3,
+ html: `<div class="b3-list-item__first"><svg class="b3-list-item__graphic"><use xlink:href="#iconHTML5"></use></svg><span class="b3-list-item__text">${window.siyuan.languages.insertHTMLFile}</span>
+<input class="b3-form__upload" data-upload-mode="html-iframe" type="file" multiple="multiple" accept=".html,.htm"></div>`,
}, {
filter: [window.siyuan.languages.insertIframeURL, "insert iframe link", "插入 iframe 链接", "charuiframelianjie", "criframelj"],
id: "insertIframeURL",
diff --git a/app/src/protyle/hint/index.ts b/app/src/protyle/hint/index.ts
index 4540d1ca4c..ea4964b06c 100644
--- a/app/src/protyle/hint/index.ts
+++ b/app/src/protyle/hint/index.ts
@@ -364,7 +364,9 @@ export class Hint {
range.setStart(range.startContainer, this.lastIndex);
}
range.deleteContents();
- uploadFiles(protyle, event.target.files, event.target);
+ uploadFiles(protyle, event.target.files, event.target, undefined, undefined, {
+ htmlAsIframe: event.target.dataset.uploadMode === "html-iframe",
+ });
hideElements(["hint", "toolbar"], protyle);
});
});
diff --git a/app/src/protyle/upload/index.ts b/app/src/protyle/upload/index.ts
index d4955920bb..7b44f56092 100644
--- a/app/src/protyle/upload/index.ts
+++ b/app/src/protyle/upload/index.ts
@@ -22,6 +22,10 @@ interface FileWithPath extends File {
path: string;
}
+export interface IUploadInsertOptions {
+ htmlAsIframe?: boolean;
+}
+
export class Upload {
public element: HTMLElement;
public isUploading: boolean;
@@ -90,7 +94,7 @@ const validateFile = (protyle: IProtyle, files: File[]) => {
return {files: uploadFileList, msgId};
};
-const genUploadedLabel = async (responseText: string, protyle: IProtyle) => {
+const genUploadedLabel = async (responseText: string, protyle: IProtyle, options?: IUploadInsertOptions) => {
const response = JSON.parse(responseText);
let errorTip = "";
@@ -148,7 +152,7 @@ const genUploadedLabel = async (responseText: string, protyle: IProtyle) => {
content: path,
name: name
});
- successFileText += genAssetHTML(type, path, name, filename);
+ successFileText += genAssetHTML(type, path, name, filename, options?.htmlAsIframe);
if (!Constants.SIYUAN_ASSETS_AUDIO.includes(type) && !Constants.SIYUAN_ASSETS_VIDEO.includes(type) &&
keys.length - 1 !== index) {
if (nodeElement && nodeElement.classList.contains("table")) {
@@ -268,7 +272,8 @@ const genUploadedLabel = async (responseText: string, protyle: IProtyle) => {
}, hasImage ? 0 : Constants.TIMEOUT_LOAD);
};
-export const uploadLocalFiles = (files: ILocalFiles[], protyle: IProtyle, isUpload: boolean) => {
+export const uploadLocalFiles = (files: ILocalFiles[], protyle: IProtyle, isUpload: boolean,
+ options?: IUploadInsertOptions) => {
let msg = "";
const assetPaths: string[] = [];
files.forEach(item => {
@@ -295,13 +300,14 @@ export const uploadLocalFiles = (files: ILocalFiles[], protyle: IProtyle, isUplo
if (tip) {
showMessage(window.siyuan.languages.dndFolderTip.replace("${x}", `<b>${escapeHtml(tip.substring(0, tip.length - 2))}</b>`));
}
- genUploadedLabel(JSON.stringify(response), protyle);
+ genUploadedLabel(JSON.stringify(response), protyle, options);
});
});
};
export const uploadFiles = (protyle: IProtyle, files: FileList | DataTransferItemList | File[], element?: HTMLInputElement,
- successCB?: (res: string) => void, completeCB?: (succeeded: boolean) => void) => {
+ successCB?: (res: string) => void, completeCB?: (succeeded: boolean) => void,
+ options?: IUploadInsertOptions) => {
// FileList | DataTransferItemList | File[] => File[]
let fileList = [];
for (let i = 0; i < files.length; i++) {
@@ -409,7 +415,7 @@ export const uploadFiles = (protyle: IProtyle, files: FileList | DataTransferIte
if (protyle.options.upload.format) {
responseText = protyle.options.upload.format(files as File [], xhr.responseText);
}
- genUploadedLabel(responseText, protyle);
+ genUploadedLabel(responseText, protyle, options);
}
let succeeded = true;
try {
diff --git a/app/src/protyle/util/editorCommonEvent.ts b/app/src/protyle/util/editorCommonEvent.ts
index c49ec10663..70c1100a96 100644
--- a/app/src/protyle/util/editorCommonEvent.ts
+++ b/app/src/protyle/util/editorCommonEvent.ts
@@ -2048,15 +2048,22 @@ export const dropEvent = (protyle: IProtyle, editorElement: HTMLElement) => {
size: event.dataTransfer.files[i].size
});
} else {
- paste(protyle, event);
+ paste(protyle, event, {
+ htmlAsIframe: window.siyuan.config.editor.dragHTMLFileToIframe && !event.altKey,
+ });
break;
}
}
if (files.length > 0) {
- uploadLocalFiles(files, protyle, !event.altKey);
+ uploadLocalFiles(files, protyle, !event.altKey, {
+ htmlAsIframe: window.siyuan.config.editor.dragHTMLFileToIframe && !event.altKey,
+ });
}
} else {
- paste(protyle, event);
+ paste(protyle, event, {
+ htmlAsIframe: event.dataTransfer.types.includes("Files") &&
+ window.siyuan.config.editor.dragHTMLFileToIframe && !event.altKey,
+ });
}
clearSelect(["av", "img"], protyle.wysiwyg.element);
} else {
diff --git a/app/src/protyle/util/paste.ts b/app/src/protyle/util/paste.ts
index 747d46590a..49b3272890 100644
--- a/app/src/protyle/util/paste.ts
+++ b/app/src/protyle/util/paste.ts
@@ -1,5 +1,6 @@
import {Constants} from "../../constants";
import {uploadFiles, uploadLocalFiles} from "../upload";
+import type {IUploadInsertOptions} from "../upload";
import {processPasteCode, processRender} from "./processCode";
import {getLocalFiles, getTextSiyuanFromTextHTML, readText} from "./compatibility";
import {hasClosestBlock, hasClosestByAttribute, hasClosestByClassName} from "./hasClosest";
@@ -487,7 +488,7 @@ const pasteCrossBlockRange = (protyle: IProtyle, tempElement: HTMLElement, range
export const paste = async (protyle: IProtyle, event: (ClipboardEvent | DragEvent | IClipboardData) & {
target: HTMLElement
-}) => {
+}, uploadOptions?: IUploadInsertOptions) => {
if ("clipboardData" in event || "dataTransfer" in event) {
event.stopPropagation();
event.preventDefault();
@@ -620,7 +621,7 @@ export const paste = async (protyle: IProtyle, event: (ClipboardEvent | DragEven
}
if (!nodeElement) {
if (files && files.length > 0) {
- uploadFiles(protyle, files);
+ uploadFiles(protyle, files, undefined, undefined, undefined, uploadOptions);
}
return;
}
@@ -920,7 +921,7 @@ export const paste = async (protyle: IProtyle, event: (ClipboardEvent | DragEven
});
return;
} else if (files && files.length > 0) {
- uploadFiles(protyle, files);
+ uploadFiles(protyle, files, undefined, undefined, undefined, uploadOptions);
return;
} else if (textPlain.trim() !== "" && (files && files.length === 0 || !files)) {
if (range.toString() !== "") {
diff --git a/app/src/types/config.d.ts b/app/src/types/config.d.ts
index 84bdc583c2..39a4ec1419 100644
--- a/app/src/types/config.d.ts
+++ b/app/src/types/config.d.ts
@@ -686,6 +686,10 @@ declare namespace Config {
* Whether to auto-convert pasted URLs to links
*/
pasteURLAutoConvert: boolean;
+ /**
+ * Whether to embed dragged HTML files as IFrame blocks
+ */
+ dragHTMLFileToIframe: boolean;
/**
* Whether to enable read-only mode
*/
diff --git a/kernel/agent/agent.go b/kernel/agent/agent.go
index 07d0143336..ac0f00424c 100644
--- a/kernel/agent/agent.go
+++ b/kernel/agent/agent.go
@@ -62,6 +62,7 @@ const systemPrompt = `You are a SiYuan AI assistant. You help users manage their
- Attributes: attr.get/set on any block. Database/attribute views: database.item_add (rows), database.key_add (columns), database.render (view). Create database blocks via database tools, never via the file tool.
- Icons: attr.set only changes a document BLOCK's icon — it cannot set a NOTEBOOK's icon. For notebooks use notebook.set_icon (a specific emoji) or notebook.random_icon (random emoji, optionally scoped by id; omit id to randomize ALL notebooks).
- Document images: image.list finds local images referenced by a document; call image.analyze on a returned asset path to attach it to the current model for understanding. image.generate creates a reusable image asset for insertion or other document operations.
+- HTML components: asset.create_html writes HTML content as an asset and inserts a sandboxed IFrame block in one operation. Prefer self-contained HTML; only use remote resources when the user requests them.
## Response Guidelines
- Reply in the language configured in SiYuan's appearance settings. When mentioning documents/blocks the user can open, format them as markdown links: [title](siyuan://blocks/<blockID>). Only use block IDs actually returned by a tool call (block.get/get_children/breadcrumb/batch_get/search); never fabricate IDs. For general mentions without a specific block, plain text is fine.
@@ -176,7 +177,7 @@ var toolSignatureKeys = map[string][]string{
"template": {"id", "path", "name", "keyword"},
"history": {"path", "notebook", "query"},
"repo": {"id", "left", "right", "name", "keyword"},
- "asset": {"id", "path"},
+ "asset": {"id", "path", "name", "parentID", "nextID", "previousID"},
"image": {"documentID", "assetPath", "action"},
"import": {"notebook", "path"},
"export": {"id"},
diff --git a/kernel/conf/editor.go b/kernel/conf/editor.go
index 81e448ee85..956f9fb7d4 100644
--- a/kernel/conf/editor.go
+++ b/kernel/conf/editor.go
@@ -70,6 +70,7 @@ type Editor struct {
HeadingNumberFormat string `json:"headingNumberFormat"` // 标题编号格式
HeadingEmbedMode int `json:"headingEmbedMode"` // 标题嵌入块模式,0:显示标题与下方的块,1:仅显示标题,2:仅显示标题下方的块
PasteURLAutoConvert bool `json:"pasteURLAutoConvert"` // 粘贴网址时自动转为链接
+ DragHTMLFileToIframe bool `json:"dragHTMLFileToIframe"` // 是否将拖拽的 HTML 文件嵌入为 IFrame 块
Markdown *util.Markdown `json:"markdown"` // Markdown 配置
}
@@ -123,6 +124,7 @@ func NewEditor() *Editor {
HeadingNumberFormat: DefaultHeadingNumberFormat,
HeadingEmbedMode: 0,
PasteURLAutoConvert: false,
+ DragHTMLFileToIframe: false,
Markdown: util.MarkdownSettings,
}
}
diff --git a/kernel/mcp/tools/asset.go b/kernel/mcp/tools/asset.go
index 4f937389b2..af68141126 100644
--- a/kernel/mcp/tools/asset.go
+++ b/kernel/mcp/tools/asset.go
@@ -18,23 +18,42 @@ package tools
import (
"fmt"
+ "html"
"os"
"path/filepath"
"strings"
"github.com/siyuan-note/siyuan/kernel/model"
+ "github.com/siyuan-note/siyuan/kernel/treenode"
+ "github.com/siyuan-note/siyuan/kernel/util"
)
+const maxHTMLAssetContentSize = 2 * 1024 * 1024
+
var AssetTool = &Tool{
Name: "asset",
- Description: "Asset management. Actions: upload(id, files=comma-separated absolute paths), unused(), clean(path?), stat(path).",
+ Description: "Asset management. Actions: upload(id, files=comma-separated absolute paths), create_html(id, html, name?, parentID?, previousID?, nextID?), unused(), clean(path?), stat(path). create_html writes an HTML asset and inserts a sandboxed IFrame block in one operation.",
+ EffectScope: EffectScopeLocal,
+ ActionEffects: map[string]ToolEffects{
+ "upload": {LocalWrite: true},
+ "create_html": {LocalWrite: true},
+ "unused": {LocalRead: true},
+ "clean": {LocalWrite: true},
+ "stat": {LocalRead: true},
+ },
InputSchema: ToolSchema{
Type: "object",
Properties: map[string]Property{
- "action": {Type: "string", Description: "Operation", Enum: []string{"upload", "unused", "clean", "stat"}},
- "id": {Type: "string", Description: "Document block ID (for upload)"},
- "files": {Type: "string", Description: "Comma-separated absolute file paths (for upload)"},
- "path": {Type: "string", Description: "Single unused asset path to remove, relative to data directory (for clean, optional). Use as returned by the unused action, e.g. assets/image/xxx.png."},
+ "action": {Type: "string", Description: "Operation", Enum: []string{"upload", "create_html", "unused", "clean", "stat"}},
+ "notebook": {Type: "string", Description: "Notebook ID that owns the target document; required for encrypted notebooks"},
+ "id": {Type: "string", Description: "Document block ID (for upload, create_html)"},
+ "files": {Type: "string", Description: "Comma-separated absolute file paths (for upload)"},
+ "name": {Type: "string", Description: "HTML asset filename ending in .html or .htm (for create_html, default component.html)"},
+ "html": {Type: "string", Description: "HTML document content (for create_html, maximum 2 MiB)"},
+ "parentID": {Type: "string", Description: "Parent block ID (for create_html, defaults to the document ID)"},
+ "previousID": {Type: "string", Description: "Previous sibling block ID (for create_html)"},
+ "nextID": {Type: "string", Description: "Next sibling block ID (for create_html)"},
+ "path": {Type: "string", Description: "Single unused asset path to remove, relative to data directory (for clean, optional). Use as returned by the unused action, e.g. assets/image/xxx.png."},
},
Required: []string{"action"},
},
@@ -50,6 +69,8 @@ func assetHandler(args map[string]any) (CallToolResult, error) {
switch action {
case "upload":
return assetUpload(args)
+ case "create_html":
+ return assetCreateHTML(args)
case "unused":
return assetUnused(args)
case "clean":
@@ -58,11 +79,119 @@ func assetHandler(args map[string]any) (CallToolResult, error) {
return assetStat(args)
}
return CallToolResult{
- Content: []ContentItem{{Type: "text", Text: "unknown action '" + action + "', expected one of: [upload, unused, clean, stat]"}},
+ Content: []ContentItem{{Type: "text", Text: "unknown action '" + action + "', expected one of: [upload, create_html, unused, clean, stat]"}},
IsError: true,
}, nil
}
+func assetCreateHTML(args map[string]any) (CallToolResult, error) {
+ id, _ := args["id"].(string)
+ if id == "" {
+ return CallToolResult{Content: []ContentItem{{Type: "text", Text: "id is required"}}, IsError: true}, nil
+ }
+ htmlContent, exists := args["html"].(string)
+ if !exists || strings.TrimSpace(htmlContent) == "" {
+ return CallToolResult{Content: []ContentItem{{Type: "text", Text: "html is required"}}, IsError: true}, nil
+ }
+ if len([]byte(htmlContent)) > maxHTMLAssetContentSize {
+ return CallToolResult{Content: []ContentItem{{Type: "text", Text: "html exceeds the 2 MiB limit"}}, IsError: true}, nil
+ }
+ name, nameErr := normalizeHTMLAssetName(args["name"])
+ if nameErr != nil {
+ return CallToolResult{Content: []ContentItem{{Type: "text", Text: nameErr.Error()}}, IsError: true}, nil
+ }
+
+ parentID, _ := args["parentID"].(string)
+ previousID, _ := args["previousID"].(string)
+ nextID, _ := args["nextID"].(string)
+ if parentID == "" && previousID == "" && nextID == "" {
+ parentID = id
+ }
+ boxID, release, scopeErr := beginBlockToolScope(args, true, id, parentID, previousID, nextID)
+ if scopeErr != nil {
+ return blockToolError(scopeErr.Error())
+ }
+ defer release()
+
+ docBlockTree := treenode.GetBlockTreeInExactBox(id, boxID)
+ if docBlockTree == nil || docBlockTree.ID != docBlockTree.RootID {
+ return CallToolResult{Content: []ContentItem{{Type: "text", Text: "id must be a document block ID"}}, IsError: true}, nil
+ }
+ for _, targetID := range []string{parentID, previousID, nextID} {
+ if targetID == "" {
+ continue
+ }
+ target := treenode.GetBlockTreeInExactBox(targetID, boxID)
+ if target == nil || target.RootID != docBlockTree.RootID {
+ return CallToolResult{Content: []ContentItem{{Type: "text", Text: "insertion target must belong to document " + id}}, IsError: true}, nil
+ }
+ }
+ if parentID != "" && previousID == "" && nextID == "" {
+ if err := treenode.CheckContainerParent(parentID); err != nil {
+ return CallToolResult{Content: []ContentItem{{Type: "text", Text: err.Error()}}, IsError: true}, nil
+ }
+ }
+
+ assetPath, _, err := model.InsertAssetBytes(id, name, []byte(htmlContent))
+ if err != nil {
+ return CallToolResult{Content: []ContentItem{{Type: "text", Text: "create HTML asset failed: " + err.Error()}}, IsError: true}, nil
+ }
+ blockDOM, blockID, err := htmlAssetIFrameBlockDOM(assetPath)
+ if err != nil {
+ return CallToolResult{Content: []ContentItem{{Type: "text", Text: "create IFrame block failed: " + err.Error()}}, IsError: true}, nil
+ }
+
+ transactions := []*model.Transaction{{
+ DoOperations: []*model.Operation{{
+ Action: "insert",
+ Data: blockDOM,
+ ParentID: parentID,
+ PreviousID: previousID,
+ NextID: nextID,
+ }},
+ }}
+ model.PerformTransactions(&transactions)
+ model.FlushTxQueue()
+ util.PushReloadProtyle(docBlockTree.RootID)
+
+ return CallToolResult{
+ Content: []ContentItem{{Type: "text", Text: fmt.Sprintf("Created HTML IFrame block: %s\nAsset: %s", blockID, assetPath)}},
+ StructuredContent: map[string]any{
+ "blockID": blockID,
+ "assetPath": assetPath,
+ },
+ StructuredContentSet: true,
+ }, nil
+}
+
+func normalizeHTMLAssetName(value any) (string, error) {
+ name, _ := value.(string)
+ name = strings.TrimSpace(name)
+ if name == "" {
+ name = "component.html"
+ }
+ name = filepath.Base(name)
+ ext := strings.ToLower(filepath.Ext(name))
+ if ext != ".html" && ext != ".htm" {
+ return "", fmt.Errorf("name must end in .html or .htm")
+ }
+ return name, nil
+}
+
+func htmlAssetIFrameBlockDOM(assetPath string) (dom, blockID string, err error) {
+ src := html.EscapeString(model.HTMLAssetIFrameSrc(assetPath))
+ dom, err = markdownToBlockDOM(`<iframe sandbox="allow-scripts" src="` + src + `" border="0" frameborder="no" framespacing="0" allowfullscreen="true"></iframe>`)
+ if err != nil {
+ return
+ }
+ tree := util.NewLute().BlockDOM2Tree(dom)
+ if tree == nil || tree.Root == nil || tree.Root.FirstChild == nil {
+ return "", "", fmt.Errorf("empty IFrame block")
+ }
+ blockID = tree.Root.FirstChild.ID
+ return
+}
+
func assetUpload(args map[string]any) (CallToolResult, error) {
id, _ := args["id"].(string)
if id == "" {
diff --git a/kernel/mcp/tools/asset_test.go b/kernel/mcp/tools/asset_test.go
new file mode 100644
index 0000000000..b11fc88f9e
--- /dev/null
+++ b/kernel/mcp/tools/asset_test.go
@@ -0,0 +1,49 @@
+// 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.
+
+package tools
+
+import (
+ "strings"
+ "testing"
+
+ "github.com/88250/lute/ast"
+ "github.com/siyuan-note/siyuan/kernel/util"
+)
+
+func TestNormalizeHTMLAssetName(t *testing.T) {
+ if got, err := normalizeHTMLAssetName(nil); err != nil || got != "component.html" {
+ t.Fatalf("default HTML asset name = %q, %v", got, err)
+ }
+ if got, err := normalizeHTMLAssetName("../Widget.HTM"); err != nil || got != "Widget.HTM" {
+ t.Fatalf("normalized HTML asset name = %q, %v", got, err)
+ }
+ if _, err := normalizeHTMLAssetName("component.xhtml"); err == nil {
+ t.Fatal("XHTML asset name must be rejected")
+ }
+}
+
+func TestHTMLAssetIFrameBlockDOM(t *testing.T) {
+ dom, blockID, err := htmlAssetIFrameBlockDOM("assets/component.html?box=box-id")
+ if err != nil {
+ t.Fatal(err)
+ }
+ if blockID == "" {
+ t.Fatal("IFrame block ID is empty")
+ }
+ if !strings.Contains(dom, `sandbox="allow-scripts"`) || strings.Contains(dom, "allow-same-origin") {
+ t.Fatalf("IFrame sandbox is unsafe: %s", dom)
+ }
+ if !strings.Contains(dom, "iframe=true") {
+ t.Fatalf("IFrame source is missing the render marker: %s", dom)
+ }
+ tree := util.NewLute().BlockDOM2Tree(dom)
+ if tree.Root.FirstChild == nil || tree.Root.FirstChild.Type != ast.NodeIFrame {
+ t.Fatalf("created block is not an IFrame: %s", dom)
+ }
+}
diff --git a/kernel/model/assets.go b/kernel/model/assets.go
index 9b6032766d..e0630e350c 100644
--- a/kernel/model/assets.go
+++ b/kernel/model/assets.go
@@ -1018,6 +1018,34 @@ func AssetPathWithoutQuery(relativePath string) string {
return filepath.ToSlash(relativePath)
}
+// HTMLAssetIFrameSrc 返回用于安全渲染 HTML 资源的 IFrame 地址。
+func HTMLAssetIFrameSrc(assetPath string) string {
+ if IsHTMLAssetIFrameSrc(assetPath) {
+ return assetPath
+ }
+ parsed, err := url.Parse(assetPath)
+ if err != nil {
+ return assetPath
+ }
+ query := parsed.Query()
+ query.Set("iframe", "true")
+ parsed.RawQuery = query.Encode()
+ return parsed.String()
+}
+
+// IsHTMLAssetIFrameSrc 判断资源地址是否为 HTML 文件 IFrame 渲染地址。
+func IsHTMLAssetIFrameSrc(assetPath string) bool {
+ parsed, err := url.Parse(assetPath)
+ if err != nil || !strings.EqualFold(parsed.Query().Get("iframe"), "true") {
+ return false
+ }
+ if parsed.IsAbs() || parsed.Host != "" || !strings.HasPrefix(strings.TrimPrefix(parsed.Path, "/"), "assets/") {
+ return false
+ }
+ ext := strings.ToLower(path.Ext(parsed.Path))
+ return ext == ".html" || ext == ".htm"
+}
+
func assetPathAndBox(relativePath, defaultBoxID string) (cleanPath, boxID string, err error) {
relativePath = strings.TrimSpace(relativePath)
boxID = defaultBoxID
diff --git a/kernel/model/export.go b/kernel/model/export.go
index 59939154b4..7bb573c3aa 100644
--- a/kernel/model/export.go
+++ b/kernel/model/export.go
@@ -1430,6 +1430,8 @@ func ExportHTML(id, savePath string, pdf, keepFold, merge bool) (name, dom strin
if pdf {
processIFrame(tree)
+ } else {
+ processHTMLFileIFrame(tree)
}
luteEngine := NewLute()
@@ -1509,19 +1511,31 @@ func materializeHeadingNumbers(tree *parse.Tree, numbers map[string]string) {
func processIFrame(tree *parse.Tree) {
// 导出 PDF/Word 时 IFrame 块使用超链接 https://github.com/siyuan-note/siyuan/issues/4035
+ processIFrameWithFilter(tree, nil)
+}
+
+func processHTMLFileIFrame(tree *parse.Tree) {
+ // 导出 HTML 时将 HTML 文件组件转换为链接。
+ processIFrameWithFilter(tree, func(src string) bool {
+ return IsHTMLAssetIFrameSrc(src)
+ })
+}
+
+func processIFrameWithFilter(tree *parse.Tree, filter func(src string) bool) {
ast.Walk(tree.Root, func(n *ast.Node, entering bool) ast.WalkStatus {
if !entering || ast.NodeIFrame != n.Type {
return ast.WalkContinue
}
+ src := treenode.GetNodeSrcTokens(n)
+ if filter != nil && !filter(src) {
+ return ast.WalkContinue
+ }
n.Type = ast.NodeParagraph
- index := bytes.Index(n.Tokens, []byte("src=\""))
- if 0 > index {
+ if src == "" {
n.AppendChild(&ast.Node{Type: ast.NodeText, Tokens: n.Tokens})
} else {
- src := n.Tokens[index+len("src=\""):]
- src = src[:bytes.Index(src, []byte("\""))]
- src = html.UnescapeHTML(src)
+ src := html.UnescapeHTML([]byte(src))
link := &ast.Node{Type: ast.NodeLink}
link.AppendChild(&ast.Node{Type: ast.NodeOpenBracket})
link.AppendChild(&ast.Node{Type: ast.NodeText, Tokens: src})
diff --git a/kernel/model/export_asset_test.go b/kernel/model/export_asset_test.go
index da20e2dfc5..a7a08eb6b7 100644
--- a/kernel/model/export_asset_test.go
+++ b/kernel/model/export_asset_test.go
@@ -99,3 +99,20 @@ func TestResolveExportAssetPaths(t *testing.T) {
})
}
}
+
+func TestProcessHTMLFileIFrame(t *testing.T) {
+ root := &ast.Node{Type: ast.NodeDocument}
+ component := &ast.Node{Type: ast.NodeIFrame, Tokens: []byte(`<iframe src="assets/component.html?iframe=true"></iframe>`)}
+ external := &ast.Node{Type: ast.NodeIFrame, Tokens: []byte(`<iframe src="https://example.com/component.html?iframe=true"></iframe>`)}
+ root.AppendChild(component)
+ root.AppendChild(external)
+
+ processHTMLFileIFrame(&parse.Tree{Root: root})
+
+ if component.Type != ast.NodeParagraph || component.FirstChild == nil || component.FirstChild.Type != ast.NodeLink {
+ t.Fatalf("HTML file IFrame was not converted to a link: %#v", component)
+ }
+ if external.Type != ast.NodeIFrame || external.FirstChild != nil {
+ t.Fatalf("external IFrame must remain unchanged: %#v", external)
+ }
+}
diff --git a/kernel/model/html_asset_test.go b/kernel/model/html_asset_test.go
new file mode 100644
index 0000000000..b00f58e4b4
--- /dev/null
+++ b/kernel/model/html_asset_test.go
@@ -0,0 +1,50 @@
+// 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.
+
+package model
+
+import "testing"
+
+func TestHTMLAssetIFrameSrc(t *testing.T) {
+ tests := []struct {
+ name string
+ src string
+ want string
+ }{
+ {name: "HTML", src: "assets/component.html", want: "assets/component.html?iframe=true"},
+ {name: "HTM with query", src: "assets/component.htm?box=box-id", want: "assets/component.htm?box=box-id&iframe=true"},
+ {name: "replace marker", src: "assets/component.html?iframe=false", want: "assets/component.html?iframe=true"},
+ {name: "preserve fragment", src: "assets/component.html#preview", want: "assets/component.html?iframe=true#preview"},
+ {name: "already marked", src: "assets/component.html?iframe=true", want: "assets/component.html?iframe=true"},
+ }
+ for _, test := range tests {
+ t.Run(test.name, func(t *testing.T) {
+ if got := HTMLAssetIFrameSrc(test.src); got != test.want {
+ t.Fatalf("HTMLAssetIFrameSrc(%q) = %q, want %q", test.src, got, test.want)
+ }
+ if !IsHTMLAssetIFrameSrc(test.want) {
+ t.Fatalf("IsHTMLAssetIFrameSrc(%q) = false", test.want)
+ }
+ })
+ }
+}
+
+func TestIsHTMLAssetIFrameSrcRejectsInvalidSources(t *testing.T) {
+ for _, src := range []string{
+ "assets/component.html",
+ "assets/component.html?iframe=false",
+ "assets/component.xhtml?iframe=true",
+ "assets/component.js?iframe=true",
+ "https://example.com/component.html?iframe=true",
+ "component.html?iframe=true",
+ } {
+ if IsHTMLAssetIFrameSrc(src) {
+ t.Fatalf("IsHTMLAssetIFrameSrc(%q) = true", src)
+ }
+ }
+}
diff --git a/kernel/server/serve.go b/kernel/server/serve.go
index 70f1b27cf0..dbb7d41669 100644
--- a/kernel/server/serve.go
+++ b/kernel/server/serve.go
@@ -856,6 +856,8 @@ var assetScriptCapableExts = map[string]bool{
".shtml": true, ".svg": true, ".xhtml": true, ".xml": true,
}
+const htmlAssetIFrameCSP = "sandbox allow-scripts; object-src 'none'; base-uri 'none'; form-action 'none'; frame-ancestors 'self'"
+
// isAssetInlineUnsafe 判断资产是否禁止浏览器内联渲染:
// 可执行脚本的扩展名,或标准库无法识别 Content-Type 的扩展名(http.ServeFile 会内容嗅探,可能识别为 text/html 执行脚本)
func isAssetInlineUnsafe(absPath string) bool {
@@ -870,13 +872,25 @@ func isAssetInlineUnsafe(absPath string) bool {
// 无条件加 X-Content-Type-Options: nosniff,可执行脚本的类型无条件强制附件下载;
// absPath 用于判断内容类型,dispositionName 用于 Content-Disposition 文件名(加密笔记本场景为原始文件名)
func secureAssetContentHeaders(context *gin.Context, absPath, dispositionName string) {
- setAssetsAttachmentDisposition(context, dispositionName)
context.Header("X-Content-Type-Options", "nosniff")
+ if isHTMLAssetIFrameRequest(context, absPath) {
+ context.Header("Content-Type", "text/html; charset=utf-8")
+ context.Header("Content-Security-Policy", htmlAssetIFrameCSP)
+ return
+ }
+ setAssetsAttachmentDisposition(context, dispositionName)
if isAssetInlineUnsafe(absPath) {
context.Header("Content-Disposition", formatContentDispositionAttachment(filepath.Base(dispositionName)))
}
}
+func isHTMLAssetIFrameRequest(context *gin.Context, absPath string) bool {
+ return strings.HasPrefix(context.Request.URL.Path, "/assets/") &&
+ !strings.EqualFold(context.Query("download"), "true") &&
+ model.IsHTMLAssetIFrameSrc(context.Request.URL.Path+"?"+context.Request.URL.RawQuery) &&
+ (strings.EqualFold(filepath.Ext(absPath), ".html") || strings.EqualFold(filepath.Ext(absPath), ".htm"))
+}
+
func isValidAssetRequestPath(requestPath string) bool {
relativePath := strings.TrimPrefix(requestPath, "/")
if relativePath == "" || relativePath == "." {
diff --git a/kernel/server/serve_assets_test.go b/kernel/server/serve_assets_test.go
index 8ac13572c8..529a6423ca 100644
--- a/kernel/server/serve_assets_test.go
+++ b/kernel/server/serve_assets_test.go
@@ -177,6 +177,61 @@ func TestSecureAssetContentHeadersForcesAttachmentOnScriptCapableAssets(t *testi
}
}
+func TestSecureAssetContentHeadersSandboxesHTMLIFrameAssets(t *testing.T) {
+ assetPath := filepath.Join(t.TempDir(), "component.html")
+ if err := os.WriteFile(assetPath, []byte("<script>fetch('https://example.com')</script>"), 0644); err != nil {
+ t.Fatalf("write test asset failed: %v", err)
+ }
+ recorder := httptest.NewRecorder()
+ context, _ := gin.CreateTestContext(recorder)
+ context.Request = httptest.NewRequest(http.MethodGet, "/assets/component.html?iframe=true", nil)
+ secureAssetContentHeaders(context, assetPath, assetPath)
+
+ if disposition := recorder.Header().Get("Content-Disposition"); disposition != "" {
+ t.Fatalf("HTML IFrame asset must render inline, got Content-Disposition %q", disposition)
+ }
+ if got := recorder.Header().Get("Content-Type"); got != "text/html; charset=utf-8" {
+ t.Fatalf("HTML IFrame asset Content-Type = %q", got)
+ }
+ if got := recorder.Header().Get("Content-Security-Policy"); got != htmlAssetIFrameCSP {
+ t.Fatalf("HTML IFrame asset CSP = %q", got)
+ }
+ if recorder.Header().Get("X-Content-Type-Options") != "nosniff" {
+ t.Fatal("HTML IFrame asset missing X-Content-Type-Options header")
+ }
+}
+
+func TestSecureAssetContentHeadersRejectsInvalidHTMLIFrameRequests(t *testing.T) {
+ tests := []struct {
+ name string
+ requestURL string
+ filename string
+ }{
+ {name: "explicit download", requestURL: "/assets/component.html?iframe=true&download=true", filename: "component.html"},
+ {name: "non HTML asset", requestURL: "/assets/component.js?iframe=true", filename: "component.js"},
+ {name: "non asset route", requestURL: "/history/component.html?iframe=true", filename: "component.html"},
+ }
+ for _, test := range tests {
+ t.Run(test.name, func(t *testing.T) {
+ assetPath := filepath.Join(t.TempDir(), test.filename)
+ if err := os.WriteFile(assetPath, []byte("test"), 0644); err != nil {
+ t.Fatalf("write test asset failed: %v", err)
+ }
+ recorder := httptest.NewRecorder()
+ context, _ := gin.CreateTestContext(recorder)
+ context.Request = httptest.NewRequest(http.MethodGet, test.requestURL, nil)
+ secureAssetContentHeaders(context, assetPath, assetPath)
+ if !strings.HasPrefix(recorder.Header().Get("Content-Disposition"), "attachment") {
+ t.Fatalf("invalid HTML IFrame request must download, got Content-Disposition %q",
+ recorder.Header().Get("Content-Disposition"))
+ }
+ if csp := recorder.Header().Get("Content-Security-Policy"); csp != "" {
+ t.Fatalf("invalid HTML IFrame request must not receive sandbox CSP, got %q", csp)
+ }
+ })
+ }
+}
+
func TestSecureAssetContentHeadersAllowsInlineSafeAssets(t *testing.T) {
// 图片、音视频、PDF 等安全类型保持内联渲染,但仍需 nosniff
cases := []string{"test.png", "test.jpg", "test.webp", "test.mp4", "test.mp3", "test.pdf", "test.txt"}