fix(worldapi): single-path admin login and resilient public statistics

* fix(worldapi): run admin password login and authorized panel through the same /api/v1/docs URL

* fix(worldapi): reuse native UserLevel-200 password authentication for docs login

* fix(worldapi): wire same-path Control Center authentication in Robust

* fix(worldapi): keep embedded dashboard login on the same KeyHelp-safe docs path

* ci(worldapi): require single-path docs login, scoped bearer and password+level check

* ci(worldapi): reflect same-path admin login in Experiences Control Center guard

* ci(worldapi): ensure same-path POST responds as an auth endpoint rather than HTTP 200 shell

* docs(worldapi): document simple same-path KeyHelp login and no-secret test commands

* fix(worldapi): return available resident statistics when optional GridUser history fails, mark unknown metrics null

* fix(worldapi): load public statistics without stale explorer tokens and display partial data transparently

* test(worldapi): guard partial statistics with unknown, not fabricated zero, values

* ci(worldapi): require graceful missing-GridUser statistics with truthful unknown values

* docs(worldapi): document truthful partial stats versus missing account authority

* fix(worldapi): avoid duplicate security headers on authenticated same-path docs GET
This commit is contained in:
OpenGenesis (MPL 2.0) authored and GitHub committed 2026-10-15 03:46:45 +02:00
1 parent 6986f344da
commit b6eae3c8f9
11 files changed
+322 -72

No files matched your search

+13
View File
@@ -293,6 +293,10 @@ jobs:
shell: bash
run: python3 tools/ci/verify_region_mutations.py
- name: Verify World API public statistics degraded-mode correctness
shell: bash
run: python3 tools/ci/verify_statistics_fallback.py
- name: Verify World API online region listing
shell: bash
run: python3 tools/ci/verify_region_listing.py
@@ -1139,6 +1143,15 @@ jobs:
curl --silent --fail --max-time 2 http://127.0.0.1:19090/api/v1/docs > /tmp/nexverse-api-docs.html
grep -F 'OpenGenesisLINK – Control Center' /tmp/nexverse-api-docs.html
# Same-path POST must reach the dedicated auth handler, never return
# the HTML login shell with a misleading HTTP 200. This synthetic
# smoke runs in public-only mode, so real admin login is disabled.
DOCS_LOGIN_STATUS="$(curl --silent --max-time 3 --output /tmp/ogl-docs-login.json --write-out '%{http_code}' \
-X POST -H 'Content-Type: application/json' \
--data '{"username":"ci-user","password":"not-a-real-password"}' \
http://127.0.0.1:19090/api/v1/docs)"
test "$DOCS_LOGIN_STATUS" = 503
grep -F '"error":"admin_login_unavailable"' /tmp/ogl-docs-login.json
# Full Control Center HTML must never be returned without a
# server-verified local administrator token, regardless of UI scripts.
DOCS_STATUS="$(curl --silent --output /tmp/ogl-docs-denied.txt --write-out '%{http_code}' --max-time 3 http://127.0.0.1:19090/api/v1/docs/panel)"
+14 -7
View File
@@ -585,7 +585,7 @@ Archivprüfungen bleiben auch für freigegebene Importe aktiv.</div>
<button class="action" id="adminLoginSubmit">Als Administrator anmelden</button>
<button class="action" id="adminLoginLogout" disabled>Abmelden</button>
</div>
<p class="authnote" id="adminLoginMessage" role="status">Der Login verwendet die Grid-Benutzeranmeldung <code>POST /api/v1/auth/session</code> und prüft den UserLevel auf dem Server. Das Access-Token wird nur im Arbeitsspeicher dieser Seite gehalten, nicht als Cookie oder im Browserspeicher abgelegt.</p>
<p class="authnote" id="adminLoginMessage" role="status">Der Login prüft Grid-Benutzername, Passwort und UserLevel ab 200 direkt am OGL-Server. Das Access-Token wird nur im Arbeitsspeicher dieser Seite gehalten, nicht als Cookie oder im Browserspeicher abgelegt.</p>
</div>
</section>
@@ -721,18 +721,18 @@ async function adminLogin(){
try{
const body={username,password};
if(totp)body.totp=totp;
const res=await fetch('/api/v1/auth/session',{
const res=await fetch('/api/v1/docs',{
method:'POST',headers:{'Content-Type':'application/json','Accept':'application/json'},
body:JSON.stringify(body),cache:'no-store',credentials:'same-origin'
});
const data=await res.json().catch(()=>null);
if(!res.ok)throw new Error('HTTP '+res.status+' ('+(data&&data.error||'login_failed')+')');
if(!data||typeof data!=='object'||Array.isArray(data)||!Number.isInteger(data.user_level))
throw new Error('Ungültige World-API-Login-Antwort (HTTP '+res.status+'). /api/v1/auth/session und Reverse-Proxy-Routing prüfen.');
throw new Error('Die Anmeldung konnte nicht bestätigt werden. Der Server liefert keine gültige Benutzerantwort.');
if(Number(data.user_level)<200)
throw new Error('Zugriff verweigert: UserLevel 200 erforderlich.');
if(typeof data.access_token!=='string'||data.access_token.length<24)
throw new Error('World API: Login-Antwort ohne gültiges access_token (HTTP '+res.status+'). Backend und Proxy prüfen.');
throw new Error('Anmeldung nicht möglich: Der Server konnte keine Sitzung erstellen.');
adminSessionToken=data.access_token;
adminSessionExpiry=Date.now()+Math.max(0,Number(data.expires_in||0)-30)*1000;
if(!adminIsActive())throw new Error('Administratorsitzung bereits abgelaufen.');
@@ -998,6 +998,9 @@ function renderStatistics(data){
erzeugt_am:data.generated_at,
kontostatus:states,
datenqualitaet:{
vollstaendig:quality.complete,
griduser_datenquelle:quality.griduser_source,
fehlende_kennzahlen:quality.missing_metrics||[],
registrierungsquelle:qv(quality.registered_source),
online_quelle:qv(quality.online_source),
historische_aktivitaet:qv(quality.historical_activity),
@@ -1008,8 +1011,12 @@ function renderStatistics(data){
}
async function loadStatistics(){
const headers={'Accept':'application/json'};
const bearer=$('statsBearer').value.trim()||$('bearer').value.trim()||adminAuthToken();
const key=$('statsApiKey').value.trim()||$('apiKey').value.trim();
// Do not reuse arbitrary credentials typed into the API Explorer:
// expired/incorrect bearer or API keys turn otherwise public aggregates
// into 401/403. Only the verified admin session or explicit stats
// credentials should be sent to the statistics endpoint.
const bearer=$('statsBearer').value.trim()||adminAuthToken();
const key=$('statsApiKey').value.trim();
if(bearer)headers.Authorization='Bearer '+bearer;
if(key)headers['X-NexVerse-Api-Key']=key;
$('statsStatus').textContent='Lade Statistik…';$('statsDot').className='dot';
@@ -1023,7 +1030,7 @@ async function loadStatistics(){
return;
}
renderStatistics(data||{});
$('statsStatus').textContent='Live · '+(data.protected_details?'Details':'Aggregiert')+' · '+formatStatDate(data.generated_at);
$('statsStatus').textContent='Live · '+(data.data_quality&&data.data_quality.complete===false?'Teilweise (Datenquelle fehlt)':data.protected_details?'Details':'Aggregiert')+' · '+formatStatDate(data.generated_at);
$('statsDot').className='dot good';
}catch(err){
$('statsStatus').textContent='Statistik nicht erreichbar';$('statsDot').className='dot bad';$('statsQuality').textContent=String(err);
+85 -39
View File
@@ -99,16 +99,22 @@ namespace NexVerse.Server.Api
return;
}
if (m_UserAccounts == null || m_GridUsers == null)
if (m_UserAccounts == null)
{
WriteError(
response,
HttpStatusCode.ServiceUnavailable,
"statistics_data_unavailable",
"UserAccount or GridUser statistics storage is not available.");
"UserAccount statistics storage is not available.");
return;
}
// A GridUser storage issue must not take down the entire public
// statistics endpoint when authoritative resident account totals
// can still be read. Mark activity/visitor metrics as unknown.
// If account enumeration ALSO fails, return 503 instead of
// inventing a grid with zero registered users.
try
{
BuildSummary(response, includeProtectedDetails);
@@ -133,7 +139,21 @@ namespace NexVerse.Server.Api
DateTimeOffset weekCutoff = now.AddDays(-7);
DateTimeOffset monthCutoff = now.AddDays(-30);
GridUserData[] rawRows = m_GridUsers.GetAll(string.Empty) ?? Array.Empty<GridUserData>();
bool gridUserAvailable = m_GridUsers != null;
GridUserData[] rawRows = Array.Empty<GridUserData>();
if (gridUserAvailable)
{
try
{
rawRows = m_GridUsers.GetAll(string.Empty) ?? Array.Empty<GridUserData>();
}
catch (Exception e)
{
m_Log.Warn("[NEX-STATS]: GridUser statistics unavailable; serving partial account aggregates.", e);
gridUserAvailable = false;
}
}
List<ActivityRecord> parsed = rawRows.Select(ParseActivity).Where(x => x != null).ToList();
Dictionary<string, ActivityRecord> localActivity =
@@ -153,6 +173,9 @@ namespace NexVerse.Server.Api
.ToDictionary(x => x.Key, x => MostRecent(x), StringComparer.OrdinalIgnoreCase);
List<UserAccount> accounts = LoadAccounts(localActivity, out bool completeAccountEnumeration);
if (!gridUserAvailable && !completeAccountEnumeration)
throw new InvalidOperationException(
"Both GridUser history and complete UserAccount enumeration are unavailable.");
Dictionary<string, UserAccount> accountById =
accounts.GroupBy(x => x.PrincipalID.ToString(), StringComparer.OrdinalIgnoreCase)
@@ -262,12 +285,18 @@ namespace NexVerse.Server.Api
StringComparer.OrdinalIgnoreCase)
.ToDictionary(x => x.Key, x => x.Count(), StringComparer.OrdinalIgnoreCase);
int neverLoggedIn =
accounts.Count(account =>
{
string id = account.PrincipalID.ToString();
return !localActivity.TryGetValue(id, out ActivityRecord record) || !record.LoginAt.HasValue;
});
int? neverLoggedIn = gridUserAvailable
? accounts.Count(account =>
{
string id = account.PrincipalID.ToString();
return !localActivity.TryGetValue(id, out ActivityRecord record) || !record.LoginAt.HasValue;
})
: null;
// A missing GridUser history alone does not imply that everybody
// is offline. If the PresenceService is authoritative, resident
// online counts remain meaningful, otherwise report unknown.
bool residentOnlineKnown = gridUserAvailable || presenceAvailable;
string correlationId = Correlation(response);
@@ -283,39 +312,48 @@ namespace NexVerse.Server.Api
accounts.Count(x => IsRecent(FromUnix(x.Created), weekCutoff)),
registrations_last_30_days =
accounts.Count(x => IsRecent(FromUnix(x.Created), monthCutoff)),
online_now = residentsOnline.Count,
active_last_24_hours =
accounts.Count(x => HasRecentActivity(x, localActivity, dayCutoff)),
active_last_7_days =
accounts.Count(x => HasRecentActivity(x, localActivity, weekCutoff)),
active_last_30_days =
accounts.Count(x => HasRecentActivity(x, localActivity, monthCutoff)),
online_now = residentOnlineKnown ? residentsOnline.Count : (int?)null,
active_last_24_hours = gridUserAvailable
? accounts.Count(x => HasRecentActivity(x, localActivity, dayCutoff))
: (int?)null,
active_last_7_days = gridUserAvailable
? accounts.Count(x => HasRecentActivity(x, localActivity, weekCutoff))
: (int?)null,
active_last_30_days = gridUserAvailable
? accounts.Count(x => HasRecentActivity(x, localActivity, monthCutoff))
: (int?)null,
never_logged_in = neverLoggedIn
},
hypergrid = new
{
online_now = hypergridOnline.Count,
known_visitors_total = knownHypergrid.Count,
visitors_last_7_days =
knownHypergrid.Count(x => IsRecent(x.LastActivityAt, weekCutoff)),
visitors_last_30_days =
knownHypergrid.Count(x => IsRecent(x.LastActivityAt, monthCutoff)),
known_home_grids =
knownHypergrid.Select(x => x.HomeGrid)
.Where(x => !string.IsNullOrWhiteSpace(x))
.Distinct(StringComparer.OrdinalIgnoreCase)
.Count(),
home_grids_online_now =
hypergridOnline.Select(x => x.HomeGrid)
online_now = gridUserAvailable ? hypergridOnline.Count : (int?)null,
known_visitors_total = gridUserAvailable ? knownHypergrid.Count : (int?)null,
visitors_last_7_days = gridUserAvailable
? knownHypergrid.Count(x => IsRecent(x.LastActivityAt, weekCutoff))
: (int?)null,
visitors_last_30_days = gridUserAvailable
? knownHypergrid.Count(x => IsRecent(x.LastActivityAt, monthCutoff))
: (int?)null,
known_home_grids = gridUserAvailable
? knownHypergrid.Select(x => x.HomeGrid)
.Where(x => !string.IsNullOrWhiteSpace(x))
.Distinct(StringComparer.OrdinalIgnoreCase)
.Count()
: (int?)null,
home_grids_online_now = gridUserAvailable
? hypergridOnline.Select(x => x.HomeGrid)
.Where(x => !string.IsNullOrWhiteSpace(x))
.Distinct(StringComparer.OrdinalIgnoreCase)
.Count()
: (int?)null
},
detail_level = includeProtectedDetails ? "authenticated" : "aggregate",
detail_level = !gridUserAvailable
? "partial"
: includeProtectedDetails ? "authenticated" : "aggregate",
protected_details = includeProtectedDetails,
online = new
{
total = allOnline.Count,
total = gridUserAvailable ? allOnline.Count : (int?)null,
users = includeProtectedDetails
? allOnline.Select(OnlinePayload).ToArray()
: Array.Empty<object>()
@@ -329,18 +367,26 @@ namespace NexVerse.Server.Api
: Array.Empty<object>(),
data_quality = new
{
complete = gridUserAvailable && completeAccountEnumeration,
griduser_source = gridUserAvailable ? "available" : "unavailable",
missing_metrics = gridUserAvailable
? Array.Empty<string>()
: new[] { "activity_history", "hypergrid_visitors", "hypergrid_online", "total_online" },
registered_source =
completeAccountEnumeration
? "UserAccountService aggregate"
: "GridUser/UserAccount fallback",
online_source =
presenceAvailable
? "PresenceService"
: "GridUser Online flag with five-day stale guard",
historical_activity =
"Unique identities use the latest GridUser Login/Logout timestamps.",
hypergrid_history =
"Known Hypergrid counts are distinct visitor/home-grid identities, not cumulative visit sessions.",
online_source = presenceAvailable
? "PresenceService"
: gridUserAvailable
? "GridUser Online flag with five-day stale guard"
: "unavailable",
historical_activity = gridUserAvailable
? "Unique identities use the latest GridUser Login/Logout timestamps."
: "unavailable",
hypergrid_history = gridUserAvailable
? "Known Hypergrid counts are distinct visitor/home-grid identities, not cumulative visit sessions."
: "unavailable",
exact_visit_sessions_available = false
},
correlation_id = correlationId
+10
View File
@@ -1660,6 +1660,16 @@ namespace NexVerse.Server.Api
});
}
// Dedicated Control Center route: user name and Grid password,
// local UserLevel >= 200, then the existing signed session. This is
// called by POST /api/v1/docs to keep the admin UI on one proxy path.
public void HandleControlCenterLogin(
IOSHttpRequest request,
IOSHttpResponse response)
{
HandleNativeSessionLogin(request, response, true);
}
private void HandleNativeSessionLogin(
IOSHttpRequest request,
IOSHttpResponse response,
@@ -566,6 +566,13 @@ namespace NexVerse.Server.Api
adminMinimumLevel,
new PersistentNexSecurityStore(apiConfig.GetString("SecurityStorePath", "data/nexverse-security.json")));
// Admin login now POSTs to the exact same URL serving the
// login page, /api/v1/docs. This works even when a KeyHelp
// reverse proxy routes only the public docs path correctly.
// The endpoint still checks credentials and UserLevel >= 200,
// and the dashboard is still guarded by a signed bearer.
oglDocs.ConfigureDocsSessionLogin(userRouter.HandleControlCenterLogin);
NexEconomyApi economyApi =
new NexEconomyApi(
authenticator,
+55 -6
View File
@@ -19,6 +19,7 @@ namespace NexVerse.Server.Api
{
private readonly NexApiDocsPage m_Docs = new();
private volatile NexApiAuthenticator m_Authenticator;
private Action<IOSHttpRequest, IOSHttpResponse> m_DocsSessionLogin;
private const int MinimumLevel = 200;
public OglApiDocsAccess() { }
@@ -32,11 +33,59 @@ namespace NexVerse.Server.Api
throw new ArgumentNullException(nameof(authenticator));
}
/// <summary>
/// The same URL handles the login page, password login and authenticated
/// dashboard. This avoids relying on a separate /auth/session proxy
/// rewrite for the login page hosted at a KeyHelp reverse-proxy domain.
/// A signed, short-lived bearer is still required for all admin data.
/// </summary>
public void ConfigureDocsSessionLogin(
Action<IOSHttpRequest, IOSHttpResponse> sessionLogin)
{
m_DocsSessionLogin = sessionLogin ??
throw new ArgumentNullException(nameof(sessionLogin));
}
public void HandleLogin(IOSHttpRequest request, IOSHttpResponse response)
{
// The protected panel sets its own security headers. Do not
// duplicate Cache-Control/nosniff when dispatching a bearer GET.
if (request != null &&
string.Equals(request.HttpMethod, "GET", StringComparison.OrdinalIgnoreCase) &&
(request.Headers?["Authorization"] ?? string.Empty).StartsWith(
"Bearer ", StringComparison.OrdinalIgnoreCase))
{
HandlePanel(request, response);
return;
}
CommonHeaders(response);
if (request == null ||
!string.Equals(request.HttpMethod, "GET", StringComparison.OrdinalIgnoreCase))
if (request == null)
{
Reject(response, HttpStatusCode.MethodNotAllowed, "method_not_allowed");
return;
}
if (string.Equals(request.HttpMethod, "POST", StringComparison.OrdinalIgnoreCase))
{
Action<IOSHttpRequest, IOSHttpResponse> login = m_DocsSessionLogin;
if (login == null)
{
response.StatusCode = (int)HttpStatusCode.ServiceUnavailable;
response.ContentType = "application/json; charset=utf-8";
response.RawBuffer = Encoding.UTF8.GetBytes(
"{\"error\":\"admin_login_unavailable\"}");
return;
}
// Native authentication performs the actual GridUser password,
// UserLevel 200, login state and optional account MFA checks.
// No alternate authentication scheme or public admin bypass.
login(request, response);
return;
}
if (!string.Equals(request.HttpMethod, "GET", StringComparison.OrdinalIgnoreCase))
{
Reject(response, HttpStatusCode.MethodNotAllowed, "method_not_allowed");
return;
@@ -200,7 +249,7 @@ form.addEventListener('submit',async event=>{
try{
const credentials={username:form.elements.namedItem('username').value.trim(),password:form.elements.namedItem('password').value};
if(form.elements.namedItem('totp').value.trim())credentials.totp=form.elements.namedItem('totp').value.trim();
const login=await fetch('/api/v1/auth/session',{method:'POST',headers:{'Content-Type':'application/json','Accept':'application/json'},body:JSON.stringify(credentials),cache:'no-store',credentials:'same-origin'});
const login=await fetch('/api/v1/docs',{method:'POST',headers:{'Content-Type':'application/json','Accept':'application/json'},body:JSON.stringify(credentials),cache:'no-store',credentials:'same-origin'});
form.elements.namedItem('password').value='';form.elements.namedItem('totp').value='';
const data=await login.json().catch(()=>null);
if(!login.ok)throw Error(login.status===401?'Anmeldung fehlgeschlagen. Benutzername, Passwort oder TOTP überprüfen.':'Anmeldung fehlgeschlagen (HTTP '+login.status+', '+(data&&data.error||'api_error')+').');
@@ -208,14 +257,14 @@ form.addEventListener('submit',async event=>{
// route) is NOT a successful GridUser login. Never treat a missing
// user_level as an administrator: Number(undefined) is NaN.
if(!data||typeof data!=='object'||Array.isArray(data)||!Number.isInteger(data.user_level))
throw Error('Ungültige World-API-Login-Antwort (HTTP '+login.status+'). Prüfe /api/v1/auth/session und das Reverse-Proxy-Routing.');
throw Error('Die Anmeldung konnte nicht bestätigt werden. Der Server liefert keine gültige Benutzerantwort.');
if(Number(data.user_level)<200)throw Error('Zugriff verweigert: UserLevel 200 erforderlich.');
if(typeof data.access_token!=='string'||data.access_token.length<24)
throw Error('World API: Login-Antwort ohne gültiges access_token (HTTP '+login.status+'). Bitte Login-Backend und Proxy prüfen.');
throw Error('Anmeldung nicht möglich: Der Server konnte keine Sitzung erstellen.');
token=data.access_token;
expires=Date.now()+Math.max(0,Number(data.expires_in||0)-30)*1000;
if(!expires||expires<=Date.now())throw Error('Die Administratorsitzung ist bereits abgelaufen.');
const panel=await fetch('/api/v1/docs/panel',{headers:{'Authorization':'Bearer '+token,'Accept':'text/html'},cache:'no-store',credentials:'same-origin'});
const panel=await fetch('/api/v1/docs',{headers:{'Authorization':'Bearer '+token,'Accept':'text/html'},cache:'no-store',credentials:'same-origin'});
if(!panel.ok){
const errorCode=panel.headers.get('X-OGL-Docs-Error')||'';
const messages={
+10 -1
View File
@@ -77,7 +77,16 @@ Without credentials, the endpoint returns a privacy-safe aggregate view when the
When privileged World API authentication is enabled, a Bearer token or `X-NexVerse-Api-Key` with `statistics:read` may request the protected detail view. Protected credentials must only be used over TLS or an equivalent trusted transport.
If credentials are supplied while privileged authentication is disabled, the server returns a controlled service/authentication error rather than silently ignoring the credential or falling back to an anonymous response. A missing statistics data backend returns `503 statistics_data_unavailable`; the route itself must not disappear as a 404 merely because privileged endpoints are disabled.
If credentials are supplied while privileged authentication is disabled, the server returns a controlled service/authentication error rather than silently ignoring the credential or falling back to an anonymous response. If **UserAccountService** cannot be loaded, the route still returns
`503 statistics_data_unavailable`. If the optional GridUser history provider
is missing or its query fails, but authoritative UserAccount enumeration still
works, the route returns `200` with available resident-account totals,
`data_quality.complete=false`, `griduser_source="unavailable"` and
`null` for historical, Hypergrid and other unavailable metrics.
`null` means **unknown**, never a fabricated count of zero.
If **both** GridUser history and account enumeration fail, a controlled
`503 statistics_unavailable` remains correct. The route itself must not
disappear as a 404 merely because privileged endpoints are disabled.
The response reports its effective privacy level through:
+70 -16
View File
@@ -8,39 +8,93 @@
- **Stadt-NexVerse / NexVerse:** nur Eigenname eines Grids, das OpenGenesisLINK betreibt. Das Admin-Interface darf keinen festen Grid-Namen als Produktname einsetzen.
- Die bestehenden C#-Namespaces `NexVerse.*`, die REST-Routen `/api/v1/*`, Header `X-NexVerse-Api-Key`, Umweltvariablen `NEXVERSE_*`, Datenbanknamen und Protokollfelder bleiben zur **Rückwärtskompatibilität** bestehen. Ein technischer API-Vertragswechsel erfordert eine gesonderte, versionierte Migrationsphase und Client-/Viewer-Tests.
## Browser-Oberfläche
## Browser-Oberfläche / einfache Anmeldung
`GET /api/v1/docs` gibt nur die **OGL-Administrator-Anmeldung** aus. Das vollständige Dashboard mit Übersicht, Statistik, Grid-Planer, Simulatoren, Roadmap, API-Explorer und Schlüsselverwaltung liegt unter:
Die Startadresse für Stadt-NexVerse lautet
`https://world.stadt-nexverse.de/api/v1/docs`.
`GET /api/v1/docs/panel`
Der Browser verwendet für **den gesamten Login und das Laden des
Control Centers denselben Pfad**:
Dieser zweite Endpunkt liefert **kein Dashboard-HTML**, bevor der Server eine gültige lokale Administrator-Session geprüft hat.
1. `GET /api/v1/docs`: Anmeldeformular mit Grid-Benutzername (z. B.
`Sleimer.Akina`) und Passwort anzeigen.
2. `POST /api/v1/docs`: dieselben zwei Eingaben serverseitig im
bestehenden GridUser-/AuthenticationService prüfen, danach
`UserLevel >= 200` und freigegebenen Account bestätigen.
Sofern dieses Konto aktiv TOTP nutzt, wird auch dessen bestehende
Sicherheitsprüfung eingehalten.
3. Bei gültigen Daten wird intern ein signiertes, zeitlich begrenztes
Session-Token erstellt. Die UI zeigt keine technische Token-Eingabe.
4. `GET /api/v1/docs` mit `Authorization: Bearer ...`: vollständiges
Control Center, nur nach erneuter Prüfung des lokalen Accounts.
5. Logout entfernt das Token und den eingeblendeten Admin-Frame.
Design: dunkles Glas-/Neon-Layout, cyan-violette Rahmenbeleuchtung, animierter Aurora-Hintergrund, Rastereffekt, schwebende Cards, responsive Sidebar. `prefers-reduced-motion` deaktiviert die Animationen. Keine externen JavaScript-/Font-/Bild-CDNs.
**Kompatibilität:** `GET /api/v1/docs/panel`,
`POST /api/v1/auth/session` und
`POST /api/v1/auth/admin/session` bleiben für vorhandene Clients
weiterhin verfügbar. Die Web-Anmeldeseite benötigt diese zusätzlichen
Pfade jedoch nicht mehr.
## Authentifizierung (serverseitig)
**Sicherheit:** Unangemeldete Besucher bekommen niemals das
geschützte Dashboard. Weder Passwörter noch signierte Tokens werden
in HTML gespeichert oder in URL-Parametern übertragen. Der Browser
bewahrt sein Token ausschließlich im Arbeitsspeicher auf. Anfragen
werden per HTTPS und mit `Cache-Control: no-store` ausgeführt.
Geschützte Daten bleiben an `LoginAllowed`, den lokalen
`UserLevel >= 200`, die Principal-ID und die serverseitig
berechneten Administratorscopes gebunden.
1. Die Login-Maske sendet über **HTTPS** `POST /api/v1/auth/admin/session` mit `username`, `password`, bei aktiviertem MFA `totp`. Der bereits bestehende OGL-Admin-Login lehnt Nicht-Administratoren **vor** einer Tokenerstellung ab.
2. Für die vollständige Oberfläche sendet der Browser `Authorization: Bearer <token>` an `/api/v1/docs/panel`.
3. Der Server verifiziert das Access-Token kryptografisch und prüft die aktuelle Kontenlage über `NexApiAuthenticator`, nicht anhand von Browserdaten: gültiger lokal eingeloggter GridUser (keine API-Key-/Service-Identität), `LoginAllowed`, `UserLevel >= max(200, AdminMinimumUserLevel)`, `admin:*`, korrekte Principal-ID.
4. Bei jedem neu angefragten Dashboard ist diese Prüfung erneut erforderlich. Token im Browser nur **im Arbeitsspeicher**, keine LocalStorage-/SessionStorage-/Cookie-Persistierung durch die Oberfläche. Der Login-Shell-Frame empfängt Dashboard-HTML erst nach erfolgreichem authentifiziertem Fetch. `Cache-Control: no-store`.
5. Bei 401/fehlendem Rechteumfang wird kein Admin-HTML geliefert. Die API-Zugriffsrechte aller übrigen Endpunkte bleiben unabhängig geschützt, und bestehende Maschinen-API-Keys funktionieren für ihre bisherigen Endpunkte weiter.
### KeyHelp Reverse Proxy
**Wichtig:** Der Administrator-Login setzt für die Ausgabe eigener Access-Tokens `[NexVerseWorldApi] EnableNativeTokens = true` mit produktionsgeeignetem Signing-Key und der bestehenden OAuth-/Token-Konfiguration voraus. Diese Konfiguration wird **nicht** automatisch durch die UI aktiviert. Als Reverse-Proxy HTTPS korrekt terminieren und die Anmeldung nicht über unverschlüsseltes HTTP erlauben. Bei einer Reverse-Proxy-Verbindung erkennt die Dashboard-Route `X-Forwarded-Proto: https` ausschließlich von einem lokalen Loopback-Peer an.
Für `world.stadt-nexverse.de` muss KeyHelp HTTPS für die Domain
terminieren und **alle Methoden** (GET/POST) sowie den unveränderten
Pfad `/api/v1/docs` an den laufenden ROBUST-HTTP-Port weiterreichen.
Insbesondere den `Authorization`-Header bei GET nicht unterdrücken.
Für die restlichen Dashboard-Funktionen müssen auch `/api/v1/*`
weitergeleitet werden. Die genutzte ROBUST-Portnummer hängt von der
vorhandenen Konfiguration ab; hier wird keine neue Portnummer vorgegeben.
Beispiel **nur für das Berechtigungsniveau**:
In der ROBUST-Konfiguration:
```ini
~~~ini
[NexVerseWorldApi]
Enabled = true
EnablePrivilegedEndpoints = true
AdminMinimumUserLevel = 200
```
EnableNativeTokens = true
PublicBaseUrl = "https://world.stadt-nexverse.de"
NativeTokenIssuer = "https://world.stadt-nexverse.de"
~~~
Der Zugangslevel ist eine **Untergrenze** und kann mit einem höheren bereits eingestellten Wert nicht abgesenkt werden.
Außerdem muss `NativeTokenSigningKey` auf das bestehende geschützte
Secret (mindestens 32 UTF-8-Bytes) verweisen. Keinen Schlüssel in
GitHub oder Chat kopieren. Die bereits ausgelieferte
`bin/Robust.HG.ini` enthält die betreffenden Einstellungen.
**Prüfung ohne echte Zugangsdaten:**
~~~bash
curl -si https://world.stadt-nexverse.de/api/v1/docs
curl -si -H 'Content-Type: application/json' \
--data '{"username":"ungueltig","password":"ungueltig"}' \
https://world.stadt-nexverse.de/api/v1/docs
~~~
Erwartet: die erste Anfrage zeigt das Formular (`HTTP 200`);
die zweite darf bei aktivem Admin-Backend **niemals HTTP 200** liefern.
Sie muss das falsche Passwort mit `HTTP 401` und JSON ablehnen.
Bei inaktivem Admin-Backend wird `HTTP 503` zurückgegeben.
Ein `HTTP 200` mit Login-HTML oder fremdem JSON bei POST bedeutet,
dass die Domain noch an eine falsche/stale Anwendung oder KeyHelp-Regel
gebunden ist. In diesem Fall lässt sich der Fehler **nicht allein durch
Code auf GitHub** korrigieren.
## Manuelle Sicherheits-/Browser-Abnahme
- Unangemeldet `GET /api/v1/docs`: Login-Formular sichtbar, Admin-Oberfläche noch nicht heruntergeladen.
- `GET /api/v1/docs/panel` ohne Bearer und mit ungültigem Bearer: **401, kein HTML**.
- `GET /api/v1/docs` mit ungültigem Bearer: **401 oder 403, niemals Dashboard-HTML**.
- `POST /api/v1/docs` mit falschem Passwort: **401 als JSON**, nicht 200.
- GridUser Level 0 / 100: Anmeldung **403**; kein Admin-Token.
- GridUser Level 200 mit `admin:*`, korrektem Passwort und gegebenenfalls TOTP: Dashboard zugänglich.
- Level 200 ohne effektives `admin:*`, gesperrter User oder nachträglich gesenkter UserLevel: Zugang verweigert.
@@ -85,7 +85,7 @@ for name in ("NEXVERSE_EXPERIENCES_API_KEY",
assert admin_route in api
ui=contents("NexVerse/Server/Api/NexApiDocsPage.cs")
for marker in ('data-page="adminlogin"','id="page-adminlogin"','id="adminLoginPassword"',
"'/api/v1/auth/session'","function adminIsActive()", "function adminLogout()",
"'/api/v1/docs'","function adminIsActive()", "function adminLogout()",
"'secrets','nodes','grid'", 'id="page-secrets"',
"'/api/v1/auth/api-keys'","window.crypto.getRandomValues(bytes)"):
assert marker in ui,marker
+16 -2
View File
@@ -38,7 +38,20 @@ must(access,
for login_ui in (access, dashboard):
must(login_ui, "!Number.isInteger(data.user_level)",
"typeof data.access_token!=='string'",
"/api/v1/auth/session", "Reverse-Proxy-Routing")
"/api/v1/docs", "Der Server konnte keine Sitzung erstellen.")
# One stable HTTPS path for the entire browser login handshake, independent
# of KeyHelp's rules for an additional /api/v1/auth/session URL.
must(access,
'public void ConfigureDocsSessionLogin(',
'login(request, response);',
'HandlePanel(request, response);',
"fetch('/api/v1/docs',{method:'POST'",
"fetch('/api/v1/docs',{headers:",
'if (login == null)', 'admin_login_unavailable')
must(user,
'public void HandleControlCenterLogin(',
'HandleNativeSessionLogin(request, response, true);')
must(api, 'oglDocs.ConfigureDocsSessionLogin(userRouter.HandleControlCenterLogin);')
must(user,
'"session_token_unavailable"',
"if (string.IsNullOrWhiteSpace(accessToken))")
@@ -65,7 +78,8 @@ must(user,
'm_Users.VerifyPassword(', 'm_Tokens.Issue(', 'user_level = user.UserLevel',
'access_token =', 'GetUserAccount(', 'nativeClaims.SecurityStamp')
assert user.index('m_Users.VerifyPassword(') < user.index('m_Tokens.Issue(')
assert "const res=await fetch('/api/v1/auth/session'" in dashboard
assert "const res=await fetch('/api/v1/docs'" in dashboard
assert "const res=await fetch('/api/v1/auth/session'" not in dashboard
assert "Number(data.user_level)<200" in dashboard
assert "if(!window.isSecureContext)" not in dashboard[dashboard.index("async function adminLogin()"):dashboard.index("const $=id=>")]
assert "data.administrator" not in dashboard
+41
View File
@@ -0,0 +1,41 @@
#!/usr/bin/env python3
"""Regression guard: statistics must keep safe public aggregates during GridUser failure."""
from pathlib import Path
root = Path(__file__).resolve().parents[2]
stats = (root / "NexVerse/Server/Api/NexStatisticsApi.cs").read_text(encoding="utf-8")
ui = (root / "NexVerse/Server/Api/NexApiDocsPage.cs").read_text(encoding="utf-8")
routes = (root / "NexVerse/Server/Api/NexVerseWorldApiConnector.cs").read_text(encoding="utf-8")
for marker in (
'"statistics_data_unavailable"',
'if (m_UserAccounts == null)',
'bool gridUserAvailable = m_GridUsers != null;',
'm_GridUsers.GetAll(string.Empty)',
'catch (Exception e)',
'gridUserAvailable = false;',
'if (!gridUserAvailable && !completeAccountEnumeration)',
'"Both GridUser history and complete UserAccount enumeration are unavailable."',
'active_last_7_days = gridUserAvailable',
'online_now = gridUserAvailable ? hypergridOnline.Count : (int?)null',
'total = gridUserAvailable ? allOnline.Count : (int?)null',
'missing_metrics = gridUserAvailable',
'griduser_source = gridUserAvailable ? "available" : "unavailable"',
'complete = gridUserAvailable && completeAccountEnumeration',
):
assert marker in stats, "Statistics fallback contract missing: " + marker
assert "m_UserAccounts == null || m_GridUsers == null" not in stats
assert stats.index('if (m_UserAccounts == null)') < stats.index('BuildSummary(response, includeProtectedDetails);')
assert '"/api/v1/statistics/summary"' in routes
assert routes.count('"/api/v1/statistics/summary"') == 2, "Statistics route must work with and without privileged API"
start = ui.split("async function loadStatistics(){", 1)[1].split("\nfunction ", 1)[0]
assert "const bearer=$('statsBearer').value.trim()||adminAuthToken();" in start
assert "const key=$('statsApiKey').value.trim();" in start
assert "$('bearer').value.trim()" not in start, "Unrelated explorer bearer must never break public stats"
assert "$('apiKey').value.trim()" not in start, "Unrelated explorer API key must never break public stats"
assert "Teilweise (Datenquelle fehlt)" in start
assert "feh" in ui
print("OGL statistics partial-data and public aggregate routing: PASS")