feat(gen1): independent simulator web administration and SYS.API foundation
Gen 1: os_webinterface.dll + parallel SYS.API mit OGL-Command-Center
This commit is contained in:
37 files changed
+3555
-324
No files matched your search
@@ -969,6 +969,23 @@ jobs:
|
||||
dotnet run --project tools/ci/OglDynamicTextureRetentionRegression/OglDynamicTextureRetentionRegression.csproj --configuration Release
|
||||
|
||||
|
||||
- name: Verify parallel SYS.API foundation and UserLevel 200 security
|
||||
shell: bash
|
||||
run: |
|
||||
set -euo pipefail
|
||||
python3 tools/ci/verify_sys_api_foundation.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
|
||||
|
||||
- name: Verify isolated simulator admin web DLL and security contract
|
||||
shell: bash
|
||||
run: |
|
||||
set -euo pipefail
|
||||
python3 tools/ci/verify_os_webinterface.py
|
||||
dotnet build addons/OSWebInterface/os_webinterface.csproj --configuration Release --no-restore
|
||||
dotnet run --project tools/ci/OSWebInterfaceSmoke/OSWebInterfaceSmoke.csproj --configuration Release
|
||||
|
||||
- name: Verify Generation 1 approved-viewer admission policy
|
||||
shell: bash
|
||||
run: |
|
||||
|
||||
+929
-315
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,400 @@
|
||||
// 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.Region.Framework.Scenes;
|
||||
using OpenSim.Services.Interfaces;
|
||||
|
||||
namespace OpenGenesisLINK.Addons.OSWebInterface;
|
||||
|
||||
internal sealed class AdminHttpServer : IDisposable
|
||||
{
|
||||
private sealed record Session(UUID Principal, string Name, string Csrf, DateTimeOffset Expires);
|
||||
private sealed class Attempt { public int Count; public DateTimeOffset Reset = DateTimeOffset.UtcNow.AddMinutes(5); }
|
||||
private sealed record LoginRequest(string Username, string Password);
|
||||
private sealed record RegionRequest(string RegionId);
|
||||
private sealed record UpdateRequest(string Sha);
|
||||
private sealed record ImportRequest(string RegionId);
|
||||
|
||||
private static readonly ILog Log = LogManager.GetLogger(typeof(AdminHttpServer));
|
||||
private static readonly JsonSerializerOptions JsonOptions = new(JsonSerializerDefaults.Web);
|
||||
private readonly ConcurrentDictionary<UUID, Scene> _scenes;
|
||||
private readonly ConcurrentDictionary<string, Session> _sessions = new();
|
||||
private readonly ConcurrentDictionary<string, Attempt> _attempts = new();
|
||||
private readonly HttpListener _listener = new();
|
||||
private readonly CancellationTokenSource _stop = new();
|
||||
private readonly AdminOperations _operations;
|
||||
private readonly LiveUpdateBridge _liveUpdate;
|
||||
private readonly Uri? _publicOrigin;
|
||||
private readonly string _loopbackHost;
|
||||
private Task? _acceptTask;
|
||||
private readonly DateTimeOffset _started = DateTimeOffset.UtcNow;
|
||||
|
||||
public AdminHttpServer(ConcurrentDictionary<UUID, Scene> scenes, string storage, int port, int retention, List<(string Name, Uri Uri)> services, LiveUpdateBridge liveUpdate, string publicOrigin)
|
||||
{
|
||||
_loopbackHost = $"127.0.0.1:{port}";
|
||||
if (!string.IsNullOrWhiteSpace(publicOrigin))
|
||||
{
|
||||
if (!Uri.TryCreate(publicOrigin, UriKind.Absolute, out Uri? parsed) ||
|
||||
parsed.Scheme != Uri.UriSchemeHttps || parsed.AbsolutePath != "/" ||
|
||||
parsed.Query.Length != 0 || parsed.Fragment.Length != 0 ||
|
||||
parsed.UserInfo.Length != 0)
|
||||
throw new ArgumentException("PublicOrigin muss eine HTTPS-Origin ohne Pfad sein.");
|
||||
_publicOrigin = parsed;
|
||||
}
|
||||
_scenes = scenes;
|
||||
_operations = new AdminOperations(scenes, storage, retention, services);
|
||||
_liveUpdate = liveUpdate;
|
||||
// Binding to any public interface is deliberately unsupported.
|
||||
_listener.Prefixes.Add($"http://127.0.0.1:{port}/");
|
||||
}
|
||||
|
||||
public void Start()
|
||||
{
|
||||
_listener.Start();
|
||||
_acceptTask = Task.Run(AcceptLoopAsync);
|
||||
}
|
||||
|
||||
private async Task AcceptLoopAsync()
|
||||
{
|
||||
while (!_stop.IsCancellationRequested)
|
||||
{
|
||||
HttpListenerContext context;
|
||||
try { context = await _listener.GetContextAsync(); }
|
||||
catch (Exception e) when (e is HttpListenerException or ObjectDisposedException) { break; }
|
||||
_ = Task.Run(() => DispatchAsync(context));
|
||||
}
|
||||
}
|
||||
|
||||
private static string Token() => Convert.ToHexString(RandomNumberGenerator.GetBytes(32)).ToLowerInvariant();
|
||||
|
||||
private static async Task<T?> ReadJsonAsync<T>(HttpListenerRequest req) where T : class
|
||||
{
|
||||
if (req.ContentLength64 > 16384 || req.ContentType is null ||
|
||||
!req.ContentType.StartsWith("application/json", StringComparison.OrdinalIgnoreCase))
|
||||
return null;
|
||||
using var buffer = new MemoryStream();
|
||||
byte[] block = new byte[4096];
|
||||
int count;
|
||||
while ((count = await req.InputStream.ReadAsync(block)) > 0)
|
||||
{
|
||||
if (buffer.Length + count > 16384) return null;
|
||||
buffer.Write(block, 0, count);
|
||||
}
|
||||
try { return JsonSerializer.Deserialize<T>(buffer.ToArray(), JsonOptions); }
|
||||
catch (JsonException) { return null; }
|
||||
}
|
||||
|
||||
private static async Task SendAsync(HttpListenerResponse response, int code, object data)
|
||||
{
|
||||
response.StatusCode = code;
|
||||
response.ContentType = "application/json; charset=utf-8";
|
||||
byte[] payload = JsonSerializer.SerializeToUtf8Bytes(data, JsonOptions);
|
||||
response.ContentLength64 = payload.Length;
|
||||
await response.OutputStream.WriteAsync(payload);
|
||||
}
|
||||
|
||||
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'; script-src 'self'; style-src 'self'; connect-src 'self'; img-src 'self' data:; base-uri 'none'; form-action 'self'; frame-ancestors 'none'";
|
||||
}
|
||||
|
||||
private bool IsTrustedProxyRequest(HttpListenerRequest request) =>
|
||||
_publicOrigin is not null &&
|
||||
IPAddress.IsLoopback(request.RemoteEndPoint?.Address ?? IPAddress.None) &&
|
||||
string.Equals(request.Headers["Host"], _loopbackHost, StringComparison.OrdinalIgnoreCase) &&
|
||||
string.Equals(request.Headers["X-Forwarded-Proto"], "https", StringComparison.OrdinalIgnoreCase) &&
|
||||
string.Equals(request.Headers["X-Forwarded-Host"], _publicOrigin.Authority, StringComparison.OrdinalIgnoreCase);
|
||||
|
||||
private bool SameOrigin(HttpListenerRequest request)
|
||||
{
|
||||
// Reverse proxy must send Host: 127.0.0.1:PORT to satisfy the listener
|
||||
// and replace X-Forwarded-Host/Proto with a configured HTTPS origin.
|
||||
string origin = request.Headers["Origin"] ?? "";
|
||||
if (!string.IsNullOrEmpty(origin))
|
||||
{
|
||||
if (!Uri.TryCreate(origin, UriKind.Absolute, out Uri? parsed)) return false;
|
||||
bool local = parsed.Scheme == Uri.UriSchemeHttp &&
|
||||
string.Equals(parsed.Authority, _loopbackHost, StringComparison.OrdinalIgnoreCase);
|
||||
bool proxy = IsTrustedProxyRequest(request) &&
|
||||
string.Equals(parsed.GetLeftPart(UriPartial.Authority),
|
||||
_publicOrigin!.GetLeftPart(UriPartial.Authority), StringComparison.OrdinalIgnoreCase);
|
||||
return local || proxy;
|
||||
}
|
||||
string fetchSite = request.Headers["Sec-Fetch-Site"] ?? "";
|
||||
return fetchSite is "" or "same-origin" or "none";
|
||||
}
|
||||
|
||||
private bool TrySession(HttpListenerRequest request, out Session? session)
|
||||
{
|
||||
session = null;
|
||||
string? id = request.Cookies["ogl_admin"]?.Value;
|
||||
if (id is null || !_sessions.TryGetValue(id, out Session? s)) return false;
|
||||
if (s.Expires <= DateTimeOffset.UtcNow)
|
||||
{
|
||||
_sessions.TryRemove(id, out _);
|
||||
return false;
|
||||
}
|
||||
// UserLevel can be revoked while a session is active. Revalidate on each action.
|
||||
Scene? scene = _scenes.Values.FirstOrDefault(v => v.UserAccountService is not null);
|
||||
if (scene is null) return false;
|
||||
try
|
||||
{
|
||||
UserAccount? account = scene.UserAccountService?.GetUserAccount(UUID.Zero, s.Principal);
|
||||
if (account is null || account.UserLevel <= 0 || !account.LoginAllowed) return false;
|
||||
}
|
||||
catch (Exception e) { Log.Warn("[OS WEBINTERFACE] Account revalidation failed", e); return false; }
|
||||
session = s;
|
||||
return true;
|
||||
}
|
||||
|
||||
private async Task LoginAsync(HttpListenerContext ctx)
|
||||
{
|
||||
var request = await ReadJsonAsync<LoginRequest>(ctx.Request);
|
||||
if (request is null || string.IsNullOrWhiteSpace(request.Username) ||
|
||||
string.IsNullOrEmpty(request.Password) || request.Username.Length > 120 ||
|
||||
request.Password.Length > 1024)
|
||||
{
|
||||
await SendAsync(ctx.Response, 400, new { error = "Ungültige Anmeldung" });
|
||||
return;
|
||||
}
|
||||
string key = request.Username.Trim().ToLowerInvariant();
|
||||
Attempt attempt = _attempts.GetOrAdd(key, _ => new Attempt());
|
||||
lock (attempt)
|
||||
{
|
||||
if (attempt.Reset <= DateTimeOffset.UtcNow) { attempt.Count = 0; attempt.Reset = DateTimeOffset.UtcNow.AddMinutes(5); }
|
||||
if (++attempt.Count > 8)
|
||||
{
|
||||
ctx.Response.StatusCode = 429;
|
||||
return;
|
||||
}
|
||||
}
|
||||
string[] split = request.Username.Replace('.', ' ').Split(' ', 2, StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries);
|
||||
if (split.Length != 2)
|
||||
{
|
||||
await SendAsync(ctx.Response, 401, new { error = "Anmeldung fehlgeschlagen" });
|
||||
return;
|
||||
}
|
||||
|
||||
Scene? scene = _scenes.Values.FirstOrDefault(s => s.UserAccountService is not null && s.AuthenticationService is not null);
|
||||
if (scene is null)
|
||||
{
|
||||
await SendAsync(ctx.Response, 503, new { error = "Authentifizierungsdienste nicht verfügbar" });
|
||||
return;
|
||||
}
|
||||
try
|
||||
{
|
||||
UserAccount? account = scene.UserAccountService.GetUserAccount(UUID.Zero, split[0], split[1]);
|
||||
if (account is null || !account.LoginAllowed)
|
||||
{
|
||||
await SendAsync(ctx.Response, 401, new { error = "Anmeldung fehlgeschlagen" });
|
||||
return;
|
||||
}
|
||||
// Same password transformation as the simulator login service.
|
||||
string hashed = Util.Md5Hash(request.Password);
|
||||
string token = scene.AuthenticationService.Authenticate(account.PrincipalID, hashed, 30);
|
||||
if (string.IsNullOrWhiteSpace(token) || !UUID.TryParse(token, out UUID secureSession) || secureSession == UUID.Zero)
|
||||
{
|
||||
await SendAsync(ctx.Response, 401, new { error = "Anmeldung fehlgeschlagen" });
|
||||
return;
|
||||
}
|
||||
try { scene.AuthenticationService.Release(account.PrincipalID, token); }
|
||||
catch (Exception e) { Log.Warn("[OS WEBINTERFACE] Token cleanup failed", e); }
|
||||
if (account.UserLevel <= 0)
|
||||
{
|
||||
await SendAsync(ctx.Response, 403, new { error = "Access Denied – Keine Berechtigung." });
|
||||
return;
|
||||
}
|
||||
lock (attempt) attempt.Count = 0;
|
||||
string sid = Token();
|
||||
var session = new Session(account.PrincipalID, account.Name, Token(), DateTimeOffset.UtcNow.AddHours(1));
|
||||
_sessions[sid] = session;
|
||||
bool secure = ctx.Request.IsSecureConnection || IsTrustedProxyRequest(ctx.Request);
|
||||
ctx.Response.AppendHeader("Set-Cookie", "ogl_admin=" + sid +
|
||||
"; Path=/; HttpOnly; SameSite=Strict; Max-Age=3600" + (secure ? "; Secure" : ""));
|
||||
await SendAsync(ctx.Response, 200, new { name = session.Name, csrf = session.Csrf, expires = session.Expires });
|
||||
Log.Info("[OS WEBINTERFACE] Administrative session established");
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
Log.Error("[OS WEBINTERFACE] Authentication service error", e);
|
||||
await SendAsync(ctx.Response, 503, new { error = "Authentifizierungsdienst nicht verfügbar" });
|
||||
}
|
||||
}
|
||||
|
||||
private static async Task ServeResourceAsync(HttpListenerResponse response, string resource, string contentType)
|
||||
{
|
||||
using Stream? stream = typeof(AdminHttpServer).Assembly.GetManifestResourceStream(
|
||||
"os_webinterface.www." + resource);
|
||||
if (stream is null) { response.StatusCode = 404; return; }
|
||||
response.ContentType = contentType;
|
||||
response.ContentLength64 = stream.Length;
|
||||
await stream.CopyToAsync(response.OutputStream);
|
||||
}
|
||||
|
||||
private bool ValidateMutation(HttpListenerRequest request, Session session) =>
|
||||
SameOrigin(request) && string.Equals(request.Headers["X-OGL-CSRF"], session.Csrf, StringComparison.Ordinal);
|
||||
|
||||
private async Task DispatchAsync(HttpListenerContext ctx)
|
||||
{
|
||||
try
|
||||
{
|
||||
SecurityHeaders(ctx.Response);
|
||||
HttpListenerRequest request = ctx.Request;
|
||||
string route = request.Url?.AbsolutePath ?? "/";
|
||||
string method = request.HttpMethod;
|
||||
if (method == "GET" && route is "/" or "/index.html")
|
||||
{
|
||||
await ServeResourceAsync(ctx.Response, "index.html", "text/html; charset=utf-8");
|
||||
return;
|
||||
}
|
||||
if (method == "GET" && route == "/style.css")
|
||||
{
|
||||
await ServeResourceAsync(ctx.Response, "style.css", "text/css; charset=utf-8");
|
||||
return;
|
||||
}
|
||||
if (method == "GET" && route == "/app.js")
|
||||
{
|
||||
await ServeResourceAsync(ctx.Response, "app.js", "text/javascript; charset=utf-8");
|
||||
return;
|
||||
}
|
||||
if (method == "POST" && route == "/api/login")
|
||||
{
|
||||
if (!SameOrigin(request)) { await SendAsync(ctx.Response, 403, new { error = "Origin nicht erlaubt" }); return; }
|
||||
await LoginAsync(ctx); return;
|
||||
}
|
||||
if (!route.StartsWith("/api/", StringComparison.Ordinal))
|
||||
{
|
||||
await SendAsync(ctx.Response, 404, new { error = "Nicht gefunden" }); return;
|
||||
}
|
||||
if (!TrySession(request, out Session? session) || session is null)
|
||||
{
|
||||
await SendAsync(ctx.Response, 401, new { error = "Nicht angemeldet" }); return;
|
||||
}
|
||||
if (method != "GET" && !ValidateMutation(request, session))
|
||||
{
|
||||
await SendAsync(ctx.Response, 403, new { error = "CSRF/Origin-Prüfung fehlgeschlagen" }); return;
|
||||
}
|
||||
if (method == "POST" && route == "/api/logout")
|
||||
{
|
||||
string? sid = request.Cookies["ogl_admin"]?.Value;
|
||||
if (sid is not null) _sessions.TryRemove(sid, out _);
|
||||
ctx.Response.AppendHeader("Set-Cookie", "ogl_admin=; Path=/; HttpOnly; SameSite=Strict; Max-Age=0");
|
||||
await SendAsync(ctx.Response, 200, new { ok = true }); return;
|
||||
}
|
||||
if (method == "GET" && route == "/api/me")
|
||||
{
|
||||
await SendAsync(ctx.Response, 200, new { name = session.Name, csrf = session.Csrf }); return;
|
||||
}
|
||||
if (method == "GET" && route == "/api/overview")
|
||||
{
|
||||
await SendAsync(ctx.Response, 200, new
|
||||
{
|
||||
started = _started,
|
||||
uptimeSeconds = (long)(DateTimeOffset.UtcNow - _started).TotalSeconds,
|
||||
memoryBytes = Environment.WorkingSet,
|
||||
gcBytes = GC.GetTotalMemory(false),
|
||||
regions = _operations.RegionSummary(),
|
||||
endpoints = _operations.PortSummary(),
|
||||
services = await _operations.ServiceSummaryAsync(_stop.Token)
|
||||
});
|
||||
return;
|
||||
}
|
||||
if (method == "GET" && route == "/api/logs")
|
||||
{
|
||||
await SendAsync(ctx.Response, 200, new { content = _operations.LogTail() }); return;
|
||||
}
|
||||
if (method == "GET" && route == "/api/jobs")
|
||||
{
|
||||
await SendAsync(ctx.Response, 200, new { jobs = _operations.Jobs() }); return;
|
||||
}
|
||||
if (method == "POST" && route == "/api/regions/restart")
|
||||
{
|
||||
var payload = await ReadJsonAsync<RegionRequest>(request);
|
||||
if (payload is null || !_operations.Restart(payload.RegionId))
|
||||
await SendAsync(ctx.Response, 404, new { error = "Region nicht gefunden" });
|
||||
else await SendAsync(ctx.Response, 202, new { message = "Region-Neustart angefordert" });
|
||||
return;
|
||||
}
|
||||
if (method == "POST" && route == "/api/oar/export")
|
||||
{
|
||||
var payload = await ReadJsonAsync<RegionRequest>(request);
|
||||
if (payload is null) { await SendAsync(ctx.Response, 400, new { error = "Region fehlt" }); return; }
|
||||
await SendAsync(ctx.Response, 202, _operations.Export(payload.RegionId)); return;
|
||||
}
|
||||
if (method == "POST" && route == "/api/oar/import")
|
||||
{
|
||||
string regionId = request.QueryString["region"] ?? "";
|
||||
if (request.ContentLength64 <= 0 || request.ContentLength64 > AdminOperations.MaxUploadBytes ||
|
||||
request.ContentType != "application/octet-stream")
|
||||
{
|
||||
await SendAsync(ctx.Response, 413, new { error = "Nur OAR-Dateien bis 2 GiB erlaubt" }); return;
|
||||
}
|
||||
var job = await _operations.ImportAsync(regionId, request.InputStream, request.ContentLength64, _stop.Token);
|
||||
await SendAsync(ctx.Response, 202, job); return;
|
||||
}
|
||||
if (method == "GET" && route == "/api/oar/download")
|
||||
{
|
||||
string id = request.QueryString["id"] ?? "";
|
||||
string? file = _operations.ExportFile(id);
|
||||
if (file is null) { await SendAsync(ctx.Response, 404, new { error = "Archiv nicht verfügbar" }); return; }
|
||||
ctx.Response.ContentType = "application/octet-stream";
|
||||
ctx.Response.Headers["Content-Disposition"] = "attachment; filename=\"region-" + id + ".oar\"";
|
||||
using var input = File.Open(file, FileMode.Open, FileAccess.Read, FileShare.Read);
|
||||
ctx.Response.ContentLength64 = input.Length;
|
||||
await input.CopyToAsync(ctx.Response.OutputStream);
|
||||
return;
|
||||
}
|
||||
if (method == "GET" && route == "/api/updates/check")
|
||||
{
|
||||
await SendAsync(ctx.Response, 200, await _operations.CheckGitAsync(_stop.Token)); return;
|
||||
}
|
||||
if (method == "GET" && route == "/api/updates/live-status")
|
||||
{
|
||||
await SendAsync(ctx.Response, 200, await _liveUpdate.StatusAsync(_stop.Token)); return;
|
||||
}
|
||||
if (method == "POST" && route == "/api/updates/live-start")
|
||||
{
|
||||
await SendAsync(ctx.Response, 202, await _liveUpdate.StartAsync(_stop.Token)); return;
|
||||
}
|
||||
if (method == "POST" && route == "/api/updates/stage")
|
||||
{
|
||||
var payload = await ReadJsonAsync<UpdateRequest>(request);
|
||||
if (payload is null) { await SendAsync(ctx.Response, 400, new { error = "Commit fehlt" }); return; }
|
||||
await SendAsync(ctx.Response, 200, await _operations.StageUpdateAsync(payload.Sha, _stop.Token)); return;
|
||||
}
|
||||
await SendAsync(ctx.Response, 404, new { error = "Route nicht gefunden" });
|
||||
}
|
||||
catch (AdminOperations.OperationException e)
|
||||
{
|
||||
if (ctx.Response.OutputStream.CanWrite)
|
||||
await SendAsync(ctx.Response, e.Status, new { error = e.Message });
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
Log.Error("[OS WEBINTERFACE] Request failed", e);
|
||||
try { if (ctx.Response.OutputStream.CanWrite) await SendAsync(ctx.Response, 500, new { error = "Interner Fehler" }); } catch { }
|
||||
}
|
||||
finally { try { ctx.Response.Close(); } catch { } }
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
_stop.Cancel();
|
||||
try { _listener.Stop(); _listener.Close(); } catch { }
|
||||
_operations.Dispose();
|
||||
_liveUpdate.Dispose();
|
||||
_sessions.Clear();
|
||||
_stop.Dispose();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,397 @@
|
||||
// SPDX-License-Identifier: MPL-2.0
|
||||
using System.Collections.Concurrent;
|
||||
using System.Diagnostics;
|
||||
using System.Net;
|
||||
using System.Net.Http.Headers;
|
||||
using System.Net.NetworkInformation;
|
||||
using System.Net.Sockets;
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
using log4net;
|
||||
using OpenMetaverse;
|
||||
using OpenSim.Region.Framework.Interfaces;
|
||||
using OpenSim.Region.Framework.Scenes;
|
||||
|
||||
namespace OpenGenesisLINK.Addons.OSWebInterface;
|
||||
|
||||
/// <summary>Privileged operations, scoped to scenes hosted by this ONE simulator.</summary>
|
||||
internal sealed class AdminOperations : IDisposable
|
||||
{
|
||||
public const long MaxUploadBytes = 2L * 1024 * 1024 * 1024;
|
||||
internal sealed class OperationException(int code, string message) : Exception(message)
|
||||
{
|
||||
public int Status { get; } = code;
|
||||
}
|
||||
private sealed class Job
|
||||
{
|
||||
public string Id = "";
|
||||
public string Region = "";
|
||||
public string Kind = "";
|
||||
public string State = "queued";
|
||||
public string Message = "";
|
||||
public DateTimeOffset Created = DateTimeOffset.UtcNow;
|
||||
public long Bytes;
|
||||
public long Total;
|
||||
public string File = "";
|
||||
}
|
||||
private readonly ConcurrentDictionary<UUID, Scene> _scenes;
|
||||
private readonly ConcurrentDictionary<string, Job> _jobs = new();
|
||||
private readonly ConcurrentDictionary<UUID, string> _busy = new();
|
||||
private readonly string _archiveDir;
|
||||
private readonly string _storage;
|
||||
private readonly int _retention;
|
||||
private readonly List<(string Name, Uri Uri)> _services;
|
||||
private readonly UpdateStager _updateStager;
|
||||
private static readonly ILog Log = LogManager.GetLogger(typeof(AdminOperations));
|
||||
private static readonly HttpClient GitClient = CreateGitClient();
|
||||
|
||||
public AdminOperations(ConcurrentDictionary<UUID, Scene> scenes, string storage, int retention, List<(string Name, Uri Uri)> services)
|
||||
{
|
||||
_scenes = scenes;
|
||||
_storage = storage;
|
||||
_retention = retention;
|
||||
_services = services;
|
||||
_updateStager = new UpdateStager(storage, retention);
|
||||
_archiveDir = Path.Combine(storage, "archives");
|
||||
Directory.CreateDirectory(_archiveDir);
|
||||
}
|
||||
private static HttpClient CreateGitClient()
|
||||
{
|
||||
var h = new HttpClientHandler { AllowAutoRedirect = false };
|
||||
var client = new HttpClient(h) { Timeout = TimeSpan.FromSeconds(12) };
|
||||
client.DefaultRequestHeaders.UserAgent.Add(new ProductInfoHeaderValue("OpenGenesisLINK-Admin", "0.1"));
|
||||
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/vnd.github+json"));
|
||||
return client;
|
||||
}
|
||||
|
||||
private Scene Region(string id)
|
||||
{
|
||||
if (!UUID.TryParse(id, out UUID uid) || !_scenes.TryGetValue(uid, out Scene? s))
|
||||
throw new OperationException(404, "Region nicht gefunden");
|
||||
return s;
|
||||
}
|
||||
private (Scene Scene, IRegionArchiverModule Archiver) GetArchiver(string id)
|
||||
{
|
||||
Scene scene = Region(id);
|
||||
var archive = scene.RequestModuleInterface<IRegionArchiverModule>();
|
||||
if (archive is null) throw new OperationException(503, "OAR-Modul in dieser Region nicht verfügbar");
|
||||
return (scene, archive);
|
||||
}
|
||||
private Job Begin(string id, string kind)
|
||||
{
|
||||
Scene scene = Region(id);
|
||||
string jobId = Guid.NewGuid().ToString("N");
|
||||
var job = new Job { Id = jobId, Region = scene.RegionInfo.RegionName, Kind = kind };
|
||||
if (!_busy.TryAdd(scene.RegionInfo.RegionID, jobId))
|
||||
throw new OperationException(409, "Diese Region führt bereits einen Archivauftrag aus");
|
||||
_jobs[jobId] = job;
|
||||
return job;
|
||||
}
|
||||
private void Complete(UUID regionId, Job job, string? error)
|
||||
{
|
||||
job.Message = error ?? "";
|
||||
job.State = string.IsNullOrWhiteSpace(error) ? "completed" : "failed";
|
||||
_busy.TryRemove(new KeyValuePair<UUID, string>(regionId, job.Id));
|
||||
}
|
||||
|
||||
public object[] RegionSummary()
|
||||
{
|
||||
return _scenes.Values.OrderBy(s => s.RegionInfo.RegionName).Select(s =>
|
||||
{
|
||||
var r = s.RegionInfo;
|
||||
return (object)new
|
||||
{
|
||||
id = r.RegionID.ToString(),
|
||||
name = r.RegionName,
|
||||
location = $"{r.RegionLocX}, {r.RegionLocY}",
|
||||
size = $"{r.RegionSizeX} × {r.RegionSizeY}",
|
||||
udpPort = r.InternalEndPoint?.Port,
|
||||
httpPort = r.HttpPort,
|
||||
serverUri = r.ServerURI,
|
||||
ready = s.Ready,
|
||||
agents = s.GetRootAgentCount(),
|
||||
scriptsEnabled = s.ScriptsEnabled,
|
||||
physicsEnabled = s.PhysicsEnabled
|
||||
};
|
||||
}).ToArray();
|
||||
}
|
||||
|
||||
public object[] PortSummary()
|
||||
{
|
||||
IPEndPoint[] udp;
|
||||
IPEndPoint[] tcp;
|
||||
try
|
||||
{
|
||||
udp = IPGlobalProperties.GetIPGlobalProperties().GetActiveUdpListeners();
|
||||
tcp = IPGlobalProperties.GetIPGlobalProperties().GetActiveTcpListeners();
|
||||
}
|
||||
catch { udp = []; tcp = []; }
|
||||
var rows = new List<object>();
|
||||
foreach (Scene s in _scenes.Values.OrderBy(v => v.RegionInfo.RegionName))
|
||||
{
|
||||
var r = s.RegionInfo;
|
||||
int udpPort = r.InternalEndPoint?.Port ?? 0;
|
||||
rows.Add(new
|
||||
{
|
||||
name = r.RegionName, protocol = "UDP", port = udpPort,
|
||||
local = udpPort > 0 && udp.Any(x => x.Port == udpPort),
|
||||
publicStatus = "Nicht extern geprüft – Router/NAT/Firewall unbekannt",
|
||||
hint = "Fritz!Box: UDP-Port an die lokale Simulator-IP weiterleiten"
|
||||
});
|
||||
int httpPort = (int)r.HttpPort;
|
||||
rows.Add(new
|
||||
{
|
||||
name = r.RegionName, protocol = "TCP", port = httpPort,
|
||||
local = httpPort > 0 && tcp.Any(x => x.Port == httpPort),
|
||||
publicStatus = "Nicht extern geprüft – Router/NAT/Firewall unbekannt",
|
||||
hint = "Fritz!Box: TCP-Port beziehungsweise HTTPS-Proxy prüfen"
|
||||
});
|
||||
}
|
||||
return rows.ToArray();
|
||||
}
|
||||
|
||||
public async Task<object[]> ServiceSummaryAsync(CancellationToken stop)
|
||||
{
|
||||
var checks = _services.Select(async item =>
|
||||
{
|
||||
bool reachable = false;
|
||||
using var timeout = CancellationTokenSource.CreateLinkedTokenSource(stop);
|
||||
timeout.CancelAfter(TimeSpan.FromSeconds(2));
|
||||
try
|
||||
{
|
||||
using var client = new TcpClient();
|
||||
await client.ConnectAsync(item.Uri.Host, item.Uri.Port, timeout.Token);
|
||||
reachable = client.Connected;
|
||||
}
|
||||
catch (Exception) { }
|
||||
return (object)new
|
||||
{
|
||||
name = item.Name,
|
||||
host = item.Uri.Host,
|
||||
port = item.Uri.Port,
|
||||
protocol = item.Uri.Scheme.ToUpperInvariant() + "/TCP",
|
||||
reachable,
|
||||
detail = reachable ? "TCP-Verbindung erfolgreich – Dienstfunktion nicht geprüft" :
|
||||
"TCP nicht erreichbar: Dienst, DNS, Routing oder Firewall prüfen"
|
||||
};
|
||||
});
|
||||
return await Task.WhenAll(checks);
|
||||
}
|
||||
|
||||
public bool Restart(string id)
|
||||
{
|
||||
Scene s;
|
||||
try { s = Region(id); }
|
||||
catch (OperationException) { return false; }
|
||||
_ = Task.Run(async () =>
|
||||
{
|
||||
await Task.Delay(500);
|
||||
try { s.RestartNow(); }
|
||||
catch (Exception e) { Log.Error("[OS WEBINTERFACE] Region restart failed", e); }
|
||||
});
|
||||
Log.Warn("[OS WEBINTERFACE] Region restart requested: " + s.RegionInfo.RegionName);
|
||||
return true;
|
||||
}
|
||||
|
||||
public string LogTail()
|
||||
{
|
||||
string path = Path.Combine(AppContext.BaseDirectory, "OpenSim.log");
|
||||
if (!File.Exists(path))
|
||||
{
|
||||
string logs = Path.Combine(AppContext.BaseDirectory, "logs");
|
||||
if (Directory.Exists(logs))
|
||||
path = Directory.GetFiles(logs, "*.log")
|
||||
.OrderByDescending(File.GetLastWriteTimeUtc).FirstOrDefault() ?? "";
|
||||
}
|
||||
if (string.IsNullOrEmpty(path) || !File.Exists(path)) return "Keine OpenSim.log gefunden.";
|
||||
try
|
||||
{
|
||||
using var f = File.Open(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete);
|
||||
long size = Math.Min(f.Length, 100 * 1024);
|
||||
f.Seek(-size, SeekOrigin.End);
|
||||
using var reader = new StreamReader(f, Encoding.UTF8, true, 1024);
|
||||
string text = reader.ReadToEnd();
|
||||
return text.Length > 90_000 ? text[^90_000..] : text;
|
||||
}
|
||||
catch (IOException) { return "Logdatei vorübergehend nicht lesbar."; }
|
||||
}
|
||||
|
||||
public object[] Jobs() => _jobs.Values.OrderByDescending(x => x.Created).Take(30)
|
||||
.Select(x => (object)new
|
||||
{
|
||||
id = x.Id, region = x.Region, kind = x.Kind, state = x.State,
|
||||
message = x.Message, created = x.Created, bytes = x.Bytes, total = x.Total,
|
||||
download = x.Kind == "export" && x.State == "completed"
|
||||
}).ToArray();
|
||||
|
||||
public object Export(string regionId)
|
||||
{
|
||||
var (scene, archive) = GetArchiver(regionId);
|
||||
Job job = Begin(regionId, "export");
|
||||
job.File = Path.Combine(_archiveDir, job.Id + ".oar");
|
||||
EventManager.OarFileSaved? complete = null;
|
||||
complete = (requestId, message) =>
|
||||
{
|
||||
if (requestId != Guid.ParseExact(job.Id, "N")) return;
|
||||
scene.EventManager.OnOarFileSaved -= complete;
|
||||
if (string.IsNullOrWhiteSpace(message) && !File.Exists(job.File))
|
||||
message = "OAR-Datei wurde nicht erstellt";
|
||||
Complete(scene.RegionInfo.RegionID, job, message);
|
||||
if (job.State == "completed") job.Bytes = new FileInfo(job.File).Length;
|
||||
};
|
||||
scene.EventManager.OnOarFileSaved += complete;
|
||||
try
|
||||
{
|
||||
job.State = "saving";
|
||||
archive.ArchiveRegion(job.File, Guid.ParseExact(job.Id, "N"), new Dictionary<string, object>());
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
scene.EventManager.OnOarFileSaved -= complete;
|
||||
Complete(scene.RegionInfo.RegionID, job, e.Message);
|
||||
}
|
||||
return new { id = job.Id, state = job.State };
|
||||
}
|
||||
|
||||
public async Task<object> ImportAsync(string regionId, Stream source, long contentLength, CancellationToken stop)
|
||||
{
|
||||
var (scene, archive) = GetArchiver(regionId);
|
||||
Job job = Begin(regionId, "import");
|
||||
job.File = Path.Combine(_archiveDir, job.Id + ".upload");
|
||||
job.Total = contentLength;
|
||||
try
|
||||
{
|
||||
job.State = "uploading";
|
||||
using (var dst = new FileStream(job.File, FileMode.CreateNew, FileAccess.Write, FileShare.None, 64 * 1024, true))
|
||||
{
|
||||
byte[] buffer = new byte[64 * 1024];
|
||||
int read;
|
||||
while ((read = await source.ReadAsync(buffer, stop)) != 0)
|
||||
{
|
||||
job.Bytes += read;
|
||||
if (job.Bytes > contentLength || job.Bytes > MaxUploadBytes)
|
||||
throw new OperationException(413, "OAR Upload zu groß");
|
||||
await dst.WriteAsync(buffer.AsMemory(0, read), stop);
|
||||
}
|
||||
}
|
||||
if (job.Bytes != contentLength)
|
||||
throw new OperationException(400, "Unvollständiger OAR-Upload");
|
||||
|
||||
EventManager.OarFileLoaded? complete = null;
|
||||
complete = (requestId, loadedScenes, message) =>
|
||||
{
|
||||
if (requestId != Guid.ParseExact(job.Id, "N")) return;
|
||||
scene.EventManager.OnOarFileLoaded -= complete;
|
||||
Complete(scene.RegionInfo.RegionID, job, message);
|
||||
try { File.Delete(job.File); } catch { }
|
||||
};
|
||||
scene.EventManager.OnOarFileLoaded += complete;
|
||||
try
|
||||
{
|
||||
job.State = "importing";
|
||||
archive.DearchiveRegion(job.File, Guid.ParseExact(job.Id, "N"), new Dictionary<string, object>());
|
||||
}
|
||||
catch
|
||||
{
|
||||
scene.EventManager.OnOarFileLoaded -= complete;
|
||||
throw;
|
||||
}
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
Complete(scene.RegionInfo.RegionID, job, e.Message);
|
||||
try { File.Delete(job.File); } catch { }
|
||||
if (e is OperationException) throw;
|
||||
throw new OperationException(500, "OAR-Import fehlgeschlagen: " + e.Message);
|
||||
}
|
||||
Log.Warn("[OS WEBINTERFACE] OAR import initiated for " + scene.RegionInfo.RegionName);
|
||||
return new { id = job.Id, state = job.State };
|
||||
}
|
||||
|
||||
public string? ExportFile(string id)
|
||||
{
|
||||
if (!Guid.TryParseExact(id, "N", out _) ||
|
||||
!_jobs.TryGetValue(id, out Job? j) ||
|
||||
j.Kind != "export" || j.State != "completed")
|
||||
return null;
|
||||
string expected = Path.Combine(_archiveDir, id + ".oar");
|
||||
return j.File == expected && File.Exists(expected) ? expected : null;
|
||||
}
|
||||
|
||||
public async Task<object> CheckGitAsync(CancellationToken stop)
|
||||
{
|
||||
const string endpoint = "https://api.github.com/repos/opengenesislink/opengenesislinkserver/commits?sha=main&per_page=12";
|
||||
string? local = null;
|
||||
try { local = await GitShaAsync(stop); } catch { }
|
||||
try
|
||||
{
|
||||
using var response = await GitClient.GetAsync(endpoint, stop);
|
||||
response.EnsureSuccessStatusCode();
|
||||
using var document = JsonDocument.Parse(await response.Content.ReadAsStringAsync(stop));
|
||||
var entries = document.RootElement.EnumerateArray().Select(c => new
|
||||
{
|
||||
sha = c.GetProperty("sha").GetString(),
|
||||
title = (c.GetProperty("commit").GetProperty("message").GetString() ?? "").Split('\n')[0],
|
||||
date = c.GetProperty("commit").GetProperty("committer").GetProperty("date").GetString()
|
||||
}).ToArray();
|
||||
string? remote = entries.FirstOrDefault()?.sha;
|
||||
int? newCommitCount = null;
|
||||
if (local is not null && remote is not null && local != remote &&
|
||||
local.Length == 40 && local.All(Uri.IsHexDigit))
|
||||
{
|
||||
try
|
||||
{
|
||||
string compare = "https://api.github.com/repos/opengenesislink/opengenesislinkserver/compare/" +
|
||||
local + "..." + remote;
|
||||
using var compared = await GitClient.GetAsync(compare, stop);
|
||||
if (compared.IsSuccessStatusCode)
|
||||
{
|
||||
using var detail = JsonDocument.Parse(await compared.Content.ReadAsStringAsync(stop));
|
||||
newCommitCount = detail.RootElement.GetProperty("total_commits").GetInt32();
|
||||
entries = detail.RootElement.GetProperty("commits").EnumerateArray().Select(c => new
|
||||
{
|
||||
sha = c.GetProperty("sha").GetString(),
|
||||
title = (c.GetProperty("commit").GetProperty("message").GetString() ?? "").Split('\n')[0],
|
||||
date = c.GetProperty("commit").GetProperty("committer").GetProperty("date").GetString()
|
||||
}).ToArray();
|
||||
}
|
||||
}
|
||||
catch (Exception e) { Log.Warn("[OS WEBINTERFACE] GitHub compare unavailable", e); }
|
||||
}
|
||||
return new
|
||||
{
|
||||
local, remote, upToDate = local is not null && local == remote,
|
||||
newCommitCount, commits = entries,
|
||||
note = newCommitCount > entries.Length
|
||||
? "Es gibt weitere neue Commits; GitHub liefert in dieser Abfrage nur eine Teilmenge."
|
||||
: "Git-Commits sind Quellcode-Stände, keine geprüften Binär-Releases. Ein Update muss gebaut und vor Aktivierung getestet werden."
|
||||
};
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
return new { local, error = "GitHub nicht erreichbar: " + e.GetType().Name };
|
||||
}
|
||||
}
|
||||
|
||||
private static async Task<string?> GitShaAsync(CancellationToken stop)
|
||||
{
|
||||
string? root = Directory.GetParent(AppContext.BaseDirectory.TrimEnd(Path.DirectorySeparatorChar))?.FullName;
|
||||
if (root is null || !Directory.Exists(Path.Combine(root, ".git"))) return null;
|
||||
var start = new ProcessStartInfo("git")
|
||||
{
|
||||
WorkingDirectory = root, RedirectStandardOutput = true,
|
||||
RedirectStandardError = true, UseShellExecute = false
|
||||
};
|
||||
start.ArgumentList.Add("rev-parse");
|
||||
start.ArgumentList.Add("HEAD");
|
||||
using Process? p = Process.Start(start);
|
||||
if (p is null) return null;
|
||||
string output = (await p.StandardOutput.ReadToEndAsync(stop)).Trim();
|
||||
await p.WaitForExitAsync(stop);
|
||||
return p.ExitCode == 0 && output.Length == 40 ? output : null;
|
||||
}
|
||||
|
||||
public Task<object> StageUpdateAsync(string sha, CancellationToken stop) => _updateStager.StageAsync(sha, stop);
|
||||
|
||||
public void Dispose() { }
|
||||
}
|
||||
@@ -0,0 +1,99 @@
|
||||
// SPDX-License-Identifier: MPL-2.0
|
||||
using System.Net.Http.Headers;
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
|
||||
namespace OpenGenesisLINK.Addons.OSWebInterface;
|
||||
|
||||
/// <summary>
|
||||
/// Optional integration with the separately installed and independently
|
||||
/// authenticated OGL G1 live-update systemd service. This DLL NEVER runs
|
||||
/// a shell and NEVER receives script paths/commands from the browser.
|
||||
/// </summary>
|
||||
internal sealed class LiveUpdateBridge : IDisposable
|
||||
{
|
||||
private readonly bool _enabled;
|
||||
private readonly string _nodeId;
|
||||
private readonly string _token;
|
||||
private readonly HttpClient _http;
|
||||
|
||||
public LiveUpdateBridge(bool requested, string nodeId, string serviceUrl, string token)
|
||||
{
|
||||
_nodeId = nodeId;
|
||||
_token = token;
|
||||
bool goodId = nodeId.Length is >= 1 and <= 64 &&
|
||||
char.IsLetterOrDigit(nodeId[0]) &&
|
||||
nodeId.All(c => char.IsLetterOrDigit(c) || c is '.' or '_' or '-');
|
||||
bool local = Uri.TryCreate(serviceUrl, UriKind.Absolute, out Uri? u) &&
|
||||
u.Scheme == "http" && u.Host == "127.0.0.1" &&
|
||||
u.Port is >= 1025 and <= 65535 &&
|
||||
u.AbsolutePath == "/" && u.Query.Length == 0 && u.Fragment.Length == 0;
|
||||
_enabled = requested && goodId && local && Encoding.UTF8.GetByteCount(token) >= 32 &&
|
||||
!OperatingSystem.IsWindows();
|
||||
_http = new HttpClient(new HttpClientHandler { AllowAutoRedirect = false })
|
||||
{
|
||||
BaseAddress = _enabled ? new Uri(serviceUrl.TrimEnd('/') + "/") :
|
||||
new Uri("http://127.0.0.1:19090/"),
|
||||
Timeout = TimeSpan.FromSeconds(6)
|
||||
};
|
||||
}
|
||||
|
||||
private HttpRequestMessage Request(HttpMethod method, string relative, object? body = null)
|
||||
{
|
||||
var req = new HttpRequestMessage(method, relative);
|
||||
req.Headers.Authorization = new AuthenticationHeaderValue("Bearer", _token);
|
||||
if (body is not null)
|
||||
{
|
||||
req.Content = new StringContent(JsonSerializer.Serialize(body), Encoding.UTF8, "application/json");
|
||||
}
|
||||
return req;
|
||||
}
|
||||
|
||||
public async Task<object> StatusAsync(CancellationToken stop)
|
||||
{
|
||||
if (!_enabled) return new { enabled = false, reachable = false, message = "Live-Updates sind nicht aktiviert oder der externe Updater ist nicht sicher konfiguriert." };
|
||||
try
|
||||
{
|
||||
using var request = Request(HttpMethod.Get, "v1/status");
|
||||
using var response = await _http.SendAsync(request, stop);
|
||||
if (!response.IsSuccessStatusCode)
|
||||
return new { enabled = true, reachable = false, message = "Update-Dienst verweigert Statusabfrage: " + (int)response.StatusCode };
|
||||
using var document = JsonDocument.Parse(await response.Content.ReadAsStringAsync(stop));
|
||||
return new { enabled = true, reachable = true, update = document.RootElement.Clone() };
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
return new { enabled = true, reachable = false, message = "Updater auf 127.0.0.1 nicht erreichbar" };
|
||||
}
|
||||
}
|
||||
|
||||
public async Task<object> StartAsync(CancellationToken stop)
|
||||
{
|
||||
if (!_enabled) throw new AdminOperations.OperationException(403, "Live-Update-Dienst ist nicht aktiviert.");
|
||||
using var request = Request(HttpMethod.Post, "v1/updates", new
|
||||
{
|
||||
node_id = _nodeId,
|
||||
operation_id = Guid.NewGuid().ToString()
|
||||
});
|
||||
try
|
||||
{
|
||||
using var response = await _http.SendAsync(request, stop);
|
||||
if (!response.IsSuccessStatusCode)
|
||||
throw new AdminOperations.OperationException((int)response.StatusCode, "Update-Dienst hat den Auftrag abgelehnt (" + (int)response.StatusCode + ").");
|
||||
using var document = JsonDocument.Parse(await response.Content.ReadAsStringAsync(stop));
|
||||
return new
|
||||
{
|
||||
accepted = true,
|
||||
update = document.RootElement.Clone(),
|
||||
note = "Updater führt Backup, Git-Aktualisierung und .NET-10-Build eigenständig aus. Anschließend Simulator manuell neu starten."
|
||||
};
|
||||
}
|
||||
catch (AdminOperations.OperationException) { throw; }
|
||||
catch (Exception e)
|
||||
{
|
||||
throw new AdminOperations.OperationException(503, "Lokaler Update-Dienst nicht erreichbar: " + e.GetType().Name);
|
||||
}
|
||||
}
|
||||
|
||||
public void Dispose() => _http.Dispose();
|
||||
}
|
||||
@@ -0,0 +1,114 @@
|
||||
// SPDX-License-Identifier: MPL-2.0
|
||||
using System.Collections.Concurrent;
|
||||
using log4net;
|
||||
using Mono.Addins;
|
||||
using Nini.Config;
|
||||
using System.Collections.Generic;
|
||||
using OpenMetaverse;
|
||||
using OpenSim.Region.Framework.Interfaces;
|
||||
using OpenSim.Region.Framework.Scenes;
|
||||
|
||||
[assembly: Addin("OSWebInterface", Namespace = "OpenGenesisLINK", Version = "0.1.0")]
|
||||
[assembly: AddinDependency("::OpenSim.Region.Framework", OpenSim.VersionInfo.VersionNumber)]
|
||||
|
||||
namespace OpenGenesisLINK.Addons.OSWebInterface;
|
||||
|
||||
/// <summary>
|
||||
/// Opt-in, loopback-only simulator administration. The DLL is independent of OpenSim.dll.
|
||||
/// A separate TLS reverse proxy is REQUIRED before using it from another host.
|
||||
/// </summary>
|
||||
[Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "OSWebInterface")]
|
||||
public sealed class OSWebInterfaceModule : ISharedRegionModule
|
||||
{
|
||||
private static readonly ILog Log = LogManager.GetLogger(typeof(OSWebInterfaceModule));
|
||||
private readonly ConcurrentDictionary<UUID, Scene> _scenes = new();
|
||||
private AdminHttpServer? _server;
|
||||
private bool _enabled;
|
||||
private int _port;
|
||||
private string _storage = "";
|
||||
|
||||
public string Name => "OSWebInterface";
|
||||
public Type? ReplaceableInterface => null;
|
||||
|
||||
public void Initialise(IConfigSource source)
|
||||
{
|
||||
IConfig? c = source?.Configs["OSWebInterface"];
|
||||
_enabled = c?.GetBoolean("Enabled", false) ?? false;
|
||||
if (!_enabled) return;
|
||||
_port = c?.GetInt("Port", 9847) ?? 9847;
|
||||
int retention = Math.Clamp(c?.GetInt("BackupRetention", 5) ?? 5, 1, 20);
|
||||
string folder = c?.GetString("DataDirectory", "os-webinterface-data") ?? "os-webinterface-data";
|
||||
if (_port < 1025 || _port > 65535 || Path.IsPathRooted(folder) ||
|
||||
folder.Contains("..", StringComparison.Ordinal) ||
|
||||
folder.Contains(':', StringComparison.Ordinal))
|
||||
{
|
||||
Log.Error("[OS WEBINTERFACE] Unsafe port or DataDirectory; module disabled.");
|
||||
_enabled = false;
|
||||
return;
|
||||
}
|
||||
_storage = Path.GetFullPath(Path.Combine(AppContext.BaseDirectory, folder));
|
||||
try
|
||||
{
|
||||
Directory.CreateDirectory(_storage);
|
||||
var services = new List<(string Name, Uri Uri)>();
|
||||
foreach (var item in new (string Section, string Option)[]
|
||||
{
|
||||
("AssetService", "AssetServerURI"),
|
||||
("InventoryService", "InventoryServerURI"),
|
||||
("GridService", "GridServerURI"),
|
||||
("UserAccountService", "UserAccountServerURI"),
|
||||
("AuthenticationService", "AuthenticationServerURI"),
|
||||
("PresenceService", "PresenceServerURI"),
|
||||
("FriendsService", "FriendsServerURI"),
|
||||
("Hypergrid", "GatekeeperURI")
|
||||
})
|
||||
{
|
||||
string configured = source?.Configs[item.Section]?.GetString(item.Option, "") ?? "";
|
||||
if (Uri.TryCreate(configured, UriKind.Absolute, out Uri? endpoint) &&
|
||||
(endpoint.Scheme == Uri.UriSchemeHttp || endpoint.Scheme == Uri.UriSchemeHttps))
|
||||
services.Add((item.Section, endpoint));
|
||||
}
|
||||
IConfig? node = source?.Configs["NexVerseNodeAgent"];
|
||||
bool liveAllowed = c?.GetBoolean("AllowLiveUpdates", false) == true &&
|
||||
node?.GetBoolean("Enabled", false) == true &&
|
||||
node.GetBoolean("LiveUpdateEnabled", false);
|
||||
string nodeId = node?.GetString("NodeId", Environment.MachineName) ?? Environment.MachineName;
|
||||
string liveUrl = node?.GetString("LiveUpdateServiceUrl", "http://127.0.0.1:19090") ?? "";
|
||||
string liveToken = Environment.GetEnvironmentVariable("OGL_NODE_UPDATER_TOKEN") ?? "";
|
||||
var bridge = new LiveUpdateBridge(liveAllowed, nodeId, liveUrl, liveToken);
|
||||
string publicOrigin = c?.GetString("PublicOrigin", "")?.Trim() ?? "";
|
||||
_server = new AdminHttpServer(_scenes, _storage, _port, retention, services, bridge, publicOrigin);
|
||||
_server.Start();
|
||||
Log.Info($"[OS WEBINTERFACE] Enabled on http://127.0.0.1:{_port}/ (loopback only). Configure an HTTPS reverse proxy for remote access.");
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
Log.Error("[OS WEBINTERFACE] Failed to start; admin web disabled", e);
|
||||
_server?.Dispose();
|
||||
_server = null;
|
||||
_enabled = false;
|
||||
}
|
||||
}
|
||||
|
||||
public void AddRegion(Scene scene)
|
||||
{
|
||||
if (_enabled) _scenes[scene.RegionInfo.RegionID] = scene;
|
||||
}
|
||||
|
||||
public void PostInitialise() { }
|
||||
|
||||
public void RegionLoaded(Scene scene) { }
|
||||
|
||||
public void RemoveRegion(Scene scene)
|
||||
{
|
||||
_scenes.TryRemove(scene.RegionInfo.RegionID, out _);
|
||||
}
|
||||
|
||||
public void Close()
|
||||
{
|
||||
_enabled = false;
|
||||
_server?.Dispose();
|
||||
_server = null;
|
||||
_scenes.Clear();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,182 @@
|
||||
// SPDX-License-Identifier: MPL-2.0
|
||||
using System.IO.Compression;
|
||||
using System.Net;
|
||||
using System.Net.Http.Headers;
|
||||
using System.Text.Json;
|
||||
|
||||
namespace OpenGenesisLINK.Addons.OSWebInterface;
|
||||
|
||||
/// <summary>
|
||||
/// Safe download-only update stage: verifies advertised SHA, saves the GitHub
|
||||
/// source snapshot, and backs up configuration BEFORE any future installation.
|
||||
/// Does not execute downloaded source or replace running simulator assemblies.
|
||||
/// </summary>
|
||||
internal sealed class UpdateStager
|
||||
{
|
||||
private static readonly HttpClient GitHub = CreateClient();
|
||||
private readonly string _data;
|
||||
private readonly int _retention;
|
||||
private readonly SemaphoreSlim _lock = new(1, 1);
|
||||
public const long MaxSnapshot = 256L * 1024 * 1024;
|
||||
|
||||
private static HttpClient CreateClient()
|
||||
{
|
||||
var client = new HttpClient(new HttpClientHandler { AllowAutoRedirect = false })
|
||||
{
|
||||
Timeout = TimeSpan.FromMinutes(5)
|
||||
};
|
||||
client.DefaultRequestHeaders.UserAgent.Add(new ProductInfoHeaderValue("OpenGenesisLINK-UpdateStage", "0.1"));
|
||||
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/vnd.github+json"));
|
||||
return client;
|
||||
}
|
||||
public UpdateStager(string data, int retention)
|
||||
{
|
||||
_data = data;
|
||||
_retention = retention;
|
||||
}
|
||||
|
||||
private static void PrivateDirectory(string dir)
|
||||
{
|
||||
Directory.CreateDirectory(dir);
|
||||
if (!OperatingSystem.IsWindows())
|
||||
File.SetUnixFileMode(dir, UnixFileMode.UserRead | UnixFileMode.UserWrite | UnixFileMode.UserExecute);
|
||||
}
|
||||
private static void PrivateFile(string file)
|
||||
{
|
||||
if (!OperatingSystem.IsWindows())
|
||||
File.SetUnixFileMode(file, UnixFileMode.UserRead | UnixFileMode.UserWrite);
|
||||
}
|
||||
private static bool Sha(string sha) =>
|
||||
sha.Length == 40 && sha.All(Uri.IsHexDigit);
|
||||
|
||||
private static async Task<HttpResponseMessage> RequestSnapshot(string sha, CancellationToken stop)
|
||||
{
|
||||
var first = await GitHub.GetAsync(
|
||||
"https://api.github.com/repos/opengenesislink/opengenesislinkserver/tarball/" + sha,
|
||||
HttpCompletionOption.ResponseHeadersRead, stop);
|
||||
if (first.StatusCode is HttpStatusCode.MovedPermanently or HttpStatusCode.Redirect or
|
||||
HttpStatusCode.RedirectMethod or HttpStatusCode.TemporaryRedirect or HttpStatusCode.PermanentRedirect)
|
||||
{
|
||||
Uri? target = first.Headers.Location;
|
||||
first.Dispose();
|
||||
if (target is null || target.Scheme != Uri.UriSchemeHttps ||
|
||||
!string.Equals(target.Host, "codeload.github.com", StringComparison.OrdinalIgnoreCase) ||
|
||||
!target.AbsolutePath.StartsWith("/opengenesislink/opengenesislinkserver/", StringComparison.Ordinal))
|
||||
throw new IOException("GitHub-Snapshot verweist auf eine unerwartete Adresse.");
|
||||
return await GitHub.GetAsync(target, HttpCompletionOption.ResponseHeadersRead, stop);
|
||||
}
|
||||
return first;
|
||||
}
|
||||
|
||||
public async Task<object> StageAsync(string sha, CancellationToken stop)
|
||||
{
|
||||
if (!Sha(sha)) throw new AdminOperations.OperationException(400, "Ungültiger Commit SHA");
|
||||
if (OperatingSystem.IsWindows()) throw new AdminOperations.OperationException(501, "Windows-Update-Backup benötigt zuerst geprüfte NTFS-ACL-Berechtigungen; Update-Staging deaktiviert.");
|
||||
if (!_lock.Wait(0)) throw new AdminOperations.OperationException(409, "Ein Update-Download läuft bereits");
|
||||
try
|
||||
{
|
||||
using var latestResponse = await GitHub.GetAsync(
|
||||
"https://api.github.com/repos/opengenesislink/opengenesislinkserver/commits/main", stop);
|
||||
latestResponse.EnsureSuccessStatusCode();
|
||||
using var latestDocument = JsonDocument.Parse(await latestResponse.Content.ReadAsStringAsync(stop));
|
||||
string latest = latestDocument.RootElement.GetProperty("sha").GetString() ?? "";
|
||||
if (!string.Equals(latest, sha, StringComparison.OrdinalIgnoreCase))
|
||||
throw new AdminOperations.OperationException(409, "Commit ist nicht mehr die aktuelle main-Version. Bitte neu prüfen.");
|
||||
|
||||
string stage = Path.Combine(_data, "updates");
|
||||
string backups = Path.Combine(_data, "configuration-backups");
|
||||
PrivateDirectory(stage);
|
||||
PrivateDirectory(backups);
|
||||
string filename = Path.Combine(stage, sha.ToLowerInvariant() + ".tar.gz");
|
||||
if (File.Exists(filename))
|
||||
return new { state = "staged", sha, path = "updates/" + Path.GetFileName(filename), note = "Quellcode bereits heruntergeladen. Keine Binärdateien verändert." };
|
||||
|
||||
string tmp = filename + ".partial";
|
||||
try
|
||||
{
|
||||
using var response = await RequestSnapshot(sha, stop);
|
||||
response.EnsureSuccessStatusCode();
|
||||
if (response.Content.Headers.ContentLength > MaxSnapshot)
|
||||
throw new IOException("Quellcode-Snapshot überschreitet das Downloadlimit.");
|
||||
await using (var input = await response.Content.ReadAsStreamAsync(stop))
|
||||
await using (var output = new FileStream(tmp, FileMode.CreateNew, FileAccess.Write,
|
||||
FileShare.None, 128 * 1024, true))
|
||||
{
|
||||
byte[] buffer = new byte[128 * 1024];
|
||||
long copied = 0;
|
||||
int count;
|
||||
while ((count = await input.ReadAsync(buffer, stop)) > 0)
|
||||
{
|
||||
copied += count;
|
||||
if (copied > MaxSnapshot) throw new IOException("Quellcode-Snapshot zu groß");
|
||||
await output.WriteAsync(buffer.AsMemory(0, count), stop);
|
||||
}
|
||||
}
|
||||
PrivateFile(tmp);
|
||||
// Config and secret backup is local only, restricted to the service account.
|
||||
string stamp = DateTimeOffset.UtcNow.ToString("yyyyMMddTHHmmssfffZ");
|
||||
string backup = Path.Combine(backups, stamp + "-" + sha[..12] + ".zip");
|
||||
BackupConfigs(backup);
|
||||
File.Move(tmp, filename);
|
||||
PrivateFile(filename);
|
||||
Prune(backups);
|
||||
return new
|
||||
{
|
||||
state = "staged", sha, path = "updates/" + Path.GetFileName(filename),
|
||||
backup = "configuration-backups/" + Path.GetFileName(backup),
|
||||
note = "Quellcode heruntergeladen und Konfiguration gesichert. Noch KEIN Build, KEINE Installation und KEIN Neustart erfolgt."
|
||||
};
|
||||
}
|
||||
finally { try { if (File.Exists(tmp)) File.Delete(tmp); } catch { } }
|
||||
}
|
||||
catch (AdminOperations.OperationException) { throw; }
|
||||
catch (Exception e) { throw new AdminOperations.OperationException(502, "Update konnte nicht vorbereitet werden: " + e.Message); }
|
||||
finally { _lock.Release(); }
|
||||
}
|
||||
|
||||
private static void BackupConfigs(string backup)
|
||||
{
|
||||
string root = AppContext.BaseDirectory.TrimEnd(Path.DirectorySeparatorChar);
|
||||
// Never allow a backup root provided by the browser.
|
||||
string[] direct = ["OpenSim.ini", "OpenSimDefaults.ini", "nexverse.local.env"];
|
||||
string[] dirs = ["Regions", "config-include"];
|
||||
using var zip = new ZipArchive(File.Open(backup, FileMode.CreateNew), ZipArchiveMode.Create);
|
||||
PrivateFile(backup);
|
||||
foreach (string f in direct)
|
||||
{
|
||||
string path = Path.Combine(root, f);
|
||||
if (File.Exists(path) && (File.GetAttributes(path) & FileAttributes.ReparsePoint) == 0)
|
||||
zip.CreateEntryFromFile(path, f, CompressionLevel.Optimal);
|
||||
}
|
||||
foreach (string d in dirs)
|
||||
{
|
||||
string folder = Path.Combine(root, d);
|
||||
if (!Directory.Exists(folder)) continue;
|
||||
foreach (string f in Directory.EnumerateFiles(folder, "*", SearchOption.AllDirectories))
|
||||
{
|
||||
if ((File.GetAttributes(f) & FileAttributes.ReparsePoint) != 0) continue;
|
||||
string relative = Path.GetRelativePath(root, f);
|
||||
if (relative.EndsWith(".ini", StringComparison.OrdinalIgnoreCase) ||
|
||||
relative.EndsWith(".xml", StringComparison.OrdinalIgnoreCase) ||
|
||||
relative.EndsWith(".pem", StringComparison.OrdinalIgnoreCase) ||
|
||||
relative.EndsWith(".env", StringComparison.OrdinalIgnoreCase) ||
|
||||
relative.EndsWith(".p12", StringComparison.OrdinalIgnoreCase) ||
|
||||
relative.EndsWith(".pfx", StringComparison.OrdinalIgnoreCase) ||
|
||||
relative.EndsWith(".key", StringComparison.OrdinalIgnoreCase) ||
|
||||
relative.EndsWith(".crt", StringComparison.OrdinalIgnoreCase) ||
|
||||
relative.EndsWith(".json", StringComparison.OrdinalIgnoreCase))
|
||||
zip.CreateEntryFromFile(f, relative.Replace('\\', '/'), CompressionLevel.Optimal);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void Prune(string backupDir)
|
||||
{
|
||||
foreach (string old in Directory.EnumerateFiles(backupDir, "*.zip")
|
||||
.OrderByDescending(File.GetCreationTimeUtc).Skip(_retention))
|
||||
{
|
||||
if (Path.GetFileName(old).Length > 30)
|
||||
File.Delete(old);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net10.0</TargetFramework>
|
||||
<AssemblyName>os_webinterface</AssemblyName>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<Nullable>enable</Nullable>
|
||||
</PropertyGroup>
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="../../OpenSim/Framework/OpenSim.Framework.csproj" />
|
||||
<ProjectReference Include="../../OpenSim/Region/Framework/OpenSim.Region.Framework.csproj" />
|
||||
<ProjectReference Include="../../OpenSim/Services/Interfaces/OpenSim.Services.Interfaces.csproj" />
|
||||
<Reference Include="Mono.Addins"><HintPath>../../bin/Mono.Addins.dll</HintPath><Private>false</Private></Reference>
|
||||
<Reference Include="Nini"><HintPath>../../bin/Nini.dll</HintPath><Private>false</Private></Reference>
|
||||
<Reference Include="OpenMetaverse"><HintPath>../../bin/OpenMetaverse.dll</HintPath><Private>false</Private></Reference>
|
||||
<Reference Include="OpenMetaverseTypes"><HintPath>../../bin/OpenMetaverseTypes.dll</HintPath><Private>false</Private></Reference>
|
||||
<Reference Include="log4net"><HintPath>../../bin/log4net.dll</HintPath><Private>false</Private></Reference>
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<EmbeddedResource Include="www/index.html" />
|
||||
<EmbeddedResource Include="www/app.js" />
|
||||
<EmbeddedResource Include="www/style.css" />
|
||||
</ItemGroup>
|
||||
<Target Name="CopyAddonToSimulatorBin" AfterTargets="Build" Condition="'$(DesignTimeBuild)' != 'true'">
|
||||
<Copy SourceFiles="$(TargetPath)" DestinationFiles="$(MSBuildThisFileDirectory)../../bin/$(TargetFileName)" SkipUnchangedFiles="true" />
|
||||
</Target>
|
||||
</Project>
|
||||
@@ -0,0 +1,65 @@
|
||||
"use strict";
|
||||
const $ = id => document.getElementById(id);
|
||||
let csrf="",overview=null,jobsTimer=null,modalAction=null,latestSha=null;
|
||||
const money = size => (size/(1024**2)).toFixed(1)+" MiB";
|
||||
const sleepTime = s => {const h=Math.floor(s/3600),m=Math.floor((s%3600)/60);return h+"h "+m+"m"};
|
||||
function notice(message, title="Hinweis", action=null) { $("modal-title").textContent=title; $("modal-message").textContent=message; $("modal").hidden=false; modalAction=action; $("modal-cancel").hidden=!action; }
|
||||
$("modal-ok").onclick=()=>{ $("modal").hidden=true; if(modalAction){const a=modalAction;modalAction=null;a();} };
|
||||
$("modal-cancel").onclick=()=>{$("modal").hidden=true;modalAction=null};
|
||||
async function api(path, options={}) {
|
||||
const headers = {...options.headers};
|
||||
if(options.method&&options.method!=="GET") headers["X-OGL-CSRF"]=csrf;
|
||||
const response=await fetch(path,{...options,headers,credentials:"same-origin",cache:"no-store"});
|
||||
const data=await response.json().catch(()=>({error:"Ungültige Serverantwort"}));
|
||||
if(!response.ok) throw new Error(data.error||"Serverfehler "+response.status);
|
||||
return data;
|
||||
}
|
||||
function jsonPost(path,obj){return api(path,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(obj)})}
|
||||
function row(...entries){const tr=document.createElement("tr");entries.forEach(e=>{const td=document.createElement("td");td.textContent=String(e??"–");tr.append(td)});return tr}
|
||||
function table(target,head,rows){const t=document.createElement("table"),thead=document.createElement("thead"),tbody=document.createElement("tbody");const th=document.createElement("tr");head.forEach(h=>{let x=document.createElement("th");x.textContent=h;th.append(x)});thead.append(th);rows.forEach(r=>tbody.append(r));t.append(thead,tbody);$(target).replaceChildren(t)}
|
||||
function statusCell(tr,status) {const td=tr.lastElementChild;td.replaceChildren();const span=document.createElement("span");span.className="status"+(status==="OK"?"":" bad");span.textContent=status;td.append(span)}
|
||||
function renderOverview(d) {
|
||||
overview=d; const regs=d.regions||[];
|
||||
$("num-regions").textContent=regs.length;
|
||||
$("num-avatars").textContent=regs.reduce((n,r)=>n+r.agents,0);
|
||||
$("num-memory").textContent=money(d.memoryBytes);
|
||||
$("num-uptime").textContent=sleepTime(d.uptimeSeconds);
|
||||
table("overview-regions",["Region","Koordinaten","Größe","Avatare","Status"],regs.map(r=>{const x=row(r.name,r.location,r.size,r.agents,r.ready?"OK":"Nicht bereit");statusCell(x,r.ready?"OK":"Fehler");return x}));
|
||||
table("services-table",["Dienst","Host","Port","Protokoll","Status"],(d.services||[]).map(v=>row(v.name,v.host,v.port,v.protocol,v.reachable?"Erreichbar":"Nicht erreichbar")));
|
||||
const wrapper=$("region-actions");wrapper.replaceChildren();
|
||||
regs.forEach(r=>{
|
||||
const c=document.createElement("article");c.className="region-card";
|
||||
const title=document.createElement("h3");title.textContent=r.name;
|
||||
const subtitle=document.createElement("p");subtitle.textContent="Region "+r.id;
|
||||
const inf=document.createElement("p");inf.textContent=r.location+" · "+r.size+" · "+r.agents+" Avatare · UDP "+r.udpPort+" · TCP "+r.httpPort;
|
||||
const btn=document.createElement("button");btn.className="danger";btn.textContent="Region neu starten";
|
||||
btn.onclick=()=>notice("Soll die Region „"+r.name+"“ tatsächlich neu gestartet werden? Aktive Bewohner werden unterbrochen.","Neustart bestätigen",async()=>{try{await jsonPost("/api/regions/restart",{regionId:r.id});notice("Regionsneustart wurde angefordert.");}catch(e){notice(e.message,"Fehler")}});
|
||||
c.append(title,subtitle,inf,btn);wrapper.append(c);
|
||||
});
|
||||
const sel=$("archive-region"),v=sel.value;sel.replaceChildren();
|
||||
regs.forEach(r=>{const o=document.createElement("option");o.value=r.id;o.textContent=r.name;sel.append(o)});if(regs.some(r=>r.id===v))sel.value=v;
|
||||
table("ports-table",["Region","Protokoll","Port","Lokaler Listener","Öffentlicher Zugang"],(d.endpoints||[]).map(p=>{const x=row(p.name,p.protocol,p.port,p.local?"OK":"Nicht aktiv",p.publicStatus);return x}));
|
||||
}
|
||||
async function refresh(){try{renderOverview(await api("/api/overview"));}catch(e){notice(e.message,"Verbindung fehlgeschlagen")}}
|
||||
async function loadJobs(){try{const data=await api("/api/jobs");const rows=(data.jobs||[]).map(j=>{const x=row(j.region,j.kind,j.state,j.total?(100*j.bytes/j.total).toFixed(0)+"%":"–",j.message||"–","");
|
||||
if(j.download){const a=document.createElement("a");a.href="/api/oar/download?id="+encodeURIComponent(j.id);a.textContent="OAR herunterladen";a.style.color="#69c7fb";x.lastElementChild.replaceChildren(a)}return x});
|
||||
table("job-table",["Region","Art","Status","Upload","Meldung","Download"],rows)}catch(e){notice(e.message,"Aufträge")}}
|
||||
async function loadLogs(){try{$("log-text").textContent=(await api("/api/logs")).content;}catch(e){$("log-text").textContent=e.message}}
|
||||
async function loadUpdates(){try{const live=await api("/api/updates/live-status");const status=live.update||{};$("update-live-status").textContent=live.enabled?(live.reachable?("Status: "+(status.state||"unbekannt")+" · Schritt "+(status.phase||0)+"/7 · "+(status.message||"")):live.message):"Nicht aktiviert – AllowLiveUpdates, NodeAgent und externer Updater müssen konfiguriert werden.";$("update-live-start").hidden=!(live.enabled&&live.reachable&&status.state!=="running"&&status.state!=="queued");const d=await api("/api/updates/check");latestSha=d.remote||null;$("local-sha").textContent=d.local||"Kein lokaler Git-Checkout erkannt";$("remote-sha").textContent=d.remote||"–";$("version-note").textContent=(d.newCommitCount!=null?d.newCommitCount+" Commits seit deinem Stand. ":"")+(d.error||d.note||"");const box=$("commits");box.replaceChildren();(d.commits||[]).forEach(c=>{const x=document.createElement("article");x.className="commit";const b=document.createElement("b");b.textContent=c.title;const sm=document.createElement("small");sm.textContent=c.sha.slice(0,12)+" · "+new Date(c.date).toLocaleString("de-DE");x.append(b,sm);box.append(x)})}catch(e){notice(e.message,"GitHub")}}
|
||||
function showView(name){document.querySelectorAll(".view").forEach(v=>v.hidden=v.id!==name);document.querySelectorAll("nav a").forEach(v=>v.classList.toggle("active",v.dataset.view===name));const titles={overview:"Übersicht",regions:"Regionen & Aktionen",archives:"OAR-Archive",network:"Netzwerk & Ports",logs:"Simulator-Logs",updates:"Updates & GitHub"};$("page-title").textContent=titles[name]||"Übersicht";if(name==="logs")loadLogs();if(name==="archives")loadJobs();if(name==="updates")loadUpdates();}
|
||||
document.querySelectorAll("nav a").forEach(a=>a.onclick=e=>{e.preventDefault();showView(a.dataset.view)});
|
||||
$("login-form").onsubmit=async e=>{e.preventDefault();try{const d=await api("/api/login",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({username:$("username").value,password:$("password").value})});csrf=d.csrf;$("identity").textContent=d.name;$("login-view").hidden=true;$("dashboard").hidden=false;$("password").value="";await refresh();}catch(err){notice(err.message,err.message.includes("Access Denied")?"Access Denied":"Anmeldung fehlgeschlagen")}};
|
||||
$("refresh").onclick=refresh;
|
||||
$("logout").onclick=async()=>{try{await api("/api/logout",{method:"POST"})}finally{csrf="";$("dashboard").hidden=true;$("login-view").hidden=false}};
|
||||
$("oar-file").onchange=()=>{$("selected-file").textContent=$("oar-file").files[0]?.name||""};
|
||||
$("oar-export").onclick=async()=>{try{const d=await jsonPost("/api/oar/export",{regionId:$("archive-region").value});notice("OAR-Sicherung gestartet: "+d.id);await loadJobs()}catch(e){notice(e.message,"OAR Export")}};
|
||||
$("oar-import").onclick=()=>{const f=$("oar-file").files[0];if(!f){notice("Bitte zuerst eine .oar-Datei auswählen.");return;}if(f.size>2*1024**3){notice("Die Datei überschreitet 2 GiB.");return;}notice("ACHTUNG: OAR-Import kann alle Objekte und Gelände der gewählten Region überschreiben. Jetzt „"+f.name+"“ importieren?","OAR-Import bestätigen",async()=>{try{const d=await new Promise((resolve,reject)=>{const xhr=new XMLHttpRequest();xhr.open("POST","/api/oar/import?region="+encodeURIComponent($("archive-region").value));xhr.withCredentials=true;xhr.setRequestHeader("Content-Type","application/octet-stream");xhr.setRequestHeader("X-OGL-CSRF",csrf);xhr.upload.onprogress=e=>{if(e.lengthComputable)$("selected-file").textContent="Upload: "+Math.round(e.loaded*100/e.total)+"% ("+f.name+")";};xhr.onerror=()=>reject(new Error("Netzwerkfehler beim OAR Upload"));xhr.onload=()=>{let v;try{v=JSON.parse(xhr.responseText||"{}")}catch{v={error:"Ungültige Serverantwort"}}xhr.status>=200&&xhr.status<300?resolve(v):reject(new Error(v.error||"Upload fehlgeschlagen"))};xhr.send(f)});notice("Import angenommen: "+d.id+". Status im Auftragsbereich sichtbar.");await loadJobs()}catch(e){notice(e.message,"OAR Import")}})};
|
||||
$("update-live-start").onclick=()=>notice("ACHTUNG: Der unabhängige Updater sichert lokale Konfigurationen und führt anschließend git reset --hard origin/main sowie einen .NET-10-Build aus. Die laufenden Binaries können währenddessen verändert werden. Ein Wartungsfenster und ein manueller Simulator-Neustart sind erforderlich. Update jetzt wirklich starten?","Live-Update bestätigen",async()=>{try{const d=await api("/api/updates/live-start",{method:"POST"});notice(d.note||"Live-Update angefordert.","Auftrag angenommen");await loadUpdates()}catch(e){notice(e.message,"Live-Update fehlgeschlagen")}});
|
||||
$("update-stage").onclick=()=>{if(!latestSha){notice("Bitte zuerst GitHub prüfen.");return}notice("Commit "+latestSha.slice(0,12)+" herunterladen und vertrauliche Konfiguration lokal sichern? Es werden keine laufenden Programmdateien verändert.","Update vorbereiten",async()=>{try{const d=await jsonPost("/api/updates/stage",{sha:latestSha});notice(d.note+" Sicherung: "+d.backup,"Download abgeschlossen")}catch(e){notice(e.message,"Update fehlgeschlagen")}})};
|
||||
$("logs-refresh").onclick=loadLogs;$("updates-refresh").onclick=loadUpdates;$("jobs-refresh").onclick=loadJobs;
|
||||
async function bootstrap(){try{const d=await api("/api/me");csrf=d.csrf;$("identity").textContent=d.name;$("dashboard").hidden=false;$("login-view").hidden=true;await refresh()}catch{}}bootstrap();
|
||||
setInterval(()=>{if(!$("dashboard").hidden){refresh();if(!$("archives").hidden)loadJobs()}},30000);
|
||||
|
||||
setInterval(()=>{if(!$("dashboard").hidden&&!$("archives").hidden)loadJobs()},4000);
|
||||
|
||||
setInterval(()=>{if(!$("dashboard").hidden&&!$("updates").hidden)api("/api/updates/live-status").then(d=>{const s=d.update||{};$("update-live-status").textContent=d.enabled?(d.reachable?("Status: "+(s.state||"?")+" · Schritt "+(s.phase||0)+"/7 · "+(s.message||"")):d.message):"Nicht aktiviert";$("update-live-start").hidden=!(d.enabled&&d.reachable&&s.state!=="running"&&s.state!=="queued")}).catch(()=>{})},10000);
|
||||
@@ -0,0 +1,52 @@
|
||||
<!doctype html>
|
||||
<html lang="de">
|
||||
<head>
|
||||
<meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<meta name="color-scheme" content="dark">
|
||||
<title>OpenGenesisLINK | Simulator Control</title>
|
||||
<link rel="stylesheet" href="/style.css">
|
||||
<script src="/app.js" defer></script>
|
||||
</head>
|
||||
<body>
|
||||
<div id="login-view" class="login-screen">
|
||||
<div class="login-panel">
|
||||
<div class="brand-mark">O<span>G</span>L</div>
|
||||
<p class="eyebrow">OPENGENESISLINK GENERATION 1</p>
|
||||
<h1>Simulator Control</h1>
|
||||
<p class="muted">Melde dich mit deinem Avatar-Konto an. Zugelassen sind Konten mit UserLevel größer als 0.</p>
|
||||
<form id="login-form">
|
||||
<label>Avatar-Name<input id="username" autocomplete="username" required placeholder="Vorname Nachname"></label>
|
||||
<label>Passwort<input id="password" type="password" autocomplete="current-password" required></label>
|
||||
<button type="submit" class="primary">Sicher anmelden</button>
|
||||
</form>
|
||||
<small class="muted">Zugang über den lokalen Simulator. Für externe Nutzung ist ein HTTPS-Reverse-Proxy erforderlich.</small>
|
||||
</div>
|
||||
</div>
|
||||
<div id="dashboard" hidden>
|
||||
<aside>
|
||||
<div class="side-brand"><div class="brand-mark small">O<span>G</span>L</div><div><strong>OpenGenesisLINK</strong><small>SIMULATOR CONTROL</small></div></div>
|
||||
<div class="side-label">INSTANZ</div>
|
||||
<nav><a href="#overview" data-view="overview" class="active">Übersicht</a><a href="#regions" data-view="regions">Regionen & Aktionen</a><a href="#archives" data-view="archives">OAR Sicherungen</a><a href="#network" data-view="network">Netzwerk & Ports</a><a href="#logs" data-view="logs">Live-Protokoll</a><a href="#updates" data-view="updates">Updates & GitHub</a></nav>
|
||||
<div class="side-footer"><span class="live-dot"></span> Simulator-Verwaltung lokal <p>Verbindung zu einem laufenden Simulatorprozess</p></div>
|
||||
</aside>
|
||||
<main>
|
||||
<header class="topbar"><div><span class="eyebrow">ADMINISTRATIONSZENTRALE</span><h2 id="page-title">Übersicht</h2></div><div class="top-right"><span id="identity" class="pill">Administrator</span><button id="refresh" class="ghost">Aktualisieren</button><button id="logout" class="ghost">Abmelden</button></div></header>
|
||||
<section id="overview" class="view">
|
||||
<div class="hero"><div><span class="eyebrow">SYSTEM CONTROL</span><h2>Deine virtuelle Infrastruktur.<br><em>Alles im Blick.</em></h2><p>Status, Regionen, Speicher und Dienste deiner Simulatorinstanz – zentral verwaltet.</p></div><div class="hero-ring"><span>OGL</span><small>GEN 1</small></div></div>
|
||||
<div class="stats">
|
||||
<article class="stat"><p>Geladene Regionen</p><strong id="num-regions">–</strong><small>in dieser Instanz</small></article>
|
||||
<article class="stat"><p>Avatare online</p><strong id="num-avatars">–</strong><small>Root-Avatare</small></article>
|
||||
<article class="stat"><p>Arbeitsspeicher</p><strong id="num-memory">–</strong><small>Simulator-Prozess</small></article>
|
||||
<article class="stat"><p>Instanz-Uptime</p><strong id="num-uptime">–</strong><small>seit Webmodul-Start</small></article>
|
||||
</div>
|
||||
<section class="panel"><div class="section-head"><div><h3>ROBUST & Grid-Dienste</h3><p>TCP-Erreichbarkeit der konfigurierten Service-Endpunkte</p></div></div><div id="services-table" class="table-wrap"></div></section><section class="panel"><div class="section-head"><div><h3>Regionen im Überblick</h3><p>Bereitschaft, aktuelle Besucher und Portkonfiguration</p></div></div><div id="overview-regions" class="table-wrap"></div></section>
|
||||
</section>
|
||||
<section id="regions" class="view" hidden><div class="section-head"><div><h3>Regionen & Aktionen</h3><p>Neustart ausschließlich für lokal geladene Regionen</p></div></div><div id="region-actions" class="cards"></div></section>
|
||||
<section id="archives" class="view" hidden><div class="section-head"><div><h3>OAR-Archive</h3><p>Lokaler Export, Download und Import mit Statusverfolgung. Ein Import verändert Regionsinhalt.</p></div></div><div class="panel"><label>Region auswählen<select id="archive-region"></select></label><div class="button-row"><button id="oar-export" class="primary">OAR-Sicherung erstellen</button><label for="oar-file" class="filelabel">OAR-Datei auswählen<input type="file" id="oar-file" accept=".oar,application/octet-stream" hidden></label><button id="oar-import" class="danger">Ausgewählte OAR importieren</button></div><div class="muted" id="selected-file"></div></div><section class="panel"><div class="section-head"><h3>Archivaufträge</h3><button class="ghost" id="jobs-refresh">Status abfragen</button></div><div id="job-table" class="table-wrap"></div></section></section>
|
||||
<section id="network" class="view" hidden><div class="section-head"><div><h3>Netzwerkdiagnose</h3><p>TCP-/UDP-Listener auf dem Simulatorhost und die konfigurierte Region-Ports</p></div></div><div class="panel notice">Lokale Listener sind keine Bestätigung der externen Erreichbarkeit: Fritz!Box-Portfreigaben, CGNAT und Firewall-Regeln müssen zusätzlich von außerhalb getestet werden.</div><div id="ports-table" class="table-wrap panel"></div></section>
|
||||
<section id="logs" class="view" hidden><div class="section-head"><div><h3>Simulator-Protokoll</h3><p>Letzte 90.000 Zeichen der aktiven Logdatei</p></div><button id="logs-refresh" class="ghost">Log aktualisieren</button></div><pre id="log-text" class="terminal">Lade Protokoll …</pre></section>
|
||||
<section id="updates" class="view" hidden><div class="section-head"><div><h3>GitHub & Versionskontrolle</h3><p>Commit-Stand des offiziellen OpenGenesisLINK-Repositorys</p></div><button id="updates-refresh" class="ghost">GitHub prüfen</button></div><div class="panel"><p>Installierter Commit</p><strong id="local-sha" class="mono">–</strong><p>Aktueller Main-Commit</p><strong id="remote-sha" class="mono">–</strong><div id="version-note" class="muted"></div><div class="button-row"><button class="primary" id="update-stage">Quellcode herunterladen & Konfiguration sichern</button></div></div><section class="panel"><h3>Unabhängiger Live-Updater</h3><p id="update-live-status" class="muted">Status wird geprüft ...</p><div class="button-row"><button class="danger" id="update-live-start" hidden>Update installieren (manueller Neustart danach)</button></div></section><section class="panel"><h3>Letzte Änderungen</h3><div id="commits"></div></section><div class="panel notice">Die Download-Schaltfläche bereitet ein Update nur vor: GitHub-Quellcode herunterladen, lokale Konfiguration sicher sichern und alte Backups nach Retentionsregel entfernen. Ein produktives In-place-Update kann optional an den vorhandenen, unabhängig installierten und authentifizierten OGL-Node-Updater delegiert werden. Das erfordert zwei explizite Freigaben und wird vor Start bestätigt. Danach ist ein manueller Neustart erforderlich.</div></section>
|
||||
</main>
|
||||
</div>
|
||||
<div id="modal" class="modal" hidden><div class="dialog" role="alertdialog" aria-modal="true" aria-labelledby="modal-title"><div class="modal-icon">!</div><h3 id="modal-title">Hinweis</h3><p id="modal-message"></p><div class="button-row"><button class="primary" id="modal-ok">Verstanden</button><button class="ghost" id="modal-cancel" hidden>Abbrechen</button></div></div></div>
|
||||
</body></html>
|
||||
@@ -0,0 +1 @@
|
||||
:root{color-scheme:dark;font-family:Inter,ui-sans-serif,system-ui,-apple-system,"Segoe UI",sans-serif;background:#0b101b;color:#e9eef9;font-size:14px}*{box-sizing:border-box}body{margin:0;min-height:100vh}button,input,select{font:inherit}button{cursor:pointer;border-radius:10px;padding:10px 17px;border:1px solid #30415a;background:#161f32;color:#eef5ff}button:hover{filter:brightness(1.17)}button.primary{background:linear-gradient(120deg,#24b2ef,#087bdd);color:white;border:0;font-weight:700}button.danger{color:#ffb6b8;border-color:#92484d}button.ghost{background:#151e2d}.muted,p{color:#94a5bb}.eyebrow{letter-spacing:.22em;font-size:10px;color:#6cc9f2;font-weight:750}.brand-mark{width:64px;height:64px;display:grid;place-items:center;font-weight:900;letter-spacing:-.17em;padding-right:.15em;font-size:22px;background:linear-gradient(135deg,#17ade4,#6244bf);border-radius:18px;box-shadow:0 10px 34px #0788cc44}.brand-mark span{color:#b9eafe}.brand-mark.small{width:46px;height:46px;border-radius:14px;font-size:17px}h1{font-size:35px;margin:.6em 0 .25em}h2{font-size:30px;margin:6px 0 0;font-weight:750}h3{font-size:19px;margin:0 0 6px}.login-screen{min-height:100vh;display:grid;place-items:center;padding:25px;background:radial-gradient(ellipse at 70% 18%,#132d50 0,transparent 40%),radial-gradient(ellipse at 16% 82%,#19204c 0,transparent 48%),#0b101b}.login-panel{width:min(100%,460px);padding:46px;background:#151d2de8;border:1px solid #35425b;border-radius:24px;box-shadow:0 32px 120px #0006}.login-panel .muted{line-height:1.6}label{display:block;font-size:13px;color:#bccce1;font-weight:650;margin:18px 0}input,select{display:block;width:100%;background:#0d1523;border:1px solid #36455e;border-radius:9px;padding:13px;color:#ecf3fc;margin-top:8px;outline:0}input:focus,select:focus{border-color:#51bdf3}.login-panel .primary{width:100%;margin:12px 0 18px;padding:14px}small{font-size:11px}aside{position:fixed;inset:0 auto 0 0;width:255px;background:#111927;border-right:1px solid #27374b;padding:27px 16px;display:flex;flex-direction:column}.side-brand{display:flex;gap:12px;align-items:center;padding:0 9px 33px}.side-brand strong{font-size:14px}.side-brand small{display:block;color:#7b90a8;letter-spacing:.16em;font-size:9px;margin-top:4px}.side-label{font-size:10px;color:#67819f;letter-spacing:.18em;margin:0 12px 10px}nav{display:flex;flex-direction:column;gap:4px}nav a{text-decoration:none;color:#aabbd0;padding:14px 15px;border-radius:10px;font-weight:550}nav a.active,nav a:hover{background:#1a2c45;color:#65c8ff}nav a.active{box-shadow:inset 3px 0 #22a8f6}.side-footer{margin-top:auto;font-size:12px;border-top:1px solid #25344b;padding:18px 10px 0}.side-footer p{font-size:11px}.live-dot{width:8px;height:8px;border-radius:50%;background:#4cdb9b;display:inline-block;margin-right:8px;box-shadow:0 0 14px #42bb86}main{margin-left:255px;max-width:1600px;min-height:100vh;padding:28px 38px 70px}.topbar{display:flex;justify-content:space-between;align-items:center;gap:15px;padding-bottom:28px}.top-right{display:flex;align-items:center;gap:10px}.pill{padding:9px 13px;background:#1a283c;color:#8ad5fa;border:1px solid #2b4967;border-radius:30px;white-space:nowrap}.hero{display:flex;justify-content:space-between;align-items:center;background:radial-gradient(circle at 84% 50%,#24528b70,transparent 38%),linear-gradient(120deg,#172c48,#121c30);border:1px solid #2b4666;border-radius:21px;padding:35px 43px;min-height:250px}.hero h2{font-size:36px;line-height:1.18}.hero h2 em{font-style:normal;color:#49c1f8}.hero p{max-width:420px;line-height:1.55}.hero-ring{width:160px;height:160px;border:9px solid #2f6594;box-shadow:0 0 0 1px #50c6fa99,inset 0 0 40px #159deb33,0 0 55px #39b0e922;border-radius:50%;display:flex;flex-direction:column;justify-content:center;align-items:center}.hero-ring span{font-weight:900;font-size:43px;letter-spacing:-.1em}.hero-ring small{letter-spacing:.2em;color:#62caff}.stats{display:grid;grid-template-columns:repeat(4,minmax(0,1fr));gap:16px;margin:24px 0}.stat,.panel,.region-card{border:1px solid #27364d;background:#151f30;border-radius:15px;padding:23px}.stat p{margin:0 0 12px;font-weight:650}.stat strong{font-size:30px;font-weight:800}.stat small{display:block;color:#6d87a5;margin-top:8px}.panel{margin:20px 0}.section-head{display:flex;justify-content:space-between;align-items:center;gap:15px;margin:9px 0 18px}.section-head p{font-size:12px;margin:5px 0}.table-wrap{overflow-x:auto}table{width:100%;border-collapse:collapse;text-align:left}th{font-size:11px;text-transform:uppercase;letter-spacing:.08em;color:#8299b4;padding:14px;border-bottom:1px solid #2b3e55}td{padding:14px;border-bottom:1px solid #243348;color:#c9d6e7}td strong{color:#f4f7ff}.status{display:inline-block;border-radius:15px;padding:5px 9px;background:#273e49;color:#70dbb3;font-size:11px}.status.bad{background:#412b36;color:#ffacb4}.cards{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:18px}.region-card h3{font-size:20px}.region-card p{fonLine truncated
|
||||
@@ -0,0 +1,57 @@
|
||||
// SPDX-License-Identifier: MPL-2.0
|
||||
using System.Security.Cryptography;
|
||||
using System.Text;
|
||||
|
||||
namespace OpenGenesisLINK.SysApi;
|
||||
|
||||
/// <summary>
|
||||
/// Local root-readable portal machine credential. Never log it or return it to a browser.
|
||||
/// Portal deployment can receive the credential through an authorized, secure channel.
|
||||
/// </summary>
|
||||
public static class PortalSecretStore
|
||||
{
|
||||
private const string Variable = "OGL_SYSAPI_PORTAL_TOKEN";
|
||||
|
||||
public static string OpenOrCreate(string folder)
|
||||
{
|
||||
if (OperatingSystem.IsWindows())
|
||||
throw new PlatformNotSupportedException("Windows credential-file ACL provisioning must be implemented before enabling SysApi");
|
||||
folder = Path.GetFullPath(folder);
|
||||
if (Directory.Exists(folder) && (File.GetAttributes(folder) & FileAttributes.ReparsePoint) != 0)
|
||||
throw new IOException("Symlink secret directory rejected");
|
||||
Directory.CreateDirectory(folder);
|
||||
File.SetUnixFileMode(folder, UnixFileMode.UserRead | UnixFileMode.UserWrite | UnixFileMode.UserExecute);
|
||||
string path = Path.Combine(folder, ".env");
|
||||
if (File.Exists(path))
|
||||
{
|
||||
if ((File.GetAttributes(path) & FileAttributes.ReparsePoint) != 0)
|
||||
throw new IOException("Symlink secret file rejected");
|
||||
File.SetUnixFileMode(path, UnixFileMode.UserRead | UnixFileMode.UserWrite);
|
||||
string[] matches = File.ReadAllLines(path, Encoding.UTF8)
|
||||
.Where(v => v.StartsWith(Variable + "=", StringComparison.Ordinal)).ToArray();
|
||||
if (matches.Length != 1)
|
||||
throw new IOException("Existing credential file does not contain exactly one portal token");
|
||||
string existing = matches[0][(Variable.Length + 1)..].Trim();
|
||||
if (existing.Length != 128 || !existing.All(Uri.IsHexDigit))
|
||||
throw new IOException("Existing portal token is invalid; manual rotation is required");
|
||||
return existing;
|
||||
}
|
||||
|
||||
string token = Convert.ToHexString(RandomNumberGenerator.GetBytes(64)).ToLowerInvariant();
|
||||
// CreateNew guarantees that an existing credential is never silently overwritten.
|
||||
try
|
||||
{
|
||||
using var file = new FileStream(path, FileMode.CreateNew, FileAccess.Write, FileShare.None);
|
||||
File.SetUnixFileMode(path, UnixFileMode.UserRead | UnixFileMode.UserWrite);
|
||||
byte[] data = Encoding.UTF8.GetBytes(Variable + "=" + token + Environment.NewLine);
|
||||
file.Write(data);
|
||||
file.Flush(flushToDisk: true);
|
||||
return token;
|
||||
}
|
||||
catch (IOException) when (File.Exists(path))
|
||||
{
|
||||
// Concurrent startup: reread the exact same persisted secret.
|
||||
return OpenOrCreate(folder);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
// SPDX-License-Identifier: MPL-2.0
|
||||
using log4net;
|
||||
using Nini.Config;
|
||||
using OpenSim.Framework.Servers.HttpServer;
|
||||
using OpenSim.Server.Base;
|
||||
using OpenSim.Server.Handlers.Base;
|
||||
using OpenSim.Services.Interfaces;
|
||||
|
||||
namespace OpenGenesisLINK.SysApi;
|
||||
|
||||
/// <summary>
|
||||
/// Side-by-side ROBUST service plugin. Does not replace NexVerseWorldApiConnector.
|
||||
/// Port 8851 is an INTERNAL HTTP listener; HTTPS 8850 requires an ACME-backed
|
||||
/// loopback reverse proxy, with no plaintext public listener.
|
||||
/// </summary>
|
||||
public sealed class SysApiConnector : ServiceConnector
|
||||
{
|
||||
private static readonly ILog Log = LogManager.GetLogger(typeof(SysApiConnector));
|
||||
private static SysApiHost? _host;
|
||||
private static readonly object Gate = new();
|
||||
|
||||
public SysApiConnector(IConfigSource config, IHttpServer existingRobustListener, string configName)
|
||||
: base(config, existingRobustListener, configName)
|
||||
{
|
||||
var cfg = config.Configs["SysApi"];
|
||||
if (cfg?.GetBoolean("Enabled", false) != true)
|
||||
{
|
||||
Log.Info("[SYS.API] Disabled by configuration.");
|
||||
return;
|
||||
}
|
||||
try
|
||||
{
|
||||
int port = cfg.GetInt("InternalPort", 8851);
|
||||
if (port is < 1025 or > 65535)
|
||||
throw new InvalidOperationException("Invalid SysApi internal port");
|
||||
string publicOrigin = cfg.GetString("PublicOrigin", "").Trim();
|
||||
string secretDirectory = cfg.GetString("SecretDirectory", "/etc/oglwebinterface").Trim();
|
||||
if (string.IsNullOrWhiteSpace(secretDirectory) || !Path.IsPathRooted(secretDirectory))
|
||||
throw new InvalidOperationException("SysApi secret directory must be absolute");
|
||||
lock (Gate)
|
||||
{
|
||||
if (_host != null) return;
|
||||
var accounts = LoadService<IUserAccountService>(config, "UserAccountService");
|
||||
var authentication = LoadService<IAuthenticationService>(config, "AuthenticationService");
|
||||
if (accounts is null || authentication is null)
|
||||
throw new InvalidOperationException("SYS.API requires local ROBUST account and authentication services");
|
||||
var token = PortalSecretStore.OpenOrCreate(secretDirectory);
|
||||
var host = new SysApiHost(port, publicOrigin, accounts, authentication, token);
|
||||
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);
|
||||
}
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
// Never prevent ROBUST/legacy World API startup for an optional SYS.API failure.
|
||||
Log.Error("[SYS.API] Optional module initialization failed; ROBUST and legacy World API remain available.", e);
|
||||
}
|
||||
}
|
||||
|
||||
private static T? LoadService<T>(IConfigSource config, string section) where T : class
|
||||
{
|
||||
string id = config.Configs[section]?.GetString("LocalServiceModule", "") ?? "";
|
||||
return string.IsNullOrWhiteSpace(id) ? null :
|
||||
ServerUtils.LoadPlugin<T>(id, new object[] {config});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,357 @@
|
||||
// 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 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 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)
|
||||
{
|
||||
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));
|
||||
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'; 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 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 == "/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 == "/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" },
|
||||
legacyWorldApiUnchanged = 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 (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;
|
||||
}
|
||||
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,
|
||||
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 { } }
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
if (Interlocked.Exchange(ref _disposed, 1) != 0) return;
|
||||
_stop.Cancel();
|
||||
_http.Stop();
|
||||
_http.Close();
|
||||
_sessions.Clear();
|
||||
_stop.Dispose();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net10.0</TargetFramework>
|
||||
<AssemblyName>sys.api</AssemblyName>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<Nullable>enable</Nullable>
|
||||
<GenerateAssemblyInfo>true</GenerateAssemblyInfo>
|
||||
</PropertyGroup>
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="../../OpenSim/Server/Handlers/OpenSim.Server.Handlers.csproj"/>
|
||||
<ProjectReference Include="../../OpenSim/Server/Base/OpenSim.Server.Base.csproj"/>
|
||||
<ProjectReference Include="../../OpenSim/Framework/OpenSim.Framework.csproj"/>
|
||||
<ProjectReference Include="../../OpenSim/Framework/Servers/HttpServer/OpenSim.Framework.Servers.HttpServer.csproj"/>
|
||||
<ProjectReference Include="../../OpenSim/Services/Interfaces/OpenSim.Services.Interfaces.csproj"/>
|
||||
<Reference Include="OpenMetaverse"><HintPath>../../bin/OpenMetaverse.dll</HintPath><Private>false</Private></Reference>
|
||||
<Reference Include="OpenMetaverseTypes"><HintPath>../../bin/OpenMetaverseTypes.dll</HintPath><Private>false</Private></Reference>
|
||||
<Reference Include="Nini"><HintPath>../../bin/Nini.dll</HintPath><Private>false</Private></Reference>
|
||||
<Reference Include="log4net"><HintPath>../../bin/log4net.dll</HintPath><Private>false</Private></Reference>
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<EmbeddedResource Include="www/index.html"/>
|
||||
<EmbeddedResource Include="www/app.js"/>
|
||||
<EmbeddedResource Include="www/style.css"/>
|
||||
<EmbeddedResource Include="www/ogl-mascot.webp"/>
|
||||
</ItemGroup>
|
||||
<Target Name="CopySysApiToServerBin" AfterTargets="Build" Condition="'$(DesignTimeBuild)' != 'true'">
|
||||
<Copy SourceFiles="$(TargetPath)" DestinationFiles="$(MSBuildThisFileDirectory)../../bin/$(TargetFileName)" SkipUnchangedFiles="true"/>
|
||||
</Target>
|
||||
</Project>
|
||||
@@ -0,0 +1,48 @@
|
||||
"use strict";
|
||||
const $=id=>document.getElementById(id);let csrf="";let activeModal=false;
|
||||
const int=n=>new Intl.NumberFormat("de-DE").format(n);
|
||||
const modal=(title,msg)=>{$("notice-title").textContent=title;$("notice-text").textContent=msg;$("notice").hidden=false;activeModal=true;};
|
||||
$("notice-dismiss").onclick=()=>{$("notice").hidden=true;activeModal=false};
|
||||
const json=async(path,options={})=>{
|
||||
const h={...options.headers};if(options.method&&options.method!=="GET")h["X-OGL-CSRF"]=csrf;
|
||||
const r=await fetch(path,{...options,headers:h,credentials:"same-origin",cache:"no-store"});
|
||||
const j=await r.json().catch(()=>({error:"Ungültige Antwort"}));
|
||||
if(!r.ok)throw new Error(j.error||"HTTP "+r.status);return j;
|
||||
};
|
||||
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";
|
||||
const info=$("diag");info.replaceChildren();
|
||||
for(const [label,value,good] of [
|
||||
["System API:",d.status,true],["Eigenständige DLL:","sys.api.dll",true],
|
||||
["Legacy World API:","unverändert / parallel",d.oldWorldApiUnchanged],
|
||||
["Portal Token:","gespeichert / Browserzugriff gesperrt",d.portalTokenPresent],
|
||||
["Öffentliche TLS-Origin:",d.tlsConfigured?"konfiguriert":"noch nicht eingerichtet",d.tlsConfigured]
|
||||
]){const line=document.createElement("div");const key=document.createElement("span");key.textContent=label+" ";const val=document.createElement("strong");val.className=good?"good":"";val.textContent=value;line.append(key,val);info.append(line);}
|
||||
const list=$("endpoint-list");list.replaceChildren();for(const [route,desc] of [
|
||||
["/v1/health","Öffentlicher Betriebsstatus"],
|
||||
["/api/v1/portal/ping","Server-zu-Server-Authentifizierung mit einem Token"],
|
||||
["/api/v1/portal/capabilities","Verfügbare API-Funktionen (Token erforderlich)"]
|
||||
]){const e=document.createElement("div");e.className="endpoint";const name=document.createElement("code");name.textContent="GET "+route;const small=document.createElement("small");small.textContent=desc;e.append(name,small);list.append(e);}
|
||||
};
|
||||
const showDashboard=(name,csrfToken)=>{csrf=csrfToken;$("login-shell").hidden=true;$("dashboard").hidden=false;$("admin-label").textContent=name;view().catch(e=>modal("API-Fehler",e.message))};
|
||||
$("signin").addEventListener("submit",async e=>{
|
||||
e.preventDefault();const name=$("username").value,pwd=$("password").value;
|
||||
const submit=$("signin").querySelector("button");submit.disabled=true;
|
||||
try{const d=await json("/api/session/login",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({username:name,password:pwd})});$("password").value="";showDashboard(d.name,d.csrf)}
|
||||
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;}
|
||||
});
|
||||
$("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))));
|
||||
const tick=()=>{$("clock").textContent=new Date().toLocaleTimeString("de-DE",{hour12:false})};setInterval(tick,1000);tick();
|
||||
(async()=>{try{const d=await json("/api/session");showDashboard(d.user,d.csrf)}catch{}})();
|
||||
setInterval(()=>{if(!$("dashboard").hidden)view().catch(()=>{})},30000);
|
||||
const canvas=$("stars"),ctx=canvas.getContext("2d"),reduce=window.matchMedia("(prefers-reduced-motion: reduce)").matches;
|
||||
let w=0,h=0,particles=[];
|
||||
function resize(){w=canvas.width=innerWidth;h=canvas.height=innerHeight;const count=Math.min(110,Math.floor(w*h/15000));particles=Array.from({length:count},()=>({x:Math.random()*w,y:Math.random()*h,r:.3+Math.random()*1.5,vy:.15+Math.random()*.45,phase:Math.random()*Math.PI*2}));}
|
||||
window.addEventListener("resize",resize);resize();
|
||||
function draw(t){ctx.clearRect(0,0,w,h);ctx.fillStyle="#3bbcff";for(const p of particles){let alpha=.18+.28*Math.abs(Math.sin(t*.00035+p.phase));ctx.globalAlpha=alpha;ctx.beginPath();ctx.arc(p.x,p.y,p.r,0,Math.PI*2);ctx.fill();if(!reduce){p.y-=p.vy;if(p.y<-5){p.y=h+5;p.x=Math.random()*w;}}}ctx.globalAlpha=1;if(!reduce)requestAnimationFrame(draw);}
|
||||
if(!reduce)requestAnimationFrame(draw);else draw(0);
|
||||
@@ -0,0 +1,58 @@
|
||||
<!doctype html>
|
||||
<html lang="de"><head>
|
||||
<meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
|
||||
<meta name="theme-color" content="#050a18">
|
||||
<title>OpenGenesisLINK — System API Command Center</title>
|
||||
<link rel="stylesheet" href="/style.css"><script src="/app.js" defer></script>
|
||||
</head><body>
|
||||
<canvas id="stars" aria-hidden="true"></canvas>
|
||||
<div class="background-grid" aria-hidden="true"></div>
|
||||
<div class="light halo-one" aria-hidden="true"></div><div class="light halo-two" aria-hidden="true"></div>
|
||||
<div id="login-shell">
|
||||
<div class="login-layout">
|
||||
<div class="identity-area">
|
||||
<div class="topbrand"><span class="ogl-emblem">O<span>G</span>L</span><span>OPENGENESISLINK <small>GENERATION 1 · SYSTEM CORE</small></span></div>
|
||||
<div class="mascot-halo"><div class="orbit orbit-one"></div><div class="orbit orbit-two"></div><img src="/ogl-mascot.webp" class="mascot" alt="Offizielles OGL Maskottchen"></div>
|
||||
<div class="intro"><div class="eyebrow"><span class="pulsedot"></span> OPENGENESISLINK SYSTEM API · V1</div>
|
||||
<h1>Control the <span>Next Reality.</span></h1>
|
||||
<p>Eine neue Generation der Grid-Steuerung. Unabhängig. Modular. Geschützt.</p>
|
||||
<div class="feature-tags"><span>◈ INDEPENDENT MODULE</span><span>◉ SECURE PORTAL LINK</span><span>◇ REAL-TIME CONTROL</span></div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="login-card hologram"><div class="edge-line"></div>
|
||||
<div class="card-top"><span class="small-icon">⦿</span><span class="eyebrow">SECURE ADMIN ACCESS</span><span class="status-chip"><i></i> SYSTEM READY</span></div>
|
||||
<h2>Willkommen zurück.</h2><p>Authentifiziere dich mit deinem Avatar-Konto, um das System Command Center zu öffnen.</p>
|
||||
<form id="signin">
|
||||
<label for="username">AVATAR-NAME</label><div class="field"><span>◈</span><input id="username" name="username" type="text" maxlength="128" placeholder="Vorname Nachname" autocomplete="username" required></div>
|
||||
<label for="password">PASSWORT</label><div class="field"><span>⌑</span><input id="password" name="password" type="password" placeholder="••••••••••••" autocomplete="current-password" required></div>
|
||||
<button class="big-button" type="submit"><span>ADMINISTRATORKONSOLE ÖFFNEN</span><span class="arrow">↗</span></button>
|
||||
</form>
|
||||
<div class="access"><span class="shield">⬡</span><div><strong>USERLEVEL 200+ ERFORDERLICH</strong><small>Die Anmeldung verwendet deine bestehenden Grid-Zugangsdaten.</small></div></div>
|
||||
</div>
|
||||
</div>
|
||||
<footer>© OpenGenesisLINK · SYS.API FOUNDATION <span id="clock"></span> <span>POWERED BY OGL</span></footer>
|
||||
</div>
|
||||
<div id="dashboard" hidden>
|
||||
<aside class="sidebar hologram"><div class="side-head"><span class="ogl-emblem">O<span>G</span>L</span><div><b>System Core</b><small>SYS.API // GEN 1</small></div></div>
|
||||
<div class="side-line">NAVIGATION</div>
|
||||
<nav><a href="#overview" class="selected">⌁ <span>Command Center</span></a><a href="#endpoints">▤ <span>API Endpunkte</span></a><a href="#security">⬡ <span>Security & Portal</span></a><a href="#future">▧ <span>Module (Coming Soon)</span></a></nav>
|
||||
<div class="sidebar-bottom"><img src="/ogl-mascot.webp" alt="" class="mini-mascot"><span class="live-indicator"><i></i> OGL CORE CONNECTED</span><small>LEGACY WORLD API REMAINS ACTIVE</small></div></aside>
|
||||
<main class="main"><header class="dash-header"><div><div class="eyebrow">OPENGENESISLINK / SYSTEM COMMAND</div><h2>System <span>Dashboard</span></h2></div><div class="righthead"><span id="admin-label" class="admin-label">ADMINISTRATOR</span><button id="signout" class="ghost-button">Abmelden ↗</button></div></header>
|
||||
<section id="overview" class="dash-section">
|
||||
<div class="hero-panel hologram"><div class="hero-text"><span class="eyebrow"><span class="pulsedot"></span> SYSTEM STATUS / OPERATIONAL</span><h3>One Grid.<br><em>Infinite Possibilities.</em></h3><p>Eine API. Ein Portal-Token. Keine unnötigen Scope-Schlüssel in diesem neuen Modul.</p><button class="ghost-button" id="refresh">↻ STATUS AKTUALISIEREN</button></div><img src="/ogl-mascot.webp" class="hero-mascot" alt="OGL Maskottchen"></div>
|
||||
<div class="metric-grid">
|
||||
<article class="metric hologram"><div class="label">SYS.API</div><div class="value">v1 <span>●</span></div><small>EIGENSTÄNDIGES MODUL</small></article>
|
||||
<article class="metric hologram"><div class="label">ÖFFENTLICHER HTTPS PORT</div><div class="value">8850</div><small>LET'S ENCRYPT VOR BEREITSTELLUNG</small></article>
|
||||
<article class="metric hologram"><div class="label">LAUFZEIT</div><div id="uptime" class="value">--</div><small>SEIT MODULSTART</small></article>
|
||||
<article class="metric hologram"><div class="label">ADMIN USERLEVEL</div><div class="value">200+</div><small>AVATAR LOGIN ERFORDERLICH</small></article>
|
||||
</div>
|
||||
<div class="two-cols"><section class="module-card hologram"><div class="panel-title"><span>◈</span><h3>Architektur</h3></div><div class="node-path"><div><b>STADTPORTAL</b><small>SERVER-TO-SERVER</small></div><span>⟷</span><div><b>SYS.API</b><small>PORT 8850 / TLS</small></div><span>║</span><div><b>ROBUST</b><small>ALTE API BLEIBT</small></div></div></section>
|
||||
<section class="module-card hologram"><div class="panel-title"><span>⬡</span><h3>Systemdiagnose</h3></div><div id="diag" class="diagnostic">Lade aktuelle Werte...</div></section></div>
|
||||
</section>
|
||||
<section id="endpoints" class="dash-section"><div class="section-title"><h3>API v1 Endpoints</h3><p>Grundgerüst. Weitere Funktionen folgen als eigene Module.</p></div><div class="module-card hologram" id="endpoint-list"></div></section>
|
||||
<section id="security" class="dash-section"><div class="section-title"><h3>Security & Portal</h3><p>Die Kommunikation mit dem Stadtportal erfolgt über einen einzigen geschützten Machine-Token.</p></div><div class="module-card hologram"><div class="security-pill">⬡ TOKEN GENERATED SERVER-SIDE</div><p>Der Portal-Token wird beim ersten Start unter <code>/etc/oglwebinterface/.env</code> gespeichert (0600). Er wird nicht im Browser angezeigt. Die Weitergabe an das Portal erfolgt ausschließlich über einen abgesicherten Backend-Kanal.</p><p>Für Administratoren gilt UserLevel 200+. Jeder API-Aufruf mit Avatar-Sitzung wird erneut berechtigt.</p></div></section>
|
||||
<section id="future" class="dash-section"><div class="section-title"><h3>API Modules</h3><p>Bereit für deine nächsten Funktionsvorgaben.</p></div><div class="module-card hologram"><div class="module-pending">+ Neue API-Module werden hier integriert, ohne die bestehende World API abzuschalten.</div></div></section>
|
||||
</main>
|
||||
</div>
|
||||
<div id="notice" class="modal" hidden><div class="modal-card hologram" role="alertdialog" aria-labelledby="notice-title" aria-modal="true"><span class="alert-icon">!</span><h3 id="notice-title">Access Denied</h3><p id="notice-text">Keine Berechtigung.</p><button id="notice-dismiss" class="big-button">VERSTANDEN</button></div></div>
|
||||
</body></html>
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 79 KiB |
@@ -0,0 +1 @@
|
||||
:root{color-scheme:dark;--cyan:#29e5ff;--blue:#138fff;--violet:#8c5bff;--ink:#050915;--panel:#101b31d9;--edge:#42a7df36;--pale:#b3cbe0}*{box-sizing:border-box}html{scroll-behavior:smooth}body{font:14px/1.5 Inter,ui-sans-serif,system-ui,-apple-system,"Segoe UI",sans-serif;color:#eaf7ff;background:radial-gradient(ellipse at 80% 20%,#11345f 0%,transparent 50%),#050916;margin:0;min-height:100vh;overflow-x:hidden}button,input{font:inherit}a{color:inherit;text-decoration:none}button{cursor:pointer}#stars,.background-grid{position:fixed;inset:0;pointer-events:none;z-index:-2}#stars{height:100vh;width:100vw}.background-grid{z-index:-1;background-image:linear-gradient(90deg,#36adff0a 1px,transparent 1px),linear-gradient(#36adff0a 1px,transparent 1px);background-size:75px 75px;mask-image:linear-gradient(to bottom,transparent,#fff 30%,#fff 75%,transparent);transform:perspective(700px) rotateX(50deg) scale(1.6);transform-origin:center 70%;animation:gridflow 28s linear infinite}.light{position:fixed;width:400px;height:400px;border-radius:50%;filter:blur(100px);z-index:-1;pointer-events:none;opacity:.24}.halo-one{background:#007bff;left:-220px;bottom:-180px;animation:float 13s ease-in-out infinite alternate}.halo-two{background:#7e3ded;right:-220px;top:5%;animation:float 16s ease-in-out infinite alternate-reverse}@keyframes gridflow{to{background-position:0 300px}}@keyframes float{to{transform:translate(150px,-90px)}}@keyframes drift{to{transform:translateY(-12px)}}@keyframes glow{50%{filter:drop-shadow(0 0 24px #24bcff88)}}@keyframes orbit{to{transform:rotate(360deg)}}@keyframes shine{to{background-position:200% 0}}[hidden]{display:none!important}.hologram{background:linear-gradient(140deg,#172c4ad1,#101829e9 70%);border:1px solid var(--edge);backdrop-filter:blur(24px);box-shadow:0 16px 70px #0006,0 0 45px #0f69c211;border-radius:22px}.eyebrow{font-size:11px;font-weight:800;letter-spacing:.23em;color:#7fe6ff}.pulsedot,.status-chip i,.live-indicator i{display:inline-block;width:8px;height:8px;background:#3bf7bf;border-radius:50%;box-shadow:0 0 16px #41eeab;animation:glow 2s infinite}.topbrand{display:flex;align-items:center;gap:17px;font-size:15px;font-weight:800;letter-spacing:.13em}.topbrand small{display:block;color:#65cde9;letter-spacing:.21em;font-size:9px;margin-top:4px}.ogl-emblem{display:inline-grid;place-items:center;width:67px;height:67px;border:1px solid #51d6ff77;border-radius:19px;background:linear-gradient(145deg,#224c9a,#15264a);box-shadow:0 0 29px #1685eb5c,inset 0 0 25px #1b96df33;font-size:26px;font-weight:1000;letter-spacing:-.14em;padding-right:.15em}.ogl-emblem span{color:var(--cyan)}.login-layout{min-height:calc(100vh - 55px);max-width:1500px;margin:auto;padding:45px clamp(25px,5vw,85px) 25px;display:grid;grid-template-columns:1.13fr .87fr;gap:clamp(25px,6vw,100px);align-items:center}.identity-area{align-self:stretch;display:flex;flex-direction:column;justify-content:space-between}.mascot-halo{height:clamp(265px,36vw,490px);position:relative;display:grid;place-items:center;margin:0 0 4px}.mascot{height:100%;max-width:100%;object-fit:contain;z-index:1;animation:drift 5s ease-in-out infinite alternate,glow 4s ease-in-out infinite}.orbit{border:1px solid #30bdff45;position:absolute;border-radius:50%;width:min(76%,450px);aspect-ratio:1;box-shadow:0 0 20px #1689cf28;transform:rotateX(65deg);animation:orbit 36s linear infinite}.orbit-two{width:min(93%,540px);transform:rotateX(30deg) rotateZ(20deg);border-color:#6e7aff4c;animation-duration:54s;animation-direction:reverse}.intro{padding-bottom:10px}.intro h1{font-size:clamp(36px,4vw,68px);line-height:1.07;letter-spacing:-.055em;margin:15px 0}.intro h1 span{display:block;background:linear-gradient(110deg,#6ee7ff 10%,#088cff 50%,#b37cff 100%);background-size:220% auto;color:transparent;background-clip:text;animation:shine 7s ease-in-out infinite}.intro p{font-size:16px;color:var(--pale);max-width:570px}.feature-tags{display:flex;flex-wrap:wrap;gap:10px;margin-top:22px}.feature-tags span{font-size:9px;letter-spacing:.13em;color:#73cdeb;border:1px solid #3d729f7d;border-radius:7px;padding:8px 10px;background:#12345355}.login-card{position:relative;padding:clamp(28px,3.5vw,54px);max-width:550px;width:100%;margin:auto;overflow:hidden}.edge-line{position:absolute;top:0;left:16%;width:65%;height:2px;background:linear-gradient(90deg,transparent,var(--cyan),transparent);box-shadow:0 0 26px var(--cyan)}.card-top{display:flex;align-items:center;gap:12px;white-space:nowrap}.small-icon{display:grid;place-items:center;border:1px solid #39a5de66;background:#142a48;width:36px;height:36px;border-radius:11px;color:#70dcff}.status-chip{margin-left:auto;color:#75edc3;font-size:10px;letter-spacing:.07em}.status-chip i{width:6px;height:6px;margin-right:4px}.login-card h2{font-size:32px;letter-spacing:-.035em;margin:35px 0 8px}.login-card p,.module-card p{color:#adc2d8;line-height:1.8}.login-card label{display:block;margin:25px 0 10px;font-size:10px;font-weight:800;color:#98c7e5;Line truncated
|
||||
@@ -581,3 +581,17 @@
|
||||
[Architecture]
|
||||
Include-Architecture = "config-include/GridHypergrid.ini"
|
||||
|
||||
|
||||
; ============================================================================
|
||||
; OpenGenesisLINK standalone Simulator Admin Interface (separate DLL).
|
||||
; Disabled by default. Listens only on 127.0.0.1; use a HTTPS reverse proxy
|
||||
; and firewall for access from another PC. Each simulator requires its own port.
|
||||
; On successful Avatar login UserLevel MUST be greater than 0.
|
||||
[OSWebInterface]
|
||||
Enabled = false
|
||||
Port = 9847
|
||||
DataDirectory = "os-webinterface-data"
|
||||
BackupRetention = 5
|
||||
AllowLiveUpdates = false
|
||||
; Optional HTTPS-Origin of your reverse proxy, e.g. https://sim-admin.example.org
|
||||
PublicOrigin = ""
|
||||
@@ -464,3 +464,17 @@
|
||||
WebDavUsername = ""
|
||||
WebDavPasswordFile = ""
|
||||
MaximumArchiveMiB = 10240
|
||||
|
||||
; ============================================================================
|
||||
; OpenGenesisLINK standalone Simulator Admin Interface (separate DLL).
|
||||
; Disabled by default. Listens only on 127.0.0.1; use a HTTPS reverse proxy
|
||||
; and firewall for access from another PC. Each simulator requires its own port.
|
||||
; On successful Avatar login UserLevel MUST be greater than 0.
|
||||
[OSWebInterface]
|
||||
Enabled = false
|
||||
Port = 9847
|
||||
DataDirectory = "os-webinterface-data"
|
||||
BackupRetention = 5
|
||||
AllowLiveUpdates = false
|
||||
; Optional HTTPS-Origin of your reverse proxy, e.g. https://sim-admin.example.org
|
||||
PublicOrigin = ""
|
||||
@@ -148,6 +148,7 @@
|
||||
GridServiceConnector = "${Const|PrivatePort}/OpenSim.Server.Handlers.dll:GridServiceConnector"
|
||||
GridInfoServerInConnector = "${Const|PublicPort}/OpenSim.Server.Handlers.dll:GridInfoServerInConnector"
|
||||
NexVerseWorldApiConnector = "NexVerseWorldApi@${Const|PublicPort}/OGL.API.dll:NexVerseWorldApiConnector"
|
||||
SysApiConnector = "SysApi@${Const|PrivatePort}/sys.api.dll:SysApiConnector"
|
||||
NexEconomyConnector = "NexEconomy@${Const|PrivatePort}/OGL.API.dll:NexEconomyConnector"
|
||||
AuthenticationServiceConnector = "${Const|PrivatePort}/OpenSim.Server.Handlers.dll:AuthenticationServiceConnector"
|
||||
AvatarServiceConnector = "${Const|PrivatePort}/OpenSim.Server.Handlers.dll:AvatarServiceConnector"
|
||||
@@ -1164,3 +1165,14 @@
|
||||
WeatherSeed = 20261028
|
||||
TimeZone = "Europe/Berlin"
|
||||
DisplayName = "Stadt-NexVerse"
|
||||
|
||||
|
||||
; Parallel OGL System API foundation. Keeps existing World API fully intact.
|
||||
; The internal admin service listens only on 127.0.0.1:8851. Port 8850 must
|
||||
; be exposed exclusively by an HTTPS proxy with a valid ACME certificate.
|
||||
[SysApi]
|
||||
Enabled = false
|
||||
InternalPort = 8851
|
||||
PublicPort = 8850
|
||||
PublicOrigin = ""
|
||||
SecretDirectory = "/etc/oglwebinterface"
|
||||
@@ -146,6 +146,7 @@
|
||||
GridServiceConnector = "${Const|PrivatePort}/OpenSim.Server.Handlers.dll:GridServiceConnector"
|
||||
GridInfoServerInConnector = "${Const|PublicPort}/OpenSim.Server.Handlers.dll:GridInfoServerInConnector"
|
||||
NexVerseWorldApiConnector = "NexVerseWorldApi@${Const|PublicPort}/OGL.API.dll:NexVerseWorldApiConnector"
|
||||
SysApiConnector = "SysApi@${Const|PrivatePort}/sys.api.dll:SysApiConnector"
|
||||
NexEconomyConnector = "NexEconomy@${Const|PrivatePort}/OGL.API.dll:NexEconomyConnector"
|
||||
AuthenticationServiceConnector = "${Const|PrivatePort}/OpenSim.Server.Handlers.dll:AuthenticationServiceConnector"
|
||||
AvatarServiceConnector = "${Const|PrivatePort}/OpenSim.Server.Handlers.dll:AvatarServiceConnector"
|
||||
@@ -1183,3 +1184,14 @@
|
||||
SharedStorageRoot = ""
|
||||
RetentionDays = 30
|
||||
MaximumArchiveMiB = 10240
|
||||
|
||||
|
||||
; Parallel OGL System API foundation. Keeps existing World API fully intact.
|
||||
; The internal admin service listens only on 127.0.0.1:8851. Port 8850 must
|
||||
; be exposed exclusively by an HTTPS proxy with a valid ACME certificate.
|
||||
[SysApi]
|
||||
Enabled = false
|
||||
InternalPort = 8851
|
||||
PublicPort = 8850
|
||||
PublicOrigin = ""
|
||||
SecretDirectory = "/etc/oglwebinterface"
|
||||
@@ -129,6 +129,7 @@
|
||||
GridServiceConnector = "${Const|PrivatePort}/OpenSim.Server.Handlers.dll:GridServiceConnector"
|
||||
GridInfoServerInConnector = "${Const|PublicPort}/OpenSim.Server.Handlers.dll:GridInfoServerInConnector"
|
||||
NexVerseWorldApiConnector = "NexVerseWorldApi@${Const|PublicPort}/OGL.API.dll:NexVerseWorldApiConnector"
|
||||
SysApiConnector = "SysApi@${Const|PrivatePort}/sys.api.dll:SysApiConnector"
|
||||
NexEconomyConnector = "NexEconomy@${Const|PrivatePort}/OGL.API.dll:NexEconomyConnector"
|
||||
AuthenticationServiceConnector = "${Const|PrivatePort}/OpenSim.Server.Handlers.dll:AuthenticationServiceConnector"
|
||||
AvatarServiceConnector = "${Const|PrivatePort}/OpenSim.Server.Handlers.dll:AvatarServiceConnector"
|
||||
@@ -1188,3 +1189,14 @@
|
||||
SharedStorageRoot = ""
|
||||
RetentionDays = 30
|
||||
MaximumArchiveMiB = 10240
|
||||
|
||||
|
||||
; Parallel OGL System API foundation. Keeps existing World API fully intact.
|
||||
; The internal admin service listens only on 127.0.0.1:8851. Port 8850 must
|
||||
; be exposed exclusively by an HTTPS proxy with a valid ACME certificate.
|
||||
[SysApi]
|
||||
Enabled = false
|
||||
InternalPort = 8851
|
||||
PublicPort = 8850
|
||||
PublicOrigin = ""
|
||||
SecretDirectory = "/etc/oglwebinterface"
|
||||
@@ -107,6 +107,7 @@
|
||||
GridServiceConnector = "${Const|PrivatePort}/OpenSim.Server.Handlers.dll:GridServiceConnector"
|
||||
GridInfoServerInConnector = "${Const|PublicPort}/OpenSim.Server.Handlers.dll:GridInfoServerInConnector"
|
||||
NexVerseWorldApiConnector = "NexVerseWorldApi@${Const|PublicPort}/OGL.API.dll:NexVerseWorldApiConnector"
|
||||
SysApiConnector = "SysApi@${Const|PrivatePort}/sys.api.dll:SysApiConnector"
|
||||
NexEconomyConnector = "NexEconomy@${Const|PrivatePort}/OGL.API.dll:NexEconomyConnector"
|
||||
AuthenticationServiceConnector = "${Const|PrivatePort}/OpenSim.Server.Handlers.dll:AuthenticationServiceConnector"
|
||||
AvatarServiceConnector = "${Const|PrivatePort}/OpenSim.Server.Handlers.dll:AvatarServiceConnector"
|
||||
@@ -873,3 +874,14 @@
|
||||
SharedStorageRoot = ""
|
||||
RetentionDays = 30
|
||||
MaximumArchiveMiB = 10240
|
||||
|
||||
|
||||
; Parallel OGL System API foundation. Keeps existing World API fully intact.
|
||||
; The internal admin service listens only on 127.0.0.1:8851. Port 8850 must
|
||||
; be exposed exclusively by an HTTPS proxy with a valid ACME certificate.
|
||||
[SysApi]
|
||||
Enabled = false
|
||||
InternalPort = 8851
|
||||
PublicPort = 8850
|
||||
PublicOrigin = ""
|
||||
SecretDirectory = "/etc/oglwebinterface"
|
||||
+5
-8
@@ -1,12 +1,9 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
|
||||
# Normal Generation-1 server build includes OGLWeather and NexCity modules
|
||||
# via OpenSim.sln. No additional manual addon builds necessary.
|
||||
dotnet build -c Release OpenSim.sln
|
||||
for addon in OGLWeather NexTraffic NexTransit NexSmartLight OGLEnergy; do
|
||||
test -s "bin/OpenGenesisLINK.Addons.${addon}.dll" || {
|
||||
echo "Missing built addon: ${addon}" >&2
|
||||
exit 1
|
||||
}
|
||||
for addon in NexTraffic NexTransit NexSmartLight OGLWeather OGLEnergy; do
|
||||
test -s "bin/OpenGenesisLINK.Addons.${addon}.dll" || { echo "Missing city addon DLL: ${addon}" >&2; exit 1; }
|
||||
done
|
||||
test -s bin/os_webinterface.dll || { echo "Missing simulator admin DLL: os_webinterface" >&2; exit 1; }
|
||||
test -s bin/sys.api.dll || { echo "Missing ROBUST SYS.API DLL: sys.api" >&2; exit 1; }
|
||||
bash addon-modules/OGLAssetService/build.sh Release
|
||||
@@ -0,0 +1,66 @@
|
||||
# OpenGenesisLINK Generation 1 – Simulator Control (os_webinterface.dll)
|
||||
|
||||
**Status:** Opt-in addon, developer preview. **Not enabled in production.**
|
||||
|
||||
## Independent DLL
|
||||
|
||||
os_webinterface.dll is a .NET 10 Mono.Addins ISharedRegionModule, loaded by the simulator's existing region-module manager. No additional web administration handlers are added to OpenSim.dll. Each simulator has its own panel and own port.
|
||||
|
||||
The HTTP listener binds ONLY to 127.0.0.1. For remote access use an HTTPS reverse proxy with firewall and certificate, never expose the raw port through Fritz!Box. Because HttpListener matches the local Host header, the reverse proxy MUST overwrite Host to 127.0.0.1:9847 and explicitly set X-Forwarded-Host to the public domain plus X-Forwarded-Proto=https. Configure PublicOrigin as that exact public HTTPS origin (https://sim-admin.example.org); without this option external browser login is intentionally rejected.
|
||||
|
||||
Example Nginx location block (in an existing HTTPS virtual host for sim-admin.example.org):
|
||||
|
||||
location / {
|
||||
proxy_pass http://127.0.0.1:9847;
|
||||
proxy_set_header Host 127.0.0.1:9847;
|
||||
proxy_set_header X-Forwarded-Host sim-admin.example.org;
|
||||
proxy_set_header X-Forwarded-Proto https;
|
||||
}
|
||||
|
||||
Configure PublicOrigin = "https://sim-admin.example.org" and ensure Nginx never forwards client-supplied Forwarded headers unmodified. You must configure real TLS certificates and outside firewall separately.
|
||||
|
||||
## Configuration (simulator bin/OpenSim.ini)
|
||||
|
||||
[OSWebInterface]
|
||||
Enabled = true
|
||||
Port = 9847
|
||||
DataDirectory = "os-webinterface-data"
|
||||
BackupRetention = 5
|
||||
AllowLiveUpdates = false
|
||||
PublicOrigin = ""
|
||||
|
||||
Default Enabled=false; activating requires ONE planned simulator restart. Every simulator process must use a distinct port.
|
||||
|
||||
## Avatar authentication and authorization
|
||||
|
||||
Login with the local avatar first + last name (or First.Last) and its password. The simulator's native account and authentication services validate credentials. Only active avatars with UserLevel > 0 can log in. A valid avatar with UserLevel <= 0 receives HTTP 403: Access Denied – Keine Berechtigung.
|
||||
|
||||
Security: cryptographically random one-hour HttpOnly SameSite=Strict sessions; Secure cookies behind HTTPS; permissions revalidated on every request; CSRF and Origin checks for mutations; anti-bruteforce backoff; restrictive CSP. Passwords are never stored or echoed.
|
||||
|
||||
**UserLevel > 0 is full simulator administrative authority in this module.** Do not elevate untrusted accounts or publish the panel without strong TLS/firewall protection.
|
||||
|
||||
## Functionality
|
||||
|
||||
* Overview: Region ID/name, grid coordinates, size, readiness, root avatars, scripts/physics settings, RAM, uptime, UDP/TCP ports.
|
||||
* Region actions: restart a single local scene after explicit confirmation. Other simulator instances are not controlled by this DLL.
|
||||
* OAR: asynchronous export to a local archive, download, upload and import with job status and byte count (2 GiB limit). Existing OGL archive feature gates are enforced by the underlying archiver and NOT bypassed.
|
||||
* Logs: last 90,000 characters of OpenSim.log or the newest log inside the logs directory.
|
||||
* Services: probes configured ROBUST/Grid/Asset/Inventory/User/Authentication/Presence/Friends/Hypergrid endpoint TCP reachability (not application-level correctness).
|
||||
* Network: checks local TCP/UDP listeners. External reachability cannot be inferred from this alone: Fritz!Box, NAT/CGNAT, ISP inbound restrictions and firewall must be independently probed from outside the LAN.
|
||||
* Git: check current SHA and latest commit titles on official OpenGenesisLINK main.
|
||||
* Safe update staging: explicitly download a pinned latest-GitHub source snapshot, create private ZIP backup of config including keyfiles, and rotate old staging backups. Staging does not compile or overwrite binaries.
|
||||
* Optional live installation: when [OSWebInterface] AllowLiveUpdates=true AND [NexVerseNodeAgent] Enabled=true AND LiveUpdateEnabled=true, and the independent, preinstalled OGL G1 node-updater.service is running on loopback with OGL_NODE_UPDATER_TOKEN, the panel can submit an explicit, confirmed live-update operation. The independent updater backs up configs, fetches official main, runs the .NET 10 build and reports 7 phases. It does NOT restart the simulator. This is an in-place update with potential service disturbance; use a maintenance window and verify rollback before activation. The external updater's backup-retention policy is separate from BackupRetention for web staging.
|
||||
|
||||
## Tests
|
||||
|
||||
python3 tools/ci/verify_os_webinterface.py
|
||||
dotnet build addons/OSWebInterface/os_webinterface.csproj -c Release
|
||||
dotnet build OpenSim.sln -c Release
|
||||
|
||||
Perform local Bomlitz acceptance before enabling on production, including valid/invalid UserLevel login, disposable-region restart, OAR roundtrip, HTTPS reverse proxy and external connectivity testing.
|
||||
|
||||
Note: Update snapshot staging is currently restricted to Linux due to required NTFS ACL enforcement for backups containing secrets on Windows. On Windows, the monitoring and admin functions remain available.
|
||||
|
||||
## Live update installation (optional; Linux only)
|
||||
|
||||
Read the existing standalone updater documentation: doc/OpenGenesisLINK/G1_STANDALONE_NODE_UPDATER.md. Install its systemd unit outside the source checkout, configure the same OGL_NODE_UPDATER_TOKEN (minimum 32 bytes), a valid NodeId and the loopback URL (typically http://127.0.0.1:19090/). This module NEVER runs arbitrary shell commands or accepts browser-supplied repo roots, commands or update URLs. The administrator explicitly confirms the live update; only the independent service performs git reset --hard and builds after backing up the checkout config. Always schedule downtime, back up the database separately, and restart the simulator manually when the independent service shows completed.
|
||||
@@ -0,0 +1,54 @@
|
||||
# OpenGenesisLINK Generation 1 — SYS.API foundation
|
||||
|
||||
**New opt-in ROBUST module:** \`sys.api.dll\`. The existing \`OGL.API.dll\`, its API routes, tokens and scopes remain intact. Future SYS.API business functions will be specified separately.
|
||||
|
||||
## Architecture
|
||||
- The ROBUST ServiceList loads \`SysApiConnector\` from \`sys.api.dll\`.
|
||||
- Internal service: \`http://127.0.0.1:8851\` (loopback only).
|
||||
- Public access: \`https://YOUR_DOMAIN:8850\` through a valid Let's Encrypt TLS reverse proxy (such as Nginx). Never expose plaintext on public 8850.
|
||||
- The UI uses the exact OGL mascot supplied by the operator, resized to a 500px WebP asset, plus animated particles, light beams, responsive holographic design.
|
||||
- Every instance needs a distinct internal port.
|
||||
|
||||
## ROBUST configuration
|
||||
Within the existing ServiceList, the connector is installed alongside the legacy API.
|
||||
|
||||
[SysApi]
|
||||
Enabled = true
|
||||
InternalPort = 8851
|
||||
PublicPort = 8850
|
||||
PublicOrigin = "https://YOUR_DOMAIN:8850"
|
||||
SecretDirectory = "/etc/oglwebinterface"
|
||||
|
||||
Distributed templates set Enabled=false until deliberately configured. On a Linux server the ROBUST service account must have permission to write the protected secret directory.
|
||||
|
||||
## Portal token — first start
|
||||
The module generates 64 cryptographically random bytes, persisted in \`/etc/oglwebinterface/.env\` as \`OGL_SYSAPI_PORTAL_TOKEN\`. It sets the directory 0700 and the file 0600; existing tokens survive restarts. Invalid or symlinked files fail closed. Tokens never appear in the UI, application logs or query strings.
|
||||
|
||||
The Stadtportal backend will need the same token delivered through a separate secure administrator-controlled provisioning step; the module cannot safely modify an unknown remote portal's environment automatically. Use \`Authorization: Bearer <token>\` only on backend requests. This new foundation has one token, no OAuth scopes for machine-to-machine calls; individual future actions will still need explicit server-side authorization and audit.
|
||||
|
||||
## Web administration
|
||||
Avatar username/password are checked against ROBUST's existing user and authentication services. Only active accounts with **UserLevel >= 200** can log into the dashboard. Valid credentials below level 200 receive **403 Access Denied – Keine Berechtigung**. Admin sessions use random one-hour HttpOnly/SameSite cookies, Secure behind trusted HTTPS proxy, CSRF and origin controls, rate limiting, and revalidation of UserLevel on each request.
|
||||
|
||||
Initial endpoints:
|
||||
- GET /v1/health (minimal public status)
|
||||
- GET /api/v1/portal/ping (portal token)
|
||||
- GET /api/v1/portal/capabilities (portal token)
|
||||
- GET /api/admin/overview (admin avatar session)
|
||||
|
||||
No destructive privileged API functions are exposed yet. Legacy World API remains unchanged.
|
||||
|
||||
## Let's Encrypt — mandatory prerequisites
|
||||
A domain/FQDN and successful ACME validation are REQUIRED before public TLS can be enabled. Let's Encrypt cannot issue a certificate on TCP/8850 alone. HTTP-01 uses public TCP/80, where the production ROBUST already listens; DNS-01 needs a DNS provider challenge, and TLS-ALPN needs TCP/443. Do NOT stop production ROBUST or expose unencrypted 8850 to perform issuance.
|
||||
|
||||
Use the HTTPS gateway that already terminates the city's portal TLS, or configure a routed ACME HTTP-01 webroot challenge, or an automated DNS-01 provider. With valid certificates installed at \`/etc/letsencrypt/live/YOUR_DOMAIN/{fullchain.pem,privkey.pem}\`, use \`tools/ops/sys-api-nginx-8850.conf.example\` and verify \`nginx -t\`. Enable the certbot or equivalent ACME renew timer and a deploy hook to reload nginx after renewal. The DLL never reads private certificate keys. The public proxy must replace Host with 127.0.0.1:8851, X-Forwarded-Host with YOUR_DOMAIN:8850 and X-Forwarded-Proto with https.
|
||||
|
||||
## Tests
|
||||
python3 tools/ci/verify_sys_api_foundation.py
|
||||
dotnet build addons/SysApi/sys.api.csproj -c Release
|
||||
dotnet run --project tools/ci/SysApiSmoke/SysApiSmoke.csproj -c Release
|
||||
|
||||
Smoke covers UserLevel 199 vs 200, revoked permissions, invalid credentials, bearer token, secret persistence, CSP, official mascot embedding and origin checks. Production activation and public certificate issuance require the operator's actual FQDN and an acceptance test.
|
||||
|
||||
## Automated ACME installer (after choosing a domain)
|
||||
|
||||
Once the FQDN, ACME email and externally reachable HTTP-01 webroot are configured, the root-only helper `tools/ops/sys-api-tls-install.sh <fqdn> <email> <webroot>` verifies the HTTP-01 route, obtains the official Let’s Encrypt certificate via certbot, applies the Nginx 8850 TLS template, validates Nginx, and enables the certbot renewal timer plus a reload hook. It refuses to proceed if external TCP/80 does not return the challenge. It does **not** change or stop ROBUST TCP/80. If HTTP-01 cannot be routed, issue through DNS-01 at your trusted gateway instead. Never publish 8851 or use a self-signed cert for production.
|
||||
+5
-1
@@ -37,13 +37,17 @@ case "$1" in
|
||||
addons/NexTransit/OpenGenesisLINK.Addons.NexTransit.csproj \
|
||||
addons/NexSmartLight/OpenGenesisLINK.Addons.NexSmartLight.csproj \
|
||||
addons/OGLWeather/OpenGenesisLINK.Addons.OGLWeather.csproj \
|
||||
addons/OGLEnergy/OpenGenesisLINK.Addons.OGLEnergy.csproj
|
||||
addons/OGLEnergy/OpenGenesisLINK.Addons.OGLEnergy.csproj \
|
||||
addons/OSWebInterface/os_webinterface.csproj \
|
||||
addons/SysApi/sys.api.csproj
|
||||
printf '%s\n' \
|
||||
'#!/bin/sh' 'set -eu' \
|
||||
'dotnet build -c Release OpenSim.sln' \
|
||||
'for addon in NexTraffic NexTransit NexSmartLight OGLWeather OGLEnergy; do' \
|
||||
' test -s "bin/OpenGenesisLINK.Addons.${addon}.dll" || { echo "Missing city addon DLL: ${addon}" >&2; exit 1; }' \
|
||||
'done' \
|
||||
'test -s bin/os_webinterface.dll || { echo "Missing simulator admin DLL: os_webinterface" >&2; exit 1; }' \
|
||||
'test -s bin/sys.api.dll || { echo "Missing ROBUST SYS.API DLL: sys.api" >&2; exit 1; }' \
|
||||
'bash addon-modules/OGLAssetService/build.sh Release' > compile.sh
|
||||
chmod +x compile.sh
|
||||
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net10.0</TargetFramework>
|
||||
<OutputType>Exe</OutputType>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<Nullable>enable</Nullable>
|
||||
</PropertyGroup>
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="../../../addons/OSWebInterface/os_webinterface.csproj" />
|
||||
<Reference Include="Nini"><HintPath>../../../bin/Nini.dll</HintPath><Private>true</Private></Reference>
|
||||
<Reference Include="Mono.Addins"><HintPath>../../../bin/Mono.Addins.dll</HintPath><Private>true</Private></Reference>
|
||||
</ItemGroup>
|
||||
</Project>
|
||||
@@ -0,0 +1,84 @@
|
||||
// SPDX-License-Identifier: MPL-2.0
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Net.Sockets;
|
||||
using System.Text;
|
||||
using Nini.Config;
|
||||
using OpenGenesisLINK.Addons.OSWebInterface;
|
||||
|
||||
using var probe = new TcpListener(IPAddress.Loopback, 0);
|
||||
probe.Start();
|
||||
int port = ((IPEndPoint)probe.LocalEndpoint).Port;
|
||||
probe.Stop();
|
||||
|
||||
var config = new IniConfigSource();
|
||||
IConfig entry = config.Configs.Add("OSWebInterface");
|
||||
entry.Set("Enabled", "true");
|
||||
entry.Set("Port", port.ToString());
|
||||
entry.Set("DataDirectory", "os-webinterface-smoke-test");
|
||||
entry.Set("PublicOrigin", "https://admin.example.test");
|
||||
var module = new OSWebInterfaceModule();
|
||||
module.Initialise(config);
|
||||
try
|
||||
{
|
||||
using var client = new HttpClient(new HttpClientHandler { UseCookies = false }) {
|
||||
BaseAddress = new Uri($"http://127.0.0.1:{port}/"),
|
||||
Timeout = TimeSpan.FromSeconds(8)
|
||||
};
|
||||
var home = await client.GetAsync("/");
|
||||
if (home.StatusCode != HttpStatusCode.OK)
|
||||
throw new Exception("Index document status " + home.StatusCode);
|
||||
string html = await home.Content.ReadAsStringAsync();
|
||||
if (!html.Contains("Simulator Control")) throw new Exception("Index body missing");
|
||||
if (home.Headers.Contains("Access-Control-Allow-Origin"))
|
||||
throw new Exception("Unexpected CORS header");
|
||||
if (!home.Headers.Contains("Content-Security-Policy"))
|
||||
throw new Exception("CSP missing");
|
||||
foreach (string path in new[] { "/style.css", "/app.js" })
|
||||
{
|
||||
using var staticFile = await client.GetAsync(path);
|
||||
if (staticFile.StatusCode != HttpStatusCode.OK)
|
||||
throw new Exception("Static resource missing: " + path);
|
||||
}
|
||||
using var deniedUpdate = await client.GetAsync("/api/updates/live-status");
|
||||
if (deniedUpdate.StatusCode != HttpStatusCode.Unauthorized)
|
||||
throw new Exception("Unauthenticated live-updater status not denied");
|
||||
using var foreignHostRequest = new HttpRequestMessage(HttpMethod.Get, "/");
|
||||
foreignHostRequest.Headers.Host = "admin.example.test";
|
||||
using var foreignHostResponse = await client.SendAsync(foreignHostRequest);
|
||||
if (foreignHostResponse.StatusCode != HttpStatusCode.NotFound)
|
||||
throw new Exception("Listener unexpectedly accepted foreign Host header");
|
||||
using var proxyLogin = new HttpRequestMessage(HttpMethod.Post, "/api/login");
|
||||
proxyLogin.Headers.Add("Origin", "https://admin.example.test");
|
||||
proxyLogin.Headers.Add("X-Forwarded-Host", "admin.example.test");
|
||||
proxyLogin.Headers.Add("X-Forwarded-Proto", "https");
|
||||
proxyLogin.Content = new StringContent("{\"username\":\"Test User\",\"password\":\"123\"}", Encoding.UTF8, "application/json");
|
||||
using var trusted = await client.SendAsync(proxyLogin);
|
||||
if (trusted.StatusCode != HttpStatusCode.ServiceUnavailable)
|
||||
throw new Exception("Trusted reverse proxy login did not reach authentication layer");
|
||||
using var fakeProxyLogin = new HttpRequestMessage(HttpMethod.Post, "/api/login");
|
||||
fakeProxyLogin.Headers.Add("Origin", "https://attacker.example");
|
||||
fakeProxyLogin.Headers.Add("X-Forwarded-Host", "admin.example.test");
|
||||
fakeProxyLogin.Headers.Add("X-Forwarded-Proto", "https");
|
||||
fakeProxyLogin.Content = new StringContent("{\"username\":\"Test User\",\"password\":\"123\"}", Encoding.UTF8, "application/json");
|
||||
using var fakeProxy = await client.SendAsync(fakeProxyLogin);
|
||||
if (fakeProxy.StatusCode != HttpStatusCode.Forbidden)
|
||||
throw new Exception("Forged reverse-proxy Origin was not rejected");
|
||||
using var denied = await client.GetAsync("/api/overview");
|
||||
if (denied.StatusCode != HttpStatusCode.Unauthorized)
|
||||
throw new Exception("Unauthenticated overview not denied");
|
||||
using var forged = new HttpRequestMessage(HttpMethod.Post, "/api/login");
|
||||
forged.Headers.Add("Origin", "https://attacker.example");
|
||||
forged.Content = new StringContent("{\"username\":\"Test User\",\"password\":\"123\"}",
|
||||
Encoding.UTF8, "application/json");
|
||||
using var rejected = await client.SendAsync(forged);
|
||||
if (rejected.StatusCode != HttpStatusCode.Forbidden)
|
||||
throw new Exception("Cross-origin login not denied");
|
||||
using var noBackends = await client.PostAsync("/api/login",
|
||||
new StringContent("{\"username\":\"Test User\",\"password\":\"123\"}", Encoding.UTF8,
|
||||
"application/json"));
|
||||
if (noBackends.StatusCode != HttpStatusCode.ServiceUnavailable)
|
||||
throw new Exception("Missing authentication service did not fail closed");
|
||||
Console.WriteLine("OSWebInterface HTTP smoke PASS: UI, CSP, 401, CSRF, fail-closed login and trusted HTTPS reverse proxy");
|
||||
}
|
||||
finally { module.Close(); }
|
||||
@@ -0,0 +1,133 @@
|
||||
// SPDX-License-Identifier: MPL-2.0
|
||||
using System.Net;
|
||||
using Nini.Config;
|
||||
using System.Net.Http;
|
||||
using System.Net.Sockets;
|
||||
using System.Reflection;
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
using OpenMetaverse;
|
||||
using OpenSim.Services.Interfaces;
|
||||
using OpenGenesisLINK.SysApi;
|
||||
using OpenSim.Framework;
|
||||
using System.Security.Cryptography;
|
||||
|
||||
// Invalid opt-in settings must not crash ROBUST or disable the legacy World API.
|
||||
var unavailable = new IniConfigSource();
|
||||
unavailable.Configs.Add("SysApi").Set("Enabled", "true");
|
||||
new SysApiConnector(unavailable, null!, "SysApi");
|
||||
|
||||
var dir = Path.Combine(Path.GetTempPath(), "ogl-sysapi-smoke-" + Guid.NewGuid().ToString("N"));
|
||||
string first = PortalSecretStore.OpenOrCreate(dir);
|
||||
string second = PortalSecretStore.OpenOrCreate(dir);
|
||||
if (first != second || first.Length != 128 || File.ReadAllText(Path.Combine(dir, ".env")).Contains("CorrectSecret"))
|
||||
throw new Exception("Token store not stable or secure");
|
||||
if (!OperatingSystem.IsWindows() &&
|
||||
(File.GetUnixFileMode(Path.Combine(dir, ".env")) &
|
||||
(UnixFileMode.GroupRead | UnixFileMode.OtherRead)) != 0)
|
||||
throw new Exception("Secret permissions not private");
|
||||
|
||||
using var free = new TcpListener(IPAddress.Loopback, 0);
|
||||
free.Start();
|
||||
int port = ((IPEndPoint)free.LocalEndpoint).Port;
|
||||
free.Stop();
|
||||
using var host = new SysApiHost(port, "https://sysapi.example.test:8850",
|
||||
DispatchProxy.Create<IUserAccountService, AccountProxy>(),
|
||||
DispatchProxy.Create<IAuthenticationService, AuthenticationProxy>(), first);
|
||||
host.Start();
|
||||
try
|
||||
{
|
||||
using var client = new HttpClient(new HttpClientHandler { UseCookies = true })
|
||||
{
|
||||
BaseAddress = new Uri($"http://127.0.0.1:{port}/"),
|
||||
Timeout = TimeSpan.FromSeconds(8)
|
||||
};
|
||||
static void Expect(HttpStatusCode actual, HttpStatusCode desired, string test)
|
||||
{ if (actual != desired) throw new Exception($"{test}: expected {desired}, got {actual}"); }
|
||||
using var index = await client.GetAsync("/");
|
||||
Expect(index.StatusCode, HttpStatusCode.OK, "Index");
|
||||
if (!(await index.Content.ReadAsStringAsync()).Contains("Control the"))
|
||||
throw new Exception("Interactive command center absent");
|
||||
if (!index.Headers.Contains("Content-Security-Policy"))
|
||||
throw new Exception("Missing restrictive CSP");
|
||||
foreach (string asset in new[] {"/style.css","/app.js","/ogl-mascot.webp"})
|
||||
{
|
||||
using var file = await client.GetAsync(asset);
|
||||
Expect(file.StatusCode, HttpStatusCode.OK, "asset "+asset);
|
||||
if (asset.EndsWith(".webp") && (await file.Content.ReadAsByteArrayAsync()).Length < 60000)
|
||||
throw new Exception("Official OGL mascot asset not embedded");
|
||||
}
|
||||
using var health = await client.GetAsync("/v1/health");
|
||||
Expect(health.StatusCode, HttpStatusCode.OK, "health");
|
||||
using var anonymous = await client.GetAsync("/api/admin/overview");
|
||||
Expect(anonymous.StatusCode, HttpStatusCode.Unauthorized, "dashboard 401");
|
||||
using var noToken = await client.GetAsync("/api/v1/portal/ping");
|
||||
Expect(noToken.StatusCode, HttpStatusCode.Unauthorized, "portal no token");
|
||||
client.DefaultRequestHeaders.Authorization = new("Bearer", first);
|
||||
using var yesToken = await client.GetAsync("/api/v1/portal/ping");
|
||||
Expect(yesToken.StatusCode, HttpStatusCode.OK, "portal token");
|
||||
client.DefaultRequestHeaders.Authorization = new("Bearer", new string('a',128));
|
||||
using var badToken = await client.GetAsync("/api/v1/portal/ping");
|
||||
Expect(badToken.StatusCode, HttpStatusCode.Unauthorized, "portal wrong token");
|
||||
client.DefaultRequestHeaders.Authorization = null;
|
||||
async Task<HttpResponseMessage> LoginAsync(string pw)
|
||||
{
|
||||
return await client.PostAsync("/api/session/login",
|
||||
new StringContent(JsonSerializer.Serialize(new { username="Test Operator",password=pw }),
|
||||
Encoding.UTF8, "application/json"));
|
||||
}
|
||||
using var bad = await LoginAsync("bad-password");
|
||||
Expect(bad.StatusCode, HttpStatusCode.Unauthorized, "wrong password");
|
||||
AccountProxy.Level = 199;
|
||||
using var denied = await LoginAsync("CorrectSecret");
|
||||
Expect(denied.StatusCode, HttpStatusCode.Forbidden, "user level below 200");
|
||||
AccountProxy.Level = 200;
|
||||
using var allowed = await LoginAsync("CorrectSecret");
|
||||
Expect(allowed.StatusCode, HttpStatusCode.OK, "user level 200");
|
||||
using var admin = await client.GetAsync("/api/admin/overview");
|
||||
Expect(admin.StatusCode, HttpStatusCode.OK, "authorized dashboard");
|
||||
AccountProxy.Level = 0;
|
||||
using var revoked = await client.GetAsync("/api/admin/overview");
|
||||
Expect(revoked.StatusCode, HttpStatusCode.Unauthorized, "revoked permission");
|
||||
var forged = new HttpRequestMessage(HttpMethod.Post,"/api/session/login");
|
||||
forged.Headers.TryAddWithoutValidation("Origin","https://attacker.example");
|
||||
forged.Content = new StringContent("{}",Encoding.UTF8,"application/json");
|
||||
using var forgedResult = await client.SendAsync(forged);
|
||||
Expect(forgedResult.StatusCode, HttpStatusCode.Forbidden, "cross-origin");
|
||||
var foreignHost = new HttpRequestMessage(HttpMethod.Get,"/");
|
||||
foreignHost.Headers.Host="attacker.example";
|
||||
using var foreign = await client.SendAsync(foreignHost);
|
||||
Expect(foreign.StatusCode, HttpStatusCode.NotFound, "host binding");
|
||||
Console.WriteLine("PASS: sys.api avatar UserLevel 200 gate, revoked session, OAuth-free portal token, official mascot, CSP and origin security");
|
||||
}
|
||||
finally
|
||||
{
|
||||
Directory.Delete(dir,recursive:true);
|
||||
}
|
||||
|
||||
public class AccountProxy : DispatchProxy
|
||||
{
|
||||
public static int Level = 199;
|
||||
public static UUID Principal = UUID.Random();
|
||||
protected override object? Invoke(MethodInfo? method, object?[]? args)
|
||||
{
|
||||
if (method?.Name == "GetUserAccount")
|
||||
return new UserAccount(UUID.Zero, Principal, "Test", "Operator", "")
|
||||
{
|
||||
UserLevel = Level
|
||||
};
|
||||
throw new NotImplementedException(method?.Name);
|
||||
}
|
||||
}
|
||||
|
||||
public class AuthenticationProxy : DispatchProxy
|
||||
{
|
||||
protected override object? Invoke(MethodInfo? method, object?[]? args) =>
|
||||
method?.Name switch
|
||||
{
|
||||
"Authenticate" when (string)args![1]! == Util.Md5Hash("CorrectSecret") => UUID.Random().ToString(),
|
||||
"Authenticate" => "",
|
||||
"Release" => true,
|
||||
_ => throw new NotImplementedException(method?.Name)
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
<PropertyGroup><TargetFramework>net10.0</TargetFramework><OutputType>Exe</OutputType><ImplicitUsings>enable</ImplicitUsings><Nullable>enable</Nullable></PropertyGroup>
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="../../../addons/SysApi/sys.api.csproj"/>
|
||||
<Reference Include="Nini"><HintPath>../../../bin/Nini.dll</HintPath><Private>true</Private></Reference>
|
||||
<Reference Include="OpenMetaverseTypes"><HintPath>../../../bin/OpenMetaverseTypes.dll</HintPath><Private>true</Private></Reference>
|
||||
</ItemGroup>
|
||||
</Project>
|
||||
@@ -0,0 +1,69 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Generation 1 simulator web interface static security/integration regression."""
|
||||
from pathlib import Path
|
||||
|
||||
root = Path(__file__).resolve().parents[2]
|
||||
def text(path):
|
||||
return (root / path).read_text(encoding="utf-8-sig")
|
||||
|
||||
project = text("addons/OSWebInterface/os_webinterface.csproj")
|
||||
module = text("addons/OSWebInterface/OSWebInterfaceModule.cs")
|
||||
http = text("addons/OSWebInterface/AdminHttpServer.cs")
|
||||
ops = text("addons/OSWebInterface/AdminOperations.cs")
|
||||
updates = text("addons/OSWebInterface/UpdateStager.cs")
|
||||
live = text("addons/OSWebInterface/LiveUpdateBridge.cs")
|
||||
js = text("addons/OSWebInterface/www/app.js")
|
||||
ini_paths = ("bin/OpenSim.ini", "bin/OpenSim.ini.example")
|
||||
for ini in ini_paths:
|
||||
c = text(ini).split("[OSWebInterface]", 1)
|
||||
assert len(c) == 2 and "Enabled = false" in c[1] and "AllowLiveUpdates = false" in c[1] and 'PublicOrigin = ""' in c[1], ini
|
||||
|
||||
for part in (
|
||||
"<AssemblyName>os_webinterface</AssemblyName>",
|
||||
"EmbeddedResource Include=\"www/index.html\"",
|
||||
"EmbeddedResource Include=\"www/app.js\"",
|
||||
"EmbeddedResource Include=\"www/style.css\"",
|
||||
):
|
||||
assert part in project, part
|
||||
for part in (
|
||||
'Id = "OSWebInterface"', "ISharedRegionModule",
|
||||
'GetBoolean("Enabled", false)',
|
||||
"http://127.0.0.1:", "Directory.CreateDirectory",
|
||||
"_server?.Dispose()",
|
||||
):
|
||||
assert part in module, part
|
||||
for part in (
|
||||
"GetUserAccount(UUID.Zero", "Authenticate(account.PrincipalID",
|
||||
"account.UserLevel <= 0", "!account.LoginAllowed",
|
||||
"Access Denied – Keine Berechtigung.",
|
||||
"_liveUpdate.StatusAsync", "_liveUpdate.StartAsync",
|
||||
"HttpOnly; SameSite=Strict", "X-OGL-CSRF", "SameOrigin(",
|
||||
"Content-Security-Policy", "TrySession(request", "IsTrustedProxyRequest", "PublicOrigin",
|
||||
'"/api/regions/restart"', '"/api/oar/import"', '"/api/oar/export"',
|
||||
'"/api/oar/download"', '"/api/updates/check"', '"/api/updates/stage"',
|
||||
):
|
||||
assert part in http, part
|
||||
for part in (
|
||||
"RestartNow()", "ArchiveRegion(", "DearchiveRegion(",
|
||||
"OnOarFileSaved", "OnOarFileLoaded", "GetActiveUdpListeners",
|
||||
"GetActiveTcpListeners", "publicStatus =",
|
||||
"MaxUploadBytes", "FileShare.ReadWrite", "CheckGitAsync(",
|
||||
):
|
||||
assert part in ops, part
|
||||
for part in (
|
||||
"PrivateFile", "File.SetUnixFileMode",
|
||||
"BackupConfigs(", "configuration-backups", "Prune(",
|
||||
"File.Move(tmp, filename)", "git", "latest",
|
||||
):
|
||||
assert part in updates, part
|
||||
for marker in ("v1/status", "v1/updates", "127.0.0.1", "OGL", "Bearer", "_nodeId"):
|
||||
assert marker in live, marker
|
||||
assert "Process.Start(" not in live, "Web DLL must never run arbitrary commands."
|
||||
assert "Process.Start(" not in updates, "Updater must never execute downloaded source."
|
||||
assert "innerHTML" not in js, "Client must avoid arbitrary HTML insertion."
|
||||
assert "textContent" in js
|
||||
|
||||
for p in ("OpenSim.sln", "runprebuild.sh", "compile.sh"):
|
||||
assert "os_webinterface" in text(p) or "OSWebInterface" in text(p), p
|
||||
assert "verify_os_webinterface.py" in text(".github/workflows/nexjast-ci.yml")
|
||||
print("OS webinterface: opt-in module, auth, CSRF, OAR, logs, ports, staging and build integration OK")
|
||||
@@ -0,0 +1,44 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Static SYS.API security, branding and rollout contract."""
|
||||
from pathlib import Path
|
||||
root=Path(__file__).resolve().parents[2]
|
||||
read=lambda p:(root/p).read_text(encoding="utf-8")
|
||||
api=read("addons/SysApi/SysApiHost.cs")
|
||||
auth=read("addons/SysApi/SysApiConnector.cs")
|
||||
secret=read("addons/SysApi/PortalSecretStore.cs")
|
||||
js=read("addons/SysApi/www/app.js")
|
||||
web=read("addons/SysApi/www/index.html")
|
||||
project=read("addons/SysApi/sys.api.csproj")
|
||||
for needle in ("sys.api", "www/ogl-mascot.webp", "OpenSim.Server.Handlers.csproj"):
|
||||
assert needle in project,needle
|
||||
for needle in ('UserLevel < 200', 'Access Denied – Keine Berechtigung',
|
||||
'Authenticate(account.PrincipalID', 'GetUserAccount(UUID.Zero',
|
||||
'CryptographicOperations.FixedTimeEquals', 'HttpOnly; SameSite=Strict',
|
||||
'X-OGL-CSRF', 'IsTrustedProxy', 'Content-Security-Policy',
|
||||
'127.0.0.1:', '/api/v1/portal/ping', '/api/v1/portal/capabilities',
|
||||
'/api/admin/overview'):
|
||||
assert needle in api,needle
|
||||
for needle in ('GetBoolean("Enabled", false)', 'IUserAccountService',
|
||||
'IAuthenticationService', 'PortalSecretStore.OpenOrCreate'):
|
||||
assert needle in auth,needle
|
||||
assert "Optional module initialization failed" in auth and "catch (Exception e)" in auth
|
||||
for needle in ('FileMode.CreateNew', 'RandomNumberGenerator.GetBytes(64)',
|
||||
'UnixFileMode.UserRead | UnixFileMode.UserWrite'):
|
||||
assert needle in secret,needle
|
||||
assert "innerHTML" not in js
|
||||
assert "ogl-mascot.webp" in web
|
||||
assert (root/"addons/SysApi/www/ogl-mascot.webp").stat().st_size > 60000
|
||||
for p in ("bin/Robust.HG.ini","bin/Robust.HG.ini.example","bin/Robust.ini.example",
|
||||
"bin/Robust.HG.OGLAsset.ini.example"):
|
||||
contents=read(p)
|
||||
assert 'SysApiConnector = "SysApi@' in contents, p
|
||||
assert "[SysApi]" in contents and "Enabled = false" in contents.split("[SysApi]")[1],p
|
||||
assert "os_webinterface" in read("OpenSim.sln")
|
||||
assert "sys.api" in read("OpenSim.sln")
|
||||
assert "sys.api" in read("runprebuild.sh") and "sys.api.dll" in read("compile.sh")
|
||||
assert "NexVerseWorldApiConnector" in read("bin/Robust.HG.ini"),"Legacy World API removed"
|
||||
assert "ssl_certificate" in read("tools/ops/sys-api-nginx-8850.conf.example")
|
||||
installer=read("tools/ops/sys-api-tls-install.sh")
|
||||
for marker in ("certbot certonly", "certbot.timer", "nginx -t", "renewal-hooks/deploy", "/.well-known/acme-challenge/"):
|
||||
assert marker in installer, marker
|
||||
print("SYS.API independent DLL, UserLevel 200, persistent token, TLS proxy, legacy API and OGL mascot: PASS")
|
||||
@@ -0,0 +1,29 @@
|
||||
# OpenGenesisLINK SYS.API HTTPS on port 8850.
|
||||
# Replace YOUR_DOMAIN with the actual ACME-validated FQDN.
|
||||
# A VALID Let's Encrypt fullchain/key must exist BEFORE enabling this server.
|
||||
# This proxy only terminates TLS; sys.api.dll listens on localhost:8851.
|
||||
server {
|
||||
listen 8850 ssl;
|
||||
listen [::]:8850 ssl;
|
||||
server_name YOUR_DOMAIN;
|
||||
|
||||
ssl_certificate /etc/letsencrypt/live/YOUR_DOMAIN/fullchain.pem;
|
||||
ssl_certificate_key /etc/letsencrypt/live/YOUR_DOMAIN/privkey.pem;
|
||||
ssl_protocols TLSv1.2 TLSv1.3;
|
||||
ssl_session_tickets off;
|
||||
add_header Strict-Transport-Security "max-age=31536000" always;
|
||||
|
||||
client_max_body_size 32k;
|
||||
proxy_connect_timeout 5s;
|
||||
proxy_read_timeout 15s;
|
||||
|
||||
location / {
|
||||
proxy_pass http://127.0.0.1:8851;
|
||||
proxy_set_header Host 127.0.0.1:8851;
|
||||
proxy_set_header X-Forwarded-Host YOUR_DOMAIN:8850;
|
||||
proxy_set_header X-Forwarded-Proto https;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $remote_addr;
|
||||
proxy_set_header Authorization $http_authorization;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
#!/usr/bin/env bash
|
||||
# SPDX-License-Identifier: MPL-2.0
|
||||
# Provision TLS on external port 8850 using an already routed HTTP-01 webroot.
|
||||
# Never stops or reconfigures the ROBUST process that owns port 80.
|
||||
set -Eeuo pipefail
|
||||
if [[ $# -ne 3 ]]; then
|
||||
echo "Usage: sudo bash $0 <sysapi-fqdn> <acme-email> <public-http01-webroot>" >&2
|
||||
exit 2
|
||||
fi
|
||||
domain="$(printf '%s' "$1" | tr '[:upper:]' '[:lower:]')"
|
||||
email="$2"
|
||||
webroot="$3"
|
||||
[[ "$EUID" -eq 0 ]] || { echo "Root required" >&2; exit 2; }
|
||||
[[ "$domain" =~ ^[a-z0-9][a-z0-9.-]{2,245}[a-z0-9]$ ]] &&
|
||||
[[ "$domain" == *.* ]] && [[ "$domain" != *..* ]] ||
|
||||
{ echo "Invalid FQDN" >&2; exit 2; }
|
||||
[[ "$email" =~ ^[^[:space:]@]+@[^[:space:]@]+\.[^[:space:]@]+$ ]] ||
|
||||
{ echo "Valid ACME contact email required" >&2; exit 2; }
|
||||
[[ -d "$webroot" && ! -L "$webroot" ]] ||
|
||||
{ echo "ACME webroot missing or symlink" >&2; exit 2; }
|
||||
for binary in certbot nginx curl openssl; do
|
||||
command -v "$binary" >/dev/null ||
|
||||
{ echo "Missing $binary; install it first" >&2; exit 2; }
|
||||
done
|
||||
challenge_dir="$webroot/.well-known/acme-challenge"
|
||||
install -d -m 0755 "$challenge_dir"
|
||||
nonce="$(openssl rand -hex 16)"
|
||||
challenge="$challenge_dir/ogl-sysapi-check-$nonce"
|
||||
trap 'rm -f "$challenge"' EXIT
|
||||
printf '%s' "$nonce" > "$challenge"
|
||||
public="$(curl -fsSL --max-time 12 \
|
||||
"http://$domain/.well-known/acme-challenge/ogl-sysapi-check-$nonce" || true)"
|
||||
[[ "$public" == "$nonce" ]] ||
|
||||
{ echo "HTTP-01 cannot reach webroot through public TCP/80 for $domain." >&2
|
||||
echo "Route ACME challenges via the public gateway or use DNS-01." >&2
|
||||
exit 3; }
|
||||
certbot certonly --webroot -w "$webroot" -d "$domain" \
|
||||
--agree-tos --non-interactive --email "$email" --keep-until-expiring
|
||||
cert="/etc/letsencrypt/live/$domain/fullchain.pem"
|
||||
key="/etc/letsencrypt/live/$domain/privkey.pem"
|
||||
[[ -s "$cert" && -s "$key" ]] ||
|
||||
{ echo "Missing freshly issued certificate" >&2; exit 4; }
|
||||
template="$(dirname "$(realpath "$0")")/sys-api-nginx-8850.conf.example"
|
||||
[[ -r "$template" ]] || { echo "Nginx template missing" >&2; exit 4; }
|
||||
target=/etc/nginx/conf.d/ogl-sys-api-8850.conf
|
||||
backup=""
|
||||
if [[ -e "$target" ]]; then
|
||||
backup="$target.backup-$(date -u +%Y%m%d%H%M%S)"
|
||||
cp -p "$target" "$backup"
|
||||
fi
|
||||
sed "s/YOUR_DOMAIN/$domain/g" "$template" > "$target"
|
||||
if ! nginx -t; then
|
||||
if [[ -n "$backup" ]]; then cp -p "$backup" "$target"; else rm -f "$target"; fi
|
||||
nginx -t || true
|
||||
echo "Nginx config invalid; reverted" >&2
|
||||
exit 5
|
||||
fi
|
||||
install -d -m 0755 /etc/letsencrypt/renewal-hooks/deploy
|
||||
hook=/etc/letsencrypt/renewal-hooks/deploy/ogl-sysapi-nginx-reload
|
||||
printf '#!/bin/sh\nsystemctl reload nginx\n' > "$hook"
|
||||
chmod 0755 "$hook"
|
||||
if systemctl list-unit-files certbot.timer >/dev/null 2>&1; then
|
||||
systemctl enable --now certbot.timer
|
||||
else
|
||||
echo "Configure an ACME renewal timer for this certificate." >&2
|
||||
fi
|
||||
systemctl reload nginx || systemctl start nginx
|
||||
echo "HTTPS proxy ready at https://$domain:8850/"
|
||||
echo "Set [SysApi] PublicOrigin accordingly and verify public NAT/firewall."
|
||||
echo "Port 8851 must remain private; renewals reload Nginx."
|
||||
Reference in new issue
Block a user