feat(oglvoice): central LiveKit JWT authority and verified region admission (#119)

* feat(oglvoice): issue narrowly scoped LiveKit JWTs with HG-safe identity and short TTL

* feat(oglvoice): HMAC-bind simulator join assertions to exact request payloads

* feat(oglvoice): add locked-down Robust LiveKit session token endpoint with node ACL and replay protection

* feat(oglvoice): wire optional server-only LiveKit JWT session authority into Robust

* test(oglvoice): validate LiveKit JWT, room scope, tenant binding, HG identity and signed assertions

* test(oglvoice): validate LiveKit JWT, room scope, tenant binding, HG identity and signed assertions

* test(oglvoice): ensure only Robust hosts token signing keys and enforces node ACL

* docs(config): add disabled-by-default OGLVoice LiveKit session authority and secure key sourcing

* docs(config): add disabled-by-default OGLVoice LiveKit session authority and secure key sourcing

* feat(oglvoice): gate avatar admission by live Scene circuit, Estate and Parcel voice policy

* feat(oglvoice): add trusted simulator-only admission lookup interface

* feat(oglvoice): expose verified root-avatar Estate/Parcel admission through region module

* ci(oglvoice): validate LiveKit JWT scope and admission transport in the release workflow

* docs(oglvoice): detail opt-in LiveKit JWT authority, session admission security and remaining Firestorm gate

* docs(release): record LiveKit token authority as foundation without claiming voice readiness

* test(oglvoice): verify Scene root presence and Estate/Parcel admission wiring

* fix(oglvoice): accept legitimate HTTP Hypergrid identity origins without weakening voice-provider TLS policy

* test(oglvoice): cover legacy HTTP Hypergrid home origins with HTTPS-only provider separation
This commit is contained in:
OpenGenesis (MPL 2.0) authored and GitHub committed 2026-10-09 19:54:03 +02:00
1 parent efead30820
commit ee8ee5ab23
15 files changed
+711 -2

No files matched your search

+8
View File
@@ -322,6 +322,14 @@ jobs:
shell: bash
run: dotnet run --configuration Release --project tools/ci/OglVoiceDiscoveryRegression/OglVoiceDiscoveryRegression.csproj
- name: Verify OGLVoice central session authority and region permission gate
shell: bash
run: python3 tools/ci/verify_oglvoice_session_authority.py
- name: Regression-test OGLVoice LiveKit token privileges and HG binding
shell: bash
run: dotnet run --configuration Release --project tools/ci/OglVoiceSessionRegression/OglVoiceSessionRegression.csproj
- name: Verify Firestorm bridge bootstrap compatibility
shell: bash
run: python3 tools/ci/verify_firestorm_bridge_bootstrap.py
@@ -0,0 +1,144 @@
// SPDX-License-Identifier: MPL-2.0
using System;
using System.Collections.Generic;
using System.Security.Cryptography;
using System.Text;
using System.Text.Json;
using System.Text.RegularExpressions;
namespace NexVerse.Core.Voice
{
/// <summary>
/// A verified simulator admission assertion. Construct this ONLY after
/// checking the active root ScenePresence, circuit session, parcel/estate
/// voice permissions, and foreign HG circuit identity. This DTO alone
/// does not prove any of those conditions.
/// </summary>
public sealed class OglVoiceAdmission
{
public string TenantId { get; init; }
public Guid RegionId { get; init; }
public Guid AvatarId { get; init; }
public Guid SessionId { get; init; }
public string HomeGridOrigin { get; init; }
public bool IsHypergridGuest { get; init; }
public bool VoiceAllowed { get; init; }
}
public sealed class OglVoiceIssuedToken
{
public string Token { get; init; }
public string Room { get; init; }
public string ParticipantIdentity { get; init; }
public long ExpiresAtUnix { get; init; }
}
/// <summary>
/// Standard LiveKit JWT (HS256) with least-privilege video grants.
/// OGLVoice MUST issue these from the trusted central control plane;
/// the LiveKit API secret NEVER belongs in simulator settings or CAPS.
/// </summary>
public sealed class OglVoiceLiveKitTokenIssuer
{
private static readonly Regex s_TenantId = new(
@"^[a-zA-Z0-9][a-zA-Z0-9_.-]{0,95}$",
RegexOptions.CultureInvariant | RegexOptions.Compiled);
private readonly string m_ApiKey;
private readonly byte[] m_ApiSecret;
private readonly string m_TenantId;
public OglVoiceLiveKitTokenIssuer(string tenantId, string apiKey, string apiSecret)
{
if (string.IsNullOrWhiteSpace(tenantId) || !s_TenantId.IsMatch(tenantId))
throw new ArgumentException("Tenant ID is invalid", nameof(tenantId));
if (string.IsNullOrWhiteSpace(apiKey) || apiKey.Length > 128 ||
!Regex.IsMatch(apiKey, @"^[a-zA-Z0-9_-]+$"))
throw new ArgumentException("Invalid LiveKit API key", nameof(apiKey));
if (string.IsNullOrWhiteSpace(apiSecret) ||
Encoding.UTF8.GetByteCount(apiSecret) < 32)
throw new ArgumentException("LiveKit API secret must be at least 32 bytes", nameof(apiSecret));
m_ApiKey = apiKey;
m_ApiSecret = Encoding.UTF8.GetBytes(apiSecret);
m_TenantId = tenantId;
}
public OglVoiceIssuedToken Issue(OglVoiceAdmission admission,
DateTimeOffset now, int lifetimeSeconds = 120)
{
if (admission == null)
throw new ArgumentNullException(nameof(admission));
if (lifetimeSeconds < 30 || lifetimeSeconds > 300)
throw new ArgumentOutOfRangeException(nameof(lifetimeSeconds));
if (admission.TenantId != m_TenantId || !admission.VoiceAllowed ||
admission.RegionId == Guid.Empty || admission.AvatarId == Guid.Empty ||
admission.SessionId == Guid.Empty)
throw new UnauthorizedAccessException("Invalid or unauthorized voice admission");
string avatarIdentity;
if (admission.IsHypergridGuest)
{
if (string.IsNullOrWhiteSpace(admission.HomeGridOrigin))
throw new UnauthorizedAccessException("HG guest must have verified home grid");
avatarIdentity = OglVoiceHypergridIdentity.DeriveGuestId(
admission.HomeGridOrigin, admission.AvatarId);
}
else
{
if (!string.IsNullOrWhiteSpace(admission.HomeGridOrigin))
throw new UnauthorizedAccessException("Local identity cannot carry arbitrary HG home");
avatarIdentity = "local:" + admission.AvatarId.ToString("D");
}
// Each participant is unique within its specific region and agent
// session, including simultaneous HG visitors with colliding UUIDs.
string room = "ogl." + m_TenantId + ".region." +
admission.RegionId.ToString("N");
string identityData = m_TenantId + "\n" + room + "\n" +
avatarIdentity + "\n" + admission.SessionId.ToString("N");
string identity = "ogl:" + Convert.ToHexString(
SHA256.HashData(Encoding.UTF8.GetBytes(identityData))).ToLowerInvariant();
long issued = now.ToUnixTimeSeconds();
long expiry = checked(issued + lifetimeSeconds);
string header = Base64Url(JsonSerializer.SerializeToUtf8Bytes(
new { alg = "HS256", typ = "JWT" }));
string claims = Base64Url(JsonSerializer.SerializeToUtf8Bytes(new
{
iss = m_ApiKey,
sub = identity,
iat = issued,
nbf = issued - 5,
exp = expiry,
jti = Guid.NewGuid().ToString("N"),
video = new
{
roomJoin = true,
room,
canPublish = true,
canPublishData = true,
canSubscribe = true,
canUpdateOwnMetadata = false
},
metadata = JsonSerializer.Serialize(new
{
tenant = m_TenantId,
region = admission.RegionId.ToString("D"),
guest = admission.IsHypergridGuest
})
}));
string unsigned = header + "." + claims;
byte[] signature = HMACSHA256.HashData(m_ApiSecret, Encoding.ASCII.GetBytes(unsigned));
return new OglVoiceIssuedToken
{
Token = unsigned + "." + Base64Url(signature),
Room = room,
ParticipantIdentity = identity,
ExpiresAtUnix = expiry
};
}
private static string Base64Url(byte[] bytes) =>
Convert.ToBase64String(bytes).TrimEnd('=').Replace('+', '-').Replace('/', '_');
}
}
@@ -0,0 +1,53 @@
// SPDX-License-Identifier: MPL-2.0
using System;
using System.Globalization;
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;
namespace NexVerse.Core.Voice
{
/// <summary>Request authentication for private OGLVoice session minting.</summary>
public static class OglVoiceSessionProof
{
private static readonly Regex s_Node = new(
@"^[a-zA-Z0-9][a-zA-Z0-9_.-]{0,127}$", RegexOptions.CultureInvariant);
private static readonly Regex s_Nonce = new(@"^[a-f0-9]{32}$", RegexOptions.CultureInvariant);
private static readonly Regex s_Signature = new(@"^[a-f0-9]{64}$", RegexOptions.CultureInvariant);
public static string Sign(string key, string node, long stamp,
string nonce, byte[] body)
{
OglVoiceDiscoveryProof.ValidateKey(key);
if (node == null || !s_Node.IsMatch(node) ||
nonce == null || !s_Nonce.IsMatch(nonce) ||
stamp <= 0 || body == null || body.Length == 0 || body.Length > 4096)
throw new ArgumentException("Invalid OGLVoice session proof input");
string bodyHash = Convert.ToHexString(SHA256.HashData(body)).ToLowerInvariant();
string message = "session\n" + node + "\n" +
stamp.ToString(CultureInfo.InvariantCulture) + "\n" +
nonce + "\n" + bodyHash;
return Convert.ToHexString(
HMACSHA256.HashData(Encoding.UTF8.GetBytes(key), Encoding.UTF8.GetBytes(message))
).ToLowerInvariant();
}
public static bool Verify(string key, string node, string timestamp, string nonce,
byte[] body, string signature, DateTimeOffset now)
{
if (!long.TryParse(timestamp, NumberStyles.None, CultureInfo.InvariantCulture,
out long stamp) ||
Math.Abs(now.ToUnixTimeSeconds() - stamp) > 60 ||
signature == null || !s_Signature.IsMatch(signature))
return false;
try
{
byte[] expected = Convert.FromHexString(Sign(key, node, stamp, nonce, body));
return CryptographicOperations.FixedTimeEquals(
expected, Convert.FromHexString(signature));
}
catch (ArgumentException) { return false; }
}
}
}
@@ -0,0 +1,15 @@
// SPDX-License-Identifier: MPL-2.0
using NexVerse.Core.Voice;
using OpenMetaverse;
namespace NexVerse.RegionModules.Voice
{
/// <summary>
/// Local simulator-side admission verification only; does not mint or
/// transmit LiveKit tokens or provide Firestorm voice capabilities.
/// </summary>
public interface IOglVoiceSessionAdmission
{
bool TryBuildAdmission(UUID agentId, out OglVoiceAdmission assertion);
}
}
@@ -0,0 +1,82 @@
// SPDX-License-Identifier: MPL-2.0
using System;
using NexVerse.Core.Voice;
using OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Region.Framework.Scenes;
namespace NexVerse.RegionModules.Voice
{
/// <summary>
/// Turn the current trusted Region scene into a bounded voice admission
/// assertion. Never accept an avatar/session/role copied from a viewer form.
/// This is deliberately separate from provider discovery.
/// </summary>
public static class OglVoiceRegionAdmission
{
public static bool TryCreate(Scene scene, UUID agentId, string tenant,
bool allowHypergridGuests, out OglVoiceAdmission admission)
{
admission = null;
if (scene == null || string.IsNullOrWhiteSpace(tenant) ||
!scene.TryGetScenePresence(agentId, out ScenePresence sp) ||
sp == null || sp.IsDeleted || sp.IsChildAgent ||
sp.IsNPC || sp.IsInTransit ||
sp.ControllingClient == null ||
scene.RegionInfo?.EstateSettings?.AllowVoice != true)
return false;
var circuit = scene.AuthenticateHandler.GetAgentCircuitData(agentId);
if (circuit == null || circuit.AgentID != agentId ||
circuit.SessionID != sp.ControllingClient.SessionId ||
circuit.SessionID.IsZero())
return false;
var parcel = scene.LandChannel?.GetLandObject(
sp.AbsolutePosition.X, sp.AbsolutePosition.Y);
if (parcel?.LandData == null ||
(parcel.LandData.Flags & (uint)ParcelFlags.AllowVoiceChat) == 0)
return false;
bool guest = (circuit.teleportFlags &
(uint)Constants.TeleportFlags.ViaHGLogin) != 0;
if (guest && !allowHypergridGuests)
return false;
string home = null;
if (guest)
{
if (circuit.ServiceURLs == null ||
!circuit.ServiceURLs.TryGetValue("HomeURI", out object rawHome) ||
rawHome == null)
return false;
home = rawHome.ToString();
// HomeURI is the verified Hypergrid identity, NOT a URL
// for fetching secrets or media. HG1.5 still legitimately
// uses HTTP origins, unlike private OGLVoice service URLs.
// Canonicalization/validation is shared with the JWT issuer.
try
{
OglVoiceHypergridIdentity.DeriveGuestId(
home, Guid.Parse(agentId.ToString()));
}
catch (ArgumentException)
{
return false;
}
}
admission = new OglVoiceAdmission
{
TenantId = tenant,
RegionId = Guid.Parse(scene.RegionInfo.RegionID.ToString()),
AvatarId = Guid.Parse(agentId.ToString()),
SessionId = Guid.Parse(circuit.SessionID.ToString()),
IsHypergridGuest = guest,
HomeGridOrigin = home,
VoiceAllowed = true
};
return true;
}
}
}
@@ -20,7 +20,7 @@ namespace NexVerse.RegionModules.Voice
[Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule",
Id = "OglVoiceRegionDiscoveryModule")]
public sealed class OglVoiceRegionDiscoveryModule :
ISharedRegionModule, IOglVoiceProviderLookup
ISharedRegionModule, IOglVoiceProviderLookup, IOglVoiceSessionAdmission
{
private static readonly ILog m_Log = LogManager.GetLogger(typeof(OglVoiceRegionDiscoveryModule));
private readonly ConcurrentDictionary<UUID, Scene> m_Scenes = new();
@@ -130,6 +130,22 @@ namespace NexVerse.RegionModules.Voice
return;
m_Scenes[scene.RegionInfo.RegionID] = scene;
scene.RegisterModuleInterface<IOglVoiceProviderLookup>(this);
scene.RegisterModuleInterface<IOglVoiceSessionAdmission>(this);
}
public bool TryBuildAdmission(UUID agentId, out OglVoiceAdmission assertion)
{
assertion = null;
OglVoiceProviderDescriptor provider = CurrentProvider;
if (provider == null)
return false;
foreach (Scene scene in m_Scenes.Values)
{
if (OglVoiceRegionAdmission.TryCreate(scene, agentId,
provider.tenant_id, provider.hypergrid_guests, out assertion))
return true;
}
return false;
}
public void RegionLoaded(Scene scene) { }
@@ -138,6 +154,7 @@ namespace NexVerse.RegionModules.Voice
{
if (scene == null || !m_Scenes.TryRemove(scene.RegionInfo.RegionID, out _))
return;
scene.UnregisterModuleInterface<IOglVoiceSessionAdmission>(this);
scene.UnregisterModuleInterface<IOglVoiceProviderLookup>(this);
}
@@ -245,7 +245,28 @@ namespace NexVerse.Server.Api
server.AddSimpleStreamHandler(new SimpleStreamHandler(
OglVoiceGridDiscoveryEndpoint.Route, discovery.Handle,
"OGLVoice signed grid provider discovery"));
m_Log.Info("[OGL-VOICE]: Sichere Grid-Provider-Discovery aktiv; LiveKit-/Viewer-CAPS noch nicht implementiert.");
m_Log.Info("[OGL-VOICE]: Sichere Grid-Provider-Discovery aktiv; Viewer-CAPS noch nicht implementiert.");
if (oglVoiceConfig.GetBoolean("EnableSessionAuthority", false))
{
// Server-only secrets, NEVER serialized into provider
// descriptors or stored in public simulator INI examples.
string apiKey = Environment.GetEnvironmentVariable("OGLVOICE_LIVEKIT_API_KEY");
string apiSecret = Environment.GetEnvironmentVariable("OGLVOICE_LIVEKIT_API_SECRET");
OglVoiceLiveKitTokenIssuer issuer =
new OglVoiceLiveKitTokenIssuer(provider.tenant_id, apiKey, apiSecret);
string allowedNodeCsv = oglVoiceConfig.GetString("AllowedNodes", "");
string[] allowedNodes = allowedNodeCsv.Split(',',
StringSplitOptions.TrimEntries | StringSplitOptions.RemoveEmptyEntries);
OglVoiceSessionAuthorityEndpoint sessions =
new OglVoiceSessionAuthorityEndpoint(
issuer, provider, discoveryKey, allowedNodes);
server.AddSimpleStreamHandler(new SimpleStreamHandler(
OglVoiceSessionAuthorityEndpoint.Route, sessions.Handle,
"OGLVoice internal LiveKit session authority"));
m_Log.Info("[OGL-VOICE]: LiveKit-Session-Authority fuer explizit zugelassene Simulatoren bereit.");
}
}
IConfig offlineImMailRelayConfig = config.Configs["OfflineIMMailRelay"];
@@ -0,0 +1,156 @@
// SPDX-License-Identifier: MPL-2.0
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Text.Json;
using NexVerse.Core.Voice;
using OpenSim.Framework.Servers.HttpServer;
namespace NexVerse.Server.Api
{
/// <summary>
/// Internal simulator-to-Robust LiveKit token exchange. The endpoint does
/// not register any viewer capabilities or give clients a way to select
/// tenants/rooms. Region-side presence and Estate/Parcel policy must first
/// be asserted by an authorized simulator node.
/// </summary>
internal sealed class OglVoiceSessionAuthorityEndpoint
{
public const string Route = "/internal/oglvoice/v1/sessions";
private readonly OglVoiceLiveKitTokenIssuer m_Issuer;
private readonly OglVoiceProviderDescriptor m_Provider;
private readonly string m_SharedKey;
private readonly HashSet<string> m_AllowedNodes;
private readonly Dictionary<string, long> m_Seen = new(StringComparer.Ordinal);
private readonly object m_Lock = new();
private const int MaxChallenges = 4096;
public OglVoiceSessionAuthorityEndpoint(OglVoiceLiveKitTokenIssuer issuer,
OglVoiceProviderDescriptor provider, string sharedKey, IEnumerable<string> allowedNodes)
{
m_Issuer = issuer ?? throw new ArgumentNullException(nameof(issuer));
m_Provider = provider ?? throw new ArgumentNullException(nameof(provider));
m_Provider.Validate();
OglVoiceDiscoveryProof.ValidateKey(sharedKey);
m_SharedKey = sharedKey;
m_AllowedNodes = new HashSet<string>(allowedNodes ?? Array.Empty<string>(),
StringComparer.Ordinal);
if (m_AllowedNodes.Count == 0 ||
m_AllowedNodes.Contains("*"))
throw new InvalidOperationException("OGLVoice session authority requires explicit AllowedNodes");
foreach (string node in m_AllowedNodes)
OglVoiceSessionProof.Sign(sharedKey, node,
DateTimeOffset.UtcNow.ToUnixTimeSeconds(),
OglVoiceDiscoveryProof.NewNonce(), new byte[] { 1 });
}
public void Handle(IOSHttpRequest request, IOSHttpResponse response)
{
response.KeepAlive = false;
response.ContentType = "application/json; charset=utf-8";
response.AddHeader("Cache-Control", "no-store");
response.AddHeader("Pragma", "no-cache");
response.AddHeader("X-Content-Type-Options", "nosniff");
if (request == null || !string.Equals(request.HttpMethod, "POST",
StringComparison.OrdinalIgnoreCase))
{
Error(response, HttpStatusCode.MethodNotAllowed, "method_not_allowed");
return;
}
string node = request.Headers?["X-OGLVoice-Node"];
if (string.IsNullOrEmpty(node) || !m_AllowedNodes.Contains(node))
{
Error(response, HttpStatusCode.Forbidden, "node_not_allowed");
return;
}
byte[] body;
using (MemoryStream buffer = new())
{
byte[] chunk = new byte[4096];
int count;
// Cap before allocating arbitrary length input.
while ((count = request.InputStream.Read(chunk, 0, chunk.Length)) > 0)
{
if (buffer.Length + count > 4096)
{
Error(response, HttpStatusCode.RequestEntityTooLarge, "payload_too_large");
return;
}
buffer.Write(chunk, 0, count);
}
body = buffer.ToArray();
}
string timestamp = request.Headers?["X-OGLVoice-Timestamp"];
string nonce = request.Headers?["X-OGLVoice-Nonce"];
string signature = request.Headers?["X-OGLVoice-Signature"];
DateTimeOffset now = DateTimeOffset.UtcNow;
if (!OglVoiceSessionProof.Verify(m_SharedKey, node, timestamp,
nonce, body, signature, now))
{
Error(response, HttpStatusCode.Unauthorized, "invalid_proof");
return;
}
lock (m_Lock)
{
long expiry = now.ToUnixTimeSeconds() - 121;
List<string> removals = new();
foreach (var item in m_Seen)
if (item.Value < expiry)
removals.Add(item.Key);
foreach (string old in removals) m_Seen.Remove(old);
string key = node + ":" + nonce;
if (m_Seen.ContainsKey(key))
{
Error(response, HttpStatusCode.Conflict, "replayed_challenge");
return;
}
if (m_Seen.Count >= MaxChallenges)
{
Error(response, HttpStatusCode.ServiceUnavailable, "challenge_capacity");
return;
}
m_Seen.Add(key, now.ToUnixTimeSeconds());
}
try
{
OglVoiceAdmission admission = JsonSerializer.Deserialize<OglVoiceAdmission>(body);
if (admission == null ||
(admission.IsHypergridGuest && !m_Provider.hypergrid_guests) ||
admission.TenantId != m_Provider.tenant_id)
{
Error(response, HttpStatusCode.Forbidden, "voice_not_authorized");
return;
}
OglVoiceIssuedToken token = m_Issuer.Issue(admission, now);
response.StatusCode = (int)HttpStatusCode.OK;
response.RawBuffer = JsonSerializer.SerializeToUtf8Bytes(new
{
access_token = token.Token,
room = token.Room,
identity = token.ParticipantIdentity,
expires_at = token.ExpiresAtUnix,
service_url = m_Provider.provider_url
});
}
catch (Exception e) when (e is JsonException || e is ArgumentException ||
e is UnauthorizedAccessException)
{
Error(response, HttpStatusCode.Forbidden, "voice_not_authorized");
}
}
private static void Error(IOSHttpResponse response, HttpStatusCode status, string code)
{
response.StatusCode = (int)status;
response.RawBuffer = JsonSerializer.SerializeToUtf8Bytes(new { error = code });
}
}
}
+10
View File
@@ -682,6 +682,16 @@
TenantId = "nexverse"
IncludeHypergridGuests = true
; OPTIONAL/EXPERIMENTAL: Robust grants time-limited LiveKit WebRTC
; session tokens ONLY to explicitly allowed, HMAC-authenticated nodes.
; This does NOT activate Firestorm voice/voice balls.
; Set OGLVOICE_LIVEKIT_API_KEY and OGLVOICE_LIVEKIT_API_SECRET
; as protected environment variables on Robust, never in .ini.
; Enable ONLY after private TLS + node ACL + actual voice-room verification.
EnableSessionAuthority = false
AllowedNodes = ""
; Die eingehende interne Route ist
; /internal/oglvoice/v1/provider (NexBus-HMAC + Replay-Schutz).
; Keine OGLVoice-LiveKit/Admin-Schluessel im Simulator verteilen.
+10
View File
@@ -594,6 +594,16 @@
TenantId = "nexverse"
IncludeHypergridGuests = true
; OPTIONAL/EXPERIMENTAL: Robust grants time-limited LiveKit WebRTC
; session tokens ONLY to explicitly allowed, HMAC-authenticated nodes.
; This does NOT activate Firestorm voice/voice balls.
; Set OGLVOICE_LIVEKIT_API_KEY and OGLVOICE_LIVEKIT_API_SECRET
; as protected environment variables on Robust, never in .ini.
; Enable ONLY after private TLS + node ACL + actual voice-room verification.
EnableSessionAuthority = false
AllowedNodes = ""
; Die eingehende interne Route ist
; /internal/oglvoice/v1/provider (NexBus-HMAC + Replay-Schutz).
; Keine OGLVoice-LiveKit/Admin-Schluessel im Simulator verteilen.
+26
View File
@@ -32,6 +32,32 @@ Der **erste reale serverseitige OGLVoice-Integrationsschritt** ist die vertrauen
**Nächste zwingende Schritte:** OGLVoice-Control-Plane mit echten Tenant-/Session-Token-Regeln; serverseitig beglaubigte Region/HG-Präsenz; Firestorm-LLSD-CAPS-/Media-Adapter; LiveKit; vollständige Remote-Speaker-/Voice-Orb-Kompatibilität. **Eine erfolgreiche Provider-Discovery beweist noch keine funktionierende Sprachkommunikation.**
## Dev-Zwischenstand – serverseitige LiveKit-Session-Authority
**Implementiert (noch nicht aktiv):**
- `OglVoiceLiveKitTokenIssuer` stellt standardkonforme **HS256-signierte LiveKit-JWT** mit ausschließlich `video.roomJoin`, `canPublish`, `canSubscribe` und `canPublishData` aus. Jeder Token ist auf `ogl.<tenant>.region.<regionUUID>` und eine Avatar-/Session-Identität beschränkt; TTL 30–300 s, Standard 120 s.
- Fremde HG-Avatare erhalten eindeutige Identitäten aus kanonischem Herkunfts-Grid und Avatar-UUID. Der Token eines HG-Gastes gehört dem **besuchten Tenant**.
- `POST /internal/oglvoice/v1/sessions` in Robust akzeptiert **nur explizit erlaubte Simulator-NodeIds** mit HMAC-SHA256-signiertem Body, 60-s-Timestamp, Einmal-Nonce und Replay-Abwehr. Er kann weder beliebige Tenants noch alle Räume als Wildcard autorisieren.
- LiveKit API-Key und Secret werden ausschließlich aus geschützten Robust-Umgebungsvariablen `OGLVOICE_LIVEKIT_API_KEY` und `OGLVOICE_LIVEKIT_API_SECRET` geladen. **Keine Geheimnisse in Region-INI, Provider-Discovery, Viewer-CAPS oder GitHub.**
- `OglVoiceRegionAdmission` validiert aktive Root-Avatar-Präsenz, nicht-NPC, übereinstimmenden Circuit-Session-Identifier, Estate-/Parcel-Voice-Berechtigung und den HG-Flag/Heim-Grid-Ursprung. Die interne Region-Schnittstelle `IOglVoiceSessionAdmission` bietet ausschließlich diese geprüfte Assertion an.
- `EnableSessionAuthority = false` in Robust-Konfigurationen bleibt die Voreinstellung. Zum Aktivieren ist mindestens `[OGLVoice] Enabled=true`, ein gültiger Provider, `EnableSessionAuthority=true`, eine **explizite** `AllowedNodes`-Liste, bestehendes NexBus-SharedKey-Material und ein TLS-geschützter interner Endpunkt erforderlich.
**Beispiel (nur nach separater Live-Abnahme):**
```ini
[OGLVoice]
Enabled = true
Mode = "GridAuthority"
ServiceUrl = "https://voice.stadt-nexverse.de"
TenantId = "nexverse"
IncludeHypergridGuests = true
EnableSessionAuthority = true
AllowedNodes = "sim-stuttgart-01,sim-freiburg-01"
```
Der Simulator muss die Admission **direkt aus seiner Scene**, nicht aus Formularfeldern eines Clients, erzeugen und intern zum Robust signieren. Die zentrale Token-Authority kann nur die Signatur des vertrauenswürdigen Nodes prüfen und benötigt langfristig zusätzlich dedizierte Node-Credentials, eine zentrale Teilnehmer-/Region-Registry sowie wirksame Revocation.
**Noch ausdrücklich offen:** Die interne Admission wird noch **nicht** automatisch per Simulator-CAPS an die Token-Authority weitergeleitet. Es existiert weder ein LiveKit-Medien-/Signalisierungsadapter für den unveränderten Firestorm noch Spatial-Mischung, Avatar-Voice-Kugel, speaking roster, serverseitige Sitzungsentfernung bei Teleport/Logout, ein produktives Tenant-Abrechnungssystem oder ein Operator-Live-Test. Die **ausgestellten JWTs sind Tokenbausteine**, keine funktionierende Voice-Verbindung für den Viewer. Solange diese Komponenten fehlen, OGLVoice-Session-Authority und Viewer-CAPS deaktiviert lassen.
## 1. Produktziel
**OGLVoice** ersetzt die im Server entfernten Vivox-/FreeSwitch-Implementierungen durch einen selbst betriebenen, **zentralen, mandantenfähigen WebRTC-Voice-Dienst**. Das operative Prinzip entspricht einem externen zentralen Voice-Provider: Eine ganze virtuelle Welt kann einen einzigen Voice-Provider verwenden; es wird **kein Voice-Medienserver je Simulator** verlangt.
+2
View File
@@ -19,6 +19,8 @@ Das Release bündelt den gesamten geplanten Meilenstein **0.9.3.9** (OGLVoice un
- [ ] Bestehenden NexVoice-/LiveKit-Quellcode einschließlich Credentials/Signalisierung sicher prüfen; keine Produktivschlüssel kopieren.
- [ ] OGLVoice Central Control Plane: Tenant-Registry, Auth, Räume, Tokens, Nutzungszählung, Revoke und Audit.
- [x] **Sicherer JWT-Kern und Robust-Token-Authority:** serverseitiges LiveKit-HS256-Signing, kurzlebige raumgebundene Tokens, Explicit-Node-ACL und signierte Simulator-Anfragen; standardmaessig deaktiviert. **Noch kein automatischer Viewer-CAPS-/Region-Join, kein LiveKit-Medien-Gateway und keine Quoten-/Revocation-Control-Plane.**
- [x] **Region-seitige lokale Pruefung:** aktuelle Root-Agent-/Circuit-Sitzung, Estate-/Parcel-Voice, Guest-Herkunft und NPC-Ausschluss; noch nicht an Firestorm/LiveKit angeschlossen.
- [ ] NexVerse als nicht selbst zuweisbaren First-Party-`unlimited`-Tenant, keine künstlichen User-/Sim-/Region-/Minutenlimits.
- [ ] Dritt-Grid-Isolation und konfigurierbare, atomar durchgesetzte Plan-Limits (Abrechnung später).
- [x] **Discovery v1:** C#-Robust-Authority und signierte/authentifizierte Simulator-Provider-Discovery mit bestehendem NexBus-SharedKey, Standalone-Modus und Replay-Abwehr; **nur Provider-Metadaten**, keine LiveKit-/Viewer-Sessions.
@@ -0,0 +1,14 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net8.0</TargetFramework>
<Nullable>disable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
<ItemGroup>
<Compile Include="../../../NexVerse/Core/Voice/OglVoiceHypergridIdentity.cs" Link="OglVoiceHypergridIdentity.cs" />
<Compile Include="../../../NexVerse/Core/Voice/OglVoiceDiscoveryProof.cs" Link="OglVoiceDiscoveryProof.cs" />
<Compile Include="../../../NexVerse/Core/Voice/OglVoiceLiveKitTokenIssuer.cs" Link="OglVoiceLiveKitTokenIssuer.cs" />
<Compile Include="../../../NexVerse/Core/Voice/OglVoiceSessionProof.cs" Link="OglVoiceSessionProof.cs" />
</ItemGroup>
</Project>
@@ -0,0 +1,109 @@
using System;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Text.Json;
using NexVerse.Core.Voice;
static void Assert(bool b, string msg) { if (!b) throw new Exception("OGLVoice session regression: " + msg); }
static void Reject(Action a, string msg)
{
try { a(); } catch (Exception e) when (
e is ArgumentException || e is UnauthorizedAccessException) { return; }
throw new Exception("Expected rejection: " + msg);
}
const string key = "oglvoice-test-key", secret = "ci-only-never-production-use-0123456789-abcdef";
OglVoiceLiveKitTokenIssuer issuer = new("nexverse", key, secret);
Guid region = Guid.NewGuid(), avatar = Guid.NewGuid(), session = Guid.NewGuid();
OglVoiceAdmission local = new()
{
TenantId = "nexverse", RegionId = region,
AvatarId = avatar, SessionId = session, VoiceAllowed = true
};
DateTimeOffset now = DateTimeOffset.FromUnixTimeSeconds(1791568800);
OglVoiceIssuedToken token = issuer.Issue(local, now);
string[] parts = token.Token.Split('.');
Assert(parts.Length == 3, "compact JWT");
static byte[] Decode(string data)
{
string p = data.Replace('-', '+').Replace('_', '/');
return Convert.FromBase64String(p.PadRight((p.Length + 3) / 4 * 4, '='));
}
using JsonDocument header = JsonDocument.Parse(Decode(parts[0]));
using JsonDocument body = JsonDocument.Parse(Decode(parts[1]));
Assert(header.RootElement.GetProperty("alg").GetString() == "HS256", "algorithm");
byte[] expectedSig = HMACSHA256.HashData(Encoding.UTF8.GetBytes(secret),
Encoding.ASCII.GetBytes(parts[0] + "." + parts[1]));
Assert(CryptographicOperations.FixedTimeEquals(expectedSig, Decode(parts[2])), "signature");
JsonElement claims = body.RootElement;
Assert(claims.GetProperty("iss").GetString() == key, "issuer");
Assert(claims.GetProperty("sub").GetString() == token.ParticipantIdentity, "identity");
Assert(claims.GetProperty("iat").GetInt64() == now.ToUnixTimeSeconds(), "issued at");
Assert(claims.GetProperty("exp").GetInt64() == now.ToUnixTimeSeconds() + 120, "expiry");
JsonElement grant = claims.GetProperty("video");
Assert(grant.GetProperty("roomJoin").GetBoolean(), "room join grant");
Assert(grant.GetProperty("room").GetString() == "ogl.nexverse.region." + region.ToString("N"),
"isolated region room");
Assert(grant.GetProperty("canPublish").GetBoolean() && grant.GetProperty("canSubscribe").GetBoolean(), "audio grant");
Assert(!grant.TryGetProperty("roomAdmin", out _), "no admin permissions");
Assert(!grant.TryGetProperty("roomList", out _), "no global room list");
Assert(!grant.TryGetProperty("roomCreate", out _), "no room create");
Assert(token.Token.Length > 200, "signed token present");
Assert(!token.Token.Contains(secret), "no inline secret");
Reject(() => issuer.Issue(new OglVoiceAdmission
{ TenantId = "external", RegionId = region, AvatarId = avatar,
SessionId = session, VoiceAllowed = true }, now), "cross-tenant");
Reject(() => issuer.Issue(new OglVoiceAdmission
{ TenantId = "nexverse", RegionId = region, AvatarId = avatar,
SessionId = session, VoiceAllowed = false }, now), "voice disallowed");
Reject(() => issuer.Issue(new OglVoiceAdmission
{ TenantId = "nexverse", RegionId = region, AvatarId = avatar,
SessionId = Guid.Empty, VoiceAllowed = true }, now), "missing session");
Reject(() => issuer.Issue(new OglVoiceAdmission
{ TenantId = "nexverse", RegionId = region, AvatarId = avatar,
SessionId = session, VoiceAllowed = true, IsHypergridGuest = true }, now), "guest without home");
Reject(() => issuer.Issue(new OglVoiceAdmission
{ TenantId = "nexverse", RegionId = region, AvatarId = avatar,
SessionId = session, VoiceAllowed = true, HomeGridOrigin = "https://forged.example" },
now), "local home injection");
Reject(() => issuer.Issue(local, now, 600), "excessive TTL");
Reject(() => new OglVoiceLiveKitTokenIssuer("../nexverse", key, secret), "invalid tenant");
OglVoiceIssuedToken guest = issuer.Issue(new OglVoiceAdmission
{
TenantId = "nexverse", RegionId = region, AvatarId = avatar, SessionId = session,
IsHypergridGuest = true, HomeGridOrigin = "https://osgrid.example", VoiceAllowed = true
}, now);
Assert(guest.Room == token.Room, "guest participates in visiting grid");
OglVoiceIssuedToken httpHgGuest = issuer.Issue(new OglVoiceAdmission
{
TenantId = "nexverse", RegionId = region, AvatarId = avatar, SessionId = session,
IsHypergridGuest = true, HomeGridOrigin = "http://legacy-hg.example:8002",
VoiceAllowed = true
}, now);
Assert(httpHgGuest.Room == token.Room, "legacy HTTP Hypergrid identity does not disable voice");
Assert(guest.ParticipantIdentity != token.ParticipantIdentity, "HG identity isolation");
Assert(guest.ParticipantIdentity != issuer.Issue(new OglVoiceAdmission {
TenantId = "nexverse", RegionId = region, AvatarId = avatar, SessionId = session,
IsHypergridGuest = true, HomeGridOrigin = "https://different-grid.example",
VoiceAllowed = true }, now).ParticipantIdentity, "HG origin isolation");
Assert(token.ParticipantIdentity != issuer.Issue(new OglVoiceAdmission {
TenantId = "nexverse", RegionId = region, AvatarId = avatar, SessionId = Guid.NewGuid(),
VoiceAllowed = true }, now).ParticipantIdentity, "reconnect session isolation");
const string nodeKey = "ci-nexbus-32byte-shared-key-testing-ONLY";
string nonce = OglVoiceDiscoveryProof.NewNonce();
byte[] signedBody = JsonSerializer.SerializeToUtf8Bytes(local);
long stamp = now.ToUnixTimeSeconds();
string proof = OglVoiceSessionProof.Sign(nodeKey, "simulator-a", stamp, nonce, signedBody);
Assert(OglVoiceSessionProof.Verify(nodeKey, "simulator-a", stamp.ToString(), nonce,
signedBody, proof, now), "valid body-bound HMAC");
byte[] changed = (byte[])signedBody.Clone(); changed[^2] ^= 0x01;
Assert(!OglVoiceSessionProof.Verify(nodeKey, "simulator-a", stamp.ToString(), nonce,
changed, proof, now), "tampered body");
Assert(!OglVoiceSessionProof.Verify(nodeKey, "simulator-b", stamp.ToString(), nonce,
signedBody, proof, now), "wrong node");
Assert(!OglVoiceSessionProof.Verify(nodeKey, "simulator-a", stamp.ToString(), nonce,
signedBody, proof, now.AddMinutes(2)), "expired request");
Console.WriteLine("OGLVoice LiveKit JWT and authenticated session assertions: OK");
@@ -0,0 +1,42 @@
#!/usr/bin/env python3
"""OGLVoice server-only credential and session-authority integration guard."""
from pathlib import Path
base = Path(__file__).resolve().parents[2]
issuer = (base/"NexVerse/Core/Voice/OglVoiceLiveKitTokenIssuer.cs").read_text()
proof = (base/"NexVerse/Core/Voice/OglVoiceSessionProof.cs").read_text()
endpoint = (base/"NexVerse/Server/Api/OglVoiceSessionAuthorityEndpoint.cs").read_text()
connector = (base/"NexVerse/Server/Api/NexVerseWorldApiConnector.cs").read_text()
for value in ("HMACSHA256.HashData", "roomJoin = true",
"canPublish = true", "canSubscribe = true",
"TenantId != m_TenantId", "lifetimeSeconds > 300",
"OglVoiceHypergridIdentity.DeriveGuestId", "jti = Guid.NewGuid()"):
assert value in issuer, value
for value in ("bodyHash", "SHA256.HashData", "CryptographicOperations.FixedTimeEquals",
"OglVoiceDiscoveryProof.ValidateKey"):
assert value in proof, value
for value in ("AllowedNodes", "m_AllowedNodes", "m_Seen",
"replayed_challenge", "Cache-Control", "no-store",
"OglVoiceSessionProof.Verify", "m_Issuer.Issue",
"MaxChallenges", "payload_too_large"):
assert value in endpoint, value
for value in ('EnableSessionAuthority', "OGLVOICE_LIVEKIT_API_KEY",
"OGLVOICE_LIVEKIT_API_SECRET",
"OglVoiceSessionAuthorityEndpoint.Route"):
assert value in connector, value
assert "EnableSessionAuthority" in (base/"bin/Robust.HG.ini.example").read_text()
assert "EnableSessionAuthority" in (base/"bin/Robust.ini.example").read_text()
assert "Environment.GetEnvironmentVariable" in connector
assert "OGLVOICE_LIVEKIT_API_SECRET" not in (base/"bin/OpenSim.ini.example").read_text()
admission = (base/"NexVerse/RegionModules/Voice/OglVoiceRegionAdmission.cs").read_text()
module = (base/"NexVerse/RegionModules/Voice/OglVoiceRegionDiscoveryModule.cs").read_text()
for value in ("ScenePresence", "IsChildAgent", "IsNPC",
"IsInTransit", "circuit.SessionID", "AllowVoice",
"ParcelFlags.AllowVoiceChat", "ViaHGLogin",
"OglVoiceHypergridIdentity", "TryCreate"):
# HG identity gets verified by token issuer after admission
if value == "OglVoiceHypergridIdentity":
continue
assert value in admission, value
assert "IOglVoiceSessionAdmission" in module
assert "OglVoiceRegionAdmission.TryCreate" in module
print("OGLVoice server-only LiveKit credential and session-authority integration: OK")