using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Xml.Linq; using RynthCore.Plugin.RynthDreamWeave; using RynthCore.Plugin.ServerPack; using RynthCore.RynthAiTests.Harness; namespace RynthServerPack.Tests; // DreamWeave's web buttons, the pure part: the destinations and the "/weblogin" reply's wire text. internal static class DreamWeaveWebTests { public static void Register(Runner r) { r.Add("dreamweave web: a player's copy of the launch line is never taken", PlayerCopy); r.Add("dreamweave web: the launch URL is built from constants and a clean code", UrlFromConstants); r.Add("dreamweave web: destination ids are verbs no one else uses", IdsAreFree); r.Add("dreamweave web: LaunchWire: code alphabet is strict", Alphabet); r.Add("dreamweave web: ACE's refusals parse as refusals, other lines are ignored", Refusals); r.Add("dreamweave web: replies count only while asked, once", RepliesOnlyWhileAsked); r.Add("dreamweave web: one request at a time, never stuck", OneAtATime); r.Add("dreamweave web: the code never reaches a status or message", CodeNeverInStatus); r.Add("dreamweave web: a code-shaped refusal is replaced, never shown", CodeShapedRefusal); r.Add("dreamweave web: an expired request frees itself", SelfExpiry); r.Add("dreamweave web: reset keeps the throttle", ResetKeepsThrottle); r.Add("dreamweave web: a late code is eaten while it could still be valid", LateCodeIsStale); r.Add("dreamweave web: overlapping requests never leak a code to chat", OverlappingRequests); r.Add("dreamweave web: profile keys separate accounts", ProfileKeys); r.Add("dreamweave web: ImGui only in WebButtons, no context switching, no host calls from draw", ThreadRules); r.Add("dreamweave web: the plugin's shared hooks hand off to the web tools first", HooksHandOff); } // -- Host wiring (source scan: the plugin is NativeAOT, so its host code can't run here) -- private static string PluginsRoot() { string? dir = AppContext.BaseDirectory; while (dir != null && !Directory.Exists(Path.Combine(dir, "Plugins", "Shared", "ServerPack"))) dir = Path.GetDirectoryName(dir); if (dir == null) throw new DirectoryNotFoundException("Plugins not found above " + AppContext.BaseDirectory); return Path.Combine(dir, "Plugins"); } private static IEnumerable SourceFiles(string root) => Directory.GetFiles(root, "*.cs", SearchOption.AllDirectories) .Where(p => !p.Contains(Path.DirectorySeparatorChar + "bin" + Path.DirectorySeparatorChar, StringComparison.OrdinalIgnoreCase) && !p.Contains(Path.DirectorySeparatorChar + "obj" + Path.DirectorySeparatorChar, StringComparison.OrdinalIgnoreCase)); /// /// The website feature's own files, the ones its rules hold to: DreamWeaveWeb*.cs, Web*.cs and LaunchWire.cs. /// The plugin's other features (the Skills and Character panels, the Bank page) draw with ImGui themselves. /// private static List WebFiles(string dw) { var files = SourceFiles(dw).Where(p => { string n = Path.GetFileName(p); return n.StartsWith("DreamWeaveWeb", StringComparison.Ordinal) || n.StartsWith("Web", StringComparison.Ordinal) || n == "LaunchWire.cs"; }).ToList(); Check.True(files.Count >= 6, "the website feature's files are found (" + files.Count + ")"); return files; } /// The text with // comments removed (a "//" right after ':' is a URL, kept), so a rule named in a comment doesn't count. private static string StripComments(string text) { var sb = new System.Text.StringBuilder(text.Length); foreach (string line in text.Split('\n')) { int at = 0, cut = -1; while ((at = line.IndexOf("//", at, StringComparison.Ordinal)) >= 0) { if (at == 0 || line[at - 1] != ':') { cut = at; break; } at += 2; } sb.Append(cut >= 0 ? line.Substring(0, cut) : line).Append('\n'); } return sb.ToString(); } /// The statement after each : a balanced { } block, or up to the next ';'. private static List StatementsAfter(string code, string head) { var found = new List(); int at = 0; while ((at = code.IndexOf(head, at, StringComparison.Ordinal)) >= 0) { int i = at + head.Length; while (i < code.Length && char.IsWhiteSpace(code[i])) i++; if (i < code.Length && code[i] == '{') { int depth = 0, j = i; for (; j < code.Length; j++) { if (code[j] == '{') depth++; else if (code[j] == '}' && --depth == 0) break; } found.Add(code.Substring(i, Math.Min(j + 1, code.Length) - i)); } else { int semi = code.IndexOf(';', i); found.Add(code.Substring(i, (semi < 0 ? code.Length : semi + 1) - i)); } at = i; } return found; } /// The token as a call or member access of its own: "ChatLine(" matches, "OnChatLine(" does not. private static bool Mentions(string code, string token) => System.Text.RegularExpressions.Regex.IsMatch(code, @"(?= 0) { n++; at += needle.Length; } return n; } // DreamWeavePlugin.cs and DreamWeaveSkills.cs own the hooks the web tools share with the bank and the Skills // panel: each hands off to its Web* method before its own code, so no gate of theirs comes first. private static void HooksHandOff() { string dw = Path.Combine(PluginsRoot(), "RynthCore.Plugin.RynthDreamWeave"); string plugin = StripComments(File.ReadAllText(Path.Combine(dw, "DreamWeavePlugin.cs"))); string skills = StripComments(File.ReadAllText(Path.Combine(dw, "DreamWeaveSkills.cs"))); (string Code, string Head, string Call)[] hooks = { (plugin, "partial void ServerLoginComplete()", "WebLoginComplete();"), (plugin, "partial void ServerLogout()", "WebLogout();"), (plugin, "partial void ServerShutdown()", "WebShutdown();"), (plugin, "partial void ServerChatText(string text, int chatType, ref bool eat)", "WebChatText(text, chatType, ref eat);"), (plugin, "partial void ServerTick(bool active)", "WebTick();"), (skills, "partial void ServerChatCommand(string[] parts, ref bool handled)", "WebChatCommand(parts, ref handled);"), (skills, "partial void ServerCommandVerbs(List verbs)", null!), }; foreach (var (code, head, call) in hooks) { List body = StatementsAfter(code, head); Check.Eq(body.Count, 1, head + ": implemented once"); if (body.Count != 1 || call == null) continue; Check.True(body[0].TrimStart('{', ' ', '\n', '\r').StartsWith(call, StringComparison.Ordinal), head + ": " + call + " comes first"); } List verbs = StatementsAfter(skills, "partial void ServerCommandVerbs(List verbs)"); Check.True(verbs.Count == 1 && verbs[0].Contains("WebCommandVerbs(verbs);", StringComparison.Ordinal), "ServerCommandVerbs adds the web verbs"); List info = StatementsAfter(plugin, "partial void ServerInfoLines(Action line)"); Check.True(info.Count == 1 && info[0].Contains("WebInfoLines(line);", StringComparison.Ordinal), "ServerInfoLines adds the web tools' line"); // The web tools implement none of the hooks they are handed: one implementation each, in the hub files. string web = StripComments(File.ReadAllText(Path.Combine(dw, "DreamWeaveWebTools.cs"))); foreach (string hook in new[] { "ServerLoginComplete", "ServerLogout", "ServerShutdown", "ServerChatText", "ServerTick", "ServerChatCommand", "ServerCommandVerbs", "ServerInfoLines" }) Check.False(web.Contains("partial void " + hook + "(", StringComparison.Ordinal), "DreamWeaveWebTools.cs leaves " + hook + " to the hub"); } private static void ThreadRules() { string plugins = PluginsRoot(); string dw = Path.Combine(plugins, "RynthCore.Plugin.RynthDreamWeave"); string buttonsPath = Path.Combine(dw, "DreamWeave", "WebButtons.cs"); string hostPath = Path.Combine(dw, "DreamWeaveWebTools.cs"); Check.True(File.Exists(buttonsPath), "DreamWeave\\WebButtons.cs exists"); Check.True(File.Exists(hostPath), "DreamWeaveWebTools.cs exists"); if (!File.Exists(buttonsPath) || !File.Exists(hostPath)) return; var bareImGui = new System.Text.RegularExpressions.Regex(@"(? drawLocks = StatementsAfter(buttons, "lock (l.Gate)"); Check.Eq(drawLocks.Count, 1, "WebButtons.cs: one lock, to copy Pending and Status out"); foreach (string s in drawLocks) Check.False(bareImGui.IsMatch(s) || s.Contains("SafeImGui", StringComparison.Ordinal) || s.Contains("click(", StringComparison.Ordinal), "WebButtons.cs: nothing is drawn or clicked under the lock"); string host = StripComments(File.ReadAllText(hostPath)); List cardHook = StatementsAfter(host, "partial void ServerCardActions()"); Check.Eq(cardHook.Count, 1, "DreamWeaveWebTools.cs implements ServerCardActions once"); string clickPath = cardHook.Count == 1 ? cardHook[0] : ""; Check.True(clickPath.Contains("WebButtons.Draw(", StringComparison.Ordinal), "the card hook draws through WebButtons.Draw"); Check.True(host.Contains("RunOnTick(() => StartLaunch(d))", StringComparison.Ordinal), "the button path queues StartLaunch with RunOnTick"); Check.False(clickPath.Contains("StartLaunch(d)", StringComparison.Ordinal) && !clickPath.Contains("RunOnTick(", StringComparison.Ordinal), "the card hook never calls StartLaunch directly"); // Every lock on the launcher holds launcher calls only: no send, open, reply or log under it. List hostLocks = StatementsAfter(host, "lock (_web.Gate)"); Check.True(hostLocks.Count >= 5, "the host takes the launcher's lock (" + hostLocks.Count + " places)"); foreach (string s in hostLocks) foreach (string banned in new[] { "Send(", "OpenWeb(", "Reply.", "ChatLine(", "ChatFail(", "LogTagged(", "Host.", "ShellExecute", "CloseWeb(" }) Check.False(Mentions(s, banned), "no " + banned + " under lock (_web.Gate): " + s.Trim().Replace('\n', ' ')); Check.False(host.Contains("DateTime", StringComparison.Ordinal) || host.Contains("Stopwatch", StringComparison.Ordinal), "nowMs comes from Environment.TickCount64 only"); Check.True(host.Contains("Environment.TickCount64", StringComparison.Ordinal), "the host uses Environment.TickCount64"); // The code goes into the launch URL and nowhere else. int uses = System.Text.RegularExpressions.Regex.Matches(host, @"\blaunchCode\b").Count; Check.Eq(uses, 3, "launchCode: declared, filled by OnChatLine, used once (DreamWeaveWeb.LaunchUrl)"); Check.Eq(CountOf(host, "out launchCode"), 1, "launchCode is filled only by OnChatLine"); Check.True(host.Contains("DreamWeaveWeb.LaunchUrl(launchCode, ", StringComparison.Ordinal), "the code's one use is the launch URL"); // Stale eats the line and does nothing else. int stale = host.IndexOf("case LaunchLine.Stale:", StringComparison.Ordinal); Check.True(stale >= 0, "the chat hook handles LaunchLine.Stale"); if (stale >= 0) { int end = host.IndexOf("return;", stale, StringComparison.Ordinal); string arm = end < 0 ? "" : host.Substring(stale, end - stale); Check.True(arm.Contains("eat = true;", StringComparison.Ordinal), "Stale eats the line"); foreach (string banned in new[] { "Reply.", "ChatLine(", "ChatFail(", "LogTagged(", "OpenWeb(", "Cancel(", "Host." }) Check.False(Mentions(arm, banned), "Stale does nothing else: no " + banned); } } private const string Code = "AbCdEfGhIjKlMnOpQrStUvWxYz0123456789-_AbCde"; // 43 chars private const string Line = "[WEB] Launch code: " + Code + " (single use, expires in 60 seconds)"; private static bool Parse(string? text, int type, out string code, out string refusal) => LaunchWire.TryParse(text, type, out code, out refusal); private static void PlayerCopy() { Check.Eq(Code.Length, LaunchWire.CodeLength, "fixture code is 43 chars"); foreach (int type in new[] { 0x02, 0x03, 0x08, 0x0C, 0x13 }) Check.True(!Parse(Line, type, out _, out _), "player-authored chat type 0x" + type.ToString("X2") + " refused"); Check.True(!Parse("Bob tells you, " + Line, 0x05, out _, out _), "a tell wrapper with a system type refused"); Check.True(!Parse("hello " + Line, 0x05, out _, out _), "the lead mid-line refused"); Check.True(Parse(Line, 0x05, out string code, out string refusal), "valid line, system type"); Check.Eq(code, Code, "the code"); Check.Eq(refusal, "", "no refusal on success"); Check.True(Parse(Line, -1, out code, out _), "unknown type: the anchor alone protects"); Check.Eq(code, Code, "the code (type -1)"); Check.True(!Parse(null, 0x05, out _, out _), "null refused"); Check.True(!Parse("", 0x05, out _, out _), "empty refused"); } private static void UrlFromConstants() { string head = "[WEB] Launch code: "; Check.True(!Parse(head + Code.Substring(1) + " (single use)", 0x05, out _, out _), "42-char code refused"); Check.True(!Parse(head + Code + "A (single use)", 0x05, out _, out _), "44-char run (no space after 43) refused"); Check.True(!Parse(head + Code + "&to=//evil.com", 0x05, out _, out _), "code followed by &to= refused"); Check.True(!Parse(head + Code, 0x05, out _, out _), "no trailing space refused"); Check.True(!Parse(head + Code.Substring(0, 42) + "! (single use)", 0x05, out _, out _), "bad code char refused"); Check.True(!Parse(head + Code.Substring(0, 42) + "% (single use)", 0x05, out _, out _), "percent in code refused"); // None of the malformed success lines may leak out as a refusal either. Check.True(!Parse(head + Code.Substring(1) + " x", 0x05, out _, out string r1) && r1 == "", "malformed success is not a refusal"); WebDestination suit = DreamWeaveWeb.ById("suit")!; string url = DreamWeaveWeb.LaunchUrl(Code, suit); Check.True(url.StartsWith(DreamWeaveWeb.SiteBase + "/launch?code=", StringComparison.Ordinal), "url starts with the base"); Check.Eq(url, DreamWeaveWeb.SiteBase + "/launch?code=" + Code + "&to=%2Ftools%2Fsuit", "exact suit url"); Check.True(url.EndsWith("%2Ftools%2Fsuit", StringComparison.Ordinal), "ends with the escaped path"); Check.Eq(url.Split("&to=").Length - 1, 1, "exactly one &to="); foreach (WebDestination d in DreamWeaveWeb.Destinations) { string u = DreamWeaveWeb.LaunchUrl(Code, d); Check.True(ServerWebOpen.IsAllowedUrl(u, DreamWeaveWeb.AllowedHosts), d.Id + ": url passes the allowlist"); Check.True(d.Path.StartsWith("/", StringComparison.Ordinal) && !d.Path.StartsWith("//", StringComparison.Ordinal), d.Id + ": path is rooted, not //"); Check.True(d.Path.IndexOfAny(new[] { '?', '#', '\\' }) < 0, d.Id + ": no ? # or backslash in path"); Check.True(d.Label.Length > 0 && d.Tooltip.Length > 0, d.Id + ": label and tooltip"); } Check.True(DreamWeaveWeb.ById("SUIT") == suit, "ById is case-insensitive"); Check.True(DreamWeaveWeb.ById("nope") == null && DreamWeaveWeb.ById(null) == null && DreamWeaveWeb.ById("") == null, "unknown id -> null"); Check.Eq(LaunchWire.RequestFor(suit), "/weblogin", "request is /weblogin"); } private static void IdsAreFree() { var seen = new HashSet(); string[] serverIds = ServerPluginIds(); Check.True(serverIds.Length > 0, "found the server plugin ids"); foreach (WebDestination d in DreamWeaveWeb.Destinations) { Check.True(d.Id.Length >= 1 && d.Id.Length <= 16 && d.Id.All(c => c >= 'a' && c <= 'z'), d.Id + ": 1-16 chars [a-z]"); Check.True(Array.IndexOf(ServerPackCommands.SharedVerbs, d.Id) < 0, d.Id + ": not a shared verb"); Check.True(Array.IndexOf(serverIds, d.Id) < 0, d.Id + ": not a server plugin id"); Check.True(seen.Add(d.Id), d.Id + ": unique"); } } private static void Alphabet() { const string b64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"; Check.Eq(b64.Length, 64, "64 base64url chars"); foreach (char c in b64) Check.True(LaunchWire.IsCodeChar(c), "accepted: " + c); char[] bad = { '+', '/', '=', '&', '?', '#', '%', '.', ' ', '\t', '!', '~', '\u00e9', '\u0000' }; foreach (char c in bad) { string name = "U+" + ((int)c).ToString("X4"); Check.True(!LaunchWire.IsCodeChar(c), "IsCodeChar rejects " + name); foreach (int idx in new[] { 0, 21, 42 }) { char[] chars = Code.ToCharArray(); chars[idx] = c; string line = "[WEB] Launch code: " + new string(chars) + " (single use, expires in 60 seconds)"; Check.True(!Parse(line, 0x05, out string code, out string refusal), "refused: " + name + " at " + idx); Check.Eq(code, "", "no code: " + name + " at " + idx); Check.Eq(refusal, "", "no refusal: " + name + " at " + idx); } } // Round trip of a code holding both '-' and '_'. string dashed = "-_" + Code.Substring(2); Check.True(Parse("[WEB] Launch code: " + dashed + " (single use, expires in 60 seconds)", 0x05, out string got, out _), "dash/underscore code parses"); Check.Eq(got, dashed, "dash/underscore code intact"); Check.True(DreamWeaveWeb.LaunchUrl(got, DreamWeaveWeb.ById("market")!).Contains("code=" + dashed + "&to=", StringComparison.Ordinal), "url carries the code verbatim"); // The stem alone marks the success shape: malformed, it is dropped, never a refusal. foreach (string l in new[] { "[WEB] Launch code:" + Code, "[WEB] Launch code " + Code, "[WEB] Launch code", "[WEB] Launch codes " + Code }) { Check.True(!Parse(l, 0x05, out string c2, out string r2), "malformed success-shaped line dropped: " + l); Check.Eq(c2, "", "no code: " + l); Check.Eq(r2, "", "no refusal text: " + l); } } private static void Refusals() { string[] lines = { "[WEB] Signing in to the website from the game is turned off on this server.", "[WEB] The website sign-in service is not available right now.", "[WEB] You are requesting website sign-in codes too quickly. Wait a minute and try again.", }; foreach (string l in lines) { Check.True(Parse(l, 0x05, out string code, out string refusal), "refusal parses: " + l); Check.Eq(code, "", "no code in a refusal"); Check.Eq(refusal, l.Substring(LaunchWire.ReplyLead.Length), "refusal text after the lead"); Check.True(!Parse(l, 0x02, out _, out _), "a player's copy of a refusal is ignored"); } Check.True(!Parse("You say, \"hi\"", 0x05, out _, out _), "other chat ignored"); Check.True(!Parse("[WEBX] Launch code: " + Code, 0x05, out _, out _), "lookalike lead ignored"); } private static WebDestination Market => DreamWeaveWeb.ById("market")!; private static void RepliesOnlyWhileAsked() { var w = new WebLauncher(); Check.True(w.OnChatLine(Line, 0x05, 0, out _, out _, out _) == LaunchLine.NotOurs, "nothing pending: not ours"); Check.True(w.Begin(Market, 1000) == LaunchBegin.Started, "begin"); Check.Eq(w.Status, "Asking DreamWeave for a login code for Market...", "asking status"); var k = w.OnChatLine(Line, 0x05, 1000 + 9_999, out var dest, out string code, out string msg); Check.True(k == LaunchLine.Code, "line at +9,999 ms is the code"); Check.Eq(code, Code, "the code"); Check.Eq(msg, "", "no message on a code"); Check.True(ReferenceEquals(dest, Market), "destination handed back"); Check.True(w.Pending == null, "code clears pending"); Check.True(w.OnChatLine(Line, 0x05, 1000 + 9_999, out dest, out code, out msg) == LaunchLine.Stale, "an identical second line is stale: eaten, opens nothing"); Check.True(dest == null && code == "" && msg == "", "no outputs on Stale"); // Timeout at exactly +10,000. var t = new WebLauncher(); t.Begin(Market, 50_000); Check.True(t.OnChatLine(Line, 0x05, 60_000, out _, out _, out _) == LaunchLine.Stale, "a valid code at +10,000 ms is late: stale, not a code"); Check.True(t.TakeTimedOut(59_999) == null, "not timed out at +9,999"); Check.True(ReferenceEquals(t.TakeTimedOut(60_000), Market), "timed out once at +10,000"); Check.True(t.TakeTimedOut(60_001) == null, "and only once"); Check.True(t.Pending == null, "timeout clears pending"); Check.Eq(t.Status, "No reply from DreamWeave to /weblogin within 10 s, so nothing was opened.", "timeout status"); // Refusal clears pending. var f = new WebLauncher(); f.Begin(Market, 0); string refusal = "[WEB] The website sign-in service is not available right now."; Check.True(f.OnChatLine(refusal, 0x05, 10, out dest, out code, out msg) == LaunchLine.Refused, "refusal"); Check.Eq(msg, "The website sign-in service is not available right now.", "refusal message"); Check.Eq(code, "", "no code on refusal"); Check.Eq(f.Status, "Market: DreamWeave said: The website sign-in service is not available right now.", "refusal status"); Check.True(f.Pending == null, "refusal clears pending"); // A player's copy and unrelated chat leave the request pending. var p = new WebLauncher(); p.Begin(Market, 0); Check.True(p.OnChatLine(Line, 0x02, 5, out _, out _, out _) == LaunchLine.NotOurs, "player copy not ours"); Check.True(p.OnChatLine("You say, \"hi\"", 0x05, 5, out _, out _, out _) == LaunchLine.NotOurs, "other chat not ours"); Check.True(p.Pending != null, "still pending"); // Reset clears pending and status. p.Reset(); Check.True(p.Pending == null, "reset clears pending"); Check.Eq(p.Status, "", "reset clears status"); Check.True(p.OnChatLine(Line, 0x05, 5, out _, out _, out _) == LaunchLine.Stale, "after reset: a code is stale, still eaten"); } private static void OneAtATime() { var w = new WebLauncher(); Check.True(w.Begin(Market, 100_000) == LaunchBegin.Started, "first begin"); Check.True(w.Begin(DreamWeaveWeb.ById("suit")!, 100_001) == LaunchBegin.Busy, "second while pending: busy"); Check.True(w.Begin(DreamWeaveWeb.ById("suit")!, 100_000 + 5_000) == LaunchBegin.Busy, "busy wins over too-soon/free"); Check.True(ReferenceEquals(w.Pending, Market), "first request still the pending one"); w.Cancel("Could not send /weblogin."); Check.True(w.Pending == null, "cancel clears pending"); Check.Eq(w.Status, "Could not send /weblogin.", "cancel status"); Check.True(w.Begin(Market, 100_000 + 2_999) == LaunchBegin.TooSoon, "within 3 s of the last begin: too soon"); Check.True(w.Pending == null, "too soon starts nothing"); Check.True(w.Begin(Market, 100_000 + 3_000) == LaunchBegin.Started, "at 3 s: started"); // Never stuck: a timeout frees the slot. Check.True(w.TakeTimedOut(103_000 + 10_000) != null, "timeout"); Check.True(w.Begin(Market, 113_000) == LaunchBegin.Started, "begin after timeout"); } private static void CodeNeverInStatus() { var w = new WebLauncher(); w.Begin(Market, 0); Check.True(!w.Status.Contains(Code), "status while asking"); var k = w.OnChatLine(Line, 0x05, 100, out _, out string code, out string msg); Check.True(k == LaunchLine.Code, "code flow"); Check.Eq(code.Length, 43, "43-char code returned"); Check.True(!w.Status.Contains(Code), "status after code"); Check.True(!msg.Contains(Code), "message after code"); Check.True(!w.Status.Contains(code.Substring(0, 12)), "no code fragment in status"); // Timeout and refusal paths too. var t = new WebLauncher(); t.Begin(Market, 0); t.TakeTimedOut(10_000); Check.True(!t.Status.Contains(Code), "timeout status"); var f = new WebLauncher(); f.Begin(Market, 0); f.OnChatLine("[WEB] nope", 0x05, 1, out _, out _, out msg); Check.True(!f.Status.Contains(Code) && !msg.Contains(Code), "refusal status and message"); } private static void CodeShapedRefusal() { var w = new WebLauncher(); w.Begin(Market, 0); var k = w.OnChatLine("[WEB] Try again later: " + Code, 0x05, 10, out var dest, out string code, out string msg); Check.True(k == LaunchLine.Refused, "still a refusal, so the caller eats the line"); Check.True(ReferenceEquals(dest, Market), "destination handed back"); Check.Eq(code, "", "no code"); Check.True(!msg.Contains(Code), "message has no code"); Check.True(!w.Status.Contains(Code), "status has no code"); Check.Eq(msg, "DreamWeave sent an unexpected reply.", "fixed replacement text"); Check.Eq(w.Status, "Market: DreamWeave said: DreamWeave sent an unexpected reply.", "status from the replacement"); Check.True(w.Pending == null, "pending cleared"); // A long run of code chars anywhere, and a 42-char run (below the limit) left alone. var w2 = new WebLauncher(); w2.Begin(Market, 0); w2.OnChatLine("[WEB] x " + Code + Code + " y", 0x05, 10, out _, out _, out msg); Check.Eq(msg, "DreamWeave sent an unexpected reply.", "longer run replaced"); var w3 = new WebLauncher(); w3.Begin(Market, 0); w3.OnChatLine("[WEB] id " + Code.Substring(1) + " ok", 0x05, 10, out _, out _, out msg); Check.Eq(msg, "id " + Code.Substring(1) + " ok", "42-char run is ordinary text"); } private static void SelfExpiry() { var w = new WebLauncher(); w.Begin(Market, 0); Check.True(w.Begin(Market, 9_999) == LaunchBegin.Busy, "before the deadline: busy"); Check.True(w.Begin(Market, 10_001) != LaunchBegin.Busy, "past the deadline: not busy"); var x = new WebLauncher(); x.Begin(Market, 0); Check.True(x.Begin(DreamWeaveWeb.ById("suit")!, 10_001) == LaunchBegin.Started, "expired, then started as normal"); Check.True(x.Pending!.Id == "suit", "the new request is the pending one"); Check.True(x.TakeTimedOut(10_001) == null, "the new request is not timed out yet"); Check.Eq(x.TakeTimedOut(20_001)?.Id ?? "none", "suit", "and it times out at its own deadline"); } private static void ResetKeepsThrottle() { var w = new WebLauncher(); Check.True(w.Begin(Market, 1_000) == LaunchBegin.Started, "begin"); w.Reset(); Check.True(w.Pending == null, "reset clears pending"); Check.True(w.Begin(Market, 1_001) == LaunchBegin.TooSoon, "throttle survives a relog"); } private static void LateCodeIsStale() { var w = new WebLauncher(); w.Begin(Market, 0); var k = w.OnChatLine(Line, 0x05, 10_500, out var dest, out string code, out string msg); Check.True(k == LaunchLine.Stale, "valid code at +10,500 ms is stale"); Check.True(dest == null && code == "" && msg == "", "stale carries nothing"); Check.True(w.Pending != null, "stale does not clear pending"); Check.True(!w.Status.Contains(Code), "status has no code"); Check.True(ReferenceEquals(w.TakeTimedOut(10_500), Market), "timeout still fires once"); Check.True(w.TakeTimedOut(10_501) == null, "and only once"); Check.Eq(w.Status, "No reply from DreamWeave to /weblogin within 10 s, so nothing was opened.", "timeout status intact"); Check.True(w.OnChatLine(Line, 0x05, 20_000, out dest, out code, out _) == LaunchLine.Stale, "still stale after the timeout was taken"); Check.True(dest == null && code == "", "no destination or code"); Check.True(w.OnChatLine(Line, 0x05, 69_999, out _, out _, out _) == LaunchLine.Stale, "last stale ms (+69,999)"); Check.True(w.OnChatLine(Line, 0x05, 70_001, out _, out _, out _) == LaunchLine.NotOurs, "at +70,001 ms: not ours"); Check.True(w.OnChatLine("[WEB] some refusal", 0x05, 20_000, out _, out _, out _) == LaunchLine.NotOurs, "a late refusal is not ours"); Check.True(w.OnChatLine(Line, 0x02, 20_000, out _, out _, out _) == LaunchLine.NotOurs, "a late player copy is not ours"); var n = new WebLauncher(); Check.True(n.OnChatLine(Line, 0x05, 10_500, out _, out _, out _) == LaunchLine.NotOurs, "no Begin ever: not ours"); // A consumed request's window persists: a repeat is eaten. var c = new WebLauncher(); c.Begin(Market, 0); c.OnChatLine(Line, 0x05, 100, out _, out _, out _); Check.True(c.OnChatLine(Line, 0x05, 10_500, out _, out _, out _) == LaunchLine.Stale, "after a consumed code: a repeat is stale"); // A new Begin never ends the old stale window: the new request takes a code while pending, // and the window still covers the old code once the new request is gone. var b = new WebLauncher(); b.Begin(Market, 0); b.TakeTimedOut(10_000); b.Begin(Market, 20_000); Check.True(b.OnChatLine(Line, 0x05, 20_100, out _, out _, out _) == LaunchLine.Code, "new request takes the code while pending"); Check.True(b.OnChatLine(Line, 0x05, 20_200, out _, out _, out _) == LaunchLine.Stale, "then a further valid code is stale"); // A refused Begin does not extend the stale window. var t = new WebLauncher(); t.Begin(Market, 0); t.Cancel("send failed"); // Pending would answer Busy; TooSoon needs a free slot Check.True(t.Begin(Market, 2_999) == LaunchBegin.TooSoon, "second begin inside the throttle is refused"); Check.True(t.OnChatLine(Line, 0x05, 70_000, out _, out _, out _) == LaunchLine.NotOurs, "a refused Begin leaves the window anchored at the first"); // A Busy Begin does not extend the stale window either. var y = new WebLauncher(); y.Begin(Market, 0); Check.True(y.Begin(Market, 9_999) == LaunchBegin.Busy, "second begin while pending is Busy"); y.Cancel("send failed"); Check.True(y.OnChatLine(Line, 0x05, 70_000, out _, out _, out _) == LaunchLine.NotOurs, "a Busy Begin leaves the window anchored at the first"); // Window upper boundary. Check.Eq(LaunchWire.CodeLifetimeMs, 60_000L, "code lifetime"); var u = new WebLauncher(); u.Begin(Market, 0); Check.True(u.OnChatLine(Line, 0x05, 69_999, out _, out _, out _) == LaunchLine.Stale, "+69,999 stale"); Check.True(u.OnChatLine(Line, 0x05, 70_000, out _, out _, out _) == LaunchLine.NotOurs, "+70,000 not ours"); } private static void ProfileKeys() { string? a = WebProfile.Key("dreamweave", "Alice"); string? b = WebProfile.Key("dreamweave", "Bob"); Check.True(a != null && b != null, "keys exist"); Check.True(a != b, "different accounts -> different keys"); Check.Eq(WebProfile.Key("dreamweave", " alice "), a, "trimmed and case-folded"); Check.Eq(WebProfile.Key("dreamweave", "ALICE"), a, "case-folded"); Check.Eq(WebProfile.Key("dreamweave", "Alice"), a, "stable across calls"); Check.True(WebProfile.Key("coldeve", "Alice") != a, "same account, other server -> different key"); Check.True(a!.StartsWith("dreamweave/", StringComparison.Ordinal), "prefixed by the server id"); string[] accounts = { "Alice", "Bob", "a", "x y", "caf" + (char)0xE9, "A-very-long-account-name-0123456789-0123456789-0123456789" }; foreach (string acct in accounts) { string? k = WebProfile.Key("dreamweave", acct); Check.True(ServerWebOpen.IsValidProfileKey(k), "valid key for " + acct.Length + " chars"); // A 1-2 char account could appear in the server id or the hex by chance; the rest cannot. if (acct.Length >= 3) Check.True(!k!.Contains(acct.Trim().ToLowerInvariant()), "key never contains the account text"); } Check.Eq(WebProfile.Key("dreamweave", "alice"), "dreamweave/67b613ccd746148225de235baae58eab", "key format is frozen (changing it orphans saved web logins)"); Check.Eq(WebProfile.Key("coldeve", "alice"), "coldeve/1101ebeaa4456aba9ca33cd292d7b99c", "key format is frozen (changing it orphans saved web logins)"); Check.True(WebProfile.Key("DreamWeave", "alice") == null, "uppercase server id -> null"); Check.True(WebProfile.Key("dream/weave", "alice") == null, "slash in server id -> null"); Check.True(WebProfile.Key("", "alice") == null, "empty server id -> null"); Check.True(WebProfile.Key("dreamweave", null) == null, "null account -> null"); Check.True(WebProfile.Key("dreamweave", "") == null, "empty account -> null"); Check.True(WebProfile.Key("dreamweave", " ") == null, "blank account -> null"); } private static void OverlappingRequests() { // Scenario 1: request 1 times out, request 2 begins, request 1's late code arrives. var w = new WebLauncher(); w.Begin(Market, 0); w.TakeTimedOut(10_000); Check.True(w.Begin(Market, 13_000) == LaunchBegin.Started, "request 2"); Check.True(w.OnChatLine(Line, 0x05, 14_000, out _, out _, out _) == LaunchLine.Code, "the late code is taken by request 2 (indistinguishable)"); Check.True(w.OnChatLine(Line, 0x05, 15_000, out var dest, out string code, out string msg) == LaunchLine.Stale, "request 2's own reply is stale, never chat"); Check.True(dest == null && code == "" && msg == "", "stale carries nothing"); // Scenario 2: request 1 expires, request 2 begins and is cancelled, the late code arrives. var c = new WebLauncher(); c.Begin(Market, 0); c.TakeTimedOut(10_000); c.Begin(Market, 13_000); c.Cancel("Could not send /weblogin."); Check.True(c.OnChatLine(Line, 0x05, 14_000, out _, out _, out _) == LaunchLine.Stale, "after cancel: stale"); // Reset while pending, then the code. var r = new WebLauncher(); r.Begin(Market, 0); r.Reset(); Check.True(r.OnChatLine(Line, 0x05, 5_000, out _, out _, out _) == LaunchLine.Stale, "after reset while pending: stale"); Check.True(r.OnChatLine("[WEB] some refusal", 0x05, 5_000, out _, out _, out _) == LaunchLine.NotOurs, "refusals outside a request stay not ours"); // Cancel right after Begin: the ask may have been sent anyway. var k = new WebLauncher(); k.Begin(Market, 0); k.Cancel("x"); Check.True(k.OnChatLine(Line, 0x05, 2_000, out _, out _, out _) == LaunchLine.Stale, "cancelled request's code is stale"); } private static string[] ServerPluginIds() { string? dir = AppContext.BaseDirectory; while (dir != null && !Directory.Exists(Path.Combine(dir, "Plugins", "Shared", "ServerPack"))) dir = Path.GetDirectoryName(dir); if (dir == null) throw new DirectoryNotFoundException("Plugins not found above " + AppContext.BaseDirectory); var ids = new List(); foreach (string p in Directory.GetDirectories(Path.Combine(dir, "Plugins"), "RynthCore.Plugin.Rynth*")) { string csproj = Path.Combine(p, Path.GetFileName(p) + ".csproj"); if (!File.Exists(csproj)) continue; string id = XDocument.Load(csproj).Descendants("RynthPluginServerId").FirstOrDefault()?.Value.Trim() ?? ""; if (id.Length > 0) ids.Add(id); } return ids.ToArray(); } }