diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md index feb6dfa5..e5e40a4b 100644 --- a/docs/CHANGELOG.md +++ b/docs/CHANGELOG.md @@ -3,6 +3,7 @@ ## Unreleased ### Added +- **Sheet for a phone or tablet (D105, Wave 4 item 4.8):** More, Export, "Export to another tool or device" now offers "Sheet for a phone or tablet (HTML page, no internet needed)". It writes one `.tomestack-sheet.html` file that opens in any browser, with no script and no network: the core numbers, abilities, skills, attacks, spells (with slots as checkboxes), resources, features, notices and, in a personal copy only, your session notes. Ticks on the phone are not saved: reopening the file starts from the export. A share copy goes through the same preview and licence filter as the other exports. The sheet export model v1 is unchanged. [features/static-session-sheet.md](features/static-session-sheet.md). - **Development only, test load caps and a gate script:** local test runs no longer use every core. Vitest runs at most 8 workers (override with `TOMESTACK_TEST_WORKERS`), and xUnit runs at most 8 threads per test project on machines with more than 8 cores; CI keeps its defaults. `scripts/gate.ps1` runs gate steps 1–8 in order, with per-step logs, a summary, a watchdog for a hung e2e or a11y run, DevHost cleanup, an optional lower priority and a CPU check. No app change. - **Accessibility check in CI, two contrast fixes:** `npm run test:a11y` runs axe, colour contrast included, in the installed Edge against the DevHost, in light and dark, over home, each builder step and each sheet tab, plus home in each named theme. Serious and critical violations fail it, and it now runs in CI. It found two low-contrast spots, both fixed without changing any colour: the "Offline" tag in the header now sits on the page colour, and in the dark theme the sheet's status-bar buttons (Hit points, Armor Class, Initiative, Speed) now sit on the page colour instead of the browser's grey button face. - **Tests only:** the UI flow tests in `src/Ui/e2e/` are split by feature (the 69 tests of `flow.e2e.tsx` into eight files, the 13 of `forms.e2e.tsx` into two, shared helpers in `helpers.tsx`); no test changed and no file is over 800 lines. The e2e files now run one after another against the shared DevHost. No app change. diff --git a/docs/LIVING_SPECS.md b/docs/LIVING_SPECS.md index ad3d2912..43705c16 100644 --- a/docs/LIVING_SPECS.md +++ b/docs/LIVING_SPECS.md @@ -141,9 +141,11 @@ Create `CHANGELOG.md` with `## Unreleased` and subsections `Added`, `Changed`, ` | D102 | Wave 4 row 4.4: first paint budget in the smoke run? | **Decided (owner ruling, 2026-11-12):** the smoke ready time (process start to the end of the in-app smoke script, the report's `processStartToReadyMs`; an upper bound on first paint) over 15 s locally or 45 s in CI (`CI=true`; raised from 30 s by owner ruling 2026-11-14 after a 36,010 ms hosted run) fails the smoke (`scripts/ready-budget.ps1`, called by `scripts/smoke.ps1`; `-MaxReadyMs` overrides, a negative value skips). Older builds without the field are not checked, but a plain smoke run passes `-Require`, so a current build that omits it fails. [performance.md](performance.md#smoke-ready-time-budget) | Decided; built (4.4b) | | D103 | Save for an older TomeStack: previous minor only (row 4.5)? | **Decided (owner ruling R4, 2026-11-11; 2026-11-13 rulings):** "Save for an older TomeStack" offers only the previous minor, 0.8.0 from 0.9.0. A build never lists its own minor, so a 0.8.1 build lists none until the 0.9.0 row is added. The 0.7.0, 0.6.0 and 0.5.0 rows stay in the release ladder for re-pin and "opens in", and their lowering steps stay in `RulesCore`; their goldens and outcomes are deleted. The picker says "Only the version before this one is listed. To open the file in an older TomeStack, update that TomeStack first." The real-build proof is the previous minor's: `for-0.8.0/` opened by the real v0.8.0 build (`outcomes/0.8.0.json`, 5 pass), run by the weekly job. [package-format.md](features/package-format.md#save-for-an-older-tomestack-d85) | Decided; built (4.5) | | D104 | Content revisions insert-only in the database? | **Decided (owner rulings, 2026-11-17, Wave 4 item 4.7):** database migration 13 makes `content_revisions` insert-only in the database. A BEFORE UPDATE and a BEFORE DELETE trigger on every row (drafts too) abort with "content revisions are insert-only". There is no runtime exception: the ADR-003 v2 rewrite, the one sanctioned rewrite of published revisions, always runs at migration 2, before 13. A future rewrite migration must drop and re-create the triggers inside its own migration. **Pre-upgrade copies** are named `tomestack.db.v-.bak` (UTC), for example `tomestack.db.v12-20261117T090503Z.bak`. The newest 3 are kept across versions; older `tomestack.db.v.bak` copies count and are removed first. App-version copies `tomestack.db.app-*.bak` are unchanged. The migration is forward-only: older builds (0.8.x and earlier) refuse a database-13 folder, and restoring the copy is the way back. | Decided; built (Wave 4 4.7) | +| D105 | A static session sheet for a phone or tablet? | **Decided (owner rulings, 2026-11-18, Wave 4 item 4.8):** a new export target `html-sheet` writes one HTML file (`.tomestack-sheet.html`, adapter 1.0.0) with no script and no external resource. A tag-level self-check (`HtmlSheet.Validate`) refuses scripts, event attributes, `src`, links that are not `#`, `style` attributes, embedding tags, `@import` and `url(`; a Content-Security-Policy meta tag is only a backstop, because many phone viewers ignore it. Every text is HTML-encoded, and the local-path and user-name scan covers the HTML, the sheet JSON and the raw note text. Pools, spell slots, death saves and hit dice are native checkboxes: ticks are not saved, and reopening the file starts from the export. Death saves are pre-ticked from play state. Session notes are included only in a personal copy; a share copy leaves them out and is preflighted as for the other targets. The trigger is the export panel only (More, Export). The sheet export model v1 is unchanged. | Decided; built (Wave 4 4.8) | ## Change history +- **2026-11-18 · Static session sheet (D105, Wave 4 row 4.8):** a new export target, `html-sheet`, writes one script-free HTML page of the sheet for a phone or tablet: no network, no links, a Content-Security-Policy that allows only its one hashed style, and plain tick boxes that are not saved. A personal copy may include session notes; a share copy never does. It only reads the sheet export model v1. Details in `docs/features/static-session-sheet.md`. No character, package format, database or dependency change. - **2026-11-17 · Wave 4 item 4.7: database migration v13 (D104):** `content_revisions` is insert-only in the database (BEFORE UPDATE and BEFORE DELETE triggers on every row, drafts too). The pre-upgrade copies are named `tomestack.db.v-.bak` and the newest 3 are kept. Older builds refuse the database-13 folder. No character, content or package format change. - **2026-11-14 · Smoke ready-time budget in CI 45 s (D102):** the CI budget goes from 30 s to 45 s (owner ruling 2026-11-14); main 43600fc5 failed only on a 36,010 ms ready time and the next run passed. The local budget stays 15 s. `scripts/ready-budget.ps1`. No character, package format, database or dependency change. - **2026-11-13 · Save for an older TomeStack: previous minor only (D103, Wave 4 row 4.5):** the save offers only the previous minor, 0.8.0 from 0.9.0 (owner ruling R4). The 0.7.0, 0.6.0 and 0.5.0 rows stay in the ladder for re-pin and "opens in"; their lowering steps stay in `RulesCore`, and their goldens and outcomes are deleted. The real-build proof is v0.8.0 (`outcomes/0.8.0.json`, 5 pass). No character, package format, database or dependency change. diff --git a/docs/features/export-adapters.md b/docs/features/export-adapters.md index 1497f57f..529880f8 100644 --- a/docs/features/export-adapters.md +++ b/docs/features/export-adapters.md @@ -10,6 +10,7 @@ BACKLOG B20 · ROADMAP M6 slice 4 · [ADR-012](../decisions/ADR-012-export-adapt | --- | --- | --- | --- | | Foundry VTT, dnd5e system (`foundry-dnd5e`) | `.foundry-dnd5e.json`: one Actor document for "Import Data" on an actor | 1.0.0 | **Foundry core 14.367 with dnd5e 6.0.6** (the pinned pair; dnd5e 6.0.6, released 2026-10-06, declares compatibility minimum 14.367, verified 14) | | TomeStack sheet (`sheet-json`) | `.tomestack-sheet.json`: the sheet export model v1 itself | 1.0.0 | `docs/schemas/sheet-export.v1.schema.json` | +| Static session sheet (`html-sheet`) | `.tomestack-sheet.html`: one script-free HTML page for a phone or tablet ([static-session-sheet.md](static-session-sheet.md)) | 1.0.0 | Its own tag-level check and golden file | | Roll20 | none | none | **Deferred** (owner decision D14): no documented, supported import file for its official 5e sheets. The neutral JSON is what any tool can read | **How the pin was verified (2026-09-29; moved to 6.0.6 on 2026-11-11).** The dnd5e data models at tag `release-6.0.6` of `github.com/foundryvtt/dnd5e`: `module/data/actor/character.mjs`, `templates/common.mjs`, `creature.mjs` and `attributes.mjs`; the item models `class.mjs`, `subclass.mjs`, `feat.mjs`, `spell.mjs` and `weapon.mjs`; `templates/item-description.mjs` and `activities.mjs`; `shared/damage-field.mjs` and `uses-field.mjs`; and `system.json` for the compatibility pair. They were read in full on 2026-09-29 for the previous pin; for `release-6.0.6` the two tags were diffed instead, and the only change in these files is a private migration path for skill and tool check bonuses in `templates/common.mjs`, which the adapter never writes. Each data model has a `_migrateData` step that Foundry runs when it builds a document from its source, and `system.json` names 6.0.0 as `needsMigrationVersion`: a document stamped with an older system version is migrated on load, so one pin stays importable while the system keeps those migrations. The file is stamped `_stats.systemVersion` 6.0.6 and `coreVersion` 14.367. The weekly workflow (`.github/workflows/weekly.yml`, `scripts/foundry-pin.mjs`) compares these files and the compatibility block with the latest dnd5e release and opens or updates one "Foundry dnd5e pin drift" issue when they differ; `FoundryPinDocTests` keeps this page's versions equal to the constants in `FoundryDnd5e.cs`. diff --git a/docs/features/static-session-sheet.md b/docs/features/static-session-sheet.md new file mode 100644 index 00000000..54f09487 --- /dev/null +++ b/docs/features/static-session-sheet.md @@ -0,0 +1,46 @@ +# Static session sheet (D105) + +Wave 4 item 4.8 · decision [D105](../LIVING_SPECS.md) · status: **built; the owner's check on a real phone is not recorded yet.** + +A sheet for the table when you would rather not carry a laptop. It is one HTML file you send to a phone or tablet and open in the browser. It needs no internet, no app and no TomeStack. It is a second target of the export adapters ([export-adapters.md](export-adapters.md)); the printable sheet (Print… on the character sheet) stays the full backup. + +## Making one + +1. Open a character, then **More**, **Export**. +2. Under "Export to another tool or device", choose **Sheet for a phone or tablet (HTML page, no internet needed)**. +3. Choose the purpose, as for the other formats: + - **Share** keeps only totals from content that may not be shared, and leaves out your session notes. + - **Personal copy** includes your own homebrew and your session notes, and is labelled "Do not share it". +4. Read the preview and save. The Save dialog offers "HTML page". The file is named `.tomestack-sheet.html`. + +A share copy goes through the same preflight as the other exports. The preview adds two warnings: "Includes N session notes." (personal copy) and "Ticks on the phone are not saved: reopening the file starts from this export." + +## What is in the file + +A header (name, classes, level, rules family, export date and the purpose label); Armor Class, initiative and proficiency bonus; hit points printed, with two empty write-in fields; abilities and saves; skills; conditions and exhaustion; death saves (pre-ticked from the play state); weapon attacks; spellcasting, with slots as checkboxes and each spell in a collapsible block; resources (up to 20 uses as checkboxes, more as a write-in field, and "no fixed maximum" as text); hit dice; toggles as read-only text; class columns; features in collapsible blocks; session notes (personal copy only); and the sources, licence notices and what was left out. + +It follows the phone's light or dark setting. Printing it shows summaries only. + +## What it does not do + +- **Ticks are not saved.** They are plain checkboxes. Close the page or reload it and everything goes back to the export. Nothing writes back to TomeStack. +- **No script, no network.** The page loads nothing from anywhere and has no links at all. +- It does not recalculate. Change the character in TomeStack and export again. +- The sheet export model v1 is unchanged; this target only reads it. + +## Safety rules + +1. **Every text is HTML-encoded**, including homebrew names and descriptions and your notes. +2. **A tag-level self-check** (`HtmlSheet.Validate`, a small hand-written tokenizer) runs on the finished page before anything is written. It refuses scripts, event attributes, `src`, any link that is not `#...`, `style` attributes, embedding tags (frames, objects and the like), `@import` and `url(`. A failure is `export.invalid-output`, as for the other adapters. +3. **A Content-Security-Policy meta tag** blocks everything except the page's own style block (matched by hash). It is a backstop only: many phone viewers ignore it, so the self-check is the real guard. +4. **The privacy scan** that every export gets (data folder, profile, linked PDFs, the Windows user name as a path segment) covers the HTML, the sheet JSON it came from and the raw note text. + +## Tests + +- `tests/AppService.Tests/HtmlSheetTests.cs`: the content of each section, encoding of hostile text, and the self-check refusing each forbidden construct. +- `tests/AppService.Tests/ExportAdapterTests.cs`: the golden file `Golden/multiclass-caster.tomestack-sheet.html` (open it in any browser to see the result), notes only in a personal copy, and a local path refused. +- `tests/AppService.Tests/HostServicesTests.cs`: the Save dialog filter ("HTML page", `.html`). +- `src/Ui/src/components/VttExportPanel.test.tsx`: the choice in the export panel. +- `src/Ui/a11y/static-sheet.a11y.tsx`: axe in Edge, light and dark. + +**Not verified:** opening the file on a real phone or tablet, and a Narrator or screen-reader pass. 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..c624d3cb 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 @@ -88,13 +88,16 @@ public VttExportPreview PreviewVttExport(Guid characterId, string target, SheetP { if (!ExportTargets.Contains(target)) throw new AppValidationException([new("export.target-unknown", $"'{(target?.Length > 40 ? target[..40] : target)}' is not an export target this TomeStack has ({string.Join(", ", ExportTargets)}).")]); - var sheet = SheetExportFor(characterId, purpose); + var character = LoadCharacter(characterId); + var sheet = SheetExportFor(character, purpose); string text; string fileName; string adapterVersion; string? targetVersion; IReadOnlyList differences = []; var baseName = SafeName(sheet.Character.Name); + var htmlNotes = 0; + string? rawNotes = null; if (target == FoundryDnd5e.Target) { var actor = FoundryDnd5e.Map(sheet); @@ -105,6 +108,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) + { + 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.")]); + fileName = baseName + HtmlSheet.FileSuffix; + (adapterVersion, targetVersion) = (HtmlSheet.AdapterVersion, "HTML page, no script"); + } else { var node = SheetJson.Map(sheet); @@ -117,7 +131,10 @@ 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 }; + // 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); @@ -129,6 +146,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/src/AppService/Exports/HtmlSheet.cs b/src/AppService/Exports/HtmlSheet.cs new file mode 100644 index 00000000..5addc8b3 --- /dev/null +++ b/src/AppService/Exports/HtmlSheet.cs @@ -0,0 +1,537 @@ +using System.Globalization; +using System.Net; +using System.Security.Cryptography; +using System.Text; +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 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. 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) + { + ArgumentNullException.ThrowIfNull(html); + var reasons = new List(); + void Add(string reason) + { + if (!reasons.Contains(reason)) + reasons.Add(reason); + } + + const string doctype = ""; + var n = html.Length; + var i = 0; + while (true) + { + var lt = html.IndexOf('<', i); + if (lt < 0) + break; + i = lt + 1; + if (html.AsSpan(lt).StartsWith(doctype, StringComparison.OrdinalIgnoreCase)) + { + i = lt + doctype.Length; + continue; + } + if (i >= n || !(IsLetter(html[i]) || (html[i] == '/' && i + 1 < n && IsLetter(html[i + 1])))) + { + 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 closed = false; + while (i < n) + { + 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 (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(" c is (>= 'a' and <= 'z') or (>= 'A' and <= 'Z'); + + 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 ?? ""); + + 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) + { + spent = Math.Max(0, 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/src/AppService/Extensions/ExtensionService.cs b/src/AppService/Extensions/ExtensionService.cs index 41eb6d4d..f96cbe37 100644 --- a/src/AppService/Extensions/ExtensionService.cs +++ b/src/AppService/Extensions/ExtensionService.cs @@ -535,10 +535,16 @@ private static void KeepFew(ConcurrentDictionary pending) } /// The sheet export model v1 of a character (ADR-011, ADR-007 item 11), for extensions and adapters. - internal SheetExport SheetExportFor(Guid characterId, SheetPurpose purpose) - { - var character = _store.FindCharacter(characterId) + internal SheetExport SheetExportFor(Guid characterId, SheetPurpose purpose) => SheetExportFor(LoadCharacter(characterId), purpose); + + /// The character as stored, or character.not-found. + internal Character LoadCharacter(Guid characterId) => + _store.FindCharacter(characterId) ?? throw new AppValidationException([new("character.not-found", $"Character {characterId} does not exist.")]); + + /// The same export for a character already read, so one request reads the character once. + internal SheetExport SheetExportFor(Character character, SheetPurpose purpose) + { var sheet = CharacterCalculator.Calculate(character, _store); return SheetExportBuilder.Build(character, sheet, _store, purpose, _bundledSources, _time.GetUtcNow()); } diff --git a/src/Ui/a11y/static-sheet.a11y.tsx b/src/Ui/a11y/static-sheet.a11y.tsx new file mode 100644 index 00000000..044ee2a1 --- /dev/null +++ b/src/Ui/a11y/static-sheet.a11y.tsx @@ -0,0 +1,67 @@ +// 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 + + +
+

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/HtmlSheetTests.cs b/tests/AppService.Tests/HtmlSheetTests.cs new file mode 100644 index 00000000..8d15c2f3 --- /dev/null +++ b/tests/AppService.Tests/HtmlSheetTests.cs @@ -0,0 +1,255 @@ +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"), t("srd-5.2.1"), 3, [new SheetClass(t("Wayfarer"), 3, 8, t("Lantern Path"), Ref, t("Homebrew"), Ref)]), + [new SheetAbility(t("str"), 10, 0, 0, SheetProficiency.None), new SheetAbility(t("dex"), 16, 3, 5, SheetProficiency.Proficient)], + [new SheetSkill("stealth", t("Stealth"), t("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"), t("int"), 5, 13, 3, "prepared", "spellSlots", + [new SheetSpell(t("Lantern Spark"), 1, true, t("evocation"), t("1 action"), t("60 feet"), t("V, S"), t("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, t("1d6+3"), t("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("\" 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))); + } + + [Fact] + 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] + 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, "Resources", StringComparison.Ordinal); + return html[at..html.IndexOf("", at, StringComparison.Ordinal)]; + } + + var unbounded = Resources(null); + Assert.Contains("Spent 0", unbounded, StringComparison.Ordinal); + Assert.DoesNotContain("-1", unbounded, StringComparison.Ordinal); + var big = Resources(21); + Assert.Contains("Spent 0 of 21", big, StringComparison.Ordinal); + Assert.DoesNotContain("-1", big, StringComparison.Ordinal); + } + + [Fact] + public void Long_texts_sit_in_details() + { + var html = HtmlSheet.Render(Sample(), Extras()); + + Assert.Matches(new Regex("
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.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")))); + } +} 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 @@ +