Files
opengenesislinkserver/addons/SysApi/SysApiHost.cs
T

966 lines
49 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// SPDX-License-Identifier: MPL-2.0
using System.Collections.Concurrent;
using System.Net;
using System.Security.Cryptography;
using System.Text;
using System.Text.Json;
using log4net;
using OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Services.Interfaces;
namespace OpenGenesisLINK.SysApi;
public sealed class SysApiHost : IDisposable
{
private static readonly ILog Log = LogManager.GetLogger(typeof(SysApiHost));
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 record ViewerRestrictionInput(string Name, string? Reason);
private sealed record GridRestrictionInput(string Grid, string? Reason);
private sealed record CitizenRulesPublishInput(string Version, string Url, string Sha256);
private sealed record AdminNoteInput(string Note);
private sealed class Attempts { public int Count; public DateTimeOffset Until = DateTimeOffset.UtcNow.AddMinutes(5); }
private readonly HttpListener _http = new();
private readonly CancellationTokenSource _stop = new();
private readonly ConcurrentDictionary<string, AdminSession> _sessions = new();
private readonly ConcurrentDictionary<string, Attempts> _attempts = new();
private readonly IUserAccountService _accounts;
private readonly IAuthenticationService _auth;
private readonly ISysApiReadModel? _readModel;
private readonly ISysApiAlertPublisher? _alertPublisher;
private readonly SysApiNvMoney? _nvMoney;
private readonly SemaphoreSlim _alertGate = new(1, 1);
private DateTimeOffset _lastAlertAt = DateTimeOffset.MinValue;
private readonly ISysApiAccessPolicyStore? _accessPolicy;
private readonly SysApiResidentGateway? _residents;
private readonly ISysApiAdminData? _adminData;
private readonly byte[] _policyReadToken;
private readonly byte[] _portalToken;
private readonly Uri? _publicOrigin;
private readonly string _localAuthority;
private readonly DateTimeOffset _startup = DateTimeOffset.UtcNow;
private Task? _listenerTask;
private int _disposed;
public SysApiHost(int localPort, string publicOrigin, IUserAccountService accounts,
IAuthenticationService auth, string portalToken, ISysApiReadModel? readModel = null,
ISysApiAccessPolicyStore? accessPolicy = null, string policyReadToken = "",
SysApiResidentGateway? residents = null,
ISysApiAdminData? adminData = null,
ISysApiAlertPublisher? alertPublisher = null,
SysApiNvMoney? nvMoney = 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;
_accessPolicy = accessPolicy;
_residents = residents;
_adminData = adminData;
_alertPublisher = alertPublisher;
_nvMoney = nvMoney;
_policyReadToken = policyReadToken.Length >= 32 && policyReadToken.Length <= 128 &&
policyReadToken.All(Uri.IsHexDigit) ? Encoding.ASCII.GetBytes(policyReadToken) : Array.Empty<byte>();
if (portalToken.Length != 128 || !portalToken.All(Uri.IsHexDigit))
throw new ArgumentException("Invalid portal token", nameof(portalToken));
_portalToken = Encoding.ASCII.GetBytes(portalToken);
_localAuthority = "127.0.0.1:" + localPort;
if (publicOrigin.Length != 0)
{
if (!Uri.TryCreate(publicOrigin, UriKind.Absolute, out var address) ||
address.Scheme != Uri.UriSchemeHttps || address.AbsolutePath != "/" ||
address.UserInfo.Length != 0 || address.Query.Length != 0 || address.Fragment.Length != 0)
throw new ArgumentException("PublicOrigin must be an HTTPS origin without path or query");
_publicOrigin = address;
}
// Public port 8850 is reserved for HTTPS termination via an ACME-provisioned proxy.
// Never bind the internal module directly to the public interface.
_http.Prefixes.Add($"http://127.0.0.1:{localPort}/");
}
public void Start()
{
_http.Start();
_listenerTask = Task.Run(ServeAsync);
}
private async Task ServeAsync()
{
while (!_stop.IsCancellationRequested)
{
HttpListenerContext request;
try { request = await _http.GetContextAsync(); }
catch (Exception e) when (e is HttpListenerException or ObjectDisposedException) { break; }
_ = Task.Run(() => HandleAsync(request));
}
}
private static string RandomSecret() => Convert.ToHexString(RandomNumberGenerator.GetBytes(32)).ToLowerInvariant();
private static void SecurityHeaders(HttpListenerResponse r)
{
r.Headers["X-Content-Type-Options"] = "nosniff";
r.Headers["Referrer-Policy"] = "no-referrer";
r.Headers["X-Frame-Options"] = "DENY";
r.Headers["Cache-Control"] = "no-store, private";
r.Headers["Content-Security-Policy"] = "default-src 'none'; img-src 'self' data:; " +
"script-src 'self'; worker-src 'self'; manifest-src 'self'; style-src 'self'; connect-src 'self'; form-action 'self'; " +
"frame-ancestors 'none'; base-uri 'none'; object-src 'none'";
}
private bool IsTrustedProxy(HttpListenerRequest req) =>
_publicOrigin is not null &&
IPAddress.IsLoopback(req.RemoteEndPoint?.Address ?? IPAddress.None) &&
string.Equals(req.Headers["Host"], _localAuthority, StringComparison.OrdinalIgnoreCase) &&
string.Equals(req.Headers["X-Forwarded-Proto"], "https", StringComparison.OrdinalIgnoreCase) &&
string.Equals(req.Headers["X-Forwarded-Host"], _publicOrigin.Authority, StringComparison.OrdinalIgnoreCase);
private bool SameOrigin(HttpListenerRequest req)
{
string origin = req.Headers["Origin"] ?? "";
string fetchSite = req.Headers["Sec-Fetch-Site"] ?? "";
if (fetchSite.Length > 0 && fetchSite is not ("same-origin" or "none")) return false;
if (origin.Length == 0) return true;
if (!Uri.TryCreate(origin, UriKind.Absolute, out Uri? parsed)) return false;
bool direct = parsed.Scheme == "http" &&
string.Equals(parsed.Authority, _localAuthority, StringComparison.OrdinalIgnoreCase);
bool proxy = IsTrustedProxy(req) && string.Equals(
parsed.GetLeftPart(UriPartial.Authority),
_publicOrigin!.GetLeftPart(UriPartial.Authority),
StringComparison.OrdinalIgnoreCase);
return direct || proxy;
}
private bool HasPortalToken(HttpListenerRequest req)
{
string header = req.Headers["Authorization"] ?? "";
if (!header.StartsWith("Bearer ", StringComparison.Ordinal) || header.Length != 135)
return false;
return CryptographicOperations.FixedTimeEquals(
Encoding.ASCII.GetBytes(header[7..]), _portalToken);
}
private bool HasPolicyReaderToken(HttpListenerRequest req)
{
string header = req.Headers["Authorization"] ?? "";
return _policyReadToken.Length >= 32 && header.StartsWith("Bearer ", StringComparison.Ordinal) &&
header.Length == _policyReadToken.Length + 7 &&
CryptographicOperations.FixedTimeEquals(Encoding.ASCII.GetBytes(header[7..]), _policyReadToken);
}
private bool TryAdmin(HttpListenerRequest req, out AdminSession s)
{
s = default;
string? sid = req.Cookies["ogl_sysapi"]?.Value;
if (sid is null || !_sessions.TryGetValue(sid, out var candidate)) return false;
if (candidate.Expires < DateTimeOffset.UtcNow) { _sessions.TryRemove(sid, out _); return false; }
try
{
var account = _accounts.GetUserAccount(UUID.Zero, candidate.Avatar);
if (account is null || account.UserLevel < 200 || !account.LoginAllowed)
{
_sessions.TryRemove(sid, out _);
return false;
}
}
catch (Exception ex) { Log.Warn("[SYS.API] Session authorization unavailable", ex); return false; }
s = candidate;
return true;
}
private static async Task<T?> ReadInput<T>(HttpListenerRequest req) where T : class
{
if (req.ContentLength64 > 16384 ||
!(req.ContentType?.StartsWith("application/json", StringComparison.OrdinalIgnoreCase) ?? false))
return null;
using var ms = new MemoryStream();
byte[] buffer = new byte[4096];
int n;
while ((n = await req.InputStream.ReadAsync(buffer)) > 0)
{
if (ms.Length + n > 16384) return null;
ms.Write(buffer.AsSpan(0, n));
}
try { return JsonSerializer.Deserialize<T>(ms.ToArray(), Json); }
catch (JsonException) { return null; }
}
private static async Task ReplyAsync(HttpListenerResponse r, int status, object data)
{
r.StatusCode = status;
r.ContentType = "application/json; charset=utf-8";
byte[] bytes = JsonSerializer.SerializeToUtf8Bytes(data, Json);
r.ContentLength64 = bytes.Length;
await r.OutputStream.WriteAsync(bytes);
}
private static async Task AssetAsync(HttpListenerResponse r, string suffix, string mime)
{
var asm = typeof(SysApiHost).Assembly;
string? name = asm.GetManifestResourceNames().FirstOrDefault(x =>
x.EndsWith(".www." + suffix, StringComparison.Ordinal));
if (name is null) { r.StatusCode = 404; return; }
using var content = asm.GetManifestResourceStream(name);
if (content is null) { r.StatusCode = 404; return; }
r.ContentType = mime;
r.ContentLength64 = content.Length;
await content.CopyToAsync(r.OutputStream);
}
private async Task LoginAsync(HttpListenerContext context)
{
var req = context.Request;
var data = await ReadInput<LoginInput>(req);
if (data is null || string.IsNullOrWhiteSpace(data.Username) ||
string.IsNullOrWhiteSpace(data.Password) || data.Username.Length > 128 || data.Password.Length > 1024)
{
await ReplyAsync(context.Response, 400, new { error = "Invalid login request" });
return;
}
string key = data.Username.Trim().ToLowerInvariant();
Attempts throttle = _attempts.GetOrAdd(key, _ => new Attempts());
lock (throttle)
{
if (DateTimeOffset.UtcNow > throttle.Until)
{
throttle.Count = 0;
throttle.Until = DateTimeOffset.UtcNow.AddMinutes(5);
}
if (++throttle.Count > 8)
{
context.Response.StatusCode = 429;
return;
}
}
string[] parts = data.Username.Replace('.', ' ')
.Split(' ', 2, StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries);
if (parts.Length != 2)
{
await ReplyAsync(context.Response, 401, new { error = "Anmeldung fehlgeschlagen" });
return;
}
try
{
var account = _accounts.GetUserAccount(UUID.Zero, parts[0], parts[1]);
if (account is null || !account.LoginAllowed)
{
await ReplyAsync(context.Response, 401, new { error = "Anmeldung fehlgeschlagen" });
return;
}
string hashed = Util.Md5Hash(data.Password);
string loginToken = _auth.Authenticate(account.PrincipalID, hashed, 30);
if (!UUID.TryParse(loginToken, out var session) || session == UUID.Zero)
{
await ReplyAsync(context.Response, 401, new { error = "Anmeldung fehlgeschlagen" });
return;
}
try { _auth.Release(account.PrincipalID, loginToken); }
catch (Exception e) { Log.Warn("[SYS.API] Failed to release one-time auth session", e); }
if (account.UserLevel < 200)
{
await ReplyAsync(context.Response, 403, new { error = "Access Denied – Keine Berechtigung" });
return;
}
lock (throttle) throttle.Count = 0;
string sid = RandomSecret();
AdminSession s = new(account.PrincipalID, account.Name, RandomSecret(),
DateTimeOffset.UtcNow.AddHours(1));
_sessions[sid] = s;
bool secure = context.Request.IsSecureConnection || IsTrustedProxy(context.Request);
context.Response.AppendHeader("Set-Cookie", $"ogl_sysapi={sid}; Path=/; " +
"HttpOnly; SameSite=Strict; Max-Age=3600" + (secure ? "; Secure" : ""));
await ReplyAsync(context.Response, 200, new { name = s.Name, csrf = s.Csrf, minLevel = 200 });
Log.Info("[SYS.API] Web administrator authenticated (UserLevel>=200).");
}
catch (Exception e)
{
Log.Error("[SYS.API] Login validation unavailable", e);
await ReplyAsync(context.Response, 503, new { error = "Authentifizierungsdienst nicht erreichbar" });
}
}
private async Task HandleAsync(HttpListenerContext context)
{
try
{
var req = context.Request;
var response = context.Response;
SecurityHeaders(response);
string path = req.Url?.AbsolutePath ?? "";
bool isGet = req.HttpMethod == "GET";
if (isGet && path is "/" or "/index.html")
{
await AssetAsync(response, "index.html", "text/html; charset=utf-8");
return;
}
if (isGet && path == "/money.js") { await AssetAsync(response, "money.js", "text/javascript; charset=utf-8"); return; }
if (isGet && path == "/app.js") { await AssetAsync(response, "app.js", "text/javascript; charset=utf-8"); return; }
if (isGet && path == "/style.css") { await AssetAsync(response, "style.css", "text/css; charset=utf-8"); return; }
if (isGet && path == "/ogl-mascot.webp") { await AssetAsync(response, "ogl-mascot.webp", "image/webp"); return; }
if (isGet && path == "/pwa.js") { await AssetAsync(response, "pwa.js", "text/javascript; charset=utf-8"); return; }
if (isGet && path == "/account-profile.js") { await AssetAsync(response, "account-profile.js", "text/javascript; charset=utf-8"); return; }
if (isGet && path == "/account-profile.css") { await AssetAsync(response, "account-profile.css", "text/css; charset=utf-8"); return; }
if (isGet && path == "/admin-data.js") { await AssetAsync(response, "admin-data.js", "text/javascript; charset=utf-8"); return; }
if (isGet && path == "/admin-data.css") { await AssetAsync(response, "admin-data.css", "text/css; charset=utf-8"); return; }
if (isGet && path == "/updates.js") { await AssetAsync(response, "updates.js", "text/javascript; charset=utf-8"); return; }
if (isGet && path == "/updates.css") { await AssetAsync(response, "updates.css", "text/css; charset=utf-8"); return; }
if (isGet && path == "/mobile.css") { await AssetAsync(response, "mobile.css", "text/css; charset=utf-8"); return; }
if (isGet && path == "/manifest.webmanifest") { await AssetAsync(response, "manifest.webmanifest", "application/manifest+json; charset=utf-8"); return; }
if (isGet && path == "/service-worker.js") { await AssetAsync(response, "service-worker.js", "text/javascript; charset=utf-8"); return; }
if (isGet && path == "/offline.html") { await AssetAsync(response, "offline.html", "text/html; charset=utf-8"); return; }
if (isGet && path == "/ogl-icon-192.png") { await AssetAsync(response, "ogl-icon-192.png", "image/png"); return; }
if (isGet && path == "/ogl-icon-512.png") { await AssetAsync(response, "ogl-icon-512.png", "image/png"); return; }
if (isGet && path == "/ogl-icon-maskable-512.png") { await AssetAsync(response, "ogl-icon-maskable-512.png", "image/png"); return; }
if (isGet && path == "/ogl-apple-touch-icon.png") { await AssetAsync(response, "ogl-apple-touch-icon.png", "image/png"); return; }
if (isGet && path == "/v1/health")
{
await ReplyAsync(response, 200, new { status = "online", module = "sys.api",
port = 8850, version = 1 }); return;
}
if (req.HttpMethod == "POST" && path == "/api/session/login")
{
if (!SameOrigin(req))
{
await ReplyAsync(response, 403, new { error = "Origin rejected" }); return;
}
await LoginAsync(context); return;
}
if (isGet && path is "/api/v1/portal/ping" or "/api/v1/portal/capabilities")
{
if (!HasPortalToken(req))
{
await ReplyAsync(response, 401, new { error = "Invalid portal credential" }); return;
}
await ReplyAsync(response, 200, path.EndsWith("ping")
? new { ok = true, service = "sys.api", apiVersion = "v1" }
: (object)new { apiVersion = "v1", authentication = "single-machine-token", endpoints = new[]
{ "/api/v1/portal/ping", "/api/v1/portal/capabilities",
"/api/v1/UserAccounts/lists", "/api/v1/UserAccounts/{uuid}",
"/api/v1/GridUser/lists", "/api/v1/Presence/lists",
"/api/v1/Regions/lists", "/api/v1/UUID/resolve?uuid={uuid}",
"/api/v1/viewer-blocklist", "/api/v1/grid-blocklist",
"/api/v1/policies/active", "/api/v1/citizen-rules/current",
"/api/v1/citizen-rules/publish",
"/api/v1/portal/services",
"/api/v1/residents/session", "/api/v1/residents/me",
"/api/v1/residents/capabilities",
"/api/v1/residents/groups", "/api/v1/residents/inventory",
"/api/v1/residents/offline-ims", "/api/v1/residents/messages",
"/api/v1/residents/realestate/listings" },
legacyWorldApiUnchanged = true });
return;
}
// Operator/portal-only module status. Never includes user content.
if (isGet && path == "/api/v1/portal/services")
{
if (!HasPortalToken(req) && !TryAdmin(req, out _))
{
await ReplyAsync(response, 401, new { error = "Authorization required" });
return;
}
if (_residents is null)
{
await ReplyAsync(response, 503, new { error = "Resident APIs unavailable" });
return;
}
await ReplyAsync(response, 200, _residents.ServiceStatus());
return;
}
// Delegated resident endpoints require an independent password-backed
// citizen session, never a machine-only identity claim.
if (path.StartsWith("/api/v1/residents/", StringComparison.Ordinal))
{
if (_residents is null)
{
await ReplyAsync(response, 503, new { error = "Resident APIs unavailable" });
return;
}
await _residents.Handle(context, HasPortalToken(req));
return;
}
// Published citizen rules are centrally authoritative for every new
// viewer login. Portal server can publish via its backend-only token;
// web administrators require a verified session and CSRF protection.
if (path is "/api/v1/citizen-rules/current" or "/api/v1/citizen-rules/publish")
{
if (_accessPolicy is null)
{
await ReplyAsync(response, 503, new { error = "Citizen rules unavailable" }); return;
}
if (path.EndsWith("/current", StringComparison.Ordinal) && isGet)
{
if (!HasPortalToken(req) && !HasPolicyReaderToken(req) && !TryAdmin(req, out _))
{
await ReplyAsync(response, 401, new { error = "Authorization required" }); return;
}
try { await ReplyAsync(response, 200, _accessPolicy.CitizenRules()); }
catch (Exception)
{ await ReplyAsync(response, 503, new { error = "Rules database unavailable" }); }
return;
}
if (path.EndsWith("/publish", StringComparison.Ordinal) && req.HttpMethod == "POST")
{
bool fromPortal = HasPortalToken(req);
bool fromAdmin = TryAdmin(req, out AdminSession rulesAdmin);
if (!fromPortal && !fromAdmin)
{
await ReplyAsync(response, 401, new { error = "Publisher authorization required" }); return;
}
if (!fromPortal && (!SameOrigin(req) ||
!string.Equals(req.Headers["X-OGL-CSRF"], rulesAdmin.Csrf, StringComparison.Ordinal)))
{
await ReplyAsync(response, 403, new { error = "CSRF protection denied" }); return;
}
try
{
CitizenRulesPublishInput? payload = await ReadInput<CitizenRulesPublishInput>(req);
if (payload is null)
{
await ReplyAsync(response, 400, new { error = "Expected rules publication JSON" }); return;
}
_accessPolicy.PublishCitizenRules(payload.Version, payload.Url, payload.Sha256,
fromPortal ? "stadtportal" : rulesAdmin.Avatar.ToString());
await ReplyAsync(response, 200, new { ok = true, liveWithinSeconds = 15,
citizenRules = _accessPolicy.CitizenRules() });
}
catch (ArgumentException)
{ await ReplyAsync(response, 409, new { error = "Invalid or reused citizen rules version" }); }
catch (Exception)
{ await ReplyAsync(response, 503, new { error = "Rules database unavailable" }); }
return;
}
await ReplyAsync(response, 405, new { error = "Unsupported rules operation" }); return;
}
// SYS.API denylist administration – separate privilege for writes.
// Node pollers receive only a read token, never admin capabilities.
bool activeAccessRoute = path == "/api/v1/policies/active";
bool viewerAccessRoute = path == "/api/v1/viewer-blocklist";
bool gridAccessRoute = path == "/api/v1/grid-blocklist";
if (activeAccessRoute || viewerAccessRoute || gridAccessRoute)
{
if (_accessPolicy is null)
{
await ReplyAsync(response, 503, new { error = "Access policy unavailable" }); return;
}
bool readAuthorized = HasPolicyReaderToken(req) || HasPortalToken(req) ||
TryAdmin(req, out _);
if (isGet)
{
if (!readAuthorized)
{
await ReplyAsync(response, 401, new { error = "Authorization required" }); return;
}
try
{
await ReplyAsync(response, 200, activeAccessRoute ? _accessPolicy.Active() :
viewerAccessRoute ? _accessPolicy.ListViewers() : _accessPolicy.ListGrids());
}
catch (Exception e)
{
Log.WarnFormat("[SYS.API] Denylist query unavailable ({0})", e.GetType().Name);
await ReplyAsync(response, 503, new { error = "Policy database temporarily unavailable" });
}
return;
}
if (activeAccessRoute || req.HttpMethod is not ("POST" or "DELETE"))
{
await ReplyAsync(response, 405, new { error = "Unsupported policy mutation" }); return;
}
if (!TryAdmin(req, out AdminSession policyAdmin))
{
await ReplyAsync(response, 401, new { error = "Administrator authorization required" }); return;
}
if (!SameOrigin(req) || !string.Equals(req.Headers["X-OGL-CSRF"],
policyAdmin.Csrf, StringComparison.Ordinal))
{
await ReplyAsync(response, 403, new { error = "CSRF protection denied" }); return;
}
try
{
string actor = policyAdmin.Avatar.ToString();
if (viewerAccessRoute)
{
if (req.HttpMethod == "POST")
{
ViewerRestrictionInput? payload = await ReadInput<ViewerRestrictionInput>(req);
if (payload is null) { await ReplyAsync(response, 400, new { error = "Invalid viewer input" }); return; }
_accessPolicy.SetViewer(payload.Name, payload.Reason ?? "", actor);
}
else
{
string? name = System.Web.HttpUtility.ParseQueryString(req.Url?.Query ?? "")["name"];
if (string.IsNullOrEmpty(name)) { await ReplyAsync(response, 400, new { error = "Missing viewer name" }); return; }
_accessPolicy.RemoveViewer(name, actor);
}
}
else
{
if (req.HttpMethod == "POST")
{
GridRestrictionInput? payload = await ReadInput<GridRestrictionInput>(req);
if (payload is null) { await ReplyAsync(response, 400, new { error = "Invalid grid input" }); return; }
_accessPolicy.SetGrid(payload.Grid, payload.Reason ?? "", actor);
}
else
{
string? grid = System.Web.HttpUtility.ParseQueryString(req.Url?.Query ?? "")["grid"];
if (string.IsNullOrEmpty(grid)) { await ReplyAsync(response, 400, new { error = "Missing grid address" }); return; }
_accessPolicy.RemoveGrid(grid, actor);
}
}
await ReplyAsync(response, 200, new { ok = true, liveWithinSeconds = 15 });
}
catch (ArgumentException)
{
await ReplyAsync(response, 400, new { error = "Invalid restriction input" });
}
catch (Exception e)
{
Log.WarnFormat("[SYS.API] Restriction mutation unavailable ({0})", e.GetType().Name);
await ReplyAsync(response, 503, new { error = "Policy database temporarily unavailable" });
}
return;
}
// Administrators get a curated live DB workbench. No arbitrary SQL,
// no machine-token access, and no writes to original simulator data.
if (path=="/api/admin/data" ||
path.StartsWith("/api/admin/data/",StringComparison.Ordinal) ||
path.StartsWith("/api/admin/notes/",StringComparison.Ordinal))
{
if (!TryAdmin(req,out AdminSession dataAdmin))
{
await ReplyAsync(response,401,new{error="Administratoranmeldung erforderlich"});
return;
}
if (_adminData is null)
{
await ReplyAsync(response,503,new{error="SYS.API-Datenwerkzeuge nicht verfügbar"});
return;
}
if (path.StartsWith("/api/admin/notes/",StringComparison.Ordinal))
{
string avatar=path["/api/admin/notes/".Length..];
if(!Guid.TryParse(avatar,out Guid requested)||requested==Guid.Empty)
{
await ReplyAsync(response,400,new{error="Ungültige Avatar-UUID"});return;
}
if(req.HttpMethod is not("GET" or "PUT" or "DELETE"))
{
await ReplyAsync(response,405,new{error="Methode nicht erlaubt"});return;
}
if(!isGet && (!SameOrigin(req) ||
!string.Equals(req.Headers["X-OGL-CSRF"],dataAdmin.Csrf,StringComparison.Ordinal)))
{
await ReplyAsync(response,403,new{error="CSRF-Schutz verweigert"});return;
}
try
{
object? result;
if (isGet) result=_adminData.Note(avatar);
else if(req.HttpMethod=="PUT")
{
AdminNoteInput? input=await ReadInput<AdminNoteInput>(req);
if(input?.Note is null)
{
await ReplyAsync(response,400,new{error="Notiz fehlt"});return;
}
result=_adminData.SaveNote(avatar,input.Note,dataAdmin.Avatar.ToString());
}
else result=_adminData.DeleteNote(avatar,dataAdmin.Avatar.ToString());
await ReplyAsync(response,result is null?404:200,
result??new{error="Benutzerkonto nicht gefunden"});
}
catch(ArgumentException)
{ await ReplyAsync(response,400,new{error="Ungültige Eingabe"}); }
catch(KeyNotFoundException)
{ await ReplyAsync(response,404,new{error="Benutzerkonto nicht gefunden"}); }
catch(Exception e)
{
Log.WarnFormat("[SYS.API] Admin note unavailable ({0})",e.GetType().Name);
await ReplyAsync(response,503,new{error="Notizdienst nicht verfügbar"});
}
return;
}
if(!isGet)
{ await ReplyAsync(response,405,new{error="Nur Lesen erlaubt"});return; }
try
{
var query=req.QueryString;
bool paginate=path is "/api/admin/data/regions" or
"/api/admin/data/parcels" or "/api/admin/data/groups";
int limit=25,offset=0;
if(paginate &&
(!int.TryParse(query["limit"]??"25",out limit) ||
!int.TryParse(query["offset"]??"0",out offset) ||
limit is <1 or >100 || offset is <0 or >1000000))
{
await ReplyAsync(response,400,new{error="Ungültige Paginierung"});return;
}
object? data=path switch
{
"/api/admin/data" or "/api/admin/data/overview"
=>_adminData.Overview(),
"/api/admin/data/regions"
=>_adminData.Regions(limit,offset,query["search"]),
"/api/admin/data/parcels"
=>_adminData.Parcels(limit,offset,query["region"],query["search"]),
"/api/admin/data/groups"
=>_adminData.Groups(limit,offset,query["search"]),
"/api/admin/data/assets/summary"
=>_adminData.AssetSummary(),
"/api/admin/data/finance/summary"
=>_adminData.FinanceSummary(),
"/api/admin/data/messages/summary"
=>_adminData.MessageSummary(),
_ => null
};
if(data is null && path.StartsWith("/api/admin/data/regions/",
StringComparison.Ordinal))
{
string region=path["/api/admin/data/regions/".Length..];
data=_adminData.Region(region);
}
if(data is null && path.StartsWith("/api/admin/data/inventory/",
StringComparison.Ordinal) && path.EndsWith("/summary",StringComparison.Ordinal))
{
string id=path["/api/admin/data/inventory/".Length..
^"/summary".Length];
data=_adminData.InventorySummary(id);
}
await ReplyAsync(response,data is null?404:200,
data??new{error="Datensatz nicht gefunden"});
}
catch(ArgumentException)
{ await ReplyAsync(response,400,new{error="Ungültige Suchanfrage oder UUID"}); }
catch(Exception e)
{
Log.WarnFormat("[SYS.API] DB workbench unavailable ({0})",e.GetType().Name);
await ReplyAsync(response,503,new{error="Datenbankabfrage derzeit nicht verfügbar"});
}
return;
}
// Full profile contains contact data and is deliberately restricted
// to a revalidated SYS.API administrator cookie. A portal machine
// token cannot read it, and the legacy account API remains unchanged.
const string profilePrefix="/api/admin/accounts/";
if (path.StartsWith(profilePrefix,StringComparison.Ordinal) &&
path.EndsWith("/profile",StringComparison.Ordinal))
{
if (!TryAdmin(req,out _))
{
await ReplyAsync(response,401,new{error="Administratoranmeldung erforderlich"});
return;
}
if (!isGet)
{
await ReplyAsync(response,405,new{error="Nur Lesen erlaubt"});
return;
}
string target=path[profilePrefix.Length..^"/profile".Length];
if (!Guid.TryParse(target,out Guid userId) || userId==Guid.Empty)
{
await ReplyAsync(response,400,new{error="Ungültige Avatar-ID"});return;
}
if (_readModel is null)
{
await ReplyAsync(response,503,new{error="Kontoverzeichnis nicht verfügbar"});return;
}
try
{
object? profile=_readModel.AdminProfile(userId.ToString("D"));
await ReplyAsync(response,profile is null?404:200,
profile??new{error="Benutzerkonto nicht gefunden"});
}
catch(Exception e)
{
Log.WarnFormat("[SYS.API] Admin profile read unavailable ({0})",e.GetType().Name);
await ReplyAsync(response,503,new{error="Kontoprofil derzeit nicht verfügbar"});
}
return;
}
// Live SQL read-model: strictly allowlisted, read-only, paginated,
// accessible only to a valid backend token OR a revalidated admin.
// The legacy /UserAccounts/lists spelling is an authenticated alias.
string apiPath = path.StartsWith("/api/v1/", StringComparison.Ordinal)
? path[7..] : path;
bool listRoute = apiPath is "/UserAccounts/lists" or "/GridUser/lists" or
"/Presence/lists" or "/Regions/lists";
bool resolveRoute = apiPath == "/UUID/resolve";
bool accountRoute = apiPath.StartsWith("/UserAccounts/", StringComparison.Ordinal) &&
apiPath != "/UserAccounts/lists";
if (listRoute || resolveRoute || accountRoute)
{
if (!HasPortalToken(req) && !TryAdmin(req, out _))
{
await ReplyAsync(response, 401, new { error = "Authorization required" }); return;
}
if (!isGet)
{
await ReplyAsync(response, 405, new { error = "Read-only endpoint" }); return;
}
if (_readModel is null)
{
await ReplyAsync(response, 503, new { error = "Read model unavailable" }); return;
}
try
{
if (listRoute)
{
var query = System.Web.HttpUtility.ParseQueryString(req.Url?.Query ?? "");
if (!int.TryParse(query["limit"] ?? "50", out int limit) ||
!int.TryParse(query["offset"] ?? "0", out int offset) ||
limit is < 1 or > 100 || offset is < 0 or > 1000000 ||
(query["search"]?.Length ?? 0) > 80)
{
await ReplyAsync(response, 400, new { error = "Invalid pagination or search" }); return;
}
string table = apiPath.Split('/', StringSplitOptions.RemoveEmptyEntries)[0];
await ReplyAsync(response, 200, _readModel.List(table, limit, offset, query["search"]));
return;
}
if (resolveRoute)
{
string? uuid = System.Web.HttpUtility.ParseQueryString(req.Url?.Query ?? "")["uuid"];
if (!Guid.TryParse(uuid, out _))
{
await ReplyAsync(response, 400, new { error = "UUID must be valid" }); return;
}
await ReplyAsync(response, 200, _readModel.Resolve(uuid!)); return;
}
string id = apiPath["/UserAccounts/".Length..];
if (!Guid.TryParse(id, out _))
{
await ReplyAsync(response, 400, new { error = "UUID must be valid" }); return;
}
object? account = _readModel.Account(id);
await ReplyAsync(response, account is null ? 404 : 200,
account ?? new { error = "Account not found" });
return;
}
catch (Exception e)
{
// Never expose SQL/configuration/secrets in JSON or logs.
Log.WarnFormat("[SYS.API] Live database read unavailable ({0})", e.GetType().Name);
await ReplyAsync(response, 503, new { error = "Database read temporarily unavailable" });
return;
}
}
// Money payouts use a DIFFERENT credential from the general portal token.
// No client-provided "Stripe paid" or "PayPal completed" claim is trusted.
if (path is "/api/v1/portal/money/payouts" or "/api/v1/portal/money/rate")
{
if (_nvMoney is null || !_nvMoney.PortalEnabled)
{
await ReplyAsync(response, 503, new { error = "Portal NV$ payouts are not configured" });
return;
}
if (!IsTrustedProxy(req) || !_nvMoney.ValidPortalCredential(req))
{
await ReplyAsync(response, 401, new { error = "Dedicated payout authorization required" });
return;
}
if (isGet && path.EndsWith("/rate", StringComparison.Ordinal))
{
await ReplyAsync(response, 200, new {
nvPerEuro = SysApiNvMoney.NvPerEuro, euroCurrency = "EUR",
currency = "NV$", paymentSettlementEnabled = false
});
return;
}
if (req.HttpMethod != "POST" || path.EndsWith("/rate", StringComparison.Ordinal))
{
await ReplyAsync(response, 405, new { error = "Method not allowed" }); return;
}
await PayNvAsync(req, response, "portal", true);
return;
}
if (!TryAdmin(req, out AdminSession admin))
{
await ReplyAsync(response, 401, new { error = "Access Denied – Keine Berechtigung" }); return;
}
if (!isGet && (!SameOrigin(req) ||
!string.Equals(req.Headers["X-OGL-CSRF"], admin.Csrf, StringComparison.Ordinal)))
{
await ReplyAsync(response, 403, new { error = "CSRF protection denied" }); return;
}
if (path == "/api/admin/money/status")
{
if (!isGet)
{
await ReplyAsync(response, 405, new { error = "GET required" }); return;
}
await ReplyAsync(response, 200, _nvMoney?.Status() ??
new { enabled = false, portalEnabled = false,
nvPerEuro = SysApiNvMoney.NvPerEuro,
paymentSettlementEnabled = false });
return;
}
if (path == "/api/admin/money/payouts")
{
if (req.HttpMethod != "POST")
{
await ReplyAsync(response, 405, new { error = "POST required" }); return;
}
await PayNvAsync(req, response, admin.Avatar.ToString(), false);
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<AlertInput>(req);
if (input is null || !SysApiAlertCommand.TryParse(input.Command, out string alertMessage))
{
await ReplyAsync(response, 400,
new { error = "Only alert <message> 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,
csrf = admin.Csrf, minLevel = 200 }); return;
}
if (req.HttpMethod == "POST" && path == "/api/session/logout")
{
string? sid = req.Cookies["ogl_sysapi"]?.Value;
if (sid != null) _sessions.TryRemove(sid, out _);
response.AppendHeader("Set-Cookie",
"ogl_sysapi=; Path=/; HttpOnly; SameSite=Strict; Max-Age=0");
await ReplyAsync(response, 200, new { ok = true }); return;
}
// Dedicated binary release administration, ONLY after cookie/admin
// revalidation and CSRF/origin checks in the preceding guard.
// Portal tokens, node tokens and anonymous callers cannot publish.
if (path == "/api/admin/updates" ||
path.StartsWith("/api/admin/updates/", StringComparison.Ordinal))
{
await SysApiUpdatePublisher.Handle(req, response, path, _stop.Token);
return;
}
if (isGet && path == "/api/admin/overview")
{
await ReplyAsync(response, 200, new
{
service = "OpenGenesisLINK System API",
generation = "GEN 1",
api = "v1",
status = "operational",
port = 8850,
internalPort = new Uri(_http.Prefixes.First()).Port,
tlsConfigured = _publicOrigin is not null,
uptimeSeconds = (long)(DateTimeOffset.UtcNow - _startup).TotalSeconds,
portalTokenPresent = true,
session = admin.Name,
minAdminLevel = 200,
oldWorldApiUnchanged = true,
alertsAvailable = _alertPublisher is not null,
moneyAvailable = _nvMoney?.AdminEnabled == true,
endpoints = new[] { "/v1/health", "/api/v1/portal/ping", "/api/v1/portal/capabilities" }
});
return;
}
await ReplyAsync(response, 404, new { error = "Not found" });
}
catch (Exception e)
{
Log.Error("[SYS.API] Request failed", e);
try { await ReplyAsync(context.Response, 500, new { error = "Internal error" }); }
catch { }
}
finally { try { context.Response.Close(); } catch { } }
}
private async Task PayNvAsync(HttpListenerRequest request, HttpListenerResponse response,
string actor, bool portal)
{
if (_nvMoney is null || (portal ? !_nvMoney.PortalEnabled : !_nvMoney.AdminEnabled))
{
await ReplyAsync(response, 503, new { error = "NV$ payout feature is disabled" });
return;
}
var input = await ReadInput<NvPayoutInput>(request);
try
{
NvPayoutReceipt receipt = _nvMoney.Pay(input, actor, portal);
Log.InfoFormat("[SYS.API MONEY] Credit {0} NV$ to {1}, transaction {2}, duplicated={3}",
receipt.AmountNv, receipt.AvatarId, receipt.TransactionId, receipt.Duplicate);
await ReplyAsync(response, receipt.Duplicate ? 200 : 201, new {
receipt.TransactionId, receipt.AvatarId, receipt.AmountNv,
receipt.BalanceNv, receipt.Duplicate, currency = "NV$"
});
}
catch (ArgumentException ex)
{
await ReplyAsync(response, 400, new { error = ex.Message });
}
catch (NexVerse.Core.Economy.NexLedgerConflictException)
{
await ReplyAsync(response, 409, new { error = "Idempotency request conflicts with existing ledger transaction" });
}
catch (InvalidOperationException)
{
await ReplyAsync(response, 503, new { error = "NV$ ledger or payout service unavailable" });
}
catch (Exception ex)
{
Log.Error("[SYS.API MONEY] Financial transaction failed", ex);
await ReplyAsync(response, 503, new { error = "NV$ payout could not be completed" });
}
}
public void Dispose()
{
if (Interlocked.Exchange(ref _disposed, 1) != 0) return;
_stop.Cancel();
_http.Stop();
_http.Close();
_sessions.Clear();
_alertPublisher?.Dispose();
_alertGate.Dispose();
_stop.Dispose();
}
}