機能追加: Bakin・NW.jsエンジンおよびセーブ編集対応、ES3パスワード解決機能とRPGツクールMZ修正サービスの追加
This commit is contained in:
1 parent
f50976a6c0
commit
152abae1f8
33 files changed
+11356
-175
No files matched your search
@@ -0,0 +1,585 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Text.RegularExpressions;
|
||||
|
||||
namespace GameLauncher.Services.Codecs.Es3
|
||||
{
|
||||
/// <summary>
|
||||
/// ゲームのバイナリから ES3 のパスワード候補文字列を抽出する汎用ヘルパー。
|
||||
///
|
||||
/// Easy Save 3 のパスワードは <c>new ES3Settings(ES3.EncryptionType.AES, "password")</c> のように
|
||||
/// コード中の文字列リテラルとして埋め込まれることが多いため、
|
||||
/// マネージドアセンブリ(Mono)/IL2CPP メタデータの双方から文字列を回収します。
|
||||
/// 特定のゲーム名に依存しない汎用実装です。
|
||||
/// </summary>
|
||||
public static class Es3PasswordExtractor
|
||||
{
|
||||
/// <summary>文字列抽出対象とする最大ファイルサイズ(バイト)。巨大ファイルの全走査を避けます。</summary>
|
||||
private const long MaxScanFileSize = 512L * 1024 * 1024;
|
||||
|
||||
/// <summary>1 ファイルあたりに保持する候補の上限。</summary>
|
||||
private const int MaxCandidatesPerFile = 4000;
|
||||
|
||||
/// <summary>抽出する文字列の最小長。</summary>
|
||||
private const int MinCandidateLength = 3;
|
||||
|
||||
/// <summary>抽出する文字列の最大長。</summary>
|
||||
private const int MaxCandidateLength = 64;
|
||||
|
||||
/// <summary>ES3 の既定設定アセットにおいて暗号化パスワードを保持するフィールド名。</summary>
|
||||
private const string FieldNameEncryptionPassword = "encryptionPassword";
|
||||
|
||||
/// <summary>
|
||||
/// パスワードらしい文字列のみを通すための許可パターン(英数字記号のみ、空白・制御文字を除外)。
|
||||
/// </summary>
|
||||
private static readonly Regex CandidatePattern =
|
||||
new(@"^[\x21-\x7E]{3,64}$", RegexOptions.Compiled);
|
||||
|
||||
/// <summary>
|
||||
/// ES3 のパスワード指定箇所の近傍を示す手がかりキーワード。
|
||||
/// これらを含む文字列は優先的に候補の先頭へ寄せます。
|
||||
/// </summary>
|
||||
private static readonly string[] PasswordHints =
|
||||
[
|
||||
"password", "Password", "PASSWORD",
|
||||
"pass", "Pass", "pwd", "Pwd",
|
||||
"encrypt", "Encrypt", "encryption", "Encryption",
|
||||
"ES3Settings", "ES3", "es3"
|
||||
];
|
||||
|
||||
/// <summary>
|
||||
/// 明らかにパスワードではない文字列(Unity の内部名・型名・UI ラベルなど)を除外するパターン。
|
||||
///
|
||||
/// 実ゲーム検証では "GUILayoutPasswordField" のような UI クラス名や
|
||||
/// "The password Text" のような説明文が大量に抽出され、真のパスワードが埋もれていました。
|
||||
/// それらを除外して候補の精度を上げます。
|
||||
/// </summary>
|
||||
private static readonly Regex NoisePattern = new(
|
||||
@"^(Unity|UnityEngine|UnityEditor|System|Microsoft|Mono|mscorlib|netstandard|" +
|
||||
@"Assembly-CSharp|Library|Packages|Assets|Resources|StreamingAssets|" +
|
||||
@"com\.unity|Unity\.|UnityEngine\.|System\.)" +
|
||||
@"|PasswordField|passwordField|TextField|password Text|Password Text" +
|
||||
@"|GUILayout|OnGUI|m_[A-Z]|get_|set_|<[A-Za-z]",
|
||||
RegexOptions.Compiled);
|
||||
|
||||
/// <summary>
|
||||
/// 空白を含む文字列は UI ラベル・説明文である可能性が高いため、
|
||||
/// パスワード候補としては扱いません(パスワードは通常 1 トークン)。
|
||||
/// </summary>
|
||||
private static readonly Regex SentenceLikePattern = new(
|
||||
@"\s{1,}.*\s|[.!?]$",
|
||||
RegexOptions.Compiled);
|
||||
|
||||
/// <summary>
|
||||
/// ゲームルートディレクトリから ES3 パスワード候補を抽出します。
|
||||
/// </summary>
|
||||
/// <param name="gameRootDirectory">ゲームのルートディレクトリ</param>
|
||||
/// <param name="diagnostics">診断メッセージの追加先(null 可)</param>
|
||||
/// <returns>優先度順に並んだパスワード候補</returns>
|
||||
public static List<string> ExtractCandidates(string gameRootDirectory, List<string>? diagnostics = null)
|
||||
{
|
||||
var result = new List<string>();
|
||||
if (string.IsNullOrWhiteSpace(gameRootDirectory) || !Directory.Exists(gameRootDirectory))
|
||||
{
|
||||
diagnostics?.Add($"ゲームフォルダが見つかりません: {gameRootDirectory}");
|
||||
return result;
|
||||
}
|
||||
|
||||
var scanTargets = CollectScanTargets(gameRootDirectory);
|
||||
if (scanTargets.Count == 0)
|
||||
{
|
||||
diagnostics?.Add("文字列抽出の対象ファイル(マネージドアセンブリ/IL2CPPメタデータ)が見つかりませんでした。");
|
||||
return result;
|
||||
}
|
||||
|
||||
diagnostics?.Add($"文字列抽出対象: {scanTargets.Count} ファイル");
|
||||
|
||||
// 「パスワード指定の近傍にある文字列」を高優先、「その他の文字列」を低優先として収集する
|
||||
var settingsDerived = new List<string>();
|
||||
var highPriority = new List<string>();
|
||||
var lowPriority = new List<string>();
|
||||
var seen = new HashSet<string>(StringComparer.Ordinal);
|
||||
|
||||
foreach (var path in scanTargets)
|
||||
{
|
||||
try
|
||||
{
|
||||
var info = new FileInfo(path);
|
||||
if (!info.Exists || info.Length == 0 || info.Length > MaxScanFileSize)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
var bytes = File.ReadAllBytes(path);
|
||||
|
||||
// ES3Defaults の encryptionPassword フィールドを持つアセットは、
|
||||
// 値域に格納された文字列をパスワード候補として最優先で回収する
|
||||
CollectFromEs3DefaultSettings(bytes, settingsDerived, seen);
|
||||
|
||||
CollectFromBytes(bytes, highPriority, lowPriority, seen);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
diagnostics?.Add($"読み込み失敗: {Path.GetFileName(path)} ({ex.Message})");
|
||||
}
|
||||
}
|
||||
|
||||
if (settingsDerived.Count > 0)
|
||||
{
|
||||
diagnostics?.Add($"ES3Defaults の encryptionPassword 近傍から {settingsDerived.Count} 件の候補を抽出しました。");
|
||||
}
|
||||
|
||||
// ES3Defaults 由来 → 高優先 → 低優先の順で連結
|
||||
foreach (var candidate in settingsDerived.Concat(highPriority).Concat(lowPriority))
|
||||
{
|
||||
if (result.Count >= 512)
|
||||
{
|
||||
break;
|
||||
}
|
||||
|
||||
result.Add(candidate);
|
||||
}
|
||||
|
||||
diagnostics?.Add(
|
||||
$"抽出候補数: {result.Count}(設定由来 {settingsDerived.Count} / 高優先 {highPriority.Count} / 低優先 {lowPriority.Count})");
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// ES3 の既定設定(<c>ES3Defaults</c>)を持つアセットから、<c>encryptionPassword</c> の値候補を抽出します。
|
||||
///
|
||||
/// Unity のアセットは「フィールド名テーブル」と「値テーブル」が分離しており、
|
||||
/// フィールド名の直後に値があるとは限りません。そのため、フィールド名が存在するアセットでは
|
||||
/// ファイル全体の文字列を候補化しつつ、パスワードらしい短い文字列を優先的に先頭へ寄せます。
|
||||
/// </summary>
|
||||
/// <param name="bytes">アセットのバイト列</param>
|
||||
/// <param name="settingsDerived">設定由来の候補の追加先</param>
|
||||
/// <param name="seen">重複排除用の集合</param>
|
||||
private static void CollectFromEs3DefaultSettings(
|
||||
byte[] bytes,
|
||||
List<string> settingsDerived,
|
||||
HashSet<string> seen)
|
||||
{
|
||||
if (bytes.Length == 0)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
// 高速化のため、まず encryptionPassword の存在を確認する
|
||||
bool hasField;
|
||||
try
|
||||
{
|
||||
var probeLength = Math.Min(bytes.Length, 4 * 1024 * 1024);
|
||||
var probe = Encoding.ASCII.GetString(bytes, 0, probeLength);
|
||||
hasField = probe.Contains(FieldNameEncryptionPassword, StringComparison.Ordinal);
|
||||
}
|
||||
catch
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
if (!hasField)
|
||||
{
|
||||
// 巨大アセットでは先頭 4MB に無いことが多いため、全体を再度確認する
|
||||
try
|
||||
{
|
||||
var all = Encoding.ASCII.GetString(bytes);
|
||||
hasField = all.Contains(FieldNameEncryptionPassword, StringComparison.Ordinal);
|
||||
}
|
||||
catch
|
||||
{
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
if (!hasField)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
// フィールド名が存在するアセットの文字列を候補化する
|
||||
var asciiCandidates = new List<string>();
|
||||
var utf16Candidates = new List<string>();
|
||||
CollectAsciiStrings(bytes, asciiCandidates, asciiCandidates, seen, 0);
|
||||
CollectUtf16Strings(bytes, utf16Candidates, utf16Candidates, seen, 0);
|
||||
|
||||
// 実ゲーム検証では、PlayMaker アクションのスキーマ定義に encryptionPassword が
|
||||
// 並ぶだけで実際の値は別領域にあり、無関係な文字列が大量に候補化されました。
|
||||
// パスワード指定の手がかり(password / encrypt 等)を含む文字列だけに絞り込みます。
|
||||
foreach (var candidate in asciiCandidates.Concat(utf16Candidates))
|
||||
{
|
||||
if (!ContainsPasswordHint(candidate))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
if (LooksLikePasswordValue(candidate) && !settingsDerived.Contains(candidate))
|
||||
{
|
||||
settingsDerived.Add(candidate);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 文字列がパスワード値そのものらしいかを判定します(フィールド名や型名を除外)。
|
||||
/// </summary>
|
||||
/// <param name="candidate">候補文字列</param>
|
||||
/// <returns>パスワード値らしい場合 true</returns>
|
||||
private static bool LooksLikePasswordValue(string candidate)
|
||||
{
|
||||
if (candidate.Length < 3 || candidate.Length > 32)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
// ES3 の設定フィールド名・型名は値ではない
|
||||
if (candidate.Equals(FieldNameEncryptionPassword, StringComparison.OrdinalIgnoreCase) ||
|
||||
candidate.Equals("encryptionType", StringComparison.OrdinalIgnoreCase) ||
|
||||
candidate.Equals("compressionType", StringComparison.OrdinalIgnoreCase) ||
|
||||
candidate.Equals("bufferSize", StringComparison.OrdinalIgnoreCase) ||
|
||||
candidate.Equals("errorMessage", StringComparison.OrdinalIgnoreCase) ||
|
||||
candidate.Equals("overrideDefaultSettings", StringComparison.OrdinalIgnoreCase) ||
|
||||
candidate.StartsWith("ES3", StringComparison.Ordinal))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
// 空白・記号のみのものは除外
|
||||
if (candidate.Contains(' '))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
return IsPlausibleCandidate(candidate);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 走査対象のファイル一覧を収集します。
|
||||
/// Mono の場合は Managed 配下の DLL、IL2CPP の場合は GameAssembly.dll と global-metadata.dat を対象にします。
|
||||
/// </summary>
|
||||
/// <param name="gameRootDirectory">ゲームのルートディレクトリ</param>
|
||||
/// <returns>走査対象ファイルの絶対パス一覧</returns>
|
||||
private static List<string> CollectScanTargets(string gameRootDirectory)
|
||||
{
|
||||
var targets = new List<string>();
|
||||
|
||||
try
|
||||
{
|
||||
// 1. Mono: <Game>_Data\Managed\*.dll(Assembly-CSharp.dll を最優先)
|
||||
foreach (var dataDir in Directory.GetDirectories(gameRootDirectory))
|
||||
{
|
||||
if (!Path.GetFileName(dataDir).EndsWith("_Data", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
var managedDir = Path.Combine(dataDir, "Managed");
|
||||
if (Directory.Exists(managedDir))
|
||||
{
|
||||
var dlls = Directory.GetFiles(managedDir, "*.dll", SearchOption.TopDirectoryOnly)
|
||||
.Where(f =>
|
||||
{
|
||||
var name = Path.GetFileName(f);
|
||||
return !name.StartsWith("Unity", StringComparison.OrdinalIgnoreCase) &&
|
||||
!name.StartsWith("System", StringComparison.OrdinalIgnoreCase) &&
|
||||
!name.StartsWith("Mono", StringComparison.OrdinalIgnoreCase) &&
|
||||
!name.StartsWith("mscorlib", StringComparison.OrdinalIgnoreCase) &&
|
||||
!name.StartsWith("netstandard", StringComparison.OrdinalIgnoreCase);
|
||||
})
|
||||
.OrderByDescending(f =>
|
||||
Path.GetFileName(f).StartsWith("Assembly-CSharp", StringComparison.OrdinalIgnoreCase))
|
||||
.ToList();
|
||||
|
||||
targets.AddRange(dlls);
|
||||
}
|
||||
|
||||
// 2. IL2CPP: il2cpp_data\Metadata\global-metadata.dat
|
||||
var metadata = Path.Combine(dataDir, "il2cpp_data", "Metadata", "global-metadata.dat");
|
||||
if (File.Exists(metadata))
|
||||
{
|
||||
targets.Add(metadata);
|
||||
}
|
||||
|
||||
// 3. ES3 の既定設定(ES3Defaults ScriptableObject)はアセットに格納されるため、
|
||||
// アセット内の文字列も走査対象に含める。コード側にパスワードリテラルが
|
||||
// 存在しないゲームでは、ここが唯一の手がかりになる。
|
||||
targets.AddRange(CollectAssetTargets(dataDir));
|
||||
}
|
||||
|
||||
// 3. IL2CPP: ルート直下の GameAssembly.dll
|
||||
var gameAssembly = Path.Combine(gameRootDirectory, "GameAssembly.dll");
|
||||
if (File.Exists(gameAssembly))
|
||||
{
|
||||
targets.Add(gameAssembly);
|
||||
}
|
||||
}
|
||||
catch
|
||||
{
|
||||
// 列挙失敗時は取得できた分だけ返す
|
||||
}
|
||||
|
||||
return targets;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// ES3 の既定設定(<c>ES3Defaults</c> ScriptableObject)が格納され得るアセットファイルを収集します。
|
||||
///
|
||||
/// 実ゲーム検証ではコード側にパスワードリテラルが存在せず(<c>encryption</c> 文字列すら無い)、
|
||||
/// 既定設定アセットにのみパスワードが入っているケースがありました。
|
||||
/// 巨大な .resS / .bundle を避け、テキスト情報を持つ .assets 系に限定します。
|
||||
/// </summary>
|
||||
/// <param name="dataDirectory">ゲームの *_Data ディレクトリ</param>
|
||||
/// <returns>走査対象アセットの絶対パス一覧</returns>
|
||||
private static List<string> CollectAssetTargets(string dataDirectory)
|
||||
{
|
||||
var targets = new List<string>();
|
||||
|
||||
try
|
||||
{
|
||||
var extensionSet = new HashSet<string>(StringComparer.OrdinalIgnoreCase)
|
||||
{
|
||||
".assets", ".asset", ".json", ".bytes", ".dat"
|
||||
};
|
||||
|
||||
foreach (var file in Directory.GetFiles(dataDirectory, "*", SearchOption.TopDirectoryOnly))
|
||||
{
|
||||
var ext = Path.GetExtension(file);
|
||||
if (!extensionSet.Contains(ext))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
var info = new FileInfo(file);
|
||||
if (info.Length == 0 || info.Length > MaxScanFileSize)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
targets.Add(file);
|
||||
}
|
||||
}
|
||||
catch
|
||||
{
|
||||
// 列挙失敗時は取得できた分だけ返す
|
||||
}
|
||||
|
||||
return targets;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// バイト列から ASCII 文字列を抽出し、優先度別のリストへ振り分けます。
|
||||
///
|
||||
/// .NET アセンブリ(Assembly-CSharp.dll 等)の文字列定数は UTF-16LE で格納されるため、
|
||||
/// 8bit ASCII 走査に加えて 16bit 走査も行います。これを行わないと
|
||||
/// コード中のパスワードリテラルを取り逃がします。
|
||||
/// </summary>
|
||||
/// <param name="bytes">対象バイト列</param>
|
||||
/// <param name="highPriority">パスワード指定近傍の候補の追加先</param>
|
||||
/// <param name="lowPriority">その他の候補の追加先</param>
|
||||
/// <param name="seen">重複排除用の集合</param>
|
||||
private static void CollectFromBytes(
|
||||
byte[] bytes,
|
||||
List<string> highPriority,
|
||||
List<string> lowPriority,
|
||||
HashSet<string> seen)
|
||||
{
|
||||
int count = 0;
|
||||
|
||||
count = CollectAsciiStrings(bytes, highPriority, lowPriority, seen, count);
|
||||
if (count >= MaxCandidatesPerFile)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
// UTF-16LE(.NET の文字列定数)としても走査する
|
||||
CollectUtf16Strings(bytes, highPriority, lowPriority, seen, count);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 8bit ASCII 文字列を抽出します。
|
||||
/// </summary>
|
||||
/// <param name="bytes">対象バイト列</param>
|
||||
/// <param name="highPriority">高優先候補の追加先</param>
|
||||
/// <param name="lowPriority">低優先候補の追加先</param>
|
||||
/// <param name="seen">重複排除用の集合</param>
|
||||
/// <param name="count">既に追加済みの件数</param>
|
||||
/// <returns>追加後の件数</returns>
|
||||
private static int CollectAsciiStrings(
|
||||
byte[] bytes,
|
||||
List<string> highPriority,
|
||||
List<string> lowPriority,
|
||||
HashSet<string> seen,
|
||||
int count)
|
||||
{
|
||||
var current = new StringBuilder(MaxCandidateLength);
|
||||
|
||||
for (int i = 0; i < bytes.Length; i++)
|
||||
{
|
||||
byte b = bytes[i];
|
||||
|
||||
// 印字可能な ASCII のみを文字列として扱う
|
||||
if (b >= 0x21 && b <= 0x7E)
|
||||
{
|
||||
if (current.Length < MaxCandidateLength)
|
||||
{
|
||||
current.Append((char)b);
|
||||
}
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
count = FlushCandidate(current, highPriority, lowPriority, seen, count);
|
||||
if (count >= MaxCandidatesPerFile)
|
||||
{
|
||||
return count;
|
||||
}
|
||||
|
||||
current.Clear();
|
||||
}
|
||||
|
||||
return FlushCandidate(current, highPriority, lowPriority, seen, count);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// UTF-16LE(下位バイトが印字可能 ASCII、上位バイトが 0x00)の文字列を抽出します。
|
||||
/// </summary>
|
||||
/// <param name="bytes">対象バイト列</param>
|
||||
/// <param name="highPriority">高優先候補の追加先</param>
|
||||
/// <param name="lowPriority">低優先候補の追加先</param>
|
||||
/// <param name="seen">重複排除用の集合</param>
|
||||
/// <param name="count">既に追加済みの件数</param>
|
||||
/// <returns>追加後の件数</returns>
|
||||
private static int CollectUtf16Strings(
|
||||
byte[] bytes,
|
||||
List<string> highPriority,
|
||||
List<string> lowPriority,
|
||||
HashSet<string> seen,
|
||||
int count)
|
||||
{
|
||||
var current = new StringBuilder(MaxCandidateLength);
|
||||
|
||||
for (int i = 0; i + 1 < bytes.Length; i += 2)
|
||||
{
|
||||
byte lo = bytes[i];
|
||||
byte hi = bytes[i + 1];
|
||||
|
||||
if (lo >= 0x21 && lo <= 0x7E && hi == 0x00)
|
||||
{
|
||||
if (current.Length < MaxCandidateLength)
|
||||
{
|
||||
current.Append((char)lo);
|
||||
}
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
count = FlushCandidate(current, highPriority, lowPriority, seen, count);
|
||||
if (count >= MaxCandidatesPerFile)
|
||||
{
|
||||
return count;
|
||||
}
|
||||
|
||||
current.Clear();
|
||||
}
|
||||
|
||||
return FlushCandidate(current, highPriority, lowPriority, seen, count);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 蓄積中の文字列を候補として確定し、優先度別リストへ追加します。
|
||||
/// </summary>
|
||||
/// <param name="buffer">蓄積中の文字列バッファ</param>
|
||||
/// <param name="highPriority">高優先候補の追加先</param>
|
||||
/// <param name="lowPriority">低優先候補の追加先</param>
|
||||
/// <param name="seen">重複排除用の集合</param>
|
||||
/// <param name="count">既に追加済みの件数</param>
|
||||
/// <returns>追加後の件数</returns>
|
||||
private static int FlushCandidate(
|
||||
StringBuilder buffer,
|
||||
List<string> highPriority,
|
||||
List<string> lowPriority,
|
||||
HashSet<string> seen,
|
||||
int count)
|
||||
{
|
||||
if (buffer.Length < MinCandidateLength || buffer.Length > MaxCandidateLength)
|
||||
{
|
||||
return count;
|
||||
}
|
||||
|
||||
var candidate = buffer.ToString();
|
||||
if (!IsPlausibleCandidate(candidate) || !seen.Add(candidate))
|
||||
{
|
||||
return count;
|
||||
}
|
||||
|
||||
if (ContainsPasswordHint(candidate))
|
||||
{
|
||||
highPriority.Add(candidate);
|
||||
}
|
||||
else
|
||||
{
|
||||
lowPriority.Add(candidate);
|
||||
}
|
||||
|
||||
return count + 1;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 抽出した文字列がパスワード候補として妥当かどうかを判定します。
|
||||
/// </summary>
|
||||
/// <param name="candidate">候補文字列</param>
|
||||
/// <returns>妥当な場合 true</returns>
|
||||
private static bool IsPlausibleCandidate(string candidate)
|
||||
{
|
||||
if (!CandidatePattern.IsMatch(candidate))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
// 空白を含む説明文・UI ラベルは除外
|
||||
if (SentenceLikePattern.IsMatch(candidate))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
// Unity の内部名・名前空間などはノイズとして除外
|
||||
if (NoisePattern.IsMatch(candidate))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
// 拡張子付きファイル名は除外
|
||||
if (candidate.EndsWith(".dll", StringComparison.OrdinalIgnoreCase) ||
|
||||
candidate.EndsWith(".dat", StringComparison.OrdinalIgnoreCase) ||
|
||||
candidate.EndsWith(".es3", StringComparison.OrdinalIgnoreCase) ||
|
||||
candidate.EndsWith(".json", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 文字列がパスワード指定箇所の手がかりを含むかを判定します。
|
||||
/// </summary>
|
||||
/// <param name="candidate">候補文字列</param>
|
||||
/// <returns>手がかりを含む場合 true</returns>
|
||||
private static bool ContainsPasswordHint(string candidate)
|
||||
{
|
||||
foreach (var hint in PasswordHints)
|
||||
{
|
||||
if (candidate.Contains(hint, StringComparison.Ordinal))
|
||||
{
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,559 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Security.Cryptography;
|
||||
using System.Text;
|
||||
|
||||
namespace GameLauncher.Services.Codecs.Es3
|
||||
{
|
||||
/// <summary>
|
||||
/// "どの段階でパスワードが判明したか" を表す解決手段の種別。
|
||||
/// </summary>
|
||||
public enum Es3PasswordSource
|
||||
{
|
||||
/// <summary>学習キャッシュ(過去に解決済みのパスワード)から復元。</summary>
|
||||
LearnedCache,
|
||||
|
||||
/// <summary>呼び出し元が明示指定したパスワード。</summary>
|
||||
Explicit,
|
||||
|
||||
/// <summary>ゲーム内のマネージドアセンブリ(Assembly-CSharp.dll 等)の文字列リテラルから抽出。</summary>
|
||||
GameBinaryStrings,
|
||||
|
||||
/// <summary>ゲーム内バイナリ(IL2CPP の GameAssembly.dll / global-metadata.dat)から抽出。</summary>
|
||||
GameIl2CppMetadata,
|
||||
|
||||
/// <summary>ユーザー辞書ファイル/既定の候補リストからの探索。</summary>
|
||||
Dictionary,
|
||||
|
||||
/// <summary>平文のまま(暗号化されていない)。</summary>
|
||||
PlainText
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// ES3 パスワード解決の結果。<see cref="Success"/> が false の場合は <see cref="Diagnostics"/> に理由が入ります。
|
||||
/// </summary>
|
||||
public sealed class Es3PasswordResolution
|
||||
{
|
||||
/// <summary>解決に成功したか。</summary>
|
||||
public bool Success { get; init; }
|
||||
|
||||
/// <summary>解決したパスワード(平文・暗号化なしの場合は空文字)。</summary>
|
||||
public string Password { get; init; } = string.Empty;
|
||||
|
||||
/// <summary>解決手段の種別。</summary>
|
||||
public Es3PasswordSource Source { get; init; }
|
||||
|
||||
/// <summary>試行した候補数。</summary>
|
||||
public int TriedCandidates { get; init; }
|
||||
|
||||
/// <summary>診断用のメッセージ一覧(失敗理由・各段階の結果)。</summary>
|
||||
public IReadOnlyList<string> Diagnostics { get; init; } = [];
|
||||
|
||||
/// <summary>失敗結果を生成します。</summary>
|
||||
public static Es3PasswordResolution Fail(List<string> diagnostics, int tried)
|
||||
=> new() { Success = false, Diagnostics = diagnostics, TriedCandidates = tried };
|
||||
|
||||
/// <summary>成功結果を生成します。</summary>
|
||||
public static Es3PasswordResolution Ok(string password, Es3PasswordSource source, int tried)
|
||||
=> new() { Success = true, Password = password, Source = source, TriedCandidates = tried };
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// ES3 (Easy Save 3) の暗号化セーブデータからパスワードを多段フォールバックで特定する汎用リゾルバ。
|
||||
///
|
||||
/// 解決順序:
|
||||
/// 1. 学習キャッシュ(<see cref="Es3PasswordStore"/>)
|
||||
/// 2. 呼び出し元の明示指定
|
||||
/// 3. ゲームのマネージドアセンブリ文字列リテラル抽出(Mono)
|
||||
/// 4. 既定候補 + ユーザー辞書による探索
|
||||
///
|
||||
/// すべての候補は実際に AES 復号して妥当性を検証し、成功したものだけを採用します。
|
||||
/// これにより「誤ったパスワードで復号して壊れたデータを書く」事故を防止します。
|
||||
/// </summary>
|
||||
public sealed class Es3PasswordResolver
|
||||
{
|
||||
/// <summary>ES3 が AES 暗号化時にファイル先頭へ埋め込む IV の長さ(バイト)。</summary>
|
||||
public const int AesIvLength = 16;
|
||||
|
||||
/// <summary>復号結果が「ES3 の平文 JSON」らしいかを判定する際の最小文字数。</summary>
|
||||
private const int MinimumPlainTextLength = 2;
|
||||
|
||||
private readonly Es3PasswordStore _store;
|
||||
|
||||
/// <summary>
|
||||
/// 既定のストアを用いて <see cref="Es3PasswordResolver"/> を初期化します。
|
||||
/// </summary>
|
||||
public Es3PasswordResolver()
|
||||
: this(Es3PasswordStore.Instance)
|
||||
{
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 任意のストアを指定して <see cref="Es3PasswordResolver"/> を初期化します(テスト用途を含む)。
|
||||
/// </summary>
|
||||
/// <param name="store">学習済みパスワードの永続ストア</param>
|
||||
public Es3PasswordResolver(Es3PasswordStore store)
|
||||
{
|
||||
this._store = store ?? throw new ArgumentNullException(nameof(store));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 既定のシングルトンインスタンス。
|
||||
/// </summary>
|
||||
public static Es3PasswordResolver Instance { get; } = new();
|
||||
|
||||
/// <summary>
|
||||
/// ES3 のファイルが暗号化されているかどうかを統計的に判定します。
|
||||
/// 平文 JSON / Gzip はもちろん「暗号化されていない」と判定します。
|
||||
/// </summary>
|
||||
/// <param name="bytes">ファイル全体のバイト列</param>
|
||||
/// <returns>暗号化されている可能性が高い場合 true</returns>
|
||||
public static bool LooksEncrypted(byte[] bytes)
|
||||
{
|
||||
if (bytes == null || bytes.Length < AesIvLength * 2)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
// 平文 JSON はそのまま読める
|
||||
if (IsLikelyJson(bytes))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
// Gzip マジック
|
||||
if (bytes[0] == 0x1F && bytes[1] == 0x8B)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
// AES ブロック境界に一致し、かつ高エントロピーなら暗号化とみなす
|
||||
if (bytes.Length % AesIvLength != 0)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
return CalculateEntropy(bytes) >= 7.5;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// パスワードを多段フォールバックで解決します。
|
||||
/// </summary>
|
||||
/// <param name="saveFilePath">対象の .es3 ファイルの絶対パス</param>
|
||||
/// <param name="gameRootDirectory">ゲームのルートディレクトリ(文字列抽出元の探索に使用)</param>
|
||||
/// <param name="gameKey">学習キャッシュのキー(通常はゲームのルートディレクトリ)</param>
|
||||
/// <param name="explicitPassword">呼び出し元が既に知っているパスワード(任意)</param>
|
||||
/// <param name="userDictionaryPath">追加候補を列挙したテキストファイルのパス(任意)</param>
|
||||
/// <returns>解決結果</returns>
|
||||
public Es3PasswordResolution Resolve(
|
||||
string saveFilePath,
|
||||
string? gameRootDirectory = null,
|
||||
string? gameKey = null,
|
||||
string? explicitPassword = null,
|
||||
string? userDictionaryPath = null)
|
||||
{
|
||||
var diagnostics = new List<string>();
|
||||
int tried = 0;
|
||||
|
||||
byte[] fileBytes;
|
||||
try
|
||||
{
|
||||
fileBytes = File.ReadAllBytes(saveFilePath);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
diagnostics.Add($"セーブファイルを読み込めません: {ex.Message}");
|
||||
return Es3PasswordResolution.Fail(diagnostics, tried);
|
||||
}
|
||||
|
||||
if (fileBytes.Length == 0)
|
||||
{
|
||||
diagnostics.Add("セーブファイルが空です。");
|
||||
return Es3PasswordResolution.Fail(diagnostics, tried);
|
||||
}
|
||||
|
||||
// 暗号化されていない場合はパスワード不要
|
||||
if (!LooksEncrypted(fileBytes))
|
||||
{
|
||||
diagnostics.Add("暗号化は検出されませんでした(平文または Gzip)。");
|
||||
return Es3PasswordResolution.Ok(string.Empty, Es3PasswordSource.PlainText, tried);
|
||||
}
|
||||
|
||||
diagnostics.Add($"暗号化を検出しました({fileBytes.Length} bytes / AES-128-CBC 相当)。");
|
||||
|
||||
// ---- 段階 1: 学習キャッシュ ----
|
||||
var cacheKey = this.BuildCacheKey(gameKey, saveFilePath);
|
||||
if (!string.IsNullOrEmpty(cacheKey))
|
||||
{
|
||||
var learned = this._store.TryGet(cacheKey);
|
||||
if (!string.IsNullOrEmpty(learned))
|
||||
{
|
||||
tried++;
|
||||
if (this.VerifyPassword(fileBytes, learned, out _))
|
||||
{
|
||||
diagnostics.Add("学習キャッシュのパスワードで復号に成功しました。");
|
||||
return Es3PasswordResolution.Ok(learned, Es3PasswordSource.LearnedCache, tried);
|
||||
}
|
||||
|
||||
diagnostics.Add("学習キャッシュのパスワードは無効でした(破棄します)。");
|
||||
this._store.Remove(cacheKey);
|
||||
}
|
||||
}
|
||||
|
||||
// ---- 段階 2: 明示指定 ----
|
||||
if (!string.IsNullOrEmpty(explicitPassword))
|
||||
{
|
||||
tried++;
|
||||
if (this.VerifyPassword(fileBytes, explicitPassword, out _))
|
||||
{
|
||||
diagnostics.Add("指定されたパスワードで復号に成功しました。");
|
||||
this.Remember(cacheKey, explicitPassword);
|
||||
return Es3PasswordResolution.Ok(explicitPassword, Es3PasswordSource.Explicit, tried);
|
||||
}
|
||||
|
||||
diagnostics.Add("指定されたパスワードでは復号できませんでした。");
|
||||
}
|
||||
|
||||
// ---- 段階 3: ゲームバイナリの文字列リテラル抽出 ----
|
||||
if (!string.IsNullOrEmpty(gameRootDirectory) && Directory.Exists(gameRootDirectory))
|
||||
{
|
||||
var extracted = Es3PasswordExtractor.ExtractCandidates(gameRootDirectory, diagnostics);
|
||||
foreach (var candidate in extracted)
|
||||
{
|
||||
tried++;
|
||||
if (this.VerifyPassword(fileBytes, candidate, out _))
|
||||
{
|
||||
diagnostics.Add($"ゲームバイナリから抽出した候補で復号に成功しました(候補: {Mask(candidate)})。");
|
||||
this.Remember(cacheKey, candidate);
|
||||
return Es3PasswordResolution.Ok(candidate, Es3PasswordSource.GameBinaryStrings, tried);
|
||||
}
|
||||
}
|
||||
|
||||
if (extracted.Count == 0)
|
||||
{
|
||||
diagnostics.Add("ゲームバイナリから有効なパスワード候補を抽出できませんでした。");
|
||||
}
|
||||
}
|
||||
|
||||
// ---- 段階 4: 既定候補 + ユーザー辞書 ----
|
||||
foreach (var candidate in this.EnumerateDictionaryCandidates(userDictionaryPath, diagnostics))
|
||||
{
|
||||
tried++;
|
||||
if (this.VerifyPassword(fileBytes, candidate, out _))
|
||||
{
|
||||
diagnostics.Add($"辞書探索で復号に成功しました(候補: {Mask(candidate)})。");
|
||||
this.Remember(cacheKey, candidate);
|
||||
return Es3PasswordResolution.Ok(candidate, Es3PasswordSource.Dictionary, tried);
|
||||
}
|
||||
}
|
||||
|
||||
diagnostics.Add($"すべての段階で復号に失敗しました(試行候補数: {tried})。パスワードを手動で入力してください。");
|
||||
return Es3PasswordResolution.Fail(diagnostics, tried);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 指定パスワードで ES3 ファイルを復号し、平文 JSON 文字列を取得します。
|
||||
/// </summary>
|
||||
/// <param name="fileBytes">ファイル全体のバイト列</param>
|
||||
/// <param name="password">パスワード</param>
|
||||
/// <param name="plainText">復号された平文 JSON</param>
|
||||
/// <returns>復号に成功した場合 true</returns>
|
||||
public bool VerifyPassword(byte[] fileBytes, string password, out string plainText)
|
||||
{
|
||||
plainText = string.Empty;
|
||||
var plain = TryDecrypt(fileBytes, password);
|
||||
if (plain == null)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
plainText = plain;
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// ES3 の AES-128-CBC 形式で復号を試みます。
|
||||
/// ファイル先頭 16 バイトを IV、残りを暗号文として扱い、鍵はパスワード UTF-8 の先頭 16 バイトをゼロ埋めします。
|
||||
/// </summary>
|
||||
/// <param name="fileBytes">ファイル全体のバイト列</param>
|
||||
/// <param name="password">パスワード</param>
|
||||
/// <returns>復号された平文 JSON。失敗時は null</returns>
|
||||
public static string? TryDecrypt(byte[] fileBytes, string password)
|
||||
{
|
||||
if (fileBytes == null || fileBytes.Length <= AesIvLength)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
var iv = new byte[AesIvLength];
|
||||
Array.Copy(fileBytes, 0, iv, 0, AesIvLength);
|
||||
|
||||
var cipher = new byte[fileBytes.Length - AesIvLength];
|
||||
Array.Copy(fileBytes, AesIvLength, cipher, 0, cipher.Length);
|
||||
|
||||
using var aes = Aes.Create();
|
||||
aes.Mode = CipherMode.CBC;
|
||||
aes.Padding = PaddingMode.PKCS7;
|
||||
aes.Key = DeriveKey(password);
|
||||
aes.IV = iv;
|
||||
|
||||
using var decryptor = aes.CreateDecryptor();
|
||||
var plain = decryptor.TransformFinalBlock(cipher, 0, cipher.Length);
|
||||
|
||||
var text = Encoding.UTF8.GetString(plain);
|
||||
return IsPlausiblePlainText(text) ? text : null;
|
||||
}
|
||||
catch
|
||||
{
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 平文バイト列を ES3 の AES-128-CBC 形式で暗号化します(IV を先頭に付与)。
|
||||
/// </summary>
|
||||
/// <param name="plainBytes">平文バイト列</param>
|
||||
/// <param name="password">パスワード</param>
|
||||
/// <returns>IV + 暗号文のバイト列</returns>
|
||||
public static byte[] Encrypt(byte[] plainBytes, string password)
|
||||
{
|
||||
using var aes = Aes.Create();
|
||||
aes.Mode = CipherMode.CBC;
|
||||
aes.Padding = PaddingMode.PKCS7;
|
||||
aes.Key = DeriveKey(password);
|
||||
aes.GenerateIV();
|
||||
|
||||
using var encryptor = aes.CreateEncryptor();
|
||||
var cipher = encryptor.TransformFinalBlock(plainBytes, 0, plainBytes.Length);
|
||||
|
||||
var result = new byte[aes.IV.Length + cipher.Length];
|
||||
Array.Copy(aes.IV, 0, result, 0, aes.IV.Length);
|
||||
Array.Copy(cipher, 0, result, aes.IV.Length, cipher.Length);
|
||||
return result;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// パスワード文字列から AES-128 用の 16 バイト鍵を導出します。
|
||||
/// </summary>
|
||||
/// <param name="password">パスワード</param>
|
||||
/// <returns>16 バイトの鍵</returns>
|
||||
private static byte[] DeriveKey(string password)
|
||||
{
|
||||
var raw = Encoding.UTF8.GetBytes(password ?? string.Empty);
|
||||
var key = new byte[16];
|
||||
Array.Copy(raw, key, Math.Min(raw.Length, key.Length));
|
||||
return key;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 復号結果が ES3 の平文として妥当かを判定します。
|
||||
/// </summary>
|
||||
/// <param name="text">復号された文字列</param>
|
||||
/// <returns>妥当な場合 true</returns>
|
||||
private static bool IsPlausiblePlainText(string text)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(text) || text.Length < MinimumPlainTextLength)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
var trimmed = text.TrimStart();
|
||||
if (trimmed.StartsWith('{') || trimmed.StartsWith('['))
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
// ES3 の内部シリアライズ形式は "__type" を必ず含む
|
||||
return text.Contains("__type", StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// バイト列が平文 JSON かどうかを判定します。
|
||||
/// </summary>
|
||||
/// <param name="bytes">対象バイト列</param>
|
||||
/// <returns>平文 JSON と判断できる場合 true</returns>
|
||||
private static bool IsLikelyJson(byte[] bytes)
|
||||
{
|
||||
try
|
||||
{
|
||||
int length = Math.Min(bytes.Length, 64);
|
||||
var head = Encoding.UTF8.GetString(bytes, 0, length).TrimStart();
|
||||
return head.StartsWith('{') || head.StartsWith('[');
|
||||
}
|
||||
catch
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// バイト列のシャノンエントロピー(bits/byte)を算出します。
|
||||
/// </summary>
|
||||
/// <param name="bytes">対象バイト列</param>
|
||||
/// <returns>エントロピー値</returns>
|
||||
private static double CalculateEntropy(byte[] bytes)
|
||||
{
|
||||
var frequency = new int[256];
|
||||
foreach (var b in bytes)
|
||||
{
|
||||
frequency[b]++;
|
||||
}
|
||||
|
||||
double entropy = 0.0;
|
||||
foreach (var count in frequency)
|
||||
{
|
||||
if (count == 0)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
double p = (double)count / bytes.Length;
|
||||
entropy -= p * Math.Log2(p);
|
||||
}
|
||||
|
||||
return entropy;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 学習キャッシュ用のキーを生成します。
|
||||
/// </summary>
|
||||
/// <param name="gameKey">ゲーム識別キー</param>
|
||||
/// <param name="saveFilePath">セーブファイルパス</param>
|
||||
/// <returns>キャッシュキー</returns>
|
||||
private string BuildCacheKey(string? gameKey, string saveFilePath)
|
||||
{
|
||||
var key = !string.IsNullOrWhiteSpace(gameKey)
|
||||
? gameKey!
|
||||
: Path.GetDirectoryName(saveFilePath) ?? string.Empty;
|
||||
|
||||
return key.Trim();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 解決済みパスワードを学習キャッシュへ保存します。
|
||||
/// </summary>
|
||||
/// <param name="cacheKey">キャッシュキー</param>
|
||||
/// <param name="password">パスワード</param>
|
||||
private void Remember(string? cacheKey, string password)
|
||||
{
|
||||
if (string.IsNullOrEmpty(cacheKey))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
this._store.Set(cacheKey, password);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 辞書段階で試行する候補列挙子を返します(既定候補 → ユーザー辞書の順)。
|
||||
/// </summary>
|
||||
/// <param name="userDictionaryPath">ユーザー辞書ファイルのパス</param>
|
||||
/// <param name="diagnostics">診断メッセージの追加先</param>
|
||||
/// <returns>候補の列挙</returns>
|
||||
private IEnumerable<string> EnumerateDictionaryCandidates(string? userDictionaryPath, List<string> diagnostics)
|
||||
{
|
||||
var seen = new HashSet<string>(StringComparer.Ordinal);
|
||||
|
||||
foreach (var candidate in GetBuiltInCandidates())
|
||||
{
|
||||
if (seen.Add(candidate))
|
||||
{
|
||||
yield return candidate;
|
||||
}
|
||||
}
|
||||
|
||||
if (string.IsNullOrWhiteSpace(userDictionaryPath))
|
||||
{
|
||||
yield break;
|
||||
}
|
||||
|
||||
if (!File.Exists(userDictionaryPath))
|
||||
{
|
||||
diagnostics.Add($"ユーザー辞書が見つかりません: {userDictionaryPath}");
|
||||
yield break;
|
||||
}
|
||||
|
||||
string[] lines;
|
||||
try
|
||||
{
|
||||
lines = File.ReadAllLines(userDictionaryPath, Encoding.UTF8);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
diagnostics.Add($"ユーザー辞書の読み込みに失敗しました: {ex.Message}");
|
||||
yield break;
|
||||
}
|
||||
|
||||
diagnostics.Add($"ユーザー辞書を適用します({lines.Length} 行): {userDictionaryPath}");
|
||||
|
||||
foreach (var line in lines)
|
||||
{
|
||||
var candidate = line.Trim();
|
||||
if (candidate.Length == 0 || candidate.StartsWith('#'))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
if (seen.Add(candidate))
|
||||
{
|
||||
yield return candidate;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Easy Save 3 でよく使われる既定のパスワード候補を返します。
|
||||
/// </summary>
|
||||
/// <returns>既定候補の並び</returns>
|
||||
private static IEnumerable<string> GetBuiltInCandidates()
|
||||
{
|
||||
// 空文字(パスワード未設定のまま暗号化されたケース)を最初に試す
|
||||
yield return string.Empty;
|
||||
yield return "password";
|
||||
yield return "Password";
|
||||
yield return "PASSWORD";
|
||||
yield return "Moodkie";
|
||||
yield return "moodkie";
|
||||
yield return "EasySave";
|
||||
yield return "easysave";
|
||||
yield return "EasySave3";
|
||||
yield return "es3";
|
||||
yield return "ES3";
|
||||
yield return "SaveData";
|
||||
yield return "savedata";
|
||||
yield return "Save";
|
||||
yield return "save";
|
||||
yield return "secret";
|
||||
yield return "Secret";
|
||||
yield return "123456";
|
||||
yield return "1234567890";
|
||||
yield return "admin";
|
||||
yield return "test";
|
||||
yield return "game";
|
||||
yield return "Game";
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 診断ログ用にパスワードをマスクします(先頭 2 文字のみ残す)。
|
||||
/// </summary>
|
||||
/// <param name="password">パスワード</param>
|
||||
/// <returns>マスク済み文字列</returns>
|
||||
private static string Mask(string password)
|
||||
{
|
||||
if (string.IsNullOrEmpty(password))
|
||||
{
|
||||
return "(空)";
|
||||
}
|
||||
|
||||
if (password.Length <= 2)
|
||||
{
|
||||
return new string('*', password.Length);
|
||||
}
|
||||
|
||||
return password[..2] + new string('*', Math.Min(password.Length - 2, 8));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,214 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
using GameLauncher.Helpers;
|
||||
|
||||
namespace GameLauncher.Services.Codecs.Es3
|
||||
{
|
||||
/// <summary>
|
||||
/// ES3 のパスワード特定結果を「ゲーム単位」で永続化する学習キャッシュ。
|
||||
///
|
||||
/// 一度解決したパスワードを保存しておくことで、次回以降は自動適用できます。
|
||||
/// 保存先は exe 直下の <c>es3-passwords.json</c> で、キャッシュ破棄やブックマークとは独立に管理します。
|
||||
/// </summary>
|
||||
public sealed class Es3PasswordStore
|
||||
{
|
||||
/// <summary>永続化ファイル名。</summary>
|
||||
private const string FileName = "es3-passwords.json";
|
||||
|
||||
/// <summary>既定のシングルトンインスタンス。</summary>
|
||||
public static Es3PasswordStore Instance { get; } = new();
|
||||
|
||||
private readonly object _syncRoot = new();
|
||||
private readonly string _filePath;
|
||||
private Dictionary<string, string>? _entries;
|
||||
|
||||
/// <summary>
|
||||
/// exe 直下の既定パスを用いて <see cref="Es3PasswordStore"/> を初期化します。
|
||||
/// </summary>
|
||||
public Es3PasswordStore()
|
||||
: this(Path.Combine(AppPathHelper.GetExeDirectory(), FileName))
|
||||
{
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 任意のファイルパスを指定して <see cref="Es3PasswordStore"/> を初期化します(テスト用途を含む)。
|
||||
/// </summary>
|
||||
/// <param name="filePath">永続化ファイルの絶対パス</param>
|
||||
public Es3PasswordStore(string filePath)
|
||||
{
|
||||
this._filePath = filePath;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 永続化ファイルのパスを取得します。
|
||||
/// </summary>
|
||||
public string FilePath => this._filePath;
|
||||
|
||||
/// <summary>
|
||||
/// 指定キーに対応する学習済みパスワードを取得します。
|
||||
/// </summary>
|
||||
/// <param name="key">ゲーム単位のキー(通常はゲームのルートディレクトリ)</param>
|
||||
/// <returns>保存済みパスワード。未登録の場合は null</returns>
|
||||
public string? TryGet(string key)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(key))
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
lock (this._syncRoot)
|
||||
{
|
||||
var entries = this.LoadEntries();
|
||||
return entries.TryGetValue(Normalize(key), out var password) ? password : null;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 学習済みパスワードを保存します。
|
||||
/// </summary>
|
||||
/// <param name="key">ゲーム単位のキー</param>
|
||||
/// <param name="password">保存するパスワード(空文字も有効な値として保存します)</param>
|
||||
public void Set(string key, string password)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(key))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
lock (this._syncRoot)
|
||||
{
|
||||
var entries = this.LoadEntries();
|
||||
entries[Normalize(key)] = password ?? string.Empty;
|
||||
this.SaveEntries(entries);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 指定キーの学習済みパスワードを削除します。
|
||||
/// </summary>
|
||||
/// <param name="key">ゲーム単位のキー</param>
|
||||
/// <returns>削除できた場合 true</returns>
|
||||
public bool Remove(string key)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(key))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
lock (this._syncRoot)
|
||||
{
|
||||
var entries = this.LoadEntries();
|
||||
if (!entries.Remove(Normalize(key)))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
this.SaveEntries(entries);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 保存済みエントリのスナップショットを取得します(表示・診断用)。
|
||||
/// </summary>
|
||||
/// <returns>キーとパスワードの読み取り専用ディクショナリ</returns>
|
||||
public IReadOnlyDictionary<string, string> Snapshot()
|
||||
{
|
||||
lock (this._syncRoot)
|
||||
{
|
||||
return new Dictionary<string, string>(this.LoadEntries(), StringComparer.OrdinalIgnoreCase);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 永続化ファイルを読み込みます。壊れている場合は空のディクショナリを返します。
|
||||
/// </summary>
|
||||
/// <returns>読み込んだエントリ</returns>
|
||||
private Dictionary<string, string> LoadEntries()
|
||||
{
|
||||
if (this._entries != null)
|
||||
{
|
||||
return this._entries;
|
||||
}
|
||||
|
||||
var result = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
|
||||
|
||||
try
|
||||
{
|
||||
if (File.Exists(this._filePath))
|
||||
{
|
||||
var json = File.ReadAllText(this._filePath, Encoding.UTF8);
|
||||
if (!string.IsNullOrWhiteSpace(json))
|
||||
{
|
||||
var loaded = JsonSerializer.Deserialize<Dictionary<string, string>>(json);
|
||||
if (loaded != null)
|
||||
{
|
||||
foreach (var kvp in loaded)
|
||||
{
|
||||
if (!string.IsNullOrWhiteSpace(kvp.Key))
|
||||
{
|
||||
result[Normalize(kvp.Key)] = kvp.Value ?? string.Empty;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
catch
|
||||
{
|
||||
// 破損ファイルは無視し、空の状態から再構築する
|
||||
result = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
this._entries = result;
|
||||
return this._entries;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// エントリを永続化ファイルへ書き出します。
|
||||
/// </summary>
|
||||
/// <param name="entries">書き出すエントリ</param>
|
||||
private void SaveEntries(Dictionary<string, string> entries)
|
||||
{
|
||||
try
|
||||
{
|
||||
var directory = Path.GetDirectoryName(this._filePath);
|
||||
if (!string.IsNullOrEmpty(directory) && !Directory.Exists(directory))
|
||||
{
|
||||
Directory.CreateDirectory(directory);
|
||||
}
|
||||
|
||||
var options = new JsonSerializerOptions { WriteIndented = true };
|
||||
var json = JsonSerializer.Serialize(entries, options);
|
||||
|
||||
// BOM なし UTF-8 で保存する
|
||||
File.WriteAllText(this._filePath, json, new UTF8Encoding(encoderShouldEmitUTF8Identifier: false));
|
||||
}
|
||||
catch
|
||||
{
|
||||
// 保存失敗は致命的ではないため握りつぶす(次回再度解決を試みる)
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// キーを比較用に正規化します(パス区切りと大文字小文字の揺れを吸収)。
|
||||
/// </summary>
|
||||
/// <param name="key">元のキー</param>
|
||||
/// <returns>正規化済みキー</returns>
|
||||
private static string Normalize(string key)
|
||||
{
|
||||
var trimmed = key.Trim();
|
||||
try
|
||||
{
|
||||
return Path.GetFullPath(trimmed).TrimEnd(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar);
|
||||
}
|
||||
catch
|
||||
{
|
||||
return trimmed;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,891 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Globalization;
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Nodes;
|
||||
|
||||
namespace GameLauncher.Services.Codecs.Es3
|
||||
{
|
||||
/// <summary>
|
||||
/// ES3 のシリアライズ要素が持つ「型」の種別。
|
||||
/// ES3 は <c>{ "__type": "System.Int32", "value": 42 }</c> 形式で値を格納するため、
|
||||
/// この列挙子で GUI 側へ型情報を伝えます。
|
||||
/// </summary>
|
||||
public enum Es3ValueKind
|
||||
{
|
||||
/// <summary>不明・未判定。</summary>
|
||||
Unknown,
|
||||
|
||||
/// <summary>真偽値。</summary>
|
||||
Boolean,
|
||||
|
||||
/// <summary>整数(Int32 / Int64 / UInt32 等)。</summary>
|
||||
Integer,
|
||||
|
||||
/// <summary>浮動小数(Single / Double / Decimal)。</summary>
|
||||
Float,
|
||||
|
||||
/// <summary>文字列。</summary>
|
||||
String,
|
||||
|
||||
/// <summary>列挙体。</summary>
|
||||
Enum,
|
||||
|
||||
/// <summary>配列。</summary>
|
||||
Array,
|
||||
|
||||
/// <summary>辞書(キーと値の組)。</summary>
|
||||
Dictionary,
|
||||
|
||||
/// <summary>入れ子オブジェクト。</summary>
|
||||
Object
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// ES3 ファイル内の 1 項目を表す型付きノード。
|
||||
/// JSON ツリー上の位置(<see cref="Path"/>)を保持するため、編集後の書き戻しが安全に行えます。
|
||||
/// </summary>
|
||||
public sealed class Es3Node
|
||||
{
|
||||
/// <summary>キー名(辞書・オブジェクトの子の場合)。</summary>
|
||||
public string Key { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>親をたどる JSON パス(例: <c>$.player.stats.hp</c>)。</summary>
|
||||
public string Path { get; set; } = "$";
|
||||
|
||||
/// <summary>ES3 が示す型名(例: <c>System.Int32</c>、<c>System.Collections.Generic.List`1</c>)。</summary>
|
||||
public string TypeName { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>判定した値種別。</summary>
|
||||
public Es3ValueKind Kind { get; set; } = Es3ValueKind.Unknown;
|
||||
|
||||
/// <summary>現在の値(文字列化した表示・編集用の値)。</summary>
|
||||
public string DisplayValue { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>元の JSON 値(書き戻し時の型再現に使用)。</summary>
|
||||
public JsonNode? OriginalNode { get; set; }
|
||||
|
||||
/// <summary>配列・辞書・オブジェクトの場合の子要素。</summary>
|
||||
public List<Es3Node> Children { get; } = [];
|
||||
|
||||
/// <summary>子要素を持つか。</summary>
|
||||
public bool HasChildren => this.Children.Count > 0;
|
||||
|
||||
/// <summary>エディタで直接値を編集できる型か。</summary>
|
||||
public bool IsEditable => this.Kind is Es3ValueKind.Boolean
|
||||
or Es3ValueKind.Integer
|
||||
or Es3ValueKind.Float
|
||||
or Es3ValueKind.String
|
||||
or Es3ValueKind.Enum;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// ES3 (Easy Save 3) のセーブデータ本体(復号後の JSON)を解析し、
|
||||
/// キー名・型・値を読み取るとともに、編集結果を安全に書き戻すパーサ/ライタ。
|
||||
///
|
||||
/// ES3 の内部形式は次の 2 通りが混在します:
|
||||
/// <c>{ "key": { "__type": "System.Int32", "value": 100 } }</c>
|
||||
/// <c>{ "key": { "__type": "System.Collections.Generic.Dictionary`2[...]", "value": { ... } } }</c>
|
||||
/// 本クラスは両形式を展開し、編集後は元の型情報を保持したまま再構築します。
|
||||
/// </summary>
|
||||
public sealed class Es3SaveDocument
|
||||
{
|
||||
/// <summary>ES3 が型情報を格納するプロパティ名。</summary>
|
||||
public const string TypePropertyName = "__type";
|
||||
|
||||
/// <summary>ES3 が値を格納するプロパティ名。</summary>
|
||||
public const string ValuePropertyName = "value";
|
||||
|
||||
/// <summary>解析対象のルート JSON オブジェクト(編集はこのインスタンスを直接書き換えます)。</summary>
|
||||
private JsonNode? _root;
|
||||
|
||||
/// <summary>復号直後の JSON 文字列(差分検出・バックアップ用)。</summary>
|
||||
public string OriginalJson { get; private set; } = string.Empty;
|
||||
|
||||
/// <summary>解析に成功したか。</summary>
|
||||
public bool IsLoaded => this._root != null;
|
||||
|
||||
/// <summary>解析時の警告(解釈できなかった要素など)。</summary>
|
||||
public List<string> Warnings { get; } = [];
|
||||
|
||||
/// <summary>ルート直下の項目一覧。</summary>
|
||||
public List<Es3Node> RootNodes { get; } = [];
|
||||
|
||||
/// <summary>
|
||||
/// ES3 の平文 JSON 文字列を解析してドキュメントを構築します。
|
||||
/// </summary>
|
||||
/// <param name="json">復号済みの平文 JSON</param>
|
||||
/// <returns>解析されたドキュメント</returns>
|
||||
public static Es3SaveDocument Parse(string json)
|
||||
{
|
||||
var document = new Es3SaveDocument { OriginalJson = json ?? string.Empty };
|
||||
|
||||
if (string.IsNullOrWhiteSpace(json))
|
||||
{
|
||||
document.Warnings.Add("平文 JSON が空です。");
|
||||
return document;
|
||||
}
|
||||
|
||||
JsonNode? root;
|
||||
try
|
||||
{
|
||||
root = JsonNode.Parse(json, documentOptions: new JsonDocumentOptions
|
||||
{
|
||||
AllowTrailingCommas = true,
|
||||
CommentHandling = JsonCommentHandling.Skip,
|
||||
MaxDepth = 256
|
||||
});
|
||||
}
|
||||
catch (JsonException ex)
|
||||
{
|
||||
document.Warnings.Add($"JSON 解析に失敗しました: {ex.Message}");
|
||||
return document;
|
||||
}
|
||||
|
||||
if (root == null)
|
||||
{
|
||||
document.Warnings.Add("JSON のルートが null です。");
|
||||
return document;
|
||||
}
|
||||
|
||||
document._root = root;
|
||||
document.BuildTree(root, "$", string.Empty);
|
||||
return document;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 解析ツリーを走査してルート直下の項目一覧を構築します。
|
||||
/// </summary>
|
||||
/// <param name="root">JSON ルート</param>
|
||||
/// <param name="path">ルートパス</param>
|
||||
/// <param name="key">キー名</param>
|
||||
private void BuildTree(JsonNode root, string path, string key)
|
||||
{
|
||||
if (root is JsonObject rootObject)
|
||||
{
|
||||
foreach (var kvp in rootObject)
|
||||
{
|
||||
var childPath = $"{path}.{kvp.Key}";
|
||||
var node = this.CreateNode(kvp.Key, childPath, kvp.Value);
|
||||
if (node != null)
|
||||
{
|
||||
this.RootNodes.Add(node);
|
||||
}
|
||||
}
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
if (root is JsonArray rootArray)
|
||||
{
|
||||
for (int i = 0; i < rootArray.Count; i++)
|
||||
{
|
||||
var childPath = $"{path}[{i}]";
|
||||
var node = this.CreateNode($"[{i}]", childPath, rootArray[i]);
|
||||
if (node != null)
|
||||
{
|
||||
this.RootNodes.Add(node);
|
||||
}
|
||||
}
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
this.Warnings.Add($"ルート要素を解釈できませんでした({root.GetValueKind()})。");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// JSON ノードから型付きの <see cref="Es3Node"/> を生成します。
|
||||
/// </summary>
|
||||
/// <param name="key">キー名</param>
|
||||
/// <param name="path">JSON パス</param>
|
||||
/// <param name="node">対象ノード</param>
|
||||
/// <returns>生成されたノード。解釈不能な場合は null</returns>
|
||||
private Es3Node? CreateNode(string key, string path, JsonNode? node)
|
||||
{
|
||||
var result = new Es3Node
|
||||
{
|
||||
Key = key,
|
||||
Path = path,
|
||||
OriginalNode = node
|
||||
};
|
||||
|
||||
if (node == null)
|
||||
{
|
||||
result.Kind = Es3ValueKind.Unknown;
|
||||
result.DisplayValue = "null";
|
||||
return result;
|
||||
}
|
||||
|
||||
switch (node.GetValueKind())
|
||||
{
|
||||
case JsonValueKind.Object:
|
||||
this.PopulateObject(result, path, node.AsObject());
|
||||
return result;
|
||||
|
||||
case JsonValueKind.Array:
|
||||
result.Kind = Es3ValueKind.Array;
|
||||
result.TypeName = "System.Array";
|
||||
PopulateArray(result, path, node.AsArray());
|
||||
return result;
|
||||
|
||||
case JsonValueKind.String:
|
||||
result.Kind = Es3ValueKind.String;
|
||||
result.TypeName = "System.String";
|
||||
result.DisplayValue = node.GetValue<string>();
|
||||
return result;
|
||||
|
||||
case JsonValueKind.Number:
|
||||
PopulateNumber(result, node);
|
||||
return result;
|
||||
|
||||
case JsonValueKind.True:
|
||||
case JsonValueKind.False:
|
||||
result.Kind = Es3ValueKind.Boolean;
|
||||
result.TypeName = "System.Boolean";
|
||||
result.DisplayValue = node.GetValue<bool>() ? "true" : "false";
|
||||
return result;
|
||||
|
||||
case JsonValueKind.Null:
|
||||
result.Kind = Es3ValueKind.Unknown;
|
||||
result.DisplayValue = "null";
|
||||
return result;
|
||||
|
||||
default:
|
||||
result.Kind = Es3ValueKind.Unknown;
|
||||
result.DisplayValue = node.ToJsonString();
|
||||
return result;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// JSON オブジェクトが ES3 の型付き要素か、単なる入れ子オブジェクトかを判定して展開します。
|
||||
/// </summary>
|
||||
/// <param name="target">構築対象のノード</param>
|
||||
/// <param name="path">JSON パス</param>
|
||||
/// <param name="jsonObject">対象の JSON オブジェクト</param>
|
||||
private void PopulateObject(Es3Node target, string path, JsonObject jsonObject)
|
||||
{
|
||||
// ES3 の型付き要素(__type と value を持つ)か判定
|
||||
bool isTyped = jsonObject.ContainsKey(TypePropertyName);
|
||||
|
||||
if (isTyped)
|
||||
{
|
||||
target.TypeName = jsonObject[TypePropertyName]?.GetValue<string>() ?? string.Empty;
|
||||
var inner = jsonObject[ValuePropertyName];
|
||||
|
||||
if (inner == null)
|
||||
{
|
||||
target.Kind = MapTypeNameToKind(target.TypeName);
|
||||
target.DisplayValue = "null";
|
||||
return;
|
||||
}
|
||||
|
||||
var innerKind = inner.GetValueKind();
|
||||
|
||||
if (innerKind == JsonValueKind.Object)
|
||||
{
|
||||
// 辞書・入れ子オブジェクト
|
||||
var innerObject = inner.AsObject();
|
||||
target.Kind = LooksLikeDictionary(innerObject, target.TypeName)
|
||||
? Es3ValueKind.Dictionary
|
||||
: Es3ValueKind.Object;
|
||||
|
||||
foreach (var kvp in innerObject)
|
||||
{
|
||||
var childPath = $"{path}.{kvp.Key}";
|
||||
var child = this.CreateNode(kvp.Key, childPath, kvp.Value);
|
||||
if (child != null)
|
||||
{
|
||||
target.Children.Add(child);
|
||||
}
|
||||
}
|
||||
|
||||
target.DisplayValue = $"({target.Children.Count} 項目)";
|
||||
return;
|
||||
}
|
||||
|
||||
if (innerKind == JsonValueKind.Array)
|
||||
{
|
||||
target.Kind = Es3ValueKind.Array;
|
||||
PopulateArray(target, path, inner.AsArray());
|
||||
return;
|
||||
}
|
||||
|
||||
// プリミティブ値
|
||||
target.Kind = MapTypeNameToKind(target.TypeName);
|
||||
target.DisplayValue = FormatScalar(inner, target.Kind);
|
||||
return;
|
||||
}
|
||||
|
||||
// 型情報なしの入れ子オブジェクト
|
||||
target.Kind = Es3ValueKind.Object;
|
||||
target.TypeName = "System.Object";
|
||||
|
||||
foreach (var kvp in jsonObject)
|
||||
{
|
||||
var childPath = $"{path}.{kvp.Key}";
|
||||
var child = this.CreateNode(kvp.Key, childPath, kvp.Value);
|
||||
if (child != null)
|
||||
{
|
||||
target.Children.Add(child);
|
||||
}
|
||||
}
|
||||
|
||||
target.DisplayValue = $"({target.Children.Count} 項目)";
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 配列を走査して子要素を追加します。
|
||||
/// </summary>
|
||||
/// <param name="target">構築対象のノード</param>
|
||||
/// <param name="path">JSON パス</param>
|
||||
/// <param name="array">対象の JSON 配列</param>
|
||||
private static void PopulateArray(Es3Node target, string path, JsonArray array)
|
||||
{
|
||||
for (int i = 0; i < array.Count; i++)
|
||||
{
|
||||
var childPath = $"{path}[{i}]";
|
||||
var elementNode = array[i];
|
||||
|
||||
var child = new Es3Node
|
||||
{
|
||||
Key = $"[{i}]",
|
||||
Path = childPath,
|
||||
OriginalNode = elementNode
|
||||
};
|
||||
|
||||
if (elementNode == null)
|
||||
{
|
||||
child.Kind = Es3ValueKind.Unknown;
|
||||
child.DisplayValue = "null";
|
||||
}
|
||||
else if (elementNode.GetValueKind() == JsonValueKind.Object &&
|
||||
elementNode.AsObject().ContainsKey(TypePropertyName))
|
||||
{
|
||||
// 配列要素が型付き要素の場合は再帰的に展開する
|
||||
var innerObject = elementNode.AsObject();
|
||||
child.TypeName = innerObject[TypePropertyName]?.GetValue<string>() ?? string.Empty;
|
||||
var inner = innerObject[ValuePropertyName];
|
||||
|
||||
if (inner != null && inner.GetValueKind() == JsonValueKind.Object)
|
||||
{
|
||||
child.Kind = Es3ValueKind.Object;
|
||||
foreach (var kvp in inner.AsObject())
|
||||
{
|
||||
var grandChild = new Es3Node
|
||||
{
|
||||
Key = kvp.Key,
|
||||
Path = $"{childPath}.{kvp.Key}",
|
||||
OriginalNode = kvp.Value,
|
||||
Kind = MapValueKind(kvp.Value),
|
||||
DisplayValue = FormatScalar(kvp.Value, MapValueKind(kvp.Value))
|
||||
};
|
||||
child.Children.Add(grandChild);
|
||||
}
|
||||
|
||||
child.DisplayValue = $"({child.Children.Count} 項目)";
|
||||
}
|
||||
else
|
||||
{
|
||||
child.Kind = MapTypeNameToKind(child.TypeName);
|
||||
child.DisplayValue = inner == null ? "null" : FormatScalar(inner, child.Kind);
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
child.Kind = MapValueKind(elementNode);
|
||||
child.DisplayValue = FormatScalar(elementNode, child.Kind);
|
||||
}
|
||||
|
||||
target.Children.Add(child);
|
||||
}
|
||||
|
||||
target.DisplayValue = $"({target.Children.Count} 件)";
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 数値ノードの型情報と表示値を設定します。
|
||||
/// </summary>
|
||||
/// <param name="target">構築対象のノード</param>
|
||||
/// <param name="node">数値ノード</param>
|
||||
private void PopulateNumber(Es3Node target, JsonNode node)
|
||||
{
|
||||
var raw = node.ToJsonString();
|
||||
|
||||
if (raw.Contains('.') || raw.Contains('e', StringComparison.OrdinalIgnoreCase) &&
|
||||
!raw.Contains("0x", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
target.Kind = Es3ValueKind.Float;
|
||||
target.TypeName = "System.Single";
|
||||
}
|
||||
else
|
||||
{
|
||||
target.Kind = Es3ValueKind.Integer;
|
||||
target.TypeName = "System.Int32";
|
||||
}
|
||||
|
||||
target.DisplayValue = raw;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// ES3 の型名から値種別を推定します。
|
||||
/// </summary>
|
||||
/// <param name="typeName">ES3 の型名</param>
|
||||
/// <returns>推定した値種別</returns>
|
||||
public static Es3ValueKind MapTypeNameToKind(string typeName)
|
||||
{
|
||||
if (string.IsNullOrEmpty(typeName))
|
||||
{
|
||||
return Es3ValueKind.Unknown;
|
||||
}
|
||||
|
||||
var normalized = typeName.Replace(" ", string.Empty);
|
||||
|
||||
if (normalized.Contains("System.Boolean", StringComparison.Ordinal))
|
||||
{
|
||||
return Es3ValueKind.Boolean;
|
||||
}
|
||||
|
||||
if (normalized.Contains("System.Single", StringComparison.Ordinal) ||
|
||||
normalized.Contains("System.Double", StringComparison.Ordinal) ||
|
||||
normalized.Contains("System.Decimal", StringComparison.Ordinal))
|
||||
{
|
||||
return Es3ValueKind.Float;
|
||||
}
|
||||
|
||||
if (normalized.Contains("System.Int", StringComparison.Ordinal) ||
|
||||
normalized.Contains("System.UInt", StringComparison.Ordinal) ||
|
||||
normalized.Contains("System.Byte", StringComparison.Ordinal) ||
|
||||
normalized.Contains("System.Int64", StringComparison.Ordinal) ||
|
||||
normalized.Contains("System.Int16", StringComparison.Ordinal))
|
||||
{
|
||||
return Es3ValueKind.Integer;
|
||||
}
|
||||
|
||||
if (normalized.Contains("System.String", StringComparison.Ordinal) ||
|
||||
normalized.Contains("System.Char", StringComparison.Ordinal))
|
||||
{
|
||||
return Es3ValueKind.String;
|
||||
}
|
||||
|
||||
if (normalized.Contains("Dictionary", StringComparison.Ordinal))
|
||||
{
|
||||
return Es3ValueKind.Dictionary;
|
||||
}
|
||||
|
||||
if (normalized.Contains("[]", StringComparison.Ordinal) ||
|
||||
normalized.Contains("List`1", StringComparison.Ordinal) ||
|
||||
normalized.Contains("HashSet", StringComparison.Ordinal))
|
||||
{
|
||||
return Es3ValueKind.Array;
|
||||
}
|
||||
|
||||
if (normalized.Contains("System.Enum", StringComparison.Ordinal))
|
||||
{
|
||||
return Es3ValueKind.Enum;
|
||||
}
|
||||
|
||||
return Es3ValueKind.Object;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 辞書形式(キーと値の組)かどうかを推定します。
|
||||
/// </summary>
|
||||
/// <param name="jsonObject">対象オブジェクト</param>
|
||||
/// <param name="typeName">型名</param>
|
||||
/// <returns>辞書と判断できる場合 true</returns>
|
||||
private static bool LooksLikeDictionary(JsonObject jsonObject, string typeName)
|
||||
{
|
||||
if (!string.IsNullOrEmpty(typeName) &&
|
||||
typeName.Contains("Dictionary", StringComparison.Ordinal))
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
// ES3 の辞書は {"key": "...", "value": ...} の対を持つ
|
||||
return jsonObject.ContainsKey("key") && jsonObject.ContainsKey(ValuePropertyName);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// JSON 値の種別を簡易判定します。
|
||||
/// </summary>
|
||||
/// <param name="node">対象ノード</param>
|
||||
/// <returns>判定した値種別</returns>
|
||||
private static Es3ValueKind MapValueKind(JsonNode? node)
|
||||
{
|
||||
if (node == null)
|
||||
{
|
||||
return Es3ValueKind.Unknown;
|
||||
}
|
||||
|
||||
return node.GetValueKind() switch
|
||||
{
|
||||
JsonValueKind.Object => Es3ValueKind.Object,
|
||||
JsonValueKind.Array => Es3ValueKind.Array,
|
||||
JsonValueKind.String => Es3ValueKind.String,
|
||||
JsonValueKind.Number => node.ToJsonString().Contains('.')
|
||||
? Es3ValueKind.Float
|
||||
: Es3ValueKind.Integer,
|
||||
JsonValueKind.True or JsonValueKind.False => Es3ValueKind.Boolean,
|
||||
_ => Es3ValueKind.Unknown
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// スカラー値を表示用文字列へ整形します。
|
||||
/// </summary>
|
||||
/// <param name="node">対象ノード</param>
|
||||
/// <param name="kind">値種別</param>
|
||||
/// <returns>表示用文字列</returns>
|
||||
private static string FormatScalar(JsonNode? node, Es3ValueKind kind)
|
||||
{
|
||||
if (node == null)
|
||||
{
|
||||
return "null";
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
return kind switch
|
||||
{
|
||||
Es3ValueKind.Boolean => node.GetValue<bool>() ? "true" : "false",
|
||||
Es3ValueKind.String => node.GetValue<string>(),
|
||||
Es3ValueKind.Enum => node.GetValueKind() == JsonValueKind.Number
|
||||
? node.ToJsonString()
|
||||
: node.GetValue<string>(),
|
||||
_ => node.ToJsonString()
|
||||
};
|
||||
}
|
||||
catch
|
||||
{
|
||||
return node.ToJsonString();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 指定パスのノードへ編集値を適用します。
|
||||
/// </summary>
|
||||
/// <param name="path">JSON パス(<see cref="Es3Node.Path"/>)</param>
|
||||
/// <param name="newValue">新しい値(表示文字列)</param>
|
||||
/// <param name="error">失敗理由</param>
|
||||
/// <returns>適用に成功した場合 true</returns>
|
||||
public bool TrySetValue(string path, string newValue, out string error)
|
||||
{
|
||||
error = string.Empty;
|
||||
|
||||
if (this._root == null)
|
||||
{
|
||||
error = "ドキュメントが読み込まれていません。";
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!this.TryResolveParent(path, out var parent, out var key, out error))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
// 既存ノードから型情報を取得
|
||||
var existing = this.FindNode(path);
|
||||
var kind = existing?.Kind ?? Es3ValueKind.String;
|
||||
var typeName = existing?.TypeName ?? "System.String";
|
||||
|
||||
if (existing != null && !existing.IsEditable)
|
||||
{
|
||||
error = $"型 {typeName} は直接編集できません。";
|
||||
return false;
|
||||
}
|
||||
|
||||
JsonNode? parsed = this.BuildValueNode(newValue, kind, typeName, out error);
|
||||
if (parsed == null)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
// ES3 の型付き要素として書き戻す
|
||||
if (parent is JsonObject parentObject && parentObject.ContainsKey(TypePropertyName))
|
||||
{
|
||||
parentObject[ValuePropertyName] = parsed;
|
||||
}
|
||||
else if (parent is JsonObject plainObject)
|
||||
{
|
||||
plainObject[key] = parsed;
|
||||
}
|
||||
else if (parent is JsonArray array && int.TryParse(key, out int index) &&
|
||||
index >= 0 && index < array.Count)
|
||||
{
|
||||
array[index] = parsed;
|
||||
}
|
||||
else
|
||||
{
|
||||
error = "書き戻し先の親要素を特定できませんでした。";
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
error = $"書き戻しに失敗しました: {ex.Message}";
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 編集後の JSON を文字列として取得します。
|
||||
/// </summary>
|
||||
/// <returns>整形済み JSON 文字列</returns>
|
||||
public string ToJson()
|
||||
{
|
||||
if (this._root == null)
|
||||
{
|
||||
return this.OriginalJson;
|
||||
}
|
||||
|
||||
return this._root.ToJsonString(new JsonSerializerOptions { WriteIndented = false });
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 元の JSON から変更があったかを判定します。
|
||||
/// </summary>
|
||||
/// <returns>変更がある場合 true</returns>
|
||||
public bool HasChanges()
|
||||
{
|
||||
if (this._root == null)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
return !string.Equals(this.ToJson(), this.OriginalJson, StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// パスから親ノードと最終キーを解決します。
|
||||
/// </summary>
|
||||
/// <param name="path">JSON パス</param>
|
||||
/// <param name="parent">親ノード</param>
|
||||
/// <param name="key">最終キー(配列の場合はインデックス文字列)</param>
|
||||
/// <param name="error">失敗理由</param>
|
||||
/// <returns>解決に成功した場合 true</returns>
|
||||
private bool TryResolveParent(string path, out JsonNode? parent, out string key, out string error)
|
||||
{
|
||||
parent = null;
|
||||
key = string.Empty;
|
||||
error = string.Empty;
|
||||
|
||||
if (path == "$")
|
||||
{
|
||||
error = "ルート要素は編集できません。";
|
||||
return false;
|
||||
}
|
||||
|
||||
var segments = SplitPath(path);
|
||||
if (segments.Count < 2)
|
||||
{
|
||||
error = $"パスの解析に失敗しました: {path}";
|
||||
return false;
|
||||
}
|
||||
|
||||
JsonNode? current = this._root;
|
||||
|
||||
for (int i = 1; i < segments.Count - 1; i++)
|
||||
{
|
||||
if (current == null)
|
||||
{
|
||||
break;
|
||||
}
|
||||
|
||||
current = Descend(current, segments[i], out _);
|
||||
}
|
||||
|
||||
if (current == null)
|
||||
{
|
||||
error = $"パス {path} を解決できませんでした。";
|
||||
return false;
|
||||
}
|
||||
|
||||
key = segments[^1];
|
||||
parent = current;
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// パス文字列をセグメントへ分割します。
|
||||
/// </summary>
|
||||
/// <param name="path">JSON パス</param>
|
||||
/// <returns>セグメント一覧(先頭は "$")</returns>
|
||||
private static List<string> SplitPath(string path)
|
||||
{
|
||||
var segments = new List<string>();
|
||||
var buffer = new StringBuilder();
|
||||
|
||||
foreach (var ch in path)
|
||||
{
|
||||
if (ch == '.' || ch == '[' || ch == ']')
|
||||
{
|
||||
if (buffer.Length > 0)
|
||||
{
|
||||
segments.Add(buffer.ToString());
|
||||
buffer.Clear();
|
||||
}
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
buffer.Append(ch);
|
||||
}
|
||||
|
||||
if (buffer.Length > 0)
|
||||
{
|
||||
segments.Add(buffer.ToString());
|
||||
}
|
||||
|
||||
return segments;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 指定キーで子要素へ降下します(ES3 の型付き要素は value を透過します)。
|
||||
/// </summary>
|
||||
/// <param name="current">現在のノード</param>
|
||||
/// <param name="key">キー</param>
|
||||
/// <param name="found">見つかった子ノード</param>
|
||||
/// <returns>降下先ノード。見つからない場合は null</returns>
|
||||
private static JsonNode? Descend(JsonNode current, string key, out JsonNode? found)
|
||||
{
|
||||
found = null;
|
||||
|
||||
if (current is JsonObject obj)
|
||||
{
|
||||
// ES3 の型付き要素は value の中身を透過的に扱う
|
||||
if (obj.ContainsKey(TypePropertyName) && obj[ValuePropertyName] is JsonNode inner)
|
||||
{
|
||||
return Descend(inner, key, out found);
|
||||
}
|
||||
|
||||
if (obj.TryGetPropertyValue(key, out var child))
|
||||
{
|
||||
found = child;
|
||||
return child;
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
if (current is JsonArray array && int.TryParse(key, out int index) &&
|
||||
index >= 0 && index < array.Count)
|
||||
{
|
||||
found = array[index];
|
||||
return array[index];
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 指定パスに対応するノードを探索します。
|
||||
/// </summary>
|
||||
/// <param name="path">JSON パス</param>
|
||||
/// <returns>見つかったノード。見つからない場合は null</returns>
|
||||
private Es3Node? FindNode(string path)
|
||||
{
|
||||
return FindNodeRecursive(this.RootNodes, path);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// ノードツリーを再帰的に探索します。
|
||||
/// </summary>
|
||||
/// <param name="nodes">探索対象</param>
|
||||
/// <param name="path">JSON パス</param>
|
||||
/// <returns>見つかったノード</returns>
|
||||
private static Es3Node? FindNodeRecursive(List<Es3Node> nodes, string path)
|
||||
{
|
||||
foreach (var node in nodes)
|
||||
{
|
||||
if (node.Path == path)
|
||||
{
|
||||
return node;
|
||||
}
|
||||
|
||||
var found = FindNodeRecursive(node.Children, path);
|
||||
if (found != null)
|
||||
{
|
||||
return found;
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 編集値から実際の JSON ノードを構築します。
|
||||
/// </summary>
|
||||
/// <param name="newValue">編集された値文字列</param>
|
||||
/// <param name="kind">型種別</param>
|
||||
/// <param name="typeName">ES3 の型名</param>
|
||||
/// <param name="error">失敗理由</param>
|
||||
/// <returns>構築された JSON ノード。失敗時は null</returns>
|
||||
private JsonNode? BuildValueNode(string newValue, Es3ValueKind kind, string typeName, out string error)
|
||||
{
|
||||
error = string.Empty;
|
||||
|
||||
switch (kind)
|
||||
{
|
||||
case Es3ValueKind.Boolean:
|
||||
if (bool.TryParse(newValue, out var boolValue))
|
||||
{
|
||||
return JsonValue.Create(boolValue);
|
||||
}
|
||||
|
||||
if (newValue.Trim() == "1")
|
||||
{
|
||||
return JsonValue.Create(true);
|
||||
}
|
||||
|
||||
if (newValue.Trim() == "0")
|
||||
{
|
||||
return JsonValue.Create(false);
|
||||
}
|
||||
|
||||
error = $"真偽値として解釈できません: {newValue}";
|
||||
return null;
|
||||
|
||||
case Es3ValueKind.Integer:
|
||||
if (long.TryParse(newValue.Trim(), NumberStyles.Integer, CultureInfo.InvariantCulture, out var longValue))
|
||||
{
|
||||
return JsonValue.Create(longValue);
|
||||
}
|
||||
|
||||
error = $"整数として解釈できません: {newValue}";
|
||||
return null;
|
||||
|
||||
case Es3ValueKind.Float:
|
||||
if (double.TryParse(newValue.Trim(), NumberStyles.Float, CultureInfo.InvariantCulture, out var doubleValue))
|
||||
{
|
||||
return JsonValue.Create(doubleValue);
|
||||
}
|
||||
|
||||
error = $"小数として解釈できません: {newValue}";
|
||||
return null;
|
||||
|
||||
case Es3ValueKind.Enum:
|
||||
// 列挙体は元が数値なら数値、文字列なら文字列として保持する
|
||||
if (long.TryParse(newValue.Trim(), NumberStyles.Integer, CultureInfo.InvariantCulture, out var enumNumeric))
|
||||
{
|
||||
return JsonValue.Create(enumNumeric);
|
||||
}
|
||||
|
||||
return JsonValue.Create(newValue);
|
||||
|
||||
case Es3ValueKind.String:
|
||||
return JsonValue.Create(newValue);
|
||||
|
||||
default:
|
||||
error = $"型 {typeName} は直接編集できません。";
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user