feat(PR-02): DocumentModel, Analysis v2 projection, single renderer and Live browsing

- document.rs: comrak marqdo.md.v1 parse -> DocBlock/Inline with exact UTF-8 spans
- semantic.rs: typed Analysis v2 validation (schema/profile/root_id/source_digest,
  units/functions/statements/resources/imports/references/calls/diagnostics,
  per-span UTF-8 checks with explicit view.source_span_invalid warnings)
- presentation.rs: one PresentationModel/Outline with source status matrix
- render.rs: one ReaderRenderer; sanitized GFM, statement anchors, heading mode
  badges (display-only prefix strip), source pane, docs/Live|Static link policy,
  CSP meta, no inline scripts, no raw HTML execution
- server.rs: loopback-only Live reader with Host/DNS-rebinding checks, strict
  percent decoding, project path boundary, security headers, read-only APIs
- app.rs: AppContext degradation (core missing -> prose-only, check error ->
  diagnostics + revoked semantics, protocol mismatch -> hard error)
- assets: single reader.css/reader.js + embedded SHA-256 AssetBundle, copied
  legacy logo/blossom/feather with provenance
- examples + frozen-CLI Analysis goldens + rendering/HTTP/asset/no-coupling tests
- ADR-0003 heading prefix/anchor identity; docs updated
This commit is contained in:
marqdo-view dev committed 2026-11-22 11:19:11 +08:00
1 parent 8ba20a5c67
commit 80ce564f09
47 files changed
+26127 -203

No files matched your search

+87
View File
@@ -0,0 +1,87 @@
//! Asset provenance and integrity: the three reused legacy visual assets are
//! pinned by SHA-256 in `assets/licenses/ASSETS.md` and embedded by
//! `src/assets.rs` (ADR-0002).
use sha2::{Digest, Sha256};
fn sha256_hex(bytes: &[u8]) -> String {
let mut hasher = Sha256::new();
hasher.update(bytes);
let mut out = String::with_capacity(64);
for byte in hasher.finalize() {
use std::fmt::Write as _;
let _ = write!(out, "{byte:02x}");
}
out
}
#[test]
fn reused_assets_match_their_recorded_hashes() {
let root = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"));
for (file, expected) in [
(
"assets/logo.svg",
"52b2338468c62a7da86178ecec86cbb7ea44a996cd1bc4275ebb56f16f2244fe",
),
(
"assets/blossom.webp",
"901fd6b37ebb20d1dfc3bf4d265a063308605350fd317e41914fa35b06f46e00",
),
(
"assets/feather.webp",
"fbd787174be1e8027ae4661b99f7f2cc01b824d8fc875a1d2d39cbd0c052e5de",
),
] {
let bytes =
std::fs::read(root.join(file)).unwrap_or_else(|err| panic!("read {file}: {err}"));
assert_eq!(sha256_hex(&bytes), expected, "{file} digest changed");
}
let licenses = std::fs::read_to_string(root.join("assets/licenses/ASSETS.md")).unwrap();
for expected in [
"52b2338468c62a7da86178ecec86cbb7ea44a996cd1bc4275ebb56f16f2244fe",
"901fd6b37ebb20d1dfc3bf4d265a063308605350fd317e41914fa35b06f46e00",
"fbd787174be1e8027ae4661b99f7f2cc01b824d8fc875a1d2d39cbd0c052e5de",
"Apache-2.0",
] {
assert!(licenses.contains(expected), "ASSETS.md misses {expected}");
}
}
#[test]
fn embedded_asset_bundle_matches_disk_and_has_one_theme() {
let bundle = marqdo_view::assets::AssetBundle::get();
let root = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"));
let css = std::fs::read(root.join("assets/reader.css")).unwrap();
assert_eq!(sha256_hex(&css), bundle.css().sha256);
let js = std::fs::read(root.join("assets/reader.js")).unwrap();
assert_eq!(sha256_hex(&js), bundle.js().sha256);
assert_eq!(
bundle
.all()
.iter()
.filter(|asset| asset.extension == "css" || asset.extension == "js")
.count(),
2
);
}
#[test]
fn theme_has_one_token_layer_and_no_legacy_skin() {
let root = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"));
let css = std::fs::read_to_string(root.join("assets/reader.css")).unwrap();
assert_eq!(css.matches("@layer tokens").count(), 1);
assert!(css.contains(
"@layer reset, tokens, layout, typography, semantics, overlays, interactions, responsive;"
));
for banned in ["notebook-page", "reader-page", "legacy.css", "new.css"] {
assert!(!css.contains(banned), "legacy skin marker {banned} in CSS");
}
assert!(
!css.contains("!important"),
"the theme must not rely on !important overrides"
);
// No remote font/CDN requests.
for banned in ["@font-face", "fonts.googleapis", "https://"] {
assert!(!css.contains(banned), "remote resource marker {banned}");
}
}
+22 -9
View File
@@ -57,17 +57,30 @@ fn non_loopback_bind_is_refused_by_default() {
}
#[test]
fn browse_without_core_reports_core_missing() {
// Browse is not implemented yet, but the reader must still fail with a
// stable View code and exit class rather than pretending to work.
fn browse_on_missing_path_fails_without_starting_a_server() {
let cwd = std::env::current_dir().unwrap();
let output = run_view(&[], &cwd, &clean_env());
let stderr = String::from_utf8_lossy(&output.stderr);
assert_eq!(output.status.code(), Some(2), "stderr: {stderr}");
assert!(
stderr.contains("view.unsupported") || stderr.contains("view.core_missing"),
"unexpected diagnostic: {stderr}"
let output = run_view(
&["definitely-missing.mq.md", "--no-open"],
&cwd,
&clean_env(),
);
assert_eq!(output.status.code(), Some(1));
assert!(String::from_utf8_lossy(&output.stderr).contains("view.io"));
}
#[test]
fn degradation_without_core_keeps_prose_readable() {
// The reader must degrade to prose-only with an explicit status, never
// invent semantic annotations or a fake run state.
let project = common::TempProject::new("cli-degrade-no-core");
project.marqdo_project("# @knowledge 标题\n\n正文 **加粗**。\n");
let context = marqdo_view::app::AppContext::open(&project.dir, None).unwrap();
let relative = context.project().entry().relative.clone();
let model = context.load(&relative).unwrap();
assert_eq!(model.source_status.data_value(), "core-unavailable");
assert!(model.semantic.is_none());
assert!(model.document.plain_text().contains("正文"));
assert!(model.status_note.is_some());
}
#[test]
+10 -1
View File
@@ -13,7 +13,11 @@ pub fn view_bin() -> &'static str {
}
pub fn temp_root(name: &str) -> PathBuf {
let dir = PathBuf::from(env!("CARGO_TARGET_TMPDIR")).join(name);
use std::sync::atomic::{AtomicU64, Ordering};
static NEXT: AtomicU64 = AtomicU64::new(0);
let seq = NEXT.fetch_add(1, Ordering::Relaxed);
let dir = PathBuf::from(env!("CARGO_TARGET_TMPDIR"))
.join(format!("{name}-{}-{seq}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).expect("create test temp dir");
dir
@@ -79,6 +83,7 @@ case "$1" in
;;
check)
if [ -f "$dir/check_stderr" ]; then cat "$dir/check_stderr" >&2; fi
if [ -f "$dir/check_json" ]; then cat "$dir/check_json"; fi
emit=""
prev=""
for a in "$@"; do
@@ -126,6 +131,10 @@ esac
std::fs::write(self.dir.join("check_stderr"), stderr).expect("write stderr");
}
pub fn set_check_json(&self, json: &str) {
std::fs::write(self.dir.join("check_json"), json).expect("write check json");
}
pub fn set_analysis(&self, analysis: &str) {
std::fs::write(self.dir.join("analysis.json"), analysis).expect("write analysis");
}
+50 -20
View File
@@ -7,7 +7,7 @@
mod common;
use common::{minimal_analysis, sha256_hex, FakeCore, TempProject};
use marqdo_view::core_client::{CheckOptions, CoreClient, RunOptions};
use marqdo_view::core_client::{CheckOptions, CheckResponse, CoreClient, RunOptions};
use marqdo_view::project::Project;
fn fixture(name: &str) -> (TempProject, FakeCore) {
@@ -27,9 +27,11 @@ fn check_returns_exact_analysis_bytes_and_digest() {
let client = CoreClient::with_bin(&core.script).unwrap();
let project = Project::open(&project.path("index.mq.md")).unwrap();
let entry = project.entry().relative.clone();
let output = client
.check(&project, &entry, &CheckOptions::default())
.unwrap();
let output = expect_check_ok(
client
.check(&project, &entry, &CheckOptions::default())
.unwrap(),
);
assert_eq!(output.analysis_bytes, analysis.as_bytes());
assert_eq!(output.analysis_sha256, sha256_hex(analysis.as_bytes()));
@@ -52,16 +54,18 @@ fn check_refs_is_forwarded_as_a_stricter_flag() {
let client = CoreClient::with_bin(&core.script).unwrap();
let project = Project::open(&project.path("index.mq.md")).unwrap();
let entry = project.entry().relative.clone();
client
.check(
&project,
&entry,
&CheckOptions {
refs: true,
timeout: None,
},
)
.unwrap();
expect_check_ok(
client
.check(
&project,
&entry,
&CheckOptions {
refs: true,
timeout: None,
},
)
.unwrap(),
);
assert!(core.last_args().contains(&"--refs".to_string()));
}
@@ -72,13 +76,12 @@ fn check_failure_preserves_core_stderr_and_code() {
let client = CoreClient::with_bin(&core.script).unwrap();
let project = Project::open(&project.path("index.mq.md")).unwrap();
let entry = project.entry().relative.clone();
let err = client
let response = client
.check(&project, &entry, &CheckOptions::default())
.unwrap_err();
assert_eq!(err.code(), "view.analysis_failed");
assert_eq!(err.exit_code(), 1);
let text = err.to_string();
assert!(text.contains("sem.unclosed_control"), "{text}");
.unwrap();
assert!(!response.success);
assert_eq!(response.exit_code, 1);
assert!(response.stderr.contains("sem.unclosed_control"));
}
#[test]
@@ -193,6 +196,33 @@ fn missing_emit_after_success_is_an_analysis_failure() {
assert_eq!(err.code(), "view.analysis_failed");
}
fn expect_check_ok(response: CheckResponse) -> marqdo_view::core_client::CheckOutput {
assert!(response.success, "check failed: {:?}", response.diagnostics);
response.analysis.expect("analysis on success")
}
#[test]
fn failed_check_normalizes_diagnostics_without_absolute_paths() {
let (project, core) = fixture("check_diagnostics");
core.set_check(1, "");
core.set_check_json(
r#"{"command":"check","success":false,"errors":1,"diagnostics":[{"code":"sem.unclosed_control","column":1,"file":"/home/secret/project/index.mq.md","hints":[],"line":5,"message":"`if` is not closed by `end`","module":"root:fixture@0.1.0::index.mq.md","severity":"error"}]}"#,
);
let client = CoreClient::with_bin(&core.script).unwrap();
let project = Project::open(&project.path("index.mq.md")).unwrap();
let entry = project.entry().relative.clone();
let response = client
.check(&project, &entry, &CheckOptions::default())
.unwrap();
assert!(!response.success);
assert_eq!(response.diagnostics.len(), 1);
assert_eq!(response.diagnostics[0].code, "sem.unclosed_control");
assert_eq!(response.diagnostics[0].line, Some(5));
// The raw absolute `file` field is not part of the normalized type at all.
let rendered = serde_json::to_string(&response.diagnostics).unwrap();
assert!(!rendered.contains("/home/secret"), "{rendered}");
}
#[test]
fn cli_verify_end_to_end_against_fake_core() {
let (project, core) = fixture("verify_cli");
+29
View File
@@ -0,0 +1,29 @@
# Protocol goldens
These Analysis v2 files were emitted by the **frozen** `marqdo` CLI release
binary, not hand-written:
| Binary | SHA-256 |
|---|---|
| `marqdo 3.0.0-beta.1` | `062cb56e226bee55c21d238e195920caa985e62bb3877ba7b07abcc04dc0fe3f` |
| CLI source SHA | `2c7c4f31e7a388d3fcfa717a77067e696ed13854` |
Command shape used for every golden:
```bash
"$MARQDO_BIN" check <example> --emit tests/golden/analysis-v2/<name>.json
```
| Golden | Input |
|---|---|
| `mixed-modes.json` | `examples/mixed-modes/index.mq.md` |
| `control-flow.json` | `examples/control-flow/index.mq.md` |
| `tables-math.json` | `examples/tables-math/index.mq.md` |
| `welcome.json` | `examples/welcome/00-welcome.mq.md` |
`tools/gen-golden.sh` regenerates them from a frozen binary. If an example's
bytes change, its `source_digest` changes too and the tests will fail until the
golden is regenerated — that is intentional evidence, not a test bug.
`examples/diagnostics/index.mq.md` is deliberately invalid and has **no**
golden; its failure path is covered with `check --json` output.
File diff suppressed because it is too large. Load diff
+278
View File
@@ -0,0 +1,278 @@
{
"diagnostics": [],
"modules": [
{
"calls": [],
"functions": [
{
"body": [
{
"arms": [
{
"body": [
{
"kind": "assign",
"span": {
"end": 422,
"start": 406
},
"target": "result",
"value": {
"kind": "binary",
"left": {
"kind": "variable",
"name": "n",
"span": {
"end": 417,
"start": 416
}
},
"op": "mul",
"right": {
"kind": "literal",
"span": {
"end": 0,
"start": 0
},
"type": "int",
"value": "2"
},
"span": {
"end": 421,
"start": 416
}
}
},
{
"kind": "return",
"span": {
"end": 439,
"start": 424
},
"value": {
"kind": "variable",
"name": "result",
"span": {
"end": 438,
"start": 432
}
}
}
],
"condition": {
"kind": "binary",
"left": {
"kind": "variable",
"name": "n",
"span": {
"end": 398,
"start": 397
}
},
"op": "gt",
"right": {
"kind": "literal",
"span": {
"end": 0,
"start": 0
},
"type": "int",
"value": "0"
},
"span": {
"end": 402,
"start": 397
}
},
"condition_span": {
"end": 404,
"start": 392
},
"span": {
"end": 404,
"start": 392
}
},
{
"body": [
{
"kind": "return",
"span": {
"end": 461,
"start": 451
},
"value": {
"kind": "literal",
"span": {
"end": 0,
"start": 0
},
"type": "int",
"value": "0"
}
}
],
"condition": {
"kind": "literal",
"span": {
"end": 0,
"start": 0
},
"type": "bool",
"value": true
},
"condition_span": {
"end": 404,
"start": 392
},
"span": {
"end": 404,
"start": 392
}
}
],
"kind": "branch",
"span": {
"end": 404,
"start": 392
}
}
],
"effects": [
"unknown"
],
"heading_span": {
"end": 259,
"start": 246
},
"id": "root:mixed-modes@0.1.0::index.mq.md::演示.main",
"local_name": "main",
"namespace": "演示",
"signature": {
"kind": "explicit",
"params": [
{
"default": null,
"name": "n",
"required": true,
"span": {
"end": 274,
"start": 268
},
"type": "Int"
}
]
},
"span": {
"end": 470,
"start": 246
},
"unit_id": "root:mixed-modes@0.1.0::index.mq.md#演示/main"
}
],
"id": "root:mixed-modes@0.1.0::index.mq.md",
"imports": [],
"package_instance_id": "root:mixed-modes@0.1.0",
"references": [],
"relative_path": "index.mq.md",
"resources": [],
"source_digest": "c5fed57a716e06a29b669c334d475ec03bf08442e27983451ec8dd791dc999ea",
"units": [
{
"function": null,
"id": "root:mixed-modes@0.1.0::index.mq.md#",
"kind": "root",
"level": 0,
"name": "",
"span": {
"end": 470,
"start": 0
}
},
{
"function": null,
"id": "root:mixed-modes@0.1.0::index.mq.md#计算笔记",
"kind": "namespace",
"level": 1,
"name": "计算笔记",
"span": {
"end": 25,
"start": 0
}
},
{
"function": null,
"id": "root:mixed-modes@0.1.0::index.mq.md#计算笔记/算法说明",
"kind": "knowledge",
"level": 2,
"name": "算法说明",
"span": {
"end": 149,
"start": 123
}
},
{
"function": null,
"id": "root:mixed-modes@0.1.0::index.mq.md#演示",
"kind": "namespace",
"level": 1,
"name": "演示",
"span": {
"end": 244,
"start": 230
}
},
{
"function": "root:mixed-modes@0.1.0::index.mq.md::演示.main",
"id": "root:mixed-modes@0.1.0::index.mq.md#演示/main",
"kind": "function",
"level": 2,
"name": "main",
"span": {
"end": 259,
"start": 246
}
},
{
"function": null,
"id": "root:mixed-modes@0.1.0::index.mq.md#演示/main/用法",
"kind": "section",
"level": 3,
"name": "用法",
"span": {
"end": 300,
"start": 279
}
},
{
"function": "root:mixed-modes@0.1.0::index.mq.md::演示.main",
"id": "root:mixed-modes@0.1.0::index.mq.md#演示/main/计算",
"kind": "section",
"level": 3,
"name": "计算",
"span": {
"end": 390,
"start": 374
}
}
]
}
],
"producer": {
"markdown_profile": "marqdo.md.v1",
"name": "marqdo",
"version": "3.0.0-beta.1"
},
"project": {
"identity_kind": "manifest",
"lock_digest": "",
"root_id": "root:mixed-modes@0.1.0",
"stdlib": {
"digest": "sha256:5407d3665ba2fe105820d0f1af5efaafa10c277a69eb819c3225719813c8c713",
"instance_id": "std:marqdo-stdlib@0.1.0#5407d3665ba2fe105820d0f1af5efaafa10c277a69eb819c3225719813c8c713",
"version": "0.1.0"
}
},
"schema": "marqdo.analysis",
"schema_version": 2
}
+108
View File
@@ -0,0 +1,108 @@
{
"diagnostics": [],
"modules": [
{
"calls": [],
"functions": [],
"id": "root:tables-math@0.1.0::index.mq.md",
"imports": [],
"package_instance_id": "root:tables-math@0.1.0",
"references": [
{
"source": "root:tables-math@0.1.0::index.mq.md",
"span": {
"end": 403,
"start": 354
},
"state": "external",
"target_module": null,
"target_unit": null,
"url": "https://github.com/cflmy/marqdo-cli"
}
],
"relative_path": "index.mq.md",
"resources": [
{
"content_digest": "2820951a377c18ce3e89093ca7c31c204b1196a7e571781c6080f8207524a8dc",
"display": false,
"id": "root:tables-math@0.1.0::index.mq.md#resource:formula-1",
"kind": "formula",
"language": null,
"module_id": "root:tables-math@0.1.0::index.mq.md",
"span": {
"end": 164,
"start": 154
},
"unit_id": "root:tables-math@0.1.0::index.mq.md#表格、公式与惰性资源"
},
{
"content_digest": "8b1e8a7ed159e8223af79e768681907870ae7143f0b16001091377f9ff018db2",
"display": true,
"id": "root:tables-math@0.1.0::index.mq.md#resource:formula-2",
"kind": "formula",
"language": null,
"module_id": "root:tables-math@0.1.0::index.mq.md",
"span": {
"end": 222,
"start": 181
},
"unit_id": "root:tables-math@0.1.0::index.mq.md#表格、公式与惰性资源"
},
{
"content_digest": "a0d49e456637468d7f594f4e2bb513321875855c1fe85d28e0ca62f1e9180d15",
"id": "root:tables-math@0.1.0::index.mq.md#resource:code-1",
"kind": "code",
"language": "python",
"module_id": "root:tables-math@0.1.0::index.mq.md",
"span": {
"end": 280,
"start": 224
},
"unit_id": "root:tables-math@0.1.0::index.mq.md#表格、公式与惰性资源"
}
],
"source_digest": "66ce180252d201ff0f3f831d47f7a58d7f6804cb9655898cc80ef6d2262f1ce6",
"units": [
{
"function": null,
"id": "root:tables-math@0.1.0::index.mq.md#",
"kind": "root",
"level": 0,
"name": "",
"span": {
"end": 406,
"start": 0
}
},
{
"function": null,
"id": "root:tables-math@0.1.0::index.mq.md#表格、公式与惰性资源",
"kind": "namespace",
"level": 1,
"name": "表格、公式与惰性资源",
"span": {
"end": 43,
"start": 0
}
}
]
}
],
"producer": {
"markdown_profile": "marqdo.md.v1",
"name": "marqdo",
"version": "3.0.0-beta.1"
},
"project": {
"identity_kind": "manifest",
"lock_digest": "",
"root_id": "root:tables-math@0.1.0",
"stdlib": {
"digest": "sha256:5407d3665ba2fe105820d0f1af5efaafa10c277a69eb819c3225719813c8c713",
"instance_id": "std:marqdo-stdlib@0.1.0#5407d3665ba2fe105820d0f1af5efaafa10c277a69eb819c3225719813c8c713",
"version": "0.1.0"
}
},
"schema": "marqdo.analysis",
"schema_version": 2
}
+69
View File
@@ -0,0 +1,69 @@
{
"diagnostics": [],
"modules": [
{
"calls": [],
"functions": [],
"id": "root:welcome-demo@0.1.0::00-welcome.mq.md",
"imports": [],
"package_instance_id": "root:welcome-demo@0.1.0",
"references": [
{
"source": "root:welcome-demo@0.1.0::00-welcome.mq.md",
"span": {
"end": 536,
"start": 507
},
"state": "resolved",
"target_module": "root:welcome-demo@0.1.0::guide.mq.md",
"target_unit": null,
"url": "./guide.mq.md"
}
],
"relative_path": "00-welcome.mq.md",
"resources": [],
"source_digest": "879215bf0dc432b78924800a08eac37d353a9694652c5542294f4ce7fe6da173",
"units": [
{
"function": null,
"id": "root:welcome-demo@0.1.0::00-welcome.mq.md#",
"kind": "root",
"level": 0,
"name": "",
"span": {
"end": 659,
"start": 0
}
},
{
"function": null,
"id": "root:welcome-demo@0.1.0::00-welcome.mq.md#欢迎来到 Marqdo",
"kind": "namespace",
"level": 1,
"name": "欢迎来到 Marqdo",
"span": {
"end": 32,
"start": 0
}
}
]
}
],
"producer": {
"markdown_profile": "marqdo.md.v1",
"name": "marqdo",
"version": "3.0.0-beta.1"
},
"project": {
"identity_kind": "manifest",
"lock_digest": "",
"root_id": "root:welcome-demo@0.1.0",
"stdlib": {
"digest": "sha256:5407d3665ba2fe105820d0f1af5efaafa10c277a69eb819c3225719813c8c713",
"instance_id": "std:marqdo-stdlib@0.1.0#5407d3665ba2fe105820d0f1af5efaafa10c277a69eb819c3225719813c8c713",
"version": "0.1.0"
}
},
"schema": "marqdo.analysis",
"schema_version": 2
}
+230
View File
@@ -0,0 +1,230 @@
//! Live server smoke tests over a raw TCP HTTP/1.1 client (no extra deps).
//! The server is a real child process so startup, URL output, routing and
//! security headers are all exercised end to end.
mod common;
use common::{run_view, FakeCore};
use std::io::{BufRead, BufReader, Read, Write};
use std::net::TcpStream;
use std::process::{Child, Command, Stdio};
use std::time::{Duration, Instant};
struct LiveServer {
child: Child,
port: u16,
_core: FakeCore,
}
impl Drop for LiveServer {
fn drop(&mut self) {
let _ = self.child.kill();
let _ = self.child.wait();
}
}
fn start_server() -> LiveServer {
use std::sync::atomic::{AtomicUsize, Ordering};
static NEXT: AtomicUsize = AtomicUsize::new(0);
let seq = NEXT.fetch_add(1, Ordering::Relaxed);
let repo_root = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"));
let core = FakeCore::new(&format!("live-core-{seq}"));
let golden = std::fs::read(repo_root.join("tests/golden/analysis-v2/welcome.json")).unwrap();
core.set_analysis(std::str::from_utf8(&golden).unwrap());
let mut child = Command::new(common::view_bin())
.current_dir(&repo_root)
.args([
"examples/welcome",
"--port",
"0",
"--no-open",
"--marqdo-bin",
])
.arg(&core.script)
.env_remove("MARQDO_BIN")
.env_remove("MARQDO_TOOL_PROTOCOL")
.env_remove("MARQDO_PROTOCOL_ANALYSIS")
.env_remove("MARQDO_PROTOCOL_TRACE")
.stdout(Stdio::null())
.stderr(Stdio::piped())
.spawn()
.expect("spawn marqdo-view");
let stderr = child.stderr.take().expect("piped stderr");
let mut reader = BufReader::new(stderr);
let deadline = Instant::now() + Duration::from_secs(10);
let mut url: Option<String> = None;
while Instant::now() < deadline {
let mut line = String::new();
if reader.read_line(&mut line).unwrap_or(0) == 0 {
break;
}
if let Some(rest) = line.trim().strip_prefix("marqdo view: ") {
url = Some(rest.to_string());
break;
}
}
let url = url.expect("server printed its URL");
let port: u16 = url
.trim_end_matches('/')
.rsplit(':')
.next()
.expect("port in url")
.parse()
.expect("numeric port");
// Keep draining stderr so the child never blocks on a full pipe.
std::thread::spawn(move || {
let mut sink = String::new();
let _ = reader.read_to_string(&mut sink);
});
LiveServer {
child,
port,
_core: core,
}
}
struct HttpResponse {
status: u16,
headers: String,
body: String,
}
fn http_get(port: u16, host: Option<&str>, path: &str) -> HttpResponse {
let mut stream = TcpStream::connect(("127.0.0.1", port)).expect("connect");
let host = host
.map(str::to_string)
.unwrap_or_else(|| format!("127.0.0.1:{port}"));
let request =
format!("GET {path} HTTP/1.1\r\nHost: {host}\r\nConnection: close\r\nAccept: */*\r\n\r\n");
stream.write_all(request.as_bytes()).expect("write request");
let mut raw = Vec::new();
stream.read_to_end(&mut raw).expect("read response");
let text = String::from_utf8_lossy(&raw).to_string();
let (head, body) = text.split_once("\r\n\r\n").unwrap_or((&text, ""));
let status = head
.lines()
.next()
.and_then(|line| line.split_whitespace().nth(1))
.and_then(|code| code.parse().ok())
.unwrap_or(0);
HttpResponse {
status,
headers: head.to_string(),
body: body.to_string(),
}
}
#[test]
fn live_server_serves_pages_assets_and_health() {
let server = start_server();
let page = http_get(server.port, None, "/");
assert_eq!(page.status, 200);
assert!(page.headers.contains("Content-Type: text/html"));
assert!(page.headers.contains("Content-Security-Policy"));
assert!(page.headers.contains("X-Content-Type-Options: nosniff"));
assert!(page.body.contains("mq-reader"));
assert!(page.body.contains("欢迎来到 Marqdo"));
assert!(!page.body.contains("data-live=\"false\""));
// CSRF token meta is present for the future explicit-run API.
assert!(page.body.contains("mq-csrf-token"));
let css_path = page
.body
.split("href=\"/assets/")
.nth(1)
.and_then(|rest| rest.split('"').next())
.expect("css link");
let css = http_get(server.port, None, &format!("/assets/{css_path}"));
assert_eq!(css.status, 200);
assert!(css.headers.contains("text/css"));
assert!(css.body.contains("@layer tokens"));
assert!(css.headers.contains("immutable"));
let health = http_get(server.port, None, "/api/health");
assert_eq!(health.status, 200);
assert!(health.body.contains("\"schema\": \"marqdo.view-health\""));
assert!(health.body.contains("\"analysis\": 2"));
let document = http_get(server.port, None, "/file?path=guide.mq.md");
assert_eq!(document.status, 200);
assert!(document.body.contains("阅读指南"));
}
#[test]
fn live_server_rejects_dns_rebinding_and_path_escape() {
let server = start_server();
let bad_host = http_get(server.port, Some("attacker.example"), "/");
assert_eq!(bad_host.status, 400);
for path in [
"/file?path=../secret.mq.md",
"/file?path=%2e%2e%2fsecret.mq.md",
"/file?path=/etc/passwd",
"/file?path=..%2f..%2fetc%2fpasswd",
] {
let response = http_get(server.port, None, path);
assert!(
response.status == 403 || response.status == 404,
"path {path} returned {}",
response.status
);
}
let missing = http_get(server.port, None, "/file?path=missing.mq.md");
assert_eq!(missing.status, 404);
let unknown = http_get(server.port, None, "/api/run");
assert_eq!(unknown.status, 404);
}
#[test]
fn live_server_rejects_unknown_methods_and_bad_assets() {
let server = start_server();
// POST is not exposed yet.
let mut stream = TcpStream::connect(("127.0.0.1", server.port)).expect("connect");
let request = format!(
"POST /api/run HTTP/1.1\r\nHost: 127.0.0.1:{}\r\nContent-Type: application/json\r\nContent-Length: 2\r\nConnection: close\r\n\r\n{{}}",
server.port
);
stream.write_all(request.as_bytes()).unwrap();
let mut raw = Vec::new();
stream.read_to_end(&mut raw).unwrap();
let text = String::from_utf8_lossy(&raw);
assert!(text.starts_with("HTTP/1.1 405"), "{text}");
let bad_asset = http_get(server.port, None, "/assets/../../etc/passwd");
assert_eq!(bad_asset.status, 404);
}
#[test]
fn cli_verify_output_contract_still_holds_for_installed_style_invocation() {
// Regression guard: `view verify` must remain a pure static check.
let repo_root = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"));
let core = FakeCore::new("verify-core-contract");
let golden = std::fs::read(repo_root.join("tests/golden/analysis-v2/welcome.json")).unwrap();
core.set_analysis(std::str::from_utf8(&golden).unwrap());
let output = run_view(
&[
"verify",
"examples/welcome/00-welcome.mq.md",
"--json",
"--marqdo-bin",
core.script.to_str().unwrap(),
],
&repo_root,
&[("MARQDO_BIN", None)],
);
assert_eq!(
output.status.code(),
Some(0),
"stderr: {}",
String::from_utf8_lossy(&output.stderr)
);
let json: serde_json::Value = serde_json::from_slice(&output.stdout).expect("json output");
assert_eq!(json["result"], "PASS");
assert_eq!(json["executed"], false);
assert_eq!(json["analysis"]["schema_version"], 2);
}
+2 -2
View File
@@ -135,8 +135,8 @@ fn exactly_one_reader_theme_and_script_entry() {
let mut js = Vec::new();
collect_files(&assets, "css", &mut css);
collect_files(&assets, "js", &mut js);
assert!(css.len() <= 1, "more than one CSS entry: {css:?}");
assert!(js.len() <= 1, "more than one JS entry: {js:?}");
assert_eq!(css.len(), 1, "exactly one CSS entry: {css:?}");
assert_eq!(js.len(), 1, "exactly one JS entry: {js:?}");
for path in &css {
assert_eq!(
path.file_name().and_then(|n| n.to_str()),
+250
View File
@@ -0,0 +1,250 @@
//! Rendering contract tests: one renderer, safe Markdown, exact source view,
//! verified semantic annotations and Live/Export link differences.
mod common;
use marqdo_view::document::{DocumentIdentity, DocumentModel};
use marqdo_view::presentation::{self, BuildInput, Navigation, SourceStatus};
use marqdo_view::project::{Project, SafeRelativePath, ViewConfig};
use marqdo_view::render::{ReaderRenderer, RenderContext};
use marqdo_view::semantic;
fn example(name: &str) -> (marqdo_view::presentation::PresentationModel, String) {
let root = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"))
.join("examples")
.join(name);
let project = Project::open(&root).unwrap();
let entry = project.entry().relative.clone();
let source = project.read_source_text(&entry).unwrap();
let document = DocumentModel::parse(source.clone(), DocumentIdentity::placeholder(&entry));
let golden_name = name;
let golden = std::fs::read(
std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"))
.join("tests/golden/analysis-v2")
.join(format!("{golden_name}.json")),
)
.unwrap_or_else(|err| panic!("missing golden for {name}: {err}"));
let verified =
semantic::verify_analysis(&golden, &source, &document.source_index, entry.as_str())
.unwrap_or_else(|err| panic!("golden does not verify for {name}: {err}"));
let config = ViewConfig::load(project.root()).unwrap_or_default();
let navigation = Navigation::from_project(&project, &config, &entry);
let model = presentation::build(BuildInput {
document,
analysis: Some(&verified),
status: SourceStatus::StaticOk,
status_note: None,
diagnostics: Vec::new(),
navigation,
core_version: Some("3.0.0-beta.1".to_string()),
});
(model, source)
}
fn render_live(model: &marqdo_view::presentation::PresentationModel) -> String {
ReaderRenderer::new()
.render(model, &RenderContext::live())
.html
}
fn render_static(model: &marqdo_view::presentation::PresentationModel, depth: usize) -> String {
ReaderRenderer::new()
.render(model, &RenderContext::static_site(depth))
.html
}
fn heading_ids(html: &str) -> Vec<String> {
let mut ids = Vec::new();
for part in html.split("<h").skip(1) {
let Some(after_tag) = part.split_once(' ') else {
continue;
};
let rest = after_tag.1;
if let Some(id_part) = rest.split_once("id=\"") {
if let Some((id, _)) = id_part.1.split_once('"') {
ids.push(id.to_string());
}
}
}
ids
}
#[test]
fn page_has_exactly_one_theme_and_one_script() {
let (model, _) = example("mixed-modes");
let html = render_live(&model);
assert_eq!(html.matches("<link rel=\"stylesheet\"").count(), 1);
assert_eq!(
html.matches("<script").count(),
1,
"no inline scripts allowed"
);
assert!(html.contains("<script defer src=\"/assets/reader."));
assert!(html.contains("Content-Security-Policy"));
assert!(html.contains("default-src 'none'"));
assert!(html.contains("data-live=\"true\""));
// The one source of prose is the Markdown document itself.
assert!(html.contains("计算笔记"));
assert!(html.contains("静态阅读"));
}
#[test]
fn semantic_annotations_come_from_analysis_and_are_unique() {
let (model, _) = example("mixed-modes");
let html = render_live(&model);
assert!(html.contains("data-source-status=\"static-ok\""));
assert!(html.contains("data-statement-kind=\"return\""));
assert!(html.contains("data-statement-kind=\"branch\""));
assert!(html.contains("data-statement-kind=\"assign\""));
assert!(html.contains("mq-mode-badge"));
assert!(html.contains("EXEC"));
assert!(html.contains("params(n: Int)"));
let ids = heading_ids(&html);
let mut deduped = ids.clone();
deduped.sort();
deduped.dedup();
assert_eq!(ids.len(), deduped.len(), "duplicate heading ids: {ids:?}");
}
#[test]
fn tables_math_and_code_are_inert_and_readable() {
let (model, source) = example("tables-math");
let html = render_live(&model);
assert!(html.contains("<table>"));
assert!(html.contains("mq-table-wrap"));
assert!(html.contains("mq-math-block"));
assert!(html.contains("代码围栏永远是惰性资源"));
assert!(html.contains("mq-codeblock"));
// Inert resources are never executed: no run controls are enabled.
assert!(html.contains("data-live=\"true\""));
assert!(!html.contains("RUNNING"));
// Source is preserved exactly in the textarea (escaped only).
assert!(source.contains("```python"));
assert!(html.contains("mq-raw-source"));
}
#[test]
fn welcome_hero_only_when_configured() {
let (welcome, _) = example("welcome");
let html = render_live(&welcome);
assert!(welcome.navigation.welcome);
assert!(html.contains("mq-welcome"));
assert!(html.contains("WELCOME TO"));
assert!(html.contains("代码即文档 · 文档即知识库 · 知识即可执行"));
let (ordinary, _) = example("tables-math");
let html = render_live(&ordinary);
assert!(!ordinary.navigation.welcome);
assert!(!html.contains("mq-welcome"));
}
#[test]
fn live_and_static_share_content_but_rewrite_links() {
let (model, _) = example("welcome");
let live = render_live(&model);
let static_site = render_static(&model, 0);
assert!(live.contains("/file?path=guide.mq.md"));
assert!(static_site.contains("pages/guide.mq.md.html"));
assert!(!static_site.contains("/file?path="));
// Same prose and semantics.
for needle in ["欢迎来到 Marqdo", "代码即文档", "mq-document"] {
assert!(live.contains(needle));
assert!(static_site.contains(needle));
}
// Assets are relative from the site root.
assert!(static_site.contains("href=\"assets/reader."));
assert!(live.contains("href=\"/assets/reader."));
}
#[test]
fn static_pages_use_parent_relative_assets_and_links() {
let (model, _) = example("welcome");
let html = render_static(&model, 1);
assert!(html.contains("href=\"../assets/reader."));
assert!(html.contains("../pages/guide.mq.md.html"));
}
#[test]
fn malicious_markdown_cannot_inject_markup_or_scripts() {
let source = r#"# 安全测试
<script>alert('xss')</script>
<img src=x onerror="alert(1)">
[危险链接](javascript:alert(1))
[数据链接](data:text/html;base64,PHNjcmlwdD4=)
[正常链接](https://example.com/ok)
<svg onload="alert(1)"></svg>
正常 **正文** 与 `代码`。
"#
.to_string();
let document = DocumentModel::parse(
source,
DocumentIdentity {
project_root_id: String::new(),
module_id: String::new(),
relative_path: "index.mq.md".into(),
source_sha256: String::new(),
},
);
let project = Project::open(
&std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("examples/tables-math"),
)
.unwrap();
let config = ViewConfig::default();
let navigation = Navigation::from_project(
&project,
&config,
&SafeRelativePath::parse("index.mq.md").unwrap(),
);
let model = presentation::build(BuildInput {
document,
analysis: None,
status: SourceStatus::CoreUnavailable,
status_note: Some("test".into()),
diagnostics: Vec::new(),
navigation,
core_version: None,
});
let html = render_live(&model);
assert!(!html.contains("<script>alert"));
assert!(!html.contains("<img src=x"));
assert!(!html.contains("<svg onload"));
assert!(!html.contains("href=\"javascript:"));
assert!(!html.contains("href=\"data:text/html"));
// Ordinary page chrome (logo, dock icons) is allowed, but no tag carries an
// attacker-supplied event handler.
assert!(!html.contains("onerror=\"") && !html.contains("onload=\""));
// The exact source is still available in the source pane, safely escaped.
assert!(html.contains("&lt;script&gt;alert"));
assert!(html.contains("https://example.com/ok"));
assert!(html.contains("已忽略原始 HTML"));
assert!(html.contains("正文"));
}
#[test]
fn rendering_is_deterministic() {
let (model, _) = example("control-flow");
let first = render_live(&model);
let second = render_live(&model);
assert_eq!(first, second);
}
#[test]
fn run_controls_are_explicitly_unavailable_before_pr04() {
let (model, _) = example("control-flow");
let html = render_live(&model);
assert!(html.contains("data-live=\"true\""));
assert!(
html.contains("data-disabled=\"true\"") || html.contains("aria-disabled"),
"run control must have an explicit disabled marker"
);
// No fake RUNNING/SUCCEEDED marker on a freshly opened document.
assert!(!html.contains("data-run-state=\"running\""));
assert!(!html.contains("data-run-state=\"succeeded\""));
}