From 7a8422dfbd698e69c46ffb0fe6c1cf3ab2287450 Mon Sep 17 00:00:00 2001 From: "OpenGenesis (EULA)" <153564363+opengenesislink@users.noreply.github.com> Date: Wed, 25 Nov 2026 21:00:51 +0100 Subject: [PATCH 01/12] feat(g1): secure NV$ ledger-backed payout domain with deterministic idempotency --- addons/SysApi/SysApiNvMoney.cs | 179 +++++++++++++++++++++++++++++++++ 1 file changed, 179 insertions(+) create mode 100644 addons/SysApi/SysApiNvMoney.cs diff --git a/addons/SysApi/SysApiNvMoney.cs b/addons/SysApi/SysApiNvMoney.cs new file mode 100644 index 00000000..11a89264 --- /dev/null +++ b/addons/SysApi/SysApiNvMoney.cs @@ -0,0 +1,179 @@ +// SPDX-License-Identifier: LicenseRef-OpenGenesisLINK-EULA +using System; +using System.Collections.Generic; +using System.Linq; +using System.Net; +using System.Security.Cryptography; +using System.Text; +using NexVerse.Core.Economy; +using NexVerse.Server.Api; +using OpenMetaverse; +using OpenSim.Framework; +using OpenSim.Services.Interfaces; + +namespace OpenGenesisLINK.SysApi; + +/// +/// Security boundary for administrative NV$ credits. Reuses the live, +/// MariaDB-backed NexVerse double-entry ledger; never maintains a second balance. +/// No payment-provider event can independently authorize a credit. +/// +public sealed class SysApiNvMoney +{ + private static readonly Guid CounterpartyId = + Guid.Parse("4e565324-5359-5341-5049-444d00000001"); + private readonly IUserAccountService _accounts; + private readonly Func _getEconomy; + private readonly byte[] _portalToken; + private readonly object _payoutGate = new(); + + public bool AdminEnabled { get; } + public bool PortalEnabled { get; } + public int MaxNv { get; } + public const int NvPerEuro = 100; + + public SysApiNvMoney( + IUserAccountService accounts, + bool adminEnabled, bool portalEnabled, int maxNv, string portalToken, + Func? getEconomy = null) + { + _accounts = accounts ?? throw new ArgumentNullException(nameof(accounts)); + if (maxNv is < 1 or > 1000000) throw new ArgumentOutOfRangeException(nameof(maxNv)); + _getEconomy = getEconomy is not null ? getEconomy : + () => NexEconomyConnector.Current?.Enabled == true + ? NexEconomyConnector.Current.Economy + : null; + AdminEnabled = adminEnabled; + MaxNv = maxNv; + if (portalToken.Length != 0 && + (portalToken.Length is < 64 or > 128 || !portalToken.All(Uri.IsHexDigit))) + throw new ArgumentException("Portal money token must be 64–128 hex characters"); + _portalToken = Encoding.ASCII.GetBytes(portalToken); + PortalEnabled = portalEnabled && _portalToken.Length >= 64; + if (portalEnabled && !PortalEnabled) + throw new InvalidOperationException("Dedicated portal payout credential is missing"); + } + + public bool ValidPortalCredential(HttpListenerRequest request) + { + if (!PortalEnabled) return false; + string authorization = request.Headers["Authorization"] ?? ""; + if (!authorization.StartsWith("Bearer ", StringComparison.Ordinal) || + authorization.Length != _portalToken.Length + 7) return false; + return CryptographicOperations.FixedTimeEquals( + Encoding.ASCII.GetBytes(authorization[7..]), _portalToken); + } + + public object Status() => new { + enabled = AdminEnabled, + portalEnabled = PortalEnabled, + ledgerAvailable = _getEconomy() is not null, + maxPayoutNv = MaxNv, + nvPerEuro = NvPerEuro, + euroCurrency = "EUR", + settlementProviders = new[] {"stripe: not configured", "paypal: not configured"}, + paymentSettlementEnabled = false + }; + + public static long EuroCentsToNv(long euroCents) + { + // Exactly 100 NV$ per EUR. No floating-point arithmetic. + if (euroCents <= 0 || euroCents > 100000000) + throw new ArgumentOutOfRangeException(nameof(euroCents)); + return euroCents; + } + + public NvPayoutReceipt Pay(NvPayoutInput? input, string actor, bool portal) + { + if (portal ? !PortalEnabled : !AdminEnabled) + throw new InvalidOperationException("NV$ payout feature is disabled"); + if (input is null || + !Guid.TryParse(input.AvatarId, out Guid residentId) || + residentId == Guid.Empty || + !Guid.TryParse(input.RequestId, out Guid requestId) || + requestId == Guid.Empty) + throw new ArgumentException("Valid avatarId and requestId UUIDs required"); + if (input.AmountNv is < 1 or > int.MaxValue || + input.AmountNv > MaxNv) + throw new ArgumentException("NV$ payout amount is outside configured limits"); + string reason = (input.Description ?? "").Trim(); + if (reason.Length is < 4 or > 120 || + reason.Any(char.IsControl)) + throw new ArgumentException("Transaction description must be 4–120 printable characters"); + // A public payment success flag must NEVER be accepted as proof of settled + // funds. Stripe/PayPal adapters require server-side signed-event verification. + if (!string.Equals(input.Source, + portal ? "portal-manual" : "admin-manual", + StringComparison.Ordinal)) + throw new ArgumentException("Only explicitly authorized manual payouts are accepted"); + + string ledgerActor = portal ? "sysapi-portal" : "sysapi-admin:" + actor; + Guid transactionId = TransactionGuid(requestId); + string correlationId = "sysapi-nv-payout-" + requestId.ToString("N"); + + lock (_payoutGate) + { + NexEconomyService economy = _getEconomy() ?? + throw new InvalidOperationException("NV$ durable ledger unavailable"); + var account = _accounts.GetUserAccount(UUID.Zero, new UUID(residentId)); + if (account is null || !account.LocalToGrid || + account.PrincipalID.Guid != residentId) + throw new ArgumentException("Avatar must be an existing local grid resident"); + + // Check existing records first, then verify the ENTIRE immutable + // request identity. Never re-credit on HTTP retries or duplicated + // payment callbacks. The ledger's transaction UUID is unique in SQL. + NexLedgerTransaction? existing = economy.GetTransaction(transactionId); + if (existing != null) + return ValidateExisting(existing, residentId, input.AmountNv, + reason, ledgerActor, correlationId, economy); + + economy.EnsureResidentAccount(residentId, account.EffectiveDisplayName); + economy.EnsureSystemAccount(CounterpartyId, "NV$ SYS.API Administration"); + NexLedgerAppendResult result = economy.AdministrativeAdjustment( + residentId, CounterpartyId, input.AmountNv, + ledgerActor, reason, correlationId, transactionId); + var verified = ValidateExisting(result.Transaction, residentId, + input.AmountNv, reason, ledgerActor, correlationId, economy); + return new NvPayoutReceipt(verified.TransactionId, residentId, + input.AmountNv, verified.BalanceNv, !result.Created); + } + } + + private static NvPayoutReceipt ValidateExisting( + NexLedgerTransaction transaction, Guid residentId, long amount, + string reason, string actor, string correlationId, NexEconomyService economy) + { + if (transaction.Kind != "admin_adjustment" || + transaction.Postings.Count != 2 || + transaction.Postings[0].AccountId != CounterpartyId || + transaction.Postings[0].Side != NexLedgerSide.Debit || + transaction.Postings[0].AmountMinor != amount || + transaction.Postings[1].AccountId != residentId || + transaction.Postings[1].Side != NexLedgerSide.Credit || + transaction.Postings[1].AmountMinor != amount || + transaction.CorrelationId != correlationId || + !transaction.Metadata.TryGetValue("actor", out string? previousActor) || + !string.Equals(previousActor, actor, StringComparison.Ordinal) || + !transaction.Metadata.TryGetValue("reason", out string? previousReason) || + !string.Equals(previousReason, reason, StringComparison.Ordinal)) + throw new NexLedgerConflictException("The request ID belongs to a different payout"); + return new NvPayoutReceipt(transaction.TransactionId, residentId, + amount, economy.GetBalance(residentId), true); + } + + public static Guid TransactionGuid(Guid requestId) + { + byte[] hash = SHA256.HashData( + Encoding.UTF8.GetBytes("ogl-sysapi-nv-grant-v1:" + requestId.ToString("N"))); + return new Guid(hash.AsSpan(0, 16)); + } +} + +public sealed record NvPayoutInput( + string? AvatarId, long AmountNv, string? Description, + string? RequestId, string? Source); + +public sealed record NvPayoutReceipt( + Guid TransactionId, Guid AvatarId, long AmountNv, + long BalanceNv, bool Duplicate); From f1f6fd10d92c4943571eada1df7225f4a7af9277 Mon Sep 17 00:00:00 2001 From: "OpenGenesis (EULA)" <153564363+opengenesislink@users.noreply.github.com> Date: Wed, 25 Nov 2026 21:00:56 +0100 Subject: [PATCH 02/12] feat(g1): integrate authorized manual payouts into complete SYS.API and ROBUST economy --- addons/SysApi/SysApiHost.cs | 95 ++++++++++++++++++++++++++++++++++++- 1 file changed, 94 insertions(+), 1 deletion(-) diff --git a/addons/SysApi/SysApiHost.cs b/addons/SysApi/SysApiHost.cs index 81827e57..27fa6799 100644 --- a/addons/SysApi/SysApiHost.cs +++ b/addons/SysApi/SysApiHost.cs @@ -32,6 +32,7 @@ public sealed class SysApiHost : IDisposable private readonly IAuthenticationService _auth; private readonly ISysApiReadModel? _readModel; private readonly ISysApiAlertPublisher? _alertPublisher; + private readonly SysApiNvMoney? _nvMoney; private readonly SemaphoreSlim _alertGate = new(1, 1); private DateTimeOffset _lastAlertAt = DateTimeOffset.MinValue; private readonly ISysApiAccessPolicyStore? _accessPolicy; @@ -50,7 +51,8 @@ public sealed class SysApiHost : IDisposable ISysApiAccessPolicyStore? accessPolicy = null, string policyReadToken = "", SysApiResidentGateway? residents = null, ISysApiAdminData? adminData = null, - ISysApiAlertPublisher? alertPublisher = null) + ISysApiAlertPublisher? alertPublisher = null, + SysApiNvMoney? nvMoney = null) { if (localPort is < 1025 or > 65535) throw new ArgumentOutOfRangeException(nameof(localPort)); _accounts = accounts ?? throw new ArgumentNullException(nameof(accounts)); @@ -60,6 +62,7 @@ public sealed class SysApiHost : IDisposable _residents = residents; _adminData = adminData; _alertPublisher = alertPublisher; + _nvMoney = nvMoney; _policyReadToken = policyReadToken.Length >= 32 && policyReadToken.Length <= 128 && policyReadToken.All(Uri.IsHexDigit) ? Encoding.ASCII.GetBytes(policyReadToken) : Array.Empty(); if (portalToken.Length != 128 || !portalToken.All(Uri.IsHexDigit)) @@ -295,6 +298,7 @@ public sealed class SysApiHost : IDisposable await AssetAsync(response, "index.html", "text/html; charset=utf-8"); return; } + if (isGet && path == "/money.js") { await AssetAsync(response, "money.js", "text/javascript; charset=utf-8"); return; } if (isGet && path == "/app.js") { await AssetAsync(response, "app.js", "text/javascript; charset=utf-8"); return; } if (isGet && path == "/style.css") { await AssetAsync(response, "style.css", "text/css; charset=utf-8"); return; } if (isGet && path == "/ogl-mascot.webp") { await AssetAsync(response, "ogl-mascot.webp", "image/webp"); return; } @@ -749,6 +753,35 @@ public sealed class SysApiHost : IDisposable return; } } + // Money payouts use a DIFFERENT credential from the general portal token. + // No client-provided "Stripe paid" or "PayPal completed" claim is trusted. + if (path is "/api/v1/portal/money/payouts" or "/api/v1/portal/money/rate") + { + if (_nvMoney is null || !_nvMoney.PortalEnabled) + { + await ReplyAsync(response, 503, new { error = "Portal NV$ payouts are not configured" }); + return; + } + if (!IsTrustedProxy(req) || !_nvMoney.ValidPortalCredential(req)) + { + await ReplyAsync(response, 401, new { error = "Dedicated payout authorization required" }); + return; + } + if (isGet && path.EndsWith("/rate", StringComparison.Ordinal)) + { + await ReplyAsync(response, 200, new { + nvPerEuro = SysApiNvMoney.NvPerEuro, euroCurrency = "EUR", + currency = "NV$", paymentSettlementEnabled = false + }); + return; + } + if (req.HttpMethod != "POST" || path.EndsWith("/rate", StringComparison.Ordinal)) + { + await ReplyAsync(response, 405, new { error = "Method not allowed" }); return; + } + await PayNvAsync(req, response, "portal", true); + return; + } if (!TryAdmin(req, out AdminSession admin)) { await ReplyAsync(response, 401, new { error = "Access Denied – Keine Berechtigung" }); return; @@ -758,6 +791,27 @@ public sealed class SysApiHost : IDisposable { await ReplyAsync(response, 403, new { error = "CSRF protection denied" }); return; } + if (path == "/api/admin/money/status") + { + if (!isGet) + { + await ReplyAsync(response, 405, new { error = "GET required" }); return; + } + await ReplyAsync(response, 200, _nvMoney?.Status() ?? + new { enabled = false, portalEnabled = false, + nvPerEuro = SysApiNvMoney.NvPerEuro, + paymentSettlementEnabled = false }); + return; + } + if (path == "/api/admin/money/payouts") + { + if (req.HttpMethod != "POST") + { + await ReplyAsync(response, 405, new { error = "POST required" }); return; + } + await PayNvAsync(req, response, admin.Avatar.ToString(), false); + return; + } if (path == "/api/admin/alerts") { if (req.HttpMethod != "POST") @@ -843,6 +897,7 @@ public sealed class SysApiHost : IDisposable minAdminLevel = 200, oldWorldApiUnchanged = true, alertsAvailable = _alertPublisher is not null, + moneyAvailable = _nvMoney?.AdminEnabled == true, endpoints = new[] { "/v1/health", "/api/v1/portal/ping", "/api/v1/portal/capabilities" } }); return; @@ -858,6 +913,44 @@ public sealed class SysApiHost : IDisposable finally { try { context.Response.Close(); } catch { } } } + private async Task PayNvAsync(HttpListenerRequest request, HttpListenerResponse response, + string actor, bool portal) + { + if (_nvMoney is null || (portal ? !_nvMoney.PortalEnabled : !_nvMoney.AdminEnabled)) + { + await ReplyAsync(response, 503, new { error = "NV$ payout feature is disabled" }); + return; + } + var input = await ReadInput(request); + try + { + NvPayoutReceipt receipt = _nvMoney.Pay(input, actor, portal); + Log.InfoFormat("[SYS.API MONEY] Credit {0} NV$ to {1}, transaction {2}, duplicated={3}", + receipt.AmountNv, receipt.AvatarId, receipt.TransactionId, receipt.Duplicate); + await ReplyAsync(response, receipt.Duplicate ? 200 : 201, new { + receipt.TransactionId, receipt.AvatarId, receipt.AmountNv, + receipt.BalanceNv, receipt.Duplicate, currency = "NV$" + }); + } + catch (ArgumentException ex) + { + await ReplyAsync(response, 400, new { error = ex.Message }); + } + catch (NexVerse.Core.Economy.NexLedgerConflictException) + { + await ReplyAsync(response, 409, new { error = "Idempotency request conflicts with existing ledger transaction" }); + } + catch (InvalidOperationException) + { + await ReplyAsync(response, 503, new { error = "NV$ ledger or payout service unavailable" }); + } + catch (Exception ex) + { + Log.Error("[SYS.API MONEY] Financial transaction failed", ex); + await ReplyAsync(response, 503, new { error = "NV$ payout could not be completed" }); + } + } + public void Dispose() { if (Interlocked.Exchange(ref _disposed, 1) != 0) return; From 77ba0d7736a4a5f90530a340c5ef2b1efc79a4df Mon Sep 17 00:00:00 2001 From: "OpenGenesis (EULA)" <153564363+opengenesislink@users.noreply.github.com> Date: Wed, 25 Nov 2026 21:01:00 +0100 Subject: [PATCH 03/12] feat(g1): integrate authorized manual payouts into complete SYS.API and ROBUST economy --- addons/SysApi/SysApiConnector.cs | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/addons/SysApi/SysApiConnector.cs b/addons/SysApi/SysApiConnector.cs index 57be4d1b..a4ca5b3a 100644 --- a/addons/SysApi/SysApiConnector.cs +++ b/addons/SysApi/SysApiConnector.cs @@ -104,9 +104,16 @@ public sealed class SysApiConnector : ServiceConnector ex.GetType().Name); } } + // Completely independent authorization from the general portal token. + // Portal payouts fail closed unless a dedicated credential is explicitly configured. + var moneyBridge = new SysApiNvMoney( + accounts, cfg.GetBoolean("MoneyAdminEnabled", false), + cfg.GetBoolean("MoneyPortalEnabled", false), + cfg.GetInt("MoneyMaxNvPerPayout", 10000), + Environment.GetEnvironmentVariable("OGL_SYSAPI_MONEY_PORTAL_TOKEN") ?? ""); var host = new SysApiHost(port, publicOrigin, accounts, authentication, token, readModel, policyStore, policyReadToken, residentGateway, adminData, - alertPublisher); + alertPublisher, moneyBridge); host.Start(); _host = host; Log.InfoFormat("[SYS.API] Foundation active on loopback 127.0.0.1:{0}; public TLS proxy port 8850 requires ACME certificate.", port); From f51de06bbc03b9b8ee09d0a3b318cc8fb10ca915 Mon Sep 17 00:00:00 2001 From: "OpenGenesis (EULA)" <153564363+opengenesislink@users.noreply.github.com> Date: Wed, 25 Nov 2026 21:01:14 +0100 Subject: [PATCH 04/12] feat(sys.api): admin money payout browser module, no backend token exposed --- addons/SysApi/www/money.js | 73 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 73 insertions(+) create mode 100644 addons/SysApi/www/money.js diff --git a/addons/SysApi/www/money.js b/addons/SysApi/www/money.js new file mode 100644 index 00000000..d1b05946 --- /dev/null +++ b/addons/SysApi/www/money.js @@ -0,0 +1,73 @@ +"use strict"; +// This module never holds a machine token. Only a revalidated UserLevel 200+ +// cookie plus the existing same-origin CSRF header can authorize manual payouts. +(()=>{ + const el=id=>document.getElementById(id); + const status=el("nv-money-status"),results=el("nv-money-results"); + const search=el("nv-money-search"),form=el("nv-money-form"); + const selected=el("nv-money-selected"),idInput=el("nv-money-avatar-id"); + const send=el("nv-money-submit"); + let requestId="",lastIntent=""; + const refresh=async()=>{ + try{ + const d=await json("/api/admin/money/status"); + status.textContent=d.enabled + ? "NV$-Ledger "+(d.ledgerAvailable?"verbunden":"nicht erreichbar")+ + " · Höchstbetrag "+d.maxPayoutNv+" NV$ · 100 NV$ = 1 EUR" + : "Administrative Auszahlungen sind noch nicht freigegeben."; + send.disabled=!d.enabled||!d.ledgerAvailable; + el("nv-money-amount").max=d.maxPayoutNv||10000; + }catch(e){status.textContent="Bitte als Administrator anmelden: "+e.message;send.disabled=true;} + }; + el("nv-money-nav").addEventListener("click",()=>refresh()); + search.addEventListener("submit",async ev=>{ + ev.preventDefault();const q=el("nv-money-query").value.trim(); + if(q.length<2){results.textContent="Bitte mindestens zwei Zeichen eingeben.";return;} + results.textContent="Suche läuft..."; + try{ + const d=await json("/api/v1/UserAccounts/lists?limit=30&offset=0&search="+encodeURIComponent(q)); + results.replaceChildren(); + for(const account of d.items){ + if(!/^[0-9a-fA-F-]{36}$/.test(account.uuid))continue; + const button=document.createElement("button"); + button.type="button";button.className="ghost-button"; + button.textContent=(account.avatarName||"Avatar")+" · "+account.uuid; + button.addEventListener("click",()=>{ + idInput.value=account.uuid; + selected.textContent=(account.avatarName||"Avatar")+" ("+account.uuid+")"; + requestId="";lastIntent=""; + }); + results.append(button); + } + if(!results.childNodes.length)results.textContent="Kein Avatar gefunden."; + }catch(e){results.textContent="Kontensuche fehlgeschlagen: "+e.message;} + }); + form.addEventListener("input",()=>{requestId="";lastIntent="";}); + form.addEventListener("submit",async ev=>{ + ev.preventDefault(); + const avatarId=idInput.value,amountNv=Number(el("nv-money-amount").value); + const description=el("nv-money-description").value.trim(); + if(!/^[0-9a-fA-F-]{36}$/.test(avatarId)||!Number.isSafeInteger(amountNv)||amountNv<=0|| + description.length<4||description.length>120){ + status.textContent="Avatar auswählen, positiven ganzzahligen Betrag und Beschreibung angeben."; + return; + } + const intent=avatarId+"|"+amountNv+"|"+description; + if(intent!==lastIntent){requestId=crypto.randomUUID();lastIntent=intent;} + if(!confirm("NV$-Gutschrift verbindlich ausführen?\n\n"+ + selected.textContent+"\nBetrag: "+amountNv+" NV$\nGrund: "+description))return; + send.disabled=true; + try{ + const receipt=await json("/api/admin/money/payouts",{ + method:"POST",headers:{"Content-Type":"application/json"}, + body:JSON.stringify({avatarId,amountNv,description,requestId,source:"admin-manual"}) + }); + status.textContent="Buchung "+(receipt.duplicate?"bereits vorhanden":"ausgeführt")+ + ". Transaktion "+receipt.transactionId+" · neuer Kontostand "+receipt.balanceNv+" NV$."; + if(!receipt.duplicate){form.reset();idInput.value="";selected.textContent="Kein Avatar gewählt";} + requestId="";lastIntent=""; + }catch(e){status.textContent="Auszahlung nicht bestätigt: "+e.message+ + ". Bei Netzproblemen dieselbe unveränderte Buchung erneut versuchen.";} + finally{send.disabled=false;} + }); +})(); From 352416a187224d76cba2c3cfa3306ffb5fbb9157 Mon Sep 17 00:00:00 2001 From: "OpenGenesis (EULA)" <153564363+opengenesislink@users.noreply.github.com> Date: Wed, 25 Nov 2026 21:01:20 +0100 Subject: [PATCH 05/12] feat(sys.api): add avatar payout selection to admin PWA preserving existing modules --- addons/SysApi/www/index.html | 36 +++++++++++++++++++++++++++++++++--- 1 file changed, 33 insertions(+), 3 deletions(-) diff --git a/addons/SysApi/www/index.html b/addons/SysApi/www/index.html index cf553756..0b1d7952 100644 --- a/addons/SysApi/www/index.html +++ b/addons/SysApi/www/index.html @@ -12,7 +12,7 @@ - + @@ -47,7 +47,7 @@
OPENGENESISLINK / SYSTEM COMMAND

System Dashboard

ADMINISTRATOR
@@ -120,6 +120,36 @@
Konten werden nach dem Login geladen.
+
+

NV$ Auszahlungen

+

Manuelle Gutschriften über das zentrale, revisionsfähige NV$-Ledger. + 100 NV$ entsprechen 1 EUR. Nur authentifizierte Administratoren (UserLevel 200+).

+
+

Auszahlung wird geprüft …

+ +
+

Gewählt: Kein Avatar gewählt

+
+ + + + +
+

Jede Gutschrift erhält eine eindeutige Transaktions-ID. + Doppelte Anfragen werden nicht erneut verbucht. Stripe und PayPal + sind nur vorbereitet; ohne bestätigte Zahlungsereignisse erfolgt + keine automatische Echtgeld-Umwandlung.

+
+

SYS.API · Datenbank & Werkzeuge

Live-Auswertungen aus der bestehenden MariaDB. Nur definierte Datenquellen und @@ -281,4 +311,4 @@

- \ No newline at end of file + From fdb231228fe7c6223c45db156a15581114e9647c Mon Sep 17 00:00:00 2001 From: "OpenGenesis (EULA)" <153564363+opengenesislink@users.noreply.github.com> Date: Wed, 25 Nov 2026 21:01:24 +0100 Subject: [PATCH 06/12] feat(sys.api): add avatar payout selection to admin PWA preserving existing modules --- addons/SysApi/www/style.css | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/addons/SysApi/www/style.css b/addons/SysApi/www/style.css index f8ee7662..53f4bc77 100644 --- a/addons/SysApi/www/style.css +++ b/addons/SysApi/www/style.css @@ -26,3 +26,12 @@ #alert-send:disabled{opacity:.55;cursor:not-allowed} @media(max-width:640px){.alert-panel{padding:18px}.alert-panel select,.alert-panel textarea{font-size:16px}} + +/* NV$ safe payout dashboard */ +#nv-money-results { display:flex; flex-wrap:wrap; align-items:flex-start; gap:8px; padding:12px 0; } +#nv-money-form { grid-template-columns:minmax(140px,1fr) minmax(240px,2fr) auto; } +#nv-money-form label { display:grid; gap:6px; } +#nv-money-form input { padding:12px; background:#07152b; border:1px solid #367dad66; + border-radius:10px; color:#effaff; width:100%; } +#nv-money-status { min-height:1.8em; color:#bde4f7; } +@media(max-width:920px){#nv-money-form {grid-template-columns:1fr;}} From ee8e40d54b3486be735f7cf5afc1e5c8ea5a216f Mon Sep 17 00:00:00 2001 From: "OpenGenesis (EULA)" <153564363+opengenesislink@users.noreply.github.com> Date: Wed, 25 Nov 2026 21:01:28 +0100 Subject: [PATCH 07/12] feat(sys.api): add avatar payout selection to admin PWA preserving existing modules --- addons/SysApi/www/service-worker.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/addons/SysApi/www/service-worker.js b/addons/SysApi/www/service-worker.js index 1eb5b817..2f3c30b8 100644 --- a/addons/SysApi/www/service-worker.js +++ b/addons/SysApi/www/service-worker.js @@ -1,7 +1,7 @@ /* OpenGenesisLINK SYS.API: static-only offline support. NEVER cache pages, sessions, API responses, private data or forms. */ "use strict"; -const CACHE = "ogl-sysapi-static-v6"; +const CACHE = "ogl-sysapi-static-v7"; const PRECACHE = [ "/offline.html", "/style.css", "/mobile.css", "/pwa.js", "/account-profile.css", "/account-profile.js", "/admin-data.css", "/admin-data.js", "/updates.css", "/updates.js", "/manifest.webmanifest", "/ogl-mascot.webp", From 6544c4986067653744dee7634191d8c32bb7e31d Mon Sep 17 00:00:00 2001 From: "OpenGenesis (EULA)" <153564363+opengenesislink@users.noreply.github.com> Date: Wed, 25 Nov 2026 21:01:42 +0100 Subject: [PATCH 08/12] build/security(gen1): include SYS.API money module, secure-disabled defaults and regression guards --- addons/SysApi/sys.api.csproj | 1 + 1 file changed, 1 insertion(+) diff --git a/addons/SysApi/sys.api.csproj b/addons/SysApi/sys.api.csproj index 80853642..44a57cba 100644 --- a/addons/SysApi/sys.api.csproj +++ b/addons/SysApi/sys.api.csproj @@ -32,6 +32,7 @@ + From 953897c3692f835804b8e895503ee2a58c6cc65d Mon Sep 17 00:00:00 2001 From: "OpenGenesis (EULA)" <153564363+opengenesislink@users.noreply.github.com> Date: Wed, 25 Nov 2026 21:01:46 +0100 Subject: [PATCH 09/12] build/security(gen1): include SYS.API money module, secure-disabled defaults and regression guards --- bin/Robust.HG.ini | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/bin/Robust.HG.ini b/bin/Robust.HG.ini index ef16fb39..a8a6eca4 100644 --- a/bin/Robust.HG.ini +++ b/bin/Robust.HG.ini @@ -1190,6 +1190,10 @@ ; The internal admin service listens only on 127.0.0.1:8851. Port 8850 must ; be exposed exclusively by an HTTPS proxy with a valid ACME certificate. [SysApi] + ; Separate operator and money-portal release gates. No credits until explicitly enabled. + MoneyAdminEnabled = false + MoneyPortalEnabled = false + MoneyMaxNvPerPayout = 10000 Enabled = false ; Optional broadcast of the native 'alert' command over signed NexBus. ; Requires active signed NexBus service with SharedKey and simulator Peers. From 01d90ea8762dd3093c5aa0e24aacc8323aa10599 Mon Sep 17 00:00:00 2001 From: "OpenGenesis (EULA)" <153564363+opengenesislink@users.noreply.github.com> Date: Wed, 25 Nov 2026 21:01:49 +0100 Subject: [PATCH 10/12] build/security(gen1): include SYS.API money module, secure-disabled defaults and regression guards --- tools/ci/verify_sys_api_foundation.py | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/tools/ci/verify_sys_api_foundation.py b/tools/ci/verify_sys_api_foundation.py index d057935e..8f395b97 100644 --- a/tools/ci/verify_sys_api_foundation.py +++ b/tools/ci/verify_sys_api_foundation.py @@ -26,6 +26,22 @@ for needle in ('FileMode.CreateNew', 'RandomNumberGenerator.GetBytes(64)', 'UnixFileMode.UserRead | UnixFileMode.UserWrite'): assert needle in secret,needle assert "innerHTML" not in js +money = read("addons/SysApi/SysApiNvMoney.cs") +money_js = read("addons/SysApi/www/money.js") +for marker in ("/api/admin/money/payouts", "/api/v1/portal/money/payouts", + "/api/v1/portal/money/rate", "ValidPortalCredential", + 'if (!IsTrustedProxy(req)', "paymentSettlementEnabled = false"): + assert marker in api + money, "SYS.API money security invariant absent: " + marker +for marker in ("AdministrativeAdjustment(", "GetTransaction(", "NexLedgerConflictException", + "FixedTimeEquals", "portal-manual", "admin-manual", "NvPerEuro = 100"): + assert marker in money, marker +assert "innerHTML" not in money_js +assert "OGL_SYSAPI_MONEY_PORTAL_TOKEN" in auth +assert 'MoneyPortalEnabled", false' in auth +assert 'MoneyAdminEnabled", false' in auth +assert 'www/money.js' in project +assert 'id="nv-money-form"' in web + assert "ogl-mascot.webp" in web # Never replace production's complete SYS.API with a foundation-only build: # doing so removes the centrally published citizen rules and blocks all logins. From 5ec824bc0138816cd8983f6bb8af6fff1fb8a43f Mon Sep 17 00:00:00 2001 From: "OpenGenesis (EULA)" <153564363+opengenesislink@users.noreply.github.com> Date: Wed, 25 Nov 2026 21:02:03 +0100 Subject: [PATCH 11/12] test(g1): in-memory NV$ money payout, policy, portal auth and idempotency HTTP regressions --- tools/ci/SysApiSmoke/Program.cs | 117 +++++++++++++++++++++++++++++++- 1 file changed, 116 insertions(+), 1 deletion(-) diff --git a/tools/ci/SysApiSmoke/Program.cs b/tools/ci/SysApiSmoke/Program.cs index 58c29005..40f81dd3 100644 --- a/tools/ci/SysApiSmoke/Program.cs +++ b/tools/ci/SysApiSmoke/Program.cs @@ -10,6 +10,7 @@ using OpenMetaverse; using OpenSim.Services.Interfaces; using OpenGenesisLINK.SysApi; using NexVerse.Core.Messaging; +using NexVerse.Core.Economy; using OpenSim.Framework; using System.Security.Cryptography; @@ -76,11 +77,24 @@ free.Start(); int port = ((IPEndPoint)free.LocalEndpoint).Port; free.Stop(); var alertSink = new TestAlertPublisher(); +// In-memory test ledger only; absolutely no production NV$ or SQL connections. +var fakeMoneyStore = new InMemoryNexLedgerStore(); +var fakeEconomy = new NexEconomyService( + new NexDoubleEntryLedger(fakeMoneyStore), fakeMoneyStore); +var moneyBridge = new SysApiNvMoney( + DispatchProxy.Create(), + adminEnabled:true, portalEnabled:true, maxNv:10000, + portalToken:new string('C', 64), getEconomy:()=>fakeEconomy); +if (SysApiNvMoney.NvPerEuro != 100 || + SysApiNvMoney.EuroCentsToNv(100) != 100 || + SysApiNvMoney.EuroCentsToNv(150) != 150) + throw new Exception("100 NV$ per EUR fixed-point conversion regression"); using var host = new SysApiHost(port, "https://sysapi.example.test:8850", DispatchProxy.Create(), DispatchProxy.Create(), first, new FakeSysApiReadModel(), accessPolicy: new FakeSysApiAccessPolicyStore(), - policyReadToken: new string('A',64), alertPublisher: alertSink); + policyReadToken: new string('A',64), alertPublisher: alertSink, + nvMoney: moneyBridge); host.Start(); try { @@ -91,6 +105,19 @@ try }; static void Expect(HttpStatusCode actual, HttpStatusCode desired, string test) { if (actual != desired) throw new Exception($"{test}: expected {desired}, got {actual}"); } + using (var anonymousMoney = await client.GetAsync("/api/admin/money/status")) + Expect(anonymousMoney.StatusCode,HttpStatusCode.Unauthorized,"money status auth"); + using (var anonymousPortal = await client.PostAsync("/api/v1/portal/money/payouts", + new StringContent("{}", Encoding.UTF8, "application/json"))) + Expect(anonymousPortal.StatusCode,HttpStatusCode.Unauthorized,"portal money token required"); + using(var moneyJs=await client.GetAsync("/money.js")) + { + Expect(moneyJs.StatusCode,HttpStatusCode.OK,"embedded money JavaScript"); + string script=await moneyJs.Content.ReadAsStringAsync(); + if(!script.Contains("/api/admin/money/payouts") || + !script.Contains("crypto.randomUUID()") ||script.Contains("innerHTML")) + throw new Exception("Money UI does not use secure payout request contract"); + } using var index = await client.GetAsync("/"); Expect(index.StatusCode, HttpStatusCode.OK, "Index"); if (!(await index.Content.ReadAsStringAsync()).Contains("Control the")) @@ -203,6 +230,94 @@ try new StringContent("{\"command\":\"alert WARNUNG: Test\"}", Encoding.UTF8, "application/json"))) Expect(withoutCsrf.StatusCode, HttpStatusCode.Forbidden, "alert CSRF required"); client.DefaultRequestHeaders.Add("X-OGL-CSRF", csrf); + // Real ledger bookkeeping and replay/reconciliation tests on a volatile + // IN-MEMORY store. No production user, SQL row, payment or funds changed. + using (var moneyStatus = await client.GetAsync("/api/admin/money/status")) + { + Expect(moneyStatus.StatusCode,HttpStatusCode.OK,"money status admin"); + if (!(await moneyStatus.Content.ReadAsStringAsync()).Contains("100")) + throw new Exception("Invalid fixed rate in money status"); + } + Guid payoutRequestId = Guid.NewGuid(); + var moneyPayload = new { + avatarId = AccountProxy.Principal.ToString(), amountNv = 125, + description = "Automated test payout", requestId = payoutRequestId.ToString("D"), + source = "admin-manual" + }; + async Task SendMoney(object body) => + await client.PostAsync("/api/admin/money/payouts", + new StringContent(JsonSerializer.Serialize(body),Encoding.UTF8,"application/json")); + using (var firstPayout = await SendMoney(moneyPayload)) + Expect(firstPayout.StatusCode,HttpStatusCode.Created,"first money credit"); + if (fakeEconomy.GetBalance(AccountProxy.Principal.Guid) != 125) + throw new Exception("Incorrect ledger balance after first admin payout"); + using (var duplicatePayout = await SendMoney(moneyPayload)) + Expect(duplicatePayout.StatusCode,HttpStatusCode.OK,"duplicate money idempotency"); + if (fakeEconomy.GetBalance(AccountProxy.Principal.Guid) != 125) + throw new Exception("Duplicate payout credited more than once"); + using (var alteredPayout = await SendMoney(new { + avatarId=AccountProxy.Principal.ToString(),amountNv=126, + description="Automated test payout",requestId=payoutRequestId.ToString("D"), + source="admin-manual" + })) + Expect(alteredPayout.StatusCode,HttpStatusCode.Conflict,"replay with altered payout rejected"); + using (var fakeProviderPayment = await SendMoney(new { + avatarId=AccountProxy.Principal.ToString(),amountNv=100, + description="pretend stripe payment",requestId=Guid.NewGuid().ToString("D"), + source="stripe" + })) + Expect(fakeProviderPayment.StatusCode,HttpStatusCode.BadRequest, + "unverified Stripe payment must never mint NV$"); + using (var amountTooLarge = await SendMoney(new { + avatarId=AccountProxy.Principal.ToString(),amountNv=10001, + description="too large amount",requestId=Guid.NewGuid().ToString("D"), + source="admin-manual" + })) + Expect(amountTooLarge.StatusCode,HttpStatusCode.BadRequest,"limit enforced"); + using (var portalWithoutProxy = new HttpRequestMessage( + HttpMethod.Post,"/api/v1/portal/money/payouts")) + { + portalWithoutProxy.Headers.Authorization=new("Bearer",new string('C',64)); + portalWithoutProxy.Content=new StringContent(JsonSerializer.Serialize(new { + avatarId=AccountProxy.Principal.ToString(),amountNv=50, + description="Portal test grant",requestId=Guid.NewGuid().ToString("D"), + source="portal-manual"}),Encoding.UTF8,"application/json"); + using var rejection=await client.SendAsync(portalWithoutProxy); + Expect(rejection.StatusCode,HttpStatusCode.Unauthorized, + "portal token must never bypass trusted TLS proxy"); + } + if(fakeEconomy.GetBalance(AccountProxy.Principal.Guid)!=125) + throw new Exception("Unauthorized portal call changed NV$ balance"); + // Valid backend credential is distinct from the general read-only portal token. + // It may authorize an explicit manual grant, but not a claimed provider settlement. + Guid portalRequestId=Guid.NewGuid(); + async Task PortalMoney(string source,long amount,Guid reqId) + { + var msg=new HttpRequestMessage(HttpMethod.Post,"/api/v1/portal/money/payouts"); + msg.Headers.Authorization=new("Bearer",new string('C',64)); + msg.Headers.TryAddWithoutValidation("X-Forwarded-Proto","https"); + msg.Headers.TryAddWithoutValidation("X-Forwarded-Host","sysapi.example.test:8850"); + msg.Content=new StringContent(JsonSerializer.Serialize(new{ + avatarId=AccountProxy.Principal.ToString(),amountNv=amount, + description="Portal test grant",requestId=reqId.ToString("D"), + source=source + }),Encoding.UTF8,"application/json"); + using(msg) return await client.SendAsync(msg); + } + using(var settled=await PortalMoney("portal-manual",50,portalRequestId)) + Expect(settled.StatusCode,HttpStatusCode.Created,"authenticated portal grant"); + using(var repeated=await PortalMoney("portal-manual",50,portalRequestId)) + Expect(repeated.StatusCode,HttpStatusCode.OK,"portal at most one grant"); + using(var alteredPortal=await PortalMoney("portal-manual",75,portalRequestId)) + Expect(alteredPortal.StatusCode,HttpStatusCode.Conflict,"portal replay mismatch rejected"); + using(var unverified=await PortalMoney("paypal",50,Guid.NewGuid())) + Expect(unverified.StatusCode,HttpStatusCode.BadRequest,"claimed Paypal settlement never accepted"); + if(fakeEconomy.GetBalance(AccountProxy.Principal.Guid)!=175) + throw new Exception("Portal payments failed double-entry or idempotency"); + Console.WriteLine("PASS: SYS.API portal token isolation, TLS proxy gate, in-memory ledger credits and payment-provider denial"); + + Console.WriteLine("PASS: SYS.API NV$ exact 100:1 rate, admin ledger credit, idempotency, mismatch rejection, portal auth and fake-payment denial"); + async Task PostAlert(string command) => await client.PostAsync("/api/admin/alerts", new StringContent(JsonSerializer.Serialize(new { command }), Encoding.UTF8, "application/json")); From 0c1da7c78c8a6a8b559a81b26f9cb0d922841f8d Mon Sep 17 00:00:00 2001 From: "OpenGenesis (EULA)" <153564363+opengenesislink@users.noreply.github.com> Date: Wed, 25 Nov 2026 21:02:07 +0100 Subject: [PATCH 12/12] docs(g1): standalone SYS.API money payout with EUR fixed rate and PSP settlement gate --- doc/OpenGenesisLINK/SYS_API_NV_MONEY.md | 49 +++++++++++++++++++++++++ 1 file changed, 49 insertions(+) create mode 100644 doc/OpenGenesisLINK/SYS_API_NV_MONEY.md diff --git a/doc/OpenGenesisLINK/SYS_API_NV_MONEY.md b/doc/OpenGenesisLINK/SYS_API_NV_MONEY.md new file mode 100644 index 00000000..b3d12fa7 --- /dev/null +++ b/doc/OpenGenesisLINK/SYS_API_NV_MONEY.md @@ -0,0 +1,49 @@ +# SYS.API NV$ Auszahlungen – OpenGenesisLINK Generation 1 + +Stand 25.11.2026. Autoritatives Geldsystem ist das vorhandene MariaDB-gestützte NexVerse-Doppelbuch-Ledger; es wird keine zweite Wallet-Datenbank angelegt. + +## Auszahlungsoberfläche +Der Admin (UserLevel 200+) wählt einen lokalen Avatar über die bestehende Bürgerkontensuche aus, gibt einen ganzzahligen NV$-Betrag und einen Grund ein und bestätigt ausdrücklich. Die Oberfläche verwendet die bestehende Admin-Sitzung, Same-Origin und CSRF; kein Machine-Token erreicht den Browser. + +## Admin- und Portal-Endpunkte +- GET /api/admin/money/status – Ledgerbereitschaft, Limits und Wechselkurs. +- POST /api/admin/money/payouts – nur Administrator (UserLevel 200+), erneute Autorisierung, CSRF. +- GET /api/v1/portal/money/rate – nur mit eigenem NV$-Payout-Token über TLS-Proxy. +- POST /api/v1/portal/money/payouts – nur separate Server-zu-Server-Berechtigung; ausschließlich manuell genehmigte Portal-Gutschriften. + +Beispiel POST /api/v1/portal/money/payouts: + +```json +{ + "avatarId": "", + "amountNv": 100, + "description": "Manuell freigegebene Gutschrift durch Stadtportal", + "requestId": "", + "source": "portal-manual" +} +``` + +Authorization: Bearer und Content-Type: application/json; keine Tokens oder Passwörter im Browser oder GitHub. + +Antwort 201: neue Transaktion; 200: identische Wiederholung, keine neue Gutschrift; 409: dieselbe requestId mit geändertem Betrag, Empfänger, Grund oder Akteur; 400: ungültige Felder; 401: unberechtigt; 503: nicht aktiviert bzw. Ledger nicht erreichbar. Transaktion und UUID werden im Doppelbuch-Ledger protokolliert. + +## Sicherer Standard + +```ini +[SysApi] + MoneyAdminEnabled = false + MoneyPortalEnabled = false + MoneyMaxNvPerPayout = 10000 +``` + +Portalaktivierung benötigt zusätzlich OGL_SYSAPI_MONEY_PORTAL_TOKEN (64–128 zufällige Hex-Zeichen) nur als geschütztes Server-Secret. Der allgemeine Portal-Read-Token reicht für Auszahlungen nicht aus. Eine requestId muss bei HTTP-Retries unverändert bleiben. Maximalbeträge sind begrenzt; Payment-Systeme sind davon getrennt. + +## Euro und künftige Provider + +100 NV$ = 1,00 EUR. Für eine Zahlungen in EUR-Cent gilt ohne Rundungsfehler: NV$-Anzahl = Euro-Cent-Betrag. Beispiel: 250 Cent = 250 NV$. + +Stripe/PayPal werden nicht über einen Browserparameter „bezahlt=true“ vertrauenswürdig. Automatische Echtgeld-Gutschriften sind noch NICHT aktiv (paymentSettlementEnabled=false). Vor Aktivierung sind serverseitige Signatur-/Webhook- und Zahlungsstatusprüfung, EUR-Betrag, deduplizierte Provider-Event- und Payment-ID, Refund/Chargeback, Audit, Merchant-Bindung und abnahmereife End-to-End-Tests erforderlich. Provider-Webhooks dürfen nie ungeprüft an das manuelle Portal-Payout weitergeleitet werden. + +## Abnahme + +Isolierter .NET10-Build mit null Fehlern und null Warnungen. HTTP-Smoketest bestätigt Admin-Session, CSRF, unabhängig geschützten Portal-Token/TLS-Proxy, korrekte 100 NV$/EUR-Rate, einmalige Ledger-Gutschriften, Wiederholschutz, 409 bei Betragsänderung, Ablehnung unbestätigter PayPal-/Stripe-Behauptungen sowie weiterhin funktionierende Bürgerordnung und Alerts. Geldtests verwenden ausschließlich einen temporären InMemoryNexLedgerStore, keine produktiven Kontostände.