feat(livestreamassist): add read-only WebSocket API

Add a Fleck/Newtonsoft.Json listener for local and LAN clients, with system methods, main-thread reflection reads, and ZipMod packaging of the two runtime DLLs. Ctrl+F8 statistics assist is unchanged. In-game and LAN acceptance remain pending.
This commit is contained in:
soarqin committed 2026-09-17 18:14:51 +08:00
1 parent ce9a4b73cd
commit 94254b8c28
16 files changed
+3300 -37

No files matched your search

@@ -0,0 +1,44 @@
param(
[Parameter(Mandatory)]
[string] $TargetDir
)
Set-StrictMode -Version Latest
$ErrorActionPreference = 'Stop'
$TargetDir = $TargetDir.Trim().Trim('"').TrimEnd('\', '/')
$steamPath = $null
foreach ($regPath in @(
'HKCU:\Software\Valve\Steam',
'HKLM:\Software\Valve\Steam',
'HKLM:\Software\Wow6432Node\Valve\Steam'
)) {
try {
$val = (Get-ItemProperty -LiteralPath $regPath -Name SteamPath -ErrorAction Stop).SteamPath
if ($val -and (Test-Path $val)) { $steamPath = $val; break }
} catch { }
}
if (-not $steamPath) { throw 'Steam installation not found; cannot copy game facades for ReflectionReaderCheck.' }
$vdfPath = Join-Path $steamPath 'steamapps\libraryfolders.vdf'
$vdfContent = Get-Content $vdfPath -Raw -Encoding UTF8
$blockPattern = '"(?:\d+)"\s*\{([^{}]*(?:\{[^{}]*\}[^{}]*)*)\}'
$managed = $null
foreach ($block in [regex]::Matches($vdfContent, $blockPattern, 'Singleline')) {
$text = $block.Groups[1].Value
if ($text -notmatch '"1366540"\s+"[^"]+"') { continue }
$pathMatch = [regex]::Match($text, '"path"\s+"([^"]+)"')
if (-not $pathMatch.Success) { continue }
$libPath = $pathMatch.Groups[1].Value -replace '\\\\', '\' -replace '/', '\'
$candidate = Join-Path $libPath 'steamapps\common\Dyson Sphere Program\DSPGAME_Data\Managed'
if (Test-Path $candidate) { $managed = $candidate; break }
}
if (-not $managed) { throw 'DSP Managed directory not found; cannot copy game facades for ReflectionReaderCheck.' }
foreach ($name in @('netstandard.dll', 'UnityEngine.CoreModule.dll', 'UnityEngine.SharedInternalsModule.dll')) {
$src = Join-Path $managed $name
if (-not (Test-Path $src)) { throw "Missing $src" }
Copy-Item -LiteralPath $src -Destination (Join-Path $TargetDir $name) -Force
}
@@ -0,0 +1,210 @@
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using LiveStreamAssist.Api;
using UnityEngine;
namespace ReflectionReaderCheck;
static class Program
{
static int _failed;
static int Main()
{
var reader = new ReflectionReader(typeof(Program).Assembly);
try
{
InheritedPrivateFields(reader);
BlockedGetter(reader);
NullIntermediateAndTerminal(reader);
DictionaryKeys(reader);
Indexes(reader);
ShallowCycle(reader);
Int64Precision(reader);
NonFinite(reader);
UnityAndStreamBlocked(reader);
}
finally
{
reader.ClearCache();
}
if (_failed > 0)
{
Console.Error.WriteLine($"FAILED {_failed} check(s)");
return 1;
}
Console.WriteLine("OK");
return 0;
}
static void InheritedPrivateFields(ReflectionReader reader)
{
var obj = new DerivedFixture { Visible = 3 };
obj.SetBaseSecret(9);
var result = reader.Read(obj, typeof(DerivedFixture), new[] { new PathSeg("baseSecret") }, default);
Check(result.Error == null, "inherited private field readable");
Check(Equals(result.Encoded, 9), "inherited private field value");
var desc = reader.Describe(obj, typeof(DerivedFixture), Array.Empty<PathSeg>());
Check(HasMember(desc, "baseSecret"), "describe lists inherited private field");
Check(HasMember(desc, "Visible"), "describe lists derived field");
}
static void BlockedGetter(ReflectionReader reader)
{
var obj = new DerivedFixture();
var read = reader.Read(obj, typeof(DerivedFixture), new[] { new PathSeg("Boom") }, default);
Check(read.Error != null && read.Error.Kind == "MEMBER_NOT_ALLOWED", "blocked getter is MEMBER_NOT_ALLOWED");
var backing = reader.Read(obj, typeof(DerivedFixture), new[] { new PathSeg("<Boom>k__BackingField") }, default);
Check(backing.Error != null && backing.Error.Kind == "MEMBER_NOT_FOUND", "backing field not exposed");
var desc = reader.Describe(obj, typeof(DerivedFixture), Array.Empty<PathSeg>());
Check(!HasMember(desc, "Boom"), "blocked getter omitted from describe");
}
static void NullIntermediateAndTerminal(ReflectionReader reader)
{
var obj = new DerivedFixture();
var terminal = reader.Read(obj, typeof(DerivedFixture), new[] { new PathSeg("Child") }, default);
Check(terminal.Error == null && terminal.IsNull, "null terminal succeeds");
var mid = reader.Read(obj, typeof(DerivedFixture), new[] { new PathSeg("Child"), new PathSeg("Visible") }, default);
Check(mid.Error != null && mid.Error.Kind == "NULL_PATH", "null intermediate is NULL_PATH");
var desc = reader.Describe(obj, typeof(DerivedFixture), new[] { new PathSeg("Child") });
Check(desc.Error == null && desc.IsNull, "describe null terminal");
Check(desc.TypeName == "ReflectionReaderCheck.DerivedFixture", "null uses declared type");
}
static void DictionaryKeys(ReflectionReader reader)
{
var obj = new DerivedFixture();
obj.IntDict[1001] = 4;
obj.StrDict["a"] = 5;
var ok = reader.Read(obj, typeof(DerivedFixture), new[] { new PathSeg("IntDict"), new PathSeg((object)1001) }, default);
Check(ok.Error == null && Equals(ok.Encoded, 4), "int dictionary key");
var mismatch = reader.Read(obj, typeof(DerivedFixture), new[] { new PathSeg("IntDict"), new PathSeg((object)"1001") }, default);
Check(mismatch.Error != null && mismatch.Error.Kind == "INVALID_PARAMS", "string key not converted to int");
var missing = reader.Read(obj, typeof(DerivedFixture), new[] { new PathSeg("IntDict"), new PathSeg((object)9) }, default);
Check(missing.Error != null && missing.Error.Kind == "KEY_NOT_FOUND", "missing int key");
var str = reader.Read(obj, typeof(DerivedFixture), new[] { new PathSeg("StrDict"), new PathSeg((object)"a") }, default);
Check(str.Error == null && Equals(str.Encoded, 5), "string dictionary key");
var summary = reader.Read(obj, typeof(DerivedFixture), new[] { new PathSeg("IntDict") }, default);
Check(summary.Error == null && summary.Encoded is Dictionary<string, object> d && Equals(d["$kind"], "dictionary"),
"dictionary terminal is summary");
}
static void Indexes(ReflectionReader reader)
{
var obj = new DerivedFixture { Arr = new[] { 10, 20, 30 }, List = new List<int> { 7, 8 } };
var a0 = reader.Read(obj, typeof(DerivedFixture), new[] { new PathSeg("Arr"), new PathSeg(0) }, default);
Check(a0.Error == null && Equals(a0.Encoded, 10), "array index 0");
var oob = reader.Read(obj, typeof(DerivedFixture), new[] { new PathSeg("Arr"), new PathSeg(3) }, default);
Check(oob.Error != null && oob.Error.Kind == "INDEX_OUT_OF_RANGE", "array oob");
var page = reader.Read(obj, typeof(DerivedFixture), new[] { new PathSeg("Arr") },
new ReadOptions { HasOffset = true, Offset = 1, HasLimit = true, Limit = 1 });
Check(page.Error == null, "array page");
var dict = (Dictionary<string, object>)page.Encoded;
var items = (List<object>)dict["items"];
Check(items.Count == 1 && Equals(items[0], 20) && Equals(dict["totalCount"], 3) && Equals(dict["hasMore"], true),
"array page contents");
var empty = reader.Read(obj, typeof(DerivedFixture), new[] { new PathSeg("List") },
new ReadOptions { HasOffset = true, Offset = 8, HasLimit = true, Limit = 2 });
var emptyDict = (Dictionary<string, object>)empty.Encoded;
Check(((List<object>)emptyDict["items"]).Count == 0 && Equals(emptyDict["hasMore"], false) && Equals(emptyDict["offset"], 8),
"offset past end is empty page");
}
static void ShallowCycle(ReflectionReader reader)
{
var obj = new DerivedFixture();
obj.Cycle = obj;
var summary = reader.Read(obj, typeof(DerivedFixture), Array.Empty<PathSeg>(), default);
Check(summary.Error == null && summary.Encoded is Dictionary<string, object> d && Equals(d["$kind"], "object"),
"cyclic object without select is summary");
var hop = reader.Read(obj, typeof(DerivedFixture), new[] { new PathSeg("Cycle"), new PathSeg("Cycle") }, default);
Check(hop.Error == null && hop.Encoded is Dictionary<string, object> d2 && Equals(d2["$kind"], "object"),
"explicit cyclic path stays a summary");
}
static void Int64Precision(ReflectionReader reader)
{
var obj = new DerivedFixture { Big = 9007199254740993L, BigU = 18446744073709551615UL };
var signed = reader.Read(obj, typeof(DerivedFixture), new[] { new PathSeg("Big") }, default);
Check(Equals(signed.Encoded, "9007199254740993"), "int64 beyond 2^53 is decimal string");
var unsigned = reader.Read(obj, typeof(DerivedFixture), new[] { new PathSeg("BigU") }, default);
Check(Equals(unsigned.Encoded, ulong.MaxValue.ToString(CultureInfo.InvariantCulture)), "uint64 is decimal string");
}
static void NonFinite(ReflectionReader reader)
{
var obj = new DerivedFixture { Nan = double.NaN, Inf = double.PositiveInfinity };
var nan = reader.Read(obj, typeof(DerivedFixture), new[] { new PathSeg("Nan") }, default);
Check(nan.Error != null && nan.Error.Kind == "UNSUPPORTED_VALUE", "NaN is UNSUPPORTED_VALUE");
var inf = reader.Read(obj, typeof(DerivedFixture), new[] { new PathSeg("Inf") }, default);
Check(inf.Error != null && inf.Error.Kind == "UNSUPPORTED_VALUE", "Infinity is UNSUPPORTED_VALUE");
}
static void UnityAndStreamBlocked(ReflectionReader reader)
{
var obj = new DerivedFixture();
var unity = reader.Read(obj, typeof(DerivedFixture), new[] { new PathSeg("Texture") }, default);
Check(unity.Error != null && unity.Error.Kind == "MEMBER_NOT_ALLOWED", "UnityEngine.Object field blocked");
var stream = reader.Read(obj, typeof(DerivedFixture), new[] { new PathSeg("Buffer") }, default);
Check(stream.Error != null && stream.Error.Kind == "MEMBER_NOT_ALLOWED", "Stream field blocked");
var desc = reader.Describe(obj, typeof(DerivedFixture), Array.Empty<PathSeg>());
Check(!HasMember(desc, "Texture") && !HasMember(desc, "Buffer"), "infrastructure omitted from describe");
var vec = reader.Read(obj, typeof(DerivedFixture), new[] { new PathSeg("Vec") },
new ReadOptions { HasSelect = true, Select = new[] { "x" } });
Check(vec.Error == null, "Unity vector fields readable");
}
static bool HasMember(WalkResult desc, string name)
{
if (desc.Members == null) return false;
foreach (var m in desc.Members)
{
if (m.Name == name) return true;
}
return false;
}
static void Check(bool cond, string name)
{
if (cond)
{
Console.WriteLine("ok " + name);
return;
}
_failed++;
Console.Error.WriteLine("fail " + name);
}
}
class BaseFixture
{
int baseSecret;
public void SetBaseSecret(int value) => baseSecret = value;
}
class DerivedFixture : BaseFixture
{
public int Visible;
public DerivedFixture Child = null;
public DerivedFixture Cycle = null;
public long Big;
public ulong BigU;
public double Nan;
public double Inf;
public Dictionary<int, int> IntDict = new Dictionary<int, int>();
public Dictionary<string, int> StrDict = new Dictionary<string, int>();
public int[] Arr;
public List<int> List;
public Texture Texture = null;
public MemoryStream Buffer = new MemoryStream();
public Vector3 Vec = new Vector3(1f, 2f, 3f);
public int Boom => throw new InvalidOperationException("getter must not run");
}
@@ -0,0 +1,16 @@
<?xml version="1.0" encoding="utf-8"?>
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<AssemblyName>ReflectionReaderCheck</AssemblyName>
<RootNamespace>ReflectionReaderCheck</RootNamespace>
<BepInExPluginGuid>org.soardev.livestreamassist.reflectioncheck</BepInExPluginGuid>
<PackPreloaderTargetDir>none</PackPreloaderTargetDir>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\..\LiveStreamAssist.csproj" />
</ItemGroup>
<Target Name="CopyGameFacades" AfterTargets="Build">
<Exec Command="powershell.exe -NoProfile -ExecutionPolicy Bypass -File &quot;$(MSBuildThisFileDirectory)Copy-GameFacades.ps1&quot; -TargetDir $(TargetDir)." />
</Target>
</Project>
@@ -0,0 +1,223 @@
#Requires -Version 7.0
param(
[Parameter(Mandatory)]
[string] $ServerUri,
[switch] $RequireGame,
[int] $TimeoutSec = 8
)
Set-StrictMode -Version Latest
$ErrorActionPreference = 'Stop'
$failed = 0
$script:seq = 0
$utf8 = [Text.UTF8Encoding]::new($false)
function New-Id {
$script:seq++
"t-$script:seq"
}
function Connect-Api {
param([string] $Uri)
$ws = [Net.WebSockets.ClientWebSocket]::new()
$cts = [Threading.CancellationTokenSource]::new([TimeSpan]::FromSeconds($TimeoutSec))
$ws.ConnectAsync([Uri]$Uri, $cts.Token).GetAwaiter().GetResult()
return @{ Ws = $ws; Cts = $cts }
}
function Close-Api {
param($Conn)
if (-not $Conn) { return }
try {
if ($Conn.Ws.State -eq [Net.WebSockets.WebSocketState]::Open) {
$Conn.Ws.CloseAsync([Net.WebSockets.WebSocketCloseStatus]::NormalClosure, '', $Conn.Cts.Token).GetAwaiter().GetResult()
}
} catch { }
try { $Conn.Ws.Dispose() } catch { }
try { $Conn.Cts.Dispose() } catch { }
}
function Send-Text {
param($Conn, [string] $Text, [bool] $End = $true)
$bytes = $utf8.GetBytes($Text)
$seg = [ArraySegment[byte]]::new($bytes)
$Conn.Ws.SendAsync($seg, [Net.WebSockets.WebSocketMessageType]::Text, $End, $Conn.Cts.Token).GetAwaiter().GetResult()
}
function Receive-Message {
param($Conn)
$buffer = [byte[]]::new(65536)
$ms = [IO.MemoryStream]::new()
do {
$seg = [ArraySegment[byte]]::new($buffer)
$result = $Conn.Ws.ReceiveAsync($seg, $Conn.Cts.Token).GetAwaiter().GetResult()
if ($result.MessageType -eq [Net.WebSockets.WebSocketMessageType]::Close) {
return @{ Closed = $true; CloseStatus = [int]$Conn.Ws.CloseStatus; Text = $null }
}
$ms.Write($buffer, 0, $result.Count)
} while (-not $result.EndOfMessage)
return @{ Closed = $false; Text = $utf8.GetString($ms.ToArray()) }
}
function Invoke-Rpc {
param($Conn, [string] $Method, $Params = @{}, [string] $Id = $(New-Id))
$body = [ordered]@{ jsonrpc = '2.0'; id = $Id; method = $Method; params = $Params }
Send-Text $Conn ($body | ConvertTo-Json -Compress -Depth 16)
$msg = Receive-Message $Conn
if ($msg.Closed) { throw "Connection closed while waiting for $Method (close $($msg.CloseStatus))" }
return ($msg.Text | ConvertFrom-Json)
}
function Assert-True {
param([bool] $Cond, [string] $Name)
if ($Cond) { Write-Host "ok $Name" }
else { Write-Host "fail $Name"; $script:failed++ }
}
function Assert-Kind {
param($Resp, [string] $Kind, [string] $Name)
$actual = $null
if ($Resp.error -and $Resp.error.data) { $actual = [string]$Resp.error.data.kind }
Assert-True ($actual -eq $Kind) "$Name (kind=$actual)"
}
$conn = $null
try {
$conn = Connect-Api $ServerUri
$ping = Invoke-Rpc $conn 'system.ping'
Assert-True ($null -ne $ping.result.serverTimeUtc) 'system.ping'
$info = Invoke-Rpc $conn 'system.info'
Assert-True ($info.result.apiVersion -eq '1.0.0') 'system.info apiVersion'
Assert-True ($info.result.limits.maxRequestBytes -eq 65536) 'system.info limits'
Assert-True ($info.result.capabilities.'api.stats' -eq $false) 'api.stats false'
Assert-True ($info.result.capabilities.subscriptions -eq $false) 'subscriptions false'
Assert-True ($info.result.PSObject.Properties.Name -contains 'gameVersionReady') 'gameVersionReady present'
$ok = Invoke-Rpc $conn 'system.validate' @{ apiMajor = 1; requiredCapabilities = @('reflection.read') }
Assert-True ($ok.result.compatible -eq $true) 'validate compatible'
$statsCap = Invoke-Rpc $conn 'system.validate' @{ apiMajor = 1; requiredCapabilities = @('api.stats') }
Assert-True ($statsCap.result.compatible -eq $false -and $statsCap.result.missingCapabilities[0] -eq 'api.stats') 'validate missing api.stats'
$major = Invoke-Rpc $conn 'system.validate' @{ apiMajor = 2 }
Assert-True ($major.result.compatible -eq $false -and $major.result.apiMajorCompatible -eq $false) 'validate major mismatch'
$stats = Invoke-Rpc $conn 'system.stats'
Assert-True ($stats.result.available -eq $false -and $null -eq $stats.result.metrics) 'system.stats placeholder'
Send-Text $conn '{not-json'
$parse = (Receive-Message $conn).Text | ConvertFrom-Json
Assert-Kind $parse 'PARSE_ERROR' 'malformed JSON'
Send-Text $conn '{"jsonrpc":"2.0","method":"system.ping","params":{}}'
$noId = (Receive-Message $conn).Text | ConvertFrom-Json
Assert-Kind $noId 'INVALID_REQUEST' 'missing id'
Send-Text $conn '{"jsonrpc":"2.0","id":1,"method":"system.ping","params":{}}'
$numId = (Receive-Message $conn).Text | ConvertFrom-Json
Assert-Kind $numId 'INVALID_REQUEST' 'numeric id'
$unknown = Invoke-Rpc $conn 'system.nope'
Assert-Kind $unknown 'METHOD_NOT_FOUND' 'unknown method'
$extra = Invoke-Rpc $conn 'system.ping' @{ foo = 1 }
Assert-Kind $extra 'INVALID_PARAMS' 'unknown ping param'
Send-Text $conn '[{"jsonrpc":"2.0","id":"b","method":"system.ping"}]'
$batch = (Receive-Message $conn).Text | ConvertFrom-Json
Assert-Kind $batch 'INVALID_REQUEST' 'batch array'
Send-Text $conn '{"jsonrpc":"2.0","id":"dup","method":"data.read","params":{"root":"history","path":["currentTech"]}}'
Send-Text $conn '{"jsonrpc":"2.0","id":"dup","method":"data.read","params":{"root":"history","path":["currentTech"]}}'
$dup = Receive-Message $conn
if ($dup.Closed) {
Assert-True ($dup.CloseStatus -eq 1008) "duplicate outstanding id close $($dup.CloseStatus)"
} else {
Assert-True $false 'duplicate outstanding id should close'
}
Close-Api $conn
$conn = Connect-Api $ServerUri
$ping2 = Invoke-Rpc $conn 'system.ping'
Assert-True ($null -ne $ping2.result.serverTimeUtc) 'recover after duplicate-id close'
$conn.Ws.SendAsync(
[ArraySegment[byte]]::new([byte[]](1, 2, 3)),
[Net.WebSockets.WebSocketMessageType]::Binary,
$true,
$conn.Cts.Token).GetAwaiter().GetResult()
$bin = Receive-Message $conn
Assert-True ($bin.Closed -and $bin.CloseStatus -eq 1003) "binary rejected $($bin.CloseStatus)"
Close-Api $conn
$conn = Connect-Api $ServerUri
$big = 'x' * 70000
Send-Text $conn $big
$over = Receive-Message $conn
Assert-True ($over.Closed -and $over.CloseStatus -eq 1009) "oversized close $($over.CloseStatus)"
Close-Api $conn
$uri = [Uri]$ServerUri
$badPath = Connect-Api "$($uri.Scheme)://$($uri.Authority)/nope"
$bad = Receive-Message $badPath
Assert-True ($bad.Closed -and $bad.CloseStatus -eq 1008) "wrong path close $($bad.CloseStatus)"
Close-Api $badPath
$conn = Connect-Api $ServerUri
$part1 = '{"jsonrpc":"2.0","id":"frag","method":'
$part2 = '"system.ping","params":{}}'
Send-Text $conn $part1 $false
Send-Text $conn $part2
$frag = (Receive-Message $conn).Text | ConvertFrom-Json
Assert-True ($null -ne $frag.result.serverTimeUtc) 'fragmented text message'
$unknownRoot = Invoke-Rpc $conn 'data.read' @{ root = 'no-such-root' }
Assert-Kind $unknownRoot 'ROOT_NOT_FOUND' 'unknown root'
if ($RequireGame) {
$roots = Invoke-Rpc $conn 'data.roots'
Assert-True ($roots.result.gameReady -eq $true) 'data.roots gameReady'
Assert-True ($null -ne $roots.result.sessionId) 'sessionId'
$tech = Invoke-Rpc $conn 'data.read' @{ root = 'history'; path = @('currentTech') }
Assert-True ($null -eq $tech.error) 'read history.currentTech'
$queue = Invoke-Rpc $conn 'data.read' @{ root = 'history'; path = @('techQueue'); offset = 0; limit = 8 }
Assert-True ($null -eq $queue.error) 'read history.techQueue'
$techId = [int]$tech.result.value
if ($techId -eq 0 -and $queue.result.value.items) {
foreach ($item in @($queue.result.value.items)) {
if ([int]$item -ne 0) { $techId = [int]$item; break }
}
}
if ($techId -eq 0) {
throw 'No research ID from currentTech or techQueue'
}
$state = Invoke-Rpc $conn 'data.read' @{
root = 'history'
path = @('techStates', @{ key = $techId })
select = @('curLevel', 'hashUploaded', 'hashNeeded')
}
Assert-True ($null -eq $state.error) "read techStates[$techId]"
Assert-True ($null -ne $state.result.value.curLevel) 'research curLevel'
} else {
$roots = Invoke-Rpc $conn 'data.roots'
Assert-True ($roots.result.PSObject.Properties.Name -contains 'gameReady') 'data.roots without save'
if ($roots.result.gameReady -eq $true) {
Write-Host 'note game is ready; -RequireGame would exercise research reads'
}
}
$still = Invoke-Rpc $conn 'system.ping'
Assert-True ($null -ne $still.result.serverTimeUtc) 'ping after protocol errors'
}
finally {
Close-Api $conn
}
if ($failed -gt 0) {
Write-Error "FAILED $failed assertion(s)"
exit 1
}
Write-Host 'OK'
exit 0