機能追加: Bakin・NW.jsエンジンおよびセーブ編集対応、ES3パスワード解決機能とRPGツクールMZ修正サービスの追加

This commit is contained in:
armonica committed 2026-11-20 19:55:34 +09:00
1 parent f50976a6c0
commit 152abae1f8
33 files changed
+11356 -175

No files matched your search

+295 -52
View File
@@ -9,6 +9,7 @@ using System.Text.Json;
using System.Text.Json.Nodes;
using GameLauncher.Engines.Unity;
using GameLauncher.Models;
using GameLauncher.Services.Codecs.Es3;
namespace GameLauncher.Services.Codecs
{
@@ -24,19 +25,63 @@ namespace GameLauncher.Services.Codecs
/// <summary>
/// パスワード入力が必要かどうかを取得します。
/// 暗号化の有無はファイルごとに異なるため、実際の要否は <see cref="NeedsPassword"/> で判定します。
/// </summary>
public bool RequiresPassword => false;
public bool RequiresPassword => true;
/// <summary>
/// パスワード入力ダイアログに表示する案内メッセージを取得します。
/// </summary>
public string? PasswordPromptMessage => "暗号化パスワードが設定されている場合は入力してください(未設定・既定の場合は空欄):";
// キャッシュ用の最新平文JSONノード
private JsonNode? _cachedRootNode;
/// <summary>
/// 直近の読み込み時に使用した解析ドキュメント(編集・書き戻し用)。
/// </summary>
private Es3SaveDocument? _document;
/// <summary>直近の読み込み対象ファイルの絶対パス。</summary>
private string? _loadedFilePath;
/// <summary>直近の読み込み時に暗号化されていたか。</summary>
private bool _wasEncrypted;
/// <summary>直近の読み込み時に復号に使用したパスワード。</summary>
private string? _usedPassword;
/// <summary>直近の読み込み時に Gzip 圧縮されていたか。</summary>
private bool _wasGzip;
/// <summary>直近の読み込み時の診断メッセージ(未対応時の案内表示に使用)。</summary>
private readonly List<string> _diagnostics = [];
/// <summary>
/// 直近の読み込みに関する診断メッセージを取得します。
/// </summary>
public IReadOnlyList<string> Diagnostics => this._diagnostics;
/// <summary>
/// 指定ファイルがパスワード入力(復号)を必要とするかを判定します。
/// </summary>
/// <param name="filePath">セーブファイルの絶対パス</param>
/// <returns>暗号化されており復号が必要な場合 true</returns>
public bool NeedsPassword(string filePath)
{
try
{
if (!File.Exists(filePath))
{
return false;
}
var bytes = File.ReadAllBytes(filePath);
return Es3PasswordResolver.LooksEncrypted(bytes);
}
catch
{
return false;
}
}
/// <summary>
/// 指定されたセーブファイルが本コーデックで処理可能かを判定します。
/// </summary>
@@ -67,14 +112,19 @@ namespace GameLauncher.Services.Codecs
public List<SaveDataPropertyEntry> LoadProperties(string filePath, string? optionalPassword = null)
{
var list = new List<SaveDataPropertyEntry>();
this._diagnostics.Clear();
this._document = null;
this._loadedFilePath = filePath;
this._wasEncrypted = false;
this._usedPassword = null;
this._wasGzip = false;
if (!File.Exists(filePath)) return list;
byte[] fileBytes = File.ReadAllBytes(filePath);
if (fileBytes.Length == 0) return list;
string? jsonText = null;
this._wasEncrypted = false;
this._usedPassword = null;
// 1. まず平文 JSON または Gzip 解凍を試みる
try
@@ -83,6 +133,7 @@ namespace GameLauncher.Services.Codecs
if (text.TrimStart().StartsWith("{") || text.TrimStart().StartsWith("["))
{
jsonText = text;
this._diagnostics.Add("平文 JSON として読み込みました。");
}
}
catch { }
@@ -96,60 +147,142 @@ namespace GameLauncher.Services.Codecs
using var gzip = new GZipStream(ms, CompressionMode.Decompress);
using var reader = new StreamReader(gzip, Encoding.UTF8);
jsonText = reader.ReadToEnd();
this._wasGzip = true;
this._diagnostics.Add("Gzip 圧縮を解凍して読み込みました。");
}
catch { }
}
// 3. パスワード指定または既定パスワードによる AES 復号を試みる
// 3. パスワードを多段フォールバックで解決して AES 復号する
if (jsonText == null)
{
var candidatePasswords = new List<string>();
if (!string.IsNullOrEmpty(optionalPassword))
{
candidatePasswords.Add(optionalPassword);
}
candidatePasswords.AddRange(new[] { "Moodkie", "password", "", "SaveData" });
var gameRoot = Path.GetDirectoryName(filePath);
var resolution = Es3PasswordResolver.Instance.Resolve(
filePath,
gameRootDirectory: gameRoot,
gameKey: gameRoot,
explicitPassword: optionalPassword);
foreach (var pwd in candidatePasswords)
this._diagnostics.AddRange(resolution.Diagnostics);
if (resolution.Success && !string.IsNullOrEmpty(resolution.Password))
{
var decrypted = this.TryDecryptAes(fileBytes, pwd);
if (!string.IsNullOrEmpty(decrypted))
jsonText = Es3PasswordResolver.TryDecrypt(fileBytes, resolution.Password);
if (!string.IsNullOrEmpty(jsonText))
{
jsonText = decrypted;
this._wasEncrypted = true;
this._usedPassword = pwd;
break;
this._usedPassword = resolution.Password;
}
}
}
if (string.IsNullOrEmpty(jsonText))
{
// JSON展開ができなかった場合、バイナリキー・バリュー形式として先頭・重要オフセットを抽出
this._diagnostics.Add("復号できませんでした。パスワードを手動で入力してください。");
return this.ExtractBinaryPropertiesFallback(fileBytes);
}
// JSON からプロパティを再帰的に展開
try
{
this._cachedRootNode = JsonNode.Parse(jsonText);
if (this._cachedRootNode is JsonObject rootObj)
{
this.FlattenJsonObject(rootObj, "", list);
}
else if (this._cachedRootNode is JsonArray rootArr)
{
this.FlattenJsonArray(rootArr, "Array", list);
}
}
catch
// 4. ES3 の型付き形式を解析してプロパティへ展開
var document = Es3SaveDocument.Parse(jsonText);
if (!document.IsLoaded)
{
this._diagnostics.AddRange(document.Warnings);
return this.ExtractBinaryPropertiesFallback(fileBytes);
}
this._document = document;
this._diagnostics.AddRange(document.Warnings);
this.FlattenNodes(document.RootNodes, string.Empty, list);
return list;
}
/// <summary>
/// 型付きノードを平坦化してプロパティ一覧へ変換します(型タグ付きで編集可能にします)。
/// </summary>
/// <param name="nodes">変換対象のノード</param>
/// <param name="prefix">現在の階層プレフィックス</param>
/// <param name="list">追加先のプロパティリスト</param>
private void FlattenNodes(List<Es3Node> nodes, string prefix, List<SaveDataPropertyEntry> list)
{
foreach (var node in nodes)
{
var key = string.IsNullOrEmpty(prefix) ? node.Key : $"{prefix}.{node.Key}";
var category = string.IsNullOrEmpty(prefix) ? "基本変数" : prefix;
if (node.HasChildren)
{
list.Add(new SaveDataPropertyEntry
{
Key = key,
Category = category,
Type = FormatKindLabel(node),
EditValue = node.DisplayValue,
Description = $"JSON パス: {node.Path}",
RawData = node,
Kind = MapToValueKind(node.Kind)
});
this.FlattenNodes(node.Children, key, list);
continue;
}
list.Add(new SaveDataPropertyEntry
{
Key = key,
Category = category,
Type = FormatKindLabel(node),
EditValue = node.DisplayValue,
Description = $"JSON パス: {node.Path}",
RawData = node,
Kind = MapToValueKind(node.Kind)
});
}
}
/// <summary>
/// ES3 の値種別を、GUI の型別エディタ用の種別へ変換します。
/// </summary>
/// <param name="kind">ES3 の値種別</param>
/// <returns>GUI 用の値種別</returns>
private static SaveDataPropertyEntry.ValueKind MapToValueKind(Es3ValueKind kind)
{
return kind switch
{
Es3ValueKind.Boolean => SaveDataPropertyEntry.ValueKind.Boolean,
Es3ValueKind.Integer => SaveDataPropertyEntry.ValueKind.Integer,
Es3ValueKind.Float => SaveDataPropertyEntry.ValueKind.Float,
Es3ValueKind.String => SaveDataPropertyEntry.ValueKind.String,
Es3ValueKind.Enum => SaveDataPropertyEntry.ValueKind.Enum,
Es3ValueKind.Array or Es3ValueKind.Dictionary or Es3ValueKind.Object
=> SaveDataPropertyEntry.ValueKind.Complex,
_ => SaveDataPropertyEntry.ValueKind.Unknown
};
}
/// <summary>
/// ノードの型名を表示用ラベルに整形します。
/// </summary>
/// <param name="node">対象ノード</param>
/// <returns>表示用の型ラベル</returns>
private static string FormatKindLabel(Es3Node node)
{
var kind = node.Kind switch
{
Es3ValueKind.Boolean => "bool",
Es3ValueKind.Integer => "int",
Es3ValueKind.Float => "float",
Es3ValueKind.String => "string",
Es3ValueKind.Enum => "enum",
Es3ValueKind.Array => "array",
Es3ValueKind.Dictionary => "dictionary",
Es3ValueKind.Object => "object",
_ => "unknown"
};
return string.IsNullOrEmpty(node.TypeName) ? kind : $"{kind} ({node.TypeName})";
}
/// <summary>
/// JSONオブジェクトを再帰的に走査し、プロパティ一覧に追加します。
/// </summary>
@@ -312,40 +445,71 @@ namespace GameLauncher.Services.Codecs
{
try
{
if (this._cachedRootNode != null)
if (this._document is { IsLoaded: true } document)
{
// JSON の値を更新
// 編集値を解析ツリーへ適用する
foreach (var prop in properties)
{
if (prop.RawData is string keyPath)
if (!prop.IsModified || prop.RawData is not Es3Node node)
{
this.UpdateJsonNodeByPath(this._cachedRootNode, keyPath, prop.EditValue, prop.Type);
continue;
}
if (!node.IsEditable)
{
continue;
}
if (document.TrySetValue(node.Path, prop.EditValue, out var applyError))
{
node.DisplayValue = prop.EditValue;
}
else
{
this._diagnostics.Add($"'{prop.Key}' の適用をスキップしました: {applyError}");
}
}
var options = new JsonSerializerOptions
// 変更がなければ書き込まない
if (!document.HasChanges())
{
WriteIndented = true,
Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping
};
string updatedJson = this._cachedRootNode.ToJsonString(options);
byte[] outputBytes = Encoding.UTF8.GetBytes(updatedJson);
// もともと暗号化されていた場合は再暗号化
if (this._wasEncrypted)
{
string pwd = !string.IsNullOrEmpty(optionalPassword) ? optionalPassword : (this._usedPassword ?? "Moodkie");
outputBytes = this.EncryptAes(outputBytes, pwd);
this._diagnostics.Add("変更点がないため保存をスキップしました。");
return true;
}
// バックアップ作成
byte[] outputBytes = Encoding.UTF8.GetBytes(document.ToJson());
// もともと Gzip 圧縮されていた場合は再圧縮する
if (this._wasGzip)
{
outputBytes = CompressGzip(outputBytes);
}
// もともと暗号化されていた場合は同一パスワードで再暗号化する
if (this._wasEncrypted)
{
var pwd = !string.IsNullOrEmpty(optionalPassword)
? optionalPassword!
: this._usedPassword ?? string.Empty;
outputBytes = Es3PasswordResolver.Encrypt(outputBytes, pwd);
}
// 往復検証: 書き込み前に「出力バイト列を読み直して構造が一致するか」を確認する
if (!this.VerifyRoundTrip(outputBytes, document, out var verifyError))
{
this._diagnostics.Add($"往復検証に失敗したため保存を中止しました: {verifyError}");
return false;
}
// バックアップ作成(既存規約に従い .bak を残す)
if (File.Exists(filePath))
{
File.Copy(filePath, filePath + ".bak", overwrite: true);
}
File.WriteAllBytes(filePath, outputBytes);
this._diagnostics.Add($"保存しました({outputBytes.Length} bytes)。");
return true;
}
else
@@ -372,12 +536,91 @@ namespace GameLauncher.Services.Codecs
return true;
}
}
catch
catch (Exception ex)
{
this._diagnostics.Add($"保存中に例外が発生しました: {ex.Message}");
return false;
}
}
/// <summary>
/// 出力バイト列を読み直して編集内容が保持されているかを検証します(往復検証)。
/// 検証に失敗した場合はファイルへ書き込まず、元データを温存します。
/// </summary>
/// <param name="outputBytes">書き込み予定のバイト列</param>
/// <param name="document">編集済みドキュメント</param>
/// <param name="error">検証失敗の理由</param>
/// <returns>検証に成功した場合 true</returns>
private bool VerifyRoundTrip(byte[] outputBytes, Es3SaveDocument document, out string error)
{
error = string.Empty;
try
{
string? verifiedJson;
if (this._wasEncrypted)
{
var pwd = this._usedPassword ?? string.Empty;
verifiedJson = Es3PasswordResolver.TryDecrypt(outputBytes, pwd);
}
else if (this._wasGzip)
{
using var ms = new MemoryStream(outputBytes);
using var gzip = new GZipStream(ms, CompressionMode.Decompress);
using var reader = new StreamReader(gzip, Encoding.UTF8);
verifiedJson = reader.ReadToEnd();
}
else
{
verifiedJson = Encoding.UTF8.GetString(outputBytes);
}
if (string.IsNullOrEmpty(verifiedJson))
{
error = "出力データを復号・解凍できませんでした。";
return false;
}
var reparsed = Es3SaveDocument.Parse(verifiedJson);
if (!reparsed.IsLoaded)
{
error = "出力データを再解析できませんでした。";
return false;
}
// ルート直下の要素数が一致することを最低条件とする
if (reparsed.RootNodes.Count != document.RootNodes.Count)
{
error = $"要素数が一致しません(期待 {document.RootNodes.Count} / 実際 {reparsed.RootNodes.Count})。";
return false;
}
return true;
}
catch (Exception ex)
{
error = ex.Message;
return false;
}
}
/// <summary>
/// バイト列を Gzip 圧縮します(元が Gzip だった場合に元形式を維持するため)。
/// </summary>
/// <param name="plainBytes">平文バイト列</param>
/// <returns>圧縮済みバイト列</returns>
private static byte[] CompressGzip(byte[] plainBytes)
{
using var output = new MemoryStream();
using (var gzip = new GZipStream(output, CompressionLevel.Optimal, leaveOpen: true))
{
gzip.Write(plainBytes, 0, plainBytes.Length);
}
return output.ToArray();
}
/// <summary>
/// キーパスに基づいてJSONノードの値を更新します。
/// </summary>