diff --git a/plugins/live-markdown/CHANGELOG.md b/plugins/live-markdown/CHANGELOG.md index c446a220b..e34419a98 100644 --- a/plugins/live-markdown/CHANGELOG.md +++ b/plugins/live-markdown/CHANGELOG.md @@ -5,6 +5,18 @@ All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). +## 0.1.1 - 2026-11-25 + +### Fixed + +- 修复 WebDAV 同步时不同工作区的同名文件会映射到同一远端路径、互相覆盖的问题:本设备记录每个云端文件绑定的本地文件和上次同步的内容,上传或拉取前先核对;会覆盖未同步内容时按冲突跳过并提示原因。 +- 本地与云端在上次同步后都被修改时视为冲突,两侧都不写入;升级后首次同步时,内容不一致且没有同步记录的文件会被拦下,内容一致的文件直接建立绑定。 +- 保存后自动上传遇到同名冲突时也会提示,避免本地与云端悄悄分叉。 + +### Changed + +- 拆分 WebDAV 同步模块为传输层、同步记录与冲突判定、同步流程三部分;每次上传前先读取云端内容用于核对。 + ## 0.1.0 - 2026-11-17 ### 工作区多文件夹支持与默认工作区移除(2026-11-17) diff --git a/plugins/live-markdown/package-lock.json b/plugins/live-markdown/package-lock.json index 29df7f62f..fabfbdfe3 100644 --- a/plugins/live-markdown/package-lock.json +++ b/plugins/live-markdown/package-lock.json @@ -1,12 +1,12 @@ { "name": "ztools-live-markdown", - "version": "0.1.0", + "version": "0.1.1", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "ztools-live-markdown", - "version": "0.1.0", + "version": "0.1.1", "license": "MIT", "dependencies": { "@codemirror/commands": "^6.11.1", diff --git a/plugins/live-markdown/package.json b/plugins/live-markdown/package.json index 616551de3..9fdd32149 100644 --- a/plugins/live-markdown/package.json +++ b/plugins/live-markdown/package.json @@ -1,6 +1,6 @@ { "name": "ztools-live-markdown", - "version": "0.1.0", + "version": "0.1.1", "private": true, "type": "module", "description": "High-performance live-preview Markdown editor built in React 19 & TypeScript for ZTools.", diff --git a/plugins/live-markdown/plugin.json b/plugins/live-markdown/plugin.json index 3ec161073..a5e56e5ef 100644 --- a/plugins/live-markdown/plugin.json +++ b/plugins/live-markdown/plugin.json @@ -3,7 +3,7 @@ "title": "Live Markdown", "description": "高性能沉浸式所见即所得 Markdown 编辑器:支持实时预览/源码模式切换、大纲与文件树、全局搜索、数学公式、Mermaid 图表、交互式表格、专注模式、打字机模式与 6 套经典排版主题", "author": "harris", - "version": "0.1.0", + "version": "0.1.1", "main": "dist/index.html", "preload": "preload/services.cjs", "logo": "logo.svg", diff --git a/plugins/live-markdown/preload/webdav-sync-ledger.cjs b/plugins/live-markdown/preload/webdav-sync-ledger.cjs new file mode 100644 index 000000000..269d6b3a5 --- /dev/null +++ b/plugins/live-markdown/preload/webdav-sync-ledger.cjs @@ -0,0 +1,147 @@ +"use strict"; + +// WebDAV 同步台账与冲突守卫。 +// +// 远端文件只按文件名寻址,不同工作区的同名文件会映射到同一个远端路径。 +// 台账按「服务器 + 远端目录 + 文件名」记录本设备上次同步时绑定的本地文件和内容哈希, +// 任何写入(上传覆盖云端、拉取覆盖本地)都必须证明被覆盖的一侧正是上次同步的版本, +// 否则视为冲突并跳过,绝不静默覆盖。 + +const crypto = require("node:crypto"); +const path = require("node:path"); + +const LEDGER_STORAGE_KEY = "live_markdown_webdav_sync_ledger_v1"; + +function hashContent(content) { + return crypto.createHash("sha256").update(String(content ?? ""), "utf8").digest("hex"); +} + +function normalizeLocalPath(filePath) { + if (!filePath || typeof filePath !== "string") return null; + const resolved = path.resolve(filePath); + return process.platform === "win32" ? resolved.toLowerCase() : resolved; +} + +function remoteKey(config, fileName) { + const server = String(config.serverUrl || "").trim().replace(/\/+$/, ""); + return `${server}|${config.remotePath}|${fileName}`; +} + +function resolveDefaultStorage() { + const ztools = typeof window !== "undefined" ? window.ztools : null; + if (ztools?.dbStorage && typeof ztools.dbStorage.getItem === "function" && typeof ztools.dbStorage.setItem === "function") { + return ztools.dbStorage; + } + if (typeof localStorage !== "undefined" && typeof localStorage.getItem === "function" && typeof localStorage.setItem === "function") { + return localStorage; + } + return null; +} + +function createMemoryStorage() { + const map = new Map(); + return { + getItem: (key) => (map.has(key) ? map.get(key) : null), + setItem: (key, value) => { + map.set(key, String(value)); + } + }; +} + +function createWebdavSyncLedger(storage) { + const store = storage || resolveDefaultStorage() || createMemoryStorage(); + + // 台账损坏时按“没有任何同步记录”处理:只会产生更多冲突提示,不会放行覆盖。 + function readAll() { + try { + const raw = store.getItem(LEDGER_STORAGE_KEY); + if (!raw) return {}; + const parsed = typeof raw === "string" ? JSON.parse(raw) : raw; + return parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : {}; + } catch { + return {}; + } + } + + function writeAll(entries) { + store.setItem(LEDGER_STORAGE_KEY, JSON.stringify(entries)); + } + + return { + get(config, fileName) { + const entry = readAll()[remoteKey(config, fileName)]; + return entry && typeof entry === "object" ? entry : null; + }, + record(config, fileName, { localPath, contentHash }) { + const all = readAll(); + // 本地路径为空(未保存文档)表示“未绑定”:守卫只按内容哈希判定,之后另存为的文件可以正常接管。 + all[remoteKey(config, fileName)] = { + localPath: normalizeLocalPath(localPath), + contentHash, + syncedAt: Date.now() + }; + writeAll(all); + }, + forget(config, fileName) { + const all = readAll(); + delete all[remoteKey(config, fileName)]; + writeAll(all); + } + }; +} + +/** 拉取:云端内容将写入 localPath。localHash 为 null 表示本地文件不存在。 */ +function decidePullWrite({ binding, localPath, localHash, remoteHash }) { + if (localHash === null || localHash === remoteHash) return { allowed: true }; + const normalized = normalizeLocalPath(localPath); + if (binding && binding.localPath && binding.localPath !== normalized) { + return { allowed: false, reason: "bound-elsewhere" }; + } + if (binding && binding.localPath === normalized) { + return binding.contentHash === localHash + ? { allowed: true } + : { allowed: false, reason: "local-modified" }; + } + return { allowed: false, reason: "local-unknown" }; +} + +/** 上传:localPath 的内容将覆盖云端。remoteHash 为 null 表示云端文件不存在。 */ +function decidePushWrite({ binding, localPath, localHash, remoteHash }) { + if (remoteHash === null || remoteHash === localHash) return { allowed: true }; + if (!binding) return { allowed: false, reason: "unknown-remote" }; + const normalized = normalizeLocalPath(localPath); + if (binding.localPath && binding.localPath !== normalized) { + return { allowed: false, reason: "bound-elsewhere" }; + } + return binding.contentHash === remoteHash + ? { allowed: true } + : { allowed: false, reason: "remote-changed" }; +} + +function describeConflict(direction, fileName, reason) { + const action = direction === "push" ? "上传" : "拉取"; + switch (reason) { + case "bound-elsewhere": + return `《${fileName}》已与另一个本地文件同步(可能是其他工作区的同名文件),已跳过${action}以免互相覆盖。请重命名其中一个文件,或为该工作区使用独立的 WebDAV 远端目录。`; + case "remote-changed": + return `云端《${fileName}》在上次同步后已被其他设备或工作区修改,已跳过上传以免覆盖云端内容,请先核对差异。`; + case "unknown-remote": + return `云端已存在内容不同的《${fileName}》,且本设备没有它的同步记录,已跳过上传以免覆盖云端内容。确认以本地为准时,可先在 WebDAV 面板删除云端副本再同步。`; + case "local-modified": + return `本地《${fileName}》有尚未同步的修改,与云端内容不一致,已跳过拉取以免覆盖本地文件。`; + case "local-unknown": + default: + return `本地已存在内容不同的《${fileName}》,且本设备没有它的同步记录,已跳过${action}以免覆盖。确认以云端为准时,可先移走或重命名本地文件再拉取。`; + } +} + +module.exports = { + LEDGER_STORAGE_KEY, + hashContent, + normalizeLocalPath, + createWebdavSyncLedger, + createMemoryStorage, + decidePullWrite, + decidePushWrite, + describeConflict +}; diff --git a/plugins/live-markdown/preload/webdav-sync.cjs b/plugins/live-markdown/preload/webdav-sync.cjs index 1278dcf7b..81c43f5c3 100644 --- a/plugins/live-markdown/preload/webdav-sync.cjs +++ b/plugins/live-markdown/preload/webdav-sync.cjs @@ -1,303 +1,46 @@ "use strict"; +// WebDAV 同步编排层:连接测试、上传、拉取、删除与工作区同步。 +// 传输细节在 webdav-transport.cjs;所有覆盖写入(云端或本地)都先经过 webdav-sync-ledger.cjs 的冲突守卫。 + const fs = require("node:fs"); const path = require("node:path"); -const http = require("node:http"); -const https = require("node:https"); -const { URL } = require("node:url"); - -const { isMarkdownFile } = require("./fs-workspace.cjs"); - -function normalizeRemotePath(remotePath) { - const raw = String(remotePath || "/TyporaNotes/").trim(); - const collapsed = raw.replace(/\\/g, "/").replace(/\/+/g, "/"); - const withLeading = collapsed.startsWith("/") ? collapsed : `/${collapsed}`; - return withLeading.endsWith("/") ? withLeading : `${withLeading}/`; -} - -function normalizeWebdavConfig(config = {}) { - const serverUrl = String(config.serverUrl || "").trim(); - const username = String(config.username || "").trim(); - const password = String(config.password || ""); - const remotePath = normalizeRemotePath(config.remotePath); - const syncDirection = - config.syncDirection === "push" || config.syncDirection === "pull" - ? config.syncDirection - : "bidirectional"; - - return { - enabled: Boolean(config.enabled), - serverUrl, - username, - password, - remotePath, - autoSyncOnSave: config.autoSyncOnSave !== false, - syncDirection - }; -} - -function sanitizeDocFileName(fileName) { - const base = path.basename(String(fileName || "Untitled.md").trim() || "Untitled.md"); - const ext = path.extname(base).toLowerCase(); - if (!ext) { - return `${base}.md`; - } - return base; -} - -function isMarkdownFileName(fileName) { - return isMarkdownFile(String(fileName || "")); -} - -function buildAuthHeader(username, password) { - if (!username && !password) return null; - const token = Buffer.from(`${username}:${password}`, "utf8").toString("base64"); - return `Basic ${token}`; -} - -function resolveWebdavUrl(serverUrl, remotePath, fileName = "") { - if (!serverUrl) { - throw new Error("WebDAV 服务器地址不能为空"); - } - let parsedBase; - try { - parsedBase = new URL(serverUrl); - } catch { - throw new Error(`无效的 WebDAV 服务器 URL: ${serverUrl}`); - } - if (parsedBase.protocol !== "http:" && parsedBase.protocol !== "https:") { - throw new Error("WebDAV 仅支持 http:// 或 https:// 协议"); - } - - const basePath = parsedBase.pathname.replace(/\/+$/, ""); - const relSegments = normalizeRemotePath(remotePath) - .split("/") - .filter(Boolean) - .map((seg) => encodeURIComponent(decodeURIComponent(seg))); - - let fullPathname = `${basePath}/${relSegments.join("/")}/`.replace(/\/+/g, "/"); - if (fileName) { - const safeFile = sanitizeDocFileName(fileName); - fullPathname = `${fullPathname}${encodeURIComponent(safeFile)}`; - } - - const target = new URL(parsedBase.toString()); - target.pathname = fullPathname; - return target; -} - -function sendWebdavRequest(targetUrl, options = {}, redirectCount = 0) { - const urlObj = targetUrl instanceof URL ? targetUrl : new URL(String(targetUrl)); - const client = urlObj.protocol === "https:" ? https : http; - const method = options.method || "GET"; - const timeoutMs = options.timeoutMs || 12000; - const maxRedirects = options.maxRedirects ?? 3; - const bodyBuffer = - options.body === undefined || options.body === null - ? null - : Buffer.isBuffer(options.body) - ? options.body - : Buffer.from(String(options.body), "utf8"); - - const headers = { - "User-Agent": "ZTools-Markdown-WebDAV/1.0", - ...(options.headers || {}) - }; - - if (bodyBuffer) { - headers["Content-Length"] = String(bodyBuffer.length); - } - - return new Promise((resolve, reject) => { - const req = client.request( - urlObj, - { - method, - headers, - timeout: timeoutMs - }, - (res) => { - const statusCode = res.statusCode || 0; - const locationHeader = res.headers?.location; - if ( - [301, 302, 307, 308].includes(statusCode) && - locationHeader && - redirectCount < maxRedirects - ) { - res.resume(); - try { - const redirectedUrl = new URL(locationHeader, urlObj); - if ( - redirectedUrl.protocol === "http:" || - redirectedUrl.protocol === "https:" - ) { - resolve( - sendWebdavRequest(redirectedUrl, options, redirectCount + 1) - ); - return; - } - } catch { - // Fall through and return raw response if redirect URL is malformed - } - } - const chunks = []; - res.on("data", (chunk) => chunks.push(chunk)); - res.on("end", () => { - const buffer = Buffer.concat(chunks); - resolve({ - statusCode, - statusMessage: res.statusMessage || "", - headers: res.headers || {}, - bodyBuffer: buffer, - bodyText: buffer.toString("utf8") - }); - }); - } - ); - - req.on("timeout", () => { - req.destroy(new Error(`WebDAV 请求超时 (${timeoutMs}ms)`)); - }); - - req.on("error", (err) => { - reject(err); - }); - - if (bodyBuffer && bodyBuffer.length > 0) { - req.write(bodyBuffer); - } - req.end(); - }); +const { + normalizeRemotePath, + normalizeWebdavConfig, + sanitizeDocFileName, + isMarkdownFileName, + buildAuthHeader, + resolveWebdavUrl, + sendWebdavRequest, + ensureRemoteCollection, + parsePropfindXml +} = require("./webdav-transport.cjs"); +const { + hashContent, + createWebdavSyncLedger, + decidePullWrite, + decidePushWrite, + describeConflict +} = require("./webdav-sync-ledger.cjs"); + +let defaultLedger = null; +function resolveLedger(options) { + if (options && options.ledger) return options.ledger; + if (!defaultLedger) defaultLedger = createWebdavSyncLedger(); + return defaultLedger; } -async function ensureRemoteCollection(rawConfig) { - const config = normalizeWebdavConfig(rawConfig); +function authHeaders(config) { const auth = buildAuthHeader(config.username, config.password); - const baseHeaders = auth ? { Authorization: auth } : {}; - - const segments = config.remotePath.split("/").filter(Boolean); - let cumulative = "/"; - for (const seg of segments) { - cumulative = `${cumulative}${seg}/`; - const colUrl = resolveWebdavUrl(config.serverUrl, cumulative); - const res = await sendWebdavRequest(colUrl, { - method: "MKCOL", - headers: baseHeaders - }); - // 201 Created, 405 Method Not Allowed (already exists), 200/204/207/301/302 are acceptable - if (res.statusCode === 401 || res.statusCode === 403) { - return { - ok: false, - status: res.statusCode, - message: `WebDAV 鉴权失败 (HTTP ${res.statusCode}),请检查账号或应用密码` - }; - } - } - return { ok: true, status: 201 }; -} - -function decodeXmlEntities(str) { - return String(str || "") - .replace(/&/g, "&") - .replace(/</g, "<") - .replace(/>/g, ">") - .replace(/"/g, '"') - .replace(/'/g, "'"); -} - -function extractXmlTagText(xmlBlock, localTagName) { - const regex = new RegExp( - `<(?:[a-zA-Z0-9_-]+:)?${localTagName}\\b[^>]*>([\\s\\S]*?)<\\/(?:[a-zA-Z0-9_-]+:)?${localTagName}>`, - "i" - ); - const match = xmlBlock.match(regex); - return match ? decodeXmlEntities(match[1].trim()) : ""; -} - -function isCollectionResource(xmlBlock) { - const resTypeMatch = xmlBlock.match( - /<(?:[a-zA-Z0-9_-]+:)?resourcetype\b[^>]*>([\s\S]*?)<\/(?:[a-zA-Z0-9_-]+:)?resourcetype>/i - ); - if (!resTypeMatch) return false; - return /<(?:[a-zA-Z0-9_-]+:)?collection\b/i.test(resTypeMatch[1]); -} - -function parsePropfindXml(xmlText, collectionUrlPathname) { - const responseBlocks = - String(xmlText || "").match( - /<(?:[a-zA-Z0-9_-]+:)?response\b[^>]*>[\s\S]*?<\/(?:[a-zA-Z0-9_-]+:)?response>/gi - ) || []; - - const normalizedCollectionPath = decodeURIComponent( - String(collectionUrlPathname || "").replace(/\/+$/, "") - ); - - const files = []; - const seenNames = new Set(); - - for (const block of responseBlocks) { - const rawHref = extractXmlTagText(block, "href"); - if (!rawHref) continue; - - let hrefPathname = rawHref; - try { - if (/^https?:\/\//i.test(rawHref)) { - hrefPathname = new URL(rawHref).pathname; - } - } catch { - // keep rawHref - } - - const decodedHref = decodeURIComponent(hrefPathname); - const trimmedHref = decodedHref.replace(/\/+$/, ""); - - if (!trimmedHref || trimmedHref === normalizedCollectionPath) { - continue; - } - - if (isCollectionResource(block) || decodedHref.endsWith("/")) { - continue; - } - - const fileName = path.posix.basename(trimmedHref); - if (!fileName || !isMarkdownFileName(fileName) || seenNames.has(fileName)) { - continue; - } - - const sizeStr = extractXmlTagText(block, "getcontentlength"); - const lastModStr = extractXmlTagText(block, "getlastmodified"); - const etagStr = extractXmlTagText(block, "getetag").replace(/^"+|"+$/g, ""); - - const size = Number.isFinite(Number(sizeStr)) ? Number(sizeStr) : 0; - const parsedTime = lastModStr ? Date.parse(lastModStr) : NaN; - const hasValidMtime = Number.isFinite(parsedTime); - const mtimeMs = hasValidMtime ? parsedTime : 0; - - seenNames.add(fileName); - files.push({ - name: fileName, - href: rawHref, - size, - lastModified: lastModStr || "", - mtimeMs, - hasValidMtime, - etag: etagStr - }); - } - - files.sort((a, b) => b.mtimeMs - a.mtimeMs || a.name.localeCompare(b.name)); - return files; + return auth ? { Authorization: auth } : {}; } async function testWebdavConnection(rawConfig) { try { const config = normalizeWebdavConfig(rawConfig); const collectionUrl = resolveWebdavUrl(config.serverUrl, config.remotePath); - const auth = buildAuthHeader(config.username, config.password); - const headers = { - ...(auth ? { Authorization: auth } : {}) - }; const mkcolResult = await ensureRemoteCollection(config); if (!mkcolResult.ok) { @@ -318,7 +61,7 @@ async function testWebdavConnection(rawConfig) { const res = await sendWebdavRequest(collectionUrl, { method: "PROPFIND", headers: { - ...headers, + ...authHeaders(config), Depth: "1", "Content-Type": "application/xml; charset=utf-8" }, @@ -384,73 +127,110 @@ async function listWebdavFiles(rawConfig) { }; } -async function pushWebdavDocument(rawConfig, docName, content) { +/** 读取云端文档;不存在时返回 null。 */ +async function fetchRemoteDocument(config, safeName) { + const targetUrl = resolveWebdavUrl(config.serverUrl, config.remotePath, safeName); + const res = await sendWebdavRequest(targetUrl, { method: "GET", headers: authHeaders(config) }); + if (res.statusCode === 404 || res.statusCode === 410) return null; + if (res.statusCode < 200 || res.statusCode >= 300) { + throw new Error(`拉取云端文档 ${safeName} 失败: HTTP ${res.statusCode} ${res.statusMessage}`); + } + const lastModHeader = res.headers["last-modified"]; + const parsedMtime = lastModHeader ? Date.parse(lastModHeader) : NaN; + return { + content: res.bodyText, + mtimeMs: Number.isFinite(parsedMtime) ? parsedMtime : Date.now() + }; +} + +function readLocalHash(filePath) { + if (!filePath || !fs.existsSync(filePath)) return null; + return hashContent(fs.readFileSync(filePath, "utf8")); +} + +function conflictResult(direction, safeName, reason) { + const message = describeConflict(direction, safeName, reason); + return { ok: false, conflict: true, reason, name: safeName, error: message, message }; +} + +async function pushWebdavDocument(rawConfig, docName, content, options = {}) { const config = normalizeWebdavConfig(rawConfig); + const ledger = resolveLedger(options); const safeName = sanitizeDocFileName(docName); const mkcolResult = await ensureRemoteCollection(config); if (!mkcolResult.ok) { throw new Error(mkcolResult.message); } - const targetUrl = resolveWebdavUrl(config.serverUrl, config.remotePath, safeName); - const auth = buildAuthHeader(config.username, config.password); const bodyStr = String(content ?? ""); - - const res = await sendWebdavRequest(targetUrl, { - method: "PUT", - headers: { - ...(auth ? { Authorization: auth } : {}), - "Content-Type": "text/markdown; charset=utf-8" - }, - body: bodyStr + const localHash = hashContent(bodyStr); + const localPath = typeof options.localPath === "string" && options.localPath ? options.localPath : null; + const remote = await fetchRemoteDocument(config, safeName); + const remoteHash = remote ? hashContent(remote.content) : null; + const decision = decidePushWrite({ + binding: ledger.get(config, safeName), + localPath, + localHash, + remoteHash }); + if (!decision.allowed) { + return { ...conflictResult("push", safeName, decision.reason), syncedAt: Date.now() }; + } - if (res.statusCode < 200 || res.statusCode >= 300) { - throw new Error( - `上传 ${safeName} 失败: HTTP ${res.statusCode} ${res.statusMessage}` - ); + const targetUrl = resolveWebdavUrl(config.serverUrl, config.remotePath, safeName); + if (remoteHash !== localHash) { + const res = await sendWebdavRequest(targetUrl, { + method: "PUT", + headers: { ...authHeaders(config), "Content-Type": "text/markdown; charset=utf-8" }, + body: bodyStr + }); + if (res.statusCode < 200 || res.statusCode >= 300) { + throw new Error(`上传 ${safeName} 失败: HTTP ${res.statusCode} ${res.statusMessage}`); + } } + ledger.record(config, safeName, { localPath, contentHash: localHash }); return { ok: true, name: safeName, remoteUrl: targetUrl.toString(), - status: res.statusCode, + status: 201, size: Buffer.byteLength(bodyStr, "utf8"), syncedAt: Date.now() }; } -async function pullWebdavDocument(rawConfig, remoteFileName, localTargetDir = null) { +async function pullWebdavDocument(rawConfig, remoteFileName, localTargetDir = null, options = {}) { const config = normalizeWebdavConfig(rawConfig); + const ledger = resolveLedger(options); const safeName = sanitizeDocFileName(remoteFileName); - const targetUrl = resolveWebdavUrl(config.serverUrl, config.remotePath, safeName); - const auth = buildAuthHeader(config.username, config.password); - - const res = await sendWebdavRequest(targetUrl, { - method: "GET", - headers: { - ...(auth ? { Authorization: auth } : {}) - } - }); - - if (res.statusCode < 200 || res.statusCode >= 300) { - throw new Error( - `拉取云端文档 ${safeName} 失败: HTTP ${res.statusCode} ${res.statusMessage}` - ); + const remote = await fetchRemoteDocument(config, safeName); + if (!remote) { + throw new Error(`拉取云端文档 ${safeName} 失败: HTTP 404 Not Found`); } - - const content = res.bodyText; - const lastModHeader = res.headers["last-modified"]; - const parsedMtime = lastModHeader ? Date.parse(lastModHeader) : NaN; - const mtimeMs = Number.isFinite(parsedMtime) ? parsedMtime : Date.now(); + const { content, mtimeMs } = remote; + const remoteHash = hashContent(content); let savedPath = null; let savedDir = ""; if (localTargetDir && typeof localTargetDir === "string" && fs.existsSync(localTargetDir)) { savedDir = path.resolve(localTargetDir); - savedPath = path.join(savedDir, safeName); - fs.writeFileSync(savedPath, content, "utf8"); + const targetPath = path.join(savedDir, safeName); + const localHash = readLocalHash(targetPath); + const decision = decidePullWrite({ + binding: ledger.get(config, safeName), + localPath: targetPath, + localHash, + remoteHash + }); + if (!decision.allowed) { + return { ...conflictResult("pull", safeName, decision.reason), path: null, dir: savedDir, syncedAt: Date.now() }; + } + if (localHash !== remoteHash) { + fs.writeFileSync(targetPath, content, "utf8"); + } + savedPath = targetPath; + ledger.record(config, safeName, { localPath: targetPath, contentHash: remoteHash }); } return { @@ -465,51 +245,44 @@ async function pullWebdavDocument(rawConfig, remoteFileName, localTargetDir = nu }; } -async function deleteWebdavDocument(rawConfig, remoteFileName) { +async function deleteWebdavDocument(rawConfig, remoteFileName, options = {}) { const config = normalizeWebdavConfig(rawConfig); const safeName = sanitizeDocFileName(remoteFileName); const targetUrl = resolveWebdavUrl(config.serverUrl, config.remotePath, safeName); - const auth = buildAuthHeader(config.username, config.password); - const res = await sendWebdavRequest(targetUrl, { - method: "DELETE", - headers: { - ...(auth ? { Authorization: auth } : {}) - } - }); + const res = await sendWebdavRequest(targetUrl, { method: "DELETE", headers: authHeaders(config) }); - if ( - res.statusCode !== 404 && - (res.statusCode < 200 || res.statusCode >= 300) - ) { - throw new Error( - `删除云端文档 ${safeName} 失败: HTTP ${res.statusCode} ${res.statusMessage}` - ); + if (res.statusCode !== 404 && (res.statusCode < 200 || res.statusCode >= 300)) { + throw new Error(`删除云端文档 ${safeName} 失败: HTTP ${res.statusCode} ${res.statusMessage}`); } + resolveLedger(options).forget(config, safeName); - return { - ok: true, - name: safeName, - status: res.statusCode - }; + return { ok: true, name: safeName, status: res.statusCode }; +} + +function collectLocalMarkdown(localDir) { + const localMap = new Map(); + if (!localDir) return localMap; + for (const entry of fs.readdirSync(localDir, { withFileTypes: true })) { + if (!entry.isFile() || entry.name.startsWith(".")) continue; + if (!isMarkdownFileName(entry.name)) continue; + const fullPath = path.join(localDir, entry.name); + const stat = fs.statSync(fullPath); + localMap.set(entry.name, { name: entry.name, path: fullPath, content: null, mtimeMs: stat.mtimeMs, size: stat.size }); + } + return localMap; } async function syncWorkspaceWithWebdav(rawConfig, options = {}) { const config = normalizeWebdavConfig(rawConfig); - const direction = - options.direction || config.syncDirection || "bidirectional"; + const ledgerOptions = { ledger: resolveLedger(options) }; + const direction = options.direction || config.syncDirection || "bidirectional"; const localDir = - options.localDir && - typeof options.localDir === "string" && - fs.existsSync(options.localDir) + options.localDir && typeof options.localDir === "string" && fs.existsSync(options.localDir) ? path.resolve(options.localDir) : null; const activeDoc = - options.activeDoc && - typeof options.activeDoc === "object" && - options.activeDoc.name - ? options.activeDoc - : null; + options.activeDoc && typeof options.activeDoc === "object" && options.activeDoc.name ? options.activeDoc : null; const initialList = await listWebdavFiles(config); if (!initialList.ok) { @@ -520,6 +293,7 @@ async function syncWorkspaceWithWebdav(rawConfig, options = {}) { downloaded: [], downloadedPaths: [], skipped: [], + conflicts: [], remoteFiles: [], syncedAt: Date.now(), message: initialList.message @@ -531,32 +305,18 @@ async function syncWorkspaceWithWebdav(rawConfig, options = {}) { const downloaded = []; const downloadedPaths = []; const skipped = []; + const conflicts = []; + const conflictNames = new Set(); + const noteConflict = (result, dir) => { + conflictNames.add(result.name); + conflicts.push({ name: result.name, direction: dir, reason: result.reason, message: result.message }); + }; - // 1. Collect local markdown file metadata without reading file contents upfront - const localMap = new Map(); - if (localDir) { - const entries = fs.readdirSync(localDir, { withFileTypes: true }); - for (const entry of entries) { - if (!entry.isFile() || entry.name.startsWith(".")) continue; - if (!isMarkdownFileName(entry.name)) continue; - const fullPath = path.join(localDir, entry.name); - const stat = fs.statSync(fullPath); - localMap.set(entry.name, { - name: entry.name, - path: fullPath, - content: null, - mtimeMs: stat.mtimeMs, - size: stat.size - }); - } - } + // 1. 收集本地 Markdown 元数据,不预读内容 + const localMap = collectLocalMarkdown(localDir); - // Also include activeDoc if it's not already in localMap and direction allows push - if ( - activeDoc && - (direction === "push" || direction === "bidirectional") && - !localMap.has(sanitizeDocFileName(activeDoc.name)) - ) { + // 当前文档不在工作区根目录时也参与上传 + if (activeDoc && (direction === "push" || direction === "bidirectional") && !localMap.has(sanitizeDocFileName(activeDoc.name))) { const safeActiveName = sanitizeDocFileName(activeDoc.name); const activeContent = String(activeDoc.content ?? ""); localMap.set(safeActiveName, { @@ -568,7 +328,7 @@ async function syncWorkspaceWithWebdav(rawConfig, options = {}) { }); } - // 2. Push phase (local -> remote) + // 2. 上传阶段(本地 -> 云端) if (direction === "push" || direction === "bidirectional") { for (const [name, localFile] of localMap.entries()) { const remoteFile = remoteMap.get(name); @@ -576,40 +336,36 @@ async function syncWorkspaceWithWebdav(rawConfig, options = {}) { const shouldPush = direction === "push" || !remoteFile || - (remoteHasMtime - ? localFile.mtimeMs >= remoteFile.mtimeMs - 1000 - : localFile.size !== remoteFile.size); - - if (shouldPush) { - const contentToPush = - localFile.content !== null - ? localFile.content - : fs.readFileSync(localFile.path, "utf8"); - await pushWebdavDocument(config, name, contentToPush); - uploaded.push(name); - } else { + (remoteHasMtime ? localFile.mtimeMs >= remoteFile.mtimeMs - 1000 : localFile.size !== remoteFile.size); + + if (!shouldPush) { skipped.push(name); + continue; } + const contentToPush = localFile.content !== null ? localFile.content : fs.readFileSync(localFile.path, "utf8"); + const pushed = await pushWebdavDocument(config, name, contentToPush, { ...ledgerOptions, localPath: localFile.path }); + if (pushed.ok) uploaded.push(name); + else noteConflict(pushed, "push"); } } - // 3. Pull phase (remote -> localDir) + // 3. 拉取阶段(云端 -> localDir) if ((direction === "pull" || direction === "bidirectional") && localDir) { for (const [name, remoteFile] of remoteMap.entries()) { - if (uploaded.includes(name)) continue; + if (uploaded.includes(name) || conflictNames.has(name)) continue; const localFile = localMap.get(name); const remoteHasMtime = Boolean(remoteFile.mtimeMs > 0); const shouldPull = - direction === "pull" || - !localFile || - (remoteHasMtime && remoteFile.mtimeMs > localFile.mtimeMs + 1000); + direction === "pull" || !localFile || (remoteHasMtime && remoteFile.mtimeMs > localFile.mtimeMs + 1000); if (shouldPull) { - const pulled = await pullWebdavDocument(config, name, localDir); - downloaded.push(name); - if (pulled.path) { - downloadedPaths.push(pulled.path); + const pulled = await pullWebdavDocument(config, name, localDir, ledgerOptions); + if (!pulled.ok) { + noteConflict(pulled, "pull"); + continue; } + downloaded.push(name); + if (pulled.path) downloadedPaths.push(pulled.path); } else if (!skipped.includes(name)) { skipped.push(name); } @@ -618,6 +374,7 @@ async function syncWorkspaceWithWebdav(rawConfig, options = {}) { const refreshed = await listWebdavFiles(config); const remoteFiles = refreshed.ok ? refreshed.files : initialList.files; + const conflictNote = conflicts.length > 0 ? `,${conflicts.length} 篇同名冲突已跳过` : ""; return { ok: true, @@ -626,9 +383,10 @@ async function syncWorkspaceWithWebdav(rawConfig, options = {}) { downloaded, downloadedPaths, skipped, + conflicts, remoteFiles, syncedAt: Date.now(), - message: `同步完成:上传 ${uploaded.length} 篇,下载 ${downloaded.length} 篇(云端共 ${remoteFiles.length} 篇)` + message: `同步完成:上传 ${uploaded.length} 篇,下载 ${downloaded.length} 篇${conflictNote}(云端共 ${remoteFiles.length} 篇)` }; } diff --git a/plugins/live-markdown/preload/webdav-transport.cjs b/plugins/live-markdown/preload/webdav-transport.cjs new file mode 100644 index 000000000..22741cc68 --- /dev/null +++ b/plugins/live-markdown/preload/webdav-transport.cjs @@ -0,0 +1,304 @@ +"use strict"; + +// WebDAV 传输层:URL 解析、鉴权、HTTP 请求、MKCOL 与 PROPFIND 解析。不涉及本地文件写入与冲突判定。 + +const path = require("node:path"); +const http = require("node:http"); +const https = require("node:https"); +const { URL } = require("node:url"); + +const { isMarkdownFile } = require("./fs-workspace.cjs"); + +function normalizeRemotePath(remotePath) { + const raw = String(remotePath || "/TyporaNotes/").trim(); + const collapsed = raw.replace(/\\/g, "/").replace(/\/+/g, "/"); + const withLeading = collapsed.startsWith("/") ? collapsed : `/${collapsed}`; + return withLeading.endsWith("/") ? withLeading : `${withLeading}/`; +} + +function normalizeWebdavConfig(config = {}) { + const serverUrl = String(config.serverUrl || "").trim(); + const username = String(config.username || "").trim(); + const password = String(config.password || ""); + const remotePath = normalizeRemotePath(config.remotePath); + const syncDirection = + config.syncDirection === "push" || config.syncDirection === "pull" + ? config.syncDirection + : "bidirectional"; + + return { + enabled: Boolean(config.enabled), + serverUrl, + username, + password, + remotePath, + autoSyncOnSave: config.autoSyncOnSave !== false, + syncDirection + }; +} + +function sanitizeDocFileName(fileName) { + const base = path.basename(String(fileName || "Untitled.md").trim() || "Untitled.md"); + const ext = path.extname(base).toLowerCase(); + if (!ext) { + return `${base}.md`; + } + return base; +} + +function isMarkdownFileName(fileName) { + return isMarkdownFile(String(fileName || "")); +} + +function buildAuthHeader(username, password) { + if (!username && !password) return null; + const token = Buffer.from(`${username}:${password}`, "utf8").toString("base64"); + return `Basic ${token}`; +} + +function resolveWebdavUrl(serverUrl, remotePath, fileName = "") { + if (!serverUrl) { + throw new Error("WebDAV 服务器地址不能为空"); + } + let parsedBase; + try { + parsedBase = new URL(serverUrl); + } catch { + throw new Error(`无效的 WebDAV 服务器 URL: ${serverUrl}`); + } + if (parsedBase.protocol !== "http:" && parsedBase.protocol !== "https:") { + throw new Error("WebDAV 仅支持 http:// 或 https:// 协议"); + } + + const basePath = parsedBase.pathname.replace(/\/+$/, ""); + const relSegments = normalizeRemotePath(remotePath) + .split("/") + .filter(Boolean) + .map((seg) => encodeURIComponent(decodeURIComponent(seg))); + + let fullPathname = `${basePath}/${relSegments.join("/")}/`.replace(/\/+/g, "/"); + if (fileName) { + const safeFile = sanitizeDocFileName(fileName); + fullPathname = `${fullPathname}${encodeURIComponent(safeFile)}`; + } + + const target = new URL(parsedBase.toString()); + target.pathname = fullPathname; + return target; +} + +function sendWebdavRequest(targetUrl, options = {}, redirectCount = 0) { + const urlObj = targetUrl instanceof URL ? targetUrl : new URL(String(targetUrl)); + const client = urlObj.protocol === "https:" ? https : http; + const method = options.method || "GET"; + const timeoutMs = options.timeoutMs || 12000; + const maxRedirects = options.maxRedirects ?? 3; + const bodyBuffer = + options.body === undefined || options.body === null + ? null + : Buffer.isBuffer(options.body) + ? options.body + : Buffer.from(String(options.body), "utf8"); + + const headers = { + "User-Agent": "ZTools-Markdown-WebDAV/1.0", + ...(options.headers || {}) + }; + + if (bodyBuffer) { + headers["Content-Length"] = String(bodyBuffer.length); + } + + return new Promise((resolve, reject) => { + const req = client.request( + urlObj, + { + method, + headers, + timeout: timeoutMs + }, + (res) => { + const statusCode = res.statusCode || 0; + const locationHeader = res.headers?.location; + if ( + [301, 302, 307, 308].includes(statusCode) && + locationHeader && + redirectCount < maxRedirects + ) { + res.resume(); + try { + const redirectedUrl = new URL(locationHeader, urlObj); + if ( + redirectedUrl.protocol === "http:" || + redirectedUrl.protocol === "https:" + ) { + resolve( + sendWebdavRequest(redirectedUrl, options, redirectCount + 1) + ); + return; + } + } catch { + // Fall through and return raw response if redirect URL is malformed + } + } + + const chunks = []; + res.on("data", (chunk) => chunks.push(chunk)); + res.on("end", () => { + const buffer = Buffer.concat(chunks); + resolve({ + statusCode, + statusMessage: res.statusMessage || "", + headers: res.headers || {}, + bodyBuffer: buffer, + bodyText: buffer.toString("utf8") + }); + }); + } + ); + + req.on("timeout", () => { + req.destroy(new Error(`WebDAV 请求超时 (${timeoutMs}ms)`)); + }); + + req.on("error", (err) => { + reject(err); + }); + + if (bodyBuffer && bodyBuffer.length > 0) { + req.write(bodyBuffer); + } + req.end(); + }); +} + +async function ensureRemoteCollection(rawConfig) { + const config = normalizeWebdavConfig(rawConfig); + const auth = buildAuthHeader(config.username, config.password); + const baseHeaders = auth ? { Authorization: auth } : {}; + + const segments = config.remotePath.split("/").filter(Boolean); + let cumulative = "/"; + for (const seg of segments) { + cumulative = `${cumulative}${seg}/`; + const colUrl = resolveWebdavUrl(config.serverUrl, cumulative); + const res = await sendWebdavRequest(colUrl, { + method: "MKCOL", + headers: baseHeaders + }); + // 201 Created, 405 Method Not Allowed (already exists), 200/204/207/301/302 are acceptable + if (res.statusCode === 401 || res.statusCode === 403) { + return { + ok: false, + status: res.statusCode, + message: `WebDAV 鉴权失败 (HTTP ${res.statusCode}),请检查账号或应用密码` + }; + } + } + return { ok: true, status: 201 }; +} + +function decodeXmlEntities(str) { + return String(str || "") + .replace(/&/g, "&") + .replace(/</g, "<") + .replace(/>/g, ">") + .replace(/"/g, '"') + .replace(/'/g, "'"); +} + +function extractXmlTagText(xmlBlock, localTagName) { + const regex = new RegExp( + `<(?:[a-zA-Z0-9_-]+:)?${localTagName}\\b[^>]*>([\\s\\S]*?)<\\/(?:[a-zA-Z0-9_-]+:)?${localTagName}>`, + "i" + ); + const match = xmlBlock.match(regex); + return match ? decodeXmlEntities(match[1].trim()) : ""; +} + +function isCollectionResource(xmlBlock) { + const resTypeMatch = xmlBlock.match( + /<(?:[a-zA-Z0-9_-]+:)?resourcetype\b[^>]*>([\s\S]*?)<\/(?:[a-zA-Z0-9_-]+:)?resourcetype>/i + ); + if (!resTypeMatch) return false; + return /<(?:[a-zA-Z0-9_-]+:)?collection\b/i.test(resTypeMatch[1]); +} + +function parsePropfindXml(xmlText, collectionUrlPathname) { + const responseBlocks = + String(xmlText || "").match( + /<(?:[a-zA-Z0-9_-]+:)?response\b[^>]*>[\s\S]*?<\/(?:[a-zA-Z0-9_-]+:)?response>/gi + ) || []; + + const normalizedCollectionPath = decodeURIComponent( + String(collectionUrlPathname || "").replace(/\/+$/, "") + ); + + const files = []; + const seenNames = new Set(); + + for (const block of responseBlocks) { + const rawHref = extractXmlTagText(block, "href"); + if (!rawHref) continue; + + let hrefPathname = rawHref; + try { + if (/^https?:\/\//i.test(rawHref)) { + hrefPathname = new URL(rawHref).pathname; + } + } catch { + // keep rawHref + } + + const decodedHref = decodeURIComponent(hrefPathname); + const trimmedHref = decodedHref.replace(/\/+$/, ""); + + if (!trimmedHref || trimmedHref === normalizedCollectionPath) { + continue; + } + + if (isCollectionResource(block) || decodedHref.endsWith("/")) { + continue; + } + + const fileName = path.posix.basename(trimmedHref); + if (!fileName || !isMarkdownFileName(fileName) || seenNames.has(fileName)) { + continue; + } + + const sizeStr = extractXmlTagText(block, "getcontentlength"); + const lastModStr = extractXmlTagText(block, "getlastmodified"); + const etagStr = extractXmlTagText(block, "getetag").replace(/^"+|"+$/g, ""); + + const size = Number.isFinite(Number(sizeStr)) ? Number(sizeStr) : 0; + const parsedTime = lastModStr ? Date.parse(lastModStr) : NaN; + const hasValidMtime = Number.isFinite(parsedTime); + const mtimeMs = hasValidMtime ? parsedTime : 0; + + seenNames.add(fileName); + files.push({ + name: fileName, + href: rawHref, + size, + lastModified: lastModStr || "", + mtimeMs, + hasValidMtime, + etag: etagStr + }); + } + + files.sort((a, b) => b.mtimeMs - a.mtimeMs || a.name.localeCompare(b.name)); + return files; +} + +module.exports = { + normalizeRemotePath, + normalizeWebdavConfig, + sanitizeDocFileName, + isMarkdownFileName, + buildAuthHeader, + resolveWebdavUrl, + sendWebdavRequest, + ensureRemoteCollection, + parsePropfindXml +}; diff --git a/plugins/live-markdown/scripts/verify-dist.mjs b/plugins/live-markdown/scripts/verify-dist.mjs index 0073d99f8..00c42d2e6 100644 --- a/plugins/live-markdown/scripts/verify-dist.mjs +++ b/plugins/live-markdown/scripts/verify-dist.mjs @@ -20,7 +20,9 @@ const requiredFiles = [ "preload/services.cjs", "preload/fs-workspace.cjs", "preload/exporter.cjs", - "preload/webdav-sync.cjs" + "preload/webdav-sync.cjs", + "preload/webdav-transport.cjs", + "preload/webdav-sync-ledger.cjs" ]; for (const relativePath of requiredFiles) { diff --git a/plugins/live-markdown/src/hooks/useWebdavSync.ts b/plugins/live-markdown/src/hooks/useWebdavSync.ts index 3137f4ecc..e8b685e16 100644 --- a/plugins/live-markdown/src/hooks/useWebdavSync.ts +++ b/plugins/live-markdown/src/hooks/useWebdavSync.ts @@ -146,7 +146,8 @@ export function useWebdavSync({ const res = await bridge.pushWebdavDocument( webdavConfig, doc.name || "Untitled.md", - doc.content + doc.content, + { localPath: doc.path } ); if (res.ok) { setWebdavSyncState("success"); @@ -159,7 +160,8 @@ export function useWebdavSync({ setWebdavSyncState("error"); const errMsg = res.error || "WebDAV 上传失败"; setWebdavStatusMessage(errMsg); - if (!silent) showToast(errMsg); + // 同名冲突即使在保存后静默同步时也要告知用户,否则云端与本地会悄悄分叉。 + if (!silent || res.conflict) showToast(errMsg); } } catch (err) { const msg = err instanceof Error ? err.message : String(err); @@ -172,6 +174,7 @@ export function useWebdavSync({ bridge, doc.content, doc.name, + doc.path, handleOpenWebdavSettings, handleRefreshWebdavFiles, showToast, @@ -196,7 +199,7 @@ export function useWebdavSync({ path: res.path, name: res.name, dir: res.dir || targetLocalDir || doc.dir, - content: res.content, + content: res.content ?? "", isDirty: false, mtimeMs: res.mtimeMs || Date.now() }); @@ -315,6 +318,16 @@ export function useWebdavSync({ } } + const conflicts = Array.isArray(res.conflicts) ? res.conflicts : []; + if (conflicts.length > 0) { + const detail = + conflicts.length === 1 + ? conflicts[0].message + : `${res.message}。冲突文件:${conflicts.map((c) => c.name).join("、")}`; + setWebdavStatusMessage(detail); + showToast(detail); + return; + } showToast(res.message); } else { setWebdavSyncState("error"); diff --git a/plugins/live-markdown/src/types/typora.ts b/plugins/live-markdown/src/types/typora.ts index db2a25192..167ec4114 100644 --- a/plugins/live-markdown/src/types/typora.ts +++ b/plugins/live-markdown/src/types/typora.ts @@ -203,26 +203,46 @@ export interface WebdavListResult { syncedAt: number; } +/** 同名冲突原因:写入会覆盖本设备未同步过的内容时,同步引擎拒绝写入。 */ +export type WebdavConflictReason = + | "bound-elsewhere" + | "remote-changed" + | "unknown-remote" + | "local-modified" + | "local-unknown"; + +export interface WebdavConflict { + name: string; + direction: "push" | "pull"; + reason: WebdavConflictReason; + message: string; +} + export interface WebdavPushResult { ok: boolean; name: string; - remoteUrl: string; - status: number; - size: number; + remoteUrl?: string; + status?: number; + size?: number; syncedAt: number; error?: string; + conflict?: boolean; + reason?: WebdavConflictReason; } export interface WebdavPullResult { ok: boolean; name: string; - content: string; + /** 冲突被拦截时不返回内容。 */ + content?: string; path: string | null; dir: string; - size: number; - mtimeMs: number; + size?: number; + mtimeMs?: number; syncedAt: number; error?: string; + conflict?: boolean; + reason?: WebdavConflictReason; } export interface WebdavSyncResult { @@ -232,6 +252,8 @@ export interface WebdavSyncResult { downloaded: string[]; downloadedPaths?: string[]; skipped: string[]; + /** 因同名冲突被拦截、未写入任何一侧的文件。 */ + conflicts?: WebdavConflict[]; remoteFiles: WebdavRemoteFile[]; syncedAt: number; message: string; @@ -423,7 +445,8 @@ export interface TyporaBridgeApi { pushWebdavDocument?: ( config: WebdavConfig, docName: string, - content: string + content: string, + options?: { localPath?: string | null } ) => Promise; pullWebdavDocument?: ( config: WebdavConfig, diff --git a/plugins/live-markdown/tests/preload/webdav-conflict.test.cjs b/plugins/live-markdown/tests/preload/webdav-conflict.test.cjs new file mode 100644 index 000000000..2419131f5 --- /dev/null +++ b/plugins/live-markdown/tests/preload/webdav-conflict.test.cjs @@ -0,0 +1,175 @@ +"use strict"; + +// 回归:不同工作区的同名文件共用一个 WebDAV 远端目录时,同步不得静默覆盖任何一侧。 + +const test = require("node:test"); +const assert = require("node:assert/strict"); +const fs = require("node:fs"); +const os = require("node:os"); +const path = require("node:path"); +const webdavApi = require("../../preload/webdav-sync.cjs"); +const { + LEDGER_STORAGE_KEY, + createWebdavSyncLedger, + createMemoryStorage, + decidePullWrite, + decidePushWrite, + hashContent +} = require("../../preload/webdav-sync-ledger.cjs"); +const { createE2EMockWebdavServer } = require("../e2e/mock-webdav.cjs"); + +const REMOTE_NOTE = "/dav/TyporaNotes/notes.md"; + +async function withServer(run) { + const { server, files } = createE2EMockWebdavServer(); + files.clear(); + await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve)); + const config = { + enabled: true, + serverUrl: `http://127.0.0.1:${server.address().port}/dav/`, + username: "typora_e2e", + password: "pass_123", + remotePath: "/TyporaNotes/", + autoSyncOnSave: true, + syncDirection: "bidirectional" + }; + const root = fs.mkdtempSync(path.join(os.tmpdir(), "lm-webdav-conflict-")); + const wsA = path.join(root, "workspace-a"); + const wsB = path.join(root, "workspace-b"); + fs.mkdirSync(wsA); + fs.mkdirSync(wsB); + const ledger = createWebdavSyncLedger(createMemoryStorage()); + try { + await run({ config, files, wsA, wsB, ledger }); + } finally { + await new Promise((resolve) => server.close(resolve)); + fs.rmSync(root, { recursive: true, force: true }); + } +} + +function setRemote(files, content) { + files.set(REMOTE_NOTE, { content, mtimeMs: Date.now() + 60_000, etag: `etag-${Date.now()}` }); +} + +test("pulling into another workspace never overwrites its same-named file", async () => { + await withServer(async ({ config, files, wsA, wsB, ledger }) => { + fs.writeFileSync(path.join(wsA, "notes.md"), "# A\n", "utf8"); + fs.writeFileSync(path.join(wsB, "notes.md"), "# B\n", "utf8"); + + const syncA = await webdavApi.syncWorkspaceWithWebdav(config, { localDir: wsA, direction: "push", ledger }); + assert.deepEqual(syncA.uploaded, ["notes.md"]); + assert.equal(files.get(REMOTE_NOTE).content, "# A\n"); + + const syncB = await webdavApi.syncWorkspaceWithWebdav(config, { localDir: wsB, direction: "pull", ledger }); + assert.equal(syncB.ok, true); + assert.deepEqual(syncB.downloaded, []); + assert.equal(syncB.conflicts.length, 1); + assert.equal(syncB.conflicts[0].reason, "bound-elsewhere"); + assert.equal(fs.readFileSync(path.join(wsB, "notes.md"), "utf8"), "# B\n"); + + const pulled = await webdavApi.pullWebdavDocument(config, "notes.md", wsB, { ledger }); + assert.equal(pulled.ok, false); + assert.equal(pulled.conflict, true); + assert.equal(pulled.path, null); + assert.equal(fs.readFileSync(path.join(wsB, "notes.md"), "utf8"), "# B\n"); + }); +}); + +test("pushing from another workspace never overwrites the remote copy", async () => { + await withServer(async ({ config, files, wsA, wsB, ledger }) => { + fs.writeFileSync(path.join(wsA, "notes.md"), "# A\n", "utf8"); + fs.writeFileSync(path.join(wsB, "notes.md"), "# B\n", "utf8"); + await webdavApi.syncWorkspaceWithWebdav(config, { localDir: wsA, direction: "push", ledger }); + + const syncB = await webdavApi.syncWorkspaceWithWebdav(config, { localDir: wsB, direction: "push", ledger }); + assert.deepEqual(syncB.uploaded, []); + assert.equal(syncB.conflicts[0].reason, "bound-elsewhere"); + assert.equal(files.get(REMOTE_NOTE).content, "# A\n"); + + // 未保存的同名新文档(没有本地路径)同样不能覆盖已绑定的云端文件。 + const unsaved = await webdavApi.pushWebdavDocument(config, "notes.md", "# draft\n", { ledger }); + assert.equal(unsaved.ok, false); + assert.equal(unsaved.reason, "bound-elsewhere"); + assert.equal(files.get(REMOTE_NOTE).content, "# A\n"); + }); +}); + +test("the bound workspace still syncs normally in both directions", async () => { + await withServer(async ({ config, files, wsA, ledger }) => { + const noteA = path.join(wsA, "notes.md"); + fs.writeFileSync(noteA, "# A\n", "utf8"); + await webdavApi.syncWorkspaceWithWebdav(config, { localDir: wsA, direction: "push", ledger }); + + // 其他设备修改了云端,本地未改:允许拉取覆盖。 + setRemote(files, "# A from phone\n"); + const pulled = await webdavApi.syncWorkspaceWithWebdav(config, { localDir: wsA, direction: "pull", ledger }); + assert.deepEqual(pulled.downloaded, ["notes.md"]); + assert.equal(fs.readFileSync(noteA, "utf8"), "# A from phone\n"); + + // 本地修改、云端未改:允许上传覆盖。 + fs.writeFileSync(noteA, "# A edited\n", "utf8"); + const pushed = await webdavApi.pushWebdavDocument(config, "notes.md", "# A edited\n", { ledger, localPath: noteA }); + assert.equal(pushed.ok, true); + assert.equal(files.get(REMOTE_NOTE).content, "# A edited\n"); + }); +}); + +test("both sides changed since the last sync is a conflict in either direction", async () => { + await withServer(async ({ config, files, wsA, ledger }) => { + const noteA = path.join(wsA, "notes.md"); + fs.writeFileSync(noteA, "# base\n", "utf8"); + await webdavApi.syncWorkspaceWithWebdav(config, { localDir: wsA, direction: "push", ledger }); + + fs.writeFileSync(noteA, "# local edit\n", "utf8"); + setRemote(files, "# remote edit\n"); + + const pulled = await webdavApi.pullWebdavDocument(config, "notes.md", wsA, { ledger }); + assert.equal(pulled.reason, "local-modified"); + assert.equal(fs.readFileSync(noteA, "utf8"), "# local edit\n"); + + const pushed = await webdavApi.pushWebdavDocument(config, "notes.md", "# local edit\n", { ledger, localPath: noteA }); + assert.equal(pushed.reason, "remote-changed"); + assert.equal(files.get(REMOTE_NOTE).content, "# remote edit\n"); + }); +}); + +test("without a ledger entry, differing content on either side is never overwritten", async () => { + await withServer(async ({ config, files, wsB, ledger }) => { + const noteB = path.join(wsB, "notes.md"); + fs.writeFileSync(noteB, "# legacy local\n", "utf8"); + setRemote(files, "# legacy remote\n"); + + const pulled = await webdavApi.pullWebdavDocument(config, "notes.md", wsB, { ledger }); + assert.equal(pulled.reason, "local-unknown"); + assert.equal(fs.readFileSync(noteB, "utf8"), "# legacy local\n"); + + const pushed = await webdavApi.pushWebdavDocument(config, "notes.md", "# legacy local\n", { ledger, localPath: noteB }); + assert.equal(pushed.reason, "unknown-remote"); + assert.equal(files.get(REMOTE_NOTE).content, "# legacy remote\n"); + + // 内容一致时直接建立绑定,不视为冲突。 + fs.writeFileSync(noteB, "# legacy remote\n", "utf8"); + const adopted = await webdavApi.pullWebdavDocument(config, "notes.md", wsB, { ledger }); + assert.equal(adopted.ok, true); + assert.equal(adopted.path, noteB); + }); +}); + +test("a corrupt ledger fails closed", () => { + const storage = createMemoryStorage(); + storage.setItem(LEDGER_STORAGE_KEY, "{not json"); + const ledger = createWebdavSyncLedger(storage); + const config = { serverUrl: "https://dav.example", remotePath: "/TyporaNotes/" }; + assert.equal(ledger.get(config, "notes.md"), null); + const decision = decidePullWrite({ + binding: null, + localPath: "/tmp/notes.md", + localHash: hashContent("local"), + remoteHash: hashContent("remote") + }); + assert.equal(decision.allowed, false); + assert.equal( + decidePushWrite({ binding: null, localPath: "/tmp/notes.md", localHash: hashContent("a"), remoteHash: hashContent("b") }).allowed, + false + ); +});