Skip to content

AI-native knowledge base & Evernote/Obsidian alternative with instant sync & native MCP. Free on Cloudflare or self-hosted via Docker.

fix(import): preserve linked images and external URIs (#657)

sivdead4cf212e55ed8
diff --git a/apps/web/src/lib/note-import/enml.ts b/apps/web/src/lib/note-import/enml.ts
index 028704be..e3a47c74 100644
--- a/apps/web/src/lib/note-import/enml.ts
+++ b/apps/web/src/lib/note-import/enml.ts
@@ -50,9 +50,9 @@ const prepareEnml = (source: string, resources: readonly ImportResource[]) => {
media.setAttribute(image ? "src" : "href", `evernote-resource:${hash}`);
if (image) media.setAttribute("alt", label);
else media.textContent = label;
- const block = document.createElement("div");
- block.appendChild(media);
- node.parentNode!.replaceChild(block, node);
+ const replacement = image && node.closest("a") ? media : document.createElement("div");
+ if (replacement !== media) replacement.appendChild(media);
+ node.parentNode!.replaceChild(replacement, node);
}
return root;
};
diff --git a/docs/changes/2026-10-27-third-party-import.md b/docs/changes/2026-10-27-third-party-import.md
index d40eb298..ec9b454f 100644
--- a/docs/changes/2026-10-27-third-party-import.md
+++ b/docs/changes/2026-10-27-third-party-import.md
@@ -95,6 +95,10 @@ Per-note creation previously called `getNotebook` with repeated `COUNT/MAX`, pro
| R36 | Use own-property semantics for filenames, MIME extensions and resource URL maps, safely storing legal keys such as `__proto__` without treating prototype properties as MIME values or uploaded resources. Add no filename restrictions. | Real uploads and retries of `toString`, `constructor`, `__proto__` and related names preserve final URLs, MIME values and original bytes without duplicates. |
| R37 | Store only required memo baselines in import results: IDs, notebook, revision/content fingerprint and source timestamps, not full Markdown/JSON/text. Clear intended Markdown after successful or confirmed commits; retain commit-comparison content only for the current incomplete item. | Multiple large completed notes leave no full bodies in the result index or UI snapshots. Lost-final-response verification, task-local retries and concurrent-edit protection still pass. |
| R38 | Use Turndown’s existing asterisk emphasis option for ENML so default underscores do not become literal text between adjacent Chinese characters. Preserve bold, links, tables and attachments without changing shared Markdown syntax. | The real Evernote export retains Chinese italics in saved API JSON and the Web page; bold and other formatting still pass. |
+| R40 | Keep images inside ENML links inline so Markdown conversion preserves the outer URL/title, image target and label in saved content. Ordinary images and attachments retain existing block layout, escaping and upload behavior. Add no image attributes or rendering-safety changes. | Reproduce the lost outer link first. Import directly linked images and images nested in inline elements through the real API; check saved JSON, Markdown round-trips and saving/reopening. Existing ordinary-media cases still pass. |
+| R41 | Preserve external URIs in standard Markdown, including FTP and Obsidian protocols, without resolving them as local attachments, reading their targets, activating new protocols or adding preflight warnings. Keep rejecting `file:` and Windows drive forms under existing local-path rules; retain traversal, invalid local encoding and literal Wiki-path behavior. | Reproduce FTP/Obsidian URIs being reported as `outsideRoot` first. Verify error-free Obsidian/Joplin preflight, no resource uploads and unchanged URI text after real import. Traversal, `file:`, drive paths and invalid local encoding remain rejected. |
+
+R40 removes block wrapping only for linked images, retaining R24/R25's ordinary-media layout rather than changing all ENML formatting. R41 separates URI classification from local resource lookup without extending a protocol allowlist or weakening path validation. Existing rendering-safety rules still decide whether a link may be activated.
## Delivery contents
@@ -119,6 +123,8 @@ Shared codec repairs affect editing round-trips for images, lists and attachment
## Completion reconciliation
-I01–I11, R01–R39 and C01/C02 are implemented; every behavior in the task diff maps to these entries, with no additional input restrictions, permissions or sync/backup protocol changes. Focused checks cover source formats, hierarchy/metadata/original bytes, failure retries, concurrent-edit protection and resource cleanup. See [acceptance conclusions](evidence/2026-10-27-third-party-import/README.md) for the conditions and measurements of large-library reads, cursor exports, real-browser preflight and large-body result retention. Both typechecks, the Web build and targeted lint pass.
+I01–I11, R01–R41 and C01/C02 are implemented; every behavior in the task diff maps to these entries, with no additional input restrictions, permissions or sync/backup protocol changes. Focused checks cover source formats, hierarchy/metadata/original bytes, failure retries, concurrent-edit protection and resource cleanup. See [acceptance conclusions](evidence/2026-10-27-third-party-import/README.md) for the conditions and measurements of large-library reads, cursor exports, real-browser preflight and large-body result retention. Both typechecks, the Web build and targeted lint pass.
+
+R40/R41 regressions reproduce the original failures before repair; all 24 affected checks pass afterwards. Production Web with real Worker/IndexedDB and an isolated API imports linked images, edits/saves and reopens them with outer links and original image bytes intact. External-URI preflight allows confirmation and actual import retains source text with no resource uploads. Obsidian/Joplin API regressions and existing local-path rejection checks pass.
-Cloudflare has R27–R30 and `0085`; the acceptance document records the real prior-instance upgrade and readback. R31–R39 and `0086` are not deployed. Earlier macOS/Linux native results do not cover the latest repairs. Windows native, USB mobile devices, older-client editing, AppImage installation/cross-version updates and Docker container deployment remain unverified; builds and driver-level checks do not replace those flows.
+Cloudflare has R27–R30 and `0085`; the acceptance document records the real prior-instance upgrade and readback. R31–R41 and `0086` are not deployed. Earlier macOS/Linux native results do not cover the latest repairs. Windows native, USB mobile devices, older-client editing, AppImage installation/cross-version updates and Docker container deployment remain unverified; builds and driver-level checks do not replace those flows.
diff --git a/docs/changes/2026-10-27-third-party-import.zh-CN.md b/docs/changes/2026-10-27-third-party-import.zh-CN.md
index abbbf36d..61ced336 100644
--- a/docs/changes/2026-10-27-third-party-import.zh-CN.md
+++ b/docs/changes/2026-10-27-third-party-import.zh-CN.md
@@ -95,6 +95,10 @@ Markdown 位置识别和序列化复用成熟解析器,不继续维护正则
| R36 | 文件名、扩展名及资源 URL 映射使用自有属性语义,安全写入 `__proto__` 等合法键,不把原型属性当作 MIME 或已上传资源;不增加文件名限制。 | `toString`、`constructor`、`__proto__` 等附件真实上传、重试不重复,最终 URL、MIME 和原始字节正确。 |
| R37 | 导入结果索引中的 memo 仅保存 ID、目录、版本、内容指纹和原始时间等必要基线,不保留完整正文、JSON 或摘要;成功或确认成功后清除待确认正文,仅当前未完成项保留核对提交所需内容。 | 多篇大正文完成后,结果索引及结果页快照不包含整篇正文;最终响应丢失核对、同任务重试和人工编辑冲突保护仍通过。 |
| R38 | ENML 斜体改用 Turndown 已有的星号分隔选项,避免默认下划线在相邻中文之间变成字面文本;保留原粗体、链接、表格及附件语义,不改共享 Markdown 语法。 | 真实 Evernote 导出的中文斜体在实际 API 保存的 JSON 和 Web 页面中仍为斜体;原有粗体与其他格式继续通过。 |
+| R40 | ENML 链接中的图片保持行内结构,使外层 URL/title 与图片目标、标签经过 Markdown 转换后仍可保存。普通图片和附件沿用现有块结构、转义及上传规则,不新增图片属性或改变渲染安全策略。 | 先复现链接内媒体转换丢失外链,再通过真实 API 导入直接及嵌套在行内元素中的链接图片,核对保存的 JSON、Markdown 往返和保存重开;原有普通媒体用例继续通过。 |
+| R41 | 标准 Markdown 中的外部 URI(包括 FTP、Obsidian 等协议)原文保留,不作为本地附件解析、不读取目标,也不新增协议激活能力或预检警告。`file:` 和 Windows 盘符形式仍按既有本地路径规则拒绝,真实目录越界、无效本地编码及 Wiki 字面路径规则不变。 | 先复现 FTP/Obsidian URI 误报 `outsideRoot`,再验证 Obsidian/Joplin 预检无错误、无资源上传、实际导入读回 URI 原文;本地越界、`file:`、盘符和无效编码仍拒绝。 |
+
+R40 只取消链接内图片的块级包装,保留 R24/R25 对普通媒体的布局处理,避免为修复外链改写全部 ENML 排版。R41 将 URI 分类与本地资源查找分开,不扩充协议白名单,也不放宽路径校验;链接是否可激活仍由既有渲染安全规则决定。
## 交付内容
@@ -119,6 +123,8 @@ R39 已完成正式 migration、本地旧结构升级和契约回归,实际 D1
## 完成核对
-I01–I11、R01–R39、C01/C02 已实现,实际 diff 的行为变化均对应上述条目;没有额外输入限制、权限或同步/备份协议变更。来源格式、目录/元数据/原字节、失败重试、并发编辑保护及资源清理通过针对性验证。大库读量、导出续页、真实浏览器预检及大正文结果留存的条件与测量见[验收结论](evidence/2026-10-27-third-party-import/README.zh-CN.md)。两项类型检查、Web 构建和目标 lint 通过。
+I01–I11、R01–R41、C01/C02 已实现,实际 diff 的行为变化均对应上述条目;没有额外输入限制、权限或同步/备份协议变更。来源格式、目录/元数据/原字节、失败重试、并发编辑保护及资源清理通过针对性验证。大库读量、导出续页、真实浏览器预检及大正文结果留存的条件与测量见[验收结论](evidence/2026-10-27-third-party-import/README.zh-CN.md)。两项类型检查、Web 构建和目标 lint 通过。
+
+R40/R41 的失败回归先复现原问题,修复后 24 项受影响检查通过。生产 Web 的真实 Worker、IndexedDB 和隔离 API 完成链接图片导入、编辑保存及重开,外层链接与原图字节保持一致;外部 URI 预检可确认、实际导入保留原文且零资源上传。Obsidian/Joplin 的 API 回归及原有本地路径拒绝检查通过。
-Cloudflare 已部署 R27–R30 与 `0085`,真实旧实例升级及数据读回结论见验收文档;R31–R39 和 `0086` 尚未部署。此前 macOS/Linux 原生结果未覆盖最新修复。Windows 原生、USB 移动真机、旧客户端编辑、AppImage 安装/跨版本升级和 Docker 容器部署仍未验证;不得将构建或驱动级检查作为这些验收的替代。
+Cloudflare 已部署 R27–R30 与 `0085`,真实旧实例升级及数据读回结论见验收文档;R31–R41 和 `0086` 尚未部署。此前 macOS/Linux 原生结果未覆盖最新修复。Windows 原生、USB 移动真机、旧客户端编辑、AppImage 安装/跨版本升级和 Docker 容器部署仍未验证;不得将构建或驱动级检查作为这些验收的替代。
diff --git a/docs/changes/evidence/2026-10-27-third-party-import/README.md b/docs/changes/evidence/2026-10-27-third-party-import/README.md
index 0d16150d..09caa592 100644
--- a/docs/changes/evidence/2026-10-27-third-party-import/README.md
+++ b/docs/changes/evidence/2026-10-27-third-party-import/README.md
@@ -26,7 +26,7 @@ See the [real-source fixtures](../../../../tests/fixtures/note-import/real-apps/
- Cloudflare: an earlier candidate merged with upstream 2.16.1 passed an existing-instance upgrade and actual three-source imports. The `0072` → `0084` upgrade retained four existing notes and one resource, while upstream `0078` cleared factory colors on five default notebooks. The current R27–R30 API/Web and `0085` are now deployed; all pre-upgrade business fields in 18 notes, 19 notebooks, 23 resources and the workspace remain identical. The existing authenticated session, health and OpenAPI probes pass. Deployed Settings imports one additional ENEX note with original timestamps/tags and five matching attachment payloads; PNG/SVG load and the PDF is readable.
- Upgrading the original API against the same database retained existing bodies, tags, timestamps and resource bytes. Driver-level checks do not establish Docker container deployment acceptance.
-Earlier native candidates do not cover the latest image/list and R31–R39 repairs. R31–R39 and `0086` are not deployed to Cloudflare. Windows native, physical mobile devices, older-client editing, AppImage installation and cross-version automatic updates remain unverified. Current Cloudflare checks did not repeat password login or complete saving a Web ZIP to the local filesystem; the user can confirm these through the login and export entries.
+Earlier native candidates do not cover the latest image/list and R31–R41 repairs. R31–R41 and `0086` are not deployed to Cloudflare. Windows native, physical mobile devices, older-client editing, AppImage installation and cross-version automatic updates remain unverified. Current Cloudflare checks did not repeat password login or complete saving a Web ZIP to the local filesystem; the user can confirm these through the login and export entries.
## Large libraries and quotas
@@ -120,6 +120,10 @@ Bullet, ordered, task and nested lists retain four images in their list items af
ENML uses Turndown’s asterisk emphasis delimiter so Chinese italics adjacent to surrounding text remain italic, verified in the real Evernote export’s saved JSON and Web render.
+Images inside ENML links remain inline. Real-API checks cover both directly linked images and images nested in inline elements: saved JSON, Markdown round-trips and editing/reopening retain outer URLs/titles, image targets and labels. Production Web imports through actual Worker/IndexedDB, edits text in the editor, waits for saving and reopens the note after switching away. Both images and their outer links remain, with original image bytes unchanged.
+
+FTP and Obsidian app URIs in Obsidian/Joplin pass preflight and real-API import with unchanged source text and zero resource uploads. The production Web Settings entry also completes preflight and import. Traversal, `file:`, Windows drive forms and invalid local encoding remain rejected. The new cases fail before repair; afterwards all 24 affected checks, both typechecks, the Web build and targeted lint pass.
+
## Task state and cleanup
Local-space failure before folder creation writes nothing remotely; failure to save a mapping after creation retains uncertainty without duplicate folders. Confirmed RAW Markdown attachments are not fully scanned as notes, while unconfirmed resource-folder notes remain supported. Same-note duplicate ENEX resources are cleaned per note; unreadable encrypted ZIPs and initialization cancellation settle promptly. Legal prototype-property attachment names upload and retry without duplicate resources or changed bytes.
diff --git a/docs/changes/evidence/2026-10-27-third-party-import/README.zh-CN.md b/docs/changes/evidence/2026-10-27-third-party-import/README.zh-CN.md
index 48790788..bdf4bfe6 100644
--- a/docs/changes/evidence/2026-10-27-third-party-import/README.zh-CN.md
+++ b/docs/changes/evidence/2026-10-27-third-party-import/README.zh-CN.md
@@ -26,7 +26,7 @@ Web 设置入口及此前隔离的原生运行时已验证以下自造来源样
- Cloudflare:此前合并上游 2.16.1 的候选完成既有实例升级与三来源实际导入。`0072` → `0084` 保持 4 篇既有笔记及 1 个资源,5 个默认笔记本配色按上游 `0078` 清除。当前 R27–R30 的 API/Web 及 `0085` 已部署,升级前的 18 篇笔记、19 个笔记本、23 个资源和工作区业务字段保持一致;既有登录会话、健康检查和 OpenAPI 探针通过。线上设置入口再导入 1 篇 ENEX,原始时间、标签和 5 个附件字节一致,PNG/SVG 加载且 PDF 可阅读。
- 同一数据库从原 API 基线升级后,已有正文、标签、时间和资源字节保持一致。Docker 驱动的接口检查不等同于 Docker 容器部署验收。
-旧原生候选不覆盖最新图片/列表及 R31–R39 修复;R31–R39 和 `0086` 尚未部署到 Cloudflare。Windows 原生、移动端真机、旧客户端编辑、AppImage 安装及跨版本自动升级仍未验证。当前 Cloudflare 验证未重新输入密码登录,Web ZIP 的本机保存也未完成;这两项需用户通过登录页和导出入口确认。
+旧原生候选不覆盖最新图片/列表及 R31–R41 修复;R31–R41 和 `0086` 尚未部署到 Cloudflare。Windows 原生、移动端真机、旧客户端编辑、AppImage 安装及跨版本自动升级仍未验证。当前 Cloudflare 验证未重新输入密码登录,Web ZIP 的本机保存也未完成;这两项需用户通过登录页和导出入口确认。
## 大库与额度
@@ -120,6 +120,10 @@ bun run build:web
ENML 使用 Turndown 的星号斜体分隔选项,保留相邻中文之间的斜体;真实 Evernote 导出的 API JSON 和 Web 页面均验证通过。
+ENML 链接内的图片保持行内结构,直接位于链接中及嵌套在行内元素中的两种图片均经真实 API 验证:保存的 JSON、Markdown 往返和编辑重开保留外层 URL/title 与图片目标、标签。生产 Web 的实际 Worker/IndexedDB 导入后,在编辑器修改文字、等待保存并切换笔记重开,两张图片及其外链仍在,原图字节一致。
+
+Obsidian/Joplin 中的 FTP、Obsidian 应用 URI 均通过预检及真实 API 导入,正文原文保留,资源上传为零;生产 Web 设置入口也完成预检与导入。真实目录越界、`file:`、Windows 盘符及无效本地编码仍拒绝。上述新场景在修复前失败,修复后 24 项受影响检查、两项类型检查、Web 构建和目标 lint 通过。
+
## 任务状态与清理
本地空间在目录创建前失败时不写远端;创建后映射保存失败仍保留待确认状态,不重复建目录。确认后的 RAW Markdown 附件不全文扫描成笔记,无描述的资源目录笔记仍可导入。ENEX 同篇重复资源按篇清理,加密 ZIP 无法读取及初始化取消均及时结束;合法原型属性名附件上传和重试保持原字节、无重复。
diff --git a/docs/third-party-import-plan.md b/docs/third-party-import-plan.md
index 18c14c4e..612aa5a1 100644
--- a/docs/third-party-import-plan.md
+++ b/docs/third-party-import-plan.md
@@ -35,7 +35,7 @@ Use **client-side parsing with shared server-side writes**, rather than separate
- Accept one or multiple `.enex` files, nested directories containing ENEX, and ZIPs containing them. Preserve the full directory path; each ENEX filename becomes a leaf notebook. Multiple selected files without relative paths become sibling notebooks. Do not infer source hierarchy absent from the export.
- For `.notes`, explicitly ask users to export `.enex` from Evernote and try again; do not guess that it is XML or ZIP.
- Scan XML in chunks for titles, tags, `created`, `updated`, ENML, and resource descriptors. Import one note at a time, decoding resource base64 incrementally. A SAX text callback must not rebuild an entire attachment in memory.
-- Use Turndown for ENML conversion, covering tables, tasks, images, and attachments. Incremental MD5 is used only to match ENEX `en-media` identifiers, not as a security check.
+- Use Turndown for ENML conversion, covering tables, tasks, images, and attachments. Keep linked images inline to preserve outer URLs/titles; ordinary media retains existing block layout. Incremental MD5 is used only to match ENEX `en-media` identifiers, not as a security check.
- Upload resources attached to a note even when its body does not reference them, appending attachment links. Retain encrypted source content as plain text with a notice rather than discarding it behind a placeholder.
### Obsidian Vault
@@ -57,8 +57,9 @@ Use **client-side parsing with shared server-side writes**, rather than separate
- Preserve valid source instants as timezone-qualified ISO timestamps. Retain and warn about missing or timezone-ambiguous values rather than presenting invented times as original. Omitted fields retain the existing creation API default of the import time.
- Whether `_resources`, `assets`, or similar directories become notebooks depends on whether they contain notes or ancestors of notes—not their name alone. Resource-only directories do not become empty notebooks.
- Repeated references to one attachment in one note create one upload. Across notes, upload separately under existing resource ownership rules. Preflight attachment counts mean planned EdgeEver resources, not unique source files. Resources unrelated to any note are listed as not imported.
-- Rewrite actual image/link targets, not code blocks, inline code, or matching plain text. Preserve external HTTP(S) links without downloading remote images.
-- Normalized paths must stay within the selected root. Do not follow archive symlinks or extract archives to arbitrary user directories. Report multiple entries mapping to one normalized path as ambiguous.
+- Rewrite actual image/link targets, not code blocks, inline code, or matching plain text.
+- Preserve external URIs in standard Markdown, including HTTP(S), FTP and Obsidian app links, without local-attachment lookup, target reads or new preflight warnings. Existing link-opening and rendering-safety policies remain unchanged.
+- Normalized paths must stay within the selected root. Continue rejecting `file:` URIs and Windows drive forms, including drive-relative paths, under existing local-path rules; Wiki targets remain literal filenames. Do not follow archive symlinks or extract archives to arbitrary user directories. Report multiple entries mapping to one normalized path as ambiguous.
- Convert only static HTML content; do not execute scripts or event handlers. XML processing does not fetch DTDs or resolve external entities, while still accepting ordinary ENEX format declarations.
- Retain existing limits: notebook names of 80 characters, note titles of 160, images up to 100 MiB, and other attachments up to 1 GiB. Normalize tags in source order, remove empty/duplicate values and keep the first 24. Ignore extras with a non-blocking preflight warning showing the ignored count; ordinary editing retains its existing tag persistence rules. Preflight reports violations; it does not truncate text/titles or compress images to claim success. Errors preventing faithful import must be fixed first; warnings such as absent optional metadata may be acknowledged.
diff --git a/docs/third-party-import-plan.zh-CN.md b/docs/third-party-import-plan.zh-CN.md
index 6c9ee29f..af374b69 100644
--- a/docs/third-party-import-plan.zh-CN.md
+++ b/docs/third-party-import-plan.zh-CN.md
@@ -35,7 +35,7 @@
- 接受单个或多个 `.enex`、包含 ENEX 的多级目录,以及这些内容的 ZIP。目录路径完整保留,每个 ENEX 文件名对应一个叶级笔记本;多选且没有相对路径的文件作为同级笔记本。不推测导出中不存在的原平台目录。
- `.notes` 明确提示“请从印象笔记导出为 .enex 后重试”,不作为 XML 或 ZIP 猜测解析。
- 分块扫描 XML,读取标题、标签、`created`、`updated`、ENML 和内嵌资源描述。导入时逐篇处理,资源 base64 分块解码;不能在 SAX 的单个文本事件里重新积累整个附件。
-- ENML 转换沿用 Turndown,覆盖表格、待办、图片和附件。MD5 只用于匹配 ENEX 的 `en-media` 资源标识,采用增量实现;不把它当作安全校验。
+- ENML 转换沿用 Turndown,覆盖表格、待办、图片和附件。链接中的图片保持行内结构,保留外层 URL/title;普通媒体仍沿用既有块布局。MD5 只用于匹配 ENEX 的 `en-media` 资源标识,采用增量实现;不把它当作安全校验。
- 笔记自带但未在正文中引用的附件仍上传,并在正文末尾补充附件链接。加密段落以纯文本保留原始加密内容及提示,不用占位文案替换后丢弃原文。
### Obsidian Vault
@@ -57,8 +57,9 @@
- 有效来源时间保留其时刻,写入为带时区的 ISO 时间。缺失或无法确定时区的时间保留原始值并提示;不冒充原始笔记时间,缺失字段沿用现有创建接口的导入时刻默认值。
- `_resources`、`assets` 等目录是否建笔记本取决于是否包含笔记或其子目录是否含笔记,不能只按名称整目录排除。纯资源目录不建空笔记本。
- 同一附件在同一篇笔记中被多次引用只上传一次;跨笔记沿用现有资源归属模型分别上传。预检的“附件数”指计划创建的 EdgeEver 资源数,不是唯一源文件数;未关联到任何笔记的资源列为未导入项。
-- 只改写正文中实际的图片/链接目标,不对代码块、行内代码或相似文字做全局替换。外部 HTTP(S) 链接保留,不下载远程图片。
-- 路径规范化后不得越出所选根目录;不跟随归档中的符号链接,不把归档解压到用户任意目录。同一规范路径对应多个条目时报告歧义。
+- 只改写正文中实际的图片/链接目标,不对代码块、行内代码或相似文字做全局替换。
+- 标准 Markdown 中的外部 URI(如 HTTP(S)、FTP、Obsidian 应用链接)原文保留,不作为本地附件查找,不读取目标,也不新增预检警告。既有链接打开和渲染安全策略不变。
+- 路径规范化后不得越出所选根目录;`file:` URI 和 Windows 盘符形式(含驱动器相对路径)继续按本地路径规则拒绝,Wiki 目标仍按字面文件名处理。不跟随归档中的符号链接,不把归档解压到用户任意目录。同一规范路径对应多个条目时报告歧义。
- HTML 仅转换静态内容,不执行脚本或事件处理器;XML 不联网读取 DTD 或解析外部实体,正常 ENEX 的格式声明仍可读取。
- 沿用当前名称、标题和上传限制,包括笔记本名 80 字符、标题 160 字符、图片 100 MiB、其他附件 1 GiB。标签按来源顺序去空、去重后保留前 24 个;超出部分忽略,预检提示忽略数量但不阻止导入。普通编辑的标签保存规则不变。预检列出不符合项,不截断正文、标题或自动压图来“导入成功”。影响完整还原的错误须先修正,缺失可选元数据等警告可确认后继续。
diff --git a/packages/shared/src/note-import/session.ts b/packages/shared/src/note-import/session.ts
index 9ebd0a14..8d224502 100644
--- a/packages/shared/src/note-import/session.ts
+++ b/packages/shared/src/note-import/session.ts
@@ -212,6 +212,8 @@ export class NoteImportSession {
private async resolveReference(note: ImportNote, ref: ImportReference): Promise<ImportResource | undefined> {
let href = ref.href;
if (/^(?:https?:|mailto:|tel:|data:|#|\/\/)/i.test(href)) return;
+ // Keep file/drive forms in local-path validation; other URI targets are not opened.
+ if (!ref.wiki && /^[a-z][a-z0-9+.-]*:/i.test(href) && !/^(?:file:|[a-z]:)/i.test(href)) return;
if (this.format === "joplin" && /^:\/[0-9a-f]{32}/i.test(href)) {
const suffixAt = ref.wiki ? href.indexOf("#") : href.search(/[?#]/);
ref.suffix = suffixAt === -1 ? "" : href.slice(suffixAt);
diff --git a/tests/note-import.integration.test.mjs b/tests/note-import.integration.test.mjs
index 85832d2e..3686917f 100644
--- a/tests/note-import.integration.test.mjs
+++ b/tests/note-import.integration.test.mjs
@@ -610,6 +610,62 @@ describe("native third-party import through the real API", () => {
await session.close(); db.close();
});
+ test("ENML linked images retain outer links through saved documents", async () => {
+ const { client, db } = await target();
+ const data = await readFile(new URL("./fixtures/note-import/real-apps/assets/样本 图.png", import.meta.url));
+ const hash = new Bun.CryptoHasher("md5").update(data).digest("hex");
+ const links = [
+ { href: "https://example.com/full", title: "Full image", alt: "Direct image" },
+ { href: "https://example.com/details?view=full#photo", title: "Details", alt: "Nested image" },
+ ];
+ const media = alt => `<en-media type="image/png" hash="${hash}" alt="${alt}"/>`;
+ const enml = `<en-note><a href="${links[0].href}" title="${links[0].title}">${media(links[0].alt)}</a><div>Before <a href="${links[1].href}" title="${links[1].title}"><span>${media(links[1].alt)}</span></a> after</div></en-note>`;
+ const enex = `<en-export><note><title>Linked images</title><content><![CDATA[${enml}]]></content><created>20200102T030405Z</created><updated>20210203T040506Z</updated><resource><data encoding="base64">${data.toString("base64")}</data><mime>image/png</mime><resource-attributes><file-name>linked.png</file-name></resource-attributes></resource></note></en-export>`;
+ const session = new NoteImportSession("evernote", [{ path: "linked.enex", file: new File([enex], "linked.enex") }], new MemoryImportIndex());
+ try {
+ expect(await session.scan()).toMatchObject({ notes: 1, resources: 1, errors: 0, warnings: 0 });
+ expect(await executeNoteImport({ reader: session, index: session.index, client, convertEnml: convertImportEnml })).toMatchObject({ completed: 1, failed: 0, resources: 1 });
+ const [state] = await session.index.page("result");
+ const imageUrl = Object.values(state.urls)[0];
+ const checkImages = doc => {
+ const images = [];
+ const visit = node => { if (node.type === "image") images.push(node.attrs); node.content?.forEach(visit); };
+ visit(doc);
+ expect(images).toHaveLength(links.length);
+ for (const [index, link] of links.entries()) expect(images[index]).toMatchObject({ src: imageUrl, alt: link.alt, link: { href: link.href, title: link.title } });
+ };
+ const { memo } = await client.getMemo(state.memo.id);
+ checkImages(memo.contentJson);
+ checkImages(markdownToDoc(docToMarkdown(memo.contentJson)));
+ expect(memo.contentMarkdown).not.toContain("evernote-resource:");
+ const edited = structuredClone(memo.contentJson);
+ edited.content.push({ type: "paragraph", content: [{ type: "text", text: "Edited after import" }] });
+ const { editSession } = await client.createMemoEditSession(memo.id);
+ await client.updateMemo(memo.id, { contentJson: edited, contentMarkdown: docToMarkdown(edited), expectedRevision: memo.revision, expectedContentHash: memo.contentHash, editSessionId: editSession.id });
+ const reopened = (await client.getMemo(memo.id)).memo;
+ checkImages(reopened.contentJson);
+ expect(reopened.contentMarkdown).toContain("Edited after import");
+ const blob = await client.getResourceBlob(imageUrl);
+ expect(new Uint8Array(await blob.arrayBuffer())).toEqual(new Uint8Array(data));
+ } finally { await session.close(); db.close(); }
+ }, 30_000);
+
+ for (const format of ["obsidian", "joplin"]) test(`${format}: external URIs survive preflight and real import`, async () => {
+ const { client, db } = await target();
+ const body = "---\ncreated: 2020-01-02T03:04:05Z\nupdated: 2021-02-03T04:05:06Z\n---\n\n[FTP](ftp://example.com/file)\n\n[Vault](obsidian://open?vault=Demo&file=Note)";
+ const session = new NoteImportSession(format, [{ path: "external.md", file: new File([body], "external.md") }], new MemoryImportIndex());
+ try {
+ const before = db.query("SELECT COUNT(*) AS n FROM memos").get().n;
+ expect(await session.scan()).toMatchObject({ notes: 1, resources: 0, errors: 0, warnings: 0 });
+ expect(db.query("SELECT COUNT(*) AS n FROM memos").get().n).toBe(before);
+ expect(await executeNoteImport({ reader: session, index: session.index, client, convertEnml: convertImportEnml })).toMatchObject({ completed: 1, failed: 0, resources: 0 });
+ const [state] = await session.index.page("result");
+ expect((await client.getMemo(state.memo.id)).memo.contentMarkdown).toBe(body);
+ expect(state.urls).toEqual({});
+ expect(db.query("SELECT COUNT(*) AS n FROM resources WHERE memo_id=?").get(state.memo.id).n).toBe(0);
+ } finally { await session.close(); db.close(); }
+ }, 30_000);
+
test("nested links, labels, titles and referenced definitions retain Markdown structure", async () => {
const { client, db } = await target();
const body = '[![thumb](assets/image.svg "Preview")](assets/manual.txt "Document")\n\n[section [A]](assets/manual.txt "See manual")\n\n[`code label`](assets/manual.txt)\n\n![reference][image]\n\n[image][]\n\n[image]\n\n[image]: assets/image.svg "Ref title"\n[unused]: missing.png\n\n`![code](missing.png)`';
@@ -998,10 +1054,11 @@ describe("real desktop-app exports", () => {
await session.close(); db.close();
});
- test("percent decoding retains traversal and invalid-UTF-8 rejection", async () => {
- const session = new NoteImportSession("joplin", [{ path: "note.md", file: new File(["[outside](%2e%2e/secret.txt)\n\n[invalid](%FF%20.txt)"], "note.md") }], new MemoryImportIndex());
- expect(await session.scan()).toMatchObject({ errors: 2 });
- expect((await session.index.page("issue")).filter(issue => issue.code === "outsideRoot")).toHaveLength(2);
+ test("local paths retain traversal, drive, file-URI and invalid-UTF-8 rejection", async () => {
+ const body = ["[outside](%2e%2e/secret.txt)", "[invalid](%FF%20.txt)", "[file](file:///private/secret.txt)", "[drive](C:/private/secret.txt)", "[drive relative](C:secret.txt)"].join("\n\n");
+ const session = new NoteImportSession("joplin", [{ path: "note.md", file: new File([body], "note.md") }], new MemoryImportIndex());
+ expect(await session.scan()).toMatchObject({ errors: 5 });
+ expect((await session.index.page("issue")).filter(issue => issue.code === "outsideRoot")).toHaveLength(5);
await session.close();
});
});