1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
use std::sync::LazyLock;
use std::time::{Duration, Instant};
use pulldown_cmark::{CodeBlockKind, CowStr, Event, Options, Parser, Tag, TagEnd};
use syntect::html::{ClassStyle, ClassedHTMLGenerator};
use syntect::parsing::{SyntaxReference, SyntaxSet};
use syntect::util::LinesWithEndings;
pub const HIGHLIGHT_LIMIT: usize = 512 << 10;
const HIGHLIGHT_BUDGET: Duration = Duration::from_secs(2);
const CLASSES: ClassStyle = ClassStyle::SpacedPrefixed { prefix: "hl-" };
static SYNTAXES: LazyLock<SyntaxSet> = LazyLock::new(SyntaxSet::load_defaults_newlines);
pub fn warm_up() {
LazyLock::force(&SYNTAXES);
}
fn syntax_for(path: &str, first_line: &str) -> Option<&'static SyntaxReference> {
let file = path.rsplit('/').next().unwrap_or(path);
let ext = file.rsplit_once('.').map_or(file, |(_, ext)| ext);
SYNTAXES
.find_syntax_by_extension(ext)
.or_else(|| SYNTAXES.find_syntax_by_extension(file))
.or_else(|| SYNTAXES.find_syntax_by_first_line(first_line))
}
fn syntax_for_fence(lang: &str) -> Option<&'static SyntaxReference> {
let lang = lang.split([',', ' ', '{']).next().unwrap_or("").trim();
if lang.is_empty() {
return None;
}
SYNTAXES.find_syntax_by_token(lang)
}
fn highlight_with(code: &str, syntax: Option<&'static SyntaxReference>) -> String {
highlight_within(code, syntax, HIGHLIGHT_BUDGET)
}
fn highlight_within(code: &str, syntax: Option<&'static SyntaxReference>, budget: Duration) -> String {
let plain = || html_escape::encode_text(code).into_owned();
let Some(syntax) = syntax.filter(|_| code.len() <= HIGHLIGHT_LIMIT) else { return plain() };
let deadline = Instant::now() + budget;
let mut generator = ClassedHTMLGenerator::new_with_class_style(syntax, &SYNTAXES, CLASSES);
for line in LinesWithEndings::from(code) {
if Instant::now() >= deadline || generator.parse_html_for_line_which_includes_newline(line).is_err() {
return plain();
}
}
generator.finalize()
}
pub fn highlight(path: &str, code: &str) -> String {
highlight_with(code, syntax_for(path, code.lines().next().unwrap_or("")))
}
pub fn is_markdown(path: &str) -> bool {
let lower = path.to_ascii_lowercase();
[".md", ".markdown", ".mdown", ".mkd"].iter().any(|ext| lower.ends_with(ext))
}
pub enum Target {
External(String),
Repo(Vec<u8>),
Blocked,
}
pub fn resolve_link(dir: &[u8], target: &str) -> Target {
let lower = target.to_ascii_lowercase();
if lower.starts_with("http://")
|| lower.starts_with("https://")
|| lower.starts_with("mailto:")
|| target.starts_with('#')
{
return Target::External(target.to_string());
}
let path = target.split(['#', '?']).next().unwrap_or("");
if path.split('/').next().is_some_and(|first| first.contains(':')) {
return Target::Blocked;
}
let mut parts: Vec<Vec<u8>> = if path.starts_with('/') {
Vec::new()
} else {
dir.split(|b| *b == b'/').filter(|p| !p.is_empty()).map(<[u8]>::to_vec).collect()
};
for raw in path.split('/') {
let part = gitv_core::percent_decode(raw);
match part.as_slice() {
b"" | b"." => {}
b".." => {
if parts.pop().is_none() {
return Target::Blocked;
}
}
part if part.contains(&b'/') || part.contains(&0) => return Target::Blocked,
_ => parts.push(part),
}
}
Target::Repo(parts.join(&b'/'))
}
pub fn markdown(source: &str, dir: &[u8], link: &dyn Fn(&[u8], bool) -> String) -> String {
let options =
Options::ENABLE_TABLES | Options::ENABLE_STRIKETHROUGH | Options::ENABLE_TASKLISTS | Options::ENABLE_FOOTNOTES;
let rewrite = |dest: CowStr<'_>, image: bool| -> CowStr<'static> {
match resolve_link(dir, &dest) {
Target::External(url) if url.starts_with('#') => format!("#md-{}", &url[1..]).into(),
Target::External(url) => url.into(),
Target::Repo(path) => {
let mut url = link(&path, image);
if let Some((_, fragment)) = dest.split_once('#') {
url.push('#');
if !image && is_markdown(&String::from_utf8_lossy(&path)) {
url.push_str("md-");
}
url.push_str(fragment);
}
url.into()
}
Target::Blocked => "#".into(),
}
};
let mut events = Vec::new();
let mut fence: Option<(Option<&'static SyntaxReference>, String)> = None;
for event in Parser::new_ext(source, options) {
if let Some((_, code)) = fence.as_mut() {
match event {
Event::Text(text) => code.push_str(&text),
Event::End(TagEnd::CodeBlock) => {
let (syntax, code) = fence.take().unwrap_or_default();
events.push(Event::Html(
format!("<pre class=\"code\">{}</pre>\n", highlight_with(&code, syntax)).into(),
));
}
_ => {}
}
continue;
}
events.push(match event {
Event::Start(Tag::CodeBlock(kind)) => {
let syntax = match kind {
CodeBlockKind::Fenced(lang) => syntax_for_fence(&lang),
CodeBlockKind::Indented => None,
};
fence = Some((syntax, String::new()));
continue;
}
Event::Html(raw) | Event::InlineHtml(raw) => Event::Text(raw),
Event::Start(Tag::Link { link_type, dest_url, title, id }) => {
Event::Start(Tag::Link { link_type, dest_url: rewrite(dest_url, false), title, id })
}
Event::Start(Tag::Image { link_type, dest_url, title, id }) => {
Event::Start(Tag::Image { link_type, dest_url: rewrite(dest_url, true), title, id })
}
other => other,
});
}
let mut used = std::collections::HashSet::new();
let mut suffixes = std::collections::HashMap::new();
let mut heading = None;
for index in 0..events.len() {
match &events[index] {
Event::Start(Tag::Heading { .. }) => heading = Some((index, String::new())),
Event::Text(text) | Event::Code(text) => {
if let Some((_, title)) = &mut heading {
title.push_str(text);
}
}
Event::End(TagEnd::Heading(_)) => {
if let Some((start, title)) = heading.take() {
let base: String = title
.to_lowercase()
.chars()
.filter_map(|c| {
if c.is_whitespace() {
Some('-')
} else if c.is_alphanumeric() || matches!(c, '-' | '_') {
Some(c)
} else {
None
}
})
.collect();
let base = format!("md-{base}");
let mut id = base.clone();
let suffix = suffixes.entry(base.clone()).or_insert(0usize);
while !used.insert(id.clone()) {
*suffix += 1;
id = format!("{base}-{suffix}");
}
if let Event::Start(Tag::Heading { id: target, .. }) = &mut events[start] {
*target = Some(id.into());
}
}
}
_ => {}
}
}
let mut out = String::new();
pulldown_cmark::html::push_html(&mut out, events.into_iter());
out
}
#[cfg(test)]
mod tests {
use super::*;
fn link(path: &[u8], image: bool) -> String {
format!("/{}?path={}", if image { "raw" } else { "blob" }, String::from_utf8_lossy(path))
}
#[test]
fn escapes_raw_html() {
let html = markdown("hi <script>alert(1)</script>\n\n<div onclick=x>", b"", &link);
assert!(!html.contains("<script"), "{html}");
assert!(!html.contains("<div"), "{html}");
}
#[test]
fn links_match_unique_heading_ids() {
let html = markdown(
"# Install *Git*
# Install Git
[second](#install-git-1) [guide](guide.md#install-git)",
b"",
&link,
);
for fragment in [
"id=\"md-install-git\"",
"id=\"md-install-git-1\"",
"href=\"#md-install-git-1\"",
"href=\"/blob?path=guide.md#md-install-git\"",
] {
assert!(html.contains(fragment), "{html}");
}
}
#[test]
fn ignores_heading_attributes() {
let html = markdown("# Title {onclick=alert(1) #main .skip style=x}", b"", &link);
assert!(html.contains(">Title {onclick=alert(1) #main .skip style=x}</h1>"));
assert!(!html.contains(" onclick="));
}
#[test]
fn blocks_dangerous_links() {
let html = markdown("[x](javascript:alert(1)) [y](../../etc/passwd)", b"docs", &link);
assert!(!html.contains("javascript:"), "{html}");
assert!(!html.contains("passwd"), "{html}");
}
#[test]
fn rewrites_relative_links_and_images() {
let html =
markdown("[a](guide.md#top) [b](/src/lib.rs)  [d](https://x.dev)", b"docs", &link);
assert!(html.contains("href=\"/blob?path=docs/guide.md#md-top\""), "{html}");
assert!(html.contains("href=\"/blob?path=src/lib.rs\""), "{html}");
assert!(html.contains("src=\"/raw?path=img/logo.png\""), "{html}");
assert!(html.contains("href=\"https://x.dev\""), "{html}");
}
#[test]
fn link_destinations_are_decoded_once() {
let repo = |dir: &[u8], target: &str| match resolve_link(dir, target) {
Target::Repo(path) => Some(path),
_ => None,
};
assert_eq!(repo(b"docs", "My%20File.md"), Some(b"docs/My File.md".to_vec()));
assert_eq!(repo(b"docs", "a+b.md"), Some(b"docs/a+b.md".to_vec()), "a plus is a plus");
assert_eq!(repo(b"docs", "100%25.md"), Some(b"docs/100%.md".to_vec()));
assert_eq!(repo(b"caf\xe9", "x.md"), Some(b"caf\xe9/x.md".to_vec()), "the folder keeps its bytes");
assert_eq!(repo(b"a/b", "%2E%2E/c"), Some(b"a/c".to_vec()), "an encoded .. is still ..");
assert_eq!(repo(b"", "a%2Fb"), None, "no file name contains a slash");
assert_eq!(repo(b"", "a%00b"), None);
}
#[test]
fn highlighting_past_its_budget_falls_back_to_plain_text() {
let syntax = syntax_for("x.rs", "");
assert!(highlight_within("fn main() {}\n", syntax, Duration::from_secs(60)).contains("hl-"));
assert_eq!(highlight_within("fn <b>\n", syntax, Duration::ZERO), "fn <b>\n");
}
#[test]
fn highlights_fenced_code_and_files() {
let html = markdown("```rust\nfn main() {}\n```", b"", &link);
assert!(html.contains("<pre class=\"code\">") && html.contains("hl-"), "{html}");
assert!(highlight("x.py", "def f(): pass\n").contains("hl-"));
assert!(highlight("run", "#!/bin/sh\necho hi\n").contains("hl-"));
assert_eq!(highlight("notes.unknownext", "<b>"), "<b>");
}
}