using System.Security.Cryptography;
using System.Text;
using System.Text.Json;
namespace XFEWarframe.Client.Runtime;
public sealed record GameLoginRequest(string RequestId, string ServerUrl, string Email, string PasswordHash)
{
public override string ToString() => $"GameLoginRequest {{ RequestId = {RequestId}, Credentials = [redacted] }}";
public void Validate()
{
if (!Guid.TryParseExact(RequestId, "N", out _) || ServerUrl is not { Length: > 0 and <= 2048 } || ServerUrl != ClientProtocol.NormalizeServer(ServerUrl) ||
Email is not { Length: >= 3 and <= 254 } || !Email.Contains('@') || Email.Any(char.IsControl) ||
PasswordHash is not { Length: 128 } || PasswordHash.Any(c => !char.IsAsciiHexDigit(c)))
throw new ArgumentException("游戏登录参数无效。");
}
}
public sealed record GameLoginStatus(bool Available, string RequestId, string Phase, string Message = "")
{
public bool Completed => Phase is "succeeded" or "failed" or "cancelled";
}
/// One native attempt per request. Credentials are held only until the engine consumes them.
public sealed class GameLoginQueue(TimeProvider? clock = null)
{
private readonly object gate = new();
private readonly TimeProvider time = clock ?? TimeProvider.System;
private GameLoginRequest? pending;
private byte[]? fingerprint;
private DateTimeOffset expires;
private GameLoginStatus status = new(true, "", "idle");
public GameLoginStatus Status { get { lock (gate) return status; } }
public GameLoginStatus Submit(GameLoginRequest request)
{
request.Validate();
var bytes = Encoding.UTF8.GetBytes(request.ServerUrl + "\n" + request.Email + "\n" + request.PasswordHash);
byte[] hash;
try { hash = SHA256.HashData(bytes); }
finally { CryptographicOperations.ZeroMemory(bytes); }
lock (gate)
{
if (status.RequestId == request.RequestId)
{
if (fingerprint is null || !CryptographicOperations.FixedTimeEquals(hash, fingerprint))
throw new InvalidOperationException("此登录请求编号已被使用。");
return status;
}
if (status.Phase is "waiting" or "signing-in" or "loading" or "entering-game")
throw new InvalidOperationException("游戏正在处理登录请求。");
pending = request; fingerprint = hash; expires = time.GetUtcNow().AddMinutes(2);
return status = new(true, request.RequestId, "waiting", "等待游戏登录界面…");
}
}
public GameLoginRequest? Advance(int profileState, bool ready, bool enteredGame = false)
{
lock (gate)
{
if (status.Phase is not ("waiting" or "signing-in" or "loading" or "entering-game")) return null;
if (time.GetUtcNow() >= expires)
{
Finish("failed", status.Phase == "waiting" ? "原生登录界面未就绪,可在游戏内手动登录。" :
"自动登录未完成。若仍停留在过场画面,请退出游戏后使用手动登录。");
return null;
}
if (profileState == 4)
{
if (status.Phase == "waiting") Finish("failed", "此游戏已经登录,请勿覆盖现有账号。");
else if (status.Phase is "loading" or "entering-game")
{
if (enteredGame) Finish("succeeded", "游戏登录成功");
else if (status.Phase == "loading") status = status with { Phase = "entering-game", Message = "账号验证成功,正在进入游戏…" };
}
return null;
}
if (status.Phase != "waiting") return null;
if (profileState == 1) { Finish("failed", "游戏已有登录操作正在进行。"); return null; }
if (!ready || profileState != 0) return null;
var result = pending; pending = null;
status = status with { Phase = "signing-in", Message = "正在登录游戏…" };
return result;
}
}
public void NativeCompleted(bool success)
{
lock (gate)
{
if (status.Phase != "signing-in") return;
if (success) status = status with { Phase = "loading", Message = "账号验证成功,正在载入…" };
else Finish("failed", "游戏登录失败,请检查账号、服务器连接或在游戏内手动登录。");
}
}
public void PresentationFailed(string requestId)
{
lock (gate)
{
if (status.RequestId == requestId && status.Phase == "entering-game")
Finish("failed", "账号验证已通过,但游戏未完成进场。请退出游戏后使用手动登录。");
}
}
public GameLoginStatus Cancel(string requestId)
{
lock (gate)
{
if (status.RequestId == requestId && status.Phase == "waiting") Finish("cancelled", "自动登录已取消。");
return status;
}
}
private void Finish(string phase, string message) { pending = null; status = status with { Phase = phase, Message = message }; }
}
public static class GameLoginCoordinator
{
public const string MinimumRuntimeVersion = "1.4.18";
public static async Task LoginAsync(string directory, int processId, GameLoginRequest request,
IProgress? progress = null, CancellationToken cancellation = default)
{
request.Validate();
using var deadline = CancellationTokenSource.CreateLinkedTokenSource(cancellation);
deadline.CancelAfter(TimeSpan.FromMinutes(2));
var token = deadline.Token;
RuntimeControlClient? runtime = null;
var submitted = false;
try
{
while (runtime is null)
{
token.ThrowIfCancellationRequested();
using var process = System.Diagnostics.Process.GetProcessById(processId);
if (process.HasExited) throw new InvalidOperationException("游戏已退出,无法完成自动登录。");
var session = (await RuntimeDiscovery.FindAsync(directory, token).ConfigureAwait(false)).SingleOrDefault(x => x.ProcessId == processId);
if (session is null) { await Task.Delay(250, token).ConfigureAwait(false); continue; }
var candidate = new RuntimeControlClient(session);
try
{
var status = await candidate.StatusAsync(token).ConfigureAwait(false);
if (ClientProtocol.NormalizeServer(status.ServerUrl) != request.ServerUrl) throw new InvalidOperationException("游戏连接的服务器与启动器账号不同,自动登录已停止。");
if (!Version.TryParse(status.Version, out var version) || version < Version.Parse(MinimumRuntimeVersion))
throw new InvalidOperationException($"一键登录需要兼容组件 {MinimumRuntimeVersion} 或更新版本。可在游戏内手动登录。");
if (!status.Capabilities.Any(c => c.Key == "game_login" && c.Available)) throw new InvalidOperationException("此游戏版本暂未通过一键登录绑定检查,请在游戏内手动登录。");
runtime = candidate;
}
catch { candidate.Dispose(); throw; }
}
var current = await runtime.LoginGameAsync(request, token).ConfigureAwait(false); submitted = true;
while (true)
{
if (current.RequestId != request.RequestId) throw new InvalidOperationException("游戏登录请求已改变。");
progress?.Report(current.Message);
if (current.Phase == "succeeded") return current;
if (current.Completed) throw new InvalidOperationException(current.Message);
await Task.Delay(250, token).ConfigureAwait(false);
current = await runtime.GameLoginStatusAsync(token).ConfigureAwait(false);
}
}
catch (OperationCanceledException) when (!cancellation.IsCancellationRequested)
{ throw new InvalidOperationException("自动登录等待超时。若仍停留在过场画面,请退出游戏后使用手动登录。"); }
finally
{
if (runtime is not null && submitted)
{
try { using var cleanup = new CancellationTokenSource(TimeSpan.FromSeconds(2)); await runtime.CancelGameLoginAsync(request.RequestId, cleanup.Token).ConfigureAwait(false); }
catch (Exception ex) when (ex is HttpRequestException or OperationCanceledException or IOException) { }
}
runtime?.Dispose();
}
}
}