diff --git a/docs/launcher.md b/docs/launcher.md index 942662c..8f5c2d5 100644 --- a/docs/launcher.md +++ b/docs/launcher.md @@ -1335,6 +1335,8 @@ Mods, modules and leagues use the same editor on Windows and Linux. Each setting left and its control in a column on the right; in a card under 520 pixels wide the control moves under the text. - On/off switches; text with length and pattern checks; single and multiple choices, including typed game-value sources. +- Text fields declared with the `password` format are masked. The local settings file and configuration history + store the value as plain text. - Numbers with exact-value boxes and sliders when bounded; percentages and multipliers are displayed in their declared units, and durations are edited in seconds. Step sizes and integer restrictions are checked before saving. - Ranges have separate minimum and maximum controls; low cannot exceed high. @@ -1348,7 +1350,10 @@ Unreadable existing user files block editing instead of being silently replaced. Modules and Leagues ask before discarding a draft when switching selection or refreshing. Saving checks the reviewed file's hash, so another tool's changes require a refresh. Changes use the shared workspace lock and the normal optional save backup. Previous configuration files are copied to Waypoint's `config-history//` before replacement, separately from save backups. -Reset to defaults asks first. Mod values use `data/mods/`, module values `data/modules/`, and league values `data/leagues/`. +Reset to defaults asks first. Mod values use `data/mods/` unless the installed mod declares a `userSettingsFile` and has its own `.json` beside its +`mod.json`; Waypoint edits that file and preserves it across updates. Module values use `data/modules/` and league values +use `data/leagues/`. For GlobalChat’s channel maps, use **Add entry** or **Remove** to edit routes. Choose a route type +to show the applicable server address and port or Discord channel ID. ### Backups diff --git a/docs/runtime-contract.md b/docs/runtime-contract.md index 3edc465..46fc72e 100644 --- a/docs/runtime-contract.md +++ b/docs/runtime-contract.md @@ -285,9 +285,10 @@ BuildMod or live.ps1 builds it; refused on release installs). Under the mutex an dropped. UninstallMod moves `Mods/Binaries/` (and `Mods/Source/` in a checkout) the same way, drops the registry entry and the mod's line of `mod-state.txt`. A batch passes `-ModIds a;b` (all checked first, one backup): InstallMod adds `-ModStageds` and `-ModTargets` in the same order, and BuildMod's `-ModProjects a;b` builds several in one -parallel MSBuild run over a temporary traversal project. SaveModSettings atomically writes `data/mods/.json` from -validated values. Core reads `settings.json` and the user file itself; script mods are fingerprinted by their scripts' -hashes. The one checkout write outside the adapter is the on/off switch: Core replaces `mod-state.txt` atomically +parallel MSBuild run over a temporary traversal project. SaveModSettings atomically writes the mod's user settings from +validated values. When the installed manifest declares `userSettingsFile` as `.json` and that file exists beside the +manifest, Core reads it and the adapter writes it there. Waypoint preserves the file during binary updates. Otherwise, +Core and the adapter use `data/mods/.json`. Script mods are fingerprinted by their scripts' hashes. The one checkout write outside the adapter is the on/off switch: Core replaces `mod-state.txt` atomically (`ModCatalog.WriteChoice`) while holding Shared's workspace lock, so a switch is instant; EnableMod and DisableMod remain for other callers. A running server with no verified source hook gets a restart notice in both interfaces; releases are unknown because they have no source. Saved choices are not proof of a runtime load. diff --git a/scripts/ModBridge.ps1 b/scripts/ModBridge.ps1 index 71a99e4..2f91f95 100644 --- a/scripts/ModBridge.ps1 +++ b/scripts/ModBridge.ps1 @@ -226,6 +226,20 @@ function Get-StagedModPath([string]$path, [switch]$File) { else { Require (Test-Path -LiteralPath $full -PathType Container) 'The prepared mod folder is missing.' } return $full } +function Get-InstalledModSettings([string]$folder, [string]$id) { + if ($id -cin @('mod','settings')) { return } + $name = $id + '.json' + $path = Join-Path $folder $name + $manifest = Join-Path $folder 'mod.json' + if (-not (Test-Path -LiteralPath $path -PathType Leaf) -or -not (Test-Path -LiteralPath $manifest -PathType Leaf)) { return } + Assert-Physical $manifest + Require ((Get-Item -LiteralPath $manifest).Length -le 262144) 'Mod manifest exceeds its size limit.' + $declaration = [IO.File]::ReadAllText($manifest) | ConvertFrom-Json + if ($declaration.PSObject.Properties['userSettingsFile'] -and $declaration.userSettingsFile -ceq $name) { + Assert-Physical $path + return $path + } +} function Move-ModAside([string]$folder, [string]$target) { # Never deleted: the previous copy of a mod moves to Mods/.replaced/, where the Gateway does not look. if (-not (Test-Path -LiteralPath $folder)) { return } @@ -235,6 +249,7 @@ function Move-ModAside([string]$folder, [string]$target) { New-Item -ItemType Directory -Path (Split-Path $aside) -Force | Out-Null Move-Item -LiteralPath $folder -Destination $aside Write-Host "The previous Mods/$target/$ModId is kept at $aside." + return $aside } function Install-StagedMod($snapshot) { # -ModIds, -ModStageds and -ModTargets (';'-separated, in the same order) install several with one backup; every one is @@ -266,10 +281,17 @@ function Install-StagedMod($snapshot) { Assert-Physical $root New-Item -ItemType Directory -Path $root -Force | Out-Null $destination = Join-Path $root $mod.Id - Move-ModAside $destination $mod.Target + $settingsName = $mod.Id + '.json' + $installedSettings = Join-Path $destination $settingsName + $keepSettings = $mod.Target -eq 'Binaries' -and [bool](Get-InstalledModSettings $destination $mod.Id) + $aside = Move-ModAside $destination $mod.Target # A release replaces a source install of the same mod, which live.ps1 would otherwise build over it. - if ($mod.Target -eq 'Binaries' -and -not $script:isRelease) { Move-ModAside (At "Mods/Source/$($mod.Id)") 'Source' } + if ($mod.Target -eq 'Binaries' -and -not $script:isRelease) { $null = Move-ModAside (At "Mods/Source/$($mod.Id)") 'Source' } Copy-Item -LiteralPath $mod.Staged -Destination $destination -Recurse + if ($keepSettings) { + Assert-Physical $installedSettings + Copy-Item -LiteralPath (Join-Path $aside $settingsName) -Destination $installedSettings -Force + } Remove-Item -LiteralPath $mod.Staged -Recurse -Force Write-Host "Installed $($mod.Id) into Mods/$($mod.Target)." } @@ -285,7 +307,8 @@ function Save-ModSettings($snapshot) { Require ($parsed -is [Management.Automation.PSCustomObject]) 'Mod settings must be a JSON object.' Backup-Saves $snapshot Set-Stage 'Saving mod settings' $ModId - $folder = At 'data/mods' + $installed = Join-Path (Get-ModFolder) $ModId + $folder = if (Get-InstalledModSettings $installed $ModId) { $installed } else { At 'data/mods' } Assert-Physical $folder New-Item -ItemType Directory -Path $folder -Force | Out-Null $path = Join-Path $folder "$ModId.json" @@ -322,8 +345,8 @@ function Uninstall-Mod($snapshot) { Set-Stage $(if ($mods.Count -eq 1) { 'Uninstalling mod' } else { 'Uninstalling mods' }) (($ids -join ', ') + ' to Mods/.replaced') foreach ($mod in $mods) { $script:ModId = $mod.Id - if ($mod.HasSource) { Move-ModAside $mod.Source 'Source' } - Move-ModAside $mod.Binary 'Binaries' + if ($mod.HasSource) { $null = Move-ModAside $mod.Source 'Source' } + $null = Move-ModAside $mod.Binary 'Binaries' } if (-not $script:isRelease) { Write-ManagedMods @(Read-ManagedMods | Where-Object { $_.Id -cnotin $ids }) } $state = Join-Path (Get-ModFolder) 'mod-state.txt' diff --git a/src/Launcher.Core/ModSettingsForm.cs b/src/Launcher.Core/ModSettingsForm.cs index e81abcd..1f1b9ae 100644 --- a/src/Launcher.Core/ModSettingsForm.cs +++ b/src/Launcher.Core/ModSettingsForm.cs @@ -54,6 +54,20 @@ public static ModSettingsForm Load(string id, string declarationsPath, string ro var settings = Parse(declarations); var user = new JsonObject(); string userPath = Path.Combine(root, UserFile(id, kind)); + if (kind == "mods" && id is not ("mod" or "settings")) + { + string folder = Path.GetDirectoryName(declarationsPath)!; + string name = id + ".json"; + string manifest = Path.Combine(folder, "mod.json"); + string besideMod = Path.Combine(folder, name); + if (File.Exists(besideMod) && File.Exists(manifest)) + { + if (!ModCatalog.Physical(manifest) || new FileInfo(manifest).Length > 256 * 1024) + throw new IOException(L.Text("The existing settings cannot be safely read. Nothing was changed.")); + if (JsonNode.Parse(File.ReadAllText(manifest), NodeOptions, Jsonc)?["userSettingsFile"] is JsonValue marker + && marker.TryGetValue(out string? configured) && configured == name) userPath = besideMod; + } + } string userHash = GameSystems.Hash(userPath); if (File.Exists(userPath)) { @@ -94,11 +108,13 @@ static IReadOnlyList ParseSettings(JsonObject settings, int depth, b : (o!.DeepClone(), Show(o!))).ToList() : []; string type = Text("type"); + string format = Text("format"); if (!ModSetting.EditableTypes.Contains(type)) throw new InvalidDataException(L.Text("Unsupported setting type: {0}", type)); if (d["when"] is not (null or JsonObject) || d["advanced"] is { } advanced && advanced.GetValueKind() is not (JsonValueKind.True or JsonValueKind.False) || d["options"] is not null && (d["options"] is not JsonArray { Count: > 0 } || options.Count == 0 || d["source"] is not null) || type is "choice" or "choices" && options.Count == 0 && Text("source").Length == 0 - || Text("format") is not ("" or "percent" or "duration" or "multiplier") + || format is not ("" or "percent" or "duration" or "multiplier" or "password") + || format == "password" && type != "text" || Text("applies") is not ("" or "now" or "nextArea" or "restart") || Text("of") is not ("" or "integer" or "number") || Text("of").Length > 0 && type != "range") throw Invalid(); if (Text("pattern").Length > 0) @@ -107,7 +123,7 @@ static IReadOnlyList ParseSettings(JsonObject settings, int depth, b var children = type == "group" && d["settings"] is JsonObject group ? ParseSettings(group, depth + 1) : null; ModSetting? Nested(string key) => d[key] is JsonObject child ? ParseSettings(new JsonObject { [key] = child.DeepClone() }, depth + 1, needsDefault: false)[0] : null; JsonNode? defaults = children is null ? d["default"]?.DeepClone() : new JsonObject(children.Select(c => KeyValuePair.Create(c.Name, c.Default?.DeepClone()))); - result.Add(new(name, type, defaults, Text("label"), Text("description"), Text("unit"), Text("format"), + result.Add(new(name, type, defaults, Text("label"), Text("description"), Text("unit"), format, Number("min"), Number("max"), options, Text("source"), Whole("minItems"), Whole("maxItems"), Whole("minLength"), Whole("maxLength"), Text("applies") is { Length: > 0 } applies ? applies : "now", d["advanced"] is JsonValue a && a.TryGetValue(out bool adv) && adv, Number("step"), Text("pattern"), Text("of") == "integer", type == "list" ? Nested("item") : null, @@ -211,6 +227,12 @@ bool Numeric(JsonNode? n, bool whole = false) => n?.GetValueKind() == JsonValueK bool Allowed(JsonNode? n) => setting.Options.Count > 0 ? setting.Options.Any(o => Equal(o.Value, n)) : setting.Source.Length > 0 && n?.GetValueKind() == JsonValueKind.String && n.GetValue().Length > 0; bool Count(int n) => !(n < setting.MinItems || n > setting.MaxItems); + bool MatchesPattern(string text) + { + try { return setting.Pattern.Length == 0 || System.Text.RegularExpressions.Regex.IsMatch(text, @"\A(?:" + setting.Pattern + @")\z", + System.Text.RegularExpressions.RegexOptions.None, TimeSpan.FromMilliseconds(100)); } + catch (Exception e) when (e is ArgumentException or System.Text.RegularExpressions.RegexMatchTimeoutException) { return false; } + } switch (setting.Type) { case "bool": return kind is JsonValueKind.True or JsonValueKind.False ? null : Invalid(); @@ -224,13 +246,12 @@ bool Allowed(JsonNode? n) => setting.Options.Count > 0 ? setting.Options.Any(o = if (kind != JsonValueKind.String) return Invalid(); string text = value.GetValue(); if (text.Length < setting.MinLength || text.Length > setting.MaxLength) return Invalid(); - try { return setting.Pattern.Length == 0 || System.Text.RegularExpressions.Regex.IsMatch(text, "\\A(?:" + setting.Pattern + ")\\z", - System.Text.RegularExpressions.RegexOptions.None, TimeSpan.FromMilliseconds(100)) ? null : Invalid(); } - catch (Exception e) when (e is ArgumentException or System.Text.RegularExpressions.RegexMatchTimeoutException) { return Invalid(); } + return MatchesPattern(text) ? null : Invalid(); case "list": return value is JsonArray list && Count(list.Count) && setting.Item is { } item && list.All(n => Validate(item, n) is null) ? null : Invalid(); case "map": return value is JsonObject map && setting.Value is { } entry - && map.All(p => (setting.Options.Count == 0 && setting.Source.Length == 0 || Allowed(JsonValue.Create(p.Key))) + && Count(map.Count) && map.All(p => MatchesPattern(p.Key) + && (setting.Options.Count == 0 && setting.Source.Length == 0 || Allowed(JsonValue.Create(p.Key))) && Validate(entry, p.Value) is null) ? null : Invalid(); case "group": return value is JsonObject group && setting.Children is { } children && children.All(c => group.FirstOrDefault(p => p.Key.Equals(c.Name, StringComparison.OrdinalIgnoreCase)).Value is not { } child diff --git a/src/Waypoint/SettingsEditor.cs b/src/Waypoint/SettingsEditor.cs index 451852b..a272c98 100644 --- a/src/Waypoint/SettingsEditor.cs +++ b/src/Waypoint/SettingsEditor.cs @@ -144,6 +144,19 @@ void BuildGroup(StackPanel panel, IReadOnlyList settings, Func new JsonArray(boxes.Where(b => b.Box.IsChecked == true).Select(b => b.Value.DeepClone()).ToArray()); break; + case "text" when setting.Format == "password": +#if WINDOWS + var password = new PasswordBox { Password = ModSettingsForm.Show(value), MaxLength = setting.MaxLength ?? 0 }; + password.PasswordChanged += (_, _) => Change(); + read = () => JsonValue.Create(password.Password); +#else + var password = new TextBox { Text = ModSettingsForm.Show(value), PasswordChar = '●', MaxLength = setting.MaxLength ?? 0 }; + password.TextChanged += (_, _) => Change(); + read = () => JsonValue.Create(password.Text ?? ""); +#endif + A11y.SetName(password, setting.Title); + control.Children.Add(password); + break; default: var entry = new TextBox { Text = ModSettingsForm.Show(value) }; A11y.SetName(entry, setting.Title); @@ -255,7 +268,14 @@ void Add(JsonNode? current, string key = "") keys.SelectedItem = keys.Items.OfType().FirstOrDefault(i => (string?)i.Tag == key); row.Children.Add(keys); keys.SelectionChanged += (_, _) => Change(); readKey = () => (keys.SelectedItem as ComboBoxItem)?.Tag as string ?? ""; } - else { var keyBox = new TextBox { Text = key }; row.Children.Add(keyBox); keyBox.TextChanged += (_, _) => Change(); readKey = () => keyBox.Text ?? ""; } + else + { + var keyBox = new TextBox { Text = key }; + A11y.SetName(keyBox, L.Text("Key")); + row.Children.Add(keyBox); + keyBox.TextChanged += (_, _) => Change(); + readKey = () => keyBox.Text?.Trim() ?? ""; + } } var read = Field(row, item, current); var remove = Button(L.Text("Remove"), () => { rows.Children.Remove(row); entries.RemoveAll(e => e.Row == row); Change(); }); diff --git a/tests/ModBrowser.Tests.ps1 b/tests/ModBrowser.Tests.ps1 index 85220f3..f7ebd67 100644 --- a/tests/ModBrowser.Tests.ps1 +++ b/tests/ModBrowser.Tests.ps1 @@ -75,11 +75,21 @@ try { [IO.File]::WriteAllText($settings, '[]') Refused { Operation 'SaveModSettings' 'alpha' $settings } 'non-object settings are refused' Check ([IO.File]::ReadAllText((At 'data/mods/alpha.json')).Contains('ownerValue')) 'refused settings preserve the previous values' + $manifest = Get-Content -Raw -LiteralPath (At 'Mods/Binaries/alpha/mod.json') | ConvertFrom-Json + $manifest | Add-Member -NotePropertyName userSettingsFile -NotePropertyValue alpha.json + $manifest | ConvertTo-Json | Set-Content -LiteralPath (At 'Mods/Binaries/alpha/mod.json') + [IO.File]::WriteAllText((At 'Mods/Binaries/alpha/alpha.json'), '{"quantity":3}') + [IO.File]::WriteAllText($settings, '{"quantity":4}') + Operation 'SaveModSettings' 'alpha' $settings + Check ((Get-Content -LiteralPath (At 'Mods/Binaries/alpha/alpha.json') -Raw | ConvertFrom-Json).quantity -eq 4) 'save updates the installed mod settings' + Check ((Get-Content -LiteralPath (At 'data/mods/alpha.json') -Raw | ConvertFrom-Json).quantity -eq 2) 'save leaves fallback settings intact' New-Item -ItemType Directory -Force (At 'Mods/Source/alpha') | Out-Null Set-Content -LiteralPath (At 'Mods/Source/alpha/owner.cs') 'owner source' Operation 'InstallMod' 'alpha' (Stage 'alpha' '2') 'Binaries' Check ((Get-Content -LiteralPath (At 'Mods/Binaries/alpha/mod.json') -Raw | ConvertFrom-Json).version -eq '2') 'update installs the new version' Check (-not (Test-Path -LiteralPath (At 'Mods/Source/alpha'))) 'binary update retires the source that could overwrite it' + Check ((Get-Content -LiteralPath (At 'Mods/Binaries/alpha/alpha.json') -Raw | ConvertFrom-Json).quantity -eq 4) 'upgrade preserves installed mod settings' + Check (@(Get-ChildItem -LiteralPath (At 'Mods/.replaced') -Recurse -Filter owner.cs).Count -eq 1) 'retired source remains recoverable' Check (@(Get-ChildItem -LiteralPath (At 'Mods/.replaced') -Recurse -Filter alpha.dll | Where-Object { [IO.File]::ReadAllText($_.FullName) -eq 'inert fixture 1' }).Count -eq 1) 'previous binary remains recoverable' Check ([IO.File]::ReadAllText((At 'Mods/Binaries/mod-state.txt')).Contains('alpha off')) 'update preserves disabled choices' diff --git a/tests/Waypoint.Tests/SettingsFormTests.cs b/tests/Waypoint.Tests/SettingsFormTests.cs index 364a6fe..bba8326 100644 --- a/tests/Waypoint.Tests/SettingsFormTests.cs +++ b/tests/Waypoint.Tests/SettingsFormTests.cs @@ -34,6 +34,40 @@ ModSettingsForm Load(string? user = null) } return ModSettingsForm.Load("example", Path.Combine(_root, "settings.json"), _root, "modules"); } + [Fact] + public void Installed_mod_values_take_precedence_and_map_keys_can_be_validated() + { + string installed = Path.Combine(_root, "Mods", "Binaries", "globalchat"); + Directory.CreateDirectory(installed); + File.WriteAllText(Path.Combine(installed, "mod.json"), """{"userSettingsFile":"globalchat.json"}"""); + string schema = Path.Combine(installed, "settings.json"); + File.WriteAllText(schema, """ + {"settings":{"token":{"type":"text","format":"password","default":""}, + "channels":{"type":"map","default":{},"pattern":"[1-9][0-9]*", + "value":{"type":"group","settings":{"type":{"type":"choice","default":"blank","options":["blank","server"]}}}}}} + """); + string legacy = Path.Combine(_root, ModSettingsForm.UserFile("globalchat")); + Directory.CreateDirectory(Path.GetDirectoryName(legacy)!); + File.WriteAllText(legacy, """{"channels":{"2":{"type":"server"}}}"""); + File.WriteAllText(Path.Combine(installed, "globalchat.json"), """{"token":"sample-value","channels":{"5":{"type":"server"}}}"""); + var form = ModSettingsForm.Load("globalchat", schema, _root); + var token = form.Settings.Single(s => s.Name == "token"); + Assert.Equal("password", token.Format); + Assert.Equal("sample-value", form.Current(token)!.GetValue()); + var editedValues = form.Settings.ToDictionary(s => s.Name, form.Current); + Assert.Equal("sample-value", form.Values(editedValues)["token"]!.GetValue()); + editedValues["token"] = JsonValue.Create(""); + Assert.False(form.Values(editedValues).ContainsKey("token")); + var channels = form.Settings.Single(s => s.Name == "channels"); + var edited = Assert.IsType(form.Current(channels)); + Assert.True(edited.Remove("5")); + edited["10"] = JsonNode.Parse("""{"type":"blank"}"""); + Assert.Single(edited); + Assert.Null(ModSettingsForm.Validate(channels, edited)); + edited["foo"] = new JsonObject(); + Assert.NotNull(ModSettingsForm.Validate(channels, edited)); + } + [Theory] [InlineData("enabled", "true", "1")] [InlineData("rate", "0.7", "0.75")]