RynthCore as of 2026-10-04 (internal 843c801): RynthNav auto-travel and the navigation map, plugin API v75 (server and titles), launcher with Available plugins, download progress and the update on the front page, opt-in usage statistics, NPC names, radar colours, title-bar text size, FPS limiter, client action unlocks, release 2026.10.4.6

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Tom Bohar 2026-10-04 18:34:27 -04:00
commit a24ed6df7c
322 changed files with 83009 additions and 7504 deletions

View file

@ -27,6 +27,13 @@ internal sealed class AppSettings
/// with; the new one loads on the next AC start. Core updates always ask first.
public bool AutoUpdatePlugins { get; set; } = true;
/// "Help improve RynthCore": one anonymous usage report a day (see the launcher's
/// UsageStats.cs for exactly what is sent). OFF unless the player turns it on.
public bool UsageStatsEnabled { get; set; }
/// True once the launcher has explained usage statistics and asked (shown once).
public bool UsageStatsAsked { get; set; }
/// When true, the launcher kills any RynthCore-mode acclient.exe it
/// launched that hasn't reached IsLoggedIn within
/// <see cref="StuckClientTimeoutSeconds"/>. Catches stuck char-select,

View file

@ -1,5 +1,7 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text.Json;
using System.Text.Json.Serialization;
@ -12,15 +14,22 @@ internal static class AppSettingsStore
WriteIndented = true,
Converters =
{
// Before the general enum converter: InjectionMode is written so that every
// launcher can read it ("Decal + RynthCore" lives in decal-accounts.json).
new SharedInjectionModeConverter(),
new JsonStringEnumConverter()
}
};
private static string SettingsDirectory =>
/// <summary>Tests only (tools\LauncherSettingsTests): a folder used instead of %APPDATA%\RynthCore.</summary>
internal static string? DirectoryOverride { get; set; }
private static string SettingsDirectory => DirectoryOverride ??
Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "RynthCore");
private static string SettingsPath => Path.Combine(SettingsDirectory, "appsettings.json");
private static string BackupPath => SettingsPath + ".bak";
private static string DecalAccountsPath => DecalAccountModes.PathIn(SettingsDirectory);
/// <summary>
/// Set when the last Load() hit a corrupt/unreadable file (quarantined it,
@ -30,10 +39,22 @@ internal static class AppSettingsStore
/// </summary>
public static string? LastLoadDiagnostic { get; private set; }
/// <summary>
/// Set when the last Load() moved "Decal + RynthCore" accounts out of appsettings.json
/// into decal-accounts.json (a file written by a pre-release Decal bridge build), or found
/// decal-accounts.json unreadable. Null otherwise.
/// </summary>
public static string? LastMigrationNote { get; private set; }
public static AppSettings Load()
{
LastLoadDiagnostic = null;
LastMigrationNote = null;
return ApplyDecalAccounts(LoadShared());
}
private static AppSettings LoadShared()
{
if (!File.Exists(SettingsPath))
return new AppSettings();
@ -85,13 +106,56 @@ internal static class AppSettingsStore
}
}
/// <summary>
/// Puts back the "Decal + RynthCore" accounts listed in decal-accounts.json (those that
/// appsettings.json still lists as RynthCore). An appsettings.json that itself says
/// "DecalBridge" (written by a pre-release bridge build) is rewritten at once, .bak
/// included, so no launcher finds that value there again.
/// </summary>
private static AppSettings ApplyDecalAccounts(AppSettings settings)
{
List<LaunchAccountProfile> accounts = settings.AccountProfiles ?? new List<LaunchAccountProfile>();
int legacy = accounts.Count(a => a.InjectionMode == InjectionMode.DecalBridge);
HashSet<string> ids = DecalAccountModes.ReadIds(DecalAccountsPath, out string? error);
if (error != null)
LastMigrationNote = error;
foreach (LaunchAccountProfile account in accounts)
if (DecalAccountModes.IsDecalBridge(ids, account.Id, account.InjectionMode))
account.InjectionMode = InjectionMode.DecalBridge;
if (legacy > 0)
{
try
{
Save(settings);
File.Copy(SettingsPath, BackupPath, overwrite: true);
LastMigrationNote = $"Moved {legacy} \"Decal + RynthCore\" account(s) from appsettings.json to " +
$"{DecalAccountModes.FileName}, so older launchers can still read appsettings.json.";
}
catch (Exception ex)
{
LastMigrationNote = $"Could not move \"Decal + RynthCore\" accounts to {DecalAccountModes.FileName} " +
$"({ex.GetType().Name}: {ex.Message}); the next save retries.";
}
}
return settings;
}
public static void Save(AppSettings settings)
{
// "Decal + RynthCore" accounts go to decal-accounts.json first; appsettings.json
// lists them as RynthCore (SharedInjectionModeConverter).
Directory.CreateDirectory(SettingsDirectory);
DecalAccountModes.WriteIds(DecalAccountsPath,
(settings.AccountProfiles ?? new List<LaunchAccountProfile>())
.Where(a => a.InjectionMode == InjectionMode.DecalBridge)
.Select(a => a.Id));
// Atomic write: serialize to a temp file, then swap it in. A crash or
// power cut mid-write can no longer truncate the live file (which holds
// every server/account profile and is rewritten constantly); the swap
// also maintains a .bak Load() can recover from.
Directory.CreateDirectory(SettingsDirectory);
string tmp = SettingsPath + ".tmp";
File.WriteAllText(tmp, JsonSerializer.Serialize(settings, JsonOptions));
if (File.Exists(SettingsPath))
@ -99,4 +163,32 @@ internal static class AppSettingsStore
else
File.Move(tmp, SettingsPath);
}
/// <summary>
/// InjectionMode in appsettings.json. Writes only names every launcher knows: DecalBridge is
/// written as <see cref="DecalAccountModes.SharedMode"/> (decal-accounts.json holds the real
/// choice). Reads names and numbers; a name or number this build doesn't know reads as RynthCore
/// instead of making the whole file unreadable.
/// </summary>
private sealed class SharedInjectionModeConverter : JsonConverter<InjectionMode>
{
public override InjectionMode Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
if (reader.TokenType == JsonTokenType.Number && reader.TryGetInt32(out int number))
return Enum.IsDefined((InjectionMode)number) ? (InjectionMode)number : InjectionMode.RynthCore;
if (reader.TokenType == JsonTokenType.String)
{
return Enum.TryParse(reader.GetString(), ignoreCase: true, out InjectionMode mode) && Enum.IsDefined(mode)
? mode
: InjectionMode.RynthCore;
}
throw new JsonException($"InjectionMode: unexpected {reader.TokenType}.");
}
public override void Write(Utf8JsonWriter writer, InjectionMode value, JsonSerializerOptions options)
{
InjectionMode shared = value == InjectionMode.DecalBridge ? DecalAccountModes.SharedMode : value;
writer.WriteStringValue(shared.ToString());
}
}
}

View file

@ -46,6 +46,13 @@ internal static class CharacterCacheStore
List<string> serverCharacters = ReadCharacterFile(GetServerScopedPath(safeServer, safeAccount));
if (serverCharacters.Count > 0)
return serverCharacters;
// The same account name can exist on several servers. The legacy
// account-only file predates server scoping, so it is only trusted
// while no server-scoped file exists for this account at all;
// otherwise it would hand one server's characters to another.
if (HasAnyServerScopedFile(safeAccount))
return [];
}
return ReadCharacterFile(GetAccountScopedPath(safeAccount));
@ -84,7 +91,11 @@ internal static class CharacterCacheStore
if (string.IsNullOrWhiteSpace(accountName) || string.IsNullOrWhiteSpace(characterName))
return;
List<string> characters = Read(accountName, serverName);
// With a server, seed only from that server's own file so a legacy
// account-only list cannot be merged into the wrong server.
List<string> characters = string.IsNullOrWhiteSpace(serverName)
? Read(accountName, serverName)
: ReadStrict(accountName, serverName);
if (!characters.Any(existing => IsSameCharacter(existing, characterName)))
characters.Add(characterName);
@ -96,27 +107,34 @@ internal static class CharacterCacheStore
private static bool IsSameCharacter(string a, string b) =>
string.Equals(a.Trim().TrimStart('+'), b.Trim().TrimStart('+'), StringComparison.OrdinalIgnoreCase);
public static void DeleteForAccount(string accountName)
/// Deletes the character cache for one (account, server) pair. Other servers'
/// files for the same account name are left alone. The legacy account-only
/// file is removed only when <paramref name="includeLegacy"/> is set (the
/// caller knows whether another profile still uses this account name).
public static void DeleteForAccount(string accountName, string serverName, bool includeLegacy)
{
if (string.IsNullOrWhiteSpace(accountName))
return;
try
{
string rootDirectory = GetRootDirectory();
if (!Directory.Exists(rootDirectory))
return;
string safeAccount = SanitizeFileName(accountName);
foreach (string file in Directory.GetFiles(rootDirectory, $"characters_*_{safeAccount}.json"))
if (!string.IsNullOrWhiteSpace(serverName))
{
try { File.Delete(file); } catch { }
string serverScopedPath = GetServerScopedPath(SanitizeFileName(serverName), safeAccount);
if (File.Exists(serverScopedPath))
{
try { File.Delete(serverScopedPath); } catch { }
}
}
string accountScopedPath = GetAccountScopedPath(safeAccount);
if (File.Exists(accountScopedPath))
if (includeLegacy)
{
try { File.Delete(accountScopedPath); } catch { }
string accountScopedPath = GetAccountScopedPath(safeAccount);
if (File.Exists(accountScopedPath))
{
try { File.Delete(accountScopedPath); } catch { }
}
}
}
catch
@ -124,6 +142,20 @@ internal static class CharacterCacheStore
}
}
private static bool HasAnyServerScopedFile(string safeAccountName)
{
try
{
string rootDirectory = GetRootDirectory();
return Directory.Exists(rootDirectory) &&
Directory.EnumerateFiles(rootDirectory, $"characters_*_{safeAccountName}.json").Any();
}
catch
{
return false;
}
}
private static string GetRootDirectory() =>
Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "RynthCore");

View file

@ -0,0 +1,113 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text.Json;
namespace RynthCore.App;
/// <summary>
/// Which accounts run as "Decal + RynthCore" (<see cref="InjectionMode.DecalBridge"/>), kept in
/// <c>decal-accounts.json</c> next to <c>%APPDATA%\RynthCore\appsettings.json</c> and keyed by
/// account profile id.
///
/// Why a file of its own: every launcher of this Windows user shares appsettings.json, and a
/// launcher released before the Decal bridge has no "DecalBridge" value in its InjectionMode.
/// Its AppSettingsStore takes a file with that value for corrupt, quarantines it and falls back
/// to the .bak, or to empty defaults (and then saves those). So appsettings.json always lists a
/// "Decal + RynthCore" account as <see cref="SharedMode"/> (RynthCore), and this file says which
/// of those are really "Decal + RynthCore".
///
/// An entry only counts while appsettings.json still says RynthCore for that account: an older
/// launcher that switched the account to Decal (or that deleted it) wins, and the next save of a
/// newer launcher drops the stale entry. Shared with the injector (LaunchCommand).
/// </summary>
internal static class DecalAccountModes
{
public const string FileName = "decal-accounts.json";
/// <summary>What appsettings.json says for a "Decal + RynthCore" account.</summary>
public const InjectionMode SharedMode = InjectionMode.RynthCore;
private const int SchemaVersion = 1;
private const string Note =
"Accounts the RynthCore launcher runs as \"Decal + RynthCore\" (experimental). " +
"appsettings.json lists them as RynthCore, so launchers without that mode can still read it. " +
"Delete this file to set them all back to RynthCore.";
private sealed class FileModel
{
public int Version { get; set; } = SchemaVersion;
public string Note { get; set; } = DecalAccountModes.Note;
public List<string> DecalBridgeAccountIds { get; set; } = new();
}
private static readonly JsonSerializerOptions WriteOptions = new() { WriteIndented = true };
public static string PathIn(string settingsDirectory) => Path.Combine(settingsDirectory, FileName);
/// <summary>
/// The account ids listed in <paramref name="path"/>. An absent file is an empty set; an
/// unreadable one too, with the reason in <paramref name="error"/> (the accounts then run
/// as appsettings.json says, which is RynthCore).
/// </summary>
public static HashSet<string> ReadIds(string path, out string? error)
{
error = null;
var ids = new HashSet<string>(StringComparer.Ordinal);
try
{
if (!File.Exists(path))
return ids;
FileModel? model = JsonSerializer.Deserialize<FileModel>(File.ReadAllText(path));
foreach (string id in model?.DecalBridgeAccountIds ?? new List<string>())
if (!string.IsNullOrWhiteSpace(id))
ids.Add(id);
}
catch (Exception ex)
{
error = $"{FileName} could not be read ({ex.GetType().Name}: {ex.Message}); " +
"its accounts run as RynthCore until the mode is picked again.";
ids.Clear();
}
return ids;
}
/// <summary>
/// True when an account that appsettings.json lists with <paramref name="sharedMode"/> is a
/// "Decal + RynthCore" account: it is in <paramref name="ids"/> and still says RynthCore.
/// </summary>
public static bool IsDecalBridge(IReadOnlySet<string> ids, string? accountId, InjectionMode sharedMode) =>
sharedMode == SharedMode && !string.IsNullOrEmpty(accountId) && ids.Contains(accountId);
/// <summary>
/// Records <paramref name="ids"/> as the "Decal + RynthCore" accounts. Writes only when the
/// list changed; with no accounts left, the file is removed. Atomic (temp file + swap).
/// </summary>
public static void WriteIds(string path, IEnumerable<string> ids)
{
List<string> sorted = ids.Where(id => !string.IsNullOrWhiteSpace(id))
.Distinct(StringComparer.Ordinal)
.OrderBy(id => id, StringComparer.Ordinal)
.ToList();
if (sorted.Count == 0)
{
if (File.Exists(path))
File.Delete(path);
return;
}
if (File.Exists(path))
{
HashSet<string> current = ReadIds(path, out string? error);
if (error == null && current.SetEquals(sorted))
return;
}
Directory.CreateDirectory(Path.GetDirectoryName(path)!);
string tmp = path + ".tmp";
File.WriteAllText(tmp, JsonSerializer.Serialize(new FileModel { DecalBridgeAccountIds = sorted }, WriteOptions));
File.Move(tmp, path, overwrite: true);
}
}

View file

@ -0,0 +1,495 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.Json;
namespace RynthCore.App;
/// <summary>Registry roots the Decal check reads. "32" = the 32-bit view (WOW6432Node on 64-bit Windows).</summary>
internal enum RegRoot { Machine32, Machine64, User32, User64 }
/// <summary>A read-only registry key (real one, or a fake in tools\DecalBridgeCheckTests).</summary>
internal interface IRegKey : IDisposable
{
object? GetValue(string name);
string[] GetSubKeyNames();
string[] GetValueNames();
}
/// <summary>
/// Everything <see cref="DecalBridgeCheck"/> reads from the machine. The real one is
/// <see cref="RealDecalCheckHost"/>; the offline tests use a fake.
/// </summary>
internal interface IDecalCheckHost
{
bool Is64BitOs { get; }
/// <summary>The launcher (or injector) runs elevated. A client it starts is elevated too.</summary>
bool LauncherElevated { get; }
/// <summary>UAC registry virtualization is on for this process (as it is for a non-elevated AC).</summary>
bool LauncherVirtualized { get; }
/// <summary>The real registry: no UAC virtualization (HKLM is HKLM, the VirtualStore is its own key).</summary>
IRegKey? OpenReal(RegRoot root, string subKey);
/// <summary>
/// HKLM (32-bit view) as THIS process sees it, virtualized when the process is. Only the
/// bridge's own entry is asked for (the real host snapshots it before virtualization is
/// switched off for the rest of the check).
/// </summary>
IRegKey? OpenOwnViewMachine32(string subKey);
bool FileExists(string path);
/// <summary>The file carries a Zone.Identifier stream ("downloaded from the internet").</summary>
bool HasZoneIdentifier(string path);
Version? AssemblyVersionOf(string path);
Version? ReferenceVersionOf(string assemblyPath, string referenceName);
/// <summary>requestedExecutionLevel from the exe's embedded manifest or its .manifest file, null if none.</summary>
string? ExecutionLevelOf(string exePath);
string? ReadTextFile(string path);
}
/// <summary>
/// "Check Decal bridge": can a Decal + RynthCore client started now load the RynthCore Decal
/// bridge? (docs/DECAL_BRIDGE_PLAN.md, "Where Decal reads its filters").
///
/// Decal lists network filters from HKLM\SOFTWARE\Decal\NetworkFilters (decalnet.dll), read
/// by the 32-bit client through the 32-bit view (WOW6432Node), and Decal.Adapter reads each
/// .NET filter's Path/Assembly/Object from SOFTWARE\Decal\NetworkFilters\{id}. Which key that
/// really is depends on the CLIENT's token:
/// - a non-elevated acclient.exe (no manifest, UAC on) is virtualized: when the per-user copy
/// HKCU\Software\Classes\VirtualStore\MACHINE\SOFTWARE\WOW6432Node\Decal\NetworkFilters
/// exists, Decal reads ONLY that copy; otherwise the real HKLM key;
/// - an elevated client (the launcher runs as administrator, acclient.exe set to "Run as
/// administrator", UAC off), or one with a manifest, or with virtualization off by policy,
/// is not virtualized and reads the real HKLM key - a per-user registration is invisible.
/// The check predicts that, reads our entry from where Decal will read it, and where it can
/// (the launcher's token is virtualized exactly when the client's will be) reads it again
/// through the launcher's own view, which is the client's view.
/// </summary>
internal static class DecalBridgeCheck
{
public enum Level { Ok, Info, Warn, Fail }
public sealed record Line(Level Level, string Text);
public sealed class Result
{
public List<Line> Lines { get; } = new();
public bool DecalInstalled { get; set; }
public string? DecalVersion { get; set; }
public bool ClientVirtualized { get; set; }
public string ClientReason { get; set; } = string.Empty;
/// <summary>Where Decal reads its filter list on this machine, for people.</summary>
public string FiltersReadFrom { get; set; } = string.Empty;
public bool ReadsPerUserCopy { get; set; }
/// <summary>Our entry is where Decal reads, enabled, with the DLL in place.</summary>
public bool BridgeVisibleToDecal { get; set; }
/// <summary>Not registered where Decal reads, and that place is HKLM: needs administrator rights once.</summary>
public bool NeedsMachineWideRegistration { get; set; }
public bool Blocking => Lines.Any(l => l.Level == Level.Fail);
public void Add(Level level, string text) => Lines.Add(new Line(level, text));
public string Summary => Blocking
? "Decal bridge check: FAILED - " + string.Join(" ", Lines.Where(l => l.Level == Level.Fail).Select(l => l.Text))
: "Decal bridge check: OK - " + FiltersReadFrom + (DecalVersion != null ? $"; Decal {DecalVersion}" : "");
public string ToReport()
{
var sb = new StringBuilder();
foreach (Line l in Lines)
{
string tag = l.Level switch { Level.Ok => "OK ", Level.Info => " ", Level.Warn => "WARN", _ => "FAIL" };
sb.Append(tag).Append(" ").AppendLine(l.Text);
}
sb.AppendLine();
sb.AppendLine(Blocking
? "Result: a Decal + RynthCore client started now would NOT load the bridge (no RynthCore overlay, then a crash). Fix the FAIL lines first."
: "Result: a Decal + RynthCore client started now will load the bridge.");
return sb.ToString();
}
}
/// <summary>Decal's .NET surrogate CLSID (Decal.Adapter.Surrogate).</summary>
public const string SurrogateClsid = "{71A69713-6593-47EC-0002-0000000DECA1}";
/// <summary>The bridge targets .NET Framework 4.8 (Release key 528040).</summary>
private const int Net48Release = 528040;
public static string VirtualStoreDecalPath(bool is64BitOs, string group) => is64BitOs
? @"Software\Classes\VirtualStore\MACHINE\SOFTWARE\WOW6432Node\Decal\" + group
: @"Software\Classes\VirtualStore\MACHINE\SOFTWARE\Decal\" + group;
public static string MachineDecalPath(string group) => @"SOFTWARE\Decal\" + group;
/// <summary>
/// Will a client started by this launcher get UAC registry virtualization? False when it
/// runs elevated or Windows doesn't virtualize it (reason says which).
/// </summary>
public static bool PredictClientVirtualized(IDecalCheckHost host, string? acClientPath, out string reason)
{
int? lua = DwordOf(host, RegRoot.Machine64, @"SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System", "EnableLUA");
if (lua == 0)
{
reason = "UAC is turned off on this PC (EnableLUA=0), so Windows gives every program the real machine registry";
return false;
}
int? virt = DwordOf(host, RegRoot.Machine64, @"SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System", "EnableVirtualization");
if (virt == 0)
{
reason = "UAC registry virtualization is turned off by policy (EnableVirtualization=0)";
return false;
}
if (host.LauncherElevated)
{
reason = "RynthCore runs as administrator, so the AC client it starts does too, and Windows gives it the real machine registry";
return false;
}
if (!string.IsNullOrEmpty(acClientPath))
{
string? level = host.ExecutionLevelOf(acClientPath);
if (level != null)
{
reason = $"{Path.GetFileName(acClientPath)} has a manifest (requestedExecutionLevel={level}), so Windows doesn't virtualize it";
return false;
}
string? layer = RunAsAdminLayer(host, acClientPath);
if (layer != null)
{
reason = $"{acClientPath} is set to \"Run this program as an administrator\" ({layer})";
return false;
}
}
reason = "AC runs without administrator rights, so Windows virtualizes its registry";
return true;
}
/// <summary>
/// Where a client (virtualized or not) reads SOFTWARE\Decal\&lt;group&gt;: the per-user
/// VirtualStore copy when it is virtualized and the copy exists, else the real HKLM key.
/// </summary>
public static (RegRoot Root, string Path, bool PerUser) WhereDecalReads(IDecalCheckHost host, bool clientVirtualized, string group)
{
if (clientVirtualized)
{
string vs = VirtualStoreDecalPath(host.Is64BitOs, group);
using IRegKey? k = host.OpenReal(RegRoot.User64, vs);
if (k != null)
return (RegRoot.User64, vs, true);
}
return (RegRoot.Machine32, MachineDecalPath(group), false);
}
/// <summary>
/// What the installer (and every update) writes, so a client finds the bridge whatever
/// its rights (installer\RynthCore.iss: <see cref="DecalBridgeRegistration.RegisterMachineWide"/>
/// elevated, <see cref="DecalBridgeRegistration.InstallPerUser"/> as the installing user):
/// - Machine: always (when Decal is installed). Elevated and unvirtualized clients read
/// only HKLM; a virtualized client without a per-user copy reads HKLM too.
/// - PerUser: only into a per-user copy that ALREADY exists. A virtualized client then
/// reads that copy and nothing else, so the HKLM entry is hidden from it. Creating a
/// copy that doesn't exist would be harmful: it would hide every HKLM filter added later
/// (a Decal plugin installed for all users) from this user's non-elevated clients.
/// </summary>
public static (bool Machine, bool PerUser) PlanInstall(IDecalCheckHost host)
{
bool decal = StringOf(host, RegRoot.Machine32, MachineDecalPath("Agent"), "AgentPath") != null;
if (!decal) return (false, false);
using IRegKey? copy = host.OpenReal(RegRoot.User64, VirtualStoreDecalPath(host.Is64BitOs, "NetworkFilters"));
return (true, copy != null);
}
public static string Describe(bool is64BitOs, RegRoot root, string path) => root switch
{
RegRoot.Machine32 => is64BitOs ? @"HKLM\SOFTWARE\WOW6432Node\" + path.Substring("SOFTWARE\\".Length) : @"HKLM\" + path,
RegRoot.Machine64 => @"HKLM\" + path,
_ => @"HKCU\" + path,
};
/// <summary>Runs every check. Reads only; changes nothing.</summary>
public static Result Run(IDecalCheckHost host, string bridgeDirectory, string? acClientPath, string? engineJsonPath)
{
var r = new Result();
string dir = bridgeDirectory.TrimEnd('\\');
// 1. Decal and its version.
string? agentPath = StringOf(host, RegRoot.Machine32, MachineDecalPath("Agent"), "AgentPath");
r.DecalInstalled = agentPath != null && host.FileExists(Path.Combine(agentPath, "Inject.dll"));
if (!r.DecalInstalled)
{
r.Add(Level.Fail, @"Decal is not installed (HKLM\SOFTWARE\Decal\Agent AgentPath\Inject.dll not found).");
return r;
}
string adapter = Path.Combine(agentPath!, "Decal.Adapter.dll");
Version? installed = host.FileExists(adapter) ? host.AssemblyVersionOf(adapter) : null;
string bridgeDll = Path.Combine(dir, DecalBridgeRegistration.AssemblyFile);
bool bridgePresent = host.FileExists(bridgeDll);
Version? needed = bridgePresent ? host.ReferenceVersionOf(bridgeDll, "Decal.Adapter") : null;
r.DecalVersion = installed?.ToString();
if (installed == null)
r.Add(Level.Fail, $"Decal.Adapter.dll is missing or unreadable in {agentPath} - reinstall Decal.");
else if (needed != null && installed < needed)
r.Add(Level.Fail, $"Decal {installed} is older than the {needed} the bridge is built for - update Decal (decaldev.com), then check again.");
else
r.Add(Level.Ok, $"Decal {installed} in {agentPath}" + (needed != null ? $" (bridge built for {needed})." : "."));
// 2. The bridge DLL itself.
if (!bridgePresent)
r.Add(Level.Fail, $"{DecalBridgeRegistration.AssemblyFile} is missing from {dir} - reinstall RynthCore.");
else if (host.HasZoneIdentifier(bridgeDll))
r.Add(Level.Warn, $"{bridgeDll} is marked as downloaded from the internet; .NET may refuse to load it. Repair removes the mark (or: right-click > Properties > Unblock).");
else
r.Add(Level.Ok, $"Bridge DLL present: {bridgeDll}.");
// 3. How the client will see the registry.
r.ClientVirtualized = PredictClientVirtualized(host, acClientPath, out string why);
r.ClientReason = why;
r.Add(Level.Info, "AC client: " + why + ".");
// 4. Where Decal reads its filters, and our entry there.
var where = WhereDecalReads(host, r.ClientVirtualized, "NetworkFilters");
r.ReadsPerUserCopy = where.PerUser;
string whereText = Describe(host.Is64BitOs, where.Root, where.Path);
r.FiltersReadFrom = "Decal reads its filters from " + whereText + (where.PerUser ? " (your Windows user's copy)" : "");
r.Add(Level.Info, r.FiltersReadFrom + ".");
string? entryProblem = EntryProblem(host, where.Root, where.Path + "\\" + DecalBridgeRegistration.FilterGuid, out string? registeredPath);
if (entryProblem == null)
{
r.BridgeVisibleToDecal = true;
r.Add(Level.Ok, $"RynthCore Decal Bridge is registered there and enabled ({registeredPath}).");
}
else
{
r.NeedsMachineWideRegistration = !where.PerUser;
r.Add(Level.Fail, $"Decal will not load the bridge: {entryProblem} in {whereText}." +
(where.PerUser
? " Repair (or a Decal + RynthCore launch) registers it for your Windows user."
: " That key is shared by all users: Repair adds it there once and Windows asks for administrator permission."));
}
// Other places, for people (a registration Decal won't read explains a "registered but nothing happens").
if (where.PerUser)
{
using IRegKey? m = host.OpenReal(RegRoot.Machine32, MachineDecalPath("NetworkFilters") + "\\" + DecalBridgeRegistration.FilterGuid);
if (m != null && IsOurs(m) && entryProblem != null)
r.Add(Level.Info, "(A machine-wide entry exists, but your per-user copy hides it from AC.)");
}
else
{
using IRegKey? u = host.OpenReal(RegRoot.User64, VirtualStoreDecalPath(host.Is64BitOs, "NetworkFilters") + "\\" + DecalBridgeRegistration.FilterGuid);
if (u != null && IsOurs(u) && entryProblem != null)
r.Add(Level.Info, "(A per-user registration exists, but this AC client doesn't read it: " + why + ".)");
}
// 5. The same entry through this process's own view, when that view IS the client's.
bool sameView = host.LauncherVirtualized == r.ClientVirtualized;
if (sameView)
{
using IRegKey? live = host.OpenOwnViewMachine32(MachineDecalPath("NetworkFilters") + "\\" + DecalBridgeRegistration.FilterGuid);
bool liveOk = live != null && IsOurs(live) && IsEnabled(live);
if (liveOk == r.BridgeVisibleToDecal)
r.Add(Level.Ok, $"Read back as AC will see it: {(liveOk ? "bridge listed and enabled" : "bridge not listed")}.");
else
r.Add(liveOk ? Level.Warn : Level.Fail,
$"Read back as AC will see it: {(liveOk ? "bridge listed" : "bridge NOT listed")}, which disagrees with {whereText}. Windows serves this PC's registry differently than expected.");
}
else
{
r.Add(Level.Info, "Not read back live: AC will run with other rights than this launcher.");
}
// 6. Hidden machine filters (a per-user list hides every HKLM entry it lacks).
if (where.PerUser)
{
List<string> hidden = HiddenMachineFilters(host, where.Path);
if (hidden.Count > 0)
r.Add(Level.Warn, "Hidden from AC by your per-user filter list (in HKLM, not in the copy): " + string.Join(", ", hidden) +
". If 'World Object Filter' is among them, VTank won't start.");
}
// 7. Decal's .NET surrogate: Decal must be able to create it, and must not have it disabled.
var surWhere = WhereDecalReads(host, r.ClientVirtualized, "Surrogates");
using (IRegKey? s = host.OpenReal(surWhere.Root, surWhere.Path + "\\" + SurrogateClsid))
{
if (s == null)
r.Add(Level.Fail, $"Decal's .NET surrogate is not listed in {Describe(host.Is64BitOs, surWhere.Root, surWhere.Path)} - no .NET filter or plugin can load. Reinstall Decal.");
else if (!IsEnabled(s))
r.Add(Level.Fail, "Decal's .NET surrogate (Decal.Adapter Surrogate) is disabled in Decal - enable it in Decal's agent (or reinstall Decal).");
else
r.Add(Level.Ok, "Decal's .NET surrogate is enabled.");
}
string? comProblem = SurrogateComProblem(host, clientElevated: !r.ClientVirtualized && IsClientElevated(host, acClientPath), out string comWhere);
if (comProblem != null)
r.Add(Level.Fail, comProblem);
else
r.Add(Level.Ok, $"Decal.Adapter's COM class resolves ({comWhere}). The bridge itself needs no COM registration: Decal.Adapter loads it from Path\\Assembly.");
// 8. .NET Framework 4.8.
int? release = DwordOf(host, RegRoot.Machine32, @"SOFTWARE\Microsoft\NET Framework Setup\NDP\v4\Full", "Release");
if (release == null)
r.Add(Level.Fail, ".NET Framework 4 is not installed (Decal needs it).");
else if (release < Net48Release)
r.Add(Level.Warn, $".NET Framework older than 4.8 (Release {release}); the bridge targets 4.8 - install .NET Framework 4.8.");
// 9. engine.json settings that turn bridge mode off.
if (engineJsonPath != null)
{
(string? mode, bool? inGame) = ReadEngineSettings(host, engineJsonPath);
if (mode != null && (mode.Equals("Off", StringComparison.OrdinalIgnoreCase) || mode.Equals("false", StringComparison.OrdinalIgnoreCase)))
r.Add(Level.Fail, $"engine.json has \"DecalBridge\": {mode} - bridge mode is off for every client. Remove that line ({engineJsonPath}).");
if (inGame == false)
r.Add(Level.Warn, "engine.json has \"DecalInGameImGui\": false - no RynthCore overlay under Decal (by choice).");
}
return r;
}
// ── pieces (internal for the tests) ─────────────────────────────────────
internal static string? EntryProblem(IDecalCheckHost host, RegRoot root, string entryPath, out string? registeredPath)
{
registeredPath = null;
using IRegKey? k = host.OpenReal(root, entryPath);
if (k == null) return "the RynthCore Decal Bridge is not registered";
if (!IsOurs(k)) return "another filter uses the bridge's id";
registeredPath = k.GetValue("Path") as string;
if (!IsEnabled(k)) return "the RynthCore Decal Bridge is registered but disabled";
if (!string.Equals(k.GetValue("Surrogate") as string, SurrogateClsid, StringComparison.OrdinalIgnoreCase))
return "the bridge entry has the wrong Surrogate";
string? file = k.GetValue("Assembly") as string;
if (string.IsNullOrEmpty(registeredPath) || string.IsNullOrEmpty(file))
return "the bridge entry has no Path/Assembly";
if (!host.FileExists(Path.Combine(registeredPath, file)))
return $"the registered bridge DLL is missing ({Path.Combine(registeredPath, file)})";
return null;
}
internal static List<string> HiddenMachineFilters(IDecalCheckHost host, string perUserPath)
{
var hidden = new List<string>();
using IRegKey? machine = host.OpenReal(RegRoot.Machine32, MachineDecalPath("NetworkFilters"));
using IRegKey? user = host.OpenReal(RegRoot.User64, perUserPath);
if (machine == null || user == null) return hidden;
var seen = new HashSet<string>(user.GetSubKeyNames(), StringComparer.OrdinalIgnoreCase);
foreach (string name in machine.GetSubKeyNames())
{
if (seen.Contains(name) || string.Equals(name, DecalBridgeRegistration.FilterGuid, StringComparison.OrdinalIgnoreCase))
continue;
using IRegKey? k = host.OpenReal(RegRoot.Machine32, MachineDecalPath("NetworkFilters") + "\\" + name);
hidden.Add(k?.GetValue("") is string friendly && friendly.Length > 0 ? friendly : name);
}
return hidden;
}
/// <summary>
/// Decal.Adapter's surrogate is an mscoree COM class. A non-elevated client resolves it
/// per-user first (HKCU\Software\Classes), then machine-wide; an elevated one ignores
/// per-user COM registrations.
/// </summary>
internal static string? SurrogateComProblem(IDecalCheckHost host, bool clientElevated, out string where)
{
where = string.Empty;
string sub = @"\CLSID\" + SurrogateClsid + @"\InprocServer32";
var candidates = new List<(RegRoot Root, string Path, string Label)>();
if (!clientElevated) candidates.Add((RegRoot.User32, @"Software\Classes" + sub, "per-user"));
candidates.Add((RegRoot.Machine32, @"SOFTWARE\Classes" + sub, "machine-wide"));
foreach (var c in candidates)
{
using IRegKey? k = host.OpenReal(c.Root, c.Path);
if (k == null) continue;
where = c.Label;
string server = k.GetValue("") as string ?? string.Empty;
if (!server.EndsWith("mscoree.dll", StringComparison.OrdinalIgnoreCase))
return $"Decal.Adapter's COM class ({c.Label}) points at '{server}', not mscoree.dll - reinstall Decal.";
if (string.IsNullOrEmpty(k.GetValue("Assembly") as string))
return $"Decal.Adapter's COM class ({c.Label}) names no assembly - reinstall Decal.";
if (k.GetValue("CodeBase") is string cb && cb.Length > 0)
{
string file = cb.StartsWith("file:", StringComparison.OrdinalIgnoreCase) ? cb.Substring(5).TrimStart('/') : cb;
if (!host.FileExists(file.Replace('/', '\\')))
return $"Decal.Adapter's COM class ({c.Label}) points at a missing file ({file}) - reinstall Decal.";
}
return null;
}
bool perUserOnly = clientElevated && OpenExists(host, RegRoot.User32, @"Software\Classes" + sub);
return perUserOnly
? "Decal.Adapter's COM class is registered only for your Windows user, and an AC running as administrator ignores per-user COM classes - reinstall Decal for all users."
: "Decal.Adapter's COM class (Decal.Adapter.Surrogate) is not registered - reinstall Decal.";
}
private static bool IsClientElevated(IDecalCheckHost host, string? acClientPath)
{
if (host.LauncherElevated) return true;
if (string.IsNullOrEmpty(acClientPath)) return false;
string? level = host.ExecutionLevelOf(acClientPath);
if (level != null && (level.Equals("requireAdministrator", StringComparison.OrdinalIgnoreCase) || level.Equals("highestAvailable", StringComparison.OrdinalIgnoreCase)))
return true;
if (RunAsAdminLayer(host, acClientPath) != null) return true;
// UAC off: an administrator's programs run with the full token.
return DwordOf(host, RegRoot.Machine64, @"SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System", "EnableLUA") == 0;
}
private static string? RunAsAdminLayer(IDecalCheckHost host, string exePath)
{
foreach ((RegRoot root, string key) in new[]
{
(RegRoot.User64, @"Software\Microsoft\Windows NT\CurrentVersion\AppCompatFlags\Layers"),
(RegRoot.Machine64, @"SOFTWARE\Microsoft\Windows NT\CurrentVersion\AppCompatFlags\Layers"),
})
{
using IRegKey? k = host.OpenReal(root, key);
if (k == null) continue;
foreach (string name in k.GetValueNames())
{
if (!string.Equals(name, exePath, StringComparison.OrdinalIgnoreCase)) continue;
string flags = k.GetValue(name) as string ?? string.Empty;
string[] parts = flags.Split(' ', StringSplitOptions.RemoveEmptyEntries);
if (parts.Any(p => p.Equals("RUNASADMIN", StringComparison.OrdinalIgnoreCase) || p.Equals("RUNASHIGHEST", StringComparison.OrdinalIgnoreCase)))
return (root == RegRoot.User64 ? "your compatibility settings" : "compatibility settings for all users") + ": " + flags.Trim();
}
}
return null;
}
private static (string? Mode, bool? InGame) ReadEngineSettings(IDecalCheckHost host, string path)
{
try
{
string? text = host.ReadTextFile(path);
if (text == null) return (null, null);
using JsonDocument doc = JsonDocument.Parse(text, new JsonDocumentOptions { CommentHandling = JsonCommentHandling.Skip, AllowTrailingCommas = true });
string? mode = null;
bool? inGame = null;
if (doc.RootElement.TryGetProperty("DecalBridge", out JsonElement m))
mode = m.ValueKind switch { JsonValueKind.String => m.GetString(), JsonValueKind.True => "true", JsonValueKind.False => "false", _ => null };
if (doc.RootElement.TryGetProperty("DecalInGameImGui", out JsonElement g) && (g.ValueKind == JsonValueKind.True || g.ValueKind == JsonValueKind.False))
inGame = g.GetBoolean();
return (mode, inGame);
}
catch
{
return (null, null);
}
}
internal static bool IsOurs(IRegKey k) =>
string.Equals(k.GetValue("Object") as string, DecalBridgeRegistration.FilterObject, StringComparison.Ordinal);
internal static bool IsEnabled(IRegKey k) => k.GetValue("Enabled") is int e && e != 0;
private static bool OpenExists(IDecalCheckHost host, RegRoot root, string path)
{
using IRegKey? k = host.OpenReal(root, path);
return k != null;
}
private static int? DwordOf(IDecalCheckHost host, RegRoot root, string path, string name)
{
using IRegKey? k = host.OpenReal(root, path);
return k?.GetValue(name) is int v ? v : null;
}
private static string? StringOf(IDecalCheckHost host, RegRoot root, string path, string name)
{
using IRegKey? k = host.OpenReal(root, path);
return k?.GetValue(name) is string s && s.Length > 0 ? s : null;
}
}

View file

@ -0,0 +1,810 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.Json;
using Microsoft.Win32;
namespace RynthCore.App;
/// <summary>
/// Registers (and cleanly unregisters) the RynthCore Decal bridge - the small Decal
/// network filter in src\RynthCore.DecalBridge - in Decal's filter list. See
/// docs\DECAL_BRIDGE_PLAN.md, "Where Decal reads its filters".
///
/// <see cref="RegisterForClients"/> picks the place: the per-user copy below when the AC
/// client will be virtualized (the usual, non-elevated case), the machine-wide HKLM list
/// (administrator rights, once) when it won't be. An elevated or unvirtualized client never
/// reads the per-user copy (2026-10-03: a player's Decal + RynthCore client never loaded the
/// bridge). <see cref="DecalBridgeCheck"/> verifies the result.
///
/// Per-user. The launcher runs without admin rights, so it can't write Decal's own
/// key (HKLM\SOFTWARE\WOW6432Node\Decal\NetworkFilters). acclient.exe is a legacy 32-bit
/// program that Windows "virtualizes": its reads of that HKLM key are served from the
/// per-user copy under HKCU\Software\Classes\VirtualStore when one exists. Registering
/// there makes every Decal client this user starts load the bridge (it stays idle unless
/// RynthCore is in the same client).
///
/// The trap (measured 2026-09-29): once the per-user NetworkFilters key exists, Decal
/// sees ONLY its entries - HKLM's filters (World Object Filter, Echo Filter, ...) vanish,
/// Decal's WorldFilter is null and VTank refuses to start. So when this class has to
/// create that key, it first mirrors every HKLM filter entry into it, and on each
/// Register call it copies over HKLM entries added since.
///
/// What it adds is recorded in %APPDATA%\RynthCore\decal-bridge-registration.json;
/// Unregister removes exactly that: the bridge's own entry, the mirrored copies nobody has
/// changed since, and the per-user key itself only if this class created it and nothing
/// else is left in it. Register is idempotent.
///
/// Opt-in only: nothing calls Register unless the user picked "Decal + RynthCore" for an
/// account (or ran the injector's --decal-bridge register).
/// </summary>
internal static class DecalBridgeRegistration
{
/// <summary>The bridge's fixed filter id (one entry, whatever the install path).</summary>
public const string FilterGuid = "{5B3E0D57-2C41-4F8A-9D6E-8C1B70DECA11}";
public const string FilterObject = "RynthCore.DecalBridge.BridgeFilter";
public const string AssemblyFile = "RynthCore.DecalBridge.dll";
public const string FilterName = "RynthCore Decal Bridge";
/// <summary>Decal's .NET surrogate, the value every Decal.Adapter filter registers with.</summary>
private const string DotNetSurrogate = "{71A69713-6593-47EC-0002-0000000DECA1}";
private const string DecalFiltersSubKey = @"SOFTWARE\Decal\NetworkFilters"; // seen through the 32-bit view
private const RegistryView MachineView = RegistryView.Registry32; // what the 32-bit client reads
private static string StatePath => Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "RynthCore", "decal-bridge-registration.json");
/// <summary>HKCU path of the per-user copy the virtualized 32-bit client reads.</summary>
public static string VirtualStoreFiltersSubKey => Environment.Is64BitOperatingSystem
? @"Software\Classes\VirtualStore\MACHINE\SOFTWARE\WOW6432Node\Decal\NetworkFilters"
: @"Software\Classes\VirtualStore\MACHINE\SOFTWARE\Decal\NetworkFilters";
/// <summary>The folder the launcher registers: &lt;install&gt;\DecalBridge.</summary>
public static string DefaultBridgeDirectory => Path.Combine(AppContext.BaseDirectory, "DecalBridge");
public sealed class Status
{
public bool DecalInstalled;
public bool PerUserKeyExists;
public bool PerUserKeyCreatedByUs;
public bool RegisteredPerUser;
public bool RegisteredMachineWide;
public bool Enabled;
public bool MachineEnabled;
public string? RegisteredPath;
public bool DllPresent;
/// <summary>A client started by this process gets UAC registry virtualization (reads the per-user copy when it exists).</summary>
public bool ClientVirtualized = true;
public string ClientReason = string.Empty;
/// <summary>HKLM filters a Decal client of this user can't see (hidden by the per-user key).</summary>
public List<string> HiddenMachineFilters = new();
/// <summary>What a Decal client started now will load (see DecalBridgeCheck for the full check).</summary>
public bool EffectiveForClients => ClientVirtualized && PerUserKeyExists
? RegisteredPerUser && Enabled
: RegisteredMachineWide && MachineEnabled;
public override string ToString()
{
var sb = new StringBuilder();
sb.Append($"Decal installed: {DecalInstalled}. ");
sb.Append($"Bridge registered for clients started now: {(EffectiveForClients ? "yes" : "no")}");
if (RegisteredPerUser) sb.Append(" (per-user entry present)");
if (RegisteredMachineWide) sb.Append(" (machine-wide entry present)");
if (RegisteredPath != null) sb.Append($", path {RegisteredPath}{(DllPresent ? "" : " (DLL MISSING)")}");
sb.Append('.');
if (ClientReason.Length > 0) sb.Append($" Client: {ClientReason}.");
if (PerUserKeyExists)
sb.Append($" Per-user filter list: {(PerUserKeyCreatedByUs ? "created by RynthCore" : "existed before RynthCore")}.");
if (HiddenMachineFilters.Count > 0)
sb.Append($" Hidden from Decal clients (in HKLM, not in the per-user list): {string.Join(", ", HiddenMachineFilters)}.");
return sb.ToString();
}
}
private sealed class State
{
public bool CreatedFiltersKey { get; set; }
public string BridgePath { get; set; } = string.Empty;
public DateTime RegisteredUtc { get; set; }
/// <summary>Mirrored HKLM subkey -> fingerprint of the copy as written.</summary>
public Dictionary<string, string> MirroredKeys { get; set; } = new(StringComparer.OrdinalIgnoreCase);
/// <summary>Mirrored values of the NetworkFilters key itself -> fingerprint.</summary>
public Dictionary<string, string> MirroredValues { get; set; } = new(StringComparer.OrdinalIgnoreCase);
}
// ── public API ───────────────────────────────────────────────────────────
public static Status GetStatus(string? acClientPath = null)
{
bool virt = RealDecalCheckHost.PredictClientVirtualized(acClientPath ?? DecalLocator.TryGetDecalAcClientPath(), out string reason, out _);
Status s;
using (RealRegistryView.Enter()) s = GetStatusCore();
s.ClientVirtualized = virt;
s.ClientReason = reason;
return s;
}
private static Status GetStatusCore()
{
var s = new Status { DecalInstalled = DecalLocator.IsInstalled() };
State? state = LoadState();
using RegistryKey? machine = OpenMachineFilters();
using RegistryKey? user = OpenUserFilters(writable: false);
s.PerUserKeyExists = user != null;
s.PerUserKeyCreatedByUs = user != null && state?.CreatedFiltersKey == true;
using (RegistryKey? m = machine?.OpenSubKey(FilterGuid))
{
if (m != null && IsOurs(m))
{
s.RegisteredMachineWide = true;
s.MachineEnabled = Enabled(m);
if (user == null) ReadEntry(m, s);
}
}
using (RegistryKey? u = user?.OpenSubKey(FilterGuid))
{
if (u != null && IsOurs(u))
{
s.RegisteredPerUser = true;
ReadEntry(u, s);
}
}
if (machine != null && user != null)
{
HashSet<string> seen = new(user.GetSubKeyNames(), StringComparer.OrdinalIgnoreCase);
foreach (string name in machine.GetSubKeyNames())
if (!seen.Contains(name))
s.HiddenMachineFilters.Add(DescribeFilter(machine, name));
}
return s;
}
public enum Outcome { Registered, NeedsAdmin, Failed }
/// <summary>
/// Registers the bridge where a Decal client started now reads its filter list, then
/// verifies it with <see cref="DecalBridgeCheck"/> (reading back from that place, and
/// through this process's own view when it is the client's).
/// - Client virtualized (non-elevated AC, the usual case): the per-user VirtualStore copy,
/// as before (no administrator rights needed).
/// - Client not virtualized (RynthCore/AC run as administrator, UAC off, a manifest,
/// virtualization off by policy): Decal reads the real
/// HKLM\SOFTWARE\(WOW6432Node\)Decal\NetworkFilters, where a per-user entry is
/// invisible. Written directly when this process may; otherwise <see cref="Outcome.NeedsAdmin"/>,
/// and the caller runs <c>--decal-bridge-register-machine</c> elevated (<see cref="RunElevated"/>).
/// Idempotent. Also removes a "downloaded from the internet" mark from the bridge DLL.
/// </summary>
public static Outcome RegisterForClients(string bridgeDirectory, string? acClientPath, string? engineJsonPath,
out string report, out DecalBridgeCheck.Result? check)
{
check = null;
var log = new List<string>();
string dir;
try { dir = Path.GetFullPath(bridgeDirectory).TrimEnd('\\'); }
catch (Exception ex) { report = $"Bad bridge folder '{bridgeDirectory}': {ex.Message}"; return Outcome.Failed; }
string dll = Path.Combine(dir, AssemblyFile);
if (File.Exists(dll) && File.Exists(dll + ":Zone.Identifier"))
log.Add(RealDecalCheckHost.RemoveZoneIdentifier(dll)
? "removed the 'downloaded from the internet' mark from the bridge DLL"
: "could not remove the 'downloaded from the internet' mark from the bridge DLL");
bool virtualized = RealDecalCheckHost.PredictClientVirtualized(acClientPath, out string why, out _);
bool ok;
string step;
if (virtualized)
{
ok = RegisterPerUser(dir, out step);
}
else
{
Outcome mw = RegisterMachineWide(dir, out step);
if (mw == Outcome.NeedsAdmin)
{
log.Add($"AC reads Decal's filter list for all users on this PC ({why}); adding the bridge there needs administrator rights once.");
report = string.Join(" ", log);
return Outcome.NeedsAdmin;
}
ok = mw == Outcome.Registered;
step = $"({why}) " + step;
}
log.Add(step);
check = RealDecalCheckHost.Check(dir, acClientPath, engineJsonPath);
log.Add(check.Summary);
report = string.Join(" ", log);
if (!ok) return Outcome.Failed;
if (check.Blocking) return check.NeedsMachineWideRegistration ? Outcome.NeedsAdmin : Outcome.Failed;
return Outcome.Registered;
}
/// <summary>
/// <see cref="RegisterForClients"/> for Decal's own acclient.exe (PortalPath). False (with
/// the reason) when it needs administrator rights or the check fails.
/// </summary>
public static bool Register(string bridgeDirectory, out string report) =>
RegisterForClients(bridgeDirectory, DecalLocator.TryGetDecalAcClientPath(), null, out report, out _) == Outcome.Registered;
/// <summary>
/// Adds the bridge to the machine-wide list, HKLM\SOFTWARE\(WOW6432Node\)Decal\NetworkFilters
/// (32-bit view). Needs administrator rights: run elevated (--decal-bridge-register-machine).
/// Virtualization is off while it writes, so a non-elevated process gets "access denied"
/// (NeedsAdmin) instead of a silent write into the per-user copy. Idempotent; nothing to mirror
/// (the machine list is the one every other filter is in).
/// </summary>
public static Outcome RegisterMachineWide(string bridgeDirectory, out string report)
{
var log = new List<string>();
using (RealRegistryView.Enter())
{
try
{
if (!DecalLocator.IsInstalled())
{
report = "Decal is not installed (HKLM\\SOFTWARE\\Decal\\Agent) - nothing registered.";
return Outcome.Failed;
}
string dir = Path.GetFullPath(bridgeDirectory).TrimEnd('\\');
if (!File.Exists(Path.Combine(dir, AssemblyFile)))
{
report = $"{AssemblyFile} not found in {dir} - nothing registered.";
return Outcome.Failed;
}
using RegistryKey hklm = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, MachineView);
using RegistryKey filters = hklm.CreateSubKey(DecalFiltersSubKey, writable: true);
using (RegistryKey? existing = filters.OpenSubKey(FilterGuid))
{
if (existing != null && !IsOurs(existing))
{
report = $"another filter uses the bridge's id {FilterGuid} in the machine-wide list - nothing changed.";
return Outcome.Failed;
}
}
using (RegistryKey entry = filters.CreateSubKey(FilterGuid, writable: true))
{
SetIfDifferent(entry, "", FilterName, RegistryValueKind.String, log);
SetIfDifferent(entry, "Enabled", 1, RegistryValueKind.DWord, log);
SetIfDifferent(entry, "Assembly", AssemblyFile, RegistryValueKind.String, log);
SetIfDifferent(entry, "Path", dir, RegistryValueKind.String, log);
SetIfDifferent(entry, "Object", FilterObject, RegistryValueKind.String, log);
SetIfDifferent(entry, "Surrogate", DotNetSurrogate, RegistryValueKind.String, log);
}
report = log.Count == 0
? $"Decal bridge already registered for all users ({dir}); nothing changed."
: $"Decal bridge registered for all users ({dir}): {string.Join("; ", log)}.";
return Outcome.Registered;
}
catch (Exception ex) when (ex is UnauthorizedAccessException or System.Security.SecurityException)
{
report = "Registering the Decal bridge for all users needs administrator rights.";
return Outcome.NeedsAdmin;
}
catch (Exception ex)
{
report = $"Decal bridge registration for all users failed: {Describe(ex)}";
return Outcome.Failed;
}
}
}
/// <summary>
/// The installer's per-user half (installer\RynthCore.iss, run as the installing user on
/// every install and update; the elevated half is <see cref="RegisterMachineWide"/>).
/// Writes our entry into this user's VirtualStore copy of Decal's filter list ONLY when
/// that copy already exists - see <see cref="DecalBridgeCheck.PlanInstall"/> for why both
/// places are written and why a missing copy is never created here. The entry is ours
/// (Object = <see cref="FilterObject"/>), so <see cref="Unregister"/> removes it.
/// </summary>
public static bool InstallPerUser(string bridgeDirectory, out string report)
{
try
{
var plan = RealDecalCheckHost.PlanInstall();
if (!plan.Machine)
{
report = "Decal is not installed - nothing to do for this user.";
return true;
}
if (!plan.PerUser)
{
report = "This user has no per-user copy of Decal's filter list - the machine-wide entry is the one AC reads; nothing written.";
return true;
}
string dir = Path.GetFullPath(bridgeDirectory).TrimEnd('\\');
if (!File.Exists(Path.Combine(dir, AssemblyFile)))
{
report = $"{AssemblyFile} not found in {dir} - nothing written.";
return false;
}
var log = new List<string>();
using (RealRegistryView.Enter())
{
using RegistryKey? user = OpenUserFilters(writable: true);
if (user == null)
{
report = "The per-user copy disappeared - nothing written.";
return true;
}
using (RegistryKey? existing = user.OpenSubKey(FilterGuid))
{
if (existing != null && !IsOurs(existing))
{
report = $"another filter uses the bridge's id {FilterGuid} in the per-user copy - nothing changed.";
return false;
}
}
using RegistryKey entry = user.CreateSubKey(FilterGuid, writable: true);
SetIfDifferent(entry, "", FilterName, RegistryValueKind.String, log);
SetIfDifferent(entry, "Enabled", 1, RegistryValueKind.DWord, log);
SetIfDifferent(entry, "Assembly", AssemblyFile, RegistryValueKind.String, log);
SetIfDifferent(entry, "Path", dir, RegistryValueKind.String, log);
SetIfDifferent(entry, "Object", FilterObject, RegistryValueKind.String, log);
SetIfDifferent(entry, "Surrogate", DotNetSurrogate, RegistryValueKind.String, log);
}
report = log.Count == 0
? $"Decal bridge already in this user's per-user copy ({dir}); nothing changed."
: $"Decal bridge added to this user's existing per-user copy ({dir}): {string.Join("; ", log)}.";
return true;
}
catch (Exception ex)
{
report = $"Per-user Decal bridge entry failed: {Describe(ex)}";
return false;
}
}
/// <summary>The machine-wide list holds our entry (the launcher/injector never adds it without being asked).</summary>
public static bool MachineEntryIsOurs()
{
using (RealRegistryView.Enter())
{
try
{
using RegistryKey? machine = OpenMachineFilters();
using RegistryKey? m = machine?.OpenSubKey(FilterGuid);
return m != null && IsOurs(m);
}
catch { return false; }
}
}
/// <summary>Removes our machine-wide entry (only ours). Needs administrator rights.</summary>
public static Outcome UnregisterMachineWide(out string report)
{
using (RealRegistryView.Enter())
{
try
{
using RegistryKey hklm = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, MachineView);
using RegistryKey? probe = hklm.OpenSubKey(DecalFiltersSubKey);
using RegistryKey? m = probe?.OpenSubKey(FilterGuid);
if (m == null || !IsOurs(m))
{
report = "No machine-wide Decal bridge entry; nothing to remove.";
return Outcome.Registered;
}
using RegistryKey filters = hklm.OpenSubKey(DecalFiltersSubKey, writable: true)!;
filters.DeleteSubKeyTree(FilterGuid, throwOnMissingSubKey: false);
report = "Removed the machine-wide Decal bridge entry.";
return Outcome.Registered;
}
catch (Exception ex) when (ex is UnauthorizedAccessException or System.Security.SecurityException)
{
report = "Removing the machine-wide Decal bridge entry needs administrator rights.";
return Outcome.NeedsAdmin;
}
catch (Exception ex)
{
report = $"Removing the machine-wide Decal bridge entry failed: {Describe(ex)}";
return Outcome.Failed;
}
}
}
/// <summary>
/// Runs <paramref name="exePath"/> elevated (Windows shows its administrator prompt) and
/// waits for it. NeedsAdmin when the person said no at the prompt.
/// </summary>
public static Outcome RunElevated(string exePath, string arguments, out string report)
{
try
{
var psi = new System.Diagnostics.ProcessStartInfo(exePath, arguments)
{
UseShellExecute = true,
Verb = "runas",
WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden,
};
using System.Diagnostics.Process? p = System.Diagnostics.Process.Start(psi);
if (p == null)
{
report = "Windows did not start the administrator step.";
return Outcome.Failed;
}
if (!p.WaitForExit(120_000))
{
report = "The administrator step did not finish within 2 minutes.";
return Outcome.Failed;
}
report = p.ExitCode == 0 ? "The administrator step finished." : $"The administrator step failed (exit code {p.ExitCode}).";
return p.ExitCode == 0 ? Outcome.Registered : Outcome.Failed;
}
catch (System.ComponentModel.Win32Exception ex) when (ex.NativeErrorCode == 1223)
{
report = "Cancelled at the Windows administrator prompt.";
return Outcome.NeedsAdmin;
}
catch (Exception ex)
{
report = $"Could not start the administrator step: {ex.Message}";
return Outcome.Failed;
}
}
/// <summary>
/// Makes Decal clients of this user load the bridge from <paramref name="bridgeDirectory"/>
/// through the per-user VirtualStore copy (virtualized clients only: see
/// <see cref="RegisterForClients"/>). Idempotent. Returns false (with the reason in
/// <paramref name="report"/>) when Decal isn't installed or the bridge DLL isn't there.
/// </summary>
public static bool RegisterPerUser(string bridgeDirectory, out string report)
{
using (RealRegistryView.Enter()) return RegisterCore(bridgeDirectory, out report);
}
private static bool RegisterCore(string bridgeDirectory, out string report)
{
var log = new List<string>();
try
{
if (!DecalLocator.IsInstalled())
{
report = "Decal is not installed (HKLM\\SOFTWARE\\Decal\\Agent) - nothing registered.";
return false;
}
string dir = Path.GetFullPath(bridgeDirectory).TrimEnd('\\');
if (!File.Exists(Path.Combine(dir, AssemblyFile)))
{
report = $"{AssemblyFile} not found in {dir} - nothing registered.";
return false;
}
State state = LoadState() ?? new State();
using RegistryKey? machine = OpenMachineFilters();
using RegistryKey? existingUser = OpenUserFilters(writable: true);
if (existingUser == null && state.CreatedFiltersKey)
{
// Someone removed the key we created; start the record over.
state = new State();
}
RegistryKey? user = existingUser;
try
{
if (user == null)
{
// No per-user list yet. If an administrator already registered the bridge in
// HKLM with this path, clients see it without us creating anything.
using (RegistryKey? m = machine?.OpenSubKey(FilterGuid))
{
if (m != null && IsOurs(m) && Enabled(m) &&
string.Equals((m.GetValue("Path") as string)?.TrimEnd('\\'), dir, StringComparison.OrdinalIgnoreCase))
{
report = "Already registered machine-wide (HKLM) with this path; nothing changed.";
return true;
}
}
user = UserHive().CreateSubKey(VirtualStoreFiltersSubKey, writable: true);
state.CreatedFiltersKey = true;
log.Add($"created HKCU\\{VirtualStoreFiltersSubKey}");
}
if (state.CreatedFiltersKey && machine != null)
SyncMirror(machine, user, state, log);
using (RegistryKey entry = user.CreateSubKey(FilterGuid, writable: true))
{
SetIfDifferent(entry, "", FilterName, RegistryValueKind.String, log);
SetIfDifferent(entry, "Enabled", 1, RegistryValueKind.DWord, log);
SetIfDifferent(entry, "Assembly", AssemblyFile, RegistryValueKind.String, log);
SetIfDifferent(entry, "Path", dir, RegistryValueKind.String, log);
SetIfDifferent(entry, "Object", FilterObject, RegistryValueKind.String, log);
SetIfDifferent(entry, "Surrogate", DotNetSurrogate, RegistryValueKind.String, log);
}
}
finally
{
if (!ReferenceEquals(user, existingUser)) user?.Dispose();
}
state.BridgePath = dir;
state.RegisteredUtc = DateTime.UtcNow;
SaveState(state);
report = log.Count == 0
? $"Decal bridge already registered for this user ({dir}); nothing changed."
: $"Decal bridge registered for this user ({dir}): {string.Join("; ", log)}.";
return true;
}
catch (Exception ex)
{
report = $"Decal bridge registration failed: {ex.GetType().Name}: {ex.Message}" +
(log.Count > 0 ? $" (done before the failure: {string.Join("; ", log)})" : "");
return false;
}
}
/// <summary>
/// Removes what <see cref="Register"/> added: the bridge's entry, the mirrored copies of
/// HKLM filters, and the per-user key if this class created it and nothing foreign is
/// left in it. A mirrored copy that changed since (Decal plugins write to "HKLM" through
/// UAC virtualization, so their writes land in our per-user copy) is removed as well when
/// RynthCore created the key: HKLM still holds the original, and a per-user list left with
/// a few entries would hide every other HKLM filter from Decal clients (VTank then has no
/// WorldFilter). Anything RynthCore didn't add is left in place and reported, and the
/// record (%APPDATA%\RynthCore\decal-bridge-registration.json) is kept until nothing of
/// ours remains, so a later unregister can finish the job.
/// </summary>
public static bool Unregister(out string report)
{
using (RealRegistryView.Enter()) return UnregisterCore(out report);
}
private static bool UnregisterCore(out string report)
{
var log = new List<string>();
var failed = new List<string>();
try
{
State? state = LoadState();
bool done = true;
using RegistryKey? user = OpenUserFilters(writable: true);
if (user != null)
{
foreach (string name in user.GetSubKeyNames())
{
try
{
bool ours;
using (RegistryKey? k = user.OpenSubKey(name))
ours = k != null && IsOurs(k);
if (!ours) continue;
user.DeleteSubKeyTree(name, throwOnMissingSubKey: false);
log.Add($"removed bridge entry {name}");
}
catch (Exception ex) { failed.Add($"{name}: {Describe(ex)}"); }
}
if (state?.CreatedFiltersKey == true)
{
int same = 0, changed = 0;
foreach (KeyValuePair<string, string> kv in state.MirroredKeys)
{
try
{
bool unchanged;
using (RegistryKey? k = user.OpenSubKey(kv.Key))
{
if (k == null) continue;
unchanged = Fingerprint(k) == kv.Value;
}
user.DeleteSubKeyTree(kv.Key, throwOnMissingSubKey: false);
if (unchanged) same++; else changed++;
}
catch (Exception ex) { failed.Add($"{kv.Key}: {Describe(ex)}"); }
}
foreach (KeyValuePair<string, string> kv in state.MirroredValues)
{
try { user.DeleteValue(kv.Key, throwOnMissingValue: false); }
catch (Exception ex) { failed.Add($"value {kv.Key}: {Describe(ex)}"); }
}
log.Add($"removed {same + changed} mirrored filter entr{(same + changed == 1 ? "y" : "ies")}" +
(changed > 0 ? $" ({changed} changed by Decal plugins since; HKLM keeps the originals)" : ""));
var foreign = new List<string>();
foreach (string n in user.GetSubKeyNames()) foreign.Add(n);
foreach (string n in user.GetValueNames()) if (n.Length > 0) foreign.Add(n);
if (foreign.Count == 0 && failed.Count == 0)
{
user.Dispose();
UserHive().DeleteSubKey(VirtualStoreFiltersSubKey, throwOnMissingSubKey: false);
log.Add($"removed HKCU\\{VirtualStoreFiltersSubKey} (created by RynthCore)");
}
else
{
done = false;
log.Add($"left HKCU\\{VirtualStoreFiltersSubKey} in place" +
(foreign.Count > 0 ? $": it holds entries RynthCore didn't add ({string.Join(", ", foreign)})" : ""));
}
}
}
if (failed.Count > 0)
done = false;
if (done && File.Exists(StatePath))
File.Delete(StatePath);
else if (!done)
log.Add($"kept {StatePath} for the next unregister");
if (failed.Count > 0)
{
report = $"Decal bridge unregistration incomplete: {string.Join("; ", failed)}" +
(log.Count > 0 ? $" (done: {string.Join("; ", log)})" : "");
return false;
}
report = log.Count == 0 ? "Decal bridge was not registered for this user; nothing to remove." : string.Join("; ", log) + ".";
return true;
}
catch (Exception ex)
{
report = $"Decal bridge unregistration failed: {Describe(ex)}" +
(log.Count > 0 ? $" (done before the failure: {string.Join("; ", log)})" : "");
return false;
}
}
// Exception type, message and the innermost frame, for a one-line report.
private static string Describe(Exception ex)
{
string? frame = ex.StackTrace?.Split('\n').Select(l => l.Trim()).FirstOrDefault(l => l.Length > 0);
return $"{ex.GetType().Name}: {ex.Message}" + (frame != null ? $" [{frame}]" : "");
}
// ── mirror ───────────────────────────────────────────────────────────────
// Copies HKLM entries the per-user list lacks, and refreshes copies nobody changed
// since we wrote them (so a filter the user enables/disables machine-wide follows).
private static void SyncMirror(RegistryKey machine, RegistryKey user, State state, List<string> log)
{
int added = 0, refreshed = 0;
foreach (string name in machine.GetValueNames())
{
if (name.Length == 0) continue;
object? v = machine.GetValue(name, null, RegistryValueOptions.DoNotExpandEnvironmentNames);
if (v == null) continue;
RegistryValueKind kind = machine.GetValueKind(name);
object? have = user.GetValue(name, null, RegistryValueOptions.DoNotExpandEnvironmentNames);
bool ours = state.MirroredValues.TryGetValue(name, out string? print);
if (have == null || (ours && ValuePrint(user.GetValueKind(name), have) == print))
{
user.SetValue(name, v, kind);
state.MirroredValues[name] = ValuePrint(kind, v);
}
}
foreach (string name in machine.GetSubKeyNames())
{
if (string.Equals(name, FilterGuid, StringComparison.OrdinalIgnoreCase)) continue;
using RegistryKey? src = machine.OpenSubKey(name);
if (src == null) continue;
string srcPrint = Fingerprint(src);
using RegistryKey? existing = user.OpenSubKey(name);
if (existing == null)
{
using RegistryKey dst = user.CreateSubKey(name, writable: true);
CopyTree(src, dst);
state.MirroredKeys[name] = Fingerprint(dst);
added++;
}
else if (state.MirroredKeys.TryGetValue(name, out string? written) &&
Fingerprint(existing) == written && srcPrint != written)
{
existing.Dispose();
user.DeleteSubKeyTree(name, throwOnMissingSubKey: false);
using RegistryKey dst = user.CreateSubKey(name, writable: true);
CopyTree(src, dst);
state.MirroredKeys[name] = Fingerprint(dst);
refreshed++;
}
}
if (added > 0) log.Add($"mirrored {added} HKLM filter entr{(added == 1 ? "y" : "ies")} (so Decal still sees them)");
if (refreshed > 0) log.Add($"refreshed {refreshed} mirrored entr{(refreshed == 1 ? "y" : "ies")} from HKLM");
}
private static void CopyTree(RegistryKey src, RegistryKey dst)
{
foreach (string name in src.GetValueNames())
{
object? v = src.GetValue(name, null, RegistryValueOptions.DoNotExpandEnvironmentNames);
if (v != null) dst.SetValue(name, v, src.GetValueKind(name));
}
foreach (string sub in src.GetSubKeyNames())
{
using RegistryKey? s = src.OpenSubKey(sub);
if (s == null) continue;
using RegistryKey d = dst.CreateSubKey(sub, writable: true);
CopyTree(s, d);
}
}
/// <summary>A stable text form of a key's values and subkeys, to tell "still as we wrote it".</summary>
private static string Fingerprint(RegistryKey key)
{
var sb = new StringBuilder();
foreach (string name in key.GetValueNames().OrderBy(n => n, StringComparer.OrdinalIgnoreCase))
{
object? v = key.GetValue(name, null, RegistryValueOptions.DoNotExpandEnvironmentNames);
if (v == null) continue;
RegistryValueKind kind;
try { kind = key.GetValueKind(name); }
catch (IOException) { continue; } // removed between the listing and the read
sb.Append(name.ToLowerInvariant()).Append('=').Append(ValuePrint(kind, v)).Append(';');
}
foreach (string sub in key.GetSubKeyNames().OrderBy(n => n, StringComparer.OrdinalIgnoreCase))
{
using RegistryKey? s = key.OpenSubKey(sub);
if (s != null) sb.Append('[').Append(sub.ToLowerInvariant()).Append(':').Append(Fingerprint(s)).Append(']');
}
return sb.ToString();
}
private static string ValuePrint(RegistryValueKind kind, object v) => kind + ":" + v switch
{
byte[] b => Convert.ToHexString(b),
string[] a => string.Join("\u0001", a),
_ => Convert.ToString(v, System.Globalization.CultureInfo.InvariantCulture) ?? string.Empty,
};
// ── registry helpers ─────────────────────────────────────────────────────
private static RegistryKey UserHive() => RegistryKey.OpenBaseKey(RegistryHive.CurrentUser,
Environment.Is64BitOperatingSystem ? RegistryView.Registry64 : RegistryView.Default);
private static RegistryKey? OpenUserFilters(bool writable) => UserHive().OpenSubKey(VirtualStoreFiltersSubKey, writable);
private static RegistryKey? OpenMachineFilters() =>
RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, MachineView).OpenSubKey(DecalFiltersSubKey);
private static bool IsOurs(RegistryKey k) =>
string.Equals(k.GetValue("Object") as string, FilterObject, StringComparison.Ordinal);
private static bool Enabled(RegistryKey k) => k.GetValue("Enabled") is int e && e != 0;
private static void ReadEntry(RegistryKey k, Status s)
{
s.Enabled = Enabled(k);
s.RegisteredPath = k.GetValue("Path") as string;
s.DllPresent = s.RegisteredPath != null && File.Exists(Path.Combine(s.RegisteredPath, AssemblyFile));
}
private static string DescribeFilter(RegistryKey parent, string name)
{
using RegistryKey? k = parent.OpenSubKey(name);
return k?.GetValue("") is string friendly && friendly.Length > 0 ? friendly : name;
}
private static void SetIfDifferent(RegistryKey key, string name, object value, RegistryValueKind kind, List<string> log)
{
object? have = key.GetValue(name, null, RegistryValueOptions.DoNotExpandEnvironmentNames);
if (have != null && key.GetValueKind(name) == kind && Equals(have, value))
return;
key.SetValue(name, value, kind);
log.Add($"set {(name.Length == 0 ? "(default)" : name)}");
}
private static State? LoadState()
{
try
{
if (!File.Exists(StatePath)) return null;
State? s = JsonSerializer.Deserialize<State>(File.ReadAllText(StatePath));
if (s == null) return null;
// Dictionary comparers don't survive serialization.
s.MirroredKeys = new Dictionary<string, string>(s.MirroredKeys, StringComparer.OrdinalIgnoreCase);
s.MirroredValues = new Dictionary<string, string>(s.MirroredValues, StringComparer.OrdinalIgnoreCase);
return s;
}
catch
{
return null;
}
}
private static void SaveState(State s)
{
string? dir = Path.GetDirectoryName(StatePath);
if (dir != null) Directory.CreateDirectory(dir);
File.WriteAllText(StatePath, JsonSerializer.Serialize(s, new JsonSerializerOptions { WriteIndented = true }));
}
}

View file

@ -14,4 +14,10 @@ internal enum InjectionMode
/// account runs against Decal + UBService + VTank or whatever Decal plugins
/// the user has registered.</summary>
Decal = 1,
/// <summary>Decal first, then RynthCore in the same client ("Decal + RynthCore"). The
/// engine takes chat from Decal through the RynthCore Decal bridge, which the launcher
/// registers for this Windows user before the launch (DecalBridgeRegistration;
/// docs/DECAL_BRIDGE_PLAN.md).</summary>
DecalBridge = 2,
}

View file

@ -0,0 +1,274 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using System.Reflection.Metadata;
using System.Reflection.PortableExecutable;
using System.Runtime.InteropServices;
using System.Text;
using Microsoft.Win32;
namespace RynthCore.App;
/// <summary>A registry key copied into memory (also the tests' fake key).</summary>
internal sealed class RegSnapshot : IRegKey
{
public Dictionary<string, object> Values { get; } = new(StringComparer.OrdinalIgnoreCase);
public List<string> SubKeys { get; } = new();
public object? GetValue(string name) => Values.TryGetValue(name, out object? v) ? v : null;
public string[] GetSubKeyNames() => SubKeys.ToArray();
public string[] GetValueNames() => new List<string>(Values.Keys).ToArray();
public void Dispose() { }
public static RegSnapshot? Of(RegistryKey? key)
{
if (key == null) return null;
var s = new RegSnapshot();
foreach (string n in key.GetValueNames())
{
object? v = key.GetValue(n, null, RegistryValueOptions.DoNotExpandEnvironmentNames);
if (v != null) s.Values[n] = v;
}
s.SubKeys.AddRange(key.GetSubKeyNames());
return s;
}
}
/// <summary>The real machine for <see cref="DecalBridgeCheck"/>.</summary>
internal sealed class RealDecalCheckHost : IDecalCheckHost
{
private const int TokenElevation = 20, TokenVirtualizationEnabled = 24;
private static readonly string BridgeEntryMachinePath =
DecalBridgeCheck.MachineDecalPath("NetworkFilters") + "\\" + DecalBridgeRegistration.FilterGuid;
private readonly RegSnapshot? _ownViewBridgeEntry;
private readonly Dictionary<string, string?> _levels = new(StringComparer.OrdinalIgnoreCase);
public bool Is64BitOs => Environment.Is64BitOperatingSystem;
public bool LauncherElevated { get; }
public bool LauncherVirtualized { get; }
/// <summary>Construct OUTSIDE a <see cref="RealRegistryView"/> scope: it reads the process's own view.</summary>
private RealDecalCheckHost()
{
LauncherElevated = TokenFlag(TokenElevation);
LauncherVirtualized = TokenFlag(TokenVirtualizationEnabled);
try
{
using RegistryKey hklm = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, Is64BitOs ? RegistryView.Registry32 : RegistryView.Default);
using RegistryKey? k = hklm.OpenSubKey(BridgeEntryMachinePath);
_ownViewBridgeEntry = RegSnapshot.Of(k);
}
catch { _ownViewBridgeEntry = null; }
}
/// <summary>Runs the check against this machine. Reads only.</summary>
public static DecalBridgeCheck.Result Check(string bridgeDirectory, string? acClientPath, string? engineJsonPath)
{
var host = new RealDecalCheckHost();
using (RealRegistryView.Enter())
return DecalBridgeCheck.Run(host, bridgeDirectory, acClientPath, engineJsonPath);
}
/// <summary>Only the client-virtualization prediction (registration uses it to pick the key).</summary>
public static bool PredictClientVirtualized(string? acClientPath, out string reason, out bool launcherElevated)
{
var host = new RealDecalCheckHost();
launcherElevated = host.LauncherElevated;
using (RealRegistryView.Enter())
return DecalBridgeCheck.PredictClientVirtualized(host, acClientPath, out reason);
}
public static bool IsProcessElevated() => TokenFlag(TokenElevation);
/// <summary><see cref="DecalBridgeCheck.PlanInstall"/> on this machine.</summary>
public static (bool Machine, bool PerUser) PlanInstall()
{
var host = new RealDecalCheckHost();
using (RealRegistryView.Enter())
return DecalBridgeCheck.PlanInstall(host);
}
public IRegKey? OpenReal(RegRoot root, string subKey)
{
try
{
(RegistryHive hive, RegistryView view) = root switch
{
RegRoot.Machine32 => (RegistryHive.LocalMachine, Is64BitOs ? RegistryView.Registry32 : RegistryView.Default),
RegRoot.Machine64 => (RegistryHive.LocalMachine, Is64BitOs ? RegistryView.Registry64 : RegistryView.Default),
RegRoot.User32 => (RegistryHive.CurrentUser, Is64BitOs ? RegistryView.Registry32 : RegistryView.Default),
_ => (RegistryHive.CurrentUser, Is64BitOs ? RegistryView.Registry64 : RegistryView.Default),
};
using RegistryKey baseKey = RegistryKey.OpenBaseKey(hive, view);
using RegistryKey? k = baseKey.OpenSubKey(subKey);
return RegSnapshot.Of(k);
}
catch
{
return null;
}
}
public IRegKey? OpenOwnViewMachine32(string subKey) =>
string.Equals(subKey, BridgeEntryMachinePath, StringComparison.OrdinalIgnoreCase) ? _ownViewBridgeEntry : null;
public bool FileExists(string path)
{
try { return File.Exists(path); } catch { return false; }
}
public bool HasZoneIdentifier(string path)
{
try { return File.Exists(path + ":Zone.Identifier"); } catch { return false; }
}
/// <summary>Removes the "downloaded from the internet" mark. True if none is left.</summary>
public static bool RemoveZoneIdentifier(string path)
{
try
{
string ads = path + ":Zone.Identifier";
if (File.Exists(ads)) File.Delete(ads);
return !File.Exists(ads);
}
catch { return false; }
}
public Version? AssemblyVersionOf(string path)
{
try { return AssemblyName.GetAssemblyName(path).Version; } catch { return null; }
}
public Version? ReferenceVersionOf(string assemblyPath, string referenceName)
{
try
{
using FileStream fs = File.OpenRead(assemblyPath);
using var pe = new PEReader(fs);
if (!pe.HasMetadata) return null;
MetadataReader md = pe.GetMetadataReader();
foreach (AssemblyReferenceHandle h in md.AssemblyReferences)
{
AssemblyReference r = md.GetAssemblyReference(h);
if (string.Equals(md.GetString(r.Name), referenceName, StringComparison.OrdinalIgnoreCase))
return r.Version;
}
}
catch { }
return null;
}
public string? ExecutionLevelOf(string exePath)
{
if (_levels.TryGetValue(exePath, out string? cached)) return cached;
string? level = null;
try
{
if (File.Exists(exePath))
level = LevelIn(Encoding.UTF8.GetString(File.ReadAllBytes(exePath)));
// An external manifest counts only when the exe has none embedded.
if (level == null && File.Exists(exePath + ".manifest"))
level = LevelIn(File.ReadAllText(exePath + ".manifest"));
}
catch { }
_levels[exePath] = level;
return level;
}
/// <summary>The level="..." of a requestedExecutionLevel element, or null.</summary>
internal static string? LevelIn(string text)
{
int i = text.IndexOf("requestedExecutionLevel", StringComparison.Ordinal);
if (i < 0) return null;
int end = text.IndexOf('>', i);
string element = end > i ? text.Substring(i, end - i) : text.Substring(i, Math.Min(200, text.Length - i));
int l = element.IndexOf("level=", StringComparison.Ordinal);
if (l < 0) return null;
int q = l + 6;
if (q >= element.Length) return null;
char quote = element[q];
int close = element.IndexOf(quote, q + 1);
return close > q ? element.Substring(q + 1, close - q - 1) : null;
}
public string? ReadTextFile(string path)
{
try { return File.Exists(path) ? File.ReadAllText(path) : null; } catch { return null; }
}
private static bool TokenFlag(int infoClass)
{
try
{
if (!OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, out IntPtr token)) return false;
try
{
int v = 0;
return GetTokenInformation(token, infoClass, ref v, sizeof(int), out _) && v != 0;
}
finally { CloseHandle(token); }
}
catch { return false; }
}
private const uint TOKEN_QUERY = 0x0008;
[DllImport("kernel32.dll")] private static extern IntPtr GetCurrentProcess();
[DllImport("kernel32.dll")] private static extern bool CloseHandle(IntPtr handle);
[DllImport("advapi32.dll", SetLastError = true)] private static extern bool OpenProcessToken(IntPtr process, uint access, out IntPtr token);
[DllImport("advapi32.dll", SetLastError = true)] private static extern bool GetTokenInformation(IntPtr token, int infoClass, ref int info, int length, out int returned);
}
/// <summary>
/// The launcher has no requestedExecutionLevel in its manifest, so Windows runs it with UAC
/// registry virtualization: its HKLM reads return the per-user VirtualStore copy where one
/// exists, and its HKLM writes land there silently (measured 2026-09-30). Registration and
/// the check have to see (and write) the real HKLM and the real per-user copy, so
/// virtualization is switched off for this process while they run and switched back on
/// after. A process without virtualization (the injector, an elevated launcher) is left alone.
/// </summary>
internal sealed class RealRegistryView : IDisposable
{
private const int TokenVirtualizationEnabled = 24;
private const uint TOKEN_QUERY = 0x0008, TOKEN_ADJUST_DEFAULT = 0x0080;
private IntPtr _token;
public static IDisposable Enter()
{
var scope = new RealRegistryView();
try
{
if (!OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY | TOKEN_ADJUST_DEFAULT, out IntPtr token))
return scope;
int on = 0;
if (GetTokenInformation(token, TokenVirtualizationEnabled, ref on, sizeof(int), out _) && on != 0)
{
int off = 0;
if (SetTokenInformation(token, TokenVirtualizationEnabled, ref off, sizeof(int)))
{
scope._token = token; // restored in Dispose
return scope;
}
}
CloseHandle(token);
}
catch { }
return scope;
}
public void Dispose()
{
if (_token == IntPtr.Zero) return;
int on = 1;
SetTokenInformation(_token, TokenVirtualizationEnabled, ref on, sizeof(int));
CloseHandle(_token);
_token = IntPtr.Zero;
}
[DllImport("kernel32.dll")] private static extern IntPtr GetCurrentProcess();
[DllImport("kernel32.dll")] private static extern bool CloseHandle(IntPtr handle);
[DllImport("advapi32.dll", SetLastError = true)] private static extern bool OpenProcessToken(IntPtr process, uint access, out IntPtr token);
[DllImport("advapi32.dll", SetLastError = true)] private static extern bool GetTokenInformation(IntPtr token, int infoClass, ref int info, int length, out int returned);
[DllImport("advapi32.dll", SetLastError = true)] private static extern bool SetTokenInformation(IntPtr token, int infoClass, ref int info, int length);
}