From c1643d7cdc035cafb6518ca3268718fba8d6155f Mon Sep 17 00:00:00 2001 From: "OpenGenesis (MPL 2.0)" <153564363+opengenesislink@users.noreply.github.com> Date: Wed, 11 Nov 2026 22:47:37 +0100 Subject: [PATCH] =?UTF-8?q?feat(g1):=20Stadt=20NexVerse=20Feed=20v2=20?= =?UTF-8?q?=E2=80=93=20modernes=20Webprofil,=20OAuth=20und=20opt-in=20Auto?= =?UTF-8?q?-Posts=20(#437)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * feat(feed): add followed-resident activity timeline and viewer reaction state * feat(feed): authenticated avatar identity, following timeline and reaction metadata * feat(feed): interactive same-origin OAuth PKCE web profile composer and timeline UI * feat(feed): upgrade Firestorm web profile to interactive same-origin PKCE UI * config(feed): inject registered public OAuth client and exact /feed callback * config(feed): expose optional public OAuth client ID for direct viewer posting * config(feed): expose optional public OAuth client ID for direct viewer posting * config(feed): expose optional public OAuth client ID for direct viewer posting * feat(feed): preserve own like state in following timeline * feat(feed): return scoped reaction state in personalized timeline * docs(api): document OAuth avatar identity and followed feed timeline endpoints * docs(feed): production-oriented public OAuth registration and interactive viewer rollout * ci(feed): verify OAuth PKCE, private profiles, timeline and real browser JS syntax * test(feed): exercise real MariaDB followed timeline and viewer reaction state * test(feed): import LINQ for followed timeline integration checks * ci(feed): gate interactive OAuth feed on privacy contracts and browser syntax * docs(feed): distinguish legacy read-only v1 from opt-in interactive webprofile v2 * feat(feed): idempotent first-party OAuth client bootstrap respecting admin disable * feat(feed): enable by default and bootstrap OAuth public client on ROBUST startup * config(feed): default enable web feed and automatic public OAuth provisioning * config(feed): default enable web feed and automatic public OAuth provisioning * config(feed): default enable web feed and automatic public OAuth provisioning * style(feed): redesign responsive Stadt NexVerse feed, composer, profile and stream cards * style(feed): Stadt NexVerse branded profile hero and cards, powered by OpenGenesisLINK footer * style(feed): modern interactive avatar cards, action buttons, responsive timelines * test(feed): align release contracts with safe auto-enabled feed default * test(feed): align release contracts with safe auto-enabled feed default * test(feed): align release contracts with safe auto-enabled feed default * test(feed): verify Stadt NexVerse branding, mobile fallback and CSP * ci(feed): gate modern NexVerse brand design and browser security * test(feed): check stream title in client layout rather than static server HTML * docs(feed): document default-enabled first-party web profile and safety gates * docs(feed): document default-enabled first-party web profile and safety gates * docs(feed): use automatic persistent OAuth client by default, manual override optional * test(feed): cover built-in OAuth public client bootstrap and safe operator opt-out * feat(feed): opt-in automatic event/classified activity settings and idempotent SQL receipts * fix(feed): purge activity consent and dedup records in atomic self/admin account deletion * feat(feed): validated and consent-gated auto posts for approved events/classifieds * feat(feed): publish verified discovery approval events for consent-gated auto posts * feat(feed): bind vetted discovery events to opt-in activity publisher * feat(feed): authenticated per-avatar opt-in controls for automatic activities * feat(feed): modern per-avatar opt-in switches for event and classified auto posts * db(feed): migration for opt-in auto-post consent and dedup receipts * test(feed): live MariaDB auto activity consent/dedup and account deletion * docs(api): add authenticated personal auto-activity preference endpoints * ci(feed): contract gate for consented auto posts and durable cleanup * test(feed): match default-on feed config and atomic activity-consent deletion * ci(feed): include privacy-gated automatic event and classified publication checks * docs(feed): opt-in auto event/classified posts, NexVerse branding and safe activation * fix(feed): accept MySQL TINYINT(1) boolean mapping in auto activity consent * docs(release): reflect default-on interactive NexVerse feed and opt-in auto activity schema * fix(feed): import OpenSim.Framework for avatar profile properties * fix(feed): avoid C# out-variable scope collisions in activity preferences route * docs(api): sync ChatGPT route index with profile feed OAuth and activity preferences * test(feed): account for retention sweep in personalized timeline route * test(feed): match multiline OAuth client lookup without false CI failure --- .github/workflows/nexjast-ci.yml | 7 + NexVerse/Core/Security/NexOAuthStore.cs | 62 ++ .../Api/NexChatGptInstructionDownloads.cs | 5 +- NexVerse/Server/Api/NexDiscoveryApi.cs | 34 +- .../Server/Api/NexVerseWorldApiConnector.cs | 59 +- .../Server/Api/NexVerseWorldApiHandlers.cs | 7 + NexVerse/Server/Api/OglProfileFeedApi.cs | 259 ++++++- .../Server/Api/OglProfileFeedAutoPublisher.cs | 121 ++++ NexVerse/Server/Api/OglProfileFeedStore.cs | 195 ++++++ NexVerse/Server/Api/OglProfileFeedWebApp.cs | 654 ++++++++++++++++++ .../UserAccountService/UserAccountService.cs | 26 + bin/Robust.HG.ini | 8 +- bin/Robust.HG.ini.example | 8 +- bin/Robust.ini.example | 8 +- .../OGL_PROFILE_FEED_INTERACTIVE_V2.md | 203 ++++++ .../OGL_PROFILE_FEED_ROLLOUT.md | 29 +- doc/OpenGenesisLINK/OGL_PROFILE_FEED_V1.md | 17 +- .../20261111_ogl_profile_feed_activity.sql | 31 + .../Program.cs | 47 ++ tools/ci/verify_ogl_profile_feed.py | 2 +- tools/ci/verify_ogl_profile_feed_activity.py | 55 ++ tools/ci/verify_ogl_profile_feed_branding.py | 44 ++ .../ci/verify_ogl_profile_feed_interactive.py | 70 ++ tools/ci/verify_ogl_profile_feed_rollout.py | 9 +- 24 files changed, 1902 insertions(+), 58 deletions(-) create mode 100644 NexVerse/Server/Api/OglProfileFeedAutoPublisher.cs create mode 100644 NexVerse/Server/Api/OglProfileFeedWebApp.cs create mode 100644 doc/OpenGenesisLINK/OGL_PROFILE_FEED_INTERACTIVE_V2.md create mode 100644 doc/OpenGenesisLINK/migrations/20261111_ogl_profile_feed_activity.sql create mode 100644 tools/ci/verify_ogl_profile_feed_activity.py create mode 100644 tools/ci/verify_ogl_profile_feed_branding.py create mode 100644 tools/ci/verify_ogl_profile_feed_interactive.py diff --git a/.github/workflows/nexjast-ci.yml b/.github/workflows/nexjast-ci.yml index f383c620..a4b901fc 100644 --- a/.github/workflows/nexjast-ci.yml +++ b/.github/workflows/nexjast-ci.yml @@ -466,6 +466,13 @@ jobs: python3 tools/ci/verify_ogl_profile_feed_rollout.py python3 tools/release/check_g1_fee_feed_rollout.py --sim bin/OpenSim.ini --robust bin/Robust.HG.ini + - name: Verify interactive OGL Profile Feed OAuth PKCE and CEF app + shell: bash + run: | + python3 tools/ci/verify_ogl_profile_feed_interactive.py + python3 tools/ci/verify_ogl_profile_feed_branding.py + python3 tools/ci/verify_ogl_profile_feed_activity.py + - name: Verify World API OGLWeather portal contracts shell: bash run: | diff --git a/NexVerse/Core/Security/NexOAuthStore.cs b/NexVerse/Core/Security/NexOAuthStore.cs index f2e2b688..96792016 100644 --- a/NexVerse/Core/Security/NexOAuthStore.cs +++ b/NexVerse/Core/Security/NexOAuthStore.cs @@ -209,6 +209,68 @@ namespace NexVerse.Core.Security return new NexOAuthClientRegistration(CloneClient(client), secret); } + // Idempotent first-party public OAuth client bootstrap. A disabled + // existing client is an explicit operator opt-out: never recreate or + // silently re-enable it. Keep this atomic within the auth store lock. + public NexOAuthClient EnsureProfileFeedPublicClient( + string redirectUri, IEnumerable allowedScopes) + { + if (!Uri.TryCreate(redirectUri, UriKind.Absolute, out Uri uri) || + uri.Scheme != Uri.UriSchemeHttps || + uri.AbsolutePath != "/feed" || + !string.IsNullOrEmpty(uri.Query) || + !string.IsNullOrEmpty(uri.Fragment) || + !string.IsNullOrEmpty(uri.UserInfo)) + throw new ArgumentException( + "Profile Feed OAuth requires a fixed HTTPS /feed callback.", + nameof(redirectUri)); + + string[] scopes = NormalizeValues(allowedScopes); + if (scopes.Length == 0) + throw new ArgumentException("Allowed OAuth scopes required.", nameof(allowedScopes)); + + const string firstPartyName = "Stadt NexVerse Profile Feed"; + lock (m_Sync) + { + NexOAuthClient existing = m_Document.Clients.FirstOrDefault( + c => string.Equals(c.Name, firstPartyName, + StringComparison.OrdinalIgnoreCase)); + if (existing != null) + { + // A modified redirect/scope or disabled client needs a + // conscious operator decision, not a silent replacement. + if (!existing.Enabled || + existing.ClientType != NexOAuthClientTypes.Public || + existing.RedirectUris == null || + existing.RedirectUris.Length != 1 || + !string.Equals(existing.RedirectUris[0], redirectUri, + StringComparison.Ordinal) || + existing.AllowedScopes == null || + !scopes.SequenceEqual( + NormalizeValues(existing.AllowedScopes))) + return null; + return CloneClient(existing); + } + + long now = DateTimeOffset.UtcNow.ToUnixTimeSeconds(); + NexOAuthClient client = new NexOAuthClient + { + ClientId = "nx_" + Guid.NewGuid().ToString("N"), + Name = firstPartyName, + ClientType = NexOAuthClientTypes.Public, + RedirectUris = new[] { redirectUri }, + AllowedScopes = scopes, + Enabled = true, + SecurityStamp = 1, + CreatedAt = now, + UpdatedAt = now + }; + m_Document.Clients.Add(client); + SaveLocked(); + return CloneClient(client); + } + } + public IReadOnlyList ListClients() { lock (m_Sync) diff --git a/NexVerse/Server/Api/NexChatGptInstructionDownloads.cs b/NexVerse/Server/Api/NexChatGptInstructionDownloads.cs index c9a25b5d..5f31b863 100644 --- a/NexVerse/Server/Api/NexChatGptInstructionDownloads.cs +++ b/NexVerse/Server/Api/NexChatGptInstructionDownloads.cs @@ -648,7 +648,10 @@ namespace NexVerse.Server.Api AppendCatalogGroup(md, requestedAudience, "shared", "Places", "/api/v1/places", "/api/v1/places/{placeId}"); - AppendCatalogGroup(md, requestedAudience, "shared", "OpenGenesisLINK Profilfeed (Opt-in): Statusmeldungen, Kommentare, Likes, Follows", + AppendCatalogGroup(md, requestedAudience, "shared", "Stadt NexVerse Profilfeed: Avatar-Posts, oeffentliche Aktivitäten, Kommentare, Follows", + "/api/v1/feed/me", + "/api/v1/feed/me/activities", + "/api/v1/feed/timeline", "/api/v1/feed/{principalId}", "/api/v1/feed/{principalId}/{postId}", "/api/v1/feed/{principalId}/{postId}/comments", diff --git a/NexVerse/Server/Api/NexDiscoveryApi.cs b/NexVerse/Server/Api/NexDiscoveryApi.cs index fd24f357..5406760b 100644 --- a/NexVerse/Server/Api/NexDiscoveryApi.cs +++ b/NexVerse/Server/Api/NexDiscoveryApi.cs @@ -10,6 +10,7 @@ using NexVerse.Core.Audit; using NexVerse.Core.Discovery; using NexVerse.Core.Economy; using NexVerse.Core.Experiences; +using NexVerse.Core.Messaging; using NexVerse.Core.Security; using OpenMetaverse; using OpenSim.Framework; @@ -34,6 +35,7 @@ namespace NexVerse.Server.Api private readonly Func m_Economy; private readonly INexAuditSink m_Audit; private readonly string m_TeleportBaseUri; + private readonly INexEventBus m_EventBus; public NexDiscoveryApi( NexApiAuthenticator authenticator, @@ -44,7 +46,7 @@ namespace NexVerse.Server.Api NexDiscoveryStore store, Func economy, INexAuditSink audit, - string teleportBaseUri) + string teleportBaseUri, INexEventBus eventBus = null) { m_Authenticator = authenticator ?? throw new ArgumentNullException(nameof(authenticator)); m_Users = users; @@ -55,6 +57,30 @@ namespace NexVerse.Server.Api m_Economy = economy ?? throw new ArgumentNullException(nameof(economy)); m_Audit = audit ?? NullNexAuditSink.Instance; m_TeleportBaseUri = (teleportBaseUri ?? string.Empty).Trim().TrimEnd('/'); + m_EventBus = eventBus; + } + + private void PublishApprovedActivity(string kind, Guid entityId) + { + if (m_EventBus == null || entityId == Guid.Empty) return; + try + { + m_EventBus.Publish(new NexEvent( + kind == "event" ? "discovery.event.approved" : + "discovery.classified.approved", + "nexverse.world-api", + new Dictionary { + ["entity_id"] = entityId.ToString("D") + })); + } + catch (Exception error) + { + // Discovery data is already committed; the optional Feed + // cannot fail a successful published event/classified. + System.Diagnostics.Trace.TraceWarning( + "[NEX-DISCOVERY]: Activity event delivery failed: " + + error.GetType().Name); + } } public void HandleSearch(IOSHttpRequest request, IOSHttpResponse response) @@ -333,6 +359,7 @@ namespace NexVerse.Server.Api NexEventRecord incoming = ReadBody(request); NexEventRecord prior = incoming.EventId == Guid.Empty ? null : m_Store.GetEvent(incoming.EventId); + bool wasApproved = prior?.State == NexDiscoveryPublicationState.Approved; if (prior == null && incoming.EventId != Guid.Empty) throw new KeyNotFoundException("Event was not found."); if (!principal.HasScope(NexScopes.AdminAll)) @@ -362,6 +389,8 @@ namespace NexVerse.Server.Api } NexEventRecord saved = m_Store.UpsertEvent(incoming); Audit(principal, "discovery.event.upserted", "event:" + saved.EventId, response); + if (saved.State == NexDiscoveryPublicationState.Approved && !wasApproved) + PublishApprovedActivity("event", saved.EventId); WriteJson(response, new { @event = saved, correlation_id = Correlation(response) }, HttpStatusCode.Created); } catch (Exception e) @@ -399,6 +428,7 @@ namespace NexVerse.Server.Api NexClassifiedRecord incoming = ReadBody(request); NexClassifiedRecord prior = incoming.ClassifiedId == Guid.Empty ? null : m_Store.GetClassified(incoming.ClassifiedId); + bool wasApproved = prior?.State == NexDiscoveryPublicationState.Approved; if (prior == null && incoming.ClassifiedId != Guid.Empty) throw new KeyNotFoundException("Classified was not found."); if (!principal.HasScope(NexScopes.AdminAll)) @@ -425,6 +455,8 @@ namespace NexVerse.Server.Api } NexClassifiedRecord saved = m_Store.UpsertClassified(incoming); Audit(principal, "discovery.classified.upserted", "classified:" + saved.ClassifiedId, response); + if (saved.State == NexDiscoveryPublicationState.Approved && !wasApproved) + PublishApprovedActivity("classified", saved.ClassifiedId); WriteJson(response, new { classified = saved, correlation_id = Correlation(response) }, HttpStatusCode.Created); } catch (Exception e) diff --git a/NexVerse/Server/Api/NexVerseWorldApiConnector.cs b/NexVerse/Server/Api/NexVerseWorldApiConnector.cs index 679dc68e..27368555 100644 --- a/NexVerse/Server/Api/NexVerseWorldApiConnector.cs +++ b/NexVerse/Server/Api/NexVerseWorldApiConnector.cs @@ -34,6 +34,8 @@ namespace NexVerse.Server.Api private static NexOtlpHttpExporter s_OtlpExporter; private static readonly object s_OfflineImMailRelaySync = new object(); private static NexOfflineImMailRelay s_OfflineImMailRelay; + private static readonly object s_FeedActivitySync = new object(); + private static OglProfileFeedAutoPublisher s_FeedActivityPublisher; // The HTTP route must exist even if later privileged connector startup // fails (e.g. an unavailable optional service). The public-only @@ -1060,7 +1062,8 @@ namespace NexVerse.Server.Api ? NexEconomyConnector.Current.Economy : null, auditSink, - teleportBaseUri); + teleportBaseUri, + eventBus); NexCitizenWorldMapApi citizenWorldMap = new NexCitizenWorldMapApi(grid, teleportBaseUri); server.AddSimpleStreamHandler( @@ -1355,9 +1358,10 @@ namespace NexVerse.Server.Api "NexVerse WebProfileV3"), true); - // Optional social profile feed. Off by default until its - // independent schema, account-deletion and viewer gates pass. - if (apiConfig.GetBoolean("EnableProfileFeed", false)) + // Feed enabled by default; unsafe database layouts are + // rejected by the guarded setup below. Operators can + // still opt out explicitly in the effective ROBUST INI. + if (apiConfig.GetBoolean("EnableProfileFeed", true)) { // Feed and self-deletion must use one atomic database. // This intentionally rejects cross-database profile @@ -1385,8 +1389,53 @@ namespace NexVerse.Server.Api OglProfileFeedStore feedStore = new OglProfileFeedStore( profileConnectionString, apiConfig.GetInt("ProfileFeedRetentionDays", 180)); + string feedCallback = publicBaseUrl.TrimEnd('/') + "/feed"; + string feedClientId = apiConfig.GetString( + "ProfileFeedOAuthClientId", string.Empty).Trim(); + + // Default: provision one stable first-party OAuth + // public client at first start, never a client + // secret. Explicit admin revocation wins. + if (string.IsNullOrEmpty(feedClientId) && + oauthStore is PersistentNexOAuthStore feedAuthStore) + { + try + { + NexOAuthClient profileClient = + feedAuthStore.EnsureProfileFeedPublicClient( + feedCallback, new[] + { + NexScopes.ProfileRead, + NexScopes.ProfileWrite, + NexScopes.RelationshipsRead, + NexScopes.RelationshipsWrite + }); + if (profileClient == null) + m_Log.Warn("[OGL-FEED]: First-party OAuth client was disabled or modified; interactive login remains off until operator review."); + else + feedClientId = profileClient.ClientId; + } + catch (Exception bootstrapError) + { + m_Log.Error("[OGL-FEED]: OAuth bootstrap failed; read-only feed remains available.", + bootstrapError); + } + } + if (string.IsNullOrWhiteSpace(feedClientId)) + m_Log.Warn("[OGL-FEED]: OAuth unavailable; profile feed is read-only."); + OglProfileFeedApi feedApi = new OglProfileFeedApi( - userAccounts, profilesData, authenticator, feedStore, auditSink); + userAccounts, profilesData, authenticator, feedStore, auditSink, + feedClientId, feedCallback); + + lock (s_FeedActivitySync) + { + s_FeedActivityPublisher?.Dispose(); + s_FeedActivityPublisher = new OglProfileFeedAutoPublisher( + eventBus, feedStore, discoveryStore, + userAccounts, profilesData, auditSink); + } + server.AddSimpleStreamHandler( new SimpleStreamHandler("/api/v1/feed", apiGate.Wrap(feedApi.HandleApi), "OpenGenesisLINK profile activity feed"), true); diff --git a/NexVerse/Server/Api/NexVerseWorldApiHandlers.cs b/NexVerse/Server/Api/NexVerseWorldApiHandlers.cs index 65f6d0a5..044ee905 100644 --- a/NexVerse/Server/Api/NexVerseWorldApiHandlers.cs +++ b/NexVerse/Server/Api/NexVerseWorldApiHandlers.cs @@ -284,6 +284,13 @@ namespace NexVerse.Server.Api ("post", "Destination-Aufruf für Popularitätsranking registrieren", "200")), ["/api/v1/destinations/{destinationId}/moderation"] = AuthenticatedOperations( ("post", "Destination freigeben oder ablehnen", "discovery:manage", "200")), + ["/api/v1/feed/me/activities"] = AuthenticatedOperations( + ("get", "Eigene Opt-in-Einstellungen fuer oeffentliche Auto-Beitraege lesen", "profile:read", "200"), + ("put", "Eigene Opt-in-Einstellungen fuer oeffentliche Auto-Beitraege aendern", "profile:write", "200")), + ["/api/v1/feed/me"] = AuthenticatedOperations( + ("get", "Eigenen Avatar fuer eine Webprofile-OAuth-Session ermitteln", "profile:read", "200")), + ["/api/v1/feed/timeline"] = AuthenticatedOperations( + ("get", "Aktuelle oeffentliche Beitraege von abonnierten lokalen Avataren lesen", "relationships:read", "200")), ["/api/v1/feed/{principalId}"] = MergeOperations( GetOperation("Feed eines veroeffentlichten lokalen Avatars lesen; private Feeds nur mit Owner/Admin-Berechtigung"), AuthenticatedOperations(("post", "Eigene Statusmeldung veroeffentlichen", "profile:write", "201"))), diff --git a/NexVerse/Server/Api/OglProfileFeedApi.cs b/NexVerse/Server/Api/OglProfileFeedApi.cs index 5bd65030..f4238744 100644 --- a/NexVerse/Server/Api/OglProfileFeedApi.cs +++ b/NexVerse/Server/Api/OglProfileFeedApi.cs @@ -1,11 +1,12 @@ // SPDX-License-Identifier: MPL-2.0 -// Server-owned, opt-in profile activity feed. Public viewer pages are read-only: -// browser profile tabs do not receive a resident OAuth token by default. +// Server-owned, opt-in profile activity feed. No avatar credentials from +// simulator circuits: interactive writes require browser OAuth PKCE S256. using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Net; +using System.Security.Cryptography; using System.Text; using System.Text.Json; using System.Linq; @@ -26,15 +27,20 @@ namespace NexVerse.Server.Api private readonly NexApiAuthenticator m_Auth; private readonly OglProfileFeedStore m_Store; private readonly INexAuditSink m_Audit; + private readonly string m_OAuthClientId; + private readonly string m_OAuthRedirectUri; internal OglProfileFeedApi(IUserAccountService accounts, IProfilesData profiles, - NexApiAuthenticator auth, OglProfileFeedStore store, INexAuditSink audit) + NexApiAuthenticator auth, OglProfileFeedStore store, INexAuditSink audit, + string oauthClientId = "", string oauthRedirectUri = "") { m_Accounts=accounts ?? throw new ArgumentNullException(nameof(accounts)); m_Profiles=profiles ?? throw new ArgumentNullException(nameof(profiles)); m_Auth=auth ?? throw new ArgumentNullException(nameof(auth)); m_Store=store ?? throw new ArgumentNullException(nameof(store)); m_Audit=audit ?? NullNexAuditSink.Instance; + m_OAuthClientId=oauthClientId?.Trim() ?? ""; + m_OAuthRedirectUri=oauthRedirectUri?.Trim() ?? ""; } private static bool Is(IOSHttpRequest request, string method) @@ -43,6 +49,119 @@ namespace NexVerse.Server.Api public void HandleApi(IOSHttpRequest request, IOSHttpResponse response) { string[] p=(request?.UriPath ?? "").Trim('/').Split('/'); + // Profile Feed auto-publication preferences are owned by the + // authenticated local avatar, never supplied by a query parameter. + if (p.Length == 5 && p[0] == "api" && p[1] == "v1" && + p[2] == "feed" && p[3] == "me" && p[4] == "activities") + { + bool read = Is(request,"GET"); + if (!read && !Is(request,"PUT")) + { + Json(response,HttpStatusCode.MethodNotAllowed, + new {error="get_or_put_required"}); + return; + } + if (!m_Auth.TryAuthenticate(request, + read ? NexScopes.ProfileRead : NexScopes.ProfileWrite, + out NexPrincipal activityPrincipal,out UserAccount account, + out int activityStatus,out string activityAuthError)) + { + Json(response,(HttpStatusCode)activityStatus,new {error=activityAuthError}); + return; + } + if (account == null || !account.LocalToGrid || + !UUID.TryParse(activityPrincipal.Subject,out UUID resident) || + resident != account.PrincipalID) + { + Json(response,HttpStatusCode.Forbidden, + new {error="local_resident_required"}); + return; + } + if (!read) + { + if (!TryActivitySettings(request,out bool autoEvents, + out bool autoClassifieds)) + { + Json(response,HttpStatusCode.BadRequest, + new {error="invalid_auto_activity_settings"}); + return; + } + if (!m_Store.SetActivitySettings(resident,autoEvents,autoClassifieds)) + { + Json(response,HttpStatusCode.NotFound, + new {error="resident_not_found"}); + return; + } + } + var settings=m_Store.GetActivitySettings(resident); + Json(response,HttpStatusCode.OK,new { + auto_events=settings.Events, + auto_classifieds=settings.Classifieds + }); + return; + } + + // Session bootstrap and personalized following timeline do not + // have a profile-owner UUID. Both require local OAuth residents. + if(p.Length==4 && (p[3]=="me" || p[3]=="timeline")) + { + string required=p[3]=="me" ? NexScopes.ProfileRead + : NexScopes.RelationshipsRead; + if(!Is(request,"GET")) + { + Json(response,HttpStatusCode.MethodNotAllowed,new {error="get_required"}); + return; + } + if(!m_Auth.TryAuthenticate(request,required,out NexPrincipal viewer, + out UserAccount viewerAccount,out int code,out string failure)) + { + Json(response,(HttpStatusCode)code,new {error=failure}); + return; + } + if(viewerAccount==null || !viewerAccount.LocalToGrid || + !UUID.TryParse(viewer.Subject,out UUID me) || + viewerAccount.PrincipalID!=me) + { + Json(response,HttpStatusCode.Forbidden,new {error="local_resident_required"}); + return; + } + if(p[3]=="me") + { + Json(response,HttpStatusCode.OK, + new {avatar_id=me.ToString(),name=viewerAccount.Name}); + return; + } + m_Store.PruneExpired(); + // Defense in depth: a follow does not override the target's + // PublishProfile setting. No private posts in this timeline. + var items=m_Store.ListFollowingPosts(me,80); + var visible=new List(); + var visibleIds=new HashSet(StringComparer.Ordinal); + foreach(var item in items) + { + UserAccount followed=m_Accounts.GetUserAccount(UUID.Zero,item.Owner); + if(followed==null || !followed.LocalToGrid)continue; + UserProfileProperties properties=new UserProfileProperties { + UserId=item.Owner }; + string profileError=""; + if(!m_Profiles.GetAvatarProperties(ref properties,ref profileError) || + !properties.PublishProfile)continue; + visibleIds.Add(item.Entry.Id); + visible.Add(new { + owner_id=item.Owner.ToString(),owner_name=followed.Name, + id=item.Entry.Id,text=item.Entry.Text, + created_at=item.Entry.CreatedAt,likes=item.Entry.Likes, + comments=item.Entry.Comments + }); + if(visible.Count>=30)break; + } + Json(response,HttpStatusCode.OK,new { + posts=visible, + liked_post_ids=m_Store.ListLikedFollowingPostIds(me) + .Where(visibleIds.Contains).ToArray() + }); + return; + } if(p.Length < 4 || p.Length > 7 || !p[0].Equals("api",StringComparison.OrdinalIgnoreCase) || !p[1].Equals("v1",StringComparison.OrdinalIgnoreCase) || @@ -73,9 +192,23 @@ namespace NexVerse.Server.Api { if(!AllowRead(request,response,ownerId,profile.PublishProfile))return; var posts=m_Store.ListPosts(ownerId); + UUID viewerId=UUID.Zero; + // Optional personalization: anonymous profiles remain public. + // An invalid bearer never gains write/read permissions. + if(!string.IsNullOrWhiteSpace(request?.Headers?["Authorization"]) && + m_Auth.TryAuthenticate(request,NexScopes.RelationshipsRead, + out NexPrincipal viewer,out UserAccount viewerAccount, + out _,out _) && + viewerAccount!=null && viewerAccount.LocalToGrid && + UUID.TryParse(viewer.Subject,out UUID authenticatedViewer) && + viewerAccount.PrincipalID==authenticatedViewer) + viewerId=authenticatedViewer; Json(response,HttpStatusCode.OK,new { owner_id=ownerId.ToString(), name=owner.Name, followers=m_Store.Followers(ownerId), + following=!viewerId.IsZero() && m_Store.IsFollowing(ownerId,viewerId), + liked_post_ids=viewerId.IsZero() ? Array.Empty() + : m_Store.ListLikedPostIds(ownerId,viewerId).ToArray(), posts=posts.Select(post=>new { id=post.Id,author_id=post.AuthorId,text=post.Text, created_at=post.CreatedAt,likes=post.Likes,comments=post.Comments @@ -97,7 +230,10 @@ namespace NexVerse.Server.Api Json(response,HttpStatusCode.OK,new { post_id=publicPost.ToString(), comments=m_Store.ListComments(publicPost).Select(c=>new { - id=c.Id,author_id=c.AuthorId,text=c.Text,created_at=c.CreatedAt + id=c.Id,author_id=c.AuthorId,text=c.Text,created_at=c.CreatedAt, + author_name=UUID.TryParse(c.AuthorId,out UUID cid) + ? m_Accounts.GetUserAccount(UUID.Zero,cid)?.Name ?? "Einwohner" + : "Einwohner" }).ToArray() }); return; @@ -238,6 +374,18 @@ namespace NexVerse.Server.Api Json(response,HttpStatusCode.MethodNotAllowed,new {error="get_required"}); return; } + string nonce=Convert.ToBase64String(RandomNumberGenerator.GetBytes(16)); + // OAuth uses one exact registered redirect URI: /feed, never + // unregistered per-avatar query strings. This page processes the + // one-time code only in the browser and immediately erases its URL. + if(request.QueryString?["code"]!=null || + request.QueryString?["error"]!=null) + { + WriteFeedHtml(response, + OglProfileFeedWebApp.CallbackPage(nonce,m_OAuthClientId, + m_OAuthRedirectUri),nonce); + return; + } string name=(request.QueryString?["name"] ?? "").Trim(); // Firestorm expands [AGENT_NAME] to First.Last or First.Resident. // Do not infer identity or permission from the URL alone. @@ -261,7 +409,7 @@ namespace NexVerse.Server.Api WebMessage(response,HttpStatusCode.ServiceUnavailable,"Profil derzeit nicht verfügbar."); return; } - if(!profile.PublishProfile) + if(!profile.PublishProfile && string.IsNullOrWhiteSpace(m_OAuthClientId)) { WebMessage(response,HttpStatusCode.NotFound,"Dieser Feed ist privat."); return; @@ -270,27 +418,45 @@ namespace NexVerse.Server.Api var html=new StringBuilder(); html.Append("") .Append("") - .Append("Stadt NexVerse – Profilfeed") - .Append(""); - html.Append("
STADT NEXVERSE · OPEN GENESIS LINK

") - .Append(WebUtility.HtmlEncode(account.Name)).Append("

Profilfeed
"); - var posts=m_Store.ListPosts(account.PrincipalID,20); + .Append("") + .Append("Stadt NexVerse · Profilfeed
"); + html.Append("
") + .Append("NV") + .Append("
Stadt NexVerse
") + .Append("Dein virtuelles Zuhause
") + .Append("") + .Append("NexVerse Community
"); + html.Append("
") + .Append("
") + .Append(WebUtility.HtmlEncode((names[0].Substring(0,1) + + names[1].Substring(0,1)).ToUpperInvariant())) + .Append("
") + .Append("Einwohnerprofil

") + .Append(WebUtility.HtmlEncode(account.Name)) + .Append("

Momente, Geschichten und Neuigkeiten aus Stadt NexVerse
") + .Append("
"); + html.Append(OglProfileFeedWebApp.Controls()) + .Append("
"); + var posts=profile.PublishProfile ? m_Store.ListPosts(account.PrincipalID,20) + : new List(); if(posts.Count==0)html.Append("

Hier wurden noch keine Beiträge veröffentlicht.

"); foreach(var post in posts) { - html.Append("
") + html.Append("
") + .Append("") + .Append(WebUtility.HtmlEncode((names[0].Substring(0,1) + + names[1].Substring(0,1)).ToUpperInvariant())) + .Append("
") .Append(WebUtility.HtmlEncode(account.Name)) - .Append("
") + .Append("
") .Append(DateTimeOffset.FromUnixTimeSeconds(post.CreatedAt).UtcDateTime.ToString("dd.MM.yyyy HH:mm")) - .Append(" UTC
") + .Append(" UTC
") .Append(WebUtility.HtmlEncode(post.Text)) - .Append("
Gefällt mir: ") - .Append(post.Likes).Append(" · Kommentare: ").Append(post.Comments).Append("
"); + .Append("
") + .Append(post.Likes).Append(" Gefaellt mir · ").Append(post.Comments) + .Append(" Kommentare
"); foreach(var comment in m_Store.ListComments(new UUID(post.Id),10)) { UserAccount author=UUID.TryParse(comment.AuthorId,out UUID cid) @@ -302,15 +468,30 @@ namespace NexVerse.Server.Api } html.Append("
"); } - html.Append("
Beiträge, Kommentare und Reaktionen werden über das authentifizierte Stadtportal verwaltet.") - .Append(" Stadt NexVerse
"); + html.Append("
") + .Append("© Stadt NexVerse · Deine Welt. Deine Community.") + .Append("Powered by OpenGenesisLINK") + .Append("
"); + html.Append(OglProfileFeedWebApp.Script(nonce, + account.PrincipalID.ToString(),account.Name,profile.PublishProfile, + m_OAuthClientId,m_OAuthRedirectUri)); + html.Append(""); + WriteFeedHtml(response,html.ToString(),nonce); + } + + private static void WriteFeedHtml(IOSHttpResponse response,string html,string nonce) + { response.StatusCode=(int)HttpStatusCode.OK; response.ContentType="text/html; charset=utf-8"; response.AddHeader("Cache-Control","no-store"); response.AddHeader("X-Content-Type-Options","nosniff"); response.AddHeader("Referrer-Policy","no-referrer"); - response.AddHeader("Content-Security-Policy","default-src 'none'; style-src 'unsafe-inline'; frame-ancestors 'none'; base-uri 'none'; form-action 'none'"); - response.RawBuffer=Encoding.UTF8.GetBytes(html.ToString()); + response.AddHeader("X-Frame-Options","DENY"); + response.AddHeader("Content-Security-Policy", + "default-src 'none'; style-src 'unsafe-inline'; " + + "script-src 'nonce-" + nonce + "'; connect-src 'self'; " + + "base-uri 'none'; form-action 'none'; frame-ancestors 'none'"); + response.RawBuffer=Encoding.UTF8.GetBytes(html); } private void AuditModeratorAction(UUID actor, UUID owner, UUID post, string action) @@ -349,6 +530,36 @@ namespace NexVerse.Server.Api return true; } + private static bool TryActivitySettings(IOSHttpRequest request, + out bool events,out bool classifieds) + { + events=false; + classifieds=false; + try + { + using var reader=new StreamReader(request.InputStream,Encoding.UTF8, + true,1024,leaveOpen:true); + char[] buffer=new char[2049]; + int length=reader.ReadBlock(buffer,0,buffer.Length); + if(length<=0 || length>=buffer.Length)return false; + using JsonDocument json=JsonDocument.Parse(new string(buffer,0,length)); + JsonElement root=json.RootElement; + if(root.ValueKind!=JsonValueKind.Object || + !root.TryGetProperty("auto_events",out JsonElement first) || + !root.TryGetProperty("auto_classifieds",out JsonElement second)) + return false; + if((first.ValueKind!=JsonValueKind.True && + first.ValueKind!=JsonValueKind.False) || + (second.ValueKind!=JsonValueKind.True && + second.ValueKind!=JsonValueKind.False)) + return false; + events=first.GetBoolean(); + classifieds=second.GetBoolean(); + return true; + } + catch{return false;} + } + private static bool TryText(IOSHttpRequest request,string field,int max,out string value) { value=""; diff --git a/NexVerse/Server/Api/OglProfileFeedAutoPublisher.cs b/NexVerse/Server/Api/OglProfileFeedAutoPublisher.cs new file mode 100644 index 00000000..9ca4feb2 --- /dev/null +++ b/NexVerse/Server/Api/OglProfileFeedAutoPublisher.cs @@ -0,0 +1,121 @@ +// SPDX-License-Identifier: MPL-2.0 +// Resident-approved, idempotent and privacy-bound discovery activity posts. +// Unauthenticated event-bus payloads never authorize publication: every +// referenced entity is independently re-read from the authoritative store. +using System; +using System.Collections.Generic; +using log4net; +using NexVerse.Core.Audit; +using NexVerse.Core.Discovery; +using NexVerse.Core.Messaging; +using OpenMetaverse; +using OpenSim.Data; +using OpenSim.Framework; +using OpenSim.Services.Interfaces; + +namespace NexVerse.Server.Api +{ + internal sealed class OglProfileFeedAutoPublisher : IDisposable + { + private static readonly ILog s_Log = + LogManager.GetLogger(typeof(OglProfileFeedAutoPublisher)); + private readonly OglProfileFeedStore m_Feed; + private readonly NexDiscoveryStore m_Discovery; + private readonly IUserAccountService m_Accounts; + private readonly IProfilesData m_Profiles; + private readonly INexAuditSink m_Audit; + private readonly IDisposable m_Events; + private readonly IDisposable m_Classifieds; + + internal OglProfileFeedAutoPublisher( + INexEventBus bus, OglProfileFeedStore feed, + NexDiscoveryStore discovery, IUserAccountService accounts, + IProfilesData profiles, INexAuditSink audit) + { + m_Feed = feed ?? throw new ArgumentNullException(nameof(feed)); + m_Discovery = discovery ?? throw new ArgumentNullException(nameof(discovery)); + m_Accounts = accounts ?? throw new ArgumentNullException(nameof(accounts)); + m_Profiles = profiles ?? throw new ArgumentNullException(nameof(profiles)); + m_Audit = audit ?? NullNexAuditSink.Instance; + if (bus == null) throw new ArgumentNullException(nameof(bus)); + m_Events = bus.Subscribe("discovery.event.approved", OnActivity); + m_Classifieds = bus.Subscribe("discovery.classified.approved", OnActivity); + } + + private void OnActivity(NexEvent ev) + { + // The source label is an extra guard, NOT proof of authorization. + // The durable source record and the resident's consent are checked + // before any post can be committed. + if (ev == null || ev.Source != "nexverse.world-api" || + !ev.Data.TryGetValue("entity_id", out string reference) || + !Guid.TryParse(reference, out Guid id) || id == Guid.Empty) + return; + string kind = ev.Name == "discovery.event.approved" ? "event" : + ev.Name == "discovery.classified.approved" ? "classified" : ""; + if (kind.Length == 0) return; + + try + { + Guid ownerGuid; + string title; + if (kind == "event") + { + NexEventRecord record = m_Discovery.GetEvent(id); + if (record == null || + record.State != NexDiscoveryPublicationState.Approved) + return; + ownerGuid = record.OrganizerId; + title = record.Name; + } + else + { + NexClassifiedRecord record = m_Discovery.GetClassified(id); + if (record == null || + record.State != NexDiscoveryPublicationState.Approved) + return; + ownerGuid = record.OwnerId; + title = record.Name; + } + if (ownerGuid == Guid.Empty || string.IsNullOrWhiteSpace(title)) + return; + UUID owner = new UUID(ownerGuid); + UserAccount account = m_Accounts.GetUserAccount(UUID.Zero,owner); + if (account == null || !account.LocalToGrid || !account.LoginAllowed) + return; + UserProfileProperties properties = new UserProfileProperties { UserId=owner }; + string err = ""; + if (!m_Profiles.GetAvatarProperties(ref properties,ref err) || + !properties.PublishProfile) + return; + + // Never copy arbitrary text, private coordinates, visitor logs + // or other event-bus payload fields into an auto post. + string safeName = title.Trim(); + if (safeName.Length > 140) safeName = safeName.Substring(0,140); + string body = kind == "event" + ? "Ich habe ein neues Event in Stadt NexVerse veroeffentlicht: " + safeName + : "Mein neuer Eintrag in Stadt NexVerse ist verfuegbar: " + safeName; + if (m_Feed.TryCreateActivityPost(owner,kind,id,body)) + m_Audit.Record(new NexAuditEvent(owner.ToString(), + "feed.activity.auto." + kind, "profile-feed:" + owner, + ev.CorrelationId, new Dictionary { + ["entity_id"]=id.ToString("D") + })); + } + catch (Exception error) + { + // Publishing the source entity has already committed; never + // undo its API response because optional feed posting failed. + s_Log.Warn("[OGL-FEED]: Auto activity post failed: " + + error.GetType().Name); + } + } + + public void Dispose() + { + m_Events.Dispose(); + m_Classifieds.Dispose(); + } + } +} diff --git a/NexVerse/Server/Api/OglProfileFeedStore.cs b/NexVerse/Server/Api/OglProfileFeedStore.cs index b7b32921..8cc9a03f 100644 --- a/NexVerse/Server/Api/OglProfileFeedStore.cs +++ b/NexVerse/Server/Api/OglProfileFeedStore.cs @@ -75,6 +75,23 @@ namespace NexVerse.Server.Api PRIMARY KEY(owner,follower), INDEX ix_ogl_feed_follower(follower) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4"); + Execute(db, @"CREATE TABLE IF NOT EXISTS ogl_profile_feed_activity_settings( + owner CHAR(36) CHARACTER SET ascii COLLATE ascii_bin NOT NULL PRIMARY KEY, + auto_events TINYINT(1) NOT NULL DEFAULT 0, + auto_classifieds TINYINT(1) NOT NULL DEFAULT 0, + updated_at BIGINT NOT NULL + ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4"); + Execute(db, @"CREATE TABLE IF NOT EXISTS ogl_profile_feed_activity_receipts( + owner CHAR(36) CHARACTER SET ascii COLLATE ascii_bin NOT NULL, + activity_kind VARCHAR(32) CHARACTER SET ascii COLLATE ascii_bin NOT NULL, + reference_id CHAR(36) CHARACTER SET ascii COLLATE ascii_bin NOT NULL, + post_id CHAR(36) CHARACTER SET ascii COLLATE ascii_bin NOT NULL, + created_at BIGINT NOT NULL, + PRIMARY KEY(owner,activity_kind,reference_id), + INDEX ix_ogl_feed_activity_time(owner,created_at), + CONSTRAINT fk_ogl_feed_activity_post FOREIGN KEY(post_id) + REFERENCES ogl_profile_feed_posts(id) ON DELETE CASCADE + ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4"); m_RetentionTimer = new Timer(_ => { try @@ -195,6 +212,184 @@ namespace NexVerse.Server.Api return posts; } + // No automatic public posts until the resident explicitly enables + // the corresponding activity type. Values default to false. + internal (bool Events, bool Classifieds) GetActivitySettings(UUID owner) + { + using var db=Open(); + using var cmd=db.CreateCommand(); + cmd.CommandText=@"SELECT auto_events,auto_classifieds + FROM ogl_profile_feed_activity_settings WHERE owner=@owner"; + Add(cmd,"@owner",owner.ToString()); + using var rd=cmd.ExecuteReader(); + return rd.Read() ? (Convert.ToBoolean(rd.GetValue(0)), + Convert.ToBoolean(rd.GetValue(1))) + : (false,false); + } + + internal bool SetActivitySettings(UUID owner, bool events, bool classifieds) + { + using var db=Open(); + using var tx=db.BeginTransaction(); + if(!LockExistingResidents(db,tx,owner))return false; + using var cmd=db.CreateCommand(); + cmd.Transaction=tx; + cmd.CommandText=@"INSERT INTO ogl_profile_feed_activity_settings + (owner,auto_events,auto_classifieds,updated_at) + VALUES (@owner,@events,@classifieds,@at) + ON DUPLICATE KEY UPDATE auto_events=VALUES(auto_events), + auto_classifieds=VALUES(auto_classifieds), + updated_at=VALUES(updated_at)"; + Add(cmd,"@owner",owner.ToString()); + Add(cmd,"@events",events?1:0); + Add(cmd,"@classifieds",classifieds?1:0); + Add(cmd,"@at",Now); + cmd.ExecuteNonQuery(); + tx.Commit(); + return true; + } + + // The published discovery record is revalidated by the subscriber. + // A same-DB receipt is inserted atomically with each post, so event + // redelivery and overlapping ROBUST workers cannot duplicate it. + internal bool TryCreateActivityPost(UUID owner,string kind,Guid reference,string text) + { + if(owner.IsZero() || reference==Guid.Empty || + (kind!="event" && kind!="classified") || + string.IsNullOrWhiteSpace(text) || text.Length>1500) + return false; + using var db=Open(); + using var tx=db.BeginTransaction(); + if(!LockExistingResidents(db,tx,owner))return false; + + string setting = kind=="event" ? "auto_events" : "auto_classifieds"; + using(var permission=db.CreateCommand()) + { + permission.Transaction=tx; + permission.CommandText="SELECT "+setting+ + " FROM ogl_profile_feed_activity_settings WHERE owner=@owner"; + Add(permission,"@owner",owner.ToString()); + if(Convert.ToInt32(permission.ExecuteScalar() ?? 0)!=1)return false; + } + + // Separate anti-spam budget for auto activity; account row lock + // serializes posts by avatar. + using(var budget=db.CreateCommand()) + { + budget.Transaction=tx; + budget.CommandText=@"SELECT COUNT(*) FROM ogl_profile_feed_activity_receipts + WHERE owner=@owner AND created_at>=@hour"; + Add(budget,"@owner",owner.ToString()); + Add(budget,"@hour",Now-3600); + if(Convert.ToInt32(budget.ExecuteScalar())>=3)return false; + budget.Parameters.Clear(); + budget.CommandText=@"SELECT COUNT(*) FROM ogl_profile_feed_activity_receipts + WHERE owner=@owner AND created_at>=@day"; + Add(budget,"@owner",owner.ToString()); + Add(budget,"@day",Now-86400); + if(Convert.ToInt32(budget.ExecuteScalar())>=15)return false; + } + + UUID post=UUID.Random(); + using(var postCommand=db.CreateCommand()) + { + postCommand.Transaction=tx; + postCommand.CommandText=@"INSERT INTO ogl_profile_feed_posts + (id,owner,author,body,created_at) + VALUES(@post,@owner,@owner,@body,@at)"; + Add(postCommand,"@post",post.ToString()); + Add(postCommand,"@owner",owner.ToString()); + Add(postCommand,"@body",text.Trim()); + Add(postCommand,"@at",Now); + postCommand.ExecuteNonQuery(); + } + using(var marker=db.CreateCommand()) + { + marker.Transaction=tx; + marker.CommandText=@"INSERT IGNORE INTO ogl_profile_feed_activity_receipts + (owner,activity_kind,reference_id,post_id,created_at) + VALUES(@owner,@kind,@reference,@post,@at)"; + Add(marker,"@owner",owner.ToString()); + Add(marker,"@kind",kind); + Add(marker,"@reference",reference.ToString("D")); + Add(marker,"@post",post.ToString()); + Add(marker,"@at",Now); + if(marker.ExecuteNonQuery()!=1)return false; + } + tx.Commit(); + return true; + } + + internal List<(UUID Owner, Post Entry)> ListFollowingPosts(UUID follower, int limit=60) + { + var result=new List<(UUID Owner, Post Entry)>(); + using var db=Open(); + using var cmd=db.CreateCommand(); + cmd.CommandText=@"SELECT p.owner,p.id,p.author,p.body,p.created_at, + (SELECT COUNT(*) FROM ogl_profile_feed_likes l WHERE l.post_id=p.id), + (SELECT COUNT(*) FROM ogl_profile_feed_comments c WHERE c.post_id=p.id) + FROM ogl_profile_feed_follows f + INNER JOIN ogl_profile_feed_posts p ON p.owner=f.owner + WHERE f.follower=@follower AND p.created_at>=@cutoff + ORDER BY p.created_at DESC,p.id DESC LIMIT @count"; + Add(cmd,"@follower",follower.ToString()); + Add(cmd,"@cutoff",Cutoff); + Add(cmd,"@count",Math.Clamp(limit,1,100)); + using var rd=cmd.ExecuteReader(); + while(rd.Read()) + result.Add((new UUID(rd.GetString(0)),new Post { + Id=rd.GetString(1),AuthorId=rd.GetString(2), + Text=rd.GetString(3),CreatedAt=rd.GetInt64(4), + Likes=Convert.ToInt32(rd.GetValue(5)), + Comments=Convert.ToInt32(rd.GetValue(6)) + })); + return result; + } + + internal List ListLikedPostIds(UUID owner, UUID actor) + { + var result=new List(); + using var db=Open(); + using var cmd=db.CreateCommand(); + cmd.CommandText=@"SELECT l.post_id FROM ogl_profile_feed_likes l + INNER JOIN ogl_profile_feed_posts p ON p.id=l.post_id + WHERE p.owner=@owner AND l.actor=@actor AND p.created_at>=@cutoff"; + Add(cmd,"@owner",owner.ToString()); + Add(cmd,"@actor",actor.ToString()); + Add(cmd,"@cutoff",Cutoff); + using var rd=cmd.ExecuteReader(); + while(rd.Read())result.Add(rd.GetString(0)); + return result; + } + + internal List ListLikedFollowingPostIds(UUID follower) + { + var result=new List(); + using var db=Open(); + using var cmd=db.CreateCommand(); + cmd.CommandText=@"SELECT l.post_id FROM ogl_profile_feed_likes l + INNER JOIN ogl_profile_feed_posts p ON p.id=l.post_id + INNER JOIN ogl_profile_feed_follows f ON f.owner=p.owner + WHERE f.follower=@follower AND l.actor=@follower + AND p.created_at>=@cutoff"; + Add(cmd,"@follower",follower.ToString()); + Add(cmd,"@cutoff",Cutoff); + using var rd=cmd.ExecuteReader(); + while(rd.Read())result.Add(rd.GetString(0)); + return result; + } + + internal bool IsFollowing(UUID owner, UUID follower) + { + using var db=Open(); + using var cmd=db.CreateCommand(); + cmd.CommandText=@"SELECT COUNT(*) FROM ogl_profile_feed_follows + WHERE owner=@owner AND follower=@follower"; + Add(cmd,"@owner",owner.ToString()); + Add(cmd,"@follower",follower.ToString()); + return Convert.ToInt32(cmd.ExecuteScalar())>0; + } + internal List ListComments(UUID post, int limit = 30) { var result = new List(); diff --git a/NexVerse/Server/Api/OglProfileFeedWebApp.cs b/NexVerse/Server/Api/OglProfileFeedWebApp.cs new file mode 100644 index 00000000..36b41aa9 --- /dev/null +++ b/NexVerse/Server/Api/OglProfileFeedWebApp.cs @@ -0,0 +1,654 @@ +// SPDX-License-Identifier: MPL-2.0 +// Small self-hosted, same-origin interactive web profile UI. +// All authorization and state mutation remain with the World API. +using System; +using System.Net; +using System.Text.Json; + +namespace NexVerse.Server.Api +{ + internal static class OglProfileFeedWebApp + { + internal static string Controls() + { + return """ + +

+ + + + +
+
DEIN NEXVERSE
+

Aktuelles aus dem Profil

+ +
+ """; + } + + internal static string Styles() + { + return """ + :root{color-scheme:dark;--nv-bg:#070e1e;--nv-panel:#121d34; + --nv-border:rgba(161,192,245,.17);--nv-txt:#f0f6ff;--nv-muted:#95a9c8; + --nv-cyan:#70e2ef;--nv-blue:#598af9;--nv-purple:#a27af4; + --nv-glow:rgba(86,146,240,.22);--nv-radius:18px} + *{box-sizing:border-box}html{scroll-behavior:smooth} + body{min-height:100vh;margin:0;padding:0;background:var(--nv-bg); + color:var(--nv-txt);font:14px/1.65 system-ui,-apple-system,"Segoe UI",sans-serif} + body::before{content:"";position:fixed;inset:0;z-index:0;pointer-events:none; + background:radial-gradient(ellipse 65% 36% at 90% 0%,rgba(103,81,211,.22),transparent), + radial-gradient(ellipse 55% 36% at 0% 15%,rgba(44,131,206,.20),transparent)} + [hidden]{display:none!important}button,textarea{font:inherit} + button{display:inline-flex;align-items:center;justify-content:center;gap:7px; + min-height:38px;padding:7px 13px;color:#dfeeff;cursor:pointer; + border:1px solid rgba(142,169,213,.27);border-radius:11px; + background:rgba(92,119,160,.14);transition:background .15s,border-color .15s,transform .15s} + button:hover{border-color:rgba(113,223,243,.67);background:rgba(80,120,175,.25)} + button:active{transform:translateY(1px)} + button:disabled{cursor:not-allowed;opacity:.45} + button:focus-visible,textarea:focus-visible,a:focus-visible{ + outline:2px solid var(--nv-cyan);outline-offset:3px} + button.ogl-primary{background:linear-gradient(115deg,#497af0,#7555dd); + color:white;border-color:rgba(179,187,255,.47);font-weight:650; + box-shadow:0 6px 18px rgba(58,90,189,.20)} + button.ogl-primary:hover{background:linear-gradient(115deg,#5893ff,#8b68f3)} + button.ogl-outline{background:transparent} + a{color:#88ddec;text-decoration:none}a:hover{text-decoration:underline} + .ogl-shell{position:relative;z-index:1;max-width:870px;margin:0 auto;padding:0 18px 30px} + .ogl-brandbar{display:flex;align-items:center;gap:12px;padding:19px 1px 15px} + .ogl-emblem{display:inline-flex;align-items:center;justify-content:center; + flex:0 0 43px;width:43px;height:43px;border-radius:14px; + border:1px solid rgba(167,222,255,.48);background:linear-gradient(140deg,#123d6f,#6657d6); + font-weight:850;font-size:15px;letter-spacing:-1.5px;color:white; + box-shadow:0 0 26px rgba(88,133,241,.24)} + .ogl-brandname{font-size:18px;font-weight:830;letter-spacing:.1px;line-height:1.1; + background:linear-gradient(100deg,#f2fcff,#8fe8ff 65%,#b3a4ff); + -webkit-background-clip:text;background-clip:text;color:transparent} + .ogl-brandtag{display:block;color:var(--nv-muted);font-size:10px; + letter-spacing:1.5px;text-transform:uppercase;font-weight:650} + .ogl-brandbar .ogl-spacer{flex:1} + .ogl-network-chip{font-size:11px;color:#9ddce1;border:1px solid rgba(84,199,197,.28); + background:rgba(22,117,136,.16);padding:5px 10px;border-radius:999px; + white-space:nowrap} + .ogl-hero{position:relative;overflow:hidden;border-radius:22px; + border:1px solid rgba(148,181,249,.27); + background:linear-gradient(119deg,#172e54 0%,#15213f 45%,#32235e 100%); + box-shadow:0 18px 45px rgba(3,8,22,.25);margin:0 0 15px} + .ogl-hero::before{content:"";pointer-events:none;position:absolute;inset:0; + background:radial-gradient(circle at 87% 28%,rgba(167,117,254,.27),transparent 32%), + linear-gradient(135deg,transparent 60%,rgba(101,207,254,.12) 61%, + transparent 62%);opacity:.9} + .ogl-cover{height:76px;border-bottom:1px solid rgba(168,191,245,.13); + background:linear-gradient(115deg,rgba(26,167,208,.14),transparent 45%), + radial-gradient(circle at 78% 60%,rgba(125,106,228,.25),transparent 35%)} + .ogl-profile{position:relative;display:flex;align-items:center;gap:16px; + padding:0 20px 22px;margin-top:-23px} + .ogl-portrait{display:inline-flex;align-items:center;justify-content:center; + flex:none;width:66px;height:66px;border:3px solid #17274a;border-radius:20px; + color:white;font-weight:800;font-size:21px;letter-spacing:-1px; + background:linear-gradient(145deg,#087b9d,#516dda 55%,#986fe7); + box-shadow:0 9px 22px rgba(10,13,37,.38)} + .ogl-portrait-small{width:42px;height:42px;font-size:13px; + border-radius:13px;border-width:2px} + .ogl-profile-copy{padding-top:24px;min-width:0} + .ogl-kicker{color:#89eaf2;font-size:10px;letter-spacing:1.6px; + font-weight:800;text-transform:uppercase} + .ogl-profile h1{font-size:clamp(19px,4vw,26px);line-height:1.25; + margin:3px 0 2px;overflow-wrap:anywhere;letter-spacing:-.5px} + .ogl-subtitle{color:#adc4e1;font-size:12px} + .ogl-controls{display:flex;align-items:center;gap:8px;flex-wrap:wrap; + margin:14px 0 6px;padding:10px;background:rgba(20,33,59,.75); + border:1px solid var(--nv-border);border-radius:15px} + .ogl-navtabs{display:flex;align-items:center;gap:5px;flex-wrap:wrap} + .ogl-controls button{border-color:transparent;background:transparent} + .ogl-controls button[aria-pressed=true]{background:rgba(73,127,205,.28); + border-color:rgba(124,187,246,.38);color:#effdff} + .ogl-controls .ogl-login{background:linear-gradient(110deg,#387bb3,#5b55bb); + font-weight:650} + .ogl-spacer{flex:1} + .ogl-auth-status{margin:5px 4px 14px;font-size:11px;color:var(--nv-muted)} + .ogl-compose{margin:12px 0 17px;padding:18px;border-radius:var(--nv-radius); + border:1px solid rgba(105,173,238,.29); + background:linear-gradient(145deg,rgba(26,48,78,.96),rgba(20,28,56,.97)); + box-shadow:0 12px 32px rgba(5,9,25,.20)} + .ogl-compose-heading{display:flex;align-items:center;gap:12px;margin-bottom:13px} + .ogl-compose-heading strong{display:block;font-size:14px} + .ogl-compose-heading .sub{display:block;font-size:11px} + textarea{resize:vertical;display:block;width:100%;min-height:90px; + border:1px solid rgba(137,171,219,.3);border-radius:12px; + color:var(--nv-txt);background:rgba(6,15,32,.65);padding:12px 14px; + font-size:13px;line-height:1.6} + textarea::placeholder{color:#7f98b8} + .ogl-compose-bottom{display:flex;align-items:center;justify-content:flex-end; + gap:12px;margin-top:12px;flex-wrap:wrap} + .ogl-compose-hint{margin-right:auto;color:#829dbb;font-size:11px} + .ogl-auto-settings{margin:10px 0 15px;padding:16px; + border:1px solid var(--nv-border);border-radius:var(--nv-radius); + background:linear-gradient(120deg,rgba(18,37,58,.97),rgba(26,31,57,.97))} + .ogl-auto-title{display:flex;align-items:center;justify-content:space-between;gap:10px} + .ogl-auto-title h3{margin:0;font-size:15px} + .ogl-private-chip{color:#9fe4d9;background:rgba(28,134,133,.13); + border:1px solid rgba(83,189,174,.3);padding:4px 9px;border-radius:999px; + font-size:10px;white-space:nowrap} + .ogl-toggle{display:flex;align-items:center;gap:10px;margin-top:8px; + padding:10px 11px;border:1px solid rgba(130,171,218,.17); + border-radius:10px;background:rgba(7,15,35,.34);cursor:pointer} + .ogl-toggle input{width:18px;height:18px;accent-color:#6196ec; + cursor:pointer;flex:none} + .ogl-settings-actions{display:flex;align-items:center;justify-content:space-between; + gap:9px;flex-wrap:wrap;margin-top:12px} + .ogl-follow-controls{display:flex;align-items:center;gap:14px; + justify-content:space-between;margin:12px 0;padding:10px 13px; + background:rgba(31,49,76,.55);border:1px solid var(--nv-border);border-radius:12px} + .ogl-feedback{margin:4px 2px;color:var(--nv-cyan);font-size:12px} + .ogl-error{color:#ffb6ae!important} + .ogl-stream-heading{display:flex;align-items:center;justify-content:space-between; + margin:18px 2px 10px;padding:0 3px} + .ogl-stream-heading h2{font-size:16px;margin:0;font-weight:750;letter-spacing:-.2px} + .ogl-eyebrow{font-size:10px;letter-spacing:1.5px;color:#87b9e1;font-weight:750} + .ogl-live-dot{width:8px;height:8px;border-radius:50%;background:#76dfcf; + box-shadow:0 0 0 5px rgba(75,208,191,.1)} + .post{position:relative;overflow:hidden;margin:11px 0;padding:18px 19px 15px; + background:linear-gradient(135deg,rgba(24,40,69,.96),rgba(18,28,52,.96)); + border:1px solid var(--nv-border);border-radius:var(--nv-radius); + box-shadow:0 6px 19px rgba(0,0,0,.12)} + .post:hover{border-color:rgba(125,178,241,.38)} + .ogl-post-header{display:flex;gap:11px;align-items:center;margin-bottom:12px} + .ogl-post-avatar{width:38px;height:38px;flex:none;display:flex;align-items:center; + justify-content:center;border-radius:12px;color:#ddf9ff;font-size:13px; + font-weight:850;background:linear-gradient(135deg,#206a8b,#6654b9)} + .ogl-post-who{min-width:0;flex:1} + .ogl-post-name{font-weight:750;font-size:13px;color:#f3f7ff; + overflow-wrap:anywhere} + .ogl-post-name a{color:inherit} + .meta{color:#94adce;font-size:11px} + .content{white-space:pre-wrap;overflow-wrap:anywhere;font-size:14px; + line-height:1.75;color:#e5f1ff;margin:0 0 17px} + .ogl-reactions{border-top:1px solid rgba(155,185,236,.13); + padding-top:11px;color:#9cb5d3;font-size:11px} + .ogl-actions{display:flex;gap:7px;flex-wrap:wrap;margin-top:9px} + .ogl-actions button{min-height:32px;font-size:11px;padding:5px 9px} + .ogl-actions .ogl-liked{color:#f9a2d8;border-color:rgba(245,137,206,.36); + background:rgba(185,56,129,.13)} + .ogl-comment-list{margin-top:11px} + .comment{margin:7px 0 0;padding:10px 12px;background:rgba(9,22,43,.65); + border-left:3px solid #5586da;border-radius:4px 11px 11px 4px; + color:#dceafe;white-space:pre-wrap;overflow-wrap:anywhere} + .comment strong{color:#90d8f4} + .ogl-comment-compose{display:flex;gap:7px;margin-top:9px;align-items:flex-end} + .ogl-comment-compose textarea{min-height:45px;flex:1} + .sub,.ogl-muted{color:var(--nv-muted);font-size:12px} + .ogl-user-link{color:#9de6f5} + .ogl-empty{padding:38px 18px;text-align:center;border:1px dashed + rgba(124,171,227,.28);border-radius:17px;margin:10px 0; + color:#b5cce4;background:rgba(23,43,70,.35)} + .ogl-loading{opacity:.65} + footer.ogl-footer{display:flex;align-items:center;justify-content:space-between; + gap:10px;flex-wrap:wrap;padding:22px 4px 10px;color:#859bb9; + font-size:11px;border-top:1px solid rgba(146,177,227,.11);margin-top:24px} + .ogl-powered{color:#91a5bd;letter-spacing:.2px} + .ogl-powered strong{color:#cad6ea;font-weight:650} + .ogl-visually-hidden{position:absolute;width:1px;height:1px;padding:0; + margin:-1px;overflow:hidden;clip:rect(0,0,0,0);white-space:nowrap;border:0} + @media(max-width:560px){ + .ogl-shell{padding:0 12px 24px}.ogl-profile{padding:0 14px 17px;gap:11px} + .ogl-portrait{width:58px;height:58px;border-radius:17px} + .ogl-brandbar{padding-top:13px}.ogl-network-chip{font-size:10px} + .ogl-controls{padding:7px}.ogl-controls button{font-size:12px;padding:6px 9px} + .ogl-navtabs{flex:1}.ogl-compose,.post{padding:14px;border-radius:14px} + .ogl-compose-hint{display:none}.ogl-profile-copy{padding-top:18px} + .ogl-comment-compose{flex-direction:column;align-items:stretch} + .ogl-comment-compose button{align-self:flex-end} + } + @media(prefers-reduced-motion:reduce){ + *,*::before,*::after{transition:none!important;scroll-behavior:auto!important} + } + """; + } + + internal static string Script(string nonce, string ownerId, + string ownerName, bool published, string clientId, string redirectUri) + { + string json=JsonSerializer.Serialize(new { + ownerId=ownerId ?? "", ownerName=ownerName ?? "", + published, clientId=clientId ?? "", redirectUri=redirectUri ?? "" + }); + // System.Text.Json's default encoder escapes '<' and other + // HTML-significant characters; the JSON element is not executable. + return ""; + } + + internal static string CallbackPage(string nonce, string clientId, + string redirectUri) + { + return "" + + "" + + "Stadt NexVerse - Avatar-Anmeldung

Stadt NexVerse

" + + "

Anmeldung wird abgeschlossen...

" + + Script(nonce, "", "", false, clientId, redirectUri) + + ""; + } + + private const string ScriptBody = """ + (() => { + 'use strict'; + const config = JSON.parse(document.getElementById('ogl-cfg').textContent); + const $ = (id) => document.getElementById(id); + const params = new URL(location.href).searchParams; + const tokenKey = 'oglFeedAccess'; + const expiresKey = 'oglFeedExpires'; + const pendingKey = 'oglFeedPending'; + const scope = 'profile:read profile:write relationships:read relationships:write'; + const base = '/api/v1/feed/'; + let me = null, tab = 'profile', following = false; + let liked = new Set(), loadedPosts = []; + function feedback(message, problem = false) { + const target = $('ogl-feedback'); + if (!target) return; + target.textContent = message || ''; + target.classList.toggle('ogl-error', !!problem); + } + function authStatus(message) { + if ($('ogl-auth-status')) $('ogl-auth-status').textContent = message; + } + function access() { + const expires = Number(sessionStorage.getItem(expiresKey) || 0); + if (expires <= Date.now()) { + sessionStorage.removeItem(tokenKey); + sessionStorage.removeItem(expiresKey); + return ''; + } + return sessionStorage.getItem(tokenKey) || ''; + } + function node(tag, className, text, parent) { + const element = document.createElement(tag); + if (className) element.className = className; + if (text !== undefined) element.textContent = String(text); + if (parent) parent.appendChild(element); + return element; + } + function action(label, parent, handler) { + const element = node('button', '', label, parent); + element.type = 'button'; + element.addEventListener('click', () => { + Promise.resolve(handler()).catch(e => feedback(e.message, true)); + }); + return element; + } + function formatTime(timestamp) { + const d = new Date(Number(timestamp) * 1000); + return Number.isFinite(d.getTime()) ? d.toLocaleString('de-DE') : ''; + } + async function api(path, method = 'GET', body) { + const headers = { Accept: 'application/json' }; + const token = access(); + if (token) headers.Authorization = 'Bearer ' + token; + if (body !== undefined) headers['Content-Type'] = 'application/json'; + const response = await fetch(path, { + method, headers, credentials: 'omit', cache: 'no-store', + body: body === undefined ? undefined : JSON.stringify(body) + }); + const data = await response.json().catch(() => ({})); + if (!response.ok) { + if (response.status === 401) { + sessionStorage.removeItem(tokenKey); + sessionStorage.removeItem(expiresKey); + } + throw Error(data.error || ('HTTP ' + response.status)); + } + return data; + } + function b64url(bytes) { + return btoa(String.fromCharCode(...bytes)) + .replaceAll('+', '-').replaceAll('/', '_').replace(/=+$/g, ''); + } + async function startLogin() { + if (!config.clientId || !config.redirectUri) { + throw Error('Die OAuth-Anmeldung ist auf ROBUST noch nicht konfiguriert.'); + } + const redirect = new URL(config.redirectUri); + if (redirect.origin !== location.origin || redirect.pathname !== '/feed' || + redirect.search || redirect.hash || location.protocol !== 'https:') { + throw Error('Der OAuth-Ruecksprung muss dieselbe HTTPS-Domain /feed verwenden.'); + } + if (!crypto || !crypto.subtle) { + throw Error('Dieser Viewer-Browser unterstuetzt kein sicheres PKCE.'); + } + const verifier = b64url(crypto.getRandomValues(new Uint8Array(32))); + const state = b64url(crypto.getRandomValues(new Uint8Array(24))); + const digest = await crypto.subtle.digest('SHA-256', + new TextEncoder().encode(verifier)); + const challenge = b64url(new Uint8Array(digest)); + sessionStorage.setItem(pendingKey, JSON.stringify({ + verifier, state, target: config.ownerName, at: Date.now() + })); + const url = new URL('/oauth/authorize', location.origin); + for (const [k, v] of Object.entries({ + response_type: 'code', client_id: config.clientId, + redirect_uri: redirect.href, code_challenge: challenge, + code_challenge_method: 'S256', scope, state + })) url.searchParams.set(k, v); + location.assign(url.href); + } + async function completeLogin() { + const code = params.get('code'); + const oauthError = params.get('error'); + if (!code && !oauthError) return false; + // Remove one-time code from browser history before any + // network request or further UI navigation. + history.replaceState(null, '', '/feed'); + const raw = sessionStorage.getItem(pendingKey); + sessionStorage.removeItem(pendingKey); + if (!raw) throw Error('Anmeldung abgelaufen: bitte erneut starten.'); + const pending = JSON.parse(raw); + if (Date.now() - pending.at > 10 * 60 * 1000 || + params.get('state') !== pending.state) { + throw Error('OAuth-Sicherheitspruefung fehlgeschlagen (state).'); + } + if (oauthError) throw Error('Anmeldung abgelehnt: ' + oauthError); + const form = new URLSearchParams({ + grant_type: 'authorization_code', + client_id: config.clientId, + redirect_uri: config.redirectUri, + code, code_verifier: pending.verifier + }); + const response = await fetch('/oauth/token', { + method: 'POST', credentials: 'omit', cache: 'no-store', + headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, + body: form + }); + const data = await response.json(); + if (!response.ok || !data.access_token) + throw Error(data.error || 'Token-Austausch fehlgeschlagen.'); + sessionStorage.setItem(tokenKey, data.access_token); + sessionStorage.setItem(expiresKey, + String(Date.now() + Math.max(0, Number(data.expires_in || 0) - 30) * 1000)); + const target = pending.target || ''; + location.replace(target ? '/feed?name=' + encodeURIComponent(target) : '/feed'); + return true; + } + async function logout() { + const token = access(); + sessionStorage.removeItem(tokenKey); + sessionStorage.removeItem(expiresKey); + me = null; + renderAccess(); + feedback('Avatar abgemeldet.'); + if (token) { + const body = new URLSearchParams({ token }); + fetch('/oauth/revoke', { method: 'POST', credentials: 'omit', + headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, + body }).catch(() => {}); + } + await load(); + } + function renderAccess() { + const signedIn = !!me; + if ($('ogl-login')) $('ogl-login').hidden = signedIn || !config.clientId; + if ($('ogl-logout')) $('ogl-logout').hidden = !signedIn; + if ($('ogl-compose')) $('ogl-compose').hidden = + !signedIn || me.avatar_id !== config.ownerId; + if ($('ogl-follow-controls')) $('ogl-follow-controls').hidden = + !signedIn || !config.ownerId || me.avatar_id === config.ownerId || + !config.published; + if ($('ogl-auto-settings')) $('ogl-auto-settings').hidden = + !signedIn || me.avatar_id !== config.ownerId || tab !== 'profile'; + if ($('ogl-tab-following')) $('ogl-tab-following').disabled = !signedIn; + authStatus(signedIn ? 'Angemeldet als ' + me.name : + (config.clientId ? 'Zum Schreiben mit deinem Avatar anmelden.' : + 'Dieser Feed ist derzeit nur lesbar (OAuth nicht konfiguriert).')); + } + function switchTab(next) { + if (next === 'following' && !me) { + feedback('Zum Lesen deiner abonnierten Beitraege zuerst anmelden.', true); + return; + } + tab = next; + for (const t of ['profile', 'following']) { + if ($('ogl-tab-' + t)) + $('ogl-tab-' + t).setAttribute('aria-pressed', String(t === next)); + } + if ($('ogl-compose')) $('ogl-compose').hidden = + next !== 'profile' || !me || me.avatar_id !== config.ownerId; + if ($('ogl-follow-controls')) $('ogl-follow-controls').hidden = + next !== 'profile' || !me || me.avatar_id === config.ownerId || + !config.published; + if ($('ogl-auto-settings')) $('ogl-auto-settings').hidden = + next !== 'profile' || !me || me.avatar_id !== config.ownerId; + load().catch(e => feedback(e.message, true)); + } + async function loadActivitySettings() { + if (!me || me.avatar_id !== config.ownerId) return; + const data = await api(base + 'me/activities'); + $('ogl-auto-events').checked = !!data.auto_events; + $('ogl-auto-classifieds').checked = !!data.auto_classifieds; + } + async function saveActivitySettings() { + if (!me || me.avatar_id !== config.ownerId) return; + const button = $('ogl-save-activities'); + button.disabled = true; + try { + await api(base + 'me/activities', 'PUT', { + auto_events: $('ogl-auto-events').checked, + auto_classifieds: $('ogl-auto-classifieds').checked + }); + feedback('Deine automatischen Aktivitaeten wurden gespeichert.'); + } finally { button.disabled = false; } + } + async function publish() { + const box = $('ogl-post-text'); + const text = box.value.trim(); + if (!text || text.length > 1500) return feedback('Bitte Text mit 1-1500 Zeichen eingeben.', true); + const button = $('ogl-publish'); + button.disabled = true; + try { + await api(base + config.ownerId, 'POST', { text }); + box.value = ''; + $('ogl-counter').textContent = '0/1500'; + feedback('Dein Beitrag wurde veroeffentlicht.'); + await load(); + } finally { button.disabled = false; } + } + async function toggleFollow() { + const next = !following; + await api(base + config.ownerId + '/following', next ? 'PUT' : 'DELETE'); + following = next; + $('ogl-follow').textContent = following ? 'Entfolgen' : 'Folgen'; + feedback(following ? 'Avatar abonniert.' : 'Avatar nicht mehr abonniert.'); + await load(); + } + async function toggleLike(owner, post) { + const wasLiked = liked.has(post); + await api(base + owner + '/' + post + '/likes', wasLiked ? 'DELETE' : 'PUT'); + if (wasLiked) liked.delete(post); else liked.add(post); + await load(); + } + async function displayComments(owner, post, target) { + target.replaceChildren(); + const data = await api(base + owner + '/' + post + '/comments'); + for (const comment of (data.comments || [])) { + const line = node('div', 'comment', '', target); + node('strong', '', comment.author_name || 'Einwohner', line); + node('span', '', ': ' + comment.text, line); + if (me && comment.author_id === me.avatar_id) { + action('Loeschen', line, async () => { + await api(base + owner + '/' + post + '/comments/' + comment.id, 'DELETE'); + await displayComments(owner, post, target); + }); + } + } + if (me) { + const row = node('div', 'ogl-comment-compose', '', target); + const entry = node('textarea', '', '', row); + entry.maxLength = 800; + entry.rows = 2; + entry.placeholder = 'Kommentar schreiben...'; + const send = action('Senden', row, async () => { + const text = entry.value.trim(); + if (!text || text.length > 800) return; + send.disabled = true; + try { + await api(base + owner + '/' + post + '/comments', 'POST', { text }); + await displayComments(owner, post, target); + feedback('Kommentar gespeichert.'); + } finally { send.disabled = false; } + }); + } + } + function initials(displayName) { + const words = String(displayName || 'NexVerse').trim().split(/[.\s]+/).filter(Boolean); + const letters = words.slice(0, 2).map(w => w.slice(0, 1).toUpperCase()).join(''); + return letters || 'NV'; + } + function renderPost(data, parent) { + const owner = data.owner_id || config.ownerId; + const name = data.owner_name || config.ownerName || 'Einwohner'; + const section = node('article', 'post', '', parent); + const header = node('div', 'ogl-post-header', '', section); + node('span', 'ogl-post-avatar', initials(name), header) + .setAttribute('aria-hidden', 'true'); + const author = node('div', 'ogl-post-who', '', header); + const authorName = node('div', 'ogl-post-name', '', author); + if (data.owner_name) { + const link = node('a', 'ogl-user-link', name, authorName); + link.href = '/feed?name=' + encodeURIComponent(name.replaceAll(' ', '.')); + } else { + node('strong', '', name, authorName); + } + node('div', 'meta', formatTime(data.created_at), author); + node('div', 'content', data.text, section); + const likes = Number(data.likes || 0); + const comments = Number(data.comments || 0); + node('div', 'ogl-reactions', likes + ' Gefaellt mir · ' + + comments + ' Kommentare', section); + const buttons = node('div', 'ogl-actions', '', section); + if (me) { + const likeBtn = action(liked.has(data.id) ? '♥ Gefaellt mir' : '♡ Gefaellt mir', + buttons, () => toggleLike(owner, data.id)); + if (liked.has(data.id)) likeBtn.classList.add('ogl-liked'); + likeBtn.setAttribute('aria-pressed', String(liked.has(data.id))); + } + const commentArea = node('div', 'ogl-comment-list', '', section); + action('◌ Kommentare', buttons, + () => displayComments(owner, data.id, commentArea)); + if (me && me.avatar_id === owner) { + action('Beitrag loeschen', buttons, async () => { + if (!confirm('Diesen Beitrag dauerhaft loeschen?')) return; + await api(base + owner + '/' + data.id, 'DELETE'); + feedback('Beitrag geloescht.'); + await load(); + }); + } + } + async function load() { + if (!config.ownerId) return; + if ($('ogl-stream-title')) $('ogl-stream-title').textContent = + tab === 'following' ? 'Aus deinem Netzwerk' : 'Aktuelles aus dem Profil'; + const target = $('ogl-feed-posts'); + if (!target) return; + const route = tab === 'following' ? base + 'timeline' : base + config.ownerId; + const data = await api(route); + following = !!data.following; + if ($('ogl-follow')) $('ogl-follow').textContent = + following ? 'Entfolgen' : 'Folgen'; + liked = new Set(data.liked_post_ids || []); + loadedPosts = data.posts || []; + target.replaceChildren(); + if (!loadedPosts.length) { + node('div', 'ogl-empty', tab === 'following' ? + 'Dein Feed ist noch ruhig. Folge anderen Einwohnern, um ihre Geschichten zu sehen.' : + 'Noch keine Beitraege. Der naechste NexVerse-Moment wartet schon.', target); + return; + } + for (const post of loadedPosts) renderPost(post, target); + } + async function initialize() { + // This is the fixed registered OAuth callback, without name. + if (params.has('code') || params.has('error')) { + try { await completeLogin(); } + catch (error) { feedback(error.message, true); } + return; + } + if ($('ogl-tab-profile')) { + $('ogl-login').addEventListener('click', () => + startLogin().catch(e => feedback(e.message, true))); + $('ogl-logout').addEventListener('click', logout); + $('ogl-publish').addEventListener('click', () => + publish().catch(e => feedback(e.message, true))); + $('ogl-post-text').addEventListener('input', (event) => { + $('ogl-counter').textContent = event.target.value.length + '/1500'; + }); + $('ogl-follow').addEventListener('click', () => + toggleFollow().catch(e => feedback(e.message, true))); + $('ogl-save-activities').addEventListener('click', () => + saveActivitySettings().catch(e => feedback(e.message, true))); + for (const name of ['profile', 'following']) { + $('ogl-tab-' + name).addEventListener('click', () => switchTab(name)); + } + } + if (access()) { + try { me = await api(base + 'me'); } + catch (error) { + sessionStorage.removeItem(tokenKey); + sessionStorage.removeItem(expiresKey); + } + } + renderAccess(); + try { await loadActivitySettings(); } + catch (error) { feedback('Auto-Aktivitaeten: ' + error.message, true); } + try { await load(); } catch (error) { feedback(error.message, true); } + } + initialize().catch(error => feedback(error.message, true)); + })(); + """; + } +} diff --git a/OpenSim/Services/UserAccountService/UserAccountService.cs b/OpenSim/Services/UserAccountService/UserAccountService.cs index 67403c0e..ae9b1912 100644 --- a/OpenSim/Services/UserAccountService/UserAccountService.cs +++ b/OpenSim/Services/UserAccountService/UserAccountService.cs @@ -950,6 +950,32 @@ namespace OpenSim.Services.UserAccountService "Partial OGL Profile Feed schema; account deletion stopped."); if (feedTables == 4) { + // Optional G1 Feed v2/v3 activity settings and idempotency + // receipts are purged in the same account transaction. + // A partially installed extension schema is unsafe. + int activityTables; + using (DbCommand activity = db.CreateCommand()) + { + activity.Transaction = tx; + activity.CommandText = @"SELECT COUNT(*) FROM information_schema.tables + WHERE table_schema = DATABASE() + AND table_name IN ('ogl_profile_feed_activity_settings', + 'ogl_profile_feed_activity_receipts')"; + activityTables = Convert.ToInt32(activity.ExecuteScalar()); + } + if (activityTables != 0 && activityTables != 2) + throw new InvalidOperationException( + "Partial OGL Profile Feed activity schema; account deletion stopped."); + if (activityTables == 2) + { + DeletionSql(db, tx, + "DELETE FROM `ogl_profile_feed_activity_receipts` WHERE `owner` = @userId", + avatarId, false, true); + DeletionSql(db, tx, + "DELETE FROM `ogl_profile_feed_activity_settings` WHERE `owner` = @userId", + avatarId, false, true); + } + // Delete own interactions with other profiles first. // Post deletion cascades to post-owned comments/likes. DeletionSql(db, tx, diff --git a/bin/Robust.HG.ini b/bin/Robust.HG.ini index 82c17fb9..5dba6ab8 100644 --- a/bin/Robust.HG.ini +++ b/bin/Robust.HG.ini @@ -776,11 +776,15 @@ [NexVerseWorldApi] Enabled = true - ; OGL Profilfeed: bleibt deaktiviert bis Account-Loeschflow und Retention abgesichert sind. - EnableProfileFeed = false + ; OGL Profilfeed standardmaessig aktiv, bei nicht passender Datenbank fail-closed. + EnableProfileFeed = true ; Feedbeitraege und Kommentare nach 180 Tagen automatisch ausblenden ; und loeschen; zulaessig 7..3650 Tage. Follows bis zur Entfolgung. ProfileFeedRetentionDays = 180 + ; Optional custom public OAuth client ID, never a secret. Empty means + ; auto-provision the first-party public client at ROBUST start. + ; A manually disabled client stays disabled; never silently reactivate. + ProfileFeedOAuthClientId = "" ; Only the Stadtportal BACKEND with a dedicated users:register API key ; may register avatars. Enable after publishing Benjamin/Luna models. ; Registrierungs-POST ist nur mit users:register-Maschinenschlüssel diff --git a/bin/Robust.HG.ini.example b/bin/Robust.HG.ini.example index 8744f13d..e61e4be0 100644 --- a/bin/Robust.HG.ini.example +++ b/bin/Robust.HG.ini.example @@ -777,11 +777,15 @@ ; may register avatars. Enable after publishing Benjamin/Luna models. PortalAvatarRegistrationEnabled = false ; Optional local profile feed. Creates 4 MariaDB tables when enabled. - ; Keep off until account deletion/retention and Viewer tests are signed off. - EnableProfileFeed = false + ; Enabled by default; schema/account deletion checks fail closed if unsafe. + EnableProfileFeed = true ; Feedbeitraege und Kommentare nach 180 Tagen automatisch ausblenden ; und loeschen; zulaessig 7..3650 Tage. Follows bis zur Entfolgung. ProfileFeedRetentionDays = 180 + ; Optional custom public OAuth client ID, never a secret. Empty means + ; auto-provision the first-party public client at ROBUST start. + ; A manually disabled client stays disabled; never silently reactivate. + ProfileFeedOAuthClientId = "" ; P0 #301: keep disabled until the portal has migrated to World-owned ; one-time challenges. Backend must hold separate recovery-only API key. ; Challenges are stored in a new InnoDB table (ogl_password_recovery) diff --git a/bin/Robust.ini.example b/bin/Robust.ini.example index 46ba7b9f..38800e12 100644 --- a/bin/Robust.ini.example +++ b/bin/Robust.ini.example @@ -654,11 +654,15 @@ ; may register avatars. Enable after publishing Benjamin/Luna models. PortalAvatarRegistrationEnabled = false ; Optional local profile feed. Creates 4 MariaDB tables when enabled. - ; Keep off until account deletion/retention and Viewer tests are signed off. - EnableProfileFeed = false + ; Enabled by default; schema/account deletion checks fail closed if unsafe. + EnableProfileFeed = true ; Feedbeitraege und Kommentare nach 180 Tagen automatisch ausblenden ; und loeschen; zulaessig 7..3650 Tage. Follows bis zur Entfolgung. ProfileFeedRetentionDays = 180 + ; Optional custom public OAuth client ID, never a secret. Empty means + ; auto-provision the first-party public client at ROBUST start. + ; A manually disabled client stays disabled; never silently reactivate. + ProfileFeedOAuthClientId = "" ; P0 #301: keep disabled until the portal has migrated to World-owned ; one-time challenges. Backend must hold separate recovery-only API key. ; Challenges are stored in a new InnoDB table (ogl_password_recovery) diff --git a/doc/OpenGenesisLINK/OGL_PROFILE_FEED_INTERACTIVE_V2.md b/doc/OpenGenesisLINK/OGL_PROFILE_FEED_INTERACTIVE_V2.md new file mode 100644 index 00000000..c63c1914 --- /dev/null +++ b/doc/OpenGenesisLINK/OGL_PROFILE_FEED_INTERACTIVE_V2.md @@ -0,0 +1,203 @@ +# OpenGenesisLINK Generation 1: interaktiver Profilfeed (v2) + +Der Feed ist in der ausgelieferten ROBUST-Konfiguration standardmaessig +aktiv. Die Serverpruefungen fuer die gemeinsame MariaDB und die lokale +Konto-Loeschung bleiben verpflichtend; bei Fehlern wird das Modul +abgewiesen. Die interaktive OAuth-App wird beim ersten Start mit einem +stabilen, oeffentlichen First-Party-Client automatisch eingerichtet. +Wenn ein Administrator diesen Client deaktiviert oder veraendert, wird +er **nicht** automatisch wieder aktiviert. + +Ab dieser Stufe kann +ein lokaler Stadt-NexVerse-Avatar im eingebetteten Firestorm-Webprofil +nach einer **eigenstaendigen, sicheren OAuth-Anmeldung** direkt posten, +kommentieren, liken, folgen und seine "Abonniert"-Timeline ansehen. +Ein nativer TrixieStorm-Tab ist dafuer nicht erforderlich. + +**Datenschutz/Technik:** Der Viewer uebergibt dem eingebetteten Browser +weder Passwort noch simulatorseitigen Maschinenschluessel. +Die Anmeldung wird allein ueber den bestehenden `/oauth/authorize`-Dienst +mit Avatarname, Passwort und ggf. TOTP durchgefuehrt. OAuth 2.0 +Authorization Code mit PKCE S256, zufaelligem `state`, registriertem +exaktem Redirect und kurzem Zugriffstoken. Keine Passwoerter im Feed, +keine OAuth-Tokens in Query-Parametern, keine Browser-Maschinenkeys. +Der Token wird **ausschliesslich in sessionStorage** des HTTPS-Ursprungs +verwahrt und laeuft standardmaessig nach 1800 Sekunden ab; kein +`offline_access`/Refresh-Token. Logout entfernt und widerruft den Token +(soweit der Revocation-Dienst erreichbar ist). +In Browsern ohne `crypto.subtle` oder `sessionStorage` kann man die +Weboberflaeche nur lesend verwenden. Inworld-Viewer-Browser muessen +HTTPS und PKCE/WebCrypto unterstuetzen. + +## 1. Voraussetzungen + +- `EnableProfileFeed=true` und die gemeinsame MariaDB aus + [Rollout v1](OGL_PROFILE_FEED_ROLLOUT.md). +- `[NexVerseWorldApi] EnableNativeTokens=true` und funktionierendes + OIDC/OAuth-Backend mit gesichertem Signing Key. Ohne das keine + interaktive Feed-Anmeldung. +- `[NexVerseWorldApi] PublicBaseUrl` muss **exakt** die oeffentliche + HTTPS-Origin des Feeds sein, z. B. `https://world.stadt-nexverse.de`. +- Reverse Proxy muss `/feed`, `/api/v1/feed`, `/oauth/authorize`, + `/oauth/token`, `/oauth/revoke` auf denselben ROBUST routen. +- Avatar-Login funktioniert ueber den bestehenden interaktiven + `/oauth/authorize`-Browser-Flow. UserLevel/Scopes stammen aus + `NexAuthorizationPolicy`. Keine manuelle Weitergabe von Tokens. + +## 2. OAuth-Client wird standardmaessig automatisch eingerichtet + +Bei einer normalen ROBUST-Installation reicht: + +```ini +[NexVerseWorldApi] +EnableProfileFeed = true +EnableNativeTokens = true +ProfileFeedRetentionDays = 180 +ProfileFeedOAuthClientId = "" +PublicBaseUrl = "https://world.stadt-nexverse.de" +``` + +ROBUST erstellt beim ersten Start einen **oeffentlichen First-Party-OAuth- +Client** `Stadt NexVerse Profile Feed` im bestehenden, persistenten +OAuth-Speicher. Der Client hat ausschliesslich +`profile:read profile:write relationships:read relationships:write` und +die exakt registrierte HTTPS-Redirect-Adresse +`https://world.stadt-nexverse.de/feed`. Es wird kein geheimer +Client-Key in den Browser gegeben. + +Weitere ROBUST-Neustarts verwenden denselben Client, ohne Duplikate. +Ein absichtlich deaktivierter oder in Redirect/Berechtigungen +veraenderter Client wird **nicht** stillschweigend wiederhergestellt: +die interaktive Anmeldung bleibt dann aus, waehrend das Feedprofil +lesbar bleibt. Ein Administrator kann stattdessen einen eigenen +Public Client registrieren und dessen ID explizit in +`ProfileFeedOAuthClientId` setzen. `EnableProfileFeed=false` deaktiviert +das gesamte Feed-Modul. + +Nach einem Upgrade ROBUST kontrolliert neu starten, dann +`https://world.stadt-nexverse.de/feed?name=First.Last` +im Viewer oeffnen und die Anmeldung mit einem Testavatar pruefen. +Vorhandene Posts/Kommentare werden nicht neu angelegt oder geloescht. + +## 3. Bedienung im Profil + +1. Eigene oder fremde lokale Avatarprofile im Viewer oeffnen und auf + **Mit Avatar anmelden** klicken. +2. Im OAuth-Formular mit Avatarname, Passwort und ggf. TOTP anmelden. + Danach kehrt der Browser zu demselben Profil zurueck. +3. Im **eigenen** Profil erscheint "Was gibt es Neues?" zum Schreiben. + Maximal 1500 Zeichen, hoechstens drei Posts/10 Minuten und + 30 Posts/24 Stunden. Der Avatar kann eigene Posts loeschen. +4. In **oeffentlichen** fremden Profilen kann man + **Folgen/Entfolgen**, kommentieren (maximal 800 Zeichen, 10/min) + und **Gefaellt mir** setzen/entfernen. Eigene Kommentare lassen + sich loeschen. +5. Mit **Abonniert** sieht man den persoenlichen Feed aller + **noch oeffentlichen** gefolgten lokalen Avatare. Ein spaeter + privat gestelltes Profil verschwindet aus dieser Timeline. +6. **Abmelden** beendet die Browser-Sitzung; Token abgelaufen: + erneut anmelden. Kein dauerhafter Zugriff auf Avatarpasswoerter. + +Nur der Server prueft Owner, Scopes und Privatsphaere. Namen, Posttexte +und Kommentare werden fuer HTML serverseitig escaped bzw. +in JavaScript nur mit `textContent` eingefuegt. Die HTTP-HTML- +Antwort setzt `Cache-Control: no-store` und ein Nonce-basiertes +`Content-Security-Policy`, keine externen Skripte. + +## 4. Automatische Beitraege bei ausgewaehlten Aktivitaeten + +Im eigenen Stadt-NexVerse-Profil unter **Deine Aktivitaeten teilen** +koennen Einwohner getrennt zwei Optionen aktivieren: + +- **Neue freigegebene Events:** Nach der erstmaligen Freigabe eines + selbst organisierten Events im offiziellen Discovery-Dienst entsteht + ein kurzer Textbeitrag. +- **Neue freigegebene Eintraege:** Nach der erstmaligen Freigabe eines + eigenen Classifieds-Eintrags entsteht ein Textbeitrag. + +**Beide Optionen sind fuer jeden Einwohner standardmaessig aus.** +Die Freigabe ist individuell ueber das eigene Profil aenderbar. Die +automatische Publikation erfordert ausserdem einen lokalen, +aktivierten Avatar und ein oeffentliches Profil. Admins koennen keine +Feed-Einwilligung eines anderen Avatars ueber dessen OAuth-Token +vortaeuschen. + +Der NexVerse Discovery Service sendet Ereignisse erst bei der +Transition zu `Approved`. Der Feed-Service liest das Event oder +Classified **noch einmal aus dem autoritativen Discovery Store**, statt +beliebige Event-Bus-Texte als Beitrag zu uebernehmen. Nur Titel +(maximal 140 Zeichen) und die Art der Aktivitaet gelangen in den Post, +keine automatisch ausgelesenen Teleports, Onlinezeiten, Koordinaten +oder Inventarinhalte. Die Event-ID wird per MariaDB Unique-Key +dauerhaft gegen Doppelposts gesichert (solange der Beitrag noch +existiert). Hoechstens drei automatische Beitraege pro Stunde und +15 pro Tag. Die normalen Beitragslimits bleiben getrennt. + +Die Einstellungen und Duplikat-Receipts liegen in +`ogl_profile_feed_activity_settings` und +`ogl_profile_feed_activity_receipts`; das neue Schema wird bei +aktivem Feed automatisch erzeugt oder vorab ueber +`doc/OpenGenesisLINK/migrations/20261111_ogl_profile_feed_activity.sql` +installiert. Konto-Selbstloeschung und administrative Loeschung +entfernen beide Tabellen-Eintraege innerhalb der gleichen +MariaDB-Transaktion. Eine getrennte Datenbank fuer diese Werte wird +nicht verwendet. + +`GET /api/v1/feed/me/activities` mit `profile:read` liefert +`auto_events` und `auto_classifieds`. +`PUT /api/v1/feed/me/activities` mit `profile:write` +nimmt ausschliesslich Boolean-Einstellungen an, z. B.: + +```json +{"auto_events":true,"auto_classifieds":false} +``` + +Ein Konto kann diese Auswahl jederzeit widerrufen; bereits +veroeffentlichte Beitraege sind wie normale Posts einzeln loeschbar. +Aenderungen an bestehenden Discovery-Events erzeugen keine neuen +automatischen Posts. + +## 5. API-Erweiterungen + +- `GET /api/v1/feed/me` - lokaler Bearer-Avatar + (`profile:read`) +- `GET /api/v1/feed/timeline` - eigene gefolgte **oeffentliche** + Posts (`relationships:read`) +- `GET /api/v1/feed/{principalId}` - optional personalisierte + `following` und `liked_post_ids` bei gueltigem Bearer +- `GET /api/v1/feed/{principalId}/{postId}/comments` - + sichtbarer Kommentar-Verfassername + +Vorhandene POST-/DELETE-/PUT-APIs bleiben unveraendert; SQLite wird +nicht als neuer Feed-Datenspeicher verwendet. Das System ueberschreibt +keine bestehenden Viewer-Account-Daten. + +## 6. Abnahme + +- Anonyme Feedansicht und gesperrter Feed; Eigentuemer sieht Privat- + Feed erst nach OAuth; fremder Avatar wird serverseitig abgewiesen. +- Login auf demselben Browser/HTTPS-Origin; falscher `state` und + fehlender PKCE-Verifier werden abgewiesen. +- Login mit TOTP, erneutes Laden und Logout. Kein Token in + Webprofil-URL, Proxyzugriffslog oder Referer. +- Eigene Posts, Kommentare, Likes und Follow-Hierarchie mit + **zwei** Testavatares; fremder Profileigentumspfad 403. +- `Abonniert` nach einem PublishProfile-Opt-out: + Post darf **nicht** mehr angezeigt werden. +- Mobile Webansicht, Firestorm OpenSim 7.2.4 und TrixieStorm: + testen, ob Inworld-CEF `crypto.subtle` und sessionStorage + freigibt. Bei fehlenden Features im externen Browser testen. +- Reverse-Proxy routet OAuth und Feed; Backup und + Wiederherstellung der MariaDB bleiben Rollout-Voraussetzung. + +## 7. Nicht implementiert: Erweiterungsstufen + +Dies ist **nicht** bereits volle Second-Life-Paritaet. Es fehlen: +Snapshot-/Fotoupload (erfordert sichere Asset-Verknuepfung und +Metadatenbereinigung), granularere Leserechte (Freunde/nur Einwohner), +Meldesystem/Moderationsqueue, Benachrichtigungen, Suche nach Tags und +Orten, geplante Beitragsveroeffentlichung sowie Hypergrid-Foederation. + +Diese Funktionen duerfen erst nach separaten Sicherheits- und +Datenschutztests produktiv zugeschaltet werden; z. B. keine +automatische Veroeffentlichung von Standort oder Onlinezeiten. diff --git a/doc/OpenGenesisLINK/OGL_PROFILE_FEED_ROLLOUT.md b/doc/OpenGenesisLINK/OGL_PROFILE_FEED_ROLLOUT.md index 9ca99722..95d1af90 100644 --- a/doc/OpenGenesisLINK/OGL_PROFILE_FEED_ROLLOUT.md +++ b/doc/OpenGenesisLINK/OGL_PROFILE_FEED_ROLLOUT.md @@ -11,8 +11,9 @@ getrennten MariaDB-/Simulator-Staging die Schritte abarbeiten. fehlende Systemgebuehrenwallet wird **vor** dem Erzeugen erkannt. Ledger-Timeout nach externer Mutation bleibt ein zu pruefender Abstimmungsfall, keine magische Exactly-once-Transaktion. -- OGL Profilfeed v1: Posts, Kommentare, Likes und Folgen per - OAuth-geschuetzter World-API; lesende Web-Ansicht fuer den Viewer. +- OGL Profilfeed v2: Posts, Kommentare, Likes und Folgen per + OAuth-geschuetzter World-API; direkt bedienbares responsives + Stadt-NexVerse-Webprofil bei erfolgreichem PKCE-Login. - Feed aktiviert nur auf **derselben MariaDB** wie der lokale UserAccountService. Schreibvorgaenge sperren die Accountzeile; Selbstloeschung und administrative Kernloeschung entfernen eigene @@ -111,13 +112,17 @@ Gebuehrenwallet-Test bestaetigt werden. ## 4. Feed-Migration und Aktivierung -Zuerst ROBUST mit neuem Code und `EnableProfileFeed=false` starten. +Zuerst ROBUST im Staging mit neuem Code und bei Bedarf voruebergehend +`EnableProfileFeed=false` starten. Der konfigurierte Standard ist nun +`true`, sofern die gemeinsamen MariaDB-/Loeschbedingungen erfuellt sind. Live-Healthcheck `/api/v1/health` und aktuelle OAuth-Scopes pruefen. Optional und empfohlen: Migration `doc/OpenGenesisLINK/migrations/20261111_ogl_profile_feed.sql` vorab -in dieselbe MariaDB einspielen. Ohne manuellen Import erzeugt der -Opt-in-Feed beim ersten Start mit `CREATE TABLE IF NOT EXISTS` dieselben -vier InnoDB-Tabellen. Dies ist eine **Schema-Migration**, kein bloesser +in dieselbe MariaDB einspielen, gefolgt von +`doc/OpenGenesisLINK/migrations/20261111_ogl_profile_feed_activity.sql`. +Ohne manuellen Import erzeugt der +Feed beim ersten Start mit `CREATE TABLE IF NOT EXISTS` die vier +Basis- und zwei zusaetzliche InnoDB-Aktivitaetstabellen. Dies ist eine **Schema-Migration**, kein bloesser Schalter. Bei Produktionsbetrieb vorher Backup. Auf ROBUST im vorhandenen Block: @@ -126,6 +131,7 @@ Auf ROBUST im vorhandenen Block: [NexVerseWorldApi] EnableProfileFeed = true ProfileFeedRetentionDays = 180 +ProfileFeedOAuthClientId = "" [GridInfoService] web_profile_url = https://world.stadt-nexverse.de/feed?name=[AGENT_NAME] @@ -162,7 +168,7 @@ einer dedizierten Fee-Wallet durchspielen: Token/Passwoerter duerfen nicht in Logs und Browser-URLs auftauchen. - Staging-Kontoloeschung: der geloeschte Avatar hatte eigene Posts, Kommentare auf einem fremden Profil, Likes, Followers/Follows. - Danach in **allen vier Tabellen** keine Referenz auf diese UUID. + Danach in **allen sechs Tabellen** keine Referenz auf diese UUID. Post-Fremdkommentare auf dem geloeschten eigenen Feed fallen per Fremdschluessel-Kaskade ebenfalls weg. - Zwei parallele Requests Post-vs-Kontoloeschung: es darf kein @@ -183,8 +189,10 @@ Nur bei allen bestandenen Schritten Rollout freigeben. Wallet und Profil-/Group-/Upload-Pfade testen. 3. Zunaechst kostenpflichtige Aktionen auf weitere Nodes schalten, Ledger-/Job-Error-Rate und Transaktionsdifferenzen beobachten. -4. Feed separat erst nach Datenloesch-/Privatsphaere-Tests aktivieren. - Den Viewer nur als lesende Webansicht kommunizieren. +4. Feed separat erst nach Datenloesch-/Privatsphaere-Tests freigeben. + Der Viewer kann nach eigenstaendiger OAuth-PKCE-Anmeldung direkt + Statusbeitraege, Likes und Kommentare bearbeiten. Browser ohne + WebCrypto bleiben lesend. 5. Erst danach uebrige Nodes/Regionen rolling aktualisieren. Keine gleichzeitigen grossflaechigen Neustarts, keine automatischen Datenbank-Loeschjobs ausser der dokumentierten Retention. @@ -193,7 +201,8 @@ Nur bei allen bestandenen Schritten Rollout freigeben. Bei Fehlern `EnableProfileFeed=false` setzen und ROBUST kontrolliert neu starten; `web_profile_url` voruebergehend entfernen/deaktivieren. -Die vier Feed-Tabellen **nicht** loeschen: dies sind Einwohnerdaten. +Die sechs Feed-Tabellen **nicht** loeschen: dies sind Einwohnerdaten +einschliesslich privater Opt-in-Einstellungen. Aktive Schreib-/Loeschoperationen vor einem Downgrade drainen. Wird auf einen **alten** ROBUST-Build vor diesem Fix zurueckgestellt, `PortalAccountSelfDeleteEnabled=false` bis zur Wiederherstellung diff --git a/doc/OpenGenesisLINK/OGL_PROFILE_FEED_V1.md b/doc/OpenGenesisLINK/OGL_PROFILE_FEED_V1.md index b1516604..457fef66 100644 --- a/doc/OpenGenesisLINK/OGL_PROFILE_FEED_V1.md +++ b/doc/OpenGenesisLINK/OGL_PROFILE_FEED_V1.md @@ -1,6 +1,7 @@ # OpenGenesisLINK Profile Feed v1 — Stadt NexVerse -Status: **opt-in mit Rollout-Gates**, kein automatisches Live-Deployment. +Status: **standardmaessig aktiviert**, aber bei inkompatibler MariaDB +fail-closed; kein automatisches Produktiv-Deployment oder Neustart. Account-Loeschung und Retention sind im aktuellen Generation-1-Stand implementiert. Staging-/Viewer-Abnahme vor produktiver Freigabe erforderlich: [OGL_PROFILE_FEED_ROLLOUT.md](OGL_PROFILE_FEED_ROLLOUT.md). @@ -47,12 +48,14 @@ Posts/Kommentare werden HTML-escaped gerendert (keine aktiven HTML-Inhalte). Aus dem vorhandenen Inventar werden keine Medien oder privaten Texturen übernommen. Externe Bild-URLs sind in Phase 1 nicht unterstützt. -**Die Webansicht im unveränderten Firestorm ist vorerst lesend.** -Der Viewer stellt dem Feed-Webbrowser kein sicheres OAuth-Token zur Verfügung. -Texte, Kommentare, Likes und Followeraktionen werden deshalb über die -authentifizierte World API bedient; die Portalseite muss dafür noch ihre -Bedienoberfläche implementieren. Keine automatische Übernahme der Second-Life- -Feed-Daten; Stadt NexVerse betreibt einen eigenständigen Datenspeicher. +**Der v1-Modus bleibt ohne OAuth-Client lesend.** +Der unveraenderte Viewer uebergibt dem Feed-Webbrowser kein sicheres +OAuth-Token. Ab v2 kann sich der Avatar im Webprofil aber **separat** +ueber den bestehenden OAuth-Browserflow mit PKCE anmelden und Statusposts, +Kommentare, Likes und Follows direkt bedienen, ohne den Viewer zu patchen. +Siehe [interaktiver Feed v2](OGL_PROFILE_FEED_INTERACTIVE_V2.md). +Keine automatische Uebernahme der Second-Life-Feed-Daten; Stadt NexVerse +betreibt einen eigenstaendigen Datenspeicher. ## Konfiguration diff --git a/doc/OpenGenesisLINK/migrations/20261111_ogl_profile_feed_activity.sql b/doc/OpenGenesisLINK/migrations/20261111_ogl_profile_feed_activity.sql new file mode 100644 index 00000000..7ab9a4cd --- /dev/null +++ b/doc/OpenGenesisLINK/migrations/20261111_ogl_profile_feed_activity.sql @@ -0,0 +1,31 @@ +-- OpenGenesisLINK G1, opt-in auto activity / Feed v2+ +-- Existing UserAccountService and UserProfilesService must share a single +-- MariaDB database. Import after a verified backup, with ROBUST stopped +-- or Feed disabled during migration. CREATE IF NOT EXISTS preserves data. + +CREATE TABLE IF NOT EXISTS ogl_profile_feed_activity_settings ( + owner CHAR(36) CHARACTER SET ascii COLLATE ascii_bin NOT NULL PRIMARY KEY, + auto_events TINYINT(1) NOT NULL DEFAULT 0, + auto_classifieds TINYINT(1) NOT NULL DEFAULT 0, + updated_at BIGINT NOT NULL +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; + +CREATE TABLE IF NOT EXISTS ogl_profile_feed_activity_receipts ( + owner CHAR(36) CHARACTER SET ascii COLLATE ascii_bin NOT NULL, + activity_kind VARCHAR(32) CHARACTER SET ascii COLLATE ascii_bin NOT NULL, + reference_id CHAR(36) CHARACTER SET ascii COLLATE ascii_bin NOT NULL, + post_id CHAR(36) CHARACTER SET ascii COLLATE ascii_bin NOT NULL, + created_at BIGINT NOT NULL, + PRIMARY KEY (owner, activity_kind, reference_id), + INDEX ix_ogl_feed_activity_time (owner, created_at), + CONSTRAINT fk_ogl_feed_activity_post FOREIGN KEY (post_id) + REFERENCES ogl_profile_feed_posts(id) ON DELETE CASCADE +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; + +-- Both tables should exist with InnoDB. Never drop them during rollback: +-- consent and receipt history are needed to avoid reposting. +SELECT table_name, engine FROM information_schema.tables +WHERE table_schema=DATABASE() AND table_name IN + ('ogl_profile_feed_activity_settings', + 'ogl_profile_feed_activity_receipts') +ORDER BY table_name; diff --git a/tools/ci/OglProfileFeedMariaDbRegression/Program.cs b/tools/ci/OglProfileFeedMariaDbRegression/Program.cs index 199af95e..9df88f0c 100644 --- a/tools/ci/OglProfileFeedMariaDbRegression/Program.cs +++ b/tools/ci/OglProfileFeedMariaDbRegression/Program.cs @@ -2,6 +2,7 @@ // Integration test: real MariaDB, real OglProfileFeedStore, concurrent writes // and the SQL contract of account deletion; isolated synthetic local avatars. using System; +using System.Linq; using System.Threading.Tasks; using MySql.Data.MySqlClient; using NexVerse.Server.Api; @@ -44,6 +45,14 @@ try "explicitly authorized moderation failed"); Check(store.Like(post, bob, true), "like failed"); Check(store.Follow(alice, bob, true), "follow failed"); + Check(store.IsFollowing(alice, bob), "follow state not visible"); + Check(store.ListFollowingPosts(bob).Any(x => + x.Owner == alice && x.Entry.Id == post.ToString()), + "follower timeline did not include public owner's post"); + Check(store.ListLikedPostIds(alice, bob).Contains(post.ToString()), + "profile reaction state missing"); + Check(store.ListLikedFollowingPostIds(bob).Contains(post.ToString()), + "timeline reaction state missing"); Check(store.ListPosts(alice).Count == 1, "own post not visible"); Check(store.ListPosts(alice)[0].Likes == 1 && store.ListPosts(alice)[0].Comments == 1 && @@ -95,6 +104,30 @@ try // Current posts remain valid. Deleting their owner cascades correctly. Check(store.CreatePost(alice, "Second post", out UUID second), "second post failed"); + + // Auto activity is OFF until the local avatar explicitly opts in. + Check(!store.GetActivitySettings(alice).Events && + !store.GetActivitySettings(alice).Classifieds, + "automatic public posts must default to disabled"); + Guid eventId = Guid.NewGuid(); + Guid classifiedId = Guid.NewGuid(); + Check(!store.TryCreateActivityPost(alice, "event", eventId, "Event without consent"), + "an event was posted without avatar consent"); + Check(store.SetActivitySettings(alice, true, false), + "unable to save per-avatar event consent"); + Check(store.GetActivitySettings(alice).Events && + !store.GetActivitySettings(alice).Classifieds, + "per-avatar auto activity preferences not persisted"); + Check(store.TryCreateActivityPost(alice, "event", eventId, "Event after consent"), + "consented event was not posted"); + Check(!store.TryCreateActivityPost(alice, "event", eventId, "Repeated delivery"), + "same approved event was posted twice"); + Check(!store.TryCreateActivityPost(alice, "classified", classifiedId, + "Classified without consent"), "classified was posted without opt-in"); + Check(store.SetActivitySettings(alice, true, true), + "unable to enable classified activity"); + Check(store.TryCreateActivityPost(alice, "classified", classifiedId, + "New approved classified"), "consented classified was not posted"); using (var delete = new MySqlConnection(connection)) { delete.Open(); @@ -107,6 +140,14 @@ try } Check(!store.IsPostOwned(alice, second), "deleted account's content survived"); + Check(Scalar(bootstrap, null, + "SELECT COUNT(*) FROM ogl_profile_feed_activity_settings WHERE owner=@id", + ("@id", alice.ToString())).ToString() == "0", + "deleted resident's auto consent survived"); + Check(Scalar(bootstrap, null, + "SELECT COUNT(*) FROM ogl_profile_feed_activity_receipts WHERE owner=@id", + ("@id", alice.ToString())).ToString() == "0", + "deleted resident's activity receipts survived"); Check(!store.CreatePost(alice, "ghost", out _), "deleted owner could post"); Console.WriteLine("OGL Profile Feed MariaDB deletion, lock and retention: PASS"); @@ -120,6 +161,10 @@ finally ("@a", alice.ToString()), ("@b", bob.ToString())); Exec(bootstrap, null, "DELETE FROM ogl_profile_feed_follows WHERE owner IN (@a,@b) OR follower IN (@a,@b)", ("@a", alice.ToString()), ("@b", bob.ToString())); + Exec(bootstrap, null, "DELETE FROM ogl_profile_feed_activity_receipts WHERE owner IN (@a,@b)", + ("@a", alice.ToString()), ("@b", bob.ToString())); + Exec(bootstrap, null, "DELETE FROM ogl_profile_feed_activity_settings WHERE owner IN (@a,@b)", + ("@a", alice.ToString()), ("@b", bob.ToString())); Exec(bootstrap, null, "DELETE FROM ogl_profile_feed_posts WHERE owner IN (@a,@b)", ("@a", alice.ToString()), ("@b", bob.ToString())); Exec(bootstrap, null, "DELETE FROM `UserAccounts` WHERE `PrincipalID` IN (@a,@b)", @@ -136,6 +181,8 @@ static void PurgeAvatar(MySqlConnection db, MySqlTransaction tx, UUID id) Exec(db, tx, "DELETE FROM ogl_profile_feed_comments WHERE author=@id", ("@id", p)); Exec(db, tx, "DELETE FROM ogl_profile_feed_likes WHERE actor=@id", ("@id", p)); Exec(db, tx, "DELETE FROM ogl_profile_feed_follows WHERE owner=@id OR follower=@id", ("@id", p)); + Exec(db, tx, "DELETE FROM ogl_profile_feed_activity_receipts WHERE owner=@id", ("@id", p)); + Exec(db, tx, "DELETE FROM ogl_profile_feed_activity_settings WHERE owner=@id", ("@id", p)); Exec(db, tx, "DELETE FROM ogl_profile_feed_posts WHERE owner=@id OR author=@id", ("@id", p)); Exec(db, tx, "DELETE FROM `UserAccounts` WHERE `PrincipalID`=@id", ("@id", p)); } diff --git a/tools/ci/verify_ogl_profile_feed.py b/tools/ci/verify_ogl_profile_feed.py index 774d12f5..5554d6a0 100644 --- a/tools/ci/verify_ogl_profile_feed.py +++ b/tools/ci/verify_ogl_profile_feed.py @@ -29,7 +29,7 @@ for key in ('["/api/v1/feed/{principalId}"]', assert key in contract,key for name in ("Robust.HG.ini.example","Robust.ini.example"): cfg=(root/"bin"/name).read_text() - assert "EnableProfileFeed = false" in cfg + assert "EnableProfileFeed = true" in cfg assert "; web_profile_url = https://world.stadt-nexverse.de/feed?name=[AGENT_NAME]" in cfg assert "Keine automatische" in docs and "Datenschutz" in docs print("OGL Profile Feed: opt-in, privacy, owner write, scoped interactions, viewer web route OK") diff --git a/tools/ci/verify_ogl_profile_feed_activity.py b/tools/ci/verify_ogl_profile_feed_activity.py new file mode 100644 index 00000000..d7c9d9f7 --- /dev/null +++ b/tools/ci/verify_ogl_profile_feed_activity.py @@ -0,0 +1,55 @@ +#!/usr/bin/env python3 +"""Gate personal opt-in, authoritative discovery, durable dedup and deletion.""" +from pathlib import Path +root=Path(__file__).resolve().parents[2] +read=lambda name:(root/name).read_text(encoding="utf-8") +store=read("NexVerse/Server/Api/OglProfileFeedStore.cs") +auto=read("NexVerse/Server/Api/OglProfileFeedAutoPublisher.cs") +discovery=read("NexVerse/Server/Api/NexDiscoveryApi.cs") +connector=read("NexVerse/Server/Api/NexVerseWorldApiConnector.cs") +account=read("OpenSim/Services/UserAccountService/UserAccountService.cs") +api=read("NexVerse/Server/Api/OglProfileFeedApi.cs") +web=read("NexVerse/Server/Api/OglProfileFeedWebApp.cs") +migration=read("doc/OpenGenesisLINK/migrations/20261111_ogl_profile_feed_activity.sql") +contract=read("NexVerse/Server/Api/NexVerseWorldApiHandlers.cs") +for text in (store,migration): + for name in ("ogl_profile_feed_activity_settings", + "ogl_profile_feed_activity_receipts","auto_events", + "auto_classifieds","ON DELETE CASCADE"): + # settings, receipts and cascade must be consistent in migrations + assert name in text,name +assert "auto_events TINYINT(1) NOT NULL DEFAULT 0" in store +assert "auto_classifieds TINYINT(1) NOT NULL DEFAULT 0" in store +assert "GetActivitySettings(UUID owner)" in store +assert "SetActivitySettings(UUID owner, bool events, bool classifieds)" in store +assert "TryCreateActivityPost(" in store +assert "LockExistingResidents(db,tx,owner)" in store +assert "INSERT IGNORE INTO ogl_profile_feed_activity_receipts" in store +assert "marker.ExecuteNonQuery()!=1" in store +assert "tx.Commit();" in store + +for needle in ("ev.Source != \"nexverse.world-api\"", + "m_Discovery.GetEvent(id)", "m_Discovery.GetClassified(id)", + "record.State != NexDiscoveryPublicationState.Approved", + "account.LocalToGrid", "properties.PublishProfile", + "TryCreateActivityPost(owner,kind,id,body)"): + assert needle in auto, needle +for needle in ("PublishApprovedActivity(\"event\"", "PublishApprovedActivity(\"classified\"", + "saved.State == NexDiscoveryPublicationState.Approved && !wasApproved", + '["entity_id"] = entityId.ToString("D")'): + assert needle in discovery,needle +assert "s_FeedActivityPublisher" in connector and "new OglProfileFeedAutoPublisher(" in connector +assert "teleportBaseUri,\n eventBus);" in connector +for needle in ("p[4] == \"activities\"", "NexScopes.ProfileWrite", + "GetActivitySettings(resident)", "SetActivitySettings(resident", + "TryActivitySettings("): + assert needle in api,needle +for needle in ("ogl-auto-events", "ogl-auto-classifieds", + "ogl-auto-settings", "saveActivitySettings()", + "loadActivitySettings()", "'PUT'"): + assert needle in web,needle +assert '["/api/v1/feed/me/activities"]' in contract +for needle in ("ogl_profile_feed_activity_receipts", "ogl_profile_feed_activity_settings", + "Partial OGL Profile Feed activity schema"): + assert needle in account,needle +print("OGL Feed automatic activity privacy, consent, dedup and deletion contract: PASS") diff --git a/tools/ci/verify_ogl_profile_feed_branding.py b/tools/ci/verify_ogl_profile_feed_branding.py new file mode 100644 index 00000000..a1f482e2 --- /dev/null +++ b/tools/ci/verify_ogl_profile_feed_branding.py @@ -0,0 +1,44 @@ +#!/usr/bin/env python3 +"""Protect Stadt NexVerse ownership of the profile feed presentation.""" +from pathlib import Path + +root = Path(__file__).resolve().parents[2] +api = (root / "NexVerse/Server/Api/OglProfileFeedApi.cs").read_text(encoding="utf-8") +web = (root / "NexVerse/Server/Api/OglProfileFeedWebApp.cs").read_text(encoding="utf-8") + +# Both the server-first HTML fallback and the hydrated browser UI must be +# styled. Nothing may rely on external fonts, remote images or JS CDNs. +for needle in ( + "Stadt NexVerse · Profilfeed", + "ogl-shell", "ogl-brandbar", "ogl-hero", "ogl-cover", + "ogl-portrait", "ogl-post-header", + "ogl-reactions", "ogl-footer", + 'Powered by OpenGenesisLINK', + "WebUtility.HtmlEncode(account.Name)", + "WebUtility.HtmlEncode(post.Text)", + "WebUtility.HtmlEncode(comment.Text)", + "OglProfileFeedWebApp.Styles()", +): + assert needle in api, needle + +# This string must never appear as a competing brand beside NexVerse. +assert "STADT NEXVERSE · OPEN GENESIS LINK" not in api +assert api.count("Powered by OpenGenesisLINK") == 1 + +for needle in ( + "Dein virtuelles Zuhause", "ogl-profile", "ogl-compose", + "ogl-compose-heading", "ogl-stream-heading", + "ogl-post-header", "ogl-post-avatar", "ogl-reactions", + "ogl-comment-compose", ".ogl-follow-controls", "ogl-liked", + "@media(max-width:560px)", "@media(prefers-reduced-motion:reduce)", + "aria-live", "aria-label", "textContent", +): + assert needle in web or needle in api, needle +for forbidden in ( + "fonts.googleapis.com", "cdn.jsdelivr.net", "unpkg.com", + "innerHTML", "document.write", "localStorage", +): + assert forbidden not in web and forbidden not in api, forbidden +assert "script-src 'nonce-" in api +assert "frame-ancestors 'none'" in api +print("OGL Feed Stadt NexVerse branding, modern responsive shell and CSP: PASS") diff --git a/tools/ci/verify_ogl_profile_feed_interactive.py b/tools/ci/verify_ogl_profile_feed_interactive.py new file mode 100644 index 00000000..a861c3e4 --- /dev/null +++ b/tools/ci/verify_ogl_profile_feed_interactive.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Non-bypassable OAuth/PKCE and privacy release contracts for interactive feed.""" +from pathlib import Path +import os +import subprocess +import tempfile + +root = Path(__file__).resolve().parents[2] +read = lambda file: (root / file).read_text(encoding="utf-8") +api = read("NexVerse/Server/Api/OglProfileFeedApi.cs") +store = read("NexVerse/Server/Api/OglProfileFeedStore.cs") +web = read("NexVerse/Server/Api/OglProfileFeedWebApp.cs") +connector = read("NexVerse/Server/Api/NexVerseWorldApiConnector.cs") +contract = read("NexVerse/Server/Api/NexVerseWorldApiHandlers.cs") +docs = read("doc/OpenGenesisLINK/OGL_PROFILE_FEED_INTERACTIVE_V2.md") + +# Authenticated identity and owner-bound write paths. +for needle in ("p[3]==\"me\"", "p[3]==\"timeline\"", + "NexScopes.ProfileRead", "NexScopes.RelationshipsRead", + "viewerAccount.PrincipalID!=me", "ListFollowingPosts(", + "!properties.PublishProfile", "visibleIds.Add(", + "ListLikedFollowingPostIds(", + "OglProfileFeedWebApp.Controls()", "OglProfileFeedWebApp.Script(", + "OglProfileFeedWebApp.CallbackPage("): + assert needle in api, needle +assert api.index("if(p.Length==4 && (p[3]==\"me\" || p[3]==\"timeline\"))") < api.index("!UUID.TryParse(p[3]"), "route ordering" +for needle in ("ListFollowingPosts(", "IsFollowing(", "ListLikedPostIds(", + "ListLikedFollowingPostIds(", "p.created_at>=@cutoff", + "f.follower=@follower"): + assert needle in store, needle +assert "profile.PublishProfile ? m_Store.ListPosts(" in api, "SSR private-profile leak" +for needle in ('"ProfileFeedOAuthClientId", string.Empty', + "publicBaseUrl.TrimEnd('/') + \"/feed\""): + assert needle in connector, needle +assert "X-Frame-Options" in api +assert "script-src 'nonce-" in api and "connect-src 'self'" in api +assert "RandomNumberGenerator.GetBytes(16)" in api +assert "No OAuth" not in web +for needle in ("code_challenge_method: 'S256'", "crypto.getRandomValues", + "crypto.subtle.digest('SHA-256'", "sessionStorage.setItem(pendingKey", + "params.get('state') !== pending.state", "history.replaceState", + "grant_type: 'authorization_code'", "credentials: 'omit'", + "sessionStorage.removeItem(tokenKey)", "textContent", + "/oauth/authorize", "/oauth/token", "/oauth/revoke"): + assert needle in web, needle +for forbidden in ("localStorage", "document.cookie", "innerHTML", "client_secret"): + assert forbidden not in web, forbidden +assert "profile:read profile:write relationships:read relationships:write" in web +oauth_store = read("NexVerse/Core/Security/NexOAuthStore.cs") +assert "EnsureProfileFeedPublicClient(" in oauth_store +assert "ClientType = NexOAuthClientTypes.Public" in oauth_store +assert "existing.Enabled" in oauth_store +assert "ProfileFeedOAuthClientId" in docs +assert "EnableNativeTokens = true" in docs +assert "EnsureProfileFeedPublicClient(" in connector +for path in ("bin/Robust.HG.ini", "bin/Robust.HG.ini.example", "bin/Robust.ini.example"): + config = read(path) + assert "ProfileFeedOAuthClientId = \"\"" in config, path + assert "EnableProfileFeed = true" in config, path +for needle in ('["/api/v1/feed/me"]', '["/api/v1/feed/timeline"]'): + assert needle in contract + +# Parse the JavaScript sent to the actual viewer rather than accepting a +# merely textual C# signature. GitHub Actions ubuntu-latest provides node. +script = web.split('private const string ScriptBody = """', 1)[1].rsplit('""";', 1)[0] +with tempfile.TemporaryDirectory() as directory: + source = Path(directory) / "feed-webapp.js" + source.write_text(script, encoding="utf-8") + subprocess.run(["node", "--check", os.fspath(source)], check=True) +print("Interactive OGL Feed v2 OAuth, timeline, privacy and browser JS: PASS") diff --git a/tools/ci/verify_ogl_profile_feed_rollout.py b/tools/ci/verify_ogl_profile_feed_rollout.py index 526f19a4..385707e0 100644 --- a/tools/ci/verify_ogl_profile_feed_rollout.py +++ b/tools/ci/verify_ogl_profile_feed_rollout.py @@ -40,9 +40,12 @@ for needle in ( assert purge.index("ogl_profile_feed_comments") < purge.rfind("DELETE FROM `ogl_profile_feed_posts`") assert "same MySQL datastore" in account assert "same MariaDB provider/connection" in connector or "SAME MariaDB provider/connection" in connector -assert 'GetBoolean("EnableProfileFeed", false)' in connector +assert 'GetBoolean("EnableProfileFeed", true)' in connector assert "userAccounts is not IOglLocalAvatarDeletion" in connector +assert "ogl_profile_feed_activity_receipts" in account +assert "ogl_profile_feed_activity_settings" in account +assert "Partial OGL Profile Feed activity schema" in account assert "bool moderator = false" in store assert "OR @moderator=1" in store assert "actorAccount.UserLevel >= 200" in api @@ -63,12 +66,12 @@ for needle in ("ProfileFeedRetentionDays", "profileConnectionString"): for needle in ("PruneExpired()", "Cutoff", "created_at>=@cutoff", "m_RetentionTimer = new Timer("): assert needle in store -assert api.count("m_Store.PruneExpired();") == 2 +assert api.count("m_Store.PruneExpired();") >= 2 # HTML, profile and following reads for path in ("bin/Robust.HG.ini", "bin/Robust.HG.ini.example", "bin/Robust.ini.example"): cfg = read(path) - assert "EnableProfileFeed = false" in cfg, path + assert "EnableProfileFeed = true" in cfg, path assert "ProfileFeedRetentionDays = 180" in cfg, path assert "Rollback" in docs and "Migration" in docs print("OGL Profile Feed G1 deletion and retention rollout contracts: PASS")