diff --git a/.github/workflows/nexjast-ci.yml b/.github/workflows/nexjast-ci.yml index 451ee60e..ff764b0d 100644 --- a/.github/workflows/nexjast-ci.yml +++ b/.github/workflows/nexjast-ci.yml @@ -1329,6 +1329,12 @@ jobs: NEX_LEDGER_POSTGRESQL: "Host=127.0.0.1;Port=35432;Database=ogl_ledger_ci;Username=ledger;Password=ledgerpass;SSL Mode=Disable;" run: dotnet run --configuration Release --project tools/ci/NexLedgerSqlMatrixRegression/NexLedgerSqlMatrixRegression.csproj + - name: Run real MariaDB NexPortalIM archive regression + shell: bash + env: + NEX_PORTAL_IM_MARIADB: "Data Source=127.0.0.1;Port=33306;Database=ogl_ledger_ci;User ID=ledger;Password=ledgerpass;Old Guids=true;SslMode=None;" + run: dotnet run --configuration Release --project tools/ci/NexPortalImMariaDbRegression/NexPortalImMariaDbRegression.csproj + - name: Run real MariaDB NexGroups authorization and invitation regression shell: bash env: diff --git a/NexVerse/Server/Api/INexCitizenImStore.cs b/NexVerse/Server/Api/INexCitizenImStore.cs new file mode 100644 index 00000000..23db08ef --- /dev/null +++ b/NexVerse/Server/Api/INexCitizenImStore.cs @@ -0,0 +1,33 @@ +// SPDX-License-Identifier: MPL-2.0 +using System; +using System.Collections.Generic; + +namespace NexVerse.Server.Api +{ + // Unified opt-in API contract. The SQLite and MySQL/MariaDB implementations + // must enforce consent and per-owner access identically. + internal interface INexCitizenImStore + { + bool IsEnabled(Guid owner); + void SetEnabled(Guid owner, bool enabled); + void DeleteHistory(Guid owner); + bool Append(Guid eventId, Guid sender, Guid receiver, + string senderName, string message, string source); + List Read(Guid owner, long after, int limit, + Guid? peer = null); + List Conversations(Guid owner, int limit); + } + + internal sealed class NexCitizenImEntry + { + public long seq { get; set; } + public string event_id { get; set; } + public string from_agent_id { get; set; } + public string to_agent_id { get; set; } + public string peer_id { get; set; } + public string sender_name { get; set; } + public string message { get; set; } + public string source { get; set; } + public DateTimeOffset accepted_at { get; set; } + } +} diff --git a/NexVerse/Server/Api/NexApiDocsPage.cs b/NexVerse/Server/Api/NexApiDocsPage.cs index 22f2dfc3..f307b5a9 100644 --- a/NexVerse/Server/Api/NexApiDocsPage.cs +++ b/NexVerse/Server/Api/NexApiDocsPage.cs @@ -618,9 +618,11 @@ Archivprüfungen bleiben auch für freigegebene Importe aktiv.
+

Für die Stadtportal-Registrierung genügt dieser einzelne Schlüssel. Der Button ignoriert die Vorauswahl für Experiences und NexBus und verlangt keine NexBus-URLs. NEXVERSE_REGISTER_API_KEY gehört ausschließlich in die geschützte Umgebung des Stadtportal-Backends, niemals in Browser-JavaScript oder auf öffentliche Seiten.

Der Gruppenland-Button erstellt ausschließlich groups:read, unabhängig von den anderen Häkchen und ohne NexBus-URLs. NEXVERSE_GROUP_LAND_API_KEY gehört nur in die geschützte Environment-Datei der Simulatoren. Bereits aktive Schlüssel werden vor einer Neuausstellung geprüft.

+

NexPortalIM: Dieser HMAC-Schlüssel ist kein Maschinen-API-Key. Der separate Button erzeugt nach Admin-Prüfung einen kryptografisch zufälligen 48-Byte-Schlüssel direkt im Browser. Speichere NEX_PORTAL_IM_SECRET auf ROBUST und allen beteiligten Simulatoren mit identischem Wert. Er wird weder im Browser dauerhaft gespeichert noch an die World API übertragen; verlorene Werte lassen sich nicht wiederherstellen. Bei Rotation alle Hosts koordiniert umstellen.

Der NexBus-SharedKey ist kein World-API-Key. Er wird lokal im Browser per kryptografisch sicherem Zufall erzeugt und muss auf allen beteiligten Nodes identisch sein.

@@ -1694,7 +1696,7 @@ function secretBuildLines(values) { 'NEXVERSE_GROUP_LAND_API_KEY','NEXVERSE_EXPERIENCES_API_KEY', 'NEXVERSE_EXPERIENCES_VIEWER_PERMISSIONS_API_KEY', 'NEXVERSE_EXPERIENCES_VIEWER_MANAGE_API_KEY', - 'NEXVERSE_NEXBUS_SHARED_KEY','NEXVERSE_NEXBUS_PEER_URL','NEXVERSE_NEXBUS_PEERS']; + 'NEX_PORTAL_IM_SECRET','NEXVERSE_NEXBUS_SHARED_KEY','NEXVERSE_NEXBUS_PEER_URL','NEXVERSE_NEXBUS_PEERS']; $('secretOutput').value=names.filter(name=>Object.hasOwn(values,name)).map(name=>name+'='+values[name]).join('\n')+'\n'; $('secretCopy').disabled=!Object.keys(values).length; } @@ -1790,6 +1792,28 @@ async function secretAdminToken() { if(!token)throw new Error('Eine aktive Admin-Sitzung mit UserLevel 200 ist erforderlich.'); return token; } +async function secretGeneratePortalIm() { + if(secretIssuePending)return; + if(!window.isSecureContext) { + secretStatus('HMAC-Schlüssel dürfen ausschließlich unter HTTPS generiert werden.',false); + return; + } + secretIssuePending=true; + $('secretGeneratePortalIm').disabled=true; + try { + const token=await secretAdminToken(); + await secretJson('/api/v1/auth/admin/session',{ + headers:{'Authorization':'Bearer '+token}}); + if(!window.confirm('Neuen NexPortalIM-Schlüssel erstellen? Ein bestehender Schlüssel wird NICHT automatisch auf ROBUST oder Simulatoren umgestellt.'))return; + secretBuildLines({NEX_PORTAL_IM_SECRET:secretRandomHmac()}); + secretStatus('Neuen NexPortalIM-HMAC-Schlüssel erzeugt. Jetzt sicher auf ROBUST und allen Simulatoren mit identischem Wert eintragen.',true); + }catch(error) { + secretStatus('NexPortalIM-Schlüssel nicht erzeugt: '+String(error.message||error),false); + }finally { + secretIssuePending=false; + $('secretGeneratePortalIm').disabled=false; + } +} let secretIssuePending=false; async function secretGenerate(onlyRegistration=false, onlyGroupLand=false) { if(secretIssuePending)return; @@ -1979,6 +2003,7 @@ $('adminLoginTotp').addEventListener('keydown',event=>{if(event.key==='Enter'){e $('secretGenerate').addEventListener('click',()=>secretGenerate()); $('secretGenerateRegistration').addEventListener('click',()=>secretGenerate(true)); $('secretGenerateGroupLand').addEventListener('click',()=>secretGenerate(false,true)); +$('secretGeneratePortalIm').addEventListener('click',secretGeneratePortalIm); $('secretCopy').addEventListener('click',secretCopy); $('secretClear').addEventListener('click',secretClear); $('secretLoadKeys').addEventListener('click',secretLoadKeys); diff --git a/NexVerse/Server/Api/NexCitizenImApi.cs b/NexVerse/Server/Api/NexCitizenImApi.cs index d64e35c7..d29b9f66 100644 --- a/NexVerse/Server/Api/NexCitizenImApi.cs +++ b/NexVerse/Server/Api/NexCitizenImApi.cs @@ -31,13 +31,13 @@ namespace NexVerse.Server.Api private readonly Func m_InstantMessageResolver; private readonly object m_InstantMessageSync = new object(); private readonly INexAuditSink m_Audit; - private readonly NexCitizenImStore m_Store; + private readonly INexCitizenImStore m_Store; private readonly ConcurrentDictionary> m_SendWindows = new ConcurrentDictionary>(); public NexCitizenImApi(IUserAccountService accounts, IFriendsService friends, NexApiAuthenticator auth, IInstantMessage instantMessages, - INexAuditSink audit, NexCitizenImStore store = null, + INexAuditSink audit, INexCitizenImStore store = null, Func instantMessageResolver = null) { m_Accounts = accounts ?? throw new ArgumentNullException(nameof(accounts)); diff --git a/NexVerse/Server/Api/NexCitizenImIngress.cs b/NexVerse/Server/Api/NexCitizenImIngress.cs index abc6f3a2..6d075dc3 100644 --- a/NexVerse/Server/Api/NexCitizenImIngress.cs +++ b/NexVerse/Server/Api/NexCitizenImIngress.cs @@ -19,12 +19,12 @@ namespace NexVerse.Server.Api internal sealed class NexCitizenImIngress { private readonly byte[] m_Key; - private readonly NexCitizenImStore m_Store; + private readonly INexCitizenImStore m_Store; private readonly IUserAccountService m_Accounts; private readonly IFriendsService m_Friends; private const int MaxBody = 8192; - internal NexCitizenImIngress(string sharedSecret, NexCitizenImStore store, + internal NexCitizenImIngress(string sharedSecret, INexCitizenImStore store, IUserAccountService accounts, IFriendsService friends) { if (Encoding.UTF8.GetByteCount(sharedSecret ?? "") < 32) diff --git a/NexVerse/Server/Api/NexCitizenImMySqlStore.cs b/NexVerse/Server/Api/NexCitizenImMySqlStore.cs new file mode 100644 index 00000000..7ba72ad6 --- /dev/null +++ b/NexVerse/Server/Api/NexCitizenImMySqlStore.cs @@ -0,0 +1,238 @@ +// SPDX-License-Identifier: MPL-2.0 +using System; +using System.Collections.Generic; +using System.Data; +using System.Data.Common; +using MySql.Data.MySqlClient; + +namespace NexVerse.Server.Api +{ + /// + /// Consent-gated portal archive in the grid's existing MySQL/MariaDB + /// database. Separate tables: never alter existing OpenSim IM/offline IM. + /// Parameterized queries, deduplicated events, transactional opt-out. + /// + internal sealed class NexCitizenImMySqlStore : INexCitizenImStore + { + private readonly Func m_Connect; + private readonly int m_RetentionDays; + private const int MaxEntriesPerOwner = 10000; + + internal NexCitizenImMySqlStore(string provider, string connectionString, int retentionDays) + { + if (string.IsNullOrWhiteSpace(provider) || + (provider.IndexOf("MySQL", StringComparison.OrdinalIgnoreCase) < 0 && + provider.IndexOf("MariaDB", StringComparison.OrdinalIgnoreCase) < 0)) + throw new NotSupportedException("Portal IM MySql backend requires OpenSim.Data.MySQL.dll (MariaDB/MySQL)."); + if (string.IsNullOrWhiteSpace(connectionString)) + throw new ArgumentException("Existing grid MariaDB ConnectionString is required."); + m_Connect = () => new MySqlConnection(connectionString); + m_RetentionDays = Math.Clamp(retentionDays, 7, 365); + + using DbConnection db = Open(); + Execute(db, null, @"CREATE TABLE IF NOT EXISTS portal_im_settings ( + owner CHAR(36) NOT NULL PRIMARY KEY, + enabled TINYINT(1) NOT NULL DEFAULT 0, + updated_at BIGINT NOT NULL + ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4"); + Execute(db, null, @"CREATE TABLE IF NOT EXISTS portal_im_entries ( + seq BIGINT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY, + event_id CHAR(36) NOT NULL, + owner CHAR(36) NOT NULL, + from_agent CHAR(36) NOT NULL, + to_agent CHAR(36) NOT NULL, + peer CHAR(36) NOT NULL, + sender_name VARCHAR(160) NOT NULL, + body TEXT NOT NULL, + source VARCHAR(16) NOT NULL, + accepted_at BIGINT NOT NULL, + UNIQUE KEY uq_portal_im_owner_event (owner,event_id), + KEY ix_portal_im_owner_seq (owner,seq), + KEY ix_portal_im_owner_peer_seq (owner,peer,seq), + KEY ix_portal_im_expiry (accepted_at) + ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4"); + } + + private DbConnection Open() + { + DbConnection db = m_Connect(); + db.Open(); + return db; + } + + private static DbCommand Command(DbConnection db, DbTransaction tx, + string sql, params (string Name, object Value)[] parameters) + { + DbCommand cmd = db.CreateCommand(); + cmd.Transaction = tx; + cmd.CommandText = sql; + foreach ((string name, object value) in parameters) + { + DbParameter arg = cmd.CreateParameter(); + arg.ParameterName = name; + arg.Value = value ?? DBNull.Value; + cmd.Parameters.Add(arg); + } + return cmd; + } + + private static int Execute(DbConnection db, DbTransaction tx, + string sql, params (string Name, object Value)[] parameters) + { + using DbCommand cmd = Command(db, tx, sql, parameters); + return cmd.ExecuteNonQuery(); + } + + private static string Id(Guid value) => value.ToString("D"); + + public bool IsEnabled(Guid owner) + { + using DbConnection db = Open(); + using DbCommand cmd = Command(db, null, + "SELECT enabled FROM portal_im_settings WHERE owner=@owner", + ("@owner", Id(owner))); + return Convert.ToInt32(cmd.ExecuteScalar() ?? 0) == 1; + } + + public void SetEnabled(Guid owner, bool enabled) + { + using DbConnection db = Open(); + using DbTransaction tx = db.BeginTransaction(); + Execute(db, tx, @"INSERT INTO portal_im_settings (owner,enabled,updated_at) + VALUES (@owner,@enabled,@now) + ON DUPLICATE KEY UPDATE enabled=VALUES(enabled),updated_at=VALUES(updated_at)", + ("@owner", Id(owner)), ("@enabled", enabled ? 1 : 0), + ("@now", DateTimeOffset.UtcNow.ToUnixTimeSeconds())); + if (!enabled) + DeleteOwner(db, tx, owner); + tx.Commit(); + } + + private static void DeleteOwner(DbConnection db, DbTransaction tx, Guid owner) + => Execute(db, tx, + "DELETE FROM portal_im_entries WHERE owner=@owner", + ("@owner", Id(owner))); + + public void DeleteHistory(Guid owner) + { + using DbConnection db = Open(); + using DbTransaction tx = db.BeginTransaction(); + DeleteOwner(db, tx, owner); + tx.Commit(); + } + + public bool Append(Guid eventId, Guid sender, Guid receiver, + string senderName, string message, string source) + { + if (eventId == Guid.Empty || sender == Guid.Empty || + receiver == Guid.Empty || sender == receiver || + string.IsNullOrWhiteSpace(message)) + return false; + + using DbConnection db = Open(); + using DbTransaction tx = db.BeginTransaction(); + long now = DateTimeOffset.UtcNow.ToUnixTimeSeconds(); + bool written = false; + Guid[] participants = { sender, receiver }; + foreach (Guid owner in participants) + { + // The consent check lives in the INSERT itself, not a + // preceding app-side read, preventing archived non-opt-in IMs. + written |= Execute(db, tx, @"INSERT IGNORE INTO portal_im_entries + (event_id,owner,from_agent,to_agent,peer,sender_name,body,source,accepted_at) + SELECT @event,@owner,@from,@to,@peer,@name,@body,@source,@now + FROM portal_im_settings + WHERE owner=@owner AND enabled=1", + ("@event", Id(eventId)), ("@owner", Id(owner)), + ("@from", Id(sender)), ("@to", Id(receiver)), + ("@peer", Id(owner == sender ? receiver : sender)), + ("@name", (senderName ?? string.Empty).Length > 160 + ? senderName.Substring(0, 160) : senderName ?? string.Empty), + ("@body", message), ("@source", source ?? string.Empty), + ("@now", now)) > 0; + } + + Execute(db, tx, "DELETE FROM portal_im_entries WHERE accepted_at < @cutoff", + ("@cutoff", now - m_RetentionDays * 86400L)); + + foreach (Guid owner in participants) + { + // Fetch cutoff before deletion. Avoid self-referencing MySQL + // DELETE subqueries (ERROR 1093) and maintain the 10k cap. + object cutoff; + using (DbCommand limit = Command(db, tx, + "SELECT seq FROM portal_im_entries WHERE owner=@owner " + + "ORDER BY seq DESC LIMIT 1 OFFSET 9999", + ("@owner", Id(owner)))) + cutoff = limit.ExecuteScalar(); + if (cutoff != null && cutoff != DBNull.Value) + Execute(db, tx, + "DELETE FROM portal_im_entries WHERE owner=@owner AND seq < @seq", + ("@owner", Id(owner)), ("@seq", Convert.ToInt64(cutoff))); + } + tx.Commit(); + return written; + } + + public List Read(Guid owner, long after, int limit, + Guid? peer = null) + { + List result = new List(); + using DbConnection db = Open(); + using DbCommand cmd = Command(db, null, + @"SELECT seq,event_id,from_agent,to_agent,peer,sender_name, + body,source,accepted_at FROM portal_im_entries + WHERE owner=@owner AND seq>@after" + + (peer.HasValue ? " AND peer=@peer" : "") + + " ORDER BY seq ASC LIMIT @limit", + ("@owner", Id(owner)), + ("@after", Math.Max(0, after)), + ("@limit", Math.Clamp(limit, 1, 100))); + if (peer.HasValue) + { + DbParameter par = cmd.CreateParameter(); + par.ParameterName = "@peer"; + par.Value = Id(peer.Value); + cmd.Parameters.Add(par); + } + using DbDataReader reader = cmd.ExecuteReader(); + while (reader.Read()) + result.Add(new NexCitizenImEntry + { + seq = Convert.ToInt64(reader.GetValue(0)), + event_id = reader.GetString(1), + from_agent_id = reader.GetString(2), + to_agent_id = reader.GetString(3), + peer_id = reader.GetString(4), + sender_name = reader.GetString(5), + message = reader.GetString(6), + source = reader.GetString(7), + accepted_at = DateTimeOffset.FromUnixTimeSeconds( + Convert.ToInt64(reader.GetValue(8))) + }); + return result; + } + + public List Conversations(Guid owner, int limit) + { + List result = new List(); + using DbConnection db = Open(); + using DbCommand cmd = Command(db, null, + @"SELECT e.peer,e.seq,e.accepted_at FROM portal_im_entries e + JOIN (SELECT peer,MAX(seq) seq FROM portal_im_entries + WHERE owner=@owner GROUP BY peer) latest ON latest.seq=e.seq + WHERE e.owner=@owner ORDER BY e.seq DESC LIMIT @limit", + ("@owner", Id(owner)), ("@limit", Math.Clamp(limit, 1, 100))); + using DbDataReader reader = cmd.ExecuteReader(); + while (reader.Read()) + result.Add(new + { + peer_id = reader.GetString(0), + last_seq = Convert.ToInt64(reader.GetValue(1)), + last_message_at = DateTimeOffset.FromUnixTimeSeconds( + Convert.ToInt64(reader.GetValue(2))) + }); + return result; + } + } +} diff --git a/NexVerse/Server/Api/NexCitizenImStore.cs b/NexVerse/Server/Api/NexCitizenImStore.cs index f16a4f3c..0e471e5b 100644 --- a/NexVerse/Server/Api/NexCitizenImStore.cs +++ b/NexVerse/Server/Api/NexCitizenImStore.cs @@ -10,7 +10,7 @@ namespace NexVerse.Server.Api /// Separate, opt-in portal transcript store. This is NOT the OpenSim offline-IM /// database. Each message is recorded only for opted-in local participants. /// - internal sealed class NexCitizenImStore + internal sealed class NexCitizenImStore : INexCitizenImStore { private readonly object m_Sync = new object(); private readonly string m_ConnectionString; @@ -72,7 +72,7 @@ namespace NexVerse.Server.Api private static void Add(SqliteCommand cmd, string name, object value) => cmd.Parameters.AddWithValue(name, value); - internal bool IsEnabled(Guid owner) + public bool IsEnabled(Guid owner) { lock (m_Sync) { @@ -84,7 +84,7 @@ namespace NexVerse.Server.Api } } - internal void SetEnabled(Guid owner, bool enabled) + public void SetEnabled(Guid owner, bool enabled) { lock (m_Sync) { @@ -116,7 +116,7 @@ namespace NexVerse.Server.Api cmd.ExecuteNonQuery(); } - internal void DeleteHistory(Guid owner) + public void DeleteHistory(Guid owner) { lock (m_Sync) { @@ -127,7 +127,7 @@ namespace NexVerse.Server.Api } } - internal bool Append( + public bool Append( Guid eventId, Guid sender, Guid receiver, string senderName, string message, string source) { @@ -186,7 +186,7 @@ namespace NexVerse.Server.Api } } - internal List Read(Guid owner, long after, int limit, Guid? peer = null) + public List Read(Guid owner, long after, int limit, Guid? peer = null) { List entries = new List(); lock (m_Sync) @@ -219,7 +219,7 @@ namespace NexVerse.Server.Api return entries; } - internal List Conversations(Guid owner, int limit) + public List Conversations(Guid owner, int limit) { List entries = new List(); lock (m_Sync) @@ -245,16 +245,4 @@ namespace NexVerse.Server.Api } } - internal sealed class NexCitizenImEntry - { - public long seq { get; set; } - public string event_id { get; set; } - public string from_agent_id { get; set; } - public string to_agent_id { get; set; } - public string peer_id { get; set; } - public string sender_name { get; set; } - public string message { get; set; } - public string source { get; set; } - public DateTimeOffset accepted_at { get; set; } - } } diff --git a/NexVerse/Server/Api/NexVerseWorldApiConnector.cs b/NexVerse/Server/Api/NexVerseWorldApiConnector.cs index eedb404a..cc5ca57b 100644 --- a/NexVerse/Server/Api/NexVerseWorldApiConnector.cs +++ b/NexVerse/Server/Api/NexVerseWorldApiConnector.cs @@ -1010,27 +1010,75 @@ namespace NexVerse.Server.Api IInstantMessage citizenInstantMessages = LoadOptionalService(config, "HGInstantMessageService"); - NexCitizenImStore citizenImStore = null; + INexCitizenImStore citizenImStore = null; IConfig portalImConfig = config.Configs["NexPortalIM"]; if (portalImConfig != null && portalImConfig.GetBoolean("Enabled", false)) { + // Archive transport credentials are NOT World API + // machine tokens. Both ROBUST and simulators need the + // identical 32+ byte HMAC secret in the process env. string sharedImSecret = Environment.GetEnvironmentVariable("NEX_PORTAL_IM_SECRET"); if (string.IsNullOrWhiteSpace(sharedImSecret)) sharedImSecret = portalImConfig.GetString("SharedSecret", ""); - if (System.Text.Encoding.UTF8.GetByteCount(sharedImSecret) < 32) - throw new InvalidOperationException( - "[NEX-PORTAL-IM]: Enabled archive requires a 32-byte shared secret."); - citizenImStore = new NexCitizenImStore( - portalImConfig.GetString("StorePath", "data/nexverse-portal-im.sqlite"), - portalImConfig.GetInt("RetentionDays", 30)); - NexCitizenImIngress citizenImIngress = new NexCitizenImIngress( - sharedImSecret, citizenImStore, userAccounts, friendsService); - server.AddSimpleStreamHandler( - new SimpleStreamHandler("/internal/nexportal/im/v1", - citizenImIngress.Handle, "NexVerse Simulator Portal IM Ingest"), - true); - m_Log.Info("[NEX-PORTAL-IM]: Opt-in portal conversation archive enabled."); + if (System.Text.Encoding.UTF8.GetByteCount(sharedImSecret ?? "") < 32 || + (sharedImSecret ?? "").Contains("${Environment|", StringComparison.Ordinal)) + { + // A missing optional archive secret must never prevent + // World API, login, or the rest of ROBUST from starting. + m_Log.Error("[NEX-PORTAL-IM]: Archive requested but NEX_PORTAL_IM_SECRET " + + "is missing or shorter than 32 UTF-8 bytes. Archive disabled until provisioned."); + } + else + { + try + { + string backend = portalImConfig.GetString( + "StoreBackend", "SQLite").Trim(); + int retention = portalImConfig.GetInt("RetentionDays", 30); + if (backend.Equals("MariaDB", StringComparison.OrdinalIgnoreCase) || + backend.Equals("MySQL", StringComparison.OrdinalIgnoreCase)) + { + // Empty overrides inherit the authoritative + // [DatabaseService] connection used by ROBUST. + string provider = portalImConfig.GetString( + "StorageProvider", "").Trim(); + if (provider.Length == 0) + provider = databaseStorageProvider; + string connection = portalImConfig.GetString( + "ConnectionString", "").Trim(); + if (connection.Length == 0) + connection = databaseConnectionString; + citizenImStore = new NexCitizenImMySqlStore( + provider, connection, retention); + } + else if (backend.Equals("SQLite", StringComparison.OrdinalIgnoreCase)) + { + citizenImStore = new NexCitizenImStore( + portalImConfig.GetString("StorePath", + "data/nexverse-portal-im.sqlite"), retention); + } + else + throw new NotSupportedException( + "[NEX-PORTAL-IM]: Unsupported StoreBackend (MariaDB/MySQL or SQLite required)."); + + NexCitizenImIngress citizenImIngress = new NexCitizenImIngress( + sharedImSecret, citizenImStore, userAccounts, friendsService); + server.AddSimpleStreamHandler( + new SimpleStreamHandler("/internal/nexportal/im/v1", + citizenImIngress.Handle, "NexVerse Simulator Portal IM Ingest"), + true); + m_Log.InfoFormat( + "[NEX-PORTAL-IM]: Opt-in conversation archive enabled using {0}.", + backend); + } + catch (Exception e) + { + citizenImStore = null; + m_Log.Error("[NEX-PORTAL-IM]: Archive initialization failed; " + + "World API remains online and archive requests report unavailable.", e); + } + } } NexCitizenImApi citizenImApi = new NexCitizenImApi(userAccounts, friendsService, authenticator, diff --git a/OpenSim/Region/CoreModules/Avatar/InstantMessage/NexCitizenImForwarder.cs b/OpenSim/Region/CoreModules/Avatar/InstantMessage/NexCitizenImForwarder.cs index 841a8379..df45bff0 100644 --- a/OpenSim/Region/CoreModules/Avatar/InstantMessage/NexCitizenImForwarder.cs +++ b/OpenSim/Region/CoreModules/Avatar/InstantMessage/NexCitizenImForwarder.cs @@ -47,7 +47,8 @@ namespace OpenSim.Region.CoreModules.Avatar.InstantMessage (url.Scheme != Uri.UriSchemeHttps && !(url.Scheme == Uri.UriSchemeHttp && url.IsLoopback)) || url.AbsolutePath != "/internal/nexportal/im/v1" || - Encoding.UTF8.GetByteCount(secret) < 32) + Encoding.UTF8.GetByteCount(secret ?? "") < 32 || + (secret ?? "").Contains("${Environment|", StringComparison.Ordinal)) { m_Log.Warn("[NEX-PORTAL-IM]: Forwarding disabled: require HTTPS/loopback URL and 32-byte secret."); return null; diff --git a/bin/OpenSim.ini b/bin/OpenSim.ini index 511137ea..166a8e0f 100644 --- a/bin/OpenSim.ini +++ b/bin/OpenSim.ini @@ -105,8 +105,8 @@ Cap_SetDisplayName = "localhost" [SimulatorFeatures] - SearchServerURI = "https://world.stadt-nexverse.de/search?q=[QUERY]&type=[TYPE]&maturity=[MATURITY]" - DestinationGuideURI = "https://world.stadt-nexverse.de/destinations" + SearchServerURI = "https://stadt-nexverse.de/service/search?q=[QUERY]&type=[TYPE]&maturity=[MATURITY]" + DestinationGuideURI = "https://stadt-nexverse.de/service/destination" [Chat] @@ -154,7 +154,7 @@ [NexDiscoveryViewer] Enabled = true LegacyFirestormCompatibility = true - WorldApiBaseUrl = "${Const|BaseURL}:${Const|PublicPort}" + WorldApiBaseUrl = "https://world.stadt-nexverse.de" RequestTimeoutMilliseconds = 3000 [NexExperiencesViewer] @@ -197,11 +197,11 @@ AppDomainLoading = false [NexPortalIM] - ; Forward authenticated viewer IMs to ROBUST only after portal chat - ; archival has been provisioned on ROBUST. Must use the SAME secret. - ; Loopback only works when ROBUST runs on this simulator's host. - Enabled = false - IngestUrl = "http://127.0.0.1/internal/nexportal/im/v1" + ; HMAC-signed forwarder: must match ROBUST NEX_PORTAL_IM_SECRET. + ; Reverse proxy must forward this internal path to ROBUST, + ; restricted to trusted simulator source IPs. + Enabled = true + IngestUrl = "https://world.stadt-nexverse.de/internal/nexportal/im/v1" SharedSecret = "${Environment|NEX_PORTAL_IM_SECRET}" [OSSL] diff --git a/bin/OpenSim.ini.example b/bin/OpenSim.ini.example index f62f0d6d..bac4548d 100644 --- a/bin/OpenSim.ini.example +++ b/bin/OpenSim.ini.example @@ -101,8 +101,8 @@ Cap_SetDisplayName = "localhost" [SimulatorFeatures] - SearchServerURI = "https://world.stadt-nexverse.de/search?q=[QUERY]&type=[TYPE]&maturity=[MATURITY]" - DestinationGuideURI = "https://world.stadt-nexverse.de/destinations" + SearchServerURI = "https://stadt-nexverse.de/service/search?q=[QUERY]&type=[TYPE]&maturity=[MATURITY]" + DestinationGuideURI = "https://stadt-nexverse.de/service/destination" [Chat] @@ -197,7 +197,8 @@ [NexPortalIM] Enabled = false - IngestUrl = "http://127.0.0.1/internal/nexportal/im/v1" + ; When ROBUST and Simulator are separate hosts use the protected HTTPS proxy path. + IngestUrl = "https://world.stadt-nexverse.de/internal/nexportal/im/v1" SharedSecret = "${Environment|NEX_PORTAL_IM_SECRET}" [OSSL] diff --git a/bin/Robust.HG.ini b/bin/Robust.HG.ini index 4afc194c..8c38e5ec 100644 --- a/bin/Robust.HG.ini +++ b/bin/Robust.HG.ini @@ -691,11 +691,15 @@ NodeStaleAfterSeconds = 90 [NexPortalIM] - ; Optional per-resident portal chat history; do not enable before - ; provisioning the SAME 32+-byte HMAC secret in ROBUST and simulators. - ; The store is a private, writable SQLite database on the ROBUST host. - Enabled = false - StorePath = "data/nexverse-portal-im.sqlite" + ; Optional private portal IM archive in the existing [DatabaseService] + ; MySQL/MariaDB schema; tables created automatically at startup. + ; Missing 32+-byte NEX_PORTAL_IM_SECRET disables ONLY the archive, + ; not the World API. Configure the SAME key on all simulators. + Enabled = true + StoreBackend = "MariaDB" + ; Empty overrides inherit the authoritative [DatabaseService] values. + StorageProvider = "" + ConnectionString = "" RetentionDays = 30 SharedSecret = "${Environment|NEX_PORTAL_IM_SECRET}" diff --git a/bin/Robust.HG.ini.example b/bin/Robust.HG.ini.example index 4ac18b11..9e20c22b 100644 --- a/bin/Robust.HG.ini.example +++ b/bin/Robust.HG.ini.example @@ -730,7 +730,11 @@ ; Opt-in web chat history and authenticated simulator -> Robust ingestion. ; The active Simulator must use the same NEX_PORTAL_IM_SECRET. Enabled = false - StorePath = "data/nexverse-portal-im.sqlite" + ; Set true after provisioning one shared 32+-byte HMAC secret. + ; MariaDB uses the existing [DatabaseService] connection. + StoreBackend = "MariaDB" + StorageProvider = "" + ConnectionString = "" RetentionDays = 30 SharedSecret = "${Environment|NEX_PORTAL_IM_SECRET}" diff --git a/doc/NexVerse/PORTAL_IM_CHAT.md b/doc/NexVerse/PORTAL_IM_CHAT.md index 48e6f3f0..6f78f4af 100644 --- a/doc/NexVerse/PORTAL_IM_CHAT.md +++ b/doc/NexVerse/PORTAL_IM_CHAT.md @@ -176,9 +176,11 @@ Datenbankproblemen meldet dagegen `[NEX-PORTAL-IM]`. Keine automatischen Datenbankneuanlagen durch einen bloßen Lesezugriff außerhalb des konfigurierten Store-Starts. -Die produktive `bin/Robust.HG.ini` und `bin/OpenSim.ini` enthalten -nun beide die `[NexPortalIM]`-Sektion, aus Sicherheitsgründen zunächst -`Enabled = false`. Für die tatsächliche Chat-Nutzung: +Die aktive `bin/Robust.HG.ini` und `bin/OpenSim.ini` enthalten +nun beide `[NexPortalIM] Enabled = true`. ROBUST nutzt die vorhandene +MariaDB-Grid-Datenbank (keine separate SQLite-Datei). Fehlt der mindestens +32 Byte lange gemeinsame HMAC-Schlüssel, **bleibt die World API online**, +aber das Archiv ist explizit `unavailable`. Für die tatsächliche Chat-Nutzung: 1. EINE geheime, zufällige Schlüsselzeichenfolge mit mindestens 32 UTF-8-Bytes erzeugen, z. B. `openssl rand -hex 32`. @@ -187,19 +189,23 @@ nun beide die `[NexPortalIM]`-Sektion, aus Sicherheitsgründen zunächst Secret-Quelle) auf ROBUST **und jedem beteiligten Simulator** mit demselben Wert hinterlegen. Bereits existierende Secrets nicht ohne Migrationsplanung ersetzen. -2. In `bin/Robust.HG.ini` `[NexPortalIM] Enabled = true` - setzen. Der ROBUST-Dienstbenutzer muss den Ordner - `data/` sowie `data/nexverse-portal-im.sqlite` - schreibend erreichen; `StorePath` wird relativ zum - **Arbeitsverzeichnis** des ROBUST-Prozesses aufgelöst. -3. Für Firestorm-Empfang in jedem beteiligten Simulator - `bin/OpenSim.ini` auf `[NexPortalIM] Enabled = true` - stellen. `IngestUrl` muss auf den geschützten ROBUST- - Endpunkt `/internal/nexportal/im/v1` zeigen. Loopback - `127.0.0.1` nur verwenden, wenn ROBUST tatsächlich auf - **demselben Host** läuft; andernfalls einen privaten, - abgesicherten HTTPS-Endpunkt nutzen und den Ingest-Zugang - für Fremde sperren. +2. In `bin/Robust.HG.ini` ist `[NexPortalIM] Enabled = true` + bereits gesetzt. `StoreBackend = "MariaDB"` übernimmt automatisch + die **bestehende** `[DatabaseService]`-Verbindung. Beim ersten Start + werden `portal_im_settings` und `portal_im_entries` mit + Unique-Constraint und Indizes angelegt. Es werden **keine** + bestehenden OpenSim-Tabellen verändert. Der Datenbanknutzer benötigt + dafür `CREATE` (oder der Administrator legt das Schema vorab an). +3. Für Firestorm-Empfang verwendet `bin/OpenSim.ini` bereits + `[NexPortalIM] Enabled = true` und + `IngestUrl = "https://world.stadt-nexverse.de/internal/nexportal/im/v1"`. + **Betriebsvoraussetzung:** Reverse Proxy für diesen exakten Pfad + zum World-API/ROBUST-Listener konfigurieren und per Firewall/IP-Allowlist + ausschließlich Simulator-Hosts zulassen. HMAC-Signatur validiert + außerdem alle übertragenen Nachrichten. Falls ROBUST und Simulator + wirklich auf demselben Host laufen, kann alternativ der zutreffende + `http://127.0.0.1:/internal/nexportal/im/v1` verwendet + werden, aber niemals Loopback auf einem fremden Host. 4. ROBUST und betroffene Simulatoren vollständig neu starten. `GET /api/v1/messages/settings` mit einem lokalen `relationships:read`-Token prüfen (`available: true`, @@ -219,14 +225,16 @@ Die Beispielsektionen liegen in `bin/Robust.HG.ini.example` und `bin/Robust.ini. ```ini [NexPortalIM] Enabled = true - StorePath = "data/nexverse-portal-im.sqlite" + StoreBackend = "MariaDB" + StorageProvider = "" + ConnectionString = "" RetentionDays = 30 SharedSecret = "${Environment|NEX_PORTAL_IM_SECRET}" ``` -Generiere **einen neuen zufälligen Wert mit mindestens 32 Bytes** als Umgebungsvariable `NEX_PORTAL_IM_SECRET` und verwende **denselben** Wert in Robust und allen beteiligten Simulatorprozessen. Nicht mit OAuth-, OIDC- oder NexBus-Schlüsseln gleichsetzen und den Wert weder committen noch protokollieren. Der Datenbankpfad muss mit restriktiven Dateirechten für den Robust-Prozess beschreibbar sein. +**Schlüssel über die World API generieren:** In `https://world.stadt-nexverse.de/api/v1/docs` als Administrator anmelden, dann `Schlüssel & Einrichtung` → `NexPortalIM-HMAC-Schlüssel erstellen`. Der Button prüft die Admin-Sitzung, erzeugt mit `crypto.getRandomValues` 48 kryptografisch zufällige Bytes und zeigt ausschließlich `NEX_PORTAL_IM_SECRET=` zum Kopieren. Der Wert wird **nicht** in der World-API-Datenbank gespeichert. Er muss identisch in den geschützten `/etc/nexverse/nexverse.env`-Dateien von ROBUST und **allen** Simulatoren liegen (`chmod 600`); danach die Dienste neu starten. Vorhandene Schlüssel nicht ungeplant rotieren. Keine Auth-Tokens/Schlüssel ins Git-Repository committen. -Der separate SQLite-Store ist allein für den Portalchat. Er führt keine Migrationen an den bestehenden OpenSim-Nutzerdatenbanken durch. Datensicherung und Löschrichtlinie separat festlegen. +Die Portal-IM-Tabellen liegen jetzt getrennt von den bestehenden OpenSim-IM-Tabellen im konfigurierten MariaDB-Grid. Ein Backup muss `portal_im_settings` und `portal_im_entries` einschließen; Zugangskontrolle, Opt-in und Löschfristen gelten unverändert. Ein vorher benutztes `data/nexverse-portal-im.sqlite` wird **nicht automatisch** nach MariaDB migriert. Bei existierender produktiver Historie ist eine kontrollierte Migration vor dem Umschalten erforderlich. ## OpenSim-Simulator-Konfiguration @@ -235,7 +243,7 @@ In `bin/OpenSim.ini.example`: ```ini [NexPortalIM] Enabled = true - IngestUrl = "http://127.0.0.1/internal/nexportal/im/v1" + IngestUrl = "https://world.stadt-nexverse.de/internal/nexportal/im/v1" SharedSecret = "${Environment|NEX_PORTAL_IM_SECRET}" ``` diff --git a/prebuild.xml b/prebuild.xml index 1d39451c..e23fa17f 100644 --- a/prebuild.xml +++ b/prebuild.xml @@ -2012,6 +2012,7 @@ + diff --git a/tools/ci/NexPortalImMariaDbRegression/NexPortalImMariaDbRegression.csproj b/tools/ci/NexPortalImMariaDbRegression/NexPortalImMariaDbRegression.csproj new file mode 100644 index 00000000..e8e856b9 --- /dev/null +++ b/tools/ci/NexPortalImMariaDbRegression/NexPortalImMariaDbRegression.csproj @@ -0,0 +1,18 @@ + + + Exe + net8.0 + disable + enable + + + + + + ../../../bin/MySql.Data.dll + True + + + + + diff --git a/tools/ci/NexPortalImMariaDbRegression/Program.cs b/tools/ci/NexPortalImMariaDbRegression/Program.cs new file mode 100644 index 00000000..67fe3792 --- /dev/null +++ b/tools/ci/NexPortalImMariaDbRegression/Program.cs @@ -0,0 +1,74 @@ +// SPDX-License-Identifier: MPL-2.0 +// Real MariaDB opt-in archive regression in the existing grid database. +using System; +using NexVerse.Server.Api; + +string connection = Environment.GetEnvironmentVariable("NEX_PORTAL_IM_MARIADB"); +if (string.IsNullOrWhiteSpace(connection)) + throw new InvalidOperationException("NEX_PORTAL_IM_MARIADB is required"); +INexCitizenImStore store = new NexCitizenImMySqlStore( + "OpenSim.Data.MySQL.dll", connection, 30); +Guid alice = Guid.NewGuid(), bob = Guid.NewGuid(); +Guid event1 = Guid.NewGuid(), event2 = Guid.NewGuid(); +try +{ + Check(!store.IsEnabled(alice) && !store.IsEnabled(bob), + "default must be opted out"); + Check(!store.Append(event1, alice, bob, "Alice", "unconsented", "portal"), + "no archive before explicit consent"); + Check(store.Read(alice, 0, 20).Count == 0 && + store.Read(bob, 0, 20).Count == 0, + "unconsented data persisted"); + + store.SetEnabled(alice, true); + Check(store.IsEnabled(alice), "Alice opt-in not persisted"); + Check(store.Append(event1, alice, bob, "Alice", "first", "portal"), + "opted-in sender not archived"); + Check(!store.Append(event1, alice, bob, "Alice", "first", "portal"), + "duplicate event was archived twice"); + Check(store.Read(alice, 0, 20).Count == 1 && + store.Read(bob, 0, 20).Count == 0, + "participant opt-in isolation failed"); + + store.SetEnabled(bob, true); + Check(store.Append(event2, bob, alice, "Bob", "second", "viewer"), + "reply not archived"); + var aliceRows = store.Read(alice, 0, 20); + var bobRows = store.Read(bob, 0, 20); + Check(aliceRows.Count == 2 && bobRows.Count == 1, + "wrong participant archive counts"); + Check(aliceRows[1].source == "viewer" && + aliceRows[1].message == "second", + "viewer reply content mismatch"); + Check(store.Read(alice, aliceRows[0].seq, 100).Count == 1, + "cursor pagination failed"); + Check(store.Read(alice, 0, 100, bob).Count == 2, + "peer filter failed"); + Check(store.Conversations(alice, 20).Count == 1, + "conversation aggregation failed"); + + INexCitizenImStore restarted = new NexCitizenImMySqlStore( + "OpenSim.Data.MySQL.dll", connection, 30); + Check(restarted.IsEnabled(bob) && + restarted.Read(bob, 0, 20).Count == 1, + "persisted state lost on restart"); + + store.SetEnabled(alice, false); + Check(!store.IsEnabled(alice) && + store.Read(alice, 0, 20).Count == 0 && + store.Read(bob, 0, 20).Count == 1, + "opt-out must purge only the requesting owner"); + store.DeleteHistory(bob); + Check(store.IsEnabled(bob) && store.Read(bob, 0, 20).Count == 0, + "history delete must preserve consent setting"); + Console.WriteLine("MariaDB portal IM archive real SQL regression: OK"); +} +finally +{ + store.SetEnabled(alice, false); + store.SetEnabled(bob, false); +} +static void Check(bool result, string message) +{ + if (!result) throw new InvalidOperationException("NexPortalIM SQL: " + message); +} diff --git a/tools/ci/NexPortalImStoreRegression/NexPortalImStoreRegression.csproj b/tools/ci/NexPortalImStoreRegression/NexPortalImStoreRegression.csproj index 3e1f408d..2e119a70 100644 --- a/tools/ci/NexPortalImStoreRegression/NexPortalImStoreRegression.csproj +++ b/tools/ci/NexPortalImStoreRegression/NexPortalImStoreRegression.csproj @@ -10,6 +10,7 @@ ../../../bin/Mono.Data.Sqlite.dll True + diff --git a/tools/ci/verify_nexdiscovery.py b/tools/ci/verify_nexdiscovery.py index c9774604..157ab213 100644 --- a/tools/ci/verify_nexdiscovery.py +++ b/tools/ci/verify_nexdiscovery.py @@ -166,5 +166,5 @@ gridinfo_section = robust_hg_deploy.split("\n[GridInfoService]\n", 1)[1].split(" assert "welcome = https://stadt-nexverse.de/service/welcome" in gridinfo_section sim_features = opensim_config.split("[SimulatorFeatures]", 1)[1].split("\n[", 1)[0] -assert 'SearchServerURI = "https://world.stadt-nexverse.de/search?q=[QUERY]&type=[TYPE]&maturity=[MATURITY]"' in sim_features -assert 'DestinationGuideURI = "https://world.stadt-nexverse.de/destinations"' in sim_features +assert 'SearchServerURI = "https://stadt-nexverse.de/service/search?q=[QUERY]&type=[TYPE]&maturity=[MATURITY]"' in sim_features +assert 'DestinationGuideURI = "https://stadt-nexverse.de/service/destination"' in sim_features diff --git a/tools/ci/verify_portal_im_inbox.py b/tools/ci/verify_portal_im_inbox.py index ad826fb5..e0c589f3 100644 --- a/tools/ci/verify_portal_im_inbox.py +++ b/tools/ci/verify_portal_im_inbox.py @@ -94,10 +94,17 @@ for ini in ("bin/Robust.HG.ini", "bin/OpenSim.ini"): config = Path(ini).read_text() assert "[NexPortalIM]" in config, f"portal IM config not present: {ini}" config_section = config.split("[NexPortalIM]", 1)[1].split("\n[", 1)[0] - assert "Enabled = false" in config_section, "never turn on archive without provisioned secret" + assert "Enabled = true" in config_section assert 'SharedSecret = "${Environment|NEX_PORTAL_IM_SECRET}"' in config_section -assert 'StorePath = "data/nexverse-portal-im.sqlite"' in Path("bin/Robust.HG.ini").read_text() -assert 'IngestUrl = "http://127.0.0.1/internal/nexportal/im/v1"' in Path("bin/OpenSim.ini").read_text() +assert 'StoreBackend = "MariaDB"' in Path("bin/Robust.HG.ini").read_text() +assert 'IngestUrl = "https://world.stadt-nexverse.de/internal/nexportal/im/v1"' in Path("bin/OpenSim.ini").read_text() +assert "m_Log.Error(\"[NEX-PORTAL-IM]: Archive requested but" in connector +assert "NexCitizenImMySqlStore(" in connector +assert "INexCitizenImStore citizenImStore" in connector +assert "StoreBackend" in connector and "databaseConnectionString" in connector +assert "catch (Exception e)" in connector +assert "NEX_PORTAL_IM_SECRET" in Path("NexVerse/Server/Api/NexApiDocsPage.cs").read_text() +assert 'id="secretGeneratePortalIm"' in Path("NexVerse/Server/Api/NexApiDocsPage.cs").read_text() assert '' in prebuild for item in ( '["/api/v1/messages/events"]',