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

XFEWarframe

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

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

namespace XFEWarframe.Core.Services;

// Desktop sessions are independent of game nonces and never grant management access.
public sealed partial class PlayerPortal(StateStore store, ServerOptions options, TimeProvider clock, Accounts accounts, Func<ItemCatalog> catalog)
{
    private sealed record Session(string AccountId, string Credential, DateTimeOffset Expires);
    private readonly ConcurrentDictionary<string, Session> sessions = new();
    private readonly Dictionary<string, (DateTimeOffset Until, int Count)> attempts = new();
    private static readonly string[] Currencies = ["RegularCredits", "PremiumCredits", "FusionPoints", "PrimeTokens", "CrewShipFusionPoints"];
    private static readonly string DummyCredential = Accounts.HashPassword("invalid-player-login");

    public async Task<ApiResponse> Handle(ApiRequest request, bool maintenance)
    {
        if (maintenance) throw new ApiException(503, "服务器正在维护,请稍后再试。");
        if (!request.Path.StartsWith("/player/v1/", StringComparison.Ordinal)) throw new ApiException(404, "Unknown player API version");
        var path = request.Path["/player/v1/".Length..].TrimEnd('/');
        var expected = path is "info" or "me" or "inventory" or "catalog" or "avatar" or "riven/catalog" or "editor/revision" ? "GET" : path is "register" or "login" or "logout" or "wallet/grant" or "items/grant" or "riven/calculate" or "identity" ? "POST" : path is "editor" or "archive" && request.Method is "GET" or "POST" ? request.Method : null;
        if (expected is null) throw new ApiException(404, "Unknown player endpoint");
        if (request.Method != expected) throw new ApiException(405, "Method not allowed");
        if (path is "login" or "register" or "identity") LimitAuthentication(request.ClientIp);
        if (path == "avatar") return await Avatars.Image(await store.Read(state => Avatars.Type(Authenticate(state, request.AdminToken))), options);
        if (path == "editor/revision") return await store.Read(state => ApiResponse.Json(new
        {
            version = AccountEditor.Version(state, Authenticate(state, request.AdminToken)),
            permissions = EditorPermissions.PlayerVersion(state, options), enabled = EditorPermissions.Enabled(state)
        }));
        return await store.Update(state =>
        {
            var registration = state.Obj("config").Value<bool?>("allowPlayerRegistration") ?? options.AllowPlayerRegistration;
            var grants = PlayerPermissions.Currency(state, options);
            var itemGrants = PlayerPermissions.Items(state, options);
            var editing = EditorPermissions.Enabled(state);
            var editingRevision = EditorPermissions.PlayerVersion(state, options);
            var rivenEditing = EditorPermissions.Allows(state, options, "riven");
            if (path == "info") return ApiResponse.Json(new { registrationEnabled = registration, currencyGrantEnabled = grants, itemGrantEnabled = itemGrants, editingEnabled = editing, serverName = ServerIdentity.Name(state, options), apiVersion = ServerIdentity.ApiVersion });
            if (path is "register" or "login")
            {
                var body = request.ObjectBody();
                var email = body.RequiredString("email", 254).Trim().ToLowerInvariant();
                var password = body.RequiredString("password", 256);
                JObject account;
                if (path == "register")
                {
                    if (!registration) throw new ApiException(403, "服务器已关闭玩家注册。");
                    if (!MailAddress.TryCreate(email, out var address) || address.Address != email || password.Length < 8)
                        throw new ApiException(400, "请输入有效邮箱和至少 8 位的密码。");
                    account = accounts.Create(state, email, Accounts.GamePassword(password), body.RequiredString("displayName", 24).Trim());
                }
                else
                {
                    var found = Accounts.All(state).FirstOrDefault(x => x.Value<string>("email") == email);
                    var valid = Accounts.VerifyPassword(Accounts.GamePassword(password), found?.Value<string>("credential") ?? DummyCredential);
                    if (!valid || found is null) throw new ApiException(401, "邮箱或密码不正确。");
                    account = found;
                    if (account.Value<bool>("Banned")) throw new ApiException(403, "此账号已被停用。");
                }
                if (path == "register" && body.Value<bool?>("signIn") == false) return ApiResponse.Json(new { profile = Snapshot(account, grants, itemGrants)["profile"] }, 201);
                var now = clock.GetUtcNow();
                foreach (var entry in sessions.Where(x => x.Value.Expires <= now)) sessions.TryRemove(entry.Key, out _);
                if (sessions.Count >= 10000) throw new ApiException(503, "登录会话已满,请稍后再试。");
                var token = Convert.ToHexStringLower(RandomNumberGenerator.GetBytes(32));
                var expires = now.AddHours(12);
                sessions[TokenHash(token)] = new(account.Value<string>("id")!, account.Value<string>("credential")!, expires);
                var response = Snapshot(account, grants, itemGrants, editing, editingRevision, rivenEditing);
                response["token"] = token;
                response["expiresAt"] = expires;
                return ApiResponse.Json(response, path == "register" ? 201 : 200);
            }
            var current = Authenticate(state, request.AdminToken);
            if (path == "identity") return EditIdentity(state, current, request.ObjectBody());
            if (path == "editor")
            {
                if (!editing) throw new ApiException(403, "管理员尚未开放存档编辑。");
                var editor = new AccountEditor(catalog(), clock, options);
                if (request.Method == "GET") return ApiResponse.Json(EditorPermissions.Filter(state, options, editor.Read(state, current, request)));
                var body = request.ObjectBody(); EditorPermissions.Require(state, options, body);
                return ApiResponse.Json(editor.Apply(state, current, body));
            }
            if (path == "archive")
            {
                var action = request.Method == "GET" ? "archive.export" : "archive.import";
                if (!EditorPermissions.Allows(state, options, action)) throw new ApiException(403, "管理员未授权此存档操作,或所需权限已撤销。");
                return ApiResponse.Json(request.Method == "GET" ? InventoryArchive.Read(state, current) :
                    InventoryArchive.Import(store, state, current, request.ObjectBody(), catalog(), clock, requireVersion: true));
            }
            if (path is "riven/catalog" or "riven/calculate")
            {
                if (!EditorPermissions.Allows(state, options, "riven")) throw new ApiException(403, "管理员尚未开放紫卡编辑。");
                return ApiResponse.Json(path == "riven/catalog" ? RivenCalculator.Catalog(catalog().WithLanguage(request.Q("lang")), request.Q("type")) : RivenCalculator.Calculate(request.ObjectBody(), catalog().WithLanguage(request.Q("lang"))));
            }
            if (path == "logout") { sessions.TryRemove(TokenHash(request.AdminToken!), out _); return ApiResponse.Json(new { loggedOut = true }); }
            if (path == "me") return ApiResponse.Json(Snapshot(current, grants, itemGrants, editing, editingRevision, rivenEditing));
            if (path == "inventory") return ApiResponse.Json(InventoryPage(current, request, grants, itemGrants, editing, editingRevision, rivenEditing));
            if (path is "catalog" or "items/grant")
            {
                if (!itemGrants) throw new ApiException(403, "服务器已关闭玩家自助添加物品。");
                if (path == "catalog") return ApiResponse.Json(CatalogPage(request));
                var item = Wire.ReadObject(request.Body);
                var type = catalog().ResolveType(item.RequiredString("type"));
                var count = item.Integer("count", 1, 100);
                PlayerPermissions.CheckItem(catalog(), type);
                var itemReceipts = current.Obj("PlayerItemReceipts");
                var itemKey = Receipt(itemReceipts, item, out var expires);
                if (itemReceipts[itemKey] is JObject prior)
                {
                    if (prior.Value<string>("type") != type || prior.Value<long>("count") != count) throw new ApiException(409, "请求编号已用于另一笔操作。");
                }
                else
                {
                    new ItemAcquisition(catalog(), clock, current).Add(current.Obj("Inventory"), type, (int)count, premium: true);
                    itemReceipts[itemKey] = new JObject { ["type"] = type, ["count"] = count, ["expiresAt"] = expires };
                }
                return ApiResponse.Json(Snapshot(current, grants, itemGrants, editing, editingRevision, rivenEditing));
            }
            if (!grants) throw new ApiException(403, "服务器已关闭玩家自助添加货币,请联系管理员。");
            var grant = Wire.ReadObject(request.Body);
            var currency = grant.RequiredString("currency", 40);
            if (!Currencies.Contains(currency)) throw new ApiException(400, "不支持的货币类型。");
            var amount = grant.Integer("amount", -10_000_000, 10_000_000);
            if (amount == 0) throw new ApiException(400, "调整数量不能为零。");
            if (!Guid.TryParseExact(grant.RequiredString("requestId", 36), "D", out var requestId)) throw new ApiException(400, "Invalid requestId");
            if (!DateTimeOffset.TryParse(grant.RequiredString("requestedAt", 40), out var requestedAt) ||
                requestedAt < clock.GetUtcNow().AddMinutes(-10) || requestedAt > clock.GetUtcNow().AddMinutes(1))
                throw new ApiException(400, "操作已过期,请刷新余额后重新提交。");
            var receipts = current.Obj("PlayerWalletReceipts");
            foreach (var old in receipts.Properties().Where(p => DateTimeOffset.Parse(p.Value.Value<string>("expiresAt")!) <= clock.GetUtcNow()).ToArray()) old.Remove();
            var key = requestId.ToString("D");
            if (receipts[key] is JObject previous)
            {
                if (previous.Value<string>("currency") != currency || previous.Value<long>("amount") != amount)
                    throw new ApiException(409, "请求编号已用于另一笔操作。");
                return ApiResponse.Json(Snapshot(current, grants, itemGrants, editing, editingRevision, rivenEditing));
            }
            if (receipts.Count >= 1000) throw new ApiException(429, "操作过于频繁,请稍后再试。");
            Inventory.ChangeCurrency(current.Obj("Inventory"), currency, amount, applyRules: false);
            receipts[key] = new JObject { ["currency"] = currency, ["amount"] = amount, ["expiresAt"] = requestedAt.AddMinutes(11).ToString("O") };
            return ApiResponse.Json(Snapshot(current, grants, itemGrants, editing, editingRevision, rivenEditing));
        });
    }

    private JObject Authenticate(JObject state, string? token)
    {
        if (token is null || token.Length != 64 || !sessions.TryGetValue(TokenHash(token), out var session))
            throw new ApiException(401, "请先登录玩家账号。");
        var account = state.Obj("accounts")[session.AccountId] as JObject;
        if (session.Expires <= clock.GetUtcNow() || account is null || account.Value<bool>("Banned") ||
            !Wire.SecretEquals(session.Credential, account.Value<string>("credential")))
        {
            sessions.TryRemove(TokenHash(token), out _);
            throw new ApiException(401, "登录已过期或账号状态已变更,请重新登录。");
        }
        return account;
    }

    private static string TokenHash(string token) => Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(token)));
    private static JObject Snapshot(JObject account, bool grants, bool itemGrants, bool editing = false, string editingRevision = "", bool rivenEditing = false) => new()
    {
        ["profile"] = new JObject { ["id"] = account["id"], ["email"] = account["email"], ["displayName"] = account["DisplayName"], ["avatarType"] = Avatars.Type(account), ["online"] = account.Value<long>("Nonce") != 0 && account.Value<bool?>("Dropped") != true },
        ["wallet"] = new JObject(Currencies.Select(key => new JProperty(key, account.Obj("Inventory").Value<long>(key)))),
        ["currencyGrantEnabled"] = grants, ["itemGrantEnabled"] = itemGrants, ["editingEnabled"] = editing, ["editingRevision"] = editingRevision, ["rivenEditingEnabled"] = rivenEditing
    };

    private JObject InventoryPage(JObject account, ApiRequest request, bool grants, bool itemGrants, bool editing, string editingRevision, bool rivenEditing)
    {
        var items = catalog().WithLanguage(request.Q("lang"));
        var rows = new List<JObject>();
        foreach (var property in account.Obj("Inventory").Properties().Where(p => p.Value is JArray))
        foreach (var entry in (JArray)property.Value)
        {
            var type = entry is JObject obj ? obj.Value<string>("ItemType") : entry.Type == JTokenType.String ? entry.ToString() : null;
            if (type is null || !type.StartsWith("/Lotus/", StringComparison.Ordinal)) continue;
            var name = type.Split('/').Last();
            try { name = entry is JObject owned ? items.InstanceName(owned) : items.Name(items.Get(type).Meta, type); } catch (ApiException) { }
            rows.Add(new JObject { ["id"] = entry is JObject item ? Wire.Id(item["ItemId"]) : "", ["type"] = type, ["name"] = name, ["category"] = property.Name,
                ["tags"] = items.Presentation(type).Value<string>("tags") ?? "",
                ["count"] = entry is JObject counted ? counted.Value<long?>("ItemCount") ?? 1 : 1, ["xp"] = entry is JObject equipment ? equipment.Value<long?>("XP") ?? 0 : 0 });
        }
        var query = request.Q("q") ?? "";
        if (query.Length > 200) throw new ApiException(400, "搜索文字过长。");
        var category = request.Q("category");
        var filtered = rows.Where(x => (string.IsNullOrEmpty(category) || x.Value<string>("category") == category) &&
            (x.Value<string>("name")!.Contains(query, StringComparison.OrdinalIgnoreCase) || x.Value<string>("type")!.Contains(query, StringComparison.OrdinalIgnoreCase))).ToArray();
        var skip = request.Q("skip") is string offset && int.TryParse(offset, out var start) && start >= 0 ? start : 0;
        var result = Snapshot(account, grants, itemGrants, editing, editingRevision, rivenEditing);
        result["total"] = filtered.Length;
        result["categories"] = new JArray(rows.Select(x => x.Value<string>("category")!).Distinct().Order());
        result["items"] = new JArray(filtered.OrderBy(x => x.Value<string>("name")).ThenBy(x => x.Value<string>("id")).Skip(skip).Take(100));
        return result;
    }

    private string Receipt(JObject receipts, JObject body, out string expires)
    {
        if (!Guid.TryParseExact(body.RequiredString("requestId", 36), "D", out var id)) throw new ApiException(400, "Invalid requestId");
        if (!DateTimeOffset.TryParse(body.RequiredString("requestedAt", 40), out var time) || time < clock.GetUtcNow().AddMinutes(-10) || time > clock.GetUtcNow().AddMinutes(1))
            throw new ApiException(400, "操作已过期,请刷新仓库后重新提交。");
        foreach (var old in receipts.Properties().Where(p => DateTimeOffset.Parse(p.Value.Value<string>("expiresAt")!) <= clock.GetUtcNow()).ToArray()) old.Remove();
        var key = id.ToString("D");
        if (receipts[key] is null && receipts.Count >= 1000) throw new ApiException(429, "操作过于频繁,请稍后再试。");
        expires = time.AddMinutes(11).ToString("O");
        return key;
    }

    private JObject CatalogPage(ApiRequest request)
    {
        var query = request.Q("q") ?? "";
        if (query.Length > 200) throw new ApiException(400, "搜索文字过长。");
        var items = catalog().WithLanguage(request.Q("lang"));
        var eligible = items.Entries.Where(x => PlayerPermissions.Grantable(x.Category)).ToArray();
        var filtered = eligible.Where(x => (string.IsNullOrEmpty(request.Q("category")) || x.Category == request.Q("category")) &&
            (x.Type.Contains(query, StringComparison.OrdinalIgnoreCase) || items.Name(x.Meta, x.Type).Contains(query, StringComparison.OrdinalIgnoreCase))).OrderBy(x => x.Type).ToArray();
        var skip = int.TryParse(request.Q("skip"), out var value) && value >= 0 ? value : 0;
        return new JObject { ["total"] = filtered.Length, ["categories"] = new JArray(eligible.Select(x => x.Category).Distinct().Order()),
            ["items"] = new JArray(filtered.Skip(skip).Take(80).Select(x => new JObject { ["type"] = x.Type, ["name"] = items.Name(x.Meta, x.Type), ["category"] = x.Category, ["tags"] = items.Presentation(x.Type).Value<string>("tags") ?? "" })) };
    }

    private void LimitAuthentication(string ip)
    {
        lock (attempts)
        {
            var now = clock.GetUtcNow();
            foreach (var key in attempts.Where(x => x.Value.Until <= now).Select(x => x.Key).ToArray()) attempts.Remove(key);
            if (attempts.Count >= 10000) throw new ApiException(429, "登录请求过多,请稍后再试。");
            var attempt = attempts.GetValueOrDefault(ip, (Until: now.AddMinutes(1), Count: 0));
            if (attempt.Count >= 30) throw new ApiException(429, "尝试过于频繁,请一分钟后重试。");
            attempts[ip] = (attempt.Until, attempt.Count + 1);
        }
    }
}