diff --git a/src/CommandForge.Application/Ports/IUserCommandStore.cs b/src/CommandForge.Application/Ports/IUserCommandStore.cs new file mode 100644 index 0000000..dcc7e3a --- /dev/null +++ b/src/CommandForge.Application/Ports/IUserCommandStore.cs @@ -0,0 +1,19 @@ +using CommandForge.Domain; + +namespace CommandForge.Application.Ports; + +/// +/// Stores user-defined commands locally, fully separate from the vetted embedded catalog +/// (golden rule #1). These commands always run without elevation. +/// +public interface IUserCommandStore +{ + /// All user-defined commands, in stored order. + public IReadOnlyList GetAll(); + + /// Creates or overwrites a command (matched by id) and persists. + public void Save(UserCommand command); + + /// Deletes the command (no-op if absent) and persists. + public void Delete(string id); +} diff --git a/src/CommandForge.Application/UserCommands/UserCommandFactory.cs b/src/CommandForge.Application/UserCommands/UserCommandFactory.cs new file mode 100644 index 0000000..050e22d --- /dev/null +++ b/src/CommandForge.Application/UserCommands/UserCommandFactory.cs @@ -0,0 +1,38 @@ +using CommandForge.Domain; + +namespace CommandForge.Application.UserCommands; + +/// +/// Builds an executable for a user-defined command. +/// +/// SAFETY (golden rule #1): the produced definition ALWAYS has +/// = false, so user commands run as the current (non-elevated) user and can never be routed to the +/// elevation broker by RunCommandUseCase. The id is namespaced with so it +/// can never collide with — or be mistaken for — a vetted catalog id; even if a bug routed it to the +/// Elevator, the Elevator validates ids against its own embedded catalog and rejects anything else. +/// +public static class UserCommandFactory +{ + /// Prefix marking an id as user-defined (never present in the vetted catalog). + public const string IdPrefix = "user:"; + + /// Converts a user command to a non-elevated executable definition. + public static CommandDefinition ToDefinition(UserCommand command) + { + ArgumentNullException.ThrowIfNull(command); + + return new CommandDefinition + { + Id = IdPrefix + command.Id, + CategoryId = "user", + TitleKey = command.Name, + DescriptionKey = command.Name, + Executable = command.Executable, + ArgsTemplate = command.Arguments, + ExecutionMode = ExecutionMode.Capture, + RequiresAdmin = false, // INVARIANT — a user command must never elevate. + DangerLevel = DangerLevel.Caution, + Restart = RestartPolicy.No, + }; + } +} diff --git a/src/CommandForge.Domain/UserCommand.cs b/src/CommandForge.Domain/UserCommand.cs new file mode 100644 index 0000000..9b38be5 --- /dev/null +++ b/src/CommandForge.Domain/UserCommand.cs @@ -0,0 +1,20 @@ +namespace CommandForge.Domain; + +/// +/// A user-defined command. These are NOT part of the vetted, embedded catalog and ALWAYS run +/// without elevation (asInvoker) — see golden rule #1. Stored separately from the catalog. +/// +public sealed record UserCommand +{ + /// Stable local id (generated when the command is created). + public required string Id { get; init; } + + /// User-visible name. + public required string Name { get; init; } + + /// Executable to run (e.g. cmd, powershell, or a full path). + public required string Executable { get; init; } + + /// Command-line arguments (optional). + public string Arguments { get; init; } = ""; +} diff --git a/src/CommandForge.Infrastructure/AppPaths.cs b/src/CommandForge.Infrastructure/AppPaths.cs index 850b996..a1f7825 100644 --- a/src/CommandForge.Infrastructure/AppPaths.cs +++ b/src/CommandForge.Infrastructure/AppPaths.cs @@ -29,6 +29,9 @@ public static class AppPaths /// %AppData%\CommandForge\recipes.json — user-defined recipes (command chains). public static string RecipesFilePath { get; } = Path.Combine(DataDirectory, "recipes.json"); + /// %AppData%\CommandForge\user-commands.json — user-defined (non-elevated) commands. + public static string UserCommandsFilePath { get; } = Path.Combine(DataDirectory, "user-commands.json"); + /// Ensures the data and logs directories exist. public static void EnsureCreated() { diff --git a/src/CommandForge.Infrastructure/DependencyInjection/ServiceCollectionExtensions.cs b/src/CommandForge.Infrastructure/DependencyInjection/ServiceCollectionExtensions.cs index 975d94e..60cd1db 100644 --- a/src/CommandForge.Infrastructure/DependencyInjection/ServiceCollectionExtensions.cs +++ b/src/CommandForge.Infrastructure/DependencyInjection/ServiceCollectionExtensions.cs @@ -40,6 +40,7 @@ public static class ServiceCollectionExtensions services.AddSingleton(); services.AddSingleton(); services.AddSingleton(); + services.AddSingleton(); services.AddSingleton(); services.AddSingleton(); services.AddSingleton(); diff --git a/src/CommandForge.Infrastructure/UserCommands/JsonUserCommandStore.cs b/src/CommandForge.Infrastructure/UserCommands/JsonUserCommandStore.cs new file mode 100644 index 0000000..e21481b --- /dev/null +++ b/src/CommandForge.Infrastructure/UserCommands/JsonUserCommandStore.cs @@ -0,0 +1,83 @@ +using System.Text.Json; +using CommandForge.Application.Ports; +using CommandForge.Domain; + +namespace CommandForge.Infrastructure.UserCommands; + +/// +/// backed by a local user-commands.json, kept entirely +/// separate from the embedded catalog (golden rule #1). All data stays on the machine (no telemetry). +/// +public sealed class JsonUserCommandStore : IUserCommandStore +{ + private readonly string _path; + private List _commands; + + /// Creates a store backed by the default . + public JsonUserCommandStore() + : this(AppPaths.UserCommandsFilePath) + { + } + + /// Creates a store backed by an explicit path (used in tests). + public JsonUserCommandStore(string path) + { + _path = path; + _commands = Load(path); + } + + /// + public IReadOnlyList GetAll() => _commands; + + /// + public void Save(UserCommand command) + { + ArgumentNullException.ThrowIfNull(command); + + _commands.RemoveAll(c => string.Equals(c.Id, command.Id, StringComparison.Ordinal)); + _commands.Add(command); + SaveFile(); + } + + /// + public void Delete(string id) + { + if (_commands.RemoveAll(c => string.Equals(c.Id, id, StringComparison.Ordinal)) > 0) + { + SaveFile(); + } + } + + private void SaveFile() + { + var directory = Path.GetDirectoryName(_path); + if (!string.IsNullOrEmpty(directory)) + { + Directory.CreateDirectory(directory); + } + + var file = new UserCommandsFile { Commands = _commands }; + var json = JsonSerializer.Serialize(file, UserCommandJsonContext.Default.UserCommandsFile); + File.WriteAllText(_path, json); + } + + private static List Load(string path) + { + if (!File.Exists(path)) + { + return []; + } + + try + { + var json = File.ReadAllText(path); + var file = JsonSerializer.Deserialize(json, UserCommandJsonContext.Default.UserCommandsFile); + return file?.Commands.ToList() ?? []; + } + catch (JsonException) + { + // Corrupt file: start empty rather than crashing on startup. + return []; + } + } +} diff --git a/src/CommandForge.Infrastructure/UserCommands/UserCommandJsonContext.cs b/src/CommandForge.Infrastructure/UserCommands/UserCommandJsonContext.cs new file mode 100644 index 0000000..9ae0db3 --- /dev/null +++ b/src/CommandForge.Infrastructure/UserCommands/UserCommandJsonContext.cs @@ -0,0 +1,20 @@ +using System.Text.Json.Serialization; +using CommandForge.Domain; + +namespace CommandForge.Infrastructure.UserCommands; + +/// Persisted shape of user-commands.json: a schema version plus the user commands. +internal sealed record UserCommandsFile +{ + public int Version { get; init; } = 1; + + public IReadOnlyList Commands { get; init; } = []; +} + +/// System.Text.Json source-generation context for user-commands.json (camelCase, indented). +[JsonSourceGenerationOptions( + PropertyNamingPolicy = JsonKnownNamingPolicy.CamelCase, + WriteIndented = true, + AllowTrailingCommas = true)] +[JsonSerializable(typeof(UserCommandsFile))] +internal sealed partial class UserCommandJsonContext : JsonSerializerContext; diff --git a/src/CommandForge.Wpf/Resources/Strings.resx b/src/CommandForge.Wpf/Resources/Strings.resx index bfdce6e..c63ce3f 100644 --- a/src/CommandForge.Wpf/Resources/Strings.resx +++ b/src/CommandForge.Wpf/Resources/Strings.resx @@ -124,6 +124,9 @@ Recipes + + My commands + Settings @@ -1198,6 +1201,49 @@ Delete recipe "{0}"? + + These commands are not part of the vetted catalog and always run without administrator rights. You alone are responsible for what they do. + + + Saved commands + + + New + + + Delete + + + Name + + + Executable (e.g. cmd, powershell) + + + Arguments + + + Save + + + Run + + + No commands yet. + + + Run this command? + + + This runs WITHOUT administrator rights: + +{0} + +Continue? + + + Delete "{0}"? + Toggle favorite diff --git a/src/CommandForge.Wpf/Resources/Strings.vi.resx b/src/CommandForge.Wpf/Resources/Strings.vi.resx index b50ce35..4465a8a 100644 --- a/src/CommandForge.Wpf/Resources/Strings.vi.resx +++ b/src/CommandForge.Wpf/Resources/Strings.vi.resx @@ -124,6 +124,9 @@ Chuỗi lệnh + + Lệnh của tôi + Cài đặt @@ -1198,6 +1201,49 @@ Xóa chuỗi "{0}"? + + Các lệnh này không thuộc catalog đã kiểm duyệt và luôn chạy KHÔNG có quyền quản trị. Bạn hoàn toàn chịu trách nhiệm về những gì chúng thực hiện. + + + Lệnh đã lưu + + + Tạo mới + + + Xóa + + + Tên + + + Tệp thực thi (vd cmd, powershell) + + + Đối số + + + Lưu + + + Chạy + + + Chưa có lệnh nào. + + + Chạy lệnh này? + + + Lệnh này chạy KHÔNG có quyền quản trị: + +{0} + +Tiếp tục? + + + Xóa "{0}"? + Bật/tắt yêu thích diff --git a/src/CommandForge.Wpf/ViewModels/MainViewModel.cs b/src/CommandForge.Wpf/ViewModels/MainViewModel.cs index 470b36e..4dca491 100644 --- a/src/CommandForge.Wpf/ViewModels/MainViewModel.cs +++ b/src/CommandForge.Wpf/ViewModels/MainViewModel.cs @@ -41,6 +41,7 @@ public sealed partial class MainViewModel : ObservableObject IExecutionHistoryService history, IClock clock, IRecipeStore recipeStore, + IUserCommandStore userCommandStore, ISystemInfoService systemInfo, SettingsViewModel settingsViewModel, LogViewerViewModel logViewer, @@ -55,6 +56,7 @@ public sealed partial class MainViewModel : ObservableObject ArgumentNullException.ThrowIfNull(history); ArgumentNullException.ThrowIfNull(clock); ArgumentNullException.ThrowIfNull(recipeStore); + ArgumentNullException.ThrowIfNull(userCommandStore); ArgumentNullException.ThrowIfNull(systemInfo); ArgumentNullException.ThrowIfNull(settingsViewModel); ArgumentNullException.ThrowIfNull(logViewer); @@ -97,6 +99,7 @@ public sealed partial class MainViewModel : ObservableObject Home = new HomeViewModel(_itemsById, settings, systemInfo, item => SelectCommandById(item.Command.Id)); History = new HistoryViewModel(_itemsById, history, SelectCommandById, RunCommandByIdAsync); Recipes = new RecipesViewModel(_itemsById, execution, recipeStore, history, clock); + UserCommands = new UserCommandsViewModel(userCommandStore, execution); Categories.Add(new CategoryViewModel(null, "Sidebar_AllCommands", "ViewGridOutline", vms.Items.Count)); foreach (var category in catalog.GetCategories()) @@ -128,6 +131,9 @@ public sealed partial class MainViewModel : ObservableObject /// The recipes view-model (shown when is Recipes). public RecipesViewModel Recipes { get; } + /// The user-defined commands view-model (shown when is UserCommands). + public UserCommandsViewModel UserCommands { get; } + /// The Settings screen view-model (shown when is Settings). public SettingsViewModel Settings { get; } @@ -199,6 +205,13 @@ public sealed partial class MainViewModel : ObservableObject CurrentSection = ShellSection.Recipes; } + [RelayCommand] + private void ShowUserCommands() + { + UserCommands.Refresh(); + CurrentSection = ShellSection.UserCommands; + } + [RelayCommand] private void ShowSettings() => CurrentSection = ShellSection.Settings; diff --git a/src/CommandForge.Wpf/ViewModels/ShellSection.cs b/src/CommandForge.Wpf/ViewModels/ShellSection.cs index cefd9ce..2e45a40 100644 --- a/src/CommandForge.Wpf/ViewModels/ShellSection.cs +++ b/src/CommandForge.Wpf/ViewModels/ShellSection.cs @@ -15,6 +15,9 @@ public enum ShellSection /// The recipes screen (build/run command chains). Recipes, + /// The user-defined commands screen (non-elevated, separate from the catalog). + UserCommands, + /// The Settings screen. Settings, diff --git a/src/CommandForge.Wpf/ViewModels/UserCommandsViewModel.cs b/src/CommandForge.Wpf/ViewModels/UserCommandsViewModel.cs new file mode 100644 index 0000000..640758e --- /dev/null +++ b/src/CommandForge.Wpf/ViewModels/UserCommandsViewModel.cs @@ -0,0 +1,176 @@ +using System.Collections.ObjectModel; +using System.Globalization; +using System.Windows; +using CommandForge.Application.Ports; +using CommandForge.Application.UserCommands; +using CommandForge.Domain; +using CommandForge.Wpf.Resources; +using CommunityToolkit.Mvvm.ComponentModel; +using CommunityToolkit.Mvvm.Input; + +namespace CommandForge.Wpf.ViewModels; + +/// +/// "My commands" screen: create and run user-defined commands. These are kept entirely separate +/// from the vetted catalog and ALWAYS run without elevation (golden rule #1) — the run path uses +/// , which forces RequiresAdmin = false. +/// +public sealed partial class UserCommandsViewModel : ObservableObject +{ + private readonly IUserCommandStore _store; + private readonly ExecutionViewModel _execution; + private string? _editingId; + + public UserCommandsViewModel(IUserCommandStore store, ExecutionViewModel execution) + { + ArgumentNullException.ThrowIfNull(store); + ArgumentNullException.ThrowIfNull(execution); + + _store = store; + _execution = execution; + + _execution.PropertyChanged += (_, e) => + { + if (e.PropertyName == nameof(ExecutionViewModel.IsRunning)) + { + RunCommand.NotifyCanExecuteChanged(); + } + }; + + Refresh(); + } + + /// The shared execution view-model — drives the console output panel. + public ExecutionViewModel Execution => _execution; + + /// Saved user commands. + public ObservableCollection Commands { get; } = []; + + [ObservableProperty] + [NotifyCanExecuteChangedFor(nameof(DeleteCommand))] + private UserCommand? _selectedCommand; + + [ObservableProperty] + [NotifyCanExecuteChangedFor(nameof(SaveCommand))] + private string _editName = string.Empty; + + [ObservableProperty] + [NotifyCanExecuteChangedFor(nameof(SaveCommand))] + [NotifyCanExecuteChangedFor(nameof(RunCommand))] + private string _editExecutable = string.Empty; + + [ObservableProperty] + private string _editArguments = string.Empty; + + /// Reloads the saved-command list from the store. + public void Refresh() + { + Commands.Clear(); + foreach (var command in _store.GetAll()) + { + Commands.Add(command); + } + } + + partial void OnSelectedCommandChanged(UserCommand? value) + { + if (value is null) + { + return; + } + + _editingId = value.Id; + EditName = value.Name; + EditExecutable = value.Executable; + EditArguments = value.Arguments; + } + + [RelayCommand] + private void New() + { + SelectedCommand = null; + _editingId = null; + EditName = string.Empty; + EditExecutable = string.Empty; + EditArguments = string.Empty; + } + + [RelayCommand(CanExecute = nameof(CanSave))] + private void Save() + { + var name = EditName.Trim(); + var executable = EditExecutable.Trim(); + if (name.Length == 0 || executable.Length == 0) + { + return; + } + + var id = _editingId ?? Guid.NewGuid().ToString("N"); + _store.Save(new UserCommand { Id = id, Name = name, Executable = executable, Arguments = EditArguments.Trim() }); + _editingId = id; + Refresh(); + SelectedCommand = Commands.FirstOrDefault(c => string.Equals(c.Id, id, StringComparison.Ordinal)); + } + + private bool CanSave() => !string.IsNullOrWhiteSpace(EditName) && !string.IsNullOrWhiteSpace(EditExecutable); + + [RelayCommand(CanExecute = nameof(HasSelected))] + private void Delete() + { + if (SelectedCommand is not { } command) + { + return; + } + + if (MessageBox.Show( + string.Format(CultureInfo.CurrentCulture, Strings.Get("UserCmd_DeleteConfirm"), command.Name), + Strings.Get("UserCmd_Delete"), + MessageBoxButton.YesNo, + MessageBoxImage.Warning) != MessageBoxResult.Yes) + { + return; + } + + _store.Delete(command.Id); + New(); + Refresh(); + } + + private bool HasSelected() => SelectedCommand is not null; + + [RelayCommand(CanExecute = nameof(CanRun))] + private async Task RunAsync() + { + var executable = EditExecutable.Trim(); + if (executable.Length == 0 || _execution.IsRunning) + { + return; + } + + var userCommand = new UserCommand + { + Id = _editingId ?? "unsaved", + Name = string.IsNullOrWhiteSpace(EditName) ? executable : EditName.Trim(), + Executable = executable, + Arguments = EditArguments.Trim(), + }; + + // Transparency (Security.md §3): show the exact command line, and that it runs without admin. + var commandLine = string.IsNullOrEmpty(userCommand.Arguments) + ? executable + : executable + " " + userCommand.Arguments; + if (MessageBox.Show( + string.Format(CultureInfo.CurrentCulture, Strings.Get("UserCmd_RunConfirm"), commandLine), + Strings.Get("UserCmd_RunTitle"), + MessageBoxButton.YesNo, + MessageBoxImage.Warning) != MessageBoxResult.Yes) + { + return; + } + + // SAFETY: ToDefinition forces RequiresAdmin = false → runs asInvoker, never via the broker. + await _execution.RunAsync(UserCommandFactory.ToDefinition(userCommand)); + } + + private bool CanRun() => !string.IsNullOrWhiteSpace(EditExecutable) && !_execution.IsRunning; +} diff --git a/src/CommandForge.Wpf/Views/MainWindow.xaml b/src/CommandForge.Wpf/Views/MainWindow.xaml index 35566c9..48b4743 100644 --- a/src/CommandForge.Wpf/Views/MainWindow.xaml +++ b/src/CommandForge.Wpf/Views/MainWindow.xaml @@ -32,6 +32,9 @@ + + + @@ -73,6 +76,7 @@ + + +