Removes the option to disable theme scripts

This commit is contained in:
BinaryAlley committed 2026-08-21 11:47:16 -07:00
1 parent 531450b3db
commit 15945c2e56
17 files changed
+15 -201

No files matched your search

@@ -14,11 +14,6 @@ namespace Lumina.Application.Common.Infrastructure.Themes;
/// </summary>
public interface IThemeService
{
/// <summary>
/// Gets a value indicating whether theme templates may contain script elements and theme assets may include script files.
/// </summary>
bool AllowThemeScripts { get; }
/// <summary>
/// Gets the maximum allowed size of a theme archive, in bytes.
/// </summary>
@@ -35,7 +35,7 @@ public class GetThemeSettingsQueryHandler : IQueryHandler<GetThemeSettingsQuery,
/// </returns>
public Task<Result<ThemeSettingsResponse>> HandleAsync(GetThemeSettingsQuery query, CancellationToken cancellationToken)
{
ThemeSettingsResponse response = new(_themeService.MaxArchiveBytes, _themeService.AllowThemeScripts, _themeService.DefaultThemeId);
ThemeSettingsResponse response = new(_themeService.MaxArchiveBytes, _themeService.DefaultThemeId);
return Task.FromResult(Result.From(response));
}
}
@@ -9,11 +9,9 @@ namespace Lumina.Contracts.Responses.Themes;
/// Represents a theme settings response.
/// </summary>
/// <param name="MaxArchiveBytes">The maximum allowed size of a theme archive, in bytes.</param>
/// <param name="AllowThemeScripts">Whether theme templates may contain script elements and theme assets may include script files.</param>
/// <param name="DefaultThemeId">The identifier of the theme selected when no valid current theme is available.</param>
[DebuggerDisplay("MaxArchiveBytes: {MaxArchiveBytes}")]
public record ThemeSettingsResponse(
long MaxArchiveBytes,
bool AllowThemeScripts,
string DefaultThemeId
);
@@ -46,9 +46,4 @@ public sealed class ThemeEngineOptionsDto
/// Gets or sets the maximum allowed number of entries in a theme pack archive.
/// </summary>
public int MaxEntries { get; set; } = 250;
/// <summary>
/// Gets or sets a value indicating whether script elements in theme templates and script files in theme assets are allowed to be served.
/// </summary>
public bool AllowThemeScripts { get; set; }
}
@@ -45,12 +45,6 @@ public sealed class ThemeService : IThemeService
"^[A-Za-z0-9][A-Za-z0-9._ -]*$",
RegexOptions.Compiled | RegexOptions.CultureInvariant);
// strips every script element from a template, both the inline content and the src attribute variants,
// so that no script bundled in a theme is executed in any client when scripts are disabled
private static readonly Regex s_scriptElementPattern = new(
"<script\\b[^>]*>[\\s\\S]*?</script\\s*>",
RegexOptions.Compiled | RegexOptions.IgnoreCase | RegexOptions.CultureInvariant);
private static readonly JsonSerializerOptions s_manifestJsonOptions = new(JsonSerializerDefaults.Web)
{
PropertyNameCaseInsensitive = true,
@@ -87,11 +81,6 @@ public sealed class ThemeService : IThemeService
_mutationGate = s_storageGates.GetOrAdd(_storageRoot, static _ => new SemaphoreSlim(1, 1));
}
/// <summary>
/// Gets a value indicating whether theme templates may contain script elements and theme assets may include script files.
/// </summary>
public bool AllowThemeScripts => _options.AllowThemeScripts;
/// <summary>
/// Gets the maximum allowed size of a theme archive, in bytes.
/// </summary>
@@ -280,8 +269,6 @@ public sealed class ThemeService : IThemeService
return Errors.Themes.ThemeFilesUnreadable;
string template = await File.ReadAllTextAsync(fullPathResult.Value, cancellationToken);
if (!AllowThemeScripts)
template = StripScriptElements(template);
return template;
}
@@ -330,10 +317,6 @@ public sealed class ThemeService : IThemeService
if (!normalizedPath.StartsWith("assets/", StringComparison.Ordinal))
return PackageInvalid("The requested asset is not located under the assets directory.");
// scripts in theme assets are gated globally: when disabled, script files are not served at all
if (!AllowThemeScripts && string.Equals(Path.GetExtension(normalizedPath), ".js", StringComparison.OrdinalIgnoreCase))
return Errors.Themes.ThemeFilesUnreadable;
Result<string> fullPathResult = ResolveContainedPath(ResolveThemePath(themeId), normalizedPath);
if (fullPathResult.IsFailure)
return fullPathResult.Errors;
@@ -782,16 +765,6 @@ public sealed class ThemeService : IThemeService
return Error.Validation(code: "Theme.Package.Invalid", description: description);
}
/// <summary>
/// Removes every script element from a theme template, so that no script bundled in the theme runs when scripts are disabled.
/// </summary>
/// <param name="template">The template content to strip script elements from.</param>
/// <returns>The template content without script elements.</returns>
private static string StripScriptElements(string template)
{
return s_scriptElementPattern.Replace(template, string.Empty);
}
/// <summary>
/// Resolves the storage path of a theme pack directory for a theme identifier.
/// </summary>
@@ -13,8 +13,7 @@
"MaxArchiveBytes": 8388608,
"MaxExpandedBytes": 25165824,
"MaxSingleFileBytes": 6291456,
"MaxEntries": 250,
"AllowThemeScripts": true
"MaxEntries": 250
},
"ConnectionStrings": {
"DefaultConnection": "Server=<host>;Database=<database>;User Id=<user>;Password=<password>;"
@@ -19,12 +19,11 @@ public class GetThemeSettingsEndpointSummary : Summary<GetThemeSettingsEndpoint,
public GetThemeSettingsEndpointSummary()
{
Summary = "Retrieves the theme engine settings.";
Description = "Retrieves the settings of the theme engine, including whether theme scripts are allowed and the maximum archive size.";
Description = "Retrieves the settings of the theme engine, including the maximum archive size.";
Response(200, "The theme engine settings are returned.",
example: new ThemeSettingsResponse(
MaxArchiveBytes: 8388608,
AllowThemeScripts: false,
DefaultThemeId: "lumina-default"
));
}
@@ -22,11 +22,6 @@ public sealed class ThemeAdminDto
/// </summary>
public required string CurrentThemeId { get; init; }
/// <summary>
/// Gets or sets a value indicating whether theme templates may load script files.
/// </summary>
public required bool AllowThemeScripts { get; init; }
/// <summary>
/// Gets or sets the maximum allowed size of a theme archive, in bytes.
/// </summary>
@@ -9,11 +9,9 @@ namespace Lumina.Presentation.Web.Common.DTO.Themes;
/// Data transfer object for the theme engine settings returned by the remote API.
/// </summary>
/// <param name="MaxArchiveBytes">The maximum allowed size of a theme archive, in bytes.</param>
/// <param name="AllowThemeScripts">Whether theme templates may contain script elements and theme assets may include script files.</param>
/// <param name="DefaultThemeId">The identifier of the theme selected when no valid current theme is available.</param>
[DebuggerDisplay("MaxArchiveBytes: {MaxArchiveBytes}")]
public sealed record ThemeSettingsResponseDto(
long MaxArchiveBytes,
bool AllowThemeScripts,
string DefaultThemeId
);
@@ -58,7 +58,6 @@ public class GetThemesEndpoint : BaseEndpoint<EmptyRequest, IResult>
{
Themes = themes,
CurrentThemeId = currentTheme.Id,
AllowThemeScripts = settings.AllowThemeScripts,
MaxArchiveBytes = settings.MaxArchiveBytes
};
return JsonSuccess(themeAdmin);
@@ -20,17 +20,14 @@ public class ThemeSettingsResponseFixture
/// Creates a random valid <see cref="ThemeSettingsResponse"/>.
/// </summary>
/// <param name="maxArchiveBytes">Optional. The maximum allowed size of a theme archive, in bytes.</param>
/// <param name="allowThemeScripts">Optional. Whether theme templates may contain script elements.</param>
/// <param name="defaultThemeId">Optional. The identifier of the default theme.</param>
/// <returns>The created <see cref="ThemeSettingsResponse"/>.</returns>
public ThemeSettingsResponse Create(
long? maxArchiveBytes = null,
bool? allowThemeScripts = null,
string? defaultThemeId = null)
{
return new ThemeSettingsResponse(
maxArchiveBytes ?? _faker.Random.Long(1_000_000, 100_000_000),
allowThemeScripts ?? _faker.Random.Bool(),
defaultThemeId ?? _faker.Lorem.Slug(2));
}
@@ -25,7 +25,6 @@ public class ThemeEngineOptionsDtoFixture
/// <param name="maxExpandedBytes">Optional maximum total size of an extracted theme pack, in bytes.</param>
/// <param name="maxSingleFileBytes">Optional maximum size of a single file within a theme pack, in bytes.</param>
/// <param name="maxEntries">Optional maximum number of entries in a theme pack archive.</param>
/// <param name="allowThemeScripts">Optional value indicating whether script elements are allowed.</param>
/// <returns>A configured <see cref="ThemeEngineOptionsDto"/> instance.</returns>
public ThemeEngineOptionsDto Create(
string? storagePath = null,
@@ -34,8 +33,7 @@ public class ThemeEngineOptionsDtoFixture
long? maxArchiveBytes = null,
long? maxExpandedBytes = null,
long? maxSingleFileBytes = null,
int? maxEntries = null,
bool? allowThemeScripts = null)
int? maxEntries = null)
{
Faker faker = new();
return new ThemeEngineOptionsDto
@@ -46,8 +44,7 @@ public class ThemeEngineOptionsDtoFixture
MaxArchiveBytes = maxArchiveBytes ?? faker.Random.Long(1_000_000, 100_000_000),
MaxExpandedBytes = maxExpandedBytes ?? faker.Random.Long(10_000_000, 500_000_000),
MaxSingleFileBytes = maxSingleFileBytes ?? faker.Random.Long(1_000_000, 50_000_000),
MaxEntries = maxEntries ?? faker.Random.Int(1, 1000),
AllowThemeScripts = allowThemeScripts ?? faker.Random.Bool()
MaxEntries = maxEntries ?? faker.Random.Int(1, 1000)
};
}
@@ -18,18 +18,15 @@ public class ThemeSettingsResponseDtoFixture
/// Creates a new <see cref="ThemeSettingsResponseDto"/> instance with randomized test data.
/// </summary>
/// <param name="maxArchiveBytes">Optional maximum allowed archive size, in bytes.</param>
/// <param name="allowThemeScripts">Whether theme templates may load script files.</param>
/// <param name="defaultThemeId">Optional identifier of the fallback theme.</param>
/// <returns>A configured <see cref="ThemeSettingsResponseDto"/> instance.</returns>
public ThemeSettingsResponseDto Create(
long? maxArchiveBytes = null,
bool? allowThemeScripts = null,
string? defaultThemeId = null)
{
Faker faker = new();
return new ThemeSettingsResponseDto(
MaxArchiveBytes: maxArchiveBytes ?? faker.Random.Long(1024 * 1024, 256 * 1024 * 1024),
AllowThemeScripts: allowThemeScripts ?? faker.Random.Bool(),
DefaultThemeId: defaultThemeId ?? faker.Lorem.Word()
);
}
@@ -37,10 +37,8 @@ public class GetThemeSettingsQueryHandlerTests
// Arrange
GetThemeSettingsQuery query = _getThemeSettingsQueryFixture.Create();
long maxArchiveBytes = 50_000_000;
bool allowThemeScripts = false;
string defaultThemeId = "default-theme";
_mockThemeService.MaxArchiveBytes.Returns(maxArchiveBytes);
_mockThemeService.AllowThemeScripts.Returns(allowThemeScripts);
_mockThemeService.DefaultThemeId.Returns(defaultThemeId);
// Act
@@ -49,7 +47,6 @@ public class GetThemeSettingsQueryHandlerTests
// Assert
Assert.False(result.IsFailure);
Assert.Equal(maxArchiveBytes, result.Value.MaxArchiveBytes);
Assert.Equal(allowThemeScripts, result.Value.AllowThemeScripts);
Assert.Equal(defaultThemeId, result.Value.DefaultThemeId);
}
}
@@ -51,8 +51,7 @@ public class ThemeServiceTests : IDisposable
maxArchiveBytes: 8 * 1024 * 1024,
maxExpandedBytes: 24 * 1024 * 1024,
maxSingleFileBytes: 6 * 1024 * 1024,
maxEntries: 250,
allowThemeScripts: false);
maxEntries: 250);
_sut = CreateSut(_options);
}
@@ -76,52 +75,6 @@ public class ThemeServiceTests : IDisposable
}
}
[Fact]
public void AllowThemeScripts_WhenConfiguredFalse_ShouldReturnFalse()
{
// Arrange
ThemeEngineOptionsDto options = _themeEngineOptionsDtoFixture.Create(
storagePath: Path.Combine(_testRootPath, "themes"),
bundledThemesPath: Path.Combine(_testRootPath, "bundled"),
defaultThemeId: "lumina-default",
maxArchiveBytes: 8 * 1024 * 1024,
maxExpandedBytes: 24 * 1024 * 1024,
maxSingleFileBytes: 6 * 1024 * 1024,
maxEntries: 250,
allowThemeScripts: false);
options.AllowThemeScripts = false;
ThemeService sut = CreateSut(options);
// Act
bool result = sut.AllowThemeScripts;
// Assert
Assert.False(result);
}
[Fact]
public void AllowThemeScripts_WhenConfiguredTrue_ShouldReturnTrue()
{
// Arrange
ThemeEngineOptionsDto options = _themeEngineOptionsDtoFixture.Create(
storagePath: Path.Combine(_testRootPath, "themes"),
bundledThemesPath: Path.Combine(_testRootPath, "bundled"),
defaultThemeId: "lumina-default",
maxArchiveBytes: 8 * 1024 * 1024,
maxExpandedBytes: 24 * 1024 * 1024,
maxSingleFileBytes: 6 * 1024 * 1024,
maxEntries: 250,
allowThemeScripts: false);
options.AllowThemeScripts = true;
ThemeService sut = CreateSut(options);
// Act
bool result = sut.AllowThemeScripts;
// Assert
Assert.True(result);
}
[Fact]
public void MaxArchiveBytes_WhenConfigured_ShouldReturnConfiguredValue()
{
@@ -133,8 +86,7 @@ public class ThemeServiceTests : IDisposable
maxArchiveBytes: 8 * 1024 * 1024,
maxExpandedBytes: 24 * 1024 * 1024,
maxSingleFileBytes: 6 * 1024 * 1024,
maxEntries: 250,
allowThemeScripts: false);
maxEntries: 250);
options.MaxArchiveBytes = 12345;
ThemeService sut = CreateSut(options);
@@ -156,8 +108,7 @@ public class ThemeServiceTests : IDisposable
maxArchiveBytes: 8 * 1024 * 1024,
maxExpandedBytes: 24 * 1024 * 1024,
maxSingleFileBytes: 6 * 1024 * 1024,
maxEntries: 250,
allowThemeScripts: false);
maxEntries: 250);
options.DefaultThemeId = "custom-default";
ThemeService sut = CreateSut(options);
@@ -288,8 +239,7 @@ public class ThemeServiceTests : IDisposable
maxArchiveBytes: 8 * 1024 * 1024,
maxExpandedBytes: 24 * 1024 * 1024,
maxSingleFileBytes: 6 * 1024 * 1024,
maxEntries: 250,
allowThemeScripts: false);
maxEntries: 250);
options.MaxArchiveBytes = 128;
ThemeService sut = CreateSut(options);
byte[] archive = _themePackFixture.Create();
@@ -453,8 +403,7 @@ public class ThemeServiceTests : IDisposable
maxArchiveBytes: 8 * 1024 * 1024,
maxExpandedBytes: 24 * 1024 * 1024,
maxSingleFileBytes: 6 * 1024 * 1024,
maxEntries: 250,
allowThemeScripts: false);
maxEntries: 250);
options.MaxEntries = 2;
ThemeService sut = CreateSut(options);
byte[] archive = _themePackFixture.Create();
@@ -478,8 +427,7 @@ public class ThemeServiceTests : IDisposable
maxArchiveBytes: 8 * 1024 * 1024,
maxExpandedBytes: 24 * 1024 * 1024,
maxSingleFileBytes: 6 * 1024 * 1024,
maxEntries: 250,
allowThemeScripts: false);
maxEntries: 250);
options.MaxSingleFileBytes = 10;
ThemeService sut = CreateSut(options);
string manifestJson = _themePackFixture.CreateManifestJson();
@@ -506,8 +454,7 @@ public class ThemeServiceTests : IDisposable
maxArchiveBytes: 8 * 1024 * 1024,
maxExpandedBytes: 24 * 1024 * 1024,
maxSingleFileBytes: 6 * 1024 * 1024,
maxEntries: 250,
allowThemeScripts: false);
maxEntries: 250);
options.MaxSingleFileBytes = 400;
options.MaxExpandedBytes = 300;
ThemeService sut = CreateSut(options);
@@ -1039,48 +986,6 @@ public class ThemeServiceTests : IDisposable
Assert.Equal(DEFAULT_TEMPLATE, result.Value);
}
[Fact]
public async Task GetTemplateAsync_WhenScriptsAreDisabled_ShouldStripScriptElements()
{
// Arrange
byte[] archive = _themePackFixture.Create(defaultTemplateContent: "<script>alert('xss')</script><p>safe content</p>");
await InstallValidThemeAsync(archive);
// Act
Result<string> result = await _sut.GetTemplateAsync("test-theme", "unknown-page", CancellationToken.None);
// Assert
Assert.True(result.IsSuccess);
Assert.Equal("<p>safe content</p>", result.Value);
}
[Fact]
public async Task GetTemplateAsync_WhenScriptsAreEnabled_ShouldPreserveScriptElements()
{
// Arrange
ThemeEngineOptionsDto options = _themeEngineOptionsDtoFixture.Create(
storagePath: Path.Combine(_testRootPath, "themes"),
bundledThemesPath: Path.Combine(_testRootPath, "bundled"),
defaultThemeId: "lumina-default",
maxArchiveBytes: 8 * 1024 * 1024,
maxExpandedBytes: 24 * 1024 * 1024,
maxSingleFileBytes: 6 * 1024 * 1024,
maxEntries: 250,
allowThemeScripts: false);
options.AllowThemeScripts = true;
ThemeService sut = CreateSut(options);
const string TEMPLATE_WITH_SCRIPT = "<script>alert('xss')</script><p>safe content</p>";
byte[] archive = _themePackFixture.Create(defaultTemplateContent: TEMPLATE_WITH_SCRIPT);
await InstallValidThemeAsync(archive, sut);
// Act
Result<string> result = await sut.GetTemplateAsync("test-theme", "unknown-page", CancellationToken.None);
// Assert
Assert.True(result.IsSuccess);
Assert.Equal(TEMPLATE_WITH_SCRIPT, result.Value);
}
[Fact]
public async Task GetAssetAsync_WhenAssetExists_ShouldReturnFileBytesAndContentType()
{
@@ -1146,7 +1051,7 @@ public class ThemeServiceTests : IDisposable
}
[Fact]
public async Task GetAssetAsync_WhenScriptsAreDisabledAndAssetIsJavaScript_ShouldReturnThemeFilesUnreadable()
public async Task GetAssetAsync_WhenAssetIsJavaScript_ShouldReturnJavaScriptContentType()
{
// Arrange
byte[] archive = _themePackFixture.Create(additionalFiles: new Dictionary<string, string>
@@ -1158,35 +1063,6 @@ public class ThemeServiceTests : IDisposable
// Act
Result<ThemeAssetDto> result = await _sut.GetAssetAsync("test-theme", "assets/app.js", CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal("ThemeFilesUnreadable", result.FirstError.Description);
}
[Fact]
public async Task GetAssetAsync_WhenScriptsAreEnabledAndAssetIsJavaScript_ShouldReturnJavaScriptContentType()
{
// Arrange
ThemeEngineOptionsDto options = _themeEngineOptionsDtoFixture.Create(
storagePath: Path.Combine(_testRootPath, "themes"),
bundledThemesPath: Path.Combine(_testRootPath, "bundled"),
defaultThemeId: "lumina-default",
maxArchiveBytes: 8 * 1024 * 1024,
maxExpandedBytes: 24 * 1024 * 1024,
maxSingleFileBytes: 6 * 1024 * 1024,
maxEntries: 250,
allowThemeScripts: false);
options.AllowThemeScripts = true;
ThemeService sut = CreateSut(options);
byte[] archive = _themePackFixture.Create(additionalFiles: new Dictionary<string, string>
{
["assets/app.js"] = "console.log('hello');"
});
await InstallValidThemeAsync(archive, sut);
// Act
Result<ThemeAssetDto> result = await sut.GetAssetAsync("test-theme", "assets/app.js", CancellationToken.None);
// Assert
Assert.True(result.IsSuccess);
Assert.Equal("application/javascript", result.Value.ContentType);
@@ -53,7 +53,7 @@ public class GetThemesEndpointTests
_mockApiHttpClient.GetAsync<ThemeResponseDto>(ApiRoutes.Themes.GET_CURRENT_THEME, Arg.Any<CancellationToken>())
.Returns(currentTheme);
_mockApiHttpClient.GetAsync<ThemeSettingsResponseDto>(ApiRoutes.Themes.GET_THEME_SETTINGS, Arg.Any<CancellationToken>())
.Returns(_themeSettingsResponseDtoFixture.Create(maxArchiveBytes: 10 * 1024 * 1024, allowThemeScripts: true));
.Returns(_themeSettingsResponseDtoFixture.Create(maxArchiveBytes: 10 * 1024 * 1024));
// Act
IResult result = await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None);
@@ -67,7 +67,6 @@ public class GetThemesEndpointTests
Assert.Equal(2, data.GetProperty("themes").GetArrayLength());
Assert.Equal("editorial-paper", data.GetProperty("themes")[0].GetProperty("id").GetString());
Assert.Equal("lumina-default", data.GetProperty("currentThemeId").GetString());
Assert.True(data.GetProperty("allowThemeScripts").GetBoolean());
Assert.Equal(10 * 1024 * 1024, data.GetProperty("maxArchiveBytes").GetInt64());
Assert.Equal(10.0, data.GetProperty("maxArchiveMegabytes").GetDouble());
}
@@ -103,7 +103,7 @@ public class ThemeServiceTests
public async Task GetThemeSettingsAsync_WhenApiReturnsSettings_ShouldReturnSettings()
{
// Arrange
ThemeSettingsResponseDto settings = _themeSettingsResponseDtoFixture.Create(maxArchiveBytes: 10 * 1024 * 1024, allowThemeScripts: true);
ThemeSettingsResponseDto settings = _themeSettingsResponseDtoFixture.Create(maxArchiveBytes: 10 * 1024 * 1024);
_mockApiHttpClient.GetAsync<ThemeSettingsResponseDto>(ApiRoutes.Themes.GET_THEME_SETTINGS, Arg.Any<CancellationToken>())
.Returns(settings);