From e81076f33c39f7c48246f87f2076e9df89b96059 Mon Sep 17 00:00:00 2001 From: "OpenGenesis (EULA)" <153564363+opengenesislink@users.noreply.github.com> Date: Sun, 22 Nov 2026 21:53:26 +0100 Subject: [PATCH] feat(g1): global SYS.API alerts over signed NexBus to all simulator regions Adds a CSRF-protected admin-only alert command with severity presets and 5-second rate limit; signs a NexBus event and fans out via native IDialogModule.SendGeneralAlert across all hosted regions, including EventSim when configured. Default remains opt-in. NexVerse CI, .NET10 full build, SYS.API HTTP/HMAC tests and security contracts passed. Cross-platform builds/ROBUST boot passed; release-artifact upload remains blocked by GitHub storage quota. No production deployment. --- .github/workflows/nexjast-ci.yml | 1 + .../NodeAgent/NexVerseNodeAgentModule.cs | 45 ++++++++ addons/SysApi/SysApiConnector.cs | 27 ++++- addons/SysApi/SysApiGlobalAlert.cs | 101 ++++++++++++++++++ addons/SysApi/SysApiHost.cs | 59 +++++++++- addons/SysApi/sys.api.csproj | 1 + addons/SysApi/www/app.js | 26 +++++ addons/SysApi/www/index.html | 19 +++- addons/SysApi/www/style.css | 14 ++- bin/Robust.HG.ini | 4 + bin/Robust.HG.ini.example | 4 + bin/Robust.ini.example | 4 + .../SYS_API_GLOBAL_ALERT_GEN1_20261122.md | 43 ++++++++ tools/ci/SysApiSmoke/Program.cs | 100 ++++++++++++++++- tools/ci/verify_sysapi_global_alert.py | 62 +++++++++++ 15 files changed, 504 insertions(+), 6 deletions(-) create mode 100644 addons/SysApi/SysApiGlobalAlert.cs create mode 100644 doc/OpenGenesisLINK/SYS_API_GLOBAL_ALERT_GEN1_20261122.md create mode 100644 tools/ci/verify_sysapi_global_alert.py diff --git a/.github/workflows/nexjast-ci.yml b/.github/workflows/nexjast-ci.yml index 4f5474c5..db0fdaf2 100644 --- a/.github/workflows/nexjast-ci.yml +++ b/.github/workflows/nexjast-ci.yml @@ -977,6 +977,7 @@ jobs: set -euo pipefail python3 tools/ci/verify_sys_api_foundation.py python3 tools/ci/verify_sys_api_readmodel.py + python3 tools/ci/verify_sysapi_global_alert.py bash -n tools/ops/sys-api-tls-install.sh dotnet build addons/SysApi/sys.api.csproj --configuration Release --no-restore dotnet run --project tools/ci/SysApiSmoke/SysApiSmoke.csproj --configuration Release diff --git a/NexVerse/RegionModules/NodeAgent/NexVerseNodeAgentModule.cs b/NexVerse/RegionModules/NodeAgent/NexVerseNodeAgentModule.cs index 8205da80..3930f46a 100644 --- a/NexVerse/RegionModules/NodeAgent/NexVerseNodeAgentModule.cs +++ b/NexVerse/RegionModules/NodeAgent/NexVerseNodeAgentModule.cs @@ -93,6 +93,7 @@ namespace NexVerse.RegionModules.NodeAgent private IDisposable m_MoveRegionSubscription; private IDisposable m_RegionLifecycleSubscription; private IDisposable m_NodeControlSubscription; + private IDisposable m_AdminAlertSubscription; private IDisposable m_NodeUpdateSubscription; private IDisposable m_NodeLiveUpdateSubscription; private bool m_LiveUpdaterEnabled; @@ -348,6 +349,7 @@ namespace NexVerse.RegionModules.NodeAgent "region.control.lifecycle.requested", HandleRegionLifecycleCommand); m_NodeControlSubscription = m_Bus.Subscribe("node.control.requested", HandleNodeControlCommand); + m_AdminAlertSubscription = m_Bus.Subscribe("admin.alert.requested", HandleAdminAlert); m_NodeUpdateSubscription = m_Bus.Subscribe("node.update.stage.requested", HandleStageUpdateCommand); m_NodeLiveUpdateSubscription = m_Bus.Subscribe("node.update.live.requested", HandleLiveUpdateCommand); m_OarControlSubscription = m_Bus.Subscribe("archive.oar.requested", HandleOarCommand); @@ -408,6 +410,47 @@ namespace NexVerse.RegionModules.NodeAgent NodeData())); } + // The NexBus event is authenticated and deduplicated by the existing + // signed transport. One shared NodeAgent fans it out to every Scene in + // this simulator process, including multi-region processes. + private void HandleAdminAlert(NexEvent alert) + { + if (!m_Enabled || Volatile.Read(ref m_Stopping) != 0 || + alert == null || alert.Data == null || + !string.Equals(alert.Source, "opengenesislink.sysapi", StringComparison.Ordinal) || + !alert.Data.TryGetValue("command", out string command) || + command != "alert" || + !alert.Data.TryGetValue("administrator", out string operatorId) || + !UUID.TryParse(operatorId, out UUID administrator) || administrator == UUID.Zero || + !alert.Data.TryGetValue("message", out string message) || + string.IsNullOrWhiteSpace(message) || message.Length > 500 || + message.Any(ch => char.IsControl(ch) || ch is '\u2028' or '\u2029')) + return; + TimeSpan age = DateTimeOffset.UtcNow - alert.Timestamp; + if (age < TimeSpan.FromSeconds(-5) || age > TimeSpan.FromSeconds(30)) + return; + + int notifiedRegions = 0; + foreach (Scene scene in m_Scenes.Values) + { + try + { + IDialogModule dialog = scene.RequestModuleInterface(); + if (dialog == null) continue; + // Same viewer notification as the native console "alert". + dialog.SendGeneralAlert(message); + ++notifiedRegions; + } + catch (Exception e) + { + m_Log.WarnFormat("[NEX-ALERT] Region {0} failed for event {1} ({2})", + scene.RegionInfo.RegionID, alert.EventId, e.GetType().Name); + } + } + m_Log.InfoFormat("[NEX-ALERT] Event {0} from Sys.API broadcast to {1} local regions on node {2}", + alert.EventId, notifiedRegions, m_NodeId); + } + public void Close() { if (!m_Enabled || Interlocked.Exchange(ref m_Stopping, 1) != 0) @@ -432,6 +475,8 @@ namespace NexVerse.RegionModules.NodeAgent m_RegionLifecycleSubscription = null; m_NodeControlSubscription?.Dispose(); m_NodeControlSubscription = null; + m_AdminAlertSubscription?.Dispose(); + m_AdminAlertSubscription = null; m_NodeUpdateSubscription?.Dispose(); m_NodeUpdateSubscription = null; m_NodeLiveUpdateSubscription?.Dispose(); diff --git a/addons/SysApi/SysApiConnector.cs b/addons/SysApi/SysApiConnector.cs index dbcd5fb2..2db6feec 100644 --- a/addons/SysApi/SysApiConnector.cs +++ b/addons/SysApi/SysApiConnector.cs @@ -54,7 +54,32 @@ public sealed class SysApiConnector : ServiceConnector Log.WarnFormat("[SYS.API] Database read model unavailable ({0}); JSON data endpoints disabled.", e.GetType().Name); } - var host = new SysApiHost(port, publicOrigin, accounts, authentication, token, readModel); + // Global alerts use the pre-existing HMAC-signed NexBus. Do not + // expose arbitrary console execution or write to any simulator INI. + ISysApiAlertPublisher? alertPublisher = null; + if (cfg.GetBoolean("AlertsEnabled", false)) + { + try + { + var bus = config.Configs["NexBus"]; + if (bus?.GetBoolean("Enabled", false) != true || + string.IsNullOrWhiteSpace(bus.GetString("Peers", ""))) + throw new InvalidOperationException("Distributed NexBus with simulator peers is required"); + int robustPort = config.Configs["Const"]?.GetInt("PublicPort", 0) ?? 0; + alertPublisher = new NexBusSysApiAlertPublisher( + robustPort, + bus.GetString("InboundPath", "/internal/nexbus/v1/events"), + bus.GetString("SharedKey", "")); + } + catch (Exception ex) + { + // A missing transport must not disable the administrative API. + Log.WarnFormat("[SYS.API ALERT] Disabled: NexBus relay unavailable ({0})", + ex.GetType().Name); + } + } + var host = new SysApiHost(port, publicOrigin, accounts, authentication, token, + readModel, alertPublisher); host.Start(); _host = host; Log.InfoFormat("[SYS.API] Foundation active on loopback 127.0.0.1:{0}; public TLS proxy port 8850 requires ACME certificate.", port); diff --git a/addons/SysApi/SysApiGlobalAlert.cs b/addons/SysApi/SysApiGlobalAlert.cs new file mode 100644 index 00000000..d299275f --- /dev/null +++ b/addons/SysApi/SysApiGlobalAlert.cs @@ -0,0 +1,101 @@ +// SPDX-License-Identifier: MPL-2.0 +// Explicit "alert " command only; never execute arbitrary console text. +using System.Net; +using System.Net.Http; +using System.Text; +using System.Text.Json; +using NexVerse.Core.Messaging; +using OpenMetaverse; + +namespace OpenGenesisLINK.SysApi; + +public interface ISysApiAlertPublisher : IDisposable +{ + Task PublishAsync(string message, UUID administrator, CancellationToken cancellationToken); +} + +public static class SysApiAlertCommand +{ + public static bool TryParse(string? command, out string message) + { + message = ""; + if (command is null || command.Length > 512 || + !command.StartsWith("alert ", StringComparison.OrdinalIgnoreCase)) + return false; + + string value = command[6..].Trim(); + if (value.Length is < 1 or > 500) + return false; + foreach (char ch in value) + { + // Viewer alerts are single-line messages; avoid injected console commands. + if (char.IsControl(ch) || ch is '\u2028' or '\u2029') + return false; + } + message = value; + return true; + } +} + +/// +/// Submits one HMAC-authenticated NexBus event to the *local* ROBUST listener. +/// NexBus then forwards the same event ID to each configured simulator peer. +/// HTTP 202 means queued by ROBUST, not verified delivered to every viewer. +/// +public sealed class NexBusSysApiAlertPublisher : ISysApiAlertPublisher +{ + private readonly HttpClient _client; + private readonly Uri _localEndpoint; + private readonly string _sharedKey; + + public NexBusSysApiAlertPublisher(int localRobustPort, string inboundPath, string sharedKey) + { + if (localRobustPort is < 1 or > 65535) + throw new ArgumentOutOfRangeException(nameof(localRobustPort)); + if (inboundPath != "/internal/nexbus/v1/events") + throw new ArgumentException("Untrusted NexBus inbound path", nameof(inboundPath)); + NexBusProtocol.ValidateSharedKey(sharedKey); + _sharedKey = sharedKey; + _localEndpoint = new Uri("http://127.0.0.1:" + localRobustPort + inboundPath); + _client = new HttpClient(new HttpClientHandler + { + AllowAutoRedirect = false, + UseProxy = false + }) { Timeout = TimeSpan.FromSeconds(5) }; + } + + public async Task PublishAsync( + string message, UUID administrator, CancellationToken cancellationToken) + { + if (administrator == UUID.Zero || message.Length is < 1 or > 500) + throw new ArgumentException("Invalid alert or administrator"); + var outgoing = new NexEvent("admin.alert.requested", "opengenesislink.sysapi", + new Dictionary + { + ["command"] = "alert", + ["message"] = message, + ["administrator"] = administrator.ToString() + }); + byte[] payload = NexBusProtocol.Serialize(outgoing); + using var request = new HttpRequestMessage(HttpMethod.Post, _localEndpoint); + request.Headers.TryAddWithoutValidation("X-NexBus-Node", "SysApi"); + request.Headers.TryAddWithoutValidation("X-NexBus-Signature", + "sha256=" + NexBusProtocol.Sign(payload, _sharedKey)); + request.Content = new ByteArrayContent(payload); + request.Content.Headers.ContentType = + new System.Net.Http.Headers.MediaTypeHeaderValue("application/json"); + using HttpResponseMessage response = + await _client.SendAsync(request, cancellationToken); + if (response.StatusCode != HttpStatusCode.Accepted) + throw new InvalidOperationException("NexBus did not accept the alert"); + + using JsonDocument receipt = + JsonDocument.Parse(await response.Content.ReadAsStringAsync(cancellationToken)); + if (!receipt.RootElement.TryGetProperty("accepted", out JsonElement accepted) || + accepted.ValueKind != JsonValueKind.True) + throw new InvalidOperationException("NexBus rejected the alert"); + return outgoing.EventId; + } + + public void Dispose() => _client.Dispose(); +} diff --git a/addons/SysApi/SysApiHost.cs b/addons/SysApi/SysApiHost.cs index 2fd97745..38d08e0d 100644 --- a/addons/SysApi/SysApiHost.cs +++ b/addons/SysApi/SysApiHost.cs @@ -17,6 +17,7 @@ public sealed class SysApiHost : IDisposable private static readonly JsonSerializerOptions Json = new(JsonSerializerDefaults.Web); private readonly record struct AdminSession(UUID Avatar, string Name, string Csrf, DateTimeOffset Expires); private sealed record LoginInput(string Username, string Password); + private sealed record AlertInput(string Command); private sealed class Attempts { public int Count; public DateTimeOffset Until = DateTimeOffset.UtcNow.AddMinutes(5); } private readonly HttpListener _http = new(); @@ -26,6 +27,9 @@ public sealed class SysApiHost : IDisposable private readonly IUserAccountService _accounts; private readonly IAuthenticationService _auth; private readonly ISysApiReadModel? _readModel; + private readonly ISysApiAlertPublisher? _alertPublisher; + private readonly SemaphoreSlim _alertGate = new(1, 1); + private DateTimeOffset _lastAlertAt = DateTimeOffset.MinValue; private readonly byte[] _portalToken; private readonly Uri? _publicOrigin; private readonly string _localAuthority; @@ -34,12 +38,14 @@ public sealed class SysApiHost : IDisposable private int _disposed; public SysApiHost(int localPort, string publicOrigin, IUserAccountService accounts, - IAuthenticationService auth, string portalToken, ISysApiReadModel? readModel = null) + IAuthenticationService auth, string portalToken, ISysApiReadModel? readModel = null, + ISysApiAlertPublisher? alertPublisher = null) { if (localPort is < 1025 or > 65535) throw new ArgumentOutOfRangeException(nameof(localPort)); _accounts = accounts ?? throw new ArgumentNullException(nameof(accounts)); _auth = auth ?? throw new ArgumentNullException(nameof(auth)); _readModel = readModel; + _alertPublisher = alertPublisher; if (portalToken.Length != 128 || !portalToken.All(Uri.IsHexDigit)) throw new ArgumentException("Invalid portal token", nameof(portalToken)); _portalToken = Encoding.ASCII.GetBytes(portalToken); @@ -373,6 +379,52 @@ public sealed class SysApiHost : IDisposable { await ReplyAsync(response, 403, new { error = "CSRF protection denied" }); return; } + if (path == "/api/admin/alerts") + { + if (req.HttpMethod != "POST") + { + await ReplyAsync(response, 405, new { error = "POST required" }); return; + } + if (_alertPublisher is null) + { + await ReplyAsync(response, 503, new { error = "Global alerts require an enabled NexBus relay" }); return; + } + AlertInput? input = await ReadInput(req); + if (input is null || !SysApiAlertCommand.TryParse(input.Command, out string alertMessage)) + { + await ReplyAsync(response, 400, + new { error = "Only alert is supported (1–500 characters, one line)" }); + return; + } + await _alertGate.WaitAsync(_stop.Token); + try + { + if (DateTimeOffset.UtcNow - _lastAlertAt < TimeSpan.FromSeconds(5)) + { + await ReplyAsync(response, 429, new { error = "Bitte mindestens fünf Sekunden zwischen Alerts warten" }); + return; + } + Guid eventId; + try { eventId = await _alertPublisher.PublishAsync(alertMessage, admin.Avatar, _stop.Token); } + catch (Exception ex) when (ex is HttpRequestException or InvalidOperationException or + OperationCanceledException or JsonException) + { + Log.WarnFormat("[SYS.API ALERT] Central NexBus rejected alert ({0})", ex.GetType().Name); + await ReplyAsync(response, 503, new { error = "NexBus alert distribution unavailable" }); + return; + } + _lastAlertAt = DateTimeOffset.UtcNow; + // Audit only the event ID and administrator; do not log private message text. + Log.InfoFormat("[SYS.API ALERT] Queued global alert {0} by {1}", eventId, admin.Avatar); + await ReplyAsync(response, 202, new + { + queued = true, eventId, command = "alert", + status = "NexBus accepted; delivery to individual regions is asynchronous" + }); + } + finally { _alertGate.Release(); } + return; + } if (isGet && path == "/api/session") { await ReplyAsync(response, 200, new { user = admin.Name, @@ -402,7 +454,8 @@ public sealed class SysApiHost : IDisposable session = admin.Name, minAdminLevel = 200, oldWorldApiUnchanged = true, - endpoints = new[] { "/v1/health", "/api/v1/portal/ping", "/api/v1/portal/capabilities" } + alertsAvailable = _alertPublisher is not null, + endpoints = new[] { "/v1/health", "/api/v1/portal/ping", "/api/v1/portal/capabilities", "/api/admin/alerts" } }); return; } @@ -424,6 +477,8 @@ public sealed class SysApiHost : IDisposable _http.Stop(); _http.Close(); _sessions.Clear(); + _alertPublisher?.Dispose(); + _alertGate.Dispose(); _stop.Dispose(); } } diff --git a/addons/SysApi/sys.api.csproj b/addons/SysApi/sys.api.csproj index 1ae421b7..fd480f61 100644 --- a/addons/SysApi/sys.api.csproj +++ b/addons/SysApi/sys.api.csproj @@ -7,6 +7,7 @@ true + diff --git a/addons/SysApi/www/app.js b/addons/SysApi/www/app.js index 903e2bd1..8c984c6f 100644 --- a/addons/SysApi/www/app.js +++ b/addons/SysApi/www/app.js @@ -13,6 +13,8 @@ const view=async()=>{ const d=await json("/api/admin/overview"); $("admin-label").textContent=d.session+" · LEVEL 200+"; $("uptime").textContent=int(Math.max(0,Math.floor(d.uptimeSeconds/60)))+"m"; + $("alert-send").disabled=!d.alertsAvailable; + $("alert-status").textContent=d.alertsAvailable?"Alert-Versand bereit (ROBUST/NexBus)":"Nicht eingerichtet: [SysApi] AlertsEnabled und ein signierter NexBus mit Simulator-Peers sind erforderlich."; const info=$("diag");info.replaceChildren(); for(const [label,value,good] of [ ["System API:",d.status,true],["Eigenständige DLL:","sys.api.dll",true], @@ -34,6 +36,30 @@ $("signin").addEventListener("submit",async e=>{ catch(err){modal(err.message.includes("Access Denied")?"Access Denied":"Anmeldung fehlgeschlagen",err.message.includes("Access Denied")?"Keine Berechtigung. Für diese Verwaltung ist UserLevel 200 oder höher erforderlich.":err.message)} finally{submit.disabled=false;} }); +const renderAlertPreview=()=>{ + const kind=$("alert-level").value,body=$("alert-message").value.trim(); + $("alert-preview").textContent="alert "+kind+": "+(body||"…"); +}; +$("alert-level").addEventListener("change",renderAlertPreview); +$("alert-message").addEventListener("input",renderAlertPreview); +$("alert-form").addEventListener("submit",async event=>{ + event.preventDefault(); + const msg=$("alert-message").value.trim(),kind=$("alert-level").value; + const result=$("alert-result"),button=$("alert-send"); + if(!msg || msg.length>450 || /[\r\n\u2028\u2029]/u.test(msg)){ + result.textContent="Bitte eine einzeilige Nachricht mit höchstens 450 Zeichen eingeben.";return; + } + const command="alert "+kind+": "+msg; + if(!window.confirm("Diesen Alert wirklich an alle verbundenen Regionen senden?\n\n"+command))return; + button.disabled=true;result.textContent="Alert wird an NexBus übertragen …"; + try{ + const receipt=await json("/api/admin/alerts",{method:"POST", + headers:{"Content-Type":"application/json"},body:JSON.stringify({command})}); + result.textContent="Alert an NexBus übergeben (ID "+receipt.eventId+"). Die Zustellung an die einzelnen Simulatoren erfolgt asynchron."; + }catch(error){result.textContent="Versand nicht bestätigt: "+error.message} + finally{button.disabled=false;} +}); +renderAlertPreview(); $("signout").onclick=async()=>{try{await json("/api/session/logout",{method:"POST"})}catch{}csrf="";$("dashboard").hidden=true;$("login-shell").hidden=false}; $("refresh").onclick=()=>view().catch(e=>modal("Systemfehler",e.message)); document.querySelectorAll("nav a").forEach(a=>a.addEventListener("click",()=>document.querySelectorAll("nav a").forEach(v=>v.classList.toggle("selected",v===a)))); diff --git a/addons/SysApi/www/index.html b/addons/SysApi/www/index.html index cd2f1cac..ebb65a4b 100644 --- a/addons/SysApi/www/index.html +++ b/addons/SysApi/www/index.html @@ -35,7 +35,7 @@