From 52b0b008603a3036e1dbfad82e82a9034bd5346d Mon Sep 17 00:00:00 2001 From: Daniel Wallace Date: Sat, 7 Nov 2026 14:33:03 -0800 Subject: [PATCH 1/6] ServerPack: card-actions hook for a server's own buttons Adds partial void ServerCardActions(), drawn at the top of the server card under RynthCore's verdict (render thread). ServerPackUi takes an optional cardActions delegate; the plugin passes DrawCardActions (a delegate cannot bind an unimplemented partial, CS0762). Co-Authored-By: Claude Opus 5.5 --- Plugins/Shared/ServerPack/ServerPackPlugin.cs | 11 +++++- Plugins/Shared/ServerPack/ServerPackUi.cs | 6 ++- .../ServerPackHooksTests.cs | 39 ++++++++++++++++++- 3 files changed, 53 insertions(+), 3 deletions(-) diff --git a/Plugins/Shared/ServerPack/ServerPackPlugin.cs b/Plugins/Shared/ServerPack/ServerPackPlugin.cs index f1f30c3..d2f1a96 100644 --- a/Plugins/Shared/ServerPack/ServerPackPlugin.cs +++ b/Plugins/Shared/ServerPack/ServerPackPlugin.cs @@ -33,6 +33,8 @@ // plugins that apply a server rule without knowing the server. // ServerCommandVerbs(list) its own "/rserver " words, handled in ServerChatCommand. // RunOnTick(action) work for the next tick (a page's button, on the render thread). +// ServerCardActions() the server's own buttons at the top of its card, under RynthCore's verdict +// (render thread: ImGui calls only; queue work with RunOnTick). // Send(command) a chat command as if typed (pump thread, logged in only); // LogTagged(text) the engine log, "[RynthConquest] ..."; ChatLine(text) the chat window. // Resources\quests..csv (no code) the server's own quest list: embedded by ServerPlugin.props and @@ -102,7 +104,7 @@ public sealed partial class ServerPackPlugin : RynthPluginBase var verbs = new List(); ServerCommandVerbs(verbs); foreach (string v in verbs) if (!string.IsNullOrWhiteSpace(v)) _serverVerbs.Add(v.Trim()); - _ui = new ServerPackUi(_model, RynthPluginInfo.Name + " " + Marshal.PtrToStringAnsi(VersionPointer), () => _world, _pages); + _ui = new ServerPackUi(_model, RynthPluginInfo.Name + " " + Marshal.PtrToStringAnsi(VersionPointer), () => _world, _pages, DrawCardActions); } internal ServerPackInfo Info => _model.Info; @@ -147,6 +149,10 @@ public sealed partial class ServerPackPlugin : RynthPluginBase /// Every frame while logged in (render thread, AC's main thread; the engine's ImGui context current). partial void ServerRender(); /// + /// Drawn at the top of the server card, under RynthCore's verdict; render thread; queue work with RunOnTick. + /// + partial void ServerCardActions(); + /// /// An incoming chat line (pump thread, logged in only): set to keep it out of /// the chat window (it comes in true when an earlier plugin already ate it). /// @@ -165,6 +171,9 @@ public sealed partial class ServerPackPlugin : RynthPluginBase /// The live numbers of the profile ("values"). Any thread. internal ServerProfileValues ProfileValues => _profileValues; + // A delegate cannot bind an unimplemented partial method (CS0762), so the card gets this wrapper. + private void DrawCardActions() => ServerCardActions(); + /// The pages this plugin draws. internal IReadOnlyList Pages => _pages; diff --git a/Plugins/Shared/ServerPack/ServerPackUi.cs b/Plugins/Shared/ServerPack/ServerPackUi.cs index f1a65da..e5fe52c 100644 --- a/Plugins/Shared/ServerPack/ServerPackUi.cs +++ b/Plugins/Shared/ServerPack/ServerPackUi.cs @@ -26,6 +26,7 @@ internal sealed class ServerPackUi private readonly Func _world; private readonly string _windowTitle; private readonly IReadOnlyList _pages; + private readonly Action? _cardActions; private string _status = string.Empty; /// The standalone window is open ("/rserver"). @@ -34,12 +35,14 @@ internal sealed class ServerPackUi /// "RynthColdeve 0.1.0", for the title and the card. /// The world name the client reports now (null when unknown). /// The server's own pages: tabs of the window after the card. - public ServerPackUi(ServerPackModel model, string pluginLabel, Func world, IReadOnlyList? pages = null) + /// The server's own buttons, drawn under the verdict (render thread); null when it has none. + public ServerPackUi(ServerPackModel model, string pluginLabel, Func world, IReadOnlyList? pages = null, Action? cardActions = null) { _model = model; _pluginLabel = pluginLabel; _world = world; _pages = pages ?? Array.Empty(); + _cardActions = cardActions; _windowTitle = model.Info.Name + " server (" + pluginLabel + ")##server_" + model.Info.Id; } @@ -82,6 +85,7 @@ internal sealed class ServerPackUi { ServerPackInfo info = _model.Info; RenderVerdict(info); + if (_cardActions != null) { ImGui.Separator(); _cardActions(); } ImGui.Separator(); RenderFacts(info); if (info.Commands.Length > 0) diff --git a/Tools/RynthServerPack.Tests/ServerPackHooksTests.cs b/Tools/RynthServerPack.Tests/ServerPackHooksTests.cs index 66de8ea..68ce76b 100644 --- a/Tools/RynthServerPack.Tests/ServerPackHooksTests.cs +++ b/Tools/RynthServerPack.Tests/ServerPackHooksTests.cs @@ -24,6 +24,7 @@ internal static class ServerPackHooksTests r.Add("hooks: settings migration runs once, and a broken file means defaults", SettingsMigration); r.Add("hooks: profile values are published, validated and read back", ProfileValues); r.Add("hooks: the own-reply window opens, stretches and closes", ReplyWindow); + r.Add("hooks: the card draws server actions under the verdict, once", CardActions); } internal static string TempDir() @@ -199,4 +200,40 @@ internal static class ServerPackHooksTests req.Clear(); Check.False(req.Awaiting(1001), "cleared"); } -} + + // Source scan: the card hands the server's own buttons a spot right under RynthCore's verdict. + private static string ServerPackDir() + { + 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\\Shared\\ServerPack not found above " + AppContext.BaseDirectory); + return Path.Combine(dir, "Plugins", "Shared", "ServerPack"); + } + + private static int CountOf(string text, string needle) + { + int n = 0, at = 0; + while ((at = text.IndexOf(needle, at, StringComparison.Ordinal)) >= 0) { n++; at += needle.Length; } + return n; + } + + private static void CardActions() + { + string ui = File.ReadAllText(Path.Combine(ServerPackDir(), "ServerPackUi.cs")); + string plugin = File.ReadAllText(Path.Combine(ServerPackDir(), "ServerPackPlugin.cs")); + + int body = ui.IndexOf("public void RenderBody()", StringComparison.Ordinal); + Check.True(body >= 0, "RenderBody exists"); + int verdict = ui.IndexOf("RenderVerdict(info);", body, StringComparison.Ordinal); + int facts = ui.IndexOf("RenderFacts(info);", body, StringComparison.Ordinal); + Check.True(verdict > body && facts > verdict, "RenderBody draws the verdict, then the facts"); + Check.Eq(CountOf(ui, "_cardActions()"), 1, "the card actions are invoked exactly once"); + int call = ui.IndexOf("_cardActions()", StringComparison.Ordinal); + Check.True(call > verdict && call < facts, "the actions are drawn after the verdict and before the facts"); + + Check.True(plugin.Contains("DrawCardActions", StringComparison.Ordinal) && plugin.Contains("partial void ServerCardActions();", StringComparison.Ordinal), + "the plugin declares the ServerCardActions hook and DrawCardActions"); + Check.True(plugin.Contains("_pages, DrawCardActions)", StringComparison.Ordinal), "the plugin passes DrawCardActions to ServerPackUi"); + } +} \ No newline at end of file -- 2.43.0 From 5c6af0bbe5545554fd092c9448945c0da354d3a4 Mon Sep 17 00:00:00 2001 From: Daniel Wallace Date: Sat, 7 Nov 2026 14:34:27 -0800 Subject: [PATCH 2/6] ServerPack: card actions add no separator of their own Hookless servers render exactly as before: call _cardActions?.Invoke() after RenderVerdict and let the existing separator close the block. Test now pins the RenderBody separator count and restores the trailing CRLF. Co-Authored-By: Claude Opus 5.5 --- Plugins/Shared/ServerPack/ServerPackUi.cs | 2 +- Tools/RynthServerPack.Tests/ServerPackHooksTests.cs | 11 ++++++++--- 2 files changed, 9 insertions(+), 4 deletions(-) diff --git a/Plugins/Shared/ServerPack/ServerPackUi.cs b/Plugins/Shared/ServerPack/ServerPackUi.cs index e5fe52c..1df73e6 100644 --- a/Plugins/Shared/ServerPack/ServerPackUi.cs +++ b/Plugins/Shared/ServerPack/ServerPackUi.cs @@ -85,7 +85,7 @@ internal sealed class ServerPackUi { ServerPackInfo info = _model.Info; RenderVerdict(info); - if (_cardActions != null) { ImGui.Separator(); _cardActions(); } + _cardActions?.Invoke(); ImGui.Separator(); RenderFacts(info); if (info.Commands.Length > 0) diff --git a/Tools/RynthServerPack.Tests/ServerPackHooksTests.cs b/Tools/RynthServerPack.Tests/ServerPackHooksTests.cs index 68ce76b..0ef0c2a 100644 --- a/Tools/RynthServerPack.Tests/ServerPackHooksTests.cs +++ b/Tools/RynthServerPack.Tests/ServerPackHooksTests.cs @@ -228,12 +228,17 @@ internal static class ServerPackHooksTests int verdict = ui.IndexOf("RenderVerdict(info);", body, StringComparison.Ordinal); int facts = ui.IndexOf("RenderFacts(info);", body, StringComparison.Ordinal); Check.True(verdict > body && facts > verdict, "RenderBody draws the verdict, then the facts"); - Check.Eq(CountOf(ui, "_cardActions()"), 1, "the card actions are invoked exactly once"); - int call = ui.IndexOf("_cardActions()", StringComparison.Ordinal); + Check.Eq(CountOf(ui, "_cardActions?.Invoke()"), 1, "the card actions are invoked exactly once"); + int call = ui.IndexOf("_cardActions?.Invoke()", StringComparison.Ordinal); Check.True(call > verdict && call < facts, "the actions are drawn after the verdict and before the facts"); + // Hookless servers must render exactly as before: no separator was added to the card (base RenderBody has 5). + int bodyEnd = ui.IndexOf("private void RenderVerdict", body, StringComparison.Ordinal); + Check.Eq(CountOf(ui.Substring(body, bodyEnd - body), "ImGui.Separator()"), 5, "RenderBody separator count is unchanged from base"); + Check.False(ui.Substring(verdict, call - verdict).Contains("Separator", StringComparison.Ordinal), "no separator between the verdict and the actions"); + Check.True(plugin.Contains("DrawCardActions", StringComparison.Ordinal) && plugin.Contains("partial void ServerCardActions();", StringComparison.Ordinal), "the plugin declares the ServerCardActions hook and DrawCardActions"); Check.True(plugin.Contains("_pages, DrawCardActions)", StringComparison.Ordinal), "the plugin passes DrawCardActions to ServerPackUi"); } -} \ No newline at end of file +} -- 2.43.0 From dd802169338f62b49aa4f37cb921fb0192a2e290 Mon Sep 17 00:00:00 2001 From: Daniel Wallace Date: Sat, 7 Nov 2026 14:36:19 -0800 Subject: [PATCH 3/6] ServerPack: open a web page in the engine's panel, else the browser Pure allowlist/route rules (ServerWebOpen) plus the host opener (ServerPackWeb): ShellExecuteW on a background STA thread; panel seams stubbed. Co-Authored-By: Claude Opus 5.5 --- Plugins/Shared/ServerPack/ServerPackWeb.cs | 81 +++++++++++++++++++ Plugins/Shared/ServerPack/ServerPlugin.props | 3 + Plugins/Shared/ServerPack/ServerWebOpen.cs | 79 ++++++++++++++++++ Tools/RynthServerPack.Tests/Program.cs | 1 + .../RynthServerPack.Tests.csproj | 2 + .../ServerWebOpenTests.cs | 49 +++++++++++ 6 files changed, 215 insertions(+) create mode 100644 Plugins/Shared/ServerPack/ServerPackWeb.cs create mode 100644 Plugins/Shared/ServerPack/ServerWebOpen.cs create mode 100644 Tools/RynthServerPack.Tests/ServerWebOpenTests.cs diff --git a/Plugins/Shared/ServerPack/ServerPackWeb.cs b/Plugins/Shared/ServerPack/ServerPackWeb.cs new file mode 100644 index 0000000..af3c95e --- /dev/null +++ b/Plugins/Shared/ServerPack/ServerPackWeb.cs @@ -0,0 +1,81 @@ +// ServerPackWeb.cs - the host side of ServerWebOpen: open a server's web page in the engine's web +// panel when it has one, else in the system browser. A server's own code calls OpenWeb on the pump +// (ServerChatCommand, a RunOnTick action); the answer goes to `done`, which may run on a worker +// thread (Reply is any-thread). The answer never contains the URL. +// +// Never Process.Start inside acclient: the browser opens with ShellExecuteW, as the engine does +// (ProblemReport.cs), on its own short-lived STA thread so the shell call never blocks the pump. +// The panel seams (PanelAvailable, TryOpenPanel) are stubs until the engine API is wired. +using System; +using System.Runtime.InteropServices; +using System.Threading; + +namespace RynthCore.Plugin.ServerPack; + +public sealed partial class ServerPackPlugin +{ + [DllImport("shell32.dll", CharSet = CharSet.Unicode, EntryPoint = "ShellExecuteW")] + private static extern IntPtr ShellExecuteW(IntPtr hwnd, string? operation, string file, string? parameters, string? directory, int showCmd); + + // Seams for the engine's web panel. + private bool PanelAvailable => false; + + private bool TryOpenPanel(WebOpenRequest r, out string error) + { + error = "The web panel is not available."; + return false; + } + + /// Opens the page (pump thread). `done` gets the route taken and a message without the URL. + internal void OpenWeb(WebOpenRequest r, Action done) + { + WebOpenRoute route = ServerWebOpen.Route(r, PanelAvailable); + if (route == WebOpenRoute.Refused) + { + done(new WebOpenOutcome(route, false, "That page is not on this server's list of pages, so it was not opened.")); + return; + } + + if (route == WebOpenRoute.Panel) + { + if (TryOpenPanel(r, out string error)) + { + done(new WebOpenOutcome(route, true, "Opened in the web panel.")); + return; + } + // The panel failed: the browser is the fallback, and the report below says it was the browser. + LogTagged("web panel did not open: " + error); + route = WebOpenRoute.Browser; + } + + string url = r.Url; + var thread = new Thread(() => + { + string message; + bool ok; + try + { + long code = ShellExecuteW(IntPtr.Zero, "open", url, null, null, 1).ToInt64(); + ok = code > 32; + message = ok ? "Opened in your browser." : $"Couldn't open your browser (code {code})."; + } + catch (Exception) + { + ok = false; + message = "Couldn't open your browser (code 0)."; + } + done(new WebOpenOutcome(WebOpenRoute.Browser, ok, message)); + }) + { + IsBackground = true, + Name = "ServerPack web open", + }; + thread.SetApartmentState(ApartmentState.STA); + thread.Start(); + } + + /// Closes the engine's web panel if this plugin opened one. Nothing to close until the panel API is wired. + internal void CloseWeb() + { + } +} diff --git a/Plugins/Shared/ServerPack/ServerPlugin.props b/Plugins/Shared/ServerPack/ServerPlugin.props index 9e8606b..d7abb0d 100644 --- a/Plugins/Shared/ServerPack/ServerPlugin.props +++ b/Plugins/Shared/ServerPack/ServerPlugin.props @@ -67,6 +67,9 @@ + + + diff --git a/Plugins/Shared/ServerPack/ServerWebOpen.cs b/Plugins/Shared/ServerPack/ServerWebOpen.cs new file mode 100644 index 0000000..2100a4d --- /dev/null +++ b/Plugins/Shared/ServerPack/ServerWebOpen.cs @@ -0,0 +1,79 @@ +// ServerWebOpen.cs - the rules for opening a server's web page from a server plugin: which URLs are +// allowed and where the page goes (the engine's web panel when it has one, else the system browser). +// Pure (no engine, no threads): RynthServerPack.Tests covers it. The host side is ServerPackWeb.cs. +// No Regex: the plugins are NativeAOT and Regex costs size, so the key is parsed by hand. +using System; +using System.Collections.Generic; + +namespace RynthCore.Plugin.ServerPack; + +/// A page to open. The URL comes from constants in the plugin, never from chat. +internal sealed record WebOpenRequest(string Url, IReadOnlyList AllowedHosts, string ProfileKey, string Title); + +internal enum WebOpenRoute { Panel, Browser, Refused } + +/// What happened. The message never contains the URL. +internal sealed record WebOpenOutcome(WebOpenRoute Route, bool Ok, string Message); + +internal static class ServerWebOpen +{ + /// + /// Absolute https, no userinfo, the default port, and a host equal to an allowed entry + /// (OrdinalIgnoreCase). An entry "*.x" matches subdomains of x only, never x itself. + /// + public static bool IsAllowedUrl(string? url, IReadOnlyList allowedHosts) + { + if (string.IsNullOrEmpty(url) || allowedHosts == null) return false; + if (!Uri.TryCreate(url, UriKind.Absolute, out Uri? uri)) return false; + if (!string.Equals(uri.Scheme, "https", StringComparison.Ordinal)) return false; + if (uri.UserInfo.Length != 0 || !uri.IsDefaultPort) return false; + string host = uri.Host; + if (host.Length == 0) return false; + + foreach (string entry in allowedHosts) + { + if (string.IsNullOrEmpty(entry)) continue; + if (entry.StartsWith("*.", StringComparison.Ordinal)) + { + string suffix = entry.Substring(1); // ".x" + if (suffix.Length > 1 + && host.Length > suffix.Length + && host.EndsWith(suffix, StringComparison.OrdinalIgnoreCase)) + return true; + } + else if (string.Equals(host, entry, StringComparison.OrdinalIgnoreCase)) + { + return true; + } + } + return false; + } + + /// ^[a-z0-9-]{1,32}/[0-9a-f]{32}$ - the engine's panel profile key (server/token). + public static bool IsValidProfileKey(string? key) + { + if (key == null) return false; + int slash = key.IndexOf('/'); + if (slash < 1 || slash > 32) return false; + if (key.Length - slash - 1 != 32) return false; + for (int i = 0; i < slash; i++) + { + char c = key[i]; + if (!((c >= 'a' && c <= 'z') || (c >= '0' && c <= '9') || c == '-')) return false; + } + for (int i = slash + 1; i < key.Length; i++) + { + char c = key[i]; + if (!((c >= '0' && c <= '9') || (c >= 'a' && c <= 'f'))) return false; + } + return true; + } + + /// Refused if the URL is not allowed; Browser if there is no panel or no valid key; else Panel. + public static WebOpenRoute Route(WebOpenRequest r, bool panelAvailable) + { + if (!IsAllowedUrl(r.Url, r.AllowedHosts)) return WebOpenRoute.Refused; + if (!panelAvailable || !IsValidProfileKey(r.ProfileKey)) return WebOpenRoute.Browser; + return WebOpenRoute.Panel; + } +} diff --git a/Tools/RynthServerPack.Tests/Program.cs b/Tools/RynthServerPack.Tests/Program.cs index 0bf26e2..88e690e 100644 --- a/Tools/RynthServerPack.Tests/Program.cs +++ b/Tools/RynthServerPack.Tests/Program.cs @@ -22,6 +22,7 @@ internal static class Program ServerPackCommandsTests.Register(runner); DreamWeaveSkillsTests.Register(runner); DreamWeaveTests.Register(runner); + ServerWebOpenTests.Register(runner); return runner.Run("RynthServerPack tests", args.Length > 0 ? args[0] : null); } } diff --git a/Tools/RynthServerPack.Tests/RynthServerPack.Tests.csproj b/Tools/RynthServerPack.Tests/RynthServerPack.Tests.csproj index cd4e37a..67ccd9a 100644 --- a/Tools/RynthServerPack.Tests/RynthServerPack.Tests.csproj +++ b/Tools/RynthServerPack.Tests/RynthServerPack.Tests.csproj @@ -32,6 +32,8 @@ + + diff --git a/Tools/RynthServerPack.Tests/ServerWebOpenTests.cs b/Tools/RynthServerPack.Tests/ServerWebOpenTests.cs new file mode 100644 index 0000000..acbeb10 --- /dev/null +++ b/Tools/RynthServerPack.Tests/ServerWebOpenTests.cs @@ -0,0 +1,49 @@ +using System; +using RynthCore.Plugin.ServerPack; +using RynthCore.RynthAiTests.Harness; + +namespace RynthServerPack.Tests; + +// The web opener's pure part: which URLs a server plugin may open, and where the page goes. +internal static class ServerWebOpenTests +{ + public static void Register(Runner r) + { + r.Add("web open: only https on an allowed host, and the route follows the engine", Rules); + } + + private static readonly string[] Hosts = { "www.acdreamweave.com" }; + private static readonly string[] Wild = { "*.acdreamweave.com" }; + private const string Key = "dreamweave/0123456789abcdef0123456789abcdef"; + + private static void Rules() + { + Check.True(ServerWebOpen.IsAllowedUrl("https://www.acdreamweave.com/x", Hosts), "https on the host"); + Check.True(ServerWebOpen.IsAllowedUrl("https://WWW.AcDreamWeave.com/x", Hosts), "host case-insensitive"); + Check.True(!ServerWebOpen.IsAllowedUrl("http://www.acdreamweave.com/x", Hosts), "http refused"); + Check.True(!ServerWebOpen.IsAllowedUrl("https://user@www.acdreamweave.com/x", Hosts), "userinfo refused"); + Check.True(!ServerWebOpen.IsAllowedUrl("https://www.acdreamweave.com:444/x", Hosts), "other port refused"); + Check.True(!ServerWebOpen.IsAllowedUrl("https://www.acdreamweave.com.evil.com/x", Hosts), "suffix host refused"); + Check.True(!ServerWebOpen.IsAllowedUrl("javascript:alert(1)", Hosts), "javascript refused"); + Check.True(!ServerWebOpen.IsAllowedUrl(null, Hosts), "null refused"); + Check.True(!ServerWebOpen.IsAllowedUrl("/relative", Hosts), "relative refused"); + + Check.True(ServerWebOpen.IsAllowedUrl("https://wiki.acdreamweave.com/", Wild), "wildcard matches a subdomain"); + Check.True(!ServerWebOpen.IsAllowedUrl("https://acdreamweave.com/", Wild), "wildcard excludes the bare domain"); + Check.True(!ServerWebOpen.IsAllowedUrl("https://evilacdreamweave.com/", Wild), "wildcard needs the dot"); + + Check.True(ServerWebOpen.IsValidProfileKey(Key), "dreamweave/ + 32 hex"); + Check.True(!ServerWebOpen.IsValidProfileKey("dreamweave/0123456789ABCDEF0123456789abcdef"), "uppercase refused"); + Check.True(!ServerWebOpen.IsValidProfileKey("../0123456789abcdef0123456789abcdef"), "dotdot refused"); + Check.True(!ServerWebOpen.IsValidProfileKey(Key + "0"), "longer refused"); + Check.True(!ServerWebOpen.IsValidProfileKey(""), "empty refused"); + Check.True(!ServerWebOpen.IsValidProfileKey(null), "null refused"); + + var ok = new WebOpenRequest("https://www.acdreamweave.com/x", Hosts, Key, "t"); + Check.Eq(ServerWebOpen.Route(ok, true), WebOpenRoute.Panel, "panel"); + Check.Eq(ServerWebOpen.Route(ok, false), WebOpenRoute.Browser, "no panel -> browser"); + Check.Eq(ServerWebOpen.Route(ok with { ProfileKey = "" }, true), WebOpenRoute.Browser, "empty key -> browser"); + Check.Eq(ServerWebOpen.Route(ok with { ProfileKey = "Bad/Key" }, true), WebOpenRoute.Browser, "bad key -> browser"); + Check.Eq(ServerWebOpen.Route(ok with { Url = "http://www.acdreamweave.com/x" }, true), WebOpenRoute.Refused, "bad url refused"); + } +} -- 2.43.0 From c085c16e1534c62a260485a20bcd149517d763b4 Mon Sep 17 00:00:00 2001 From: Daniel Wallace Date: Sat, 7 Nov 2026 14:38:48 -0800 Subject: [PATCH 4/6] ServerPack web open: fall back only before the panel navigates PanelResult + pure FallbackToBrowser; guard TryOpenPanel throws; guard done callbacks; hand ShellExecuteW the validated absolute URI. Co-Authored-By: Claude Opus 5.5 --- Plugins/Shared/ServerPack/ServerPackWeb.cs | 38 ++++++++++++------- Plugins/Shared/ServerPack/ServerWebOpen.cs | 19 ++++++++++ .../ServerWebOpenTests.cs | 7 ++++ 3 files changed, 51 insertions(+), 13 deletions(-) diff --git a/Plugins/Shared/ServerPack/ServerPackWeb.cs b/Plugins/Shared/ServerPack/ServerPackWeb.cs index af3c95e..cabecd7 100644 --- a/Plugins/Shared/ServerPack/ServerPackWeb.cs +++ b/Plugins/Shared/ServerPack/ServerPackWeb.cs @@ -17,13 +17,14 @@ public sealed partial class ServerPackPlugin [DllImport("shell32.dll", CharSet = CharSet.Unicode, EntryPoint = "ShellExecuteW")] private static extern IntPtr ShellExecuteW(IntPtr hwnd, string? operation, string file, string? parameters, string? directory, int showCmd); - // Seams for the engine's web panel. + // Seam for the engine's web panel (a stub until the engine API is wired). private bool PanelAvailable => false; - private bool TryOpenPanel(WebOpenRequest r, out string error) + private PanelResult TryOpenPanel(WebOpenRequest r) => PanelResult.RefusedBeforeNavigate; + + private static void Finish(Action done, WebOpenOutcome outcome) { - error = "The web panel is not available."; - return false; + try { done(outcome); } catch { } } /// Opens the page (pump thread). `done` gets the route taken and a message without the URL. @@ -32,23 +33,35 @@ public sealed partial class ServerPackPlugin WebOpenRoute route = ServerWebOpen.Route(r, PanelAvailable); if (route == WebOpenRoute.Refused) { - done(new WebOpenOutcome(route, false, "That page is not on this server's list of pages, so it was not opened.")); + Finish(done, new WebOpenOutcome(route, false, "That page is not on this server's list of pages, so it was not opened.")); return; } if (route == WebOpenRoute.Panel) { - if (TryOpenPanel(r, out string error)) + PanelResult result; + try { result = TryOpenPanel(r); } + catch (Exception) { result = PanelResult.RefusedBeforeNavigate; } + + if (result == PanelResult.Opened) { - done(new WebOpenOutcome(route, true, "Opened in the web panel.")); + Finish(done, new WebOpenOutcome(WebOpenRoute.Panel, true, "Opened in the web panel.")); return; } - // The panel failed: the browser is the fallback, and the report below says it was the browser. - LogTagged("web panel did not open: " + error); - route = WebOpenRoute.Browser; + if (!ServerWebOpen.FallbackToBrowser(result)) + { + LogTagged("web panel: " + result); + Finish(done, new WebOpenOutcome(WebOpenRoute.Panel, false, "The web panel couldn't open that page.")); + return; + } + LogTagged("web panel: " + result + ", using the browser"); } - string url = r.Url; + if (!ServerWebOpen.TryGetAllowedUri(r.Url, r.AllowedHosts, out string url)) + { + Finish(done, new WebOpenOutcome(WebOpenRoute.Refused, false, "That page is not on this server's list of pages, so it was not opened.")); + return; + } var thread = new Thread(() => { string message; @@ -64,7 +77,7 @@ public sealed partial class ServerPackPlugin ok = false; message = "Couldn't open your browser (code 0)."; } - done(new WebOpenOutcome(WebOpenRoute.Browser, ok, message)); + Finish(done, new WebOpenOutcome(WebOpenRoute.Browser, ok, message)); }) { IsBackground = true, @@ -73,7 +86,6 @@ public sealed partial class ServerPackPlugin thread.SetApartmentState(ApartmentState.STA); thread.Start(); } - /// Closes the engine's web panel if this plugin opened one. Nothing to close until the panel API is wired. internal void CloseWeb() { diff --git a/Plugins/Shared/ServerPack/ServerWebOpen.cs b/Plugins/Shared/ServerPack/ServerWebOpen.cs index 2100a4d..7b0392c 100644 --- a/Plugins/Shared/ServerPack/ServerWebOpen.cs +++ b/Plugins/Shared/ServerPack/ServerWebOpen.cs @@ -12,6 +12,9 @@ internal sealed record WebOpenRequest(string Url, IReadOnlyList AllowedH internal enum WebOpenRoute { Panel, Browser, Refused } +/// What the engine's panel did. Only a refusal before navigating may fall back to the browser. +internal enum PanelResult { Opened, RefusedBeforeNavigate, UrlNotAllowed, FailedAfterNavigate } + /// What happened. The message never contains the URL. internal sealed record WebOpenOutcome(WebOpenRoute Route, bool Ok, string Message); @@ -22,13 +25,25 @@ internal static class ServerWebOpen /// (OrdinalIgnoreCase). An entry "*.x" matches subdomains of x only, never x itself. /// public static bool IsAllowedUrl(string? url, IReadOnlyList allowedHosts) + => TryGetAllowedUri(url, allowedHosts, out _); + + /// The same check, giving the validated absolute URI (what the browser should be handed). + public static bool TryGetAllowedUri(string? url, IReadOnlyList allowedHosts, out string absoluteUri) { + absoluteUri = string.Empty; if (string.IsNullOrEmpty(url) || allowedHosts == null) return false; if (!Uri.TryCreate(url, UriKind.Absolute, out Uri? uri)) return false; if (!string.Equals(uri.Scheme, "https", StringComparison.Ordinal)) return false; if (uri.UserInfo.Length != 0 || !uri.IsDefaultPort) return false; string host = uri.Host; if (host.Length == 0) return false; + if (!HostAllowed(host, allowedHosts)) return false; + absoluteUri = uri.AbsoluteUri; + return true; + } + + private static bool HostAllowed(string host, IReadOnlyList allowedHosts) + { foreach (string entry in allowedHosts) { @@ -49,6 +64,10 @@ internal static class ServerWebOpen return false; } + /// Fall back to the browser only when the panel refused before navigating. After a + /// navigate the one-time code is spent (a dead link), and UrlNotAllowed must not bypass the engine's list. + public static bool FallbackToBrowser(PanelResult r) => r == PanelResult.RefusedBeforeNavigate; + /// ^[a-z0-9-]{1,32}/[0-9a-f]{32}$ - the engine's panel profile key (server/token). public static bool IsValidProfileKey(string? key) { diff --git a/Tools/RynthServerPack.Tests/ServerWebOpenTests.cs b/Tools/RynthServerPack.Tests/ServerWebOpenTests.cs index acbeb10..25ffd9e 100644 --- a/Tools/RynthServerPack.Tests/ServerWebOpenTests.cs +++ b/Tools/RynthServerPack.Tests/ServerWebOpenTests.cs @@ -45,5 +45,12 @@ internal static class ServerWebOpenTests Check.Eq(ServerWebOpen.Route(ok with { ProfileKey = "" }, true), WebOpenRoute.Browser, "empty key -> browser"); Check.Eq(ServerWebOpen.Route(ok with { ProfileKey = "Bad/Key" }, true), WebOpenRoute.Browser, "bad key -> browser"); Check.Eq(ServerWebOpen.Route(ok with { Url = "http://www.acdreamweave.com/x" }, true), WebOpenRoute.Refused, "bad url refused"); + + Check.True(ServerWebOpen.FallbackToBrowser(PanelResult.RefusedBeforeNavigate), "refused before navigate -> browser"); + Check.True(!ServerWebOpen.FallbackToBrowser(PanelResult.Opened), "opened -> no browser"); + Check.True(!ServerWebOpen.FallbackToBrowser(PanelResult.UrlNotAllowed), "engine allowlist is not bypassed"); + Check.True(!ServerWebOpen.FallbackToBrowser(PanelResult.FailedAfterNavigate), "spent code -> no browser"); + Check.True(ServerWebOpen.TryGetAllowedUri("https://www.acdreamweave.com/x?a=1", Hosts, out string abs) && abs == "https://www.acdreamweave.com/x?a=1", "validated absolute uri"); + Check.True(!ServerWebOpen.TryGetAllowedUri("http://www.acdreamweave.com/", Hosts, out string none) && none.Length == 0, "refused gives no uri"); } } -- 2.43.0 From 8ceba81070925174ffbd80d6988cb35746901045 Mon Sep 17 00:00:00 2001 From: Daniel Wallace Date: Sat, 7 Nov 2026 15:46:37 -0800 Subject: [PATCH 5/6] ServerPack: ServerUsageLines, a server's own /rserver usage lines An optional hook, collected once in the constructor. ServerPackCommands.Usage appends a server's lines (trimmed, blanks dropped) after the shared two, and "/rserver help" and an unknown word print them all. A server without the hook prints exactly the two lines it always has (pinned on Coldeve). ServerProjectsTests.PluginsDir is internal so other tests can share it. Co-Authored-By: Claude Opus 5.5 --- .../Shared/ServerPack/ServerPackCommands.cs | 20 ++++++++++++++----- Plugins/Shared/ServerPack/ServerPackPlugin.cs | 16 ++++++++++++--- .../ServerPackCommandsTests.cs | 20 +++++++++++++++++++ .../ServerProjectsTests.cs | 2 +- 4 files changed, 49 insertions(+), 9 deletions(-) diff --git a/Plugins/Shared/ServerPack/ServerPackCommands.cs b/Plugins/Shared/ServerPack/ServerPackCommands.cs index 8cdd6c0..d258f2f 100644 --- a/Plugins/Shared/ServerPack/ServerPackCommands.cs +++ b/Plugins/Shared/ServerPack/ServerPackCommands.cs @@ -46,12 +46,22 @@ internal static class ServerPackCommands /// "/rserver [show|hide|toggle]": the window after it. public static string Window(string serverName, bool shown) => CommandReply.Shown($"The {serverName} window", shown); - /// The usage, two lines. - public static string[] Usage(string serverName) => new[] + /// + /// The usage: two lines, then the server's own (ServerUsageLines), if any. With none, the two lines are + /// exactly what every server plugin has always printed. + /// + public static string[] Usage(string serverName, IReadOnlyList? serverLines = null) { - $"/rserver [show|hide|toggle] - the {serverName} server card (also in the Mini Remote's Char section).", - $"/rserver info - what is known about {serverName}; /rserver auto|on|off - this character's override.", - }; + var lines = new List + { + $"/rserver [show|hide|toggle] - the {serverName} server card (also in the Mini Remote's Char section).", + $"/rserver info - what is known about {serverName}; /rserver auto|on|off - this character's override.", + }; + if (serverLines != null) + foreach (string l in serverLines) + if (!string.IsNullOrWhiteSpace(l)) lines.Add(l.Trim()); + return lines.ToArray(); + } public static string Unknown(string word) => $"Unknown '/rserver {word}'."; } diff --git a/Plugins/Shared/ServerPack/ServerPackPlugin.cs b/Plugins/Shared/ServerPack/ServerPackPlugin.cs index d2f1a96..a30ac23 100644 --- a/Plugins/Shared/ServerPack/ServerPackPlugin.cs +++ b/Plugins/Shared/ServerPack/ServerPackPlugin.cs @@ -32,6 +32,7 @@ // SetProfileValue(key, n) a live number in its "RynthServer.Profile" ("values"), for other // plugins that apply a server rule without knowing the server. // ServerCommandVerbs(list) its own "/rserver " words, handled in ServerChatCommand. +// ServerUsageLines(add) the usage lines for those words, after the shared two (help, unknown word). // RunOnTick(action) work for the next tick (a page's button, on the render thread). // ServerCardActions() the server's own buttons at the top of its card, under RynthCore's verdict // (render thread: ImGui calls only; queue work with RunOnTick). @@ -87,6 +88,8 @@ public sealed partial class ServerPackPlugin : RynthPluginBase private readonly ConcurrentQueue _tickActions = new(); // The server's own "/rserver" verbs (ServerCommandVerbs). private readonly HashSet _serverVerbs = new(StringComparer.OrdinalIgnoreCase); + // The server's own "/rserver" usage lines (ServerUsageLines), after the shared two. + private readonly List _usageLines = new(); private volatile bool _loginComplete; private volatile string? _world; private bool _wasActive; @@ -104,6 +107,7 @@ public sealed partial class ServerPackPlugin : RynthPluginBase var verbs = new List(); ServerCommandVerbs(verbs); foreach (string v in verbs) if (!string.IsNullOrWhiteSpace(v)) _serverVerbs.Add(v.Trim()); + ServerUsageLines(_usageLines.Add); _ui = new ServerPackUi(_model, RynthPluginInfo.Name + " " + Marshal.PtrToStringAnsi(VersionPointer), () => _world, _pages, DrawCardActions); } @@ -135,6 +139,11 @@ public sealed partial class ServerPackPlugin : RynthPluginBase /// instead of being read as another server's id. Called once, from the constructor. /// partial void ServerCommandVerbs(List verbs); + /// + /// Usage lines for the server's own verbs, printed after the shared two by "/rserver help" and an + /// unknown word. Called once, from the constructor (no Host yet). + /// + partial void ServerUsageLines(Action add); /// Extra lines for "/rserver info". partial void ServerInfoLines(Action line); /// The server's own pages (ServerPackPages.cs). Called once, from the constructor (no Host yet). @@ -475,9 +484,10 @@ public sealed partial class ServerPackPlugin : RynthPluginBase bool handled = false; ServerChatCommand(parts, ref handled); if (handled) return; - if (verb == ServerVerb.Unknown) Reply.Fail(ServerPackCommands.Unknown(parts[1]) + " " + ServerPackCommands.Usage(Info.Name)[0]); - else ChatLine(ServerPackCommands.Usage(Info.Name)[0]); - ChatLine(ServerPackCommands.Usage(Info.Name)[1]); + string[] usage = ServerPackCommands.Usage(Info.Name, _usageLines); + if (verb == ServerVerb.Unknown) Reply.Fail(ServerPackCommands.Unknown(parts[1]) + " " + usage[0]); + else ChatLine(usage[0]); + for (int i = 1; i < usage.Length; i++) ChatLine(usage[i]); } private void PrintInfo() diff --git a/Tools/RynthServerPack.Tests/ServerPackCommandsTests.cs b/Tools/RynthServerPack.Tests/ServerPackCommandsTests.cs index 7ab9644..7a50db9 100644 --- a/Tools/RynthServerPack.Tests/ServerPackCommandsTests.cs +++ b/Tools/RynthServerPack.Tests/ServerPackCommandsTests.cs @@ -1,5 +1,6 @@ using System; using System.Collections.Generic; +using System.Linq; using RynthCore.Plugin.ServerPack; using RynthCore.Plugin.Shared; using RynthCore.RynthAiTests.Harness; @@ -50,6 +51,25 @@ internal static class ServerPackCommandsTests Check.Eq(usage.Length, 2, "two usage lines"); Check.True(usage[0].Contains("/rserver [show|hide|toggle]") && usage[1].Contains("/rserver auto|on|off"), "the usage names every verb"); Check.Eq(ServerPackCommands.Unknown("wobble"), "Unknown '/rserver wobble'.", "an unknown word"); + + // A server without ServerUsageLines (Coldeve) prints exactly the two shared lines, byte for byte. + string[] pinned = + { + "/rserver [show|hide|toggle] - the Coldeve server card (also in the Mini Remote's Char section).", + "/rserver info - what is known about Coldeve; /rserver auto|on|off - this character's override.", + }; + Check.Eq(string.Join("\n", usage), string.Join("\n", pinned), "hookless usage is unchanged"); + Check.Eq(string.Join("\n", ServerPackCommands.Usage("Coldeve", new List())), string.Join("\n", pinned), "no own lines: unchanged"); + Check.Eq(string.Join("\n", ServerPackCommands.Usage("Coldeve", new List { "", " " })), string.Join("\n", pinned), "blank own lines are dropped"); + string coldeve = string.Join("\n", System.IO.Directory.GetFiles(System.IO.Path.Combine(ServerProjectsTests.PluginsDir(), "RynthCore.Plugin.RynthColdeve"), "*.cs", System.IO.SearchOption.AllDirectories) + .Where(f => !f.Contains("\\obj\\") && !f.Contains("\\bin\\")).Select(System.IO.File.ReadAllText)); + Check.False(coldeve.Contains("ServerUsageLines", StringComparison.Ordinal), "Coldeve has no ServerUsageLines (so the pin above is what it prints)"); + + // A server's own lines follow the shared two, which stay first and unchanged. + string[] own = ServerPackCommands.Usage("Coldeve", new List { " /rserver x - one more line " }); + 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"); } private static void Queue() diff --git a/Tools/RynthServerPack.Tests/ServerProjectsTests.cs b/Tools/RynthServerPack.Tests/ServerProjectsTests.cs index 621b92c..7e8468b 100644 --- a/Tools/RynthServerPack.Tests/ServerProjectsTests.cs +++ b/Tools/RynthServerPack.Tests/ServerProjectsTests.cs @@ -35,7 +35,7 @@ internal static class ServerProjectsTests "levistras", }; - private static string PluginsDir() + internal static string PluginsDir() { string? dir = AppContext.BaseDirectory; while (dir != null && !Directory.Exists(Path.Combine(dir, "Plugins", "Shared", "ServerPack"))) -- 2.43.0 From 8dda4fdf96e512d0239415dd2d7292ae848a87fd Mon Sep 17 00:00:00 2001 From: Daniel Wallace Date: Sat, 7 Nov 2026 15:45:18 -0800 Subject: [PATCH 6/6] ServerPack web open: a request never prints its URL; Windows error wording WebOpenRequest is a record, so its generated ToString printed the URL, which can carry a one-time code. It now names the title only. The browser failure reads "Couldn't open your browser (Windows error N)." Co-Authored-By: Claude Opus 5.5 --- Plugins/Shared/ServerPack/ServerPackWeb.cs | 4 ++-- Plugins/Shared/ServerPack/ServerWebOpen.cs | 10 ++++++++-- .../RynthServerPack.Tests/ServerWebOpenTests.cs | 16 ++++++++++++++++ 3 files changed, 26 insertions(+), 4 deletions(-) diff --git a/Plugins/Shared/ServerPack/ServerPackWeb.cs b/Plugins/Shared/ServerPack/ServerPackWeb.cs index cabecd7..d2ee718 100644 --- a/Plugins/Shared/ServerPack/ServerPackWeb.cs +++ b/Plugins/Shared/ServerPack/ServerPackWeb.cs @@ -70,12 +70,12 @@ public sealed partial class ServerPackPlugin { long code = ShellExecuteW(IntPtr.Zero, "open", url, null, null, 1).ToInt64(); ok = code > 32; - message = ok ? "Opened in your browser." : $"Couldn't open your browser (code {code})."; + message = ok ? "Opened in your browser." : $"Couldn't open your browser (Windows error {code})."; } catch (Exception) { ok = false; - message = "Couldn't open your browser (code 0)."; + message = "Couldn't open your browser (Windows error 0)."; } Finish(done, new WebOpenOutcome(WebOpenRoute.Browser, ok, message)); }) diff --git a/Plugins/Shared/ServerPack/ServerWebOpen.cs b/Plugins/Shared/ServerPack/ServerWebOpen.cs index 7b0392c..760c526 100644 --- a/Plugins/Shared/ServerPack/ServerWebOpen.cs +++ b/Plugins/Shared/ServerPack/ServerWebOpen.cs @@ -7,8 +7,14 @@ using System.Collections.Generic; namespace RynthCore.Plugin.ServerPack; -/// A page to open. The URL comes from constants in the plugin, never from chat. -internal sealed record WebOpenRequest(string Url, IReadOnlyList AllowedHosts, string ProfileKey, string Title); +/// +/// A page to open. The URL comes from constants in the plugin, never from chat, but it may carry a +/// one-time code, so ToString names the title only (a record's generated ToString would print the URL). +/// +internal sealed record WebOpenRequest(string Url, IReadOnlyList AllowedHosts, string ProfileKey, string Title) +{ + public override string ToString() => "WebOpenRequest(" + Title + ")"; +} internal enum WebOpenRoute { Panel, Browser, Refused } diff --git a/Tools/RynthServerPack.Tests/ServerWebOpenTests.cs b/Tools/RynthServerPack.Tests/ServerWebOpenTests.cs index 25ffd9e..a17c88f 100644 --- a/Tools/RynthServerPack.Tests/ServerWebOpenTests.cs +++ b/Tools/RynthServerPack.Tests/ServerWebOpenTests.cs @@ -10,12 +10,28 @@ internal static class ServerWebOpenTests public static void Register(Runner r) { r.Add("web open: only https on an allowed host, and the route follows the engine", Rules); + r.Add("web open: a request never prints its URL, and the browser's error says Windows", NoUrlInText); } private static readonly string[] Hosts = { "www.acdreamweave.com" }; private static readonly string[] Wild = { "*.acdreamweave.com" }; private const string Key = "dreamweave/0123456789abcdef0123456789abcdef"; + private static void NoUrlInText() + { + const string secret = "AbCdEfGhIjKlMnOpQrStUvWxYz0123456789-_AbCde"; + var r = new WebOpenRequest("https://www.acdreamweave.com/launch?code=" + secret + "&to=%2Fmarket", Hosts, Key, "DreamWeave"); + Check.Eq(r.ToString(), "WebOpenRequest(DreamWeave)", "ToString names the title only"); + Check.False(r.ToString().Contains(secret, StringComparison.Ordinal), "ToString never carries the code"); + Check.False(("" + r).Contains("acdreamweave", StringComparison.Ordinal), "nor the URL"); + Check.False((r with { Title = "x" }).ToString().Contains(secret, StringComparison.Ordinal), "a copy neither"); + + string web = System.IO.File.ReadAllText(System.IO.Path.Combine(ServerProjectsTests.PluginsDir(), "Shared", "ServerPack", "ServerPackWeb.cs")); + Check.True(web.Contains("$\"Couldn't open your browser (Windows error {code}).\"", StringComparison.Ordinal), "the browser failure names the Windows error"); + Check.True(web.Contains("\"Couldn't open your browser (Windows error 0).\"", StringComparison.Ordinal), "and its exception path"); + Check.False(web.Contains("(code ", StringComparison.Ordinal), "the old \"(code N)\" wording is gone"); + } + private static void Rules() { Check.True(ServerWebOpen.IsAllowedUrl("https://www.acdreamweave.com/x", Hosts), "https on the host"); -- 2.43.0