using System.Collections.Concurrent;
using System.Net;
using System.Net.Sockets;
using System.Reflection;
using System.Security.Cryptography;
using System.Text.Json;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.HttpOverrides;
using Microsoft.Extensions.Logging;
namespace MSCO.Server;
///
/// Web-Panel: Anmelden, Spielerliste, Kick/Ban/Admin, Banns, Live-Konsole mit Eingabe, Chat,
/// Welt zurücksetzen, Backups, Benutzerverwaltung.
///
/// Port: Standard ist derselbe Port wie der Gameserver - der Server erkennt an den ersten Bytes, ob ein Browser
/// (HTTP) oder das Spiel verbindet, und reicht Browser-Verbindungen an das Panel weiter (das intern nur auf
/// 127.0.0.1 lauscht). Mit PanelPort in server.json läuft es stattdessen auf einem eigenen Port.
///
/// Hinter einem Reverse-Proxy: PanelTrustProxy = true übernimmt X-Forwarded-For/-Proto/-Prefix,
/// PanelBasePath (z.B. "/panel") für den Betrieb unter einem Unterpfad.
///
public sealed class AdminPanel
{
const string CookieName = "msco_panel";
const string CsrfHeader = "X-MSCO-Panel";
static readonly TimeSpan SessionLifetime = TimeSpan.FromHours(12);
static readonly TimeSpan ActionTimeout = TimeSpan.FromSeconds(8);
const int MaxLoginFailures = 8;
static readonly TimeSpan LoginWindow = TimeSpan.FromMinutes(5);
sealed class Session
{
public string User;
public DateTime Expires;
}
readonly ServerHost host; // läuft immer - der Gameserver darunter kann aus sein
readonly string dataDir;
ServerConfig config;
readonly PanelUsers users;
readonly ConcurrentDictionary sessions = new();
readonly ConcurrentDictionary> failures = new();
// Weitergereichte Verbindungen (gleicher Port): lokaler Port der Weiterleitung -> echte Adresse des Browsers
readonly ConcurrentDictionary relayed = new();
WebApplication app;
/// Einmal-Code für das erste Konto (null, sobald es einen Benutzer gibt).
public string SetupCode { get; private set; }
/// Interner Port, wenn das Panel den Spiel-Port mitbenutzt.
public int InternalPort { get; private set; }
public bool SharesGamePort { get; private set; }
AdminPanel(ServerHost host, ServerConfig config, string dataDir)
{
this.host = host;
this.dataDir = dataDir;
this.config = config;
users = new PanelUsers(Path.Combine(dataDir, "panel_users.json"));
}
// ---------------------------------------------------------------- Start
public static AdminPanel Start(ServerHost host, ServerConfig config, string dataDir)
{
var panel = new AdminPanel(host, config, dataDir);
try
{
panel.StartWeb();
}
catch (Exception e)
{
GameServer.Log("Web panel could not start: " + e.Message);
return null;
}
return panel;
}
void StartWeb()
{
SharesGamePort = config.PanelPort <= 0 || config.PanelPort == config.Port;
IPAddress bind;
int port;
if (SharesGamePort)
{
bind = IPAddress.Loopback;
port = InternalPort = FreeLoopbackPort();
}
else
{
bind = ParseBind(config.PanelBindAddress);
port = config.PanelPort;
}
var builder = WebApplication.CreateSlimBuilder(new WebApplicationOptions { ContentRootPath = AppContext.BaseDirectory });
builder.Logging.ClearProviders();
builder.WebHost.ConfigureKestrel(k =>
{
k.Listen(bind, port);
k.Limits.MaxRequestBodySize = 64 * 1024;
k.AddServerHeader = false;
});
app = builder.Build();
// Weitergereichte Verbindung: echte Browser-Adresse wiederherstellen (sonst wäre jeder 127.0.0.1)
app.Use(async (ctx, next) =>
{
var remote = ctx.Connection.RemoteIpAddress;
if (remote != null && IPAddress.IsLoopback(remote) && relayed.TryGetValue(ctx.Connection.RemotePort, out var real))
ctx.Connection.RemoteIpAddress = real;
await next();
});
if (config.PanelTrustProxy)
{
var forwarded = new ForwardedHeadersOptions
{
ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto | ForwardedHeaders.XForwardedHost
};
forwarded.KnownIPNetworks.Clear(); // jedem Proxy vertrauen (PanelTrustProxy ist eine bewusste Entscheidung)
forwarded.KnownProxies.Clear();
app.UseForwardedHeaders(forwarded);
// Proxy unter Unterpfad (Reverse-Proxy mit X-Forwarded-Prefix)
app.Use(async (ctx, next) =>
{
string prefix = ctx.Request.Headers["X-Forwarded-Prefix"];
if (!string.IsNullOrEmpty(prefix) && prefix.StartsWith('/')) ctx.Request.PathBase = prefix.TrimEnd('/');
await next();
});
}
string basePath = (config.PanelBasePath ?? "").Trim().TrimEnd('/');
if (basePath.Length > 0)
{
if (!basePath.StartsWith('/')) basePath = "/" + basePath;
app.UsePathBase(basePath);
}
// Sicherheits-Header
app.Use(async (ctx, next) =>
{
var h = ctx.Response.Headers;
h["X-Content-Type-Options"] = "nosniff";
h["X-Frame-Options"] = "DENY";
h["Referrer-Policy"] = "no-referrer";
h["Content-Security-Policy"] = "default-src 'self'; img-src 'self' data: https://avatars.steamstatic.com; style-src 'self'; script-src 'self'; frame-ancestors 'none'; base-uri 'none'; form-action 'self'";
if (ctx.Request.Path.StartsWithSegments("/api")) h["Cache-Control"] = "no-store";
await next();
});
MapFiles();
MapApi();
app.StartAsync().GetAwaiter().GetResult();
if (users.Empty) CreateSetupCode();
if (SharesGamePort)
GameServer.Log($"Web panel: http://:{config.Port}/{(basePath.Length > 0 ? basePath.TrimStart('/') + "/" : "")} (same port as the game)");
else
GameServer.Log($"Web panel: http://{(bind.Equals(IPAddress.Any) ? "" : bind.ToString())}:{port}{basePath}/");
}
/// Neu gelesene Einstellungen (der Host liest server.json bei jedem Start neu).
public void UpdateConfig(ServerConfig newConfig) => config = newConfig;
public void Stop()
{
try
{
using var timeout = new CancellationTokenSource(TimeSpan.FromSeconds(2));
app?.StopAsync(timeout.Token).GetAwaiter().GetResult();
}
catch { }
}
void CreateSetupCode()
{
const string alphabet = "ABCDEFGHJKLMNPQRSTUVWXYZ23456789";
var code = new char[10];
for (int i = 0; i < code.Length; i++) code[i] = alphabet[RandomNumberGenerator.GetInt32(alphabet.Length)];
SetupCode = new string(code, 0, 5) + "-" + new string(code, 5, 5);
GameServer.Log("============================================================");
GameServer.Log(" WEB PANEL SETUP - open the panel in your browser and enter");
GameServer.Log(" this code to create the owner account: " + SetupCode);
GameServer.Log("============================================================");
}
/// Konsolenbefehl "panel": Adresse und (falls noch nötig) den Einrichtungs-Code zeigen.
public void PrintInfo()
{
GameServer.Log(SharesGamePort ? $"Web panel on the game port {config.Port}" : $"Web panel on port {config.PanelPort}");
if (SetupCode != null) GameServer.Log("Setup code for the first account: " + SetupCode);
else GameServer.Log($"{users.All().Count} panel user(s): " + string.Join(", ", users.All().Select(u => $"{u.Name} ({u.Role})")));
}
static int FreeLoopbackPort()
{
var probe = new TcpListener(IPAddress.Loopback, 0);
probe.Start();
int port = ((IPEndPoint)probe.LocalEndpoint).Port;
probe.Stop();
return port;
}
static IPAddress ParseBind(string address)
{
if (string.IsNullOrWhiteSpace(address) || address == "*" || address == "0.0.0.0") return IPAddress.Any;
if (address == "localhost") return IPAddress.Loopback;
return IPAddress.TryParse(address, out var ip) ? ip : IPAddress.Any;
}
// ---------------------------------------------------------------- Gleicher Port: HTTP erkennen und weiterreichen
/// Beginnen die Bytes wie eine HTTP-Anfrage? (Spiel-Pakete beginnen mit einer kleinen Längenangabe.)
public static bool LooksLikeHttp(byte[] b, int n)
{
if (n < 4) return false;
for (int i = 0; i < 3; i++)
if (b[i] < 'A' || b[i] > 'Z') return false;
return (b[3] >= 'A' && b[3] <= 'Z') || b[3] == ' '; // "GET ", "PUT ", POST, HEAD, DELE, OPTI, PATC ...
}
/// Browser-Verbindung vom Spiel-Port an das intern laufende Panel weiterreichen (in beide Richtungen).
public async Task RelayAsync(TcpClient browser)
{
var real = (browser.Client.RemoteEndPoint as IPEndPoint)?.Address;
using var panel = new TcpClient { NoDelay = true };
int localPort = 0;
try
{
await panel.ConnectAsync(IPAddress.Loopback, InternalPort);
localPort = ((IPEndPoint)panel.Client.LocalEndPoint).Port;
if (real != null) relayed[localPort] = real.IsIPv4MappedToIPv6 ? real.MapToIPv4() : real;
using var a = browser.GetStream();
using var b = panel.GetStream();
var up = a.CopyToAsync(b);
var down = b.CopyToAsync(a);
await Task.WhenAny(up, down);
}
catch { }
finally
{
if (localPort != 0) relayed.TryRemove(localPort, out _);
try { browser.Close(); } catch { }
}
}
// ---------------------------------------------------------------- Dateien (Oberfläche)
void MapFiles()
{
byte[] html = Resource("panel.index.html"), js = Resource("panel.app.js"), i18n = Resource("panel.i18n.js"), css = Resource("panel.app.css"), logo = Resource("panel.logo.png");
app.MapGet("/", (HttpContext ctx) =>
{
// /panel ohne Schrägstrich -> /panel/ (sonst zeigen die relativen Adressen der Seite ins Leere)
if (ctx.Request.PathBase.HasValue && !ctx.Request.Path.HasValue)
return Results.Redirect(ctx.Request.PathBase + "/");
return Results.Bytes(html, "text/html; charset=utf-8");
});
app.MapGet("/app.js", () => Results.Bytes(js, "text/javascript; charset=utf-8"));
app.MapGet("/i18n.js", () => Results.Bytes(i18n, "text/javascript; charset=utf-8"));
app.MapGet("/app.css", () => Results.Bytes(css, "text/css; charset=utf-8"));
if (logo != null) app.MapGet("/logo.png", () => Results.Bytes(logo, "image/png"));
}
static byte[] Resource(string name)
{
using var s = Assembly.GetExecutingAssembly().GetManifestResourceStream(name);
if (s == null) return null;
using var ms = new MemoryStream();
s.CopyTo(ms);
return ms.ToArray();
}
// ---------------------------------------------------------------- API
void MapApi()
{
// --- Anmeldung
app.MapGet("/api/session", (HttpContext ctx) =>
{
var user = CurrentUser(ctx);
return Results.Json(new
{
needsSetup = users.Empty,
serverName = config.Name,
user = user == null ? null : new { name = user.Name, role = user.Role.ToString() }
});
});
app.MapPost("/api/setup", async (HttpContext ctx) =>
{
if (!CsrfOk(ctx)) return Forbidden("Missing header");
if (!users.Empty || SetupCode == null) return Error(400, "The panel is already set up");
if (RateLimited(ctx)) return Error(429, "Too many attempts - wait a few minutes");
var body = await Body(ctx);
string code = Str(body, "code").Trim().ToUpperInvariant();
if (!CryptographicOperations.FixedTimeEquals(System.Text.Encoding.UTF8.GetBytes(code), System.Text.Encoding.UTF8.GetBytes(SetupCode)))
{
RecordFailure(ctx);
return Error(403, "Wrong setup code (see the server console / docker logs)");
}
string name = Str(body, "username").Trim(), password = Str(body, "password");
string error = users.Add(name, password, PanelRole.Owner);
if (error != null) return Error(400, error);
SetupCode = null;
GameServer.Log($"[panel] Owner account '{name}' created ({Ip(ctx)})");
StartSession(ctx, name);
return Results.Json(new { ok = true });
});
app.MapPost("/api/login", async (HttpContext ctx) =>
{
if (!CsrfOk(ctx)) return Forbidden("Missing header");
if (RateLimited(ctx)) return Error(429, "Too many failed logins - wait a few minutes");
var body = await Body(ctx);
var user = users.Verify(Str(body, "username").Trim(), Str(body, "password"));
if (user == null)
{
RecordFailure(ctx);
GameServer.Log($"[panel] Failed login for '{Str(body, "username").Trim()}' from {Ip(ctx)}");
return Error(401, "Wrong username or password");
}
failures.TryRemove(Ip(ctx), out _);
StartSession(ctx, user.Name);
GameServer.Log($"[panel] {user.Name} logged in ({Ip(ctx)})");
return Results.Json(new { ok = true });
});
app.MapPost("/api/logout", (HttpContext ctx) =>
{
if (!CsrfOk(ctx)) return Forbidden("Missing header");
string token = ctx.Request.Cookies[CookieName];
if (token != null) sessions.TryRemove(token, out _);
ctx.Response.Cookies.Delete(CookieName, CookieOptions(ctx));
return Results.Json(new { ok = true });
});
app.MapPost("/api/me/password", async (HttpContext ctx) =>
{
var user = Require(ctx, PanelRole.Moderator, out var denied); if (user == null) return denied;
var body = await Body(ctx);
if (users.Verify(user.Name, Str(body, "current")) == null) return Error(403, "Current password is wrong");
string error = users.SetPassword(user.Name, Str(body, "password"));
if (error != null) return Error(400, error);
GameServer.Log($"[panel] {user.Name} changed their password");
return Ok("Password changed");
});
// --- Server
app.MapGet("/api/status", async (HttpContext ctx) =>
{
var user = Require(ctx, PanelRole.Moderator, out var denied); if (user == null) return denied;
return await Run(s => s.PanelStatus(), () => host.OfflineStatus());
});
app.MapGet("/api/players", async (HttpContext ctx) =>
{
var user = Require(ctx, PanelRole.Moderator, out var denied); if (user == null) return denied;
bool withAddress = user.Role >= PanelRole.Admin; // IP-Adressen nur für Admins
return await Run(s => s.PanelPlayers(withAddress), () => Array.Empty