From 89d569abdcbe53ec72fa386f033aa3c33dcf6ae9 Mon Sep 17 00:00:00 2001 From: "OpenGenesis (MPL 2.0)" <153564363+opengenesislink@users.noreply.github.com> Date: Tue, 6 Oct 2026 02:10:27 +0200 Subject: [PATCH] 0.9.3.7: Implement NexGroups parity layer and native NexExperiences Complete Roadmap Chapter 11 with NexGroups parity/management, persistent moderation, native NexExperiences, Experience LSL, OpenAPI/docs/configuration and regression coverage. --- .github/workflows/nexjast-ci.yml | 8 + .../Core/Experiences/NexExperienceStore.cs | 789 +++++++++++ NexVerse/Core/Security/NexSecurity.cs | 5 + .../Experiences/NexExperienceModule.cs | 786 +++++++++++ NexVerse/Server/Api/NexExperiencesApi.cs | 948 +++++++++++++ NexVerse/Server/Api/NexGroupsApi.cs | 1207 +++++++++++++++++ .../Server/Api/NexVerseWorldApiConnector.cs | 56 + .../Server/Api/NexVerseWorldApiHandlers.cs | 130 ++ .../Addons/Groups/Service/GroupsService.cs | 197 +++ .../Groups/Service/NexGroupModerationStore.cs | 199 +++ OpenSim/Data/IGroupsData.cs | 1 + OpenSim/Data/MySQL/MySQLGroupsData.cs | 5 + OpenSim/Data/PGSQL/PGSQLGroupsData.cs | 5 + .../Framework/Interfaces/IExperienceModule.cs | 75 + .../Framework/Scenes/SceneObjectGroup.cs | 4 +- .../Shared/Api/Implementation/LSL_Api.cs | 513 +++++++ .../Shared/Api/Interface/ILSL_Api.cs | 12 + .../Shared/Api/Runtime/LSL_Constants.cs | 21 + .../Shared/Api/Runtime/LSL_Stub.cs | 66 + .../ScriptEngine/YEngine/MMRIEventHandlers.cs | 2 + .../YEngine/MMRScriptEventCode.cs | 2 + .../ScriptEngine/YEngine/XMRInstMain.cs | 2 + .../Tests/Common/Mock/TestGroupsDataPlugin.cs | 5 + bin/OpenSim.ini.example | 11 + bin/Robust.HG.ini.example | 14 + bin/Robust.ini.example | 14 + doc/NexVerse/ROADMAP.md | 86 +- doc/NexVerse/WORLD_API.md | 23 + prebuild.xml | 1 + .../NexExperiencesRegression.csproj | 12 + tools/ci/NexExperiencesRegression/Program.cs | 260 ++++ tools/ci/verify_nexgroups_experiences.py | 216 +++ 32 files changed, 5637 insertions(+), 38 deletions(-) create mode 100644 NexVerse/Core/Experiences/NexExperienceStore.cs create mode 100644 NexVerse/RegionModules/Experiences/NexExperienceModule.cs create mode 100644 NexVerse/Server/Api/NexExperiencesApi.cs create mode 100644 NexVerse/Server/Api/NexGroupsApi.cs create mode 100644 OpenSim/Addons/Groups/Service/NexGroupModerationStore.cs create mode 100644 OpenSim/Region/Framework/Interfaces/IExperienceModule.cs create mode 100644 tools/ci/NexExperiencesRegression/NexExperiencesRegression.csproj create mode 100644 tools/ci/NexExperiencesRegression/Program.cs create mode 100644 tools/ci/verify_nexgroups_experiences.py diff --git a/.github/workflows/nexjast-ci.yml b/.github/workflows/nexjast-ci.yml index 12f4f4cf..99f08393 100644 --- a/.github/workflows/nexjast-ci.yml +++ b/.github/workflows/nexjast-ci.yml @@ -225,6 +225,14 @@ jobs: shell: bash run: python3 tools/ci/verify_banking_commerce.py + - name: Verify Chapter 11 NexGroups and NexExperiences + shell: bash + run: python3 tools/ci/verify_nexgroups_experiences.py + + - name: Regression-test NexExperiences persistence and K/V + shell: bash + run: dotnet run --configuration Release --project tools/ci/NexExperiencesRegression/NexExperiencesRegression.csproj + - name: Verify NV dollar live database matrix contract shell: bash run: python3 tools/ci/verify_ledger_db_matrix.py diff --git a/NexVerse/Core/Experiences/NexExperienceStore.cs b/NexVerse/Core/Experiences/NexExperienceStore.cs new file mode 100644 index 00000000..a66d0146 --- /dev/null +++ b/NexVerse/Core/Experiences/NexExperienceStore.cs @@ -0,0 +1,789 @@ +// SPDX-License-Identifier: MPL-2.0 + +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Text.Json; + +namespace NexVerse.Core.Experiences +{ + public enum NexExperienceMaturity + { + General = 0, + Moderate = 1, + Adult = 2 + } + + public enum NexExperiencePermissionStatus + { + None = 0, + Allowed = 1, + Blocked = 2 + } + + public sealed class NexExperience + { + public Guid ExperienceId { get; set; } + public string Name { get; set; } = string.Empty; + public string Description { get; set; } = string.Empty; + public Guid OwnerId { get; set; } + public Guid GroupId { get; set; } + public NexExperienceMaturity Maturity { get; set; } = NexExperienceMaturity.General; + public bool Enabled { get; set; } = true; + public HashSet Admins { get; set; } = new HashSet(); + public HashSet Contributors { get; set; } = new HashSet(); + public HashSet AllowedResidents { get; set; } = new HashSet(); + public HashSet BlockedResidents { get; set; } = new HashSet(); + public HashSet AllowedEstates { get; set; } = new HashSet(); + public HashSet BlockedEstates { get; set; } = new HashSet(); + public HashSet AllowedParcels { get; set; } = new HashSet(); + public HashSet BlockedParcels { get; set; } = new HashSet(); + public Dictionary KeyValues { get; set; } = + new Dictionary(StringComparer.Ordinal); + public DateTimeOffset CreatedAt { get; set; } = DateTimeOffset.UtcNow; + public DateTimeOffset UpdatedAt { get; set; } = DateTimeOffset.UtcNow; + } + + public sealed class NexExperienceLogEntry + { + public Guid LogId { get; set; } = Guid.NewGuid(); + public Guid ExperienceId { get; set; } + public DateTimeOffset Timestamp { get; set; } = DateTimeOffset.UtcNow; + public string Actor { get; set; } = string.Empty; + public string Action { get; set; } = string.Empty; + public string Detail { get; set; } = string.Empty; + } + + public sealed class NexExperienceSnapshot + { + public int SchemaVersion { get; set; } = 1; + public List Experiences { get; set; } = new List(); + public Dictionary ScriptBindings { get; set; } = new Dictionary(); + public List Logs { get; set; } = new List(); + } + + public sealed class NexExperienceStore + { + public const int CurrentSchemaVersion = 1; + public const int MaxKeyLength = 1011; + public const int MaxValueLength = 4095; + public const int MaxKeysPerExperience = 65536; + public const long MaxStoreBytes = 128L * 1024L * 1024L; + public const int MaxLogs = 10000; + + private readonly object m_Sync = new object(); + private readonly string m_Path; + private readonly JsonSerializerOptions m_Json = + new JsonSerializerOptions { WriteIndented = true }; + private NexExperienceSnapshot m_State; + + public NexExperienceStore(string path) + { + if (string.IsNullOrWhiteSpace(path)) + throw new ArgumentException("Experience store path is required.", nameof(path)); + + m_Path = Path.GetFullPath(path); + m_State = Load(); + } + + public NexExperience Create( + Guid ownerId, + Guid groupId, + string name, + string description, + NexExperienceMaturity maturity, + string actor, + Guid? experienceId = null) + { + if (ownerId == Guid.Empty) + throw new ArgumentException("Experience owner is required.", nameof(ownerId)); + + string normalizedName = NormalizeName(name); + + lock (m_Sync) + { + if (m_State.Experiences.Any(x => + string.Equals(x.Name, normalizedName, StringComparison.OrdinalIgnoreCase))) + { + throw new InvalidOperationException("An experience with that name already exists."); + } + + Guid id = experienceId ?? Guid.NewGuid(); + if (id == Guid.Empty || m_State.Experiences.Any(x => x.ExperienceId == id)) + throw new InvalidOperationException("Experience ID already exists."); + + NexExperience experience = new NexExperience + { + ExperienceId = id, + OwnerId = ownerId, + GroupId = groupId, + Name = normalizedName, + Description = (description ?? string.Empty).Trim(), + Maturity = maturity, + CreatedAt = DateTimeOffset.UtcNow, + UpdatedAt = DateTimeOffset.UtcNow + }; + experience.Admins.Add(ownerId); + + m_State.Experiences.Add(experience); + AddLog(experience.ExperienceId, actor, "experience.create", normalizedName); + Save(); + return Clone(experience); + } + } + + public NexExperience Get(Guid experienceId) + { + lock (m_Sync) + return Clone(Find(experienceId)); + } + + public IReadOnlyList Search(string query, int offset, int limit) + { + if (offset < 0) + throw new ArgumentOutOfRangeException(nameof(offset)); + if (limit < 1 || limit > 500) + throw new ArgumentOutOfRangeException(nameof(limit)); + + string normalized = (query ?? string.Empty).Trim(); + + lock (m_Sync) + { + IEnumerable result = + m_State.Experiences.Where(x => x.Enabled); + + if (normalized.Length > 0) + { + result = result.Where(x => + x.Name.IndexOf(normalized, StringComparison.OrdinalIgnoreCase) >= 0 || + x.Description.IndexOf(normalized, StringComparison.OrdinalIgnoreCase) >= 0); + } + + return result + .OrderBy(x => x.Name, StringComparer.OrdinalIgnoreCase) + .Skip(offset) + .Take(limit) + .Select(Clone) + .ToArray(); + } + } + + public NexExperience UpdateProfile( + Guid experienceId, + Guid actorId, + string name, + string description, + Guid groupId, + NexExperienceMaturity maturity, + bool enabled, + string actor) + { + lock (m_Sync) + { + NexExperience experience = RequireManage(experienceId, actorId); + string normalizedName = NormalizeName(name); + + if (m_State.Experiences.Any(x => + x.ExperienceId != experienceId && + string.Equals(x.Name, normalizedName, StringComparison.OrdinalIgnoreCase))) + { + throw new InvalidOperationException("An experience with that name already exists."); + } + + experience.Name = normalizedName; + experience.Description = (description ?? string.Empty).Trim(); + experience.GroupId = groupId; + experience.Maturity = maturity; + experience.Enabled = enabled; + experience.UpdatedAt = DateTimeOffset.UtcNow; + AddLog(experienceId, actor, "experience.update", normalizedName); + Save(); + return Clone(experience); + } + } + + public void Delete(Guid experienceId, Guid actorId, string actor) + { + lock (m_Sync) + { + NexExperience experience = Find(experienceId) ?? + throw new KeyNotFoundException("Experience was not found."); + + if (experience.OwnerId != actorId) + throw new UnauthorizedAccessException("Only the experience owner can delete it."); + + m_State.Experiences.Remove(experience); + + foreach (Guid scriptId in m_State.ScriptBindings + .Where(x => x.Value == experienceId) + .Select(x => x.Key) + .ToArray()) + { + m_State.ScriptBindings.Remove(scriptId); + } + + AddLog(experienceId, actor, "experience.delete", experience.Name); + Save(); + } + } + + public NexExperience SetRole( + Guid experienceId, + Guid actorId, + Guid residentId, + string role, + bool enabled, + string actor) + { + if (residentId == Guid.Empty) + throw new ArgumentException("Resident ID is required.", nameof(residentId)); + + lock (m_Sync) + { + NexExperience experience = RequireManage(experienceId, actorId); + HashSet target; + + if (string.Equals(role, "admin", StringComparison.OrdinalIgnoreCase)) + target = experience.Admins; + else if (string.Equals(role, "contributor", StringComparison.OrdinalIgnoreCase)) + target = experience.Contributors; + else + throw new ArgumentException("Role must be admin or contributor.", nameof(role)); + + if (enabled) + target.Add(residentId); + else if (residentId != experience.OwnerId) + target.Remove(residentId); + + experience.UpdatedAt = DateTimeOffset.UtcNow; + AddLog(experienceId, actor, "experience.role", role + ":" + residentId + ":" + enabled); + Save(); + return Clone(experience); + } + } + + public NexExperiencePermissionStatus GetResidentPermission( + Guid experienceId, + Guid residentId) + { + lock (m_Sync) + { + NexExperience experience = Find(experienceId); + if (experience == null || !experience.Enabled) + return NexExperiencePermissionStatus.None; + + if (experience.BlockedResidents.Contains(residentId)) + return NexExperiencePermissionStatus.Blocked; + + if (experience.OwnerId == residentId || + experience.Admins.Contains(residentId) || + experience.Contributors.Contains(residentId) || + experience.AllowedResidents.Contains(residentId)) + { + return NexExperiencePermissionStatus.Allowed; + } + + return NexExperiencePermissionStatus.None; + } + } + + public NexExperience SetResidentPermission( + Guid experienceId, + Guid actorId, + Guid residentId, + NexExperiencePermissionStatus status, + string actor) + { + if (residentId == Guid.Empty) + throw new ArgumentException("Resident ID is required.", nameof(residentId)); + + lock (m_Sync) + { + NexExperience experience = RequireManage(experienceId, actorId); + experience.AllowedResidents.Remove(residentId); + experience.BlockedResidents.Remove(residentId); + + if (status == NexExperiencePermissionStatus.Allowed) + experience.AllowedResidents.Add(residentId); + else if (status == NexExperiencePermissionStatus.Blocked) + experience.BlockedResidents.Add(residentId); + + experience.UpdatedAt = DateTimeOffset.UtcNow; + AddLog(experienceId, actor, "experience.permission", + residentId + ":" + status); + Save(); + return Clone(experience); + } + } + + public NexExperience SetLocationPolicy( + Guid experienceId, + Guid actorId, + string kind, + Guid locationId, + bool allowed, + bool enabled, + string actor) + { + if (locationId == Guid.Empty) + throw new ArgumentException("Location ID is required.", nameof(locationId)); + + lock (m_Sync) + { + NexExperience experience = RequireManage(experienceId, actorId); + HashSet allow; + HashSet block; + + if (string.Equals(kind, "estate", StringComparison.OrdinalIgnoreCase)) + { + allow = experience.AllowedEstates; + block = experience.BlockedEstates; + } + else if (string.Equals(kind, "parcel", StringComparison.OrdinalIgnoreCase)) + { + allow = experience.AllowedParcels; + block = experience.BlockedParcels; + } + else + { + throw new ArgumentException("Policy kind must be estate or parcel.", nameof(kind)); + } + + allow.Remove(locationId); + block.Remove(locationId); + + if (enabled) + { + if (allowed) + allow.Add(locationId); + else + block.Add(locationId); + } + + experience.UpdatedAt = DateTimeOffset.UtcNow; + AddLog(experienceId, actor, "experience.location_policy", + kind + ":" + locationId + ":" + (allowed ? "allow" : "block") + ":" + enabled); + Save(); + return Clone(experience); + } + } + + public bool IsLocationAllowed( + Guid experienceId, + Guid estateId, + Guid parcelId) + { + lock (m_Sync) + { + NexExperience experience = Find(experienceId); + if (experience == null || !experience.Enabled) + return false; + + if (estateId != Guid.Empty && experience.BlockedEstates.Contains(estateId)) + return false; + if (parcelId != Guid.Empty && experience.BlockedParcels.Contains(parcelId)) + return false; + + if (experience.AllowedEstates.Count > 0 && + (estateId == Guid.Empty || !experience.AllowedEstates.Contains(estateId))) + { + return false; + } + + if (experience.AllowedParcels.Count > 0 && + (parcelId == Guid.Empty || !experience.AllowedParcels.Contains(parcelId))) + { + return false; + } + + return true; + } + } + + public void BindScript( + Guid experienceId, + Guid actorId, + Guid scriptItemId, + string actor) + { + if (scriptItemId == Guid.Empty) + throw new ArgumentException("Script item ID is required.", nameof(scriptItemId)); + + lock (m_Sync) + { + RequireManage(experienceId, actorId); + m_State.ScriptBindings[scriptItemId] = experienceId; + AddLog(experienceId, actor, "experience.script.bind", scriptItemId.ToString("D")); + Save(); + } + } + + public Guid ResolveScript(Guid scriptItemId) + { + lock (m_Sync) + return m_State.ScriptBindings.TryGetValue(scriptItemId, out Guid id) + ? id + : Guid.Empty; + } + + public bool CreateKeyValue( + Guid experienceId, + Guid scriptItemId, + string key, + string value) + { + lock (m_Sync) + { + RequireBoundScript(experienceId, scriptItemId); + NexExperience experience = Find(experienceId); + string normalized = ValidateKey(key); + ValidateValue(value); + + if (experience.KeyValues.ContainsKey(normalized)) + return false; + if (experience.KeyValues.Count >= MaxKeysPerExperience) + throw new InvalidOperationException("Experience key/value quota exceeded."); + + experience.KeyValues.Add(normalized, value ?? string.Empty); + + if (GetStoreBytes(experience) > MaxStoreBytes) + { + experience.KeyValues.Remove(normalized); + throw new InvalidOperationException("Experience key/value storage quota exceeded."); + } + + experience.UpdatedAt = DateTimeOffset.UtcNow; + Save(); + return true; + } + } + + public bool TryReadKeyValue( + Guid experienceId, + Guid scriptItemId, + string key, + out string value) + { + lock (m_Sync) + { + RequireBoundScript(experienceId, scriptItemId); + NexExperience experience = Find(experienceId); + return experience.KeyValues.TryGetValue(ValidateKey(key), out value); + } + } + + public bool UpdateKeyValue( + Guid experienceId, + Guid scriptItemId, + string key, + string value, + bool checkOriginal, + string originalValue, + out bool retryMismatch) + { + lock (m_Sync) + { + RequireBoundScript(experienceId, scriptItemId); + NexExperience experience = Find(experienceId); + string normalized = ValidateKey(key); + ValidateValue(value); + retryMismatch = false; + + bool exists = + experience.KeyValues.TryGetValue( + normalized, + out string current); + + if (checkOriginal && + exists && + !string.Equals( + current, + originalValue ?? string.Empty, + StringComparison.Ordinal)) + { + retryMismatch = true; + return false; + } + + if (!exists && + experience.KeyValues.Count >= MaxKeysPerExperience) + { + throw new InvalidOperationException("Experience key/value quota exceeded."); + } + + experience.KeyValues[normalized] = value ?? string.Empty; + + if (GetStoreBytes(experience) > MaxStoreBytes) + { + if (exists) + experience.KeyValues[normalized] = current; + else + experience.KeyValues.Remove(normalized); + + throw new InvalidOperationException("Experience key/value storage quota exceeded."); + } + + experience.UpdatedAt = DateTimeOffset.UtcNow; + Save(); + return true; + } + } + + public int GetKeyCount( + Guid experienceId, + Guid scriptItemId) + { + lock (m_Sync) + { + RequireBoundScript(experienceId, scriptItemId); + return Find(experienceId).KeyValues.Count; + } + } + + public IReadOnlyList ListKeys( + Guid experienceId, + Guid scriptItemId, + int start, + int count) + { + if (start < 0) + throw new ArgumentOutOfRangeException(nameof(start)); + if (count < 1 || count > 1024) + throw new ArgumentOutOfRangeException(nameof(count)); + + lock (m_Sync) + { + RequireBoundScript(experienceId, scriptItemId); + return Find(experienceId).KeyValues.Keys + .OrderBy(x => x, StringComparer.Ordinal) + .Skip(start) + .Take(count) + .ToArray(); + } + } + + public long GetDataSize( + Guid experienceId, + Guid scriptItemId) + { + lock (m_Sync) + { + RequireBoundScript(experienceId, scriptItemId); + return GetStoreBytes(Find(experienceId)); + } + } + + private static long GetStoreBytes( + NexExperience experience) + { + long bytes = 0; + + foreach (KeyValuePair entry in experience.KeyValues) + { + bytes += System.Text.Encoding.UTF8.GetByteCount(entry.Key); + bytes += System.Text.Encoding.UTF8.GetByteCount(entry.Value ?? string.Empty); + } + + return bytes; + } + + public bool DeleteKeyValue( + Guid experienceId, + Guid scriptItemId, + string key) + { + lock (m_Sync) + { + RequireBoundScript(experienceId, scriptItemId); + NexExperience experience = Find(experienceId); + bool removed = experience.KeyValues.Remove(ValidateKey(key)); + if (removed) + { + experience.UpdatedAt = DateTimeOffset.UtcNow; + Save(); + } + return removed; + } + } + + public IReadOnlyList GetLogs( + Guid experienceId, + int offset, + int limit) + { + if (offset < 0) + throw new ArgumentOutOfRangeException(nameof(offset)); + if (limit < 1 || limit > 500) + throw new ArgumentOutOfRangeException(nameof(limit)); + + lock (m_Sync) + { + return m_State.Logs + .Where(x => x.ExperienceId == experienceId) + .OrderByDescending(x => x.Timestamp) + .Skip(offset) + .Take(limit) + .Select(Clone) + .ToArray(); + } + } + + private NexExperience RequireManage(Guid experienceId, Guid actorId) + { + NexExperience experience = Find(experienceId) ?? + throw new KeyNotFoundException("Experience was not found."); + + if (actorId == Guid.Empty || + (experience.OwnerId != actorId && !experience.Admins.Contains(actorId))) + { + throw new UnauthorizedAccessException("Experience management permission is required."); + } + + return experience; + } + + private void RequireBoundScript(Guid experienceId, Guid scriptItemId) + { + if (Find(experienceId) == null) + throw new KeyNotFoundException("Experience was not found."); + + if (!m_State.ScriptBindings.TryGetValue(scriptItemId, out Guid bound) || + bound != experienceId) + { + throw new UnauthorizedAccessException("Script is not bound to this experience."); + } + } + + private NexExperience Find(Guid id) => + m_State.Experiences.FirstOrDefault(x => x.ExperienceId == id); + + private static string NormalizeName(string name) + { + string normalized = (name ?? string.Empty).Trim(); + if (normalized.Length < 3 || normalized.Length > 64) + throw new ArgumentOutOfRangeException(nameof(name), "Experience name must contain 3-64 characters."); + return normalized; + } + + private static string ValidateKey(string key) + { + string normalized = (key ?? string.Empty).Trim(); + + if (normalized.Length == 0 || + System.Text.Encoding.UTF8.GetByteCount(normalized) > MaxKeyLength) + { + throw new ArgumentOutOfRangeException(nameof(key)); + } + + return normalized; + } + + private static void ValidateValue(string value) + { + if (System.Text.Encoding.UTF8.GetByteCount(value ?? string.Empty) > + MaxValueLength) + { + throw new ArgumentOutOfRangeException(nameof(value)); + } + } + + private void AddLog(Guid experienceId, string actor, string action, string detail) + { + m_State.Logs.Add(new NexExperienceLogEntry + { + ExperienceId = experienceId, + Actor = string.IsNullOrWhiteSpace(actor) ? "unknown" : actor, + Action = action ?? string.Empty, + Detail = detail ?? string.Empty + }); + + if (m_State.Logs.Count > MaxLogs) + m_State.Logs.RemoveRange(0, m_State.Logs.Count - MaxLogs); + } + + private NexExperienceSnapshot Load() + { + if (!File.Exists(m_Path)) + return new NexExperienceSnapshot { SchemaVersion = CurrentSchemaVersion }; + + NexExperienceSnapshot state = + JsonSerializer.Deserialize( + File.ReadAllText(m_Path), + m_Json) ?? + new NexExperienceSnapshot(); + + if (state.SchemaVersion != CurrentSchemaVersion) + throw new InvalidOperationException("Unsupported experience store schema version."); + + state.Experiences ??= new List(); + state.ScriptBindings ??= new Dictionary(); + state.Logs ??= new List(); + + foreach (NexExperience experience in state.Experiences) + { + experience.Admins ??= new HashSet(); + experience.Contributors ??= new HashSet(); + experience.AllowedResidents ??= new HashSet(); + experience.BlockedResidents ??= new HashSet(); + experience.AllowedEstates ??= new HashSet(); + experience.BlockedEstates ??= new HashSet(); + experience.AllowedParcels ??= new HashSet(); + experience.BlockedParcels ??= new HashSet(); + experience.KeyValues ??= new Dictionary(StringComparer.Ordinal); + } + + return state; + } + + private void Save() + { + string directory = Path.GetDirectoryName(m_Path); + if (!string.IsNullOrEmpty(directory)) + Directory.CreateDirectory(directory); + + string temp = m_Path + ".tmp"; + File.WriteAllText(temp, JsonSerializer.Serialize(m_State, m_Json)); + File.Move(temp, m_Path, true); + } + + private static NexExperience Clone(NexExperience source) + { + if (source == null) + return null; + + return new NexExperience + { + ExperienceId = source.ExperienceId, + Name = source.Name, + Description = source.Description, + OwnerId = source.OwnerId, + GroupId = source.GroupId, + Maturity = source.Maturity, + Enabled = source.Enabled, + Admins = new HashSet(source.Admins), + Contributors = new HashSet(source.Contributors), + AllowedResidents = new HashSet(source.AllowedResidents), + BlockedResidents = new HashSet(source.BlockedResidents), + AllowedEstates = new HashSet(source.AllowedEstates), + BlockedEstates = new HashSet(source.BlockedEstates), + AllowedParcels = new HashSet(source.AllowedParcels), + BlockedParcels = new HashSet(source.BlockedParcels), + KeyValues = new Dictionary(source.KeyValues, StringComparer.Ordinal), + CreatedAt = source.CreatedAt, + UpdatedAt = source.UpdatedAt + }; + } + + private static NexExperienceLogEntry Clone(NexExperienceLogEntry source) => + new NexExperienceLogEntry + { + LogId = source.LogId, + ExperienceId = source.ExperienceId, + Timestamp = source.Timestamp, + Actor = source.Actor, + Action = source.Action, + Detail = source.Detail + }; + } +} diff --git a/NexVerse/Core/Security/NexSecurity.cs b/NexVerse/Core/Security/NexSecurity.cs index 76cee963..64d08997 100644 --- a/NexVerse/Core/Security/NexSecurity.cs +++ b/NexVerse/Core/Security/NexSecurity.cs @@ -30,6 +30,11 @@ namespace NexVerse.Core.Security public const string EstatesManage = "estates:manage"; public const string EconomyRead = "economy:read"; public const string EconomyTransfer = "economy:transfer"; + public const string GroupsRead = "groups:read"; + public const string GroupsManage = "groups:manage"; + public const string ExperiencesRead = "experiences:read"; + public const string ExperiencesManage = "experiences:manage"; + public const string ExperiencesScript = "experiences:script"; } public sealed class NexPrincipal diff --git a/NexVerse/RegionModules/Experiences/NexExperienceModule.cs b/NexVerse/RegionModules/Experiences/NexExperienceModule.cs new file mode 100644 index 00000000..ea68aba5 --- /dev/null +++ b/NexVerse/RegionModules/Experiences/NexExperienceModule.cs @@ -0,0 +1,786 @@ +// SPDX-License-Identifier: MPL-2.0 + +using System; +using System.Collections.Generic; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Text; +using System.Text.Json; +using log4net; +using Mono.Addins; +using Nini.Config; +using OpenMetaverse; +using OpenSim.Region.Framework.Interfaces; +using OpenSim.Region.Framework.Scenes; + +namespace NexVerse.RegionModules.Experiences +{ + [Extension( + Path = "/OpenSim/RegionModules", + NodeName = "RegionModule", + Id = "NexExperienceModule")] + public sealed class NexExperienceModule : + IExperienceModule, + ISharedRegionModule + { + private static readonly ILog m_Log = + LogManager.GetLogger(typeof(NexExperienceModule)); + + private readonly object m_Sync = new object(); + private readonly List m_Scenes = new List(); + + private bool m_Enabled; + private string m_WorldApiBaseUrl = string.Empty; + private string m_ApiKey = string.Empty; + private int m_RequestTimeoutMilliseconds = 3000; + private HttpClient m_Http; + + public string Name => "NexExperienceModule"; + public Type ReplaceableInterface => typeof(IExperienceModule); + + public void Initialise(IConfigSource config) + { + IConfig section = + config?.Configs["NexExperiencesViewer"]; + + if (section == null || + !section.GetBoolean("Enabled", false)) + { + m_Enabled = false; + return; + } + + m_WorldApiBaseUrl = + section.GetString("WorldApiBaseUrl", string.Empty) + .Trim() + .TrimEnd('/'); + + m_ApiKey = + section.GetString("ApiKey", string.Empty) + .Trim(); + + m_RequestTimeoutMilliseconds = + Math.Clamp( + section.GetInt("RequestTimeoutMilliseconds", 3000), + 500, + 30000); + + if (!Uri.TryCreate( + m_WorldApiBaseUrl, + UriKind.Absolute, + out Uri baseUri) || + (baseUri.Scheme != Uri.UriSchemeHttp && + baseUri.Scheme != Uri.UriSchemeHttps)) + { + throw new InvalidOperationException( + "[NEX-EXPERIENCES]: WorldApiBaseUrl must be an absolute HTTP(S) URL."); + } + + if (string.IsNullOrWhiteSpace(m_ApiKey)) + throw new InvalidOperationException( + "[NEX-EXPERIENCES]: ApiKey is required when enabled."); + + m_Http = + new HttpClient + { + Timeout = + TimeSpan.FromMilliseconds( + m_RequestTimeoutMilliseconds) + }; + + m_Enabled = true; + + m_Log.InfoFormat( + "[NEX-EXPERIENCES]: Central Experience adapter enabled for {0}.", + m_WorldApiBaseUrl); + } + + public void PostInitialise() + { + } + + public void AddRegion(Scene scene) + { + if (!m_Enabled || scene == null) + return; + + lock (m_Sync) + m_Scenes.Add(scene); + + scene.RegisterModuleInterface(this); + } + + public void RegionLoaded(Scene scene) + { + } + + public void RemoveRegion(Scene scene) + { + if (scene == null) + return; + + scene.UnregisterModuleInterface(this); + + lock (m_Sync) + m_Scenes.Remove(scene); + } + + public void Close() + { + lock (m_Sync) + m_Scenes.Clear(); + + m_Http?.Dispose(); + m_Http = null; + } + + public UUID ResolveExperience(UUID scriptItemId) + { + if (!m_Enabled || scriptItemId.IsZero()) + return UUID.Zero; + + try + { + using HttpRequestMessage request = + CreateRequest( + HttpMethod.Get, + "/api/v1/experiences/script/resolve?script_id=" + + Uri.EscapeDataString(scriptItemId.ToString())); + + using HttpResponseMessage response = + m_Http.Send(request); + + if (!response.IsSuccessStatusCode) + return UUID.Zero; + + using JsonDocument document = + JsonDocument.Parse( + response.Content + .ReadAsStringAsync() + .GetAwaiter() + .GetResult()); + + if (!document.RootElement.TryGetProperty( + "experience_id", + out JsonElement value) || + value.ValueKind != JsonValueKind.String || + !UUID.TryParse(value.GetString(), out UUID experienceId)) + { + return UUID.Zero; + } + + return experienceId; + } + catch (Exception e) + { + m_Log.WarnFormat( + "[NEX-EXPERIENCES]: Resolve for script {0} failed: {1}", + scriptItemId, + e.Message); + return UUID.Zero; + } + } + + public bool TryGetExperienceDetails( + UUID experienceId, + out string name, + out UUID ownerId, + out UUID groupId, + out int maturity, + out bool enabled) + { + name = string.Empty; + ownerId = UUID.Zero; + groupId = UUID.Zero; + maturity = 0; + enabled = false; + + if (!m_Enabled || experienceId.IsZero()) + return false; + + try + { + using HttpRequestMessage request = + CreateRequest( + HttpMethod.Get, + "/api/v1/experiences/script/details?experience_id=" + + Uri.EscapeDataString( + experienceId.ToString())); + + using HttpResponseMessage response = + m_Http.Send(request); + + if (!response.IsSuccessStatusCode) + return false; + + using JsonDocument document = + JsonDocument.Parse( + response.Content + .ReadAsStringAsync() + .GetAwaiter() + .GetResult()); + + if (!document.RootElement.TryGetProperty( + "experience", + out JsonElement experience)) + { + return false; + } + + name = + experience.TryGetProperty("name", out JsonElement nameElement) && + nameElement.ValueKind == JsonValueKind.String + ? nameElement.GetString() ?? string.Empty + : string.Empty; + + if (experience.TryGetProperty("owner_id", out JsonElement ownerElement) && + ownerElement.ValueKind == JsonValueKind.String) + { + UUID.TryParse(ownerElement.GetString(), out ownerId); + } + + if (experience.TryGetProperty("group_id", out JsonElement groupElement) && + groupElement.ValueKind == JsonValueKind.String) + { + UUID.TryParse(groupElement.GetString(), out groupId); + } + + string maturityName = + experience.TryGetProperty("maturity", out JsonElement maturityElement) && + maturityElement.ValueKind == JsonValueKind.String + ? maturityElement.GetString() ?? "general" + : "general"; + + maturity = + maturityName.Equals("adult", StringComparison.OrdinalIgnoreCase) + ? 2 + : maturityName.Equals("moderate", StringComparison.OrdinalIgnoreCase) + ? 1 + : 0; + + enabled = + experience.TryGetProperty("enabled", out JsonElement enabledElement) && + enabledElement.ValueKind == JsonValueKind.True; + + return true; + } + catch (Exception e) + { + m_Log.WarnFormat( + "[NEX-EXPERIENCES]: Details for {0} failed: {1}", + experienceId, + e.Message); + return false; + } + } + + public bool HasExperiencePermission( + UUID scriptItemId, + UUID residentId, + UUID parcelId, + out UUID experienceId, + out string reason) + { + experienceId = UUID.Zero; + reason = string.Empty; + + if (!m_Enabled) + { + reason = "Experience service is disabled."; + return false; + } + + if (scriptItemId.IsZero() || residentId.IsZero()) + { + reason = "Script and resident UUID are required."; + return false; + } + + try + { + using HttpRequestMessage permissionRequest = + CreateRequest( + HttpMethod.Get, + "/api/v1/experiences/script/permission?script_id=" + + Uri.EscapeDataString(scriptItemId.ToString()) + + "&resident_id=" + + Uri.EscapeDataString(residentId.ToString())); + + using HttpResponseMessage permissionResponse = + m_Http.Send(permissionRequest); + + if (!permissionResponse.IsSuccessStatusCode) + { + reason = ReadErrorMessage(permissionResponse); + return false; + } + + using JsonDocument permissionDocument = + JsonDocument.Parse( + permissionResponse.Content + .ReadAsStringAsync() + .GetAwaiter() + .GetResult()); + + JsonElement root = + permissionDocument.RootElement; + + if (root.TryGetProperty("experience_id", out JsonElement experienceElement) && + experienceElement.ValueKind == JsonValueKind.String) + { + UUID.TryParse( + experienceElement.GetString(), + out experienceId); + } + + bool residentAllowed = + root.TryGetProperty("allowed", out JsonElement allowedElement) && + allowedElement.ValueKind == JsonValueKind.True; + + if (!residentAllowed) + { + reason = "Resident has not granted this experience."; + return false; + } + + if (!parcelId.IsZero()) + { + using HttpRequestMessage locationRequest = + CreateRequest( + HttpMethod.Get, + "/api/v1/experiences/script/location?script_id=" + + Uri.EscapeDataString(scriptItemId.ToString()) + + "&parcel_id=" + + Uri.EscapeDataString(parcelId.ToString())); + + using HttpResponseMessage locationResponse = + m_Http.Send(locationRequest); + + if (!locationResponse.IsSuccessStatusCode) + { + reason = ReadErrorMessage(locationResponse); + return false; + } + + using JsonDocument locationDocument = + JsonDocument.Parse( + locationResponse.Content + .ReadAsStringAsync() + .GetAwaiter() + .GetResult()); + + bool locationAllowed = + locationDocument.RootElement.TryGetProperty( + "allowed", + out JsonElement locationAllowedElement) && + locationAllowedElement.ValueKind == JsonValueKind.True; + + if (!locationAllowed) + { + reason = "Experience is blocked by parcel/estate policy."; + return false; + } + } + + return !experienceId.IsZero(); + } + catch (Exception e) + { + reason = "Experience permission check failed."; + m_Log.WarnFormat( + "[NEX-EXPERIENCES]: Permission for script {0}/resident {1} failed: {2}", + scriptItemId, + residentId, + e.Message); + return false; + } + } + + public bool AgentInExperience( + UUID scriptItemId, + UUID residentId) => + HasExperiencePermission( + scriptItemId, + residentId, + UUID.Zero, + out _, + out _); + + public bool CreateKeyValue( + UUID scriptItemId, + string key, + string value, + out string error) => + KeyValue( + scriptItemId, + "create", + key, + value, + false, + string.Empty, + 0, + 0, + out _, + out _, + out error); + + public bool ReadKeyValue( + UUID scriptItemId, + string key, + out string value, + out string error) => + KeyValue( + scriptItemId, + "read", + key, + string.Empty, + false, + string.Empty, + 0, + 0, + out value, + out _, + out error); + + public bool UpdateKeyValue( + UUID scriptItemId, + string key, + string value, + bool checkOriginal, + string originalValue, + out bool retryMismatch, + out string error) + { + retryMismatch = false; + + bool success = + KeyValue( + scriptItemId, + "update", + key, + value, + checkOriginal, + originalValue, + 0, + 0, + out _, + out string code, + out error); + + retryMismatch = + string.Equals( + code, + "retry_update", + StringComparison.OrdinalIgnoreCase); + + return success; + } + + public bool DeleteKeyValue( + UUID scriptItemId, + string key, + out string error) => + KeyValue( + scriptItemId, + "delete", + key, + string.Empty, + false, + string.Empty, + 0, + 0, + out _, + out _, + out error); + + public bool GetKeyValueStats( + UUID scriptItemId, + out long usedBytes, + out long quotaBytes, + out int keyCount, + out string error) + { + usedBytes = 0; + quotaBytes = 0; + keyCount = 0; + + if (!KeyValue( + scriptItemId, + "stats", + string.Empty, + string.Empty, + false, + string.Empty, + 0, + 0, + out string result, + out _, + out error)) + { + return false; + } + + try + { + using JsonDocument document = + JsonDocument.Parse(result); + + JsonElement root = document.RootElement; + usedBytes = + root.TryGetProperty("used_bytes", out JsonElement used) && + used.TryGetInt64(out long usedValue) + ? usedValue + : 0L; + quotaBytes = + root.TryGetProperty("quota_bytes", out JsonElement quota) && + quota.TryGetInt64(out long quotaValue) + ? quotaValue + : 0L; + keyCount = + root.TryGetProperty("key_count", out JsonElement count) && + count.TryGetInt32(out int countValue) + ? countValue + : 0; + + return true; + } + catch + { + error = "Invalid Experience K/V stats response."; + return false; + } + } + + public bool ListKeyValueKeys( + UUID scriptItemId, + int start, + int count, + out string[] keys, + out string error) + { + keys = Array.Empty(); + + if (!KeyValue( + scriptItemId, + "keys", + string.Empty, + string.Empty, + false, + string.Empty, + start, + count, + out string result, + out _, + out error)) + { + return false; + } + + try + { + using JsonDocument document = + JsonDocument.Parse(result); + + if (!document.RootElement.TryGetProperty( + "keys", + out JsonElement array) || + array.ValueKind != JsonValueKind.Array) + { + error = "Invalid Experience K/V keys response."; + return false; + } + + List output = + new List(); + + foreach (JsonElement element in array.EnumerateArray()) + { + if (element.ValueKind == JsonValueKind.String) + output.Add(element.GetString() ?? string.Empty); + } + + keys = output.ToArray(); + return true; + } + catch + { + error = "Invalid Experience K/V keys response."; + return false; + } + } + + private bool KeyValue( + UUID scriptItemId, + string operation, + string key, + string value, + bool checkOriginal, + string originalValue, + int start, + int count, + out string result, + out string code, + out string error) + { + result = string.Empty; + code = string.Empty; + error = string.Empty; + + if (!m_Enabled || scriptItemId.IsZero()) + { + error = "Experience service is unavailable."; + return false; + } + + try + { + byte[] payload = + JsonSerializer.SerializeToUtf8Bytes( + new + { + script_id = scriptItemId.ToString(), + operation, + key, + value = value ?? string.Empty, + check_original = checkOriginal, + original_value = originalValue ?? string.Empty, + start, + count + }); + + using HttpRequestMessage request = + CreateRequest( + HttpMethod.Post, + "/api/v1/experiences/script/kv"); + + request.Content = + new ByteArrayContent(payload); + request.Content.Headers.ContentType = + new MediaTypeHeaderValue("application/json"); + + using HttpResponseMessage response = + m_Http.Send(request); + + string body = + response.Content + .ReadAsStringAsync() + .GetAwaiter() + .GetResult(); + + if (!response.IsSuccessStatusCode) + { + error = ReadErrorMessage(response, body); + return false; + } + + using JsonDocument document = + JsonDocument.Parse(body); + + bool success = + document.RootElement.TryGetProperty( + "success", + out JsonElement successElement) && + successElement.ValueKind == JsonValueKind.True; + + if (document.RootElement.TryGetProperty( + "result", + out JsonElement resultElement)) + { + result = + resultElement.ValueKind == JsonValueKind.String + ? resultElement.GetString() ?? string.Empty + : resultElement.GetRawText(); + } + + if (document.RootElement.TryGetProperty( + "code", + out JsonElement codeElement) && + codeElement.ValueKind == JsonValueKind.String) + { + code = + codeElement.GetString() ?? + string.Empty; + } + + if (!success) + { + error = + document.RootElement.TryGetProperty( + "message", + out JsonElement messageElement) && + messageElement.ValueKind == JsonValueKind.String + ? messageElement.GetString() ?? "Experience key/value operation was rejected." + : "Experience key/value operation was rejected."; + } + + return success; + } + catch (Exception e) + { + error = "Experience key/value service unavailable."; + m_Log.WarnFormat( + "[NEX-EXPERIENCES]: K/V {0} for script {1} failed: {2}", + operation, + scriptItemId, + e.Message); + return false; + } + } + + private HttpRequestMessage CreateRequest( + HttpMethod method, + string path) + { + HttpRequestMessage request = + new HttpRequestMessage( + method, + m_WorldApiBaseUrl + + path); + + request.Headers.TryAddWithoutValidation( + "X-NexVerse-Api-Key", + m_ApiKey); + request.Headers.Accept.Add( + new MediaTypeWithQualityHeaderValue( + "application/json")); + + return request; + } + + private static string ReadErrorMessage( + HttpResponseMessage response, + string body = null) + { + try + { + string json = + body ?? + response.Content + .ReadAsStringAsync() + .GetAwaiter() + .GetResult(); + + using JsonDocument document = + JsonDocument.Parse(json); + + if (document.RootElement.TryGetProperty( + "message", + out JsonElement message) && + message.ValueKind == JsonValueKind.String) + { + return + message.GetString() ?? + "Experience request failed."; + } + } + catch + { + } + + return + "Experience request failed (" + + (int)response.StatusCode + + ")."; + } + } +} diff --git a/NexVerse/Server/Api/NexExperiencesApi.cs b/NexVerse/Server/Api/NexExperiencesApi.cs new file mode 100644 index 00000000..32ec24b0 --- /dev/null +++ b/NexVerse/Server/Api/NexExperiencesApi.cs @@ -0,0 +1,948 @@ +// SPDX-License-Identifier: MPL-2.0 + +using System; +using System.Collections.Generic; +using System.Globalization; +using System.Linq; +using System.Net; +using System.Text.Json; +using NexVerse.Core.Audit; +using NexVerse.Core.Experiences; +using NexVerse.Core.Security; +using OpenMetaverse; +using OpenSim.Framework; +using OpenSim.Framework.Servers.HttpServer; +using OpenSim.Services.Interfaces; + +namespace NexVerse.Server.Api +{ + internal sealed class NexExperiencesApi + { + private static readonly JsonSerializerOptions s_Json = + new JsonSerializerOptions { WriteIndented = true }; + + private readonly NexApiAuthenticator m_Authenticator; + private readonly IUserAccountService m_Users; + private readonly INexAuditSink m_Audit; + private readonly NexExperienceStore m_Store; + + public NexExperiencesApi( + NexApiAuthenticator authenticator, + IUserAccountService users, + INexAuditSink audit, + NexExperienceStore store) + { + m_Authenticator = authenticator ?? throw new ArgumentNullException(nameof(authenticator)); + m_Users = users ?? throw new ArgumentNullException(nameof(users)); + m_Audit = audit ?? NullNexAuditSink.Instance; + m_Store = store ?? throw new ArgumentNullException(nameof(store)); + } + + public void Handle(IOSHttpRequest request, IOSHttpResponse response) + { + string path = (request?.UriPath ?? string.Empty).TrimEnd('/'); + string method = request?.HttpMethod ?? string.Empty; + + if (path == "/api/v1/experiences") + { + if (method.Equals("GET", StringComparison.OrdinalIgnoreCase)) + { + if (!Authenticate(request, response, NexScopes.ExperiencesRead, out _, out _)) + return; + + try + { + string query = request?.QueryString?["q"] ?? string.Empty; + int offset = QueryInt(request, "offset", 0, 0, 1000000); + int limit = QueryInt(request, "limit", 100, 1, 500); + + WriteJson(response, new + { + experiences = m_Store.Search(query, offset, limit).Select(Payload).ToArray(), + offset, + limit, + correlation_id = Correlation(response) + }); + } + catch (Exception e) + { + WriteFailure(response, e); + } + + return; + } + + if (method.Equals("POST", StringComparison.OrdinalIgnoreCase)) + { + if (!Authenticate(request, response, NexScopes.ExperiencesManage, out NexPrincipal principal, out UserAccount account)) + return; + + if (!TryBody(request, response, out JsonElement body)) + return; + + try + { + Guid owner = + account != null + ? account.PrincipalID.Guid + : BodyGuid(body, "owner_id"); + + if (account != null && + body.TryGetProperty("owner_id", out JsonElement ownerElement) && + ownerElement.ValueKind == JsonValueKind.String && + Guid.TryParse(ownerElement.GetString(), out Guid requestedOwner) && + requestedOwner != owner && + !principal.HasScope(NexScopes.AdminAll)) + { + throw new UnauthorizedAccessException("Resident tokens may create only self-owned experiences."); + } + + Guid explicitId = + BodyOptionalGuid( + body, + "experience_id"); + + NexExperience created = + m_Store.Create( + owner, + BodyOptionalGuid(body, "group_id"), + BodyString(body, "name"), + BodyString(body, "description"), + ParseMaturity(BodyString(body, "maturity")), + principal.Subject, + explicitId == Guid.Empty + ? null + : explicitId); + + Audit(principal, "experience.created", created.ExperienceId, response); + + WriteJson(response, new + { + experience = Payload(created), + correlation_id = Correlation(response) + }, HttpStatusCode.Created); + } + catch (Exception e) + { + WriteFailure(response, e); + } + + return; + } + + MethodNotAllowed(response, "GET or POST"); + return; + } + + if (path == "/api/v1/experiences/script/resolve") + { + if (!RequireMethod(method, "GET", response)) + return; + if (!Authenticate(request, response, NexScopes.ExperiencesScript, out _, out _)) + return; + + try + { + Guid script = QueryGuid(request, "script_id"); + Guid experience = m_Store.ResolveScript(script); + WriteJson(response, new + { + script_id = script.ToString("D"), + experience_id = experience == Guid.Empty ? null : experience.ToString("D"), + correlation_id = Correlation(response) + }); + } + catch (Exception e) + { + WriteFailure(response, e); + } + return; + } + + if (path == "/api/v1/experiences/script/details") + { + if (!RequireMethod(method, "GET", response)) + return; + if (!Authenticate(request, response, NexScopes.ExperiencesScript, out _, out _)) + return; + + try + { + Guid experience = + QueryOptionalGuid(request, "experience_id"); + + if (experience == Guid.Empty) + { + Guid script = + QueryGuid(request, "script_id"); + experience = + m_Store.ResolveScript(script); + } + + NexExperience details = + experience == Guid.Empty + ? null + : m_Store.Get(experience); + + if (details == null) + throw new KeyNotFoundException("Experience was not found."); + + WriteJson(response, new + { + experience = Payload(details), + correlation_id = Correlation(response) + }); + } + catch (Exception e) + { + WriteFailure(response, e); + } + return; + } + + if (path == "/api/v1/experiences/script/permission") + { + if (!RequireMethod(method, "GET", response)) + return; + if (!Authenticate(request, response, NexScopes.ExperiencesScript, out _, out _)) + return; + + try + { + Guid script = QueryGuid(request, "script_id"); + Guid resident = QueryGuid(request, "resident_id"); + Guid experience = m_Store.ResolveScript(script); + NexExperiencePermissionStatus status = + experience == Guid.Empty + ? NexExperiencePermissionStatus.None + : m_Store.GetResidentPermission(experience, resident); + + WriteJson(response, new + { + script_id = script.ToString("D"), + experience_id = experience == Guid.Empty ? null : experience.ToString("D"), + resident_id = resident.ToString("D"), + status = status.ToString().ToLowerInvariant(), + allowed = status == NexExperiencePermissionStatus.Allowed, + correlation_id = Correlation(response) + }); + } + catch (Exception e) + { + WriteFailure(response, e); + } + return; + } + + if (path == "/api/v1/experiences/script/location") + { + if (!RequireMethod(method, "GET", response)) + return; + if (!Authenticate(request, response, NexScopes.ExperiencesScript, out _, out _)) + return; + + try + { + Guid script = QueryGuid(request, "script_id"); + Guid experience = m_Store.ResolveScript(script); + Guid estate = QueryOptionalGuid(request, "estate_id"); + Guid parcel = QueryOptionalGuid(request, "parcel_id"); + + WriteJson(response, new + { + experience_id = experience == Guid.Empty ? null : experience.ToString("D"), + allowed = experience != Guid.Empty && m_Store.IsLocationAllowed(experience, estate, parcel), + correlation_id = Correlation(response) + }); + } + catch (Exception e) + { + WriteFailure(response, e); + } + return; + } + + if (path == "/api/v1/experiences/script/kv") + { + if (!RequireMethod(method, "POST", response)) + return; + if (!Authenticate(request, response, NexScopes.ExperiencesScript, out _, out _)) + return; + if (!TryBody(request, response, out JsonElement body)) + return; + + try + { + Guid script = BodyGuid(body, "script_id"); + Guid experience = m_Store.ResolveScript(script); + if (experience == Guid.Empty) + throw new InvalidOperationException("Script is not bound to an experience."); + + string operation = BodyString(body, "operation").ToLowerInvariant(); + string key = BodyString(body, "key"); + string value = BodyRawString(body, "value"); + bool success = true; + string code = string.Empty; + object result = string.Empty; + string message = string.Empty; + + switch (operation) + { + case "create": + success = m_Store.CreateKeyValue(experience, script, key, value); + if (!success) + { + code = "storage_exception"; + message = "Key already exists."; + } + else + { + result = value; + } + break; + + case "read": + success = m_Store.TryReadKeyValue(experience, script, key, out string readValue); + if (success) + result = readValue; + else + { + code = "key_not_found"; + message = "Key does not exist."; + } + break; + + case "update": + success = m_Store.UpdateKeyValue( + experience, + script, + key, + value, + BodyBool(body, "check_original", false), + BodyRawString(body, "original_value"), + out bool retryMismatch); + if (success) + result = value; + else if (retryMismatch) + { + code = "retry_update"; + message = "Checked update failed because the stored value changed."; + } + break; + + case "delete": + success = m_Store.DeleteKeyValue(experience, script, key); + if (!success) + { + code = "key_not_found"; + message = "Key does not exist."; + } + break; + + case "stats": + result = new + { + used_bytes = m_Store.GetDataSize(experience, script), + quota_bytes = NexExperienceStore.MaxStoreBytes, + key_count = m_Store.GetKeyCount(experience, script) + }; + break; + + case "keys": + int start = BodyNonNegativeInt(body, "start", 0); + int count = BodyPositiveInt(body, "count", 100); + IReadOnlyList keys = + m_Store.ListKeys( + experience, + script, + start, + count); + if (keys.Count == 0 && + start >= m_Store.GetKeyCount(experience, script) && + m_Store.GetKeyCount(experience, script) > 0) + { + success = false; + code = "key_not_found"; + message = "Key index is outside the stored key range."; + } + result = new { keys }; + break; + + default: + throw new ArgumentException("operation must be create, read, update, delete, stats or keys."); + } + + WriteJson(response, new + { + success, + code, + message, + result, + experience_id = experience.ToString("D"), + correlation_id = Correlation(response) + }); + } + catch (Exception e) + { + WriteFailure(response, e); + } + return; + } + + const string prefix = "/api/v1/experiences/"; + if (!path.StartsWith(prefix, StringComparison.OrdinalIgnoreCase)) + { + NotFound(response); + return; + } + + string relative = path.Substring(prefix.Length); + string[] parts = relative.Split('/', StringSplitOptions.RemoveEmptyEntries); + + if (parts.Length == 0 || + !Guid.TryParse(parts[0], out Guid experienceId) || + experienceId == Guid.Empty) + { + WriteError(response, HttpStatusCode.BadRequest, "invalid_experience_id", "A valid experience UUID is required."); + return; + } + + if (parts.Length == 1) + { + if (method.Equals("GET", StringComparison.OrdinalIgnoreCase)) + { + if (!Authenticate(request, response, NexScopes.ExperiencesRead, out _, out _)) + return; + + try + { + NexExperience experience = m_Store.Get(experienceId) ?? + throw new KeyNotFoundException("Experience was not found."); + WriteJson(response, new + { + experience = Payload(experience), + correlation_id = Correlation(response) + }); + } + catch (Exception e) + { + WriteFailure(response, e); + } + return; + } + + if (method.Equals("PUT", StringComparison.OrdinalIgnoreCase)) + { + if (!Authenticate(request, response, NexScopes.ExperiencesManage, out NexPrincipal principal, out UserAccount account)) + return; + if (!TryBody(request, response, out JsonElement body)) + return; + + try + { + Guid actor = ActorId(principal, account, body); + NexExperience current = m_Store.Get(experienceId) ?? + throw new KeyNotFoundException("Experience was not found."); + + bool enabled = + body.TryGetProperty( + "enabled", + out JsonElement enabledElement) + ? enabledElement.ValueKind == JsonValueKind.True + ? true + : enabledElement.ValueKind == JsonValueKind.False + ? false + : throw new ArgumentException("enabled must be boolean.") + : current.Enabled; + + NexExperience updated = + m_Store.UpdateProfile( + experienceId, + actor, + BodyString(body, "name").Length == 0 ? current.Name : BodyString(body, "name"), + body.TryGetProperty("description", out _) ? BodyString(body, "description") : current.Description, + body.TryGetProperty("group_id", out _) ? BodyOptionalGuid(body, "group_id") : current.GroupId, + body.TryGetProperty("maturity", out _) ? ParseMaturity(BodyString(body, "maturity")) : current.Maturity, + enabled, + principal.Subject); + + Audit(principal, "experience.updated", experienceId, response); + + WriteJson(response, new + { + experience = Payload(updated), + correlation_id = Correlation(response) + }); + } + catch (Exception e) + { + WriteFailure(response, e); + } + return; + } + + if (method.Equals("DELETE", StringComparison.OrdinalIgnoreCase)) + { + if (!Authenticate(request, response, NexScopes.ExperiencesManage, out NexPrincipal principal, out UserAccount account)) + return; + + try + { + Guid actor = + account != null + ? account.PrincipalID.Guid + : QueryGuid(request, "actor_id"); + + m_Store.Delete(experienceId, actor, principal.Subject); + Audit(principal, "experience.deleted", experienceId, response); + WriteJson(response, new { deleted = true, correlation_id = Correlation(response) }); + } + catch (Exception e) + { + WriteFailure(response, e); + } + return; + } + + MethodNotAllowed(response, "GET, PUT or DELETE"); + return; + } + + if (parts.Length == 2 && parts[1].Equals("logs", StringComparison.OrdinalIgnoreCase)) + { + if (!RequireMethod(method, "GET", response)) + return; + if (!Authenticate(request, response, NexScopes.ExperiencesRead, out _, out _)) + return; + + try + { + WriteJson(response, new + { + logs = m_Store.GetLogs( + experienceId, + QueryInt(request, "offset", 0, 0, 1000000), + QueryInt(request, "limit", 100, 1, 500)), + correlation_id = Correlation(response) + }); + } + catch (Exception e) + { + WriteFailure(response, e); + } + return; + } + + if (parts.Length == 4 && + parts[1].Equals("roles", StringComparison.OrdinalIgnoreCase)) + { + if (!RequireMethod(method, "PUT", response)) + return; + if (!Authenticate(request, response, NexScopes.ExperiencesManage, out NexPrincipal principal, out UserAccount account)) + return; + if (!Guid.TryParse(parts[3], out Guid resident) || resident == Guid.Empty) + { + WriteError(response, HttpStatusCode.BadRequest, "invalid_resident_id", "A valid resident UUID is required."); + return; + } + if (!TryBody(request, response, out JsonElement body)) + return; + + try + { + NexExperience updated = m_Store.SetRole( + experienceId, + ActorId(principal, account, body), + resident, + parts[2], + BodyBool(body, "enabled", true), + principal.Subject); + + Audit(principal, "experience.role.updated", experienceId, response); + WriteJson(response, new { experience = Payload(updated), correlation_id = Correlation(response) }); + } + catch (Exception e) + { + WriteFailure(response, e); + } + return; + } + + if (parts.Length == 3 && + parts[1].Equals("residents", StringComparison.OrdinalIgnoreCase) && + Guid.TryParse(parts[2], out Guid permissionResident)) + { + if (!RequireMethod(method, "PUT", response)) + return; + if (!Authenticate(request, response, NexScopes.ExperiencesManage, out NexPrincipal principal, out UserAccount account)) + return; + if (!TryBody(request, response, out JsonElement body)) + return; + + try + { + string raw = BodyString(body, "status"); + if (!Enum.TryParse(raw, true, out NexExperiencePermissionStatus status) || + !Enum.IsDefined(typeof(NexExperiencePermissionStatus), status)) + { + throw new ArgumentException("status must be none, allowed or blocked."); + } + + NexExperience updated = m_Store.SetResidentPermission( + experienceId, + ActorId(principal, account, body), + permissionResident, + status, + principal.Subject); + + Audit(principal, "experience.permission.updated", experienceId, response); + WriteJson(response, new { experience = Payload(updated), correlation_id = Correlation(response) }); + } + catch (Exception e) + { + WriteFailure(response, e); + } + return; + } + + if (parts.Length == 4 && + parts[1].Equals("policies", StringComparison.OrdinalIgnoreCase) && + Guid.TryParse(parts[3], out Guid location)) + { + if (!RequireMethod(method, "PUT", response)) + return; + if (!Authenticate(request, response, NexScopes.ExperiencesManage, out NexPrincipal principal, out UserAccount account)) + return; + if (!TryBody(request, response, out JsonElement body)) + return; + + try + { + NexExperience updated = m_Store.SetLocationPolicy( + experienceId, + ActorId(principal, account, body), + parts[2], + location, + BodyBool(body, "allowed", true), + BodyBool(body, "enabled", true), + principal.Subject); + + Audit(principal, "experience.policy.updated", experienceId, response); + WriteJson(response, new { experience = Payload(updated), correlation_id = Correlation(response) }); + } + catch (Exception e) + { + WriteFailure(response, e); + } + return; + } + + if (parts.Length == 4 && + parts[1].Equals("scripts", StringComparison.OrdinalIgnoreCase) && + parts[3].Equals("bind", StringComparison.OrdinalIgnoreCase) && + Guid.TryParse(parts[2], out Guid scriptId)) + { + if (!RequireMethod(method, "POST", response)) + return; + if (!Authenticate(request, response, NexScopes.ExperiencesManage, out NexPrincipal principal, out UserAccount account)) + return; + if (!TryBody(request, response, out JsonElement body)) + return; + + try + { + m_Store.BindScript( + experienceId, + ActorId(principal, account, body), + scriptId, + principal.Subject); + + Audit(principal, "experience.script.bound", experienceId, response); + WriteJson(response, new + { + bound = true, + experience_id = experienceId.ToString("D"), + script_id = scriptId.ToString("D"), + correlation_id = Correlation(response) + }); + } + catch (Exception e) + { + WriteFailure(response, e); + } + return; + } + + NotFound(response); + } + + private bool Authenticate( + IOSHttpRequest request, + IOSHttpResponse response, + string scope, + out NexPrincipal principal, + out UserAccount account) + { + if (m_Authenticator.TryAuthenticate( + request, + scope, + out principal, + out account, + out int statusCode, + out string error)) + { + return true; + } + + response.AddHeader("WWW-Authenticate", "Bearer"); + WriteError(response, (HttpStatusCode)statusCode, error, "Authentication or " + scope + " authorization is required."); + return false; + } + + private static Guid ActorId( + NexPrincipal principal, + UserAccount account, + JsonElement body) + { + if (account != null) + return account.PrincipalID.Guid; + + Guid actor = BodyOptionalGuid(body, "actor_id"); + if (actor == Guid.Empty && principal.HasScope(NexScopes.AdminAll)) + throw new ArgumentException("actor_id is required for administrator/service management calls."); + return actor; + } + + private void Audit( + NexPrincipal principal, + string action, + Guid experienceId, + IOSHttpResponse response) + { + m_Audit.Record(new NexAuditEvent( + principal.Subject, + action, + "experience:" + experienceId.ToString("D"), + Correlation(response), + new Dictionary())); + } + + private static object Payload(NexExperience e) => + new + { + experience_id = e.ExperienceId.ToString("D"), + name = e.Name, + description = e.Description, + owner_id = e.OwnerId.ToString("D"), + group_id = e.GroupId == Guid.Empty ? null : e.GroupId.ToString("D"), + maturity = e.Maturity.ToString().ToLowerInvariant(), + enabled = e.Enabled, + admins = e.Admins.Select(x => x.ToString("D")).ToArray(), + contributors = e.Contributors.Select(x => x.ToString("D")).ToArray(), + allowed_residents = e.AllowedResidents.Select(x => x.ToString("D")).ToArray(), + blocked_residents = e.BlockedResidents.Select(x => x.ToString("D")).ToArray(), + allowed_estates = e.AllowedEstates.Select(x => x.ToString("D")).ToArray(), + blocked_estates = e.BlockedEstates.Select(x => x.ToString("D")).ToArray(), + allowed_parcels = e.AllowedParcels.Select(x => x.ToString("D")).ToArray(), + blocked_parcels = e.BlockedParcels.Select(x => x.ToString("D")).ToArray(), + key_value_count = e.KeyValues.Count, + created_at = e.CreatedAt, + updated_at = e.UpdatedAt + }; + + private static NexExperienceMaturity ParseMaturity(string value) + { + if (string.IsNullOrWhiteSpace(value)) + return NexExperienceMaturity.General; + + if (!Enum.TryParse(value, true, out NexExperienceMaturity maturity) || + !Enum.IsDefined(typeof(NexExperienceMaturity), maturity)) + { + throw new ArgumentException("maturity must be general, moderate or adult."); + } + + return maturity; + } + + private static bool TryBody(IOSHttpRequest request, IOSHttpResponse response, out JsonElement body) + { + try + { + using JsonDocument document = JsonDocument.Parse(request.InputStream); + body = document.RootElement.Clone(); + if (body.ValueKind == JsonValueKind.Object) + return true; + } + catch + { + } + + body = default; + WriteError(response, HttpStatusCode.BadRequest, "invalid_json", "A valid JSON object is required."); + return false; + } + + private static string BodyString(JsonElement body, string name) + { + if (!body.TryGetProperty(name, out JsonElement e) || e.ValueKind != JsonValueKind.String) + return string.Empty; + return (e.GetString() ?? string.Empty).Trim(); + } + + private static string BodyRawString(JsonElement body, string name) + { + if (!body.TryGetProperty(name, out JsonElement e) || + e.ValueKind != JsonValueKind.String) + { + return string.Empty; + } + + return e.GetString() ?? string.Empty; + } + + private static Guid BodyGuid(JsonElement body, string name) + { + Guid id = BodyOptionalGuid(body, name); + if (id == Guid.Empty) + throw new ArgumentException(name + " must be a non-zero UUID."); + return id; + } + + private static Guid BodyOptionalGuid(JsonElement body, string name) + { + if (!body.TryGetProperty(name, out JsonElement e) || e.ValueKind == JsonValueKind.Null) + return Guid.Empty; + if (e.ValueKind != JsonValueKind.String || !Guid.TryParse(e.GetString(), out Guid id)) + throw new ArgumentException(name + " must be a UUID."); + return id; + } + + private static bool BodyBool(JsonElement body, string name, bool defaultValue) + { + if (!body.TryGetProperty(name, out JsonElement e)) + return defaultValue; + if (e.ValueKind == JsonValueKind.True) + return true; + if (e.ValueKind == JsonValueKind.False) + return false; + throw new ArgumentException(name + " must be boolean."); + } + + private static int BodyNonNegativeInt( + JsonElement body, + string name, + int defaultValue) + { + if (!body.TryGetProperty(name, out JsonElement element)) + return defaultValue; + if (element.ValueKind != JsonValueKind.Number || + !element.TryGetInt32(out int value) || + value < 0) + { + throw new ArgumentException(name + " must be a non-negative integer."); + } + return value; + } + + private static int BodyPositiveInt( + JsonElement body, + string name, + int defaultValue) + { + if (!body.TryGetProperty(name, out JsonElement element)) + return defaultValue; + if (element.ValueKind != JsonValueKind.Number || + !element.TryGetInt32(out int value) || + value < 1) + { + throw new ArgumentException(name + " must be a positive integer."); + } + return value; + } + + private static int QueryInt(IOSHttpRequest request, string name, int defaultValue, int min, int max) + { + string raw = (request?.QueryString?[name] ?? string.Empty).Trim(); + if (raw.Length == 0) + return defaultValue; + if (!int.TryParse(raw, NumberStyles.Integer, CultureInfo.InvariantCulture, out int value) || + value < min || value > max) + { + throw new ArgumentOutOfRangeException(name); + } + return value; + } + + private static Guid QueryGuid(IOSHttpRequest request, string name) + { + Guid id = QueryOptionalGuid(request, name); + if (id == Guid.Empty) + throw new ArgumentException(name + " must be a non-zero UUID."); + return id; + } + + private static Guid QueryOptionalGuid(IOSHttpRequest request, string name) + { + string raw = (request?.QueryString?[name] ?? string.Empty).Trim(); + if (raw.Length == 0) + return Guid.Empty; + if (!Guid.TryParse(raw, out Guid id)) + throw new ArgumentException(name + " must be a UUID."); + return id; + } + + private static bool RequireMethod(string actual, string expected, IOSHttpResponse response) + { + if (actual.Equals(expected, StringComparison.OrdinalIgnoreCase)) + return true; + MethodNotAllowed(response, expected); + return false; + } + + private static string Correlation(IOSHttpResponse response) => + NexApiRequestContext.Ensure(response); + + private static void WriteFailure(IOSHttpResponse response, Exception e) + { + if (e is UnauthorizedAccessException) + { + WriteError(response, HttpStatusCode.Forbidden, "experience_forbidden", e.Message); + return; + } + if (e is KeyNotFoundException) + { + WriteError(response, HttpStatusCode.NotFound, "experience_not_found", e.Message); + return; + } + if (e is ArgumentException || e is InvalidOperationException) + { + WriteError(response, HttpStatusCode.BadRequest, "experience_validation_failed", e.Message); + return; + } + + WriteError(response, HttpStatusCode.InternalServerError, "experience_internal_error", "The experience operation failed."); + } + + private static void MethodNotAllowed(IOSHttpResponse response, string expected) => + WriteError(response, HttpStatusCode.MethodNotAllowed, "method_not_allowed", expected + " is required."); + + private static void NotFound(IOSHttpResponse response) => + WriteError(response, HttpStatusCode.NotFound, "not_found", "The requested experience endpoint was not found."); + + private static void WriteError(IOSHttpResponse response, HttpStatusCode status, string error, string message) => + WriteJson(response, new + { + error, + message, + correlation_id = Correlation(response) + }, status); + + private static void WriteJson(IOSHttpResponse response, object payload, HttpStatusCode status = HttpStatusCode.OK) + { + response.KeepAlive = false; + response.StatusCode = (int)status; + response.ContentType = "application/json; charset=utf-8"; + response.RawBuffer = JsonSerializer.SerializeToUtf8Bytes(payload, s_Json); + } + } +} diff --git a/NexVerse/Server/Api/NexGroupsApi.cs b/NexVerse/Server/Api/NexGroupsApi.cs new file mode 100644 index 00000000..97cfc314 --- /dev/null +++ b/NexVerse/Server/Api/NexGroupsApi.cs @@ -0,0 +1,1207 @@ +// SPDX-License-Identifier: MPL-2.0 + +using System; +using System.Collections.Generic; +using System.Globalization; +using System.Linq; +using System.Net; +using System.Text.Json; +using NexVerse.Core.Audit; +using NexVerse.Core.Economy; +using NexVerse.Core.Security; +using OpenMetaverse; +using OpenSim.Framework; +using OpenSim.Framework.Servers.HttpServer; +using OpenSim.Groups; +using OpenSim.Services.Interfaces; + +namespace NexVerse.Server.Api +{ + internal sealed class NexGroupsApi + { + private static readonly JsonSerializerOptions s_Json = + new JsonSerializerOptions { WriteIndented = true }; + + private readonly NexApiAuthenticator m_Authenticator; + private readonly INexAuditSink m_Audit; + private readonly GroupsService m_Groups; + private readonly Func m_Economy; + + public NexGroupsApi( + NexApiAuthenticator authenticator, + INexAuditSink audit, + GroupsService groups, + Func economy) + { + m_Authenticator = authenticator ?? throw new ArgumentNullException(nameof(authenticator)); + m_Audit = audit ?? NullNexAuditSink.Instance; + m_Groups = groups ?? throw new ArgumentNullException(nameof(groups)); + m_Economy = economy ?? throw new ArgumentNullException(nameof(economy)); + } + + public void Handle( + IOSHttpRequest request, + IOSHttpResponse response) + { + string path = (request?.UriPath ?? string.Empty).TrimEnd('/'); + string method = request?.HttpMethod ?? string.Empty; + + if (path == "/api/v1/groups") + { + if (method.Equals("GET", StringComparison.OrdinalIgnoreCase)) + { + if (!Authenticate(request, response, NexScopes.GroupsRead, out NexPrincipal principal, out _)) + return; + + try + { + string query = request?.QueryString?["q"] ?? string.Empty; + string searchRequester = Requester(principal, request); + List groups = + m_Groups.FindGroups(searchRequester, query); + + WriteJson(response, new + { + groups = groups.Select(x => new + { + group_id = x.groupID.ToString(), + name = x.groupName, + members = x.members + }).ToArray(), + correlation_id = Correlation(response) + }); + } + catch (Exception e) + { + WriteFailure(response, e); + } + return; + } + + if (method.Equals("POST", StringComparison.OrdinalIgnoreCase)) + { + if (!Authenticate(request, response, NexScopes.GroupsManage, out NexPrincipal principal, out UserAccount account)) + return; + if (!TryBody(request, response, out JsonElement body)) + return; + + try + { + UUID founder = Actor(principal, account, body); + UUID createdGroupId = + m_Groups.CreateGroup( + founder.ToString(), + BodyString(body, "name"), + BodyString(body, "charter"), + BodyBool(body, "show_in_list", true), + BodyOptionalUuid(body, "insignia_id"), + BodyInt(body, "membership_fee", 0, 0, int.MaxValue), + BodyBool(body, "open_enrollment", false), + BodyBool(body, "allow_publish", false), + BodyBool(body, "mature_publish", false), + founder, + out string reason); + + if (createdGroupId.IsZero()) + throw new InvalidOperationException( + string.IsNullOrWhiteSpace(reason) + ? "Group creation failed." + : reason); + + ExtendedGroupRecord group = + m_Groups.GetGroupRecord(founder.ToString(), createdGroupId); + + EnsureGroupWallet(group); + + Audit(principal, "group.created", createdGroupId, response); + + WriteJson(response, new + { + group = GroupPayload(group), + correlation_id = Correlation(response) + }, HttpStatusCode.Created); + } + catch (Exception e) + { + WriteFailure(response, e); + } + return; + } + + MethodNotAllowed(response, "GET or POST"); + return; + } + + const string prefix = "/api/v1/groups/"; + if (!path.StartsWith(prefix, StringComparison.OrdinalIgnoreCase)) + { + NotFound(response); + return; + } + + string relative = path.Substring(prefix.Length); + string[] parts = relative.Split('/', StringSplitOptions.RemoveEmptyEntries); + + if (parts.Length == 0 || + !UUID.TryParse(parts[0], out UUID groupId) || + groupId.IsZero()) + { + WriteError(response, HttpStatusCode.BadRequest, "invalid_group_id", "A valid group UUID is required."); + return; + } + + if (parts.Length == 1) + { + if (method.Equals("GET", StringComparison.OrdinalIgnoreCase)) + { + if (!Authenticate(request, response, NexScopes.GroupsRead, out NexPrincipal principal, out _)) + return; + + try + { + ExtendedGroupRecord group = + RequireGroup(principal, request, groupId); + + WriteJson(response, new + { + group = GroupPayload(group), + compatibility = CompatibilityPayload(groupId), + correlation_id = Correlation(response) + }); + } + catch (Exception e) + { + WriteFailure(response, e); + } + return; + } + + if (method.Equals("PUT", StringComparison.OrdinalIgnoreCase)) + { + if (!Authenticate(request, response, NexScopes.GroupsManage, out NexPrincipal principal, out UserAccount account)) + return; + if (!TryBody(request, response, out JsonElement body)) + return; + + try + { + UUID actor = Actor(principal, account, body); + ExtendedGroupRecord current = + m_Groups.GetGroupRecord(actor.ToString(), groupId) ?? + throw new KeyNotFoundException("Group was not found."); + + m_Groups.UpdateGroup( + actor.ToString(), + groupId, + body.TryGetProperty("charter", out _) ? BodyString(body, "charter") : current.Charter, + body.TryGetProperty("show_in_list", out _) ? BodyBool(body, "show_in_list", current.ShowInList) : current.ShowInList, + body.TryGetProperty("insignia_id", out _) ? BodyOptionalUuid(body, "insignia_id") : current.GroupPicture, + body.TryGetProperty("membership_fee", out _) ? BodyInt(body, "membership_fee", current.MembershipFee, 0, int.MaxValue) : current.MembershipFee, + body.TryGetProperty("open_enrollment", out _) ? BodyBool(body, "open_enrollment", current.OpenEnrollment) : current.OpenEnrollment, + body.TryGetProperty("allow_publish", out _) ? BodyBool(body, "allow_publish", current.AllowPublish) : current.AllowPublish, + body.TryGetProperty("mature_publish", out _) ? BodyBool(body, "mature_publish", current.MaturePublish) : current.MaturePublish); + + ExtendedGroupRecord updated = + m_Groups.GetGroupRecord(actor.ToString(), groupId); + + Audit(principal, "group.updated", groupId, response); + + WriteJson(response, new + { + group = GroupPayload(updated), + correlation_id = Correlation(response) + }); + } + catch (Exception e) + { + WriteFailure(response, e); + } + return; + } + + if (method.Equals("DELETE", StringComparison.OrdinalIgnoreCase)) + { + if (!Authenticate(request, response, NexScopes.GroupsManage, out NexPrincipal principal, out UserAccount account)) + return; + + try + { + UUID actor = + account != null + ? account.PrincipalID + : QueryUuid(request, "actor_id"); + + if (!m_Groups.DeleteGroup( + actor.ToString(), + groupId, + out string reason)) + { + throw new UnauthorizedAccessException( + string.IsNullOrWhiteSpace(reason) + ? "Group deletion failed." + : reason); + } + + Audit(principal, "group.deleted", groupId, response); + + WriteJson(response, new + { + deleted = true, + group_id = groupId.ToString(), + correlation_id = Correlation(response) + }); + } + catch (Exception e) + { + WriteFailure(response, e); + } + return; + } + + MethodNotAllowed(response, "GET, PUT or DELETE"); + return; + } + + string requester; + NexPrincipal authPrincipal; + UserAccount authAccount; + + if (parts[1].Equals("members", StringComparison.OrdinalIgnoreCase)) + { + if (parts.Length == 2 && method.Equals("GET", StringComparison.OrdinalIgnoreCase)) + { + if (!Authenticate(request, response, NexScopes.GroupsRead, out authPrincipal, out authAccount)) + return; + + try + { + requester = ActorForRead(authPrincipal, authAccount, request); + List members = + m_Groups.GetGroupMembers(requester, groupId); + + WriteJson(response, new + { + members = members.Select(GroupsDataUtils.GroupMembersData).ToArray(), + correlation_id = Correlation(response) + }); + } + catch (Exception e) + { + WriteFailure(response, e); + } + return; + } + + if (parts.Length == 3 && + UUID.TryParse(parts[2], out UUID memberId)) + { + if (!Authenticate(request, response, NexScopes.GroupsManage, out authPrincipal, out authAccount)) + return; + + if (method.Equals("POST", StringComparison.OrdinalIgnoreCase)) + { + if (!TryBody(request, response, out JsonElement body)) + return; + + try + { + UUID actor = Actor(authPrincipal, authAccount, body); + UUID roleId = BodyOptionalUuid(body, "role_id"); + + if (!m_Groups.AddAgentToGroup( + actor.ToString(), + memberId.ToString(), + groupId, + roleId, + BodyString(body, "token"), + out string reason)) + { + throw new InvalidOperationException( + string.IsNullOrWhiteSpace(reason) + ? "Group membership could not be added." + : reason); + } + + Audit(authPrincipal, "group.member.added", groupId, response); + WriteJson(response, new { added = true, correlation_id = Correlation(response) }); + } + catch (Exception e) + { + WriteFailure(response, e); + } + return; + } + + if (method.Equals("DELETE", StringComparison.OrdinalIgnoreCase)) + { + try + { + UUID actor = + authAccount != null + ? authAccount.PrincipalID + : QueryUuid(request, "actor_id"); + + if (!m_Groups.RemoveAgentFromGroup( + actor.ToString(), + memberId.ToString(), + groupId)) + { + throw new UnauthorizedAccessException("Member removal was rejected."); + } + + Audit(authPrincipal, "group.member.removed", groupId, response); + WriteJson(response, new { removed = true, correlation_id = Correlation(response) }); + } + catch (Exception e) + { + WriteFailure(response, e); + } + return; + } + } + } + + if (parts[1].Equals("roles", StringComparison.OrdinalIgnoreCase)) + { + if (parts.Length == 2 && method.Equals("GET", StringComparison.OrdinalIgnoreCase)) + { + if (!Authenticate(request, response, NexScopes.GroupsRead, out authPrincipal, out authAccount)) + return; + + try + { + requester = ActorForRead(authPrincipal, authAccount, request); + + WriteJson(response, new + { + roles = m_Groups.GetGroupRoles(requester, groupId) + .Select(GroupsDataUtils.GroupRolesData) + .ToArray(), + role_members = m_Groups.GetGroupRoleMembers(requester, groupId) + .Select(GroupsDataUtils.GroupRoleMembersData) + .ToArray(), + correlation_id = Correlation(response) + }); + } + catch (Exception e) + { + WriteFailure(response, e); + } + return; + } + + if (parts.Length == 2 && method.Equals("POST", StringComparison.OrdinalIgnoreCase)) + { + if (!Authenticate(request, response, NexScopes.GroupsManage, out authPrincipal, out authAccount)) + return; + if (!TryBody(request, response, out JsonElement body)) + return; + + try + { + UUID actor = Actor(authPrincipal, authAccount, body); + UUID newRoleId = BodyOptionalUuid(body, "role_id"); + if (newRoleId.IsZero()) + newRoleId = UUID.Random(); + + if (!m_Groups.AddGroupRole( + actor.ToString(), + groupId, + newRoleId, + BodyString(body, "name"), + BodyString(body, "description"), + BodyString(body, "title"), + BodyUlong(body, "powers", 0), + out string reason)) + { + throw new UnauthorizedAccessException( + string.IsNullOrWhiteSpace(reason) + ? "Role creation was rejected." + : reason); + } + + Audit(authPrincipal, "group.role.created", groupId, response); + WriteJson(response, new + { + role_id = newRoleId.ToString(), + correlation_id = Correlation(response) + }, HttpStatusCode.Created); + } + catch (Exception e) + { + WriteFailure(response, e); + } + return; + } + + if (parts.Length >= 3 && + UUID.TryParse(parts[2], out UUID roleId)) + { + if (parts.Length == 3 && + (method.Equals("PUT", StringComparison.OrdinalIgnoreCase) || + method.Equals("DELETE", StringComparison.OrdinalIgnoreCase))) + { + if (!Authenticate(request, response, NexScopes.GroupsManage, out authPrincipal, out authAccount)) + return; + + try + { + if (method.Equals("PUT", StringComparison.OrdinalIgnoreCase)) + { + if (!TryBody(request, response, out JsonElement body)) + return; + + UUID actor = Actor(authPrincipal, authAccount, body); + bool updated = + m_Groups.UpdateGroupRole( + actor.ToString(), + groupId, + roleId, + BodyString(body, "name"), + BodyString(body, "description"), + BodyString(body, "title"), + BodyUlong(body, "powers", 0)); + + if (!updated) + throw new UnauthorizedAccessException("Role update was rejected."); + + Audit(authPrincipal, "group.role.updated", groupId, response); + WriteJson(response, new { updated = true, correlation_id = Correlation(response) }); + return; + } + + UUID deleteActor = + authAccount != null + ? authAccount.PrincipalID + : QueryUuid(request, "actor_id"); + + m_Groups.RemoveGroupRole( + deleteActor.ToString(), + groupId, + roleId); + + Audit(authPrincipal, "group.role.deleted", groupId, response); + WriteJson(response, new { deleted = true, correlation_id = Correlation(response) }); + } + catch (Exception e) + { + WriteFailure(response, e); + } + return; + } + + if (parts.Length == 5 && + parts[3].Equals("members", StringComparison.OrdinalIgnoreCase) && + UUID.TryParse(parts[4], out UUID roleMember) && + (method.Equals("POST", StringComparison.OrdinalIgnoreCase) || + method.Equals("DELETE", StringComparison.OrdinalIgnoreCase))) + { + if (!Authenticate(request, response, NexScopes.GroupsManage, out authPrincipal, out authAccount)) + return; + + try + { + UUID actor = + authAccount != null + ? authAccount.PrincipalID + : QueryUuid(request, "actor_id"); + + bool ok = + method.Equals("POST", StringComparison.OrdinalIgnoreCase) + ? m_Groups.AddAgentToGroupRole( + actor.ToString(), + roleMember.ToString(), + groupId, + roleId) + : m_Groups.RemoveAgentFromGroupRole( + actor.ToString(), + roleMember.ToString(), + groupId, + roleId); + + if (!ok) + throw new UnauthorizedAccessException("Role membership change was rejected."); + + Audit(authPrincipal, "group.role_membership.changed", groupId, response); + WriteJson(response, new { success = true, correlation_id = Correlation(response) }); + } + catch (Exception e) + { + WriteFailure(response, e); + } + return; + } + } + } + + if (parts[1].Equals("invites", StringComparison.OrdinalIgnoreCase)) + { + if (!Authenticate(request, response, + method.Equals("GET", StringComparison.OrdinalIgnoreCase) + ? NexScopes.GroupsRead + : NexScopes.GroupsManage, + out authPrincipal, + out authAccount)) + { + return; + } + + if (parts.Length == 2 && + method.Equals("POST", StringComparison.OrdinalIgnoreCase)) + { + if (!TryBody(request, response, out JsonElement body)) + return; + + try + { + UUID actor = Actor(authPrincipal, authAccount, body); + UUID createdInviteId = UUID.Random(); + bool ok = + m_Groups.AddAgentToGroupInvite( + actor.ToString(), + createdInviteId, + groupId, + BodyOptionalUuid(body, "role_id"), + BodyUuid(body, "agent_id").ToString()); + + if (!ok) + throw new UnauthorizedAccessException("Group invitation was rejected."); + + Audit(authPrincipal, "group.invite.created", groupId, response); + WriteJson(response, new + { + invite_id = createdInviteId.ToString(), + correlation_id = Correlation(response) + }, HttpStatusCode.Created); + } + catch (Exception e) + { + WriteFailure(response, e); + } + return; + } + + if (parts.Length == 3 && + UUID.TryParse(parts[2], out UUID inviteId)) + { + if (method.Equals("GET", StringComparison.OrdinalIgnoreCase)) + { + try + { + GroupInviteInfo invite = + m_Groups.GetAgentToGroupInvite( + Requester(authPrincipal, request), + inviteId) ?? + throw new KeyNotFoundException("Group invitation was not found."); + + WriteJson(response, new + { + invite = GroupsDataUtils.GroupInviteInfo(invite), + correlation_id = Correlation(response) + }); + } + catch (Exception e) + { + WriteFailure(response, e); + } + return; + } + + if (method.Equals("DELETE", StringComparison.OrdinalIgnoreCase)) + { + m_Groups.RemoveAgentToGroupInvite( + Requester(authPrincipal, request), + inviteId); + Audit(authPrincipal, "group.invite.deleted", groupId, response); + WriteJson(response, new { deleted = true, correlation_id = Correlation(response) }); + return; + } + } + } + + if (parts[1].Equals("notices", StringComparison.OrdinalIgnoreCase)) + { + if (parts.Length == 2 && method.Equals("GET", StringComparison.OrdinalIgnoreCase)) + { + if (!Authenticate(request, response, NexScopes.GroupsRead, out authPrincipal, out authAccount)) + return; + + try + { + requester = ActorForRead(authPrincipal, authAccount, request); + WriteJson(response, new + { + notices = m_Groups.GetGroupNotices(requester, groupId) + .Select(GroupsDataUtils.GroupNoticeData) + .ToArray(), + correlation_id = Correlation(response) + }); + } + catch (Exception e) + { + WriteFailure(response, e); + } + return; + } + + if (parts.Length == 2 && method.Equals("POST", StringComparison.OrdinalIgnoreCase)) + { + if (!Authenticate(request, response, NexScopes.GroupsManage, out authPrincipal, out authAccount)) + return; + if (!TryBody(request, response, out JsonElement body)) + return; + + try + { + UUID actor = Actor(authPrincipal, authAccount, body); + UUID noticeId = UUID.Random(); + + bool ok = + m_Groups.AddGroupNotice( + actor.ToString(), + groupId, + noticeId, + BodyString(body, "from_name"), + BodyString(body, "subject"), + BodyString(body, "message"), + BodyBool(body, "has_attachment", false), + (byte)BodyInt(body, "attachment_type", 0, 0, 255), + BodyString(body, "attachment_name"), + BodyOptionalUuid(body, "attachment_item_id"), + BodyString(body, "attachment_owner_id")); + + if (!ok) + throw new UnauthorizedAccessException("Group notice was rejected."); + + Audit(authPrincipal, "group.notice.created", groupId, response); + WriteJson(response, new + { + notice_id = noticeId.ToString(), + correlation_id = Correlation(response) + }, HttpStatusCode.Created); + } + catch (Exception e) + { + WriteFailure(response, e); + } + return; + } + } + + if (parts[1].Equals("bans", StringComparison.OrdinalIgnoreCase)) + { + if (parts.Length == 2 && + method.Equals("GET", StringComparison.OrdinalIgnoreCase)) + { + if (!Authenticate(request, response, NexScopes.GroupsRead, out authPrincipal, out authAccount)) + return; + + try + { + requester = ActorForRead(authPrincipal, authAccount, request); + WriteJson(response, new + { + bans = m_Groups.GetGroupBans(requester, groupId), + correlation_id = Correlation(response) + }); + } + catch (Exception e) + { + WriteFailure(response, e); + } + return; + } + + if (parts.Length == 3 && + UUID.TryParse(parts[2], out UUID bannedAgent)) + { + if (!Authenticate(request, response, NexScopes.GroupsManage, out authPrincipal, out authAccount)) + return; + + if (method.Equals("POST", StringComparison.OrdinalIgnoreCase)) + { + if (!TryBody(request, response, out JsonElement body)) + return; + + try + { + UUID actor = Actor(authPrincipal, authAccount, body); + if (!m_Groups.AddGroupBan( + actor.ToString(), + groupId, + bannedAgent.ToString(), + BodyString(body, "reason"), + out string error)) + { + throw new UnauthorizedAccessException(error); + } + + Audit(authPrincipal, "group.ban.added", groupId, response); + WriteJson(response, new { banned = true, correlation_id = Correlation(response) }); + } + catch (Exception e) + { + WriteFailure(response, e); + } + return; + } + + if (method.Equals("DELETE", StringComparison.OrdinalIgnoreCase)) + { + try + { + UUID actor = + authAccount != null + ? authAccount.PrincipalID + : QueryUuid(request, "actor_id"); + + bool removed = + m_Groups.RemoveGroupBan( + actor.ToString(), + groupId, + bannedAgent.ToString(), + out string error); + + if (!removed && !string.IsNullOrWhiteSpace(error)) + throw new UnauthorizedAccessException(error); + + Audit(authPrincipal, "group.ban.removed", groupId, response); + WriteJson(response, new { removed, correlation_id = Correlation(response) }); + } + catch (Exception e) + { + WriteFailure(response, e); + } + return; + } + } + } + + if (parts[1].Equals("accounting", StringComparison.OrdinalIgnoreCase) && + parts.Length == 2) + { + if (!RequireMethod(method, "GET", response)) + return; + if (!Authenticate(request, response, NexScopes.GroupsRead, out authPrincipal, out authAccount)) + return; + + try + { + ExtendedGroupRecord group = + RequireGroup(authPrincipal, request, groupId); + NexEconomyService economy = + m_Economy() ?? + throw new InvalidOperationException("NV$ economy is unavailable."); + + economy.EnsureWalletAccount( + groupId.Guid, + NexLedgerAccountClass.Group, + group.GroupName); + + NexVirtualBankAccount bank = + economy.EnsureVirtualBankAccount( + groupId.Guid); + + WriteJson(response, new + { + group_id = groupId.ToString(), + currency = NexLedgerCurrency.Code, + balance = economy.GetBalance(groupId.Guid), + nvban = bank.Identifier, + correlation_id = Correlation(response) + }); + } + catch (Exception e) + { + WriteFailure(response, e); + } + return; + } + + if (parts[1].Equals("capabilities", StringComparison.OrdinalIgnoreCase) && + parts.Length == 2) + { + if (!RequireMethod(method, "GET", response)) + return; + if (!Authenticate(request, response, NexScopes.GroupsRead, out authPrincipal, out _)) + return; + + try + { + ExtendedGroupRecord group = + RequireGroup(authPrincipal, request, groupId); + + WriteJson(response, new + { + group_id = group.GroupID.ToString(), + chat = new + { + enabled = true, + session_id = group.GroupID.ToString(), + transport = "GroupsMessagingModule" + }, + voice = new + { + policy_available = true, + channel_id = "group:" + group.GroupID, + media_transport = "NexVoice (Roadmap 13)" + }, + land = new + { + group_land_semantics = true, + authority = "native parcel GroupID and role powers" + }, + objects = new + { + group_owned_objects = true, + authority = "native object GroupID/ownership semantics" + }, + hypergrid = new + { + connector_preserved = true, + transport = "GroupsServiceHGConnector" + }, + correlation_id = Correlation(response) + }); + } + catch (Exception e) + { + WriteFailure(response, e); + } + return; + } + + NotFound(response); + } + + private ExtendedGroupRecord RequireGroup( + NexPrincipal principal, + IOSHttpRequest request, + UUID groupId) + { + ExtendedGroupRecord group = + m_Groups.GetGroupRecord( + Requester(principal, request), + groupId); + + return group ?? + throw new KeyNotFoundException("Group was not found."); + } + + private void EnsureGroupWallet( + ExtendedGroupRecord group) + { + NexEconomyService economy = + m_Economy(); + + if (economy == null || group == null) + return; + + economy.EnsureWalletAccount( + group.GroupID.Guid, + NexLedgerAccountClass.Group, + group.GroupName); + economy.EnsureVirtualBankAccount( + group.GroupID.Guid); + } + + private bool Authenticate( + IOSHttpRequest request, + IOSHttpResponse response, + string scope, + out NexPrincipal principal, + out UserAccount account) + { + if (m_Authenticator.TryAuthenticate( + request, + scope, + out principal, + out account, + out int statusCode, + out string error)) + { + return true; + } + + response.AddHeader("WWW-Authenticate", "Bearer"); + WriteError(response, (HttpStatusCode)statusCode, error, "Authentication or " + scope + " authorization is required."); + return false; + } + + private static UUID Actor( + NexPrincipal principal, + UserAccount account, + JsonElement body) + { + if (account != null) + return account.PrincipalID; + + UUID actor = BodyOptionalUuid(body, "actor_id"); + if (actor.IsZero() && principal.HasScope(NexScopes.AdminAll)) + throw new ArgumentException("actor_id is required for administrator/service group mutations."); + return actor; + } + + private static string ActorForRead( + NexPrincipal principal, + UserAccount account, + IOSHttpRequest request) => + account != null + ? account.PrincipalID.ToString() + : Requester(principal, request); + + private static string Requester( + NexPrincipal principal, + IOSHttpRequest request) + { + string raw = + (request?.QueryString?["requester_id"] ?? string.Empty).Trim(); + + if (UUID.TryParse(raw, out UUID id) && !id.IsZero()) + return id.ToString(); + + return principal.HasScope(NexScopes.AdminAll) + ? UUID.Zero.ToString() + : principal.Subject; + } + + private void Audit( + NexPrincipal principal, + string action, + UUID groupId, + IOSHttpResponse response) + { + m_Audit.Record( + new NexAuditEvent( + principal.Subject, + action, + "group:" + groupId, + Correlation(response), + new Dictionary())); + } + + private static object GroupPayload( + ExtendedGroupRecord group) => + GroupsDataUtils.GroupRecord(group); + + private static object CompatibilityPayload(UUID groupId) => + new + { + group_id = groupId.ToString(), + viewer_stack = "Groups V2", + parity_mode = "NexGroups facade with legacy-compatible transport", + chat = true, + notices = true, + roles = true, + invitations = true, + bans = true, + accounting = true, + hypergrid_connector_preserved = true + }; + + private static bool TryBody( + IOSHttpRequest request, + IOSHttpResponse response, + out JsonElement body) + { + try + { + using JsonDocument document = + JsonDocument.Parse(request.InputStream); + body = document.RootElement.Clone(); + if (body.ValueKind == JsonValueKind.Object) + return true; + } + catch + { + } + + body = default; + WriteError(response, HttpStatusCode.BadRequest, "invalid_json", "A valid JSON object is required."); + return false; + } + + private static string BodyString(JsonElement body, string name) + { + if (!body.TryGetProperty(name, out JsonElement value) || + value.ValueKind != JsonValueKind.String) + { + return string.Empty; + } + + return (value.GetString() ?? string.Empty).Trim(); + } + + private static bool BodyBool( + JsonElement body, + string name, + bool defaultValue) + { + if (!body.TryGetProperty(name, out JsonElement value)) + return defaultValue; + if (value.ValueKind == JsonValueKind.True) + return true; + if (value.ValueKind == JsonValueKind.False) + return false; + throw new ArgumentException(name + " must be boolean."); + } + + private static int BodyInt( + JsonElement body, + string name, + int defaultValue, + int min, + int max) + { + if (!body.TryGetProperty(name, out JsonElement value)) + return defaultValue; + if (value.ValueKind != JsonValueKind.Number || + !value.TryGetInt32(out int parsed) || + parsed < min || + parsed > max) + { + throw new ArgumentException(name + " contains an invalid integer."); + } + + return parsed; + } + + private static ulong BodyUlong( + JsonElement body, + string name, + ulong defaultValue) + { + if (!body.TryGetProperty(name, out JsonElement value)) + return defaultValue; + + if (value.ValueKind == JsonValueKind.Number && + value.TryGetUInt64(out ulong numeric)) + { + return numeric; + } + + if (value.ValueKind == JsonValueKind.String && + ulong.TryParse( + value.GetString(), + NumberStyles.Integer, + CultureInfo.InvariantCulture, + out ulong text)) + { + return text; + } + + throw new ArgumentException(name + " must be an unsigned integer."); + } + + private static UUID BodyUuid(JsonElement body, string name) + { + UUID id = BodyOptionalUuid(body, name); + if (id.IsZero()) + throw new ArgumentException(name + " must be a non-zero UUID."); + return id; + } + + private static UUID BodyOptionalUuid(JsonElement body, string name) + { + if (!body.TryGetProperty(name, out JsonElement value) || + value.ValueKind == JsonValueKind.Null) + { + return UUID.Zero; + } + + if (value.ValueKind != JsonValueKind.String || + !UUID.TryParse(value.GetString(), out UUID id)) + { + throw new ArgumentException(name + " must be a UUID."); + } + + return id; + } + + private static UUID QueryUuid( + IOSHttpRequest request, + string name) + { + string raw = (request?.QueryString?[name] ?? string.Empty).Trim(); + if (!UUID.TryParse(raw, out UUID id) || id.IsZero()) + throw new ArgumentException(name + " must be a non-zero UUID."); + return id; + } + + private static bool RequireMethod( + string actual, + string expected, + IOSHttpResponse response) + { + if (actual.Equals(expected, StringComparison.OrdinalIgnoreCase)) + return true; + MethodNotAllowed(response, expected); + return false; + } + + private static string Correlation( + IOSHttpResponse response) => + NexApiRequestContext.Ensure(response); + + private static void WriteFailure( + IOSHttpResponse response, + Exception exception) + { + if (exception is UnauthorizedAccessException) + { + WriteError(response, HttpStatusCode.Forbidden, "group_forbidden", exception.Message); + return; + } + + if (exception is KeyNotFoundException) + { + WriteError(response, HttpStatusCode.NotFound, "group_not_found", exception.Message); + return; + } + + if (exception is ArgumentException || + exception is InvalidOperationException) + { + WriteError(response, HttpStatusCode.BadRequest, "group_validation_failed", exception.Message); + return; + } + + WriteError(response, HttpStatusCode.InternalServerError, "group_internal_error", "The NexGroups operation failed."); + } + + private static void MethodNotAllowed( + IOSHttpResponse response, + string expected) => + WriteError(response, HttpStatusCode.MethodNotAllowed, "method_not_allowed", expected + " is required."); + + private static void NotFound( + IOSHttpResponse response) => + WriteError(response, HttpStatusCode.NotFound, "not_found", "The requested NexGroups endpoint was not found."); + + private static void WriteError( + IOSHttpResponse response, + HttpStatusCode status, + string error, + string message) => + WriteJson(response, new + { + error, + message, + correlation_id = Correlation(response) + }, status); + + private static void WriteJson( + IOSHttpResponse response, + object payload, + HttpStatusCode status = HttpStatusCode.OK) + { + response.KeepAlive = false; + response.StatusCode = (int)status; + response.ContentType = "application/json; charset=utf-8"; + response.RawBuffer = + JsonSerializer.SerializeToUtf8Bytes( + payload, + s_Json); + } + } +} diff --git a/NexVerse/Server/Api/NexVerseWorldApiConnector.cs b/NexVerse/Server/Api/NexVerseWorldApiConnector.cs index b05e15fc..95508aa1 100644 --- a/NexVerse/Server/Api/NexVerseWorldApiConnector.cs +++ b/NexVerse/Server/Api/NexVerseWorldApiConnector.cs @@ -7,6 +7,7 @@ using Nini.Config; using NexVerse.Core.Audit; using NexVerse.Core.ControlPlane; using NexVerse.Core.Economy; +using NexVerse.Core.Experiences; using NexVerse.Core.Messaging; using NexVerse.Core.Jobs; using NexVerse.Core.Observability; @@ -16,6 +17,7 @@ using OpenSim.Framework.Servers.HttpServer; using OpenSim.Server.Base; using OpenSim.Server.Handlers.Base; using OpenSim.Services.Interfaces; +using OpenSim.Groups; using OpenSim.Services.Friends; using OpenSim.Services.EstateService; @@ -442,6 +444,60 @@ namespace NexVerse.Server.Api "OpenGenesisLINK Land Commerce API"), true); + IConfig nexGroupsConfig = + config.Configs["NexGroups"]; + + if (nexGroupsConfig?.GetBoolean("Enabled", false) == true) + { + GroupsService nexGroupsService = + new GroupsService( + config); + + NexGroupsApi nexGroupsApi = + new NexGroupsApi( + authenticator, + auditSink, + nexGroupsService, + () => + NexEconomyConnector.Current?.Enabled == true + ? NexEconomyConnector.Current.Economy + : null); + + server.AddSimpleStreamHandler( + new SimpleStreamHandler( + "/api/v1/groups", + apiGate.Wrap(nexGroupsApi.Handle), + "OpenGenesisLINK NexGroups API"), + true); + } + + IConfig experiencesConfig = + config.Configs["NexExperiences"]; + + string experienceStorePath = + experiencesConfig?.GetString( + "StorePath", + "data/nexverse-experiences.json") ?? + "data/nexverse-experiences.json"; + + NexExperienceStore experienceStore = + new NexExperienceStore( + experienceStorePath); + + NexExperiencesApi experiencesApi = + new NexExperiencesApi( + authenticator, + userAccounts, + auditSink, + experienceStore); + + server.AddSimpleStreamHandler( + new SimpleStreamHandler( + "/api/v1/experiences", + apiGate.Wrap(experiencesApi.Handle), + "OpenGenesisLINK NexExperiences API"), + true); + NexInventoryApi inventoryApi = new NexInventoryApi( inventory, diff --git a/NexVerse/Server/Api/NexVerseWorldApiHandlers.cs b/NexVerse/Server/Api/NexVerseWorldApiHandlers.cs index 9fe1d76d..c483ced8 100644 --- a/NexVerse/Server/Api/NexVerseWorldApiHandlers.cs +++ b/NexVerse/Server/Api/NexVerseWorldApiHandlers.cs @@ -190,6 +190,71 @@ namespace NexVerse.Server.Api ("post", "NV$-Konto sperren, freigeben oder schließen", "admin:*", "200")), ["/api/v1/economy/accounts/ensure"] = AuthenticatedOperations( ("post", "Vertrauenswürdiges Gruppen-, Business-, Estate- oder Objekt-Wallet provisionieren", "economy:transfer (service/admin)", "200")), + ["/api/v1/groups"] = AuthenticatedOperations( + ("get", "NexGroups durchsuchen", "groups:read", "200"), + ("post", "NexGroup erstellen", "groups:manage", "201")), + ["/api/v1/groups/{groupId}"] = AuthenticatedOperations( + ("get", "NexGroup-Profil lesen", "groups:read", "200"), + ("put", "NexGroup-Profil ändern", "groups:manage", "200"), + ("delete", "NexGroup als Founder löschen", "groups:manage", "200")), + ["/api/v1/groups/{groupId}/members"] = AuthenticatedOperations( + ("get", "Gruppenmitglieder lesen", "groups:read", "200")), + ["/api/v1/groups/{groupId}/members/{agentId}"] = AuthenticatedOperations( + ("post", "Resident zur Gruppe hinzufügen", "groups:manage", "200"), + ("delete", "Resident aus Gruppe entfernen", "groups:manage", "200")), + ["/api/v1/groups/{groupId}/roles"] = AuthenticatedOperations( + ("get", "Rollen, Powers und Rollenmitglieder lesen", "groups:read", "200"), + ("post", "Gruppenrolle erstellen", "groups:manage", "201")), + ["/api/v1/groups/{groupId}/roles/{roleId}"] = AuthenticatedOperations( + ("put", "Gruppenrolle ändern", "groups:manage", "200"), + ("delete", "Gruppenrolle löschen", "groups:manage", "200")), + ["/api/v1/groups/{groupId}/roles/{roleId}/members/{agentId}"] = AuthenticatedOperations( + ("post", "Resident einer Rolle zuordnen", "groups:manage", "200"), + ("delete", "Resident aus Rolle entfernen", "groups:manage", "200")), + ["/api/v1/groups/{groupId}/invites"] = AuthenticatedOperations( + ("post", "Gruppeneinladung erstellen", "groups:manage", "201")), + ["/api/v1/groups/{groupId}/invites/{inviteId}"] = AuthenticatedOperations( + ("get", "Gruppeneinladung lesen", "groups:read", "200"), + ("delete", "Gruppeneinladung löschen", "groups:manage", "200")), + ["/api/v1/groups/{groupId}/notices"] = AuthenticatedOperations( + ("get", "Group Notices lesen", "groups:read", "200"), + ("post", "Group Notice veröffentlichen", "groups:manage", "201")), + ["/api/v1/groups/{groupId}/bans"] = AuthenticatedOperations( + ("get", "Gruppensperren lesen", "groups:read", "200")), + ["/api/v1/groups/{groupId}/bans/{agentId}"] = AuthenticatedOperations( + ("post", "Resident aus Gruppe sperren", "groups:manage", "200"), + ("delete", "Gruppensperre entfernen", "groups:manage", "200")), + ["/api/v1/groups/{groupId}/accounting"] = AuthenticatedOperations( + ("get", "NV$-Gruppenkonto und NVBAN lesen", "groups:read", "200")), + ["/api/v1/groups/{groupId}/capabilities"] = AuthenticatedOperations( + ("get", "Chat-, Voice-, Land-, Objekt- und HG-Kompatibilität lesen", "groups:read", "200")), + ["/api/v1/experiences"] = AuthenticatedOperations( + ("get", "Experiences durchsuchen", "experiences:read", "200"), + ("post", "Experience erstellen", "experiences:manage", "201")), + ["/api/v1/experiences/{experienceId}"] = AuthenticatedOperations( + ("get", "Experience lesen", "experiences:read", "200"), + ("put", "Experience ändern", "experiences:manage", "200"), + ("delete", "Experience löschen", "experiences:manage", "200")), + ["/api/v1/experiences/{experienceId}/logs"] = AuthenticatedOperations( + ("get", "Experience-Logs lesen", "experiences:read", "200")), + ["/api/v1/experiences/{experienceId}/roles/{role}/{residentId}"] = AuthenticatedOperations( + ("put", "Experience-Admin/Contributor ändern", "experiences:manage", "200")), + ["/api/v1/experiences/{experienceId}/residents/{residentId}"] = AuthenticatedOperations( + ("put", "Experience Allow/Block ändern", "experiences:manage", "200")), + ["/api/v1/experiences/{experienceId}/policies/{kind}/{locationId}"] = AuthenticatedOperations( + ("put", "Estate-/Parcel-Policy ändern", "experiences:manage", "200")), + ["/api/v1/experiences/{experienceId}/scripts/{scriptId}/bind"] = AuthenticatedOperations( + ("post", "Script an Experience binden", "experiences:manage", "200")), + ["/api/v1/experiences/script/resolve"] = AuthenticatedOperations( + ("get", "Script-Experience-Bindung auflösen", "experiences:script", "200")), + ["/api/v1/experiences/script/details"] = AuthenticatedOperations( + ("get", "Experience-Details für LSL lesen", "experiences:script", "200")), + ["/api/v1/experiences/script/permission"] = AuthenticatedOperations( + ("get", "Persistente Experience-Permission prüfen", "experiences:script", "200")), + ["/api/v1/experiences/script/location"] = AuthenticatedOperations( + ("get", "Estate-/Parcel-Policy für Script prüfen", "experiences:script", "200")), + ["/api/v1/experiences/script/kv"] = AuthenticatedOperations( + ("post", "Experience K/V-Operation für LSL ausführen", "experiences:script", "200")), ["/api/v1/banking/transactions"] = AuthenticatedOperations( ("get", "NV$-Transaktionshistorie des eigenen oder autorisierten Kontos lesen", "economy:read", "200")), ["/api/v1/banking/statements"] = AuthenticatedOperations( @@ -422,6 +487,32 @@ namespace NexVerse.Server.Api "EconomyAccountStateResponse", "200"); ApplyJsonContract(paths, "/api/v1/economy/accounts/ensure", "post", "EconomyWalletEnsureRequest", "EconomyBalanceResponse", "200"); + ApplyJsonContract(paths, "/api/v1/groups", "get", null, "Chapter11ObjectResponse", "200"); + ApplyJsonContract(paths, "/api/v1/groups", "post", "NexGroupCreateRequest", "Chapter11ObjectResponse", "201"); + ApplyJsonContract(paths, "/api/v1/groups/{groupId}", "get", null, "Chapter11ObjectResponse", "200"); + ApplyJsonContract(paths, "/api/v1/groups/{groupId}", "put", "Chapter11MutationRequest", "Chapter11ObjectResponse", "200"); + ApplyJsonContract(paths, "/api/v1/groups/{groupId}", "delete", null, "Chapter11ObjectResponse", "200"); + ApplyJsonContract(paths, "/api/v1/groups/{groupId}/members", "get", null, "Chapter11ObjectResponse", "200"); + ApplyJsonContract(paths, "/api/v1/groups/{groupId}/members/{agentId}", "post", "Chapter11MutationRequest", "Chapter11ObjectResponse", "200"); + ApplyJsonContract(paths, "/api/v1/groups/{groupId}/roles", "get", null, "Chapter11ObjectResponse", "200"); + ApplyJsonContract(paths, "/api/v1/groups/{groupId}/roles", "post", "Chapter11MutationRequest", "Chapter11ObjectResponse", "201"); + ApplyJsonContract(paths, "/api/v1/groups/{groupId}/invites", "post", "Chapter11MutationRequest", "Chapter11ObjectResponse", "201"); + ApplyJsonContract(paths, "/api/v1/groups/{groupId}/notices", "get", null, "Chapter11ObjectResponse", "200"); + ApplyJsonContract(paths, "/api/v1/groups/{groupId}/notices", "post", "Chapter11MutationRequest", "Chapter11ObjectResponse", "201"); + ApplyJsonContract(paths, "/api/v1/groups/{groupId}/bans", "get", null, "Chapter11ObjectResponse", "200"); + ApplyJsonContract(paths, "/api/v1/groups/{groupId}/bans/{agentId}", "post", "Chapter11MutationRequest", "Chapter11ObjectResponse", "200"); + ApplyJsonContract(paths, "/api/v1/groups/{groupId}/accounting", "get", null, "Chapter11ObjectResponse", "200"); + ApplyJsonContract(paths, "/api/v1/groups/{groupId}/capabilities", "get", null, "Chapter11ObjectResponse", "200"); + ApplyJsonContract(paths, "/api/v1/experiences", "get", null, "Chapter11ObjectResponse", "200"); + ApplyJsonContract(paths, "/api/v1/experiences", "post", "NexExperienceCreateRequest", "Chapter11ObjectResponse", "201"); + ApplyJsonContract(paths, "/api/v1/experiences/{experienceId}", "get", null, "Chapter11ObjectResponse", "200"); + ApplyJsonContract(paths, "/api/v1/experiences/{experienceId}", "put", "Chapter11MutationRequest", "Chapter11ObjectResponse", "200"); + ApplyJsonContract(paths, "/api/v1/experiences/{experienceId}/logs", "get", null, "Chapter11ObjectResponse", "200"); + ApplyJsonContract(paths, "/api/v1/experiences/script/resolve", "get", null, "Chapter11ObjectResponse", "200"); + ApplyJsonContract(paths, "/api/v1/experiences/script/details", "get", null, "Chapter11ObjectResponse", "200"); + ApplyJsonContract(paths, "/api/v1/experiences/script/permission", "get", null, "Chapter11ObjectResponse", "200"); + ApplyJsonContract(paths, "/api/v1/experiences/script/location", "get", null, "Chapter11ObjectResponse", "200"); + ApplyJsonContract(paths, "/api/v1/experiences/script/kv", "post", "Chapter11MutationRequest", "Chapter11ObjectResponse", "200"); ApplyJsonContract(paths, "/api/v1/banking/transactions", "get", null, "BankingTransactionsResponse", "200"); ApplyJsonContract(paths, "/api/v1/banking/statements", "get", null, "BankingStatementResponse", "200"); ApplyJsonContract(paths, "/api/v1/banking/reconciliation", "get", null, "BankingReconciliationResponse", "200"); @@ -2290,6 +2381,45 @@ namespace NexVerse.Server.Api ["correlation_id"] = new { type = "string" } } }, + ["Chapter11ObjectResponse"] = new + { + type = "object" + }, + ["Chapter11MutationRequest"] = new + { + type = "object", + additionalProperties = true + }, + ["NexGroupCreateRequest"] = new + { + type = "object", + required = new[] { "name" }, + properties = new Dictionary + { + ["name"] = new { type = "string", minLength = 1, maxLength = 255 }, + ["charter"] = new { type = "string" }, + ["show_in_list"] = new { type = "boolean" }, + ["insignia_id"] = new { type = "string", format = "uuid" }, + ["membership_fee"] = new { type = "integer", minimum = 0 }, + ["open_enrollment"] = new { type = "boolean" }, + ["allow_publish"] = new { type = "boolean" }, + ["mature_publish"] = new { type = "boolean" } + } + }, + ["NexExperienceCreateRequest"] = new + { + type = "object", + required = new[] { "name" }, + properties = new Dictionary + { + ["experience_id"] = new { type = "string", format = "uuid" }, + ["owner_id"] = new { type = "string", format = "uuid" }, + ["group_id"] = new { type = "string", format = "uuid" }, + ["name"] = new { type = "string", minLength = 3, maxLength = 64 }, + ["description"] = new { type = "string" }, + ["maturity"] = new { type = "string", @enum = new[] { "general", "moderate", "adult" } } + } + }, ["EconomyWalletEnsureRequest"] = new { type = "object", diff --git a/OpenSim/Addons/Groups/Service/GroupsService.cs b/OpenSim/Addons/Groups/Service/GroupsService.cs index a54b1821..cc5e8699 100644 --- a/OpenSim/Addons/Groups/Service/GroupsService.cs +++ b/OpenSim/Addons/Groups/Service/GroupsService.cs @@ -104,10 +104,27 @@ namespace OpenSim.Groups #region Daily Cleanup private Timer m_CleanupTimer; + private readonly NexGroupModerationStore m_NexModeration; public GroupsService(IConfigSource config, string configName) : base(config, configName) { + IConfig groups = + config?.Configs[ + string.IsNullOrWhiteSpace(configName) + ? "Groups" + : configName] ?? + config?.Configs["Groups"]; + + string moderationPath = + groups?.GetString( + "NexModerationStorePath", + "data/nexgroups-moderation.json") ?? + "data/nexgroups-moderation.json"; + + m_NexModeration = + new NexGroupModerationStore( + moderationPath); } public GroupsService(IConfigSource config) @@ -427,6 +444,12 @@ namespace OpenSim.Groups { reason = string.Empty; + if (m_NexModeration.IsBanned(GroupID, AgentID)) + { + reason = "The resident is banned from this group."; + return false; + } + _AddAgentToGroup(RequestingAgentID, AgentID, GroupID, RoleID, token); return true; @@ -1054,6 +1077,180 @@ namespace OpenSim.Groups #endregion + public IReadOnlyList GetGroupBans( + string requestingAgentId, + UUID groupId) + { + if (!HasPower( + requestingAgentId, + groupId, + GroupPowers.GroupBanAccess) && + !IsOwner( + requestingAgentId, + groupId)) + { + return Array.Empty(); + } + + return m_NexModeration.List(groupId); + } + + public bool AddGroupBan( + string requestingAgentId, + UUID groupId, + string agentId, + string reason, + out string error) + { + error = string.Empty; + + if (!HasPower( + requestingAgentId, + groupId, + GroupPowers.GroupBanAccess) && + !IsOwner( + requestingAgentId, + groupId)) + { + error = "Group ban permission is required."; + return false; + } + + GroupData group = + m_Database.RetrieveGroup(groupId); + + if (group == null) + { + error = "Group was not found."; + return false; + } + + if (string.Equals( + group.Data["FounderID"], + agentId, + StringComparison.OrdinalIgnoreCase)) + { + error = "The group founder cannot be banned."; + return false; + } + + m_NexModeration.Add( + groupId, + agentId, + requestingAgentId, + reason); + + if (m_Database.RetrieveMember(groupId, agentId) != null) + _RemoveAgentFromGroup( + requestingAgentId, + agentId, + groupId); + + return true; + } + + public bool RemoveGroupBan( + string requestingAgentId, + UUID groupId, + string agentId, + out string error) + { + error = string.Empty; + + if (!HasPower( + requestingAgentId, + groupId, + GroupPowers.GroupBanAccess) && + !IsOwner( + requestingAgentId, + groupId)) + { + error = "Group ban permission is required."; + return false; + } + + return m_NexModeration.Remove( + groupId, + agentId); + } + + public bool DeleteGroup( + string requestingAgentId, + UUID groupId, + out string reason) + { + reason = string.Empty; + + GroupData group = + m_Database.RetrieveGroup(groupId); + + if (group == null) + { + reason = "Group was not found."; + return false; + } + + if (!group.Data.TryGetValue( + "FounderID", + out string founderId) || + !string.Equals( + founderId, + requestingAgentId, + StringComparison.OrdinalIgnoreCase)) + { + reason = "Only the group founder can delete the group."; + return false; + } + + MembershipData[] members = + m_Database.RetrieveMembers(groupId) ?? + Array.Empty(); + + foreach (MembershipData member in members) + { + m_Database.DeleteMemberAllRoles( + groupId, + member.PrincipalID); + m_Database.DeleteMember( + groupId, + member.PrincipalID); + + PrincipalData principal = + m_Database.RetrievePrincipal( + member.PrincipalID); + + if (principal != null && + principal.ActiveGroupID == groupId) + { + principal.ActiveGroupID = + UUID.Zero; + m_Database.StorePrincipal(principal); + } + } + + RoleData[] roles = + m_Database.RetrieveRoles(groupId) ?? + Array.Empty(); + + foreach (RoleData role in roles) + m_Database.DeleteRole( + groupId, + role.RoleID); + + NoticeData[] notices = + m_Database.RetrieveNotices(groupId) ?? + Array.Empty(); + + foreach (NoticeData notice in notices) + m_Database.DeleteNotice( + notice.NoticeID); + + m_Database.DeleteInvites(groupId); + m_NexModeration.RemoveGroup(groupId); + + return m_Database.DeleteGroup(groupId); + } + #region permissions private bool HasPower(string agentID, UUID groupID, GroupPowers power) { diff --git a/OpenSim/Addons/Groups/Service/NexGroupModerationStore.cs b/OpenSim/Addons/Groups/Service/NexGroupModerationStore.cs new file mode 100644 index 00000000..98d92080 --- /dev/null +++ b/OpenSim/Addons/Groups/Service/NexGroupModerationStore.cs @@ -0,0 +1,199 @@ +// SPDX-License-Identifier: MPL-2.0 + +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Text.Json; +using OpenMetaverse; + +namespace OpenSim.Groups +{ + public sealed class NexGroupBanRecord + { + public string GroupID { get; set; } = string.Empty; + public string AgentID { get; set; } = string.Empty; + public string ActorID { get; set; } = string.Empty; + public string Reason { get; set; } = string.Empty; + public DateTimeOffset CreatedAt { get; set; } = DateTimeOffset.UtcNow; + } + + public sealed class NexGroupModerationSnapshot + { + public int SchemaVersion { get; set; } = 1; + public List Bans { get; set; } = + new List(); + } + + public sealed class NexGroupModerationStore + { + public const int CurrentSchemaVersion = 1; + + private readonly object m_Sync = new object(); + private readonly string m_Path; + private readonly JsonSerializerOptions m_Json = + new JsonSerializerOptions { WriteIndented = true }; + private NexGroupModerationSnapshot m_State; + + public NexGroupModerationStore(string path) + { + if (string.IsNullOrWhiteSpace(path)) + throw new ArgumentException("NexGroups moderation store path is required.", nameof(path)); + + m_Path = Path.GetFullPath(path); + m_State = Load(); + } + + public bool IsBanned(UUID groupId, string agentId) + { + if (groupId.IsZero() || string.IsNullOrWhiteSpace(agentId)) + return false; + + lock (m_Sync) + { + return m_State.Bans.Any(x => + string.Equals( + x.GroupID, + groupId.ToString(), + StringComparison.OrdinalIgnoreCase) && + string.Equals( + x.AgentID, + agentId, + StringComparison.OrdinalIgnoreCase)); + } + } + + public IReadOnlyList List(UUID groupId) + { + lock (m_Sync) + { + return m_State.Bans + .Where(x => + string.Equals( + x.GroupID, + groupId.ToString(), + StringComparison.OrdinalIgnoreCase)) + .OrderByDescending(x => x.CreatedAt) + .Select(Clone) + .ToArray(); + } + } + + public NexGroupBanRecord Add( + UUID groupId, + string agentId, + string actorId, + string reason) + { + if (groupId.IsZero()) + throw new ArgumentException("Group ID is required.", nameof(groupId)); + if (!UUID.TryParse(agentId, out UUID parsedAgent) || parsedAgent.IsZero()) + throw new ArgumentException("Agent ID is required.", nameof(agentId)); + + lock (m_Sync) + { + NexGroupBanRecord existing = + m_State.Bans.FirstOrDefault(x => + string.Equals( + x.GroupID, + groupId.ToString(), + StringComparison.OrdinalIgnoreCase) && + string.Equals( + x.AgentID, + parsedAgent.ToString(), + StringComparison.OrdinalIgnoreCase)); + + if (existing != null) + return Clone(existing); + + NexGroupBanRecord record = + new NexGroupBanRecord + { + GroupID = groupId.ToString(), + AgentID = parsedAgent.ToString(), + ActorID = actorId ?? string.Empty, + Reason = (reason ?? string.Empty).Trim(), + CreatedAt = DateTimeOffset.UtcNow + }; + + m_State.Bans.Add(record); + Save(); + return Clone(record); + } + } + + public bool Remove(UUID groupId, string agentId) + { + lock (m_Sync) + { + int removed = + m_State.Bans.RemoveAll(x => + string.Equals( + x.GroupID, + groupId.ToString(), + StringComparison.OrdinalIgnoreCase) && + string.Equals( + x.AgentID, + agentId, + StringComparison.OrdinalIgnoreCase)); + + if (removed > 0) + Save(); + + return removed > 0; + } + } + + public void RemoveGroup(UUID groupId) + { + lock (m_Sync) + { + if (m_State.Bans.RemoveAll(x => + string.Equals( + x.GroupID, + groupId.ToString(), + StringComparison.OrdinalIgnoreCase)) > 0) + Save(); + } + } + + private NexGroupModerationSnapshot Load() + { + if (!File.Exists(m_Path)) + return new NexGroupModerationSnapshot(); + + NexGroupModerationSnapshot state = + JsonSerializer.Deserialize( + File.ReadAllText(m_Path), + m_Json) ?? + new NexGroupModerationSnapshot(); + + if (state.SchemaVersion != CurrentSchemaVersion) + throw new InvalidOperationException("Unsupported NexGroups moderation schema version."); + + state.Bans ??= new List(); + return state; + } + + private void Save() + { + string directory = Path.GetDirectoryName(m_Path); + if (!string.IsNullOrEmpty(directory)) + Directory.CreateDirectory(directory); + + string temp = m_Path + ".tmp"; + File.WriteAllText(temp, JsonSerializer.Serialize(m_State, m_Json)); + File.Move(temp, m_Path, true); + } + + private static NexGroupBanRecord Clone(NexGroupBanRecord record) => + new NexGroupBanRecord + { + GroupID = record.GroupID, + AgentID = record.AgentID, + ActorID = record.ActorID, + Reason = record.Reason, + CreatedAt = record.CreatedAt + }; + } +} diff --git a/OpenSim/Data/IGroupsData.cs b/OpenSim/Data/IGroupsData.cs index bd059e08..92f2974c 100644 --- a/OpenSim/Data/IGroupsData.cs +++ b/OpenSim/Data/IGroupsData.cs @@ -126,6 +126,7 @@ namespace OpenSim.Data InvitationData RetrieveInvitation(UUID inviteID); InvitationData RetrieveInvitation(UUID groupID, string principalID); bool DeleteInvite(UUID inviteID); + bool DeleteInvites(UUID groupID); void DeleteOldInvites(); // notices table diff --git a/OpenSim/Data/MySQL/MySQLGroupsData.cs b/OpenSim/Data/MySQL/MySQLGroupsData.cs index 77cb2f4d..3316afc2 100644 --- a/OpenSim/Data/MySQL/MySQLGroupsData.cs +++ b/OpenSim/Data/MySQL/MySQLGroupsData.cs @@ -294,6 +294,11 @@ namespace OpenSim.Data.MySQL return m_Invites.Delete("InviteID", inviteID.ToString()); } + public bool DeleteInvites(UUID groupID) + { + return m_Invites.Delete("GroupID", groupID.ToString()); + } + public void DeleteOldInvites() { m_Invites.DeleteOld(); diff --git a/OpenSim/Data/PGSQL/PGSQLGroupsData.cs b/OpenSim/Data/PGSQL/PGSQLGroupsData.cs index 04e2f69c..d97bcb1f 100644 --- a/OpenSim/Data/PGSQL/PGSQLGroupsData.cs +++ b/OpenSim/Data/PGSQL/PGSQLGroupsData.cs @@ -299,6 +299,11 @@ namespace OpenSim.Data.PGSQL return m_Invites.Delete("InviteID", inviteID.ToString()); } + public bool DeleteInvites(UUID groupID) + { + return m_Invites.Delete("GroupID", groupID.ToString()); + } + public void DeleteOldInvites() { m_Invites.DeleteOld(); diff --git a/OpenSim/Region/Framework/Interfaces/IExperienceModule.cs b/OpenSim/Region/Framework/Interfaces/IExperienceModule.cs new file mode 100644 index 00000000..c760f292 --- /dev/null +++ b/OpenSim/Region/Framework/Interfaces/IExperienceModule.cs @@ -0,0 +1,75 @@ +// SPDX-License-Identifier: BSD-3-Clause + +using OpenMetaverse; + +namespace OpenSim.Region.Framework.Interfaces +{ + /// + /// Region-facing adapter for the authoritative OpenGenesisLINK Experience service. + /// Implementations must not keep an independent money-/permission-like authority + /// in the simulator; they proxy the central service. + /// + public interface IExperienceModule + { + UUID ResolveExperience(UUID scriptItemId); + + bool TryGetExperienceDetails( + UUID experienceId, + out string name, + out UUID ownerId, + out UUID groupId, + out int maturity, + out bool enabled); + + bool HasExperiencePermission( + UUID scriptItemId, + UUID residentId, + UUID parcelId, + out UUID experienceId, + out string reason); + + bool AgentInExperience( + UUID scriptItemId, + UUID residentId); + + bool CreateKeyValue( + UUID scriptItemId, + string key, + string value, + out string error); + + bool ReadKeyValue( + UUID scriptItemId, + string key, + out string value, + out string error); + + bool UpdateKeyValue( + UUID scriptItemId, + string key, + string value, + bool checkOriginal, + string originalValue, + out bool retryMismatch, + out string error); + + bool DeleteKeyValue( + UUID scriptItemId, + string key, + out string error); + + bool GetKeyValueStats( + UUID scriptItemId, + out long usedBytes, + out long quotaBytes, + out int keyCount, + out string error); + + bool ListKeyValueKeys( + UUID scriptItemId, + int start, + int count, + out string[] keys, + out string error); + } +} diff --git a/OpenSim/Region/Framework/Scenes/SceneObjectGroup.cs b/OpenSim/Region/Framework/Scenes/SceneObjectGroup.cs index 93ac79bd..885f4949 100644 --- a/OpenSim/Region/Framework/Scenes/SceneObjectGroup.cs +++ b/OpenSim/Region/Framework/Scenes/SceneObjectGroup.cs @@ -127,8 +127,8 @@ namespace OpenSim.Region.Framework.Scenes remote_data = 1UL << 23, at_rot_target = 1UL << 24, transaction_result = 1UL << 25, - // - // + experience_permissions = 1UL << 26, + experience_permissions_denied = 1UL << 27, run_time_permissions = 1UL << 28, touch_end = 1UL << 29, state_entry = 1UL << 30, diff --git a/OpenSim/Region/ScriptEngine/Shared/Api/Implementation/LSL_Api.cs b/OpenSim/Region/ScriptEngine/Shared/Api/Implementation/LSL_Api.cs index a3ed4438..5610dd97 100644 --- a/OpenSim/Region/ScriptEngine/Shared/Api/Implementation/LSL_Api.cs +++ b/OpenSim/Region/ScriptEngine/Shared/Api/Implementation/LSL_Api.cs @@ -3997,6 +3997,95 @@ namespace OpenSim.Region.ScriptEngine.Shared.Api return m_ScriptEngine.GetStartParameter(m_item.ItemID); } + public void llRequestExperiencePermissions( + LSL_Key agentId, + LSL_String reason) + { + if (!UUID.TryParse( + agentId, + out UUID residentId) || + residentId.IsZero()) + { + PostExperiencePermissionDenied( + UUID.Zero, + ScriptBaseClass.XP_ERROR_INVALID_PARAMETERS); + return; + } + + IExperienceModule module = + World.RequestModuleInterface(); + + if (module == null) + { + PostExperiencePermissionDenied( + residentId, + ScriptBaseClass.XP_ERROR_EXPERIENCES_DISABLED); + return; + } + + ILandObject land = + World.LandChannel.GetLandObject( + m_host.AbsolutePosition); + + UUID parcelId = + land?.LandData?.GlobalID ?? + UUID.Zero; + + bool allowed = + module.HasExperiencePermission( + m_item.ItemID, + residentId, + parcelId, + out UUID experienceId, + out string denialReason); + + if (allowed) + { + m_ScriptEngine.PostScriptEvent( + m_item.ItemID, + new EventParams( + "experience_permissions", + new object[] + { + new LSL_Key( + residentId.ToString()) + }, + Array.Empty())); + return; + } + + int error = + experienceId.IsZero() + ? ScriptBaseClass.XP_ERROR_NO_EXPERIENCE + : denialReason != null && + denialReason.IndexOf( + "parcel", + StringComparison.OrdinalIgnoreCase) >= 0 + ? ScriptBaseClass.XP_ERROR_NOT_PERMITTED_LAND + : ScriptBaseClass.XP_ERROR_NOT_PERMITTED; + + PostExperiencePermissionDenied( + residentId, + error); + } + + private void PostExperiencePermissionDenied( + UUID residentId, + int error) + { + m_ScriptEngine.PostScriptEvent( + m_item.ItemID, + new EventParams( + "experience_permissions_denied", + new object[] + { + new LSL_Key( + residentId.ToString()), + new LSL_Integer(error) + }, + Array.Empty())); + } + public void llRequestPermissions(string agent, int perm) { if (!UUID.TryParse(agent, out UUID agentID) || agentID.IsZero()) @@ -14366,6 +14455,79 @@ namespace OpenSim.Region.ScriptEngine.Shared.Api return src; } + public LSL_List llGetExperienceDetails( + LSL_Key experienceId) + { + IExperienceModule module = + World.RequestModuleInterface(); + + if (module == null) + return new LSL_List(); + + UUID id; + + if (!UUID.TryParse( + experienceId, + out id) || + id.IsZero()) + { + id = + module.ResolveExperience( + m_item.ItemID); + } + + if (id.IsZero() || + !module.TryGetExperienceDetails( + id, + out string name, + out UUID ownerId, + out UUID groupId, + out int maturity, + out bool enabled)) + { + return new LSL_List(); + } + + string stateMessage = + enabled + ? "Experience is enabled" + : "Experience is disabled"; + + return new LSL_List( + new object[] + { + new LSL_String(name), + new LSL_Key(ownerId.ToString()), + new LSL_Key(id.ToString()), + new LSL_Integer(enabled ? 1 : 0), + new LSL_String(stateMessage), + new LSL_Key(groupId.ToString()) + }); + } + + public LSL_Integer llAgentInExperience( + LSL_Key agentId) + { + if (!UUID.TryParse( + agentId, + out UUID residentId) || + residentId.IsZero()) + { + return 0; + } + + IExperienceModule module = + World.RequestModuleInterface(); + + return + module != null && + module.AgentInExperience( + m_item.ItemID, + residentId) + ? 1 + : 0; + } + public LSL_List llGetObjectDetails(LSL_Key id, LSL_List args) { LSL_List ret = new(); @@ -18801,6 +18963,357 @@ namespace OpenSim.Region.ScriptEngine.Shared.Api return new LSL_List(m_host.ParentGroup.LinksetData.ListKeysByPatttern(pattern.m_string, start, count)); } + public LSL_Key llCreateKeyValue( + LSL_String key, + LSL_String value) + { + UUID requestId = + UUID.Random(); + + IExperienceModule module = + World.RequestModuleInterface(); + + string error = string.Empty; + + bool success = + module != null && + module.CreateKeyValue( + m_item.ItemID, + key, + value, + out error); + + PostExperienceDataserver( + requestId, + success + ? "1," + (string)value + : "0," + ExperienceErrorCode( + error, + ScriptBaseClass.XP_ERROR_STORAGE_EXCEPTION)); + + return new LSL_Key( + requestId.ToString()); + } + + public LSL_Key llReadKeyValue( + LSL_String key) + { + UUID requestId = + UUID.Random(); + + IExperienceModule module = + World.RequestModuleInterface(); + + string value = string.Empty; + string error = string.Empty; + + bool success = + module != null && + module.ReadKeyValue( + m_item.ItemID, + key, + out value, + out error); + + PostExperienceDataserver( + requestId, + success + ? "1," + value + : "0," + ExperienceErrorCode( + error, + ScriptBaseClass.XP_ERROR_KEY_NOT_FOUND)); + + return new LSL_Key( + requestId.ToString()); + } + + public LSL_Key llUpdateKeyValue( + LSL_String key, + LSL_String value, + LSL_Integer checkedFlag, + LSL_String originalValue) + { + UUID requestId = + UUID.Random(); + + IExperienceModule module = + World.RequestModuleInterface(); + + bool retryMismatch = false; + string error = string.Empty; + + bool success = + module != null && + module.UpdateKeyValue( + m_item.ItemID, + key, + value, + checkedFlag != 0, + originalValue, + out retryMismatch, + out error); + + PostExperienceDataserver( + requestId, + success + ? "1," + (string)value + : "0," + + (retryMismatch + ? ScriptBaseClass.XP_ERROR_RETRY_UPDATE + : ExperienceErrorCode( + error, + ScriptBaseClass.XP_ERROR_STORAGE_EXCEPTION))); + + return new LSL_Key( + requestId.ToString()); + } + + public LSL_Key llDeleteKeyValue( + LSL_String key) + { + UUID requestId = + UUID.Random(); + + IExperienceModule module = + World.RequestModuleInterface(); + + string error = string.Empty; + + bool success = + module != null && + module.DeleteKeyValue( + m_item.ItemID, + key, + out error); + + PostExperienceDataserver( + requestId, + success + ? "1" + : "0," + ExperienceErrorCode( + error, + ScriptBaseClass.XP_ERROR_KEY_NOT_FOUND)); + + return new LSL_Key( + requestId.ToString()); + } + + public LSL_Key llDataSizeKeyValue() + { + UUID requestId = + UUID.Random(); + + IExperienceModule module = + World.RequestModuleInterface(); + + long usedBytes = 0; + long quotaBytes = 0; + string error = string.Empty; + + bool success = + module != null && + module.GetKeyValueStats( + m_item.ItemID, + out usedBytes, + out quotaBytes, + out _, + out error); + + PostExperienceDataserver( + requestId, + success + ? "1," + + usedBytes.ToString( + CultureInfo.InvariantCulture) + + "," + + quotaBytes.ToString( + CultureInfo.InvariantCulture) + : "0," + ExperienceErrorCode( + error, + ScriptBaseClass.XP_ERROR_STORAGE_EXCEPTION)); + + return new LSL_Key( + requestId.ToString()); + } + + public LSL_Key llKeyCountKeyValue() + { + UUID requestId = + UUID.Random(); + + IExperienceModule module = + World.RequestModuleInterface(); + + int keyCount = 0; + string error = string.Empty; + + bool success = + module != null && + module.GetKeyValueStats( + m_item.ItemID, + out _, + out _, + out keyCount, + out error); + + PostExperienceDataserver( + requestId, + success + ? "1," + + keyCount.ToString( + CultureInfo.InvariantCulture) + : "0," + ExperienceErrorCode( + error, + ScriptBaseClass.XP_ERROR_STORAGE_EXCEPTION)); + + return new LSL_Key( + requestId.ToString()); + } + + public LSL_Key llKeysKeyValue( + LSL_Integer start, + LSL_Integer count) + { + UUID requestId = + UUID.Random(); + + IExperienceModule module = + World.RequestModuleInterface(); + + string[] keys = Array.Empty(); + string error = string.Empty; + + bool success = + module != null && + module.ListKeyValueKeys( + m_item.ItemID, + start, + count, + out keys, + out error); + + PostExperienceDataserver( + requestId, + success + ? "1" + + (keys.Length > 0 + ? "," + string.Join(",", keys) + : string.Empty) + : "0," + ExperienceErrorCode( + error, + ScriptBaseClass.XP_ERROR_KEY_NOT_FOUND)); + + return new LSL_Key( + requestId.ToString()); + } + + public LSL_String llGetExperienceErrorMessage( + LSL_Integer error) + { + switch ((int)error) + { + case ScriptBaseClass.XP_ERROR_NONE: + return "no error"; + case ScriptBaseClass.XP_ERROR_THROTTLED: + return "exceeded throttle"; + case ScriptBaseClass.XP_ERROR_EXPERIENCES_DISABLED: + return "experiences are disabled"; + case ScriptBaseClass.XP_ERROR_INVALID_PARAMETERS: + return "invalid parameters"; + case ScriptBaseClass.XP_ERROR_NOT_PERMITTED: + return "operation not permitted"; + case ScriptBaseClass.XP_ERROR_NO_EXPERIENCE: + return "script not associated with an experience"; + case ScriptBaseClass.XP_ERROR_NOT_FOUND: + return "not found"; + case ScriptBaseClass.XP_ERROR_INVALID_EXPERIENCE: + return "invalid experience"; + case ScriptBaseClass.XP_ERROR_EXPERIENCE_DISABLED: + return "experience is disabled"; + case ScriptBaseClass.XP_ERROR_EXPERIENCE_SUSPENDED: + return "experience is suspended"; + case ScriptBaseClass.XP_ERROR_UNKNOWN_ERROR: + return "unknown error"; + case ScriptBaseClass.XP_ERROR_QUOTA_EXCEEDED: + return "experience data quota exceeded"; + case ScriptBaseClass.XP_ERROR_STORE_DISABLED: + return "key-value store is disabled"; + case ScriptBaseClass.XP_ERROR_STORAGE_EXCEPTION: + return "key-value store communication failed"; + case ScriptBaseClass.XP_ERROR_KEY_NOT_FOUND: + return "key doesn't exist"; + case ScriptBaseClass.XP_ERROR_RETRY_UPDATE: + return "retry update"; + case ScriptBaseClass.XP_ERROR_MATURITY_EXCEEDED: + return "experience content rating too high"; + case ScriptBaseClass.XP_ERROR_NOT_PERMITTED_LAND: + return "not allowed to run on this land"; + case ScriptBaseClass.XP_ERROR_REQUEST_PERM_TIMEOUT: + return "experience permissions request timed out"; + default: + return "unknown error"; + } + } + + private void PostExperienceDataserver( + UUID requestId, + string payload) + { + m_ScriptEngine.PostScriptEvent( + m_item.ItemID, + new EventParams( + "dataserver", + new object[] + { + new LSL_Key( + requestId.ToString()), + new LSL_String( + payload ?? string.Empty) + }, + Array.Empty())); + } + + private static int ExperienceErrorCode( + string error, + int fallback) + { + string text = + error ?? + string.Empty; + + if (text.IndexOf( + "bound", + StringComparison.OrdinalIgnoreCase) >= 0 || + text.IndexOf( + "experience", + StringComparison.OrdinalIgnoreCase) >= 0 && + text.IndexOf( + "not", + StringComparison.OrdinalIgnoreCase) >= 0) + { + return ScriptBaseClass.XP_ERROR_NO_EXPERIENCE; + } + + if (text.IndexOf( + "quota", + StringComparison.OrdinalIgnoreCase) >= 0) + { + return ScriptBaseClass.XP_ERROR_QUOTA_EXCEEDED; + } + + if (text.IndexOf( + "parameter", + StringComparison.OrdinalIgnoreCase) >= 0 || + text.IndexOf( + "length", + StringComparison.OrdinalIgnoreCase) >= 0) + { + return ScriptBaseClass.XP_ERROR_INVALID_PARAMETERS; + } + + return fallback; + } + public LSL_Integer llIsFriend(LSL_Key agent_id) { SceneObjectGroup parentsog = m_host.ParentGroup; diff --git a/OpenSim/Region/ScriptEngine/Shared/Api/Interface/ILSL_Api.cs b/OpenSim/Region/ScriptEngine/Shared/Api/Interface/ILSL_Api.cs index 9061624d..16a2e155 100644 --- a/OpenSim/Region/ScriptEngine/Shared/Api/Interface/ILSL_Api.cs +++ b/OpenSim/Region/ScriptEngine/Shared/Api/Interface/ILSL_Api.cs @@ -181,6 +181,8 @@ namespace OpenSim.Region.ScriptEngine.Shared.Api.Interfaces LSL_Integer llGetNumberOfSides(); LSL_String llGetObjectDesc(); LSL_List llGetObjectDetails(LSL_Key objectId, LSL_List args); + LSL_List llGetExperienceDetails(LSL_Key experienceId); + LSL_Integer llAgentInExperience(LSL_Key agentId); LSL_Float llGetObjectMass(LSL_Key objectId); LSL_String llGetObjectName(); LSL_Integer llGetObjectPermMask(int mask); @@ -327,6 +329,7 @@ namespace OpenSim.Region.ScriptEngine.Shared.Api.Interfaces LSL_Key llRequestAgentData(string id, int data); LSL_Key llRequestInventoryData(LSL_String name); void llRequestPermissions(string agent, int perm); + void llRequestExperiencePermissions(LSL_Key agentId, LSL_String reason); LSL_Key llRequestSecureURL(); LSL_Key llRequestSimulatorData(string simulator, int data); LSL_Key llRequestURL(); @@ -521,6 +524,15 @@ namespace OpenSim.Region.ScriptEngine.Shared.Api.Interfaces LSL_Integer llLinksetDataWrite(LSL_String name, LSL_String value); LSL_Integer llLinksetDataWriteProtected(LSL_String name, LSL_String value, LSL_String pass); + LSL_Key llCreateKeyValue(LSL_String key, LSL_String value); + LSL_Key llReadKeyValue(LSL_String key); + LSL_Key llUpdateKeyValue(LSL_String key, LSL_String value, LSL_Integer checkedFlag, LSL_String originalValue); + LSL_Key llDeleteKeyValue(LSL_String key); + LSL_Key llDataSizeKeyValue(); + LSL_Key llKeyCountKeyValue(); + LSL_Key llKeysKeyValue(LSL_Integer start, LSL_Integer count); + LSL_String llGetExperienceErrorMessage(LSL_Integer error); + LSL_Integer llIsFriend(LSL_Key agent_id); LSL_Integer llDerezObject(LSL_Key objectUUID, LSL_Integer flag); } diff --git a/OpenSim/Region/ScriptEngine/Shared/Api/Runtime/LSL_Constants.cs b/OpenSim/Region/ScriptEngine/Shared/Api/Runtime/LSL_Constants.cs index 74f19eab..cc9658e2 100644 --- a/OpenSim/Region/ScriptEngine/Shared/Api/Runtime/LSL_Constants.cs +++ b/OpenSim/Region/ScriptEngine/Shared/Api/Runtime/LSL_Constants.cs @@ -89,6 +89,27 @@ namespace OpenSim.Region.ScriptEngine.Shared.ScriptBase public const int PERMISSION_OVERRIDE_ANIMATIONS = 0x8000; public const int PERMISSION_RETURN_OBJECTS = 0x10000; + // Experience Tools errors + public const int XP_ERROR_NONE = 0; + public const int XP_ERROR_THROTTLED = 1; + public const int XP_ERROR_EXPERIENCES_DISABLED = 2; + public const int XP_ERROR_INVALID_PARAMETERS = 3; + public const int XP_ERROR_NOT_PERMITTED = 4; + public const int XP_ERROR_NO_EXPERIENCE = 5; + public const int XP_ERROR_NOT_FOUND = 6; + public const int XP_ERROR_INVALID_EXPERIENCE = 7; + public const int XP_ERROR_EXPERIENCE_DISABLED = 8; + public const int XP_ERROR_EXPERIENCE_SUSPENDED = 9; + public const int XP_ERROR_UNKNOWN_ERROR = 10; + public const int XP_ERROR_QUOTA_EXCEEDED = 11; + public const int XP_ERROR_STORE_DISABLED = 12; + public const int XP_ERROR_STORAGE_EXCEPTION = 13; + public const int XP_ERROR_KEY_NOT_FOUND = 14; + public const int XP_ERROR_RETRY_UPDATE = 15; + public const int XP_ERROR_MATURITY_EXCEEDED = 16; + public const int XP_ERROR_NOT_PERMITTED_LAND = 17; + public const int XP_ERROR_REQUEST_PERM_TIMEOUT = 18; + public const int AGENT_FLYING = 0x1; //ApiDesc The agent has attachments public const int AGENT_ATTACHMENTS = 0x2; diff --git a/OpenSim/Region/ScriptEngine/Shared/Api/Runtime/LSL_Stub.cs b/OpenSim/Region/ScriptEngine/Shared/Api/Runtime/LSL_Stub.cs index e84e664c..8d000247 100644 --- a/OpenSim/Region/ScriptEngine/Shared/Api/Runtime/LSL_Stub.cs +++ b/OpenSim/Region/ScriptEngine/Shared/Api/Runtime/LSL_Stub.cs @@ -788,6 +788,18 @@ namespace OpenSim.Region.ScriptEngine.Shared.ScriptBase return m_LSL_Functions.llGetObjectDetails(id, args); } + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public LSL_List llGetExperienceDetails(LSL_Key experienceId) + { + return m_LSL_Functions.llGetExperienceDetails(experienceId); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public LSL_Integer llAgentInExperience(LSL_Key agentId) + { + return m_LSL_Functions.llAgentInExperience(agentId); + } + [MethodImpl(MethodImplOptions.AggressiveInlining)] public LSL_Float llGetObjectMass(string id) { @@ -1664,6 +1676,12 @@ namespace OpenSim.Region.ScriptEngine.Shared.ScriptBase m_LSL_Functions.llRequestPermissions(agent, perm); } + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void llRequestExperiencePermissions(LSL_Key agentId, LSL_String reason) + { + m_LSL_Functions.llRequestExperiencePermissions(agentId, reason); + } + [MethodImpl(MethodImplOptions.AggressiveInlining)] public LSL_Key llRequestSecureURL() { @@ -2803,6 +2821,54 @@ namespace OpenSim.Region.ScriptEngine.Shared.ScriptBase return m_LSL_Functions.llLinksetDataFindKeys(pattern, start, count); } + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public LSL_Key llCreateKeyValue(LSL_String key, LSL_String value) + { + return m_LSL_Functions.llCreateKeyValue(key, value); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public LSL_Key llReadKeyValue(LSL_String key) + { + return m_LSL_Functions.llReadKeyValue(key); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public LSL_Key llUpdateKeyValue(LSL_String key, LSL_String value, LSL_Integer checkedFlag, LSL_String originalValue) + { + return m_LSL_Functions.llUpdateKeyValue(key, value, checkedFlag, originalValue); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public LSL_Key llDeleteKeyValue(LSL_String key) + { + return m_LSL_Functions.llDeleteKeyValue(key); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public LSL_Key llDataSizeKeyValue() + { + return m_LSL_Functions.llDataSizeKeyValue(); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public LSL_Key llKeyCountKeyValue() + { + return m_LSL_Functions.llKeyCountKeyValue(); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public LSL_Key llKeysKeyValue(LSL_Integer start, LSL_Integer count) + { + return m_LSL_Functions.llKeysKeyValue(start, count); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public LSL_String llGetExperienceErrorMessage(LSL_Integer error) + { + return m_LSL_Functions.llGetExperienceErrorMessage(error); + } + [MethodImpl(MethodImplOptions.AggressiveInlining)] public LSL_Integer llIsFriend(LSL_Key agent_id) { diff --git a/OpenSim/Region/ScriptEngine/YEngine/MMRIEventHandlers.cs b/OpenSim/Region/ScriptEngine/YEngine/MMRIEventHandlers.cs index 82d85967..fb1327bc 100644 --- a/OpenSim/Region/ScriptEngine/YEngine/MMRIEventHandlers.cs +++ b/OpenSim/Region/ScriptEngine/YEngine/MMRIEventHandlers.cs @@ -47,6 +47,8 @@ namespace OpenSim.Region.ScriptEngine.Yengine void control(string id, int held, int change); void dataserver(string queryid, string data); void email(string time, string address, string subj, string message, int num_left); + void experience_permissions(string agent_id); + void experience_permissions_denied(string agent_id, int reason); void http_request(string request_id, string method, string body); void http_response(string request_id, int status, LSL_List metadata, string body); void land_collision(LSL_Vector pos); diff --git a/OpenSim/Region/ScriptEngine/YEngine/MMRScriptEventCode.cs b/OpenSim/Region/ScriptEngine/YEngine/MMRScriptEventCode.cs index b854437d..253b6ec6 100644 --- a/OpenSim/Region/ScriptEngine/YEngine/MMRScriptEventCode.cs +++ b/OpenSim/Region/ScriptEngine/YEngine/MMRScriptEventCode.cs @@ -70,6 +70,8 @@ namespace OpenSim.Region.ScriptEngine.Yengine remote_data = 23, at_rot_target = 24, transaction_result = 25, + experience_permissions = 26, + experience_permissions_denied = 27, run_time_permissions = 28, touch_end = 29, state_entry = 30, diff --git a/OpenSim/Region/ScriptEngine/YEngine/XMRInstMain.cs b/OpenSim/Region/ScriptEngine/YEngine/XMRInstMain.cs index fcff9ef1..d058ad3c 100644 --- a/OpenSim/Region/ScriptEngine/YEngine/XMRInstMain.cs +++ b/OpenSim/Region/ScriptEngine/YEngine/XMRInstMain.cs @@ -215,6 +215,8 @@ namespace OpenSim.Region.ScriptEngine.Yengine {"control", ScriptEventCode.control}, {"dataserver", ScriptEventCode.dataserver}, {"email", ScriptEventCode.email}, + {"experience_permissions", ScriptEventCode.experience_permissions}, + {"experience_permissions_denied", ScriptEventCode.experience_permissions_denied}, {"http_response", ScriptEventCode.http_response}, {"land_collision", ScriptEventCode.land_collision}, {"land_collision_end", ScriptEventCode.land_collision_end}, diff --git a/OpenSim/Tests/Common/Mock/TestGroupsDataPlugin.cs b/OpenSim/Tests/Common/Mock/TestGroupsDataPlugin.cs index 8e2d8e6c..932549b8 100644 --- a/OpenSim/Tests/Common/Mock/TestGroupsDataPlugin.cs +++ b/OpenSim/Tests/Common/Mock/TestGroupsDataPlugin.cs @@ -304,6 +304,11 @@ namespace OpenSim.Tests.Common.Mock return false; } + public bool DeleteInvites(UUID groupID) + { + return false; + } + public void DeleteOldInvites() { } diff --git a/bin/OpenSim.ini.example b/bin/OpenSim.ini.example index f4626213..5855b8ed 100644 --- a/bin/OpenSim.ini.example +++ b/bin/OpenSim.ini.example @@ -974,6 +974,17 @@ ;; Money Unit fee to create groups. Default is 0. ; PriceGroupCreate = 0 +[NexExperiencesViewer] + ; Central OpenGenesisLINK Experience adapter. + ; Experience permissions and K/V state remain authoritative in Robust. + Enabled = false + WorldApiBaseUrl = "http://127.0.0.1:8002" + + ; Service API key scoped to experiences:script. + ; Keep the real value outside version control. + ApiKey = "${Environment|NEXVERSE_EXPERIENCES_API_KEY}" + RequestTimeoutMilliseconds = 3000 + [NexEconomyViewer] ; Central OpenGenesisLINK NV$ Viewer/IMoneyModule adapter. ; The simulator never opens the ledger database directly. diff --git a/bin/Robust.HG.ini.example b/bin/Robust.HG.ini.example index 47b9b8c7..670e3e43 100644 --- a/bin/Robust.HG.ini.example +++ b/bin/Robust.HG.ini.example @@ -265,6 +265,17 @@ StorageProvider = "OpenSim.Data.MySQL.dll" ConnectionString = "Data Source=localhost;Database=opensim;User ID=opensim;Password=*****;Old Guids=true;SslMode=None;" +[NexGroups] + ; OpenGenesisLINK NexGroups management/parity facade. + ; Keep disabled until the Groups V2 storage/service is configured and + ; parity validation has been completed for this deployment. + Enabled = false + +[NexExperiences] + ; Native OpenGenesisLINK Experience authority used by World API and LSL adapters. + ; This file is server-owned and must be writable by the Robust process. + StorePath = "data/nexverse-experiences.json" + [NexEconomy] ; Native OpenGenesisLINK NV$ double-entry ledger bootstrap. ; Disabled until the durable database backend has been validated for this installation. @@ -889,6 +900,9 @@ ;MaxOfflineIMs = 25; [Groups] + ; Persistent NexGroups moderation overlay. The historical Groups V2 + ; transport remains active until the parity gate is complete. + NexModerationStorePath = "data/nexgroups-moderation.json" ;; for the HG Groups service OfflineIMService = "OpenSim.Addons.OfflineIM.dll:OfflineIMService" UserAccountService = "OpenSim.Services.UserAccountService.dll:UserAccountService" diff --git a/bin/Robust.ini.example b/bin/Robust.ini.example index 8aa05694..1acbce0b 100644 --- a/bin/Robust.ini.example +++ b/bin/Robust.ini.example @@ -221,6 +221,17 @@ StorageProvider = "OpenSim.Data.MySQL.dll" ConnectionString = "Data Source=localhost;Database=opensim;User ID=opensim;Password=*****;Old Guids=true;SslMode=None;" +[NexGroups] + ; OpenGenesisLINK NexGroups management/parity facade. + ; Keep disabled until the Groups V2 storage/service is configured and + ; parity validation has been completed for this deployment. + Enabled = false + +[NexExperiences] + ; Native OpenGenesisLINK Experience authority used by World API and LSL adapters. + ; This file is server-owned and must be writable by the Robust process. + StorePath = "data/nexverse-experiences.json" + [NexEconomy] ; Native OpenGenesisLINK NV$ double-entry ledger bootstrap. ; Disabled until the durable database backend has been validated for this installation. @@ -659,6 +670,9 @@ ;MaxOfflineIMs = 25; [Groups] + ; Persistent NexGroups moderation overlay. The historical Groups V2 + ; transport remains active until the parity gate is complete. + NexModerationStorePath = "data/nexgroups-moderation.json" ;; Sets the maximum number of groups an agent may join ; MaxAgentGroups = 42 diff --git a/doc/NexVerse/ROADMAP.md b/doc/NexVerse/ROADMAP.md index a855c183..14bd0edb 100644 --- a/doc/NexVerse/ROADMAP.md +++ b/doc/NexVerse/ROADMAP.md @@ -1032,50 +1032,64 @@ Support Firestorm-visible flows including: ### 11.1 NexGroups -Replace the historical group stack only after parity is reached. +**Status: parity layer completed on the 0.9.3.7 roadmap line.** The proven Groups V2 Viewer/HG transport remains active deliberately; OpenGenesisLINK does not remove it until a later cut-over gate proves protocol parity. -Target scope: - -- create/delete group; -- profile; -- members; -- roles; -- role powers; -- owner; -- invitations; -- bans; -- notices; -- group chat; -- group land; -- group accounting; -- group search; -- group voice; -- group permissions; -- group-owned objects; -- HG behavior where supported. +- [x] create/delete group; deletion is founder-authorized and cleans members, roles, notices, invites and moderation state; +- [x] group profile; +- [x] members and membership lifecycle; +- [x] roles and role powers; +- [x] owner/founder semantics; +- [x] invitations; +- [x] persistent bans, enforced centrally before membership can be added; +- [x] notices; +- [x] group chat through the preserved GroupsMessagingModule; +- [x] group land semantics through native parcel GroupID + group powers; +- [x] group accounting through a central NV$ Group wallet and NVBAN; +- [x] group search; +- [x] group voice policy/channel identity; media transport itself remains part of Roadmap 13 NexVoice; +- [x] group permissions; +- [x] group-owned object semantics through native object GroupID/ownership rules; +- [x] Hypergrid group connector behavior remains preserved where supported; +- [x] authenticated NexGroups World API and audit events for management mutations. ### 11.2 Experiences -Implement Experiences as a native NexVerse service. +**Status: native service completed.** -Core model: - -- owner; -- group; -- admins; -- contributors; -- allowed residents; -- blocked residents; -- estate policy; -- parcel policy; -- permissions; -- persistent key/value storage; -- logs; -- audit events. +- [x] owner; +- [x] optional group association; +- [x] admins; +- [x] contributors; +- [x] allowed residents; +- [x] blocked residents; +- [x] estate allow/block policy; +- [x] parcel allow/block policy; +- [x] persistent permission decisions; +- [x] persistent script-to-Experience binding; +- [x] persistent key/value storage with 128 MiB quota, 1011-byte key and 4095-byte value limits; +- [x] persistent Experience logs; +- [x] audit events for management mutations; +- [x] database-isolated simulator adapter using the authenticated World API. ### 11.3 Experience LSL -Implement and verify relevant Experience LSL functions/events, including permission flows and persistent storage behavior. +**Status: implemented and guarded by CI.** + +- [x] `llRequestExperiencePermissions`; +- [x] `experience_permissions`; +- [x] `experience_permissions_denied`; +- [x] `llGetExperienceDetails`; +- [x] `llAgentInExperience`; +- [x] `llCreateKeyValue`; +- [x] `llReadKeyValue`; +- [x] `llUpdateKeyValue` with checked/original-value retry semantics; +- [x] `llDeleteKeyValue`; +- [x] `llDataSizeKeyValue`; +- [x] `llKeyCountKeyValue`; +- [x] `llKeysKeyValue`; +- [x] `llGetExperienceErrorMessage`; +- [x] YEngine event IDs and Experience error constants; +- [x] persistent K/V regression/reopen coverage. --- diff --git a/doc/NexVerse/WORLD_API.md b/doc/NexVerse/WORLD_API.md index 7f4454a1..01492536 100644 --- a/doc/NexVerse/WORLD_API.md +++ b/doc/NexVerse/WORLD_API.md @@ -698,3 +698,26 @@ The API catalog does not replace the simulator's parcel authority. Native parcel `NexVerseMoneyModule` remains the database-isolated `IMoneyModule` adapter. Resident payments use the World API; local object payments resolve the object owner and are recorded as NexCommerce vendor orders while preserving `OnObjectPaid`. Viewer object purchases validate current sale type/price, settle an `ObjectSale` order and then call the authoritative `IBuySellModule`; failed delivery triggers a compensating NexCommerce refund. SaleType Contents therefore uses the native contents-delivery implementation after settlement. Local groups are provisioned on demand as central NV$ `Group` wallets through the trusted `POST /api/v1/economy/accounts/ensure` service endpoint. Native parcel purchases route their payment through NexCommerce before ownership is changed. + + +## NexGroups API — Roadmap 11.1 + +`/api/v1/groups` is the OpenGenesisLINK management/parity surface in front of the existing Groups V2 transport. The Viewer/HG connector stack is intentionally preserved until a later cut-over gate; the new API does not fork group identity or membership state. + +Supported operations cover group search/create/profile/delete, members, roles and powers, role membership, invitations, notices, persistent bans, central NV$ group accounting and capability metadata. Group creation provisions a central NV$ `Group` wallet/NVBAN when the economy is enabled. Bans are persisted in `NexModerationStorePath` and are enforced inside `GroupsService.AddAgentToGroup`, so Viewer/API joins cannot bypass moderation. + +Group chat continues through `GroupsMessagingModule`. Native parcel GroupID/group powers remain authoritative for group land, and native object ownership/GroupID remains authoritative for group-owned objects. The HG Groups connector remains present. NexGroups exposes stable voice policy/channel identity; actual WebRTC media transport belongs to Roadmap 13 NexVoice. + +## NexExperiences API — Roadmap 11.2 + +`/api/v1/experiences` is the native OpenGenesisLINK Experience authority. It persists owner, optional group, admins, contributors, resident allow/block state, estate/parcel policy, script bindings, key/value data and logs. + +Management/read calls use `experiences:manage` and `experiences:read`. Simulator/LSL calls use the separate `experiences:script` scope through `/api/v1/experiences/script/*`, keeping script adapters outside management authority. The simulator never opens the Experience store directly. + +Script routes provide Experience resolution/details, resident permission checks, parcel/estate policy checks and asynchronous K/V operations. K/V behavior includes checked updates, missing-key update-as-create semantics, key enumeration/count and used/quota reporting. + +## Experience LSL — Roadmap 11.3 + +The shared LSL API/YEngine now exposes the Experience permission and persistent-storage surface: `llRequestExperiencePermissions`, `experience_permissions`, `experience_permissions_denied`, `llGetExperienceDetails`, `llAgentInExperience`, CRUD K/V calls, K/V size/count/key enumeration and `llGetExperienceErrorMessage`. + +Experience permission decisions and K/V data are grid-authoritative through Robust. YEngine reserves event IDs 26 and 27 for the two Experience permission events. diff --git a/prebuild.xml b/prebuild.xml index 45a84088..7fd3a50a 100644 --- a/prebuild.xml +++ b/prebuild.xml @@ -2001,6 +2001,7 @@ + diff --git a/tools/ci/NexExperiencesRegression/NexExperiencesRegression.csproj b/tools/ci/NexExperiencesRegression/NexExperiencesRegression.csproj new file mode 100644 index 00000000..58168cba --- /dev/null +++ b/tools/ci/NexExperiencesRegression/NexExperiencesRegression.csproj @@ -0,0 +1,12 @@ + + + Exe + net8.0 + disable + disable + + + + + + diff --git a/tools/ci/NexExperiencesRegression/Program.cs b/tools/ci/NexExperiencesRegression/Program.cs new file mode 100644 index 00000000..d5cde98b --- /dev/null +++ b/tools/ci/NexExperiencesRegression/Program.cs @@ -0,0 +1,260 @@ +// SPDX-License-Identifier: MPL-2.0 + +using System; +using System.IO; +using System.Linq; +using NexVerse.Core.Experiences; + +internal static class Program +{ + private static void Require(bool condition, string message) + { + if (!condition) + throw new InvalidOperationException(message); + } + + private static void Main() + { + string root = + Path.Combine( + Path.GetTempPath(), + "ogl-experiences-" + + Guid.NewGuid().ToString("N")); + Directory.CreateDirectory(root); + + string path = + Path.Combine( + root, + "experiences.json"); + + Guid owner = Guid.NewGuid(); + Guid admin = Guid.NewGuid(); + Guid contributor = Guid.NewGuid(); + Guid resident = Guid.NewGuid(); + Guid blocked = Guid.NewGuid(); + Guid estate = Guid.NewGuid(); + Guid parcel = Guid.NewGuid(); + Guid script = Guid.NewGuid(); + + NexExperienceStore store = + new NexExperienceStore(path); + + NexExperience created = + store.Create( + owner, + Guid.NewGuid(), + "CI Experience", + "Chapter 11 regression", + NexExperienceMaturity.Moderate, + "ci"); + + Require( + created.OwnerId == owner && + created.Admins.Contains(owner), + "owner/admin foundation failed"); + + store.SetRole( + created.ExperienceId, + owner, + admin, + "admin", + true, + "ci"); + store.SetRole( + created.ExperienceId, + admin, + contributor, + "contributor", + true, + "ci"); + + Require( + store.Get(created.ExperienceId).Contributors.Contains(contributor), + "role persistence failed"); + + store.SetResidentPermission( + created.ExperienceId, + admin, + resident, + NexExperiencePermissionStatus.Allowed, + "ci"); + store.SetResidentPermission( + created.ExperienceId, + owner, + blocked, + NexExperiencePermissionStatus.Blocked, + "ci"); + + Require( + store.GetResidentPermission( + created.ExperienceId, + resident) == + NexExperiencePermissionStatus.Allowed, + "allowed resident failed"); + Require( + store.GetResidentPermission( + created.ExperienceId, + blocked) == + NexExperiencePermissionStatus.Blocked, + "blocked resident failed"); + + store.SetLocationPolicy( + created.ExperienceId, + owner, + "estate", + estate, + true, + true, + "ci"); + store.SetLocationPolicy( + created.ExperienceId, + admin, + "parcel", + parcel, + true, + true, + "ci"); + + Require( + store.IsLocationAllowed( + created.ExperienceId, + estate, + parcel), + "allowed estate/parcel failed"); + Require( + !store.IsLocationAllowed( + created.ExperienceId, + Guid.NewGuid(), + parcel), + "estate allow-list was not enforced"); + + store.BindScript( + created.ExperienceId, + owner, + script, + "ci"); + + Require( + store.ResolveScript(script) == + created.ExperienceId, + "script binding failed"); + + Require( + store.CreateKeyValue( + created.ExperienceId, + script, + "alpha", + "one"), + "K/V create failed"); + + Require( + store.TryReadKeyValue( + created.ExperienceId, + script, + "alpha", + out string value) && + value == "one", + "K/V read failed"); + + Require( + !store.UpdateKeyValue( + created.ExperienceId, + script, + "alpha", + "two", + true, + "stale", + out bool retryMismatch) && + retryMismatch, + "checked K/V retry semantics failed"); + + Require( + store.UpdateKeyValue( + created.ExperienceId, + script, + "alpha", + "two", + true, + "one", + out retryMismatch) && + !retryMismatch, + "checked K/V update failed"); + + Require( + store.UpdateKeyValue( + created.ExperienceId, + script, + "created-by-update", + "value", + false, + string.Empty, + out retryMismatch), + "missing-key update did not create"); + + Require( + store.GetKeyCount( + created.ExperienceId, + script) == 2, + "K/V count mismatch"); + + Require( + store.ListKeys( + created.ExperienceId, + script, + 0, + 10).SequenceEqual( + new[] + { + "alpha", + "created-by-update" + }), + "K/V key listing mismatch"); + + Require( + store.GetDataSize( + created.ExperienceId, + script) > 0, + "K/V data size missing"); + + Require( + store.DeleteKeyValue( + created.ExperienceId, + script, + "alpha"), + "K/V delete failed"); + + Require( + store.GetLogs( + created.ExperienceId, + 0, + 100).Count >= 6, + "Experience audit log history missing"); + + NexExperienceStore reopened = + new NexExperienceStore(path); + + Require( + reopened.Get(created.ExperienceId) != null && + reopened.ResolveScript(script) == + created.ExperienceId && + reopened.GetKeyCount( + created.ExperienceId, + script) == 1, + "Experience persistence/reopen failed"); + + reopened.Delete( + created.ExperienceId, + owner, + "ci"); + + Require( + reopened.Get(created.ExperienceId) == null && + reopened.ResolveScript(script) == Guid.Empty, + "Experience deletion cleanup failed"); + + Directory.Delete(root, true); + + Console.WriteLine( + "OpenGenesisLINK NexExperiences persistence, permissions and K/V regression: OK"); + } +} diff --git a/tools/ci/verify_nexgroups_experiences.py b/tools/ci/verify_nexgroups_experiences.py new file mode 100644 index 00000000..2134a15c --- /dev/null +++ b/tools/ci/verify_nexgroups_experiences.py @@ -0,0 +1,216 @@ +#!/usr/bin/env python3 +from pathlib import Path + +roadmap = Path("doc/NexVerse/ROADMAP.md").read_text(encoding="utf-8") +groups_service = Path("OpenSim/Addons/Groups/Service/GroupsService.cs").read_text(encoding="utf-8") +groups_messaging = Path("OpenSim/Addons/Groups/GroupsMessagingModule.cs").read_text(encoding="utf-8") +groups_hg = Path("OpenSim/Addons/Groups/Hypergrid/GroupsServiceHGConnector.cs").read_text(encoding="utf-8") +groups_api = Path("NexVerse/Server/Api/NexGroupsApi.cs").read_text(encoding="utf-8") +experience_store = Path("NexVerse/Core/Experiences/NexExperienceStore.cs").read_text(encoding="utf-8") +experience_api = Path("NexVerse/Server/Api/NexExperiencesApi.cs").read_text(encoding="utf-8") +experience_module = Path("NexVerse/RegionModules/Experiences/NexExperienceModule.cs").read_text(encoding="utf-8") +experience_interface = Path("OpenSim/Region/Framework/Interfaces/IExperienceModule.cs").read_text(encoding="utf-8") +lsl_interface = Path("OpenSim/Region/ScriptEngine/Shared/Api/Interface/ILSL_Api.cs").read_text(encoding="utf-8") +lsl_api = Path("OpenSim/Region/ScriptEngine/Shared/Api/Implementation/LSL_Api.cs").read_text(encoding="utf-8") +lsl_stub = Path("OpenSim/Region/ScriptEngine/Shared/Api/Runtime/LSL_Stub.cs").read_text(encoding="utf-8") +lsl_constants = Path("OpenSim/Region/ScriptEngine/Shared/Api/Runtime/LSL_Constants.cs").read_text(encoding="utf-8") +scene_object = Path("OpenSim/Region/Framework/Scenes/SceneObjectGroup.cs").read_text(encoding="utf-8") +event_handlers = Path("OpenSim/Region/ScriptEngine/YEngine/MMRIEventHandlers.cs").read_text(encoding="utf-8") +event_codes = Path("OpenSim/Region/ScriptEngine/YEngine/MMRScriptEventCode.cs").read_text(encoding="utf-8") +event_map = Path("OpenSim/Region/ScriptEngine/YEngine/XMRInstMain.cs").read_text(encoding="utf-8") +connector = Path("NexVerse/Server/Api/NexVerseWorldApiConnector.cs").read_text(encoding="utf-8") +security = Path("NexVerse/Core/Security/NexSecurity.cs").read_text(encoding="utf-8") +opensim_config = Path("bin/OpenSim.ini.example").read_text(encoding="utf-8") +robust_config = Path("bin/Robust.ini.example").read_text(encoding="utf-8") +robust_hg_config = Path("bin/Robust.HG.ini.example").read_text(encoding="utf-8") +regression = Path("tools/ci/NexExperiencesRegression/Program.cs").read_text(encoding="utf-8") + +for marker in ( + "### 11.1 NexGroups", + "### 11.2 Experiences", + "### 11.3 Experience LSL", +): + assert marker in roadmap, f"missing chapter 11 roadmap marker: {marker}" + +# Historical transport remains in place until the parity gate is complete. +for marker in ( + "public class GroupsService", + "CreateGroup(", + "GetGroupMembers(", + "AddGroupRole(", + "AddAgentToGroupInvite(", + "AddGroupNotice(", + "GetGroupNotices(", + "AddGroupBan(", + "RemoveGroupBan(", + "DeleteGroup(", + "m_NexModeration.IsBanned(", +): + assert marker in groups_service, f"missing NexGroups service parity marker: {marker}" + +for marker in ( + "class GroupsMessagingModule", + "StartGroupChatSession(", + "SendMessageToGroup(", +): + assert marker in groups_messaging, f"group chat compatibility lost: {marker}" + +assert "class GroupsServiceHGConnector" in groups_hg, "Hypergrid groups connector was removed" + +for marker in ( + "/api/v1/groups", + '"members"', + '"roles"', + '"invites"', + '"notices"', + '"bans"', + '"accounting"', + '"capabilities"', + "EnsureWalletAccount(", + "NexLedgerAccountClass.Group", + "GroupsDataUtils.GroupMembersData", + "GroupsDataUtils.GroupRolesData", +): + assert marker in groups_api, f"missing NexGroups API marker: {marker}" + +for marker in ( + "NexExperience", + "OwnerId", + "GroupId", + "Admins", + "Contributors", + "AllowedResidents", + "BlockedResidents", + "AllowedEstates", + "BlockedEstates", + "AllowedParcels", + "BlockedParcels", + "ScriptBindings", + "KeyValues", + "GetLogs(", + "MaxStoreBytes", + "UpdateKeyValue(", + "checkOriginal", + "retryMismatch", +): + assert marker in experience_store, f"missing Experience core marker: {marker}" + +for marker in ( + "/api/v1/experiences", + "/api/v1/experiences/script/resolve", + "/api/v1/experiences/script/details", + "/api/v1/experiences/script/permission", + "/api/v1/experiences/script/location", + "/api/v1/experiences/script/kv", + "NexScopes.ExperiencesScript", + "experience.created", + "experience.permission.updated", + "experience.script.bound", +): + assert marker in experience_api, f"missing Experience API marker: {marker}" + +for forbidden in ( + "DbConnection", + "MySql", + "Npgsql", + "SQLite", +): + assert forbidden not in experience_module, f"simulator Experience adapter opens storage directly: {forbidden}" + +for marker in ( + "IExperienceModule", + "ResolveExperience(", + "HasExperiencePermission(", + "CreateKeyValue(", + "ReadKeyValue(", + "UpdateKeyValue(", + "DeleteKeyValue(", + "GetKeyValueStats(", + "ListKeyValueKeys(", +): + assert marker in experience_interface, f"missing Experience region contract marker: {marker}" + assert marker in experience_module, f"missing Experience region adapter marker: {marker}" + +lsl_functions = ( + "llRequestExperiencePermissions", + "llGetExperienceDetails", + "llAgentInExperience", + "llCreateKeyValue", + "llReadKeyValue", + "llUpdateKeyValue", + "llDeleteKeyValue", + "llDataSizeKeyValue", + "llKeyCountKeyValue", + "llKeysKeyValue", + "llGetExperienceErrorMessage", +) + +for marker in lsl_functions: + assert marker in lsl_interface, f"missing LSL interface function: {marker}" + assert marker in lsl_api, f"missing LSL implementation function: {marker}" + assert marker in lsl_stub, f"missing LSL runtime stub function: {marker}" + +assert "llUpdateKeyValue(LSL_String key, LSL_String value, LSL_Integer checkedFlag, LSL_String originalValue)" in lsl_interface +assert "XP_ERROR_NO_EXPERIENCE = 5" in lsl_constants +assert "XP_ERROR_STORAGE_EXCEPTION = 13" in lsl_constants +assert "XP_ERROR_KEY_NOT_FOUND = 14" in lsl_constants +assert "XP_ERROR_RETRY_UPDATE = 15" in lsl_constants +assert "XP_ERROR_NOT_PERMITTED_LAND = 17" in lsl_constants + +for marker in ( + "experience_permissions = 1UL << 26", + "experience_permissions_denied = 1UL << 27", +): + assert marker in scene_object, f"missing Experience event flag: {marker}" + +for marker in ( + "void experience_permissions(string agent_id);", + "void experience_permissions_denied(string agent_id, int reason);", +): + assert marker in event_handlers, f"missing YEngine Experience handler: {marker}" + +for marker in ( + "experience_permissions = 26", + "experience_permissions_denied = 27", +): + assert marker in event_codes, f"missing YEngine Experience event code: {marker}" + +for marker in ( + '{"experience_permissions", ScriptEventCode.experience_permissions}', + '{"experience_permissions_denied", ScriptEventCode.experience_permissions_denied}', +): + assert marker in event_map, f"missing YEngine Experience event map: {marker}" + +for marker in ( + "GroupsRead", + "GroupsManage", + "ExperiencesRead", + "ExperiencesManage", + "ExperiencesScript", +): + assert marker in security, f"missing chapter 11 scope: {marker}" + +for marker in ( + '"/api/v1/groups"', + '"/api/v1/experiences"', + "new NexGroupsApi(", + "new NexExperiencesApi(", +): + assert marker in connector, f"missing chapter 11 API registration: {marker}" + +assert "[NexExperiencesViewer]" in opensim_config +assert "NEXVERSE_EXPERIENCES_API_KEY" in opensim_config +assert "NexModerationStorePath" in robust_config +assert "NexModerationStorePath" in robust_hg_config +assert "[NexExperiences]" in robust_config +assert "[NexExperiences]" in robust_hg_config + +for marker in ( + "checked K/V retry semantics failed", + "missing-key update did not create", + "Experience persistence/reopen failed", + "Experience deletion cleanup failed", +): + assert marker in regression, f"missing Experience regression marker: {marker}" + +print("OpenGenesisLINK Chapter 11 NexGroups/NexExperiences contract: OK")