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

XFEWarframe

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

公开
关注 0 Fork 0 Star 0
UTF-8
using System.Net;
using System.Net.Http.Headers;
using System.Text;
using System.Text.Json;
using XFEWarframe.Client.Runtime;
using Xunit;

namespace XFEWarframe.Client.Tests;

public sealed class RuntimeControlTests : IDisposable
{
    private readonly string root = Path.Combine(Path.GetTempPath(), "XFEWarframe-runtime-tests", Guid.NewGuid().ToString("N"));
    private string Sessions => Path.Combine(root, "sessions");
    private static ClientConfiguration Config => new() { BuildLabel = "2026.08.19.11.06", ServerName = "Local runtime check", ServerUrl = "http://127.0.0.1:18444" };

    [Fact] public async Task RuntimeUsesAuthenticatedLoopbackAndReportsOnlyImplementedCapabilities()
    {
        await using var server = new RuntimeControlServer(root, Config, new(), _ => { }, 0, Sessions);
        using var client = new RuntimeControlClient(server.Session);
        var status = await client.StatusAsync(); Assert.Equal(Config.BuildLabel, status.GameVersion); Assert.Equal(server.Session.Instance, status.Instance);
        Assert.Contains(status.Capabilities, x => x.Key == "logs" && x.Available);
        Assert.Contains(status.Capabilities, x => x.Key == "experimental_multi_abilities" && !x.Available);
        Assert.All(status.Capabilities.Where(x => x.Key is "scripts" or "camera" or "teleport" or "metadata" or "hotfix"), x => Assert.False(x.Available));
        using var http = new HttpClient(new HttpClientHandler { UseProxy = false });
        Assert.Equal(HttpStatusCode.Unauthorized, (await http.GetAsync(server.Session.Endpoint + "/status")).StatusCode);
        http.DefaultRequestHeaders.Authorization = new("Bearer", server.Session.Token);
        var reply = await http.GetStringAsync(server.Session.Endpoint + "/status"); Assert.DoesNotContain(server.Session.Token, reply);
        http.DefaultRequestHeaders.Add("Origin", "https://example.invalid");
        Assert.Equal(HttpStatusCode.Forbidden, (await http.PostAsync(server.Session.Endpoint + "/runtime/v1/logs/clear", new StringContent("{}"))).StatusCode);
        http.DefaultRequestHeaders.Remove("Origin"); http.DefaultRequestHeaders.Host = "attacker.invalid";
        Assert.Equal(HttpStatusCode.Forbidden, (await http.GetAsync(server.Session.Endpoint + "/status")).StatusCode);
        http.DefaultRequestHeaders.Host = null;
        Assert.Equal(HttpStatusCode.NotFound, (await http.PostAsync(server.Session.Endpoint + "/start_script", new StringContent("{}"))).StatusCode);
    }

    [Fact] public async Task MultipleAbilityCapabilityRequiresAnExplicitRuntimeBinding()
    {
        await using var server = new RuntimeControlServer(root, Config, new(), _ => { }, 0, Sessions, multiAbilitiesAvailable: true);
        using var client = new RuntimeControlClient(server.Session);
        var status = await client.StatusAsync();
        Assert.Contains(status.Capabilities, x => x.Key == "experimental_multi_abilities" && x.Available);
        Assert.All(status.Capabilities.Where(x => x.Key is "scripts" or "camera" or "teleport"), x => Assert.False(x.Available));
    }

    [Theory][InlineData(false, "http://127.0.0.1:18444", 404)][InlineData(true, "https://example.invalid", 404)][InlineData(true, "http://127.0.0.1:18444", 200)]
    public async Task GameAdapterRequiresLaunchOptInLoopbackAndAuthenticatedNonBrowserRequests(bool enabled, string origin, int expectedStatus)
    {
        var config = Config; config.EnableGameTestControl = enabled; config.ServerUrl = origin; config.GameServerUrl = "https://127.0.0.1:18443";
        var calls = 0;
        await using var server = new RuntimeControlServer(root, config, new(), _ => { }, 0, Sessions,
            gameControl: (operation, body, cancellation) =>
            {
                Assert.Equal("POST lua", operation); Assert.Equal("{}", Encoding.UTF8.GetString(body));
                Interlocked.Increment(ref calls); return Task.FromResult("{\"ok\":true}");
            });
        using var http = new HttpClient(new HttpClientHandler { UseProxy = false });
        var url = server.Session.Endpoint + "/runtime/v1/game/lua";
        Assert.Equal(HttpStatusCode.Unauthorized, (await http.PostAsync(url, new StringContent("{}"))).StatusCode);
        http.DefaultRequestHeaders.Authorization = new("Bearer", server.Session.Token);
        http.DefaultRequestHeaders.Add("Origin", "https://example.invalid");
        Assert.Equal(HttpStatusCode.Forbidden, (await http.PostAsync(url, new StringContent("{}"))).StatusCode);
        http.DefaultRequestHeaders.Remove("Origin");
        Assert.Equal(expectedStatus, (int)(await http.PostAsync(url, new StringContent("{}"))).StatusCode);
        Assert.Equal(expectedStatus == 200 ? 1 : 0, calls);
        Assert.Contains(server.Status().Capabilities, c => c.Key == "game_test_control" && c.Available == (expectedStatus == 200));
    }

    [Fact] public async Task GameCommandTimeoutCancelsBeforeAQueuedCommandCanExecute()
    {
        var config = Config; config.EnableGameTestControl = true; config.GameServerUrl = "https://127.0.0.1:18443";
        var cancelled = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
        var executed = false;
        await using var server = new RuntimeControlServer(root, config, new(), _ => { }, 0, Sessions,
            gameControl: async (_, _, cancellation) =>
            {
                try { await Task.Delay(TimeSpan.FromSeconds(10), cancellation); executed = true; return "{}"; }
                catch (OperationCanceledException) { cancelled.TrySetResult(); throw; }
            });
        using var http = new HttpClient(new HttpClientHandler { UseProxy = false });
        http.DefaultRequestHeaders.Authorization = new("Bearer", server.Session.Token);
        await Assert.ThrowsAsync<HttpRequestException>(() => http.PostAsync(server.Session.Endpoint + "/runtime/v1/game/lua", new StringContent("{}")));
        await cancelled.Task.WaitAsync(TimeSpan.FromSeconds(2));
        Assert.False(executed);
    }

    [Fact] public async Task RuntimeSettingsApplySavePreserveUnknownFieldsAndReloadWithoutExposingThem()
    {
        Directory.CreateDirectory(Path.Combine(root, "XFEWarframe"));
        var path = Path.Combine(root, "XFEWarframe", "runtime-settings.json");
        await File.WriteAllTextAsync(path, "{\"futureSetting\":{\"keep\":7},\"autologin_password\":\"never-return-this\"}");
        RuntimeSettings? applied = null;
        await using (var server = new RuntimeControlServer(root, Config, new(), x => applied = x, 0, Sessions))
        {
            using var client = new RuntimeControlClient(server.Session);
            Assert.False(applied!.DisableOverlay);
            await client.SettingsAsync(new(true, true)); Assert.True(applied.DisableOverlay); Assert.True(applied.ClientHttpLogging);
            Assert.DoesNotContain("disableOverlay", await File.ReadAllTextAsync(path)); // Persistence is an explicit operation.
            Assert.True((await client.SaveAsync()).Saved);
            using var http = new HttpClient(); http.DefaultRequestHeaders.Authorization = new("Bearer", server.Session.Token);
            var response = await http.PostAsync(server.Session.Endpoint + "/runtime/v1/settings", new StringContent("{\"fovOverride\":110}", Encoding.UTF8, "application/json"));
            Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
            Assert.DoesNotContain("never-return-this", await http.GetStringAsync(server.Session.Endpoint + "/status"));
        }
        Assert.Empty(Directory.EnumerateFiles(Sessions));
        using var saved = JsonDocument.Parse(await File.ReadAllTextAsync(path)); Assert.Equal(7, saved.RootElement.GetProperty("futureSetting").GetProperty("keep").GetInt32());
        await using var restarted = new RuntimeControlServer(root, Config, new(), x => applied = x, 0, Sessions);
        Assert.True(applied!.DisableOverlay); Assert.True(applied.ClientHttpLogging);
        using var reconnected = new RuntimeControlClient(restarted.Session); Assert.True((await reconnected.StatusAsync()).Settings.DisableOverlay);
    }

    [Fact] public async Task RuntimeLogsAreBoundedIncrementalAndResetAfterOverflowOrClear()
    {
        var logs = new RuntimeLogBuffer(3); logs.Add("first");
        await using var server = new RuntimeControlServer(root, Config, logs, _ => { }, 0, Sessions);
        using var client = new RuntimeControlClient(server.Session);
        var first = await client.LogsAsync(0); Assert.Single(first.Items);
        logs.Add("second"); var second = await client.LogsAsync(first.Cursor); Assert.Single(second.Items); Assert.Equal("second", second.Items[0].Message);
        foreach (var number in Enumerable.Range(0, 8)) logs.Add(number.ToString());
        var overflow = await client.LogsAsync(first.Cursor); Assert.True(overflow.Reset); Assert.Equal(3, overflow.Items.Length);
        await client.ClearLogsAsync(); var cleared = await client.LogsAsync(overflow.Cursor); Assert.True(cleared.Reset); Assert.Empty(cleared.Items);
        Assert.Empty((await client.LogsAsync(cleared.Cursor)).Items);
        logs.Add(new string('a', 10000)); Assert.Equal(2048, (await client.LogsAsync(cleared.Cursor)).Items[0].Message.Length);
    }

    [Fact] public async Task BusyDefaultPortFallsBackWithoutConnectingToTheOtherRuntime()
    {
        await using var first = new RuntimeControlServer(root, Config, new(), _ => { }, 0, Sessions);
        await using var second = new RuntimeControlServer(root, Config, new(), _ => { }, new Uri(first.Session.Endpoint).Port, Sessions);
        Assert.NotEqual(first.Session.Endpoint, second.Session.Endpoint); Assert.NotEqual(first.Session.Token, second.Session.Token);
        using var wrong = new RuntimeControlClient(second.Session with { Endpoint = first.Session.Endpoint });
        var exception = await Assert.ThrowsAsync<HttpRequestException>(() => wrong.StatusAsync()); Assert.Equal(HttpStatusCode.Unauthorized, exception.StatusCode);
    }

    [Theory][InlineData("http://example.invalid:6155")][InlineData("http://127.0.0.1:6155/status")][InlineData("https://127.0.0.1:6155")]
    public void DiscoveryRejectsRemoteOrNonCanonicalEndpoints(string endpoint) => Assert.Throws<InvalidDataException>(() =>
        RuntimeDiscovery.Validate(new(Guid.NewGuid().ToString("N"), 1, root, endpoint, new string('a', 64), DateTimeOffset.UtcNow)));

    [Fact] public async Task OriginalCardCacheApiRequiresItsBindingAndAuthenticatedDesktopRequests()
    {
        var config = Config; config.EnableGameTestControl = false;
        var calls = new List<string>();
        var status = new NativeCardCacheStatus(true, 1, 0, "zh", config.BuildLabel, "CardUtilitiesRedux/Direct3D11", "pending");
        await using var server = new RuntimeControlServer(root, config, new(), _ => { }, 0, Sessions,
            visualControl: (operation, bytes, cancellation) =>
            {
                calls.Add(operation);
                if (operation == "POST cards")
                {
                    var body = JsonSerializer.Deserialize(bytes, VisualCacheJson.Default.NativeCardCacheRequest)!;
                    Assert.Equal("zh", body.Language); Assert.Equal("{\"lvl\":0}", Assert.Single(body.Cards).Fingerprint);
                }
                return Task.FromResult(JsonSerializer.Serialize(status, VisualCacheJson.Default.NativeCardCacheStatus));
            });
        using var client = new RuntimeControlClient(server.Session);
        Assert.Contains((await client.StatusAsync()).Capabilities, x => x.Key == "original_mod_cards" && x.Available);
        Assert.Contains((await client.StatusAsync()).Capabilities, x => x.Key == "game_test_control" && !x.Available);
        Assert.Equal(status, await client.CacheCardsAsync(new("zh", [new("/Lotus/Upgrades/Mods/Warframe/AvatarHealthMaxMod", "{\"lvl\":0}")])));
        Assert.Equal(status, await client.CardCacheStatusAsync());
        Assert.Equal(new[] { "POST cards", "GET cards" }, calls);
        using var http = new HttpClient(new HttpClientHandler { UseProxy = false });
        var url = server.Session.Endpoint + "/runtime/v1/visuals/cards";
        Assert.Equal(HttpStatusCode.Unauthorized, (await http.PostAsync(url, new StringContent("{}"))).StatusCode);
        http.DefaultRequestHeaders.Authorization = new("Bearer", server.Session.Token);
        http.DefaultRequestHeaders.Add("Origin", "https://example.invalid");
        Assert.Equal(HttpStatusCode.Forbidden, (await http.PostAsync(url, new StringContent("{}"))).StatusCode);
        Assert.Equal(2, calls.Count);
        await using var old = new RuntimeControlServer(root, config, new(), _ => { }, 0, Sessions);
        using var unsupported = new RuntimeControlClient(old.Session);
        Assert.Contains((await unsupported.StatusAsync()).Capabilities, x => x.Key == "original_mod_cards" && !x.Available);
        await Assert.ThrowsAsync<HttpRequestException>(() => unsupported.CardCacheStatusAsync());
    }

    [Fact] public async Task CardBindingFailureUpdatesCapabilitiesAndRemainsReadableWithItsOriginalReason()
    {
        var status = new NativeCardCacheStatus(true, 1, 0, "zh", Config.BuildLabel, "CardUtilitiesRedux/Direct3D11", "pending", "waiting-for-card-render");
        await using var server = new RuntimeControlServer(root, Config, new(), _ => { }, 0, Sessions,
            visualControl: (operation, bytes, cancellation) =>
            {
                var snapshot = Volatile.Read(ref status);
                if (operation == "POST cards" && !snapshot.Available) throw new InvalidOperationException(snapshot.Message);
                return Task.FromResult(JsonSerializer.Serialize(snapshot, VisualCacheJson.Default.NativeCardCacheStatus));
            }, visualStatus: () => Volatile.Read(ref status));
        using var client = new RuntimeControlClient(server.Session);
        Assert.Contains((await client.StatusAsync()).Capabilities, x => x.Key == "original_mod_cards" && x.Available && x.Reason == "waiting-for-card-render");
        Volatile.Write(ref status, status with { Available = false, Pending = 0, Reason = "card-draw-binding-failed", Message = "原生卡面回调绑定失败:test script failure" });
        Assert.Contains((await client.StatusAsync()).Capabilities, x => x.Key == "original_mod_cards" && !x.Available && x.Reason == "card-draw-binding-failed");
        Assert.Equal(status, await client.CardCacheStatusAsync());
        var error = await Assert.ThrowsAsync<HttpRequestException>(() => client.CacheCardsAsync(new("zh", [new("/Lotus/Upgrades/Mods/Warframe/AvatarHealthMaxMod", "{\"lvl\":0}")])));
        Assert.Equal(HttpStatusCode.Conflict, error.StatusCode); Assert.Equal(status.Message, error.Message);
        Assert.DoesNotContain("DirectX", error.Message);
    }

    [Fact] public async Task CardCacheDiagnosisRemainsAccessibleWhenTheGraphicsBindingNeverStarted()
    {
        var status = new NativeCardCacheStatus(false, 0, 0, "zh", Config.BuildLabel, "CardUtilitiesRedux/Direct3D11", "本次游戏使用 DirectX 12。", "direct3d11-required");
        await using var server = new RuntimeControlServer(root, Config, new(), _ => { }, 0, Sessions,
            visualControl: (_, _, _) => Task.FromResult(JsonSerializer.Serialize(status, VisualCacheJson.Default.NativeCardCacheStatus)),
            visualStatus: () => status);
        using var client = new RuntimeControlClient(server.Session);
        Assert.Contains((await client.StatusAsync()).Capabilities, x => x.Key == "original_mod_cards" && !x.Available && x.Reason == status.Reason);
        Assert.Equal(status, await client.CardCacheStatusAsync());
        using var http = new HttpClient(new HttpClientHandler { UseProxy = false });
        Assert.Equal(HttpStatusCode.Unauthorized, (await http.GetAsync(server.Session.Endpoint + "/runtime/v1/visuals/cards")).StatusCode);
    }

    public void Dispose()
    {
        var allowed = Path.GetFullPath(Path.Combine(Path.GetTempPath(), "XFEWarframe-runtime-tests")) + Path.DirectorySeparatorChar;
        if (Path.GetFullPath(root).StartsWith(allowed, StringComparison.OrdinalIgnoreCase) && Directory.Exists(root)) Directory.Delete(root, true);
    }
}