diff --git a/Plugins/RynthCore.Plugin.RynthDreamWeave/DreamWeave/DreamWeaveWeb.cs b/Plugins/RynthCore.Plugin.RynthDreamWeave/DreamWeave/DreamWeaveWeb.cs index 6e8ce44..0436ea3 100644 --- a/Plugins/RynthCore.Plugin.RynthDreamWeave/DreamWeave/DreamWeaveWeb.cs +++ b/Plugins/RynthCore.Plugin.RynthDreamWeave/DreamWeave/DreamWeaveWeb.cs @@ -32,6 +32,16 @@ internal static class DreamWeaveWeb return null; } + /// The "/rserver" usage line for the destinations' verbs (ServerUsageLines). + public static string UsageLine() + { + var ids = new string[Destinations.Length]; + var labels = new string[Destinations.Length]; + for (int i = 0; i < Destinations.Length; i++) { ids[i] = Destinations[i].Id; labels[i] = Destinations[i].Label; } + return "/rserver " + string.Join(" | ", ids) + " - open the website's " + string.Join(", ", labels) + + ", logged in as this account."; + } + /// The sign-in URL for a destination. The caller has already checked the code with LaunchWire. public static string LaunchUrl(string code, WebDestination d) => SiteBase + "/launch?code=" + code + "&to=" + Uri.EscapeDataString(d.Path); diff --git a/Plugins/RynthCore.Plugin.RynthDreamWeave/DreamWeave/WebLauncher.cs b/Plugins/RynthCore.Plugin.RynthDreamWeave/DreamWeave/WebLauncher.cs index 42a87e0..0f7bb48 100644 --- a/Plugins/RynthCore.Plugin.RynthDreamWeave/DreamWeave/WebLauncher.cs +++ b/Plugins/RynthCore.Plugin.RynthDreamWeave/DreamWeave/WebLauncher.cs @@ -14,7 +14,10 @@ internal enum LaunchLine { NotOurs, Code, Refused, Stale } /// lock (Gate). The callers are the chat pump, the tick thread and the render thread. Hold /// the lock only around calls into this class, never around Send or ShellExecute. nowMs must come /// from one monotonic clock (Environment.TickCount64). After a Code reply, Status reads -/// "Opening X..."; if the open then fails, the caller must overwrite Status. +/// "Opening X..."; the caller then reports the open's answer with SetResult, never by setting Status +/// another way. Generation names the request a Code or Refused reply resolved: read it under the same +/// lock, right after OnChatLine, and pass it to SetResult. Begin (when Started) and Reset move it on, +/// so an answer for an older request, or one from before a relog, never overwrites a newer status. /// internal sealed class WebLauncher { @@ -30,8 +33,12 @@ internal sealed class WebLauncher // Nothing lowers it (not Begin, Cancel, Reset, Code, Refused or Expire), so a late code from any // earlier request is still eaten as Stale, whatever happened to the requests since. private long _staleUntilMs = long.MinValue; + private long _generation; public WebDestination? Pending => _pending; + + /// The current request's generation: after OnChatLine returns Code or Refused, the one it resolved. + public long Generation => _generation; public string Status { get; private set; } = ""; /// @@ -44,6 +51,7 @@ internal sealed class WebLauncher if (_pending != null) return LaunchBegin.Busy; if (_everBegun && nowMs - _lastBeginMs < LaunchWire.MinIntervalMs) return LaunchBegin.TooSoon; _pending = d; + _generation++; _everBegun = true; _lastBeginMs = nowMs; _deadlineMs = nowMs + LaunchWire.ReplyTimeoutMs; @@ -102,9 +110,19 @@ internal sealed class WebLauncher public void Reset() { _pending = null; + _generation++; Status = ""; } + /// + /// The answer to the request of (the open's result): set as Status only + /// while nothing is pending and no Begin or Reset has happened since; otherwise ignored. + /// + public void SetResult(long generation, string status) + { + if (_pending == null && generation == _generation) Status = status; + } + private void Expire() { _pending = null; diff --git a/Plugins/RynthCore.Plugin.RynthDreamWeave/DreamWeaveWebTools.cs b/Plugins/RynthCore.Plugin.RynthDreamWeave/DreamWeaveWebTools.cs index 407d5a2..66f55c8 100644 --- a/Plugins/RynthCore.Plugin.RynthDreamWeave/DreamWeaveWebTools.cs +++ b/Plugins/RynthCore.Plugin.RynthDreamWeave/DreamWeaveWebTools.cs @@ -26,8 +26,10 @@ public sealed partial class ServerPackPlugin private readonly WebLauncher _web = new(); // The card's click handler, made once (render thread only). private Action? _webClick; - // The "no in-game web panel" line, once per login (set from OpenWeb's done, any thread). - private int _webNoPanelNoted; + // Counts logins, so an answer from before a relog never spends this login's "no web panel" line. + private int _webLoginEpoch; + // The login that has had the "no in-game web panel" line (set from OpenWeb's done, any thread). + private int _webNoPanelNotedEpoch; // The card's draw failure, logged once rather than every frame (render thread only). private bool _webDrawFailed; @@ -45,6 +47,18 @@ public sealed partial class ServerPackPlugin } } + partial void ServerUsageLines(Action add) + { + try + { + add(DreamWeaveWeb.UsageLine()); + } + catch (Exception) + { + // The constructor has no Host to log to yet; the destinations are constants. + } + } + partial void ServerCardActions() { try @@ -117,23 +131,33 @@ public sealed partial class ServerPackPlugin } catch (Exception ex) { - LogTagged("Starting a web open failed: " + ex.GetType().Name); + try + { + LogTagged("Starting a web open failed: " + ex.GetType().Name); + Reply.Fail("Couldn't start the web open."); + } + catch (Exception) + { + } } } private void WebChatText(string text, int chatType, ref bool eat) { + // No Active check before the launcher: only a request it began (or its stale window) is ever + // not NotOurs, and a code that answers one must be eaten whatever the world is now. LaunchLine kind = LaunchLine.NotOurs; try { - if (!Active) return; WebDestination? d; string launchCode; string status; + long generation; lock (_web.Gate) { kind = _web.OnChatLine(text, chatType, Environment.TickCount64, out d, out launchCode, out _); status = _web.Status; + generation = _web.Generation; } switch (kind) { @@ -149,7 +173,13 @@ public sealed partial class ServerPackPlugin return; case LaunchLine.Code: eat = true; - if (d != null) OpenLaunch(d, DreamWeaveWeb.LaunchUrl(launchCode, d), status); + if (d == null) return; + if (!Active) + { + WebOpenFailed(d, generation, WebButtons.NotDreamWeave); + return; + } + OpenLaunch(d, DreamWeaveWeb.LaunchUrl(launchCode, d), generation); return; } } @@ -162,11 +192,12 @@ public sealed partial class ServerPackPlugin } /// - /// Opens the launch URL (pump thread). is the status the launcher set on the - /// code ("Opening X..."); the answer replaces it, so the card never stays on it. + /// Opens the launch URL (pump thread). is the request the code answered; + /// the open's answer replaces its "Opening X..." status (SetResult), so the card never stays on it. /// - private void OpenLaunch(WebDestination d, string url, string opening) + private void OpenLaunch(WebDestination d, string url, long generation) { + int epoch = Volatile.Read(ref _webLoginEpoch); try { string? account = Host.TryGetAccountName(out string name) ? name : null; @@ -175,23 +206,23 @@ public sealed partial class ServerPackPlugin bool panel = PanelAvailable; WebBrowserWhy why = ServerWebOpen.Route(request, panel) != WebOpenRoute.Browser ? WebBrowserWhy.PanelFellBack : panel ? WebBrowserWhy.NoAccount : WebBrowserWhy.NoPanel; - OpenWeb(request, outcome => WebOpened(d, outcome, why, opening)); + OpenWeb(request, outcome => WebOpened(d, outcome, why, generation, epoch)); } catch (Exception ex) { LogTagged("Opening a web page failed: " + ex.GetType().Name); - WebOpenFailed(d, "Couldn't open " + d.Label + ".", opening); + WebOpenFailed(d, generation, "Couldn't open " + d.Label + "."); } } /// OpenWeb's answer. Any thread (the browser opens on a worker thread). - private void WebOpened(WebDestination d, WebOpenOutcome outcome, WebBrowserWhy why, string opening) + private void WebOpened(WebDestination d, WebOpenOutcome outcome, WebBrowserWhy why, long generation, int epoch) { try { if (!outcome.Ok) { - WebOpenFailed(d, "Couldn't open " + d.Label + ": " + outcome.Message, opening); + WebOpenFailed(d, generation, d.Label + ": " + outcome.Message); return; } @@ -201,7 +232,8 @@ public sealed partial class ServerPackPlugin else if (why == WebBrowserWhy.NoPanel) { text = "Opened " + d.Label + "."; - if (Interlocked.Exchange(ref _webNoPanelNoted, 1) == 0) + // Once per login, and never spent by an answer from an earlier login. + if (epoch == Volatile.Read(ref _webLoginEpoch) && Interlocked.Exchange(ref _webNoPanelNotedEpoch, epoch) != epoch) note = "This RynthCore has no in-game web panel, so " + d.Label + " opened in your browser."; } else if (why == WebBrowserWhy.NoAccount) @@ -209,7 +241,7 @@ public sealed partial class ServerPackPlugin else text = "Opened " + d.Label + " in your browser: the web panel didn't take it."; - ReplaceOpeningStatus(opening, text); + SetWebResult(generation, text); Reply.Ok(text); if (note != null) Reply.Ok(note); } @@ -219,11 +251,11 @@ public sealed partial class ServerPackPlugin } } - private void WebOpenFailed(WebDestination d, string text, string opening) + private void WebOpenFailed(WebDestination d, long generation, string text) { try { - ReplaceOpeningStatus(opening, text); + SetWebResult(generation, text); Reply.Fail(text); } catch (Exception) @@ -231,17 +263,10 @@ public sealed partial class ServerPackPlugin } } - /// - /// Puts the answer in the card's status, unless a newer request has taken over the launcher since the - /// code came in (then its own status stands). Cancel is the launcher's status setter; with nothing - /// pending it only sets the status. - /// - private void ReplaceOpeningStatus(string opening, string text) + /// The open's answer as the card's status, unless a newer request (or a relog) has taken over since. + private void SetWebResult(long generation, string text) { - lock (_web.Gate) - { - if (_web.Pending == null && _web.Status == opening) _web.Cancel(text); - } + lock (_web.Gate) _web.SetResult(generation, text); } private void WebTick() @@ -249,11 +274,11 @@ public sealed partial class ServerPackPlugin try { WebDestination? timedOut; - string status = ""; + string status; lock (_web.Gate) { timedOut = _web.TakeTimedOut(Environment.TickCount64); - if (timedOut != null) status = _web.Status; + status = _web.Status; } if (timedOut != null) Reply.Fail(status); } @@ -282,7 +307,7 @@ public sealed partial class ServerPackPlugin try { lock (_web.Gate) _web.Reset(); - Interlocked.Exchange(ref _webNoPanelNoted, 0); + Interlocked.Increment(ref _webLoginEpoch); } catch (Exception ex) { diff --git a/Tools/RynthServerPack.Tests/DreamWeaveWebTests.cs b/Tools/RynthServerPack.Tests/DreamWeaveWebTests.cs index a62293d..1caeac3 100644 --- a/Tools/RynthServerPack.Tests/DreamWeaveWebTests.cs +++ b/Tools/RynthServerPack.Tests/DreamWeaveWebTests.cs @@ -29,10 +29,13 @@ internal static class DreamWeaveWebTests 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: an open's answer lands only on its own request", ResultGeneration); + r.Add("dreamweave web: the source scan's helpers read code, not comments or strings", ScanHelpers); 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) -- + // The rules are allow-lists: what may appear is named, so a new spelling of a forbidden call fails. private static string PluginsRoot() { @@ -63,55 +66,133 @@ internal static class DreamWeaveWebTests 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) + /// + /// The text with // and /* */ comments removed. String literals ("...", @"...", $"...") and char + /// literals are kept as they are, so a "//" inside one is not a comment. + /// + internal static string StripComments(string text) { var sb = new System.Text.StringBuilder(text.Length); - foreach (string line in text.Split('\n')) + int i = 0; + while (i < text.Length) { - int at = 0, cut = -1; - while ((at = line.IndexOf("//", at, StringComparison.Ordinal)) >= 0) + char c = text[i]; + char next = i + 1 < text.Length ? text[i + 1] : '\0'; + if (c == '/' && next == '/') { - if (at == 0 || line[at - 1] != ':') { cut = at; break; } - at += 2; + while (i < text.Length && text[i] != '\n') i++; + continue; } - sb.Append(cut >= 0 ? line.Substring(0, cut) : line).Append('\n'); + if (c == '/' && next == '*') + { + int end = text.IndexOf("*/", i + 2, StringComparison.Ordinal); + i = end < 0 ? text.Length : end + 2; + sb.Append(' '); + continue; + } + if (c == '"' || (c == '@' && next == '"') || (c == '$' && next == '"') || (c == '$' && next == '@') || (c == '@' && next == '$')) + { + int start = i; + bool verbatim = false; + while (i < text.Length && text[i] != '"') { if (text[i] == '@') verbatim = true; i++; } + i++; // the opening quote + while (i < text.Length) + { + if (verbatim) + { + if (text[i] == '"' && i + 1 < text.Length && text[i + 1] == '"') { i += 2; continue; } + if (text[i] == '"') { i++; break; } + } + else + { + if (text[i] == '\\') { i += 2; continue; } + if (text[i] == '"' || text[i] == '\n') { i++; break; } + } + i++; + } + sb.Append(text, start, Math.Min(i, text.Length) - start); + continue; + } + if (c == '\'') + { + int start = i++; + while (i < text.Length && text[i] != '\'' && text[i] != '\n') i += text[i] == '\\' ? 2 : 1; + i++; + sb.Append(text, start, Math.Min(i, text.Length) - start); + continue; + } + sb.Append(c); + i++; } return sb.ToString(); } - /// The statement after each : a balanced { } block, or up to the next ';'. + /// The statement at : a balanced { } block, or up to the next ';'. + private static string StatementAt(string code, int i) + { + 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; + } + return code.Substring(i, Math.Min(j + 1, code.Length) - i); + } + int semi = code.IndexOf(';', i); + return code.Substring(i, (semi < 0 ? code.Length : semi + 1) - i); + } + + /// The statement after each . 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; + found.Add(StatementAt(code, at + head.Length)); + at += head.Length; } 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, @"(?Every lock statement: its target (trimmed) and its body. + internal static List<(string Target, string Body)> Locks(string code) + { + var found = new List<(string, string)>(); + foreach (System.Text.RegularExpressions.Match m in System.Text.RegularExpressions.Regex.Matches(code, @"\block\s*\(")) + { + int open = m.Index + m.Length - 1, depth = 0, j = open; + for (; j < code.Length; j++) + { + if (code[j] == '(') depth++; + else if (code[j] == ')' && --depth == 0) break; + } + if (j >= code.Length) { found.Add(("", "")); continue; } + found.Add((code.Substring(open + 1, j - open - 1).Trim(), StatementAt(code, j + 1))); + } + return found; + } + + /// + /// Every call in that is not a member call on + /// ("_web.Begin(" is allowed; "Send(", "Helper(", "if (", "x._web.Begin(" are not). + /// + internal static List CallsNotOn(string body, string receiver) + { + var bad = new List(); + var allowed = new System.Text.RegularExpressions.Regex("^" + System.Text.RegularExpressions.Regex.Escape(receiver) + @"\.[A-Za-z_][A-Za-z0-9_]*$"); + foreach (System.Text.RegularExpressions.Match m in System.Text.RegularExpressions.Regex.Matches(body, @"(? System.Text.RegularExpressions.Regex.Replace(s, @"\s+", ""); private static int CountOf(string text, string needle) { @@ -182,33 +263,47 @@ internal static class DreamWeaveWebTests foreach (string f in SourceFiles(plugins)) Check.False(processStart.IsMatch(StripComments(File.ReadAllText(f))), Path.GetFileName(f) + ": no Process.Start under Plugins (ShellExecuteW only)"); + // WebButtons.cs calls only ImGui/SafeImGui, the launcher (under its lock) and the click it was handed. string buttons = StripComments(File.ReadAllText(buttonsPath)); - foreach (string banned in new[] { "Host.", "Send(", "OpenWeb(", "RunOnTick(", "Reply.", "ChatLine(", "ChatFail(", "LogTagged(", "ShellExecute" }) - Check.False(Mentions(buttons, banned), "WebButtons.cs: no " + banned + " (draw only draws)"); + int draw = buttons.IndexOf("public static void Draw(", StringComparison.Ordinal); + Check.True(draw >= 0, "WebButtons.Draw exists"); + string drawBody = draw < 0 ? "" : StatementAt(buttons, buttons.IndexOf(')', draw) + 1); + var drawAllowed = new System.Text.RegularExpressions.Regex(@"^(ImGui\.[A-Za-z]+|SafeImGui\.[A-Za-z]+|click|lock|if|foreach)\($"); + var drawCalls = new List(); + foreach (System.Text.RegularExpressions.Match m in System.Text.RegularExpressions.Regex.Matches(drawBody, @"(? drawLocks = StatementsAfter(buttons, "lock (l.Gate)"); + foreach (string pair in new[] { "Begin", "End", "Push", "Pop" }) + Check.False(System.Text.RegularExpressions.Regex.IsMatch(buttons, @"ImGui\." + pair), "WebButtons.cs: no ImGui." + pair + "* (no paired calls)"); + List<(string Target, string Body)> drawLocks = Locks(buttons); 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"); + foreach (var (target, body) in drawLocks) + { + Check.Eq(target, "l.Gate", "WebButtons.cs: the lock is the launcher's Gate"); + Check.Eq(string.Join(" ", CallsNotOn(body, "l")), "", "WebButtons.cs: only launcher members under the lock"); + Check.Eq(Collapse(body), "{pending=l.Pending!=null;status=l.Status;}", "WebButtons.cs: the lock copies Pending and Status, nothing else"); + } 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"); + Check.True(clickPath.Contains("WebButtons.Draw(_web, Active, _webClick ??= d => RunOnTick(() => StartLaunch(d)));", StringComparison.Ordinal), + "the card hook draws through WebButtons.Draw, and a click only queues StartLaunch with RunOnTick"); + Check.Eq(CountOf(host, "StartLaunch("), 3, "StartLaunch: defined, queued by the click, called by the verb (nothing else)"); - // Every lock on the launcher holds launcher calls only: no send, open, reply or log under it. - List hostLocks = StatementsAfter(host, "lock (_web.Gate)"); + // Every lock in the host is on the launcher and holds launcher member calls only. + List<(string Target, string Body)> hostLocks = Locks(host); 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', ' ')); + foreach (var (target, body) in hostLocks) + { + Check.Eq(target, "_web.Gate", "every lock in the host is lock (_web.Gate)"); + Check.Eq(string.Join(" ", CallsNotOn(body, "_web")), "", "only _web members under lock (_web.Gate): " + Collapse(body)); + } 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"); @@ -218,19 +313,82 @@ internal static class DreamWeaveWebTests 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"); + // The chat hook reads every line through the launcher, whatever the world: no Active before OnChatLine. + List chatHook = StatementsAfter(host, "private void WebChatText(string text, int chatType, ref bool eat)"); + Check.Eq(chatHook.Count, 1, "DreamWeaveWebTools.cs implements WebChatText once"); + string chat = chatHook.Count == 1 ? chatHook[0] : ""; + int onChat = chat.IndexOf("OnChatLine(", StringComparison.Ordinal); + Check.True(onChat > 0, "ServerChatText calls OnChatLine"); + Check.False(onChat > 0 && System.Text.RegularExpressions.Regex.IsMatch(chat.Substring(0, onChat), @"(?= 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); + int from = stale + "case LaunchLine.Stale:".Length; + int end = host.IndexOf("return;", from, StringComparison.Ordinal); + Check.Eq(end < 0 ? "" : Collapse(host.Substring(from, end - from)), "eat=true;", "the Stale arm is exactly 'eat = true; return;'"); } } + private static void ResultGeneration() + { + var w = new WebLauncher(); + w.Begin(Market, 0); + Check.True(w.OnChatLine(Line, 0x05, 100, out _, out _, out _) == LaunchLine.Code, "request 1: code"); + long gen1 = w.Generation; + Check.True(w.Begin(DreamWeaveWeb.ById("suit")!, 3_100) == LaunchBegin.Started, "request 2, 3 s later"); + Check.True(w.OnChatLine(Line, 0x05, 3_200, out _, out _, out _) == LaunchLine.Code, "request 2: code"); + long gen2 = w.Generation; + Check.True(gen2 != gen1, "each request has its own generation"); + Check.Eq(w.Status, "Opening Suit Builder...", "request 2 is opening"); + w.SetResult(gen1, "x"); + Check.Eq(w.Status, "Opening Suit Builder...", "request 1's late answer leaves the status alone"); + w.SetResult(gen2, "y"); + Check.Eq(w.Status, "y", "request 2's answer sets it"); + + // Pending, or after a Reset (a relog), an answer is ignored too. + var p = new WebLauncher(); + p.Begin(Market, 0); + long g = p.Generation; + p.SetResult(g, "x"); + Check.Eq(p.Status, "Asking DreamWeave for a login code for Market...", "ignored while a request is pending"); + p.OnChatLine(Line, 0x05, 100, out _, out _, out _); + g = p.Generation; + p.Reset(); + p.SetResult(g, "x"); + Check.Eq(p.Status, "", "an answer from before a Reset is ignored"); + + // A refused Begin moves nothing on. + var r = new WebLauncher(); + r.Begin(Market, 0); + r.OnChatLine(Line, 0x05, 100, out _, out _, out _); + long rg = r.Generation; + Check.True(r.Begin(Market, 200) == LaunchBegin.TooSoon, "too soon"); + r.SetResult(rg, "opened"); + Check.Eq(r.Status, "opened", "a TooSoon Begin keeps the open's generation"); + } + + private static void ScanHelpers() + { + string src = "int a = 1; // lock (x) { Send(); }\nstring u = \"https://x//y\"; /* Reply.Ok() */ char q = '\"'; string v = @\"a\"\"//b\"; lock (_web.Gate) b = 2;\n"; + string code = StripComments(src); + Check.False(code.Contains("Send", StringComparison.Ordinal) || code.Contains("Reply", StringComparison.Ordinal), "comments removed"); + Check.True(code.Contains("\"https://x//y\"", StringComparison.Ordinal), "// inside a string kept"); + Check.True(code.Contains("@\"a\"\"//b\"", StringComparison.Ordinal), "// inside a verbatim string kept"); + Check.True(code.Contains("lock (_web.Gate) b = 2;", StringComparison.Ordinal), "code after a char literal holding a quote kept"); + + var locks = Locks("lock(_web.Gate){ Send(\"x\"); } lock ( other ) _web.Begin(); lock (_web.Gate) { _web.Begin(d, Environment.TickCount64); if (a) b(); }"); + Check.Eq(locks.Count, 3, "every lock found, with or without a space"); + Check.Eq(locks[0].Target, "_web.Gate", "target"); + Check.Eq(string.Join(" ", CallsNotOn(locks[0].Body, "_web")), "Send(", "a bare call under the lock is caught"); + Check.Eq(locks[1].Target, "other", "another target is reported as it is"); + Check.Eq(string.Join(" ", CallsNotOn(locks[2].Body, "_web")), "if( b(", "keywords and helpers are not launcher calls"); + Check.Eq(string.Join(" ", CallsNotOn("x._web.Begin(); _web.Begin(); _web.Gate.Foo();", "_web")), "x._web.Begin( _web.Gate.Foo(", "only a direct _web member call is allowed"); + } + private const string Code = "AbCdEfGhIjKlMnOpQrStUvWxYz0123456789-_AbCde"; // 43 chars private const string Line = "[WEB] Launch code: " + Code + " (single use, expires in 60 seconds)"; diff --git a/Tools/RynthServerPack.Tests/ServerPackCommandsTests.cs b/Tools/RynthServerPack.Tests/ServerPackCommandsTests.cs index 7a50db9..25b7eaa 100644 --- a/Tools/RynthServerPack.Tests/ServerPackCommandsTests.cs +++ b/Tools/RynthServerPack.Tests/ServerPackCommandsTests.cs @@ -70,6 +70,12 @@ internal static class ServerPackCommandsTests Check.Eq(own.Length, 3, "an own line is appended"); Check.Eq(own[2], "/rserver x - one more line", "trimmed"); Check.True(own[0] == pinned[0] && own[1] == pinned[1], "the shared two come first, unchanged"); + + // DreamWeave's verbs follow the shared two. + string[] dw = ServerPackCommands.Usage("DreamWeave", new List { RynthCore.Plugin.RynthDreamWeave.DreamWeaveWeb.UsageLine() }); + Check.Eq(dw.Length, 3, "DreamWeave: three usage lines"); + Check.Eq(dw[2], "/rserver market | suit | abilities - open the website's Market, Suit Builder, Ability Planner, logged in as this account.", "DreamWeave's own line"); + Check.True(dw[0] == ServerPackCommands.Usage("DreamWeave")[0] && dw[1] == ServerPackCommands.Usage("DreamWeave")[1], "the shared two come first, unchanged"); } private static void Queue()