feat: render safe local media, MathML and Markdown anchors

This commit is contained in:
cflmy committed 2026-11-24 13:23:35 +08:00
1 parent 37291137eb
commit 07fa0d62a8
16 files changed
+1122 -67

No files matched your search

Generated
+227
View File
@@ -2,6 +2,12 @@
# It is not intended for manual editing.
version = 4
[[package]]
name = "adler2"
version = "2.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa"
[[package]]
name = "anstream"
version = "1.0.0"
@@ -58,12 +64,24 @@ version = "1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d92bec98840b8f03a5ff5413de5293bfcd8bf96467cf5452609f939ec6f5de16"
[[package]]
name = "autocfg"
version = "1.5.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53"
[[package]]
name = "base64"
version = "0.22.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6"
[[package]]
name = "bitflags"
version = "2.13.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06"
[[package]]
name = "block-buffer"
version = "0.10.4"
@@ -73,6 +91,24 @@ dependencies = [
"generic-array",
]
[[package]]
name = "bumpalo"
version = "3.20.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "87a0cf66fd1eb2fb7b822cb78370d82303750809bc6ba855f3f58e517d3238db"
[[package]]
name = "bytemuck"
version = "1.25.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "95832e849adfb21180ccb6826a99da14e5d266ae5c2e668e1602cf234f153797"
[[package]]
name = "byteorder-lite"
version = "0.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8f1fe948ff07f4bd06c30984e69f5b4899c516a3ef74f34df92a2df2ab535495"
[[package]]
name = "caseless"
version = "0.2.2"
@@ -134,6 +170,12 @@ version = "1.1.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e0921b3876b3a1df8a1c9f912e7f94342458022c2e84288015893d83c4d62a79"
[[package]]
name = "color_quant"
version = "1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3d7b894f5411737b7867f4827955924d7c254fc9f4d91a6aad6b097804b1018b"
[[package]]
name = "colorchoice"
version = "1.0.5"
@@ -166,6 +208,15 @@ dependencies = [
"libc",
]
[[package]]
name = "crc32fast"
version = "1.5.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2b929dd2a135771f40afabd1073f85eed59c800b7c61901e5c254270497dad64"
dependencies = [
"cfg-if",
]
[[package]]
name = "crypto-common"
version = "0.1.7"
@@ -198,6 +249,15 @@ version = "2.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "da7c62ceae207dd37ea5b845da6a0696c799f85e97da1ab5b7910be3c1c80223"
[[package]]
name = "fdeflate"
version = "0.3.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1e6853b52649d4ac5c0bd02320cddc5ba956bdb407c4b75a2c6b75bf51500f8c"
dependencies = [
"simd-adler32",
]
[[package]]
name = "fearless_simd"
version = "1.2.0"
@@ -221,6 +281,17 @@ version = "1.5.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "09ded33109e99472f809cb7495544506eea45e366725dacf2a383e184f660456"
[[package]]
name = "flate2"
version = "1.1.11"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "626d4928326b646e70f65ed36fc7cf9f206bdb68a0019ee7c6b4709da4e084c4"
dependencies = [
"crc32fast",
"miniz_oxide 0.9.1",
"zlib-rs",
]
[[package]]
name = "generic-array"
version = "0.14.7"
@@ -231,6 +302,16 @@ dependencies = [
"version_check",
]
[[package]]
name = "gif"
version = "0.13.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4ae047235e33e2829703574b54fdec96bfbad892062d97fed2f76022287de61b"
dependencies = [
"color_quant",
"weezl",
]
[[package]]
name = "heck"
version = "0.5.0"
@@ -243,6 +324,34 @@ version = "1.0.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "df3b46402a9d5adb4c86a0cf463f42e19994e3ee891101b1841f30a545cb49a9"
[[package]]
name = "image"
version = "0.25.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "529feb3e6769d234375c4cf1ee2ce713682b8e76538cb13f9fc23e1400a591e7"
dependencies = [
"bytemuck",
"byteorder-lite",
"color_quant",
"gif",
"image-webp",
"moxcms",
"num-traits",
"png",
"zune-core",
"zune-jpeg",
]
[[package]]
name = "image-webp"
version = "0.2.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "525e9ff3e1a4be2fbea1fdf0e98686a6d98b4d8f937e1bf7402245af1909e8c3"
dependencies = [
"byteorder-lite",
"quick-error",
]
[[package]]
name = "is_terminal_polyfill"
version = "1.70.2"
@@ -274,7 +383,10 @@ dependencies = [
"base64",
"clap",
"comrak",
"image",
"libc",
"pulldown-latex",
"roxmltree",
"semver",
"serde",
"serde_json",
@@ -298,6 +410,45 @@ dependencies = [
"fearless_simd_macros",
]
[[package]]
name = "miniz_oxide"
version = "0.8.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1fa76a2c86f704bdb222d66965fb3d63269ce38518b83cb0575fca855ebb6316"
dependencies = [
"adler2",
"simd-adler32",
]
[[package]]
name = "miniz_oxide"
version = "0.9.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b63fbc4a50860e98e7b2aa7804ded1db5cbc3aff9193adaff57a6931bf7c4b4c"
dependencies = [
"adler2",
"simd-adler32",
]
[[package]]
name = "moxcms"
version = "0.7.11"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ac9557c559cd6fc9867e122e20d2cbefc9ca29d80d027a8e39310920ed2f0a97"
dependencies = [
"num-traits",
"pxfm",
]
[[package]]
name = "num-traits"
version = "0.2.19"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841"
dependencies = [
"autocfg",
]
[[package]]
name = "once_cell_polyfill"
version = "1.70.2"
@@ -343,6 +494,19 @@ dependencies = [
"siphasher",
]
[[package]]
name = "png"
version = "0.18.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "60769b8b31b2a9f263dae2776c37b1b28ae246943cf719eb6946a1db05128a61"
dependencies = [
"bitflags",
"crc32fast",
"fdeflate",
"flate2",
"miniz_oxide 0.8.9",
]
[[package]]
name = "proc-macro2"
version = "1.0.107"
@@ -352,6 +516,27 @@ dependencies = [
"unicode-ident",
]
[[package]]
name = "pulldown-latex"
version = "0.8.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1cf850381ae0dbb131f36e31d6090f55363d079ab3e518ad0323b9cb6a96d115"
dependencies = [
"bumpalo",
]
[[package]]
name = "pxfm"
version = "0.1.30"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d55d956fa96f5ec02be2e13af0e20391a5aa83d6a074e3ad368959d0fab299ea"
[[package]]
name = "quick-error"
version = "2.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a993555f31e5a609f617c12db6250dedcac1b0a85076912c436e6fc9b2c8e6a3"
[[package]]
name = "quote"
version = "1.0.47"
@@ -361,6 +546,15 @@ dependencies = [
"proc-macro2",
]
[[package]]
name = "roxmltree"
version = "0.21.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9da7f59328b09405b181fee1018925fad50f157afb43c0c0f5c522c256dd5907"
dependencies = [
"memchr",
]
[[package]]
name = "rustc-hash"
version = "2.1.3"
@@ -427,6 +621,12 @@ dependencies = [
"digest",
]
[[package]]
name = "simd-adler32"
version = "0.3.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3a219298ac11a56ea9a6d2120044824d6f01aeb034955e7af7bc16858527deea"
[[package]]
name = "siphasher"
version = "1.0.4"
@@ -513,6 +713,12 @@ version = "0.9.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a"
[[package]]
name = "weezl"
version = "0.1.12"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a28ac98ddc8b9274cb41bb4d9d4d5c425b6020c50c46f25559911905610b4a88"
[[package]]
name = "windows-link"
version = "0.2.1"
@@ -528,8 +734,29 @@ dependencies = [
"windows-link",
]
[[package]]
name = "zlib-rs"
version = "0.6.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b268e58e7c693d7c271f93ffc4ba3b380412554231c85bf61ca7af91042a4112"
[[package]]
name = "zmij"
version = "1.0.23"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b"
[[package]]
name = "zune-core"
version = "0.4.12"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3f423a2c17029964870cfaabb1f13dfab7d092a62a29a89264f4d36990ca414a"
[[package]]
name = "zune-jpeg"
version = "0.4.21"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "29ce2c8a9384ad323cf564b67da86e21d3cfdff87908bc1223ed5c99bc792713"
dependencies = [
"zune-core",
]
+3
View File
@@ -28,6 +28,9 @@ path = "tests/integration/main.rs"
[dependencies]
base64 = "0.22"
image = { version = "=0.25.8", default-features = false, features = ["png", "jpeg", "webp", "gif"] }
pulldown-latex = "=0.8.0"
roxmltree = "0.21"
clap = { version = "4.5", features = ["derive"] }
serde = { version = "1", features = ["derive"] }
serde_json = "1"
Binary file not shown.
+155
View File
@@ -0,0 +1,155 @@
Format: https://www.debian.org/doc/packaging-manuals/copyright-format/1.0/
Upstream-Name: Noto
Upstream-Contact: https://github.com/googlei18n/noto-fonts/issues
http://groups.google.com/group/noto-font
Source: https://github.com/googlei18n/noto-fonts
Files: *
Copyright:
2010,2012-2020, Google Inc.
2015-2020, Google LLC.
License-Grant:
This Font Software is licensed under the SIL Open Font License,
Version 1.1.
License: OFL-1.1
Files:
debian/*
Copyright:
2013-2020, Jonas Smedegaard <dr@jones.dk>
2020, Purism, SPC
2013, Vasudev Kamath <kamathvasudev@gmail.com>
License-Grant:
This program is free software;
you can redistribute it and/or modify it
under the terms of the GNU General Public License
as published by the Free Software Foundation;
either version 3, or (at your option) any later version.
License: GPL-3+
Files:
debian/NotoMono/NotoMono-Regular.ttf
Copyright:
2007, Google Inc.
License-Grant:
This Font Software is licensed under the SIL Open Font License,
Version 1.1.
License: OFL-1.1
License: OFL-1.1
PREAMBLE
.
The goals of the Open Font License (OFL) are to stimulate
worldwide development of collaborative font projects,
to support the font creation efforts
of academic and linguistic communities,
and to provide a free and open framework
in which fonts may be shared and improved
in partnership with others.
.
The OFL allows the licensed fonts to be used, studied,
modified and redistributed freely
as long as they are not sold by themselves.
The fonts, including any derivative works,
can be bundled, embedded,
redistributed and/or sold with any software
provided that any reserved names are not used
by derivative works.
The fonts and derivatives, however,
cannot be released under any other type of license.
The requirement for fonts to remain under this license
does not apply to any document
created using the fonts or their derivatives.
.
DEFINITIONS
.
"Font Software" refers to the set of files
released by the Copyright Holder(s) under this license
and clearly marked as such.
This may include source files, build scripts and documentation.
.
"Reserved Font Name" refers to any names specified as such
after the copyright statement(s).
.
"Original Version" refers to the collection
of Font Software components
as distributed by the Copyright Holder(s).
.
"Modified Version" refers to any derivative
made by adding to, deleting, or substituting --
in part or in whole --
any of the components of the Original Version,
by changing formats
or by porting the Font Software to a new environment.
.
"Author" refers to any designer, engineer, programmer,
technical writer or other person
who contributed to the Font Software.
.
PERMISSION & CONDITIONS
.
Permission is hereby granted, free of charge,
to any person obtaining a copy of the Font Software,
to use, study, copy, merge, embed, modify, redistribute,
and sell modified and unmodified copies of the Font Software,
subject to the following conditions:
.
1) Neither the Font Software nor any of its individual components,
in Original or Modified Versions,
may be sold by itself.
.
2) Original or Modified Versions of the Font Software
may be bundled, redistributed and/or sold with any software,
provided that each copy contains the above copyright notice
and this license.
These can be included either as stand-alone text files,
human-readable headers or in the appropriate
machine-readable metadata fields within text or binary files
as long as those fields can be easily viewed by the user.
.
3) No Modified Version of the Font Software may use
the Reserved Font Name(s)
unless explicit written permission is granted
by the corresponding Copyright Holder.
This restriction only applies to the primary font name
as presented to the users.
.
4) The name(s) of the Copyright Holder(s)
or the Author(s) of the Font Software
shall not be used to promote,
endorse or advertise any Modified Version,
except to acknowledge the contribution(s)
of the Copyright Holder(s) and the Author(s)
or with their explicit written permission.
.
5) The Font Software,
modified or unmodified, in part or in whole,
must be distributed entirely under this license,
and must not be distributed under any other license.
The requirement for fonts to remain under this license
does not apply to any document
created using the Font Software.
.
TERMINATION
.
This license becomes null and void
if any of the above conditions are not met.
.
DISCLAIMER
.
THE FONT SOFTWARE IS PROVIDED "AS IS",
WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
INCLUDING BUT NOT LIMITED TO
ANY WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT.
IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE
FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
INCLUDING ANY GENERAL, SPECIAL, INDIRECT,
INCIDENTAL, OR CONSEQUENTIAL DAMAGES,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
ARISING FROM, OUT OF THE USE OR INABILITY TO USE
THE FONT SOFTWARE OR FROM OTHER DEALINGS IN THE FONT SOFTWARE.
License: GPL-3+
License-Reference: /usr/share/common-licenses/GPL-3
+12
View File
@@ -1370,3 +1370,15 @@
overflow-wrap: anywhere;
}
}
@font-face {
font-family: "Noto Sans Math";
src: url("__MATH_FONT__") format("truetype");
font-display: swap;
}
@layer typography {
.mq-document-image { max-inline-size: 100%; block-size: auto; }
.mq-heading-anchor { display: block; }
.mq-document math { font-family: "Noto Sans Math", math; }
}
+7 -2
View File
@@ -70,6 +70,8 @@ pub fn build(input: BuildInput<'_>) -> PresentationModel {
PresentationModel {
version: PRESENTATION_VERSION,
title: document.title(),
heading_slugs: super::links::heading_slugs(&document.blocks),
media: Default::default(),
document,
semantic,
source_status: status,
@@ -313,7 +315,8 @@ impl DocumentService {
(None, _) => None,
};
Ok(build(BuildInput {
let media = super::media::collect(&self.project, relative, &document.blocks);
let mut model = build(BuildInput {
document,
analysis: verified.as_ref(),
status,
@@ -322,7 +325,9 @@ impl DocumentService {
navigation,
core_version: self.core_version.clone(),
run: attached_run.as_ref(),
}))
});
model.media = media;
Ok(model)
}
}
+14 -1
View File
@@ -71,6 +71,18 @@ impl AssetBundle {
"image/webp",
include_bytes!("../../assets/feather.webp"),
),
asset(
"noto-math",
"ttf",
"font/ttf",
include_bytes!("../../assets/NotoSansMath-Regular.ttf"),
),
asset(
"noto-math-license",
"txt",
"text/plain; charset=utf-8",
include_bytes!("../../assets/licenses/NOTO-MATH-LICENSE.txt"),
),
];
let mut by_hashed_name = HashMap::new();
for (index, asset) in assets.iter().enumerate() {
@@ -79,7 +91,8 @@ impl AssetBundle {
let css_text = std::str::from_utf8(assets[0].bytes).expect("reader.css is UTF-8");
let css_with_images = css_text
.replace("__BLOSSOM__", &assets[3].data_uri())
.replace("__FEATHER__", &assets[4].data_uri());
.replace("__FEATHER__", &assets[4].data_uri())
.replace("__MATH_FONT__", &assets[5].hashed_name());
let css_served_sha256 = sha256_hex(css_with_images.as_bytes());
Self {
assets,
+100
View File
@@ -0,0 +1,100 @@
//! Markdown navigation and URL normalization shared by Live and export.
use crate::reader::markdown::{DocBlock, Inline};
use crate::reader::source::{SafeRelativePath, SourceSpan};
use std::collections::{HashMap, HashSet};
pub fn decode(raw: &str) -> Option<String> {
let mut result = Vec::with_capacity(raw.len());
let mut bytes = raw.bytes();
while let Some(byte) = bytes.next() {
if byte == b'%' {
let hi = (bytes.next()? as char).to_digit(16)?;
let lo = (bytes.next()? as char).to_digit(16)?;
result.push((hi * 16 + lo) as u8);
} else {
result.push(byte);
}
}
String::from_utf8(result)
.ok()
.filter(|value| !value.chars().any(char::is_control))
}
pub fn relative_url(current: &SafeRelativePath, url: &str) -> Option<SafeRelativePath> {
let relative = decode(url)?;
if relative.is_empty() || relative.starts_with('/') || relative.contains(['\\', ':']) {
return None;
}
let parent = current.parent();
let mut components = parent
.as_ref()
.map_or_else(Vec::new, |parent| parent.as_str().split('/').collect());
for part in relative.split('/') {
match part {
"" | "." => {}
".." => {
components.pop()?;
}
_ => components.push(part),
}
}
SafeRelativePath::parse(&components.join("/")).ok()
}
pub fn heading_slugs(blocks: &[DocBlock]) -> HashMap<SourceSpan, String> {
let mut slugs = HashMap::new();
let mut used = HashSet::new();
visit_headings(blocks, &mut |span, content| {
let label = content.iter().map(Inline::plain_text).collect::<String>();
let label = ["@exec", "@knowledge"]
.into_iter()
.find_map(|prefix| {
label
.strip_prefix(prefix)
.filter(|suffix| suffix.starts_with(char::is_whitespace))
})
.unwrap_or(&label)
.trim();
let base: String = label
.to_lowercase()
.chars()
.filter_map(|ch| {
if ch.is_whitespace() {
Some('-')
} else if ch.is_alphanumeric() || matches!(ch, '-' | '_') {
Some(ch)
} else {
None
}
})
.collect();
let base = if base.is_empty() { "section" } else { &base };
let base = if base.starts_with("mq-") {
format!("section-{base}")
} else {
base.to_string()
};
let mut slug = base.clone();
let mut suffix = 1;
while !used.insert(slug.clone()) {
slug = format!("{base}-{suffix}");
suffix += 1;
}
slugs.insert(span, slug);
});
slugs
}
fn visit_headings(blocks: &[DocBlock], visit: &mut impl FnMut(SourceSpan, &[Inline])) {
for block in blocks {
match block {
DocBlock::Heading { span, content, .. } => visit(*span, content),
DocBlock::List { items, .. } => visit_headings(items, visit),
DocBlock::ListItem { children, .. } | DocBlock::BlockQuote { children, .. } => {
visit_headings(children, visit)
}
_ => {}
}
}
}
+124
View File
@@ -0,0 +1,124 @@
//! Bounded TeX math to inert MathML, shared by all rendering modes.
use pulldown_latex::{config::DisplayMode, push_mathml, Parser, RenderConfig, Storage};
pub fn render(source: &str, block: bool) -> Option<String> {
if source.len() > 4096
|| source.chars().filter(|ch| *ch == '{').count() > 128
|| source.split('\\').skip(1).any(|rest| {
let end = rest
.find(|ch: char| !ch.is_ascii_alphabetic())
.unwrap_or(rest.len());
matches!(
&rest[..end],
"def"
| "gdef"
| "edef"
| "xdef"
| "newcommand"
| "renewcommand"
| "providecommand"
| "let"
| "futurelet"
| "csname"
| "input"
| "include"
| "href"
| "url"
| "includegraphics"
| "htmlClass"
| "htmlStyle"
| "htmlId"
)
})
{
return None;
}
let storage = Storage::new();
let config = RenderConfig {
display_mode: if block {
DisplayMode::Block
} else {
DisplayMode::Inline
},
..Default::default()
};
let mut html = String::new();
let mut parsed = true;
let parser = Parser::new(source, &storage).inspect(|event| parsed &= event.is_ok());
push_mathml(&mut html, parser, config).ok()?;
if !parsed || html.len() > 64 * 1024 {
return None;
}
let xml = roxmltree::Document::parse(&html).ok()?;
if xml.root_element().tag_name().name() != "math" {
return None;
}
let safe = xml
.descendants()
.filter(roxmltree::Node::is_element)
.all(|node| {
matches!(
node.tag_name().name(),
"math"
| "mrow"
| "mi"
| "mo"
| "mn"
| "mtext"
| "mfrac"
| "msqrt"
| "mroot"
| "msub"
| "msup"
| "msubsup"
| "munder"
| "mover"
| "munderover"
| "mtable"
| "mtr"
| "mtd"
| "mspace"
| "mpadded"
| "mstyle"
| "menclose"
| "mphantom"
| "mmultiscripts"
| "mprescripts"
| "none"
) && node.attributes().all(|attr| {
attr.namespace().is_none()
&& matches!(
attr.name(),
"display"
| "mathvariant"
| "mathsize"
| "mathcolor"
| "displaystyle"
| "scriptlevel"
| "stretchy"
| "symmetric"
| "movablelimits"
| "form"
| "fence"
| "separator"
| "lspace"
| "rspace"
| "minsize"
| "maxsize"
| "accent"
| "accentunder"
| "linethickness"
| "width"
| "height"
| "depth"
| "columnalign"
| "rowalign"
| "rowspacing"
| "columnspacing"
| "notation"
)
})
});
safe.then_some(html)
}
+302
View File
@@ -0,0 +1,302 @@
//! Bounded project-local assets used by the reader and static export.
use crate::reader::links::relative_url;
use crate::reader::markdown::{DocBlock, Inline};
use crate::reader::source::{sha256_hex, Project, SafeRelativePath};
use image::{ImageFormat, ImageReader};
use std::collections::{BTreeMap, BTreeSet};
use std::fs::File;
use std::io::{Cursor, Read};
use std::sync::Arc;
const MAX_BYTES: usize = 4 * 1024 * 1024;
const MAX_DOCUMENT_BYTES: usize = 16 * 1024 * 1024;
const MAX_REFERENCES: usize = 128;
const MAX_AXIS: u32 = 8192;
const MAX_PIXELS: u64 = 16_000_000;
#[derive(Debug)]
pub struct Media {
pub path: SafeRelativePath,
pub bytes: Vec<u8>,
pub digest: String,
pub mime: &'static str,
pub extension: &'static str,
pub width: u32,
pub height: u32,
}
impl Media {
pub fn filename(&self) -> String {
format!("{}.{}", self.digest, self.extension)
}
}
pub fn collect(
project: &Project,
current: &SafeRelativePath,
blocks: &[DocBlock],
) -> BTreeMap<String, Arc<Media>> {
let mut urls = BTreeSet::new();
scan_blocks(blocks, &mut urls);
let mut total = 0;
let mut resolved = BTreeMap::<SafeRelativePath, Arc<Media>>::new();
let mut result = BTreeMap::new();
for url in urls {
let Some(path) = relative_url(current, url) else {
continue;
};
if let Some(media) = resolved.get(&path) {
result.insert(url.to_string(), Arc::clone(media));
continue;
}
if let Some(media) = load(project, &path) {
total += media.bytes.len();
if total > MAX_DOCUMENT_BYTES {
break;
}
let media = Arc::new(media);
resolved.insert(path, Arc::clone(&media));
result.insert(url.to_string(), media);
}
}
result
}
fn scan_blocks<'a>(blocks: &'a [DocBlock], urls: &mut BTreeSet<&'a str>) {
for block in blocks {
match block {
DocBlock::Heading { content, .. } | DocBlock::Paragraph { content, .. } => {
scan_inlines(content, urls)
}
DocBlock::List { items, .. } => scan_blocks(items, urls),
DocBlock::ListItem { children, .. } | DocBlock::BlockQuote { children, .. } => {
scan_blocks(children, urls)
}
DocBlock::Table { header, rows, .. } => {
for cell in header.iter().chain(rows.iter().flatten()) {
scan_inlines(cell, urls);
}
}
_ => {}
}
}
}
fn scan_inlines<'a>(inlines: &'a [Inline], urls: &mut BTreeSet<&'a str>) {
for inline in inlines {
if urls.len() >= MAX_REFERENCES {
return;
}
match inline {
Inline::Image { url, .. } => {
urls.insert(url);
}
Inline::Emph { children, .. }
| Inline::Strong { children, .. }
| Inline::Strikethrough { children, .. }
| Inline::Link { children, .. } => scan_inlines(children, urls),
_ => {}
}
}
}
pub fn load(project: &Project, path: &SafeRelativePath) -> Option<Media> {
let extension = path.file_name().rsplit_once('.')?.1.to_ascii_lowercase();
let (mime, extension, format) = match extension.as_str() {
"png" => ("image/png", "png", Some(ImageFormat::Png)),
"jpeg" | "jpg" => ("image/jpeg", "jpg", Some(ImageFormat::Jpeg)),
"gif" => ("image/gif", "gif", Some(ImageFormat::Gif)),
"webp" => ("image/webp", "webp", Some(ImageFormat::WebP)),
"svg" => ("image/svg+xml", "svg", None),
_ => return None,
};
let file = open_beneath(project, path)?;
let metadata = file.metadata().ok()?;
if !metadata.is_file() || metadata.len() > MAX_BYTES as u64 {
return None;
}
let mut bytes = Vec::with_capacity(metadata.len() as usize);
file.take(MAX_BYTES as u64 + 1)
.read_to_end(&mut bytes)
.ok()?;
if bytes.len() > MAX_BYTES {
return None;
}
let (width, height) = if let Some(format) = format {
if image::guess_format(&bytes).ok()? != format {
return None;
}
let dimensions = ImageReader::with_format(Cursor::new(&bytes), format)
.into_dimensions()
.ok()?;
if !valid_dimensions(dimensions.0, dimensions.1) {
return None;
}
let mut decoder = ImageReader::with_format(Cursor::new(&bytes), format);
let mut limits = image::Limits::default();
limits.max_image_width = Some(MAX_AXIS);
limits.max_image_height = Some(MAX_AXIS);
limits.max_alloc = Some(128 * 1024 * 1024);
decoder.limits(limits);
decoder.decode().ok()?;
dimensions
} else {
svg_dimensions(&bytes)?
};
if !valid_dimensions(width, height) {
return None;
}
Some(Media {
path: path.clone(),
digest: sha256_hex(&bytes),
bytes,
mime,
extension,
width,
height,
})
}
fn valid_dimensions(width: u32, height: u32) -> bool {
width > 0
&& height > 0
&& width <= MAX_AXIS
&& height <= MAX_AXIS
&& u64::from(width) * u64::from(height) <= MAX_PIXELS
}
#[cfg(target_os = "linux")]
fn open_beneath(project: &Project, path: &SafeRelativePath) -> Option<File> {
use std::os::fd::{AsRawFd, FromRawFd};
let root = project.root_handle();
let name = std::ffi::CString::new(path.as_str()).ok()?;
// SAFETY: open_how is a C struct of integer fields.
let mut how: libc::open_how = unsafe { std::mem::zeroed() };
how.flags = (libc::O_RDONLY | libc::O_CLOEXEC | libc::O_NONBLOCK) as u64;
how.resolve = libc::RESOLVE_BENEATH | libc::RESOLVE_NO_MAGICLINKS;
// SAFETY: the descriptor and both pointers stay valid for openat2.
let fd = unsafe {
libc::syscall(
libc::SYS_openat2,
root.as_raw_fd(),
name.as_ptr(),
&how as *const libc::open_how,
std::mem::size_of_val(&how),
)
};
if fd < 0 {
return None;
}
// SAFETY: openat2 returned a new owned descriptor.
Some(unsafe { File::from_raw_fd(fd as std::os::fd::RawFd) })
}
#[cfg(not(target_os = "linux"))]
fn open_beneath(_project: &Project, _path: &SafeRelativePath) -> Option<File> {
None
}
fn svg_dimensions(bytes: &[u8]) -> Option<(u32, u32)> {
const SVG: &str = "http://www.w3.org/2000/svg";
let xml = std::str::from_utf8(bytes).ok()?;
let options = roxmltree::ParsingOptions {
nodes_limit: 10_000,
..Default::default()
};
let tree = roxmltree::Document::parse_with_options(xml, options).ok()?;
if tree.descendants().any(|node| node.is_pi()) {
return None;
}
let root = tree.root_element();
if !root.has_tag_name((SVG, "svg")) {
return None;
}
for node in tree.descendants().filter(roxmltree::Node::is_element) {
if node.tag_name().namespace() != Some(SVG)
|| !matches!(
node.tag_name().name(),
"svg"
| "g"
| "path"
| "rect"
| "circle"
| "ellipse"
| "line"
| "polyline"
| "polygon"
| "text"
| "tspan"
| "title"
| "desc"
)
{
return None;
}
for attr in node.attributes() {
if attr.namespace().is_some()
|| !matches!(
attr.name(),
"width"
| "height"
| "viewBox"
| "preserveAspectRatio"
| "x"
| "y"
| "x1"
| "x2"
| "y1"
| "y2"
| "rx"
| "ry"
| "r"
| "cx"
| "cy"
| "d"
| "points"
| "transform"
| "fill"
| "fill-rule"
| "fill-opacity"
| "stroke"
| "stroke-width"
| "stroke-opacity"
| "stroke-linecap"
| "stroke-linejoin"
| "stroke-dasharray"
| "opacity"
| "font-size"
| "text-anchor"
| "dominant-baseline"
)
|| (matches!(attr.name(), "fill" | "stroke")
&& !attr
.value()
.chars()
.all(|ch| ch.is_ascii_alphanumeric() || ch == '#'))
{
return None;
}
}
}
let dimension = |key| {
root.attribute(key)?
.trim_end_matches("px")
.parse::<u32>()
.ok()
};
if let (Some(width), Some(height)) = (dimension("width"), dimension("height")) {
return Some((width, height));
}
let viewbox: Vec<f64> = root
.attribute("viewBox")?
.split(|ch: char| ch.is_whitespace() || ch == ',')
.filter(|part| !part.is_empty())
.map(str::parse)
.collect::<Result<_, _>>()
.ok()?;
if viewbox.len() != 4 || !viewbox.iter().all(|value| value.is_finite()) {
return None;
}
Some((viewbox[2].ceil() as u32, viewbox[3].ceil() as u32))
}
+3
View File
@@ -6,7 +6,10 @@
pub mod assemble;
pub mod assets;
pub mod links;
pub mod markdown;
pub mod math;
pub mod media;
pub mod model;
pub mod render;
pub mod source;
+2
View File
@@ -91,6 +91,8 @@ pub struct PresentationModel {
pub version: u32,
pub title: String,
pub document: DocumentModel,
pub heading_slugs: std::collections::HashMap<crate::reader::source::SourceSpan, String>,
pub media: std::collections::BTreeMap<String, std::sync::Arc<super::media::Media>>,
pub semantic: Option<SemanticProjection>,
pub source_status: SourceStatus,
/// Human-readable reason for a degraded status (already normalized: no
+91 -54
View File
@@ -41,7 +41,23 @@ impl LinkPolicy {
for _ in 0..*page_depth {
prefix.push_str("../");
}
format!("{prefix}pages/{}.html", target.as_str())
format!(
"{prefix}pages/{}.html",
percent_encode_path(target.as_str())
)
}
}
}
fn media_href(&self, media: &super::media::Media) -> String {
match self {
LinkPolicy::LocalServer => format!(
"/media/{}?path={}",
media.filename(),
percent_encode_path(media.path.as_str())
),
LinkPolicy::StaticRelative { page_depth } => {
format!("{}media/{}", "../".repeat(*page_depth), media.filename())
}
}
}
@@ -814,6 +830,18 @@ fn render_block(
} => {
let unit = resolve_heading_unit(model, *span, *level);
let anchor = anchor_for_span(span.start, span.end);
let slug = model
.heading_slugs
.get(span)
.map(String::as_str)
.unwrap_or(&anchor);
if slug != anchor {
let _ = write!(
html,
"<span class=\"mq-heading-anchor\" id=\"{}\" aria-hidden=\"true\"></span>",
escape_attr(&anchor)
);
}
let (badge, cleaned) = display_heading_content(content, unit);
let data_semantic = if let Some((_, data)) = badge {
data
@@ -830,7 +858,7 @@ fn render_block(
html,
"<h{} id=\"{}\" data-source-id=\"{}\" data-semantic=\"{}\">",
level,
escape_attr(&anchor),
escape_attr(slug),
source_id_id(model, *span),
data_semantic,
);
@@ -979,13 +1007,13 @@ fn render_block(
DocBlock::MathBlock { span, literal } => {
let _ = write!(
html,
"<div class=\"mq-math-block\" data-resource-kind=\"formula\" data-source-id=\"{}\"><code>{}</code><span class=\"mq-math-note\">公式原文 · 未渲染数学</span></div>\n",
"<div class=\"mq-math-block\" data-resource-kind=\"formula\" data-source-id=\"{}\">{}</div>\n",
escape_attr(&source_id(
&model.document.identity.module_id,
*span,
"resource-formula"
)),
escape_text(literal)
render_math(literal, true)
);
}
DocBlock::ThematicBreak { .. } => html.push_str("<hr/>\n"),
@@ -1220,7 +1248,7 @@ fn render_inline(
} => {
let reference = projection.and_then(|projection| projection.reference_for_span(*span));
let state = reference.map(|reference| reference.state.as_str());
let target = resolve_link(url, current, &ctx.links);
let target = resolve_link(url, current, model, &ctx.links);
match target {
Some(href) => {
let _ = write!(html, "<a href=\"{href}\"", href = escape_attr(&href));
@@ -1246,17 +1274,14 @@ fn render_inline(
Inline::Image {
url, alt, title, ..
} => {
// Remote or unverified images are never loaded implicitly.
let _ = (url, title);
let _ = write!(
html,
"<span class=\"mq-raw-omitted\" role=\"note\">[图片已阻止自动加载:{}]</span>",
escape_text(if alt.is_empty() {
"无替代文本"
} else {
alt
})
);
if let Some(media) = model.media.get(url) {
let _ = write!(html, "<img class=\"mq-document-image\" src=\"{}\" alt=\"{}\" width=\"{}\" height=\"{}\" title=\"{}\">",
escape_attr(&ctx.links.media_href(media)), escape_attr(alt),
media.width, media.height, escape_attr(title));
} else {
let _ = write!(html, "<span class=\"mq-raw-omitted\" role=\"note\" title=\"{}\">[图片已阻止自动加载:{}]</span>",
escape_attr(url), escape_text(if alt.is_empty() { "无替代文本" } else { alt }));
}
}
Inline::Math {
span,
@@ -1277,9 +1302,8 @@ fn render_inline(
))
))
.unwrap_or_default(),
escape_text(literal)
render_math(literal, *display)
);
let _ = display;
}
Inline::HtmlInline { .. } => {
html.push_str("<span class=\"mq-raw-omitted\">已忽略原始行内 HTML</span>");
@@ -1362,51 +1386,64 @@ fn percent_encode_path(raw: &str) -> String {
/// Sanitize one Markdown link destination. Returns `None` for schemes the
/// reader must never expose (`javascript:`, `data:`, `file:`, ...) and for
/// console-control-looking payloads.
fn resolve_link(raw: &str, current: &SafeRelativePath, policy: &LinkPolicy) -> Option<String> {
fn resolve_link(
raw: &str,
current: &SafeRelativePath,
model: &PresentationModel,
policy: &LinkPolicy,
) -> Option<String> {
let url = raw.trim();
if url.is_empty() {
if url.is_empty()
|| url.chars().any(char::is_control)
|| url.contains('\\')
|| url.starts_with('/')
{
return None;
}
if url.chars().any(|ch| ch.is_control() || ch == '\u{7f}') {
return None;
let (path_with_query, fragment) = url
.split_once('#')
.map_or((url, None), |(path, fragment)| (path, Some(fragment)));
let path = path_with_query.split('?').next()?;
if let Some((scheme, _)) = path.split_once(':') {
return matches!(
scheme.to_ascii_lowercase().as_str(),
"http" | "https" | "mailto"
)
.then(|| url.to_string());
}
// Explicit scheme: only http/https/mailto are navigable. A single-letter
// prefix is a Windows drive, not a scheme.
if let Some(colon) = url.find(':') {
let scheme = &url[..colon];
if scheme.len() > 1 && scheme.chars().all(|ch| ch.is_ascii_alphabetic()) {
return match scheme.to_ascii_lowercase().as_str() {
"http" | "https" | "mailto" => Some(url.to_string()),
_ => None,
};
let fragment = fragment
.map(super::links::decode)
.unwrap_or_else(|| Some(String::new()))?;
let suffix = if fragment.is_empty() {
String::new()
} else {
format!("#{}", percent_encode_path(&fragment))
};
if path.is_empty() {
return Some(suffix);
}
let target = super::links::relative_url(current, path)?;
if target.as_str().ends_with(".mq.md") {
if !model.navigation.documents.contains(&target) {
return None;
}
}
if url.starts_with("//") {
return None;
}
if url.starts_with('#') {
return Some(url.to_string());
}
if url.starts_with('/') {
return match policy {
LinkPolicy::LocalServer => Some(url.to_string()),
LinkPolicy::StaticRelative { .. } => None,
};
}
let path_part = url.split(['?', '#']).next().unwrap_or(url);
if path_part.ends_with(".mq.md") {
let joined = match current.parent() {
Some(dir) => format!("{dir}/{path_part}"),
None => path_part.to_string(),
};
if let Ok(target) = SafeRelativePath::parse(&joined) {
return Some(policy.document_href(current, &target));
}
return None;
return Some(format!(
"{}{suffix}",
policy.document_href(current, &target)
));
}
Some(url.to_string())
}
fn render_math(literal: &str, display: bool) -> String {
super::math::render(literal, display).unwrap_or_else(|| {
format!(
"<code title=\"公式无法排版\">{}</code>",
escape_text(literal)
)
})
}
fn render_run_chips(html: &mut String, model: &PresentationModel, statement_span: SourceSpan) {
let Some(run) = &model.run else {
return;
+26 -2
View File
@@ -8,7 +8,7 @@ use serde::{Deserialize, Serialize};
use sha2::{Digest, Sha256};
/// Half-open byte span `[start, end)` into one module's exact source bytes.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, Default)]
pub struct SourceSpan {
pub start: u64,
pub end: u64,
@@ -402,6 +402,8 @@ pub struct DocumentRef {
#[derive(Debug, Clone)]
pub struct Project {
root: PathBuf,
#[cfg(target_os = "linux")]
root_handle: std::sync::Arc<std::fs::File>,
entry: DocumentRef,
}
@@ -419,6 +421,8 @@ impl Project {
if metadata.is_file() {
let root = discover_project_root(&canonical);
let project = Self {
#[cfg(target_os = "linux")]
root_handle: Self::open_root(&root)?,
entry: DocumentRef {
relative: SafeRelativePath("placeholder".to_string()),
absolute: canonical.clone(),
@@ -428,6 +432,8 @@ impl Project {
let relative = project.relative_for(&canonical)?;
Ok(Self {
root: project.root,
#[cfg(target_os = "linux")]
root_handle: project.root_handle,
entry: DocumentRef {
relative,
absolute: canonical,
@@ -436,6 +442,8 @@ impl Project {
} else if metadata.is_dir() {
let project = Self {
root: canonical.clone(),
#[cfg(target_os = "linux")]
root_handle: Self::open_root(&canonical)?,
entry: DocumentRef {
relative: SafeRelativePath("placeholder".to_string()),
absolute: canonical.clone(),
@@ -444,8 +452,8 @@ impl Project {
let documents = project.list_documents()?;
let chosen = choose_entry(&project.root, &documents)?;
Ok(Self {
root: project.root,
entry: chosen,
..project
})
} else {
Err(ViewError::PathForbidden {
@@ -454,6 +462,22 @@ impl Project {
}
}
#[cfg(target_os = "linux")]
fn open_root(path: &Path) -> ViewResult<std::sync::Arc<std::fs::File>> {
use std::os::unix::fs::OpenOptionsExt;
std::fs::OpenOptions::new()
.read(true)
.custom_flags(libc::O_DIRECTORY | libc::O_NOFOLLOW)
.open(path)
.map(std::sync::Arc::new)
.map_err(|err| ViewError::io("open project root", err))
}
#[cfg(target_os = "linux")]
pub(super) fn root_handle(&self) -> &std::fs::File {
&self.root_handle
}
pub fn root(&self) -> &Path {
&self.root
}
+55 -7
View File
@@ -50,21 +50,29 @@ impl ServerState {
/// bytes are unchanged. This path performs the read-only `check` only.
pub fn load(&self, relative: &SafeRelativePath) -> ViewResult<PresentationModel> {
let digest = self.service.project().source_digest(relative)?;
if let Ok(cache) = self.cache.lock() {
if let Some(entry) = cache.get(relative.as_str()) {
if entry.source_digest == digest {
return Ok(entry.model.clone());
}
}
let cached = self.cache.lock().ok().and_then(|cache| {
let entry = cache.get(relative.as_str())?;
(entry.source_digest == digest).then(|| entry.model.clone())
});
if let Some(mut model) = cached {
model.media = crate::reader::media::collect(
self.service.project(),
relative,
&model.document.blocks,
);
model.navigation.documents = self.service.project().list_documents()?;
return Ok(model);
}
let model = self.service.load(relative)?;
if let Ok(mut cache) = self.cache.lock() {
if cache.len() < 64 {
let mut cached = model.clone();
cached.media.clear();
cache.insert(
relative.as_str().to_string(),
CacheEntry {
source_digest: digest,
model: model.clone(),
model: cached,
},
);
}
@@ -102,6 +110,9 @@ pub fn handle(state: &ServerState, request: Request) -> ViewResult<()> {
if let Some(hashed_name) = path.strip_prefix("/assets/") {
return serve_asset(request, hashed_name);
}
if let Some(name) = path.strip_prefix("/media/") {
return serve_media(state, request, name, query);
}
if path == "/" || path == "/index.html" {
return serve_page(state, request, None);
}
@@ -387,6 +398,43 @@ fn cancel_run(state: &ServerState, request: Request, run_id: &str) -> ViewResult
}
}
fn serve_media(state: &ServerState, request: Request, name: &str, query: &str) -> ViewResult<()> {
if let Err(err) = state.security.require_session(&request) {
return respond_error(request, status_for(&err), &err);
}
let Some(path) =
query_param(query, "path").and_then(|path| SafeRelativePath::parse(&path).ok())
else {
return respond_text(
request,
StatusCode(404),
"media not found\n",
CacheKind::NoStore,
);
};
let Some(media) = crate::reader::media::load(state.service.project(), &path)
.filter(|media| media.filename() == name)
else {
return respond_text(
request,
StatusCode(404),
"media not found\n",
CacheKind::NoStore,
);
};
respond_bytes(
request,
StatusCode(200),
media.mime,
media.bytes,
CacheKind::NoStore,
vec![
Header::from_bytes("Content-Security-Policy", "default-src 'none'; sandbox")
.expect("valid media CSP"),
],
)
}
fn serve_asset(request: Request, hashed_name: &str) -> ViewResult<()> {
let bundle = AssetBundle::get();
if hashed_name == bundle.hashed_css_name() {
+1 -1
View File
@@ -81,7 +81,7 @@ fn theme_has_one_token_layer_and_no_legacy_skin() {
"the theme must not rely on !important overrides"
);
// No remote font/CDN requests.
for banned in ["@font-face", "fonts.googleapis", "https://"] {
for banned in ["fonts.googleapis", "https://"] {
assert!(!css.contains(banned), "remote resource marker {banned}");
}
}