diff --git a/src/Lumina.Presentation.Web/Common/DTO/Configuration/ThemeEngineOptionsDto.cs b/src/Lumina.Presentation.Web/Common/DTO/Configuration/ThemeEngineOptionsDto.cs new file mode 100644 index 00000000..4d32856f --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/DTO/Configuration/ThemeEngineOptionsDto.cs @@ -0,0 +1,54 @@ +#region ========================================================================= USING ===================================================================================== +using System.Diagnostics; +#endregion + +namespace Lumina.Presentation.Web.Common.DTO.Configuration; + +/// +/// Data transfer object for deserializing theme engine settings. +/// +[DebuggerDisplay("Section name: {SECTION_NAME}")] +public sealed class ThemeEngineOptionsDto +{ + public const string SECTION_NAME = "ThemeEngine"; + + /// + /// Gets or sets the directory where installed theme packages are stored. + /// + public string StoragePath { get; set; } = "Themes"; + + /// + /// Gets or sets the file name of the persisted theme settings. + /// + public string SettingsPath { get; set; } = "theme-settings.json"; + + /// + /// Gets or sets the identifier of the theme selected when no valid current theme is persisted. + /// + public string DefaultThemeId { get; set; } = "lumina-default"; + + /// + /// Gets or sets the maximum allowed size of an uploaded theme archive, in bytes. + /// + public long MaxArchiveBytes { get; set; } = 8 * 1024 * 1024; + + /// + /// Gets or sets the maximum allowed total size of an extracted theme archive, in bytes. + /// + public long MaxExpandedBytes { get; set; } = 24 * 1024 * 1024; + + /// + /// Gets or sets the maximum allowed size of a single file within a theme archive, in bytes. + /// + public long MaxSingleFileBytes { get; set; } = 6 * 1024 * 1024; + + /// + /// Gets or sets the maximum allowed number of entries in a theme archive. + /// + public int MaxEntries { get; set; } = 250; + + /// + /// Gets or sets a value indicating whether theme templates may load script files. + /// + public bool AllowThemeScripts { get; set; } +} diff --git a/src/Lumina.Presentation.Web/Common/DTO/Themes/ContentItemDto.cs b/src/Lumina.Presentation.Web/Common/DTO/Themes/ContentItemDto.cs new file mode 100644 index 00000000..01bbaab2 --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/DTO/Themes/ContentItemDto.cs @@ -0,0 +1,28 @@ +#region ========================================================================= USING ===================================================================================== +using System.Diagnostics; +#endregion + +namespace Lumina.Presentation.Web.Common.DTO.Themes; + +/// +/// Data transfer object for a content entry rendered by a theme. +/// +/// The ordering number of the content entry. +/// The title of the content entry. +/// The description of the content entry. +/// The metadata line of the content entry. +/// The badge text of the content entry. +/// The accent color of the content entry. +/// The glyph or icon of the content entry. +/// The URL the content entry links to. +[DebuggerDisplay("Number: {Number}, Title: {Title}")] +public sealed record ContentItemDto( + string Number, + string Title, + string Description, + string Meta, + string Badge, + string Accent, + string Glyph, + string Url +); diff --git a/src/Lumina.Presentation.Web/Common/DTO/Themes/InstalledThemeDto.cs b/src/Lumina.Presentation.Web/Common/DTO/Themes/InstalledThemeDto.cs new file mode 100644 index 00000000..257f3ff9 --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/DTO/Themes/InstalledThemeDto.cs @@ -0,0 +1,18 @@ +#region ========================================================================= USING ===================================================================================== +using System.Diagnostics; +#endregion + +namespace Lumina.Presentation.Web.Common.DTO.Themes; + +/// +/// Data transfer object for an installed theme. +/// +/// The validated theme manifest. +/// The display metadata of the theme. +/// The absolute path of the installed theme directory. +[DebuggerDisplay("Manifest name: {Manifest.Name}")] +public sealed record InstalledThemeDto( + ThemeManifestDto Manifest, + ThemeInfoDto Info, + string RootPath +); diff --git a/src/Lumina.Presentation.Web/Common/DTO/Themes/NavigationItemDto.cs b/src/Lumina.Presentation.Web/Common/DTO/Themes/NavigationItemDto.cs new file mode 100644 index 00000000..fef38268 --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/DTO/Themes/NavigationItemDto.cs @@ -0,0 +1,20 @@ +#region ========================================================================= USING ===================================================================================== +using System.Diagnostics; +#endregion + +namespace Lumina.Presentation.Web.Common.DTO.Themes; + +/// +/// Data transfer object for a navigation entry rendered by a theme. +/// +/// The unique key of the navigation entry. +/// The display label of the navigation entry. +/// The URL the navigation entry links to. +/// Whether the navigation entry represents the currently displayed page. +[DebuggerDisplay("Key: {Key}, Label: {Label}")] +public sealed record NavigationItemDto( + string Key, + string Label, + string Url, + bool IsCurrent +); diff --git a/src/Lumina.Presentation.Web/Common/DTO/Themes/PersistedThemeSettingsDto.cs b/src/Lumina.Presentation.Web/Common/DTO/Themes/PersistedThemeSettingsDto.cs new file mode 100644 index 00000000..d9d84f2d --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/DTO/Themes/PersistedThemeSettingsDto.cs @@ -0,0 +1,17 @@ +#region ========================================================================= USING ===================================================================================== +using System.Diagnostics; +#endregion + +namespace Lumina.Presentation.Web.Common.DTO.Themes; + +/// +/// Data transfer object for the settings persisted for the theme engine. +/// +[DebuggerDisplay("CurrentThemeId: {CurrentThemeId}")] +public sealed class PersistedThemeSettingsDto +{ + /// + /// Gets or sets the unique identifier of the currently selected theme. + /// + public string CurrentThemeId { get; set; } = string.Empty; +} diff --git a/src/Lumina.Presentation.Web/Common/DTO/Themes/StatItemDto.cs b/src/Lumina.Presentation.Web/Common/DTO/Themes/StatItemDto.cs new file mode 100644 index 00000000..380039a6 --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/DTO/Themes/StatItemDto.cs @@ -0,0 +1,18 @@ +#region ========================================================================= USING ===================================================================================== +using System.Diagnostics; +#endregion + +namespace Lumina.Presentation.Web.Common.DTO.Themes; + +/// +/// Data transfer object for a statistic rendered by a theme. +/// +/// The numeric or textual value of the statistic. +/// The label of the statistic. +/// The additional detail of the statistic. +[DebuggerDisplay("Value: {Value}, Label: {Label}")] +public sealed record StatItemDto( + string Value, + string Label, + string Detail +); diff --git a/src/Lumina.Presentation.Web/Common/DTO/Themes/ThemeAdminDto.cs b/src/Lumina.Presentation.Web/Common/DTO/Themes/ThemeAdminDto.cs new file mode 100644 index 00000000..fd24c2b4 --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/DTO/Themes/ThemeAdminDto.cs @@ -0,0 +1,39 @@ +#region ========================================================================= USING ===================================================================================== +using System; +using System.Collections.Generic; +using System.Diagnostics; +#endregion + +namespace Lumina.Presentation.Web.Common.DTO.Themes; + +/// +/// Data transfer object for the data shown on the theme administration page. +/// +[DebuggerDisplay("CurrentThemeId: {CurrentThemeId}")] +public sealed class ThemeAdminDto +{ + /// + /// Gets or sets the metadata of all installed themes. + /// + public required IReadOnlyList Themes { get; init; } + + /// + /// Gets or sets the unique identifier of the currently selected theme. + /// + public required string CurrentThemeId { get; init; } + + /// + /// Gets or sets a value indicating whether theme templates may load script files. + /// + public required bool AllowThemeScripts { get; init; } + + /// + /// Gets or sets the maximum allowed size of a theme archive, in bytes. + /// + public required long MaxArchiveBytes { get; init; } + + /// + /// Gets the maximum allowed size of a theme archive, in megabytes. + /// + public double MaxArchiveMegabytes => Math.Round(MaxArchiveBytes / 1024d / 1024d, 1); +} diff --git a/src/Lumina.Presentation.Web/Common/DTO/Themes/ThemeArchiveDto.cs b/src/Lumina.Presentation.Web/Common/DTO/Themes/ThemeArchiveDto.cs new file mode 100644 index 00000000..7434c559 --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/DTO/Themes/ThemeArchiveDto.cs @@ -0,0 +1,17 @@ +#region ========================================================================= USING ===================================================================================== +using System.Diagnostics; +using System.IO; +#endregion + +namespace Lumina.Presentation.Web.Common.DTO.Themes; + +/// +/// Data transfer object for an in-memory ZIP archive of an installed theme. +/// +/// The file name to expose when downloading the archive. +/// The ZIP archive stream positioned at its start. +[DebuggerDisplay("FileName: {FileName}")] +public sealed record ThemeArchiveDto( + string FileName, + Stream Content +); diff --git a/src/Lumina.Presentation.Web/Common/DTO/Themes/ThemeInfoDto.cs b/src/Lumina.Presentation.Web/Common/DTO/Themes/ThemeInfoDto.cs new file mode 100644 index 00000000..3303271a --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/DTO/Themes/ThemeInfoDto.cs @@ -0,0 +1,26 @@ +#region ========================================================================= USING ===================================================================================== +using System.Diagnostics; +#endregion + +namespace Lumina.Presentation.Web.Common.DTO.Themes; + +/// +/// Data transfer object for the display metadata of a theme. +/// +/// The unique identifier of the theme. +/// The display name of the theme. +/// The description of the theme. +/// The author of the theme. +/// The version of the theme, using semantic version form. +/// The URL of the theme preview image. +/// Whether the theme ships with the application or noy. +[DebuggerDisplay("Id: {Id}, Name: {Name}")] +public sealed record ThemeInfoDto( + string Id, + string Name, + string Description, + string Author, + string Version, + string PreviewUrl, + bool IsBundled +); diff --git a/src/Lumina.Presentation.Web/Common/DTO/Themes/ThemeInstallationMetadataDto.cs b/src/Lumina.Presentation.Web/Common/DTO/Themes/ThemeInstallationMetadataDto.cs new file mode 100644 index 00000000..22338ad5 --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/DTO/Themes/ThemeInstallationMetadataDto.cs @@ -0,0 +1,24 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.Enums.Themes; +using System; +using System.Diagnostics; +#endregion + +namespace Lumina.Presentation.Web.Common.DTO.Themes; + +/// +/// Data transfer object for the metadata persisted alongside an installed theme. +/// +[DebuggerDisplay("Source: {Source}")] +public sealed class ThemeInstallationMetadataDto +{ + /// + /// Gets or sets the source the theme was installed from. + /// + public ThemeInstallSource Source { get; set; } + + /// + /// Gets or sets the UTC timestamp at which the theme was installed. + /// + public DateTimeOffset InstalledAtUtc { get; set; } +} diff --git a/src/Lumina.Presentation.Web/Common/DTO/Themes/ThemeManifestDto.cs b/src/Lumina.Presentation.Web/Common/DTO/Themes/ThemeManifestDto.cs new file mode 100644 index 00000000..1e2f2b48 --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/DTO/Themes/ThemeManifestDto.cs @@ -0,0 +1,54 @@ +#region ========================================================================= USING ===================================================================================== +using System; +using System.Collections.Generic; +using System.Diagnostics; +#endregion + +namespace Lumina.Presentation.Web.Common.DTO.Themes; + +/// +/// Data transfer object for the theme.json manifest of a theme package. +/// +[DebuggerDisplay("Id: {Id}, Name: {Name}")] +public sealed class ThemeManifestDto +{ + /// + /// Gets or sets the supported schema version of the manifest. + /// + public int SchemaVersion { get; set; } + + /// + /// Gets or sets the unique identifier of the theme, a lowercase kebab-case value. + /// + public string Id { get; set; } = string.Empty; + + /// + /// Gets or sets the display name of the theme. + /// + public string Name { get; set; } = string.Empty; + + /// + /// Gets or sets the description of the theme. + /// + public string Description { get; set; } = string.Empty; + + /// + /// Gets or sets the author of the theme. + /// + public string Author { get; set; } = string.Empty; + + /// + /// Gets or sets the version of the theme, using semantic version form. + /// + public string Version { get; set; } = string.Empty; + + /// + /// Gets or sets the preview image path relative to the theme package root, or when the theme has no preview. + /// + public string? Preview { get; set; } + + /// + /// Gets or sets the template mappings from template key to an HTML file path under templates/. + /// + public Dictionary Templates { get; set; } = new(StringComparer.OrdinalIgnoreCase); +} diff --git a/src/Lumina.Presentation.Web/Common/DTO/Themes/ThemePageDto.cs b/src/Lumina.Presentation.Web/Common/DTO/Themes/ThemePageDto.cs new file mode 100644 index 00000000..6c3d3113 --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/DTO/Themes/ThemePageDto.cs @@ -0,0 +1,103 @@ +#region ========================================================================= USING ===================================================================================== +using System.Collections.Generic; +using System.Diagnostics; +#endregion + +namespace Lumina.Presentation.Web.Common.DTO.Themes; + +/// +/// Data transfer object for the full model available to a theme template while rendering a page. +/// +[DebuggerDisplay("Title: {Title}")] +public sealed class ThemePageDto +{ + /// + /// Gets or sets the key of the page, used to select the template to render. + /// + public required string PageKey { get; init; } + + /// + /// Gets or sets the name of the site displayed by the theme. + /// + public required string SiteName { get; init; } + + /// + /// Gets or sets the title of the page. + /// + public required string Title { get; init; } + + /// + /// Gets or sets the description of the page. + /// + public required string Description { get; init; } + + /// + /// Gets or sets the eyebrow text shown above the page title. + /// + public required string Eyebrow { get; init; } + + /// + /// Gets or sets the label of the primary call to action. + /// + public required string PrimaryActionLabel { get; init; } + + /// + /// Gets or sets the URL of the primary call to action. + /// + public required string PrimaryActionUrl { get; init; } + + /// + /// Gets or sets the label of the secondary call to action. + /// + public required string SecondaryActionLabel { get; init; } + + /// + /// Gets or sets the URL of the secondary call to action. + /// + public required string SecondaryActionUrl { get; init; } + + /// + /// Gets or sets the navigation entries rendered by the theme. + /// + public required IReadOnlyList Navigation { get; init; } + + /// + /// Gets or sets the content entries rendered by the theme. + /// + public required IReadOnlyList Items { get; init; } + + /// + /// Gets or sets the statistics rendered by the theme. + /// + public required IReadOnlyList Stats { get; init; } + + /// + /// Gets or sets a value indicating whether the page is a theme preview. + /// + public bool IsPreview { get; init; } + + /// + /// Gets or sets the identifier of the theme rendering the page. Populated immediately before rendering. + /// + public string ThemeId { get; set; } = string.Empty; + + /// + /// Gets or sets the name of the theme rendering the page. Populated immediately before rendering. + /// + public string ThemeName { get; set; } = string.Empty; + + /// + /// Gets or sets the version of the theme rendering the page. Populated immediately before rendering. + /// + public string ThemeVersion { get; set; } = string.Empty; + + /// + /// Gets or sets the base URL of the theme assets. Populated immediately before rendering. + /// + public string AssetBase { get; set; } = string.Empty; + + /// + /// Gets or sets the current year. Populated immediately before rendering. + /// + public int CurrentYear { get; set; } +} diff --git a/src/Lumina.Presentation.Web/Common/DTO/Themes/ThemeRenderDocumentDto.cs b/src/Lumina.Presentation.Web/Common/DTO/Themes/ThemeRenderDocumentDto.cs new file mode 100644 index 00000000..2a153aa9 --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/DTO/Themes/ThemeRenderDocumentDto.cs @@ -0,0 +1,16 @@ +#region ========================================================================= USING ===================================================================================== +using System.Diagnostics; +#endregion + +namespace Lumina.Presentation.Web.Common.DTO.Themes; + +/// +/// Data transfer object for a rendered document. +/// +/// The metadata of the resolved theme. +/// The raw template source to render. +[DebuggerDisplay("Theme name: {Theme.Name}")] +public sealed record ThemeRenderDocumentDto( + ThemeInfoDto Theme, + string Template +); diff --git a/src/Lumina.Presentation.Web/Common/DTO/Themes/ThemeRenderScopeDto.cs b/src/Lumina.Presentation.Web/Common/DTO/Themes/ThemeRenderScopeDto.cs new file mode 100644 index 00000000..108f9112 --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/DTO/Themes/ThemeRenderScopeDto.cs @@ -0,0 +1,16 @@ +#region ========================================================================= USING ===================================================================================== +using System.Diagnostics; +#endregion + +namespace Lumina.Presentation.Web.Common.DTO.Themes; + +/// +/// Data transfer object for the model resolution context used while rendering a theme template. +/// +/// The model value this scope resolves expressions against. +/// The parent scope, or for the root scope. +[DebuggerDisplay("Value: {Value}")] +public sealed record ThemeRenderScopeDto( + object? Value, + ThemeRenderScopeDto? Parent +); diff --git a/src/Lumina.Presentation.Web/Common/DTO/Themes/ThemeSectionNodeDto.cs b/src/Lumina.Presentation.Web/Common/DTO/Themes/ThemeSectionNodeDto.cs new file mode 100644 index 00000000..7fbc3876 --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/DTO/Themes/ThemeSectionNodeDto.cs @@ -0,0 +1,19 @@ +#region ========================================================================= USING ===================================================================================== +using System.Collections.Generic; +using System.Diagnostics; +#endregion + +namespace Lumina.Presentation.Web.Common.DTO.Themes; + +/// +/// Data transfer object for a conditional or repeating section in a theme template. +/// +/// The property path expression that controls the section. +/// Whether the section renders when the resolved value is falsy instead of truthy. +/// The template nodes rendered when the section is active. +[DebuggerDisplay("Expression: {Expression}")] +public sealed record ThemeSectionNodeDto( + string Expression, + bool Inverted, + IReadOnlyList Children +) : ThemeTemplateNodeDto; diff --git a/src/Lumina.Presentation.Web/Common/DTO/Themes/ThemeTemplateNodeDto.cs b/src/Lumina.Presentation.Web/Common/DTO/Themes/ThemeTemplateNodeDto.cs new file mode 100644 index 00000000..46d93183 --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/DTO/Themes/ThemeTemplateNodeDto.cs @@ -0,0 +1,6 @@ +namespace Lumina.Presentation.Web.Common.DTO.Themes; + +/// +/// Base type for all nodes of a parsed theme template. +/// +public abstract record ThemeTemplateNodeDto; diff --git a/src/Lumina.Presentation.Web/Common/DTO/Themes/ThemeTextNodeDto.cs b/src/Lumina.Presentation.Web/Common/DTO/Themes/ThemeTextNodeDto.cs new file mode 100644 index 00000000..76b5a452 --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/DTO/Themes/ThemeTextNodeDto.cs @@ -0,0 +1,14 @@ +#region ========================================================================= USING ===================================================================================== +using System.Diagnostics; +#endregion + +namespace Lumina.Presentation.Web.Common.DTO.Themes; + +/// +/// Data transfer object for a literal text segment of a theme template. +/// +/// The literal text to render as-is. +[DebuggerDisplay("Value: {Value}")] +public sealed record ThemeTextNodeDto( + string Value +) : ThemeTemplateNodeDto; diff --git a/src/Lumina.Presentation.Web/Common/DTO/Themes/ThemeVariableNodeDto.cs b/src/Lumina.Presentation.Web/Common/DTO/Themes/ThemeVariableNodeDto.cs new file mode 100644 index 00000000..aa725e1d --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/DTO/Themes/ThemeVariableNodeDto.cs @@ -0,0 +1,16 @@ +#region ========================================================================= USING ===================================================================================== +using System.Diagnostics; +#endregion + +namespace Lumina.Presentation.Web.Common.DTO.Themes; + +/// +/// Data transfer object for a variable expression in a theme template. +/// +/// The property path expression to resolve. +/// Whether the rendered value should be HTML encoded. +[DebuggerDisplay("Expression: {Expression}")] +public sealed record ThemeVariableNodeDto( + string Expression, + bool ShouldBeEscaped +) : ThemeTemplateNodeDto; diff --git a/src/Lumina.Presentation.Web/Common/DependencyInjection/PresentationWebLayerConfiguration.cs b/src/Lumina.Presentation.Web/Common/DependencyInjection/PresentationWebLayerConfiguration.cs index 8bea5b86..bd397d21 100644 --- a/src/Lumina.Presentation.Web/Common/DependencyInjection/PresentationWebLayerConfiguration.cs +++ b/src/Lumina.Presentation.Web/Common/DependencyInjection/PresentationWebLayerConfiguration.cs @@ -36,6 +36,11 @@ internal static class PresentationWebLayerConfiguration .ValidateFluently() .ValidateOnStart(); + serviceCollection.AddOptions() + .Bind(configuration.GetRequiredSection(ThemeEngineOptionsDto.SECTION_NAME)) + .ValidateFluently() + .ValidateOnStart(); + return serviceCollection; } } diff --git a/src/Lumina.Presentation.Web/Common/DependencyInjection/PresentationWebLayerServices.cs b/src/Lumina.Presentation.Web/Common/DependencyInjection/PresentationWebLayerServices.cs index 70f1f3ee..4a5a04a5 100644 --- a/src/Lumina.Presentation.Web/Common/DependencyInjection/PresentationWebLayerServices.cs +++ b/src/Lumina.Presentation.Web/Common/DependencyInjection/PresentationWebLayerServices.cs @@ -10,6 +10,7 @@ using Lumina.Presentation.Web.Common.Localization; using Lumina.Presentation.Web.Common.Security; using Lumina.Presentation.Web.Common.Services; using Lumina.Presentation.Web.Common.Validation; +using Lumina.Presentation.Web.Core.Themes; using Microsoft.AspNetCore.Authentication.Cookies; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Builder; @@ -300,6 +301,11 @@ public static class PresentationWebLayerServices services.AddHttpContextAccessor(); services.Configure(options => options.MultipartBodyLengthLimit = 10 * 1024 * 1024); + services.AddSingleton(); + services.AddSingleton(); + services.AddSingleton(); + services.AddSingleton(); + services.AddScoped(); services.AddScoped(); services.AddScoped(); diff --git a/src/Lumina.Presentation.Web/Common/Enums/Themes/ThemeInstallSource.cs b/src/Lumina.Presentation.Web/Common/Enums/Themes/ThemeInstallSource.cs new file mode 100644 index 00000000..0423b673 --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/Enums/Themes/ThemeInstallSource.cs @@ -0,0 +1,17 @@ +namespace Lumina.Presentation.Web.Common.Enums.Themes; + +/// +/// Enumeration for the source a theme was installed from. +/// +public enum ThemeInstallSource +{ + /// + /// The theme was uploaded by a user. + /// + Uploaded, + + /// + /// The theme is bundled with the application. + /// + Bundled +} diff --git a/src/Lumina.Presentation.Web/Common/Validators/ThemeEngineOptionsDtoValidator.cs b/src/Lumina.Presentation.Web/Common/Validators/ThemeEngineOptionsDtoValidator.cs new file mode 100644 index 00000000..5d1b8274 --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/Validators/ThemeEngineOptionsDtoValidator.cs @@ -0,0 +1,48 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.DTO.Configuration; +using Lumina.Presentation.Web.Common.Primitives; +using Lumina.Presentation.Web.Common.Utilities; +using Lumina.Presentation.Web.Common.Validation; +#endregion + +namespace Lumina.Presentation.Web.Common.Validators; + +/// +/// Validates the needed validation rules for the ThemeEngine application configuration settings section. +/// +public class ThemeEngineOptionsDtoValidator : AbstractValidator +{ + /// + /// Initializes a new instance of the class. + /// + public ThemeEngineOptionsDtoValidator() + { + RuleFor(themeEngineOptions => themeEngineOptions.StoragePath) + .NotEmpty() + .WithError(Error.Validation(description: "Theme storage path cannot be empty!")); + + RuleFor(themeEngineOptions => themeEngineOptions.SettingsPath) + .NotEmpty() + .WithError(Error.Validation(description: "Theme settings path cannot be empty!")); + + RuleFor(themeEngineOptions => themeEngineOptions.DefaultThemeId) + .NotEmpty() + .WithError(Error.Validation(description: "Default theme Id cannot be empty!")); + + RuleFor(themeEngineOptions => themeEngineOptions.MaxArchiveBytes) + .GreaterThan(0) + .WithError(Error.Validation(description: "Maximum archive size must be greater than 0!")); + + RuleFor(themeEngineOptions => themeEngineOptions.MaxExpandedBytes) + .GreaterThan(0) + .WithError(Error.Validation(description: "Maximum expanded size must be greater than 0!")); + + RuleFor(themeEngineOptions => themeEngineOptions.MaxSingleFileBytes) + .GreaterThan(0) + .WithError(Error.Validation(description: "Maximum single file size must be greater than 0!")); + + RuleFor(themeEngineOptions => themeEngineOptions.MaxEntries) + .GreaterThan(0) + .WithError(Error.Validation(description: "Maximum entries count must be greater than 0!")); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Themes/ThemePageRenderer.cs b/src/Lumina.Presentation.Web/Core/Themes/ThemePageRenderer.cs new file mode 100644 index 00000000..a9031382 --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Themes/ThemePageRenderer.cs @@ -0,0 +1,53 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.DTO.Themes; +using Lumina.Presentation.Web.Common.Primitives; +using System; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.Core.Themes; + +/// +/// Renders a theme template against a page model, populating the theme metadata before rendering. +/// +public sealed class ThemePageRenderer +{ + private readonly ThemeService _themeService; + private readonly ThemeTemplateEngine _templateEngine; + + /// + /// Initializes a new instance of the class. + /// + /// The service that resolves the render document. + /// The template engine used to render the document. + public ThemePageRenderer(ThemeService themeService, ThemeTemplateEngine templateEngine) + { + _themeService = themeService; + _templateEngine = templateEngine; + } + + /// + /// Renders the page model with the theme selected for the requested theme identifier. + /// + /// The page model to render. + /// The optional unique identifier of the theme to render with, falling back to the current theme when . + /// Cancellation token that can be used to stop the execution. + /// An containing either the rendered HTML, or an error. + public async Task> RenderAsync(ThemePageDto model, string? requestedThemeId = null, CancellationToken cancellationToken = default) + { + Result documentResult = await _themeService.GetRenderDocumentAsync(model.PageKey, requestedThemeId, cancellationToken); + if (documentResult.IsFailure) + return Result.Failure(documentResult.Errors); + + ThemeRenderDocumentDto document = documentResult.Value; + + model.ThemeId = document.Theme.Id; + model.ThemeName = document.Theme.Name; + model.ThemeVersion = document.Theme.Version; + model.AssetBase = $"/theme-assets/{document.Theme.Id}/assets"; + model.CurrentYear = DateTime.UtcNow.Year; + + return _templateEngine.Render(document.Template, model); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Themes/ThemeService.cs b/src/Lumina.Presentation.Web/Core/Themes/ThemeService.cs new file mode 100644 index 00000000..76578d42 --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Themes/ThemeService.cs @@ -0,0 +1,889 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.DTO.Configuration; +using Lumina.Presentation.Web.Common.DTO.Themes; +using Lumina.Presentation.Web.Common.Enums.Themes; +using Lumina.Presentation.Web.Common.Primitives; +using Microsoft.AspNetCore.Hosting; +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Options; +using System; +using System.Collections.Concurrent; +using System.Collections.Generic; +using System.IO; +using System.IO.Compression; +using System.Linq; +using System.Text; +using System.Text.Json; +using System.Text.RegularExpressions; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.Core.Themes; + +/// +/// Manages the installed theme packages: installation, selection, rendering documents and archives. +/// +public sealed class ThemeService +{ + private const string MANIFEST_FILE_NAME = "theme.json"; + private const string INSTALLATION_FILE_NAME = ".theme-install.json"; + private const long MAX_MANIFEST_BYTES = 64 * 1024; + + private static readonly Regex s_themeIdPattern = new( + "^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$", + RegexOptions.Compiled | RegexOptions.CultureInvariant); + + private static readonly Regex s_templateKeyPattern = new( + "^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$", + RegexOptions.Compiled | RegexOptions.CultureInvariant); + + private static readonly Regex s_versionPattern = new( + "^[0-9]+\\.[0-9]+\\.[0-9]+(?:[-+][A-Za-z0-9.-]+)?$", + RegexOptions.Compiled | RegexOptions.CultureInvariant); + + private static readonly Regex s_pathSegmentPattern = new( + "^[A-Za-z0-9][A-Za-z0-9._ -]*$", + RegexOptions.Compiled | RegexOptions.CultureInvariant); + + private static readonly HashSet s_assetExtensions = new(StringComparer.OrdinalIgnoreCase) + { + ".css", ".png", ".jpg", ".jpeg", ".gif", ".webp", ".svg", ".ico", + ".woff", ".woff2", ".ttf" + }; + + private static readonly JsonSerializerOptions s_manifestJsonOptions = new(JsonSerializerDefaults.Web) + { + PropertyNameCaseInsensitive = true, + MaxDepth = 16 + }; + + private static readonly JsonSerializerOptions s_metadataJsonOptions = new(JsonSerializerDefaults.Web) + { + WriteIndented = true + }; + + private readonly ThemeEngineOptionsDto _options; + private readonly ThemeSettingsStore _settingsStore; + private readonly ThemeTemplateEngine _templateEngine; + private readonly ILogger _logger; + private readonly string _contentRoot; + private readonly string _storageRoot; + private readonly string _stagingRoot; + private readonly ConcurrentDictionary _themes = new(StringComparer.OrdinalIgnoreCase); + private readonly SemaphoreSlim _mutationGate = new(1, 1); + private bool _initialized; + + /// + /// Initializes a new instance of the class. + /// + /// The web host environment, used to resolve the content root. + /// The theme engine configuration options. + /// The store that persists the current theme selection. + /// The template engine used to validate installed templates. + /// The logger for this service. + public ThemeService( + IWebHostEnvironment environment, + IOptions options, + ThemeSettingsStore settingsStore, + ThemeTemplateEngine templateEngine, + ILogger logger) + { + _contentRoot = environment.ContentRootPath; + _options = options.Value; + _settingsStore = settingsStore; + _templateEngine = templateEngine; + _logger = logger; + _storageRoot = ResolvePath(_contentRoot, _options.StoragePath); + _stagingRoot = Path.Combine(_storageRoot, ".staging"); + } + + /// + /// Gets a value indicating whether theme templates may load script files. + /// + public bool AllowThemeScripts => _options.AllowThemeScripts; + + /// + /// Gets the maximum allowed size of a theme archive, in bytes. + /// + public long MaxArchiveBytes => _options.MaxArchiveBytes; + + /// + /// Loads the bundled and previously installed themes into memory and selects a valid current theme. + /// + /// Cancellation token that can be used to stop the execution. + /// An representing either a successful operation, or an error. + public async Task> InitializeAsync(CancellationToken cancellationToken = default) + { + await _mutationGate.WaitAsync(cancellationToken); + try + { + if (_initialized) + return Result.Success; + + Directory.CreateDirectory(_storageRoot); + Directory.CreateDirectory(_stagingRoot); + CleanStagingDirectory(); + + string sampleThemeDirectory = Path.Combine(_contentRoot, "SampleThemes"); + if (Directory.Exists(sampleThemeDirectory)) + { + foreach (string? archivePath in Directory.EnumerateFiles(sampleThemeDirectory, "*.zip").OrderBy(path => path, StringComparer.OrdinalIgnoreCase)) + { + await using FileStream archive = File.OpenRead(archivePath); + Result installResult = await InstallCoreAsync(archive, skipIfInstalled: true, source: ThemeInstallSource.Bundled, cancellationToken); + if (installResult.IsFailure) + return Result.Failure(installResult.Errors); + } + } + + foreach (string themeDirectory in Directory.EnumerateDirectories(_storageRoot)) + { + if (Path.GetFileName(themeDirectory).StartsWith('.')) + continue; + + Result loadResult = await LoadInstalledThemeAsync(themeDirectory, cancellationToken); + if (loadResult.IsFailure) + { + _logger.LogWarning("Skipping invalid installed theme directory {ThemeDirectory}. {Error}", themeDirectory, loadResult.FirstError.Description); + continue; + } + + _themes[loadResult.Value.Manifest.Id] = loadResult.Value; + } + + if (_themes.IsEmpty) + return Error.Failure(code: "Theme.NoInstalledThemes", description: "No valid themes are installed. Ensure the SampleThemes archives are present."); + + string? currentThemeId = await _settingsStore.GetCurrentThemeIdAsync(cancellationToken); + if (currentThemeId is null || !_themes.ContainsKey(currentThemeId)) + await EnsureValidCurrentThemeAsync(cancellationToken); + _initialized = true; + return Result.Success; + } + finally + { + _mutationGate.Release(); + } + } + + /// + /// Gets the display metadata of all installed themes. + /// + /// The list of installed theme metadata. + public IReadOnlyList GetThemes() + { + return [.. _themes.Values + .Select(theme => theme.Info) + .OrderByDescending(theme => theme.IsBundled) + .ThenBy(theme => theme.Name, StringComparer.OrdinalIgnoreCase)]; + } + + /// + /// Determines whether a theme with the specified identifier is installed. + /// + /// The theme identifier to look up. + /// true when the theme is installed; otherwise, false. + public bool IsInstalled(string themeId) + { + return !string.IsNullOrWhiteSpace(themeId) && _themes.ContainsKey(themeId); + } + + /// + /// Gets the identifier of the currently selected theme, resolving a valid selection when needed. + /// + /// Cancellation token that can be used to stop the execution. + /// The identifier of the current theme. + public async Task GetCurrentThemeIdAsync(CancellationToken cancellationToken = default) + { + string? current = await _settingsStore.GetCurrentThemeIdAsync(cancellationToken); + if (current is not null && _themes.ContainsKey(current)) + return current; + + return await EnsureValidCurrentThemeAsync(cancellationToken); + } + + /// + /// Selects the theme with the specified identifier as the current theme. + /// + /// The identifier of the theme to select. + /// Cancellation token that can be used to stop the execution. + /// An representing either a successful operation, or an error. + public async Task> SetCurrentThemeAsync(string themeId, CancellationToken cancellationToken = default) + { + if (string.IsNullOrWhiteSpace(themeId) || !_themes.ContainsKey(themeId)) + return ThemeNotFound(themeId); + + await _settingsStore.SetCurrentThemeIdAsync(themeId, cancellationToken); + return Result.Success; + } + + /// + /// Installs a theme from the provided archive. + /// + /// The ZIP archive stream of the theme package. + /// Cancellation token that can be used to stop the execution. + /// An containing either the installed theme metadata, or an error. + public async Task> InstallAsync(Stream archive, CancellationToken cancellationToken = default) + { + await _mutationGate.WaitAsync(cancellationToken); + try + { + Result installedResult = await InstallCoreAsync(archive, skipIfInstalled: false, source: ThemeInstallSource.Uploaded, cancellationToken); + if (installedResult.IsFailure) + return Result.Failure(installedResult.Errors); + + return installedResult.Value.Info; + } + finally + { + _mutationGate.Release(); + } + } + + /// + /// Gets the theme and raw template source selected for a page key. + /// + /// The page key that selects the template to render. + /// The optional theme to render with, falling back to the current theme when null. + /// Cancellation token that can be used to stop the execution. + /// An containing either the render document, or an error. + public async Task> GetRenderDocumentAsync(string pageKey, string? requestedThemeId, CancellationToken cancellationToken = default) + { + InstalledThemeDto installedTheme; + if (!string.IsNullOrWhiteSpace(requestedThemeId)) + { + if (!_themes.TryGetValue(requestedThemeId, out InstalledThemeDto? requestedTheme)) + return ThemeNotFound(requestedThemeId); + + installedTheme = requestedTheme; + } + else + { + string currentThemeId = await GetCurrentThemeIdAsync(cancellationToken); + installedTheme = _themes[currentThemeId]; + } + + if (!installedTheme.Manifest.Templates.TryGetValue(pageKey, out string? templatePath)) + templatePath = installedTheme.Manifest.Templates["default"]; + + Result fullTemplatePathResult = ResolveContainedPath(installedTheme.RootPath, templatePath); + if (fullTemplatePathResult.IsFailure) + return Result.Failure(fullTemplatePathResult.Errors); + + string template = await File.ReadAllTextAsync(fullTemplatePathResult.Value, cancellationToken); + return new ThemeRenderDocumentDto(installedTheme.Info, template); + } + + /// + /// Resolves the absolute path of an allowed theme asset, when it exists. + /// + /// The theme identifier. + /// The asset path relative to the theme package root. + /// The resolved absolute path of the asset, empty when not resolved. + /// true when the asset was resolved; otherwise, false. + public bool TryResolveAsset(string themeId, string assetPath, out string fullPath) + { + fullPath = string.Empty; + if (!_themes.TryGetValue(themeId, out InstalledThemeDto? installedTheme)) + return false; + + Result normalizedPathResult = NormalizeRelativePath(assetPath); + if (normalizedPathResult.IsFailure) + return false; + + string normalizedPath = normalizedPathResult.Value; + if (!normalizedPath.StartsWith("assets/", StringComparison.Ordinal)) + return false; + + string extension = Path.GetExtension(normalizedPath); + if (!IsAllowedAssetExtension(extension)) + return false; + + Result candidateResult = ResolveContainedPath(installedTheme.RootPath, normalizedPath); + if (candidateResult.IsFailure) + return false; + + if (!File.Exists(candidateResult.Value)) + return false; + + fullPath = candidateResult.Value; + return true; + } + + /// + /// Builds a downloadable ZIP archive of an installed theme. + /// + /// The identifier of the theme to archive. + /// Cancellation token that can be used to stop the execution. + /// An containing either the theme archive, or an error. + public async Task> BuildArchiveAsync(string themeId, CancellationToken cancellationToken = default) + { + if (!_themes.TryGetValue(themeId, out InstalledThemeDto? installedTheme)) + return ThemeNotFound(themeId); + + MemoryStream output = new(); + using (ZipArchive archive = new(output, ZipArchiveMode.Create, leaveOpen: true)) + { + foreach (string? filePath in Directory.EnumerateFiles(installedTheme.RootPath, "*", SearchOption.AllDirectories) + .Where(path => !string.Equals(Path.GetFileName(path), INSTALLATION_FILE_NAME, StringComparison.Ordinal)) + .OrderBy(path => path, StringComparer.Ordinal)) + { + string relativePath = Path.GetRelativePath(installedTheme.RootPath, filePath).Replace(Path.DirectorySeparatorChar, '/'); + ZipArchiveEntry entry = archive.CreateEntry(relativePath, CompressionLevel.Optimal); + await using FileStream input = File.OpenRead(filePath); + await using Stream outputStream = entry.Open(); + await input.CopyToAsync(outputStream, cancellationToken); + } + } + + output.Position = 0; + string safeVersion = installedTheme.Manifest.Version.Replace('+', '-'); + return new ThemeArchiveDto($"{installedTheme.Manifest.Id}-{safeVersion}.zip", output); + } + + /// + /// Installs a theme package from an archive stream into the storage root. + /// + /// The ZIP archive stream of the theme package. + /// Whether an already installed theme with the same id is accepted without reinstalling. + /// The source the theme is installed from. + /// Cancellation token that can be used to stop the execution. + /// An containing either the installed theme, or an error. + private async Task> InstallCoreAsync(Stream sourceArchive, bool skipIfInstalled, ThemeInstallSource source, CancellationToken cancellationToken) + { + string workId = Guid.NewGuid().ToString("N"); + string temporaryArchivePath = Path.Combine(_stagingRoot, $"{workId}.zip"); + string extractionPath = Path.Combine(_stagingRoot, workId); + + try + { + Result copyResult = await CopyArchiveWithLimitAsync(sourceArchive, temporaryArchivePath, cancellationToken); + if (copyResult.IsFailure) + return Result.Failure(copyResult.Errors); + + Directory.CreateDirectory(extractionPath); + Result extractResult = await ExtractArchiveAsync(temporaryArchivePath, extractionPath, cancellationToken); + if (extractResult.IsFailure) + return Result.Failure(extractResult.Errors); + + Result stagedResult = await LoadInstalledThemeAsync(extractionPath, cancellationToken, sourceOverride: source); + if (stagedResult.IsFailure) + return Result.Failure(stagedResult.Errors); + + InstalledThemeDto stagedTheme = stagedResult.Value; + string destination = Path.Combine(_storageRoot, stagedTheme.Manifest.Id); + + if (Directory.Exists(destination)) + { + if (!skipIfInstalled) + return Error.Conflict(code: "Theme.AlreadyInstalled", description: $"A theme with id '{stagedTheme.Manifest.Id}' is already installed."); + + Result existingResult = await LoadInstalledThemeAsync(destination, cancellationToken); + if (existingResult.IsFailure) + return Result.Failure(existingResult.Errors); + + _themes[existingResult.Value.Manifest.Id] = existingResult.Value; + return existingResult.Value; + } + + ThemeInstallationMetadataDto metadata = new() + { + Source = source, + InstalledAtUtc = DateTimeOffset.UtcNow + }; + string metadataJson = JsonSerializer.Serialize(metadata, s_metadataJsonOptions); + await File.WriteAllTextAsync(Path.Combine(extractionPath, INSTALLATION_FILE_NAME), metadataJson, new UTF8Encoding(encoderShouldEmitUTF8Identifier: false), cancellationToken); + + Directory.Move(extractionPath, destination); + Result installedResult = await LoadInstalledThemeAsync(destination, cancellationToken); + if (installedResult.IsFailure) + return Result.Failure(installedResult.Errors); + + _themes[installedResult.Value.Manifest.Id] = installedResult.Value; + return installedResult.Value; + } + catch (InvalidDataException exception) + { + _logger.LogWarning(exception, "An uploaded theme archive could not be read."); + return Error.Failure(code: "Theme.Archive.ReadFailed", description: "The uploaded file is not a readable ZIP archive."); + } + finally + { + if (File.Exists(temporaryArchivePath)) + File.Delete(temporaryArchivePath); + + if (Directory.Exists(extractionPath)) + Directory.Delete(extractionPath, recursive: true); + } + } + + /// + /// Copies the source archive to the staging directory while enforcing the maximum archive size. + /// + /// The archive stream to copy. + /// The temporary file to copy the archive into. + /// Cancellation token that can be used to stop the execution. + /// An representing either a successful operation, or an error. + private async Task> CopyArchiveWithLimitAsync(Stream source, string destinationPath, CancellationToken cancellationToken) + { + await using FileStream destination = new(destinationPath, FileMode.CreateNew, FileAccess.Write, FileShare.None, bufferSize: 64 * 1024, useAsync: true); + + byte[] buffer = new byte[64 * 1024]; + long totalBytes = 0; + while (true) + { + int read = await source.ReadAsync(buffer.AsMemory(), cancellationToken); + if (read == 0) + break; + + totalBytes += read; + if (totalBytes > _options.MaxArchiveBytes) + return Error.Validation(code: "Theme.Archive.TooLarge", description: $"The theme archive exceeds the {_options.MaxArchiveBytes / 1024 / 1024} MB limit."); + + await destination.WriteAsync(buffer.AsMemory(0, read), cancellationToken); + } + + if (totalBytes == 0) + return Error.Validation(code: "Theme.Archive.Empty", description: "The uploaded theme archive is empty."); + + return Result.Success; + } + + /// + /// Extracts a staged theme archive into the staging extraction directory after validating its entries. + /// + /// The path of the staged ZIP archive. + /// The directory the archive is extracted into. + /// Cancellation token that can be used to stop the execution. + /// An representing either a successful operation, or an error. + private async Task> ExtractArchiveAsync(string archivePath, string extractionPath, CancellationToken cancellationToken) + { + using ZipArchive archive = ZipFile.OpenRead(archivePath); + if (archive.Entries.Count == 0) + return Error.Validation(code: "Theme.Archive.Empty", description: "The theme archive contains no files."); + + if (archive.Entries.Count > _options.MaxEntries) + return Error.Validation(code: "Theme.Archive.TooManyEntries", description: $"The theme archive contains more than {_options.MaxEntries} entries."); + + HashSet seenPaths = new(StringComparer.OrdinalIgnoreCase); + long expandedBytes = 0; + + foreach (ZipArchiveEntry entry in archive.Entries) + { + cancellationToken.ThrowIfCancellationRequested(); + + int unixFileType = (entry.ExternalAttributes >> 16) & 0xF000; + if (unixFileType == 0xA000) + return PackageInvalid("Symbolic links are not allowed in theme archives."); + + Result normalizedPathResult = NormalizeRelativePath(entry.FullName, allowTrailingSlash: true); + if (normalizedPathResult.IsFailure) + return Result.Failure(normalizedPathResult.Errors); + + string normalizedPath = normalizedPathResult.Value; + if (!seenPaths.Add(normalizedPath)) + return PackageInvalid($"The archive contains a duplicate path: {normalizedPath}"); + + bool isDirectory = entry.FullName.EndsWith('/') || string.IsNullOrEmpty(entry.Name); + if (isDirectory) + { + Result directoryValidationResult = ValidatePackageDirectory(normalizedPath); + if (directoryValidationResult.IsFailure) + return Result.Failure(directoryValidationResult.Errors); + + Result directoryPathResult = ResolveContainedPath(extractionPath, normalizedPath); + if (directoryPathResult.IsFailure) + return Result.Failure(directoryPathResult.Errors); + + Directory.CreateDirectory(directoryPathResult.Value); + continue; + } + + Result fileValidationResult = ValidatePackageFile(normalizedPath); + if (fileValidationResult.IsFailure) + return Result.Failure(fileValidationResult.Errors); + + if (entry.Length > _options.MaxSingleFileBytes) + return Error.Validation(code: "Theme.File.TooLarge", description: $"Theme file '{normalizedPath}' is too large."); + + expandedBytes += entry.Length; + if (expandedBytes > _options.MaxExpandedBytes) + return Error.Validation(code: "Theme.Archive.ExpandedTooLarge", description: "The expanded theme archive is too large."); + + Result outputPathResult = ResolveContainedPath(extractionPath, normalizedPath); + if (outputPathResult.IsFailure) + return Result.Failure(outputPathResult.Errors); + + string outputPath = outputPathResult.Value; + Directory.CreateDirectory(Path.GetDirectoryName(outputPath)!); + + await using Stream input = entry.Open(); + await using FileStream output = new(outputPath, FileMode.CreateNew, FileAccess.Write, FileShare.None, bufferSize: 64 * 1024, useAsync: true); + + byte[] buffer = new byte[64 * 1024]; + long entryBytes = 0; + while (true) + { + int read = await input.ReadAsync(buffer.AsMemory(), cancellationToken); + if (read == 0) + break; + + entryBytes += read; + if (entryBytes > _options.MaxSingleFileBytes) + return Error.Validation(code: "Theme.File.TooLarge", description: $"Theme file '{normalizedPath}' is too large."); + + await output.WriteAsync(buffer.AsMemory(0, read), cancellationToken); + } + } + + if (!File.Exists(Path.Combine(extractionPath, MANIFEST_FILE_NAME))) + return PackageInvalid("The archive must contain theme.json at its root."); + + return Result.Success; + } + + /// + /// Loads and validates the manifest, templates and metadata of an installed theme directory. + /// + /// The absolute path of the installed theme directory. + /// Cancellation token that can be used to stop the execution. + /// The install source to report, overriding the persisted metadata when provided. + /// An containing either the installed theme, or an error. + private async Task> LoadInstalledThemeAsync(string themeRoot, CancellationToken cancellationToken, ThemeInstallSource? sourceOverride = null) + { + string manifestPath = Path.Combine(themeRoot, MANIFEST_FILE_NAME); + if (!File.Exists(manifestPath)) + return PackageInvalid("The theme is missing theme.json."); + + if (new FileInfo(manifestPath).Length > MAX_MANIFEST_BYTES) + return Error.Validation(code: "Theme.Manifest.TooLarge", description: "theme.json exceeds the 64 KB limit."); + + string json; + ThemeManifestDto? manifest; + try + { + json = await File.ReadAllTextAsync(manifestPath, cancellationToken); + manifest = JsonSerializer.Deserialize(json, s_manifestJsonOptions); + } + catch (JsonException) + { + return Error.Validation(code: "Theme.Manifest.InvalidJson", description: "theme.json is not valid JSON."); + } + catch (IOException) + { + return Error.Failure(code: "Theme.Files.Unreadable", description: "The theme files could not be read."); + } + + if (manifest is null) + return Error.Validation(code: "Theme.Manifest.InvalidJson", description: "theme.json contains no manifest object."); + + Result manifestValidationResult = ValidateManifest(themeRoot, manifest); + if (manifestValidationResult.IsFailure) + return Result.Failure(manifestValidationResult.Errors); + + foreach (string templatePath in manifest.Templates.Values.Distinct(StringComparer.Ordinal)) + { + Result fullTemplatePathResult = ResolveContainedPath(themeRoot, templatePath); + if (fullTemplatePathResult.IsFailure) + return Result.Failure(fullTemplatePathResult.Errors); + + try + { + string template = await File.ReadAllTextAsync(fullTemplatePathResult.Value, cancellationToken); + Result templateValidationResult = _templateEngine.Validate(template); + if (templateValidationResult.IsFailure) + return Result.Failure(templateValidationResult.Errors); + } + catch (IOException) + { + return Error.Failure(code: "Theme.Files.Unreadable", description: "The theme files could not be read."); + } + } + + ThemeInstallSource source = sourceOverride ?? await ReadInstallSourceAsync(themeRoot, cancellationToken); + string previewUrl = string.IsNullOrWhiteSpace(manifest.Preview) ? "/admin/theme-placeholder.svg" : $"/theme-assets/{manifest.Id}/{manifest.Preview}"; + ThemeInfoDto info = new(manifest.Id, manifest.Name, manifest.Description, manifest.Author, manifest.Version, previewUrl, source == ThemeInstallSource.Bundled); + + return new InstalledThemeDto(manifest, info, Path.GetFullPath(themeRoot)); + } + + /// + /// Validates the manifest fields and template mappings, normalizing the referenced paths. + /// + /// The absolute path of the theme package root. + /// The manifest to validate. + /// An representing either a successful operation, or an error. + private Result ValidateManifest(string themeRoot, ThemeManifestDto manifest) + { + if (manifest.SchemaVersion != 1) + return PackageInvalid("Only theme schemaVersion 1 is supported."); + + if (manifest.Id is null || !s_themeIdPattern.IsMatch(manifest.Id) || manifest.Id.Length > 64) + return PackageInvalid("Theme id must be a lowercase kebab-case value up to 64 characters."); + + Result nameResult = ValidateText(manifest.Name, "name", 80); + if (nameResult.IsFailure) + return nameResult; + + Result descriptionResult = ValidateText(manifest.Description, "description", 300); + if (descriptionResult.IsFailure) + return descriptionResult; + + Result authorResult = ValidateText(manifest.Author, "author", 80); + if (authorResult.IsFailure) + return authorResult; + + Result versionResult = ValidateText(manifest.Version, "version", 40); + if (versionResult.IsFailure) + return versionResult; + + if (!s_versionPattern.IsMatch(manifest.Version)) + return PackageInvalid("Theme version must use semantic version form, for example 1.0.0."); + + if (manifest.Templates is null || manifest.Templates.Count == 0 || manifest.Templates.Count > 32) + return PackageInvalid("A theme must declare between 1 and 32 templates."); + + Dictionary normalizedTemplates = new(StringComparer.OrdinalIgnoreCase); + foreach ((string key, string path) in manifest.Templates) + { + if (!s_templateKeyPattern.IsMatch(key) || key.Length > 40) + return PackageInvalid($"Template key '{key}' is invalid."); + + Result normalizedPathResult = NormalizeRelativePath(path); + if (normalizedPathResult.IsFailure) + return Result.Failure(normalizedPathResult.Errors); + + string normalizedPath = normalizedPathResult.Value; + if (!normalizedPath.StartsWith("templates/", StringComparison.Ordinal) || !string.Equals(Path.GetExtension(normalizedPath), ".html", StringComparison.OrdinalIgnoreCase)) + return PackageInvalid($"Template '{key}' must point to an HTML file under templates/."); + + Result fullTemplatePathResult = ResolveContainedPath(themeRoot, normalizedPath); + if (fullTemplatePathResult.IsFailure) + return Result.Failure(fullTemplatePathResult.Errors); + + if (!File.Exists(fullTemplatePathResult.Value)) + return PackageInvalid($"Template '{key}' points to missing file '{normalizedPath}'."); + + normalizedTemplates[key] = normalizedPath; + } + + if (!normalizedTemplates.ContainsKey("default")) + return PackageInvalid("The manifest must define a 'default' template fallback."); + + manifest.Templates = normalizedTemplates; + + if (!string.IsNullOrWhiteSpace(manifest.Preview)) + { + Result previewPathResult = NormalizeRelativePath(manifest.Preview); + if (previewPathResult.IsFailure) + return Result.Failure(previewPathResult.Errors); + + string previewPath = previewPathResult.Value; + Result fullPreviewPathResult = ResolveContainedPath(themeRoot, previewPath); + if (fullPreviewPathResult.IsFailure) + return Result.Failure(fullPreviewPathResult.Errors); + + if (!previewPath.StartsWith("assets/", StringComparison.Ordinal) || !IsAllowedAssetExtension(Path.GetExtension(previewPath)) || !File.Exists(fullPreviewPathResult.Value)) + return PackageInvalid("The preview must reference an existing asset file."); + + manifest.Preview = previewPath; + } + + return Result.Success; + } + + /// + /// Reads the persisted install source of a theme directory, defaulting to Uploaded when absent or invalid. + /// + /// The absolute path of the installed theme directory. + /// Cancellation token that can be used to stop the execution. + /// The install source of the theme. + private static async Task ReadInstallSourceAsync(string themeRoot, CancellationToken cancellationToken) + { + string metadataPath = Path.Combine(themeRoot, INSTALLATION_FILE_NAME); + if (!File.Exists(metadataPath)) + return ThemeInstallSource.Uploaded; + + try + { + string json = await File.ReadAllTextAsync(metadataPath, cancellationToken); + return JsonSerializer.Deserialize(json, s_metadataJsonOptions)?.Source ?? ThemeInstallSource.Uploaded; + } + catch (JsonException) + { + return ThemeInstallSource.Uploaded; + } + } + + /// + /// Selects and persists a valid current theme, preferring the configured default theme. + /// + /// Cancellation token that can be used to stop the execution. + /// The identifier of the selected theme. + private async Task EnsureValidCurrentThemeAsync(CancellationToken cancellationToken) + { + string preferred = _options.DefaultThemeId; + string selected = _themes.ContainsKey(preferred) ? preferred : _themes.Values.OrderBy(theme => theme.Info.Name, StringComparer.OrdinalIgnoreCase).First().Manifest.Id; + await _settingsStore.SetCurrentThemeIdAsync(selected, cancellationToken); + return selected; + } + + /// + /// Validates that a package file resides in the manifest, template or asset locations. + /// + /// The normalized package-relative path of the file. + /// An representing either a successful operation, or an error. + private Result ValidatePackageFile(string normalizedPath) + { + if (string.Equals(normalizedPath, MANIFEST_FILE_NAME, StringComparison.Ordinal)) + return Result.Success; + + if (normalizedPath.StartsWith("templates/", StringComparison.Ordinal) && string.Equals(Path.GetExtension(normalizedPath), ".html", StringComparison.OrdinalIgnoreCase)) + return Result.Success; + + if (normalizedPath.StartsWith("assets/", StringComparison.Ordinal) && IsAllowedAssetExtension(Path.GetExtension(normalizedPath))) + return Result.Success; + + return PackageInvalid($"Theme file '{normalizedPath}' is outside the allowed manifest, template, or asset locations."); + } + + /// + /// Validates that a package directory resides under the templates or assets locations. + /// + /// The normalized package-relative path of the directory. + /// An representing either a successful operation, or an error. + private static Result ValidatePackageDirectory(string normalizedPath) + { + if (normalizedPath.Equals("templates", StringComparison.Ordinal) || + normalizedPath.StartsWith("templates/", StringComparison.Ordinal) || + normalizedPath.Equals("assets", StringComparison.Ordinal) || + normalizedPath.StartsWith("assets/", StringComparison.Ordinal)) + return Result.Success; + + return PackageInvalid($"Theme directory '{normalizedPath}' is not allowed."); + } + + /// + /// Determines whether the file extension is an allowed theme asset extension. + /// + /// The file extension, including the leading dot. + /// true when the extension is allowed; otherwise, false. + private bool IsAllowedAssetExtension(string extension) + { + return s_assetExtensions.Contains(extension) || (_options.AllowThemeScripts && string.Equals(extension, ".js", StringComparison.OrdinalIgnoreCase)); + } + + /// + /// Normalizes a package-relative path, rejecting paths that escape the package or violate the path rules. + /// + /// The package-relative path to normalize. + /// Whether a trailing slash, used for directory entries, is permitted. + /// An containing either the normalized path, or an error. + private static Result NormalizeRelativePath(string path, bool allowTrailingSlash = false) + { + if (string.IsNullOrWhiteSpace(path) || path.Length > 240 || path.Contains('\\') || path.Contains('\0') || path.StartsWith('/') || path.Contains("//")) + return PackageInvalid("The theme contains an invalid path."); + + string candidate = allowTrailingSlash ? path.TrimEnd('/') : path; + if (string.IsNullOrWhiteSpace(candidate)) + return PackageInvalid("The theme contains an invalid path."); + + string[] segments = candidate.Split('/'); + if (segments.Length > 12) + return PackageInvalid("A theme path is nested too deeply."); + + foreach (string segment in segments) + if (segment is "." or ".." || segment.Length > 80 || segment.EndsWith(' ') || segment.EndsWith('.') || !s_pathSegmentPattern.IsMatch(segment)) + return PackageInvalid($"Theme path segment '{segment}' is invalid."); + + return string.Join('/', segments); + } + + /// + /// Resolves a package-relative path against a package root, rejecting paths that escape the root. + /// + /// The absolute path of the package root. + /// The package-relative path to resolve. + /// An containing either the absolute path, or an error. + private static Result ResolveContainedPath(string root, string relativePath) + { + string normalized = relativePath.Replace('/', Path.DirectorySeparatorChar); + string rootPath = Path.GetFullPath(root); + string candidate = Path.GetFullPath(Path.Combine(rootPath, normalized)); + string rootWithSeparator = rootPath.EndsWith(Path.DirectorySeparatorChar) ? rootPath : rootPath + Path.DirectorySeparatorChar; + StringComparison comparison = OperatingSystem.IsWindows() ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal; + + if (!candidate.StartsWith(rootWithSeparator, comparison)) + return PackageInvalid("A theme path escapes its package root."); + + return candidate; + } + + /// + /// Validates a manifest text field: required, within the maximum length and without control characters. + /// + /// The field value to validate. + /// The name of the manifest field, used in error messages. + /// The maximum allowed length of the field. + /// An representing either a successful operation, or an error. + private static Result ValidateText(string value, string fieldName, int maxLength) + { + if (string.IsNullOrWhiteSpace(value) || value.Length > maxLength || value.Any(char.IsControl)) + return PackageInvalid($"Theme manifest field '{fieldName}' is required and must be at most {maxLength} characters."); + + return Result.Success; + } + + /// + /// Creates a validation error for an invalid theme package. + /// + /// The human-readable description of the package error. + /// The validation error describing the invalid theme package. + private static Error PackageInvalid(string description) + { + return Error.Validation(code: "Theme.Package.Invalid", description: description); + } + + /// + /// Creates a not found error for a theme identifier that is not installed. + /// + /// The missing theme identifier. + /// The not found error describing the missing theme. + private static Error ThemeNotFound(string themeId) + { + return Error.NotFound(code: "Theme.NotFound", description: $"The theme '{themeId}' is not installed."); + } + + /// + /// Removes stale files and directories left over in the staging directory. + /// + private void CleanStagingDirectory() + { + foreach (string path in Directory.EnumerateFileSystemEntries(_stagingRoot)) + { + try + { + if (Directory.Exists(path)) + Directory.Delete(path, recursive: true); + else + File.Delete(path); + } + catch (IOException exception) + { + _logger.LogDebug(exception, "Could not remove stale theme staging path {StagingPath}.", path); + } + } + } + + /// + /// Resolves a configured path to an absolute path, rooted against the content root when relative. + /// + /// The content root of the application. + /// The path from the configuration. + /// The absolute path. + private static string ResolvePath(string contentRoot, string configuredPath) + { + return Path.GetFullPath(Path.IsPathRooted(configuredPath) ? configuredPath : Path.Combine(contentRoot, configuredPath)); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Themes/ThemeSettingsStore.cs b/src/Lumina.Presentation.Web/Core/Themes/ThemeSettingsStore.cs new file mode 100644 index 00000000..ab5bf1c1 --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Themes/ThemeSettingsStore.cs @@ -0,0 +1,115 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.DTO.Configuration; +using Lumina.Presentation.Web.Common.DTO.Themes; +using Microsoft.AspNetCore.Hosting; +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Options; +using System; +using System.IO; +using System.Text; +using System.Text.Json; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.Core.Themes; + +/// +/// Persists and reads the theme settings file that stores the current theme selection. +/// +public sealed class ThemeSettingsStore +{ + private static readonly JsonSerializerOptions s_jsonOptions = new(JsonSerializerDefaults.Web) + { + WriteIndented = true + }; + + private readonly string _settingsPath; + private readonly ILogger _logger; + private readonly SemaphoreSlim _gate = new(1, 1); + + /// + /// Initializes a new instance of the class. + /// + /// The web host environment, used to resolve the content root. + /// The theme engine configuration options. + /// The logger for this store. + public ThemeSettingsStore(IWebHostEnvironment webHostEnvironment, IOptions themeEngineOptions, ILogger logger) + { + _logger = logger; + _settingsPath = ResolvePath(webHostEnvironment.ContentRootPath, themeEngineOptions.Value.SettingsPath); + } + + /// + /// Reads the unique identifier of the currently selected theme. + /// + /// Cancellation token that can be used to stop the execution. + /// The current theme identifier, or when no selection is persisted. + public async Task GetCurrentThemeIdAsync(CancellationToken cancellationToken = default) + { + await _gate.WaitAsync(cancellationToken); + try + { + if (!File.Exists(_settingsPath)) + return null; + + try + { + string json = await File.ReadAllTextAsync(_settingsPath, cancellationToken); + return JsonSerializer.Deserialize(json, s_jsonOptions)?.CurrentThemeId; + } + catch (JsonException exception) + { + _logger.LogWarning(exception, "Ignoring an invalid theme settings file at {SettingsPath}.", _settingsPath); + return null; + } + } + finally + { + _gate.Release(); + } + } + + /// + /// Persists the unique identifier of the currently selected theme. + /// + /// The theme unique identifier to persist. + /// Cancellation token that can be used to stop the execution. + public async Task SetCurrentThemeIdAsync(string themeId, CancellationToken cancellationToken = default) + { + await _gate.WaitAsync(cancellationToken); + try + { + string? directory = Path.GetDirectoryName(_settingsPath) ?? throw new InvalidOperationException("The theme settings path has no parent directory."); + Directory.CreateDirectory(directory); + + string temporaryPath = Path.Combine(directory, $".theme-settings-{Guid.NewGuid():N}.tmp"); + try + { + string json = JsonSerializer.Serialize(new PersistedThemeSettingsDto { CurrentThemeId = themeId }, s_jsonOptions); + await File.WriteAllTextAsync(temporaryPath, json, new UTF8Encoding(encoderShouldEmitUTF8Identifier: false), cancellationToken); + File.Move(temporaryPath, _settingsPath, overwrite: true); + } + finally + { + if (File.Exists(temporaryPath)) + File.Delete(temporaryPath); + } + } + finally + { + _gate.Release(); + } + } + + /// + /// Resolves a configured path to an absolute path, rooted against the content root when relative. + /// + /// The content root of the application. + /// The path from the configuration. + /// The absolute path. + private static string ResolvePath(string contentRoot, string configuredPath) + { + return Path.GetFullPath(Path.IsPathRooted(configuredPath) ? configuredPath : Path.Combine(contentRoot, configuredPath)); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Themes/ThemeTemplateEngine.cs b/src/Lumina.Presentation.Web/Core/Themes/ThemeTemplateEngine.cs new file mode 100644 index 00000000..a2aae9ce --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Themes/ThemeTemplateEngine.cs @@ -0,0 +1,472 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.DTO.Themes; +using Lumina.Presentation.Web.Common.Primitives; +using System; +using System.Collections.Generic; +using System.Globalization; +using System.Linq; +using System.Reflection; +using System.Text; +using System.Text.Encodings.Web; +using System.Text.RegularExpressions; +#endregion + +namespace Lumina.Presentation.Web.Core.Themes; + +/// +/// A small, non-executable Mustache-style renderer. Theme templates can place values, iterate collections and test truthiness, but cannot execute C#. +/// +public sealed class ThemeTemplateEngine +{ + private const int MAX_NESTING_DEPTH = 32; + private const int MAX_RENDERED_CHARACTERS = 4 * 1024 * 1024; + + private static readonly Regex s_namePartPattern = new( + "^[A-Za-z_][A-Za-z0-9_]*$", + RegexOptions.Compiled | RegexOptions.CultureInvariant); + + /// + /// Validates the structure and expressions of a theme template. + /// + /// The template source to validate. + /// An representing either a successful operation, or an error. + public Result Validate(string template) + { + ArgumentNullException.ThrowIfNull(template); + int cursor = 0; + Result> parseResult = ParseNodes(template, ref cursor, expectedClosingName: null, depth: 0); + if (parseResult.IsFailure) + return Result.Failure(parseResult.Errors); + + return Result.Success; + } + + /// + /// Renders a theme template against the provided model. + /// + /// The template source to render. + /// The model the template expressions resolve against. + /// An containing either the rendered output, or an error. + public Result Render(string template, object model) + { + ArgumentNullException.ThrowIfNull(template); + ArgumentNullException.ThrowIfNull(model); + + int cursor = 0; + Result> parseResult = ParseNodes(template, ref cursor, expectedClosingName: null, depth: 0); + if (parseResult.IsFailure) + return Result.Failure(parseResult.Errors); + + StringBuilder output = new(Math.Min(template.Length * 2, 256 * 1024)); + Result renderResult = RenderNodes(parseResult.Value, new ThemeRenderScopeDto(model, Parent: null), output); + if (renderResult.IsFailure) + return Result.Failure(renderResult.Errors); + + return output.ToString(); + } + + /// + /// Parses a template fragment into template nodes until the closing section or end of the template. + /// + /// The template source to parse. + /// The current position in the template, advanced as nodes are consumed. + /// The name of the section that closes the fragment, or at the top level. + /// The current section nesting depth. + /// An containing either the parsed nodes, or an error. + private static Result> ParseNodes(string template, ref int cursor, string? expectedClosingName, int depth) + { + if (depth > MAX_NESTING_DEPTH) + return TemplateInvalid($"Template sections may not be nested more than {MAX_NESTING_DEPTH} levels."); + + List nodes = []; + while (cursor < template.Length) + { + int opening = template.IndexOf("{{", cursor, StringComparison.Ordinal); + if (opening < 0) + { + if (cursor < template.Length) + nodes.Add(new ThemeTextNodeDto(template[cursor..])); + + cursor = template.Length; + break; + } + + if (opening > cursor) + nodes.Add(new ThemeTextNodeDto(template[cursor..opening])); + + if (template.AsSpan(opening).StartsWith("{{{".AsSpan(), StringComparison.Ordinal)) + { + int closing = template.IndexOf("}}}", opening + 3, StringComparison.Ordinal); + if (closing < 0) + return TemplateInvalid("An unescaped variable tag is not closed."); + + string expression = template[(opening + 3)..closing].Trim(); + Result expressionResult = ValidateExpression(expression); + if (expressionResult.IsFailure) + return Result>.Failure(expressionResult.Errors); + + nodes.Add(new ThemeVariableNodeDto(expression, ShouldBeEscaped: false)); + cursor = closing + 3; + continue; + } + + int tagClosing = template.IndexOf("}}", opening + 2, StringComparison.Ordinal); + if (tagClosing < 0) + return TemplateInvalid("A template tag is not closed."); + + string tag = template[(opening + 2)..tagClosing].Trim(); + cursor = tagClosing + 2; + if (tag.Length == 0) + return TemplateInvalid("Empty template tags are not allowed."); + + switch (tag[0]) + { + case '!': + continue; + case '#': + case '^': + { + string expression = tag[1..].Trim(); + Result sectionExpressionResult = ValidateExpression(expression); + if (sectionExpressionResult.IsFailure) + return Result>.Failure(sectionExpressionResult.Errors); + + Result> childrenResult = ParseNodes(template, ref cursor, expression, depth + 1); + if (childrenResult.IsFailure) + return Result>.Failure(childrenResult.Errors); + + nodes.Add(new ThemeSectionNodeDto(expression, Inverted: tag[0] == '^', Children: childrenResult.Value)); + break; + } + case '/': + { + string closingName = tag[1..].Trim(); + Result closingNameResult = ValidateExpression(closingName); + if (closingNameResult.IsFailure) + return Result>.Failure(closingNameResult.Errors); + + if (expectedClosingName is null) + return TemplateInvalid($"Closing section '{closingName}' has no matching opening section."); + + if (!string.Equals(closingName, expectedClosingName, StringComparison.Ordinal)) + return TemplateInvalid($"Section '{expectedClosingName}' is closed by '{closingName}'."); + + return nodes; + } + case '&': + { + string expression = tag[1..].Trim(); + Result unescapedExpressionResult = ValidateExpression(expression); + if (unescapedExpressionResult.IsFailure) + return Result>.Failure(unescapedExpressionResult.Errors); + + nodes.Add(new ThemeVariableNodeDto(expression, ShouldBeEscaped: false)); + break; + } + default: + { + Result variableResult = ValidateExpression(tag); + if (variableResult.IsFailure) + return Result>.Failure(variableResult.Errors); + + nodes.Add(new ThemeVariableNodeDto(tag, ShouldBeEscaped: true)); + break; + } + } + } + + if (expectedClosingName is not null) + return TemplateInvalid($"Section '{expectedClosingName}' is not closed."); + + return nodes; + } + + /// + /// Renders a list of template nodes into the output. + /// + /// The template nodes to render. + /// The model scope the expressions resolve against. + /// The output the rendered text is appended to. + /// An representing either a successful operation, or an error. + private static Result RenderNodes(IReadOnlyList nodes, ThemeRenderScopeDto scope, StringBuilder output) + { + foreach (ThemeTemplateNodeDto node in nodes) + { + switch (node) + { + case ThemeTextNodeDto text: + { + Result textResult = AppendChecked(output, text.Value); + if (textResult.IsFailure) + return Result.Failure(textResult.Errors); + + break; + } + case ThemeVariableNodeDto variable: + { + object? resolved = Resolve(variable.Expression, scope); + string value = ConvertToString(resolved); + Result variableResult = AppendChecked(output, variable.ShouldBeEscaped ? HtmlEncoder.Default.Encode(value) : value); + if (variableResult.IsFailure) + return Result.Failure(variableResult.Errors); + + break; + } + case ThemeSectionNodeDto section: + { + Result sectionResult = RenderSection(section, scope, output); + if (sectionResult.IsFailure) + return Result.Failure(sectionResult.Errors); + + break; + } + } + } + + return Result.Success; + } + + /// + /// Renders a section by evaluating its expression and iterating or conditionally rendering its children. + /// + /// The section node to render. + /// The model scope the section expression resolves against. + /// The output the rendered text is appended to. + /// An representing either a successful operation, or an error. + private static Result RenderSection(ThemeSectionNodeDto section, ThemeRenderScopeDto scope, StringBuilder output) + { + object? value = Resolve(section.Expression, scope); + bool truthy = IsTruthy(value); + if (section.Inverted) + { + if (!truthy) + return RenderNodes(section.Children, scope, output); + + return Result.Success; + } + + if (!truthy) + return Result.Success; + + if (value is bool) + return RenderNodes(section.Children, scope, output); + + if (value is System.Collections.IEnumerable enumerable and not string) + { + foreach (object? item in enumerable) + { + Result itemResult = RenderNodes(section.Children, new ThemeRenderScopeDto(item, scope), output); + if (itemResult.IsFailure) + return Result.Failure(itemResult.Errors); + } + + return Result.Success; + } + + return RenderNodes(section.Children, new ThemeRenderScopeDto(value, scope), output); + } + + /// + /// Resolves a dotted expression against the scope chain, honoring explicit parent traversal. + /// + /// The dotted property expression to resolve. + /// The scope the expression is resolved from. + /// The resolved value, or when no scope in the chain exposes it. + private static object? Resolve(string expression, ThemeRenderScopeDto startingScope) + { + int explicitParentCount = 0; + while (expression.StartsWith("../", StringComparison.Ordinal)) + { + explicitParentCount++; + expression = expression[3..]; + } + + ThemeRenderScopeDto scope = startingScope; + for (int index = 0; index < explicitParentCount; index++) + scope = scope.Parent ?? scope; + + if (expression == ".") + return scope.Value; + + if (explicitParentCount > 0) + return TryResolvePath(scope.Value, expression, out object? explicitValue) ? explicitValue : null; + + for (ThemeRenderScopeDto? candidate = scope; candidate is not null; candidate = candidate.Parent) + if (TryResolvePath(candidate.Value, expression, out object? value)) + return value; + + return null; + } + + /// + /// Resolves a dotted property path against a value, member by member. + /// + /// The value the path is resolved against. + /// The dotted property path to resolve. + /// The resolved value, or when any part of the path is missing. + /// when the full path resolved; otherwise. + private static bool TryResolvePath(object? value, string expression, out object? resolved) + { + resolved = value; + foreach (string part in expression.Split('.')) + { + if (!TryReadMember(resolved, part, out resolved)) + { + resolved = null; + return false; + } + } + + return true; + } + + /// + /// Reads a single member from a value, supporting dictionaries, collections and public properties. + /// + /// The value the member is read from. + /// The member name to read, matched case-insensitively. + /// The member value, or when the member is not found. + /// when the member was found; otherwise. + private static bool TryReadMember(object? target, string name, out object? value) + { + value = null; + if (target is null) + return false; + + if (target is IReadOnlyDictionary readOnlyDictionary) + { + foreach (KeyValuePair pair in readOnlyDictionary) + { + if (string.Equals(pair.Key, name, StringComparison.OrdinalIgnoreCase)) + { + value = pair.Value; + return true; + } + } + + return false; + } + + if (target is IDictionary dictionary) + { + foreach (KeyValuePair pair in dictionary) + { + if (string.Equals(pair.Key, name, StringComparison.OrdinalIgnoreCase)) + { + value = pair.Value; + return true; + } + } + + return false; + } + + if (string.Equals(name, "Count", StringComparison.OrdinalIgnoreCase) && target is System.Collections.ICollection collection) + { + value = collection.Count; + return true; + } + + PropertyInfo? property = target.GetType().GetProperty(name, BindingFlags.Public | BindingFlags.Instance | BindingFlags.IgnoreCase); + if (property is null || property.GetIndexParameters().Length != 0) + return false; + + value = property.GetValue(target); + return true; + } + + /// + /// Determines the truthiness of a value: and are falsy, empty strings and empty collections are falsy. + /// + /// The value to evaluate. + /// when the value is truthy; otherwise. + private static bool IsTruthy(object? value) + { + if (value is null or false) + return false; + + if (value is string text) + return text.Length > 0; + + if (value is System.Collections.IEnumerable enumerable) + { + System.Collections.IEnumerator enumerator = enumerable.GetEnumerator(); + try + { + return enumerator.MoveNext(); + } + finally + { + (enumerator as IDisposable)?.Dispose(); + } + } + + return true; + } + + /// + /// Converts a resolved value to its rendered string representation. + /// + /// The value to convert. + /// The rendered string, or an empty string for values. + private static string ConvertToString(object? value) + { + return value switch + { + null => string.Empty, + bool boolean => boolean ? "true" : "false", + DateTime dateTime => dateTime.ToString("O", CultureInfo.InvariantCulture), + DateTimeOffset dateTimeOffset => dateTimeOffset.ToString("O", CultureInfo.InvariantCulture), + IFormattable formattable => formattable.ToString(null, CultureInfo.InvariantCulture) ?? string.Empty, + _ => value.ToString() ?? string.Empty + }; + } + + /// + /// Validates a template expression: non-empty, within the length limit and composed of dotted name parts. + /// + /// The expression to validate. + /// An representing either a successful operation, or an error. + private static Result ValidateExpression(string expression) + { + if (string.IsNullOrWhiteSpace(expression) || expression.Length > 120) + return TemplateInvalid("A template expression is empty or too long."); + + string remaining = expression; + while (remaining.StartsWith("../", StringComparison.Ordinal)) + remaining = remaining[3..]; + + if (remaining == ".") + return Result.Success; + + if (remaining.Length == 0 || remaining.Split('.').Any(part => !s_namePartPattern.IsMatch(part))) + return TemplateInvalid($"Expression '{expression}' is invalid. Use property names separated by dots."); + + return Result.Success; + } + + /// + /// Appends a value to the output, enforcing the maximum rendered character limit. + /// + /// The output the value is appended to. + /// The value to append. + /// An representing either a successful operation, or an error. + private static Result AppendChecked(StringBuilder output, string value) + { + if (output.Length + value.Length > MAX_RENDERED_CHARACTERS) + return TemplateInvalid("Rendered output exceeds the 4 MB safety limit."); + + output.Append(value); + return Result.Success; + } + + /// + /// Creates a validation error for an invalid theme template. + /// + /// The human-readable description of the template error. + /// The validation error describing the invalid theme template. + private static Error TemplateInvalid(string description) + { + return Error.Validation(code: "Theme.Template.Invalid", description: description); + } +} diff --git a/src/Lumina.Presentation.Web/Program.cs b/src/Lumina.Presentation.Web/Program.cs index c314290d..b0fa5cac 100644 --- a/src/Lumina.Presentation.Web/Program.cs +++ b/src/Lumina.Presentation.Web/Program.cs @@ -41,10 +41,7 @@ public class Program if (Environment.GetEnvironmentVariable("DOTNET_RUNNING_IN_CONTAINER") == "true") { logPath = Environment.GetEnvironmentVariable("LOG_PATH") ?? "/logs"; // use docker volume path - builder.WebHost.ConfigureKestrel(options => - { - options.ListenAnyIP(5012); // HTTP only - }); + builder.WebHost.ConfigureKestrel(options => options.ListenAnyIP(5012)); // HTTP only } else logPath = Path.Combine(AppContext.BaseDirectory, "logs"); // use local binary path @@ -103,6 +100,8 @@ public class Program // handle path base from reverse proxies app.Use((context, next) => { + context.Response.Headers["X-Content-Type-Options"] = "nosniff"; + context.Response.Headers["Referrer-Policy"] = "strict-origin-when-cross-origin"; if (context.Request.Headers.TryGetValue("X-Forwarded-Prefix", out StringValues pathBase)) context.Request.PathBase = pathBase.ToString(); return next(); diff --git a/src/Lumina.Presentation.Web/appsettings.json b/src/Lumina.Presentation.Web/appsettings.json index 73c0a7f4..b83e511e 100644 --- a/src/Lumina.Presentation.Web/appsettings.json +++ b/src/Lumina.Presentation.Web/appsettings.json @@ -2,6 +2,16 @@ "EncryptionSettings": { "SecretKey": "" // base64 string }, + "ThemeEngine": { + "StoragePath": "Themes", + "SettingsPath": "theme-settings.json", + "DefaultThemeId": "editorial-paper", + "MaxArchiveBytes": 8388608, + "MaxExpandedBytes": 25165824, + "MaxSingleFileBytes": 6291456, + "MaxEntries": 250, + "AllowThemeScripts": false + }, "Serilog": { "Using": [ "Serilog.Sinks.Console", "Serilog.Sinks.File" ], "MinimumLevel": { diff --git a/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Common/Validators/ThemeEngineOptionsDtoValidatorTests.cs b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Common/Validators/ThemeEngineOptionsDtoValidatorTests.cs new file mode 100644 index 00000000..bb0e17ff --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Common/Validators/ThemeEngineOptionsDtoValidatorTests.cs @@ -0,0 +1,131 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.DTO.Configuration; +using Lumina.Presentation.Web.Common.Primitives; +using Lumina.Presentation.Web.Common.Validators; +using Lumina.Presentation.Web.UnitTests.Common.Setup; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Web.UnitTests.Common.Validators; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class ThemeEngineOptionsDtoValidatorTests +{ + private readonly ThemeEngineOptionsDtoValidator _validator = new(); + + [Fact] + public void Validate_WhenStoragePathIsEmpty_ShouldHaveValidationError() + { + // Arrange + ThemeEngineOptionsDto options = new() { StoragePath = string.Empty }; + + // Act + List result = _validator.TestValidate(options); + + // Assert + result.ShouldHaveValidationError(Error.Validation(description: "Theme storage path cannot be empty!")); + } + + [Fact] + public void Validate_WhenSettingsPathIsEmpty_ShouldHaveValidationError() + { + // Arrange + ThemeEngineOptionsDto options = new() { SettingsPath = string.Empty }; + + // Act + List result = _validator.TestValidate(options); + + // Assert + result.ShouldHaveValidationError(Error.Validation(description: "Theme settings path cannot be empty!")); + } + + [Fact] + public void Validate_WhenDefaultThemeIdIsEmpty_ShouldHaveValidationError() + { + // Arrange + ThemeEngineOptionsDto options = new() { DefaultThemeId = string.Empty }; + + // Act + List result = _validator.TestValidate(options); + + // Assert + result.ShouldHaveValidationError(Error.Validation(description: "Default theme Id cannot be empty!")); + } + + [Theory] + [InlineData(0L)] // zero, not positive + [InlineData(-1L)] // negative + public void Validate_WhenMaxArchiveBytesIsNotPositive_ShouldHaveValidationError(long maxArchiveBytes) + { + // Arrange + ThemeEngineOptionsDto options = new() { MaxArchiveBytes = maxArchiveBytes }; + + // Act + List result = _validator.TestValidate(options); + + // Assert + result.ShouldHaveValidationError(Error.Validation(description: "Maximum archive size must be greater than 0!")); + } + + [Theory] + [InlineData(0L)] // zero, not positive + [InlineData(-1L)] // negative + public void Validate_WhenMaxExpandedBytesIsNotPositive_ShouldHaveValidationError(long maxExpandedBytes) + { + // Arrange + ThemeEngineOptionsDto options = new() { MaxExpandedBytes = maxExpandedBytes }; + + // Act + List result = _validator.TestValidate(options); + + // Assert + result.ShouldHaveValidationError(Error.Validation(description: "Maximum expanded size must be greater than 0!")); + } + + [Theory] + [InlineData(0L)] // zero, not positive + [InlineData(-1L)] // negative + public void Validate_WhenMaxSingleFileBytesIsNotPositive_ShouldHaveValidationError(long maxSingleFileBytes) + { + // Arrange + ThemeEngineOptionsDto options = new() { MaxSingleFileBytes = maxSingleFileBytes }; + + // Act + List result = _validator.TestValidate(options); + + // Assert + result.ShouldHaveValidationError(Error.Validation(description: "Maximum single file size must be greater than 0!")); + } + + [Theory] + [InlineData(0)] // zero, not positive + [InlineData(-1)] // negative + public void Validate_WhenMaxEntriesIsNotPositive_ShouldHaveValidationError(int maxEntries) + { + // Arrange + ThemeEngineOptionsDto options = new() { MaxEntries = maxEntries }; + + // Act + List result = _validator.TestValidate(options); + + // Assert + result.ShouldHaveValidationError(Error.Validation(description: "Maximum entries count must be greater than 0!")); + } + + [Fact] + public void Validate_WhenOptionsAreValid_ShouldNotHaveAnyValidationErrors() + { + // Arrange + ThemeEngineOptionsDto options = new(); + + // Act + List result = _validator.TestValidate(options); + + // Assert + result.ShouldNotHaveAnyValidationErrors(); + } +}