From 86583df881248bab1af679170deb8de8d2a30a7a Mon Sep 17 00:00:00 2001 From: "OpenGenesis (MPL 2.0)" <153564363+opengenesislink@users.noreply.github.com> Date: Sat, 31 Oct 2026 22:55:04 +0100 Subject: [PATCH] feat(npc): owner-scoped World API NPC directory and signed simulator snapshots (#357) * feat(npc): port reviewed R617 NexNpcSnapshotIndex.cs * feat(npc): port reviewed R617 NexNpcSnapshotIngress.cs * feat(npc): port reviewed R617 NexNpcWorldApi.cs * feat(npc): port reviewed R617 NexNpcSnapshotPublisher.cs * feat(npc): port reviewed R617 WORLD_NPC_OWNER_API_R617.md * feat(npc): port reviewed R617 NexNpcDirectoryRegression.csproj * feat(npc): port reviewed R617 Program.cs * feat(npc): port reviewed R617 verify_npc_owner_bridge_r617.py * feat(npc): integrate R617 nexjast-ci.yml * feat(npc): integrate R617 NexChatGptInstructionDownloads.cs * feat(npc): integrate R617 NexVerseWorldApiHandlers.cs * feat(npc): integrate R617 NPCModule.cs * feat(npc): register private authenticated R617 NPC World API and HMAC ingest * fix(build): include NPC snapshot publisher in explicitly listed simulator sources --- .github/workflows/nexjast-ci.yml | 6 + .../Api/NexChatGptInstructionDownloads.cs | 5 + NexVerse/Server/Api/NexNpcSnapshotIndex.cs | 108 ++++++++++++ NexVerse/Server/Api/NexNpcSnapshotIngress.cs | 166 ++++++++++++++++++ NexVerse/Server/Api/NexNpcWorldApi.cs | 139 +++++++++++++++ .../Server/Api/NexVerseWorldApiConnector.cs | 33 ++++ .../Server/Api/NexVerseWorldApiHandlers.cs | 4 + .../OpenSim.Region.OptionalModules.csproj | 3 + .../OptionalModules/World/NPC/NPCModule.cs | 47 +++++ .../World/NPC/NexNpcSnapshotPublisher.cs | 127 ++++++++++++++ WORLD_NPC_OWNER_API_R617.md | 58 ++++++ .../NexNpcDirectoryRegression.csproj | 12 ++ tools/ci/NexNpcDirectoryRegression/Program.cs | 63 +++++++ tools/ci/verify_npc_owner_bridge_r617.py | 63 +++++++ 14 files changed, 834 insertions(+) create mode 100644 NexVerse/Server/Api/NexNpcSnapshotIndex.cs create mode 100644 NexVerse/Server/Api/NexNpcSnapshotIngress.cs create mode 100644 NexVerse/Server/Api/NexNpcWorldApi.cs create mode 100644 OpenSim/Region/OptionalModules/World/NPC/NexNpcSnapshotPublisher.cs create mode 100644 WORLD_NPC_OWNER_API_R617.md create mode 100644 tools/ci/NexNpcDirectoryRegression/NexNpcDirectoryRegression.csproj create mode 100644 tools/ci/NexNpcDirectoryRegression/Program.cs create mode 100644 tools/ci/verify_npc_owner_bridge_r617.py diff --git a/.github/workflows/nexjast-ci.yml b/.github/workflows/nexjast-ci.yml index 5a016f0e..f5fc5607 100644 --- a/.github/workflows/nexjast-ci.yml +++ b/.github/workflows/nexjast-ci.yml @@ -647,6 +647,12 @@ jobs: python3 -m py_compile tools/ops/ogl-config-example-sync.py tools/ops/ogl-empty-assets-audit.py bash -n tools/ops/ogl-node-stage-update.sh + - name: Regression-test NPC owner directory across reporting simulators (R617) + shell: bash + run: | + dotnet run --configuration Release --project tools/ci/NexNpcDirectoryRegression/NexNpcDirectoryRegression.csproj + python3 tools/ci/verify_npc_owner_bridge_r617.py + - name: Regression-test OGL FastMap deferred startup queue shell: bash run: dotnet run --configuration Release --project tools/ci/OglFastMapStartupRegression/OglFastMapStartupRegression.csproj diff --git a/NexVerse/Server/Api/NexChatGptInstructionDownloads.cs b/NexVerse/Server/Api/NexChatGptInstructionDownloads.cs index 56293b8c..571ea76b 100644 --- a/NexVerse/Server/Api/NexChatGptInstructionDownloads.cs +++ b/NexVerse/Server/Api/NexChatGptInstructionDownloads.cs @@ -217,6 +217,8 @@ namespace NexVerse.Server.Api md.AppendLine("- GET /messages, GET /messages/events?after=0 und GET /messages/with/{peerId}?after=0: nur eigene Konversationen und neue IMs (5s Polling)."); md.AppendLine("- DELETE /messages/history loescht die eigene Portal-IM-Historie, opt-out ebenfalls."); md.AppendLine("- Fuer Antworten aus Firestorm muss [NexPortalIM] in Robust und Simulator mit demselben HMAC-Secret aktiviert sein."); + md.AppendLine("- GET /npcs/mine zeigt nur die vom eigenen Simulator bestätigten aktiven NPCs des angemeldeten Einwohners; bei unvollständigen oder fehlenden Regions-Snapshots ist der Dienst bewusst nicht verfügbar."); + md.AppendLine("- GET /npcs/{npcId}/messages ist bis zur getrennt autorisierten NPC-Chatarchivierung ausdrücklich nicht verfügbar (HTTP 503). Bürger-IMs dürfen nicht als NPC-Dialoge ausgegeben werden."); md.AppendLine("- GET /profiles/{principalId} liest das OpenSim-Profil einschliesslich Bildreferenzen. PATCH /profiles/{principalId} (profile:write + Owner/Admin) darf nur die elf editierbaren Spalten der userprofile-Tabelle setzen; useruuid, profileImage, profileFirstImage sind ausnahmslos schreibgeschuetzt (HTTP 403). Ein Webupload ist kein Bestandteil."); md.AppendLine("- GET /profiles/{principalId}/image liefert autorisiert tatsaechliche PNG/JPEG-Bilddaten der *aktuell* hinterlegten Profiltextur. Oeffentlich nur bei PublishProfile, sonst ProfileRead + eigener Avatar/Admin; kein Asset-Browser oder beliebige Texture-UUID."); md.AppendLine("- profile_image_url ist ein relativer Pfad und kann null sein. Keine Schluessel/Tokens in Querystrings ablegen; Browser-Fetch fuer private Profile braucht den authentifizierten Kontext."); @@ -562,6 +564,9 @@ namespace NexVerse.Server.Api "/api/v1/messages/events", "/api/v1/messages/with/{peerId}", "/api/v1/messages/history"); + AppendCatalogGroup(md, requestedAudience, "citizen", "Eigene, verifizierte aktive World-NPCs und Verfügbarkeit von NPC-Chats", + "/api/v1/npcs/mine", + "/api/v1/npcs/{npcId}/messages"); AppendCatalogGroup(md, requestedAudience, "citizen", "OAuth2/OIDC-Flows", "/oauth/authorize", "/oauth/token", diff --git a/NexVerse/Server/Api/NexNpcSnapshotIndex.cs b/NexVerse/Server/Api/NexNpcSnapshotIndex.cs new file mode 100644 index 00000000..c6428973 --- /dev/null +++ b/NexVerse/Server/Api/NexNpcSnapshotIndex.cs @@ -0,0 +1,108 @@ +// SPDX-License-Identifier: MPL-2.0 +// R617: pure thread-safe NPC source index. No HTTP or simulator dependency. +using System; +using System.Collections.Generic; +using System.Linq; + +namespace NexVerse.Server.Api +{ + internal sealed class NexNpcOwnerEntry + { + public Guid npc_id { get; set; } + public Guid owner_principal_id { get; set; } + public string name { get; set; } + public string region_name { get; set; } + } + + internal sealed class NexNpcSnapshotIndex + { + private sealed class Region + { + internal long Sequence; + internal DateTimeOffset LastSeen; + internal List Npcs; + } + + private readonly object m_Guard = new object(); + private readonly Dictionary m_Regions = + new Dictionary(); + private long m_Version; + private readonly int m_RequiredRegions; + private static readonly TimeSpan FreshFor = TimeSpan.FromSeconds(100); + + internal NexNpcSnapshotIndex(int requiredRegions) + { + if (requiredRegions <= 0 || requiredRegions > 1024) + throw new ArgumentOutOfRangeException(nameof(requiredRegions)); + m_RequiredRegions = requiredRegions; + } + + // The presence of an expired snapshot never implies "zero NPCs". + // Restart starts unready until a live simulator proves its own state. + internal bool TryOwned(Guid owner, out List owned, + out long revision) + { + owned = new List(); + lock (m_Guard) + { + DateTimeOffset now = DateTimeOffset.UtcNow; + var fresh = m_Regions.Values.Where(x => now - x.LastSeen <= FreshFor).ToList(); + revision = m_Version; + if (fresh.Count < m_RequiredRegions || fresh.Count != m_Regions.Count) + return false; + // A conflicting owner claim from different reporting regions + // invalidates the directory rather than exposing an NPC to + // both accounts. + var owners = new Dictionary(); + foreach (Region region in fresh) + foreach (NexNpcOwnerEntry npc in region.Npcs) + { + if (owners.TryGetValue(npc.npc_id,out Guid previous) + && previous != npc.owner_principal_id) + return false; + owners[npc.npc_id] = npc.owner_principal_id; + } + var seen = new HashSet(); + foreach (Region region in fresh) + foreach (NexNpcOwnerEntry npc in region.Npcs) + if (npc.owner_principal_id == owner && seen.Add(npc.npc_id)) + owned.Add(npc); + owned.Sort((a,b) => a.npc_id.CompareTo(b.npc_id)); + return true; + } + } + + // An authorized *complete* snapshot replaces one simulator region; + // monotonic timestamps reject duplicated/replayed state changes. + internal bool Replace(Guid regionID, long sequence, + List entries) + { + if (regionID == Guid.Empty || sequence <= 0 || entries == null || + entries.Count > 1000 || + entries.Any(n => n == null || n.npc_id == Guid.Empty || + n.owner_principal_id == Guid.Empty || + string.IsNullOrWhiteSpace(n.name) || n.name.Length > 120 || + (n.region_name ?? "").Length > 120) || + entries.GroupBy(n => n.npc_id).Any(g => g.Count() != 1)) + return false; + + lock (m_Guard) + { + if (m_Regions.TryGetValue(regionID, out Region last)) + { + if (sequence <= last.Sequence) return false; + } + else if (m_Regions.Count >= 1024) return false; + m_Regions[regionID] = new Region + { + Sequence = sequence, + LastSeen = DateTimeOffset.UtcNow, + Npcs = entries.ToList() + }; + ++m_Version; + } + return true; + } + } + + } diff --git a/NexVerse/Server/Api/NexNpcSnapshotIngress.cs b/NexVerse/Server/Api/NexNpcSnapshotIngress.cs new file mode 100644 index 00000000..9c0362df --- /dev/null +++ b/NexVerse/Server/Api/NexNpcSnapshotIngress.cs @@ -0,0 +1,166 @@ +// SPDX-License-Identifier: MPL-2.0 +// R617 private simulator-to-ROBUST snapshot ingress. This is never called +// with a resident browser token or service API key. +using System; +using System.Collections.Generic; +using System.IO; +using System.Net; +using System.Security.Cryptography; +using System.Text; +using System.Text.Json; +using OpenSim.Framework.Servers.HttpServer; + +namespace NexVerse.Server.Api +{ + internal sealed class NexNpcSnapshotIngress + { + private readonly byte[] m_Secret; + private readonly NexNpcSnapshotIndex m_Index; + private const int MaxBodySize = 256 * 1024; + internal NexNpcSnapshotIngress(string secret, NexNpcSnapshotIndex index) + { + if (Encoding.UTF8.GetByteCount(secret ?? "") < 32) + throw new ArgumentException("NPC snapshot bridge requires a 32+ byte secret"); + m_Secret = Encoding.UTF8.GetBytes(secret); + m_Index = index ?? throw new ArgumentNullException(nameof(index)); + } + + internal void Handle(IOSHttpRequest request, IOSHttpResponse response) + { + if (!string.Equals(request.HttpMethod,"POST",StringComparison.OrdinalIgnoreCase)) + { + Reply(response,HttpStatusCode.MethodNotAllowed,"method_not_allowed"); + return; + } + if ((request.UriPath ?? "").TrimEnd('/') != "/internal/nexnpc/snapshot/v1") + { + Reply(response,HttpStatusCode.NotFound,"not_found"); + return; + } + byte[] body; + try + { + using var stream = new MemoryStream(); + byte[] block = new byte[4096]; + int count; + while ((count = request.InputStream.Read(block,0,block.Length)) > 0) + { + if (stream.Length + count > MaxBodySize) + { + Reply(response,HttpStatusCode.RequestEntityTooLarge,"payload_too_large"); + return; + } + stream.Write(block,0,count); + } + body = stream.ToArray(); + } + catch + { + Reply(response,HttpStatusCode.BadRequest,"invalid_payload"); + return; + } + + string stamp = request.Headers?["X-NexNPC-Time"] ?? ""; + string signature = request.Headers?["X-NexNPC-Signature"] ?? ""; + long now = DateTimeOffset.UtcNow.ToUnixTimeSeconds(); + // Range comparison is overflow-safe even for attacker-supplied + // Int64.MinValue timestamps. + if (!long.TryParse(stamp,out long seconds) || + seconds < now - 180 || seconds > now + 180 || + !ValidHmac(stamp,body,signature)) + { + Reply(response,HttpStatusCode.Unauthorized,"signature_invalid"); + return; + } + try + { + using JsonDocument document = JsonDocument.Parse(body); + JsonElement root = document.RootElement; + if (root.ValueKind != JsonValueKind.Object || + !TryGuid(root,"region_id",out Guid region) || + !root.TryGetProperty("sequence",out JsonElement seq) || + !seq.TryGetInt64(out long sequence) || sequence <= 0 || + !root.TryGetProperty("npcs",out JsonElement npcs) || + npcs.ValueKind != JsonValueKind.Array || + npcs.GetArrayLength() > 1000) + { + Reply(response,HttpStatusCode.BadRequest,"invalid_snapshot"); + return; + } + var entries = new List(); + foreach (JsonElement row in npcs.EnumerateArray()) + { + if (row.ValueKind != JsonValueKind.Object || + !TryGuid(row,"npc_id",out Guid npcID) || + !TryGuid(row,"owner_principal_id",out Guid owner) || + !TryString(row,"name",120,out string name) || + !TryString(row,"region_name",120,out string label)) + { + Reply(response,HttpStatusCode.BadRequest,"invalid_npc"); + return; + } + entries.Add(new NexNpcOwnerEntry + { + npc_id=npcID,owner_principal_id=owner,name=name,region_name=label + }); + } + if (!m_Index.Replace(region,sequence,entries)) + { + Reply(response,HttpStatusCode.Conflict,"snapshot_rejected"); + return; + } + Reply(response,HttpStatusCode.Accepted,"snapshot_accepted"); + } + catch (JsonException) + { + Reply(response,HttpStatusCode.BadRequest,"invalid_json"); + } + catch + { + Reply(response,HttpStatusCode.ServiceUnavailable,"snapshot_unavailable"); + } + } + + private bool ValidHmac(string stamp,byte[] body,string received) + { + try + { + byte[] supplied = Convert.FromBase64String(received); + byte[] head = Encoding.ASCII.GetBytes(stamp+"\n"); + byte[] signed = new byte[head.Length+body.Length]; + Buffer.BlockCopy(head,0,signed,0,head.Length); + Buffer.BlockCopy(body,0,signed,head.Length,body.Length); + using var hmac = new HMACSHA256(m_Secret); + byte[] actual = hmac.ComputeHash(signed); + return supplied.Length==actual.Length && + CryptographicOperations.FixedTimeEquals(supplied,actual); + } + catch(FormatException){return false;} + } + private static bool TryGuid(JsonElement row,string key,out Guid result) + { + result=Guid.Empty; + return row.TryGetProperty(key,out JsonElement item) && + item.ValueKind == JsonValueKind.String && + Guid.TryParse(item.GetString(),out result) && + result != Guid.Empty; + } + private static bool TryString(JsonElement row,string key,int max,out string value) + { + value=""; + if (!row.TryGetProperty(key,out JsonElement item) || + item.ValueKind!=JsonValueKind.String)return false; + value=(item.GetString()??"").Trim(); + return value.Length > 0 && value.Length <= max; + } + private static void Reply(IOSHttpResponse response,HttpStatusCode code,string status) + { + response.KeepAlive=false; + response.StatusCode=(int)code; + response.ContentType="application/json; charset=utf-8"; + response.AddHeader("Cache-Control","no-store"); + response.AddHeader("X-Content-Type-Options","nosniff"); + response.RawBuffer=JsonSerializer.SerializeToUtf8Bytes(new { status }); + } + } +} diff --git a/NexVerse/Server/Api/NexNpcWorldApi.cs b/NexVerse/Server/Api/NexNpcWorldApi.cs new file mode 100644 index 00000000..ad34f89e --- /dev/null +++ b/NexVerse/Server/Api/NexNpcWorldApi.cs @@ -0,0 +1,139 @@ +// SPDX-License-Identifier: MPL-2.0 +// R617: Source-verified, owner-scoped live NPC directory. The trusted simulator +// must publish complete signed region snapshots; no NPCs are inferred from IMs. +using System; +using System.Collections.Generic; +using System.Globalization; +using System.Linq; +using System.Net; +using System.Text.Json; +using NexVerse.Core.Security; +using OpenMetaverse; +using OpenSim.Framework.Servers.HttpServer; +using OpenSim.Services.Interfaces; + +namespace NexVerse.Server.Api +{ + internal sealed class NexNpcWorldApi + { + private readonly NexApiAuthenticator m_Authentication; + private readonly NexNpcSnapshotIndex m_Index; + + internal NexNpcWorldApi(NexApiAuthenticator authentication, + NexNpcSnapshotIndex index) + { + m_Authentication = authentication ?? throw new ArgumentNullException(nameof(authentication)); + m_Index = index; // null means no verified simulator feed configured + } + + internal void Handle(IOSHttpRequest request, IOSHttpResponse response) + { + response.AddHeader("Cache-Control", "private, no-store"); + response.AddHeader("X-Content-Type-Options", "nosniff"); + string path = (request.UriPath ?? "").TrimEnd('/'); + bool mine = path == "/api/v1/npcs/mine"; + string prefix = "/api/v1/npcs/"; + bool history = path.StartsWith(prefix, StringComparison.Ordinal) && + path.EndsWith("/messages", StringComparison.Ordinal); + if (!mine && !history) + { + Reply(response,HttpStatusCode.NotFound,new { error="not_found" }); + return; + } + if (!string.Equals(request.HttpMethod,"GET",StringComparison.OrdinalIgnoreCase)) + { + response.AddHeader("Allow", "GET"); + Reply(response,HttpStatusCode.MethodNotAllowed,new { error="method_not_allowed" }); + return; + } + if (!m_Authentication.TryAuthenticate(request, + NexScopes.RelationshipsRead, out NexPrincipal principal, + out UserAccount account, out int status, out string reason)) + { + response.AddHeader("WWW-Authenticate","Bearer"); + Reply(response,(HttpStatusCode)status,new { error=reason }); + return; + } + if (account == null || !account.Active || !account.LocalToGrid || + !Guid.TryParse(principal.Subject,out Guid owner) || + owner == Guid.Empty || owner != account.PrincipalID.Guid) + { + Reply(response,HttpStatusCode.Forbidden,new { error="resident_required" }); + return; + } + if (m_Index == null || !m_Index.TryOwned(owner, + out List owned, out long revision)) + { + Reply(response,HttpStatusCode.ServiceUnavailable, + new { error="npc_registry_unavailable", + message="No complete fresh verified simulator snapshot is available." }); + return; + } + if (mine) + { + // An opaque generation-bound cursor avoids silently skipped + // NPCs if a region changes while the owner pages through it. + string cursor = request.QueryString?["cursor"] ?? ""; + int offset = 0; + if (cursor.Length > 0) + { + string[] pieces = cursor.Split('-'); + if (pieces.Length != 2 || + !long.TryParse(pieces[0],NumberStyles.None,CultureInfo.InvariantCulture,out long at) || + !int.TryParse(pieces[1],NumberStyles.None,CultureInfo.InvariantCulture,out offset) || + offset < 0 || offset > 10000) + { + Reply(response,HttpStatusCode.BadRequest,new { error="invalid_cursor" }); + return; + } + if (at != revision) + { + Reply(response,HttpStatusCode.Conflict,new { error="npc_snapshot_changed" }); + return; + } + } + var items = owned.Skip(offset).Take(500).Select(n => new + { + npc_id=n.npc_id, owner_principal_id=n.owner_principal_id, + name=n.name, region_name=n.region_name + }).ToArray(); + int next = offset + items.Length; + Reply(response,HttpStatusCode.OK,new + { + npcs=items, next_cursor=next < owned.Count + ? revision.ToString(CultureInfo.InvariantCulture)+"-"+next.ToString(CultureInfo.InvariantCulture) + : "" + }); + return; + } + string uuid = path.Substring(prefix.Length,path.Length - prefix.Length - "/messages".Length); + if (!Guid.TryParse(uuid,out Guid npcID) || npcID == Guid.Empty) + { + Reply(response,HttpStatusCode.BadRequest,new { error="invalid_npc_id" }); + return; + } + if (!owned.Any(n => n.npc_id == npcID)) + { + Reply(response,HttpStatusCode.NotFound,new { error="npc_not_found" }); + return; + } + // An NPC is not the same as a resident peer. Never convert a + // resident opt-in IM archive into a guessed NPC conversation. + Reply(response,HttpStatusCode.ServiceUnavailable,new + { + error="npc_chat_archive_unavailable", + message="NPC conversations require an explicitly authorized source and retention policy." + }); + } + + private static void Reply(IOSHttpResponse response, + HttpStatusCode code, object payload) + { + response.KeepAlive = false; + response.StatusCode = (int)code; + response.ContentType = "application/json; charset=utf-8"; + response.AddHeader("Cache-Control","private, no-store"); + response.RawBuffer = JsonSerializer.SerializeToUtf8Bytes(payload); + } + } +} diff --git a/NexVerse/Server/Api/NexVerseWorldApiConnector.cs b/NexVerse/Server/Api/NexVerseWorldApiConnector.cs index 445ca1f4..a82d090f 100644 --- a/NexVerse/Server/Api/NexVerseWorldApiConnector.cs +++ b/NexVerse/Server/Api/NexVerseWorldApiConnector.cs @@ -655,6 +655,39 @@ namespace NexVerse.Server.Api "/api/v1/admin/console", apiGate.Wrap(robustConsole.Handle), "OpenGenesisLINK authenticated ROBUST command console")); + // R617: owner-scoped NPC directory is enabled only with a + // valid private simulator-ingest configuration. A missing/stale + // snapshot is never represented as an empty owner list. + NexNpcSnapshotIndex npcIndex = null; + IConfig npcConfig = config.Configs["NexNPCPortal"]; + if (npcConfig?.GetBoolean("Enabled", false) == true) + { + string npcSecret = Environment.GetEnvironmentVariable("NEX_NPC_INGEST_SECRET"); + int expectedRegions = npcConfig.GetInt("ExpectedRegionCount", 0); + if (System.Text.Encoding.UTF8.GetByteCount(npcSecret ?? "") >= 32 && + expectedRegions > 0 && expectedRegions <= 1024) + { + npcIndex = new NexNpcSnapshotIndex(expectedRegions); + NexNpcSnapshotIngress npcIngress = + new NexNpcSnapshotIngress(npcSecret, npcIndex); + server.AddSimpleStreamHandler(new SimpleStreamHandler( + "/internal/nexnpc/snapshot/v1", + npcIngress.Handle, + "Private signed NPC simulator snapshot ingestion"), true); + } + else + { + m_Log.Warn("[NEX-NPC]: No valid NEX_NPC_INGEST_SECRET; " + + "NPC owner directory requires a valid private secret " + + "and explicit ExpectedRegionCount (1-1024)."); + } + } + NexNpcWorldApi npcWorldApi = + new NexNpcWorldApi(authenticator, npcIndex); + server.AddSimpleStreamHandler(new SimpleStreamHandler( + "/api/v1/npcs", apiGate.Wrap(npcWorldApi.Handle), + "Owner-scoped NPC directory and private conversation availability"), true); + // Attach the existing, server-side native admin authenticator // once privileged services are available. No duplicate routing. oglDocs.ConfigureAdministratorAccess( diff --git a/NexVerse/Server/Api/NexVerseWorldApiHandlers.cs b/NexVerse/Server/Api/NexVerseWorldApiHandlers.cs index 67de8c92..06310d70 100644 --- a/NexVerse/Server/Api/NexVerseWorldApiHandlers.cs +++ b/NexVerse/Server/Api/NexVerseWorldApiHandlers.cs @@ -316,6 +316,10 @@ namespace NexVerse.Server.Api ["/api/v1/relationships/{principalId}/blocks/{targetId}"] = AuthenticatedOperations( ("put", "Einwohner blockieren und bestehende Freundschaft auflösen", "relationships:write", "200"), ("delete", "Einwohner-Blockierung aufheben", "relationships:write", "200")), + ["/api/v1/npcs/mine"] = AuthenticatedOperations( + ("get", "Eigene, vom Simulator bestätigte aktive NPCs; bei fehlender Snapshot-Quelle nicht verfügbar", "relationships:read", "200")), + ["/api/v1/npcs/{npcId}/messages"] = AuthenticatedOperations( + ("get", "Noch nicht verfügbar: NPC-Chat erfordert eine separat autorisierte Aufzeichnungsquelle", "relationships:read", "503")), ["/api/v1/messages"] = AuthenticatedOperations( ("get", "Eigene, opt-in gespeicherte IM-Konversationen lesen", "relationships:read", "200"), ("post", "Inworld-Direktnachricht an einen bestätigten lokalen Freund zustellen", "relationships:write", "202")), diff --git a/OpenSim/Region/OptionalModules/OpenSim.Region.OptionalModules.csproj b/OpenSim/Region/OptionalModules/OpenSim.Region.OptionalModules.csproj index 2a9649a5..deb71d44 100644 --- a/OpenSim/Region/OptionalModules/OpenSim.Region.OptionalModules.csproj +++ b/OpenSim/Region/OptionalModules/OpenSim.Region.OptionalModules.csproj @@ -170,6 +170,9 @@ Code + + Code + Code diff --git a/OpenSim/Region/OptionalModules/World/NPC/NPCModule.cs b/OpenSim/Region/OptionalModules/World/NPC/NPCModule.cs index d57fbf8b..993a62b7 100644 --- a/OpenSim/Region/OptionalModules/World/NPC/NPCModule.cs +++ b/OpenSim/Region/OptionalModules/World/NPC/NPCModule.cs @@ -49,6 +49,8 @@ namespace OpenSim.Region.OptionalModules.World.NPC private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); private readonly Dictionary m_avatars = new Dictionary(); + // Optional signed NPC directory bridge; never captures conversations. + private NexNpcSnapshotPublisher m_SnapshotPublisher; private NPCOptionsFlags m_NPCOptionFlags; private int m_MaxNumberNPCperScene = 40; @@ -78,17 +80,36 @@ namespace OpenSim.Region.OptionalModules.World.NPC m_NPCOptionFlags |= NPCOptionsFlags.NoNPCGroup; m_MaxNumberNPCperScene = config.GetInt("MaxNumberNPCsPerScene", m_MaxNumberNPCperScene); + if(config.GetBoolean("NexNPCSnapshotEnabled", false)) + { + string url = Environment.GetEnvironmentVariable("NEX_NPC_INGEST_URL"); + string secret = Environment.GetEnvironmentVariable("NEX_NPC_INGEST_SECRET"); + try + { + m_SnapshotPublisher = new NexNpcSnapshotPublisher( + new Uri(url ?? "", UriKind.Absolute), secret, SnapshotForScene); + } + catch (Exception) + { + m_log.Warn("[NPC]: Optional owner directory snapshot bridge disabled. " + + "Check HTTPS ingest URL and private 32+ byte secret."); + } + } } } public void AddRegion(Scene scene) { if (Enabled) + { scene.RegisterModuleInterface(this); + m_SnapshotPublisher?.Add(scene); + } } public void RegionLoaded(Scene scene) { + m_SnapshotPublisher?.Schedule(); } public void PostInitialise() @@ -97,11 +118,35 @@ namespace OpenSim.Region.OptionalModules.World.NPC public void RemoveRegion(Scene scene) { + m_SnapshotPublisher?.Remove(scene); scene.UnregisterModuleInterface(this); } public void Close() { + m_SnapshotPublisher?.Dispose(); + } + + private List SnapshotForScene(Scene scene) + { + var entries = new List(); + lock (m_avatars) + { + foreach (NPCAvatar npc in m_avatars.Values) + { + // Ownerless NPCs never appear under a resident account. + if (!ReferenceEquals(npc.Scene, scene) || npc.OwnerID.IsZero()) + continue; + entries.Add(new NexNpcPublishEntry + { + npc_id=npc.AgentId.ToString(), + owner_principal_id=npc.OwnerID.ToString(), + name=npc.Name, + region_name=scene.RegionInfo.RegionName + }); + } + } + return entries; } public string Name @@ -236,6 +281,7 @@ namespace OpenSim.Region.OptionalModules.World.NPC // m_log.DebugFormat("[NPC MODULE]: Created NPC with id {0}", npcAvatar.AgentId); + m_SnapshotPublisher?.Schedule(); return agentID; } @@ -435,6 +481,7 @@ namespace OpenSim.Region.OptionalModules.World.NPC } m_log.DebugFormat("[NPC MODULE]: Removed NPC {0} {1}", agentID, av.Name); + m_SnapshotPublisher?.Schedule(); return true; } /* diff --git a/OpenSim/Region/OptionalModules/World/NPC/NexNpcSnapshotPublisher.cs b/OpenSim/Region/OptionalModules/World/NPC/NexNpcSnapshotPublisher.cs new file mode 100644 index 00000000..41c7499d --- /dev/null +++ b/OpenSim/Region/OptionalModules/World/NPC/NexNpcSnapshotPublisher.cs @@ -0,0 +1,127 @@ +// SPDX-License-Identifier: MPL-2.0 +// R617 optional region -> ROBUST NPC directory snapshots. Live NPC metadata +// only. Not an IM/chat archive, and never sends messages or personal tokens. +using System; +using System.Collections.Generic; +using System.Linq; +using System.Net.Http; +using System.Security.Cryptography; +using System.Text; +using System.Text.Json; +using System.Threading; +using System.Threading.Tasks; +using System.Timers; +using OpenSim.Region.Framework.Scenes; + +namespace OpenSim.Region.OptionalModules.World.NPC +{ + internal sealed class NexNpcPublishEntry + { + public string npc_id { get; set; } + public string owner_principal_id { get; set; } + public string name { get; set; } + public string region_name { get; set; } + } + + internal sealed class NexNpcSnapshotPublisher : IDisposable + { + private readonly Uri m_Endpoint; + private readonly byte[] m_Key; + private readonly Func> m_List; + private readonly HashSet m_Scenes = new HashSet(); + private readonly object m_Guard = new object(); + private readonly System.Timers.Timer m_Timer; + private readonly HttpClient m_Http; + private readonly SemaphoreSlim m_Once = new SemaphoreSlim(1,1); + private long m_Sequence = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds() * 100; + private bool m_Disposed; + + internal NexNpcSnapshotPublisher(Uri endpoint,string secret, + Func> list) + { + if (endpoint == null || endpoint.Scheme != Uri.UriSchemeHttps || + endpoint.AbsolutePath != "/internal/nexnpc/snapshot/v1" || + !string.IsNullOrEmpty(endpoint.Query)) + throw new ArgumentException("NPC ingest must use the HTTPS internal snapshot path"); + if (Encoding.UTF8.GetByteCount(secret ?? "") < 32) + throw new ArgumentException("NPC ingress secret must have 32 or more UTF-8 bytes"); + m_Endpoint=endpoint; + m_Key=Encoding.UTF8.GetBytes(secret); + m_List=list ?? throw new ArgumentNullException(nameof(list)); + m_Http=new HttpClient { Timeout=TimeSpan.FromSeconds(8) }; + m_Timer=new System.Timers.Timer(25000); + m_Timer.AutoReset=true; + m_Timer.Elapsed+=(_,__)=>Schedule(); + m_Timer.Start(); + } + internal void Add(Scene scene) + { + lock(m_Guard) if(!m_Disposed) m_Scenes.Add(scene); + Schedule(); + } + internal void Remove(Scene scene) + { + lock(m_Guard) m_Scenes.Remove(scene); + // A stopped region is intentionally treated as unavailable on + // ROBUST after lease expiry, not as a falsely empty directory. + } + internal void Schedule() + { + lock(m_Guard) if(m_Disposed)return; + _=Task.Run(PublishAsync); + } + private async Task PublishAsync() + { + if(!await m_Once.WaitAsync(0).ConfigureAwait(false))return; + try + { + Scene[] scenes; + lock(m_Guard)scenes=m_Scenes.ToArray(); + foreach(Scene scene in scenes) + { + List npcs; + try{npcs=m_List(scene);}catch{continue;} + // Max NPCs per region defaults to 40, capped here at 1000. + if(npcs==null || npcs.Count>1000)continue; + var body=JsonSerializer.SerializeToUtf8Bytes(new + { + region_id=scene.RegionInfo.RegionID.ToString(), + sequence=Interlocked.Increment(ref m_Sequence), + npcs + }); + string time=DateTimeOffset.UtcNow.ToUnixTimeSeconds().ToString(); + byte[] header=Encoding.ASCII.GetBytes(time+"\n"); + byte[] signed=new byte[header.Length+body.Length]; + Buffer.BlockCopy(header,0,signed,0,header.Length); + Buffer.BlockCopy(body,0,signed,header.Length,body.Length); + using var hmac=new HMACSHA256(m_Key); + string sig=Convert.ToBase64String(hmac.ComputeHash(signed)); + try + { + using var message=new HttpRequestMessage(HttpMethod.Post,m_Endpoint); + message.Content=new ByteArrayContent(body); + message.Content.Headers.ContentType= + new System.Net.Http.Headers.MediaTypeHeaderValue("application/json"); + message.Headers.Add("X-NexNPC-Time",time); + message.Headers.Add("X-NexNPC-Signature",sig); + using HttpResponseMessage response=await m_Http.SendAsync(message).ConfigureAwait(false); + // A rejected snapshot is not authorization to alter + // NPC ownership; the next periodic snapshot retries. + } + catch (HttpRequestException) {} + catch (TaskCanceledException) {} + } + } + finally{m_Once.Release();} + } + public void Dispose() + { + lock(m_Guard){if(m_Disposed)return;m_Disposed=true;m_Scenes.Clear();} + m_Timer.Stop(); + m_Timer.Dispose(); + // Do not dispose the client/semaphore while an already running + // in-flight callback may still own the lease. These bounded + // process-lifetime resources are cleaned on simulator exit. + } + } +} diff --git a/WORLD_NPC_OWNER_API_R617.md b/WORLD_NPC_OWNER_API_R617.md new file mode 100644 index 00000000..9a146778 --- /dev/null +++ b/WORLD_NPC_OWNER_API_R617.md @@ -0,0 +1,58 @@ +# R617 – World-NPC-Eigentümerliste aus echten Simulator-Daten + +**Stand:** 31.10.2026 · **Repository:** `opengenesislinkserver` · **Zweck:** Backend für den bereits implementierten Bürgerportal-Menüpunkt `/citizen/npc`. + +## Funktionsumfang + +R617 führt die erste, bewusst begrenzte World-API-Anbindung für **aktuell aktive, im Simulator bestätigte NPCs** ein. + +- `GET /api/v1/npcs/mine` verlangt ein persönliches World-Bearer-Token mit `relationships:read`, ein aktives lokales World-Konto und eine passende Principal-ID. Es werden nur NPCs mit exakt dieser Besitzer-UUID ausgegeben. Die API liefert maximal 500 NPCs pro Seite mit einem an den Snapshot-Stand gebundenen Cursor. Bei geänderten Daten zwischen Seiten wird die Abfrage abgewiesen und nicht stillschweigend unvollständig. +- `GET /api/v1/npcs/{npcId}/messages` bestätigt dieselbe persönliche Berechtigung und den Eigentümer. Weil es noch **keine freigegebene NPC-Chat-Archivquelle** gibt, liefert sie bewusst HTTP 503 `npc_chat_archive_unavailable` statt fiktiver Nachrichten. Andere NPCs liefern 404. +- `POST /internal/nexnpc/snapshot/v1` wird ausschließlich zwischen Simulator und ROBUST benutzt. Die komplette Regionsliste wird mit HMAC-SHA256 über `X-NexNPC-Time + "\n" + JSON-Bytes` signiert. Secrets sind mindestens 32 UTF-8-Bytes; Signaturvergleich erfolgt in konstanter Zeit. Meldungen müssen maximal 180 Sekunden alt sein. Jede Region benötigt monoton steigende Sequenzen; doppelte und ältere Meldungen werden abgewiesen. +- Das Simulator-NPC-Modul übermittelt nur wirklich vorhandene, einem Avatar gehörende NPCs. Es übermittelt **keine Nachrichteninhalte und keine persönlichen World-Tokens**. Nach Änderungen sowie regelmäßig alle 25 Sekunden wird die Liste mit HTTPS gesendet. +- Sind gar keine verifizierten Schnappschüsse vorhanden, einer der erwarteten Regionen veraltet (100-Sekunden-Fenster), oder widersprechen sich die Besitzerangaben verschiedener Regionen, liefert die API HTTP 503 statt unzuverlässiger Ergebnisse. +- Normale NPC-Nutzung läuft weiterhin unverändert, wenn die optionale Schnittstelle deaktiviert ist. + +**Wichtige Einschränkung:** R617 ist eine *Live-NPC-Liste*, keine persistente Bestandsverwaltung nicht gespawnter NPCs. Um wirklich alle NPCs unabhängig vom Onlinezustand der Regionen anzuzeigen, wäre zusätzlich eine autoritative persistente NPC-Bestandsquelle nötig. Ebenso ist der Chatverlauf ausdrücklich noch nicht umgesetzt. + +## Optionale, getrennte Konfiguration + +ROBUST/World API, als vertraulich behandelte Konfiguration: + +```ini +[NexNPCPortal] +Enabled = true +# Exakte Zahl der Regionen, deren authentifizierte Snapshots erwartet werden: +ExpectedRegionCount = +``` + +Auf dem ROBUST- und **jedem** beteiligten Simulatorprozess muss derselbe separat erzeugte starke Schlüssel als Umgebungsvariable `NEX_NPC_INGEST_SECRET` vorhanden sein. Keine Secrets im Git-Repository, in dieser Datei oder im Browser ablegen. + +Jeder Simulator benötigt zusätzlich: + +```ini +[NPC] +Enabled = true +NexNPCSnapshotEnabled = true +``` + +Simulator-Prozessumgebung: + +```text +NEX_NPC_INGEST_URL=https:///internal/nexnpc/snapshot/v1 +NEX_NPC_INGEST_SECRET= +``` + +Ohne gültigen Schlüssel, explizite Regionenzahl und aktive HTTPS-Snapshot-Sender bleibt die World-NPC-Liste aus Sicherheitsgründen nicht verfügbar. Konfiguration und Neustart von ROBUST und Simulatoren erfolgen erst nach erfolgreichem Build und abgesicherter Freigabe. Secrets niemals im Chat oder in Logs ausgeben. Die private Ingest-Route sollte zusätzlich durch Reverse Proxy/Firewall ausschließlich für autorisierte Simulator-Netzwerke erreichbar sein; HMAC ist dennoch zwingend. + +## Prüfungen + +- `dotnet run --configuration Release --project tools/ci/NexNpcDirectoryRegression/NexNpcDirectoryRegression.csproj`: eigenständige dynamische Unit-Tests für die Eigentümerzuordnung, vollständige Regionsabdeckung, doppelte NPCs, Owner-Änderung, Replay-Erkennung und inkonsistente Regionsdaten. +- `python3 tools/ci/verify_npc_owner_bridge_r617.py`: 12 statische Sicherheitstests für HMAC, begrenzte Signaturgültigkeit, Authentifizierung, Besitzerfilterung, Quellprüfung, sichere Abschaltung und API-Dokumentation. +- `dotnet build --configuration Release OpenSim.sln`: vollständiger World-Server- und Simulator-Build durch GitHub CI; auf Linux Mint liegt derzeit kein .NET-Compiler vor. + +## Datenschutz und weitere Arbeit + +Die vorhandenen Bürger-IM-Archive `NexCitizenImApi` und `INexCitizenImStore` sind **keine** NPC-Chatarchive. NPC-Gespräche dürfen erst nach geklärter rechtmäßiger Aufzeichnung, Transparenz, Einwilligung (sofern nötig), Aufbewahrungs-/Löschkonzept und Zugriffssperre anderer Nutzer serverseitig erfasst werden. Ohne diesen Teil bleibt die Chatansicht im Bürgerportal ausdrücklich nicht verfügbar. Die World-API schützt den privaten Bereich in jedem Fall durch erneute Eigentümerprüfung. + +**Freigabe:** World-Repositorium und Stadtportal sind unterschiedliche Anwendungen. Den Stadtportal-Deploy-Befehl nicht als World-Server-Update ausgeben. World-R617 erst nach erfolgreicher GitHub-CI und gesonderter Betreiberfreigabe für den World-/Simulator-Rollout aktivieren. Projektversion v0.7.0.0 und Portal-Fortschritt 71 % bleiben unverändert. diff --git a/tools/ci/NexNpcDirectoryRegression/NexNpcDirectoryRegression.csproj b/tools/ci/NexNpcDirectoryRegression/NexNpcDirectoryRegression.csproj new file mode 100644 index 00000000..cad1e4f6 --- /dev/null +++ b/tools/ci/NexNpcDirectoryRegression/NexNpcDirectoryRegression.csproj @@ -0,0 +1,12 @@ + + + Exe + net8.0 + enable + disable + true + + + + + diff --git a/tools/ci/NexNpcDirectoryRegression/Program.cs b/tools/ci/NexNpcDirectoryRegression/Program.cs new file mode 100644 index 00000000..ac0bd693 --- /dev/null +++ b/tools/ci/NexNpcDirectoryRegression/Program.cs @@ -0,0 +1,63 @@ +// SPDX-License-Identifier: MPL-2.0 +// Standalone .NET 8 source-level tests for the World NPC owner registry. +// No simulator, database, personal credentials or production API needed. +using System; +using System.Collections.Generic; +using System.Linq; +using NexVerse.Server.Api; + +int checks=0; +void Check(bool valid,string name) +{ + if(!valid)throw new Exception("NPC_DIRECTORY_FAIL "+name); + ++checks; + Console.WriteLine("NPC_DIRECTORY_PASS "+name); +} +var owner1=Guid.Parse("a1111111-1111-4111-8111-111111111111"); +var owner2=Guid.Parse("a2222222-2222-4222-8222-222222222222"); +var region1=Guid.Parse("b1111111-1111-4111-8111-111111111111"); +var region2=Guid.Parse("b2222222-2222-4222-8222-222222222222"); +var id1=Guid.Parse("c1111111-1111-4111-8111-111111111111"); +var id2=Guid.Parse("c2222222-2222-4222-8222-222222222222"); +NexNpcOwnerEntry N(Guid id,Guid owner,string name="NPC")=>new() +{ + npc_id=id,owner_principal_id=owner,name=name,region_name="Testregion" +}; +var index=new NexNpcSnapshotIndex(2); +Check(!index.TryOwned(owner1,out _,out _),"No verified snapshots means unavailable"); +Check(!index.Replace(Guid.Empty,1,new(){N(id1,owner1)}),"Zero region denied"); +Check(!index.Replace(region1,1,new(){N(Guid.Empty,owner1)}),"Zero NPC denied"); +Check(!index.Replace(region1,1,new(){N(id1,Guid.Empty)}),"Unowned NPC denied"); +Check(!index.Replace(region1,1,new(){N(id1,owner1),N(id1,owner1)}),"Duplicate IDs in region denied"); +Check(!index.Replace(region1,1,new(){N(id1,owner1," ")}),"Blank name denied"); +Check(!index.Replace(region1,1,Enumerable.Range(0,1001).Select(i=> + N(Guid.NewGuid(),owner1)).ToList()),"Oversized region denied"); +Check(index.Replace(region1,1,new(){N(id1,owner1)}),"Valid signed-region snapshot accepted"); +Check(!index.TryOwned(owner1,out _,out _),"Partial expected region coverage unavailable"); +Check(index.Replace(region2,1,new(){N(id2,owner1)}),"Second region snapshot accepted"); +Check(index.TryOwned(owner1,out var mine,out long version)&& + mine.Count==2&&mine.Any(x=>x.npc_id==id1)&&mine.Any(x=>x.npc_id==id2), + "All owner NPCs appear across both regions"); +Check(index.TryOwned(owner2,out var other,out _)&&other.Count==0, + "One resident cannot read another resident NPCs"); +Check(!index.Replace(region1,1,new(){N(id1,owner2)}),"Replay or older sequence denied"); +Check(index.TryOwned(owner1,out var preserved,out long sameVersion) && + preserved.Count==2 && version==sameVersion, + "Replay never changes owner mappings or generation"); +Check(index.Replace(region2,2,new(){N(id2,owner2)}),"Updated owner mapping accepted"); +Check(index.TryOwned(owner1,out var first,out long changedVersion)&&first.Count==1 + &&changedVersion>version,"Reassignment removes NPC from original owner"); +Check(index.TryOwned(owner2,out var second,out _)&&second.Count==1 && + second[0].npc_id==id2,"Reassigned NPC appears only for new owner"); +Check(index.Replace(region2,3,new(){N(id1,owner2)}),"Conflicting region claim syntactically accepted"); +Check(!index.TryOwned(owner1,out _,out _),"Conflicting cross-region ownership fails closed"); +Check(index.Replace(region2,4,new(){N(id1,owner1)}),"Same-owner cross-region reconciliation accepted"); +Check(index.TryOwned(owner1,out var deduplicated,out _)&& + deduplicated.Count==1,"Duplicate NPC in two regions shown once"); +Check(index.Replace(region1,2,new()),"Empty verified region snapshot accepted"); +Check(index.TryOwned(owner1,out var none,out _)&&none.Count==1, + "Empty region does not delete NPCs in another valid region"); +bool badCoverage=false; +try{new NexNpcSnapshotIndex(0);}catch(ArgumentOutOfRangeException){badCoverage=true;} +Check(badCoverage,"Unconfigured expected region coverage rejected"); +Console.WriteLine("NPC_DIRECTORY_ALL="+checks+"/"+checks+"_PASS"); diff --git a/tools/ci/verify_npc_owner_bridge_r617.py b/tools/ci/verify_npc_owner_bridge_r617.py new file mode 100644 index 00000000..9c2d59c1 --- /dev/null +++ b/tools/ci/verify_npc_owner_bridge_r617.py @@ -0,0 +1,63 @@ +#!/usr/bin/env python3 +"""R617 privacy and wiring regression for the optional NPC World API bridge. + +Functional ownership, replay and source-coverage rules are exercised by the +NexNpcDirectoryRegression .NET executable; this checks integration invariants. +""" +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[2] +REGISTRY = (ROOT / "NexVerse/Server/Api/NexNpcSnapshotIndex.cs").read_text() +INGRESS = (ROOT / "NexVerse/Server/Api/NexNpcSnapshotIngress.cs").read_text() +API = (ROOT / "NexVerse/Server/Api/NexNpcWorldApi.cs").read_text() +SIM = (ROOT / "OpenSim/Region/OptionalModules/World/NPC/NPCModule.cs").read_text() +PUBLISH = (ROOT / "OpenSim/Region/OptionalModules/World/NPC/NexNpcSnapshotPublisher.cs").read_text() +CONNECTOR = (ROOT / "NexVerse/Server/Api/NexVerseWorldApiConnector.cs").read_text() +OPENAPI = (ROOT / "NexVerse/Server/Api/NexVerseWorldApiHandlers.cs").read_text() + +def check(condition, message): + if not condition: + raise AssertionError(message) + print("R617_NPC_PASS", message) + +check('NEX_NPC_INGEST_SECRET' in CONNECTOR and + 'Encoding.UTF8.GetByteCount(npcSecret ?? "") >= 32' in CONNECTOR, + "Strong separate secret required to enable NPC ingest") +check('ExpectedRegionCount' in CONNECTOR and + 'expectedRegions > 0' in CONNECTOR, + "World directory requires explicit expected region count") +check('npcIndex = null' in CONNECTOR and + 'new NexNpcWorldApi(authenticator, npcIndex)' in CONNECTOR, + "Disabled feed never returns a fabricated empty owned NPC list") +check('"/internal/nexnpc/snapshot/v1"' in INGRESS and + 'new HMACSHA256(m_Secret)' in INGRESS and + 'CryptographicOperations.FixedTimeEquals' in INGRESS, + "Simulator ingest accepts only constant-time verified HMAC") +check('seconds < now - 180 || seconds > now + 180' in INGRESS and + 'sequence <= last.Sequence' in REGISTRY, + "Time-bound signatures and monotonic snapshots reject replay") +check('m_RequiredRegions' in REGISTRY and 'fresh.Count != m_Regions.Count' in REGISTRY, + "Missing reporting regions fail closed") +check('previous != npc.owner_principal_id' in REGISTRY, + "Conflicting NPC owner claims fail closed") +check('NexScopes.RelationshipsRead' in API and + 'account.Active' in API and 'account.LocalToGrid' in API and + 'owner != account.PrincipalID.Guid' in API and + 'npc.owner_principal_id == owner' in REGISTRY, + "NPC list is scoped to verified active local resident and owner") +check('"npc_chat_archive_unavailable"' in API and + 'NexCitizenImStore' not in API and + 'NexCitizenImApi' not in API, + "No resident IMs are misrepresented as NPC conversations") +check('NexNPCSnapshotEnabled' in SIM and + 'm_SnapshotPublisher?.Schedule()' in SIM and + 'npc.OwnerID.IsZero()' in SIM, + "Simulator sends only real owned NPCs after changes") +check('Uri.UriSchemeHttps' in PUBLISH and + '"/internal/nexnpc/snapshot/v1"' in PUBLISH and + 'new HMACSHA256(m_Key)' in PUBLISH, + "Simulator requires HTTPS and signs each snapshot") +check('"/api/v1/npcs/mine"' in OPENAPI and + '"/api/v1/npcs/{npcId}/messages"' in OPENAPI, + "Both NPC API routes documented in OpenAPI") +print("R617_NPC_SOURCE_BRIDGE=12/12_PASS")