forked from cflmy/deepseek-harness
feat: embed the View read-only reader #14
No files matched your search
@@ -34,6 +34,7 @@ apps/harness/ # 独立应用仓库(父仓 gitlink:apps
|
||||
│ ├── src/release/ # 应用发行清单、签名、Gitea 发现
|
||||
│ ├── src/ecosystem/ # Runtime 信任来源、安装事务、环境、回退、Bootstrap Tool 兼容
|
||||
│ ├── src/market/ # 市场来源/索引、用户级能力存储、启用作用域、项目导入门禁
|
||||
│ ├── src/reader/ # View embed 桥、manifest/摘要校验、阅读包缓存与同源服务
|
||||
│ ├── src/bootstrap/ # 首次启动状态机、doctor、repair
|
||||
│ ├── src/distribution/ # 安装根、应用更新/回退/卸载
|
||||
│ ├── src/diagnostics/ # 脱敏报告、去重、Gitea Issue 提交
|
||||
@@ -94,6 +95,9 @@ MQDH_HOME/ # 默认 $XDG_DATA_HOME/marqdo-harness,070
|
||||
├── market/
|
||||
│ ├── index.json # 可重建的来源聚合投影
|
||||
│ └── events.jsonl # market.changed 变更事件
|
||||
├── reader/
|
||||
│ ├── packages/ # 按源/View/主题/锚点身份缓存的只读阅读包
|
||||
│ └── staging/ # 未完成的 View 导出
|
||||
├── capabilities/
|
||||
│ ├── index.json # 权威:已安装版本/激活摘要/启用作用域/导入记录
|
||||
│ ├── store/<source>-<kind>-<id>/ # 用户级能力载荷(按摘要分版本)
|
||||
@@ -154,7 +158,7 @@ MQDH_HOME/ # 默认 $XDG_DATA_HOME/marqdo-harness,070
|
||||
|
||||
## 7. Web 工作台
|
||||
|
||||
`/mqdh` 是 DSH Web 内的真实服务器渲染工作台(同一 webserver、同一 loopback 绑定)。生态目录固定按 Runtime → Tool → Std → Ext → Knowledge 展示真实来源;打开/筛选无副作用,候选检查、市场刷新、安装/激活/启用、Runtime 切换、项目导入/锁检查与 Tool 移除由按钮显式发起。市场来源、索引与能力合同见 [MARKET.md](MARKET.md),目录分层见 [ECOSYSTEM.md](ECOSYSTEM.md)。Ext 的市场条目与项目文件分开显示,项目锁语义仍由 CLI `sync --locked --json`/`lock` 承担:
|
||||
`/mqdh` 是 DSH Web 内的真实服务器渲染工作台(同一 webserver、同一 loopback 绑定)。生态目录固定按 Runtime → Tool → Std → Ext → Knowledge 展示真实来源;打开/筛选无副作用,候选检查、市场刷新、安装/激活/启用、Runtime 切换、项目导入/锁检查与 Tool 移除由按钮显式发起。市场来源、索引与能力合同见 [MARKET.md](MARKET.md),目录分层见 [ECOSYSTEM.md](ECOSYSTEM.md),View 阅读桥见 [READER.md](READER.md)。Ext 的市场条目与项目文件分开显示,项目锁语义仍由 CLI `sync --locked --json`/`lock` 承担:
|
||||
|
||||
- Runtime:CLI/Bundle/平台/环境 ID/遥测关闭状态;
|
||||
- Knowledge:集合、导入(浏览器上传文本/文件)、搜索、删除、导出;
|
||||
@@ -173,6 +177,7 @@ MQDH_HOME/ # 默认 $XDG_DATA_HOME/marqdo-harness,070
|
||||
- Runtime 安装只接受 Gitea 权威 release 的不可变 tag、资产名、平台、大小与 SHA-256;市场条目按来源配置发现,下载/解包同样强制摘要、大小、路径与链接安全;失败保留旧组合。
|
||||
- 市场不做可信/不可信中央裁决;来源标签不门禁,安装不等于对模型启用;项目导入只由 CLI 写声明与锁。
|
||||
- 私人知识、完整会话、路径、环境变量、密钥和用户源码默认不进入诊断对外内容。
|
||||
- View 阅读包同源服务只返回 manifest 列出的文件,iframe 仅 `allow-same-origin`,HTML 包 CSP 禁止脚本、表单、顶层导航与外部资源。
|
||||
|
||||
## 9. 出口、发行与引导边界
|
||||
|
||||
|
||||
@@ -0,0 +1,72 @@
|
||||
# 文稿与知识只读阅读:复用 Marqdo View
|
||||
|
||||
本文件是 MQDH 阅读桥的唯一实现合同。正文渲染、主题、公式、表格、代码、锚点、受限媒体与静态包格式由 `marqdo-view` 的公开 `export --embed` 合同负责;MQDH 只负责选中文稿、外部布局、导航、审批/运行/证据入口和同源服务。实现位于 `packages/marqdo/harness/src/reader/`。
|
||||
|
||||
## 1. 上游公开合同
|
||||
|
||||
View 候选(PR `marqdo-view#18`,`tools/view` 分支 `b1f92548`)提供:
|
||||
|
||||
```sh
|
||||
marqdo view export <doc.mq.md|doc.md> --out <dir> --embed \
|
||||
--theme light|dark --anchor <heading-id> --expect-source-sha256 <raw-lower-hex>
|
||||
```
|
||||
|
||||
`manifest.json` 的必核字段:
|
||||
|
||||
| 字段 | 要求 |
|
||||
| --- | --- |
|
||||
| `schema` / `schema_version` | `marqdo.view-export` / `1` |
|
||||
| `mode` | `embedded` |
|
||||
| `theme` | 与请求一致 |
|
||||
| `executed` | 必须为 `false` |
|
||||
| `requires` | `api_revision=1`、`analysis=3`、`observation=1`、`markdown_profile=marqdo.md.v1` |
|
||||
| `producers.view.binary_sha256` | 等于已安装 View 可执行文件的 SHA-256 |
|
||||
| `producers.cli.binary_sha256` | 等于当前 Runtime CLI 的 SHA-256(有值时) |
|
||||
| `pages[0].source_sha256` | 等于所选源文件的原始 SHA-256 |
|
||||
| `pages[0].source_status` | `static-ok` 或 `markdown-only` |
|
||||
| `entry.href` / `entry.file` | 包内相对入口,通常 `index.html` 或 `index.html#<anchor>` |
|
||||
| `entry.anchor` / `entry.heading_ids` | 与请求锚点一致;锚点必须在列表内 |
|
||||
| `files[]` / `assets[]` | 包内相对路径与 SHA-256,不得包含 `.js`/脚本 |
|
||||
|
||||
`--embed` 包只含 `index.html`、`assets/`(CSS/字体/logo)与受限 `media/`;MQDH 不生成、不解析、不覆盖这些文件。
|
||||
|
||||
## 2. 桥接层
|
||||
|
||||
`ReaderService` 对每个请求:
|
||||
|
||||
1. 解析源:工作区文件经 `resolveDocument`(拒绝绝对路径、越界、符号链接);知识源经 collection + relPath 校验,读取 `MQDH_HOME/knowledge/sources/<collection>/<rel>`。
|
||||
2. 读取已安装 Tool 的 `record.json`,定位 `bin/marqdo-view` 并计算 SHA-256;读取当前 Runtime CLI SHA-256。
|
||||
3. 缓存键 = `workspace root + 源相对路径 + 源摘要 + View 二进制摘要 + CLI 二进制摘要 + theme + anchor` 的 SHA-256。
|
||||
4. 缓存未命中时固定 argv 执行 `marqdo view export ...`,`cwd` 为工作区或知识 source root;`MARQDO_TOOL_HOME` 指向当前 Runtime 的隔离 Tool home。
|
||||
5. 校验 manifest、全部包文件摘要、入口文件、主题、锚点、源摘要与生产者摘要。
|
||||
6. 原子移动到 `MQDH_HOME/reader/packages/<id>/`,元数据写在 `<id>.json`;缓存命中不重新导出。
|
||||
|
||||
失败码:`reader.view_missing`、`reader.cli_missing`、`reader.source_invalid`、`reader.source_changed`、`reader.anchor_missing`、`reader.export_failed`、`reader.manifest_invalid`、`reader.package_missing`、`reader.package_invalid`、`reader.knowledge_source_missing`。
|
||||
|
||||
## 3. 同源服务与隔离
|
||||
|
||||
- `POST /mqdh/api/reader/open`:显式 `confirm:true`;只做静态检查与本地导出,不执行文稿。
|
||||
- `GET /mqdh/api/reader/source`:只读源文本,最多 256 KiB,不调用 View。
|
||||
- `GET /mqdh/api/reader/status`:View/CLI 可用性、版本与二进制摘要。
|
||||
- `GET /mqdh/api/reader/package/<id>/<path>`:只服务 manifest 列出的文件;拒绝越界、符号链接、未列出文件与超过 16 MiB 的单个文件。
|
||||
- HTML 包响应发送 `Content-Security-Policy: default-src 'none'; style-src 'self'; font-src 'self'; img-src 'self' data:; media-src 'self'; base-uri 'none'; form-action 'none'; frame-ancestors 'self'`。
|
||||
- 页面 iframe 固定 `sandbox="allow-same-origin"`,不开放脚本、表单或顶层导航;父页 CSP 只允许 `frame-src 'self'`。
|
||||
|
||||
## 4. 两处入口与降级
|
||||
|
||||
- **任务右侧文稿**:工作台“文稿阅读”页签输入工作区相对路径、主题与可选锚点;外层显示路径、View 版本/二进制摘要、manifest 摘要、源码切换与“运行记录”入口。运行、审批和证据仍走现有 `marqdo_program`/CLI 流程。
|
||||
- **知识命中详情**:搜索结果“在 View 阅读”使用同一桥接层、同一 View 制品与同一 iframe;collection、relPath、anchor 由知识命中提供,普通 Markdown 显示 `markdown-only`。
|
||||
- 缺 View / 缺 Runtime 时显示明确文字与恢复入口(生态中心安装 Tool);源变更、锚点缺失、manifest/摘要不匹配均返回结构化错误,不回退到第二套渲染器或静默显示旧包。
|
||||
|
||||
## 5. 不做的部分
|
||||
|
||||
- 不复制 View CSS、不写第二套 Markdown/公式/表格渲染器、不读取 View 私有文件路径。
|
||||
- 不把知识文本、外部链接或未知媒体当作可执行内容;不因阅读自动执行、安装或授权。
|
||||
- 不在 MQDH 内定义新的 View manifest 方言;只消费 `marqdo.view-export` 的公开字段。
|
||||
- 不把“View 包已生成”等同于“运行验收通过”;运行事实仍由 CLI Observation 1 与 MQDH 证据绑定。
|
||||
|
||||
## 6. 验收与限制
|
||||
|
||||
真实证据见 [evidence/2026-11-29-reader.md](evidence/2026-11-29-reader.md):候选 View 二进制 `ab353d09…`、rc.6、真实工作区 `.mq.md` 与知识 `.md`,Playwright 验证主题、公式、表格/代码横向滚动、本地图片、锚点、源码切换、知识命中入口、0 外部请求、0 页面错误。
|
||||
|
||||
未验证:正式 View Release 尚未包含 `--embed`,发布后需用同资产复验;企业代理/离线安装组合;Windows/macOS 包路径;完整 screen-reader/像素级主题走查。
|
||||
@@ -5,6 +5,7 @@
|
||||
| [ARCHITECTURE.md](ARCHITECTURE.md) | 产品边界、包结构、数据布局、执行与安全模型 |
|
||||
| [ECOSYSTEM.md](ECOSYSTEM.md) | 生态目录的发现、浏览与安装边界 |
|
||||
| [MARKET.md](MARKET.md) | 动态来源、市场索引、用户级能力存储与项目导入合同 |
|
||||
| [READER.md](READER.md) | 复用 Marqdo View 的文稿/知识只读阅读桥与隔离合同 |
|
||||
| [NETWORK.md](NETWORK.md) | 默认出口、代理/镜像/离线、审计与拒绝码 |
|
||||
| [BOOTSTRAP.md](BOOTSTRAP.md) | 首次启动状态机、`doctor`/`repair`、离线与失败处理 |
|
||||
| [DIAGNOSTICS.md](DIAGNOSTICS.md) | 本地脱敏报告、去重/限额与显式 Issue 提交 |
|
||||
|
||||
+3
-3
@@ -70,7 +70,7 @@
|
||||
| S03 文件/进程/网络边界 | PARTIAL | 路径/符号链接/argv/进程组/超时/输出上限有测试;OS 级隔离依赖 DSH 沙箱,未声称强隔离。 |
|
||||
| S04 插件/profile 旁路 | PASS | `plugin-manager` 服务关闭;插件 market/manager 工具不可用;不是仅隐藏 UI。 |
|
||||
| S05 工作区隔离 | PARTIAL | 工作区显式且路径受控;未实现每任务独立目录与跨工作区审计。 |
|
||||
| S06 浏览器真实交互 | PARTIAL | 市场工作台已用 Playwright 真实浏览器覆盖刷新/详情/安装/启用/撤销/窄窗口/暗色;知识导入检索、执行审批与完整生态安装仍未在浏览器中运行。 |
|
||||
| S06 浏览器真实交互 | PARTIAL | 市场、View 阅读与五组生态目录已用 Playwright 真实浏览器覆盖刷新/详情/安装/启用/撤销/阅读/知识命中/键盘/窄窗口/暗色;知识导入与执行审批的完整浏览器流程仍未运行。 |
|
||||
| S07 诊断脱敏 | PASS(本地/替身) | 捕获→脱敏→本地报告→显式提交全链路由 `tests/diagnostics.test.ts` 覆盖;真实公网 Gitea 权限与模板未验证,见 DIAG-03/05。 |
|
||||
| S08 独立归档冷安装 | PASS(本机) | 归档内置 Node + `install.sh`;从归档冷安装后 `mqdh --version`、`doctor --json`、`--dump-config` 通过(见 m7 证据)。未在第二台干净主机验证。 |
|
||||
| S09 CI/真实模型/发布 | PARTIAL | `scripts/ci.sh` 与 `.woodpecker/ci.yml` 已实现;父仓 PR#48 的 Woodpecker pipeline 已运行并暴露/修复 candidate manifest bug,最终通过证据以 PR 为准。真实模型两轮验收 UNVERIFIED。 |
|
||||
@@ -120,7 +120,7 @@
|
||||
|
||||
| 门禁 | 状态 | 证据或限制 |
|
||||
| --- | --- | --- |
|
||||
| CAT-01 固定顺序 Runtime/Tool/Std/Ext/Knowledge 与真实来源 | PARTIAL | `/mqdh` 生态目录按固定顺序投影真实状态;Runtime 可显式切换,Tool 候选由市场来源驱动,Ext 市场/已安装/当前项目三段视图与 CLI 锁检查并存,Std 只随 Bundle。市场工作台浏览器/键盘/窄窗口/主题验收已通过;完整五组目录的浏览器遍历未运行。 |
|
||||
| CAT-01 固定顺序 Runtime/Tool/Std/Ext/Knowledge 与真实来源 | PASS | 固定五组同工作台浏览器回归:真实 rc.6 Runtime + Bundle 17 模块 + View Tool + 锁定 Ext 项目 + 私人知识集合;组顺序、真实状态、Knowledge 同集合入口、市场行键盘 Enter、窄窗口/暗色均通过,0 外部请求、0 page error。见 [目录证据](evidence/2026-11-29-catalog.md)。浏览器态 Runtime 缺失负例已通过(空 home 五组仍可用、0 mutating request);下载中断/候选校验失败浏览器负例仍为 UNVERIFIED。 |
|
||||
| CAT-02 打开、筛选、查看详情无自动安装/执行 | PASS | `/ecosystem` 只做本地状态与文件读取;候选检查、项目锁检查、Tool 移除均由按钮显式发起。 |
|
||||
| CAT-03 Ext 锁语义(声明/锁差异/权限) | PARTIAL | 应用不解析第二套依赖图;显示 `marqdo.yaml`/`marqdo.lock` 存在性与摘要,显式按钮调用 CLI `sync --locked --json`/`lock`,错误原文展示;项目导入由 CLI `add` 写声明。 |
|
||||
| CAT-04 真实浏览器与主题回归 | PASS(市场工作台) | Playwright Chromium 149 真实打开 `/mqdh`:无 page/console error、无外部请求、键盘焦点与 Enter 打开详情、420px 窄窗口、明/暗主题截图;证据见 [市场证据](evidence/2026-11-29-market.md#6-真实浏览器与主题回归)。完整五组目录的浏览器遍历仍属 CAT-01。 |
|
||||
@@ -129,7 +129,7 @@
|
||||
| CAT-07 安装→项目导入门禁与 CLI 锁 | PASS | 未安装返回 `extension.not_installed`;已安装 ext 复制到 `marqdo-vendor/<alias>` 后由 CLI `add` 写声明、CLI `lock` 生成锁、`sync --locked` 通过;应用不写锁。真实浏览器完成启用项目→导入→生成锁→卸载被引用拒绝。 |
|
||||
| CAT-08 更新/卸载与项目引用 | PASS | 新版本安装后 `pending_activation=true`、旧版本保持激活,显式 `activate` 才切换;被 `marqdo.yaml`/`marqdo.lock` 引用时卸载返回 `extension.project_referenced`,强制卸载需显式 `force`;运行证据绑定锁摘要,重新锁后旧证据 stale。 |
|
||||
| CAT-09 市场浏览器/键盘/窄窗口/暗色回归 | PASS | Playwright Chromium 149:刷新、详情、安装、启用当前项目、撤销、搜索无网络副作用;`market-refresh` 聚焦、行 Enter 打开详情;420px 窄窗口与 dark 媒体截图;0 external request、0 page error。 |
|
||||
| READER-01 文稿/知识复用 Marqdo View 只读阅读 | UNVERIFIED(上游阻塞) | 等待 `marqdo-view#16` 公开只读嵌入与主题身份、`marqdo-view#15` 结果绑定;应用不实现第二套 Markdown/主题。 |
|
||||
| READER-01 文稿/知识复用 Marqdo View 只读阅读 | PASS(候选 View) | 已接入 View PR #18 的公开 `export --embed`:静态包 manifest、View/CLI 二进制摘要、源摘要、锚点与包文件摘要全部校验;工作区 `.mq.md` 与知识 `.md` 共用同一桥接层/View 制品,iframe 仅 `allow-same-origin`,HTML CSP 禁止脚本/外部资源。Playwright 真实验证主题、公式、表格/代码滚动、本地图片、源码切换、知识命中入口、0 外部请求、0 页面错误;证据见 [reader 证据](evidence/2026-11-29-reader.md)。正式 View Release 尚未包含 `--embed`,发布后同资产复验仍待。 |
|
||||
| SCOPE-01 局部调用、规则审阅与跨会话复用 | UNVERIFIED | 依赖真实模型/浏览器、E07 环境固定与主仓 #28 的独立规则/预期;应用现有 `marqdo_program` 已提供固定 argv/审批/证据基础,但未做真实模型验收。 |
|
||||
|
||||
## 明确边界
|
||||
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 533 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 531 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 544 KiB |
@@ -0,0 +1,75 @@
|
||||
{
|
||||
"schema": "marqdo.mqdh.catalog-evidence",
|
||||
"schema_version": 1,
|
||||
"status": "PASS",
|
||||
"application_sha": "01afaf2ce44effabdc8b45ebe575f580687dbb20",
|
||||
"group_order": [
|
||||
"Runtime",
|
||||
"Tool",
|
||||
"Std",
|
||||
"Ext",
|
||||
"Knowledge"
|
||||
],
|
||||
"runtime": {
|
||||
"cli": "3.0.0-rc.6",
|
||||
"environment": "cli-3.0.0-rc.6-8dc0b006302e",
|
||||
"bundle": "0.2.0",
|
||||
"bundle_digest": "sha256:db905508dde89763b9d43b47fc5d52c6a1d5445a91f3c86a550ced43e8aac9d7",
|
||||
"modules": 17
|
||||
},
|
||||
"tool": {
|
||||
"command": "view",
|
||||
"version": "0.3.0",
|
||||
"binary_sha256": "ab353d09868e651cddf4b7bd774c8a7d241855499b6d34d2c01233898631237c"
|
||||
},
|
||||
"ext": {
|
||||
"capability": "local:ext:demo-ext",
|
||||
"version": "0.2.0",
|
||||
"manifest_digest": "sha256:1535a268f91b4707913e9c8cf812f7dac5e618297ed6027a51787c4233efa8b7",
|
||||
"lock_digest": "sha256:090f0eb2bcaa97064929574224c739b8be75909eda76bce91acb528eb4bf2138"
|
||||
},
|
||||
"knowledge": {
|
||||
"collection": "kc-ff2818c3b057",
|
||||
"sources": 1,
|
||||
"enabled": 1
|
||||
},
|
||||
"browser": {
|
||||
"engine": "Playwright Chromium 149.0.7827.55 (Playwright 1.61.1)",
|
||||
"external_requests": 0,
|
||||
"page_errors": 0,
|
||||
"keyboard": "row-button focus + Enter detail",
|
||||
"viewports": [
|
||||
"1280x900",
|
||||
"420x900"
|
||||
],
|
||||
"themes": [
|
||||
"light",
|
||||
"dark"
|
||||
],
|
||||
"screenshots": [
|
||||
"2026-11-29-catalog-wide-light.png",
|
||||
"2026-11-29-catalog-narrow-light.png",
|
||||
"2026-11-29-catalog-narrow-dark.png"
|
||||
]
|
||||
},
|
||||
"unverified": [
|
||||
"download-interruption/candidate-validation browser negatives",
|
||||
"full tool/project mutation browser confirmation",
|
||||
"keyboard-only traversal and screen-reader"
|
||||
],
|
||||
"empty_home_negative": {
|
||||
"runtime_missing": true,
|
||||
"groups_visible": [
|
||||
"Runtime",
|
||||
"Tool",
|
||||
"Std",
|
||||
"Ext",
|
||||
"Knowledge"
|
||||
],
|
||||
"reader_status": "unavailable: installed View Tool is required",
|
||||
"requests": 14,
|
||||
"external_requests": 0,
|
||||
"mutating_requests": 0,
|
||||
"page_errors": 0
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
# 2026-11-29 生态目录五组组合证据
|
||||
|
||||
状态:固定五组同工作台浏览器回归 **PASS**;Runtime 缺失/下载中断/候选校验失败等浏览器态负例仍为 **UNVERIFIED**(由单元/HTTP 测试与 STATUS 覆盖)。应用身份与 CI 结果见 [2026-11-29-reader-ci.json](2026-11-29-reader-ci.json) 的同一候选提交。
|
||||
|
||||
## 输入
|
||||
|
||||
| 层 | 真实身份 |
|
||||
| --- | --- |
|
||||
| Runtime | CLI `3.0.0-rc.6`,环境 `cli-3.0.0-rc.6-8dc0b006302e`,Bundle `0.2.0` / `sha256:db905508…` / 17 个模块 |
|
||||
| Tool | View 候选 `0.3.0`,二进制 SHA-256 `ab353d09…`,安装在当前 Runtime 隔离 Tool home |
|
||||
| Std | 当前 Bundle 的 `std:clock`、`std:io`、`std:data/*` 等公开导入路径 |
|
||||
| Ext | 当前工作区 `marqdo.yaml` + `marqdo.lock`;市场本地来源安装的 `local:ext:demo-ext@0.2.0` |
|
||||
| Knowledge | 私人集合 `kc-ff2818c3b057` / `阅读知识`,1 份原文,已启用 |
|
||||
|
||||
## 浏览器结果
|
||||
|
||||
Playwright Chromium `149.0.7827.55` 真实打开 `/mqdh`:
|
||||
|
||||
- `#catalog .group h3` 顺序严格为 `Runtime|Tool|Std|Ext|Knowledge`。
|
||||
- 每层都能回溯真实来源:Runtime 版本/平台/环境、Tool 版本与路径、Std 命名空间导入、Ext 项目文件摘要与市场条目、Knowledge 集合计数。
|
||||
- 点击 Knowledge“打开集合”进入同一知识页;市场列表行可用键盘聚焦,`Enter` 打开 `Demo ext` 详情。
|
||||
- 0 外部请求、0 page error;窄窗口 420px 与暗色主题截图如下。
|
||||
|
||||

|
||||
|
||||

|
||||
|
||||

|
||||
|
||||
## Runtime 缺失负例
|
||||
|
||||
空 `MQDH_HOME`(无 Runtime、无 Tool、无知识集合)真实浏览器打开 `/mqdh`:五组仍按顺序显示;Runtime “未安装”、Std “随 Runtime”、Ext 文件“缺失”、Knowledge “0 个集合”;阅读页显示“阅读不可用:installed View Tool is required…”;14 个请求全部同源 GET,0 外部请求、0 mutating request、0 page error。原 DSH 对话入口仍由同一 `/mqdh` 外的页面保留。
|
||||
|
||||
## 未完成
|
||||
|
||||
- 下载中断、候选校验失败在真实浏览器中的目录态负例(命令/单元层已覆盖失败保留旧组合)。
|
||||
- Tool 安装/移除、项目依赖变更的完整浏览器确认流程(命令层已由市场/导入测试覆盖)。
|
||||
- 完整 keyboard-only 走查与 screen-reader。
|
||||
@@ -0,0 +1,53 @@
|
||||
{
|
||||
"schema": "marqdo.mqdh.ci-evidence",
|
||||
"schema_version": 1,
|
||||
"status": "PASS",
|
||||
"application_sha": "01afaf2ce44effabdc8b45ebe575f580687dbb20",
|
||||
"platform": "x86_64-unknown-linux-gnu",
|
||||
"node": "v24.22.3",
|
||||
"view": {
|
||||
"candidate": "marqdo-view#18",
|
||||
"source_sha": "b1f92548dc343435677747580806fbe58c5ab4ef",
|
||||
"binary_sha256": "ab353d09868e651cddf4b7bd774c8a7d241855499b6d34d2c01233898631237c",
|
||||
"command": "marqdo view export --embed --theme --anchor --expect-source-sha256"
|
||||
},
|
||||
"cli": {
|
||||
"version": "3.0.0-rc.6",
|
||||
"source_sha": "63776735e924ade279cdf59d5c733dc24bfdabbb",
|
||||
"binary_sha256": "4f12e6b8a2edb327c0d9ab6165f74e8e88a01b05350527e3aade6f52d4f7a06c"
|
||||
},
|
||||
"browser": {
|
||||
"engine": "Playwright Chromium 149.0.7827.55 (Playwright 1.61.1)",
|
||||
"theme": "dark/light",
|
||||
"math": 1,
|
||||
"image_natural_width": 1,
|
||||
"code_scroll": {
|
||||
"scrollWidth": 1716,
|
||||
"clientWidth": 353
|
||||
},
|
||||
"iframe_sandbox": "allow-same-origin",
|
||||
"external_requests": 0,
|
||||
"page_errors": 0,
|
||||
"knowledge_reader": "PASS",
|
||||
"screenshots": [
|
||||
"2026-11-29-reader-wide-dark.png",
|
||||
"2026-11-29-reader-narrow-dark.png",
|
||||
"2026-11-29-reader-narrow-light.png"
|
||||
]
|
||||
},
|
||||
"unverified": [
|
||||
"official View release with --embed",
|
||||
"enterprise proxy/offline View install",
|
||||
"Windows/macOS packaging",
|
||||
"full screen-reader and pixel theme review"
|
||||
],
|
||||
"remote_ci": {
|
||||
"push": "https://ci.cflmy.cn/repos/21/pipeline/21/1",
|
||||
"pull_request": "https://ci.cflmy.cn/repos/21/pipeline/22/1"
|
||||
},
|
||||
"commands": [
|
||||
"pnpm run typecheck",
|
||||
"node --import tsx/esm --test packages/marqdo/harness/tests/*.test.ts",
|
||||
"Playwright Chromium reader acceptance"
|
||||
]
|
||||
}
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 188 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 134 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 163 KiB |
@@ -0,0 +1,50 @@
|
||||
# 2026-11-29 View 只读阅读桥证据
|
||||
|
||||
状态:候选 View 真实阅读 **PASS**;正式 View Release 与跨平台 **UNVERIFIED**。应用身份与 CI 退出码见 [2026-11-29-reader-ci.json](2026-11-29-reader-ci.json)。
|
||||
|
||||
## 1. 输入与身份
|
||||
|
||||
| 输入 | 身份 |
|
||||
| --- | --- |
|
||||
| View 候选 | PR `marqdo-view#18`;`tools/view` 分支 `b1f92548dc343435677747580806fbe58c5ab4ef`;候选二进制 SHA-256 `ab353d09868e651cddf4b7bd774c8a7d241855499b6d34d2c01233898631237c` |
|
||||
| View 命令 | `marqdo view export <doc> --out <dir> --embed --theme light|dark --anchor <id> --expect-source-sha256 <hex>` |
|
||||
| CLI Runtime | `v3.0.0-rc.6`,source `63776735e924ade279cdf59d5c733dc24bfdabbb`,二进制 SHA-256 `4f12e6b8a2edb327c0d9ab6165f74e8e88a01b05350527e3aade6f52d4f7a06c` |
|
||||
| 平台 | `x86_64-unknown-linux-gnu`,glibc 2.43,Node `v24.22.3` |
|
||||
| 工作区文稿 | `reader.mq.md`:标题、宽表格、长代码块、公式、本地 1×1 PNG、`@exec main` |
|
||||
| 知识源 | collection `kc-ff2818c3b057` / `knowledge.md`:标题、引用、表格、公式;普通 Markdown |
|
||||
|
||||
View 候选 manifest 实测 `mode=embedded`、`executed=false`、`theme=dark`、`source_status=static-ok`,`producers.view.binary_sha256` 与上述候选二进制一致,`pages[0].source_sha256` 与源文件一致。
|
||||
|
||||
## 2. 桥接与失败路径
|
||||
|
||||
命令/服务已验证:
|
||||
|
||||
- 工作区阅读:`POST /mqdh/api/reader/open` → 固定 argv `marqdo view export ... --embed --theme dark --expect-source-sha256 ...` → 校验 manifest/36 个包文件摘要 → 返回 `index.html` 包 URL;第二次打开 `cached=true`。
|
||||
- 锚点:`anchor=表格` 返回 `index.html#%E8%A1%A8%E6%A0%BC`;`anchor=no-such-heading` 返回 `reader.anchor_missing`。
|
||||
- 知识阅读:同一桥接层打开 collection/relPath,manifest `source_status=markdown-only`,标题 ID 为 `知识文章`、`细节`。
|
||||
- 源切换:`GET /mqdh/api/reader/source` 返回原始文本与 `sha256:` 摘要,不调用 View。
|
||||
- 包文件:只服务 manifest 列出的文件;`index.html` 与 CSS 返回正确 content-type;未列出路径/越界/脚本路径拒绝。
|
||||
- 缺 View / 缺 Runtime / 源变更 / 摘要不符 / manifest 主题或生产者不符均有结构化错误,不回退第二套渲染器。
|
||||
|
||||
## 3. 真实浏览器
|
||||
|
||||
Playwright Chromium `149.0.7827.55`(Playwright `1.61.1`)真实打开 `/mqdh`:
|
||||
|
||||
- 工作区阅读 dark:`body[data-theme=dark]`,公式 `math` 1 个,本地图片 `naturalWidth=1`,420px 窄窗口下长代码块 `scrollWidth=1716 > clientWidth=353`,iframe `sandbox="allow-same-origin"`。
|
||||
- 嵌入正文无 `script`/`button`/`.mq-topbar`/`.mq-dock`;0 外部请求、0 page error。
|
||||
- 源码切换显示文稿原文;知识搜索命中“在 View 阅读”打开同一桥接层的知识包,正文包含“知识文章”。
|
||||
- 宽屏 dark、窄屏 dark、窄屏 light 截图:
|
||||
|
||||

|
||||
|
||||

|
||||
|
||||

|
||||
|
||||
## 4. 未验证
|
||||
|
||||
- View 正式 Release 尚未包含 `--embed`;发布后必须用同资产复验并记录 tag/资产 SHA。
|
||||
- 企业代理/离线包安装组合下的 View Tool 获取。
|
||||
- Windows/macOS 路径与打包。
|
||||
- 完整 screen-reader 与像素级主题走查。
|
||||
- View 独立阅读器与嵌入正文的自动化样式对比目前复用 View 自身 `embedded.browser.cjs` 的证据;MQDH 侧只断言同一主题、同一包和关键渲染结果。
|
||||
@@ -49,6 +49,10 @@ export interface MdhLayout {
|
||||
readonly capabilityStore: string
|
||||
readonly capabilityStaging: string
|
||||
readonly capabilityAudit: string
|
||||
/** Read-only View reader package cache. */
|
||||
readonly reader: string
|
||||
readonly readerPackages: string
|
||||
readonly readerStaging: string
|
||||
/** Private knowledge root. */
|
||||
readonly knowledge: string
|
||||
/** Imported original knowledge documents. */
|
||||
@@ -101,6 +105,9 @@ export function layoutOf(home: string): MdhLayout {
|
||||
capabilityStore: join(root, 'capabilities', 'store'),
|
||||
capabilityStaging: join(root, 'capabilities', 'staging'),
|
||||
capabilityAudit: join(root, 'capabilities', 'audit.jsonl'),
|
||||
reader: join(root, 'reader'),
|
||||
readerPackages: join(root, 'reader', 'packages'),
|
||||
readerStaging: join(root, 'reader', 'staging'),
|
||||
knowledge: join(root, 'knowledge'),
|
||||
knowledgeSources: join(root, 'knowledge', 'sources'),
|
||||
knowledgeIndex: join(root, 'knowledge', 'index'),
|
||||
@@ -136,6 +143,9 @@ export async function ensureMdhHome(home: string): Promise<MdhLayout> {
|
||||
layout.capabilities,
|
||||
layout.capabilityStore,
|
||||
layout.capabilityStaging,
|
||||
layout.reader,
|
||||
layout.readerPackages,
|
||||
layout.readerStaging,
|
||||
layout.knowledge,
|
||||
layout.knowledgeSources,
|
||||
layout.knowledgeIndex,
|
||||
|
||||
@@ -185,11 +185,12 @@ export class KnowledgeManager {
|
||||
if (text === undefined) {
|
||||
return { schema: COLLECTIONS_SCHEMA, schema_version: 1, collections: [] }
|
||||
}
|
||||
const parsed = JSON.parse(text) as CollectionsFile
|
||||
if (parsed.schema !== COLLECTIONS_SCHEMA || parsed.schema_version !== 1 || !Array.isArray(parsed.collections)) {
|
||||
const parsed: unknown = JSON.parse(text)
|
||||
const record = typeof parsed === 'object' && parsed !== null && !Array.isArray(parsed) ? parsed as Record<string, unknown> : undefined
|
||||
if (record === undefined || record.schema !== COLLECTIONS_SCHEMA || record.schema_version !== 1 || !Array.isArray(record.collections)) {
|
||||
throw new KnowledgeError('unsupported knowledge collections file')
|
||||
}
|
||||
return parsed
|
||||
return parsed as CollectionsFile
|
||||
}
|
||||
|
||||
/** Persist the collections file. */
|
||||
@@ -261,6 +262,25 @@ export class KnowledgeManager {
|
||||
return join(this.#layout.knowledgeSources, id)
|
||||
}
|
||||
|
||||
/** Resolve one imported source to its absolute copy and recorded identity. */
|
||||
async sourcePath(id: string, relPath: string): Promise<{
|
||||
root: string
|
||||
relative: string
|
||||
absolute: string
|
||||
digest: string
|
||||
title: string
|
||||
} | undefined> {
|
||||
const collection = await this.collection(id)
|
||||
if (collection === undefined) return undefined
|
||||
const relativePath = normalizeSourcePath(relPath)
|
||||
const known = collection.sources.find(source => source.relPath === relativePath)
|
||||
if (known === undefined) return undefined
|
||||
const root = this.sourceRoot(collection.id)
|
||||
const absolute = join(root, relativePath)
|
||||
assertWithin(root, absolute, 'knowledge source')
|
||||
return { root, relative: relativePath, absolute, digest: known.digest, title: known.title }
|
||||
}
|
||||
|
||||
/** Import files or directories. Nothing is written until all candidates pass. */
|
||||
async import(input: {
|
||||
collection: string
|
||||
@@ -279,8 +299,8 @@ export class KnowledgeManager {
|
||||
if (!info) { rejected.push({ path: selected, reason: 'not found' }); continue }
|
||||
if (info.isSymbolicLink()) { rejected.push({ path: selected, reason: 'symbolic link is not allowed' }); continue }
|
||||
const files = info.isDirectory()
|
||||
? await listRegularFiles(selected, { maxFiles: IMPORT_LIMITS.maxFiles }).catch((error: Error) => {
|
||||
rejected.push({ path: selected, reason: error.message })
|
||||
? await listRegularFiles(selected, { maxFiles: IMPORT_LIMITS.maxFiles }).catch((error: unknown) => {
|
||||
rejected.push({ path: selected, reason: error instanceof Error ? error.message : String(error) })
|
||||
return []
|
||||
})
|
||||
: [{ relative: basename(selected), size: info.size }]
|
||||
@@ -325,8 +345,8 @@ export class KnowledgeManager {
|
||||
rejected.push({ path: candidate.relPath, reason: 'document declares an @exec region; import a reviewed static extract instead' })
|
||||
continue
|
||||
}
|
||||
const semantic = await this.#checkExecutable(candidate.bytes, candidate.relPath).catch((error: Error) => {
|
||||
rejected.push({ path: candidate.relPath, reason: error.message })
|
||||
const semantic = await this.#checkExecutable(candidate.bytes, candidate.relPath).catch((error: unknown) => {
|
||||
rejected.push({ path: candidate.relPath, reason: error instanceof Error ? error.message : String(error) })
|
||||
return 'rejected' as const
|
||||
})
|
||||
if (semantic === 'rejected') continue
|
||||
@@ -425,11 +445,12 @@ export class KnowledgeManager {
|
||||
async indexState(id: string): Promise<IndexState | undefined> {
|
||||
const text = await readText(join(this.#layout.knowledgeIndex, id, 'state.json'))
|
||||
if (text === undefined) return undefined
|
||||
const parsed = JSON.parse(text) as IndexState
|
||||
if (parsed.schema !== 'marqdo.mqdh.knowledge-index' || parsed.schema_version !== 1) {
|
||||
const parsed: unknown = JSON.parse(text)
|
||||
const record = typeof parsed === 'object' && parsed !== null && !Array.isArray(parsed) ? parsed as Record<string, unknown> : undefined
|
||||
if (record === undefined || record.schema !== 'marqdo.mqdh.knowledge-index' || record.schema_version !== 1) {
|
||||
throw new KnowledgeError('unsupported knowledge index state')
|
||||
}
|
||||
return parsed
|
||||
return parsed as IndexState
|
||||
}
|
||||
|
||||
/** Compute the current source-tree digest for one collection. */
|
||||
@@ -453,8 +474,11 @@ export class KnowledgeManager {
|
||||
const record = await readJson<Record<string, unknown>>(join(toolHome, 'knowledge', 'record.json'))
|
||||
if (!record || record.command !== 'knowledge') return undefined
|
||||
const manifest = await readJson<Record<string, unknown>>(join(toolHome, 'knowledge', 'tool.json'))
|
||||
const requires = manifest?.requires as Record<string, unknown> | undefined
|
||||
if (!manifest || requires?.api_revision !== 1 || requires?.analysis !== 3) return undefined
|
||||
if (manifest === undefined) return undefined
|
||||
const requires = manifest.requires
|
||||
if (typeof requires !== 'object' || requires === null || Array.isArray(requires)) return undefined
|
||||
const requirement = requires as Record<string, unknown>
|
||||
if (requirement.api_revision !== 1 || requirement.analysis !== 3) return undefined
|
||||
return { cli, toolHome }
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,333 @@
|
||||
/**
|
||||
* View embedded-export manifest validation.
|
||||
*
|
||||
* View is the only renderer and theme authority. MQDH checks the public
|
||||
* `marqdo.view-export` manifest, its producer digests, the selected source
|
||||
* digest and package file digests before serving the package in a sandboxed
|
||||
* same-origin frame.
|
||||
*
|
||||
* @module @marqdo/mqdh-harness/reader/contract
|
||||
*/
|
||||
|
||||
import { lstat } from 'node:fs/promises'
|
||||
import { join } from 'node:path'
|
||||
import { digestFile, isWithin } from '../core/fsx.ts'
|
||||
import { READER_ERROR, ReaderError } from './errors.ts'
|
||||
|
||||
/** Reader theme selected by the user. */
|
||||
export type ReaderTheme = 'light' | 'dark'
|
||||
|
||||
/** Source kind accepted by the bridge. */
|
||||
export type ReaderSourceKind = 'workspace' | 'knowledge'
|
||||
|
||||
/** One requested reading surface. */
|
||||
export interface ReaderRequest {
|
||||
readonly kind: ReaderSourceKind
|
||||
/** Workspace-relative path or knowledge source relative path. */
|
||||
readonly path: string
|
||||
/** Collection id for a knowledge source. */
|
||||
readonly collection?: string | undefined
|
||||
readonly theme?: ReaderTheme | undefined
|
||||
readonly anchor?: string | undefined
|
||||
readonly force?: boolean | undefined
|
||||
}
|
||||
|
||||
/** Resolved source identity. */
|
||||
export interface ReaderSource {
|
||||
readonly kind: ReaderSourceKind
|
||||
readonly collection: string | null
|
||||
readonly root: string
|
||||
readonly relative: string
|
||||
readonly absolute: string
|
||||
/** `sha256:<hex>` digest of the exact source bytes. */
|
||||
readonly digest: string
|
||||
readonly title: string | null
|
||||
}
|
||||
|
||||
/** Installed View Tool identity from the active Runtime. */
|
||||
export interface ReaderViewTool {
|
||||
readonly command: 'view'
|
||||
readonly version: string | null
|
||||
readonly path: string
|
||||
readonly entrypoint: string
|
||||
readonly binaryPath: string
|
||||
/** Bare lowercase hex SHA-256 of the View executable. */
|
||||
readonly binarySha256: string
|
||||
readonly sourceSha: string | null
|
||||
}
|
||||
|
||||
/** One validated file of an embedded package. */
|
||||
export interface ReaderPackageFile {
|
||||
readonly path: string
|
||||
readonly sha256: string
|
||||
}
|
||||
|
||||
/** Cache metadata for one embedded package. */
|
||||
export interface ReaderPackageMeta {
|
||||
readonly schema: 'marqdo.mqdh.reader-package'
|
||||
readonly schema_version: 1
|
||||
readonly id: string
|
||||
readonly created_at: string
|
||||
readonly source: {
|
||||
readonly kind: ReaderSourceKind
|
||||
readonly collection: string | null
|
||||
readonly relative: string
|
||||
readonly digest: string
|
||||
readonly title: string | null
|
||||
}
|
||||
readonly theme: ReaderTheme
|
||||
readonly anchor: string | null
|
||||
readonly entry: {
|
||||
readonly href: string
|
||||
readonly file: string
|
||||
readonly heading_ids: readonly string[]
|
||||
readonly relative_path: string
|
||||
}
|
||||
readonly view: {
|
||||
readonly version: string | null
|
||||
readonly binary_sha256: string
|
||||
readonly source_sha: string | null
|
||||
}
|
||||
readonly cli: {
|
||||
readonly version: string | null
|
||||
readonly binary_sha256: string
|
||||
}
|
||||
readonly manifest_sha256: string
|
||||
readonly files: readonly ReaderPackageFile[]
|
||||
readonly assets: readonly ReaderPackageFile[]
|
||||
}
|
||||
|
||||
/** Reader package returned to the workbench. */
|
||||
export interface ReaderPackage {
|
||||
readonly id: string
|
||||
readonly source: ReaderPackageMeta['source']
|
||||
readonly theme: ReaderTheme
|
||||
readonly anchor: string | null
|
||||
readonly entry_href: string
|
||||
readonly heading_ids: readonly string[]
|
||||
readonly view: ReaderPackageMeta['view']
|
||||
readonly cli: ReaderPackageMeta['cli']
|
||||
readonly manifest_sha256: string
|
||||
readonly created_at: string
|
||||
readonly cached: boolean
|
||||
readonly package_url: string
|
||||
}
|
||||
|
||||
/** Expected identities one manifest must match. */
|
||||
export interface ViewManifestExpectation {
|
||||
readonly sourceSha256: string
|
||||
readonly viewBinarySha256: string
|
||||
readonly cliBinarySha256: string
|
||||
readonly theme: ReaderTheme
|
||||
readonly anchor: string | null
|
||||
readonly relativePath: string
|
||||
}
|
||||
|
||||
/** Parsed View manifest values the bridge consumes. */
|
||||
export interface ViewManifest {
|
||||
readonly schemaVersion: number
|
||||
readonly mode: string
|
||||
readonly theme: ReaderTheme
|
||||
readonly executed: boolean
|
||||
readonly requires: Record<string, unknown>
|
||||
readonly producers: Record<string, unknown>
|
||||
readonly entry: {
|
||||
readonly href: string
|
||||
readonly file: string
|
||||
readonly heading_ids: readonly string[]
|
||||
readonly relative_path: string
|
||||
readonly anchor: string | null
|
||||
readonly sha256: string
|
||||
}
|
||||
readonly pages: readonly {
|
||||
readonly source_sha256: string
|
||||
readonly source_status: string
|
||||
readonly relative_path: string
|
||||
readonly sha256: string
|
||||
}[]
|
||||
readonly files: readonly ReaderPackageFile[]
|
||||
readonly assets: readonly ReaderPackageFile[]
|
||||
}
|
||||
|
||||
/** Read a plain object or throw a manifest error. */
|
||||
function objectOf(value: unknown, label: string): Record<string, unknown> {
|
||||
if (typeof value !== 'object' || value === null || Array.isArray(value)) {
|
||||
throw new ReaderError(READER_ERROR.manifestInvalid, `${label} must be an object`)
|
||||
}
|
||||
return value as Record<string, unknown>
|
||||
}
|
||||
|
||||
/** Read a required string. */
|
||||
function stringOf(record: Record<string, unknown>, key: string, label: string): string {
|
||||
const value = record[key]
|
||||
if (typeof value !== 'string' || value === '') throw new ReaderError(READER_ERROR.manifestInvalid, `${label}.${key} must be a non-empty string`)
|
||||
return value
|
||||
}
|
||||
|
||||
/** Read an optional string. */
|
||||
function optionalString(record: Record<string, unknown>, key: string, label: string): string | null {
|
||||
const value = record[key]
|
||||
if (value === undefined || value === null) return null
|
||||
if (typeof value !== 'string') throw new ReaderError(READER_ERROR.manifestInvalid, `${label}.${key} must be a string`)
|
||||
return value
|
||||
}
|
||||
|
||||
/** Read a required digest as bare lowercase hex. */
|
||||
function digestOf(record: Record<string, unknown>, key: string, label: string): string {
|
||||
const value = record[key]
|
||||
if (typeof value !== 'string') throw new ReaderError(READER_ERROR.manifestInvalid, `${label}.${key} must be a digest`)
|
||||
const match = /^(?:sha256:)?([0-9a-f]{64})$/.exec(value)
|
||||
if (match?.[1] === undefined) throw new ReaderError(READER_ERROR.manifestInvalid, `${label}.${key} must be a SHA-256 digest`)
|
||||
return match[1]
|
||||
}
|
||||
|
||||
/** Read one file list with path and digest. */
|
||||
function fileList(record: Record<string, unknown>, key: string, label: string): ReaderPackageFile[] {
|
||||
const value = record[key]
|
||||
if (value === undefined || value === null) return []
|
||||
if (!Array.isArray(value)) throw new ReaderError(READER_ERROR.manifestInvalid, `${label}.${key} must be an array`)
|
||||
return value.map((item, index) => {
|
||||
const file = objectOf(item, `${label}.${key}[${index}]`)
|
||||
const path = stringOf(file, 'path', `${label}.${key}[${index}]`)
|
||||
assertPackagePath(path, `${label}.${key}[${index}].path`)
|
||||
return {
|
||||
path,
|
||||
sha256: digestOf(file, 'sha256', `${label}.${key}[${index}]`),
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/** Reject a package-relative path that could escape or execute. */
|
||||
export function assertPackagePath(path: string, label: string): void {
|
||||
if (path === '' || path.startsWith('/') || /^[A-Za-z]:/.test(path) || path.includes('\\') || path.includes('\0')) {
|
||||
throw new ReaderError(READER_ERROR.manifestInvalid, `${label} is not a package-relative path: ${path}`)
|
||||
}
|
||||
const segments = path.split('/')
|
||||
if (segments.some(segment => segment === '' || segment === '.' || segment === '..')) {
|
||||
throw new ReaderError(READER_ERROR.manifestInvalid, `${label} is not a safe package path: ${path}`)
|
||||
}
|
||||
if (/\.(?:m?js|jsx|ts|tsx)$/i.test(path)) {
|
||||
throw new ReaderError(READER_ERROR.manifestInvalid, `${label} must not contain scripts: ${path}`)
|
||||
}
|
||||
}
|
||||
|
||||
/** Parse one `marqdo.view-export` manifest. */
|
||||
export function parseViewManifest(value: unknown): ViewManifest {
|
||||
const record = objectOf(value, 'manifest')
|
||||
const schemaVersion = record.schema_version
|
||||
if (record.schema !== 'marqdo.view-export' || schemaVersion !== 1) {
|
||||
throw new ReaderError(READER_ERROR.manifestInvalid, 'unsupported View export schema')
|
||||
}
|
||||
const theme = stringOf(record, 'theme', 'manifest')
|
||||
if (theme !== 'light' && theme !== 'dark') throw new ReaderError(READER_ERROR.manifestInvalid, `unknown View theme: ${theme}`)
|
||||
const entry = objectOf(record.entry, 'manifest.entry')
|
||||
const rawPages = record.pages
|
||||
if (!Array.isArray(rawPages) || rawPages.length !== 1) {
|
||||
throw new ReaderError(READER_ERROR.manifestInvalid, 'embedded export must contain exactly one page')
|
||||
}
|
||||
const page = objectOf(rawPages[0], 'manifest.pages[0]')
|
||||
const rawHeadingIds = entry.heading_ids
|
||||
if (!Array.isArray(rawHeadingIds) || !rawHeadingIds.every(item => typeof item === 'string')) {
|
||||
throw new ReaderError(READER_ERROR.manifestInvalid, 'manifest.entry.heading_ids must be a string array')
|
||||
}
|
||||
return {
|
||||
schemaVersion,
|
||||
mode: stringOf(record, 'mode', 'manifest'),
|
||||
theme,
|
||||
executed: record.executed === true,
|
||||
requires: objectOf(record.requires, 'manifest.requires'),
|
||||
producers: objectOf(record.producers, 'manifest.producers'),
|
||||
entry: {
|
||||
href: stringOf(entry, 'href', 'manifest.entry'),
|
||||
file: stringOf(entry, 'file', 'manifest.entry'),
|
||||
heading_ids: rawHeadingIds,
|
||||
relative_path: stringOf(entry, 'relative_path', 'manifest.entry'),
|
||||
anchor: optionalString(entry, 'anchor', 'manifest.entry'),
|
||||
sha256: digestOf(entry, 'sha256', 'manifest.entry'),
|
||||
},
|
||||
pages: [{
|
||||
source_sha256: digestOf(page, 'source_sha256', 'manifest.pages[0]'),
|
||||
source_status: stringOf(page, 'source_status', 'manifest.pages[0]'),
|
||||
relative_path: stringOf(page, 'relative_path', 'manifest.pages[0]'),
|
||||
sha256: digestOf(page, 'sha256', 'manifest.pages[0]'),
|
||||
}],
|
||||
files: fileList(record, 'files', 'manifest'),
|
||||
assets: fileList(record, 'assets', 'manifest'),
|
||||
}
|
||||
}
|
||||
|
||||
/** Validate the manifest against the exact source, Tool and CLI identities. */
|
||||
export function validateViewManifest(manifest: ViewManifest, expected: ViewManifestExpectation): void {
|
||||
if (manifest.mode !== 'embedded') throw new ReaderError(READER_ERROR.manifestInvalid, `View export mode is ${manifest.mode}, expected embedded`)
|
||||
if (manifest.executed) throw new ReaderError(READER_ERROR.manifestInvalid, 'View embed manifest claims execution')
|
||||
if (manifest.theme !== expected.theme) throw new ReaderError(READER_ERROR.manifestInvalid, 'View theme does not match the request')
|
||||
if (manifest.requires.api_revision !== 1 || manifest.requires.analysis !== 3 || manifest.requires.observation !== 1) {
|
||||
throw new ReaderError(READER_ERROR.manifestInvalid, 'View export requires an unsupported protocol revision')
|
||||
}
|
||||
if (manifest.requires.markdown_profile !== 'marqdo.md.v1') {
|
||||
throw new ReaderError(READER_ERROR.manifestInvalid, 'View export markdown profile is not marqdo.md.v1')
|
||||
}
|
||||
const viewProducer = objectOf(manifest.producers.view, 'manifest.producers.view')
|
||||
if (digestOf(viewProducer, 'binary_sha256', 'manifest.producers.view') !== expected.viewBinarySha256) {
|
||||
throw new ReaderError(READER_ERROR.manifestInvalid, 'View producer digest does not match the installed Tool')
|
||||
}
|
||||
const cliProducer = manifest.producers.cli
|
||||
if (cliProducer !== null && cliProducer !== undefined) {
|
||||
const cli = objectOf(cliProducer, 'manifest.producers.cli')
|
||||
if (digestOf(cli, 'binary_sha256', 'manifest.producers.cli') !== expected.cliBinarySha256) {
|
||||
throw new ReaderError(READER_ERROR.manifestInvalid, 'CLI producer digest does not match the active Runtime')
|
||||
}
|
||||
}
|
||||
const page = manifest.pages[0]
|
||||
if (page === undefined) throw new ReaderError(READER_ERROR.manifestInvalid, 'View export has no page')
|
||||
if (page.source_sha256 !== expected.sourceSha256) {
|
||||
throw new ReaderError(READER_ERROR.sourceChanged, 'View export source digest does not match the selected document')
|
||||
}
|
||||
if (page.source_status !== 'static-ok' && page.source_status !== 'markdown-only') {
|
||||
throw new ReaderError(READER_ERROR.manifestInvalid, `unexpected View source status: ${page.source_status}`)
|
||||
}
|
||||
if (manifest.entry.relative_path !== expected.relativePath || page.relative_path !== expected.relativePath) {
|
||||
throw new ReaderError(READER_ERROR.manifestInvalid, 'View export entry path does not match the request')
|
||||
}
|
||||
assertPackagePath(manifest.entry.file, 'manifest.entry.file')
|
||||
assertPackagePath(manifest.entry.href.split('#')[0] ?? '', 'manifest.entry.href')
|
||||
if (manifest.entry.anchor !== expected.anchor) {
|
||||
throw new ReaderError(READER_ERROR.manifestInvalid, 'View export anchor does not match the request')
|
||||
}
|
||||
if (expected.anchor !== null && !manifest.entry.heading_ids.includes(expected.anchor)) {
|
||||
throw new ReaderError(READER_ERROR.anchorMissing, `requested anchor does not exist: ${expected.anchor}`)
|
||||
}
|
||||
if (expected.anchor === null && manifest.entry.href !== manifest.entry.file) {
|
||||
throw new ReaderError(READER_ERROR.manifestInvalid, 'View export has an unexpected entry fragment')
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Verify every package file digest and ensure the entry file is listed.
|
||||
* @param packageRoot - extracted package directory.
|
||||
* @param manifest - validated manifest.
|
||||
* @returns the verified file list.
|
||||
*/
|
||||
export async function verifyPackageFiles(packageRoot: string, manifest: ViewManifest): Promise<ReaderPackageFile[]> {
|
||||
const all = [...manifest.files, ...manifest.assets]
|
||||
const seen = new Set<string>()
|
||||
let total = 0
|
||||
for (const file of all) {
|
||||
assertPackagePath(file.path, 'package file')
|
||||
if (seen.has(file.path)) throw new ReaderError(READER_ERROR.manifestInvalid, `duplicate package file: ${file.path}`)
|
||||
seen.add(file.path)
|
||||
const target = join(packageRoot, file.path)
|
||||
if (!isWithin(packageRoot, target)) throw new ReaderError(READER_ERROR.packageInvalid, `package file escapes its root: ${file.path}`)
|
||||
const info = await lstat(target).catch(() => undefined)
|
||||
if (info === undefined || !info.isFile() || info.isSymbolicLink()) {
|
||||
throw new ReaderError(READER_ERROR.packageInvalid, `package file is not a regular file: ${file.path}`)
|
||||
}
|
||||
if (info.size > 16 * 1024 * 1024) throw new ReaderError(READER_ERROR.packageInvalid, `package file exceeds its size limit: ${file.path}`)
|
||||
total += info.size
|
||||
if (total > 64 * 1024 * 1024) throw new ReaderError(READER_ERROR.packageInvalid, 'package exceeds its total size limit')
|
||||
const actual = await digestFile(target)
|
||||
if (actual !== `sha256:${file.sha256}`) throw new ReaderError(READER_ERROR.packageInvalid, `package file digest mismatch: ${file.path}`)
|
||||
}
|
||||
if (!seen.has(manifest.entry.file)) throw new ReaderError(READER_ERROR.manifestInvalid, 'entry file is not listed in the package')
|
||||
return all
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
/**
|
||||
* Reader bridge failure codes.
|
||||
*
|
||||
* Opening a reader package performs a static View export (a CLI `check` and
|
||||
* local HTML write) but never executes the document. Failures keep their own
|
||||
* code so the workbench can distinguish a missing Tool, a source change, an
|
||||
* invalid anchor and an untrusted package.
|
||||
*
|
||||
* @module @marqdo/mqdh-harness/reader/errors
|
||||
*/
|
||||
|
||||
/** Reader failure with a stable local code. */
|
||||
export class ReaderError extends Error {
|
||||
override name = 'ReaderError'
|
||||
readonly code: string
|
||||
|
||||
constructor(code: string, message: string) {
|
||||
super(message)
|
||||
this.code = code
|
||||
}
|
||||
}
|
||||
|
||||
/** Canonical reader failure codes. */
|
||||
export const READER_ERROR = {
|
||||
viewMissing: 'reader.view_missing',
|
||||
cliMissing: 'reader.cli_missing',
|
||||
sourceInvalid: 'reader.source_invalid',
|
||||
sourceChanged: 'reader.source_changed',
|
||||
anchorMissing: 'reader.anchor_missing',
|
||||
exportFailed: 'reader.export_failed',
|
||||
manifestInvalid: 'reader.manifest_invalid',
|
||||
packageMissing: 'reader.package_missing',
|
||||
packageInvalid: 'reader.package_invalid',
|
||||
knowledgeSourceMissing: 'reader.knowledge_source_missing',
|
||||
} as const
|
||||
|
||||
/** One canonical reader failure code. */
|
||||
export type ReaderErrorCode = (typeof READER_ERROR)[keyof typeof READER_ERROR]
|
||||
@@ -0,0 +1,402 @@
|
||||
/**
|
||||
* Read-only View reader bridge.
|
||||
*
|
||||
* One bridge runs the installed View Tool's public `export --embed` command,
|
||||
* validates the resulting package manifest and producer identities, caches the
|
||||
* package by source/Tool/theme identity and serves package files for a
|
||||
* sandboxed same-origin iframe. The bridge never renders Markdown, copies View
|
||||
* CSS or executes the document.
|
||||
*
|
||||
* @module @marqdo/mqdh-harness/reader/service
|
||||
*/
|
||||
|
||||
import { createHash, randomBytes } from 'node:crypto'
|
||||
import { lstat, mkdir, readFile, realpath, rename, rm } from 'node:fs/promises'
|
||||
import { dirname, extname, join, relative as relativePath } from 'node:path'
|
||||
import { digestBytes, digestFile, isDirectory, isFile, isWithin, readJson, writeJsonAtomic } from '../core/fsx.ts'
|
||||
import type { MdhLayout } from '../core/home.ts'
|
||||
import { withLock } from '../core/lock.ts'
|
||||
import { runProcess } from '../core/process.ts'
|
||||
import type { MarqdoCli } from '../execution/cli.ts'
|
||||
import { resolveDocument } from '../workspace.ts'
|
||||
import {
|
||||
assertPackagePath, parseViewManifest, validateViewManifest, verifyPackageFiles,
|
||||
} from './contract.ts'
|
||||
import type {
|
||||
ReaderPackage, ReaderPackageFile, ReaderPackageMeta, ReaderRequest, ReaderSource, ReaderTheme,
|
||||
ReaderViewTool, ViewManifest,
|
||||
} from './contract.ts'
|
||||
import { READER_ERROR, ReaderError } from './errors.ts'
|
||||
|
||||
/** Reader bridge dependencies. */
|
||||
export interface ReaderServiceOptions {
|
||||
readonly layout: MdhLayout
|
||||
readonly cli: () => Promise<MarqdoCli | undefined>
|
||||
readonly toolHome: () => Promise<string | undefined>
|
||||
readonly viewTool: () => Promise<ReaderViewTool | undefined>
|
||||
readonly workspace: () => string
|
||||
readonly knowledgeSource: (collection: string, path: string) => Promise<ReaderSource | undefined>
|
||||
}
|
||||
|
||||
/** Reader availability projection. */
|
||||
export interface ReaderStatus {
|
||||
readonly available: boolean
|
||||
readonly view: {
|
||||
readonly version: string | null
|
||||
readonly path: string
|
||||
readonly binary_sha256: string
|
||||
readonly source_sha: string | null
|
||||
} | null
|
||||
readonly cli: { readonly version: string | null } | null
|
||||
readonly error: string | null
|
||||
}
|
||||
|
||||
/** Project source text result. */
|
||||
export interface ReaderSourceText {
|
||||
readonly kind: 'workspace' | 'knowledge'
|
||||
readonly collection: string | null
|
||||
readonly path: string
|
||||
readonly digest: string
|
||||
readonly text: string
|
||||
readonly truncated: boolean
|
||||
}
|
||||
|
||||
/** One served package file. */
|
||||
export interface ReaderPackageFileBody {
|
||||
readonly path: string
|
||||
readonly contentType: string
|
||||
readonly body: Buffer
|
||||
}
|
||||
|
||||
/** The reader bridge. */
|
||||
export class ReaderService {
|
||||
readonly #layout: MdhLayout
|
||||
readonly #cli: ReaderServiceOptions['cli']
|
||||
readonly #toolHome: ReaderServiceOptions['toolHome']
|
||||
readonly #viewTool: ReaderServiceOptions['viewTool']
|
||||
readonly #workspace: ReaderServiceOptions['workspace']
|
||||
readonly #knowledgeSource: ReaderServiceOptions['knowledgeSource']
|
||||
|
||||
constructor(options: ReaderServiceOptions) {
|
||||
this.#layout = options.layout
|
||||
this.#cli = options.cli
|
||||
this.#toolHome = options.toolHome
|
||||
this.#viewTool = options.viewTool
|
||||
this.#workspace = options.workspace
|
||||
this.#knowledgeSource = options.knowledgeSource
|
||||
}
|
||||
|
||||
/** Read the current View/CLI availability without running either. */
|
||||
async status(): Promise<ReaderStatus> {
|
||||
const view = await this.#viewTool().catch(() => undefined)
|
||||
if (view === undefined) {
|
||||
return { available: false, view: null, cli: null, error: 'installed View Tool is required for the reader' }
|
||||
}
|
||||
const cli = await this.#cli().catch(() => undefined)
|
||||
return {
|
||||
available: cli !== undefined,
|
||||
view: {
|
||||
version: view.version,
|
||||
path: view.binaryPath,
|
||||
binary_sha256: view.binarySha256,
|
||||
source_sha: view.sourceSha,
|
||||
},
|
||||
cli: cli === undefined ? null : { version: cli.version ?? null },
|
||||
error: cli === undefined ? 'active Marqdo Runtime is required for the reader' : null,
|
||||
}
|
||||
}
|
||||
|
||||
/** Resolve one workspace or knowledge source to its exact bytes and root. */
|
||||
async #source(request: ReaderRequest): Promise<ReaderSource> {
|
||||
if (request.kind === 'workspace') {
|
||||
const workspace = this.#workspace()
|
||||
let absolute: string
|
||||
try {
|
||||
absolute = await resolveDocument(workspace, request.path)
|
||||
} catch (error) {
|
||||
throw new ReaderError(READER_ERROR.sourceInvalid, error instanceof Error ? error.message : String(error))
|
||||
}
|
||||
const digest = await digestFile(absolute)
|
||||
return {
|
||||
kind: 'workspace',
|
||||
collection: null,
|
||||
root: workspace,
|
||||
relative: relativePath(workspace, absolute).split('\\').join('/'),
|
||||
absolute,
|
||||
digest,
|
||||
title: null,
|
||||
}
|
||||
}
|
||||
const collection = request.collection?.trim()
|
||||
if (collection === undefined || collection === '') {
|
||||
throw new ReaderError(READER_ERROR.sourceInvalid, 'knowledge reading requires a collection id')
|
||||
}
|
||||
const source = await this.#knowledgeSource(collection, request.path).catch(() => undefined)
|
||||
if (source === undefined) throw new ReaderError(READER_ERROR.knowledgeSourceMissing, `unknown knowledge source: ${collection}/${request.path}`)
|
||||
return source
|
||||
}
|
||||
|
||||
/** Build the cache identity for one request. */
|
||||
#cacheId(source: ReaderSource, view: ReaderViewTool, cliSha256: string, theme: ReaderTheme, anchor: string | null): string {
|
||||
return createHash('sha256').update(JSON.stringify({
|
||||
schema: 1,
|
||||
kind: source.kind,
|
||||
collection: source.collection,
|
||||
root: source.root,
|
||||
relative: source.relative,
|
||||
source: source.digest,
|
||||
view: view.binarySha256,
|
||||
cli: cliSha256,
|
||||
theme,
|
||||
anchor,
|
||||
})).digest('hex')
|
||||
}
|
||||
|
||||
/** Read valid cache metadata or return undefined. */
|
||||
async #cachedMeta(
|
||||
id: string,
|
||||
source: ReaderSource,
|
||||
view: ReaderViewTool,
|
||||
theme: ReaderTheme,
|
||||
anchor: string | null,
|
||||
): Promise<ReaderPackageMeta | undefined> {
|
||||
const raw = await readJson<unknown>(join(this.#layout.readerPackages, `${id}.json`)).catch(() => undefined)
|
||||
if (typeof raw !== 'object' || raw === null || Array.isArray(raw)) return undefined
|
||||
const record = raw as Record<string, unknown>
|
||||
if (record.schema !== 'marqdo.mqdh.reader-package' || record.schema_version !== 1) return undefined
|
||||
try {
|
||||
const meta = raw as ReaderPackageMeta
|
||||
if (meta.id !== id || meta.theme !== theme || meta.anchor !== anchor) return undefined
|
||||
if (meta.source.digest !== source.digest || meta.source.relative !== source.relative) return undefined
|
||||
if (meta.view.binary_sha256 !== view.binarySha256) return undefined
|
||||
if (!(await isDirectory(join(this.#layout.readerPackages, id)))) return undefined
|
||||
return meta
|
||||
} catch (error) {
|
||||
void error
|
||||
return undefined
|
||||
}
|
||||
}
|
||||
|
||||
/** Render a cache hit. */
|
||||
#packageFromMeta(meta: ReaderPackageMeta, cached: boolean): ReaderPackage {
|
||||
return {
|
||||
id: meta.id,
|
||||
source: meta.source,
|
||||
theme: meta.theme,
|
||||
anchor: meta.anchor,
|
||||
entry_href: meta.entry.href,
|
||||
heading_ids: meta.entry.heading_ids,
|
||||
view: meta.view,
|
||||
cli: meta.cli,
|
||||
manifest_sha256: meta.manifest_sha256,
|
||||
created_at: meta.created_at,
|
||||
cached,
|
||||
package_url: `/mqdh/api/reader/package/${meta.id}/${meta.entry.href}`,
|
||||
}
|
||||
}
|
||||
|
||||
/** Expand a View failure into a stable reader error. */
|
||||
#exportFailure(error: Error, anchor: string | null): ReaderError {
|
||||
const message = error.message.slice(0, 600)
|
||||
if (anchor !== null && /anchor|heading/i.test(message)) return new ReaderError(READER_ERROR.anchorMissing, message)
|
||||
if (/source.*sha|expect-source|digest/i.test(message)) return new ReaderError(READER_ERROR.sourceChanged, message)
|
||||
return new ReaderError(READER_ERROR.exportFailed, message)
|
||||
}
|
||||
|
||||
/**
|
||||
* Open one read-only package. A cache miss runs the installed View Tool with a
|
||||
* fixed argv; the document is statically checked, never executed.
|
||||
* @param request - source, theme and optional anchor.
|
||||
* @returns the validated package and its same-origin URL.
|
||||
*/
|
||||
async open(request: ReaderRequest): Promise<ReaderPackage> {
|
||||
const theme: ReaderTheme = request.theme ?? 'light'
|
||||
const anchor = request.anchor?.trim() || null
|
||||
const view = await this.#viewTool()
|
||||
if (view === undefined) throw new ReaderError(READER_ERROR.viewMissing, 'install the View Tool to read documents')
|
||||
const cli = await this.#cli()
|
||||
if (cli === undefined) throw new ReaderError(READER_ERROR.cliMissing, 'install a Marqdo Runtime to read documents')
|
||||
const toolHome = await this.#toolHome()
|
||||
if (toolHome === undefined) throw new ReaderError(READER_ERROR.cliMissing, 'active Runtime has no Tool home')
|
||||
const cliSha256 = (await digestFile(cli.bin)).slice('sha256:'.length)
|
||||
const source = await this.#source(request)
|
||||
const sourceSha256 = source.digest.slice('sha256:'.length)
|
||||
const id = this.#cacheId(source, view, cliSha256, theme, anchor)
|
||||
return await withLock(join(this.#layout.reader, 'open.lock'), async () => {
|
||||
if (request.force !== true) {
|
||||
const cached = await this.#cachedMeta(id, source, view, theme, anchor)
|
||||
if (cached !== undefined) return this.#packageFromMeta(cached, true)
|
||||
}
|
||||
const output = join(this.#layout.readerStaging, `open-${id.slice(0, 12)}-${randomBytes(4).toString('hex')}`)
|
||||
await mkdir(dirname(output), { recursive: true, mode: 0o700 })
|
||||
try {
|
||||
const args = [
|
||||
'view', 'export', source.relative, '--out', output, '--embed',
|
||||
'--theme', theme, '--expect-source-sha256', sourceSha256,
|
||||
...(anchor === null ? [] : ['--anchor', anchor]),
|
||||
]
|
||||
const run = await runProcess(cli.bin, args, {
|
||||
cwd: source.root,
|
||||
env: { MARQDO_TOOL_HOME: toolHome },
|
||||
limits: { timeoutMs: 120_000, maxOutputBytes: 2 * 1024 * 1024 },
|
||||
})
|
||||
if (run.exitCode !== 0) {
|
||||
throw this.#exportFailure(new Error(run.stderr.trim() || run.stdout.trim() || `view export exited ${run.exitCode}`), anchor)
|
||||
}
|
||||
const manifestBytes = await readFile(join(output, 'manifest.json')).catch(() => undefined)
|
||||
if (manifestBytes === undefined) throw new ReaderError(READER_ERROR.manifestInvalid, 'View export produced no manifest.json')
|
||||
let raw: unknown
|
||||
try {
|
||||
raw = JSON.parse(manifestBytes.toString('utf8'))
|
||||
} catch {
|
||||
throw new ReaderError(READER_ERROR.manifestInvalid, 'View manifest is not valid JSON')
|
||||
}
|
||||
const manifest = parseViewManifest(raw)
|
||||
validateViewManifest(manifest, {
|
||||
sourceSha256,
|
||||
viewBinarySha256: view.binarySha256,
|
||||
cliBinarySha256: cliSha256,
|
||||
theme,
|
||||
anchor,
|
||||
relativePath: source.relative,
|
||||
})
|
||||
const files = await verifyPackageFiles(output, manifest)
|
||||
const packageRoot = join(this.#layout.readerPackages, id)
|
||||
await rm(packageRoot, { recursive: true, force: true })
|
||||
await rename(output, packageRoot)
|
||||
const meta: ReaderPackageMeta = {
|
||||
schema: 'marqdo.mqdh.reader-package',
|
||||
schema_version: 1,
|
||||
id,
|
||||
created_at: new Date().toISOString(),
|
||||
source: {
|
||||
kind: source.kind,
|
||||
collection: source.collection,
|
||||
relative: source.relative,
|
||||
digest: source.digest,
|
||||
title: source.title,
|
||||
},
|
||||
theme,
|
||||
anchor,
|
||||
entry: {
|
||||
href: manifest.entry.href,
|
||||
file: manifest.entry.file,
|
||||
heading_ids: manifest.entry.heading_ids,
|
||||
relative_path: manifest.entry.relative_path,
|
||||
},
|
||||
view: {
|
||||
version: view.version,
|
||||
binary_sha256: view.binarySha256,
|
||||
source_sha: view.sourceSha,
|
||||
},
|
||||
cli: { version: cli.version ?? null, binary_sha256: cliSha256 },
|
||||
manifest_sha256: digestBytes(manifestBytes).slice('sha256:'.length),
|
||||
files: files.filter(file => manifest.files.some(item => item.path === file.path)),
|
||||
assets: files.filter(file => manifest.assets.some(item => item.path === file.path)),
|
||||
}
|
||||
await writeJsonAtomic(join(this.#layout.readerPackages, `${id}.json`), meta, 0o600)
|
||||
return this.#packageFromMeta(meta, false)
|
||||
} catch (error) {
|
||||
await rm(output, { recursive: true, force: true }).catch(() => undefined)
|
||||
if (error instanceof ReaderError) throw error
|
||||
throw new ReaderError(READER_ERROR.exportFailed, error instanceof Error ? error.message : String(error))
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* Read the selected source text without invoking View.
|
||||
* @param request - workspace or knowledge source.
|
||||
* @returns bounded UTF-8 source text and its digest.
|
||||
*/
|
||||
async source(request: ReaderRequest): Promise<ReaderSourceText> {
|
||||
const source = await this.#source(request)
|
||||
const bytes = await readFile(source.absolute)
|
||||
const max = 256 * 1024
|
||||
const slice = bytes.byteLength > max ? bytes.subarray(0, max) : bytes
|
||||
return {
|
||||
kind: source.kind,
|
||||
collection: source.collection,
|
||||
path: source.relative,
|
||||
digest: source.digest,
|
||||
text: slice.toString('utf8'),
|
||||
truncated: bytes.byteLength > max,
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve one file of a cached package for the same-origin route.
|
||||
* @param id - package cache id.
|
||||
* @param path - package-relative path.
|
||||
* @returns the file body and content type.
|
||||
*/
|
||||
async packageFile(id: string, path: string): Promise<ReaderPackageFileBody> {
|
||||
if (!/^[a-f0-9]{64}$/.test(id)) throw new ReaderError(READER_ERROR.packageInvalid, 'invalid reader package id')
|
||||
assertPackagePath(path, 'reader package path')
|
||||
const meta = await readJson<ReaderPackageMeta>(join(this.#layout.readerPackages, `${id}.json`))
|
||||
if (meta === undefined) throw new ReaderError(READER_ERROR.packageMissing, 'reader package is missing')
|
||||
const allowed = new Set([...meta.files.map(file => file.path), ...meta.assets.map(file => file.path), meta.entry.file])
|
||||
if (!allowed.has(path)) throw new ReaderError(READER_ERROR.packageInvalid, `file is not listed in the package manifest: ${path}`)
|
||||
const root = join(this.#layout.readerPackages, id)
|
||||
const target = join(root, path)
|
||||
if (!isWithin(root, target)) throw new ReaderError(READER_ERROR.packageInvalid, 'package path escapes its root')
|
||||
const info = await lstat(target).catch(() => undefined)
|
||||
if (info === undefined || !info.isFile() || info.isSymbolicLink()) throw new ReaderError(READER_ERROR.packageInvalid, 'package file is not a regular file')
|
||||
if (info.size > 16 * 1024 * 1024) throw new ReaderError(READER_ERROR.packageInvalid, 'package file is too large')
|
||||
const canonical = await realpath(target).catch(() => undefined)
|
||||
if (canonical === undefined || !isWithin(await realpath(root), canonical)) throw new ReaderError(READER_ERROR.packageInvalid, 'package file resolves outside its root')
|
||||
return { path, contentType: contentTypeOf(path), body: await readFile(canonical) }
|
||||
}
|
||||
|
||||
/** Whether one package file identity is already cached. */
|
||||
async cachedFile(id: string, path: string): Promise<ReaderPackageFile | undefined> {
|
||||
const meta = await readJson<ReaderPackageMeta>(join(this.#layout.readerPackages, `${id}.json`)).catch(() => undefined)
|
||||
return meta?.files.find(file => file.path === path) ?? meta?.assets.find(file => file.path === path)
|
||||
}
|
||||
|
||||
/** Remove one cached package or all packages. */
|
||||
async clear(id?: string): Promise<void> {
|
||||
if (id === undefined) {
|
||||
await rm(this.#layout.readerPackages, { recursive: true, force: true })
|
||||
await mkdir(this.#layout.readerPackages, { recursive: true, mode: 0o700 })
|
||||
return
|
||||
}
|
||||
if (!/^[a-f0-9]{64}$/.test(id)) throw new ReaderError(READER_ERROR.packageInvalid, 'invalid reader package id')
|
||||
await rm(join(this.#layout.readerPackages, id), { recursive: true, force: true })
|
||||
await rm(join(this.#layout.readerPackages, `${id}.json`), { force: true })
|
||||
}
|
||||
|
||||
/** Whether a package directory exists (used by tests and diagnostics). */
|
||||
async hasPackage(id: string): Promise<boolean> {
|
||||
return await isFile(join(this.#layout.readerPackages, `${id}.json`)) && await isDirectory(join(this.#layout.readerPackages, id))
|
||||
}
|
||||
|
||||
/** Read a package manifest for diagnostics. */
|
||||
async manifest(id: string): Promise<ViewManifest | undefined> {
|
||||
const path = join(this.#layout.readerPackages, id, 'manifest.json')
|
||||
const parsed = await readJson<unknown>(path).catch(() => undefined)
|
||||
if (parsed === undefined) return undefined
|
||||
return parseViewManifest(parsed)
|
||||
}
|
||||
}
|
||||
|
||||
/** Map package file extensions to response content types. */
|
||||
export function contentTypeOf(path: string): string {
|
||||
switch (extname(path).toLowerCase()) {
|
||||
case '.html': return 'text/html; charset=utf-8'
|
||||
case '.css': return 'text/css; charset=utf-8'
|
||||
case '.svg': return 'image/svg+xml'
|
||||
case '.png': return 'image/png'
|
||||
case '.jpg':
|
||||
case '.jpeg': return 'image/jpeg'
|
||||
case '.webp': return 'image/webp'
|
||||
case '.gif': return 'image/gif'
|
||||
case '.ttf': return 'font/ttf'
|
||||
case '.otf': return 'font/otf'
|
||||
case '.woff': return 'font/woff'
|
||||
case '.woff2': return 'font/woff2'
|
||||
case '.txt': return 'text/plain; charset=utf-8'
|
||||
case '.md': return 'text/markdown; charset=utf-8'
|
||||
default: return 'application/octet-stream'
|
||||
}
|
||||
}
|
||||
@@ -10,12 +10,15 @@
|
||||
|
||||
import { readFile, stat } from 'node:fs/promises'
|
||||
import { isAbsolute, join, resolve } from 'node:path'
|
||||
import { digestFile } from './core/fsx.ts'
|
||||
import { digestFile, isWithin, readJson, readText } from './core/fsx.ts'
|
||||
import { ensureMdhHome, resolveMdhHome } from './core/home.ts'
|
||||
import type { MdhLayout } from './core/home.ts'
|
||||
import { EcosystemManager } from './ecosystem/manager.ts'
|
||||
import type { EcosystemStatus } from './ecosystem/manager.ts'
|
||||
import { EvidenceStore } from './execution/evidence.ts'
|
||||
import { ReaderService } from './reader/service.ts'
|
||||
import type { ReaderSourceText, ReaderStatus } from './reader/service.ts'
|
||||
import type { ReaderPackage, ReaderViewTool } from './reader/contract.ts'
|
||||
import type { RunEvidence, RunRecord } from './execution/evidence.ts'
|
||||
import { MarqdoCli } from './execution/cli.ts'
|
||||
import type { CheckedDocument, ExecutedDocument, Grants, SandboxMode } from './execution/cli.ts'
|
||||
@@ -109,6 +112,7 @@ export class MdhRuntime {
|
||||
readonly bootstrap: BootstrapManager
|
||||
readonly updater: AppUpdater
|
||||
readonly knowledge: KnowledgeManager
|
||||
readonly reader: ReaderService
|
||||
readonly evidence: EvidenceStore
|
||||
readonly #cliCache = new Map<string, { cli: MarqdoCli }>()
|
||||
readonly #analysisCache = new Map<string, CheckedDocument>()
|
||||
@@ -152,6 +156,29 @@ export class MdhRuntime {
|
||||
return environment ? join(this.layout.environments, environment.id, environment.tool_home) : undefined
|
||||
},
|
||||
})
|
||||
this.reader = new ReaderService({
|
||||
layout,
|
||||
cli: () => this.cli(),
|
||||
toolHome: async () => {
|
||||
const environment = await this.ecosystem.current()
|
||||
return environment ? join(layout.environments, environment.id, environment.tool_home) : undefined
|
||||
},
|
||||
viewTool: () => this.#viewTool(),
|
||||
workspace: () => this.workspace,
|
||||
knowledgeSource: async (collection, path) => {
|
||||
const source = await this.knowledge.sourcePath(collection, path)
|
||||
if (source === undefined) return undefined
|
||||
return {
|
||||
kind: 'knowledge',
|
||||
collection,
|
||||
root: source.root,
|
||||
relative: source.relative,
|
||||
absolute: source.absolute,
|
||||
digest: source.digest,
|
||||
title: source.title,
|
||||
}
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -167,7 +194,7 @@ export class MdhRuntime {
|
||||
}
|
||||
|
||||
/** Configured workspace override applied at runtime (Web settings). */
|
||||
async setWorkspace(workspace: string): Promise<void> {
|
||||
setWorkspace(workspace: string): void {
|
||||
if (!isAbsolute(workspace)) throw new Error('workspace must be an absolute path')
|
||||
this.workspace = resolve(workspace)
|
||||
}
|
||||
@@ -204,6 +231,45 @@ export class MdhRuntime {
|
||||
return await readProjectDependencies(this.workspace)
|
||||
}
|
||||
|
||||
/** Installed View Tool identity used by the reader bridge. */
|
||||
async #viewTool(): Promise<ReaderViewTool | undefined> {
|
||||
const status = await this.ecosystem.status()
|
||||
const tool = status.tools.find(candidate => candidate.command === 'view')
|
||||
if (tool === undefined) return undefined
|
||||
const record = await readJson<Record<string, unknown>>(join(tool.path, 'record.json'))
|
||||
if (record === undefined || typeof record.entrypoint !== 'string' || record.entrypoint === '') return undefined
|
||||
const binaryPath = join(tool.path, record.entrypoint)
|
||||
if (!isWithin(tool.path, binaryPath)) return undefined
|
||||
const info = await stat(binaryPath).catch(() => undefined)
|
||||
if (info === undefined || !info.isFile()) return undefined
|
||||
const digest = await digestFile(binaryPath)
|
||||
const sourceSha = (await readText(join(tool.path, 'SOURCE_SHA')))?.trim() || null
|
||||
return {
|
||||
command: 'view',
|
||||
version: typeof record.version === 'string' ? record.version : tool.version,
|
||||
path: tool.path,
|
||||
entrypoint: record.entrypoint,
|
||||
binaryPath,
|
||||
binarySha256: digest.slice('sha256:'.length),
|
||||
sourceSha,
|
||||
}
|
||||
}
|
||||
|
||||
/** Reader availability and installed View/CLI identity. */
|
||||
async readerStatus(): Promise<ReaderStatus> {
|
||||
return await this.reader.status()
|
||||
}
|
||||
|
||||
/** Open one read-only View package for a workspace or knowledge source. */
|
||||
async openReader(request: Parameters<ReaderService['open']>[0]): Promise<ReaderPackage> {
|
||||
return await this.reader.open(request)
|
||||
}
|
||||
|
||||
/** Read source text for the reader's source toggle. */
|
||||
async readerSource(request: Parameters<ReaderService['source']>[0]): Promise<ReaderSourceText> {
|
||||
return await this.reader.source(request)
|
||||
}
|
||||
|
||||
/** Installed capabilities visible to one agent/session scope. */
|
||||
async visibleCapabilities(sessionId: string | null): Promise<VisibleCapability[]> {
|
||||
return await this.capabilities.visible(sessionId, this.workspace)
|
||||
|
||||
@@ -45,6 +45,7 @@ export const APP_HTML = `<!doctype html>
|
||||
<button role="tab" data-tab="knowledge" aria-selected="true">私人知识</button>
|
||||
<button role="tab" data-tab="ecosystem">生态中心</button>
|
||||
<button role="tab" data-tab="document">文稿检查</button>
|
||||
<button role="tab" data-tab="reader">文稿阅读</button>
|
||||
<button role="tab" data-tab="runs">运行记录</button>
|
||||
<button role="tab" data-tab="bootstrap">首次启动</button>
|
||||
<button role="tab" data-tab="update">更新与出口</button>
|
||||
@@ -162,6 +163,27 @@ export const APP_HTML = `<!doctype html>
|
||||
<div id="document-result" class="results"></div>
|
||||
</section>
|
||||
|
||||
<section id="tab-reader" class="panel" role="tabpanel" hidden>
|
||||
<h2>文稿阅读</h2>
|
||||
<p class="muted">正文由已安装 View Tool 的公开 <code>export --embed</code> 生成;标题、公式、表格、主题与媒体来自同一 View 制品。打开只做静态检查与本地导出,不执行文稿,也不联网。</p>
|
||||
<form id="reader-form" class="form inline">
|
||||
<label>工作区相对路径<input name="path" placeholder="index.mq.md" required autocomplete="off"></label>
|
||||
<label>主题<select name="theme"><option value="light">light</option><option value="dark">dark</option></select></label>
|
||||
<label>锚点(可选)<input name="anchor" placeholder="heading-id" autocomplete="off"></label>
|
||||
<button type="submit">只读打开</button>
|
||||
</form>
|
||||
<div id="reader-status" class="card" aria-live="polite">尚未打开文稿。</div>
|
||||
<div class="reader-toolbar">
|
||||
<button id="reader-source-toggle" class="ghost" type="button" disabled>查看源码</button>
|
||||
<button id="reader-runs" class="ghost" type="button">查看运行记录</button>
|
||||
<span id="reader-identity" class="muted"></span>
|
||||
</div>
|
||||
<div class="reader-frame">
|
||||
<iframe id="reader-frame" title="View 只读阅读" sandbox="allow-same-origin" referrerpolicy="no-referrer"></iframe>
|
||||
</div>
|
||||
<pre id="reader-source-text" class="code" hidden></pre>
|
||||
</section>
|
||||
|
||||
<section id="tab-runs" class="panel" role="tabpanel" hidden>
|
||||
<h2>运行记录</h2>
|
||||
<p class="muted">记录绑定源文稿摘要、Analysis、CLI/Bundle 身份与 Observation 终态;源变更后标记为过期。</p>
|
||||
@@ -287,6 +309,9 @@ button:disabled { opacity: 0.55; cursor: progress; }
|
||||
.code { background: #26241f; color: #f3efe5; border-radius: 0.6rem; padding: 0.9rem; overflow: auto; font-size: 0.8rem; max-height: 32rem; }
|
||||
.error { color: var(--danger); min-height: 1.5rem; }
|
||||
.foot { text-align: center; color: var(--muted); font-size: 0.8rem; padding: 1rem; border-top: 1px solid var(--line); }
|
||||
.reader-toolbar { display: flex; gap: 0.6rem; align-items: center; flex-wrap: wrap; margin: 0.7rem 0; }
|
||||
.reader-frame { border: 1px solid var(--line); border-radius: 0.6rem; overflow: hidden; background: #fff; }
|
||||
.reader-frame iframe { display: block; width: 100%; min-height: 70vh; border: 0; background: #fff; }
|
||||
.market { border: 1px solid var(--line); border-radius: 0.7rem; background: #fffdf8; padding: 0.9rem 1rem; margin: 1rem 0; }
|
||||
.market-toolbar { display: flex; gap: 0.7rem; align-items: end; flex-wrap: wrap; margin: 0.6rem 0; }
|
||||
.market-toolbar label { display: flex; flex-direction: column; gap: 0.2rem; font-size: 0.86rem; }
|
||||
@@ -453,6 +478,7 @@ function renderSearch(data) {
|
||||
el('h3', { text: hit.title || hit.rel_path }),
|
||||
el('div', { class: 'src', text: hit.collection_name + ' / ' + hit.rel_path + ' · ' + hit.digest + (hit.stale ? ' · 源已变更(STALE)' : '') }),
|
||||
el('pre', { text: hit.snippet || '' }),
|
||||
el('button', { class: 'ghost', type: 'button', text: '在 View 阅读', onclick: () => openKnowledgeReader(hit) }),
|
||||
));
|
||||
}
|
||||
}
|
||||
@@ -929,6 +955,79 @@ function renderMarketProject() {
|
||||
host.append(row);
|
||||
}
|
||||
|
||||
const readerState = { kind: 'workspace', path: '', collection: null, theme: 'light', anchor: '', package: null };
|
||||
|
||||
async function loadReaderStatus() {
|
||||
const status = $('#reader-status');
|
||||
if (!status) return;
|
||||
try {
|
||||
const data = await api('/reader/status');
|
||||
if (data.available) {
|
||||
const view = data.view;
|
||||
status.textContent = 'View ' + (view.version || 'unknown') + ' · ' + short(view.binary_sha256, 24) + ' · CLI ' + (data.cli?.version || 'unknown') + ' 可用。打开只读阅读不会执行文稿。';
|
||||
$('#reader-form').querySelector('button').disabled = false;
|
||||
} else {
|
||||
status.textContent = '阅读不可用:' + (data.error || 'View Tool 未安装') + '。可到“生态中心 → Tool”安装 View。';
|
||||
$('#reader-form').querySelector('button').disabled = true;
|
||||
}
|
||||
} catch (error) {
|
||||
status.textContent = '读取 View 状态失败:' + error.message;
|
||||
}
|
||||
}
|
||||
|
||||
async function openReader(request) {
|
||||
const status = $('#reader-status');
|
||||
const identity = $('#reader-identity');
|
||||
const frame = $('#reader-frame');
|
||||
clear($('#reader-source-text'));
|
||||
$('#reader-source-text').hidden = true;
|
||||
if (status) status.textContent = '正在静态检查并导出 View 阅读包…';
|
||||
if (identity) identity.textContent = '';
|
||||
if (frame) frame.removeAttribute('src');
|
||||
try {
|
||||
const data = await api('/reader/open', { method: 'POST', body: JSON.stringify({
|
||||
confirm: true,
|
||||
kind: request.kind || 'workspace',
|
||||
path: request.path,
|
||||
collection: request.collection || undefined,
|
||||
theme: request.theme || 'light',
|
||||
anchor: request.anchor || undefined,
|
||||
}) });
|
||||
readerState.kind = data.source.kind;
|
||||
readerState.path = data.source.relative;
|
||||
readerState.collection = data.source.collection;
|
||||
readerState.theme = data.theme;
|
||||
readerState.anchor = data.anchor || '';
|
||||
readerState.package = data;
|
||||
if (frame) frame.setAttribute('src', data.package_url);
|
||||
if (status) status.textContent = (data.cached ? '已复用缓存阅读包。' : '已生成并校验阅读包。') + ' 正文来自 View ' + (data.view.version || 'unknown') + ',未执行文稿。';
|
||||
if (identity) identity.textContent = 'source ' + data.source.digest + ' · manifest ' + data.manifest_sha256 + (data.anchor ? ' · anchor ' + data.anchor : '');
|
||||
$('#reader-source-toggle').disabled = false;
|
||||
} catch (error) {
|
||||
if (status) status.textContent = '打开阅读失败:' + error.message + (error.code === 'reader.view_missing' ? '。请先在生态中心安装 View Tool。' : '');
|
||||
if (frame) frame.removeAttribute('src');
|
||||
}
|
||||
}
|
||||
|
||||
async function openKnowledgeReader(hit) {
|
||||
const button = document.querySelector('[data-tab="reader"]');
|
||||
if (button) button.click();
|
||||
await openReader({ kind: 'knowledge', path: hit.rel_path, collection: hit.collection, theme: 'light', anchor: hit.anchor || '' });
|
||||
}
|
||||
|
||||
async function loadReaderSource() {
|
||||
const pkg = readerState.package;
|
||||
if (!pkg) return;
|
||||
try {
|
||||
const query = new URLSearchParams({ kind: readerState.kind, path: readerState.path });
|
||||
if (readerState.collection) query.set('collection', readerState.collection);
|
||||
const data = await api('/reader/source?' + query.toString());
|
||||
const node = $('#reader-source-text');
|
||||
node.textContent = data.text + (data.truncated ? '\\n…(已截断)' : '');
|
||||
node.hidden = false;
|
||||
} catch (error) { showError('读取源码失败:' + error.message); }
|
||||
}
|
||||
|
||||
async function loadRuns() {
|
||||
try {
|
||||
const data = await api('/runs');
|
||||
@@ -1119,6 +1218,7 @@ function bind() {
|
||||
});
|
||||
const tab = button.dataset.tab;
|
||||
if (tab === 'ecosystem') { loadEcosystem(); loadMarket(); }
|
||||
if (tab === 'reader') loadReaderStatus();
|
||||
if (tab === 'bootstrap') loadBootstrap();
|
||||
if (tab === 'update') { loadUpdate(); loadNetwork(); }
|
||||
if (tab === 'reports') loadReports();
|
||||
@@ -1186,6 +1286,13 @@ function bind() {
|
||||
await loadMarket();
|
||||
} catch (error) { showError('添加来源失败:' + error.message); }
|
||||
});
|
||||
$('#reader-form').addEventListener('submit', async (event) => {
|
||||
event.preventDefault();
|
||||
const form = new FormData(event.target);
|
||||
await openReader({ kind: 'workspace', path: String(form.get('path') || ''), theme: String(form.get('theme') || 'light'), anchor: String(form.get('anchor') || '') });
|
||||
});
|
||||
$('#reader-source-toggle').addEventListener('click', async () => { await loadReaderSource(); });
|
||||
$('#reader-runs').addEventListener('click', () => { document.querySelector('[data-tab="runs"]').click(); });
|
||||
$('#create-collection').addEventListener('submit', async (event) => {
|
||||
event.preventDefault();
|
||||
const form = new FormData(event.target);
|
||||
@@ -1305,5 +1412,6 @@ loadStatus();
|
||||
loadCollections();
|
||||
loadEcosystem();
|
||||
loadMarket();
|
||||
loadReaderStatus();
|
||||
loadRuns();
|
||||
`
|
||||
@@ -19,6 +19,7 @@ import type { DiagnosticArea } from '../diagnostics/contract.ts'
|
||||
import { discoverRelease } from '../ecosystem/sources.ts'
|
||||
import { parseSourceConfig } from '../market/config.ts'
|
||||
import { MarketError } from '../market/errors.ts'
|
||||
import { ReaderError } from '../reader/errors.ts'
|
||||
import { runProcess } from '../core/process.ts'
|
||||
import { APP_CSS, APP_HTML, APP_JS } from './assets.ts'
|
||||
import { isLoopbackAuthority, isTrustedAuthority } from './trust.ts'
|
||||
@@ -53,7 +54,7 @@ class HttpError extends Error {
|
||||
|
||||
/** Read a bounded request body. */
|
||||
async function readBody(req: IncomingMessage, maxBytes: number): Promise<Buffer> {
|
||||
const chunks: Buffer[] = []
|
||||
const chunks: Uint8Array[] = []
|
||||
let total = 0
|
||||
for await (const chunk of req) {
|
||||
const bytes = Buffer.from(chunk)
|
||||
@@ -61,7 +62,7 @@ async function readBody(req: IncomingMessage, maxBytes: number): Promise<Buffer>
|
||||
if (total > maxBytes) throw new HttpError(413, 'request body exceeds its limit')
|
||||
chunks.push(bytes)
|
||||
}
|
||||
return Buffer.concat(chunks)
|
||||
return Buffer.concat(chunks.map(chunk => Buffer.from(chunk)))
|
||||
}
|
||||
|
||||
/** Parse a JSON body. */
|
||||
@@ -90,7 +91,7 @@ function registerRoutes(
|
||||
runtime: MdhRuntime,
|
||||
config: { trustedHosts: readonly string[]; bindHost?: string | undefined },
|
||||
): void {
|
||||
const webServer = ctx.get('webServer' as never) as {
|
||||
const webServer = ctx.get('webServer') as {
|
||||
register(route: {
|
||||
kind: 'prefix'
|
||||
path: string
|
||||
@@ -128,7 +129,7 @@ function registerRoutes(
|
||||
res.writeHead(200, {
|
||||
'content-type': 'text/html; charset=utf-8',
|
||||
'content-length': Buffer.byteLength(html),
|
||||
'content-security-policy': "default-src 'none'; script-src 'self'; style-src 'self'; img-src 'self' data:; connect-src 'self'; form-action 'self'; base-uri 'none'; frame-ancestors 'none'",
|
||||
'content-security-policy': "default-src 'none'; script-src 'self'; style-src 'self'; img-src 'self' data:; connect-src 'self'; frame-src 'self'; form-action 'self'; base-uri 'none'; frame-ancestors 'none'",
|
||||
'x-content-type-options': 'nosniff',
|
||||
'referrer-policy': 'no-referrer',
|
||||
'cache-control': 'no-store',
|
||||
@@ -153,6 +154,7 @@ function registerRoutes(
|
||||
} catch (error) {
|
||||
if (error instanceof HttpError) { json(res, error.status, { error: error.message }); return }
|
||||
if (error instanceof MarketError) { json(res, 409, { error: error.message, code: error.code }); return }
|
||||
if (error instanceof ReaderError) { json(res, 409, { error: error.message, code: error.code }); return }
|
||||
const message = error instanceof Error ? error.message : String(error)
|
||||
const path = req.url ?? ''
|
||||
const area: DiagnosticArea = path.startsWith('/mqdh/api/knowledge') ? 'knowledge'
|
||||
@@ -302,6 +304,71 @@ async function handleApi(
|
||||
})
|
||||
return
|
||||
}
|
||||
if (path === '/reader/status' && method === 'GET') {
|
||||
json(res, 200, await runtime.readerStatus())
|
||||
return
|
||||
}
|
||||
if (path === '/reader/open' && method === 'POST') {
|
||||
const body = await readJson(req)
|
||||
if (body.confirm !== true) throw new HttpError(400, 'opening the reader requires explicit confirmation')
|
||||
const kind = body.kind
|
||||
if (kind !== 'workspace' && kind !== 'knowledge') throw new HttpError(400, 'kind must be workspace or knowledge')
|
||||
const sourcePath = stringField(body, 'path')
|
||||
let theme: 'light' | 'dark' | undefined
|
||||
if (body.theme !== undefined) {
|
||||
if (body.theme !== 'light' && body.theme !== 'dark') throw new HttpError(400, 'theme must be light or dark')
|
||||
theme = body.theme
|
||||
}
|
||||
const collection = typeof body.collection === 'string' && body.collection.trim() !== '' ? body.collection.trim() : undefined
|
||||
const anchor = typeof body.anchor === 'string' && body.anchor.trim() !== '' ? body.anchor.trim() : undefined
|
||||
json(res, 200, await runtime.openReader({
|
||||
kind,
|
||||
path: sourcePath,
|
||||
...(collection === undefined ? {} : { collection }),
|
||||
...(theme === undefined ? {} : { theme }),
|
||||
...(anchor === undefined ? {} : { anchor }),
|
||||
...(body.force === true ? { force: true } : {}),
|
||||
}))
|
||||
return
|
||||
}
|
||||
if (path === '/reader/source' && method === 'GET') {
|
||||
const kind = url.searchParams.get('kind') ?? 'workspace'
|
||||
if (kind !== 'workspace' && kind !== 'knowledge') throw new HttpError(400, 'kind must be workspace or knowledge')
|
||||
const sourcePath = url.searchParams.get('path') ?? ''
|
||||
if (sourcePath === '') throw new HttpError(400, 'missing path')
|
||||
const collection = url.searchParams.get('collection') ?? undefined
|
||||
json(res, 200, await runtime.readerSource({
|
||||
kind,
|
||||
path: sourcePath,
|
||||
...(collection === undefined || collection === '' ? {} : { collection }),
|
||||
}))
|
||||
return
|
||||
}
|
||||
const readerPackageMatch = /^\/reader\/package\/([a-f0-9]{64})\/(.+)$/.exec(path)
|
||||
if (readerPackageMatch && method === 'GET') {
|
||||
const id = readerPackageMatch[1]
|
||||
const encodedPath = readerPackageMatch[2]
|
||||
if (id === undefined || encodedPath === undefined) throw new HttpError(400, 'invalid reader package path')
|
||||
let filePath: string
|
||||
try {
|
||||
filePath = decodeURIComponent(encodedPath)
|
||||
} catch {
|
||||
throw new HttpError(400, 'invalid reader package path')
|
||||
}
|
||||
const file = await runtime.reader.packageFile(id, filePath)
|
||||
res.writeHead(200, {
|
||||
'content-type': file.contentType,
|
||||
'content-length': file.body.byteLength,
|
||||
'cache-control': 'no-store',
|
||||
'x-content-type-options': 'nosniff',
|
||||
'referrer-policy': 'no-referrer',
|
||||
...(file.contentType.startsWith('text/html')
|
||||
? { 'content-security-policy': "default-src 'none'; style-src 'self'; font-src 'self'; img-src 'self' data:; media-src 'self'; base-uri 'none'; form-action 'none'; frame-ancestors 'self'" }
|
||||
: {}),
|
||||
})
|
||||
res.end(file.body)
|
||||
return
|
||||
}
|
||||
if (path === '/market' && method === 'GET') {
|
||||
const config = await runtime.market.config()
|
||||
json(res, 200, {
|
||||
@@ -668,7 +735,7 @@ async function handleApi(
|
||||
proxy_https: config.proxy.https !== null,
|
||||
proxy_http: config.proxy.http !== null,
|
||||
no_proxy_entries: config.proxy.noProxy.length,
|
||||
mirrors: Object.entries(config.mirrors).map(([purpose, base]) => `${purpose}=${String(base)}`),
|
||||
mirrors: Object.entries(config.mirrors).map(([purpose, base]) => `${purpose}=${base}`),
|
||||
allowed_hosts: config.allowedHosts,
|
||||
allow_loopback: config.allowLoopback,
|
||||
allow_private: config.allowPrivate,
|
||||
@@ -756,7 +823,7 @@ async function handleApi(
|
||||
|
||||
/** Register the workbench and its API over the DSH web server. */
|
||||
export function apply(ctx: Context, config: { trustedHosts?: readonly string[] | undefined; bindHost?: string | undefined } = {}): void {
|
||||
const runtime = ctx.get('mqdhRuntime' as never) as MdhRuntime | undefined
|
||||
const runtime = ctx.get('mqdhRuntime') as MdhRuntime | undefined
|
||||
if (!runtime) throw new Error('mqdh-web requires mqdhRuntime')
|
||||
registerRoutes(ctx, runtime, { trustedHosts: config.trustedHosts ?? [], bindHost: config.bindHost })
|
||||
}
|
||||
@@ -0,0 +1,114 @@
|
||||
/** View embedded manifest validation and package file safety. */
|
||||
|
||||
import assert from 'node:assert/strict'
|
||||
import { mkdtemp, writeFile } from 'node:fs/promises'
|
||||
import { tmpdir } from 'node:os'
|
||||
import { join } from 'node:path'
|
||||
import { test } from 'node:test'
|
||||
|
||||
import {
|
||||
assertPackagePath, parseViewManifest, validateViewManifest, verifyPackageFiles,
|
||||
} from '../src/reader/contract.ts'
|
||||
import { contentTypeOf } from '../src/reader/service.ts'
|
||||
import { READER_ERROR, ReaderError } from '../src/reader/errors.ts'
|
||||
|
||||
const hex = (char: string): string => char.repeat(64)
|
||||
|
||||
/** Build one valid View embedded manifest. */
|
||||
function manifest(overrides: Record<string, unknown> = {}): Record<string, unknown> {
|
||||
const base = {
|
||||
schema: 'marqdo.view-export',
|
||||
schema_version: 1,
|
||||
mode: 'embedded',
|
||||
theme: 'dark',
|
||||
executed: false,
|
||||
requires: { api_revision: 1, analysis: 3, observation: 1, markdown_profile: 'marqdo.md.v1' },
|
||||
producers: {
|
||||
view: { name: 'marqdo-view', version: '0.3.0', binary_sha256: hex('a') },
|
||||
cli: { version: '3.0.0-rc.6', binary_sha256: hex('b') },
|
||||
},
|
||||
entry: {
|
||||
href: 'index.html#detail',
|
||||
file: 'index.html',
|
||||
heading_ids: ['detail', 'intro'],
|
||||
relative_path: 'doc.md',
|
||||
anchor: 'detail',
|
||||
sha256: hex('c'),
|
||||
},
|
||||
pages: [{
|
||||
source_sha256: hex('d'),
|
||||
source_status: 'static-ok',
|
||||
relative_path: 'doc.md',
|
||||
sha256: hex('c'),
|
||||
}],
|
||||
files: [{ path: 'index.html', sha256: hex('c') }],
|
||||
assets: [],
|
||||
}
|
||||
return { ...base, ...overrides }
|
||||
}
|
||||
|
||||
/** Expected identities for the valid manifest. */
|
||||
const expected = {
|
||||
sourceSha256: hex('d'),
|
||||
viewBinarySha256: hex('a'),
|
||||
cliBinarySha256: hex('b'),
|
||||
theme: 'dark' as const,
|
||||
anchor: 'detail',
|
||||
relativePath: 'doc.md',
|
||||
}
|
||||
|
||||
/** Assert one reader failure code. */
|
||||
function rejectCode(run: () => unknown, code: string): void {
|
||||
assert.throws(() => { run() }, (error: unknown) => error instanceof ReaderError && error.code === code)
|
||||
}
|
||||
|
||||
void test('a View embedded manifest validates against exact source and producer identities', () => {
|
||||
const parsed = parseViewManifest(manifest())
|
||||
validateViewManifest(parsed, expected)
|
||||
assert.equal(parsed.mode, 'embedded')
|
||||
assert.equal(parsed.executed, false)
|
||||
assert.equal(parsed.entry.heading_ids[0], 'detail')
|
||||
})
|
||||
|
||||
void test('View manifest identity mismatches fail closed', () => {
|
||||
const base = parseViewManifest(manifest())
|
||||
rejectCode(() => { validateViewManifest(base, { ...expected, sourceSha256: hex('f') }) }, READER_ERROR.sourceChanged)
|
||||
rejectCode(() => { validateViewManifest(base, { ...expected, viewBinarySha256: hex('f') }) }, READER_ERROR.manifestInvalid)
|
||||
rejectCode(() => { validateViewManifest(base, { ...expected, theme: 'light' }) }, READER_ERROR.manifestInvalid)
|
||||
rejectCode(() => { validateViewManifest(base, { ...expected, anchor: 'missing' }) }, READER_ERROR.manifestInvalid)
|
||||
rejectCode(() => { validateViewManifest(parseViewManifest(manifest({ executed: true })), expected) }, READER_ERROR.manifestInvalid)
|
||||
rejectCode(() => { validateViewManifest(parseViewManifest(manifest({ mode: 'site' })), expected) }, READER_ERROR.manifestInvalid)
|
||||
})
|
||||
|
||||
void test('missing anchors and script assets in package manifests are rejected', () => {
|
||||
const noAnchor = parseViewManifest(manifest({
|
||||
entry: { href: 'index.html#detail', file: 'index.html', heading_ids: ['intro'], relative_path: 'doc.md', anchor: 'detail', sha256: hex('c') },
|
||||
}))
|
||||
rejectCode(() => { validateViewManifest(noAnchor, expected) }, READER_ERROR.anchorMissing)
|
||||
assert.throws(() => { parseViewManifest(manifest({ files: [{ path: 'assets/app.js', sha256: hex('c') }] })) }, ReaderError)
|
||||
assert.throws(() => { assertPackagePath('../escape', 'package file') }, ReaderError)
|
||||
assert.throws(() => { assertPackagePath('assets/app.js', 'package file') }, ReaderError)
|
||||
})
|
||||
|
||||
void test('package file digests are verified against the manifest', async () => {
|
||||
const root = await mkdtemp(join(tmpdir(), 'mqdh-reader-'))
|
||||
await writeFile(join(root, 'index.html'), '<p>reader</p>')
|
||||
const parsed = parseViewManifest(manifest({
|
||||
entry: {
|
||||
href: 'index.html', file: 'index.html', heading_ids: [], relative_path: 'doc.md', anchor: null, sha256: hex('0'),
|
||||
},
|
||||
pages: [{ source_sha256: hex('d'), source_status: 'static-ok', relative_path: 'doc.md', sha256: hex('0') }],
|
||||
files: [{ path: 'index.html', sha256: hex('0') }],
|
||||
}))
|
||||
await assert.rejects(verifyPackageFiles(root, parsed), (error: unknown) => (
|
||||
error instanceof ReaderError && error.code === READER_ERROR.packageInvalid
|
||||
))
|
||||
})
|
||||
|
||||
void test('reader content types stay static-only', () => {
|
||||
assert.equal(contentTypeOf('index.html'), 'text/html; charset=utf-8')
|
||||
assert.equal(contentTypeOf('assets/reader.css'), 'text/css; charset=utf-8')
|
||||
assert.equal(contentTypeOf('assets/noto-math.woff2'), 'font/woff2')
|
||||
assert.equal(contentTypeOf('media/x.png'), 'image/png')
|
||||
assert.equal(contentTypeOf('media/x.js'), 'application/octet-stream')
|
||||
})
|
||||
Reference in new issue
Block a user