using System.Text.Json; using System.Text.Json.Nodes; using System.Text.Json.Serialization; using RynthCore.App; namespace LauncherSettingsTests; /// /// The launcher's shared settings with "Decal + RynthCore" accounts, in a temp folder. /// "Old launcher" = a launcher released before the Decal bridge: its InjectionMode has only /// RynthCore and Decal, read with JsonStringEnumConverter, so "DecalBridge" makes the whole /// appsettings.json unreadable for it. /// internal static class Program { private static int _checks, _failed; private static string _dir = ""; private static string Main_ => Path.Combine(_dir, "appsettings.json"); private static string Bak => Main_ + ".bak"; private static string Sidecar => Path.Combine(_dir, DecalAccountModes.FileName); private static int Main() { string root = Path.Combine(Path.GetTempPath(), "rc-launcher-settings-tests-" + Guid.NewGuid().ToString("N")); try { Scenario("negative control: the old launcher can't read DecalBridge", root, () => { File.WriteAllText(Main_, """{ "AccountProfiles": [ { "Id": "b", "InjectionMode": "DecalBridge" } ] }"""); Check(!OldLauncherCanRead(Main_), "old reader rejects \"DecalBridge\" (so the checks below mean something)"); }); Scenario("save and load", root, () => { AppSettings s = Sample(); AppSettingsStore.Save(s); AppSettingsStore.Save(s); // second save: a .bak exists too CheckSharedFilesSafe(); Check(SharedMode("a") == "RynthCore", "a is RynthCore in appsettings.json"); Check(SharedMode("b") == "RynthCore", "b (Decal + RynthCore) is written as RynthCore"); Check(SharedMode("c") == "Decal", "c is Decal in appsettings.json"); Check(SidecarIds().SequenceEqual(new[] { "b" }), "decal-accounts.json lists only b"); Check(s.AccountProfiles[1].InjectionMode == InjectionMode.DecalBridge, "save leaves the in-memory mode alone"); AppSettings loaded = AppSettingsStore.Load(); Check(Mode(loaded, "a") == InjectionMode.RynthCore, "load: a RynthCore"); Check(Mode(loaded, "b") == InjectionMode.DecalBridge, "load: b Decal + RynthCore"); Check(Mode(loaded, "c") == InjectionMode.Decal, "load: c Decal"); Check(AppSettingsStore.LastLoadDiagnostic == null && AppSettingsStore.LastMigrationNote == null, "load: no diagnostics"); }); Scenario("switch back to RynthCore", root, () => { AppSettings s = Sample(); AppSettingsStore.Save(s); s.AccountProfiles[1].InjectionMode = InjectionMode.RynthCore; AppSettingsStore.Save(s); Check(!File.Exists(Sidecar), "decal-accounts.json removed when no account uses the mode"); Check(Mode(AppSettingsStore.Load(), "b") == InjectionMode.RynthCore, "load: b RynthCore"); }); Scenario("migrate a file written by a pre-release bridge build", root, () => { string legacy = """ { "EnginePath": "X", "AccountProfiles": [ { "Id": "a", "AccountName": "A", "InjectionMode": "RynthCore" }, { "Id": "b", "AccountName": "B", "InjectionMode": "DecalBridge" }, { "Id": "d", "AccountName": "D", "InjectionMode": 2 } ] } """; File.WriteAllText(Main_, legacy); File.WriteAllText(Bak, legacy); AppSettings loaded = AppSettingsStore.Load(); Check(Mode(loaded, "b") == InjectionMode.DecalBridge, "b kept as Decal + RynthCore"); Check(Mode(loaded, "d") == InjectionMode.DecalBridge, "d (numeric 2) kept as Decal + RynthCore"); Check(loaded.EnginePath == "X", "other settings kept"); Check(AppSettingsStore.LastMigrationNote?.Contains("Moved 2") == true, "migration note: " + AppSettingsStore.LastMigrationNote); CheckSharedFilesSafe(); Check(SidecarIds().SequenceEqual(new[] { "b", "d" }), "decal-accounts.json lists b and d"); AppSettingsStore.Load(); Check(AppSettingsStore.LastMigrationNote == null, "second load: nothing left to migrate"); }); Scenario("an old launcher switches the account to Decal", root, () => { AppSettingsStore.Save(Sample()); OldLauncherEdit(accounts => SetMode(accounts, "b", "Decal")); AppSettings loaded = AppSettingsStore.Load(); Check(Mode(loaded, "b") == InjectionMode.Decal, "the old launcher's choice wins"); AppSettingsStore.Save(loaded); Check(!File.Exists(Sidecar), "the stale entry is dropped at the next save"); }); Scenario("an old launcher deletes the account", root, () => { AppSettingsStore.Save(Sample()); OldLauncherEdit(accounts => { for (int i = accounts.Count - 1; i >= 0; i--) if ((string?)accounts[i]!["Id"] == "b") accounts.RemoveAt(i); }); AppSettings loaded = AppSettingsStore.Load(); Check(loaded.AccountProfiles.All(a => a.Id != "b"), "b is gone"); AppSettingsStore.Save(loaded); Check(!File.Exists(Sidecar), "its entry is dropped at the next save"); }); Scenario("an old launcher saves without changes", root, () => { AppSettingsStore.Save(Sample()); OldLauncherEdit(_ => { }); Check(Mode(AppSettingsStore.Load(), "b") == InjectionMode.DecalBridge, "b is still Decal + RynthCore"); }); Scenario("unreadable decal-accounts.json", root, () => { AppSettingsStore.Save(Sample()); File.WriteAllText(Sidecar, "{ not json"); AppSettings loaded = AppSettingsStore.Load(); Check(Mode(loaded, "b") == InjectionMode.RynthCore, "b runs as RynthCore"); Check(Mode(loaded, "c") == InjectionMode.Decal, "other accounts unchanged"); Check(AppSettingsStore.LastLoadDiagnostic == null, "appsettings.json not taken for corrupt"); Check(AppSettingsStore.LastMigrationNote?.Contains("could not be read") == true, "note: " + AppSettingsStore.LastMigrationNote); loaded.AccountProfiles.First(a => a.Id == "b").InjectionMode = InjectionMode.DecalBridge; AppSettingsStore.Save(loaded); Check(SidecarIds().SequenceEqual(new[] { "b" }), "picking the mode again rewrites the file"); }); Scenario("a mode name this build doesn't know", root, () => { File.WriteAllText(Main_, """{ "EnginePath": "Y", "AccountProfiles": [ { "Id": "z", "InjectionMode": "SomethingNew" }, { "Id": "y", "InjectionMode": 9 } ] }"""); AppSettings loaded = AppSettingsStore.Load(); Check(AppSettingsStore.LastLoadDiagnostic == null && loaded.EnginePath == "Y", "file still loads (not quarantined)"); Check(Mode(loaded, "z") == InjectionMode.RynthCore && Mode(loaded, "y") == InjectionMode.RynthCore, "unknown modes read as RynthCore"); }); Scenario("unchanged list: decal-accounts.json is not rewritten", root, () => { AppSettings s = Sample(); AppSettingsStore.Save(s); DateTime old = new(2020, 1, 1, 0, 0, 0, DateTimeKind.Utc); File.SetLastWriteTimeUtc(Sidecar, old); AppSettingsStore.Save(s); Check(File.GetLastWriteTimeUtc(Sidecar) == old, "no rewrite when nothing changed"); s.AccountProfiles[0].InjectionMode = InjectionMode.DecalBridge; AppSettingsStore.Save(s); Check(SidecarIds().SequenceEqual(new[] { "a", "b" }), "rewritten when the list changed"); CheckSharedFilesSafe(); }); // ── saved account passwords (DPAPI) ───────────────────────────────── // Test-only passwords; nothing here touches the real settings file. const string Pw = "t3st pw \"quoted\" ü"; const string Pw2 = "Second-Test-Pw"; Scenario("password round trip", root, () => { AppSettings s = Sample(); s.AccountProfiles[0].SetPassword(Pw); AppSettingsStore.Save(s); AppSettingsStore.Save(s); // .bak too CheckNoPlainText(Pw); CheckNoPlainText("t3st pw"); Check(!RawAccount("a").ContainsKey("Password"), "no plain \"Password\" field written"); Check(!string.IsNullOrEmpty((string?)RawAccount("a")["PasswordProtected"]), "PasswordProtected written"); Check(OldLauncherCanRead(Main_), "the old launcher can still read the file"); AppSettings loaded = AppSettingsStore.Load(); LaunchAccountProfile a = loaded.AccountProfiles.First(x => x.Id == "a"); Check(a.TryGetPasswordForLaunch(out string got, out _) && got == Pw, "decrypts to the saved password"); Check(!a.PasswordNeedsReentry && a.HasSavedPassword, "saved, readable"); Check(AppSettingsStore.LastPasswordMigrationNote == null && AppSettingsStore.LastPasswordProblemNote == null, "no password notes"); var builder = new AcLaunchArgumentBuilder(); LaunchServerProfile ace = Server(AcEmulatorKind.Ace), gdle = Server(AcEmulatorKind.Gdle); // Read back the way acclient reads its command line (AcClientCommandLine.Split): the password // as typed, less its quote marks (the client can't receive one), and the host after it intact. List? aceArgs = AcClientCommandLine.Split(builder.BuildArguments(ace, a)); Check(ArgAfter(aceArgs, "-v") == "t3st pw quoted ü" && ArgAfter(aceArgs, "-h") == "127.0.0.1:9000", "ACE: the client reads the password (-v) and the host after it"); List? gdleArgs = AcClientCommandLine.Split(builder.BuildArguments(gdle, a)); Check(ArgAfter(gdleArgs, "-a") == "A:t3st pw quoted ü" && ArgAfter(gdleArgs, "-p") == "9000", "GDLE: the client reads account:password (-a) and the port"); string preview = builder.BuildMaskedArguments(ace, a); Check(!preview.Contains("t3st") && preview.Contains("-v " + AcLaunchArgumentBuilder.PasswordMask), "preview masked: " + preview); LaunchAccountProfile noPw = loaded.AccountProfiles.First(x => x.Id == "b"); Check(AcLaunchArgumentBuilder.NeedsPassword(noPw) && !AcLaunchArgumentBuilder.NeedsPassword(a), "NeedsPassword: only the account without one"); Check(builder.BuildMaskedArguments(ace, noPw).StartsWith("No password is saved for account 'B'"), "preview of an account without a password says so: " + builder.BuildMaskedArguments(ace, noPw)); // The client exits with "You can only run the game from the launcher program" on an // empty password (Conquest, 2026-10-13), so the launch is refused instead. string refusal = Throws(() => builder.BuildArguments(ace, noPw)); Check(refusal.StartsWith("No password is saved for account 'B'"), "no saved password: launch refused: " + refusal); Check(Throws(() => builder.BuildArguments(gdle, noPw)).StartsWith("No password"), "GDLE refused too"); // Account names: ACE's 50-character limit; GDLE's "account:password" argument. Check(AcLaunchArgumentBuilder.AccountNameProblem("SK", AcEmulatorKind.Ace) == null, "a short name is fine"); Check(AcLaunchArgumentBuilder.AccountNameProblem(new string('x', 51), AcEmulatorKind.Ace)?.Contains("50") == true, "51 characters: too long"); Check(AcLaunchArgumentBuilder.AccountNameProblem("a:b", AcEmulatorKind.Ace) == null, "a colon is fine on ACE"); Check(AcLaunchArgumentBuilder.AccountNameProblem("a:b", AcEmulatorKind.Gdle) != null, "a colon is refused on GDLE"); Check(AcLaunchArgumentBuilder.AccountNameProblem(" ", AcEmulatorKind.Ace) != null, "blank is refused"); LaunchAccountProfile copy = a.Clone(); Check(copy.PasswordProtected == a.PasswordProtected, "Clone keeps the encrypted password"); copy.SetPassword(Pw2); Check(copy.TryGetPasswordForLaunch(out string got2, out _) && got2 == Pw2, "a new password replaces it"); copy.ClearPassword(); Check(!copy.HasSavedPassword && copy.TryGetPasswordForLaunch(out string none, out _) && none.Length == 0, "clear"); Check(AccountPasswordProtection.Protect(Pw) != AccountPasswordProtection.Protect(Pw), "each encryption differs (salted blobs)"); }); Scenario("migrate plain-text passwords from an older file", root, () => { string legacy = """ { "EnginePath": "X", "AccountProfiles": [ { "Id": "a", "AccountName": "A", "Password": "PLAIN-PW-ONE", "InjectionMode": "RynthCore" }, { "Id": "b", "AccountName": "B", "Password": "PLAIN-PW-TWO", "InjectionMode": "RynthCore" }, { "Id": "c", "AccountName": "C", "Password": "", "InjectionMode": "Decal" }, { "Id": "d", "AccountName": "D" } ] } """; File.WriteAllText(Main_, legacy); File.WriteAllText(Bak, legacy); File.WriteAllText(Sidecar, """{ "DecalBridgeAccountIds": [ "b" ] }"""); File.WriteAllText(Main_ + ".corrupt-20260101-000000", "{ old quarantined file"); AppSettings loaded = AppSettingsStore.Load(); Check(AppSettingsStore.LastPasswordMigrationNote?.StartsWith("migrated 2 account password(s) to encrypted storage") == true, "one note: " + AppSettingsStore.LastPasswordMigrationNote); Check(AppSettingsStore.LastPasswordMigrationNote?.Contains("corrupt-") == true, "note points at the quarantined file"); Check(PwOf(loaded, "a") == "PLAIN-PW-ONE" && PwOf(loaded, "b") == "PLAIN-PW-TWO", "passwords kept"); Check(!loaded.AccountProfiles.First(x => x.Id == "c").HasSavedPassword, "empty plain password = none saved"); Check(loaded.AccountProfiles.All(x => x.LegacyPlainPassword == null), "no plain text left on the profiles"); CheckNoPlainText("PLAIN-PW-ONE"); CheckNoPlainText("PLAIN-PW-TWO"); Check(!File.ReadAllText(Main_).Contains("\"Password\"") && !File.ReadAllText(Bak).Contains("\"Password\""), "no \"Password\" field in appsettings.json or .bak"); Check(Mode(loaded, "b") == InjectionMode.DecalBridge && SidecarIds().SequenceEqual(new[] { "b" }), "decal-accounts.json survives the migration save"); Check(loaded.EnginePath == "X", "other settings kept"); CheckNotesClean("PLAIN-PW-ONE", "PLAIN-PW-TWO"); AppSettings again = AppSettingsStore.Load(); Check(AppSettingsStore.LastPasswordMigrationNote == null, "second load: nothing left to migrate"); Check(PwOf(again, "a") == "PLAIN-PW-ONE", "second load decrypts"); }); Scenario("undecryptable password (copied from another Windows user or PC)", root, () => { AppSettings s = Sample(); s.AccountProfiles[0].SetPassword(Pw); s.AccountProfiles[1].SetPassword(Pw2); s.AccountProfiles[2].SetPassword(Pw2); AppSettingsStore.Save(s); // Blobs this user can't open: a valid one with a byte changed (DPAPI's integrity // check fails as it does with another user's key), random bytes, and non-base64. byte[] blob = Convert.FromBase64String(s.AccountProfiles[0].PasswordProtected); blob[^5] ^= 0x5A; SetRaw("a", Convert.ToBase64String(blob)); SetRaw("b", Convert.ToBase64String(Guid.NewGuid().ToByteArray())); SetRaw("c", "not base64 !!"); AppSettings loaded = AppSettingsStore.Load(); // must not throw Check(AppSettingsStore.LastLoadDiagnostic == null, "the file is not taken for corrupt"); Check(loaded.AccountProfiles.All(x => x.PasswordNeedsReentry), "all three marked \"password needs re-entering\""); Check(AppSettingsStore.LastPasswordProblemNote?.Contains("3 saved account password(s)") == true && AppSettingsStore.LastPasswordProblemNote.Contains("need re-entering"), "problem note: " + AppSettingsStore.LastPasswordProblemNote); LaunchAccountProfile a = loaded.AccountProfiles.First(x => x.Id == "a"); var builder = new AcLaunchArgumentBuilder(); LaunchServerProfile ace = Server(AcEmulatorKind.Ace); string? error = null; try { builder.BuildArguments(ace, a); } catch (InvalidOperationException ex) { error = ex.Message; } Check(error?.Contains("needs re-entering") == true, "launch refused, not launched with an empty password: " + error); Check(builder.BuildMaskedArguments(ace, a).Contains("needs re-entering"), "preview says so"); Check(!a.TryGetPasswordForLaunch(out string empty, out _) && empty.Length == 0, "TryGetPasswordForLaunch false"); a.SetPassword(Pw2); // re-entered in the account editor Check(!a.PasswordNeedsReentry && a.TryGetPasswordForLaunch(out string got, out _) && got == Pw2, "re-entering fixes it"); AppSettingsStore.Save(loaded); AppSettings reloaded = AppSettingsStore.Load(); Check(!reloaded.AccountProfiles.First(x => x.Id == "a").PasswordNeedsReentry, "fixed after reload"); Check(reloaded.AccountProfiles.First(x => x.Id == "b").PasswordNeedsReentry, "the others still need re-entering"); CheckNoPlainText(Pw2); }); Scenario("nothing leaks into notes, previews or other files", root, () => { File.WriteAllText(Main_, """{ "AccountProfiles": [ { "Id": "a", "AccountName": "A", "Password": "LEAK-CHECK-PW" } ] }"""); AppSettings loaded = AppSettingsStore.Load(); CheckNotesClean("LEAK-CHECK-PW"); Check(!loaded.AccountProfiles[0].ToString().Contains("LEAK-CHECK-PW"), "display name has no password"); Check(!new AcLaunchArgumentBuilder().BuildMaskedArguments(Server(AcEmulatorKind.Gdle), loaded.AccountProfiles[0]).Contains("LEAK-CHECK-PW"), "GDLE preview masked"); AppSettingsStore.Save(loaded); CheckNoPlainText("LEAK-CHECK-PW"); }); Scenario("known servers: picking one fills the profile, saved profiles find theirs", root, () => { var all = KnownServerCatalog.All; Check(all.Count == 17, $"17 known servers (16 + ILT), got {all.Count}"); Check(all.Select(s => s.Id).Distinct(StringComparer.OrdinalIgnoreCase).Count() == all.Count, "ids unique"); Check(all.Select(s => s.Host).Distinct(StringComparer.OrdinalIgnoreCase).Count() == all.Count, "hosts unique"); Check(all.All(s => s.Port is > 0 and < 65536 && s.PluginName.StartsWith("Rynth", StringComparison.Ordinal)), "every entry has a port and a Rynth plugin"); Check(all.Select(s => s.Name).SequenceEqual(all.Select(s => s.Name).OrderBy(n => n, StringComparer.OrdinalIgnoreCase)), "listed by name"); KnownServer? reef = KnownServerCatalog.FindById("REEFCULL"); Check(reef?.Emulator == AcEmulatorKind.Gdle, "Reefcull is GDLE (id lookup ignores case)"); Check(KnownServerCatalog.FindById("portalstorm")?.Port == 9020, "PortalStorm uses 9020"); var p = new LaunchServerProfile { Id = "keep", Alias = "Main", RodatEnabled = true, Host = "x", Port = 1 }; KnownServerCatalog.ApplyTo(KnownServerCatalog.FindById("ilt")!, p); Check(p.Name == "Infinite Leaftide" && p.ConnectionString == "game.infiniteleaftide.online:9000" && p.Emulator == AcEmulatorKind.Ace, "ILT fills name, host, port, emulator: " + p.ConnectionString); Check(p.Id == "keep" && p.Alias == "Main" && p.RodatEnabled, "id, alias and Rodat kept"); Check(KnownServerCatalog.FindByHost("PLAY.COLDEVE.AC.")?.Id == "coldeve", "exact host (case, trailing dot)"); Check(KnownServerCatalog.FindByHost("infiniteleaftide.online")?.Id == "ilt", "ILT's parent domain finds ILT"); Check(KnownServerCatalog.FindByHost("aelrynth.com")?.Id == "aelrynth", "Aelrynth"); Check(KnownServerCatalog.FindByHost("other.ddns.net") == null, "a shared dynamic-DNS domain matches nothing"); Check(KnownServerCatalog.FindByHost("harvestbud.gdleac.com") == null, "Reefcull's shared host domain isn't Reefcull"); Check(KnownServerCatalog.FindByHost("172.111.230.12") == null, "an IP matches only itself"); Check(KnownServerCatalog.FindByHost("172.111.230.127")?.Id == "frostace", "FrostACE by IP"); Check(KnownServerCatalog.FindByHost("") == null && KnownServerCatalog.FindByHost(null) == null, "empty host"); }); // ── First Login dialog rules (a new server: no password, no characters yet) ── Scenario("first login on a new server", root, () => { var withPw = new LaunchAccountProfile { Id = "ilt", AccountName = "silentkelpie" }; withPw.SetPassword(Pw); var noPwSame = new LaunchAccountProfile { Id = "other", AccountName = "SilentKelpie" }; var conquest = new LaunchAccountProfile { Id = "new", AccountName = "SK", CharacterName = LaunchAccountProfile.NoneOption }; var all = new List { withPw, noPwSame, conquest }; Check(FirstLoginRules.KnownAccountNames(all, "new").SequenceEqual(new[] { "silentkelpie" }), "known names: the others, distinct ignoring case, not this profile's own"); Check(FirstLoginRules.SavedPasswordSource(all, "SILENTKELPIE", "new")?.Id == "ilt", "the same name with a saved password can be reused (case ignored)"); Check(FirstLoginRules.SavedPasswordSource(all, "SK", "new") == null, "a new name has none to reuse"); Check(FirstLoginRules.SavedPasswordSource(all, "silentkelpie", "ilt") == null, "never the profile itself"); var copy = new LaunchAccountProfile { AccountName = "silentkelpie" }; copy.CopyPasswordFrom(withPw); Check(copy.PasswordProtected == withPw.PasswordProtected && copy.TryGetPasswordForLaunch(out string reused, out _) && reused == Pw, "reuse copies the encrypted blob, and it decrypts"); var none = new List(); List firstChoices = FirstLoginRules.LoginChoices(none, conquest.CharacterName); Check(firstChoices.SequenceEqual(new[] { FirstLoginRules.StopAtCharacterSelect }), "no characters yet: only stop at character select (the old (None) isn't listed)"); Check(FirstLoginRules.CharacterNameFor(FirstLoginRules.StopAtCharacterSelect, none) == "", "stop with none known saves \"\" so the first character created is picked next time"); var chars = new List { "Alpha", "Beta" }; Check(FirstLoginRules.LoginChoices(chars, "Gamma").SequenceEqual(new[] { FirstLoginRules.StopAtCharacterSelect, "Gamma", "Alpha", "Beta" }), "several characters: all listed, the saved one kept even if not seen yet"); Check(FirstLoginRules.CharacterNameFor("Beta", chars) == "Beta", "picking a character saves it"); Check(FirstLoginRules.CharacterNameFor(FirstLoginRules.StopAtCharacterSelect, chars) == LaunchAccountProfile.NoneOption, "stop with characters known saves the explicit (None)"); Check(FirstLoginRules.Problem("SK", "", "", false, AcEmulatorKind.Ace)?.StartsWith("Enter the password") == true, "a password is required"); Check(FirstLoginRules.Problem("SK", "a", "b", false, AcEmulatorKind.Ace)?.Contains("don't match") == true, "the confirmation must match"); Check(FirstLoginRules.Problem("SK", "pw", "pw", false, AcEmulatorKind.Ace) == null, "name + matching password: ready"); Check(FirstLoginRules.Problem("silentkelpie", "", "", true, AcEmulatorKind.Ace) == null, "reusing a saved password needs no typing"); Check(FirstLoginRules.Problem("a:b", "pw", "pw", false, AcEmulatorKind.Gdle) != null, "GDLE name with a colon refused"); Check(FirstLoginRules.Problem("", "pw", "pw", false, AcEmulatorKind.Ace) != null, "a name is required"); }); // Deleting a server profile re-pointed its accounts at the first remaining server, so the // next launch sent one server's password to another (audit 2026-10-21 F2). Scenario("server profiles: an account logs on only to its own server", root, () => { var conquest = new LaunchServerProfile { Id = "conq", Name = "Conquest", Host = "conquest.example", Port = 9000 }; var ilt = new LaunchServerProfile { Id = "ilt", Name = "Infinite Leaftide", Host = "ilt.example", Port = 9000 }; var servers = new List { conquest, ilt }; var onConquest = new LaunchAccountProfile { Id = "a", AccountName = "SK", ServerId = "conq" }; var onConquest2 = new LaunchAccountProfile { Id = "b", AccountName = "Buffi", Alias = "Buffer", ServerId = "CONQ" }; var onIlt = new LaunchAccountProfile { Id = "c", AccountName = "SK", ServerId = "ilt" }; var never = new LaunchAccountProfile { Id = "d", AccountName = "New" }; var dangling = new LaunchAccountProfile { Id = "e", AccountName = "Old", ServerId = "deleted-elsewhere" }; var accounts = new List { onConquest, onConquest2, onIlt, never, dangling }; Check(AccountServerRules.ServerFor(onConquest, servers) == conquest, "its own server"); Check(AccountServerRules.ServerFor(onConquest2, servers) == conquest, "the id is matched ignoring case"); Check(AccountServerRules.ServerFor(onIlt, servers) == ilt, "the same name on another server: that server"); Check(AccountServerRules.ServerFor(never, servers) == null, "no server set: none (not the first or the selected one)"); Check(AccountServerRules.ServerFor(dangling, servers) == null, "a server that is gone: none, never another server"); Check(AccountServerRules.ServerFor(dangling, new List { ilt }) == null, "not even when only one server is left"); Check(AccountServerRules.ServerFor(onConquest, new List()) == null, "no servers at all: none"); Check(AccountServerRules.AccountsOn(conquest, accounts).Select(a => a.Id).SequenceEqual(new[] { "a", "b" }), "Conquest's accounts: a and b"); string? blocker = AccountServerRules.DeleteBlocker(conquest, accounts); Check(blocker != null && blocker.Contains("2 account(s)") && blocker.Contains("SK") && blocker.Contains("Buffer (Buffi)"), "deleting a server with accounts is refused, naming them: " + blocker); Check(blocker != null && !blocker.Contains("Old") && !blocker.Contains("New"), "only that server's accounts are named"); var unused = new LaunchServerProfile { Id = "spare", Name = "Spare", Host = "h", Port = 1 }; Check(AccountServerRules.DeleteBlocker(unused, accounts) == null, "a server no account uses can be deleted"); // The refusal leaves every account as it was (nothing re-pointed). Check(accounts.Select(a => a.ServerId).SequenceEqual(new[] { "conq", "CONQ", "ilt", "", "deleted-elsewhere" }), "no account was changed"); var many = Enumerable.Range(1, 12).Select(i => new LaunchAccountProfile { AccountName = "Acc" + i, ServerId = "ilt" }).ToList(); string? manyBlocker = AccountServerRules.DeleteBlocker(ilt, many); Check(manyBlocker != null && manyBlocker.Contains("12 account(s)") && manyBlocker.Contains("4 more") && !manyBlocker.Contains("Acc9"), "a long list names 8 and counts the rest"); Check(AccountServerRules.NoServerMessage(dangling, anyServerProfiles: true).Contains("pick the server"), "no-server launch message says what to do"); Check(AccountServerRules.NoServerMessage(never, anyServerProfiles: false).Contains("Add a server profile"), "with no servers at all: add one"); }); // A saved UserPreferences.ini whose display mode the PC can't use made every launch // fail with "Could not initialize Direct3D"; a quick exit must undo that swap. Scenario("prefs swap: did the swap change the live file", root, () => { byte[] a = "[Display]\nResolution=2560x1440\n"u8.ToArray(); byte[] b = "[Display]\nResolution=1920x1080\n"u8.ToArray(); Check(!UserPrefsSwapRecovery.SwapChangedPrefs(new UserPrefsSwap("s", "l", a, (byte[])a.Clone())), "same bytes: not the cause"); Check(UserPrefsSwapRecovery.SwapChangedPrefs(new UserPrefsSwap("s", "l", a, b)), "different bytes: changed"); Check(UserPrefsSwapRecovery.SwapChangedPrefs(new UserPrefsSwap("s", "l", a, null)), "no live file before: changed"); }); Scenario("prefs swap: failed stash set aside, live file put back", root, () => { var (swap, legacy) = PrefsSwapFiles(legacyMatches: true); var now = new DateTime(2026, 10, 14, 16, 30, 5); UserPrefsRecoveryResult r = UserPrefsSwapRecovery.Recover(swap, quarantineStash: true, restoreLive: true, legacy, now); Check(!File.Exists(swap.StashPath), "stash no longer swappable"); Check(r.QuarantinedStashPath == swap.StashPath + ".failed-20261014-163005" && File.Exists(r.QuarantinedStashPath), "stash kept as .failed-