From ccccea07fcae7e45d2c0932099ac4047783e504a Mon Sep 17 00:00:00 2001 From: Arlo Kharod <42082766+firegiant9000@users.noreply.github.com> Date: Wed, 18 Nov 2026 11:50:05 -0600 Subject: [PATCH 01/15] Static sheet: HTML renderer with tag-level self-check (4.8) --- src/AppService/Exports/HtmlSheet.cs | 461 +++++++++++++++++++++++ tests/AppService.Tests/HtmlSheetTests.cs | 222 +++++++++++ 2 files changed, 683 insertions(+) create mode 100644 src/AppService/Exports/HtmlSheet.cs create mode 100644 tests/AppService.Tests/HtmlSheetTests.cs diff --git a/src/AppService/Exports/HtmlSheet.cs b/src/AppService/Exports/HtmlSheet.cs new file mode 100644 index 00000000..ce0a212e --- /dev/null +++ b/src/AppService/Exports/HtmlSheet.cs @@ -0,0 +1,461 @@ +using System.Globalization; +using System.Net; +using System.Security.Cryptography; +using System.Text; +using System.Text.RegularExpressions; +using TomeStack.RulesCore; + +namespace TomeStack.AppService.Exports; + +/// What the HTML sheet shows besides the sheet export model: neither is part of sheet-export.v1. +/// Session notes; empty for a shared copy. +/// The character's current death saves, shown pre-ticked. +public sealed record HtmlSheetExtras(IReadOnlyList Notes, DeathSaves DeathSaves); + +/// +/// The static session sheet (4.8): one self-contained HTML page with no script, link, image or form, for a phone or +/// tablet. Every model string goes through ; ids are generated, never derived from names. +/// is the adapter's tag-level self-check before anything is written. +/// +public static partial class HtmlSheet +{ + public const string Target = "html-sheet"; + public const string AdapterVersion = "1.0.0"; + public const string FileSuffix = ".tomestack-sheet.html"; + + /// Largest pool drawn as tick boxes; the same number as PrintView's maxTickBoxes. + public const int MaxTickBoxes = 20; + + private static readonly string Css = """ + :root{--bg:#ffffff;--fg:#1a1a1a;--muted:#4a4a4a;--line:#767676;--card:#f3f3f3;--accent:#0b4fb3} + @media (prefers-color-scheme:dark){:root{--bg:#121212;--fg:#ececec;--muted:#bdbdbd;--line:#8a8a8a;--card:#1f1f1f;--accent:#8ab4f8}} + *{box-sizing:border-box} + body{margin:0;background:var(--bg);color:var(--fg);font:16px/1.45 system-ui,-apple-system,"Segoe UI",Roboto,sans-serif} + main{max-width:64rem;margin:0 auto;padding:1rem} + h1{font-size:1.6rem;margin:0 0 .5rem} + h2{font-size:1.25rem;margin:0 0 .5rem;border-bottom:1px solid var(--line)} + h3{font-size:1.05rem;margin:.75rem 0 .25rem;text-transform:capitalize} + section{background:var(--card);border:1px solid var(--line);border-radius:8px;padding:.75rem 1rem;margin:0 0 1rem;break-inside:avoid-column} + .muted{color:var(--muted)} + dl{margin:0;display:grid;grid-template-columns:max-content 1fr;gap:.25rem 1rem} + dt{color:var(--muted)} + dd{margin:0} + table{border-collapse:collapse;width:100%} + th,td{text-align:left;padding:.25rem .5rem;border-bottom:1px solid var(--line);vertical-align:top} + ul{margin:0;padding-left:1.25rem} + details{margin:.25rem 0} + summary{cursor:pointer;color:var(--accent);padding:.35rem 0;min-height:24px} + input[type=checkbox]{width:28px;height:28px;margin:.2rem .35rem .2rem 0;vertical-align:middle} + input[type=number]{width:6rem;min-height:44px;font:inherit;background:var(--bg);color:var(--fg);border:1px solid var(--line);border-radius:4px;padding:0 .5rem} + .pool{margin:.5rem 0} + .boxes{display:inline-block} + .note{white-space:pre-wrap;margin:.25rem 0 .75rem} + @media (min-width:700px){main{columns:2;column-gap:1rem}h1{column-span:all}} + @media print{:root{--bg:#fff;--fg:#000;--muted:#333;--line:#666;--card:#fff;--accent:#000}main{columns:1}details>*:not(summary){display:none}} + """.ReplaceLineEndings("\n").Insert(0, "\n") + "\n"; + + private static readonly string StyleHash = Convert.ToBase64String(SHA256.HashData(Encoding.UTF8.GetBytes(Css))); + + private static readonly string[] ForbiddenTags = ["script", "iframe", "object", "embed", "form", "base", "link", "img", "svg", "math"]; + private static readonly string[] ForbiddenAttributes = ["src", "srcset", "style", "action", "formaction", "poster", "xlink:href"]; + + /// Renders the sheet. Pure: the same inputs give the same text. + public static string Render(SheetExport sheet, HtmlSheetExtras extras) + { + ArgumentNullException.ThrowIfNull(sheet); + ArgumentNullException.ThrowIfNull(extras); + var doc = new Doc(); + var sb = doc.Sb; + var character = sheet.Character; + sb.Append("\n\n\n\n"); + sb.Append("\n"); + sb.Append("\n"); + sb.Append("").Append(Text(character.Name)).Append(" — TomeStack sheet\n"); + sb.Append("\n\n\n
\n"); + sb.Append("

").Append(Text(character.Name)).Append("

\n"); + + RenderHeader(doc, sheet); + RenderCore(doc, sheet, extras.DeathSaves); + RenderAttacks(doc, sheet); + RenderSpellcasting(doc, sheet); + RenderResources(doc, sheet); + RenderFeatures(doc, sheet); + RenderNotes(doc, extras.Notes); + RenderSources(doc, sheet); + + sb.Append("
\n\n\n"); + return sb.ToString(); + } + + /// + /// The self-check: empty when the page holds none of the forbidden constructs. Runs on tags only: encoded text can + /// never hold a raw <, so a name such as "javascript:" is text and passes. + /// + public static IReadOnlyList Validate(string html) + { + ArgumentNullException.ThrowIfNull(html); + var reasons = new List(); + void Add(string reason) + { + if (!reasons.Contains(reason)) + reasons.Add(reason); + } + + foreach (Match style in StyleRegex().Matches(html)) + { + var body = style.Groups[2].Value; + if (body.Contains("@import", StringComparison.OrdinalIgnoreCase)) + Add("style: @import"); + if (body.Contains("url(", StringComparison.OrdinalIgnoreCase)) + Add("style: url("); + if (body.Contains('\\', StringComparison.Ordinal)) + Add("style: backslash escape"); + } + + var rest = StyleRegex().Replace(html, "$1$3"); + foreach (Match tag in TagRegex().Matches(rest)) + { + var text = tag.Value; + var name = TagNameRegex().Match(text).Groups[1].Value.ToLowerInvariant(); + if (name.Length == 0) + { + Add("malformed tag"); + continue; + } + if (name[0] is '!' or '?') + { + if (name != "!doctype") + Add($"markup declaration {name}"); + continue; + } + if (Array.IndexOf(ForbiddenTags, name) >= 0) + Add($"tag <{name}>"); + var isMeta = name == "meta"; + foreach (Match attribute in AttributeRegex().Matches(text[TagNameRegex().Match(text).Length..])) + { + var attributeName = attribute.Groups[1].Value.ToLowerInvariant(); + var value = attribute.Groups[2].Success ? attribute.Groups[2].Value : attribute.Groups[3].Success ? attribute.Groups[3].Value : attribute.Groups[4].Value; + if (attributeName.StartsWith("on", StringComparison.Ordinal)) + Add($"event attribute {attributeName}"); + else if (Array.IndexOf(ForbiddenAttributes, attributeName) >= 0) + Add($"attribute {attributeName}"); + else if (attributeName == "href" && !value.StartsWith('#')) + Add("href that is not an in-page anchor"); + else if (isMeta && attributeName == "http-equiv" && !value.Equals("Content-Security-Policy", StringComparison.OrdinalIgnoreCase)) + Add($"meta http-equiv {value}"); + } + } + + if (TagRegex().Replace(rest, "").Contains('<', StringComparison.Ordinal)) + Add("unterminated tag"); + return reasons; + } + + [GeneratedRegex("<[^<>]*>", RegexOptions.CultureInvariant, matchTimeoutMilliseconds: 1000)] + private static partial Regex TagRegex(); + + [GeneratedRegex(@"^<\s*/?\s*([^\s/>]*)", RegexOptions.CultureInvariant, matchTimeoutMilliseconds: 1000)] + private static partial Regex TagNameRegex(); + + [GeneratedRegex(@"[\s/]([^\s=/>""']+)(?:\s*=\s*(?:""([^""]*)""|'([^']*)'|([^\s>""']+)))?", RegexOptions.CultureInvariant, matchTimeoutMilliseconds: 1000)] + private static partial Regex AttributeRegex(); + + [GeneratedRegex(@"(]*>)(.*?)()", RegexOptions.IgnoreCase | RegexOptions.CultureInvariant | RegexOptions.Singleline, matchTimeoutMilliseconds: 1000)] + private static partial Regex StyleRegex(); + + // The one place model strings are encoded, for text and for attribute values alike. + private static string Text(string? value) => WebUtility.HtmlEncode(value ?? ""); + + private static string N(int value) => value.ToString(CultureInfo.InvariantCulture); + + private static string Signed(int value) => value >= 0 ? "+" + N(value) : N(value); + + private sealed class Doc + { + private int _count; + + public StringBuilder Sb { get; } = new(); + + public void Open(string heading) + { + _count++; + var id = "s" + N(_count); + Sb.Append("
\n

").Append(Text(heading)).Append("

\n"); + } + + public void Close() => Sb.Append("
\n"); + } + + private static void Boxes(StringBuilder sb, string label, int count, int ticked) + { + sb.Append(""); + for (var i = 1; i <= count; i++) + sb.Append("'); + sb.Append("\n"); + } + + /// A pool of spendable things: tick boxes when small, a number when large, text when unbounded. + private static void Pool(StringBuilder sb, string label, string boxLabel, int? maximum, int spent) + { + sb.Append("
").Append(Text(label)).Append("\n"); + if (maximum is null) + sb.Append("

Spent ").Append(N(spent)).Append(" (no fixed maximum)

\n"); + else if (maximum <= 0) + { + // Nothing to spend. + } + else if (maximum <= MaxTickBoxes) + Boxes(sb, boxLabel, maximum.Value, Math.Min(spent, maximum.Value)); + else + { + sb.Append("

Spent ").Append(N(spent)).Append(" of ").Append(N(maximum.Value)).Append("

\n"); + sb.Append("\n"); + } + sb.Append("
\n"); + } + + private static void Details(StringBuilder sb, string summary, Action body) + { + sb.Append("
").Append(Text(summary)).Append("\n"); + body(); + sb.Append("
\n"); + } + + private static void Paragraph(StringBuilder sb, string? text) + { + if (!string.IsNullOrEmpty(text)) + sb.Append("

").Append(Text(text)).Append("

\n"); + } + + private static string ProficiencyText(SheetProficiency proficiency) => proficiency switch + { + SheetProficiency.Proficient => "Proficient", + SheetProficiency.Expertise => "Expertise", + _ => "", + }; + + private static void RenderHeader(Doc doc, SheetExport sheet) + { + var sb = doc.Sb; + var character = sheet.Character; + doc.Open("Character"); + sb.Append("
\n"); + sb.Append("
Level
").Append(N(character.Level)).Append("
\n"); + foreach (var @class in character.Classes) + { + sb.Append("
Class
").Append(Text(@class.Name)).Append(' ').Append(N(@class.Level)); + if (@class.Subclass is not null) + sb.Append(" (").Append(Text(@class.Subclass)).Append(')'); + sb.Append("
\n"); + } + sb.Append("
Rules
").Append(Text(character.RulesFamily)).Append("
\n"); + sb.Append("
Exported
").Append(sheet.ExportedAt.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture)).Append("
\n"); + sb.Append("
Copy
").Append(sheet.Purpose == SheetPurpose.Personal ? "Personal copy — do not share" : "For a shared game").Append("
\n"); + sb.Append("
\n"); + doc.Close(); + } + + private static void RenderCore(Doc doc, SheetExport sheet, DeathSaves deathSaves) + { + var sb = doc.Sb; + doc.Open("Core"); + sb.Append("
\n"); + foreach (var field in sheet.Fields.Where(f => f.Id is not (FieldIds.HitPoints or FieldIds.SpellAttack or FieldIds.SpellSaveDc))) + sb.Append("
").Append(Text(field.Label)).Append("
").Append(N(field.Value)).Append("
\n"); + var hp = sheet.HitPoints; + sb.Append("
Hit points
Max ").Append(N(hp.Maximum)).Append(", current ").Append(N(hp.Current)).Append(", temporary ").Append(N(hp.Temporary)).Append("
\n"); + sb.Append("
\n"); + sb.Append("

\n"); + sb.Append("

\n"); + + sb.Append("\n\n\n"); + foreach (var ability in sheet.Abilities) + { + sb.Append("\n"); + } + sb.Append("\n
AbilityScoreModifierSaveSave proficiency
").Append(Text(ability.Ability.ToUpperInvariant())).Append("").Append(N(ability.Score)).Append("").Append(Signed(ability.Modifier)) + .Append("").Append(Signed(ability.Save)).Append("").Append(ProficiencyText(ability.SaveProficiency)).Append("
\n"); + + if (sheet.Skills.Count > 0) + { + sb.Append("

Skills

\n
    \n"); + foreach (var skill in sheet.Skills) + { + sb.Append("
  • ").Append(Text(skill.Label)).Append(' ').Append(Signed(skill.Total)); + if (skill.Proficiency != SheetProficiency.None) + sb.Append(" (").Append(ProficiencyText(skill.Proficiency)).Append(")"); + sb.Append("
  • \n"); + } + sb.Append("
\n"); + } + + sb.Append("

Conditions

\n"); + sb.Append("

").Append(sheet.Conditions.Active.Count > 0 ? string.Join(", ", sheet.Conditions.Active.Select(Text)) : "None") + .Append(". Exhaustion ").Append(N(sheet.Conditions.Exhaustion)).Append(".

\n"); + + sb.Append("

Death saves

\n

Successes "); + Boxes(sb, "Death save success", DeathSaves.Maximum, Math.Clamp(deathSaves.Successes, 0, DeathSaves.Maximum)); + sb.Append("

\n

Failures "); + Boxes(sb, "Death save failure", DeathSaves.Maximum, Math.Clamp(deathSaves.Failures, 0, DeathSaves.Maximum)); + sb.Append("

\n"); + doc.Close(); + } + + private static void RenderAttacks(Doc doc, SheetExport sheet) + { + if (sheet.Attacks.Count == 0) + return; + var sb = doc.Sb; + doc.Open("Attacks"); + sb.Append("\n\n\n"); + foreach (var attack in sheet.Attacks) + { + sb.Append("\n"); + } + sb.Append("\n
AttackTo hitDamageRangeProperties
").Append(Text(attack.Name)).Append("").Append(Signed(attack.ToHit)).Append("").Append(Text(attack.Damage)).Append(' ').Append(Text(attack.DamageType)); + if (attack.VersatileDamage is not null) + sb.Append(" (versatile ").Append(Text(attack.VersatileDamage)).Append(')'); + sb.Append("").Append(Text(attack.Range)).Append("").Append(string.Join(", ", attack.Properties.Select(Text))).Append("
\n"); + doc.Close(); + } + + private static void RenderSpellcasting(Doc doc, SheetExport sheet) + { + var slots = sheet.Slots.Where(s => s.Maximum > 0).ToList(); + var pact = sheet.PactSlots is { Maximum: > 0 } p ? p : null; + if (sheet.Spellcasting.Count == 0 && slots.Count == 0 && pact is null) + return; + var sb = doc.Sb; + doc.Open("Spellcasting"); + if (slots.Count > 0 || pact is not null) + sb.Append("

Ticked means spent.

\n"); + foreach (var slot in slots) + Pool(sb, "Level " + N(slot.Level) + " slots", "Level " + N(slot.Level) + " slot", slot.Maximum, slot.Spent); + if (pact is not null) + Pool(sb, "Pact slots (level " + N(pact.Level) + ")", "Pact slot", pact.Maximum, pact.Spent); + foreach (var caster in sheet.Spellcasting) + { + sb.Append("

").Append(Text(caster.Name)).Append("

\n"); + sb.Append("

Ability ").Append(Text(caster.Ability.ToUpperInvariant())).Append(", spell attack ").Append(Signed(caster.AttackBonus)).Append(", save DC ").Append(N(caster.SaveDc)).Append("

\n"); + foreach (var level in caster.Spells.GroupBy(s => s.Level).OrderBy(g => g.Key)) + { + sb.Append("

").Append(level.Key == 0 ? "Cantrips" : "Level " + N(level.Key)).Append("

\n"); + foreach (var spell in level) + { + var markers = (spell.Prepared ? " (prepared)" : "") + (spell.Concentration ? " (concentration)" : "") + (spell.Ritual ? " (ritual)" : ""); + Details(sb, spell.Name + markers, () => + { + var facts = new[] { spell.School, spell.CastingTime, spell.Range, spell.Components, spell.Duration }.Where(f => !string.IsNullOrEmpty(f)); + Paragraph(sb, string.Join(" | ", facts)); + Paragraph(sb, spell.Summary); + Paragraph(sb, spell.Text); + }); + } + } + } + doc.Close(); + } + + private static void RenderResources(Doc doc, SheetExport sheet) + { + if (sheet.Resources.Count == 0 && sheet.HitDice.Count == 0 && sheet.Toggles.Count == 0 && sheet.Scales.Count == 0) + return; + var sb = doc.Sb; + doc.Open("Resources"); + if (sheet.Resources.Count > 0 || sheet.HitDice.Count > 0) + sb.Append("

Ticked means spent.

\n"); + foreach (var resource in sheet.Resources) + { + var title = string.Equals(resource.Label, resource.Feature, StringComparison.Ordinal) ? resource.Label : resource.Label + " (" + resource.Feature + ")"; + Pool(sb, title, resource.Label, resource.Maximum, resource.Spent); + if (resource.Recovery.Count > 0) + sb.Append("

Recovers: ").Append(string.Join("; ", resource.Recovery.Select(Text))).Append("

\n"); + } + foreach (var dice in sheet.HitDice) + Pool(sb, "Hit dice d" + N(dice.Die), "Hit die d" + N(dice.Die), dice.Total, dice.Spent); + if (sheet.Toggles.Count > 0) + { + sb.Append("

Switches

\n
    \n"); + foreach (var toggle in sheet.Toggles) + sb.Append("
  • ").Append(Text(toggle.Label)).Append(": ").Append(toggle.On ? "on" : "off").Append("
  • \n"); + sb.Append("
\n"); + } + if (sheet.Scales.Count > 0) + { + sb.Append("

Class columns

\n
    \n"); + foreach (var scale in sheet.Scales) + sb.Append("
  • ").Append(Text(scale.Label)).Append(" (").Append(Text(scale.ClassName)).Append("): ").Append(N(scale.Value)).Append("
  • \n"); + sb.Append("
\n"); + } + doc.Close(); + } + + private static void RenderFeatures(Doc doc, SheetExport sheet) + { + if (sheet.Features.Count == 0) + return; + var sb = doc.Sb; + doc.Open("Features"); + foreach (var kind in sheet.Features.GroupBy(f => f.Kind)) + { + sb.Append("

").Append(Text(kind.Key)).Append("

\n"); + foreach (var feature in kind) + { + Details(sb, feature.Name, () => + { + Paragraph(sb, feature.Summary); + foreach (var text in feature.Texts) + Paragraph(sb, text); + }); + } + } + doc.Close(); + } + + private static void RenderNotes(Doc doc, IReadOnlyList notes) + { + if (notes.Count == 0) + return; + var sb = doc.Sb; + doc.Open("Session notes"); + foreach (var note in notes.OrderByDescending(n => n.Date).ThenByDescending(n => n.CreatedAt)) + { + sb.Append("

").Append(note.Date.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture)).Append("

\n"); + sb.Append("

").Append(Text(note.Text)).Append("

\n"); + } + doc.Close(); + } + + private static void RenderSources(Doc doc, SheetExport sheet) + { + if (sheet.Notices.Count == 0 && sheet.Dropped.Count == 0) + return; + var sb = doc.Sb; + doc.Open("Sources"); + if (sheet.Notices.Count > 0) + { + sb.Append("
    \n"); + foreach (var notice in sheet.Notices) + { + sb.Append("
  • ").Append(Text(notice.Title)).Append(" by ").Append(Text(notice.Publisher)).Append(". Licence: ").Append(Text(notice.License)).Append('.'); + if (!string.IsNullOrEmpty(notice.Attribution)) + sb.Append(' ').Append(Text(notice.Attribution)); + if (!string.IsNullOrEmpty(notice.ModificationNotice)) + sb.Append(' ').Append(Text(notice.ModificationNotice)); + if (notice.TotalsOnly) + sb.Append(" (totals only)"); + sb.Append("
  • \n"); + } + sb.Append("
\n"); + } + if (sheet.Dropped.Count > 0) + { + sb.Append("

Left out of this file

\n
    \n"); + foreach (var dropped in sheet.Dropped) + sb.Append("
  • ").Append(Text(dropped.Source)).Append(" by ").Append(Text(dropped.Publisher)).Append(": ").Append(N(dropped.Items)).Append(dropped.Items == 1 ? " item" : " items").Append("
  • \n"); + sb.Append("
\n"); + } + doc.Close(); + } +} diff --git a/tests/AppService.Tests/HtmlSheetTests.cs b/tests/AppService.Tests/HtmlSheetTests.cs new file mode 100644 index 00000000..ea9f8566 --- /dev/null +++ b/tests/AppService.Tests/HtmlSheetTests.cs @@ -0,0 +1,222 @@ +using System.Security.Cryptography; +using System.Text; +using System.Text.RegularExpressions; +using TomeStack.AppService.Exports; +using TomeStack.RulesCore; + +namespace TomeStack.AppService.Tests; + +public sealed class HtmlSheetTests +{ + private const string Evil = "\">&'"; + + private static readonly ContentReference Ref = new(Guid.Empty, Guid.Empty); + private static readonly HtmlSheetExtras NoExtras = new([], new DeathSaves()); + + private static SheetExport Sample(Func? t = null) + { + t ??= s => s; + return new SheetExport( + SheetExport.FormatName, SheetExport.CurrentFormatVersion, SheetPurpose.Personal, new DateTimeOffset(2026, 11, 19, 8, 0, 0, TimeSpan.Zero), + new SheetCharacter(t("Mira Vale"), "srd-5.2.1", 3, [new SheetClass(t("Wayfarer"), 3, 8, t("Lantern Path"), Ref, "Homebrew", Ref)]), + [new SheetAbility("str", 10, 0, 0, SheetProficiency.None), new SheetAbility("dex", 16, 3, 5, SheetProficiency.Proficient)], + [new SheetSkill("stealth", t("Stealth"), "dex", 5, SheetProficiency.Expertise)], + [new SheetField(FieldIds.ArmorClass, t("Armor Class"), 15, AutomationStatus.Automatic, false), new SheetField(FieldIds.Initiative, t("Initiative"), 3, AutomationStatus.Automatic, false)], + new SheetHitPoints(24, 20, 2), + [new SheetHitDice(8, 3, 1)], + [new SheetSlots(1, 4, 1)], + null, + [new SheetCaster(t("Wayfarer"), "int", 5, 13, 3, "prepared", "spellSlots", + [new SheetSpell(t("Lantern Spark"), 1, true, t("evocation"), "1 action", "60 feet", "V, S", "Instant", false, false, t("A small flare."), t("The flare lights the way."), Ref, t("Homebrew"))], + Ref, t("Homebrew"))], + [new SheetResource(t("Trail Sense"), t("Trailcraft"), 3, 1, [t("long rest: all")], Ref, t("Homebrew"))], + [new SheetAttack(t("Walking Staff"), 5, "1d6+3", "1d8+3", t("bludgeoning"), [t("versatile")], t("5 ft"), true, Ref, t("Homebrew"))], + [new SheetFeature(t("Map Reader"), t("class"), t("Reads maps."), AutomationStatus.Reference, [t("You always know north.")], Ref, t("Homebrew"))], + [new SheetToggle(t("Lantern lit"), t("Lantern Path"), true, Ref, t("Homebrew"))], + [new SheetScale(t("Trail dice"), t("Wayfarer"), 2, Ref, t("Homebrew"))], + new SheetConditions([t("Prone")], 1), + [new SheetDropped(t("Outside Book"), t("Outside Press"), 2)], + [new SheetNotice(t("Homebrew"), t("Me"), t("CC-BY-4.0"), true, t("Credit line."), t("Changed for tests."), false)]); + } + + private static HtmlSheetExtras Extras(params SessionNote[] notes) => new(notes, new DeathSaves(2, 1)); + + private static SessionNote Note(string date, string text, int minutes = 0) => + new(Guid.NewGuid(), DateOnly.Parse(date, System.Globalization.CultureInfo.InvariantCulture), text, new DateTimeOffset(2026, 11, 1, 0, minutes, 0, TimeSpan.Zero)); + + private static int Count(string text, string needle) + { + var count = 0; + for (var at = text.IndexOf(needle, StringComparison.Ordinal); at >= 0; at = text.IndexOf(needle, at + needle.Length, StringComparison.Ordinal)) + count++; + return count; + } + + private static Match[] Find(string input, string pattern) => + [.. Regex.Matches(input, pattern, RegexOptions.CultureInvariant | RegexOptions.Singleline, TimeSpan.FromSeconds(1)).Cast()]; + + private static (int Total, int Checked) BoxesWith(string html, string labelPrefix) + { + var matches = Find(html, ""); + return (matches.Length, matches.Count(m => m.Groups[1].Success)); + } + + private static string Wrap(string body) => + "t
" + body + "
"; + + [Theory] + [InlineData("")] + [InlineData("

a

")] + [InlineData("")] + [InlineData("a")] + [InlineData("a")] + [InlineData("

a

")] + [InlineData("")] + [InlineData("")] + [InlineData("")] + [InlineData("
")] + [InlineData("")] + [InlineData("")] + [InlineData("")] + [InlineData("")] + [InlineData("")] + [InlineData("")] + [InlineData("")] + [InlineData("")] + [InlineData("

a

")] + [InlineData("javascript:alert(1) onerror=1 <script>

"))); + Assert.Empty(HtmlSheet.Validate(Wrap("a"))); + } + + [Fact] + public void Every_string_field_is_encoded() + { + var html = HtmlSheet.Render(Sample(s => Evil + s), Extras(Note("2026-11-01", Evil))); + + Assert.DoesNotContain("")); + var style = Find(html, "").Single().Groups[1].Value; + var hash = Convert.ToBase64String(SHA256.HashData(Encoding.UTF8.GetBytes(style))); + var csp = Find(html, "").Single().Groups[1].Value; + Assert.Contains("default-src 'none'", csp, StringComparison.Ordinal); + Assert.Contains("form-action 'none'", csp, StringComparison.Ordinal); + Assert.Contains("base-uri 'none'", csp, StringComparison.Ordinal); + Assert.Contains("style-src 'sha256-" + hash + "'", csp, StringComparison.Ordinal); + } + + [Fact] + public void Spent_slots_and_pools_are_pre_ticked() + { + var html = HtmlSheet.Render(Sample() with { Resources = [], HitDice = [] }, Extras()); + + Assert.Equal((4, 1), BoxesWith(html, "Level 1 slot ")); + Assert.Equal((3, 2), BoxesWith(html, "Death save success ")); + Assert.Equal((3, 1), BoxesWith(html, "Death save failure ")); + } + + [Fact] + public void Pool_boxes_are_bounded() + { + string Resources(int? maximum, int spent) + { + var html = HtmlSheet.Render(Sample() with { Resources = [new SheetResource("Pool", "Pool", maximum, spent, [], Ref, "S")], HitDice = [] }, Extras()); + var start = html.IndexOf("

Resources

", start, StringComparison.Ordinal); + return html[at..html.IndexOf("", at, StringComparison.Ordinal)]; + } + + Assert.Equal((3, 3), BoxesWith(Resources(3, 5), "Pool ")); + var none = Resources(0, 0); + Assert.Equal(0, Count(none, "Lantern Spark[^<]*\n.*The flare lights the way\\..*?", RegexOptions.Singleline, TimeSpan.FromSeconds(1)), html); + Assert.Matches(new Regex("
Map Reader\n.*You always know north\\..*?
", RegexOptions.Singleline, TimeSpan.FromSeconds(1)), html); + } + + [Fact] + public void Notes_render_only_when_given() + { + var withNotes = HtmlSheet.Render(Sample(), Extras(Note("2026-10-01", "older note"), Note("2026-11-01", "newer note"))); + Assert.Contains("Session notes", withNotes, StringComparison.Ordinal); + Assert.True(withNotes.IndexOf("newer note", StringComparison.Ordinal) < withNotes.IndexOf("older note", StringComparison.Ordinal)); + + Assert.DoesNotContain("Session notes", HtmlSheet.Render(Sample(), Extras()), StringComparison.Ordinal); + } + + [Fact] + public void Empty_sections_are_left_out() + { + var empty = Sample() with + { + Spellcasting = [], Slots = [], PactSlots = null, Resources = [], HitDice = [], Toggles = [], Scales = [], Attacks = [], Features = [], + }; + var html = HtmlSheet.Render(empty, Extras()); + + Assert.DoesNotContain("Spellcasting", html, StringComparison.Ordinal); + Assert.DoesNotContain("Resources", html, StringComparison.Ordinal); + Assert.DoesNotContain("Attacks", html, StringComparison.Ordinal); + Assert.DoesNotContain("Features", html, StringComparison.Ordinal); + Assert.DoesNotContain("Session notes", html, StringComparison.Ordinal); + Assert.Empty(HtmlSheet.Validate(html)); + Assert.Equal(1, Count(html, "

")); + } + + [Fact] + public void Non_ascii_text_survives() + { + var html = HtmlSheet.Render(Sample(s => s == "Mira Vale" ? "Zoë Ærin" : s), Extras()); + + Assert.Contains("", html, StringComparison.Ordinal); + Assert.True(html.Contains("Zoë", StringComparison.Ordinal) || html.Contains("Zoë", StringComparison.Ordinal)); + } + + [Fact] + public void Every_checkbox_and_input_has_a_name_for_screen_readers() + { + var html = HtmlSheet.Render(Sample() with { Resources = [new SheetResource("Big", "Big", 30, 2, [], Ref, "S")] }, Extras(Note("2026-11-01", "n"))); + + var inputs = Find(html, "]*>"); + Assert.NotEmpty(inputs); + foreach (var input in inputs) + Assert.Contains("aria-label=\"", input.Value, StringComparison.Ordinal); + } + + [Fact] + public void Output_is_deterministic() + { + Assert.Equal(HtmlSheet.Render(Sample(), Extras(Note("2026-11-01", "n"))), HtmlSheet.Render(Sample(), Extras(Note("2026-11-01", "n")))); + } +} From b2a88486d0dfe639a6badf002ec77591c2eb9101 Mon Sep 17 00:00:00 2001 From: Arlo Kharod <42082766+firegiant9000@users.noreply.github.com> Date: Wed, 18 Nov 2026 11:53:30 -0600 Subject: [PATCH 02/15] Static sheet: quote-aware tag and attribute scan in Validate (4.8) --- src/AppService/Exports/HtmlSheet.cs | 5 +++-- tests/AppService.Tests/HtmlSheetTests.cs | 3 +++ 2 files changed, 6 insertions(+), 2 deletions(-) diff --git a/src/AppService/Exports/HtmlSheet.cs b/src/AppService/Exports/HtmlSheet.cs index ce0a212e..8e63fc95 100644 --- a/src/AppService/Exports/HtmlSheet.cs +++ b/src/AppService/Exports/HtmlSheet.cs @@ -152,13 +152,14 @@ void Add(string reason) return reasons; } - [GeneratedRegex("<[^<>]*>", RegexOptions.CultureInvariant, matchTimeoutMilliseconds: 1000)] + // Quote-aware like the HTML tokenizer: a ">" inside a quoted value does not end the tag. An unmatched quote leaves the "<" unmatched, which Validate rejects. + [GeneratedRegex("""<(?:[^<>"']|"[^"]*"|'[^']*')*>""", RegexOptions.CultureInvariant, matchTimeoutMilliseconds: 1000)] private static partial Regex TagRegex(); [GeneratedRegex(@"^<\s*/?\s*([^\s/>]*)", RegexOptions.CultureInvariant, matchTimeoutMilliseconds: 1000)] private static partial Regex TagNameRegex(); - [GeneratedRegex(@"[\s/]([^\s=/>""']+)(?:\s*=\s*(?:""([^""]*)""|'([^']*)'|([^\s>""']+)))?", RegexOptions.CultureInvariant, matchTimeoutMilliseconds: 1000)] + [GeneratedRegex(@"(?<=[\s/""'])([^\s=/>""']+)(?:\s*=\s*(?:""([^""]*)""|'([^']*)'|([^\s>""']+)))?", RegexOptions.CultureInvariant, matchTimeoutMilliseconds: 1000)] private static partial Regex AttributeRegex(); [GeneratedRegex(@"(]*>)(.*?)()", RegexOptions.IgnoreCase | RegexOptions.CultureInvariant | RegexOptions.Singleline, matchTimeoutMilliseconds: 1000)] diff --git a/tests/AppService.Tests/HtmlSheetTests.cs b/tests/AppService.Tests/HtmlSheetTests.cs index ea9f8566..6826927c 100644 --- a/tests/AppService.Tests/HtmlSheetTests.cs +++ b/tests/AppService.Tests/HtmlSheetTests.cs @@ -85,6 +85,9 @@ private static string Wrap(string body) => [InlineData("")] [InlineData("

a

")] [InlineData("\" onclick=x>a

")] + [InlineData("

a

")] + [InlineData("

a

")] public void Validate_rejects_each_forbidden_construct(string fragment) { Assert.NotEmpty(HtmlSheet.Validate(Wrap(fragment))); From 62975f2ec44892a4b438bb3616df609f57252432 Mon Sep 17 00:00:00 2001 From: Arlo Kharod <42082766+firegiant9000@users.noreply.github.com> Date: Wed, 18 Nov 2026 11:58:39 -0600 Subject: [PATCH 03/15] Static sheet: hand-written HTML tokenizer for Validate (4.8) --- src/AppService/Exports/HtmlSheet.cs | 160 +++++++++++++++++------ tests/AppService.Tests/HtmlSheetTests.cs | 12 ++ 2 files changed, 129 insertions(+), 43 deletions(-) diff --git a/src/AppService/Exports/HtmlSheet.cs b/src/AppService/Exports/HtmlSheet.cs index 8e63fc95..ee56ccca 100644 --- a/src/AppService/Exports/HtmlSheet.cs +++ b/src/AppService/Exports/HtmlSheet.cs @@ -2,7 +2,6 @@ using System.Net; using System.Security.Cryptography; using System.Text; -using System.Text.RegularExpressions; using TomeStack.RulesCore; namespace TomeStack.AppService.Exports; @@ -17,7 +16,7 @@ public sealed record HtmlSheetExtras(IReadOnlyList Notes, DeathSave /// tablet. Every model string goes through ; ids are generated, never derived from names. /// is the adapter's tag-level self-check before anything is written. /// -public static partial class HtmlSheet +public static class HtmlSheet { public const string Target = "html-sheet"; public const string AdapterVersion = "1.0.0"; @@ -89,8 +88,9 @@ public static string Render(SheetExport sheet, HtmlSheetExtras extras) } /// - /// The self-check: empty when the page holds none of the forbidden constructs. Runs on tags only: encoded text can - /// never hold a raw <, so a name such as "javascript:" is text and passes. + /// The self-check: empty when the page holds none of the forbidden constructs. A single-pass tokenizer that follows the + /// HTML start-tag states (no regex), so it reads tags the way a browser does. Encoded text never holds a raw + /// <, so any < outside the doctype must start a tag, and text such as "javascript:" passes. /// public static IReadOnlyList Validate(string html) { @@ -102,68 +102,142 @@ void Add(string reason) reasons.Add(reason); } - foreach (Match style in StyleRegex().Matches(html)) + const string doctype = ""; + var n = html.Length; + var i = 0; + while (true) { - var body = style.Groups[2].Value; - if (body.Contains("@import", StringComparison.OrdinalIgnoreCase)) - Add("style: @import"); - if (body.Contains("url(", StringComparison.OrdinalIgnoreCase)) - Add("style: url("); - if (body.Contains('\\', StringComparison.Ordinal)) - Add("style: backslash escape"); - } - - var rest = StyleRegex().Replace(html, "$1$3"); - foreach (Match tag in TagRegex().Matches(rest)) - { - var text = tag.Value; - var name = TagNameRegex().Match(text).Groups[1].Value.ToLowerInvariant(); - if (name.Length == 0) + var lt = html.IndexOf('<', i); + if (lt < 0) + break; + i = lt + 1; + if (html.AsSpan(lt).StartsWith(doctype, StringComparison.OrdinalIgnoreCase)) { - Add("malformed tag"); + i = lt + doctype.Length; continue; } - if (name[0] is '!' or '?') + if (i >= n || !(IsLetter(html[i]) || (html[i] == '/' && i + 1 < n && IsLetter(html[i + 1])))) { - if (name != "!doctype") - Add($"markup declaration {name}"); + Add(i < n && html[i] is '!' or '?' ? "markup declaration" : "stray <"); + continue; + } + var endTag = html[i] == '/'; + if (endTag) + i++; + var nameStart = i; + while (i < n && !IsSpace(html[i]) && html[i] is not ('/' or '>')) + { + if (html[i] is '"' or '\'' or '<' or '=') + Add("malformed tag name"); + i++; + } + var name = html[nameStart..i].ToLowerInvariant(); + if (endTag) + { + while (i < n && html[i] is not ('>' or '<')) + i++; + if (i >= n || html[i] == '<') + Add("unterminated tag"); + else + i++; continue; } if (Array.IndexOf(ForbiddenTags, name) >= 0) Add($"tag <{name}>"); - var isMeta = name == "meta"; - foreach (Match attribute in AttributeRegex().Matches(text[TagNameRegex().Match(text).Length..])) + + var closed = false; + while (i < n) { - var attributeName = attribute.Groups[1].Value.ToLowerInvariant(); - var value = attribute.Groups[2].Success ? attribute.Groups[2].Value : attribute.Groups[3].Success ? attribute.Groups[3].Value : attribute.Groups[4].Value; + while (i < n && (IsSpace(html[i]) || html[i] == '/')) + i++; + if (i >= n) + break; + if (html[i] == '>') + { + i++; + closed = true; + break; + } + var attributeStart = i; + if (html[i] == '=') + i++; + while (i < n && !IsSpace(html[i]) && html[i] is not ('/' or '>' or '=')) + { + if (html[i] is '"' or '\'' or '<') + Add("malformed attribute name"); + i++; + } + var attributeName = html[attributeStart..i].ToLowerInvariant(); + while (i < n && IsSpace(html[i])) + i++; + var value = ""; + if (i < n && html[i] == '=') + { + i++; + while (i < n && IsSpace(html[i])) + i++; + if (i < n && html[i] is '"' or '\'') + { + var close = html.IndexOf(html[i], i + 1); + if (close < 0) + { + Add("unterminated quoted value"); + i = n; + break; + } + value = html[(i + 1)..close]; + i = close + 1; + } + else + { + var valueStart = i; + while (i < n && !IsSpace(html[i]) && html[i] != '>') + { + if (html[i] is '"' or '\'' or '<' or '=' or '`') + Add("malformed unquoted value"); + i++; + } + value = html[valueStart..i]; + } + } if (attributeName.StartsWith("on", StringComparison.Ordinal)) Add($"event attribute {attributeName}"); else if (Array.IndexOf(ForbiddenAttributes, attributeName) >= 0) Add($"attribute {attributeName}"); else if (attributeName == "href" && !value.StartsWith('#')) Add("href that is not an in-page anchor"); - else if (isMeta && attributeName == "http-equiv" && !value.Equals("Content-Security-Policy", StringComparison.OrdinalIgnoreCase)) + else if (name == "meta" && attributeName == "http-equiv" && !value.Equals("Content-Security-Policy", StringComparison.OrdinalIgnoreCase)) Add($"meta http-equiv {value}"); } + if (!closed) + { + Add("unterminated tag"); + break; + } + if (name == "style") + { + var end = html.IndexOf("" inside a quoted value does not end the tag. An unmatched quote leaves the "<" unmatched, which Validate rejects. - [GeneratedRegex("""<(?:[^<>"']|"[^"]*"|'[^']*')*>""", RegexOptions.CultureInvariant, matchTimeoutMilliseconds: 1000)] - private static partial Regex TagRegex(); - - [GeneratedRegex(@"^<\s*/?\s*([^\s/>]*)", RegexOptions.CultureInvariant, matchTimeoutMilliseconds: 1000)] - private static partial Regex TagNameRegex(); - - [GeneratedRegex(@"(?<=[\s/""'])([^\s=/>""']+)(?:\s*=\s*(?:""([^""]*)""|'([^']*)'|([^\s>""']+)))?", RegexOptions.CultureInvariant, matchTimeoutMilliseconds: 1000)] - private static partial Regex AttributeRegex(); + private static bool IsLetter(char c) => c is (>= 'a' and <= 'z') or (>= 'A' and <= 'Z'); - [GeneratedRegex(@"(]*>)(.*?)()", RegexOptions.IgnoreCase | RegexOptions.CultureInvariant | RegexOptions.Singleline, matchTimeoutMilliseconds: 1000)] - private static partial Regex StyleRegex(); + private static bool IsSpace(char c) => c is ' ' or '\t' or '\n' or '\f' or '\r'; // The one place model strings are encoded, for text and for attribute values alike. private static string Text(string? value) => WebUtility.HtmlEncode(value ?? ""); diff --git a/tests/AppService.Tests/HtmlSheetTests.cs b/tests/AppService.Tests/HtmlSheetTests.cs index 6826927c..d5e07a7d 100644 --- a/tests/AppService.Tests/HtmlSheetTests.cs +++ b/tests/AppService.Tests/HtmlSheetTests.cs @@ -88,6 +88,13 @@ private static string Wrap(string body) => [InlineData("

\" onclick=x>a

")] [InlineData("

a

")] [InlineData("

a

")] + [InlineData("\">a

")] + [InlineData("

\"c>")] + [InlineData("

a

")] + [InlineData("

a

")] + [InlineData("< script>x")] + [InlineData("")] + [InlineData("

a

")] public void Validate_rejects_each_forbidden_construct(string fragment) { Assert.NotEmpty(HtmlSheet.Validate(Wrap(fragment))); @@ -98,6 +105,9 @@ public void Validate_accepts_dangerous_words_in_text() { Assert.Empty(HtmlSheet.Validate(Wrap("

javascript:alert(1) onerror=1 <script>

"))); Assert.Empty(HtmlSheet.Validate(Wrap("a"))); + Assert.Empty(HtmlSheet.Validate(Wrap("

x

"))); + Assert.Empty(HtmlSheet.Validate(Wrap(""))); + Assert.Empty(HtmlSheet.Validate(Wrap("

on=1 <script> a > b

"))); } [Fact] @@ -220,6 +230,8 @@ public void Every_checkbox_and_input_has_a_name_for_screen_readers() [Fact] public void Output_is_deterministic() { + Assert.Empty(HtmlSheet.Validate(HtmlSheet.Render(Sample(), Extras(Note("2026-11-01", "n"))))); + Assert.Empty(HtmlSheet.Validate(HtmlSheet.Render(Sample() with { Resources = [new SheetResource("Big", "Big", 30, 2, [], Ref, "S")] }, NoExtras))); Assert.Equal(HtmlSheet.Render(Sample(), Extras(Note("2026-11-01", "n"))), HtmlSheet.Render(Sample(), Extras(Note("2026-11-01", "n")))); } } From f0e4e2ac1dce17eb11708d21407992b33fa41390 Mon Sep 17 00:00:00 2001 From: Arlo Kharod <42082766+firegiant9000@users.noreply.github.com> Date: Wed, 18 Nov 2026 12:19:35 -0600 Subject: [PATCH 04/15] Static sheet: html-sheet export target and Save filter (4.8) --- src/AppService/CommandDispatcher.cs | 4 +- src/AppService/Exports/ExportService.cs | 20 ++- tests/AppService.Tests/ExportAdapterTests.cs | 63 +++++++ .../multiclass-caster.tomestack-sheet.html | 160 ++++++++++++++++++ tests/AppService.Tests/HostServicesTests.cs | 28 +++ .../TomeStack.AppService.Tests.csproj | 1 + 6 files changed, 273 insertions(+), 3 deletions(-) create mode 100644 tests/AppService.Tests/Golden/multiclass-caster.tomestack-sheet.html diff --git a/src/AppService/CommandDispatcher.cs b/src/AppService/CommandDispatcher.cs index c7056259..a101dc03 100644 --- a/src/AppService/CommandDispatcher.cs +++ b/src/AppService/CommandDispatcher.cs @@ -538,7 +538,9 @@ private SaveOutcome SaveVttExportAs(ExtensionTokenPayload payload) if (host is null) throw new AppValidationException([new("host.unsupported", "This host has no native Save dialog.")], "unsupported"); var (fileName, bytes) = app.PeekVttExport(payload.Token); - var outcome = SaveBytes(fileName, bytes, "Export file", ".json"); + var outcome = fileName.EndsWith(".html", StringComparison.OrdinalIgnoreCase) + ? SaveBytes(fileName, bytes, "HTML page", ".html") + : SaveBytes(fileName, bytes, "Export file", ".json"); if (outcome.Saved) app.CompleteVttExport(payload.Token); return outcome; diff --git a/src/AppService/Exports/ExportService.cs b/src/AppService/Exports/ExportService.cs index 6952d329..4a6587d4 100644 --- a/src/AppService/Exports/ExportService.cs +++ b/src/AppService/Exports/ExportService.cs @@ -68,7 +68,7 @@ namespace TomeStack.AppService /// public sealed partial class TomeStackApp { - public static IReadOnlyList ExportTargets { get; } = [FoundryDnd5e.Target, SheetJson.Target]; + public static IReadOnlyList ExportTargets { get; } = [FoundryDnd5e.Target, SheetJson.Target, HtmlSheet.Target]; /// /// Export files are indented, and readable: HTML in a description is written as it is, not as < escapes. The @@ -95,6 +95,7 @@ public VttExportPreview PreviewVttExport(Guid characterId, string target, SheetP string? targetVersion; IReadOnlyList differences = []; var baseName = SafeName(sheet.Character.Name); + var htmlNotes = 0; if (target == FoundryDnd5e.Target) { var actor = FoundryDnd5e.Map(sheet); @@ -105,6 +106,17 @@ public VttExportPreview PreviewVttExport(Guid characterId, string target, SheetP (adapterVersion, targetVersion) = (FoundryDnd5e.AdapterVersion, $"Foundry VTT {FoundryDnd5e.CoreVersion} with dnd5e {FoundryDnd5e.SystemVersion}"); differences = FoundryDifferences(sheet); } + else if (target == HtmlSheet.Target) + { + var character = _store.FindCharacter(characterId) + ?? throw new AppValidationException([new("character.not-found", $"Character {characterId} does not exist.")]); + htmlNotes = purpose == SheetPurpose.Personal ? character.Notes.Count : 0; + text = HtmlSheet.Render(sheet, new(purpose == SheetPurpose.Personal ? character.Notes : [], character.Play.DeathSaves)); + if (HtmlSheet.Validate(text) is { Count: > 0 } problems) + throw new AppValidationException([new("export.invalid-output", $"The HTML sheet would not be safe to open ({problems[0]}), so nothing was written.")]); + fileName = baseName + HtmlSheet.FileSuffix; + (adapterVersion, targetVersion) = (HtmlSheet.AdapterVersion, "HTML page, no script"); + } else { var node = SheetJson.Map(sheet); @@ -117,7 +129,7 @@ public VttExportPreview PreviewVttExport(Guid characterId, string target, SheetP // The model is an allowlist with no path field; the scan is the second line (ADR-012 "Privacy"). The Foundry file // holds HTML-encoded text (an accented or quoted name is written as an entity), so the sheet it came from, whose // strings are the same but not encoded, is scanned too (review fix). - var scanned = target == FoundryDnd5e.Target ? [text, SheetJson.Map(sheet).ToJsonString(FileJson)] : new[] { text }; + var scanned = target == FoundryDnd5e.Target || target == HtmlSheet.Target ? [text, SheetJson.Map(sheet).ToJsonString(FileJson)] : new[] { text }; if (scanned.Any(t => OutputScan.Leaks(t, SensitivePaths(), [ScanIdentity().UserName]))) throw new AppValidationException([new("export.output-refused", "The file would contain a local path or your Windows user name, so nothing was written.")]); var bytes = Encoding.UTF8.GetBytes(text); @@ -129,6 +141,10 @@ public VttExportPreview PreviewVttExport(Guid characterId, string target, SheetP warnings.Add(new("export.personal", "Personal copy: includes your own homebrew. Do not share it.")); if (target == FoundryDnd5e.Target) warnings.Add(new("export.experimental", "Experimental: the Foundry file is checked against the dnd5e data model, but no import into a real Foundry world has been recorded yet.")); + if (htmlNotes > 0) + warnings.Add(new("export.html-notes", htmlNotes == 1 ? "Includes 1 session note." : $"Includes {htmlNotes} session notes.")); + if (target == HtmlSheet.Target) + warnings.Add(new("export.html-static", "Ticks on the phone are not saved: reopening the file starts from this export.")); return new(token, target, fileName, bytes.LongLength, adapterVersion, targetVersion, purpose, sheet.Dropped, sheet.Notices, differences, warnings); } diff --git a/tests/AppService.Tests/ExportAdapterTests.cs b/tests/AppService.Tests/ExportAdapterTests.cs index c818ca32..5a194531 100644 --- a/tests/AppService.Tests/ExportAdapterTests.cs +++ b/tests/AppService.Tests/ExportAdapterTests.cs @@ -356,4 +356,67 @@ public void The_dispatcher_previews_saves_and_downloads_an_export_once() Assert.Contains("\"export.expired\"", Send("export.download", new { token }), StringComparison.Ordinal); Assert.Contains("\"export.target-unknown\"", Send("export.preview", new { characterId = character.Id, target = "roll20" }), StringComparison.Ordinal); } + + private const string NoteOne = "Met the ferryman at the north dock."; + private const string NoteTwo = "The lamp in the cellar was still warm."; + + private static Character CasterWithNotes(TempApp temp, string? extraNote = null) + { + var caster = Golden(temp, "multiclass-caster"); + var created = new DateTimeOffset(2026, 9, 1, 12, 0, 0, TimeSpan.Zero); + var notes = new List + { + new(Guid.Parse("6f4e0000-0000-4000-8000-0000000000a1"), new DateOnly(2026, 9, 1), NoteOne, created), + new(Guid.Parse("6f4e0000-0000-4000-8000-0000000000a2"), new DateOnly(2026, 9, 8), extraNote ?? NoteTwo, created), + }; + return caster with { Notes = notes, Play = caster.Play with { DeathSaves = new(1, 1) } }; + } + + [Fact] + public void The_html_sheet_golden_is_stable() + { + using var temp = new TempApp(); + var character = temp.App.SaveCharacter(CasterWithNotes(temp)).Character; + var text = Export(temp, character.Id, HtmlSheet.Target, SheetPurpose.Personal); + Assert.Equal(text, Export(temp, character.Id, HtmlSheet.Target, SheetPurpose.Personal)); + var name = "multiclass-caster" + HtmlSheet.FileSuffix; + if (Environment.GetEnvironmentVariable("TOMESTACK_WRITE_GOLDEN") is { Length: > 0 } folder) + File.WriteAllText(Path.Combine(folder, name), text.ReplaceLineEndings("\n").TrimEnd('\n') + "\n"); + else + Assert.Equal(File.ReadAllText(Path.Combine(GoldenFolder, name)).ReplaceLineEndings("\n").TrimEnd('\n'), text.ReplaceLineEndings("\n").TrimEnd('\n')); + Assert.Empty(HtmlSheet.Validate(text)); + Assert.DoesNotContain("System Reference Document", text, StringComparison.Ordinal); + } + + [Fact] + public void Share_html_has_no_session_notes() + { + using var temp = new TempApp(); + var character = temp.App.SaveCharacter(CasterWithNotes(temp)).Character; + var text = Export(temp, character.Id, HtmlSheet.Target, SheetPurpose.Share); + Assert.DoesNotContain("Session notes", text, StringComparison.Ordinal); + Assert.DoesNotContain(NoteOne, text, StringComparison.Ordinal); + Assert.DoesNotContain(NoteTwo, text, StringComparison.Ordinal); + } + + [Fact] + public void Personal_html_preview_warns_about_notes_and_unsaved_ticks() + { + using var temp = new TempApp(); + var character = temp.App.SaveCharacter(CasterWithNotes(temp)).Character; + var preview = temp.App.PreviewVttExport(character.Id, HtmlSheet.Target, SheetPurpose.Personal); + Assert.Contains(preview.Warnings, w => w.Message == "Includes 2 session notes."); + Assert.Contains(preview.Warnings, w => w.Message.StartsWith("Ticks on the phone are not saved", StringComparison.Ordinal)); + Assert.EndsWith(HtmlSheet.FileSuffix, preview.FileName, StringComparison.Ordinal); + Assert.Equal("1.0.0", preview.AdapterVersion); + } + + [Fact] + public void A_note_holding_a_local_path_refuses_the_html_export() + { + using var temp = new TempApp(); + var character = temp.App.SaveCharacter(CasterWithNotes(temp, "Saved it under " + Path.GetFullPath(temp.App.DataDirectory))).Character; + var thrown = Assert.Throws(() => temp.App.PreviewVttExport(character.Id, HtmlSheet.Target, SheetPurpose.Personal)); + Assert.Contains(thrown.Problems, d => d.Code == "export.output-refused"); + } } diff --git a/tests/AppService.Tests/Golden/multiclass-caster.tomestack-sheet.html b/tests/AppService.Tests/Golden/multiclass-caster.tomestack-sheet.html new file mode 100644 index 00000000..551c6bdc --- /dev/null +++ b/tests/AppService.Tests/Golden/multiclass-caster.tomestack-sheet.html @@ -0,0 +1,160 @@ + + + + + + +Test Twin Caster — TomeStack sheet + + + +
+

Test Twin Caster

+
+

Character

+
+
Level
5
+
Class
Fixture Arcanist 3
+
Class
Fixture Chanter 2
+
Rules
srd-5.2.1
+
Exported
2026-09-24
+
Copy
Personal copy — do not share
+
+
+
+

Core

+
+
Armor Class
12
+
Initiative
2
+
Proficiency bonus
3
+
Hit points
Max 33, current 33, temporary 0
+
+

+

+ + + + + + + + + + +
AbilityScoreModifierSaveSave proficiency
STR8-1-1
DEX14+2+2
CON12+1+1
INT16+3+3
WIS10+0+0
CHA14+2+2
+

Skills

+
    +
  • Acrobatics +2
  • +
  • Animal Handling +0
  • +
  • Arcana +3
  • +
  • Athletics -1
  • +
  • Deception +2
  • +
  • History +3
  • +
  • Insight +0
  • +
  • Intimidation +2
  • +
  • Investigation +3
  • +
  • Medicine +0
  • +
  • Nature +3
  • +
  • Perception +0
  • +
  • Performance +2
  • +
  • Persuasion +2
  • +
  • Religion +3
  • +
  • Sleight of Hand +2
  • +
  • Stealth +2
  • +
  • Survival +0
  • +
+

Conditions

+

None. Exhaustion 0.

+

Death saves

+

Successes +

+

Failures +

+
+
+

Spellcasting

+

Ticked means spent.

+
Level 1 slots + +
+
Level 2 slots + +
+

Fixture Arcanist

+

Ability INT, spell attack +6, save DC 14

+

Cantrips

+
Fixture Spark (prepared) +

evocation | 1 action | 60 feet | V, S | Instantaneous

+

A test spell of level 0.

+

A test cantrip: a spark of light.

+
+

Level 1

+
Fixture Frost Ring (prepared) +

evocation | 1 action | Self (10-foot radius) | V, S | Instantaneous

+

A test spell of level 1.

+

A test spell: a ring of cold.

+
+

Fixture Chanter

+

Ability CHA, spell attack +5, save DC 13

+
+
+

Resources

+

Ticked means spent.

+
Hit dice d8 + +
+
+
+

Features

+

class

+
Fixture Arcanist +

A test caster (prepared, int).

+

Fixture Arcanist casts spells from the fixture-arcane list (test progression).

+
+
Fixture Chanter +

A test caster (known, cha).

+

Fixture Chanter casts spells from the fixture-song list (test progression).

+
+
+
+

Session notes

+

2026-09-08

+

The lamp in the cellar was still warm.

+

2026-09-01

+

Met the ferryman at the north dock.

+
+
+

Sources

+
    +
  • TomeStack Fixtures: Spellcasting by TomeStack project. Licence: Original test fixture. Written for TomeStack tests.
  • +
+
+
+ + diff --git a/tests/AppService.Tests/HostServicesTests.cs b/tests/AppService.Tests/HostServicesTests.cs index 97ca3689..20d1ef52 100644 --- a/tests/AppService.Tests/HostServicesTests.cs +++ b/tests/AppService.Tests/HostServicesTests.cs @@ -1,4 +1,5 @@ using System.Text.Json; +using TomeStack.AppService.Exports; using TomeStack.ImportWorker.Tests; using TomeStack.RulesCore; @@ -40,6 +41,33 @@ public void Save_as_writes_the_package_to_the_path_chosen_in_the_native_dialog_a Assert.False(File.Exists(target + ".partial")); } + private sealed class FilterHost : IHostServices + { + public (string Description, string Extension)? Filter { get; private set; } + + public string? ChooseSaveLocation(string suggestedFileName, string filterDescription, string extension) + { + Filter = (filterDescription, extension); + return null; + } + } + + [Theory] + [InlineData("html-sheet", "HTML page", ".html")] + [InlineData("sheet-json", "Export file", ".json")] + public void Html_export_saves_with_the_html_filter(string target, string description, string extension) + { + using var temp = new TempApp(); + var saved = temp.App.SaveCharacter(TempApp.LoadFixture("characters/srd51-quickfoot.json")); + var preview = temp.App.PreviewVttExport(saved.Character.Id, target, SheetPurpose.Share); + var host = new FilterHost(); + + var response = Dispatch(new CommandDispatcher(temp.App, host: host), "export.saveAs", new { token = preview.Token }); + + Assert.True(response.GetProperty("ok").GetBoolean(), response.ToString()); + Assert.Equal((description, extension), host.Filter); + } + [Fact] public void Cancelled_dialog_writes_nothing() { diff --git a/tests/AppService.Tests/TomeStack.AppService.Tests.csproj b/tests/AppService.Tests/TomeStack.AppService.Tests.csproj index 742efe3b..b3efe527 100644 --- a/tests/AppService.Tests/TomeStack.AppService.Tests.csproj +++ b/tests/AppService.Tests/TomeStack.AppService.Tests.csproj @@ -56,6 +56,7 @@ + From 12308555f068e54254586c1974226aa3a2794072 Mon Sep 17 00:00:00 2001 From: Arlo Kharod <42082766+firegiant9000@users.noreply.github.com> Date: Wed, 18 Nov 2026 12:27:10 -0600 Subject: [PATCH 05/15] Static sheet: scan the raw text of session notes too (4.8) --- src/AppService/Exports/ExportService.cs | 6 ++++++ tests/AppService.Tests/ExportAdapterTests.cs | 10 ++++++++++ 2 files changed, 16 insertions(+) diff --git a/src/AppService/Exports/ExportService.cs b/src/AppService/Exports/ExportService.cs index 4a6587d4..38b57074 100644 --- a/src/AppService/Exports/ExportService.cs +++ b/src/AppService/Exports/ExportService.cs @@ -96,6 +96,7 @@ public VttExportPreview PreviewVttExport(Guid characterId, string target, SheetP IReadOnlyList differences = []; var baseName = SafeName(sheet.Character.Name); var htmlNotes = 0; + string? rawNotes = null; if (target == FoundryDnd5e.Target) { var actor = FoundryDnd5e.Map(sheet); @@ -111,6 +112,8 @@ public VttExportPreview PreviewVttExport(Guid characterId, string target, SheetP var character = _store.FindCharacter(characterId) ?? throw new AppValidationException([new("character.not-found", $"Character {characterId} does not exist.")]); htmlNotes = purpose == SheetPurpose.Personal ? character.Notes.Count : 0; + if (htmlNotes > 0) + rawNotes = string.Join("\n", character.Notes.Select(n => n.Text)); text = HtmlSheet.Render(sheet, new(purpose == SheetPurpose.Personal ? character.Notes : [], character.Play.DeathSaves)); if (HtmlSheet.Validate(text) is { Count: > 0 } problems) throw new AppValidationException([new("export.invalid-output", $"The HTML sheet would not be safe to open ({problems[0]}), so nothing was written.")]); @@ -130,6 +133,9 @@ public VttExportPreview PreviewVttExport(Guid characterId, string target, SheetP // holds HTML-encoded text (an accented or quoted name is written as an entity), so the sheet it came from, whose // strings are the same but not encoded, is scanned too (review fix). var scanned = target == FoundryDnd5e.Target || target == HtmlSheet.Target ? [text, SheetJson.Map(sheet).ToJsonString(FileJson)] : new[] { text }; + // The HTML sheet also encodes its session notes, which the sheet model does not hold: scan their raw text too. + if (rawNotes is not null) + scanned = [.. scanned, rawNotes]; if (scanned.Any(t => OutputScan.Leaks(t, SensitivePaths(), [ScanIdentity().UserName]))) throw new AppValidationException([new("export.output-refused", "The file would contain a local path or your Windows user name, so nothing was written.")]); var bytes = Encoding.UTF8.GetBytes(text); diff --git a/tests/AppService.Tests/ExportAdapterTests.cs b/tests/AppService.Tests/ExportAdapterTests.cs index 5a194531..fe250da8 100644 --- a/tests/AppService.Tests/ExportAdapterTests.cs +++ b/tests/AppService.Tests/ExportAdapterTests.cs @@ -411,6 +411,16 @@ public void Personal_html_preview_warns_about_notes_and_unsaved_ticks() Assert.Equal("1.0.0", preview.AdapterVersion); } + [Fact] + public void A_note_holding_a_path_with_an_encoded_character_refuses_the_html_export() + { + // The HTML writes the apostrophe and the accented letter as entities, so only the raw note text can match the path. + using var temp = new TempApp(folder: "Zoë's data"); + var character = temp.App.SaveCharacter(CasterWithNotes(temp, "Saved it under " + Path.GetFullPath(temp.App.DataDirectory))).Character; + var thrown = Assert.Throws(() => temp.App.PreviewVttExport(character.Id, HtmlSheet.Target, SheetPurpose.Personal)); + Assert.Contains(thrown.Problems, d => d.Code == "export.output-refused"); + } + [Fact] public void A_note_holding_a_local_path_refuses_the_html_export() { From 2d1985ee72a111773ea3cf074e5f5d8b5bad1018 Mon Sep 17 00:00:00 2001 From: Arlo Kharod <42082766+firegiant9000@users.noreply.github.com> Date: Wed, 18 Nov 2026 12:36:10 -0600 Subject: [PATCH 06/15] Test: encoded-path note refusal no longer matches through the profile prefix --- tests/AppService.Tests/ExportAdapterTests.cs | 2 ++ 1 file changed, 2 insertions(+) diff --git a/tests/AppService.Tests/ExportAdapterTests.cs b/tests/AppService.Tests/ExportAdapterTests.cs index fe250da8..c50ebcd1 100644 --- a/tests/AppService.Tests/ExportAdapterTests.cs +++ b/tests/AppService.Tests/ExportAdapterTests.cs @@ -416,6 +416,8 @@ public void A_note_holding_a_path_with_an_encoded_character_refuses_the_html_exp { // The HTML writes the apostrophe and the accented letter as entities, so only the raw note text can match the path. using var temp = new TempApp(folder: "Zoë's data"); + // Point the profile and user name elsewhere, so the data folder is the only needle the note can match. + temp.App.ScanIdentity = () => ("Q:\\NoSuchProfileRoot", "NoSuchUserQq"); var character = temp.App.SaveCharacter(CasterWithNotes(temp, "Saved it under " + Path.GetFullPath(temp.App.DataDirectory))).Character; var thrown = Assert.Throws(() => temp.App.PreviewVttExport(character.Id, HtmlSheet.Target, SheetPurpose.Personal)); Assert.Contains(thrown.Problems, d => d.Code == "export.output-refused"); From 35eab52aac0339f246c602ea995acf9f91cdcd91 Mon Sep 17 00:00:00 2001 From: Arlo Kharod <42082766+firegiant9000@users.noreply.github.com> Date: Wed, 18 Nov 2026 12:47:46 -0600 Subject: [PATCH 07/15] Static sheet: export panel offers the phone or tablet sheet (4.8) --- src/Ui/e2e/sharing.e2e.tsx | 2 +- src/Ui/src/api/types.ts | 2 +- src/Ui/src/components/CharacterSheet.test.tsx | 2 +- src/Ui/src/components/VttExportPanel.test.tsx | 82 +++++++++++++++++++ src/Ui/src/components/VttExportPanel.tsx | 8 +- 5 files changed, 91 insertions(+), 5 deletions(-) create mode 100644 src/Ui/src/components/VttExportPanel.test.tsx diff --git a/src/Ui/e2e/sharing.e2e.tsx b/src/Ui/e2e/sharing.e2e.tsx index 738221a6..7a1da39c 100644 --- a/src/Ui/e2e/sharing.e2e.tsx +++ b/src/Ui/e2e/sharing.e2e.tsx @@ -258,7 +258,7 @@ it('exports a character for Foundry VTT and as sheet JSON after a preview, with await user.click(await screen.findByRole('button', { name: /^E2E VTT Hero/ })); const sheet = await screen.findByRole('article', { name: 'E2E VTT Hero' }); await openMore(user, sheet, 'Export…'); - const panel = within(sheet).getByRole('region', { name: 'Export for a virtual tabletop' }); + const panel = within(sheet).getByRole('region', { name: 'Export to another tool or device' }); const dataDir = inject('devHost').dataDir.toLowerCase().replaceAll('\\', '/'); // Foundry VTT (dnd5e): the preview names the pinned release, then DevHost downloads the file. diff --git a/src/Ui/src/api/types.ts b/src/Ui/src/api/types.ts index 99013477..150f9d53 100644 --- a/src/Ui/src/api/types.ts +++ b/src/Ui/src/api/types.ts @@ -1551,7 +1551,7 @@ export interface ExtensionRunPreview { } /** M6 slice 4 (ADR-012): export targets. */ -export type ExportTarget = 'foundry-dnd5e' | 'sheet-json'; +export type ExportTarget = 'foundry-dnd5e' | 'sheet-json' | 'html-sheet'; export interface VttExportPreview { token: string; diff --git a/src/Ui/src/components/CharacterSheet.test.tsx b/src/Ui/src/components/CharacterSheet.test.tsx index 7a6843b5..9b8c093a 100644 --- a/src/Ui/src/components/CharacterSheet.test.tsx +++ b/src/Ui/src/components/CharacterSheet.test.tsx @@ -942,7 +942,7 @@ describe('the More list (Wave 3 3.5)', () => { const user = userEvent.setup(); renderSheet(view()); await openMore(user, 'Export…'); - expect(await screen.findByRole('heading', { name: 'Export for a virtual tabletop' })).toBeTruthy(); + expect(await screen.findByRole('heading', { name: 'Export to another tool or device' })).toBeTruthy(); }); it('replaces the open panel when another item is chosen, focuses the new heading, and leaves the tab list without Manage', async () => { diff --git a/src/Ui/src/components/VttExportPanel.test.tsx b/src/Ui/src/components/VttExportPanel.test.tsx new file mode 100644 index 00000000..4b4155e0 --- /dev/null +++ b/src/Ui/src/components/VttExportPanel.test.tsx @@ -0,0 +1,82 @@ +// @vitest-environment jsdom +import { cleanup, render, screen, waitFor } from '@testing-library/react'; +import userEvent from '@testing-library/user-event'; +import { afterEach, beforeEach, expect, it, vi } from 'vitest'; +import { client } from '../api/client'; +import { TomeStackError } from '../api/transport'; +import type { VttExportPreview } from '../api/types'; +import { downloadBase64 } from '../files'; +import { VttExportPanel } from './VttExportPanel'; + +vi.mock('../api/client', () => ({ + client: { + previewVttExport: vi.fn(), + saveVttExportAs: vi.fn(), + downloadVttExport: vi.fn(), + packagePreflight: vi.fn(), + }, +})); +vi.mock('../files', () => ({ downloadBase64: vi.fn() })); + +afterEach(cleanup); + +function preview(target: VttExportPreview['target'], fileName: string): VttExportPreview { + return { + token: 't1', + target, + fileName, + bytes: 1, + adapterVersion: '1', + purpose: 'share', + dropped: [], + notices: [], + differences: [], + warnings: [], + }; +} + +beforeEach(() => { + vi.mocked(client.packagePreflight).mockResolvedValue({ included: [], omitted: [], blocking: [], notices: [] }); + vi.mocked(client.previewVttExport).mockResolvedValue(preview('html-sheet', 'x.tomestack-sheet.html')); +}); + +it('offers a phone or tablet sheet and previews it as html-sheet', async () => { + const user = userEvent.setup(); + render(); + await user.click(screen.getByRole('radio', { name: /Sheet for a phone or tablet/ })); + await user.click(screen.getByRole('button', { name: 'Preview export' })); + expect(client.previewVttExport).toHaveBeenCalledWith('c1', 'html-sheet', 'share'); +}); + +it('heading names other tools and devices', () => { + render(); + expect(screen.getByRole('heading', { name: 'Export to another tool or device' })).toBeTruthy(); +}); + +it('falls back to an html download in the browser', async () => { + const user = userEvent.setup(); + const onStatus = vi.fn(); + vi.mocked(client.saveVttExportAs).mockRejectedValue(new TomeStackError({ code: 'unsupported', message: 'Fixture: no dialog.' })); + vi.mocked(client.downloadVttExport).mockResolvedValue({ fileName: 'x.tomestack-sheet.html', base64: 'AA==' } as never); + render(); + await user.click(screen.getByRole('radio', { name: /Sheet for a phone or tablet/ })); + await user.click(screen.getByRole('button', { name: 'Preview export' })); + const save = await screen.findByRole('button', { name: 'Save export file…' }); + await waitFor(() => expect((save as HTMLButtonElement).disabled).toBe(false)); + await user.click(save); + await waitFor(() => expect(downloadBase64).toHaveBeenCalledWith('x.tomestack-sheet.html', 'AA==', 'text/html')); +}); + +it('keeps application/json for the TomeStack sheet (JSON) download', async () => { + const user = userEvent.setup(); + vi.mocked(client.previewVttExport).mockResolvedValue(preview('sheet-json', 'x.tomestack.json')); + vi.mocked(client.saveVttExportAs).mockRejectedValue(new TomeStackError({ code: 'unsupported', message: 'Fixture: no dialog.' })); + vi.mocked(client.downloadVttExport).mockResolvedValue({ fileName: 'x.tomestack.json', base64: 'e30=' } as never); + render(); + await user.click(screen.getByRole('radio', { name: /TomeStack sheet \(JSON\)/ })); + await user.click(screen.getByRole('button', { name: 'Preview export' })); + const save = await screen.findByRole('button', { name: 'Save export file…' }); + await waitFor(() => expect((save as HTMLButtonElement).disabled).toBe(false)); + await user.click(save); + await waitFor(() => expect(downloadBase64).toHaveBeenCalledWith('x.tomestack.json', 'e30=', 'application/json')); +}); diff --git a/src/Ui/src/components/VttExportPanel.tsx b/src/Ui/src/components/VttExportPanel.tsx index d6db81c1..af8c806d 100644 --- a/src/Ui/src/components/VttExportPanel.tsx +++ b/src/Ui/src/components/VttExportPanel.tsx @@ -51,7 +51,7 @@ export function VttExportPanel({ characterId, onError, onStatus }: Props) { // Browser development (DevHost) has no native dialog: fall back to a download. try { const file = await client.downloadVttExport(preview.token); - downloadBase64(file.fileName, file.base64, 'application/json'); + downloadBase64(file.fileName, file.base64, preview.target === 'html-sheet' ? 'text/html' : 'application/json'); onStatus(`Downloaded ${file.fileName}.`); setPreview(undefined); } catch (inner) { @@ -62,7 +62,7 @@ export function VttExportPanel({ characterId, onError, onStatus }: Props) { return (
-

Export for a virtual tabletop

+

Export to another tool or device

Format +
What the file may hold From f94594d5b5176b3592c778ccf316300e9001d005 Mon Sep 17 00:00:00 2001 From: Arlo Kharod <42082766+firegiant9000@users.noreply.github.com> Date: Wed, 18 Nov 2026 12:52:51 -0600 Subject: [PATCH 08/15] Static sheet: axe runs on the generated page in light and dark (4.8) --- src/Ui/a11y/static-sheet.a11y.tsx | 47 +++++++++++++++++++++++++++++++ src/Ui/vitest.a11y.config.ts | 2 +- 2 files changed, 48 insertions(+), 1 deletion(-) create mode 100644 src/Ui/a11y/static-sheet.a11y.tsx diff --git a/src/Ui/a11y/static-sheet.a11y.tsx b/src/Ui/a11y/static-sheet.a11y.tsx new file mode 100644 index 00000000..eb22f6e6 --- /dev/null +++ b/src/Ui/a11y/static-sheet.a11y.tsx @@ -0,0 +1,47 @@ +// 4.8: axe in the installed Edge, with colour contrast on, over the generated static session sheet (the golden export). +// Only the page's own