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 f1f30c3..a30ac23 100644
--- a/Plugins/Shared/ServerPack/ServerPackPlugin.cs
+++ b/Plugins/Shared/ServerPack/ServerPackPlugin.cs
@@ -32,7 +32,10 @@
// 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).
// 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
@@ -85,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;
@@ -102,7 +107,8 @@ 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);
+ ServerUsageLines(_usageLines.Add);
+ _ui = new ServerPackUi(_model, RynthPluginInfo.Name + " " + Marshal.PtrToStringAnsi(VersionPointer), () => _world, _pages, DrawCardActions);
}
internal ServerPackInfo Info => _model.Info;
@@ -133,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).
@@ -147,6 +158,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 +180,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;
@@ -466,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/Plugins/Shared/ServerPack/ServerPackUi.cs b/Plugins/Shared/ServerPack/ServerPackUi.cs
index f1a65da..1df73e6 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);
+ _cardActions?.Invoke();
ImGui.Separator();
RenderFacts(info);
if (info.Commands.Length > 0)
diff --git a/Plugins/Shared/ServerPack/ServerPackWeb.cs b/Plugins/Shared/ServerPack/ServerPackWeb.cs
new file mode 100644
index 0000000..d2ee718
--- /dev/null
+++ b/Plugins/Shared/ServerPack/ServerPackWeb.cs
@@ -0,0 +1,93 @@
+// 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);
+
+ // Seam for the engine's web panel (a stub until the engine API is wired).
+ private bool PanelAvailable => false;
+
+ private PanelResult TryOpenPanel(WebOpenRequest r) => PanelResult.RefusedBeforeNavigate;
+
+ private static void Finish(Action done, WebOpenOutcome outcome)
+ {
+ try { done(outcome); } catch { }
+ }
+
+ /// 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)
+ {
+ 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)
+ {
+ PanelResult result;
+ try { result = TryOpenPanel(r); }
+ catch (Exception) { result = PanelResult.RefusedBeforeNavigate; }
+
+ if (result == PanelResult.Opened)
+ {
+ Finish(done, new WebOpenOutcome(WebOpenRoute.Panel, true, "Opened in the web panel."));
+ return;
+ }
+ 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");
+ }
+
+ 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;
+ 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 (Windows error {code}).";
+ }
+ catch (Exception)
+ {
+ ok = false;
+ message = "Couldn't open your browser (Windows error 0).";
+ }
+ Finish(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..760c526
--- /dev/null
+++ b/Plugins/Shared/ServerPack/ServerWebOpen.cs
@@ -0,0 +1,104 @@
+// 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, 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 }
+
+/// 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);
+
+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)
+ => 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)
+ {
+ 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;
+ }
+
+ /// 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)
+ {
+ 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/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/ServerPackHooksTests.cs b/Tools/RynthServerPack.Tests/ServerPackHooksTests.cs
index 66de8ea..0ef0c2a 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,45 @@ 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?.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");
+ }
}
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")))
diff --git a/Tools/RynthServerPack.Tests/ServerWebOpenTests.cs b/Tools/RynthServerPack.Tests/ServerWebOpenTests.cs
new file mode 100644
index 0000000..a17c88f
--- /dev/null
+++ b/Tools/RynthServerPack.Tests/ServerWebOpenTests.cs
@@ -0,0 +1,72 @@
+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);
+ 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");
+ 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");
+
+ 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");
+ }
+}