Files
opengenesislinkserver/addons/SysApi/SysApiResidentModules.cs
T
OpenGenesis (EULA) 6320338246 fix(g1): restore complete Sys.API citizen-rules authority with global alerts
Restore all production-proven SYS.API citizen-rules, policy and resident-management sources and assets, keep secure POST login plus authenticated NexBus global alerts, restore live OglLiveAccessPolicy and login-service/bridge dependencies; add fail-closed citizen policy regressions and full SYS.API smoke guard. Production restored, isolated build and HTTP smoke passed. NexVerse CI and source gates passed; Linux/Windows/ARM64 builds and ROBUST boot passed, artifact uploads blocked by GitHub quota.
2026-11-23 15:53:36 +01:00

169 lines
8.0 KiB
C#

// SPDX-License-Identifier: MPL-2.0
using System.Collections.Specialized;
using System.Globalization;
using System.Text.Json;
using System.Text.RegularExpressions;
using MySql.Data.MySqlClient;
using NexVerse.Server.Api;
using Nini.Config;
using OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Groups;
using OpenSim.Services.Interfaces;
using OpenSim.Server.Base;
namespace OpenGenesisLINK.SysApi;
// All user-resource routes are served exclusively after password-backed
// resident authentication. A portal machine token cannot impersonate a user.
public sealed partial class SysApiResidentModules
{
private readonly GroupsService? _groups;
private readonly IInventoryService? _inventory;
private readonly IFriendsService? _friends;
private readonly IInstantMessage? _im;
private readonly string? _dbConnection;
private readonly int _groupCreationCharge;
private readonly System.Collections.Concurrent.ConcurrentDictionary<UUID,
System.Collections.Concurrent.ConcurrentQueue<DateTimeOffset>> _messageQuota = new();
public SysApiResidentModules(IConfigSource config)
{
try { _groups=new GroupsService(config); } catch { /* optional service */ }
try { _inventory=Load<IInventoryService>(config,"InventoryService"); } catch {}
try { _friends=Load<IFriendsService>(config,"FriendsService"); } catch {}
try { _im=Load<IInstantMessage>(config,"HGInstantMessageService"); } catch {}
_groupCreationCharge=config.Configs["Economy"]?.GetInt("GroupCreationCharge",0)??0;
try
{
string connection=config.Configs["DatabaseService"]?.GetString("ConnectionString","")??"";
connection=Regex.Replace(connection,@"\$\{Environment\|([A-Za-z_][A-Za-z_0-9]*)\}",
m=>Environment.GetEnvironmentVariable(m.Groups[1].Value) ??
throw new InvalidOperationException("Database secret unavailable"));
if(connection.Length>0 && !connection.Contains("${",StringComparison.Ordinal))
_dbConnection=new MySqlConnectionStringBuilder(connection)
{
ConnectionTimeout=4,DefaultCommandTimeout=8,
MaximumPoolSize=5,PersistSecurityInfo=false
}.ConnectionString;
}
catch { /* no direct SQL services */ }
}
private static T? Load<T>(IConfigSource config,string section) where T:class
{
string name=config.Configs[section]?.GetString("LocalServiceModule","")??"";
return name.Length>0 ? ServerUtils.LoadPlugin<T>(name,new object[]{config}) : null;
}
private MySqlConnection OpenDb()
{
if(_dbConnection is null)throw new NotSupportedException("No MariaDB service");
var connection=new MySqlConnection(_dbConnection);connection.Open();return connection;
}
private static MySqlCommand Sql(MySqlConnection db,string statement,
params (string Name,object Value)[] args)
{
var command=new MySqlCommand(statement,db){CommandTimeout=8};
foreach(var (key,value) in args)command.Parameters.AddWithValue(key,value);
return command;
}
// This diagnostic never opens a citizen mailbox, inventory folder, group
// membership, or property. It only reports configured server capabilities.
public object ServiceStatus()
{
bool npcReady=NexNpcSnapshotBridge.TryOwned(Guid.NewGuid(),
out _,out long generation);
return new {
modules=new {
groupManagement=_groups is not null,
inventory=_inventory is not null,
offlineMessages=_dbConnection is not null,
messageArchive=_dbConnection is not null,
instantMessageDelivery=_im is not null && _friends is not null,
propertyListings=_dbConnection is not null,
propertyTransfer=false,
npcDirectory=npcReady
},
npc=new {
status=npcReady?"verified_snapshot_ready":"verified_snapshot_unavailable",
snapshotGeneration=npcReady?generation:(long?)null
},
authentication="single-portal-token-then-avatar-password",
apiRoles=false,apiScopes=false,
propertyTransferRequiresSimulator=true
};
}
public readonly record struct Result(int Status,object Payload);
private static Result Ok(object x)=>new(200,x);
private static Result Created(object x)=>new(201,x);
private static Result Invalid(string reason)=>new(400,new{error=reason});
private static Result Forbidden(string reason)=>new(403,new{error=reason});
private static Result Unavailable(string reason)=>new(503,new{error=reason});
private static Result NotFound()=>new(404,new{error="not_found"});
private static Result Conflict(string reason)=>new(409,new{error=reason});
private static string Str(JsonElement json,string property,int max=255)
{
if(json.ValueKind!=JsonValueKind.Object || !json.TryGetProperty(property,out var v) ||
v.ValueKind!=JsonValueKind.String)throw new ArgumentException("Invalid "+property);
var s=(v.GetString()??"").Trim();
if(s.Length>max || s.Any(char.IsControl))throw new ArgumentException("Invalid "+property);
return s;
}
private static bool Bool(JsonElement json,string property,bool fallback=false)=>
json.ValueKind==JsonValueKind.Object &&
json.TryGetProperty(property,out var x) && x.ValueKind is JsonValueKind.True or JsonValueKind.False
? x.GetBoolean() : fallback;
private static int Num(JsonElement json,string property,int fallback=0)
{
if(json.ValueKind!=JsonValueKind.Object || !json.TryGetProperty(property,out var x))
return fallback;
if(!x.TryGetInt32(out int i))throw new ArgumentException("Invalid "+property);
return i;
}
private static UUID Id(string text)
{
if(!UUID.TryParse(text,out UUID id)||id.IsZero())
throw new ArgumentException("Invalid UUID");
return id;
}
private static UUID Id(JsonElement json,string key)=>Id(Str(json,key,36));
private static int Limit(NameValueCollection query,int max=100,int def=50)
{
if(!int.TryParse(query["limit"]??def.ToString(CultureInfo.InvariantCulture),out int limit) ||
limit<1||limit>max)throw new ArgumentException("Invalid page size");
return limit;
}
private static long Cursor(NameValueCollection query)
{
if(!long.TryParse(query["after"]??"0",out long cursor)||cursor<0)
throw new ArgumentException("Invalid cursor");
return cursor;
}
public Result Execute(UserAccount actor,string method,string path,NameValueCollection query,
JsonElement body)
{
if(path=="/capabilities" && method=="GET")
return Ok(ServiceStatus());
if(path.StartsWith("/groups",StringComparison.Ordinal))
return Groups(actor,method,path["/groups".Length..],query,body);
if(path.StartsWith("/inventory",StringComparison.Ordinal))
return Inventory(actor,method,path["/inventory".Length..],query,body);
if(path.StartsWith("/offline-ims",StringComparison.Ordinal))
return OfflineIm(actor,method,path["/offline-ims".Length..],query,body);
if(path.StartsWith("/messages",StringComparison.Ordinal))
return Messages(actor,method,path["/messages".Length..],query,body);
if(path.StartsWith("/realestate",StringComparison.Ordinal))
return Property(actor,method,path["/realestate".Length..],query,body);
if(path=="/npcs" && method=="GET")
{
if(!NexNpcSnapshotBridge.TryOwned(actor.PrincipalID.Guid,
out var owned,out long revision))
return Unavailable("verified_npc_snapshots_not_ready");
return Ok(new { revision, npcs=owned.Take(500).Select(n=>new{
npcId=n.NpcId.ToString(),name=n.Name,regionName=n.RegionName
}).ToArray(),more=owned.Count>500 });
}
return NotFound();
}
}