Skip to content

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

:bug: Preserve local links in table cells https://github.com/siyuan-note/siyuan/issues/20013

Danielb208f821faf6
diff --git a/app/src/menus/linkMenu.test.ts b/app/src/menus/linkMenu.test.ts
new file mode 100644
index 0000000000..2c61dd0d16
--- /dev/null
+++ b/app/src/menus/linkMenu.test.ts
@@ -0,0 +1,42 @@
+import * as assert from "node:assert/strict";
+import {readFileSync} from "node:fs";
+import {join} from "node:path";
+import {test} from "node:test";
+import {runInNewContext} from "node:vm";
+import {createSourceFile, isVariableStatement, ScriptTarget, transpileModule} from "typescript";
+
+const source = createSourceFile("protyle.ts", readFileSync(join(__dirname, "protyle.ts"), "utf8"), ScriptTarget.Latest, true);
+const declaration = source.statements.filter(isVariableStatement).flatMap(statement =>
+ Array.from(statement.declarationList.declarations)).find(item => item.name.getText(source) === "linkMenu");
+const code = transpileModule("const linkMenu = " + declaration.initializer.getText(source) + "; linkMenu(protyle, linkElement);",
+ {compilerOptions: {target: ScriptTarget.ES2022}}).outputText;
+
+test("link menus show missing targets as empty on desktop and mobile", () => {
+ if (typeof Lute === "undefined") {
+ require("../../stage/protyle/js/lute/lute.min.js");
+ }
+ for (const mobile of [false, true]) {
+ for (const target of [null, "", "D:\\基线测试\\文档.docx", "file:///D:/baseline/document.txt"]) {
+ const inputs = Array.from({length: 3}, () => ({value: "", addEventListener() {}, select() {}}));
+ const menu = {remove() {}, append() {}, fullscreen() {}, popup() {}, element: {setAttribute() {}}};
+ const linkElement = {getAttribute: (name: string) => name === "data-href" ? target : "",
+ textContent: "anchor", getBoundingClientRect: () => ({left: 0, top: 0})};
+ runInNewContext(code, {
+ Lute, protyle: {lute: {GetLinkDest: () => ""}, element: {}}, linkElement,
+ Constants: {MENU_INLINE_A: "a", ZWSP: "\u200b"},
+ window: {siyuan: {languages: {}, menus: {menu}}},
+ hasClosestBlock: () => ({outerHTML: ""}), hasTopClosestByClassName: (): undefined => undefined,
+ hideTooltip() {}, hideElements() {}, isMobile: () => mobile,
+ isLocalHTMLAssetPath: () => false, emitOpenMenu() {}, openMenu() {},
+ MenuItem: class {
+ element = {};
+ constructor(options: {bind?: (element: unknown) => void}) {
+ options.bind?.({style: {}, querySelectorAll: () => inputs, addEventListener() {}});
+ }
+ },
+ });
+ assert.equal(inputs[0].value, target || "");
+ assert.equal(inputs[1].value, "anchor");
+ }
+ }
+});
diff --git a/app/src/menus/protyle.ts b/app/src/menus/protyle.ts
index 4425784eb0..632b92d44c 100644
--- a/app/src/menus/protyle.ts
+++ b/app/src/menus/protyle.ts
@@ -1628,7 +1628,7 @@ export const linkMenu = (protyle: IProtyle, linkElement: HTMLElement, focusText
hideTooltip();
hideElements(["util", "toolbar", "hint"], protyle);
let html = nodeElement.outerHTML;
- const linkAddress = linkElement.getAttribute("data-href");
+ const linkAddress = linkElement.getAttribute("data-href") || "";
let inputElements: NodeListOf<HTMLTextAreaElement>;
if (!protyle.disabled) {
window.siyuan.menus.menu.append(new MenuItem({
diff --git a/app/src/protyle/render/av/richText.test.ts b/app/src/protyle/render/av/richText.test.ts
index f27ce326a6..20ab760b70 100644
--- a/app/src/protyle/render/av/richText.test.ts
+++ b/app/src/protyle/render/av/richText.test.ts
@@ -394,6 +394,27 @@ describe("attribute view text source compatibility", () => {
}
});
+ it("allows local link targets only with the table cell policy", () => {
+ for (const target of [
+ "D:\\基线测试\\测试文档1.docx", "D:/基线测试/测试文档1.docx", "D:\\目录\\",
+ "file:///D:\\基线测试\\测试文档1.docx", "file:///D:/基线测试/测试文档1.docx",
+ "file:///tmp/test%20document.txt", "file://server/share/document.txt",
+ "\\\\server\\share\\document.txt",
+ ]) {
+ assert.equal(getAVRichTextSafeURL(target, true), target);
+ assert.equal(getAVRichTextSafeURL(target), "");
+ }
+ for (const target of [
+ "javascript:alert(1)", "javascript&colon;alert(1)", "java%73cript:alert(1)",
+ "data:text/html,payload", "vbscript:payload", "file:relative.txt", "file://",
+ "file://user@server/share/document.txt", "file://server:123/share/document.txt",
+ "D:relative.txt", "D:\\file%0a.txt", "file:///tmp/file%00.txt",
+ "D:\\file\u200B.txt", "https:\\\\example.com\\document.txt", "\\\\server",
+ ]) {
+ assert.equal(getAVRichTextSafeURL(target, true), "", target);
+ }
+ });
+
it("keeps only supported inline color declarations", () => {
for (const id of ["error", "warning", "info", "success"]) {
const style = `color: var(--b3-card-${id}-color); background-color: var(--b3-card-${id}-background);`;
diff --git a/app/src/protyle/render/av/richText.ts b/app/src/protyle/render/av/richText.ts
index 42967d3c0a..de7ca011cc 100644
--- a/app/src/protyle/render/av/richText.ts
+++ b/app/src/protyle/render/av/richText.ts
@@ -235,18 +235,20 @@ export const sanitizeAVRichTextBlockDOM = (blockDOM: string, images = false, tab
const name = attribute.name.toLowerCase();
const imageAttribute = images && ["src", "data-src", "alt", "title", "loading"].includes(name) &&
(element.tagName === "IMG" || element.classList.contains("img"));
+ const linkTitleAttribute = tableCellCustomInline && name === "data-title" &&
+ (element.dataset.type || "").split(" ").includes("a");
const codeAttribute = images && element.dataset.type === "NodeCodeBlock" &&
(["linewrap", "ligatures", "linenumber"].includes(name) && ["true", "false"].includes(attribute.value) ||
name === Constants.CUSTOM_SY_CODE_TAB_SPACES &&
CODE_TAB_SPACE_VALUES.some(value => value.toString() === attribute.value));
- if ((!AV_RICH_TEXT_EDITOR_ALLOWED_ATTRIBUTES.includes(name) && !imageAttribute && !codeAttribute) ||
+ if ((!AV_RICH_TEXT_EDITOR_ALLOWED_ATTRIBUTES.includes(name) && !imageAttribute && !linkTitleAttribute && !codeAttribute) ||
name === "xlink:href" && !attribute.value.startsWith("#icon")) {
element.removeAttribute(attribute.name);
}
});
});
template.content.querySelectorAll<HTMLElement>('[data-type~="a"][data-href]').forEach((element) => {
- const href = getAVRichTextSafeURL(element.dataset.href);
+ const href = getAVRichTextSafeURL(element.dataset.href, tableCellCustomInline);
if (href) {
element.dataset.href = href;
} else {
diff --git a/app/src/protyle/render/av/richTextValue.ts b/app/src/protyle/render/av/richTextValue.ts
index 6a7a8e1a31..ab5d9ccdca 100644
--- a/app/src/protyle/render/av/richTextValue.ts
+++ b/app/src/protyle/render/av/richTextValue.ts
@@ -190,7 +190,7 @@ const isCleanAVRichTextAssetPath = (value: string) => {
return cleanPath === path;
};
-export const getAVRichTextSafeURL = (value?: string | null) => {
+export const getAVRichTextSafeURL = (value?: string | null, localLinks = false) => {
const original = value || "";
if (!original) {
return "";
@@ -199,7 +199,7 @@ export const getAVRichTextSafeURL = (value?: string | null) => {
return "";
}
const url = decodeAVRichTextHTMLEntities(original);
- if (typeof url !== "string" || hasUnsafeAVRichTextURLCharacter(url)) {
+ if (typeof url !== "string" || Array.from(url).some(isAVRichTextControlOrFormatCharacter)) {
return "";
}
let percentDecoded: string;
@@ -208,7 +208,27 @@ export const getAVRichTextSafeURL = (value?: string | null) => {
} catch {
return "";
}
- if (!hasValidAVRichTextUnicode(percentDecoded) || hasUnsafeAVRichTextURLCharacter(percentDecoded)) {
+ if (!hasValidAVRichTextUnicode(percentDecoded) ||
+ Array.from(percentDecoded).some(isAVRichTextControlOrFormatCharacter)) {
+ return "";
+ }
+ // 普通表格保留本地超链接,图片来源和数据库片段继续使用默认的地址规则。
+ if (localLinks) {
+ if (/^[a-z]:[\\/]/i.test(url) || /^\\\\[^\\/:?#@]+[\\/][^\\/]+/.test(url)) {
+ return url;
+ }
+ const normalized = url.replace(/\\/g, "/");
+ if (/^file:\/\/(?:[^/]+)?\//i.test(normalized) && !normalized.slice(7).split("/", 1)[0].includes(":")) {
+ try {
+ if (new URL(normalized).protocol === "file:") {
+ return url;
+ }
+ } catch {
+ return "";
+ }
+ }
+ }
+ if (hasUnsafeAVRichTextURLCharacter(url) || hasUnsafeAVRichTextURLCharacter(percentDecoded)) {
return "";
}
const scheme = url.match(/^([a-z][a-z0-9+.-]*):/i)?.[1].toLowerCase();
diff --git a/app/src/protyle/util/paste.test.ts b/app/src/protyle/util/paste.test.ts
index d2887a01fc..0095bc8f3d 100644
--- a/app/src/protyle/util/paste.test.ts
+++ b/app/src/protyle/util/paste.test.ts
@@ -162,8 +162,12 @@ describe("strip pasted IAL data attributes", () => {
});
describe("restricted cell selected text paste", () => {
+ if (typeof Lute === "undefined") {
+ require("../../../stage/protyle/js/lute/lute.min.js");
+ }
+ const lute = Lute.New();
const runPaste = async (text: string, options: {selected?: string, code?: boolean, inlineCode?: boolean,
- unsupported?: boolean} = {}) => {
+ unsupported?: boolean, tableCell?: boolean} = {}) => {
const selected = options.selected ?? "Selected & text";
const marks: Array<{type: string, value: ITextOption}> = [];
const inserted: string[] = [];
@@ -189,6 +193,7 @@ describe("restricted cell selected text paste", () => {
isUploadInsertPositionAvailable: () => true,
},
"./selection": {getEditorRange: () => range},
+ "./tableCellRichContext": {getTableCellRichContext: () => options.tableCell ? {} : undefined},
"./hasClosest": {hasClosestBlock: () => block},
"./compatibility": {isInHarmony: () => false},
"./officeMath": {extractOfficeMathHTML: () => ""},
@@ -198,7 +203,7 @@ describe("restricted cell selected text paste", () => {
"./inlineElementMarker": {stripSemanticMarkersFromRangeText: () => selected},
"../../editor/pdfAssetLink": {getPdfAnnotationReference: (): undefined => undefined},
"../../util/functions": {isDynamicRef: (value: string) => /^\(\(\d{14}-\w{7} '.*'\)\)$/.test(value)},
- "../toolbar/util": {resolveLinkDest: (value: string) => /^(https?:|file:|assets\/)/.test(value) ? value : ""},
+ "../toolbar/util": {resolveLinkDest: (value: string) => value.startsWith("assets/") ? value : lute.GetLinkDest(value)},
"../render/av/richTextValue": {getAVRichTextSafeURL},
"./normalizeText": {removeZWJ: (value: string) => value},
"./insertHTML": {insertHTML: (value: string) => inserted.push(value)},
@@ -251,6 +256,7 @@ describe("restricted cell selected text paste", () => {
["https://example.com", {code: true}],
["https://example.com", {inlineCode: true}],
["file:///private/document", {}],
+ ["D:\\基线测试\\文档.docx", {tableCell: true}],
] as const) {
it(`retains plain text fallback for ${text} ${JSON.stringify(options)}`, async () => {
const result = await runPaste(text, options);
@@ -259,6 +265,15 @@ describe("restricted cell selected text paste", () => {
});
}
+ for (const url of ["file:///D:\\基线测试\\文档.docx", "file:///tmp/document"]) {
+ it(`attaches ${url} to selected table cell text`, async () => {
+ const result = await runPaste(url, {tableCell: true});
+ assert.equal(result.marks[0].type, "a");
+ assert.equal(result.marks[0].value.color, url);
+ assert.deepEqual(result.inserted, []);
+ });
+ }
+
it("rejects unsupported content before changing the selection", async () => {
const result = await runPaste("https://example.com", {unsupported: true});
assert.deepEqual(result.marks, []);
diff --git a/app/src/protyle/util/paste.ts b/app/src/protyle/util/paste.ts
index 9f0493b82a..a192cc4b92 100644
--- a/app/src/protyle/util/paste.ts
+++ b/app/src/protyle/util/paste.ts
@@ -3,6 +3,7 @@ import {isEncryptedBox} from "../../util/pathName";
import {preparePasteAssets} from "./pasteAssets";
import {escapeHtml, escapeMarkdownPlainText} from "../../util/escape";
import {getTableCellPlainText} from "./tableCellRich";
+import {getTableCellRichContext} from "./tableCellRichContext";
import {uploadFiles, uploadLocalFiles} from "../upload";
import type {IUploadInsertOptions} from "../upload";
import {
@@ -115,7 +116,7 @@ const pastePlainTextLink = (protyle: IProtyle, range: Range, text: string) => {
return true;
}
const linkDest = resolveLinkDest(text, protyle.lute);
- if (linkDest && (!restricted || getAVRichTextSafeURL(linkDest))) {
+ if (linkDest && (!restricted || getAVRichTextSafeURL(linkDest, !!getTableCellRichContext(protyle)))) {
protyle.toolbar.range = range;
protyle.toolbar.setInlineMark(protyle, "a", "range", {type: "a", color: linkDest});
return true;
diff --git a/app/src/protyle/util/tableCellRichLute.test.ts b/app/src/protyle/util/tableCellRichLute.test.ts
index c76b6766cb..1f94bfda6b 100644
--- a/app/src/protyle/util/tableCellRichLute.test.ts
+++ b/app/src/protyle/util/tableCellRichLute.test.ts
@@ -13,7 +13,8 @@ const browserCases = async (source: string, enterSource: string, hintSource: str
const codeTabAttribute = "custom-sy-code-tab-spaces";
const api = new Function("Constants", source + "\nreturn {getAgentLute, configureAVRichTextLute, getTableCellEditorLute, " +
"canEnterCodeBlock, hasCodeBlockFence, getTableCellInlineHTML, serializeTableCellRich, " +
- "updateTableCellEditingValue, getTableCellRichBlockDOM, sanitizeAVRichTextBlockDOM, restoreTableVirtualizationDOM};")({
+ "updateTableCellEditingValue, getTableCellRichBlockDOM, sanitizeAVRichTextBlockDOM, restoreTableVirtualizationDOM, " +
+ "copyTableCellContent, renderTableCellRich};")({
CUSTOM_SY_CODE_TAB_SPACES: codeTabAttribute,
}) as
typeof import("../render/setLute") & typeof import("../render/av/richTextValue") &
@@ -22,6 +23,45 @@ const browserCases = async (source: string, enterSource: string, hintSource: str
const base = api.configureAVRichTextLute(api.getAgentLute({emojiSite: "/emojis", emojis: {},
headingAnchor: false, listStyle: false, paragraphBeginningSpace: true, sanitize: true}));
const lute = api.getTableCellEditorLute(base);
+ for (const target of [
+ "D:\\基线测试\\测试文档1.docx", "D:/基线测试/测试文档1.docx", "D:\\目录\\",
+ "file:///D:\\基线测试\\测试文档1.docx", "file:///D:/基线测试/测试文档1.docx",
+ "file:///tmp/test%20document.txt", "file://server/share/document.txt", "\\\\server\\share\\document.txt",
+ "https://example.com/document.txt", "assets/document.txt",
+ ]) {
+ const html = '<div data-type="NodeParagraph"><div contenteditable="true">' +
+ `<span data-type="a strong" data-href="${target}" data-title="title">anchor</span></div></div>`;
+ for (const multiBlock of [false, true]) {
+ let blockDOM = html + (multiBlock ? base.Md2BlockDOM("second paragraph") : "");
+ for (let pass = 0; pass < 3; pass++) {
+ const sanitized = api.sanitizeAVRichTextBlockDOM(Lute.Sanitize(blockDOM), true, true);
+ const value = api.serializeTableCellRich(sanitized);
+ const cell = document.createElement("td");
+ api.updateTableCellEditingValue(cell, value);
+ api.renderTableCellRich(cell);
+ const copied = document.createElement("td");
+ api.copyTableCellContent(copied, cell);
+ blockDOM = api.getTableCellRichBlockDOM(copied);
+ const holder = document.createElement("template");
+ holder.innerHTML = blockDOM;
+ const link = holder.content.querySelector('[data-type~="a"]');
+ check.equal(link?.getAttribute("data-href"), target, target);
+ check.equal(link?.textContent, "anchor", target);
+ check.ok(link?.getAttribute("data-type").split(" ").includes("strong"), target);
+ check.equal(link?.getAttribute("data-title"), "title", target);
+ }
+ }
+ }
+ for (const target of ["javascript:alert(1)", "data:text/html,payload", "file:///tmp/file%00.txt"]) {
+ const html = '<div data-type="NodeParagraph"><div contenteditable="true">' +
+ `<span data-type="a" data-href="${target}">anchor</span></div></div>`;
+ const holder = document.createElement("template");
+ holder.innerHTML = api.sanitizeAVRichTextBlockDOM(html, true, true);
+ check.equal(holder.content.querySelector('[data-type~="a"]')?.getAttribute("data-href"), null, target);
+ }
+ const localImage = '<div data-type="NodeParagraph"><div contenteditable="true">' +
+ '<span class="img"><img src="file:///tmp/image.png"></span></div></div>';
+ check.doesNotMatch(api.sanitizeAVRichTextBlockDOM(localImage, true, true), /<img/);
const customHTML = '<span data-type="custom_symble_strong_CJK_rectangle_yin" ' +
'style="--custom-symble-strong: rgb(0 166 240 / 1);">test</span>';
const customBlockDOM = base.Md2BlockDOM(customHTML + "\n\nsecond");
diff --git a/kernel/av/table_cell_rich.go b/kernel/av/table_cell_rich.go
index 8ede19ee10..edb1236454 100644
--- a/kernel/av/table_cell_rich.go
+++ b/kernel/av/table_cell_rich.go
@@ -2,10 +2,12 @@ package av
import (
"fmt"
+ "net/url"
"regexp"
"sort"
"strconv"
"strings"
+ "unicode/utf8"
"github.com/88250/lute/ast"
"github.com/88250/lute/parse"
@@ -13,6 +15,8 @@ import (
var (
tableCellRichCustomTypePattern = regexp.MustCompile(`^custom_[A-Za-z0-9_-]{1,128}$`)
+ tableCellRichWindowsPathPattern = regexp.MustCompile(`^[A-Za-z]:[\\/]`)
+ tableCellRichUNCPathPattern = regexp.MustCompile(`^\\\\[^\\/:?#@]+[\\/][^\\/]+`)
tableCellRichCustomPropertyPattern = regexp.MustCompile(`^--custom-[a-z0-9-]{1,128}$`)
tableCellRichCustomHexPattern = regexp.MustCompile(`^#(?:[0-9A-Fa-f]{3}|[0-9A-Fa-f]{4}|[0-9A-Fa-f]{6}|[0-9A-Fa-f]{8})$`)
tableCellRichCustomRGBPattern = regexp.MustCompile(`(?i)^rgba?\(\s*(\d{1,3})(?:,\s*|\s+)(\d{1,3})(?:,\s*|\s+)(\d{1,3})(?:\s*[,/]\s*(?:0(?:\.\d+)?|1(?:\.0+)?))?\s*\)$`)
@@ -61,7 +65,7 @@ func isAllowedTableCellRichCustomNode(node *ast.Node) bool {
return isAllowedTableCellRichCustomSpanIAL(node)
}
if ast.NodeTextMark != node.Type || !isTableCellRichCustomTextMark(node) ||
- "" != node.TextMarkFlashcardOcclusionID || !isAllowedValueTextMarkReferenceData(node) {
+ "" != node.TextMarkFlashcardOcclusionID || !isAllowedValueTextMarkReferenceData(node, true) {
return false
}
for _, typ := range strings.Fields(node.TextMarkType) {
@@ -80,6 +84,28 @@ func isAllowedTableCellRichCustomNode(node *ast.Node) bool {
return nil != node.Next && isAllowedTableCellRichCustomSpanIAL(node.Next)
}
+// 普通表格的本地超链接保留原始路径,图片来源不使用此规则。
+func isAllowedTableCellRichLocalLinkTarget(target string) bool {
+ if target != strings.TrimSpace(target) || !utf8.ValidString(target) {
+ return false
+ }
+ target, decoded, ok := decodeValueTextRichLinkTarget(target)
+ if !ok || !utf8.ValidString(decoded) || target != strings.TrimSpace(target) ||
+ containsValueTextRichUnsafeControl(target) || containsValueTextRichUnsafeControl(decoded) {
+ return false
+ }
+ if tableCellRichWindowsPathPattern.MatchString(target) || tableCellRichUNCPathPattern.MatchString(target) {
+ return true
+ }
+ normalized := strings.ReplaceAll(target, `\`, "/")
+ if !strings.HasPrefix(strings.ToLower(normalized), "file://") {
+ return false
+ }
+ parsed, err := url.Parse(normalized)
+ return nil == err && strings.EqualFold(parsed.Scheme, "file") && nil == parsed.User &&
+ !strings.Contains(parsed.Host, ":") && strings.HasPrefix(parsed.Path, "/")
+}
+
func isAllowedTableCellRichCustomSpanIAL(node *ast.Node) bool {
if nil == node || nil == node.Previous || !isTableCellRichCustomTextMark(node.Previous) {
return false
diff --git a/kernel/av/table_cell_rich_test.go b/kernel/av/table_cell_rich_test.go
index ef60de90bd..f6e2810228 100644
--- a/kernel/av/table_cell_rich_test.go
+++ b/kernel/av/table_cell_rich_test.go
@@ -115,3 +115,64 @@ func TestTableCellRichRejectsUnsafeCustomInlineStyle(t *testing.T) {
}
}
}
+
+func TestTableCellRichLocalLinks(t *testing.T) {
+ for _, target := range []string{
+ `D:\基线测试\测试文档1.docx`, `D:/基线测试/测试文档1.docx`, `D:\目录\`,
+ `file:///D:\基线测试\测试文档1.docx`, `file:///D:/基线测试/测试文档1.docx`,
+ `file:///tmp/test%20document.txt`, `file://server/share/document.txt`, `\\server\share\document.txt`,
+ } {
+ t.Run(target, func(t *testing.T) {
+ source := `<span data-type="a strong" data-href="` + target + `" data-title="title">anchor</span>`
+ rich := &ast.TableCellRich{Spec: 1, Format: "kramdown", Content: source}
+ for pass := 0; pass < 3; pass++ {
+ tree, err := ParseTableCellRich(rich)
+ if err != nil {
+ t.Fatal(err)
+ }
+ links := tree.Root.ChildrenByType(ast.NodeTextMark)
+ if len(links) != 1 || links[0].TextMarkAHref != target || links[0].TextMarkATitle != "title" ||
+ links[0].TextMarkTextContent != "anchor" || !links[0].IsTextMarkType("strong") {
+ t.Fatalf("local link changed: %s", rich.Content)
+ }
+ content, err := RenderTableCellRich(tree)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if pass > 0 && content != rich.Content {
+ t.Fatalf("table source is not stable: %q != %q", content, rich.Content)
+ }
+ rich.Content = content
+ }
+ if _, err := ParseValueTextRich(&ValueTextRich{Spec: ValueTextRichSpec,
+ Format: ValueTextRichFormatKramdown, Content: source}); err == nil {
+ t.Fatal("table local links must not expand the database rich text whitelist")
+ }
+ })
+ }
+}
+
+func TestTableCellRichRejectsUnsafeLocalLinksAndImages(t *testing.T) {
+ for _, target := range []string{
+ `javascript:alert(1)`, `javascript&colon;alert(1)`, `java%73cript:alert(1)`,
+ `data:text/html,payload`, `vbscript:payload`, `file:relative.txt`, `file://`,
+ `file://user@server/share/document.txt`, `file://server:123/share/document.txt`,
+ `D:relative.txt`, `D:\file%0a.txt`, `file:///tmp/file%00.txt`, "D:\\file\u200B.txt",
+ `https:\\example.com\document.txt`, `\\server`, "D:\\invalid\xff.txt", `D:\invalid%FF.txt`,
+ } {
+ source := `<span data-type="a" data-href="` + target + `">anchor</span>`
+ rich := &ast.TableCellRich{Spec: 1, Format: "kramdown", Content: source}
+ if _, err := ParseTableCellRich(rich); err == nil {
+ t.Fatalf("accepted unsafe table link: %q", target)
+ }
+ if rich.Content != source {
+ t.Fatal("rejected source must remain unchanged")
+ }
+ }
+ for _, target := range []string{`file:///tmp/image.png`, `D:/baseline/image.png`, `\\server\share\image.png`} {
+ rich := &ast.TableCellRich{Spec: 1, Format: "kramdown", Content: `![image](` + target + `)`}
+ if _, err := ParseTableCellRich(rich); err == nil {
+ t.Fatalf("local link policy must not expand image sources: %q", target)
+ }
+ }
+}
diff --git a/kernel/av/value.go b/kernel/av/value.go
index 40285899f5..673662e53f 100644
--- a/kernel/av/value.go
+++ b/kernel/av/value.go
@@ -604,7 +604,7 @@ func validateValueTextRichTreeWithImages(tree *parse.Tree, images bool) (err err
if !entering {
return ast.WalkContinue
}
- allowed := isAllowedValueTextRichNode(node)
+ allowed := isAllowedValueTextRichNode(node, images)
if images && ast.NodeKramdownBlockIAL == node.Type {
allowed = isAllowedValueTextRichBlockIAL(node, true)
}
@@ -666,7 +666,7 @@ func newValueTextRichLute() *lute.Lute {
return ret
}
-func isAllowedValueTextRichNode(node *ast.Node) bool {
+func isAllowedValueTextRichNode(node *ast.Node, localLinks bool) bool {
if nil == node {
return false
}
@@ -705,7 +705,8 @@ func isAllowedValueTextRichNode(node *ast.Node) bool {
ast.NodeFileAnnotationRefText:
return true
case ast.NodeLinkDest:
- return isAllowedValueTextRichLinkTarget(node.TokensStr())
+ return isAllowedValueTextRichLinkTarget(node.TokensStr()) ||
+ localLinks && !node.ParentIs(ast.NodeImage) && isAllowedTableCellRichLocalLinkTarget(node.TokensStr())
case ast.NodeCodeBlock, ast.NodeCodeBlockFenceInfoMarker:
return !isValueTextRichExecutableCodeFence(node.CodeBlockInfo)
case ast.NodeKramdownBlockIAL:
@@ -713,7 +714,7 @@ func isAllowedValueTextRichNode(node *ast.Node) bool {
case ast.NodeKramdownSpanIAL:
return isAllowedValueTextRichSpanIAL(node)
case ast.NodeTextMark:
- return isAllowedValueTextMark(node)
+ return isAllowedValueTextMark(node, localLinks)
}
return false
}
@@ -730,8 +731,8 @@ func isValueTextRichExecutableCodeFence(info []byte) bool {
return false
}
-func isAllowedValueTextMark(node *ast.Node) bool {
- if !isAllowedValueTextMarkType(node) || !isAllowedValueTextMarkReferenceData(node) {
+func isAllowedValueTextMark(node *ast.Node, localLinks bool) bool {
+ if !isAllowedValueTextMarkType(node) || !isAllowedValueTextMarkReferenceData(node, localLinks) {
return false
}
if 1 > len(node.KramdownIAL) {
@@ -756,7 +757,7 @@ func isAllowedValueTextMarkType(node *ast.Node) bool {
return true
}
-func isAllowedValueTextMarkReferenceData(node *ast.Node) bool {
+func isAllowedValueTextMarkReferenceData(node *ast.Node, localLinks bool) bool {
if node.IsTextMarkType("block-ref") {
if !ast.IsNodeIDPattern(node.TextMarkBlockRefID) ||
("d" != node.TextMarkBlockRefSubtype && "s" != node.TextMarkBlockRefSubtype) ||
@@ -780,7 +781,8 @@ func isAllowedValueTextMarkReferenceData(node *ast.Node) bool {
}
if node.IsTextMarkType("a") {
- if !isAllowedValueTextRichLinkTarget(node.TextMarkAHref) {
+ if !isAllowedValueTextRichLinkTarget(node.TextMarkAHref) &&
+ !(localLinks && isAllowedTableCellRichLocalLinkTarget(node.TextMarkAHref)) {
return false
}
} else if "" != node.TextMarkAHref || "" != node.TextMarkATitle {
diff --git a/kernel/av/value_text_test.go b/kernel/av/value_text_test.go
index 9b3c35c5eb..553d814808 100644
--- a/kernel/av/value_text_test.go
+++ b/kernel/av/value_text_test.go
@@ -987,20 +987,20 @@ func TestValueTextRichLinkTargetPolicy(t *testing.T) {
for _, target := range allowed {
linkDest := &ast.Node{Type: ast.NodeLinkDest, Tokens: []byte(target)}
textMark := &ast.Node{Type: ast.NodeTextMark, TextMarkType: "a", TextMarkAHref: target}
- if !isAllowedValueTextRichNode(linkDest) {
+ if !isAllowedValueTextRichNode(linkDest, false) {
t.Fatalf("allowed classic link destination was rejected: %q", target)
}
- if !isAllowedValueTextMark(textMark) {
+ if !isAllowedValueTextMark(textMark, false) {
t.Fatalf("allowed text mark link destination was rejected: %q", target)
}
}
for _, target := range blocked {
linkDest := &ast.Node{Type: ast.NodeLinkDest, Tokens: []byte(target)}
textMark := &ast.Node{Type: ast.NodeTextMark, TextMarkType: "a", TextMarkAHref: target}
- if isAllowedValueTextRichNode(linkDest) {
+ if isAllowedValueTextRichNode(linkDest, false) {
t.Fatalf("unsafe classic link destination was accepted: %q", target)
}
- if isAllowedValueTextMark(textMark) {
+ if isAllowedValueTextMark(textMark, false) {
t.Fatalf("unsafe text mark link destination was accepted: %q", target)
}
}
@@ -1045,13 +1045,13 @@ func TestValueTextRichInlineMemoIsPlainText(t *testing.T) {
}
for _, content := range allowed {
node := &ast.Node{Type: ast.NodeTextMark, TextMarkType: "inline-memo", TextMarkInlineMemoContent: content}
- if !isAllowedValueTextMark(node) {
+ if !isAllowedValueTextMark(node, false) {
t.Fatalf("plain inline memo was rejected: %q", content)
}
}
for _, content := range blocked {
node := &ast.Node{Type: ast.NodeTextMark, TextMarkType: "inline-memo", TextMarkInlineMemoContent: content}
- if isAllowedValueTextMark(node) {
+ if isAllowedValueTextMark(node, false) {
t.Fatalf("active or ambiguous inline memo was accepted: %q", content)
}
}
diff --git a/kernel/filesys/table_cell_rich_test.go b/kernel/filesys/table_cell_rich_test.go
index 10683e2369..ebe90f5cb1 100644
--- a/kernel/filesys/table_cell_rich_test.go
+++ b/kernel/filesys/table_cell_rich_test.go
@@ -49,9 +49,27 @@ func TestTableCellRichEncryptedLegacyReadAndAuthentication(t *testing.T) {
t.Fatal("reading a supported encrypted document must not enable rich text")
}
cell := tree.Root.FirstChild.LastChild.FirstChild
- cell.TableCellRich = &ast.TableCellRich{Spec: 1, Format: "kramdown", Content: "- first\n- second"}
+ source := "- first\n- second\n\n" +
+ `<span data-type="a" data-href="D:\基线测试\文档.docx" data-title="title">local link</span>`
+ cell.TableCellRich = &ast.TableCellRich{Spec: 1, Format: "kramdown", Content: source}
treenode.UpgradeSpec(tree)
luteEngine := util.NewLute()
+ data := render.NewJSONRenderer(tree, luteEngine.RenderOptions, luteEngine.ParseOptions).Render()
+ richCiphertext, err := encryptDataWithDEK(boxID, documentPath, data, dek)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err = os.WriteFile(absPath, richCiphertext, 0600); err != nil {
+ t.Fatal(err)
+ }
+ cache.ClearTreeCache()
+ restored, err := LoadTree(boxID, documentPath, luteEngine)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if restored.Root.FirstChild.LastChild.FirstChild.TableCellRich.Content != source {
+ t.Fatal("authenticated table reads must preserve local links")
+ }
for _, invalid := range []ast.TableCellRich{
{Spec: 99, Format: "kramdown", Content: "preserve"},
{Spec: 1, Format: "kramdown", Content: "preserve\x00source"},
diff --git a/kernel/model/table_cell_rich_test.go b/kernel/model/table_cell_rich_test.go
index dba9c24143..dd9d8f394f 100644
--- a/kernel/model/table_cell_rich_test.go
+++ b/kernel/model/table_cell_rich_test.go
@@ -40,7 +40,9 @@ func TestTableCellRichDocumentReaders(t *testing.T) {
source := "- **first**\n- second\n\n```go\na | b\nc\n```"
for _, source := range []string{source, source + "\n" +
`{: id="20260921000000-code001" linewrap="false" linenumber="true" ligatures="false"}`,
- source + "\n" + `{: id="20260921000000-code001" custom-sy-code-tab-spaces="2"}`} {
+ source + "\n" + `{: id="20260921000000-code001" custom-sy-code-tab-spaces="2"}`,
+ `first <span data-type="a" data-href="D:\基线测试\文档.docx" data-title="title">anchor</span>` + "\n\n" +
+ `<span data-type="a" data-href="file:///D:\基线测试\文档.docx">file anchor</span>`} {
for name, read := range readers {
t.Run(name, func(t *testing.T) {
tree, err := read(legacy)
@@ -128,7 +130,8 @@ func TestTableCellRichHTMLAndMarkdownExports(t *testing.T) {
luteEngine := util.NewLute()
source := "- **first**\n- second\n\n```go\na | b\nc\n```\n" +
`{: id="20260921000000-code001" linewrap="false" linenumber="true" ligatures="false" custom-sy-code-tab-spaces="2"}` +
- "\n\n![image](assets/original.png)"
+ "\n\n![image](assets/original.png)\n\n" +
+ `<span data-type="a" data-href="file:///D:/baseline/document.txt" data-title="Local title">local link</span>`
tree := parse.Parse("", []byte("| Header |\n| --- |\n| value |"), luteEngine.ParseOptions)
cell := tree.Root.FirstChild.LastChild.FirstChild
cell.TableCellRich = &ast.TableCellRich{Spec: 1, Format: "kramdown", Content: source}
@@ -141,7 +144,8 @@ func TestTableCellRichHTMLAndMarkdownExports(t *testing.T) {
t.Fatalf("standard Markdown contains internal rich source: %s", markdown)
}
}
- if !strings.Contains(markdown, "first") || !strings.Contains(markdown, "original.png") {
+ if !strings.Contains(markdown, "first") || !strings.Contains(markdown, "original.png") ||
+ !strings.Contains(markdown, "file:///D:/baseline/document.txt") {
t.Fatal("Markdown projection lost content")
}
if err := treenode.MaterializeTableCellRichExport(tree.Root); nil != err {
@@ -171,6 +175,9 @@ func TestTableCellRichHTMLAndMarkdownExports(t *testing.T) {
if !strings.Contains(html, expected) {
t.Fatalf("export missing %q: %s", expected, html)
}
+ if !strings.Contains(html, "file:///D:/baseline/document.txt") || !strings.Contains(html, "Local title") {
+ t.Fatalf("export lost the local link or its title: %s", html)
+ }
}
if strings.Contains(html, "original.png") || strings.Contains(html, "table-cell-rich") {
t.Fatal("export used stale source")