From 75207a9ceb8434c78b10773f47b73cf902194afb Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 7 Nov 2026 00:01:34 +0000 Subject: [PATCH 1/3] Put MXP images and sounds in their T= directory, and keep a short extended colour's components MXP IMAGE and SOUND appended the file to URL= (U=) but dropped T=, which the specification puts between them. SGR 38;2;40 left the 40 to be read as a black background. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Rqqt7TnKiMidjBirFcUqtL --- CHANGELOG.md | 9 +++++++++ MarkupString.Ansi/Decoding/VtPlugins.cs | 3 +++ MarkupString.Mxp/Decoding/MxpDecoding.cs | 16 ++++++++++++---- MarkupString.Tests/Decoding/MxpDecodingTests.cs | 16 ++++++++++++++++ MarkupString.Tests/Decoding/VtDecodingTests.cs | 8 ++++++++ docs/decoding.md | 7 ++++--- 6 files changed, 52 insertions(+), 7 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index bb7d12a..2ebfcb3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,15 @@ All notable changes to `MarkupString`, `MarkupString.Ansi`, `MarkupString.Html`, The format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and the project follows [Semantic Versioning](https://semver.org/spec/v2.0.0.html). +## Unreleased + +### Fixed + +- MXP `IMAGE` and `SOUND` put the file in the `T=` type's directory under the base address, as the MXP + specification says: `` is `https://h/img/maps/map.png`. +- An SGR extended colour with too few components (`38;2;40`) no longer reads what is left as codes of their own, + so it does not set a black background. + ## 2.26.0 — 2026-11-06 ### Added diff --git a/MarkupString.Ansi/Decoding/VtPlugins.cs b/MarkupString.Ansi/Decoding/VtPlugins.cs index 63196a4..d86188e 100644 --- a/MarkupString.Ansi/Decoding/VtPlugins.cs +++ b/MarkupString.Ansi/Decoding/VtPlugins.cs @@ -155,6 +155,9 @@ public static AnsiStyle Apply(AnsiStyle style, in CsiSequence sequence) } else if (first + 2 >= sequence.Count) { + // Too few components: they are still the colour's, not codes of their own (38;2;40 does not + // set a black background). + i = sequence.Count - 1; return null; } diff --git a/MarkupString.Mxp/Decoding/MxpDecoding.cs b/MarkupString.Mxp/Decoding/MxpDecoding.cs index 04dc49b..6c50fe2 100644 --- a/MarkupString.Mxp/Decoding/MxpDecoding.cs +++ b/MarkupString.Mxp/Decoding/MxpDecoding.cs @@ -699,7 +699,7 @@ private void Image(ParsedTag tag) { var file = tag.Get("FNAME", 0); if (string.IsNullOrEmpty(file)) return; - var source = Address(tag.Get("URL"), file); + var source = Address(tag.Get("URL"), tag.Get("T"), file); var (width, widthCells) = Size(tag.Get("W")); var (height, heightCells) = Size(tag.Get("H")); var align = Enum.TryParse(tag.Get("ALIGN"), ignoreCase: true, out var parsed) ? parsed : (ImageAlign?)null; @@ -758,13 +758,21 @@ private void Sound(ParsedTag tag) ? l < 0 ? SoundMarkup.Forever : l : null; var continues = music && tag.Get("C") == "1"; - Context.Point(new SoundMarkup(Address(tag.Get("U"), file), channel, volume, repeats, continues)); + Context.Point(new SoundMarkup(Address(tag.Get("U"), tag.Get("T"), file), channel, volume, repeats, continues)); } - private static string Address(string? directory, string file) + /// + /// Where a picture or sound is: the file under the base address, in the type's directory when there is one + /// ("the classname is appended to the URL, along with the name of the file itself"), or the file as it is + /// when there is no base or the file is already absolute. + /// + private static string Address(string? directory, string? type, string file) { if (string.IsNullOrEmpty(directory) || Uri.TryCreate(file, UriKind.Absolute, out _)) return file; - return directory.EndsWith('/') ? directory + file : directory + "/" + file; + var address = directory.EndsWith('/') ? directory : directory + "/"; + var kind = type?.Trim().Trim('/'); + if (!string.IsNullOrEmpty(kind)) address += kind + "/"; + return address + file; } // ── Helpers ───────────────────────────────────────────────────────────────── diff --git a/MarkupString.Tests/Decoding/MxpDecodingTests.cs b/MarkupString.Tests/Decoding/MxpDecodingTests.cs index 734a819..ee9e790 100644 --- a/MarkupString.Tests/Decoding/MxpDecodingTests.cs +++ b/MarkupString.Tests/Decoding/MxpDecodingTests.cs @@ -224,6 +224,22 @@ public async Task WhatThisPackageWrites_ReadsBack() await Assert.That(spans[^1].Style.Interaction).IsEqualTo(new Interaction(InteractionKind.Command, "look") { Hint = "Look" }); } + [Test] + public async Task Image_TypeIsADirectoryUnderTheUrl() + { + var (lines, _, _) = Decode("\e[1z\n\e[1z\n\e[1z\n"); + await Assert.That(Markups(lines[0]).OfType().Single().Source).IsEqualTo("https://example.test/img/maps/map.png"); + await Assert.That(Markups(lines[1]).OfType().Single().Source).IsEqualTo("https://example.test/img/maps/map.png"); + await Assert.That(Markups(lines[2]).OfType().Single().Source).IsEqualTo("https://example.test/doors/door.wav"); + } + + [Test] + public async Task Image_TypeWithoutUrlLeavesTheName() + { + var (lines, _, _) = Decode("\e[1z\n"); + await Assert.That(Markups(lines[0]).OfType().Single().Source).IsEqualTo("https://example.test/x.png"); + } + [Test] public async Task Image_InCells_IsDrawnOverTheLines() { diff --git a/MarkupString.Tests/Decoding/VtDecodingTests.cs b/MarkupString.Tests/Decoding/VtDecodingTests.cs index e5cb968..b6f8ba7 100644 --- a/MarkupString.Tests/Decoding/VtDecodingTests.cs +++ b/MarkupString.Tests/Decoding/VtDecodingTests.cs @@ -90,6 +90,14 @@ public async Task Sgr_StandardColour() await Assert.That(span.Style.Has(TextAttributes.Bold)).IsTrue(); } + [Test] + public async Task Sgr_TruncatedTrueColour_SetsNothing() + { + var span = Only("\e[31;38;2;40mx\n"); + await Assert.That(span.Style.Foreground).IsEqualTo(new RgbColor(170, 0, 0)); + await Assert.That(span.Style.Background).IsNull(); + } + [Test] public async Task Sgr_TrueColour_SemicolonsAndColons() { diff --git a/docs/decoding.md b/docs/decoding.md index d7b08a1..c34d130 100644 --- a/docs/decoding.md +++ b/docs/decoding.md @@ -134,7 +134,8 @@ The decoder acts on none of these. Refuse a clipboard write unless the player al | `53`, `55` | Overline on, off | | `58` | Underline colour: its parameters are read and dropped | -Any other code is ignored. An extended colour out of range leaves the colour as it was. The style +Any other code is ignored. An extended colour out of range leaves the colour as it was, and so does one +with too few components, whose components are not read as codes of their own. The style is written under the `VtPens.Style` pen as an `AnsiMarkup`. ### `ControlsPlugin` @@ -584,8 +585,8 @@ What the tags become: | `B`, `I`, `U`, `S`, `H`, `COLOR`, `FONT` | An `AnsiMarkup`. SGR inside an MXP colour wins, as in an MXP client. | | `A href hint` | A URL link, when `DecoderOptions.Links` allows the address | | `SEND href hint prompt` | A command link. With several commands (`a\|b`) or `PROMPT`, a `CommandMenuMarkup` as well. With no `href`, or `&text;` in it, the command is the tag's text. | -| `IMAGE fname url w h align` | An `ImageMarkup`. Sized in cells (`W=4c H=2c`), it is drawn over the cells the server leaves for it. | -| `SOUND`, `MUSIC` | `SoundMarkup` or `SoundStopMarkup` points | +| `IMAGE fname url t w h align` | An `ImageMarkup` at `url`, then the `t` directory, then `fname`. Sized in cells (`W=4c H=2c`), it is drawn over the cells the server leaves for it. | +| `SOUND`, `MUSIC` | `SoundMarkup` or `SoundStopMarkup` points, at `u`, then `t`, then the file | | `FRAME`, `DEST` | A `PaneMarkup` over the text in `DEST`, titled from its `FRAME` | | `VAR name` | A `VariableMarkup` over its text, and a `VariableEvent` | | `EXPIRE`, `RELOCATE`, `USER`, `PASSWORD` | Their points | From 7aad77c53f1ad0416ce949e2349f33cbbbdd82c2 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 11 Nov 2026 02:14:56 +0000 Subject: [PATCH 2/3] HTML: reverse video with one colour swaps it with the page default \e[32;7m wrote only a green background, so the text kept the page's text colour; \e[41;7m wrote only red text with no background. A terminal swaps the colour with the default on the other side. The missing side is now var(--ms-bg) or var(--ms-fg), the properties ms-invert already swaps with. Found moving SharpClient's output view to MarkupString.Web: its old renderer drew these against the output's own colours. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Rqqt7TnKiMidjBirFcUqtL --- CHANGELOG.md | 5 +++++ MarkupString.Ansi/Emitters/AnsiHtmlEmitter.cs | 15 +++++++++++++++ MarkupString.Tests/Ansi/AnsiRenderTests.cs | 11 ++++++++++- 3 files changed, 30 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 892e212..0047713 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -58,6 +58,11 @@ follows [Semantic Versioning](https://semver.org/spec/v2.0.0.html). ### Fixed +- HTML: reverse video with only one colour now swaps it with the page's default on the other side, as a + terminal does. `\e[32;7m` was a green background under the page's text colour; the text is now + `var(--ms-bg)`, and `\e[41;7m` gets `var(--ms-fg)` as its background. These are the properties `ms-invert` + already swaps. + - `BlockLayout.Blocks` keeps the width of a block laid out at a width of its own: a non-fluid layout nested in another comes back `Bounded` by the width it was built at, so a 30-cell box inside a wider box stays 30 cells instead of stretching to the outer one. A fluid layout still takes the diff --git a/MarkupString.Ansi/Emitters/AnsiHtmlEmitter.cs b/MarkupString.Ansi/Emitters/AnsiHtmlEmitter.cs index d193120..00ee6d1 100644 --- a/MarkupString.Ansi/Emitters/AnsiHtmlEmitter.cs +++ b/MarkupString.Ansi/Emitters/AnsiHtmlEmitter.cs @@ -41,6 +41,15 @@ private static void WriteSpan(in AnsiStyle style, ReadOnlySpan body, in Em var foregroundSlot = SlotOf(foreground); var backgroundSlot = SlotOf(background); var hasStyle = foregroundHex.Length > 0 || backgroundHex.Length > 0; + + // Reverse video with one colour swaps it with the page's default on the other side, as a terminal + // does: the default background becomes the text colour, or the default text colour the background. + // These are the properties ms-invert swaps with, so both cases agree. + if (hasStyle && style.Inverted) + { + if (foregroundHex.Length == 0) foregroundHex = InvertedForeground; + if (backgroundHex.Length == 0) backgroundHex = InvertedBackground; + } var hasClasses = HasClasses(style, hasStyle); if (!hasStyle && !hasClasses) @@ -80,6 +89,12 @@ private static void WriteSpan(in AnsiStyle style, ReadOnlySpan body, in Em output.Write(""); } + /// The text colour of reverse video whose background is the default: the page's background. + private const string InvertedForeground = "var(--ms-bg, #000)"; + + /// The background of reverse video whose text colour is the default: the page's text colour. + private const string InvertedBackground = "var(--ms-fg, #fff)"; + /// The standard colour, 0-15, is, or -1 for any other. private static int SlotOf(AnsiColor? color) => color switch { diff --git a/MarkupString.Tests/Ansi/AnsiRenderTests.cs b/MarkupString.Tests/Ansi/AnsiRenderTests.cs index 082fa2b..5642eb9 100644 --- a/MarkupString.Tests/Ansi/AnsiRenderTests.cs +++ b/MarkupString.Tests/Ansi/AnsiRenderTests.cs @@ -175,7 +175,16 @@ public async Task Html_InvertedWithOnlyForeground_MovesItToTheBackground() var markup = AnsiMarkup.Create(foreground: new AnsiColor.Rgb(255, 0, 0), inverted: true); var text = MarkupText.Wrap(markup, "x"); await Assert.That(Render(text, MarkupFormat.Html)) - .IsEqualTo("x"); + .IsEqualTo("x"); + } + + [Test] + public async Task Html_InvertedWithOnlyBackground_MovesItToTheText() + { + var markup = AnsiMarkup.Create(background: new AnsiColor.Rgb(0, 0, 255), inverted: true); + var text = MarkupText.Wrap(markup, "x"); + await Assert.That(Render(text, MarkupFormat.Html)) + .IsEqualTo("x"); } [Test] From ca1d433eb264b499225d85be08eb15c1572eb3f0 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 11 Nov 2026 04:03:36 +0000 Subject: [PATCH 3/3] Add UrlPolicy.RefusingControlCharacters(), an opt-in check for addresses a browser would rewrite A browser removes tabs and newlines from a link address, and controls and spaces around it, before reading its scheme. An MXP or Pueblo href="java script:alert(1)" therefore passes UrlPolicy.Safe as a relative address and runs as javascript: when clicked. RefusingControlCharacters() returns the same policy, also refusing an address holding U+0000-U+001F or U+007F-U+009F, or with a space at either end. UrlPolicy.Safe is unchanged. MarkupStringOptions.RefuseControlCharactersInLinks turns it on for AddMarkupString. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Rqqt7TnKiMidjBirFcUqtL --- CHANGELOG.md | 8 +++ .../MarkupStringOptions.cs | 6 +++ .../PublicAPI.Unshipped.txt | 2 + .../ServiceCollectionExtensions.cs | 7 ++- MarkupString.Tests/Decoding/InjectionTests.cs | 51 +++++++++++++++++++ MarkupString/PublicAPI.Unshipped.txt | 2 + MarkupString/UrlPolicy.cs | 28 +++++++++- docs/dependency-injection.md | 5 ++ 8 files changed, 107 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 025bf9a..c3cb2dd 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,6 +8,14 @@ follows [Semantic Versioning](https://semver.org/spec/v2.0.0.html). ## Unreleased +### Added + +- `UrlPolicy.RefusingControlCharacters()`: the same policy, also refusing a link address that holds a + control character (U+0000–U+001F, U+007F–U+009F) or starts or ends with a space. A browser removes those + before reading the scheme, so an MXP or Pueblo `href="java script:alert(1)"` passes `UrlPolicy.Safe` as a + relative address and runs as `javascript:` when clicked. Opt-in; `UrlPolicy.Safe` is unchanged. + `MarkupStringOptions.RefuseControlCharactersInLinks` turns it on for `AddMarkupString`. + ## 2.28.1 — 2026-11-10 ### Fixed diff --git a/MarkupString.Extensions.DependencyInjection/MarkupStringOptions.cs b/MarkupString.Extensions.DependencyInjection/MarkupStringOptions.cs index b00b6c3..90bc85a 100644 --- a/MarkupString.Extensions.DependencyInjection/MarkupStringOptions.cs +++ b/MarkupString.Extensions.DependencyInjection/MarkupStringOptions.cs @@ -21,6 +21,12 @@ public sealed class MarkupStringOptions /// such as mudclient. javascript, data, vbscript and file are never allowed. /// public List LinkSchemes { get; set; } = []; + + /// + /// Whether a link address holding a control character, or with a space at either end, is refused + /// (). Off by default. + /// + public bool RefuseControlCharactersInLinks { get; set; } } /// How each connection's output is read. diff --git a/MarkupString.Extensions.DependencyInjection/PublicAPI.Unshipped.txt b/MarkupString.Extensions.DependencyInjection/PublicAPI.Unshipped.txt index 4dbfecd..3c3c9a2 100644 --- a/MarkupString.Extensions.DependencyInjection/PublicAPI.Unshipped.txt +++ b/MarkupString.Extensions.DependencyInjection/PublicAPI.Unshipped.txt @@ -50,3 +50,5 @@ MarkupString.Extensions.DependencyInjection.MarkupDecoderFactory.CreateDecoderFo MarkupString.Extensions.DependencyInjection.MarkupDecoderFactory.MarkupDecoderFactory(MarkupString.Decoding.DecoderRegistry! registry, MarkupString.Extensions.DependencyInjection.MarkupStringOptions! options, MarkupString.IUrlPolicy! links, System.Diagnostics.Metrics.IMeterFactory? meters = null, Microsoft.Extensions.Logging.ILoggerFactory? loggers = null) -> void MarkupString.Extensions.DependencyInjection.MarkupStringBuilder.AddEffectHandler(MarkupString.Display.IEffectHandler! handler) -> MarkupString.Extensions.DependencyInjection.MarkupStringBuilder! MarkupString.Extensions.DependencyInjection.MarkupStringBuilder.AddEffectHandler() -> MarkupString.Extensions.DependencyInjection.MarkupStringBuilder! +MarkupString.Extensions.DependencyInjection.MarkupStringOptions.RefuseControlCharactersInLinks.get -> bool +MarkupString.Extensions.DependencyInjection.MarkupStringOptions.RefuseControlCharactersInLinks.set -> void diff --git a/MarkupString.Extensions.DependencyInjection/ServiceCollectionExtensions.cs b/MarkupString.Extensions.DependencyInjection/ServiceCollectionExtensions.cs index b36e3dc..3dff4b5 100644 --- a/MarkupString.Extensions.DependencyInjection/ServiceCollectionExtensions.cs +++ b/MarkupString.Extensions.DependencyInjection/ServiceCollectionExtensions.cs @@ -30,7 +30,12 @@ public static MarkupStringBuilder AddMarkupString(this IServiceCollection servic services.AddOptions(); if (configure is not null) services.Configure(configure); - services.TryAddSingleton(static sp => UrlPolicy.WithSchemes(Options(sp).LinkSchemes)); + services.TryAddSingleton(static sp => + { + var options = Options(sp); + var policy = UrlPolicy.WithSchemes(options.LinkSchemes); + return options.RefuseControlCharactersInLinks ? policy.RefusingControlCharacters() : policy; + }); services.TryAddSingleton(static sp => new MemoryPictureCache { Budget = Options(sp).Pictures.Budget }); services.TryAddSingleton(sp => { diff --git a/MarkupString.Tests/Decoding/InjectionTests.cs b/MarkupString.Tests/Decoding/InjectionTests.cs index 7783643..f8f3650 100644 --- a/MarkupString.Tests/Decoding/InjectionTests.cs +++ b/MarkupString.Tests/Decoding/InjectionTests.cs @@ -30,6 +30,44 @@ public async Task UrlPolicy_AddsSchemes_ButNeverTheDangerousOnes() await Assert.That(UrlPolicy.Safe.IsAllowed("mudclient://look")).IsFalse(); } + [Test] + [Arguments("java\tscript:alert(1)")] + [Arguments("java\nscript:alert(1)")] + [Arguments("\u0001javascript:alert(1)")] + [Arguments("\u0085javascript:alert(1)")] + [Arguments(" javascript:alert(1)")] + [Arguments("/look ")] + public async Task UrlPolicy_RefusingControlCharacters_RefusesWhatABrowserWouldStrip(string url) + { + await Assert.That(UrlPolicy.Safe.RefusingControlCharacters().IsAllowed(url)).IsFalse(); + await Assert.That(UrlPolicy.WithSchemes("mudclient").RefusingControlCharacters().IsAllowed(url)).IsFalse(); + } + + [Test] + public async Task UrlPolicy_RefusingControlCharacters_IsOptIn() + { + // A tab inside reads as a relative address unless the host asks for it to be refused. + await Assert.That(UrlPolicy.Safe.RefusesControlCharacters).IsFalse(); + await Assert.That(UrlPolicy.Safe.IsAllowed("java\tscript:alert(1)")).IsTrue(); + + var strict = UrlPolicy.WithSchemes("mudclient").RefusingControlCharacters(); + await Assert.That(strict.RefusesControlCharacters).IsTrue(); + await Assert.That(strict.RefusingControlCharacters()).IsSameReferenceAs(strict); + await Assert.That(strict.IsAllowed("mudclient://look")).IsTrue(); + await Assert.That(strict.IsAllowed("https://example.com/a b")).IsTrue(); + await Assert.That(strict.IsAllowed("javascript:alert(1)")).IsFalse(); + } + + [Test] + public async Task UrlPolicy_RefusingControlCharacters_KeepsAnMxpLinkAsText() + { + var registry = MarkupRegistry.Empty.WithAnsi().WithHtml(); + var link = MarkupText.Wrap(new AnsiMarkup(new AnsiStyle { LinkUrl = "java\tscript:alert(1)", LinkKind = LinkKind.Url }), "x"); + + await Assert.That(link.Render(MarkupFormat.Html, registry)).Contains("href="); + await Assert.That(link.Render(MarkupFormat.Html, registry.WithLinks(UrlPolicy.Safe.RefusingControlCharacters()))).IsEqualTo("x"); + } + [Test] public async Task UrlPolicy_DecidesDecodedAndDisplayedLinks() { @@ -192,4 +230,17 @@ public async Task AddMarkupString_LogsWhatDecodersDrop() var link = MarkupText.Wrap(new AnsiMarkup(new AnsiStyle { LinkUrl = "mudclient://look", LinkKind = LinkKind.Url }), "look"); await Assert.That(link.Render(MarkupFormat.Html, services.GetRequiredService())).Contains("href=\"mudclient://look\""); } + + [Test] + public async Task AddMarkupString_RefusesControlCharactersInLinksWhenAsked() + { + using var lax = new ServiceCollection().AddMarkupString().Services.BuildServiceProvider(); + using var strict = new ServiceCollection() + .AddMarkupString(options => options.RefuseControlCharactersInLinks = true) + .Services.BuildServiceProvider(); + + await Assert.That(lax.GetRequiredService().IsAllowed("java\tscript:alert(1)")).IsTrue(); + await Assert.That(strict.GetRequiredService().IsAllowed("java\tscript:alert(1)")).IsFalse(); + await Assert.That(strict.GetRequiredService().IsAllowed("https://example.com")).IsTrue(); + } } diff --git a/MarkupString/PublicAPI.Unshipped.txt b/MarkupString/PublicAPI.Unshipped.txt index 59af5dc..35eb50d 100644 --- a/MarkupString/PublicAPI.Unshipped.txt +++ b/MarkupString/PublicAPI.Unshipped.txt @@ -862,3 +862,5 @@ MarkupString.Layout.BorderStyle.Cross.get -> MarkupString.MarkupText! MarkupString.Layout.BorderStyle.Cross.init -> void MarkupString.Layout.Flex.Join.get -> bool MarkupString.Layout.Flex.Join.init -> void +MarkupString.UrlPolicy.RefusesControlCharacters.get -> bool +MarkupString.UrlPolicy.RefusingControlCharacters() -> MarkupString.UrlPolicy! diff --git a/MarkupString/UrlPolicy.cs b/MarkupString/UrlPolicy.cs index 480cb3d..48f290f 100644 --- a/MarkupString/UrlPolicy.cs +++ b/MarkupString/UrlPolicy.cs @@ -10,7 +10,8 @@ public interface IUrlPolicy /// /// The usual : relative addresses and http, https, mailto, ftp, /// ftps and tel, with whatever other schemes it is made with. javascript:, data:, -/// vbscript: and file: are never allowed. +/// vbscript: and file: are never allowed. also refuses an +/// address holding a control character, or with a space at either end. /// public sealed class UrlPolicy : IUrlPolicy { @@ -21,6 +22,12 @@ public sealed class UrlPolicy : IUrlPolicy private UrlPolicy(IEnumerable schemes) => _schemes = new HashSet(schemes, StringComparer.OrdinalIgnoreCase); + private UrlPolicy(HashSet schemes, bool refusesControlCharacters) + { + _schemes = schemes; + RefusesControlCharacters = refusesControlCharacters; + } + /// The usual schemes only. public static UrlPolicy Safe { get; } = new(Usual); @@ -34,14 +41,33 @@ public static UrlPolicy WithSchemes(params IEnumerable schemes) /// The schemes it allows. public IReadOnlyCollection Schemes => _schemes; + /// Whether it refuses an address holding a control character, or with a space at either end. + public bool RefusesControlCharacters { get; } + + /// + /// This policy, also refusing an address that holds a control character (U+0000–U+001F, U+007F–U+009F) or + /// starts or ends with a space. A browser removes tabs and newlines from an address, and controls and + /// spaces around it, before reading its scheme, so java&#9;script:alert(1) from an MXP or Pueblo + /// link passes as a relative address here and runs as javascript: when clicked. Off unless asked for, + /// so addresses a host already accepts keep working. + /// + public UrlPolicy RefusingControlCharacters() => RefusesControlCharacters ? this : new UrlPolicy(_schemes, refusesControlCharacters: true); + /// public bool IsAllowed(string url) { if (string.IsNullOrWhiteSpace(url)) return false; + if (RefusesControlCharacters && HasControlOrEdgeSpace(url)) return false; if (!Uri.TryCreate(url, UriKind.RelativeOrAbsolute, out var uri)) return false; // A relative URL or a bare fragment cannot name a scheme, so there is none to distrust. if (!uri.IsAbsoluteUri) return true; return _schemes.Contains(uri.Scheme); } + + private static bool HasControlOrEdgeSpace(string url) => + url.AsSpan().ContainsAnyInRange('\u0000', '\u001F') + || url.AsSpan().ContainsAnyInRange('\u007F', '\u009F') + || url[0] == ' ' + || url[^1] == ' '; } diff --git a/docs/dependency-injection.md b/docs/dependency-injection.md index 234eab5..3b5a306 100644 --- a/docs/dependency-injection.md +++ b/docs/dependency-injection.md @@ -52,6 +52,7 @@ binds it from configuration. The binder is source-generated, so it works in a na { "MarkupString": { "LinkSchemes": [ "mudclient" ], + "RefuseControlCharactersInLinks": true, "Decoding": { "MaxLineLength": 65536, "MaxOpenElements": 64, "AnswerCursorPosition": false }, "Pictures": { "Enabled": true, "Budget": 268435456, "MaxPixels": 16777216 }, "Display": { "Output": "Browser", "Colors": "Xterm256", "BoldIsBright": false } @@ -71,6 +72,10 @@ These are in the core packages and need no container. and `CellRenderer` take one. - `IUrlPolicy`: which link addresses are allowed. `UrlPolicy.Safe` is the default; `UrlPolicy.WithSchemes("mudclient")` adds schemes, never `javascript`, `data`, `vbscript` or `file`. + `.RefusingControlCharacters()` also refuses an address holding a control character or with a space + at either end. A browser strips those before it reads the scheme, so `java script:` in an MXP or + Pueblo link would otherwise pass as a relative address and run as `javascript:`. It is off unless + asked for (`RefuseControlCharactersInLinks` in configuration). Set it as `DecoderOptions.Links` (what a server's links become), `DisplayOptions.Links` (what is drawn as clickable), `MarkupRegistry.WithLinks` (what every writer, ANSI, HTML, MXP, Pueblo, BBCode and Markdown, writes as a link) and `HtmlTagPolicy.Links` (which addresses a checked tag may hold).