Web panel: URL, window and profile policies with offline tests

Pure C# policies (allowlist/redaction, visibility/layout, profile folder) plus tools/WebPanelTests (107 assertions).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Daniel Wallace 2026-11-07 14:17:22 -08:00
commit 0b0d2cb072
5 changed files with 468 additions and 0 deletions

View file

@ -0,0 +1,42 @@
using System.Security.Cryptography;
using System.Text;
namespace RynthCore.Engine.WebPanel;
/// <summary>Pure per-world, per-profile-key WebView2 user data folder naming. No file access.</summary>
internal static class WebPanelProfile
{
/// <summary>
/// &lt;localAppData&gt;\RynthCore\WebPanel\&lt;world&gt;\&lt;hex&gt;. World: [A-Za-z0-9 _-] kept, others
/// '_', trimmed, max 64, empty -> "_default". Hex: first 16 bytes of
/// SHA-256(UTF-8(key.Trim().ToLowerInvariant())) as lowercase hex; empty key -> "default".
/// </summary>
public static string Folder(string localAppData, string? worldName, string? profileKey)
{
return Path.Combine(localAppData, "RynthCore", "WebPanel", SanitizeWorld(worldName), KeyHex(profileKey));
}
private static string SanitizeWorld(string? world)
{
if (string.IsNullOrWhiteSpace(world)) return "_default";
var sb = new StringBuilder();
foreach (char c in world.Trim())
{
bool keep = (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || (c >= '0' && c <= '9')
|| c == ' ' || c == '_' || c == '-';
sb.Append(keep ? c : '_');
}
string s = sb.ToString();
if (s.Length > 64) s = s.Substring(0, 64);
s = s.Trim(); // a trailing space is not a valid Windows folder name
return s.Length == 0 ? "_default" : s;
}
private static string KeyHex(string? key)
{
string k = (key ?? "").Trim().ToLowerInvariant();
if (k.Length == 0) return "default";
byte[] hash = SHA256.HashData(Encoding.UTF8.GetBytes(k));
return Convert.ToHexString(hash, 0, 16).ToLowerInvariant();
}
}

View file

@ -0,0 +1,119 @@
using System.Text;
namespace RynthCore.Engine.WebPanel;
/// <summary>
/// Pure URL rules for the web panel: the navigation allowlist, the "safe to hand to the system
/// browser" test, and log redaction. No Win32, no WebView2.
/// </summary>
internal static class WebPanelUrlPolicy
{
public const int MaxEntries = 16, MaxEntryLength = 253, MaxUrlBytes = 4096;
/// <summary>
/// Parses a '\n'-separated allowlist (blank lines ignored, '\r' tolerated). An entry is
/// "host" (exact) or "*.suffix" (any subdomain depth, not the suffix itself; the suffix must
/// contain a dot). No scheme, path, port or other '*'. False on 0 or more than 16 entries or
/// any bad entry.
/// </summary>
public static bool TryParseAllowlist(string? text, out string[] entries)
{
entries = Array.Empty<string>();
if (string.IsNullOrWhiteSpace(text)) return false;
var list = new List<string>();
foreach (string raw in text.Split('\n'))
{
string e = raw.Trim().ToLowerInvariant();
if (e.Length == 0) continue;
if (list.Count >= MaxEntries) return false;
if (!IsValidEntry(e)) return false;
list.Add(e);
}
if (list.Count == 0) return false;
entries = list.ToArray();
return true;
}
private static bool IsValidEntry(string e)
{
if (e.Length > MaxEntryLength) return false;
string host = e;
if (e.StartsWith("*.", StringComparison.Ordinal))
{
host = e.Substring(2);
if (host.IndexOf('.') < 0) return false; // "*.com" would allow a whole TLD
}
return IsValidHostName(host);
}
private static bool IsValidHostName(string host)
{
if (host.Length == 0) return false;
foreach (string label in host.Split('.'))
{
if (label.Length == 0 || label.Length > 63) return false;
if (label[0] == '-' || label[^1] == '-') return false;
foreach (char c in label)
{
bool ok = (c >= 'a' && c <= 'z') || (c >= '0' && c <= '9') || c == '-';
if (!ok) return false;
}
}
return true;
}
/// <summary>
/// https only, no userinfo, default port; host compared via Uri.IdnHost, case-insensitive,
/// one trailing dot stripped. "about:blank" is allowed.
/// </summary>
public static bool IsAllowed(string? url, IReadOnlyList<string> entries)
{
if (string.IsNullOrEmpty(url)) return false;
if (Encoding.UTF8.GetByteCount(url) > MaxUrlBytes) return false;
if (string.Equals(url, "about:blank", StringComparison.OrdinalIgnoreCase)) return true;
if (!Uri.TryCreate(url, UriKind.Absolute, out Uri? uri)) return false;
if (uri.Scheme != Uri.UriSchemeHttps) return false;
if (uri.UserInfo.Length != 0) return false;
if (!uri.IsDefaultPort) return false;
string host = uri.IdnHost.ToLowerInvariant();
if (host.EndsWith('.')) host = host.Substring(0, host.Length - 1);
if (host.Length == 0) return false;
foreach (string entry in entries)
{
if (entry.StartsWith("*.", StringComparison.Ordinal))
{
string suffix = entry.Substring(1); // ".example.com"
if (host.Length > suffix.Length && host.EndsWith(suffix, StringComparison.Ordinal)) return true;
}
else if (host == entry)
{
return true;
}
}
return false;
}
/// <summary>Absolute http/https without userinfo: the only URLs that may reach ShellExecute.</summary>
public static bool IsBrowserSafe(string? url)
{
if (string.IsNullOrWhiteSpace(url)) return false;
if (!Uri.TryCreate(url, UriKind.Absolute, out Uri? uri)) return false;
if (uri.Scheme != Uri.UriSchemeHttp && uri.Scheme != Uri.UriSchemeHttps) return false;
if (uri.UserInfo.Length != 0) return false;
return uri.Host.Length != 0;
}
/// <summary>"scheme://host[:port]/path" with no userinfo, query or fragment; "&lt;invalid url&gt;" if unparseable.</summary>
public static string Redact(string? url)
{
const string Invalid = "<invalid url>";
if (string.IsNullOrEmpty(url)) return Invalid;
if (!Uri.TryCreate(url, UriKind.Absolute, out Uri? uri)) return Invalid;
if (uri.Host.Length == 0) return Invalid;
string port = uri.IsDefaultPort ? "" : ":" + uri.Port;
return uri.Scheme + "://" + uri.Host + port + uri.AbsolutePath;
}
}

View file

@ -0,0 +1,67 @@
namespace RynthCore.Engine.WebPanel;
internal readonly record struct PanelRect(int Left, int Top, int Right, int Bottom)
{
public int Width => Right - Left;
public int Height => Bottom - Top;
}
/// <summary>Panel placement as fractions (0..1) of the game client rect.</summary>
internal readonly record struct PanelFractions(double X, double Y, double W, double H);
/// <summary>Pure visibility and layout rules for the web panel window. No Win32.</summary>
internal static class WebPanelWindowPolicy
{
public const int DefaultPercent = 88, MinPercent = 30, MaxPercent = 100, MinWidthPx = 480, MinHeightPx = 320;
/// <summary>
/// false when closed, the game is gone, iconic or invisible; null (keep current) when the
/// foreground window is null mid alt-tab, so the panel never flickers; otherwise true only
/// when the foreground window belongs to the game process.
/// </summary>
public static bool? Visible(bool open, bool gameAlive, bool gameIconic, bool gameVisible,
bool foregroundNull, uint foregroundPid, uint ourPid)
{
if (!open || !gameAlive || gameIconic || !gameVisible) return false;
if (foregroundNull) return null;
return foregroundPid == ourPid;
}
/// <summary>Centered fractions for a size in percent of the client; 0 means the default (88).</summary>
public static PanelFractions Default(int widthPercent, int heightPercent)
{
double w = Pct(widthPercent) / 100.0;
double h = Pct(heightPercent) / 100.0;
return new PanelFractions((1 - w) / 2, (1 - h) / 2, w, h);
}
private static int Pct(int p) => p == 0 ? DefaultPercent : Math.Clamp(p, MinPercent, MaxPercent);
/// <summary>Screen rect for the fractions: at least 480x320 (or the whole client if smaller), never outside the client.</summary>
public static PanelRect Place(PanelRect gameClientScreen, PanelFractions f)
{
int cw = Math.Max(0, gameClientScreen.Width);
int ch = Math.Max(0, gameClientScreen.Height);
int w = Math.Clamp((int)Math.Round(Clamp01(f.W) * cw), Math.Min(MinWidthPx, cw), cw);
int h = Math.Clamp((int)Math.Round(Clamp01(f.H) * ch), Math.Min(MinHeightPx, ch), ch);
int x = Math.Clamp((int)Math.Round(Clamp01(f.X) * cw), 0, cw - w);
int y = Math.Clamp((int)Math.Round(Clamp01(f.Y) * ch), 0, ch - h);
int left = gameClientScreen.Left + x;
int top = gameClientScreen.Top + y;
return new PanelRect(left, top, left + w, top + h);
}
/// <summary>Fractions of the client for a panel rect the user dragged or resized, clamped to 0..1.</summary>
public static PanelFractions FromUserRect(PanelRect gameClientScreen, PanelRect panelScreen)
{
int cw = gameClientScreen.Width, ch = gameClientScreen.Height;
if (cw <= 0 || ch <= 0) return Default(0, 0);
double w = Clamp01((double)panelScreen.Width / cw);
double h = Clamp01((double)panelScreen.Height / ch);
double x = Math.Clamp((double)(panelScreen.Left - gameClientScreen.Left) / cw, 0, 1 - w);
double y = Math.Clamp((double)(panelScreen.Top - gameClientScreen.Top) / ch, 0, 1 - h);
return new PanelFractions(x, y, w, h);
}
private static double Clamp01(double v) => double.IsNaN(v) ? 0 : Math.Clamp(v, 0, 1);
}