ServerPack: card actions, web open, usage lines #1

Open
AwfulWaffle wants to merge 6 commits from AwfulWaffle/RynthServers:serverpack-web-open into main
12 changed files with 381 additions and 11 deletions

View file

@ -46,12 +46,22 @@ internal static class ServerPackCommands
/// <summary>"/rserver [show|hide|toggle]": the window after it.</summary> /// <summary>"/rserver [show|hide|toggle]": the window after it.</summary>
public static string Window(string serverName, bool shown) => CommandReply.Shown($"The {serverName} window", shown); public static string Window(string serverName, bool shown) => CommandReply.Shown($"The {serverName} window", shown);
/// <summary>The usage, two lines.</summary> /// <summary>
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.
/// </summary>
public static string[] Usage(string serverName, IReadOnlyList<string>? serverLines = null)
{ {
$"/rserver [show|hide|toggle] - the {serverName} server card (also in the Mini Remote's Char section).", var lines = new List<string>
$"/rserver info - what is known about {serverName}; /rserver auto|on|off - this character's override.", {
}; $"/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}'."; public static string Unknown(string word) => $"Unknown '/rserver {word}'.";
} }

View file

@ -32,7 +32,10 @@
// SetProfileValue(key, n) a live number in its "RynthServer.Profile" ("values"), for other // SetProfileValue(key, n) a live number in its "RynthServer.Profile" ("values"), for other
// plugins that apply a server rule without knowing the server. // plugins that apply a server rule without knowing the server.
// ServerCommandVerbs(list) its own "/rserver <verb>" words, handled in ServerChatCommand. // ServerCommandVerbs(list) its own "/rserver <verb>" 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). // 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); // Send(command) a chat command as if typed (pump thread, logged in only);
// LogTagged(text) the engine log, "[RynthConquest] ..."; ChatLine(text) the chat window. // LogTagged(text) the engine log, "[RynthConquest] ..."; ChatLine(text) the chat window.
// Resources\quests.<id>.csv (no code) the server's own quest list: embedded by ServerPlugin.props and // Resources\quests.<id>.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<Action> _tickActions = new(); private readonly ConcurrentQueue<Action> _tickActions = new();
// The server's own "/rserver" verbs (ServerCommandVerbs). // The server's own "/rserver" verbs (ServerCommandVerbs).
private readonly HashSet<string> _serverVerbs = new(StringComparer.OrdinalIgnoreCase); private readonly HashSet<string> _serverVerbs = new(StringComparer.OrdinalIgnoreCase);
// The server's own "/rserver" usage lines (ServerUsageLines), after the shared two.
private readonly List<string> _usageLines = new();
private volatile bool _loginComplete; private volatile bool _loginComplete;
private volatile string? _world; private volatile string? _world;
private bool _wasActive; private bool _wasActive;
@ -102,7 +107,8 @@ public sealed partial class ServerPackPlugin : RynthPluginBase
var verbs = new List<string>(); var verbs = new List<string>();
ServerCommandVerbs(verbs); ServerCommandVerbs(verbs);
foreach (string v in verbs) if (!string.IsNullOrWhiteSpace(v)) _serverVerbs.Add(v.Trim()); 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; 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. /// instead of being read as another server's id. Called once, from the constructor.
/// </summary> /// </summary>
partial void ServerCommandVerbs(List<string> verbs); partial void ServerCommandVerbs(List<string> verbs);
/// <summary>
/// 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).
/// </summary>
partial void ServerUsageLines(Action<string> add);
/// <summary>Extra lines for "/rserver info".</summary> /// <summary>Extra lines for "/rserver info".</summary>
partial void ServerInfoLines(Action<string> line); partial void ServerInfoLines(Action<string> line);
/// <summary>The server's own pages (ServerPackPages.cs). Called once, from the constructor (no Host yet).</summary> /// <summary>The server's own pages (ServerPackPages.cs). Called once, from the constructor (no Host yet).</summary>
@ -147,6 +158,10 @@ public sealed partial class ServerPackPlugin : RynthPluginBase
/// <summary>Every frame while logged in (render thread, AC's main thread; the engine's ImGui context current).</summary> /// <summary>Every frame while logged in (render thread, AC's main thread; the engine's ImGui context current).</summary>
partial void ServerRender(); partial void ServerRender();
/// <summary> /// <summary>
/// Drawn at the top of the server card, under RynthCore's verdict; render thread; queue work with RunOnTick.
/// </summary>
partial void ServerCardActions();
/// <summary>
/// An incoming chat line (pump thread, logged in only): set <paramref name="eat"/> to keep it out of /// An incoming chat line (pump thread, logged in only): set <paramref name="eat"/> to keep it out of
/// the chat window (it comes in true when an earlier plugin already ate it). /// the chat window (it comes in true when an earlier plugin already ate it).
/// </summary> /// </summary>
@ -165,6 +180,9 @@ public sealed partial class ServerPackPlugin : RynthPluginBase
/// <summary>The live numbers of the profile ("values"). Any thread.</summary> /// <summary>The live numbers of the profile ("values"). Any thread.</summary>
internal ServerProfileValues ProfileValues => _profileValues; internal ServerProfileValues ProfileValues => _profileValues;
// A delegate cannot bind an unimplemented partial method (CS0762), so the card gets this wrapper.
private void DrawCardActions() => ServerCardActions();
/// <summary>The pages this plugin draws.</summary> /// <summary>The pages this plugin draws.</summary>
internal IReadOnlyList<ServerPage> Pages => _pages; internal IReadOnlyList<ServerPage> Pages => _pages;
@ -466,9 +484,10 @@ public sealed partial class ServerPackPlugin : RynthPluginBase
bool handled = false; bool handled = false;
ServerChatCommand(parts, ref handled); ServerChatCommand(parts, ref handled);
if (handled) return; if (handled) return;
if (verb == ServerVerb.Unknown) Reply.Fail(ServerPackCommands.Unknown(parts[1]) + " " + ServerPackCommands.Usage(Info.Name)[0]); string[] usage = ServerPackCommands.Usage(Info.Name, _usageLines);
else ChatLine(ServerPackCommands.Usage(Info.Name)[0]); if (verb == ServerVerb.Unknown) Reply.Fail(ServerPackCommands.Unknown(parts[1]) + " " + usage[0]);
ChatLine(ServerPackCommands.Usage(Info.Name)[1]); else ChatLine(usage[0]);
for (int i = 1; i < usage.Length; i++) ChatLine(usage[i]);
} }
private void PrintInfo() private void PrintInfo()

View file

@ -26,6 +26,7 @@ internal sealed class ServerPackUi
private readonly Func<string?> _world; private readonly Func<string?> _world;
private readonly string _windowTitle; private readonly string _windowTitle;
private readonly IReadOnlyList<ServerPage> _pages; private readonly IReadOnlyList<ServerPage> _pages;
private readonly Action? _cardActions;
private string _status = string.Empty; private string _status = string.Empty;
/// <summary>The standalone window is open ("/rserver").</summary> /// <summary>The standalone window is open ("/rserver").</summary>
@ -34,12 +35,14 @@ internal sealed class ServerPackUi
/// <param name="pluginLabel">"RynthColdeve 0.1.0", for the title and the card.</param> /// <param name="pluginLabel">"RynthColdeve 0.1.0", for the title and the card.</param>
/// <param name="world">The world name the client reports now (null when unknown).</param> /// <param name="world">The world name the client reports now (null when unknown).</param>
/// <param name="pages">The server's own pages: tabs of the window after the card.</param> /// <param name="pages">The server's own pages: tabs of the window after the card.</param>
public ServerPackUi(ServerPackModel model, string pluginLabel, Func<string?> world, IReadOnlyList<ServerPage>? pages = null) /// <param name="cardActions">The server's own buttons, drawn under the verdict (render thread); null when it has none.</param>
public ServerPackUi(ServerPackModel model, string pluginLabel, Func<string?> world, IReadOnlyList<ServerPage>? pages = null, Action? cardActions = null)
{ {
_model = model; _model = model;
_pluginLabel = pluginLabel; _pluginLabel = pluginLabel;
_world = world; _world = world;
_pages = pages ?? Array.Empty<ServerPage>(); _pages = pages ?? Array.Empty<ServerPage>();
_cardActions = cardActions;
_windowTitle = model.Info.Name + " server (" + pluginLabel + ")##server_" + model.Info.Id; _windowTitle = model.Info.Name + " server (" + pluginLabel + ")##server_" + model.Info.Id;
} }
@ -82,6 +85,7 @@ internal sealed class ServerPackUi
{ {
ServerPackInfo info = _model.Info; ServerPackInfo info = _model.Info;
RenderVerdict(info); RenderVerdict(info);
_cardActions?.Invoke();
ImGui.Separator(); ImGui.Separator();
RenderFacts(info); RenderFacts(info);
if (info.Commands.Length > 0) if (info.Commands.Length > 0)

View file

@ -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<WebOpenOutcome> done, WebOpenOutcome outcome)
{
try { done(outcome); } catch { }
}
/// <summary>Opens the page (pump thread). `done` gets the route taken and a message without the URL.</summary>
internal void OpenWeb(WebOpenRequest r, Action<WebOpenOutcome> 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();
}
/// <summary>Closes the engine's web panel if this plugin opened one. Nothing to close until the panel API is wired.</summary>
internal void CloseWeb()
{
}
}

View file

@ -67,6 +67,9 @@
<Compile Include="$(RynthSuiteRoot)Plugins\Shared\RynthServerQuestPackApi.cs" Link="Shared\RynthServerQuestPackApi.cs" /> <Compile Include="$(RynthSuiteRoot)Plugins\Shared\RynthServerQuestPackApi.cs" Link="Shared\RynthServerQuestPackApi.cs" />
<Compile Include="$(MSBuildThisFileDirectory)ServerPackQuestPack.cs" Link="ServerPack\ServerPackQuestPack.cs" /> <Compile Include="$(MSBuildThisFileDirectory)ServerPackQuestPack.cs" Link="ServerPack\ServerPackQuestPack.cs" />
<Compile Include="$(MSBuildThisFileDirectory)ServerPackInterface.cs" Link="ServerPack\ServerPackInterface.cs" /> <Compile Include="$(MSBuildThisFileDirectory)ServerPackInterface.cs" Link="ServerPack\ServerPackInterface.cs" />
<!-- Open a web page in the engine's panel, else the browser (allowlisted https only). -->
<Compile Include="$(MSBuildThisFileDirectory)ServerWebOpen.cs" Link="ServerPack\ServerWebOpen.cs" />
<Compile Include="$(MSBuildThisFileDirectory)ServerPackWeb.cs" Link="ServerPack\ServerPackWeb.cs" />
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>

View file

@ -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;
/// <summary>
/// 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).
/// </summary>
internal sealed record WebOpenRequest(string Url, IReadOnlyList<string> AllowedHosts, string ProfileKey, string Title)
{
public override string ToString() => "WebOpenRequest(" + Title + ")";
}
internal enum WebOpenRoute { Panel, Browser, Refused }
/// <summary>What the engine's panel did. Only a refusal before navigating may fall back to the browser.</summary>
internal enum PanelResult { Opened, RefusedBeforeNavigate, UrlNotAllowed, FailedAfterNavigate }
/// <summary>What happened. The message never contains the URL.</summary>
internal sealed record WebOpenOutcome(WebOpenRoute Route, bool Ok, string Message);
internal static class ServerWebOpen
{
/// <summary>
/// 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.
/// </summary>
public static bool IsAllowedUrl(string? url, IReadOnlyList<string> allowedHosts)
=> TryGetAllowedUri(url, allowedHosts, out _);
/// <summary>The same check, giving the validated absolute URI (what the browser should be handed).</summary>
public static bool TryGetAllowedUri(string? url, IReadOnlyList<string> 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<string> 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;
}
/// <summary>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.</summary>
public static bool FallbackToBrowser(PanelResult r) => r == PanelResult.RefusedBeforeNavigate;
/// <summary>^[a-z0-9-]{1,32}/[0-9a-f]{32}$ - the engine's panel profile key (server/token).</summary>
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;
}
/// <summary>Refused if the URL is not allowed; Browser if there is no panel or no valid key; else Panel.</summary>
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;
}
}

View file

@ -22,6 +22,7 @@ internal static class Program
ServerPackCommandsTests.Register(runner); ServerPackCommandsTests.Register(runner);
DreamWeaveSkillsTests.Register(runner); DreamWeaveSkillsTests.Register(runner);
DreamWeaveTests.Register(runner); DreamWeaveTests.Register(runner);
ServerWebOpenTests.Register(runner);
return runner.Run("RynthServerPack tests", args.Length > 0 ? args[0] : null); return runner.Run("RynthServerPack tests", args.Length > 0 ? args[0] : null);
} }
} }

View file

@ -32,6 +32,8 @@
<!-- "/rserver" words and answers (2026-10-28) and the shared reply queue. --> <!-- "/rserver" words and answers (2026-10-28) and the shared reply queue. -->
<Compile Include="..\..\Plugins\Shared\ServerPack\ServerPackCommands.cs" Link="Plugin\ServerPackCommands.cs" /> <Compile Include="..\..\Plugins\Shared\ServerPack\ServerPackCommands.cs" Link="Plugin\ServerPackCommands.cs" />
<Compile Include="$(RynthSuiteRoot)Plugins\Shared\CommandReply.cs" Link="Shared\CommandReply.cs" /> <Compile Include="$(RynthSuiteRoot)Plugins\Shared\CommandReply.cs" Link="Shared\CommandReply.cs" />
<!-- The web opener's pure rules (allowlist, route). -->
<Compile Include="..\..\Plugins\Shared\ServerPack\ServerWebOpen.cs" Link="Plugin\ServerWebOpen.cs" />
<!-- RynthConquest's own features (pure parts) and the RynthOracle sources it links. --> <!-- RynthConquest's own features (pure parts) and the RynthOracle sources it links. -->
<Compile Include="..\..\Plugins\RynthCore.Plugin.RynthConquest\Conquest\ConquestData.cs" Link="Conquest\ConquestData.cs" /> <Compile Include="..\..\Plugins\RynthCore.Plugin.RynthConquest\Conquest\ConquestData.cs" Link="Conquest\ConquestData.cs" />
<Compile Include="..\..\Plugins\RynthCore.Plugin.RynthConquest\Conquest\ConquestFeature.cs" Link="Conquest\ConquestFeature.cs" /> <Compile Include="..\..\Plugins\RynthCore.Plugin.RynthConquest\Conquest\ConquestFeature.cs" Link="Conquest\ConquestFeature.cs" />

View file

@ -1,5 +1,6 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq;
using RynthCore.Plugin.ServerPack; using RynthCore.Plugin.ServerPack;
using RynthCore.Plugin.Shared; using RynthCore.Plugin.Shared;
using RynthCore.RynthAiTests.Harness; using RynthCore.RynthAiTests.Harness;
@ -50,6 +51,25 @@ internal static class ServerPackCommandsTests
Check.Eq(usage.Length, 2, "two usage lines"); 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.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"); 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>())), string.Join("\n", pinned), "no own lines: unchanged");
Check.Eq(string.Join("\n", ServerPackCommands.Usage("Coldeve", new List<string> { "", " " })), 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<string> { " /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() private static void Queue()

View file

@ -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: 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: 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 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() internal static string TempDir()
@ -199,4 +200,45 @@ internal static class ServerPackHooksTests
req.Clear(); req.Clear();
Check.False(req.Awaiting(1001), "cleared"); 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");
}
} }

View file

@ -35,7 +35,7 @@ internal static class ServerProjectsTests
"levistras", "levistras",
}; };
private static string PluginsDir() internal static string PluginsDir()
{ {
string? dir = AppContext.BaseDirectory; string? dir = AppContext.BaseDirectory;
while (dir != null && !Directory.Exists(Path.Combine(dir, "Plugins", "Shared", "ServerPack"))) while (dir != null && !Directory.Exists(Path.Combine(dir, "Plugins", "Shared", "ServerPack")))

View file

@ -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");
}
}