using System.IO; using System.Text.RegularExpressions; namespace Moli.Desktop.Plugins; public sealed partial class PluginManifestValidator : IPluginManifestValidator { public PluginManifestValidationResult Validate(string pluginDirectory, PluginManifest manifest) { if (!IdPattern().IsMatch(manifest.Id)) { return PluginManifestValidationResult.Failure("PluginIdInvalid", "Plugin id must be 3-64 characters and use letters, numbers, dot, underscore or dash."); } if (string.IsNullOrWhiteSpace(manifest.Name) || manifest.Name.Length > 80) { return PluginManifestValidationResult.Failure("PluginNameInvalid", "Plugin name length must be between 1 and 80."); } if (!SemVerPattern().IsMatch(manifest.Version)) { return PluginManifestValidationResult.Failure("PluginVersionInvalid", "Plugin version must be SemVer-like, for example 1.0.0."); } if (string.IsNullOrWhiteSpace(manifest.Entry)) { return PluginManifestValidationResult.Failure("PluginEntryMissing", "Plugin entry is required."); } if (!ValidateDefaultLayout(manifest.DefaultLayout, out var layoutError)) { return PluginManifestValidationResult.Failure("PluginDefaultLayoutInvalid", layoutError); } if (Uri.TryCreate(manifest.Entry, UriKind.Absolute, out var remoteUri) && (remoteUri.Scheme == Uri.UriSchemeHttp || remoteUri.Scheme == Uri.UriSchemeHttps)) { return PluginManifestValidationResult.Success(remoteUri, isRemoteEntry: true); } var root = Path.GetFullPath(pluginDirectory); var entryPath = Path.GetFullPath(Path.Combine(root, manifest.Entry)); if (!entryPath.StartsWith(root + Path.DirectorySeparatorChar, StringComparison.OrdinalIgnoreCase) && !string.Equals(entryPath, root, StringComparison.OrdinalIgnoreCase)) { return PluginManifestValidationResult.Failure("PluginEntryOutOfRoot", "Plugin entry must stay inside the plugin directory."); } if (!File.Exists(entryPath)) { return PluginManifestValidationResult.Failure("PluginEntryMissing", "Plugin entry file does not exist."); } return PluginManifestValidationResult.Success(new Uri(entryPath), isRemoteEntry: false); } private static bool ValidateDefaultLayout(PluginDefaultLayout layout, out string error) { if (layout.Width is < 80 or > 3840) { error = "defaultLayout.width must be between 80 and 3840."; return false; } if (layout.Height is < 40 or > 2160) { error = "defaultLayout.height must be between 40 and 2160."; return false; } if (layout.Opacity is < 0.1 or > 1) { error = "defaultLayout.opacity must be between 0.1 and 1.0."; return false; } if (layout.Scale is < 0.5 or > 3) { error = "defaultLayout.scale must be between 0.5 and 3.0."; return false; } error = ""; return true; } [GeneratedRegex("^[a-zA-Z0-9][a-zA-Z0-9._-]{2,63}$")] private static partial Regex IdPattern(); [GeneratedRegex(@"^\d+\.\d+\.\d+(?:[-+][0-9A-Za-z.-]+)?$")] private static partial Regex SemVerPattern(); }