From 1f34daffb0ac6bce0ed3ee5f1c16e5b7a3667870 Mon Sep 17 00:00:00 2001 From: marqdo-view dev Date: Sun, 22 Nov 2026 11:52:22 +0800 Subject: [PATCH] feat(PR-05): pure static export and hardened Live boundary - export.rs: marqdo view export PATH --out DIR through the same ReaderRenderer; index.html + pages/.html + hash-named assets + manifest.json - export never calls Core run; refuses output inside project root and unrelated non-empty dirs; staging + atomic rename replaces only prior View exports - offline by construction: embedded asset bytes, data-URI images, relative links, no remote subresources; --no-annotations hides anchors only - HTTP hardening: max 32 concurrent requests (503), detail-free public error JSON/pages (no absolute paths/subprocess text), 30s page check budget - tools/test-export.sh (manifest hashes + file:// Chromium offline check), tools/test-security.sh, adversarial security-project browser fixture - tests/export.rs export contracts; ADR-0005; docs updated --- CHANGELOG.md | 22 +- COMPATIBILITY.md | 4 +- README.md | 9 + docs/ADR/0005-static-export.md | 24 ++ docs/STATUS.md | 7 +- src/app.rs | 38 ++- src/error.rs | 36 +++ src/export.rs | 340 ++++++++++++++++++++ src/lib.rs | 1 + src/render.rs | 32 +- src/server.rs | 27 +- tests/browser/reader.browser.cjs | 18 ++ tests/common/mod.rs | 1 + tests/export.rs | 310 ++++++++++++++++++ tests/fixtures/security-project/index.mq.md | 17 + tests/fixtures/security-project/marqdo.yaml | 3 + tests/http_live.rs | 8 +- tools/test-browser.sh | 1 + tools/test-export.sh | 82 +++++ tools/test-security.sh | 22 ++ 20 files changed, 983 insertions(+), 19 deletions(-) create mode 100644 docs/ADR/0005-static-export.md create mode 100644 src/export.rs create mode 100644 tests/export.rs create mode 100644 tests/fixtures/security-project/index.mq.md create mode 100644 tests/fixtures/security-project/marqdo.yaml create mode 100755 tools/test-export.sh create mode 100755 tools/test-security.sh diff --git a/CHANGELOG.md b/CHANGELOG.md index 06d18ac..bbf1f74 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -75,9 +75,29 @@ Protocol axes (Tool v1, Analysis v2, Trace v2) are versioned separately. - Meta CSP no longer carries the ignored `frame-ancestors` directive (the HTTP header still enforces framing). +### Added (PR-05) + +- Static export (`marqdo view export PATH --out DIR`) through the same + `ReaderRenderer`: `index.html` + `pages/.html` + hash-named assets + + `manifest.json` (relative paths, per-file SHA-256, protocols, `executed:false`). +- Pure read-only guarantee: export never calls Core `run`, never writes into the + project root, never overwrites unrelated non-empty directories; staging + + atomic rename, previous successful export replaced safely. +- Offline by construction: same embedded asset bytes, data-URI images, no remote + fonts/CDN; relative internal links; `--no-annotations` hides semantic anchors + without changing prose. +- HTTP hardening: bounded concurrent requests (503 beyond 32), detail-free + public error JSON/pages (no absolute paths or subprocess text), 30s page check + budget. +- `tools/test-export.sh`, `tools/test-security.sh`, adversarial browser fixture + (`tests/fixtures/security-project`) proving no script execution and no + external requests; `tests/export.rs` export contracts; ADR-0005. + ### Known limitations -- `export` still returns `view.unsupported` (PR-05). +- No incremental export or multi-project site; one project per invocation. +- Export still requires a core for semantic status; without it pages are + exported as explicitly unverified prose. - `project`/`strict` grant UI, streaming output, cancellation and debugger are not implemented; variables/memory/proof states remain `UNSUPPORTED`. - Pixel-level comparison with the reference screenshot remains a manual diff --git a/COMPATIBILITY.md b/COMPATIBILITY.md index 7fff8fc..3df6344 100644 --- a/COMPATIBILITY.md +++ b/COMPATIBILITY.md @@ -30,8 +30,8 @@ Beta 版 CLI 必须使用 prerelease 范围(`>=3.0.0-beta.1,<4.0.0`);`>=3. | 文档态 / 源码态切换 | **已实现**(PR-02) | | 暖纸 Reader 视觉(单一 CSS/JS) | 计划 PR-03 | | 用户显式触发运行 + Trace v2 事件可视化 | **已实现**(PR-04,仅 `pure` 模式,需页面内确认 + CSRF) | -| Live 本机安全 API | 部分实现(PR-02 只读 + PR-04 run;PR-05 强化/导出) | -| 静态离线导出(纯只读) | 计划 PR-05 | +| Live 本机安全 API | **已实现**(PR-02 只读 + PR-04 run + PR-05 并发/公开错误/导出) | +| 静态离线导出(纯只读) | **已实现**(PR-05,同一渲染器) | | 逐语句变量值 / 参数实际值 / 内存快照 | **UNSUPPORTED**(Trace v2 不提供,绝不伪造) | | 知识“已证明”状态 | **UNSUPPORTED**(需要独立 Prove 协议与证书) | | 调试器/断点/单步 | **不实现**(首版非目标) | diff --git a/README.md b/README.md index db06361..cb9c118 100644 --- a/README.md +++ b/README.md @@ -43,6 +43,13 @@ cargo test --locked cargo build --release --locked ``` +静态导出(纯只读、离线可打开,永不执行文档): + +```bash +marqdo view export examples/welcome --out ./site +# 或:marqdo-view export examples/welcome --out ./site --marqdo-bin /path/to/marqdo +``` + 本机浏览(默认只绑定 127.0.0.1,不自动执行): ```bash @@ -64,6 +71,8 @@ MARQDO_BIN=/absolute/path/to/marqdo ```bash (cd tests/browser && npm install && PLAYWRIGHT_BROWSERS_PATH="$PWD/../.cache/pw-browsers" npx playwright install chromium) MARQDO_BIN=/absolute/path/to/marqdo ./tools/test-browser.sh +MARQDO_BIN=/absolute/path/to/marqdo ./tools/test-export.sh +./tools/test-security.sh ``` 完整安装/验收步骤见 RFC §18,脚本位于 `tools/`。 diff --git a/docs/ADR/0005-static-export.md b/docs/ADR/0005-static-export.md new file mode 100644 index 0000000..bb591bf --- /dev/null +++ b/docs/ADR/0005-static-export.md @@ -0,0 +1,24 @@ +# ADR-0005:静态导出是纯只读、同渲染器、原子发布 + +- 状态:Accepted +- 日期:2026-11-22 +- 关联:RFC-VIEW-0001 §11.3、§14.3、§14.5;PR-05 + +## 背景 + +旧 `marqdo view output` 默认在导出过程中执行文档以抓取输出快照(`static_page_data`),只有显式 `--no-exec`/`--snapshot` 才避免。这使“导出”不再是纯只读操作。新 View 的导出必须无条件纯只读,同时与 Live 共用唯一渲染器。 + +## 决策 + +1. **导出路径不存在 `run` 调用**:`export.rs` 只调用 `AppContext::load`(内部仅 `check`),从不构造 `RunOptions`、从不起子进程 `run`。导出 HTML 中不存在运行面板或可点击的运行按钮;`data-live="false"`、`data-run-available="false"`。 +2. **同一渲染器**:每个页面由 `ReaderRenderer::render(model, RenderContext::static_export(depth, annotations))` 产生;Live/Export 唯一差异是 `LinkPolicy`、`annotations` 与控件可用性。Exporter 不拼 HTML。 +3. **离线资产**:写出的 CSS/JS/图片来自 `AssetBundle` 的同一份字节;CSS 内图片为 data URI,导出站点无外链字体/CDN/远程资源。`index.html` 在站点根,`pages/.html` 按文档相对路径生成,全部链接相对化。 +4. **原子发布**:先写入同父目录的 staging 目录,成功后 `rename` 到目标;失败清理 staging,不污染上一个成功导出。目标已存在时只允许是“空目录”或带 `schema:marqdo.view-export` 清单的旧导出,否则拒绝覆盖。 +5. **边界与隐私**:拒绝输出目录位于项目根内(避免递归复制/覆盖源文件);`manifest.json` 不包含绝对机器路径,只含相对路径、SHA-256、协议/版本与 `executed:false`。 +6. **标注可关闭**:`--no-annotations` 仅让渲染器不生成语句锚点并设置 `data-annotations="off"`;正文、目录、链接、表格、源码态保持完整。 + +## 后果 + +- 对抗测试 `tests/export.rs` 使用会写 marker 的假核心:导出后 marker 不存在、假核心 argv 中没有 `run`。 +- 真实冻结核心导出两个文档页面均为 `static-ok`;`tools/test-export.sh` 校验离线资源、manifest 哈希与核心 SHA 不变。 +- 副作用:导出对每个文档执行一次 `check`(非执行),大项目导出耗时与文档数线性相关;首版不做增量导出,保持正确性优先。 diff --git a/docs/STATUS.md b/docs/STATUS.md index 4dac854..8487a72 100644 --- a/docs/STATUS.md +++ b/docs/STATUS.md @@ -25,18 +25,19 @@ | PR-02 DocumentModel + Analysis v2 浏览 | **完成** | `src/document.rs`、`src/semantic.rs`、`src/presentation.rs`、`src/render.rs`、`src/server.rs`、`tests/rendering.rs`、`tests/http_live.rs`、`tests/golden/analysis-v2/`(冻结 CLI 生成) | | PR-03 Reader 视觉重建 | **完成(像素级人工比对未执行)** | 单一 `assets/reader.css`/`assets/reader.js`;`tools/test-browser.sh` + `tests/browser/reader.browser.cjs` 在 7 个宽度、无 JS、打印、搜索、设置、显式运行下 PASS;截图证据见 `docs/evidence/PR-03/` | | PR-04 Trace v2 运行可视化 | **完成** | `src/trace.rs`、`POST /api/run`(CSRF/Origin/确认/并发)、`tests/trace_contract.rs`、`tests/http_live.rs`、`tests/golden/trace-v2/`(冻结 CLI 生成)、ADR-0004 | -| PR-05 Live 安全强化 + 静态导出 | 未开始 | — | -| PR-06 冻结 CLI 端到端验收 | 未开始 | — | +| PR-05 Live 安全强化 + 静态导出 | **完成** | `src/export.rs`、`tools/test-export.sh`、`tools/test-security.sh`、`tests/export.rs`、`tests/browser` 安全 fixture;ADR-0005 | +| PR-06 冻结 CLI 端到端验收 | 进行中 | 打包/安装冒烟与真实核心浏览/运行/导出已手动通过;待补证据 manifest、CI 脚本、最终 README/RFC §18 门禁表 | ## 证据与限制 - 旧 View 运行时状态:`LEGACY_RUNTIME_UNVERIFIED`(旧仓库无预编译产物,且任务禁止修改/编译旧仓库;只做只读静态审计)。 - PR-01 起 `marqdo view --help/--version/verify` 由本程序提供;PR-02 起 `marqdo view [PATH]` 提供本机只读浏览。 -- `export` 仍返回 `view.unsupported`(PR-05 落地);运行入口在 PR-04 起可用,但必须经过页面内显式确认 + CSRF 校验,且只允许 `pure` 模式。 +- `export` 自 PR-05 起可用,且无条件纯只读;运行入口在 PR-04 起可用,但必须经过页面内显式确认 + CSRF 校验,且只允许 `pure` 模式。 - 冻结 CLI 安装烟测通过前不得声称 Tool v1 闭环可用;证据由 `tools/install-smoke.sh` 生成。 - PR-02 的 Analysis golden 全部由冻结 CLI `check --emit` 生成(见 `tests/golden/README.md`);`examples/diagnostics` 故意 check 失败且没有 golden。 - 已知限制:逐语句变量值/参数值/内存快照/证明状态仍不可用且标为 UNSUPPORTED;`project`/`strict` 运行授权界面、SSE 流式输出、调试器未实现;`export` 未实现。 - 视觉门禁:结构化/几何/无外部资源/无 JS/打印 PASS;与参考截图的像素级人工比对 `U-01` 仍为 UNVERIFIED,需人工复核(见 `docs/evidence/PR-03/README.md`)。 - 运行安全:首版只提供 `--mode pure`;POST `/api/run` 要求同源 Origin(若提供)、CSRF token、`confirm:true`、单活动运行;运行缓存仅保存在进程内,重启即清空。 +- 导出:拒绝项目根内输出与未知非空目录;staging + rename 原子发布;manifest 无绝对路径;`--no-annotations` 只影响标注。浏览器安全 fixture 在真实 Chromium 中验证无脚本执行、无外部请求。 - 已核对旧视觉资产许可(旧仓库 Apache-2.0):logo/blossom/feather 可复用,KaTeX 不引入。 - 已知非目标:变量运行值、内存快照、调试器、Prove/Knowledge/Lint 引擎(均标 `UNSUPPORTED`)。 diff --git a/src/app.rs b/src/app.rs index 6c46e4c..8dbb9eb 100644 --- a/src/app.rs +++ b/src/app.rs @@ -9,6 +9,7 @@ use crate::core_client::{ }; use crate::document::{DocumentIdentity, DocumentModel}; use crate::error::{ViewError, ViewResult}; +use crate::export::{export as run_export, ExportOptions}; use crate::presentation::{self, BuildInput, Navigation, PresentationModel, SourceStatus}; use crate::project::{Project, SafeRelativePath, ViewConfig}; use crate::semantic::{self, CoreDiagnostic}; @@ -98,7 +99,14 @@ impl AppContext { let mut verified = None; if let Some(client) = &self.core { - match client.check(&self.project, relative, &CheckOptions::default())? { + match client.check( + &self.project, + relative, + &CheckOptions { + refs: false, + timeout: Some(std::time::Duration::from_secs(30)), + }, + )? { CheckResponse { success: false, diagnostics: raw_diagnostics, @@ -400,11 +408,29 @@ pub fn browse(opts: &RuntimeOpts) -> ViewResult { crate::server::serve(context, opts) } -pub fn export(_opts: &RuntimeOpts, _args: &ExportArgs) -> ViewResult { - Err(ViewError::Unsupported { - detail: "static export lands with PR-05; browse and verify are available in this build" - .to_string(), - }) +pub fn export(opts: &RuntimeOpts, args: &ExportArgs) -> ViewResult { + let path = args + .path + .clone() + .or_else(|| opts.path.clone()) + .unwrap_or_else(|| std::path::PathBuf::from(".")); + let context = AppContext::open(&path, opts.marqdo_bin.as_deref())?; + let summary = run_export( + &context, + &ExportOptions { + out: args.out.clone(), + no_annotations: args.no_annotations, + }, + )?; + println!( + "marqdo view export: {} page(s), {} file(s) → {}", + summary.pages, + summary.files, + summary.out.display() + ); + println!("manifest: sha256:{}", summary.manifest_sha256); + println!("executed: false (纯静态导出,未运行任何文档)"); + Ok(0) } fn generic_core_note(err: &ViewError) -> String { diff --git a/src/error.rs b/src/error.rs index 8219621..8d6a556 100644 --- a/src/error.rs +++ b/src/error.rs @@ -100,6 +100,42 @@ impl ViewError { /// JSON diagnostic with `source:"view"` so it can never masquerade as a /// Core diagnostic. Contains no absolute machine paths beyond what the /// caller already supplied. + /// Public, detail-free message for pages/JSON served to the browser. Never + /// contains absolute machine paths, scratch paths or raw subprocess text. + pub fn public_message(&self) -> &'static str { + match self.code() { + "view.core_missing" => "未找到可用的冻结核心(MARQDO_BIN)。", + "view.protocol_incompatible" => "核心或协议版本不兼容。", + "view.analysis_failed" => "Core 静态检查失败;正文仍可阅读,语义标注已撤销。", + "view.source_mismatch" => "当前源码与 Analysis 字节摘要不一致。", + "view.source_span_invalid" => "语义位置超出源码或不在 UTF-8 边界。", + "view.trace_stale" => "运行结果与当前 Analysis 不匹配,已标记为过期。", + "view.run_denied" => "运行请求未获授权或被拒绝。", + "view.path_forbidden" => "请求的路径超出允许的项目根目录。", + "view.bind_denied" => "拒绝绑定该网络地址。", + "view.asset_integrity" => "内嵌资源摘要不一致。", + "view.export_failed" => "静态导出失败(输出目录不安全或写入失败)。", + "view.resource_limit" => "超过配置的资源上限。", + "view.core_spawn" => "无法启动冻结核心。", + "view.core_timeout" => "冻结核心执行超时,已终止。", + "view.io" => "本地 I/O 失败。", + "view.unsupported" => "当前版本不支持该功能。", + _ => "View 内部错误。", + } + } + + /// Browser-safe JSON diagnostic: stable code + public message only. + pub fn to_public_json(&self) -> serde_json::Value { + serde_json::json!({ + "schema": "marqdo.view-error", + "schema_version": 1, + "code": self.code(), + "source": "view", + "message": self.public_message(), + "exit_code": self.exit_code(), + }) + } + pub fn to_json(&self) -> serde_json::Value { serde_json::json!({ "schema": "marqdo.view-error", diff --git a/src/export.rs b/src/export.rs new file mode 100644 index 0000000..0fa59b6 --- /dev/null +++ b/src/export.rs @@ -0,0 +1,340 @@ +//! Pure static site export. +//! +//! Export uses the same `AppContext::load` (static `check` only) and the same +//! `ReaderRenderer` as Live; it never calls `run`, never starts a provider and +//! never writes into the source project (RFC-VIEW-0001 §11.3). + +use crate::app::AppContext; +use crate::assets::AssetBundle; +use crate::error::{ViewError, ViewResult}; +use crate::project::SafeRelativePath; +use crate::render::ReaderRenderer; +use crate::source_map::sha256_hex; +use std::path::{Path, PathBuf}; + +const MANIFEST_SCHEMA: &str = "marqdo.view-export"; + +#[derive(Debug, Clone)] +pub struct ExportOptions { + pub out: PathBuf, + pub no_annotations: bool, +} + +#[derive(Debug)] +pub struct ExportSummary { + pub out: PathBuf, + pub pages: usize, + pub files: usize, + pub manifest_sha256: String, +} + +pub fn export(context: &AppContext, options: &ExportOptions) -> ViewResult { + let bundle = AssetBundle::get(); + let renderer = ReaderRenderer::new(); + let root = context.project().root().to_path_buf(); + let out = absolute_export_target(&options.out)?; + if out.starts_with(&root) { + return Err(ViewError::ExportFailed { + detail: format!( + "输出目录 {} 位于项目根 {} 内;请选择项目外的目录以避免递归/覆盖源文件", + out.display(), + root.display() + ), + }); + } + validate_existing_target(&out)?; + + let documents = context.project().list_documents()?; + if documents.is_empty() { + return Err(ViewError::ExportFailed { + detail: "项目内没有 .mq.md 文档可导出".to_string(), + }); + } + let entry = context.project().entry().relative.clone(); + let staging = staging_dir(&out)?; + + let result = (|| -> ViewResult { + let assets_dir = staging.join("assets"); + let pages_dir = staging.join("pages"); + std::fs::create_dir_all(&assets_dir) + .map_err(|err| ViewError::io(&format!("create {}", assets_dir.display()), err))?; + std::fs::create_dir_all(&pages_dir) + .map_err(|err| ViewError::io(&format!("create {}", pages_dir.display()), err))?; + + // Assets: the exact same bytes Live serves. + let mut asset_manifest = Vec::new(); + for asset in bundle.all() { + let name = if asset.extension == "css" && asset.name == "reader" { + bundle.hashed_css_name() + } else { + asset.hashed_name() + }; + let bytes = if asset.extension == "css" && asset.name == "reader" { + bundle.css_bytes().to_vec() + } else { + asset.bytes.to_vec() + }; + std::fs::write(assets_dir.join(&name), &bytes) + .map_err(|err| ViewError::io(&format!("write asset {name}"), err))?; + asset_manifest.push(serde_json::json!({ + "path": format!("assets/{name}"), + "sha256": sha256_hex(&bytes), + "size": bytes.len(), + })); + } + + let mut pages = Vec::new(); + let mut file_manifest: Vec = Vec::new(); + for relative in &documents { + let model = context.load(relative)?; + let depth = relative.as_str().split('/').count(); + let context = + crate::render::RenderContext::static_export(depth, !options.no_annotations); + let page = renderer.render(&model, &context); + let page_path = pages_dir.join(format!("{}.html", relative.as_str())); + if let Some(parent) = page_path.parent() { + std::fs::create_dir_all(parent) + .map_err(|err| ViewError::io(&format!("create {}", parent.display()), err))?; + } + std::fs::write(&page_path, page.html.as_bytes()) + .map_err(|err| ViewError::io(&format!("write {}", page_path.display()), err))?; + let page_sha = sha256_hex(page.html.as_bytes()); + let page_rel = format!("pages/{}.html", relative.as_str()); + file_manifest.push(serde_json::json!({ + "path": page_rel, + "sha256": page_sha, + "size": page.html.len(), + })); + pages.push(serde_json::json!({ + "relative_path": relative.as_str(), + "module_id": model.document.identity.module_id, + "source_sha256": sha256_hex(model.document.source.as_bytes()), + "source_status": model.source_status.data_value(), + "analysis_digest": model.semantic.as_ref().map(|semantic| semantic.analysis_digest.clone()), + "file": page_rel, + "sha256": page_sha, + "annotations": !options.no_annotations, + })); + } + + // index.html is the same renderer output with site-root depth. + let entry_model = context.load(&entry)?; + let entry_context = crate::render::RenderContext::static_export(0, !options.no_annotations); + let index_page = renderer.render(&entry_model, &entry_context); + let index_path = staging.join("index.html"); + std::fs::write(&index_path, index_page.html.as_bytes()) + .map_err(|err| ViewError::io(&format!("write {}", index_path.display()), err))?; + let index_sha = sha256_hex(index_page.html.as_bytes()); + file_manifest.push(serde_json::json!({ + "path": "index.html", + "sha256": index_sha, + "size": index_page.html.len(), + })); + + file_manifest.sort_by(|a, b| { + a["path"] + .as_str() + .unwrap_or("") + .cmp(b["path"].as_str().unwrap_or("")) + }); + let manifest = serde_json::json!({ + "schema": MANIFEST_SCHEMA, + "schema_version": 1, + "view": { + "name": "marqdo-view", + "version": env!("CARGO_PKG_VERSION"), + }, + "compatibility": { + "marqdo": crate::version::PRODUCT_RANGE, + "tool_protocol": crate::version::TOOL_PROTOCOL, + "analysis": crate::version::ANALYSIS_PROTOCOL, + "trace": crate::version::TRACE_PROTOCOL, + "markdown_profile": "marqdo.md.v1", + }, + "core_version": entry_model.core_version, + "entry": { + "relative_path": entry.as_str(), + "file": "index.html", + "sha256": index_sha, + }, + "pages": pages, + "assets": asset_manifest, + "files": file_manifest, + "executed": false, + "note": "Static export only; reading or exporting never executes the document.", + }); + let manifest_bytes = + serde_json::to_vec_pretty(&manifest).map_err(|err| ViewError::ExportFailed { + detail: format!("serialize export manifest: {err}"), + })?; + let manifest_path = staging.join("manifest.json"); + std::fs::write(&manifest_path, &manifest_bytes) + .map_err(|err| ViewError::io(&format!("write {}", manifest_path.display()), err))?; + + publish(&staging, &out)?; + Ok(ExportSummary { + out, + pages: documents.len(), + files: file_manifest.len() + asset_manifest.len() + 1, + manifest_sha256: sha256_hex(&manifest_bytes), + }) + })(); + + if result.is_err() { + let _ = std::fs::remove_dir_all(&staging); + } + result +} + +fn absolute_export_target(raw: &Path) -> ViewResult { + let absolute = if raw.is_absolute() { + raw.to_path_buf() + } else { + std::env::current_dir() + .map_err(|err| ViewError::io("resolve current dir", err))? + .join(raw) + }; + // Canonicalize the nearest existing ancestor so `..` cannot escape checks, + // then re-append the remaining components. + let mut existing = absolute.clone(); + let mut tail = Vec::new(); + while !existing.exists() { + let Some(name) = existing.file_name().map(|name| name.to_os_string()) else { + break; + }; + tail.push(name); + if !existing.pop() { + break; + } + } + let mut canonical = existing + .canonicalize() + .map_err(|err| ViewError::ExportFailed { + detail: format!("无法解析输出目录 {}: {err}", raw.display()), + })?; + for component in tail.into_iter().rev() { + canonical.push(component); + } + Ok(canonical) +} + +fn validate_existing_target(out: &Path) -> ViewResult<()> { + if !out.exists() { + return Ok(()); + } + let metadata = std::fs::metadata(out) + .map_err(|err| ViewError::io(&format!("stat {}", out.display()), err))?; + if !metadata.is_dir() { + return Err(ViewError::ExportFailed { + detail: format!("输出路径 {} 已存在且不是目录", out.display()), + }); + } + let entries = std::fs::read_dir(out) + .map_err(|err| ViewError::io(&format!("read {}", out.display()), err))? + .count(); + if entries == 0 { + return Ok(()); + } + let manifest = out.join("manifest.json"); + let bytes = std::fs::read(&manifest).map_err(|_| ViewError::ExportFailed { + detail: format!( + "输出目录 {} 非空且不是 marqdo-view 导出(缺少 manifest.json);拒绝覆盖", + out.display() + ), + })?; + let value: serde_json::Value = + serde_json::from_slice(&bytes).map_err(|_| ViewError::ExportFailed { + detail: format!("{} 不是合法的 View 导出清单", manifest.display()), + })?; + if value.get("schema").and_then(|schema| schema.as_str()) != Some(MANIFEST_SCHEMA) { + return Err(ViewError::ExportFailed { + detail: format!( + "输出目录 {} 的 manifest 不是 {};拒绝覆盖", + out.display(), + MANIFEST_SCHEMA + ), + }); + } + Ok(()) +} + +fn staging_dir(out: &Path) -> ViewResult { + let parent = out.parent().ok_or_else(|| ViewError::ExportFailed { + detail: "输出目录没有父目录".to_string(), + })?; + std::fs::create_dir_all(parent) + .map_err(|err| ViewError::io(&format!("create {}", parent.display()), err))?; + let staging = parent.join(format!( + ".marqdo-view-export-{}-{}", + std::process::id(), + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map(|duration| duration.as_nanos()) + .unwrap_or(0) + )); + std::fs::create_dir(&staging) + .map_err(|err| ViewError::io(&format!("create staging {}", staging.display()), err))?; + Ok(staging) +} + +fn publish(staging: &Path, out: &Path) -> ViewResult<()> { + if out.exists() { + // Only reaches here for an empty dir or a previous View export (checked + // before any write), so replacing it cannot destroy user content. + std::fs::remove_dir_all(out) + .map_err(|err| ViewError::io(&format!("replace {}", out.display()), err))?; + } + std::fs::rename(staging, out).map_err(|err| { + let _ = std::fs::remove_dir_all(staging); + ViewError::ExportFailed { + detail: format!("原子发布 {} 失败: {err}", out.display()), + } + })?; + Ok(()) +} + +/// Export link target check used by tests: no path in the manifest may be +/// absolute or contain parent traversal. +pub fn manifest_paths_are_relative(manifest: &serde_json::Value) -> bool { + let checks = manifest + .get("files") + .and_then(|files| files.as_array()) + .cloned() + .unwrap_or_default(); + checks.iter().all(|entry| { + entry + .get("path") + .and_then(|path| path.as_str()) + .map(|path| SafeRelativePath::parse(path).is_ok()) + .unwrap_or(false) + }) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn export_target_outside_project_is_accepted() { + let dir = std::env::current_dir().unwrap(); + let target = absolute_export_target(&dir.join("target/test-export-out")).unwrap(); + assert!(target.is_absolute()); + assert!(!target.to_string_lossy().contains("..")); + } + + #[test] + fn manifest_relative_paths_are_validated() { + let manifest = serde_json::json!({ + "files": [ + {"path": "index.html"}, + {"path": "pages/docs/a.mq.md.html"}, + {"path": "assets/reader.0123456789abcdef.css"} + ] + }); + assert!(manifest_paths_are_relative(&manifest)); + let bad = serde_json::json!({"files": [{"path": "../escape.html"}]}); + assert!(!manifest_paths_are_relative(&bad)); + let absolute = serde_json::json!({"files": [{"path": "/etc/passwd"}]}); + assert!(!manifest_paths_are_relative(&absolute)); + } +} diff --git a/src/lib.rs b/src/lib.rs index 45ddb28..77c8bae 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -12,6 +12,7 @@ pub mod cli; pub mod core_client; pub mod document; pub mod error; +pub mod export; pub mod presentation; pub mod project; pub mod render; diff --git a/src/render.rs b/src/render.rs index 2d2492f..120a4ad 100644 --- a/src/render.rs +++ b/src/render.rs @@ -69,6 +69,8 @@ pub struct RenderContext { /// Whether a Run control may be shown as available. False until the /// explicit-run flow exists; the button then explains that it is disabled. pub run_available: bool, + /// Static exports may hide semantic/run annotations without changing prose. + pub annotations: bool, } impl RenderContext { @@ -78,6 +80,7 @@ impl RenderContext { live: true, csrf_token: None, run_available: false, + annotations: true, } } @@ -87,8 +90,16 @@ impl RenderContext { live: false, csrf_token: None, run_available: false, + annotations: true, } } + + /// Static export with annotations optionally disabled. + pub fn static_export(page_depth: usize, annotations: bool) -> Self { + let mut context = Self::static_site(page_depth); + context.annotations = annotations; + context + } } pub struct RenderedPage { @@ -145,7 +156,7 @@ impl ReaderRenderer { - + 跳到正文 "##, presentation_version = model.version, @@ -156,6 +167,7 @@ impl ReaderRenderer { css = escape_attr(&format!("{asset_prefix}{css_name}")), js = escape_attr(&format!("{asset_prefix}{js_name}")), status = model.source_status.data_value(), + annotations = if ctx.annotations { "on" } else { "off" }, run_state = model.run_state().data_value(), run_available = if ctx.run_available { "true" } else { "false" }, live = if ctx.live { "true" } else { "false" }, @@ -1028,7 +1040,11 @@ fn render_inline( literal, ticks: _, } => { - let anchor = projection.and_then(|projection| projection.statement_for_inline(*span)); + let anchor = if ctx.annotations { + projection.and_then(|projection| projection.statement_for_inline(*span)) + } else { + None + }; html.push_str(" { - let anchor = projection.and_then(|projection| projection.statement_for_inline(*span)); + let anchor = if ctx.annotations { + projection.and_then(|projection| projection.statement_for_inline(*span)) + } else { + None + }; html.push_str(" { - let anchor = projection.and_then(|projection| projection.statement_for_inline(*span)); + let anchor = if ctx.annotations { + projection.and_then(|projection| projection.statement_for_inline(*span)) + } else { + None + }; html.push_str(" ViewResult { cache: Mutex::new(HashMap::new()), allowed_hosts: allowed_hosts(port), running: AtomicBool::new(false), + active_requests: std::sync::atomic::AtomicUsize::new(0), run_cache: Mutex::new(HashMap::new()), run_seq: AtomicU64::new(1), }); @@ -95,6 +96,8 @@ struct ServerState { allowed_hosts: Vec, /// One active run per View session. running: AtomicBool, + /// Bounded concurrent request handling. + active_requests: std::sync::atomic::AtomicUsize, run_cache: Mutex>, run_seq: AtomicU64, } @@ -161,6 +164,17 @@ impl ServerState { } fn handle(state: &ServerState, request: Request) -> ViewResult<()> { + if state.active_requests.fetch_add(1, Ordering::SeqCst) >= 32 { + state.active_requests.fetch_sub(1, Ordering::SeqCst); + return respond_text( + request, + StatusCode(503), + "text/plain; charset=utf-8", + "too many concurrent requests\n".as_bytes().to_vec(), + CacheKind::NoStore, + ); + } + let _active = ActiveRequestGuard(&state.active_requests); let method = request.method().clone(); let is_head = method == Method::Head; let is_get = method == Method::Get; @@ -569,6 +583,14 @@ fn handle_clear_run_post(state: &ServerState, mut request: Request) -> ViewResul ) } +struct ActiveRequestGuard<'a>(&'a std::sync::atomic::AtomicUsize); + +impl Drop for ActiveRequestGuard<'_> { + fn drop(&mut self) { + self.0.fetch_sub(1, Ordering::SeqCst); + } +} + struct RunningGuard<'a>(&'a AtomicBool); impl Drop for RunningGuard<'_> { @@ -666,6 +688,7 @@ fn serve_page( live: true, csrf_token: Some(state.csrf_token.clone()), run_available: state.ctx.core().is_some() && model.can_offer_run(), + annotations: true, }; let page = state.renderer.render(model, &ctx); respond_html(request, page.html.into_bytes(), is_head) @@ -675,7 +698,7 @@ fn serve_error_page(request: Request, err: &ViewError, is_head: bool) -> ViewRes let html = format!( "Marqdo View · 错误

无法生成阅读页面

{code}

{message}

返回入口

", code = escape_html(err.code()), - message = escape_html(&err.to_string()), + message = escape_html(err.public_message()), ); respond_html(request, html.into_bytes(), is_head) } @@ -797,7 +820,7 @@ fn respond_json(request: Request, status: StatusCode, value: &serde_json::Value) } fn respond_json_error(request: Request, status: StatusCode, err: &ViewError) -> ViewResult<()> { - respond_json(request, status, &err.to_json()) + respond_json(request, status, &err.to_public_json()) } fn respond_text( diff --git a/tests/browser/reader.browser.cjs b/tests/browser/reader.browser.cjs index c5b4b17..98d2f40 100644 --- a/tests/browser/reader.browser.cjs +++ b/tests/browser/reader.browser.cjs @@ -115,6 +115,24 @@ function localHostOnly(url) { ); await page.keyboard.press("Escape"); + if (projectName === "security-project") { + // X-01: an adversarial document must not execute script or fetch anything. + let alertFired = false; + page.on("dialog", async (dialog) => { + alertFired = true; + await dialog.dismiss(); + }); + await page.reload({ waitUntil: "networkidle" }); + check("adversarial doc has no alert dialog", !alertFired); + check("adversarial doc has no external requests", external.length === 0, external.join(", ")); + check("raw HTML omitted note rendered", (await page.locator(".mq-raw-omitted").count()) > 0); + check("prose survives sanitization", (await page.locator(".mq-document").innerText()).includes("普通正文")); + check( + "javascript link neutralized", + (await page.locator('a[href^="javascript:"]').count()) === 0 + ); + } + if (projectName === "welcome") { check("welcome hero only on configured page", (await page.locator(".mq-welcome").count()) === 1); check( diff --git a/tests/common/mod.rs b/tests/common/mod.rs index 1c1d73d..fbe848d 100644 --- a/tests/common/mod.rs +++ b/tests/common/mod.rs @@ -95,6 +95,7 @@ case "$1" in exit 0 ;; run) + : > "$dir/run-was-called" trace="" prev="" for a in "$@"; do diff --git a/tests/export.rs b/tests/export.rs new file mode 100644 index 0000000..cae30bd --- /dev/null +++ b/tests/export.rs @@ -0,0 +1,310 @@ +//! Static export contract tests: pure read-only, same renderer, offline assets, +//! safe output paths and no execution (RFC-VIEW-0001 §11.3, R-02, X-04). + +mod common; + +use common::{run_view, sha256_hex, FakeCore, TempProject}; +use std::path::{Path, PathBuf}; + +fn repo_root() -> PathBuf { + PathBuf::from(env!("CARGO_MANIFEST_DIR")) +} + +fn exported_dir(name: &str) -> PathBuf { + let dir = PathBuf::from(env!("CARGO_TARGET_TMPDIR")).join(format!( + "{name}-{}-{}", + std::process::id(), + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map(|d| d.as_nanos()) + .unwrap_or(0) + )); + let _ = std::fs::remove_dir_all(&dir); + dir +} + +fn fake_core_for_welcome(name: &str) -> FakeCore { + let core = FakeCore::new(name); + let golden = std::fs::read(repo_root().join("tests/golden/analysis-v2/welcome.json")).unwrap(); + core.set_analysis(std::str::from_utf8(&golden).unwrap()); + core +} + +fn export( + project: &Path, + out: &Path, + extra: &[&str], + core: Option<&FakeCore>, +) -> std::process::Output { + let mut args = vec![ + "export".to_string(), + project.to_string_lossy().to_string(), + "--out".to_string(), + out.to_string_lossy().to_string(), + ]; + args.extend(extra.iter().map(|value| value.to_string())); + let mut core_arg = Vec::new(); + if let Some(core) = core { + core_arg.push("--marqdo-bin".to_string()); + core_arg.push(core.script.to_string_lossy().to_string()); + } + let mut all: Vec<&str> = args.iter().map(String::as_str).collect(); + all.extend(core_arg.iter().map(String::as_str)); + run_view( + &all, + &repo_root(), + &[ + ("MARQDO_BIN", None), + ("MARQDO_TOOL_PROTOCOL", None), + ("MARQDO_PROTOCOL_ANALYSIS", None), + ("MARQDO_PROTOCOL_TRACE", None), + ], + ) +} + +fn manifest(out: &Path) -> serde_json::Value { + let bytes = std::fs::read(out.join("manifest.json")).expect("manifest"); + serde_json::from_slice(&bytes).expect("manifest json") +} + +#[test] +fn exports_offline_site_with_shared_renderer_and_relative_links() { + let project = repo_root().join("examples/welcome"); + let out = exported_dir("export-welcome"); + let core = fake_core_for_welcome("export-core-welcome"); + let output = export(&project, &out, &[], Some(&core)); + let stderr = String::from_utf8_lossy(&output.stderr); + assert_eq!(output.status.code(), Some(0), "stderr: {stderr}"); + + for file in [ + "index.html", + "pages/00-welcome.mq.md.html", + "pages/guide.mq.md.html", + "manifest.json", + ] { + assert!(out.join(file).is_file(), "missing {file}"); + } + let index = std::fs::read_to_string(out.join("index.html")).unwrap(); + assert!(index.contains("mq-reader")); + assert!(index.contains("href=\"assets/reader.")); + assert!(!index.contains("/file?path=")); + assert!(!index.contains("http://127.0.0.1")); + assert!(index.contains("Content-Security-Policy")); + assert!(index.contains("script-src 'self' file:")); + // Shared renderer: the only stylesheet/script are hash-named local assets. + assert_eq!(index.matches("= 2); + assert!(manifest["assets"].as_array().unwrap().len() >= 5); + let manifest_text = serde_json::to_string(&manifest).unwrap(); + assert!( + !manifest_text.contains(&project.to_string_lossy().to_string()), + "absolute project path leaked into manifest" + ); + assert!( + !manifest_text.contains("/root/"), + "absolute path in manifest" + ); + + // Every manifest file hash matches the bytes on disk. + for entry in manifest["files"].as_array().unwrap() { + let rel = entry["path"].as_str().unwrap(); + assert!(!rel.starts_with('/')); + let bytes = std::fs::read(out.join(rel)).unwrap(); + assert_eq!(sha256_hex(&bytes), entry["sha256"].as_str().unwrap()); + } + // Assets are exactly the embedded bundle bytes. + let bundle = marqdo_view::assets::AssetBundle::get(); + let css = std::fs::read(out.join("assets").join(bundle.hashed_css_name())).unwrap(); + assert_eq!(css, bundle.css_bytes()); + + // Export never spawned a run. + let argv = core.argv_lines(); + assert!(!argv.iter().any(|line| line == "arg=run")); + assert!(!core.dir.join("run-was-called").exists()); + let _ = std::fs::remove_dir_all(&out); +} + +#[test] +fn export_never_executes_side_effects() { + let project = repo_root().join("examples/control-flow"); + let out = exported_dir("export-no-exec"); + let core = FakeCore::new("export-core-noexec"); + let golden = + std::fs::read(repo_root().join("tests/golden/analysis-v2/control-flow.json")).unwrap(); + core.set_analysis(std::str::from_utf8(&golden).unwrap()); + let output = export(&project, &out, &[], Some(&core)); + assert_eq!( + output.status.code(), + Some(0), + "stderr: {}", + String::from_utf8_lossy(&output.stderr) + ); + assert!( + !core.dir.join("run-was-called").exists(), + "export invoked Core run" + ); + assert!(!core.argv_lines().iter().any(|line| line == "arg=run")); + // Export page explicitly has no run panel and no fake RUNNING state. + let index = std::fs::read_to_string(out.join("index.html")).unwrap(); + assert!(!index.contains("mq-run-panel")); + assert!(!index.contains("data-run-state=\"running\"")); + let _ = std::fs::remove_dir_all(&out); +} + +#[test] +fn no_annotations_keeps_prose_but_removes_anchors() { + let project = repo_root().join("examples/mixed-modes"); + let out = exported_dir("export-no-annotations"); + let core = FakeCore::new("export-core-noannot"); + let golden = + std::fs::read(repo_root().join("tests/golden/analysis-v2/mixed-modes.json")).unwrap(); + core.set_analysis(std::str::from_utf8(&golden).unwrap()); + let output = export(&project, &out, &["--no-annotations"], Some(&core)); + assert_eq!( + output.status.code(), + Some(0), + "stderr: {}", + String::from_utf8_lossy(&output.stderr) + ); + let index = std::fs::read_to_string(out.join("index.html")).unwrap(); + assert!(index.contains("data-annotations=\"off\"")); + assert!(!index.contains("class=\"mq-anchor\"")); + assert!(index.contains("计算笔记"), "prose must remain readable"); + assert!(index.contains("mq-document")); + let _ = std::fs::remove_dir_all(&out); +} + +#[test] +fn refuses_to_export_inside_the_project_root() { + // Using a TempProject keeps the committed examples untouched. + let project = TempProject::new("export-inside-project"); + project.write( + "marqdo.yaml", + "project:\n name: export-inside\n version: 0.1.0\n", + ); + project.write("index.mq.md", "# @knowledge hi\n"); + let core = FakeCore::new("export-core-inside"); + let out = project.path("site"); + let output = export(&project.dir, &out, &[], Some(&core)); + assert_eq!(output.status.code(), Some(1)); + let stderr = String::from_utf8_lossy(&output.stderr); + assert!(stderr.contains("view.export_failed"), "{stderr}"); + assert!(!out.exists()); +} + +#[test] +fn refuses_to_overwrite_unrelated_non_empty_directory() { + let project = repo_root().join("examples/welcome"); + let out = exported_dir("export-unrelated-dir"); + std::fs::create_dir_all(&out).unwrap(); + std::fs::write(out.join("important.txt"), "do not delete").unwrap(); + let core = fake_core_for_welcome("export-core-unrelated"); + let output = export(&project, &out, &[], Some(&core)); + assert_eq!(output.status.code(), Some(1)); + assert!(out.join("important.txt").is_file()); + assert_eq!( + std::fs::read_to_string(out.join("important.txt")).unwrap(), + "do not delete" + ); + let _ = std::fs::remove_dir_all(&out); +} + +#[test] +fn replaces_a_previous_export_atomically() { + let project = repo_root().join("examples/welcome"); + let out = exported_dir("export-replace"); + let core = fake_core_for_welcome("export-core-replace"); + let first = export(&project, &out, &[], Some(&core)); + assert_eq!(first.status.code(), Some(0)); + let first_manifest = manifest(&out); + let second = export(&project, &out, &[], Some(&core)); + assert_eq!( + second.status.code(), + Some(0), + "stderr: {}", + String::from_utf8_lossy(&second.stderr) + ); + let second_manifest = manifest(&out); + assert_eq!(first_manifest["schema"], second_manifest["schema"]); + assert!(out.join("index.html").is_file()); + let _ = std::fs::remove_dir_all(&out); +} + +#[test] +fn real_frozen_core_export_marks_both_pages_static_ok() { + let Ok(core_bin) = std::env::var("MARQDO_FROZEN_BIN") else { + eprintln!("MARQDO_FROZEN_BIN not set; skipping real-core export test"); + return; + }; + let project = repo_root().join("examples/welcome"); + let out = exported_dir("export-real-core"); + let output = run_view( + &[ + "export", + project.to_str().unwrap(), + "--out", + out.to_str().unwrap(), + ], + &repo_root(), + &[ + ("MARQDO_BIN", Some(core_bin.as_str())), + ("MARQDO_TOOL_PROTOCOL", None), + ("MARQDO_PROTOCOL_ANALYSIS", None), + ("MARQDO_PROTOCOL_TRACE", None), + ], + ); + assert_eq!( + output.status.code(), + Some(0), + "stderr: {}", + String::from_utf8_lossy(&output.stderr) + ); + for page in [ + "index.html", + "pages/00-welcome.mq.md.html", + "pages/guide.mq.md.html", + ] { + let html = std::fs::read_to_string(out.join(page)).unwrap(); + assert!( + html.contains("data-source-status=\"static-ok\""), + "{page} not static-ok" + ); + assert!(!html.contains("/file?path=")); + } + let _ = std::fs::remove_dir_all(&out); +} + +#[test] +fn exported_html_has_no_remote_subresources() { + let project = repo_root().join("examples/tables-math"); + let out = exported_dir("export-offline"); + let core = FakeCore::new("export-core-offline"); + let golden = + std::fs::read(repo_root().join("tests/golden/analysis-v2/tables-math.json")).unwrap(); + core.set_analysis(std::str::from_utf8(&golden).unwrap()); + let output = export(&project, &out, &[], Some(&core)); + assert_eq!(output.status.code(), Some(0)); + for file in ["index.html", "pages/index.mq.md.html"] { + let html = std::fs::read_to_string(out.join(file)).unwrap(); + assert!(!html.contains(" + + + + + +[危险链接](javascript:alert(2)) + +[数据链接](data:text/html;base64,PHNjcmlwdD5hbGVydCgzKTwvc2NyaXB0Pg==) + +普通正文仍然必须可读:**加粗** 与 `代码`。 + +| 安全 | 说明 | +| --- | --- | +| 原始 HTML | 已忽略 | diff --git a/tests/fixtures/security-project/marqdo.yaml b/tests/fixtures/security-project/marqdo.yaml new file mode 100644 index 0000000..70f31f9 --- /dev/null +++ b/tests/fixtures/security-project/marqdo.yaml @@ -0,0 +1,3 @@ +project: + name: security-fixture + version: 0.1.0 diff --git a/tests/http_live.rs b/tests/http_live.rs index 0b5b775..0d1e20b 100644 --- a/tests/http_live.rs +++ b/tests/http_live.rs @@ -383,7 +383,13 @@ fn run_api_rejects_missing_token_wrong_origin_and_bad_requests() { r#"{"path":"index.mq.md","mode":"project","confirm":true}"#, ); assert_eq!(project_mode.status, 403); - assert!(project_mode.body.contains("pure")); + assert!(project_mode.body.contains("view.run_denied")); + // Public errors never leak absolute paths or raw subprocess text. + assert!( + !project_mode.body.contains("/root/"), + "{}", + project_mode.body + ); let args = server._core.argv_lines(); let run_calls = args diff --git a/tools/test-browser.sh b/tools/test-browser.sh index ddd9cf3..73715f5 100755 --- a/tools/test-browser.sh +++ b/tools/test-browser.sh @@ -77,6 +77,7 @@ run_suite() { mkdir -p "$repo_root/tests/.cache" "$MQ_SCREENSHOT_DIR" run_suite examples/welcome run_suite examples/control-flow +run_suite tests/fixtures/security-project core_after="$(sha256sum "$MARQDO_BIN" | cut -d' ' -f1)" if [[ "$core_before" != "$core_after" ]]; then diff --git a/tools/test-export.sh b/tools/test-export.sh new file mode 100755 index 0000000..7b9cc22 --- /dev/null +++ b/tools/test-export.sh @@ -0,0 +1,82 @@ +#!/usr/bin/env bash +# Static export acceptance: pure read-only, offline assets, safe paths. +# +# Usage: MARQDO_BIN=/abs/path/marqdo tools/test-export.sh +set -euo pipefail + +repo_root="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" +cd "$repo_root" + +: "${MARQDO_BIN:?set MARQDO_BIN to the frozen marqdo binary}" +[[ -x "$MARQDO_BIN" ]] || { echo "error: MARQDO_BIN not executable" >&2; exit 1; } +core_before="$(sha256sum "$MARQDO_BIN" | cut -d' ' -f1)" + +binary="$repo_root/target/release/marqdo-view" +[[ -x "$binary" ]] || cargo build --release --locked + +site="$repo_root/dist/test-export-site" +rm -rf "$site" +MARQDO_BIN="$MARQDO_BIN" "$binary" export examples/welcome --out "$site" + +python3 - "$site" <<'PY' +import hashlib +import json +import pathlib +import re +import sys + +site = pathlib.Path(sys.argv[1]) +manifest = json.loads((site / "manifest.json").read_text()) +assert manifest["schema"] == "marqdo.view-export" +assert manifest["executed"] is False +assert manifest["pages"], "no pages exported" +for entry in manifest["files"]: + rel = entry["path"] + assert not rel.startswith("/") and ".." not in pathlib.PurePosixPath(rel).parts + data = (site / rel).read_bytes() + assert hashlib.sha256(data).hexdigest() == entry["sha256"], rel +index = (site / "index.html").read_text() +assert "/file?path=" not in index +assert re.search(r' { + const browser = await chromium.launch(); + const page = await browser.newPage({ viewport: { width: 1280, height: 800 } }); + const external = []; + const errors = []; + page.on("request", (request) => { + if (!request.url().startsWith("file:") && !request.url().startsWith("data:")) { + external.push(request.url()); + } + }); + page.on("console", (message) => { + if (message.type() === "error") errors.push(message.text()); + }); + page.on("pageerror", (error) => errors.push(String(error))); + await page.goto("file://" + process.env.MQ_FILE, { waitUntil: "load" }); + const text = await page.locator(".mq-document").innerText(); + if (text.trim().length < 20) throw new Error("offline page not readable"); + if (external.length) throw new Error("offline page requested " + external.join(",")); + if (errors.length) throw new Error("offline console errors: " + errors.join(" | ")); + if ((await page.locator("link[rel=stylesheet]").count()) !== 1) throw new Error("stylesheet missing"); + console.log("file:// offline browser check: PASS"); + await browser.close(); +})().catch((error) => { console.error(error.message); process.exit(1); }); +JS +else + echo "note: Playwright not installed; skipped file:// browser check" +fi + +core_after="$(sha256sum "$MARQDO_BIN" | cut -d' ' -f1)" +[[ "$core_before" == "$core_after" ]] || { echo "error: frozen core changed" >&2; exit 1; } +echo "export: PASS (offline site at $site; core sha256 $core_before unchanged)" diff --git a/tools/test-security.sh b/tools/test-security.sh new file mode 100755 index 0000000..d678e5e --- /dev/null +++ b/tools/test-security.sh @@ -0,0 +1,22 @@ +#!/usr/bin/env bash +# Security/contract suite: HTTP boundary, CSRF/Origin, path escapes, XSS +# sanitization, export-no-exec, architectural coupling gates. +# +# Usage: tools/test-security.sh +set -euo pipefail + +repo_root="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" +cd "$repo_root" + +cargo test --locked --test http_live +cargo test --locked --test rendering +cargo test --locked --test export +cargo test --locked --test no_coupling +cargo test --locked --test asset_integrity + +if [[ -n "${MARQDO_FROZEN_BIN:-}" ]]; then + MARQDO_BIN="$MARQDO_FROZEN_BIN" ./tools/test-export.sh +else + echo "note: MARQDO_FROZEN_BIN not set; skipped real-core export script" +fi +echo "security: PASS"