217 lines
9.5 KiB
Bash
Executable File
217 lines
9.5 KiB
Bash
Executable File
#!/usr/bin/env bash
|
|
# Static export acceptance: pure read-only, offline assets, safe paths.
|
|
# One renderer for Live and Export; no execution, no network.
|
|
#
|
|
# Usage: MARQDO_BIN=/abs/path/marqdo scripts/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)"
|
|
|
|
if [[ "${VIEW_USE_INSTALLED_TOOL:-0}" == 1 ]]; then
|
|
view=("$MARQDO_BIN" view)
|
|
else
|
|
binary="$repo_root/target/release/marqdo-view"
|
|
[[ -x "$binary" ]] || cargo build --release --locked
|
|
view=("$binary")
|
|
fi
|
|
|
|
site="$repo_root/dist/test-export-site"
|
|
rm -rf "$site"
|
|
MARQDO_BIN="$MARQDO_BIN" "${view[@]}" 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'<link rel="stylesheet" href="assets/reader\.[0-9a-f]{16}\.css"', index)
|
|
for pattern in ("<script src=\"http", "<link rel=\"stylesheet\" href=\"http", "url(http"):
|
|
assert pattern not in index, pattern
|
|
print("export manifest: PASS (%d pages, %d files)" % (len(manifest["pages"]), len(manifest["files"])))
|
|
PY
|
|
|
|
# #15: import an actual completed run. Rename its sentinel before exporting so
|
|
# a second execution would leave a new file at the original path.
|
|
result_work="$(mktemp -d "$repo_root/dist/import-observation.XXXXXX")"
|
|
trap 'rm -rf "$result_work"' EXIT
|
|
mkdir "$result_work/project"
|
|
cp examples/unsafe-side-effect.mq.md "$result_work/project/index.mq.md"
|
|
(cd "$result_work/project" && "$MARQDO_BIN" run index.mq.md --mode project \
|
|
--allow-write out --allow-write 'out/**' --output json > "$result_work/run.json")
|
|
mv "$result_work/project/out/view-sentinel.txt" "$result_work/once.txt"
|
|
run_id="$(python3 -c 'import json,sys; print(json.load(open(sys.argv[1]))["run"]["id"])' "$result_work/run.json")"
|
|
entry="$result_work/project/index.mq.md"
|
|
"${view[@]}" export "$entry" --out "$result_work/site" --observation "$result_work/run.json" --run-id "$run_id"
|
|
|
|
python3 - "$result_work" <<'PY'
|
|
import hashlib
|
|
import json
|
|
import pathlib
|
|
import sys
|
|
|
|
work = pathlib.Path(sys.argv[1])
|
|
snapshot_bytes = (work / 'run.json').read_bytes()
|
|
observation = json.loads(snapshot_bytes)
|
|
manifest = json.loads((work / 'site/manifest.json').read_text())
|
|
execution = manifest['execution']
|
|
assert manifest['executed_during_export'] is False
|
|
assert execution['core_run_id'] == observation['run']['id']
|
|
assert execution['observation_sha256'] == hashlib.sha256(snapshot_bytes).hexdigest()
|
|
assert execution['source_verified'] and execution['status'] == 'succeeded'
|
|
assert execution['terminal_at'] is None
|
|
assert manifest['source']['analysis_digest'] == observation['run']['source']['analysis_digest']
|
|
assert b'<script' not in (work / 'site/index.html').read_bytes()
|
|
observation['events'].pop()
|
|
observation['run']['status'] = 'incomplete'
|
|
(work / 'incomplete.json').write_text(json.dumps(observation))
|
|
PY
|
|
|
|
reject_import() {
|
|
local observation="$1" selected_id="$2" error_code="$3"
|
|
if "${view[@]}" export "$entry" --out "$result_work/invalid" \
|
|
--observation "$observation" --run-id "$selected_id" > "$result_work/rejection.log" 2>&1; then
|
|
echo 'error: invalid Observation was accepted' >&2
|
|
return 1
|
|
fi
|
|
grep -Fq "$error_code" "$result_work/rejection.log"
|
|
test ! -e "$result_work/invalid"
|
|
}
|
|
reject_import "$result_work/run.json" "wrong-run" 'view.export_invalid'
|
|
reject_import "$result_work/incomplete.json" "$run_id" 'view.export_invalid'
|
|
(cd "$result_work/project" && "$MARQDO_BIN" run index.mq.md --mode project \
|
|
--allow-write out --allow-write 'out/**' --observe-max-events 1 --output json > "$result_work/truncated.json")
|
|
mv "$result_work/project/out/view-sentinel.txt" "$result_work/truncated-once.txt"
|
|
truncated_id="$(python3 -c 'import json,sys; print(json.load(open(sys.argv[1]))["run"]["id"])' "$result_work/truncated.json")"
|
|
reject_import "$result_work/truncated.json" "$truncated_id" 'view.export_invalid'
|
|
printf '\n文稿已修改。\n' >> "$entry"
|
|
reject_import "$result_work/run.json" "$run_id" 'view.observation_stale'
|
|
test ! -e "$result_work/project/out/view-sentinel.txt"
|
|
echo 'Observation export: PASS (real CLI, selected run, stale/incomplete/truncated refusal, zero re-execution)'
|
|
|
|
# #16: embed both an analyzed document and ordinary Markdown through the same
|
|
# release binary. No project sibling or blocked media should enter the package.
|
|
embed_work="$result_work/embed"
|
|
mkdir -p "$embed_work/project"
|
|
python3 - "$embed_work" <<'PY'
|
|
import pathlib
|
|
import struct
|
|
import sys
|
|
import zlib
|
|
|
|
work = pathlib.Path(sys.argv[1])
|
|
project = work / 'project'
|
|
wide = 'long' * 100
|
|
body = f'''\n阅读正文含有公式 $r^2$ 与 [跳到详情](#detail)。
|
|
|
|
  
|
|
|
|
[远程链接](https://example.invalid) [缺失锚点](#missing) [其他文稿](other.mq.md)
|
|
|
|
<script>window.embeddedAttackDetected = true</script>
|
|
|
|
| 文字 | 列 |
|
|
| --- | --- |
|
|
| {wide} | 示例 |
|
|
|
|
```text
|
|
{wide}
|
|
```
|
|
|
|
## Detail
|
|
|
|
> 一段引用。
|
|
'''
|
|
(project / 'index.mq.md').write_text('# @knowledge 阅读\n' + body)
|
|
(project / 'plain.md').write_text('# 阅读\n' + body)
|
|
(project / 'other.mq.md').write_text('# @knowledge 不应打包\n')
|
|
def chunk(name, data):
|
|
return struct.pack('>I', len(data)) + name + data + struct.pack('>I', zlib.crc32(name + data))
|
|
image = (b'\x89PNG\r\n\x1a\n' + chunk(b'IHDR', struct.pack('>IIBBBBB', 1, 1, 8, 2, 0, 0, 0))
|
|
+ chunk(b'IDAT', zlib.compress(b'\x00\xA0\x00\x50')) + chunk(b'IEND', b''))
|
|
(project / 'image.png').write_bytes(image)
|
|
(work / 'outside.png').write_bytes(image)
|
|
(project / 'escape.png').symlink_to('../outside.png')
|
|
PY
|
|
for source in index.mq.md plain.md; do
|
|
document="$embed_work/project/$source"
|
|
document_sha="$(sha256sum "$document" | cut -d' ' -f1)"
|
|
"${view[@]}" export "$document" --out "$embed_work/$source" --embed \
|
|
--theme dark --anchor detail --expect-source-sha256 "$document_sha"
|
|
done
|
|
for option in --anchor --expect-source-sha256; do
|
|
if "${view[@]}" export "$document" --out "$embed_work/invalid" --embed \
|
|
"$option" missing > "$embed_work/rejection.log" 2>&1; then
|
|
echo "error: embedded export accepted invalid $option" >&2
|
|
exit 1
|
|
fi
|
|
grep -Eq 'view\.export_(invalid|source_changed)' "$embed_work/rejection.log"
|
|
test ! -e "$embed_work/invalid"
|
|
done
|
|
|
|
# X-04: open the exported site from file:// in a real browser (offline).
|
|
if [[ -d "$repo_root/tests/browser/node_modules/playwright" ]]; then
|
|
PLAYWRIGHT_BROWSERS_PATH="${PLAYWRIGHT_BROWSERS_PATH:-$repo_root/tests/.cache/pw-browsers}" \
|
|
MQ_FILE="$site/index.html" MQ_RESULT="$result_work/site/index.html" MQ_RUN_ID="$run_id" \
|
|
node - "$repo_root/tests/browser" <<'JS'
|
|
const path = require("path");
|
|
const { chromium } = require(path.join(process.argv[2], "node_modules/playwright"));
|
|
(async () => {
|
|
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");
|
|
await page.context().setOffline(true);
|
|
await page.goto("file://" + process.env.MQ_RESULT, { waitUntil: "load" });
|
|
await page.reload();
|
|
const result = await page.locator(".mq-snapshot").innerText();
|
|
if (!result.includes(process.env.MQ_RUN_ID) || !result.includes("成功")) throw new Error("selected result missing");
|
|
if (external.length || errors.length) throw new Error("offline snapshot requested external resources or reported browser errors");
|
|
console.log("file:// offline browser check: PASS");
|
|
await browser.close();
|
|
})().catch((error) => { console.error(error.message); process.exit(1); });
|
|
JS
|
|
PLAYWRIGHT_BROWSERS_PATH="${PLAYWRIGHT_BROWSERS_PATH:-$repo_root/tests/.cache/pw-browsers}" \
|
|
node tests/browser/embedded.browser.cjs "$embed_work" "${view[@]}"
|
|
else
|
|
echo "note: Playwright not installed; skipped file:// browser check"
|
|
fi
|
|
test ! -e "$result_work/project/out/view-sentinel.txt"
|
|
|
|
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)"
|