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/<relative>.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
This commit is contained in:
marqdo-view dev committed 2026-11-22 11:52:22 +08:00
1 parent 9a80272b5f
commit 1f34daffb0
20 files changed
+983 -19

No files matched your search

+32 -6
View File
@@ -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<i32> {
crate::server::serve(context, opts)
}
pub fn export(_opts: &RuntimeOpts, _args: &ExportArgs) -> ViewResult<i32> {
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<i32> {
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 {
+36
View File
@@ -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",
+340
View File
@@ -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<ExportSummary> {
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<ExportSummary> {
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<serde_json::Value> = 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<PathBuf> {
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<PathBuf> {
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));
}
}
+1
View File
@@ -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;
+28 -4
View File
@@ -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 {
<link rel="stylesheet" href="{css}"/>
<script defer src="{js}"></script>
</head>
<body class="mq-reader" data-mode="document" data-annotations="on" data-size="normal" data-source-status="{status}" data-run-state="{run_state}" data-run-available="{run_available}" data-live="{live}">
<body class="mq-reader" data-mode="document" data-annotations="{annotations}" data-size="normal" data-source-status="{status}" data-run-state="{run_state}" data-run-available="{run_available}" data-live="{live}">
<a class="mq-skip" href="#mq-main">跳到正文</a>
"##,
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("<code");
if let Some((_, statement)) = anchor {
let id = source_id(
@@ -1052,7 +1068,11 @@ fn render_inline(
}
}
Inline::Strong { span, children } => {
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("<strong");
if let Some((_, statement)) = anchor {
let id = source_id(
@@ -1076,7 +1096,11 @@ fn render_inline(
}
}
Inline::Emph { span, children } => {
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("<em");
if let Some((_, statement)) = anchor {
let id = source_id(
+25 -2
View File
@@ -66,6 +66,7 @@ pub fn serve(ctx: AppContext, opts: &RuntimeOpts) -> ViewResult<i32> {
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<String>,
/// One active run per View session.
running: AtomicBool,
/// Bounded concurrent request handling.
active_requests: std::sync::atomic::AtomicUsize,
run_cache: Mutex<HashMap<String, CachedRun>>,
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!(
"<!DOCTYPE html><html lang=\"zh-CN\"><head><meta charset=\"utf-8\"/><title>Marqdo View · 错误</title><meta name=\"viewport\" content=\"width=device-width, initial-scale=1\"/></head><body style=\"font:16px/1.6 system-ui,serif;background:#fcf9f5;color:#29251f;padding:2rem;max-width:46rem;margin:auto\"><h1>无法生成阅读页面</h1><p><code>{code}</code></p><p>{message}</p><p><a href=\"/\">返回入口</a></p></body></html>",
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(