XFE Git
XFE Studio Git
Git 首页 全局搜索
XFE 主站 文档 NuGet

XFEWarframe

【WinUI】基于Warframe游戏本体的公开服务器以及安装器

公开
关注 0 Fork 0 Star 0
UTF-8
using System.Security.Cryptography;
using System.Text;
using System.Collections.Concurrent;
using Newtonsoft.Json.Linq;
using XFEWarframe.Core.Data;

namespace XFEWarframe.Core.Services;

public sealed class Accounts(ServerOptions options, TimeProvider clock)
{
    private readonly ConcurrentDictionary<string, (long Nonce, long LastActivity)> gameLeases = new(StringComparer.Ordinal);
    private const long GameLeaseMilliseconds = 120000;
    public static IEnumerable<JObject> All(JObject state) => state.Obj("accounts").Properties().Select(x => (JObject)x.Value);
    public JObject Create(JObject state, string email, string password, string? name = null)
    {
        email = email.Trim().ToLowerInvariant();
        if (email.Length is < 3 or > 254 || !email.Contains('@') || password.Length is < 1 or > 4096)
            throw new ApiException(400, "Invalid email or password");
        if (All(state).Any(x => string.Equals(x.Value<string>("email"), email, StringComparison.OrdinalIgnoreCase)))
            throw new ApiException(409, "Account already exists");
        var displayName = name ?? email.Split('@')[0];
        if (displayName.Length is < 1 or > 24 || displayName == "all" || displayName.Any(char.IsControl))
            throw new ApiException(400, "DisplayName must contain 1–24 characters and cannot be 'all'");
        if (All(state).Any(x => x.Value<string>("DisplayName") == displayName)) throw new ApiException(409, "DisplayName already exists");
        var id = Wire.NewId();
        var account = new JObject
        {
            ["id"] = id, ["email"] = email, ["DisplayName"] = displayName,
            ["credential"] = HashPassword(password), ["Nonce"] = 0, ["LoginDays"] = 1,
            ["Created"] = clock.GetUtcNow().ToString("O"), ["Inventory"] = Inventory.New(),
            ["Loadouts"] = new JObject(), ["Inbox"] = new JArray(), ["Ignored"] = new JArray(),
            ["Stats"] = new JObject(), ["PersonalRooms"] = new JObject { ["Ship"] = new JObject { ["BootLocation"] = "Liset", ["Features"] = new JArray() } }
        };
        foreach (var kind in Inventory.LoadoutKeys) account.Obj("Loadouts")[kind] = new JArray();
        state.Obj("accounts")[id] = account;
        return account;
    }

    public ApiResponse Login(JObject state, ApiRequest request, GoogleIdentity? identity = null)
    {
        var body = request.ObjectBody();
        var android = body.Value<string>("ClientType") == "Android";
        if (android && identity is null) throw new ApiException(400, "incorrect login data");
        var email = android ? identity!.Email : body.RequiredString("email", 254).Trim().ToLowerInvariant();
        var password = android ? Convert.ToHexString(RandomNumberGenerator.GetBytes(32)) : body.RequiredString("password", 4096);
        var account = All(state).FirstOrDefault(x => android ? x.Value<string>("GoogleTokenId") == identity!.Subject : x.Value<string>("email") == email);
        if (account is null)
        {
            if (!(state.Obj("config").Value<bool?>("autoCreateAccount") ?? options.AutoCreateAccount)) throw new ApiException(400, "unknown user");
            account = Create(state, email, password);
            if (android) { account["GoogleTokenId"] = identity!.Subject; account["AndroidSignupPending"] = true; return ApiResponse.Json(new { error = "noAndroidAccount;countryCode=US" }, 400); }
        }
        else if (!android && !VerifyPassword(password, account.Value<string>("credential")!)) throw new ApiException(400, "incorrect login data");
        if (android && account.Value<bool>("AndroidSignupPending")) return ApiResponse.Json(new { error = "noAndroidAccount;countryCode=US" }, 400);
        if (account.Value<bool?>("Banned") == true) throw new ApiException(403, "Account is disabled");
        var installation = request.Q("xfeClientId");
        var sameInstallation = installation is { Length: 32 } && installation.All(char.IsAsciiHexDigit) && Wire.SecretEquals(installation, account.Value<string>("GameClientId"));
        var now = clock.GetUtcNow().ToUnixTimeMilliseconds(); var id = account.RequiredString("id");
        var active = gameLeases.TryGetValue(id, out var lease) && lease.Nonce == account.Value<long>("Nonce") && now - lease.LastActivity < GameLeaseMilliseconds;
        if (active && !sameInstallation && account.Value<long>("Nonce") != 0 && account.Value<string>("ClientType") != "webui" && account.Value<bool?>("Dropped") != true && body.Value<bool?>("kick") != true)
            throw new ApiException(400, "nonce still set");
        account["Nonce"] = Wire.Nonce();
        gameLeases[id] = (account.Value<long>("Nonce"), now);
        if (installation is { Length: 32 } && installation.All(char.IsAsciiHexDigit)) account["GameClientId"] = installation;
        else account.Remove("GameClientId");
        account["BuildLabel"] = request.Q("buildLabel")?.Replace(' ', '+') ?? options.FallbackBuildLabel;
        account["ClientType"] = body.Value<string>("ClientType") ?? "Windows";
        account["Language"] = body.Value<string>("lang") ?? "en";
        account["LastLogin"] = clock.GetUtcNow().ToString("O");
        account["IrcLoginAddress"] = request.ClientIp;
        account.Remove("Dropped");
        var origin = (options.GamePublicUrl ?? options.PublicUrl).TrimEnd('/');
        var response = new JObject
        {
            ["id"] = account["id"], ["DisplayName"] = account["DisplayName"], ["Nonce"] = account["Nonce"],
            ["BuildLabel"] = account["BuildLabel"], ["CountryCode"] = "", ["NRS"] = new JArray(options.NrsAddresses),
            ["IRC"] = new JArray(options.GetIrcAddresses()), ["ConsentNeeded"] = false, ["TrackedSettings"] = new JArray(),
            ["ForceLogoutVersion"] = 0, ["Groups"] = new JArray(), ["ClientType"] = account["ClientType"],
            ["CrossPlatformAllowed"] = true, ["HUB"] = origin + "/api/", ["platformCDNs"] = new JArray(origin + "/cdn/")
        };
        // The 2026.08.19 client rejects this legacy field before accepting the login.
        if (GameVersion.For(account) < GameVersion.August2026) response["DTLS"] = options.Dtls;
        return ApiResponse.Json(response);
    }

    public static ApiResponse SignupAndroid(JObject state, ApiRequest request, GoogleIdentity identity)
    {
        var account = All(state).FirstOrDefault(x => x.Value<string>("GoogleTokenId") == identity.Subject) ?? throw new ApiException(400, "account not found");
        if (account.Value<bool>("Banned")) throw new ApiException(403, "Account is disabled");
        var name = request.Q("accountName") ?? "";
        if (name.Length is < 1 or > 24 || name == "all" || name.Any(char.IsControl)) throw new ApiException(400, "Invalid display name");
        if (All(state).Any(x => x.Value<string>("id") != account.Value<string>("id") && x.Value<string>("DisplayName") == name)) throw new ApiException(409, "DisplayName already exists");
        account["DisplayName"] = name; account.Remove("AndroidSignupPending"); return ApiResponse.Text();
    }

    public JObject Authenticate(JObject state, ApiRequest request)
    {
        var id = request.Q("accountId");
        var account = id is not null ? state.Obj("accounts")[id] as JObject : null;
        if (account is null || account.Value<bool?>("Banned") == true || account.Value<long>("Nonce") == 0 ||
            !Wire.SecretEquals(request.Q("nonce"), account.Value<long>("Nonce").ToString(System.Globalization.CultureInfo.InvariantCulture)))
            throw new ApiException(401, "Invalid accountId-nonce pair");
        gameLeases[id!] = (account.Value<long>("Nonce"), clock.GetUtcNow().ToUnixTimeMilliseconds());
        return account;
    }

    public void Admin(ApiRequest request)
    {
        if (!Wire.SecretEquals(request.AdminToken, options.AdminToken)) throw new ApiException(401, "Administrator token required");
    }
    public static JObject Public(JObject account) => new()
    {
        ["id"] = account["id"], ["email"] = account["email"], ["DisplayName"] = account["DisplayName"],
        ["LastLogin"] = account["LastLogin"], ["Banned"] = account.Value<bool?>("Banned") ?? false,
        ["Online"] = account.Value<long>("Nonce") != 0 && account.Value<bool?>("Dropped") != true,
        ["SkipTutorial"] = account.Value<bool>("SkipTutorial"),
        ["PlayerLevel"] = account.Obj("Inventory")["PlayerLevel"], ["RegularCredits"] = account.Obj("Inventory")["RegularCredits"],
        ["PremiumCredits"] = account.Obj("Inventory")["PremiumCredits"]
    };

    // The game's password is already a client digest; PBKDF2 protects the stored verifier as well.
    public static string HashPassword(string password)
    {
        var salt = RandomNumberGenerator.GetBytes(16);
        var hash = Rfc2898DeriveBytes.Pbkdf2(password, salt, 100_000, HashAlgorithmName.SHA256, 32);
        return $"pbkdf2-sha256$100000${Convert.ToBase64String(salt)}${Convert.ToBase64String(hash)}";
    }
    public static bool VerifyPassword(string password, string credential)
    {
        var parts = credential.Split('$');
        if (parts.Length != 4 || parts[0] != "pbkdf2-sha256" || !int.TryParse(parts[1], out var iterations) || iterations is < 10_000 or > 1_000_000) return false;
        try { return CryptographicOperations.FixedTimeEquals(Rfc2898DeriveBytes.Pbkdf2(password, Convert.FromBase64String(parts[2]), iterations, HashAlgorithmName.SHA256, 32), Convert.FromBase64String(parts[3])); }
        catch (FormatException) { return false; }
    }
    public static string GamePassword(string password)
    {
        var digest = new Org.BouncyCastle.Crypto.Digests.WhirlpoolDigest();
        var data = Encoding.UTF8.GetBytes(password);
        digest.BlockUpdate(data, 0, data.Length);
        var result = new byte[digest.GetDigestSize()];
        digest.DoFinal(result, 0);
        return Convert.ToHexStringLower(result);
    }
}