An open-source, privacy-first, self-hosted knowledge workspace where humans and AI agents work together 开源、隐私优先、自托管的知识工作空间,让人与智能体在此协作
TypeScript agentic-aiai-agentknowledge-baselocal-firstmarkdownmcpmindmapnote-takingself-hostedsiyuanworkspace
:lock: Escape PDF annotation fields and validate .sya on the kernel side https://github.com/siyuan-note/siyuan/security/advisories/GHSA-fqpw-c3pj-w8g9
Daniel7c74f7186473
diff --git a/app/src/asset/anno.ts b/app/src/asset/anno.tsindex d7dd0656d1..37e67364f1 100644--- a/app/src/asset/anno.ts+++ b/app/src/asset/anno.ts@@ -9,6 +9,7 @@ import {Dialog} from "../dialog";import {showMessage} from "../dialog/message";import {isMobile} from "../util/functions";import {confirmDialog} from "../dialog/confirmDialog";+import {escapeAttr, escapeHtml} from "../util/escape";import {filesize} from "filesize";export const initAnno = (element: HTMLElement, pdf: any) => {@@ -160,8 +161,8 @@ export const initAnno = (element: HTMLElement, pdf: any) => {const config = getConfig(pdf);const annoItem = config[rectElement.getAttribute("data-node-id")];annoItem.color = color;- element.querySelectorAll(`.pdf__rect[data-node-id="${rectElement.getAttribute("data-node-id")}"]`).forEach(rectItem => {- (rectItem as HTMLElement).style.setProperty("--pdf-annotation-color", color);+ getRectElementsByNodeId(element, rectElement.getAttribute("data-node-id")).forEach(rectItem => {+ rectItem.style.setProperty("--pdf-annotation-color", color);});fetchPost("/api/asset/setFileAnnotation", {path: pdf.appConfig.file.replace(location.origin, "").substr(1) + ".sya",@@ -196,7 +197,7 @@ export const initAnno = (element: HTMLElement, pdf: any) => {const config = getConfig(pdf);const id = rectElement.getAttribute("data-node-id");delete config[id];- element.querySelectorAll(`[data-node-id="${id}"]`).forEach(item => {+ getRectElementsByNodeId(element, id).forEach(item => {item.remove();});fetchPost("/api/asset/setFileAnnotation", {@@ -231,8 +232,8 @@ export const initAnno = (element: HTMLElement, pdf: any) => {} else {annoItem.type = "border";}- element.querySelectorAll(`.pdf__rect[data-node-id="${rectElement.getAttribute("data-node-id")}"]`).forEach(rectItem => {- (rectItem as HTMLElement).dataset.type = annoItem.type;+ getRectElementsByNodeId(element, rectElement.getAttribute("data-node-id")).forEach(rectItem => {+ rectItem.dataset.type = annoItem.type;});fetchPost("/api/asset/setFileAnnotation", {path: pdf.appConfig.file.replace(location.origin, "").substr(1) + ".sya",@@ -276,8 +277,8 @@ const getRelationHTML = (ids: string[]) => {}let html = "";ids.forEach((id: string) => {- html += `<li data-id="${id}" class="popover__block b3-list-item b3-list-item--narrow b3-list-item--hide-action">- <span class="b3-list-item__text">${id}</span>+ html += `<li data-id="${escapeAttr(id)}" class="popover__block b3-list-item b3-list-item--narrow b3-list-item--hide-action">+ <span class="b3-list-item__text">${escapeHtml(id)}</span><span data-type="clear" class="b3-tooltips b3-tooltips__w b3-list-item__action" aria-label="${window.siyuan.languages.delete}"><svg><use xlink:href="#iconTrashcan"></use></svg></span>@@ -286,6 +287,17 @@ const getRelationHTML = (ids: string[]) => {return html;};+const getRectElementsByNodeId = (element: HTMLElement, id: string | null) => {+ // 通过属性值比较而非 CSS 选择器插值,避免 .sya 中的 ID 破坏选择器 https://github.com/siyuan-note/siyuan/security/advisories/GHSA-fqpw-c3pj-w8g9+ const results: HTMLElement[] = [];+ element.querySelectorAll("[data-node-id]").forEach(item => {+ if (item.getAttribute("data-node-id") === id) {+ results.push(item as HTMLElement);+ }+ });+ return results;+};+const setRelation = (pdf: any) => {const config = getConfig(pdf);const configItem = config[rectElement.getAttribute("data-node-id")];@@ -447,7 +459,8 @@ const getHightlightCoordsByRange = (pdf: any, color: string) => {range.setEndAfter(getTextNode(startPage.textLayer.div, false));}- const startSelected: number[] = [];+ // push 入的是 convertToPdfPoint 拼接后的 4 元素数组,因此 startSelected 实际为 number[][]+ const startSelected: number[][] = [];mergeRects(range).forEach(function (r) {startSelected.push(startViewport.convertToPdfPoint(r.left - startPageRect.x,@@ -456,7 +469,7 @@ const getHightlightCoordsByRange = (pdf: any, color: string) => {);});- const endSelected: number[] = [];+ const endSelected: number[][] = [];if (startIndex !== endIndex) {focusByRange(cloneRange);const endPage = pdf.pdfViewer.getPageView(endIndex);@@ -475,7 +488,7 @@ const getHightlightCoordsByRange = (pdf: any, color: string) => {const id = Lute.NewNodeID();const pages: {index: number- positions: number[]+ positions: number[][]}[] = [];const results = [];if (startSelected.length > 0) {@@ -534,7 +547,7 @@ const getHightlightCoordsByRect = (pdf: any, color: string, rectResizeElement: Hconst pages: {index: number- positions: number[]+ positions: number[][]}[] = [{index: startPage.id - 1,@@ -679,28 +692,37 @@ const showHighlight = (selected: IPdfAnno, pdf: any, hl?: boolean) => {} else {rectsElement.removeAttribute("data-main-rotation");}- let html = `<div class="pdf__rect popover__block" data-node-id="${selected.id}" data-relations="${selected.ids || ""}" data-mode="${selected.mode}" data-type="${selected.type}" style="--pdf-annotation-color: ${selected.color}">`;+ // 使用 setAttribute 构建元素,避免将 .sya 中的数据拼接到 HTML 中 https://github.com/siyuan-note/siyuan/security/advisories/GHSA-fqpw-c3pj-w8g9+ const rectDiv = document.createElement("div");+ rectDiv.className = "pdf__rect popover__block";+ rectDiv.setAttribute("data-node-id", selected.id);+ rectDiv.setAttribute("data-relations", selected.ids ? selected.ids.join(",") : "");+ rectDiv.setAttribute("data-mode", selected.mode);+ rectDiv.setAttribute("data-type", selected.type);+ rectDiv.style.setProperty("--pdf-annotation-color", selected.color);selected.coords.forEach((rect) => {const bounds = viewport.convertToViewportRectangle(rect);const width = Math.abs(bounds[0] - bounds[2]);if (width <= 0) {return;}- html += `<div style="left:${Math.min(bounds[0], bounds[2])}px;-top:${Math.min(bounds[1], bounds[3])}px;-width:${width}px;-height: ${Math.abs(bounds[1] - bounds[3])}px"></div>`;+ const rectChild = document.createElement("div");+ rectChild.style.left = `${Math.min(bounds[0], bounds[2])}px`;+ rectChild.style.top = `${Math.min(bounds[1], bounds[3])}px`;+ rectChild.style.width = `${width}px`;+ rectChild.style.height = `${Math.abs(bounds[1] - bounds[3])}px`;+ rectDiv.append(rectChild);});- rectsElement.insertAdjacentHTML("beforeend", html + "</div>");- rectsElement.lastElementChild.setAttribute("data-content", selected.content);+ rectDiv.setAttribute("data-content", selected.content);+ rectsElement.append(rectDiv);if (hl) {hlPDFRect(rectsElement, selected.id);}- return rectsElement.lastElementChild as HTMLElement;+ return rectDiv;};export const hlPDFRect = (element: HTMLElement, id: string) => {- element.querySelectorAll(`.pdf__rect[data-node-id="${id}"]`).forEach(item => {+ getRectElementsByNodeId(element, id).forEach(item => {if (item && item.firstElementChild) {const scrollElement = hasClosestByAttribute(item, "id", "viewerContainer");if (scrollElement) {@@ -839,7 +861,11 @@ const getConfig = (pdf: any) => {}, (response) => {let config = {};if (response.code !== 1) {- config = JSON.parse(response.data.data);+ try {+ config = JSON.parse(response.data.data);+ } catch (e) {+ config = {};+ }}pdf.appConfig.config = config;});diff --git a/app/src/types/index.d.ts b/app/src/types/index.d.tsindex eafabaab50..b765630f4f 100644--- a/app/src/types/index.d.ts+++ b/app/src/types/index.d.ts@@ -486,7 +486,7 @@ interface IInbox {interface IPdfAnno {pages?: {index: number- positions: number[]+ positions: number[][]}[]index?: number,color: string,@@ -494,7 +494,7 @@ interface IPdfAnno {content: string, // rect, textmode: string,id?: string,- coords?: number[]+ coords?: number[][]ids?: string[]}diff --git a/kernel/api/asset.go b/kernel/api/asset.goindex ce89b8c2a5..0462a06a81 100644--- a/kernel/api/asset.go+++ b/kernel/api/asset.go@@ -17,6 +17,7 @@package apiimport (+ "encoding/json""fmt""net/http""os"@@ -277,6 +278,20 @@ func getDocAssets(c *gin.Context) {ret.Data = assets}+// fileAnno 是 PDF 文件标注 .sya 的校验结构,setFileAnnotation 通过它约束客户端提交的数据结构,避免任意字符串落盘+// https://github.com/siyuan-note/siyuan/security/advisories/GHSA-fqpw-c3pj-w8g9+type fileAnno struct {+ Pages []struct {+ Index int `json:"index"`+ Positions [][]float64 `json:"positions"`+ } `json:"pages"`+ Color string `json:"color"`+ Type string `json:"type"`+ Content string `json:"content"`+ Mode string `json:"mode"`+ IDs []string `json:"ids"`+}+func setFileAnnotation(c *gin.Context) {ret := gulu.Ret.NewResult()defer c.JSON(http.StatusOK, ret)@@ -308,8 +323,25 @@ func setFileAnnotation(c *gin.Context) {return}} else {+ var annos map[string]fileAnno+ if err = json.Unmarshal([]byte(data), &annos); err != nil {+ ret.Code = -1+ ret.Msg = err.Error()+ return+ }+ if annos == nil {+ ret.Code = -1+ ret.Msg = "invalid annotation"+ return+ }+ normalized, err := json.Marshal(annos)+ if err != nil {+ ret.Code = -1+ ret.Msg = err.Error()+ return+ }// 加密笔记本的 .sya 写盘前必须加密;加密笔记本未解锁时拒绝写入(fail-closed,避免明文落盘)- writeData := []byte(data)+ writeData := normalizedif boxID != "" && model.IsEncryptedBox(boxID) {dek, dekErr := model.GetDEKIfUnlocked(boxID)if dekErr != nil {