Compare commits

..
Author SHA1 Message Date
james.maesandClaude Fable 5.2 b095d1a183 fix(rendering): refuse unsupported markup as an error and keep large documents linear
node / node (push) Successful in 14s
build / scripts (push) Successful in 14s
windows / windows (push) Successful in 1m57s
build / windows (push) Successful in 1m57s
Element nesting is bounded before any library walks the parsed tree: a
count kept while tokens arrive stops runaway input early, and an exact
measurement of the parsed tree applies the limit of 256 levels. The
renderer parses once with the sanitizer's own settings and sanitizes that
tree, so the bound is enforced between the parse and the sanitizer's
passes. Deeper markup is an ArgumentException, which the reader already
reports as an unsupported document.

An unterminated script or comment can report a text run past the end of
its block, and malformed markup can report one that starts inside
another; both are handled instead of failing the open. Raw-text
formatting is applied in one forward pass, and repeated heading titles
continue from the last anchor suffix used, so neither grows with the
square of the document. DocumentOutline accepts a cancellation token that
is honoured between its phases.

The threat model states that nesting is bounded and parse time is not.

Closes #50

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Signed-off-by: James Maes <james@kof22.com>
2026-11-10 17:19:26 -06:00
17 changed files with 537 additions and 1164 deletions

No files matched your search

+2 -2
View File
@@ -43,10 +43,10 @@ physical directory. It does not authorize native commands or remote resource acc
| Threat | Mitigation and evidence |
| --- | --- |
| Document script or native-command execution | Sanitizer regressions pass; host disables scripts/bridge; actual browser malicious-script and reader acceptance passed on 77dd04d |
| Image traversal, device/ADS paths or encoded separators | Core path-policy tests pass; denied before filesystem access. Reserved device names and forbidden characters are one written-out rule (`WindowsFileNames`), independent of the running Windows version: every device name in any letter case, with any extension, and with spaces before the extension |
| Image traversal, device/ADS paths or encoded separators | Core path-policy tests pass; denied before filesystem access |
| Junction/symlink escape or check/reopen race | Check normalized physical path on opened image handle; read same handle; real junction rejection test passes |
| Remote image tracking / resource exfiltration | No-referrer header, no document networking; actual listening-server browser denial passed on 77dd04d |
| Oversized input / image denial of service | Pre-parse character bound and image byte bound; native limit tests pass; performance acceptance remains |
| Oversized input / image denial of service | Pre-parse character bound and image byte bound; native limit tests pass. Element nesting is bounded at 256 levels before any library walks the parsed tree recursively, with an early count that stops runaway nesting while it is still being parsed; deeper markup is refused as an unsupported document. Parse time is not bounded: it grows with document size, runs off the window thread, and can be cancelled between the render, the parse and each heading |
| Settings corruption / UI exception | AppKit shell sanitation and crash handling; inherited foundation tests |
| Tampered installer/update | Fail-closed signing/provenance/checksum release pipeline; real Azure CI authorization and signed artifacts remain unverified |
| Privileged repository review abuse | Trusted review workflow only; current-SHA human acknowledgement remains required |
@@ -18,16 +18,25 @@ public sealed class DocumentOutline
/// <summary>Sanitizes first; authored identifiers cannot impersonate the generated navigation targets.</summary>
public DocumentOutline(string markdown, FrontmatterMode frontmatter = FrontmatterMode.Hide, MarkdownExtensions? extensions = null)
/// <summary>
/// Sanitizes first; authored identifiers cannot impersonate the generated navigation targets.
/// A large document takes time that grows with its size: cancellation is honoured between the
/// render, the parse and each heading, so a closed window or a newer load does not wait for it.
/// </summary>
public DocumentOutline(string markdown, FrontmatterMode frontmatter = FrontmatterMode.Hide, MarkdownExtensions? extensions = null, CancellationToken cancellation = default)
{
var sources = new DocumentSourceMap(markdown);
var sourceHeadings = new List<DocumentSourceHeading>();
using AngleSharp.Html.Dom.IHtmlDocument document = new HtmlParser().ParseDocument(new MarkdownRenderer(extensions).RenderWithSources(markdown, frontmatter, sources));
cancellation.ThrowIfCancellationRequested();
string rendered = new MarkdownRenderer(extensions).RenderWithSources(markdown, frontmatter, sources);
cancellation.ThrowIfCancellationRequested();
using AngleSharp.Html.Dom.IHtmlDocument document = new HtmlParser().ParseDocument(rendered);
IElement body = document.Body!;
var fragments = new Dictionary<string, string>(StringComparer.Ordinal);
var nextSuffix = new Dictionary<string, int>(StringComparer.Ordinal);
foreach(IElement element in body.QuerySelectorAll("h1,h2,h3,h4,h5,h6"))
{
cancellation.ThrowIfCancellationRequested();
var heading = new DocumentHeading(_headings.Count, element.LocalName[1] - '0', element.TextContent.Trim());
_headings.Add(heading);
if(element.GetAttribute(sources.AttributeName) is { } identity && sources.TryGetPosition(identity, out (int Start, int End) position))
@@ -37,11 +46,15 @@ public sealed class DocumentOutline
_elements.Add(element, heading);
element.Id = "mv-heading-" + heading.Index.ToString(CultureInfo.InvariantCulture);
string slug = Markdig.Helpers.LinkHelper.UrilizeAsGfm(heading.Title);
// Repeated titles continue from the last suffix used for that title instead of rescanning from one.
string fragment = slug;
for(int suffix = 1; fragments.ContainsKey(fragment); suffix++)
int suffix = nextSuffix.GetValueOrDefault(slug, 1);
while(fragments.ContainsKey(fragment))
{
fragment = slug + "-" + suffix.ToString(CultureInfo.InvariantCulture);
suffix++;
}
nextSuffix[slug] = suffix;
fragments.Add(fragment, element.Id);
}
foreach(IElement element in body.QuerySelectorAll("[" + sources.AttributeName + "]"))
@@ -56,6 +69,7 @@ public sealed class DocumentOutline
link.SetAttribute("href", "#" + target);
}
}
cancellation.ThrowIfCancellationRequested();
foreach(IElement element in body.QuerySelectorAll("*").Reverse())
{
if(!_elements.ContainsKey(element))
@@ -19,6 +19,12 @@ public sealed class DocumentResourcePolicy
".md", ".markdown", ".mdown", ".mkd", ".txt",
};
private static readonly HashSet<string> s_deviceNames = new(StringComparer.OrdinalIgnoreCase)
{
"CON", "PRN", "AUX", "NUL", "COM1", "COM2", "COM3", "COM4", "COM5", "COM6", "COM7", "COM8", "COM9",
"LPT1", "LPT2", "LPT3", "LPT4", "LPT5", "LPT6", "LPT7", "LPT8", "LPT9", "COM¹", "COM²", "COM³", "LPT¹", "LPT²", "LPT³",
};
private readonly string _prefix;
@@ -32,16 +38,6 @@ public sealed class DocumentResourcePolicy
/// <summary>The image file types served to the document surface.</summary>
internal static IReadOnlyCollection<string> ImageExtensions => s_imageExtensions;
/// <summary>The document file types a link may open in a new reader.</summary>
internal static IReadOnlyCollection<string> DocumentExtensions => s_documentExtensions;
/// <summary>The only top-level document URI the browser host may serve.</summary>
public Uri DocumentUri { get; }
@@ -97,7 +93,7 @@ public sealed class DocumentResourcePolicy
private static bool IsSafeSegment(string segment)
{
return segment.Length > 0 && segment is not ("." or "..") && !segment.EndsWith(' ') && !segment.EndsWith('.') &&
!segment.Any(character => char.IsControl(character) || WindowsFileNames.InvalidCharacters.Contains(character, StringComparison.Ordinal)) &&
!WindowsFileNames.IsReservedDeviceName(segment);
!segment.Any(character => char.IsControl(character) || "<>:\\|?*".Contains(character, StringComparison.Ordinal)) &&
!s_deviceNames.Contains(segment.Split('.')[0]);
}
}
@@ -142,10 +142,12 @@ internal sealed class DocumentSourceMap
string html = string.Join('\n', lines.Take(block.Lines.Count).Select(line => line.Slice.ToString()));
int? close = null;
bool seenTag = false;
var nesting = new HtmlNesting();
var parser = new HtmlParser(new HtmlParserOptions
{
OnToken = (token, range) =>
{
nesting.Observe(token);
if(!seenTag && token.Type is HtmlTokenType.StartTag or HtmlTokenType.EndTag
&& token.Name.Length == 2 && token.Name[0] == 'h' && token.Name[1] is >= '1' and <= '6')
{
@@ -209,11 +211,13 @@ internal sealed class DocumentSourceMap
private static HtmlParser CreateSourceParser(Dictionary<int, int> headingEnds)
{
int pendingHeading = -1;
var nesting = new HtmlNesting();
return new HtmlParser(new HtmlParserOptions
{
IsKeepingSourceReferences = true,
OnToken = (token, range) =>
{
nesting.Observe(token);
if(token.Name.Length == 2 && token.Name[0] == 'h' && token.Name[1] is >= '1' and <= '6')
{
if(token.Type == HtmlTokenType.StartTag)
@@ -0,0 +1,90 @@
/*
* Copyright (c) 2026 James Maes
* SPDX-License-Identifier: MIT
*/
using AngleSharp.Dom;
using AngleSharp.Html.Parser;
using AngleSharp.Html.Parser.Tokens;
namespace MarkdownViewr.Windows.Core.Documents;
/// <summary>
/// Bounds how deeply authored HTML may nest. Libraries that walk the parsed tree recursively
/// overflow the stack on a few thousand levels, and a stack overflow cannot be caught, so the
/// bound is enforced before any such walk: a cheap count while tokens arrive stops runaway
/// input early, and an exact measurement of the parsed tree applies the real limit.
/// </summary>
internal sealed class HtmlNesting
{
/// <summary>The deepest element nesting a document may have; ordinary documents use a few dozen levels.</summary>
public const int MaximumDepth = 256;
/// <summary>Start tags left open before parsing stops; an upper bound on depth that keeps the parser's work small.</summary>
public const int MaximumOpenTags = 4096;
private const string Message = "The document nests HTML more deeply than the supported limit.";
private static readonly HashSet<string> s_neverOpen = new(StringComparer.Ordinal)
{
// Void elements have no content.
"area", "base", "br", "col", "embed", "hr", "img", "input", "link", "meta", "source", "track", "wbr",
// A new one of these closes the previous one, so siblings left unclosed do not nest.
"caption", "colgroup", "dd", "dt", "li", "optgroup", "option", "p", "tbody", "td", "tfoot", "th", "thead", "tr",
};
private readonly Stack<string> _open = new();
/// <summary>
/// Counts start tags that are still open. An end tag closes only the tag on top, so the count
/// can exceed the real depth for carelessly closed markup but never falls below it.
/// </summary>
public void Observe(HtmlToken token)
{
if(token.Type == HtmlTokenType.StartTag && !s_neverOpen.Contains(token.Name))
{
_open.Push(token.Name);
if(_open.Count > MaximumOpenTags)
{
throw new ArgumentException(Message, nameof(token));
}
}
else if(token.Type == HtmlTokenType.EndTag && _open.TryPeek(out string? top) && string.Equals(top, token.Name, StringComparison.Ordinal))
{
_open.Pop();
}
}
/// <summary>Measures the parsed tree without recursion and rejects one deeper than <see cref="MaximumDepth"/>.</summary>
public static void ThrowIfTooDeep(INode root)
{
int depth = 0;
INode? node = root;
while(node is not null)
{
if(node.FirstChild is { } child)
{
node = child;
if(++depth > MaximumDepth)
{
throw new ArgumentException(Message, nameof(root));
}
}
else
{
// A leaf: climb to the nearest ancestor that has a sibling still to visit.
while(node != root && node!.NextSibling is null)
{
node = node.Parent;
depth--;
}
node = node == root ? null : node!.NextSibling;
}
}
}
}
@@ -6,6 +6,8 @@
using System.Text;
using System.Text.RegularExpressions;
using AngleSharp;
using AngleSharp.Css.Parser;
using AngleSharp.Dom;
using AngleSharp.Html.Dom;
using AngleSharp.Html.Parser;
@@ -24,6 +26,14 @@ public sealed class MarkdownRenderer
/// <summary>Bounds parser work before an opened document can consume unbounded memory.</summary>
public const int MaximumCharacters = 16 * 1024 * 1024;
// The sanitizer's own parser settings: scripting on, so noscript content stays text, and its CSS-aware context.
private static readonly IBrowsingContext s_sanitizerContext = BrowsingContext.New(Configuration.Default.WithCss(new CssParserOptions
{
IsIncludingUnknownDeclarations = true,
IsIncludingUnknownRules = true,
IsToleratingInvalidSelectors = true,
}));
private readonly MarkdownPipeline _pipeline;
private readonly MarkdownExtensions _extensions;
@@ -59,11 +69,6 @@ public sealed class MarkdownRenderer
/// <summary>The configured sanitizer, for comparing its allowlists with an independent list.</summary>
internal HtmlSanitizer Policy => _sanitizer;
/// <summary>Preserves useful markup while sanitizing every parser result, including authored raw HTML.</summary>
public string Render(string markdown, FrontmatterMode frontmatter = FrontmatterMode.Hide) => Render(markdown, frontmatter, null);
@@ -105,7 +110,23 @@ public sealed class MarkdownRenderer
_ => "",
} : "";
string html = sources is null ? RenderDocument(Markdown.Parse(body, _pipeline)) : sources.Render(body, _pipeline, markdown.Length - body.Length, RenderDocument);
return _sanitizer.Sanitize(prefix + html);
return Sanitize(prefix + html);
}
/// <summary>
/// Parses once with the sanitizer's own settings, proves the tree is shallow enough for the
/// sanitizer's recursive passes, and only then sanitizes and serializes it.
/// </summary>
private string Sanitize(string html)
{
var nesting = new HtmlNesting();
var parser = new HtmlParser(new HtmlParserOptions { IsScripting = true, OnToken = (token, _) => nesting.Observe(token) }, s_sanitizerContext);
using IHtmlDocument document = parser.ParseDocument("<!doctype html><html><body>" + html);
HtmlNesting.ThrowIfTooDeep(document.Body!);
_sanitizer.SanitizeDom(document, document.Body!);
return document.Body!.ChildNodes.ToHtml(_sanitizer.OutputFormatter);
}
@@ -129,21 +150,26 @@ public sealed class MarkdownRenderer
var block = (HtmlBlock)node;
string html = string.Join('\n', block.Lines.Lines.Take(block.Lines.Count).Select(line => line.Slice.ToString()));
var changes = new List<(int Start, int End, string Value)>();
var nesting = new HtmlNesting();
var parser = new HtmlParser(new HtmlParserOptions
{
OnToken = (token, range) =>
{
nesting.Observe(token);
if(token.Type is HtmlTokenType.StartTag or HtmlTokenType.EndTag && token.Name is "code" or "pre")
{
codeDepth = Math.Max(0, codeDepth + (token.Type == HtmlTokenType.StartTag ? 1 : -1));
}
else if(token.Type == HtmlTokenType.Character && codeDepth == 0)
{
string text = html[range.Start.Index..range.End.Index];
// An unterminated script or comment reports a range past the end of the block.
int start = Math.Min(range.Start.Index, html.Length);
int end = Math.Clamp(range.End.Index, start, html.Length);
string text = html[start..end];
string formatted = FormatRawText(text, extendSubscript);
if(!string.Equals(text, formatted, StringComparison.Ordinal))
{
changes.Add((range.Start.Index, range.End.Index, formatted));
changes.Add((start, end, formatted));
}
}
},
@@ -153,13 +179,7 @@ public sealed class MarkdownRenderer
{
continue;
}
var rewritten = new StringBuilder(html);
for(int index = changes.Count - 1; index >= 0; index--)
{
(int start, int end, string value) = changes[index];
rewritten.Remove(start, end - start).Insert(start, value);
}
string[] lines = rewritten.ToString().Split('\n');
string[] lines = Rewrite(html, changes).Split('\n');
for(int index = 0; index < block.Lines.Count; index++)
{
block.Lines.Lines[index].Slice = new Markdig.Helpers.StringSlice(lines[index]);
@@ -170,6 +190,28 @@ public sealed class MarkdownRenderer
/// <summary>
/// Applies replacements in one forward pass, so the work is linear in the block. Malformed markup
/// can report a text run that starts inside an earlier one; that run is left as authored.
/// </summary>
private static string Rewrite(string html, List<(int Start, int End, string Value)> changes)
{
var rewritten = new StringBuilder(html.Length + 64);
int copied = 0;
foreach((int start, int end, string value) in changes)
{
if(start < copied)
{
continue;
}
rewritten.Append(html, copied, start - copied).Append(value);
copied = end;
}
return rewritten.Append(html, copied, html.Length - copied).ToString();
}
/// <summary>Reference extension syntax applies only to tokenized visible text, with bounded regex work and unchanged entity spelling.</summary>
private string FormatRawText(string text, bool extendSubscript)
{
@@ -203,10 +245,12 @@ public sealed class MarkdownRenderer
}
else if(node is HtmlBlock block)
{
var nesting = new HtmlNesting();
var parser = new HtmlParser(new HtmlParserOptions
{
OnToken = (token, _) =>
{
nesting.Observe(token);
if(token.Type is HtmlTokenType.StartTag or HtmlTokenType.EndTag && token.Name is "code" or "pre")
{
codeDepth = Math.Max(0, codeDepth + (token.Type == HtmlTokenType.StartTag ? 1 : -1));
@@ -6,7 +6,6 @@
using System.Globalization;
using System.Text;
using System.Text.Encodings.Web;
using System.Text.Json;
using System.Text.Json.Nodes;
@@ -16,24 +15,8 @@ namespace MarkdownViewr.Windows.Core.Themes;
/// <summary>Validates Darin's version-one theme format before generating passive document CSS.</summary>
public sealed class ReaderTheme
{
/// <summary>The largest theme file accepted for import; bounds the read before the complete JSON text is allocated.</summary>
/// <summary>Bounds schema input before a native file read allocates the complete JSON text.</summary>
public const int MaximumCharacters = 128 * 1024;
/// <summary>
/// The largest theme the app keeps. Renaming or editing rewrites the whole theme, and JSON
/// writes some characters (emoji, no-break spaces, private-use glyphs) as six-character
/// escapes, so a kept theme can be several times the size of the file it was imported from.
/// The bound leaves room for that, so a theme that could be imported can always be renamed.
/// </summary>
public const int MaximumStoredCharacters = 8 * MaximumCharacters;
/// <summary>
/// How a renamed or edited theme is written back. Quote marks, angle brackets and most
/// non-ASCII letters are written as themselves instead of as six-character escapes, which
/// keeps ordinary CSS and text close to its imported size. Theme JSON is stored and exported,
/// never placed in a page.
/// </summary>
private static readonly JsonSerializerOptions s_compact = new() { Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping };
private static readonly string[] s_colors = ["background", "text", "heading1", "heading2", "heading3", "heading4", "heading5", "heading6", "link", "codeBackground", "codeText", "blockquoteBorder", "blockquoteBackground", "highlightBackground", "highlightText"];
private static readonly string[] s_sizes = ["baseFontSize", "h1Size", "h2Size", "h3Size", "h4Size", "h5Size", "h6Size", "codeFontSize", "lineHeight"];
private static readonly string s_baseStyles = LoadBaseStyles();
@@ -76,7 +59,7 @@ public sealed class ReaderTheme
{
JsonNode source = JsonNode.Parse(Json)!;
source["name"] = name;
return ParseCompatible(source.ToJsonString(s_compact));
return ParseCompatible(source.ToJsonString());
}
@@ -120,7 +103,7 @@ public sealed class ReaderTheme
}
source["colors"]![key] = value?.Trim();
}
return ParseCompatible(source.ToJsonString(s_compact));
return ParseCompatible(source.ToJsonString());
}
@@ -167,14 +150,13 @@ public sealed class ReaderTheme
private static ReaderTheme ParseSchema(string json, bool allowNewer)
{
ArgumentNullException.ThrowIfNull(json);
if(json.Length > MaximumStoredCharacters)
if(json.Length > MaximumCharacters)
{
throw new JsonException("The theme is too large.");
throw new JsonException("The theme exceeds the 128 Ki-character limit.");
}
using JsonDocument document = ParseDocument(json);
using var document = JsonDocument.Parse(json, new JsonDocumentOptions { MaxDepth = 16 });
JsonElement root = document.RootElement;
RequireObject(root);
RequireReadableText(root);
int schemaVersion = 1;
if(root.TryGetProperty("schemaVersion", out JsonElement version) && (version.ValueKind != JsonValueKind.Number || !version.TryGetInt32(out schemaVersion) || schemaVersion < 1 || !allowNewer && schemaVersion != 1))
{
@@ -296,68 +278,6 @@ public sealed class ReaderTheme
/// <summary>Reads the theme text as JSON; text that is not well-formed UTF-16 is an invalid theme like any other malformed input.</summary>
private static JsonDocument ParseDocument(string json)
{
try
{
return JsonDocument.Parse(json, new JsonDocumentOptions { MaxDepth = 16 });
}
catch(ArgumentException exception)
{
throw new JsonException("The theme contains text that cannot be decoded.", exception);
}
}
/// <summary>
/// Checks every property name and string in the theme once, including ones this version does
/// not read, because a kept theme is later renamed, edited and re-serialized as a whole. An
/// unpaired surrogate escape is valid JSON syntax with no string value, and a repeated
/// property name has no single value; both are invalid themes.
/// </summary>
private static void RequireReadableText(JsonElement root)
{
try
{
var pending = new Stack<JsonElement>();
pending.Push(root);
while(pending.TryPop(out JsonElement element))
{
if(element.ValueKind == JsonValueKind.Object)
{
var names = new HashSet<string>(StringComparer.Ordinal);
foreach(JsonProperty property in element.EnumerateObject())
{
if(!names.Add(property.Name))
{
throw new JsonException("The theme repeats a property: " + property.Name);
}
pending.Push(property.Value);
}
}
else if(element.ValueKind == JsonValueKind.Array)
{
foreach(JsonElement item in element.EnumerateArray())
{
pending.Push(item);
}
}
else if(element.ValueKind == JsonValueKind.String)
{
_ = element.GetString();
}
}
}
catch(InvalidOperationException exception)
{
throw new JsonException("The theme contains text that cannot be decoded.", exception);
}
}
/// <summary>Prevents wrong-shaped JSON from reaching property accessors.</summary>
private static void RequireObject(JsonElement element)
{
@@ -33,13 +33,14 @@ public static class ThemeJson
public static string SuggestedFileName(ReaderTheme theme)
{
ArgumentNullException.ThrowIfNull(theme);
string stem = string.Concat(theme.Name.Select(character => WindowsFileNames.InvalidCharacters.Contains(character, StringComparison.Ordinal) ? '_' : character))
string stem = string.Concat(theme.Name.Select(character => "<>:\"/\\|?*".Contains(character, StringComparison.Ordinal) ? '_' : character))
.Replace(' ', '-').ToLowerInvariant().Trim('.', '-');
if(stem.Length == 0)
{
stem = "theme";
}
if(WindowsFileNames.IsReservedDeviceName(stem))
string device = stem.Split('.')[0];
if(device is "con" or "prn" or "aux" or "nul" || device.Length == 4 && (device.StartsWith("com", StringComparison.Ordinal) || device.StartsWith("lpt", StringComparison.Ordinal)) && device[3] is >= '1' and <= '9' or '¹' or '²' or '³')
{
stem = "theme-" + stem;
}
@@ -1,39 +0,0 @@
/*
* Copyright (c) 2026 James Maes
* SPDX-License-Identifier: MIT
*/
namespace MarkdownViewr.Windows.Core;
/// <summary>
/// The Windows file-name rules this application relies on, written out instead of asked of the
/// running platform: the characters a name cannot contain and the names that address a device.
/// </summary>
public static class WindowsFileNames
{
/// <summary>Printable characters that cannot appear in a Windows file or folder name. Control characters are also forbidden; callers refuse those themselves.</summary>
public const string InvalidCharacters = "<>:\"/\\|?*";
private static readonly HashSet<string> s_devices = new(StringComparer.OrdinalIgnoreCase)
{
"CON", "PRN", "AUX", "NUL", "CONIN$", "CONOUT$",
"COM0", "COM1", "COM2", "COM3", "COM4", "COM5", "COM6", "COM7", "COM8", "COM9", "COM¹", "COM²", "COM³",
"LPT0", "LPT1", "LPT2", "LPT3", "LPT4", "LPT5", "LPT6", "LPT7", "LPT8", "LPT9", "LPT¹", "LPT²", "LPT³",
};
/// <summary>
/// Whether a single name addresses a device under the legacy Win32 rule: any letter case, and
/// ignoring everything after the first dot and any spaces before it, so <c>nul.txt</c> and
/// <c>COM1 .log</c> count. Current Windows versions resolve fewer of these spellings to a
/// device; the rule is applied in full on every version so the answer never depends on it.
/// </summary>
public static bool IsReservedDeviceName(string name)
{
ArgumentNullException.ThrowIfNull(name);
int dot = name.IndexOf('.', StringComparison.Ordinal);
return s_devices.Contains((dot < 0 ? name : name[..dot]).TrimEnd(' '));
}
}
@@ -1,217 +0,0 @@
/*
* Copyright (c) 2026 James Maes
* SPDX-License-Identifier: MIT
*/
using MarkdownViewr.Windows.Core.Documents;
namespace MarkdownViewr.Windows.Core.Tests;
/// <summary>
/// Each resource-policy check is exercised alone: a request that differs from a valid one in a
/// single component must be denied by that component's check, not by an unrelated one.
/// </summary>
public sealed class DocumentResourcePolicyBoundaryTests
{
/// <summary>The valid baseline every single-component variation below is derived from.</summary>
[Fact]
public void GetRelativePath_OwnDocumentRequest_IsAccepted()
{
var policy = new DocumentResourcePolicy();
Assert.Equal("image.png", policy.GetImageRelativePath(Vary(policy, "image.png", _ => { })));
Assert.Equal("child.md", policy.GetDocumentRelativePath(Vary(policy, "child.md", _ => { })));
}
/// <summary>Plain HTTP on the same host, port and path is not the document's origin.</summary>
[Fact]
public void GetRelativePath_OtherScheme_IsDenied()
{
var policy = new DocumentResourcePolicy();
Uri image = Vary(policy, "image.png", builder =>
{
builder.Scheme = "http";
builder.Port = 443;
});
Assert.Equal(443, image.Port);
Assert.Null(policy.GetImageRelativePath(image));
Assert.Null(policy.GetDocumentRelativePath(Vary(policy, "child.md", builder =>
{
builder.Scheme = "http";
builder.Port = 443;
})));
}
/// <summary>Another port on the same host is another origin.</summary>
[Fact]
public void GetRelativePath_OtherPort_IsDenied()
{
var policy = new DocumentResourcePolicy();
Assert.Null(policy.GetImageRelativePath(Vary(policy, "image.png", builder => builder.Port = 444)));
Assert.Null(policy.GetDocumentRelativePath(Vary(policy, "child.md", builder => builder.Port = 8443)));
}
/// <summary>Credentials in the request never reach a resource.</summary>
[Fact]
public void GetRelativePath_UserInformation_IsDenied()
{
var policy = new DocumentResourcePolicy();
Assert.Null(policy.GetImageRelativePath(Vary(policy, "image.png", builder => builder.UserName = "user")));
Assert.Null(policy.GetDocumentRelativePath(Vary(policy, "child.md", builder =>
{
builder.UserName = "user";
builder.Password = "secret";
})));
}
/// <summary>Another host is denied, including a subdomain of the viewer's host and a host that merely starts with it.</summary>
[Theory]
[InlineData("example.com")]
[InlineData("sub.viewer.markdownviewr.invalid")]
[InlineData("viewer.markdownviewr.invalid.example.com")]
public void GetRelativePath_OtherHost_IsDenied(string host)
{
var policy = new DocumentResourcePolicy();
Assert.Null(policy.GetImageRelativePath(Vary(policy, "image.png", builder => builder.Host = host)));
Assert.Null(policy.GetDocumentRelativePath(Vary(policy, "child.md", builder => builder.Host = host)));
}
/// <summary>The served image types and the openable document types are exactly these sets.</summary>
[Fact]
public void Extensions_ConfiguredSets_AreExactlyTheListedTypes()
{
Assert.Equal([".avif", ".bmp", ".gif", ".ico", ".jpeg", ".jpg", ".png", ".svg", ".webp"], DocumentResourcePolicy.ImageExtensions.Order(StringComparer.Ordinal), StringComparer.Ordinal);
Assert.Equal([".markdown", ".md", ".mdown", ".mkd", ".txt"], DocumentResourcePolicy.DocumentExtensions.Order(StringComparer.Ordinal), StringComparer.Ordinal);
}
/// <summary>The document's own path prefix is matched exactly; another letter case is another document.</summary>
[Fact]
public void GetRelativePath_PrefixInAnotherLetterCase_IsDenied()
{
var policy = new DocumentResourcePolicy();
string shouted = policy.DocumentUri.AbsoluteUri.Replace("/documents/", "/DOCUMENTS/", StringComparison.Ordinal);
Assert.NotEqual(policy.DocumentUri.AbsoluteUri, shouted, StringComparer.Ordinal);
Assert.Null(policy.GetImageRelativePath(new Uri(new Uri(shouted), "image.png")));
Assert.Null(policy.GetDocumentRelativePath(new Uri(new Uri(shouted), "child.md")));
Assert.Null(policy.GetHeadingIndex(new Uri(shouted + "#mv-heading-0"), 3));
Assert.Equal(0, policy.GetHeadingIndex(new Uri(policy.DocumentUri.AbsoluteUri + "#mv-heading-0"), 3));
}
/// <summary>Image types are served in any letter case; documents, pages, scripts and executables are not images.</summary>
[Theory]
[InlineData(".png", true)]
[InlineData(".jpg", true)]
[InlineData(".jpeg", true)]
[InlineData(".gif", true)]
[InlineData(".bmp", true)]
[InlineData(".webp", true)]
[InlineData(".svg", true)]
[InlineData(".avif", true)]
[InlineData(".ico", true)]
[InlineData(".PNG", true)]
[InlineData(".md", false)]
[InlineData(".markdown", false)]
[InlineData(".txt", false)]
[InlineData(".html", false)]
[InlineData(".htm", false)]
[InlineData(".js", false)]
[InlineData(".css", false)]
[InlineData(".json", false)]
[InlineData(".pdf", false)]
[InlineData(".tiff", false)]
[InlineData(".exe", false)]
[InlineData(".lnk", false)]
[InlineData(".url", false)]
[InlineData("", false)]
public void GetImageRelativePath_Extension_ServesOnlyImageTypes(string extension, bool served)
{
var policy = new DocumentResourcePolicy();
Assert.Equal(served ? "file" + extension : null, policy.GetImageRelativePath(new Uri(policy.DocumentUri, "file" + extension)));
}
/// <summary>Document types open in a new reader in any letter case; pages, images, scripts and executables do not.</summary>
[Theory]
[InlineData(".md", true)]
[InlineData(".markdown", true)]
[InlineData(".mdown", true)]
[InlineData(".mkd", true)]
[InlineData(".txt", true)]
[InlineData(".MD", true)]
[InlineData(".html", false)]
[InlineData(".htm", false)]
[InlineData(".png", false)]
[InlineData(".svg", false)]
[InlineData(".json", false)]
[InlineData(".pdf", false)]
[InlineData(".exe", false)]
[InlineData(".bat", false)]
[InlineData(".cmd", false)]
[InlineData(".ps1", false)]
[InlineData(".lnk", false)]
[InlineData(".url", false)]
[InlineData(".mdx", false)]
[InlineData("", false)]
public void GetDocumentRelativePath_Extension_OpensOnlyDocumentTypes(string extension, bool opened)
{
var policy = new DocumentResourcePolicy();
Assert.Equal(opened ? "file" + extension : null, policy.GetDocumentRelativePath(new Uri(policy.DocumentUri, "file" + extension)));
}
/// <summary>Each character Windows forbids in a name is refused on its own, for images and documents.</summary>
[Theory]
[InlineData("%3C")]
[InlineData("%3E")]
[InlineData("%3A")]
[InlineData("%22")]
[InlineData("%5C")]
[InlineData("%7C")]
[InlineData("%3F")]
[InlineData("%2A")]
public void GetRelativePath_ForbiddenCharacter_IsDenied(string encoded)
{
var policy = new DocumentResourcePolicy();
Assert.Null(policy.GetImageRelativePath(new Uri(policy.DocumentUri, "images/a" + encoded + "b.png")));
Assert.Null(policy.GetImageRelativePath(new Uri(policy.DocumentUri, "im" + encoded + "ages/ab.png")));
Assert.Null(policy.GetDocumentRelativePath(new Uri(policy.DocumentUri, "docs/a" + encoded + "b.md")));
}
/// <summary>The generated heading fragment is matched exactly; another letter case is not a heading target.</summary>
[Theory]
[InlineData("#MV-HEADING-0")]
[InlineData("#Mv-Heading-0")]
public void GetHeadingIndex_OtherSpelling_IsNotAHeadingTarget(string fragment)
{
var policy = new DocumentResourcePolicy();
Assert.Null(policy.GetHeadingIndex(new Uri(policy.DocumentUri.AbsoluteUri + fragment), 3));
}
/// <summary>Builds this document's own resource request and changes exactly one component of it.</summary>
private static Uri Vary(DocumentResourcePolicy policy, string file, Action<UriBuilder> change)
{
var builder = new UriBuilder(new Uri(policy.DocumentUri, file));
change(builder);
return builder.Uri;
}
}
@@ -0,0 +1,218 @@
/*
* Copyright (c) 2026 James Maes
* SPDX-License-Identifier: MIT
*/
using AngleSharp.Html.Dom;
using AngleSharp.Html.Parser;
using MarkdownViewr.Windows.Core.Documents;
namespace MarkdownViewr.Windows.Core.Tests;
/// <summary>
/// Deeply nested markup must be refused as an ordinary error. The renders here run on a thread
/// with a quarter of the default stack, so a recursive walk that the bound failed to stop would
/// end the test run instead of passing by luck.
/// </summary>
public sealed class HtmlNestingTests
{
private const int SmallStackBytes = 256 * 1024;
/// <summary>The deepest markup the bound allows renders completely, with stack to spare.</summary>
[Fact]
public void Render_NestingAtTheLimit_RendersOnASmallStack()
{
int levels = HtmlNesting.MaximumDepth - 1;
string markup = Repeat("<div>", levels) + "deepest" + Repeat("</div>", levels);
string? html = null;
Assert.Null(OnSmallStack(() => html = new MarkdownRenderer().Render(markup)));
using IHtmlDocument parsed = new HtmlParser().ParseDocument(html!);
Assert.Equal(levels, parsed.QuerySelectorAll("div").Length);
Assert.Contains("deepest", html, StringComparison.Ordinal);
Assert.Equal(256, HtmlNesting.MaximumDepth);
}
/// <summary>One level past the limit is an argument error, the failure the reader already reports for an unsupported document.</summary>
[Fact]
public void Render_NestingOnePastTheLimit_IsRejected()
{
string markup = Repeat("<div>", HtmlNesting.MaximumDepth) + "too deep";
Assert.IsType<ArgumentException>(OnSmallStack(() => new MarkdownRenderer().Render(markup)));
}
/// <summary>
/// A few kilobytes of nested elements, in every shape that nests, are refused before any
/// library walks the tree recursively.
/// </summary>
[Theory]
[InlineData("<div>", 3000)]
[InlineData("<b>", 3000)]
[InlineData("<span><i>", 1500)]
[InlineData("<table><tr><td>", 3000)]
[InlineData("<blockquote>", 2000)]
[InlineData("<ul><li>", 2000)]
[InlineData("<details><summary>s</summary>", 1500)]
[InlineData("<div></section>", 3000)]
public void Render_DeeplyNestedMarkup_IsRejectedBeforeAnyRecursiveWalk(string unit, int count)
{
string markup = Repeat(unit, count) + "x";
Assert.IsType<ArgumentException>(OnSmallStack(() => new MarkdownRenderer().Render(markup)));
Assert.IsType<ArgumentException>(OnSmallStack(() => _ = new DocumentOutline(markup)));
}
/// <summary>
/// Nesting far past the limit is stopped by the count kept while tokens arrive, not after the
/// whole input has been parsed: parsing it to the end takes time that grows with its square.
/// </summary>
[Fact]
public void Render_RunawayNesting_IsStoppedWhileParsing()
{
string block = Repeat("<div>", 100000) + "x";
ArgumentException stoppedInBlock = Assert.IsType<ArgumentException>(OnSmallStack(() => new MarkdownRenderer().Render(block)));
Assert.Equal("token", stoppedInBlock.ParamName);
string inline = "Paragraph " + Repeat("<b>", 100000) + "x";
ArgumentException stoppedInline = Assert.IsType<ArgumentException>(OnSmallStack(() => new MarkdownRenderer().Render(inline)));
Assert.Equal("token", stoppedInline.ParamName);
ArgumentException measured = Assert.IsType<ArgumentException>(OnSmallStack(() => new MarkdownRenderer().Render(Repeat("<div>", 300) + "x")));
Assert.Equal("root", measured.ParamName);
}
/// <summary>Nesting assembled from inline tags in a paragraph, or from many separate blocks, is measured as a whole.</summary>
[Theory]
[InlineData("Paragraph ", "<b>", "")]
[InlineData("", "<div>", "\n\n")]
[InlineData("- item ", "<span>", "")]
[InlineData("> quoted ", "<i>", "")]
public void Render_NestingAcrossInlineTagsAndBlocks_IsRejected(string prefix, string unit, string separator)
{
string markup = prefix + string.Concat(Enumerable.Repeat(unit + separator, 400)) + "x";
Assert.IsType<ArgumentException>(OnSmallStack(() => new MarkdownRenderer().Render(markup)));
}
/// <summary>Nesting hidden in frontmatter rendered as Markdown is bounded like the body.</summary>
[Fact]
public void Render_DeepNestingInMarkdownFrontmatter_IsRejected()
{
string markup = "---\n" + Repeat("<div>", 3000) + "\n---\nBody";
Assert.IsType<ArgumentException>(OnSmallStack(() => new MarkdownRenderer().Render(markup, FrontmatterMode.Markdown)));
Assert.Null(OnSmallStack(() => new MarkdownRenderer().Render(markup, FrontmatterMode.Hide)));
}
/// <summary>Wide documents are not deep: thousands of siblings, unclosed paragraphs, list items and cells render normally.</summary>
[Theory]
[InlineData("<div>x</div>")]
[InlineData("<p>x")]
[InlineData("x<br>")]
[InlineData("<span>x</span><b>y</b>")]
public void Render_ManySiblings_AreNotMistakenForNesting(string unit)
{
string markup = "<div>" + Repeat(unit, HtmlNesting.MaximumOpenTags + 500) + "</div>";
string? html = null;
Assert.Null(OnSmallStack(() => html = new MarkdownRenderer().Render(markup)));
Assert.Contains("x", html, StringComparison.Ordinal);
}
/// <summary>List items and table cells left unclosed are siblings, however many there are.</summary>
[Fact]
public void Render_ManyUnclosedItemsAndCells_AreNotMistakenForNesting()
{
string markup = "<ul>" + Repeat("<li>item", 5000) + "</ul>\n\n<table>" + Repeat("<tr><td>a<td>b", 5000) + "</table>";
string? html = null;
Assert.Null(OnSmallStack(() => html = new MarkdownRenderer().Render(markup)));
using IHtmlDocument parsed = new HtmlParser().ParseDocument(html!);
Assert.Equal(5000, parsed.QuerySelectorAll("li").Length);
Assert.Equal(10000, parsed.QuerySelectorAll("td").Length);
}
/// <summary>The early count allows exactly its bound of open tags and stops at the next one.</summary>
[Theory]
[InlineData(HtmlNesting.MaximumOpenTags, false)]
[InlineData(HtmlNesting.MaximumOpenTags + 1, true)]
public void Observe_OpenTagsAtAndPastTheBound_StopsExactlyPastIt(int count, bool stopped)
{
Assert.Equal(stopped, Record.Exception(() => Tokenize(Repeat("<div>", count))) is ArgumentException);
Assert.Equal(4096, HtmlNesting.MaximumOpenTags);
}
/// <summary>
/// The early count never falls below the real depth: an end tag closes only the tag on top,
/// so an end tag the parser would ignore cannot be used to hide nesting from the count.
/// </summary>
[Theory]
[InlineData("<div></span>")]
[InlineData("<div><table><tr><td></div>")]
[InlineData("<section><p></article>")]
public void Observe_EndTagThatDoesNotCloseTheOpenTag_DoesNotReduceTheCount(string unit)
=> Assert.IsType<ArgumentException>(Record.Exception(() => Tokenize(Repeat(unit, HtmlNesting.MaximumOpenTags + 1))));
/// <summary>Properly closed elements, void elements and self-closing siblings never accumulate.</summary>
[Theory]
[InlineData("<div><span>x</span></div>")]
[InlineData("<img src=x><br><hr><input>")]
[InlineData("<p>x<li>y<td>z<option>o")]
public void Observe_ClosedVoidAndImplicitlyClosedTags_DoNotAccumulate(string unit)
=> Assert.Null(Record.Exception(() => Tokenize(Repeat(unit, HtmlNesting.MaximumOpenTags + 1))));
/// <summary>The exact measurement walks every branch and counts from the root it is given.</summary>
[Fact]
public void ThrowIfTooDeep_ShallowWideAndBranchingTrees_AreAccepted()
{
using IHtmlDocument empty = new HtmlParser().ParseDocument("");
HtmlNesting.ThrowIfTooDeep(empty.Body!);
using IHtmlDocument branching = new HtmlParser().ParseDocument(Repeat("<div>", 200) + "a" + Repeat("</div>", 200) + "<p>b</p>" + Repeat("<span>c</span>", 2000) + Repeat("<div>", 254) + "d");
HtmlNesting.ThrowIfTooDeep(branching.Body!);
using IHtmlDocument late = new HtmlParser().ParseDocument("<p>first</p><p>second</p>" + Repeat("<div>", 256) + "deep");
Assert.Throws<ArgumentException>(() => HtmlNesting.ThrowIfTooDeep(late.Body!));
}
/// <summary>Feeds markup through a parser whose tokens go to a fresh count, as the renderer does.</summary>
private static void Tokenize(string html)
{
var nesting = new HtmlNesting();
using IHtmlDocument document = new HtmlParser(new HtmlParserOptions { OnToken = (token, _) => nesting.Observe(token) }).ParseDocument(html);
}
/// <summary>Runs on a thread with a quarter of the default stack and returns what it threw, if anything.</summary>
private static Exception? OnSmallStack(Action action)
{
Exception? failure = null;
var thread = new Thread(() => failure = Record.Exception(action), SmallStackBytes);
thread.Start();
thread.Join();
return failure;
}
/// <summary>The unit repeated without separators.</summary>
private static string Repeat(string unit, int count) => string.Concat(Enumerable.Repeat(unit, count));
}
@@ -124,15 +124,12 @@ public sealed class ReaderThemeTests
/// <summary>Null input is refused, and a theme is kept up to the stored size limit exactly and refused one character past it.</summary>
/// <summary>Null and oversized input are rejected before parser work.</summary>
[Fact]
public void Parse_OutsideSizeContract_RejectsInput()
{
Assert.Throws<ArgumentNullException>(() => ReaderTheme.Parse(null!));
string valid = ThemeCatalog.Find("Nord").Json;
Assert.Equal("Nord", ReaderTheme.Parse(valid.PadRight(ReaderTheme.MaximumStoredCharacters)).Name);
Assert.Throws<JsonException>(() => ReaderTheme.Parse(valid.PadRight(ReaderTheme.MaximumStoredCharacters + 1)));
Assert.Equal(8 * 128 * 1024, ReaderTheme.MaximumStoredCharacters);
Assert.Throws<JsonException>(() => ReaderTheme.Parse(new string(' ', 128 * 1024 + 1)));
}
@@ -0,0 +1,126 @@
/*
* Copyright (c) 2026 James Maes
* SPDX-License-Identifier: MIT
*/
using AngleSharp.Html.Dom;
using AngleSharp.Html.Parser;
using MarkdownViewr.Windows.Core.Documents;
namespace MarkdownViewr.Windows.Core.Tests;
/// <summary>Malformed and very repetitive documents render, with work that grows in step with their size.</summary>
public sealed class RendererRobustnessTests
{
/// <summary>An unterminated script followed by a comment opener reports a text run past the end of its block; the document still opens and stays passive.</summary>
[Theory]
[InlineData("<script>x<!--")]
[InlineData("<script><!--")]
[InlineData("<script>==a==\n<!--")]
[InlineData("<script>*<!--")]
[InlineData("<div>==kept==</div><script>\n<!--\n")]
public void Render_UnterminatedScriptAndComment_OpensAsPassiveMarkup(string markdown)
{
string html = new MarkdownRenderer().Render(markdown + "\n\nAfter the block.");
Assert.DoesNotContain("<script", html, StringComparison.OrdinalIgnoreCase);
var outline = new DocumentOutline("# Title\n\n" + markdown);
Assert.Equal("Title", Assert.Single(outline.Headings).Title);
Assert.DoesNotContain("<script", outline.Html, StringComparison.OrdinalIgnoreCase);
}
/// <summary>
/// Markup is parsed with scripting on, as the sanitizer library parses it: the content of a
/// noscript element is text that ends at the first closing tag, wherever that tag appears.
/// </summary>
[Fact]
public void Render_NoscriptContent_IsParsedAsTextEndingAtItsFirstClosingTag()
{
const string Markdown = "<noscript><p title=\"</noscript><img src=x onerror=execute() alt=after>\"></noscript>";
using IHtmlDocument parsed = new HtmlParser().ParseDocument(new MarkdownRenderer().Render(Markdown));
AngleSharp.Dom.IElement image = Assert.Single(parsed.QuerySelectorAll("img"));
Assert.Equal(["alt", "src"], image.Attributes.Select(attribute => attribute.Name).Order(StringComparer.Ordinal), StringComparer.Ordinal);
Assert.Empty(parsed.QuerySelectorAll("noscript,p[title]"));
}
/// <summary>Markup broken so that one text run starts inside another is left as authored there, formatted elsewhere, and still sanitized.</summary>
[Fact]
public void Render_OverlappingTextRuns_RendersWithoutRewritingTheOverlap()
{
const string Markdown = "<iframe srcdoc='<script>execute()</scr<pre><code>==literal== ^literal^ ++literal++</code></pre>\nipt>'></iframe></style><script>execute()</script>";
string html = new MarkdownRenderer().Render(Markdown);
using IHtmlDocument parsed = new HtmlParser().ParseDocument(html);
Assert.Empty(parsed.QuerySelectorAll("script,iframe,style"));
Assert.DoesNotContain("execute()</script>", html, StringComparison.Ordinal);
}
/// <summary>Every text run in a long raw block is formatted once, in place, in document order.</summary>
[Fact]
public void Render_ManyFormattedRunsInOneBlock_FormatsEachInOrder()
{
const int Runs = 3000;
string block = "<div>" + string.Concat(Enumerable.Range(0, Runs).Select(index => $"<span>==m{index}== and ^s{index}^</span>")) + "</div>";
using IHtmlDocument parsed = new HtmlParser().ParseDocument(new MarkdownRenderer().Render(block));
Assert.Equal(Enumerable.Range(0, Runs).Select(index => "m" + index.ToString(System.Globalization.CultureInfo.InvariantCulture)), parsed.QuerySelectorAll("mark").Select(mark => mark.TextContent), StringComparer.Ordinal);
Assert.Equal(Enumerable.Range(0, Runs).Select(index => "s" + index.ToString(System.Globalization.CultureInfo.InvariantCulture)), parsed.QuerySelectorAll("sup").Select(sup => sup.TextContent), StringComparer.Ordinal);
Assert.Equal(Runs, parsed.QuerySelectorAll("span").Length);
}
/// <summary>A raw block whose text needs no formatting is passed through unchanged between its neighbours.</summary>
[Fact]
public void Render_FormattedRunsBetweenUnchangedText_KeepsTheTextAroundThem()
{
using IHtmlDocument parsed = new HtmlParser().ParseDocument(new MarkdownRenderer().Render("<div>before <b>==first==</b> middle <i>plain</i> ++last++ after</div>"));
Assert.Equal("before first middle plain last after", parsed.Body!.TextContent.Trim());
Assert.Equal("first", Assert.Single(parsed.QuerySelectorAll("mark")).TextContent);
Assert.Equal("last", Assert.Single(parsed.QuerySelectorAll("ins")).TextContent);
}
/// <summary>Thousands of headings with one title get distinct anchors, and a link to any of them finds its heading.</summary>
[Fact]
public void Outline_ManyHeadingsWithTheSameTitle_AnchorEachOne()
{
const int Count = 4000;
string markdown = string.Concat(Enumerable.Repeat("# Same\n\n", Count)) + "[first](#same) [second](#same-1) [last](#same-3999) [none](#same-4000)\n";
var outline = new DocumentOutline(markdown);
Assert.Equal(Count, outline.Headings.Count);
using IHtmlDocument parsed = new HtmlParser().ParseDocument(outline.Html);
Assert.Equal(["#mv-heading-0", "#mv-heading-1", "#mv-heading-3999", "#same-4000"], parsed.QuerySelectorAll("a").Select(link => link.GetAttribute("href")!), StringComparer.Ordinal);
}
/// <summary>A heading that is literally named like a generated anchor keeps its own anchor; repeats step past it.</summary>
[Theory]
[InlineData("# Same\n\n# Same-1\n\n# Same\n\n# Same\n\n", new[] { "#same", "#same-1", "#same-2", "#same-3" })]
[InlineData("# Same-1\n\n# Same\n\n# Same\n\n# Same-1\n\n", new[] { "#same-1", "#same", "#same-2", "#same-1-1" })]
[InlineData("# A\n\n# B\n\n# A\n\n# B\n\n", new[] { "#a", "#b", "#a-1", "#b-1" })]
public void Outline_RepeatedAndLiteralSuffixTitles_AnchorInDocumentOrder(string headings, string[] anchors)
{
string markdown = headings + string.Concat(anchors.Select(anchor => $"[link]({anchor}) "));
using IHtmlDocument parsed = new HtmlParser().ParseDocument(new DocumentOutline(markdown).Html);
Assert.Equal(["#mv-heading-0", "#mv-heading-1", "#mv-heading-2", "#mv-heading-3"], parsed.QuerySelectorAll("a").Select(link => link.GetAttribute("href")!), StringComparer.Ordinal);
}
/// <summary>A load that is no longer wanted stops instead of building its outline.</summary>
[Fact]
public void Outline_CancelledBeforeItStarts_StopsWithoutBuilding()
{
using var cancellation = new CancellationTokenSource();
cancellation.Cancel();
Assert.Throws<OperationCanceledException>(() => new DocumentOutline("# Title\n\nBody", cancellation: cancellation.Token));
Assert.Equal("Title", Assert.Single(new DocumentOutline("# Title\n\nBody", cancellation: CancellationToken.None).Headings).Title);
}
}
@@ -1,220 +0,0 @@
/*
* Copyright (c) 2026 James Maes
* SPDX-License-Identifier: MIT
*/
using AngleSharp.Dom;
using AngleSharp.Html.Dom;
using AngleSharp.Html.Parser;
using Ganss.Xss;
using MarkdownViewr.Windows.Core.Documents;
namespace MarkdownViewr.Windows.Core.Tests;
/// <summary>
/// The elements, attributes and link schemes authored HTML may keep. The configured policy is
/// compared with the lists below as sets, so any change to it has to be made here as well, and
/// the rendering tests show the policy doing what the lists say.
/// </summary>
public sealed class SanitizerAllowlistTests
{
private static readonly string[] s_allowedTags =
[
"a", "abbr", "b", "blockquote", "br", "caption", "code", "dd", "del", "details", "div", "dl", "dt", "em",
"h1", "h2", "h3", "h4", "h5", "h6", "hr", "i", "img", "input", "ins", "kbd", "li", "mark", "ol", "p", "pre",
"s", "small", "span", "strong", "sub", "summary", "sup", "table", "tbody", "td", "th", "thead", "tr", "ul",
];
private static readonly string[] s_otherTags =
[
"acronym", "address", "applet", "area", "article", "aside", "audio", "base", "basefont", "bdi", "bdo", "bgsound", "big",
"blink", "button", "canvas", "center", "cite", "data", "datalist", "dfn", "dialog", "dir", "embed", "fencedframe",
"fieldset", "figcaption", "figure", "font", "footer", "form", "header", "hgroup", "iframe", "keygen", "label", "legend",
"link", "listing", "main", "map", "marquee", "math", "menu", "menuitem", "meta", "meter", "nav", "nobr", "noembed",
"noframes", "noscript", "object", "optgroup", "option", "output", "param", "picture", "plaintext", "portal", "progress",
"q", "rb", "rp", "rt", "rtc", "ruby", "samp", "script", "search", "section", "select", "selectedcontent", "slot", "source",
"strike", "style", "svg", "template", "textarea", "time", "title", "track", "tt", "u", "var", "video", "wbr", "xmp",
"custom-element",
];
private static readonly string[] s_allowedAttributes =
[
"align", "alt", "checked", "class", "colspan", "disabled", "height", "href", "rowspan", "src", "title", "type", "width",
];
private static readonly string[] s_otherAttributes =
[
"accesskey", "action", "allow", "as", "autocapitalize", "autofocus", "autoplay", "background", "bgcolor", "border",
"cellpadding", "cellspacing", "charset", "cite", "color", "content", "contenteditable", "controls", "coords",
"crossorigin", "data", "data-mv-body", "data-mv-source-fixed", "data-x", "datetime", "dir", "download", "draggable",
"enctype", "enterkeyhint", "face", "for", "form", "formaction", "formmethod", "formtarget", "headers", "hidden",
"http-equiv", "id", "inert", "inputmode", "integrity", "is", "ismap", "itemprop", "label", "lang", "list", "loading",
"longdesc", "loop", "lowsrc", "manifest", "max", "maxlength", "media", "method", "min", "multiple", "muted", "name",
"nonce", "novalidate", "nowrap", "onclick", "onerror", "onfocus", "onload", "onmouseover", "onpointerdown", "ontoggle",
"onwheel", "open", "part", "pattern", "ping", "placeholder", "popover", "popovertarget", "poster", "preload", "readonly",
"referrerpolicy", "rel", "required", "reversed", "role", "sandbox", "scope", "selected", "shape", "size", "sizes", "slot",
"span", "spellcheck", "srcdoc", "srclang", "srcset", "start", "step", "tabindex", "target", "translate", "usemap",
"valign", "value", "wrap", "xlink:href", "xml:lang", "xmlns", "aria-label",
];
/// <summary>The policy the renderer configures is exactly these elements, attributes and schemes, with no styling or data attributes.</summary>
[Fact]
public void Constructor_ConfiguredPolicy_AllowsExactlyTheListedMarkup()
{
HtmlSanitizer policy = new MarkdownRenderer().Policy;
Assert.Equal(s_allowedTags.Order(StringComparer.Ordinal), policy.AllowedTags.Order(StringComparer.Ordinal), StringComparer.Ordinal);
Assert.Equal(s_allowedAttributes.Order(StringComparer.Ordinal), policy.AllowedAttributes.Order(StringComparer.Ordinal), StringComparer.Ordinal);
Assert.Equal(["http", "https", "mailto"], policy.AllowedSchemes.Order(StringComparer.Ordinal), StringComparer.Ordinal);
Assert.Empty(policy.AllowedCssProperties);
Assert.Empty(policy.AllowedAtRules);
Assert.False(policy.AllowDataAttributes);
Assert.False(policy.AllowCssCustomProperties);
}
/// <summary>Every allowed element survives in a document that nests each one where HTML permits it.</summary>
[Fact]
public void Render_EveryAllowedElement_SurvivesSanitation()
{
const string Markup = """
<div><p><a href="x.md">a</a><abbr>b</abbr><b>c</b><br><code>d</code><del>e</del><em>f</em><i>g</i><img src="i.png" alt="h"><input type="checkbox"><ins>j</ins><kbd>k</kbd><mark>l</mark><s>m</s><small>n</small><span>o</span><strong>p</strong><sub>q</sub><sup>r</sup></p><blockquote>s</blockquote><hr><pre>t</pre><h1>1</h1><h2>2</h2><h3>3</h3><h4>4</h4><h5>5</h5><h6>6</h6><dl><dt>u</dt><dd>v</dd></dl><details><summary>w</summary>x</details><ul><li>y</li></ul><ol><li>z</li></ol><table><caption>c</caption><thead><tr><th>h</th></tr></thead><tbody><tr><td>d</td></tr></tbody></table></div>
""";
using IHtmlDocument document = Parse(new MarkdownRenderer().Render(Markup));
Assert.Equal(s_allowedTags.Order(StringComparer.Ordinal), ElementNames(document), StringComparer.Ordinal);
}
/// <summary>No other element survives between allowed elements; its text may remain but the element does not.</summary>
[Fact]
public void Render_EveryOtherElement_IsRemoved()
{
var renderer = new MarkdownRenderer();
Assert.All(s_otherTags, tag =>
{
using IHtmlDocument document = Parse(renderer.Render($"<div><{tag} title=\"t\">inner</{tag}><span>after</span></div>"));
Assert.Empty(ElementNames(document).Except(["div", "span"], StringComparer.Ordinal));
});
Assert.Empty(s_allowedTags.Intersect(s_otherTags, StringComparer.Ordinal));
}
/// <summary>Table parts that only exist inside a table, and are not allowed, are removed there while the allowed parts stay.</summary>
[Fact]
public void Render_TablePartsOutsideTheAllowlist_AreRemovedInsideATable()
{
const string Markup = "<table><colgroup><col span=\"2\"></colgroup><thead><tr><th>h</th></tr></thead><tbody><tr><td>d</td></tr></tbody><tfoot><tr><td>f</td></tr></tfoot></table>";
using IHtmlDocument document = Parse(new MarkdownRenderer().Render(Markup));
Assert.Empty(document.Body!.QuerySelectorAll("colgroup,col,tfoot"));
Assert.NotNull(document.Body.QuerySelector("table > thead > tr > th"));
Assert.NotNull(document.Body.QuerySelector("table > tbody > tr > td"));
}
/// <summary>Exactly the allowed attributes survive on an allowed element; identity, behaviour, styling and data attributes do not.</summary>
[Fact]
public void Render_EveryAttribute_KeepsExactlyTheAllowedOnes()
{
string attributes = string.Join(' ', s_allowedAttributes.Concat(s_otherAttributes).Select(name => string.Equals(name, "class", StringComparison.Ordinal) ? "class=\"frontmatter\"" : name + "=\"1\"")) + " style=\"color:red\"";
using IHtmlDocument document = Parse(new MarkdownRenderer().Render($"<div><span {attributes}>text</span></div>"));
IElement span = Assert.Single(document.Body!.QuerySelectorAll("span"));
Assert.Equal(s_allowedAttributes, span.Attributes.Select(attribute => attribute.Name).Order(StringComparer.Ordinal), StringComparer.Ordinal);
Assert.Empty(s_allowedAttributes.Intersect(s_otherAttributes, StringComparer.Ordinal));
}
/// <summary>Only the fixed styling classes and bounded code-language classes survive, spelled exactly.</summary>
[Theory]
[InlineData("frontmatter fm-key fm-value task-list task-list-item", "frontmatter fm-key fm-value task-list task-list-item")]
[InlineData("language-csharp hljs keyword", "language-csharp")]
[InlineData("LANGUAGE-csharp Language-go language-rust", "language-rust")]
[InlineData("Frontmatter FM-KEY", null)]
[InlineData("language- language-a;b language-<x>", null)]
public void Render_ClassNames_KeepsOnlyTheStylingClasses(string authored, string? kept)
{
using IHtmlDocument document = Parse(new MarkdownRenderer().Render($"<span class=\"{authored}\">text</span>"));
Assert.Equal(kept, Assert.Single(document.Body!.QuerySelectorAll("span")).GetAttribute("class"));
}
/// <summary>A code-language class is kept up to 80 characters and dropped one character past that.</summary>
[Fact]
public void Render_CodeLanguageClassAtAndPastTheLengthLimit_IsBoundedExactly()
{
string atLimit = "language-" + new string('x', 71);
Assert.Equal(80, atLimit.Length);
using IHtmlDocument kept = Parse(new MarkdownRenderer().Render($"<span class=\"{atLimit}\">text</span>"));
Assert.Equal(atLimit, Assert.Single(kept.Body!.QuerySelectorAll("span")).GetAttribute("class"));
using IHtmlDocument dropped = Parse(new MarkdownRenderer().Render($"<span class=\"{atLimit}x\">text</span>"));
Assert.Null(Assert.Single(dropped.Body!.QuerySelectorAll("span")).GetAttribute("class"));
}
/// <summary>The attribute that carries source positions is allowed only during a source-aware render, whether that render finishes or fails.</summary>
[Fact]
public void RenderWithSources_AfterTheRender_NoLongerAllowsTheSourceAttribute()
{
var renderer = new MarkdownRenderer();
var sources = new DocumentSourceMap("# Title");
Assert.Contains("Title", renderer.RenderWithSources("# Title", FrontmatterMode.Hide, sources), StringComparison.Ordinal);
Assert.DoesNotContain(sources.AttributeName, renderer.Policy.AllowedAttributes);
Assert.Throws<ArgumentOutOfRangeException>(() => renderer.RenderWithSources("# Title", (FrontmatterMode)99, sources));
Assert.DoesNotContain(sources.AttributeName, renderer.Policy.AllowedAttributes);
}
/// <summary>Only web and mail links keep a target; every other scheme, including ones Windows would hand to another application, is removed.</summary>
[Theory]
[InlineData("http://example.com/a", true)]
[InlineData("https://example.com/a", true)]
[InlineData("mailto:someone@example.com", true)]
[InlineData("child.md", true)]
[InlineData("#section", true)]
[InlineData("HTTPS://example.com/a", true)]
[InlineData("ftp://example.com/a", false)]
[InlineData("file:///C:/private.txt", false)]
[InlineData("FILE:///C:/private.txt", false)]
[InlineData("javascript:run()", false)]
[InlineData("vbscript:run()", false)]
[InlineData("data:text/html,<p>x</p>", false)]
[InlineData("blob:https://example.com/1", false)]
[InlineData("about:blank", false)]
[InlineData("ws://example.com", false)]
[InlineData("tel:5551234", false)]
[InlineData("sms:5551234", false)]
[InlineData("ms-settings:defaultapps", false)]
[InlineData("ms-msdt:/id", false)]
[InlineData("ms-word:ofe|u|https://example.com/a.docx", false)]
[InlineData("search-ms:query=x", false)]
[InlineData("shell:startup", false)]
[InlineData("res://ieframe.dll/x", false)]
[InlineData("view-source:https://example.com", false)]
[InlineData("onenote:x", false)]
public void Render_LinkScheme_KeepsOnlyWebAndMailTargets(string target, bool kept)
{
using IHtmlDocument document = Parse(new MarkdownRenderer().Render($"<a href=\"{target}\">link</a>"));
IElement link = Assert.Single(document.Body!.QuerySelectorAll("a"));
Assert.Equal(kept, link.HasAttribute("href"));
}
/// <summary>The distinct element names in the sanitized body, in ordinal order.</summary>
private static string[] ElementNames(IHtmlDocument document)
=> document.Body!.QuerySelectorAll("*").Select(element => element.LocalName).Distinct(StringComparer.Ordinal).Order(StringComparer.Ordinal).ToArray();
/// <summary>Parses renderer output the way the browser surface does.</summary>
private static IHtmlDocument Parse(string html) => new HtmlParser().ParseDocument("<!doctype html><html><body>" + html + "</body></html>");
}
@@ -35,10 +35,6 @@ public sealed class SecurityFuzzTests
"[section](#heading) ![image](images/hello%20world.png)\n", "| A | B |\n|---|---|\n| x | y |\n",
"- [x] Task\n> Quote\n", "😀 café\0\t\r\n", "<!-- <code> -->", "</code></pre></div>",
"</style><script>execute()</script>", "&lt;script&gt;literal&lt;/script&gt;", "\"'<>:=[]()\\/!?%",
"<video src='x.mp4' autoplay onplay='execute()'><source src='y.mp4'></video><audio src='x.mp3' controls></audio>",
"<embed src='x.swf'><object data='x.swf'><param name='a' value='b'></object><math><mi xlink:href='javascript:execute()'>x</mi></math>",
"<link rel='stylesheet' href='https://outside.invalid/x.css'><meta http-equiv='refresh' content='0;url=https://outside.invalid'><base href='https://outside.invalid/'>",
"<textarea autofocus onfocus='execute()'>text</textarea><select><option>one</option></select><a href='x.md' target='_blank' name='n' ping='https://outside.invalid'>x</a>",
];
@@ -246,12 +242,11 @@ public sealed class SecurityFuzzTests
/// <summary>Uses the parsed DOM's executable capabilities as the oracle, not the renderer's private allowlist.</summary>
private static void AssertPassive(IHtmlDocument document)
{
Assert.Empty(document.QuerySelectorAll("script,svg,math,iframe,object,embed,form,button,style,base,meta,link,audio,video,source,param,textarea,select,option"));
Assert.Empty(document.QuerySelectorAll("script,svg,math,iframe,object,embed,form,button,style,base,meta[http-equiv],audio,video"));
foreach(IElement element in document.QuerySelectorAll("*"))
{
Assert.DoesNotContain(element.Attributes, attribute => attribute.Name.StartsWith("on", StringComparison.OrdinalIgnoreCase));
Assert.False(element.HasAttribute("srcdoc") || element.HasAttribute("srcset") || element.HasAttribute("style"));
Assert.False(element.HasAttribute("target") || element.HasAttribute("ping") || element.HasAttribute("name") || element.HasAttribute("autofocus"));
foreach(string name in new[] { "href", "src" })
{
string? value = element.GetAttribute(name);
@@ -1,431 +0,0 @@
/*
* Copyright (c) 2026 James Maes
* SPDX-License-Identifier: MIT
*/
using System.Text.Json;
using System.Text.Json.Nodes;
using AngleSharp.Dom;
using AngleSharp.Html.Dom;
using AngleSharp.Html.Parser;
using MarkdownViewr.Windows.Core.Documents;
using MarkdownViewr.Windows.Core.Editors;
using MarkdownViewr.Windows.Core.Printing;
using MarkdownViewr.Windows.Core.Themes;
namespace MarkdownViewr.Windows.Core.Tests;
/// <summary>
/// Validation of text that comes from a document, a settings file, an imported theme or the
/// browser surface: each check is pinned by an input that only that check rejects.
/// </summary>
public sealed class UntrustedInputValidationTests
{
/// <summary>Metadata keys and values are display text: markup in either is escaped, never parsed.</summary>
[Fact]
public void RenderMetadata_MarkupInKeyAndValue_IsEscapedText()
{
const string Key = "<b>key</b>";
const string Value = "<img src=x onerror=run()> & \"quoted\"";
using IHtmlDocument parsed = new HtmlParser().ParseDocument(DocumentFrontmatter.RenderMetadata(Key + ": " + Value));
Assert.Equal(Key, Assert.Single(parsed.QuerySelectorAll("th.fm-key")).TextContent);
Assert.Equal(Value, Assert.Single(parsed.QuerySelectorAll("td.fm-value")).TextContent);
Assert.Empty(parsed.QuerySelectorAll("b,img"));
}
/// <summary>A line that starts with its colon still has a key cell, so the table keeps two columns.</summary>
[Fact]
public void RenderMetadata_LeadingColon_KeepsAnEmptyKeyCell()
{
using IHtmlDocument parsed = new HtmlParser().ParseDocument(DocumentFrontmatter.RenderMetadata(": value"));
Assert.Equal("", Assert.Single(parsed.QuerySelectorAll("th.fm-key")).TextContent);
IElement value = Assert.Single(parsed.QuerySelectorAll("td.fm-value"));
Assert.Equal("value", value.TextContent);
Assert.False(value.HasAttribute("colspan"));
}
/// <summary>The private source marker is new for every render, so an authored attribute cannot predict it.</summary>
[Fact]
public void AttributeName_EachSourceMap_IsUnpredictable()
{
string first = new DocumentSourceMap("# Title").AttributeName;
string second = new DocumentSourceMap("# Title").AttributeName;
Assert.Matches("^data-mv-source-[0-9a-f]{32}$", first);
Assert.Matches("^data-mv-source-[0-9a-f]{32}$", second);
Assert.NotEqual(first, second, StringComparer.Ordinal);
}
/// <summary>Raw HTML headings map to their source at every level, including the sixth.</summary>
[Theory]
[InlineData(1)]
[InlineData(5)]
[InlineData(6)]
public void SourceHeadings_RawHtmlHeadingLevel_MapsItsSource(int level)
{
string heading = $"<h{level}>Raw</h{level}>";
string source = "Intro\n\n" + heading + "\n\nAfter\n";
var outline = new DocumentOutline(source);
Assert.Equal(level, Assert.Single(outline.Headings).Level);
DocumentSourceHeading mapped = Assert.Single(outline.SourceHeadings);
Assert.Equal(heading, source[mapped.Start..mapped.End]);
}
/// <summary>A level the HTML standard does not define is not a heading and gets no source mapping.</summary>
[Fact]
public void SourceHeadings_RawHtmlLevelSeven_IsNotAHeading()
{
var outline = new DocumentOutline("<h7>Not a heading</h7>\n");
Assert.Empty(outline.Headings);
Assert.Empty(outline.SourceHeadings);
}
/// <summary>Loading repairs every stored list and object, not only the ones the window happens to read first.</summary>
[Fact]
public void Sanitize_CorruptPrintEditorsAndThemeLists_RepairsEachProperty()
{
var valid = new EditorConfiguration(Guid.NewGuid(), "Editor", @"C:\Editor\editor.exe");
var settings = new AppSettings
{
Print = new PrintOptions(Theme: "Bad\u0001Theme", PaddingPixels: 5000),
ConfiguredEditors = [valid, new EditorConfiguration(Guid.NewGuid(), "Script", @"C:\Editor\run.cmd"), new EditorConfiguration(Guid.Empty, "Empty", @"C:\Editor\other.exe")],
DisabledThemes = ["Nord", "Nord", "Bad\u0001Name", ""],
DeletedBuiltInThemes = ["Dracula", "Dracula", "Bad\u0002Name"],
ThemeOrder = ["Nord", "Nord", "Bad\u0003Name"],
DocumentTheme = "Bad\u0001Theme",
};
settings.Sanitize();
Assert.Equal("Clean Printing", settings.Print.Theme);
Assert.Equal(96, settings.Print.PaddingPixels);
Assert.Equal([valid], settings.ConfiguredEditors);
Assert.Equal(valid.Executable, settings.ExternalEditor);
Assert.Equal(["Nord"], settings.DisabledThemes);
Assert.Equal(["Dracula"], settings.DeletedBuiltInThemes);
Assert.Equal(["Nord"], settings.ThemeOrder);
Assert.Equal("Catppuccin Mocha", settings.DocumentTheme);
}
/// <summary>A missing print object, as an older file or a hand edit leaves it, becomes the defaults.</summary>
[Fact]
public void Sanitize_MissingPrintObject_UsesDefaults()
{
var settings = new AppSettings { Print = null! };
settings.Sanitize();
Assert.Equal(new PrintOptions(), settings.Print);
}
/// <summary>Editing a theme cannot silently raise it to a newer schema; that needs the import confirmation.</summary>
[Fact]
public void SaveEdited_SchemaVersionRaised_RequiresConfirmation()
{
ReaderTheme original = ThemeCatalog.Find(null);
JsonNode raised = JsonNode.Parse(original.Json)!;
raised["schemaVersion"] = 2;
var edited = ReaderTheme.ParseCompatible(raised.ToJsonString());
Assert.Equal(1, original.SchemaVersion);
Assert.Equal(2, edited.SchemaVersion);
Assert.Throws<InvalidOperationException>(() => ThemeManagement.SaveEdited(new AppSettings(), original, edited));
}
/// <summary>An already confirmed newer-schema theme stays editable at its own version.</summary>
[Fact]
public void SaveEdited_SameNewerSchema_IsSaved()
{
JsonNode newer = JsonNode.Parse(ThemeCatalog.Find(null).Json)!;
newer["schemaVersion"] = 2;
newer["name"] = "Owned future";
var theme = ReaderTheme.ParseCompatible(newer.ToJsonString());
AppSettings imported = ThemeManagement.Import(new AppSettings(), theme, approveNewerSchema: true);
AppSettings saved = ThemeManagement.SaveEdited(imported, theme, theme);
Assert.Equal("Owned future", saved.DocumentTheme);
Assert.Equal(2, ThemeManagement.Active(saved).SchemaVersion);
}
/// <summary>A copy of a theme whose name is already at the limit still has a name the theme parser accepts.</summary>
[Fact]
public void CopyTheme_LongestNameTakenTwice_StaysWithinTheNameLimit()
{
ReaderTheme longest = ThemeCatalog.Find(null).Rename(new string('N', 80));
AppSettings settings = ThemeManagement.Import(new AppSettings(), longest);
ReaderTheme firstCopy = ThemeManagement.CopyTheme(settings, longest);
settings = ThemeManagement.Import(settings, firstCopy);
ReaderTheme secondCopy = ThemeManagement.CopyTheme(settings, longest);
Assert.Equal(80, firstCopy.Name.Length);
Assert.Equal(80, secondCopy.Name.Length);
Assert.EndsWith(" (2)", secondCopy.Name, StringComparison.Ordinal);
Assert.Equal(secondCopy.Name, ReaderTheme.ParseCompatible(secondCopy.Json).Name);
}
/// <summary>Editor and document paths are accepted up to the Windows limit and refused one character past it.</summary>
[Fact]
public void IsExecutablePath_PathAtAndPastTheWindowsLimit_IsBoundedExactly()
{
string atLimit = @"C:\" + new string('e', 32767 - 7) + ".exe";
string pastLimit = @"C:\" + new string('e', 32768 - 7) + ".exe";
Assert.Equal(32767, atLimit.Length);
Assert.True(EditorLaunch.IsExecutablePath(atLimit));
Assert.False(EditorLaunch.IsExecutablePath(pastLimit));
string document = @"C:\" + new string('d', 32767 - 6) + ".md";
Assert.Equal(32767, document.Length);
Assert.Equal(document, Assert.Single(EditorLaunch.Create(@"C:\Editor\editor.exe", document).ArgumentList));
Assert.Throws<ArgumentException>(() => EditorLaunch.Create(@"C:\Editor\editor.exe", document + "x"));
}
/// <summary>Recent paths are kept up to the Windows limit and dropped one character past it.</summary>
[Fact]
public void Sanitize_RecentPathAtAndPastTheWindowsLimit_IsBoundedExactly()
{
string atLimit = @"C:\" + new string('d', 32767 - 6) + ".md";
Assert.Equal([atLimit], RecentDocuments.Sanitize([atLimit, atLimit + "x"]));
}
/// <summary>A find term is accepted at its limit and refused one character past it.</summary>
[Fact]
public void Constructor_FindTermAtAndPastTheLimit_IsBoundedExactly()
{
string atLimit = new('q', DocumentFind.MaximumQueryCharacters);
Assert.Equal(atLimit, new DocumentFind(atLimit + " tail", atLimit).Query);
Assert.Throws<ArgumentException>(() => new DocumentFind("source", atLimit + "q"));
}
/// <summary>The viewport result is read up to its size cap and ignored past it, even when it would parse.</summary>
[Fact]
public void FromBrowserResult_ViewportAtAndPastTheSizeCap_IsBoundedExactly()
{
string atCap = "[0.25," + new string(' ', 128 - 11) + "0.75]";
Assert.Equal(128, atCap.Length);
Assert.Equal(0.75, DocumentViewport.FromBrowserResult(atCap).VerticalFraction);
Assert.Equal(default, DocumentViewport.FromBrowserResult(atCap.Replace("[", "[ ", StringComparison.Ordinal)));
}
/// <summary>The scroll-state result is read up to its size cap for the heading count and ignored past it.</summary>
[Theory]
[InlineData(0)]
[InlineData(3)]
public void FromBrowserResult_ScrollStateAtAndPastTheSizeCap_IsBoundedExactly(int headings)
{
int cap = headings * 128 + 512;
string atCap = "[1,2,[],[]" + new string(' ', cap - 11) + "]";
Assert.Equal(cap, atCap.Length);
Assert.NotNull(DocumentScrollState.FromBrowserResult(atCap, headings));
Assert.Null(DocumentScrollState.FromBrowserResult(atCap.Replace("[1,", "[ 1,", StringComparison.Ordinal), headings));
}
/// <summary>The scroll-state result has exactly four parts; a longer array is not the application's own query result.</summary>
[Theory]
[InlineData("[1,2,[]]")]
[InlineData("[1,2,[],[],[]]")]
[InlineData("[1,2,[],[],0]")]
public void FromBrowserResult_ScrollStateWithWrongNumberOfParts_IsRejected(string json)
=> Assert.Null(DocumentScrollState.FromBrowserResult(json, 2));
/// <summary>Print styles are built from repaired options, so a corrupt padding value cannot reach the stylesheet.</summary>
[Theory]
[InlineData(double.NaN, "padding:0px")]
[InlineData(double.PositiveInfinity, "padding:0px")]
[InlineData(5000, "padding:96px")]
[InlineData(-3, "padding:0px")]
public void Build_CorruptPadding_UsesTheRepairedValue(double padding, string expected)
{
ReaderTheme theme = ThemeCatalog.Find(null);
string css = PrintStyles.Build(new PrintOptions(PaddingPixels: padding), theme, [theme], 1);
Assert.Contains(expected, css, StringComparison.Ordinal);
Assert.DoesNotContain("NaN", css, StringComparison.Ordinal);
Assert.DoesNotContain("Infinity", css, StringComparison.Ordinal);
Assert.DoesNotContain("∞", css, StringComparison.Ordinal);
}
/// <summary>
/// Text the JSON reader cannot decode, an unpaired surrogate escape, makes the theme invalid
/// wherever it appears: in a value the theme reads, in a property name, or in a value this
/// version ignores but would later re-serialize. So does a repeated property name.
/// </summary>
[Theory]
[InlineData("\"name\": \"Nord\"", "\"name\": \"\\uD83D\"")]
[InlineData("\"background\": \"#2e3440\"", "\"background\": \"\\uD800\"")]
[InlineData("\"body\": \"System\"", "\"body\": \"A\\uDC00B\"")]
[InlineData("\"name\": \"Nord\"", "\"name\": \"Nord\", \"\\uD83D\": 1")]
[InlineData("\"name\": \"Nord\"", "\"name\": \"Nord\", \"note\": \"\\uD83D\"")]
[InlineData("\"name\": \"Nord\"", "\"name\": \"Nord\", \"notes\": [1, [\"ok\", {\"deep\": \"\\uDFFF\"}]]")]
[InlineData("\"body\": \"System\"", "\"body\": \"System\", \"\\uD800x\": \"y\"")]
[InlineData("\"name\": \"Nord\"", "\"name\": \"Nord\", \"name\": \"Nord\"")]
[InlineData("\"body\": \"System\"", "\"body\": \"System\", \"body\": \"Other\"")]
[InlineData("\"name\": \"Nord\"", "\"name\": \"Nord\", \"extra\": {\"a\": 1, \"a\": 2}")]
[InlineData("\"name\": \"Nord\"", "\"name\": \"Nord\", \"na\\u006de\": \"Nord\"")]
[InlineData("\"name\": \"Nord\"", "\"name\": \"Nord\", \"notes\": [\"\\uD83D\"]")]
public void Parse_UndecodableTextOrRepeatedProperty_IsRejectedAsAnInvalidTheme(string valid, string invalid)
{
string original = ThemeCatalog.Find("Nord").Json;
Assert.Contains(valid, original, StringComparison.Ordinal);
string json = original.Replace(valid, invalid, StringComparison.Ordinal);
Assert.Throws<JsonException>(() => ReaderTheme.Parse(json));
Assert.Throws<JsonException>(() => ReaderTheme.ParseCompatible(json));
var settings = new AppSettings { UserThemes = [json, original] };
settings.Sanitize();
Assert.Equal([original], settings.UserThemes);
}
/// <summary>
/// A theme that parses can be renamed, copied, edited and imported under a new name with its
/// extra properties intact: those operations re-serialize the whole document. Names that differ
/// only in case, and the same name in two different objects, are not repeats.
/// </summary>
[Fact]
public void Parse_AcceptedThemeWithExtraProperties_SurvivesRenameCopyEditAndImport()
{
string json = ThemeCatalog.Find("Nord").Json.Replace("\"name\": \"Nord\"", "\"name\": \"Nord\", \"Name\": \"other case\", \"note\": \"caf\\u00e9 \\ud83d\\ude00\", \"future\": {\"name\": \"inner\", \"list\": [1, \"two\", null]}", StringComparison.Ordinal);
var theme = ReaderTheme.Parse(json);
Assert.Equal("Renamed", theme.Rename("Renamed").Name);
AppSettings imported = ThemeManagement.Import(new AppSettings(), theme);
Assert.Contains(ThemeManagement.All(imported), item => item.Name.StartsWith("Nord (", StringComparison.Ordinal));
Assert.EndsWith(" Copy", ThemeManagement.CopyTheme(imported, theme).Name, StringComparison.Ordinal);
ReaderTheme edited = theme.Edit("Edited", new Dictionary<string, string>(StringComparer.Ordinal), new Dictionary<string, double>(StringComparer.Ordinal), new Dictionary<string, string>(StringComparer.Ordinal), "");
Assert.Equal("Edited", edited.Name);
Assert.Contains("caf", edited.Json, StringComparison.Ordinal);
Assert.Contains("\"Name\":\"other case\"", edited.Json, StringComparison.Ordinal);
Assert.Contains("\"name\":\"inner\"", edited.Json, StringComparison.Ordinal);
}
/// <summary>
/// Renaming, copying and editing write characters as themselves, so a theme near the size
/// limit whose text is full of quote marks, angle brackets or non-ASCII characters stays
/// within the limit instead of growing sixfold and being refused.
/// </summary>
[Theory]
[InlineData("a>b+c{font:'x'}")]
[InlineData("/* \u6f22\u5b57 caf\u00e9 & <tag> */")]
public void Rename_ThemeNearTheSizeLimit_DoesNotGrowPastIt(string fragment)
{
string css = string.Concat(Enumerable.Repeat(fragment, 60_000 / fragment.Length));
string original = ThemeCatalog.Find("Nord").Json;
Assert.Contains("\"name\": \"Nord\"", original, StringComparison.Ordinal);
string json = original.Replace("\"name\": \"Nord\"", "\"name\": \"Nord\", \"note\": \"" + css + "\"", StringComparison.Ordinal);
var theme = ReaderTheme.Parse(json);
ReaderTheme renamed = theme.Rename("Renamed");
Assert.True(renamed.Json.Length <= json.Length);
Assert.Contains(fragment, renamed.Json, StringComparison.Ordinal);
ReaderTheme edited = renamed.Edit("Edited", new Dictionary<string, string>(StringComparer.Ordinal), new Dictionary<string, double>(StringComparer.Ordinal), new Dictionary<string, string>(StringComparer.Ordinal), "");
Assert.True(edited.Json.Length <= json.Length);
Assert.EndsWith(" Copy", ThemeManagement.CopyTheme(new AppSettings(), theme).Name, StringComparison.Ordinal);
}
/// <summary>
/// JSON writes emoji, no-break and ideographic spaces and private-use glyphs as six-character
/// escapes whatever the encoder. A theme as large as an import may be, made of nothing else,
/// can still be renamed, copied and edited: the stored limit leaves room for the growth.
/// </summary>
[Theory]
[InlineData("😀")]
[InlineData(" ")]
[InlineData(" ")]
[InlineData("")]
public void Rename_ThemeAtTheImportLimitMadeOfEscapedCharacters_IsKept(string character)
{
string original = ThemeCatalog.Find("Nord").Json;
string opening = "\"name\": \"Nord\", \"note\": \"";
int room = ReaderTheme.MaximumCharacters - original.Length - (opening.Length - "\"name\": \"Nord\"".Length) - 1;
string filler = string.Concat(Enumerable.Repeat(character, room / character.Length)).PadRight(room, 'x');
string json = original.Replace("\"name\": \"Nord\"", opening + filler + "\"", StringComparison.Ordinal);
Assert.Equal(ReaderTheme.MaximumCharacters, json.Length);
var theme = ReaderTheme.Parse(json);
ReaderTheme renamed = theme.Rename("A considerably longer name than the one it had");
Assert.InRange(renamed.Json.Length, json.Length + 1, ReaderTheme.MaximumStoredCharacters);
Assert.Equal(renamed.Json.Length, renamed.Rename(renamed.Name).Json.Length);
Assert.EndsWith(" Copy", ThemeManagement.CopyTheme(new AppSettings(), renamed).Name, StringComparison.Ordinal);
ReaderTheme edited = renamed.Edit("Edited", new Dictionary<string, string>(StringComparer.Ordinal), new Dictionary<string, double>(StringComparer.Ordinal), new Dictionary<string, string>(StringComparer.Ordinal), "body { color: red }");
Assert.Equal("Edited", edited.Name);
var settings = new AppSettings { UserThemes = [edited.Json] };
settings.Sanitize();
Assert.Equal([edited.Json], settings.UserThemes);
}
/// <summary>A string that is not well-formed UTF-16 is refused as an invalid theme, and a stored one is dropped, rather than failing as a programming error.</summary>
[Fact]
public void Parse_TextWithAnUnpairedSurrogate_IsRejectedAsAnInvalidTheme()
{
string original = ThemeCatalog.Find("Nord").Json;
string json = original.Replace("\"name\": \"Nord\"", "\"name\": \"No\uD83Drd\"", StringComparison.Ordinal);
Assert.DoesNotContain("\"name\": \"Nord\"", json, StringComparison.Ordinal);
Assert.Throws<JsonException>(() => ReaderTheme.Parse(json));
Assert.Throws<JsonException>(() => ReaderTheme.ParseCompatible(json));
var settings = new AppSettings { UserThemes = [json, original] };
settings.Sanitize();
Assert.Equal([original], settings.UserThemes);
}
/// <summary>Only the exact lower-case channel name selects the development identity.</summary>
[Theory]
[InlineData("DEV")]
[InlineData("Dev")]
[InlineData("dev ")]
[InlineData("development")]
public void ForChannel_OtherSpellingOfDev_KeepsTheStableIdentity(string channel)
=> Assert.Equal("markdownviewr-windows", AppIdentity.ForChannel(channel).Id);
/// <summary>A colour that is not six hexadecimal digits after a hash, or a label containing a control character, is refused.</summary>
[Theory]
[InlineData("colors.background", "\";ffffff\"")]
[InlineData("colors.background", "\"#fffffff\"")]
[InlineData("colors.background", "\"#ffffffff\"")]
[InlineData("colors.background", "\"#fffff\"")]
[InlineData("colors.background", "\"ffffff#\"")]
[InlineData("colors.text", "\"#12345g\"")]
[InlineData("name", "\"Theme\\u0001Name\"")]
[InlineData("name", "\"Theme\\u007fName\"")]
[InlineData("fonts.heading", "\"Font\\u0001Name\"")]
[InlineData("fonts.code", "\"Font\\u009bName\"")]
public void Parse_MalformedColorOrLabel_IsRejected(string path, string json)
{
JsonNode root = JsonNode.Parse(ThemeCatalog.Find(null).Json)!;
string[] parts = path.Split('.');
JsonNode parent = parts.Length == 1 ? root : root[parts[0]]!;
parent[parts[^1]] = JsonNode.Parse(json);
Assert.Throws<JsonException>(() => ReaderTheme.Parse(root.ToJsonString()));
}
}
@@ -1,125 +0,0 @@
/*
* Copyright (c) 2026 James Maes
* SPDX-License-Identifier: MIT
*/
using MarkdownViewr.Windows.Core.Documents;
using MarkdownViewr.Windows.Core.Themes;
namespace MarkdownViewr.Windows.Core.Tests;
/// <summary>The written-out Windows name rules, and the two places that depend on them.</summary>
public sealed class WindowsFileNamesTests
{
private static readonly string[] s_devices =
[
"CON", "PRN", "AUX", "NUL", "CONIN$", "CONOUT$",
"COM0", "COM1", "COM2", "COM3", "COM4", "COM5", "COM6", "COM7", "COM8", "COM9", "COM¹", "COM²", "COM³",
"LPT0", "LPT1", "LPT2", "LPT3", "LPT4", "LPT5", "LPT6", "LPT7", "LPT8", "LPT9", "LPT¹", "LPT²", "LPT³",
];
/// <summary>A device is a device in any letter case, with any extension, and with spaces before the extension or at the end.</summary>
[Fact]
public void IsReservedDeviceName_EveryDeviceSpelling_IsReserved()
{
Assert.All(Spellings(), spelling =>
{
Assert.True(WindowsFileNames.IsReservedDeviceName(spelling), spelling);
Assert.True(WindowsFileNames.IsReservedDeviceName(spelling + ".png"), spelling);
Assert.True(WindowsFileNames.IsReservedDeviceName(spelling + ".tar.md"), spelling);
Assert.True(WindowsFileNames.IsReservedDeviceName(spelling + " .png"), spelling);
Assert.True(WindowsFileNames.IsReservedDeviceName(spelling + " "), spelling);
});
Assert.Equal(96, Spellings().Count());
}
/// <summary>Names that only resemble a device stay ordinary file names; only spaces are ignored before the extension.</summary>
[Theory]
[InlineData("")]
[InlineData("console.md")]
[InlineData("COM10.png")]
[InlineData("COM")]
[InlineData("LPT.txt")]
[InlineData("xCON.png")]
[InlineData("CON-notes.md")]
[InlineData("CON-.md")]
[InlineData("null.md")]
[InlineData(" NUL.png")]
[InlineData("NUL\u00A0.png")]
[InlineData("NUL\t.png")]
[InlineData("readme.NUL")]
[InlineData("COM⁴.png")]
[InlineData("CLOCK$")]
[InlineData("CLOCK$.txt")]
public void IsReservedDeviceName_OrdinaryName_IsNotReserved(string name) => Assert.False(WindowsFileNames.IsReservedDeviceName(name));
/// <summary>A missing name is a contract error, not an ordinary file.</summary>
[Fact]
public void IsReservedDeviceName_Null_RejectsInput() => Assert.Throws<ArgumentNullException>(() => WindowsFileNames.IsReservedDeviceName(null!));
/// <summary>The printable characters Windows forbids in a name; control characters are refused separately by each caller.</summary>
[Fact]
public void InvalidCharacters_Constant_ListsThePrintableForbiddenCharacters() => Assert.Equal("\"*/:<>?\\|", new string(WindowsFileNames.InvalidCharacters.Order().ToArray()));
/// <summary>No image or linked-document request can name a device in any spelling, as the file or as a folder on the way to it.</summary>
[Fact]
public void GetRelativePath_DeviceSegment_IsDenied()
{
var policy = new DocumentResourcePolicy();
Assert.All(Spellings(), spelling =>
{
string segment = Uri.EscapeDataString(spelling);
Assert.Null(policy.GetImageRelativePath(new Uri(policy.DocumentUri, segment + ".png")));
Assert.Null(policy.GetImageRelativePath(new Uri(policy.DocumentUri, segment + "%20.png")));
Assert.Null(policy.GetImageRelativePath(new Uri(policy.DocumentUri, segment + "/picture.png")));
Assert.Null(policy.GetDocumentRelativePath(new Uri(policy.DocumentUri, segment + ".md")));
Assert.Null(policy.GetDocumentRelativePath(new Uri(policy.DocumentUri, segment + ".tar.md")));
Assert.Null(policy.GetDocumentRelativePath(new Uri(policy.DocumentUri, "docs/" + segment + "/child.md")));
});
Assert.Equal("console.png", policy.GetImageRelativePath(new Uri(policy.DocumentUri, "console.png")));
Assert.Equal("docs/com10/child.md", policy.GetDocumentRelativePath(new Uri(policy.DocumentUri, "docs/com10/child.md")));
}
/// <summary>A theme named after a device, in any case, never becomes the suggested export file name.</summary>
[Fact]
public void SuggestedFileName_EveryDeviceName_IsPrefixed()
{
Assert.All(s_devices, device =>
{
Assert.Equal("theme-" + device.ToLowerInvariant() + ".json", ThemeJson.SuggestedFileName(ThemeCatalog.Find(null).Rename(device)));
Assert.Equal("theme-" + device.ToLowerInvariant() + ".json", ThemeJson.SuggestedFileName(ThemeCatalog.Find(null).Rename(device.ToLowerInvariant())));
Assert.Equal("theme-" + device.ToLowerInvariant() + ".backup.json", ThemeJson.SuggestedFileName(ThemeCatalog.Find(null).Rename(device + ".backup")));
});
}
/// <summary>Leading and trailing dots and hyphens are dropped from a suggested name, and a name made only of them falls back to a plain one.</summary>
[Theory]
[InlineData("-Edge-", "edge.json")]
[InlineData(".Dotted.", "dotted.json")]
[InlineData("--", "theme.json")]
[InlineData(" spaced ", "spaced.json")]
[InlineData("-con-", "theme-con.json")]
public void SuggestedFileName_LeadingAndTrailingSeparators_AreTrimmed(string name, string expected)
=> Assert.Equal(expected, ThemeJson.SuggestedFileName(ThemeCatalog.Find(null).Rename(name)));
/// <summary>Each device name in upper, lower and mixed case.</summary>
private static IEnumerable<string> Spellings()
=> s_devices.SelectMany(device => new[] { device, device.ToLowerInvariant(), char.ToUpperInvariant(device[0]) + device[1..].ToLowerInvariant() });
}