dsh-reading-inbox 0.3.0 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.en.md CHANGED
@@ -26,11 +26,14 @@ This plugin is the small implementation of those three things. Everything stays
26
26
  ## Features
27
27
 
28
28
  - **One-step clipping** — paste a URL; Readability extracts the article; Markdown + original HTML + title/author/date/source/excerpt are saved.
29
+ - **Text/selection capture** — when there is no fetchable URL, paste text, Markdown or HTML into the same inbox.
30
+ - **Import/export** — download all clips as JSON (optionally with original HTML) or one Markdown file; import JSON to restore clips, annotations and saved views.
31
+ - **Offline images** — optionally download article images into `clips/<id>/assets/` and serve them through a local asset route; `meta.json` records charset, HTTP status, byte count and other provenance.
29
32
  - **Inbox UI** — unread / reading / read / archived, search, tag filters, reading view, copy link, export Markdown.
30
33
  - **Highlights and notes** — select text to highlight it (yellow / green / blue / red) and add a note. Anchors use quote + surrounding context, so a re-clip re-locates them automatically; missing text becomes stale instead of landing on the wrong sentence. Markdown export includes active annotations.
31
34
  - **Local full-text search** — CJK is indexed as unigrams + bigrams, Latin as words; title and tags are boosted. No model call.
32
35
  - **Search grammar and saved views** — `tag:security`, `is:unread`, `site:example.com`, `after:2026-01-01`, `before:2026-12-31`, `has:highlight`; results include a matched snippet; save frequent queries as views.
33
- - **Agent tools** — `reading_clip`, `reading_search`, `reading_list`, `reading_read`, `reading_update`, `reading_highlight`.
36
+ - **Agent tools** — `reading_clip`, `reading_save_text`, `reading_search`, `reading_list`, `reading_read`, `reading_update`, `reading_highlight`.
34
37
  - **Slash command** — `/inbox <url> [tag1,tag2]` without leaving the conversation.
35
38
  - **Chinese-web friendly** — detects GBK / GB2312 / UTF-8 / Big5 so pages do not turn into mojibake.
36
39
  - **Safe defaults** — http/https only; every redirect hop is re-validated; DNS answers are checked again at connect time (DNS rebinding defense); loopback, private networks, CGNAT, link-local and cloud metadata addresses are rejected; hard caps of 5 MB, 20 seconds and 5 redirects.
@@ -47,7 +50,7 @@ From npm:
47
50
  dsh plugin --profile web add dsh-reading-inbox
48
51
  ```
49
52
 
50
- > pnpm's supply-chain policy waits before adopting a freshly published version. If an install right after a release picks the previous version, pin it: `dsh plugin --profile web add dsh-reading-inbox@0.3.0`.
53
+ > pnpm's supply-chain policy waits before adopting a freshly published version. If an install right after a release picks the previous version, pin it: `dsh plugin --profile web add dsh-reading-inbox@0.5.0`.
51
54
 
52
55
  From GitHub:
53
56
 
@@ -69,8 +72,8 @@ Restart `dsh web`. A **Reading inbox** row appears in the sidebar, and `/inbox`
69
72
 
70
73
  ### In the inbox
71
74
 
72
- 1. Paste a URL into the top bar and press Enter.
73
- 2. Click an item to read it. Mark read, archive, copy the link, export Markdown, or edit tags on the right.
75
+ 1. Paste a URL into the top bar and press Enter; use “Paste text” for content without a URL.
76
+ 2. “Export” downloads all clips as JSON; “Import” restores a previous JSON export. Click an item to read it; mark read, archive, copy the link, export Markdown, or edit tags on the right.
74
77
  3. Select text in the article: a highlight toolbar appears. Pick a color, add an optional note, and save.
75
78
  4. The search box searches title, body, tags and source as you type. Combine `tag:`, `is:`, `site:`, `after:` and `has:highlight` filters when needed.
76
79
  5. Save the current query as a view below the search box; one click restores the same filters.
@@ -104,12 +107,13 @@ Command output is shown in the UI only; the full article is not pushed into mode
104
107
 
105
108
  | Tool | What it does |
106
109
  | --- | --- |
107
- | `reading_clip` | Fetch a URL, extract the article, save Markdown + original HTML, update the index. Duplicate URLs return the existing clip; `force: true` re-fetches. |
110
+ | `reading_clip` | Fetch a URL, extract the article, save Markdown + original HTML, update the index. Duplicate URLs return the existing clip; `force: true` re-fetches; `assets: 'local'` downloads article images. |
108
111
  | `reading_search` | Full-text search with `tag:` / `is:` / `site:` / `after:` / `before:` / `has:highlight` grammar, status/tag filters and pagination; returns metadata plus a matched snippet, not the body. |
109
112
  | `reading_list` | List by date, filtered by status/tag. |
110
113
  | `reading_read` | Read a Markdown slice by id; use `offset` / `nextOffset` for long articles and `hasMore` to know whether it is complete. |
111
114
  | `reading_update` | Change status or tags. Status: `unread` / `reading` / `read` / `archived`. |
112
115
  | `reading_highlight` | Create/list/update/delete highlights and notes. `action` is `create` / `list` / `update` / `delete`; `create` takes a `quote` from the article (plain text or Markdown; formatting is stripped, or pass `startOffset`/`endOffset`), plus optional `note` and `color`. |
116
+ | `reading_save_text` | Save pasted text / Markdown / HTML as a clip; use it for login walls, paywalled snippets, selections, or notes with no fetchable URL. Provide at least one of `text` / `markdown` / `html`. |
113
117
 
114
118
  ## Configuration
115
119
 
@@ -122,6 +126,9 @@ Set these in the shell that starts DSH, or in the profile's `.env`, then restart
122
126
  | `DSH_READING_INBOX_MAX_BYTES` | `5242880` | Max page size (5 MB) |
123
127
  | `DSH_READING_INBOX_MAX_MARKDOWN_CHARS` | `400000` | Max Markdown chars per article; longer content is truncated and flagged |
124
128
  | `DSH_READING_INBOX_MAX_REDIRECTS` | `5` | Max redirects |
129
+ | `DSH_READING_INBOX_ASSETS` | `remote` | Set to `local` to download article images into the clip `assets/`; can also be set per clip with the `assets` tool argument or the UI checkbox |
130
+ | `DSH_READING_INBOX_ASSET_MAX_BYTES` | `5242880` | Max bytes per image |
131
+ | `DSH_READING_INBOX_ASSET_MAX_COUNT` | `50` | Max images localized per clip |
125
132
  | `DSH_READING_INBOX_ALLOW_PRIVATE` | `0` | Set to `1` to allow localhost/private targets; for local tests only |
126
133
  | `DSH_READING_INBOX_USER_AGENT` | `dsh-reading-inbox/0.1 ...` | User-Agent for fetches |
127
134
  | `DSH_READING_INBOX_PROXY` | falls back to `HTTPS_PROXY` / `HTTP_PROXY` | HTTP proxy URL, e.g. `http://127.0.0.1:7890`; the proxy resolves the destination |
@@ -138,6 +145,7 @@ Set these in the shell that starts DSH, or in the profile's `.env`, then restart
138
145
  └── <id>/
139
146
  ├── article.md # clean Markdown body
140
147
  ├── original.html # original HTML snapshot (archive only, never rendered)
148
+ ├── assets/ # optional localized article images
141
149
  ├── annotations.json # highlights/notes (created on the first annotation)
142
150
  └── meta.json # title, URL, author, date, tags, status, annotation count
143
151
  ```
@@ -180,7 +188,7 @@ See [VERIFY.md](VERIFY.md) for the end-to-end check inside a real DSH.
180
188
 
181
189
  ```sh
182
190
  npm run build:client # rebuild client/client.js with esbuild
183
- npm test # 36 tests: extraction, rendering, SSRF, DNS checks, annotation anchoring, store races, search, routes, client bundle
191
+ npm test # 40 tests: extraction, rendering, SSRF, DNS checks, annotation anchoring, store races, search, routes, assets, client bundle
184
192
  npm run verify # end-to-end self-check
185
193
  ```
186
194
 
@@ -197,12 +205,12 @@ Layout:
197
205
 
198
206
  ## Limits and roadmap
199
207
 
200
- 0.3.0 is deliberately small:
208
+ 0.5.0 is deliberately small:
201
209
 
202
210
  - [ ] SPA / login / anti-bot pages may yield no article; add a Playwright fallback.
203
- - [ ] Images still point at remote URLs; download them into `clips/<id>/assets/` for a full offline archive.
211
+ - [x] Images can be downloaded into `clips/<id>/assets/` with provenance; full CSS/font page mirroring is still out of scope.
204
212
  - [ ] No PDF support; use `dsh-pdf-mineru` or a document reader for PDFs.
205
- - [ ] No browser extension or RSS import yet.
213
+ - [ ] No browser extension or RSS import yet; URL, paste-text, JSON import/export and agent tools are covered.
206
214
  - [ ] No sync/backup yet; the directory is portable.
207
215
  - [ ] Search is local BM25-style ranking; add chunking and result highlighting next.
208
216
 
package/README.md CHANGED
@@ -26,11 +26,14 @@ DSH 已经有 `web_fetch`、`read_url` 这类“读一次”的工具,但它
26
26
  ## 功能
27
27
 
28
28
  - **一键剪藏**:粘贴 URL → Readability 提取正文 → Markdown + 原文 HTML + 标题/作者/日期/来源/摘要。
29
+ - **文本/选区采集**:没有可抓取 URL 时,可以直接粘贴正文、Markdown 或 HTML,保存成同一收件箱条目。
30
+ - **导入/导出**:一键导出全部 JSON(可选原始 HTML)或全部 Markdown;导入 JSON 恢复文章、批注和保存视图。
31
+ - **离线图片**:可选把正文图片下载到 `clips/<id>/assets/`,详情通过本地资源路由加载;`meta.json` 记录 charset、HTTP 状态、字节数等 provenance。
29
32
  - **收件箱界面**:未读 / 在读 / 已读 / 归档,搜索、标签筛选、详情阅读、复制链接、导出 Markdown。
30
33
  - **划线与批注**:选中正文文字即可高亮(黄 / 绿 / 蓝 / 红),写笔记;批注按“引文 + 前后文”锚定,文章重新抓取后自动重定位,失败会标为失效而不是错贴。导出 Markdown 时带上有效批注。
31
34
  - **全文检索**:中文按单字 + 二元组切分,英文按词切分;标题和标签权重更高。纯本地,不调用模型。
32
35
  - **检索语法与保存视图**:支持 `tag:security`、`is:unread`、`site:example.com`、`after:2026-01-01`、`before:2026-12-31`、`has:highlight`;结果带命中 snippet;常用查询可存成视图。
33
- - **Agent 工具**:`reading_clip`、`reading_search`、`reading_list`、`reading_read`、`reading_update`、`reading_highlight`。
36
+ - **Agent 工具**:`reading_clip`、`reading_save_text`、`reading_search`、`reading_list`、`reading_read`、`reading_update`、`reading_highlight`。
34
37
  - **斜杠命令**:`/inbox <url> [tag1,tag2]`,不离开对话就能收藏。
35
38
  - **中文网页友好**:自动识别 GBK / GB2312 / UTF-8 / Big5 编码,避免乱码。
36
39
  - **安全默认**:只允许 http/https;逐跳校验重定向;DNS 解析结果在连接时再校验一次(防 DNS rebinding);拒绝本机/内网/云元数据地址;5 MB、20 秒、5 次重定向的硬上限。
@@ -47,7 +50,7 @@ DSH 已经有 `web_fetch`、`read_url` 这类“读一次”的工具,但它
47
50
  dsh plugin --profile web add dsh-reading-inbox
48
51
  ```
49
52
 
50
- > pnpm 的 supply-chain 策略会等新版本发布一段时间才默认采用它。刚发布后如果装到上一版,可显式指定版本:`dsh plugin --profile web add dsh-reading-inbox@0.3.0`。
53
+ > pnpm 的 supply-chain 策略会等新版本发布一段时间才默认采用它。刚发布后如果装到上一版,可显式指定版本:`dsh plugin --profile web add dsh-reading-inbox@0.5.0`。
51
54
 
52
55
  直接从 GitHub 安装:
53
56
 
@@ -69,8 +72,8 @@ dsh plugin --profile web add file:C:/path/to/dsh-reading-inbox
69
72
 
70
73
  ### 在收件箱里
71
74
 
72
- 1. 把网页链接粘贴到顶部的输入框,回车。
73
- 2. 左侧点击文章开始阅读;右侧可以标记已读、归档、复制链接、导出 Markdown、编辑标签。
75
+ 1. 把网页链接粘贴到顶部的输入框,回车;没有链接的内容用“粘贴文本”保存。
76
+ 2. 顶部“导出”下载全部 JSON;“导入”可以恢复之前导出的 JSON。左侧点击文章开始阅读;右侧可以标记已读、归档、复制链接、导出 Markdown、编辑标签。
74
77
  3. 选中正文文字,会浮出高亮工具栏:选颜色、写批注(可选),点“保存高亮”。
75
78
  4. 搜索框支持标题、正文、标签、来源;输入即搜。也可以用 `tag:`、`is:`、`site:`、`after:`、`has:highlight` 组合查询。
76
79
  5. 搜索框下方可以把当前查询存成“视图”,下次点一下就能回到同一组筛选。
@@ -104,12 +107,13 @@ dsh plugin --profile web add file:C:/path/to/dsh-reading-inbox
104
107
 
105
108
  | 工具 | 作用 |
106
109
  | --- | --- |
107
- | `reading_clip` | 抓取 URL,提取正文,保存 Markdown + 原文 HTML,写入索引。重复 URL 默认返回已有条目;`force: true` 重新抓取。 |
110
+ | `reading_clip` | 抓取 URL,提取正文,保存 Markdown + 原文 HTML,写入索引。重复 URL 默认返回已有条目;`force: true` 重新抓取;`assets: 'local'` 下载正文图片。 |
108
111
  | `reading_search` | 全文搜索,支持 `tag:` / `is:` / `site:` / `after:` / `before:` / `has:highlight` 查询语法、状态/标签过滤和分页;返回元数据 + 命中 snippet,不返回全文。 |
109
112
  | `reading_list` | 按时间列出,支持状态/标签过滤。 |
110
113
  | `reading_read` | 按 id 读取 Markdown 切片;用 `offset` / `nextOffset` 翻长文,`hasMore` 判断是否读完。 |
111
114
  | `reading_update` | 修改阅读状态或标签。状态:`unread` / `reading` / `read` / `archived`。 |
112
115
  | `reading_highlight` | 对文章做划线/批注:`action` 为 `create` / `list` / `update` / `delete`;`create` 传原文里的 `quote`(纯文本或 Markdown,服务端会去掉格式;也可传 `startOffset`/`endOffset`),可选 `note` 和 `color`。 |
116
+ | `reading_save_text` | 把粘贴的正文 / Markdown / HTML 保存成 clip;没有可抓取 URL 的登录页、付费墙、选中文字用它。`text` / `markdown` / `html` 至少一个。 |
113
117
 
114
118
  ## 配置
115
119
 
@@ -122,6 +126,9 @@ dsh plugin --profile web add file:C:/path/to/dsh-reading-inbox
122
126
  | `DSH_READING_INBOX_MAX_BYTES` | `5242880` | 单页最大字节数(5 MB) |
123
127
  | `DSH_READING_INBOX_MAX_MARKDOWN_CHARS` | `400000` | 单篇 Markdown 最大字符数,超出截断并标记 |
124
128
  | `DSH_READING_INBOX_MAX_REDIRECTS` | `5` | 最大重定向次数 |
129
+ | `DSH_READING_INBOX_ASSETS` | `remote` | 设为 `local` 时默认下载正文图片到 clip 的 `assets/`;也可以单次用 `reading_clip` 的 `assets` 参数或界面“本地图片”勾选 |
130
+ | `DSH_READING_INBOX_ASSET_MAX_BYTES` | `5242880` | 单张图片最大字节数 |
131
+ | `DSH_READING_INBOX_ASSET_MAX_COUNT` | `50` | 单篇最多本地化图片数 |
125
132
  | `DSH_READING_INBOX_ALLOW_PRIVATE` | `0` | 设为 `1` 才允许抓取本机/内网;只用于本地测试 |
126
133
  | `DSH_READING_INBOX_USER_AGENT` | `dsh-reading-inbox/0.1 ...` | 抓取时的 User-Agent |
127
134
  | `DSH_READING_INBOX_PROXY` | 读 `HTTPS_PROXY` / `HTTP_PROXY` | HTTP 代理地址,例如 `http://127.0.0.1:7890`;走代理时目标由代理解析 |
@@ -138,6 +145,7 @@ dsh plugin --profile web add file:C:/path/to/dsh-reading-inbox
138
145
  └── <id>/
139
146
  ├── article.md # 干净正文(Markdown)
140
147
  ├── original.html # 原始 HTML 快照(只存档,不渲染)
148
+ ├── assets/ # 可选:本地化后的正文图片
141
149
  ├── annotations.json # 划线/批注(首次批注时生成)
142
150
  └── meta.json # 标题、URL、作者、日期、标签、状态、批注数
143
151
  ```
@@ -180,7 +188,7 @@ npm run dev # http://127.0.0.1:4173/dsh-reading-inbox/
180
188
 
181
189
  ```sh
182
190
  npm run build:client # 重新构建 client/client.js(esbuild)
183
- npm test # 36 个测试:提取、渲染、SSRF、DNS 校验、批注锚定、存储竞态、检索、路由、客户端 bundle
191
+ npm test # 40 个测试:提取、渲染、SSRF、DNS 校验、批注锚定、存储竞态、检索、路由、图片本地化、客户端 bundle
184
192
  npm run verify # 端到端自检
185
193
  ```
186
194
 
@@ -197,12 +205,12 @@ npm run verify # 端到端自检
197
205
 
198
206
  ## 限制与 Roadmap
199
207
 
200
- 当前版本是 0.3.0,刻意不做大而全:
208
+ 当前版本是 0.5.0,刻意不做大而全:
201
209
 
202
210
  - [ ] SPA / 登录页 / 反爬页可能提取不到正文;下一步加 Playwright fallback。
203
- - [ ] 图片仍引用远程地址;下一步下载到 `clips/<id>/assets/` 做完整离线存档。
211
+ - [x] 图片可下载到 `clips/<id>/assets/`,记录 provenance;仍不做整页 CSS/字体资源的完整离线镜像。
204
212
  - [ ] 暂不支持 PDF;PDF 请用 `dsh-pdf-mineru` 或文档阅读插件。
205
- - [ ] 暂无浏览器扩展 / RSS 导入;先做 URL 输入和 Agent 工具。
213
+ - [ ] 暂无浏览器扩展 / RSS 导入;已有 URL、粘贴文本、JSON 导入/导出和 Agent 工具。
206
214
  - [ ] 暂无同步/备份;先保证本地目录可复制。
207
215
  - [ ] 检索是本地 BM25 风格排序;下一步加标题/正文分块与搜索结果高亮。
208
216
 
package/VERIFY.md CHANGED
@@ -62,6 +62,20 @@ dsh --profile inbox-web --no-open --port 4191
62
62
  3. 点搜索框下方的“+ 视图”,输入名称并保存;应出现视图 chip。
63
63
  4. 清空搜索后点该 chip,搜索框应恢复保存的查询,列表回到同一组结果;点 chip 上的 × 可删除视图。
64
64
 
65
+ ### 3.3 离线图片与 provenance
66
+
67
+ 1. 勾选顶部“本地图片”,剪藏一篇带正文图片的文章(或先不勾选剪藏一篇,再对同一 URL 用 `reading_clip` 的 `force: true, assets: 'local'` 重新抓取)。
68
+ 2. 期望:`clips/<id>/assets/` 下出现以内容哈希命名的图片,`article.md` 里的图片地址变成 `assets/<hash>.<ext>`。
69
+ 3. 详情页里图片仍应正常显示;直接访问 `http://127.0.0.1:4191/dsh-reading-inbox/asset/<id>/<hash>.png` 应返回图片,非 `127.0.0.1` 来源应被 403 拒绝。
70
+ 4. 打开 `clips/<id>/meta.json`,`assets` 应列出图片,`provenance` 应包含 `finalUrl`、`status`、`contentType`、`charset`、`bytes`、`extractor`。
71
+ 5. 图片超过 `DSH_READING_INBOX_ASSET_MAX_BYTES`、或超过 `DSH_READING_INBOX_ASSET_MAX_COUNT` 时,不应整篇失败:图片被跳过并在 `provenance.warnings` 里记录。
72
+
73
+ ### 3.4 粘贴文本、导入与导出
74
+
75
+ 1. 点顶部“粘贴文本”,填标题和正文(不填 URL)后保存;左侧应出现来源为“手动保存”的条目,详情里不显示“打开原文”。
76
+ 2. 点顶部“导出”,应下载 `dsh-reading-inbox.json`;换一个空数据目录后点“导入”选择该文件,文章、批注和视图应恢复。
77
+ 3. 直接访问 `http://127.0.0.1:4191/dsh-reading-inbox/api/export?format=markdown`,应下载包含所有文章和批注的 Markdown。
78
+
65
79
  ## 4. Agent 工具
66
80
 
67
81
  在对话里说:
package/index.js CHANGED
@@ -11,8 +11,8 @@ const webDir = fileURLToPath(new URL('./web/', import.meta.url))
11
11
 
12
12
  /**
13
13
  * Mount the reading inbox: storage under ~/.dsh-reading-inbox, a web panel on
14
- * the host webserver, six reading_* tools, a /inbox command, and one system
15
- * prompt section so the model knows when to clip, search, and annotate.
14
+ * the host webserver, seven reading_* tools, a /inbox command, and one system
15
+ * prompt section so the model knows when to clip, save text, search, and annotate.
16
16
  */
17
17
  export function apply(ctx) {
18
18
  const config = loadConfig()
@@ -69,6 +69,7 @@ export function apply(ctx) {
69
69
  text: [
70
70
  '本机已安装阅读收件箱(dsh-reading-inbox)。',
71
71
  '当用户说“收藏 / 剪藏 / 稍后读 / 保存这个链接”时,调用 reading_clip。',
72
+ '当用户粘贴正文、选中文字,或内容没有可抓取的 URL 时,调用 reading_save_text(text/markdown/html 至少一个)。',
72
73
  '回答关于已保存文章的问题前,先用 reading_search 找到 clip id,再用 reading_read 读原文。',
73
74
  '当用户要求划线、高亮、批注、标记重点时,调用 reading_highlight:create 传 clip id 和原文中的 quote,可选 note/color;list 查看已有批注;update/delete 需要 annotationId。',
74
75
  '不要编造收件箱里没有的内容;如果搜索没有结果,明确说没有保存过。',
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-reading-inbox",
3
- "version": "0.3.0",
3
+ "version": "0.5.0",
4
4
  "description": "DeepSeek Harness 的阅读收件箱:网页剪藏、Markdown 存档、划线批注、标签、全文检索与 Agent 工具。",
5
5
  "type": "module",
6
6
  "main": "./index.js",
package/src/config.js CHANGED
@@ -23,6 +23,9 @@ export function loadConfig(env = process.env) {
23
23
  maxBytes: positiveInt(env.DSH_READING_INBOX_MAX_BYTES, 5 * 1024 * 1024),
24
24
  maxMarkdownChars: positiveInt(env.DSH_READING_INBOX_MAX_MARKDOWN_CHARS, 400_000),
25
25
  maxRedirects: positiveInt(env.DSH_READING_INBOX_MAX_REDIRECTS, 5),
26
+ assets: env.DSH_READING_INBOX_ASSETS === 'local' ? 'local' : 'remote',
27
+ assetMaxBytes: positiveInt(env.DSH_READING_INBOX_ASSET_MAX_BYTES, 5 * 1024 * 1024),
28
+ assetMaxCount: positiveInt(env.DSH_READING_INBOX_ASSET_MAX_COUNT, 50),
26
29
  allowPrivate: env.DSH_READING_INBOX_ALLOW_PRIVATE === '1' || env.DSH_READING_INBOX_ALLOW_PRIVATE === 'true',
27
30
  blockFakeIp:
28
31
  env.DSH_READING_INBOX_BLOCK_FAKE_IP === '1' || env.DSH_READING_INBOX_BLOCK_FAKE_IP === 'true',
package/src/fetch.js CHANGED
@@ -79,9 +79,9 @@ function charsetFromHtml(buffer) {
79
79
  function decodeBody(buffer, contentType) {
80
80
  const charset = charsetFromContentType(contentType) || charsetFromHtml(buffer) || 'utf-8'
81
81
  try {
82
- return iconv.decode(buffer, charset)
82
+ return { text: iconv.decode(buffer, charset), charset }
83
83
  } catch {
84
- return buffer.toString('utf8')
84
+ return { text: buffer.toString('utf8'), charset: 'utf-8' }
85
85
  }
86
86
  }
87
87
 
@@ -156,14 +156,25 @@ export async function fetchHtml(rawUrl, config, options = {}) {
156
156
  const finalUrl = response.url || url.toString()
157
157
 
158
158
  if (HTML_TYPES.some(type => contentType.includes(type)) || contentType === '') {
159
- return { html: decodeBody(buffer, contentType), finalUrl, contentType }
159
+ const decoded = decodeBody(buffer, contentType)
160
+ return {
161
+ html: decoded.text,
162
+ finalUrl,
163
+ contentType,
164
+ charset: decoded.charset,
165
+ status: response.status,
166
+ bytes: buffer.length,
167
+ }
160
168
  }
161
169
  if (contentType.includes('text/plain')) {
162
- const text = decodeBody(buffer, contentType)
170
+ const decoded = decodeBody(buffer, contentType)
163
171
  return {
164
- html: `<!doctype html><html><head><meta charset="utf-8"></head><body><pre>${escapeHtml(text)}</pre></body></html>`,
172
+ html: `<!doctype html><html><head><meta charset="utf-8"></head><body><pre>${escapeHtml(decoded.text)}</pre></body></html>`,
165
173
  finalUrl,
166
174
  contentType,
175
+ charset: decoded.charset,
176
+ status: response.status,
177
+ bytes: buffer.length,
167
178
  }
168
179
  }
169
180
  throw new Error(`不支持的内容类型:${contentType.split(';')[0]};目前只支持 HTML/纯文本`)
@@ -171,3 +182,54 @@ export async function fetchHtml(rawUrl, config, options = {}) {
171
182
 
172
183
  throw new Error('重定向次数过多')
173
184
  }
185
+
186
+ /**
187
+ * Fetch an image with the same SSRF, redirect, timeout and byte-cap policy as
188
+ * article fetches. Used only when local asset archiving is enabled.
189
+ */
190
+ export async function fetchBinary(rawUrl, config, options = {}) {
191
+ const dispatcher = dispatcherFor(config, options.fetchImpl !== undefined)
192
+ const fetchImpl = options.fetchImpl ?? undiciFetch
193
+ const signal = signalWithTimeout(options.signal, config.timeoutMs)
194
+ const maxBytes = Math.min(config.assetMaxBytes ?? config.maxBytes, config.maxBytes)
195
+ let current = rawUrl
196
+
197
+ for (let hop = 0; hop <= config.maxRedirects; hop += 1) {
198
+ const url = await assertPublicUrl(current, config)
199
+ const response = await fetchImpl(url, {
200
+ redirect: 'manual',
201
+ signal,
202
+ ...(dispatcher === undefined ? {} : { dispatcher }),
203
+ headers: {
204
+ 'user-agent': config.userAgent,
205
+ accept: 'image/*,*/*;q=0.8',
206
+ },
207
+ })
208
+
209
+ if (REDIRECT_STATUS.has(response.status)) {
210
+ const location = response.headers.get('location')
211
+ if (location === null) throw new Error(`HTTP ${response.status} 重定向缺少 Location`)
212
+ current = new URL(location, url).toString()
213
+ if (hop === config.maxRedirects) throw new Error('重定向次数过多')
214
+ continue
215
+ }
216
+ if (!response.ok) {
217
+ throw new Error(`图片抓取失败:HTTP ${response.status} ${response.statusText}`.trim())
218
+ }
219
+
220
+ const contentType = (response.headers.get('content-type') || '').toLowerCase()
221
+ if (!contentType.startsWith('image/')) {
222
+ throw new Error(`不是图片内容:${contentType.split(';')[0] || 'unknown'}`)
223
+ }
224
+ const buffer = await readCapped(response, maxBytes)
225
+ return {
226
+ buffer,
227
+ contentType,
228
+ finalUrl: response.url || url.toString(),
229
+ status: response.status,
230
+ bytes: buffer.length,
231
+ }
232
+ }
233
+
234
+ throw new Error('重定向次数过多')
235
+ }
package/src/markdown.js CHANGED
@@ -87,7 +87,7 @@ function makeTurndown(baseUrl) {
87
87
  return turndown
88
88
  }
89
89
 
90
- function countWords(text) {
90
+ export function countWords(text) {
91
91
  const cjk = (text.match(/[぀-ヿ㐀-䶿一-鿿가-힯]/g) || []).length
92
92
  const latin = (text.replace(/[぀-ヿ㐀-䶿一-鿿가-힯]/g, ' ').match(/[A-Za-z0-9_]+/g) || []).length
93
93
  return { wordCount: cjk + latin, charCount: text.length, cjk }
@@ -112,6 +112,13 @@ function clampText(value, maxLength) {
112
112
  return text.length > maxLength ? text.slice(0, maxLength) : text
113
113
  }
114
114
 
115
+ export function htmlToMarkdown(html, baseUrl = '') {
116
+ const document = parseHTML(`<!doctype html><html><body><div id="manual-root">${String(html ?? '')}</div></body></html>`).document
117
+ const root = document.getElementById('manual-root')
118
+ if (root === null) return ''
119
+ return cleanMarkdown(makeTurndown(baseUrl).turndown(root.innerHTML))
120
+ }
121
+
115
122
  /**
116
123
  * Turn raw HTML into a clean article: metadata, a Turndown Markdown body, and
117
124
  * a safe rendered HTML fragment. Readability runs on a fresh document so meta
package/src/routes.js CHANGED
@@ -130,6 +130,44 @@ async function handleApi(req, res, url, inbox) {
130
130
  return writeJson(res, 200, { ok: true, ...(await inbox.stats()) })
131
131
  }
132
132
 
133
+ if (segments[0] === 'export' && segments.length === 1) {
134
+ if (method !== 'GET') return writeError(res, 405, 'method not allowed')
135
+ const format = url.searchParams.get('format') || 'json'
136
+ if (format === 'markdown') {
137
+ const markdown = await inbox.exportAllMarkdown()
138
+ res.writeHead(200, {
139
+ ...commonHeaders('text/markdown; charset=utf-8'),
140
+ 'content-disposition': 'attachment; filename="dsh-reading-inbox.md"',
141
+ })
142
+ res.end(markdown)
143
+ return
144
+ }
145
+ if (format !== 'json') return writeError(res, 400, 'format 只支持 json 或 markdown')
146
+ const bundle = await inbox.exportBundle({
147
+ includeOriginal: url.searchParams.get('originals') === '1',
148
+ })
149
+ res.writeHead(200, {
150
+ ...commonHeaders('application/json; charset=utf-8'),
151
+ 'content-disposition': 'attachment; filename="dsh-reading-inbox.json"',
152
+ })
153
+ res.end(JSON.stringify(bundle, null, 2))
154
+ return
155
+ }
156
+
157
+ if (segments[0] === 'import' && segments.length === 1) {
158
+ if (method !== 'POST') return writeError(res, 405, 'method not allowed')
159
+ const body = await readJsonBody(req, 20 * 1024 * 1024)
160
+ const result = await inbox.importBundle(body)
161
+ return writeJson(res, 200, { ok: true, ...result })
162
+ }
163
+
164
+ if (segments[0] === 'save-text' && segments.length === 1) {
165
+ if (method !== 'POST') return writeError(res, 405, 'method not allowed')
166
+ const body = await readJsonBody(req, 2 * 1024 * 1024)
167
+ const result = await inbox.saveText(body)
168
+ return writeJson(res, 200, { ok: true, clip: result })
169
+ }
170
+
133
171
  if (segments[0] === 'views') {
134
172
  if (segments.length === 1) {
135
173
  if (method === 'GET') {
@@ -260,6 +298,35 @@ export function createRoutes({ inbox, webDir }) {
260
298
  return
261
299
  }
262
300
 
301
+ if (url.pathname.startsWith(`${PREFIX}/asset/`)) {
302
+ if (req.method !== 'GET' && req.method !== 'HEAD') {
303
+ writeError(res, 405, 'method not allowed')
304
+ return
305
+ }
306
+ const assetPath = url.pathname.slice(`${PREFIX}/asset/`.length)
307
+ const segments = assetPath.split('/').filter(Boolean)
308
+ if (segments.length !== 2) {
309
+ writeError(res, 404, 'not found')
310
+ return
311
+ }
312
+ try {
313
+ const asset = await inbox.readAsset(decodeSegment(segments[0]), decodeSegment(segments[1]))
314
+ res.writeHead(200, {
315
+ 'content-type': asset.contentType,
316
+ 'cache-control': 'private, max-age=3600',
317
+ 'x-content-type-options': 'nosniff',
318
+ // SVG is active content. Sandboxing the response blocks scripts
319
+ // and same-origin access if a hostile SVG is opened directly;
320
+ // loading it through <img> is unaffected.
321
+ 'content-security-policy': "default-src 'none'; sandbox",
322
+ })
323
+ res.end(asset.buffer)
324
+ } catch {
325
+ writeError(res, 404, 'not found')
326
+ }
327
+ return
328
+ }
329
+
263
330
  // Relative assets and API calls in web/index.html assume the trailing
264
331
  // slash. Redirect the bare prefix instead of serving a page that would
265
332
  // resolve ./style.css and ./api against the DSH root.