Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
70 changes: 54 additions & 16 deletions AquaMai.Config.Editor/src/components/ConfigEntry.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { computed, defineComponent, type PropType } from 'vue';
import { useI18n } from 'vue-i18n';
import { ENTRY_LABEL_CLASS } from '../constants';
import { modComments } from '../modComments';
import type { ConfigEntry as ConfigEntryModel, EntryState } from '../types';
import type { ConfigEntry as ConfigEntryModel, ConfigValue, EntryState } from '../types';
import { KeyCodeID } from '../types/KeyCodeID';
import { KeyCodeName } from '../types/KeyCodeName';
import { VKCode } from '../types/VKCode';
Expand Down Expand Up @@ -44,27 +44,65 @@ export function optionsVKCode(t: (key: string) => string): { label: string; valu
});
}

export function optionsSoundChannel(t: (key: string) => string): { label: string; value: string }[] {
return [
'None',
'P1SpeakerLeft',
'P1SpeakerRight',
'P1HeadphoneLeft',
'P1HeadphoneRight',
'P2SpeakerLeft',
'P2SpeakerRight',
'P2HeadphoneLeft',
'P2HeadphoneRight',
].map((channel) => ({
label: t(`mod.soundChannel.${channel}`),
value: channel,
}));
}

export function formatConfigEntryValue(
entry: ConfigEntryModel,
value: ConfigValue,
t: (key: string) => string,
): string {
if (value === null || value === undefined) {
return '-';
}

const stringValue = String(value);
const choices = modComments.options[entry.path];
if (choices) {
return choices.find((item) => item.value === stringValue)?.label ?? stringValue;
}

switch (entry.fieldType) {
case 'System.Boolean':
return value ? t('mod.on') : t('mod.off');
case 'AquaMai.Config.Types.KeyCodeOrName':
return optionsKeyCodeOrName(t).find((item) => item.value === stringValue)?.label ?? stringValue;
case 'AquaMai.Config.Types.KeyCodeID':
return Object.entries(KeyCodeID).find(([, itemValue]) => itemValue === stringValue)?.[0] ?? stringValue;
case 'AquaMai.Config.Types.IOKeyMap':
case 'AquaMai.Config.Types.AdxKeyMap':
return optionsIoKeyMap(t).find((item) => item.value === stringValue)?.label ?? stringValue;
case 'AquaMai.Config.Types.VKCode':
return optionsVKCode(t).find((item) => item.value === stringValue)?.label ?? stringValue;
case 'AquaMai.Config.Types.SoundChannel':
return optionsSoundChannel(t).find((item) => item.value === stringValue)?.label ?? stringValue;
default:
return stringValue;
}
}

export const ConfigEntry = defineComponent({
props: {
entry: { type: Object as PropType<ConfigEntryModel>, required: true },
entryState: { type: Object as PropType<EntryState>, required: true },
},
setup(props) {
const { t, te, locale } = useI18n();
const optionsSoundChannel = [
'None',
'P1SpeakerLeft',
'P1SpeakerRight',
'P1HeadphoneLeft',
'P1HeadphoneRight',
'P2SpeakerLeft',
'P2SpeakerRight',
'P2HeadphoneLeft',
'P2HeadphoneRight',
].map((channel) => ({
label: t(`mod.soundChannel.${channel}`),
value: channel,
}));
const soundChannelOptions = optionsSoundChannel(t);

const comment = computed(() => {
const localeKey = `mod.commentOverrides.${props.entry.path.replace(/\./g, '_')}`;
Expand Down Expand Up @@ -122,7 +160,7 @@ export const ConfigEntry = defineComponent({
case 'AquaMai.Config.Types.VKCode':
return <Select v-model:value={props.entryState.value} options={optionsVKCode(t)} />;
case 'AquaMai.Config.Types.SoundChannel':
return <Select v-model:value={props.entryState.value} options={optionsSoundChannel} />;
return <Select v-model:value={props.entryState.value} options={soundChannelOptions} />;
default:
return t('mod.unsupportedType', { type: props.entry.fieldType });
}
Expand Down
2 changes: 2 additions & 0 deletions AquaMai.Config.Editor/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
export { AquaMaiConfigurator } from './components/AquaMaiConfigurator';
export {
ConfigEntry,
formatConfigEntryValue,
optionsIoKeyMap,
optionsKeyCodeOrName,
optionsSoundChannel,
optionsVKCode,
} from './components/ConfigEntry';
export { ConfigSection } from './components/ConfigSection';
Expand Down
9 changes: 7 additions & 2 deletions MaiChartManager/Controllers/Mod/ConfigurationController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -29,11 +29,16 @@ public ConfigurationController(StaticSettings settings, ILogger<ConfigurationCon
{
var dllPath = await modConfigService.GetAquaMaiDllPath();
var configSortYaml = ReadConfigSortYaml(dllPath);
var shouldSkipSignatureCheck = skipSignatureCheck || !string.Equals(dllPath, ModPaths.AquaMaiDllInstalledPath, StringComparison.OrdinalIgnoreCase);
var config = await modConfigService.GetCurrentAquaMaiConfig(forceDefault, shouldSkipSignatureCheck);
var config = await modConfigService.GetCurrentAquaMaiConfig(forceDefault, skipSignatureCheck);
return AquaMaiConfigDto.From(config, configSortYaml);
}

[HttpGet]
public async Task<IReadOnlyList<AquaMaiConfigBackupDto>> GetAquaMaiConfigBackups(bool skipSignatureCheck = false, CancellationToken ct = default)
{
return await modConfigService.GetAquaMaiConfigBackups(skipSignatureCheck, ct);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Medium · 通过局域网暴露历史设置

当应用在禁用身份验证的导出模式下运行,且备份文件包含历史覆盖值时,未经过身份验证的局域网客户端可以在启用导出模式且 UseAuth 为 false 时调用此端点;该服务会返回所有备份中解析出的覆盖值,从而暴露当前配置中已不存在的历史配置。

请对此端点要求身份验证,或以其他方式阻止未经过身份验证的局域网客户端获取备份内容。

面向 AI 智能体的提示
在 `MaiChartManager/Controllers/Mod/ConfigurationController.cs` 第 39 行:

**通过局域网暴露历史设置**

当应用在禁用身份验证的导出模式下运行,且备份文件包含历史覆盖值时,未经过身份验证的局域网客户端可以在启用导出模式且 `UseAuth` 为 false 时调用此端点;该服务会返回所有备份中解析出的覆盖值,从而暴露当前配置中已不存在的历史配置。

请对此端点要求身份验证,或以其他方式阻止未经过身份验证的局域网客户端获取备份内容。
Original comment in English

🟡 Medium · Historical settings exposed over LAN

When the application is running in export mode with authentication disabled and backup files contain historical overrides, an unauthenticated LAN client can call this endpoint when export mode is enabled and UseAuth is false; the service returns parsed override values from every backup, exposing historical configuration that is no longer present in the current config.

Require authentication for this endpoint or otherwise prevent unauthenticated LAN clients from retrieving backup contents.

Prompt for AI agents
In `MaiChartManager/Controllers/Mod/ConfigurationController.cs` at line 39:

**Historical settings exposed over LAN**

When the application is running in export mode with authentication disabled and backup files contain historical overrides, an unauthenticated LAN client can call this endpoint when export mode is enabled and `UseAuth` is false; the service returns parsed override values from every backup, exposing historical configuration that is no longer present in the current config.

Require authentication for this endpoint or otherwise prevent unauthenticated LAN clients from retrieving backup contents.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1: 该端点会直接返回所有备份中的历史覆盖值;请在 UseAuth 关闭时限制未认证访问,避免局域网客户端读取当前配置中已不存在的设置。

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At MaiChartManager/Controllers/Mod/ConfigurationController.cs, line 39:

<comment>该端点会直接返回所有备份中的历史覆盖值;请在 `UseAuth` 关闭时限制未认证访问,避免局域网客户端读取当前配置中已不存在的设置。</comment>

<file context>
@@ -29,11 +29,16 @@ public ConfigurationController(StaticSettings settings, ILogger<ConfigurationCon
+    [HttpGet]
+    public async Task<IReadOnlyList<AquaMaiConfigBackupDto>> GetAquaMaiConfigBackups(bool skipSignatureCheck = false, CancellationToken ct = default)
+    {
+        return await modConfigService.GetAquaMaiConfigBackups(skipSignatureCheck, ct);
+    }
+
</file context>

}

[HttpPut]
public async Task SetAquaMaiConfig(AquaMaiConfigDto.ConfigSave config)
{
Expand Down
123 changes: 119 additions & 4 deletions MaiChartManager/Controllers/Mod/ModConfigService.cs
Original file line number Diff line number Diff line change
@@ -1,9 +1,20 @@
using System.Globalization;
using System.Text.Json;
using AquaMai.Config.Dto;
using AquaMai.Config.HeadlessLoader;
using AquaMai.Config.Interfaces;
using MaiChartManager.Utils;

namespace MaiChartManager.Controllers.Mod;

public record AquaMaiConfigBackupDto(
string FileName,
DateTimeOffset Timestamp,
IReadOnlyDictionary<string, bool>? SectionOverrides,
IReadOnlyDictionary<string, JsonElement>? EntryOverrides,
string? ParseError
);

public class ModConfigService
{
private const string ExclusiveFullscreenSectionPath = "GameSystem.Window";
Expand Down Expand Up @@ -98,12 +109,12 @@ public void SyncExclusiveFullscreenCompatFlag(IConfig config)
}
}

public async Task<IConfig> GetCurrentAquaMaiConfig(bool forceDefault = false, bool skipSignatureCheck = false, CancellationToken ct = default)
private async Task<HeadlessConfigInterface> LoadConfigInterface(bool skipSignatureCheck, CancellationToken ct)
{
var dllPath = await GetAquaMaiDllPath(ct);

var binary = await File.ReadAllBytesAsync(dllPath, ct);
if (!skipSignatureCheck)
var shouldSkipSignatureCheck = skipSignatureCheck || !string.Equals(dllPath, ModPaths.AquaMaiDllInstalledPath, StringComparison.OrdinalIgnoreCase);
if (!shouldSkipSignatureCheck)
{
var sigResult = AquaMaiSignatureV2.VerifySignature(binary);
if (sigResult.Status != AquaMaiSignatureV2.VerifyStatus.Valid)
Expand All @@ -112,8 +123,14 @@ public async Task<IConfig> GetCurrentAquaMaiConfig(bool forceDefault = false, bo
}
}
var configInterface = HeadlessConfigLoader.LoadFromPacked(binary);
var config = configInterface.CreateConfig();
CheckConfigApiVersion(configInterface);
return configInterface;
}

public async Task<IConfig> GetCurrentAquaMaiConfig(bool forceDefault = false, bool skipSignatureCheck = false, CancellationToken ct = default)
{
var configInterface = await LoadConfigInterface(skipSignatureCheck, ct);
var config = configInterface.CreateConfig();
if (File.Exists(ModPaths.AquaMaiConfigPath) && !forceDefault)
{
try
Expand Down Expand Up @@ -146,4 +163,102 @@ public async Task<IConfig> GetCurrentAquaMaiConfig(bool forceDefault = false, bo

return config;
}

public async Task<IReadOnlyList<AquaMaiConfigBackupDto>> GetAquaMaiConfigBackups(bool skipSignatureCheck = false, CancellationToken ct = default)
{
if (string.IsNullOrEmpty(StaticSettings.GamePath) || !Directory.Exists(ModPaths.AquaMaiConfigBackupDirPath))
{
return [];
}

var files = Directory.GetFiles(ModPaths.AquaMaiConfigBackupDirPath, "*.toml");

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Medium · 大量备份历史会拖慢恢复

当备份目录中存在许多或很大的文件,或者端点被反复调用时,GetAquaMaiConfigBackups 会在每次请求时读取并解析所有备份,然后返回全部结果;由于历史记录没有上限,工作量和内存用量会不断增长,最终导致请求变慢或服务无响应。

请限制备份历史记录的数量,或对列表进行分页,使每个请求读取并返回有界数量的结果。

另见 MaiChartManager/Controllers/Mod/ModConfigService.cs:206。

面向 AI 智能体的提示
在 `MaiChartManager/Controllers/Mod/ModConfigService.cs` 第 174 行:

**大量备份历史会拖慢恢复**

当备份目录中存在许多或很大的文件,或者端点被反复调用时,`GetAquaMaiConfigBackups` 会在每次请求时读取并解析所有备份,然后返回全部结果;由于历史记录没有上限,工作量和内存用量会不断增长,最终导致请求变慢或服务无响应。

请限制备份历史记录的数量,或对列表进行分页,使每个请求读取并返回有界数量的结果。

另见 `MaiChartManager/Controllers/Mod/ModConfigService.cs:206`。
Original comment in English

🟡 Medium · Large backup histories stall recovery

When the backup directory contains many or large files, or the endpoint is called repeatedly, GetAquaMaiConfigBackups reads and parses every backup and returns all results on each request, making work and memory use grow with the uncapped history until the request slows or the service becomes unresponsive.

Limit backup history or paginate the listing so each request reads and returns a bounded set.

Also at MaiChartManager/Controllers/Mod/ModConfigService.cs:206.

Prompt for AI agents
In `MaiChartManager/Controllers/Mod/ModConfigService.cs` at line 174:

**Large backup histories stall recovery**

When the backup directory contains many or large files, or the endpoint is called repeatedly, `GetAquaMaiConfigBackups` reads and parses every backup and returns all results on each request, making work and memory use grow with the uncapped history until the request slows or the service becomes unresponsive.

Limit backup history or paginate the listing so each request reads and returns a bounded set.

Also at `MaiChartManager/Controllers/Mod/ModConfigService.cs:206`.

if (files.Length == 0)
{
return [];
}

var backupFiles = files
.Select(filePath =>
{
var fileName = Path.GetFileName(filePath);
var stem = Path.GetFileNameWithoutExtension(filePath);
var timestamp = DateTime.TryParseExact(
stem,
"yyyy-MM-dd_HH-mm-ss",
CultureInfo.InvariantCulture,
DateTimeStyles.AssumeLocal,
out var parsed)
? new DateTimeOffset(parsed)
: new DateTimeOffset(File.GetLastWriteTime(filePath));
return (filePath, fileName, timestamp);
})
.OrderByDescending(x => x.timestamp)
.ThenByDescending(x => x.fileName, StringComparer.OrdinalIgnoreCase)
.ToArray();

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2: 此列表会逐个读取并解析目录中的所有备份,历史规模会直接放大每次请求的 I/O、内存和响应体;请限制每次处理的数量或实现分页。

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At MaiChartManager/Controllers/Mod/ModConfigService.cs, line 197:

<comment>此列表会逐个读取并解析目录中的所有备份,历史规模会直接放大每次请求的 I/O、内存和响应体;请限制每次处理的数量或实现分页。</comment>

<file context>
@@ -146,4 +163,102 @@ public async Task<IConfig> GetCurrentAquaMaiConfig(bool forceDefault = false, bo
+            })
+            .OrderByDescending(x => x.timestamp)
+            .ThenByDescending(x => x.fileName, StringComparer.OrdinalIgnoreCase)
+            .ToArray();
+
+        var configInterface = await LoadConfigInterface(skipSignatureCheck, ct);
</file context>
Suggested change
.ToArray();
.Take(100).ToArray();


var configInterface = await LoadConfigInterface(skipSignatureCheck, ct);
// SetEntryValue 会写回 ReflectionField.Value,复用同一个 ReflectionManager 时每次解析前必须恢复默认值
var defaultFieldValues = configInterface.ReflectionManager.Entries
.Select(entry => (entry, value: entry.Field.GetValue(null)))
.ToArray();

var results = new List<AquaMaiConfigBackupDto>(backupFiles.Length);
foreach (var (filePath, fileName, timestamp) in backupFiles)
{
foreach (var (entry, defaultValue) in defaultFieldValues)
{
entry.Field.SetValue(null, defaultValue);
}

try
{
var toml = await File.ReadAllTextAsync(filePath, ct);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Medium · 有效备份会被误判为格式错误

当备份列表在配置保存正在写入文件时读取该文件,GetAquaMaiConfigBackups 可能会读到不完整的 TOML 文件,并对有效备份返回 ParseError,导致界面将其显示为失败状态,直到重新加载列表。

请以原子方式写入备份,确保列表请求只读取完整文件。

面向 AI 智能体的提示
在 `MaiChartManager/Controllers/Mod/ModConfigService.cs` 第 215 行:

**有效备份会被误判为格式错误**

当备份列表在配置保存正在写入文件时读取该文件,`GetAquaMaiConfigBackups` 可能会读到不完整的 TOML 文件,并对有效备份返回 `ParseError`,导致界面将其显示为失败状态,直到重新加载列表。

请以原子方式写入备份,确保列表请求只读取完整文件。
Original comment in English

🟡 Medium · Valid backups appear malformed

When the backup list reads a file while a config save is writing it, GetAquaMaiConfigBackups can read a partial TOML file and return a ParseError for a valid backup, so the UI shows it as failed until the list is reloaded.

Write backups atomically so the listing request reads only complete files.

Prompt for AI agents
In `MaiChartManager/Controllers/Mod/ModConfigService.cs` at line 215:

**Valid backups appear malformed**

When the backup list reads a file while a config save is writing it, `GetAquaMaiConfigBackups` can read a partial TOML file and return a `ParseError` for a valid backup, so the UI shows it as failed until the list is reloaded.

Write backups atomically so the listing request reads only complete files.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2: 列表读取可能与配置保存对同一备份文件的写入重叠,从而读到不完整 TOML 并暂时返回 ParseError;请原子写入备份或同步读写。

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At MaiChartManager/Controllers/Mod/ModConfigService.cs, line 215:

<comment>列表读取可能与配置保存对同一备份文件的写入重叠,从而读到不完整 TOML 并暂时返回 `ParseError`;请原子写入备份或同步读写。</comment>

<file context>
@@ -146,4 +163,102 @@ public async Task<IConfig> GetCurrentAquaMaiConfig(bool forceDefault = false, bo
+
+            try
+            {
+                var toml = await File.ReadAllTextAsync(filePath, ct);
+                var config = configInterface.CreateConfig();
+                var view = configInterface.CreateConfigView(toml);
</file context>

var config = configInterface.CreateConfig();
var view = configInterface.CreateConfigView(toml);
var migrationManager = configInterface.GetConfigMigrationManager();

if (migrationManager.GetVersion(view) != migrationManager.LatestVersion)
{
view = migrationManager.Migrate(view);
}

configInterface.GetConfigParser().Parse(config, view);

var sectionOverrides = new Dictionary<string, bool>();
var entryOverrides = new Dictionary<string, JsonElement>();
foreach (var section in config.ReflectionManager.Sections)
{
var sectionState = config.GetSectionState(section);
var effectiveEnabled = section.Attribute.AlwaysEnabled || sectionState.Enabled;
if (!section.Attribute.AlwaysEnabled && sectionState.Enabled != sectionState.DefaultEnabled)
{
sectionOverrides[section.Path] = sectionState.Enabled;
}

// 禁用栏目下的条目不会生效,保存时也会跳过
if (!effectiveEnabled)
{
continue;
}

foreach (var entry in section.Entries)
{
var entryState = config.GetEntryState(entry);
if (!Equals(entryState.Value, entryState.DefaultValue))
{
entryOverrides[entry.Path] = AquaMaiConfigDto.SerializeValue(entryState.Value);
}
}
}

results.Add(new AquaMaiConfigBackupDto(fileName, timestamp, sectionOverrides, entryOverrides, null));
}
catch (Exception ex) when (ex is not OperationCanceledException || !ct.IsCancellationRequested)
{
results.Add(new AquaMaiConfigBackupDto(fileName, timestamp, null, null, ex.Message));
}
}

return results;
}
}
53 changes: 52 additions & 1 deletion MaiChartManager/Front/src/client/apiGen.ts
Original file line number Diff line number Diff line change
Expand Up @@ -107,6 +107,15 @@ export interface AppVersionResult {
export?: boolean;
}

export interface AquaMaiConfigBackupDto {
fileName?: string | null;
/** @format date-time */
timestamp?: string;
sectionOverrides?: Record<string, boolean>;
entryOverrides?: Record<string, any>;
parseError?: string | null;
}

export interface AudioPreviewTime {
/** @format double */
startTime?: number;
Expand Down Expand Up @@ -320,6 +329,11 @@ export interface GetAssetsDirsResult {
version?: string | null;
}

export interface HardwareBridgeStatusDto {
available?: boolean;
platform?: string | null;
}

export interface ImportChartCheckResult {
accept?: boolean;
errors?: ImportChartMessage[] | null;
Expand Down Expand Up @@ -822,7 +836,7 @@ export class HttpClient<SecurityDataType = unknown> {
}

/**
* @title MaiChartManager
* @title MaiChartManager.GenClient
* @version 1.0
*/
export class Api<
Expand Down Expand Up @@ -1370,6 +1384,28 @@ export class Api<
...params,
}),

/**
* No description
*
* @tags Configuration
* @name GetAquaMaiConfigBackups
* @request GET:/MaiChartManagerServlet/GetAquaMaiConfigBackupsApi
*/
GetAquaMaiConfigBackups: (
query?: {
/** @default false */
skipSignatureCheck?: boolean;
},
params: RequestParams = {},
) =>
this.request<AquaMaiConfigBackupDto[], any>({
path: `/MaiChartManagerServlet/GetAquaMaiConfigBackupsApi`,
method: "GET",
query: query,
format: "json",
...params,
}),

/**
* No description
*
Expand Down Expand Up @@ -1877,6 +1913,21 @@ export class Api<
...params,
}),

/**
* No description
*
* @tags HardwareBridge
* @name HardwareBridgeStatus
* @request GET:/MaiChartManagerServlet/HardwareBridgeStatusApi
*/
HardwareBridgeStatus: (params: RequestParams = {}) =>
this.request<HardwareBridgeStatusDto, any>({
path: `/MaiChartManagerServlet/HardwareBridgeStatusApi`,
method: "GET",
format: "json",
...params,
}),

/**
* No description
*
Expand Down
17 changes: 17 additions & 0 deletions MaiChartManager/Front/src/locales/en.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -437,6 +437,23 @@ mod:
message: Both AquaMai and MuMod are present, please choose which to keep
deleteAquaMai: Delete AquaMai
deleteMuMod: Delete MuMod
backup:
title: Backup & Restore
empty: No backups found
diffCount: '{count} diff(s)'
noDiff: No diff
parseFailed: Parse failed
identical: Matches current config
item: Option
backupValue: Backup
currentValue: Current
restore: Restore
restoreSection: Restore Section
restoreAll: Restore All
restored: Restored
undo: Undo
emptyValue: (Empty)
loadFailed: Failed to load backups
pdx:
noDevice: No PDX device detected
deviceCount: '{count} PDX device(s) detected'
Expand Down
Loading
Loading