Add the Avalonia app and the xterm renderer, and fix two real bugs

The terminal works end to end. A new integration test drives a real sshd in
a container through a real PTY, the real pump, the real loopback WebSocket
with its token and origin checks, and a ClientWebSocket standing in for the
page: the login banner arrives, typed input round-trips, and `stty size`
reports the 100x30 the session asked for. The only untested link left is
xterm drawing bytes it was handed.

The WebView is de-risked on Windows, which was the plan's largest risk. Not
by assertion: with the app running there is an established TCP connection
from msedgewebview2 to the data plane port, so WebView2 launched, navigated
to the loopback page, executed terminal.js, and completed the WebSocket
handshake against the real token and origin checks. Linux remains unproven
and the package's own release notes now corroborate the concern -- Linux uses
a WPE backend, and it ships a NativeWebDialog described as useful where
embedded WebViews may be unavailable.

Two bugs found by building it, both of which would have shipped:

- ShellStream.Write buffers and needs an explicit Flush. Without one a
  keystroke is accepted, reported as written, and never reaches the remote:
  the terminal displays output perfectly and simply stops responding to
  input. SSH.NET's own WriteLine flushes, which is why the earlier spike
  never hit it. Found by isolating the pump against real SSH and reading
  BytesRead=51 -- banner and prompt through, nothing after.
- The Windows app manifest needs a supportedOS list, or Avalonia's native
  control host fails outright and the terminal never starts.

Also fixed a genuinely flaky test I happened to catch: SyncCursorTests
tampered with the *last* base64url character, whose low bits the decoder
ignores when the input length is not a multiple of three -- so a tampered
cursor sometimes decoded to identical bytes and verified. It failed roughly
one run in thirty, depending on a random key. Now tampers the penultimate
character, which is fully significant at every length; 40 consecutive runs
are clean.

xterm 6.0.0 plus the fit and webgl addons are vendored as UMD bundles rather
than built with npm, so a clean clone needs only the .NET SDK. Provenance
and licences are recorded next to them, along with the UMD global names
terminal.js depends on -- a bundle that switched to ES modules would load
without error and leave Terminal undefined.

The renderer acknowledges output from term.write's completion callback, not
on receipt. Acknowledging early would return flow-control credit for bytes
the screen has not caught up with, which is the one thing the credit window
exists to measure.

TerminalWorkspace moved into DodoSSH.Client.Terminal: it has no Avalonia
dependency, and having it there is what let the end-to-end test exist at all.

404 tests pass, zero warnings on a clean rebuild, format clean.
This commit is contained in:
2026-07-28 22:30:42 +02:00
parent eb354bcdd9
commit 5fccd53824
30 changed files with 2087 additions and 21 deletions
@@ -8,6 +8,13 @@
<ItemGroup>
<ProjectReference Include="../../src/DodoSSH.Client.Ssh/DodoSSH.Client.Ssh.csproj" />
<!--
For the end-to-end test that runs a real SSH session through the real data plane. It lives
here rather than in the terminal suite because this is the project that already owns the
OpenSSH container, and duplicating that fixture would mean two containers per test run.
-->
<ProjectReference Include="../../src/DodoSSH.Client.Terminal/DodoSSH.Client.Terminal.csproj" />
</ItemGroup>
<ItemGroup>
@@ -0,0 +1,127 @@
using System.Text;
using DodoSSH.Client.Terminal;
namespace DodoSSH.Client.Ssh.Tests;
/// <summary>
/// The pump against a real shell, with the transport replaced by a recorder.
/// </summary>
/// <remarks>
/// Sits between the pump's unit tests, which use a fake shell, and the full end-to-end test, which
/// adds the loopback socket. Its value is diagnostic: when output does not reach a renderer, this
/// says whether the pump and SSH.NET are producing anything at all.
/// </remarks>
[Collection(SshCollection.Name)]
public sealed class PumpOverRealSshTests(SshServerFixture fixture)
{
/// <summary>Trusts the container's host key, then connects. First contact is refused by design.</summary>
private async Task<ISshConnection> ConnectTrustedAsync()
{
var knownHosts = new InMemoryKnownHostStore();
var factory = new SshNetConnectionFactory(knownHosts);
var request = new SshConnectionRequest(
fixture.Host,
fixture.Port,
SshServerFixture.Username,
new SshPasswordCredential(SshServerFixture.Password));
var unknown = await Should.ThrowAsync<SshHostKeyUnknownException>(async () =>
await factory.ConnectAsync(request, TestContext.Current.CancellationToken));
await knownHosts.TrustAsync(unknown.Presentation, TestContext.Current.CancellationToken);
return await factory.ConnectAsync(request, TestContext.Current.CancellationToken);
}
[Fact]
public async Task ThePump_ForwardsRealShellOutput()
{
await using var connection = await ConnectTrustedAsync();
var shell = await connection.OpenShellAsync(
new TerminalSize(100, 30, 1000, 750), TestContext.Current.CancellationToken);
var transport = new CountingTransport();
await using var pump = new TerminalSessionPump(
1,
shell,
transport,
TimeProvider.System,
new TerminalPumpOptions { FlushInterval = TimeSpan.FromMilliseconds(20) });
transport.Pump = pump;
var run = pump.RunAsync(TestContext.Current.CancellationToken);
// Marker split so the PTY's echo of the command line does not satisfy the match.
await pump.WriteInputAsync(
Encoding.UTF8.GetBytes("echo \"DODO\"\"SSH-OK\"\n"),
TestContext.Current.CancellationToken);
var deadline = TimeProvider.System.GetUtcNow() + TimeSpan.FromSeconds(20);
while (TimeProvider.System.GetUtcNow() < deadline
&& !transport.Text.Contains("DODOSSH-OK", StringComparison.Ordinal))
{
await Task.Delay(50, TestContext.Current.CancellationToken);
}
transport.Text.Contains("DODOSSH-OK", StringComparison.Ordinal).ShouldBeTrue(
$"BytesRead={pump.BytesRead}, FramesSent={pump.FramesSent}, "
+ $"OutputFrames={transport.OutputFrames}, Text=<{transport.Text}>");
await pump.DisposeAsync();
try
{
await run;
}
catch (OperationCanceledException)
{
// Expected: disposing the pump cancels its run.
}
}
/// <summary>Accumulates output and acknowledges it, as a keeping-up renderer would.</summary>
private sealed class CountingTransport : ITerminalTransport
{
private readonly StringBuilder text = new();
private readonly Lock gate = new();
internal TerminalSessionPump? Pump { get; set; }
internal int OutputFrames { get; private set; }
internal string Text
{
get
{
lock (gate)
{
return text.ToString();
}
}
}
public ValueTask SendAsync(ReadOnlyMemory<byte> frame, CancellationToken cancellationToken)
{
if (!TerminalFrame.TryRead(frame.Span, out var opcode, out _, out var payload)
|| opcode != (byte)TerminalServerOpcode.Output)
{
return ValueTask.CompletedTask;
}
lock (gate)
{
OutputFrames++;
text.Append(Encoding.UTF8.GetString(payload));
}
Pump?.Acknowledge((uint)payload.Length);
return ValueTask.CompletedTask;
}
}
}
@@ -0,0 +1,252 @@
using System.Globalization;
using System.Net.WebSockets;
using System.Text;
using DodoSSH.Client.Terminal;
namespace DodoSSH.Client.Ssh.Tests;
/// <summary>
/// A real SSH session, through the real data plane, to a stand-in renderer.
/// </summary>
/// <remarks>
/// <para>
/// Everything the desktop client does when a user opens a terminal, minus the pixels: a real
/// <c>sshd</c> in a container, a real pseudo-terminal, the real loopback WebSocket with its token and
/// origin checks, and a <see cref="ClientWebSocket"/> standing in for the page. If a shell prompt
/// arrives here and typed input round-trips, the only untested link left is xterm drawing bytes it was
/// handed.
/// </para>
/// <para>
/// Worth having because the alternative is driving a GUI. The WebView's own participation is
/// verifiable separately — it opens a TCP connection to this same port — but that says nothing about
/// whether an SSH session's output reaches it.
/// </para>
/// </remarks>
[Collection(SshCollection.Name)]
public sealed class TerminalEndToEndTests(SshServerFixture fixture)
{
private static readonly TimeSpan Timeout = TimeSpan.FromSeconds(30);
/// <remarks>
/// The real page is an Avalonia resource in the app project. This test stands in for the renderer
/// itself, so a placeholder-bearing stub is all the transport needs.
/// </remarks>
private static InMemoryTerminalAssetProvider StubAssets() =>
new(new Dictionary<string, TerminalAsset>(StringComparer.Ordinal)
{
[TerminalDataPlane.PagePath] = new(
"text/html; charset=utf-8",
Encoding.UTF8.GetBytes(
$"<html data-token=\"{TerminalDataPlane.TokenPlaceholder}\" "
+ $"data-socket=\"{TerminalDataPlane.SocketUrlPlaceholder}\"></html>")),
});
[Fact]
public async Task AShellSessionReachesTheRenderer_AndInputReachesTheRemote()
{
var knownHosts = new InMemoryKnownHostStore();
await using var workspace = new TerminalWorkspace(
StubAssets(),
new SshNetConnectionFactory(knownHosts),
TimeProvider.System);
workspace.Start();
// The token comes from the served page, exactly as the real renderer obtains it.
var token = await ReadTokenAsync(workspace.PageUrl);
using var renderer = await AttachAsync(workspace.PageUrl, token);
await workspace.WaitForRendererAsync();
var sessionId = await OpenTrustedSessionAsync(workspace, knownHosts);
// SessionOpened tells the renderer to create a terminal before any output arrives for it.
var opened = await ReceiveAsync(renderer);
opened.Opcode.ShouldBe((byte)TerminalServerOpcode.SessionOpened);
opened.SessionId.ShouldBe(sessionId);
// The login banner and prompt arrive unprompted, acknowledged as the page does from
// term.write's callback.
var banner = await ReadOutputUntilAsync(renderer, sessionId, "$", acknowledge: true);
banner.ShouldContain("OpenSSH");
// Marker split so the PTY's echo of the command line does not satisfy the match.
await SendAsync(
renderer,
sessionId,
(byte)TerminalClientOpcode.Input,
Encoding.UTF8.GetBytes("echo \"DODO\"\"SSH-OK\"; stty size\n"));
var output = await ReadOutputUntilAsync(renderer, sessionId, "DODOSSH-OK", acknowledge: true);
output.ShouldContain("DODOSSH-OK");
// The size requested when the session opened is the size the remote sees, which means the
// pty-req carried it rather than the terminal silently defaulting to 80x24.
output.Replace('\r', '\n').ShouldContain("30 100");
await workspace.CloseSessionAsync(sessionId);
}
// ---- Helpers ----
/// <summary>
/// Trusts the container's host key, then opens a session.
/// </summary>
/// <remarks>
/// The refused first attempt is part of the assertion, not setup noise: a host with no pinned key
/// must not connect, and the fingerprint the user would be shown has to be in the exception.
/// </remarks>
private async Task<uint> OpenTrustedSessionAsync(
TerminalWorkspace workspace,
InMemoryKnownHostStore knownHosts)
{
var request = new SshConnectionRequest(
fixture.Host,
fixture.Port,
SshServerFixture.Username,
new SshPasswordCredential(SshServerFixture.Password));
var unknown = await Should.ThrowAsync<SshHostKeyUnknownException>(async () =>
await workspace.OpenSessionAsync(
request, TerminalSize.Default, TestContext.Current.CancellationToken));
unknown.Presentation.Fingerprint.ShouldStartWith(SshHostKeyFingerprint.Prefix);
await knownHosts.TrustAsync(unknown.Presentation, TestContext.Current.CancellationToken);
return await workspace.OpenSessionAsync(
request,
new TerminalSize(100, 30, 1000, 750),
TestContext.Current.CancellationToken);
}
private static async Task<string> ReadTokenAsync(Uri pageUrl)
{
using var client = new HttpClient();
var page = await client.GetStringAsync(pageUrl, TestContext.Current.CancellationToken);
const string Marker = "data-token=\"";
var start = page.IndexOf(Marker, StringComparison.Ordinal) + Marker.Length;
var end = page.IndexOf('"', start);
return page[start..end];
}
private static async Task<ClientWebSocket> AttachAsync(Uri pageUrl, string token)
{
var socket = new ClientWebSocket();
socket.Options.AddSubProtocol(TerminalDataPlane.SubProtocol);
socket.Options.AddSubProtocol($"token.{token}");
socket.Options.SetRequestHeader(
"Origin",
string.Create(CultureInfo.InvariantCulture, $"http://127.0.0.1:{pageUrl.Port}"));
try
{
await socket.ConnectAsync(
new Uri($"ws://127.0.0.1:{pageUrl.Port}{TerminalDataPlane.SocketPath}"),
TestContext.Current.CancellationToken);
}
catch
{
socket.Dispose();
throw;
}
return socket;
}
private static Task SendAsync(
ClientWebSocket socket,
uint sessionId,
byte opcode,
byte[] payload) =>
socket.SendAsync(
TerminalFrame.Create(opcode, sessionId, payload),
WebSocketMessageType.Binary,
endOfMessage: true,
TestContext.Current.CancellationToken);
/// <remarks>
/// Bounded by its own timeout rather than relying on a caller's deadline. A blocking receive is
/// where a missing frame turns into a hung test run instead of a failure with a message, and a hang
/// tells you nothing about which frame never came.
/// </remarks>
private static async Task<(byte Opcode, uint SessionId, byte[] Payload)> ReceiveAsync(
ClientWebSocket socket)
{
var buffer = new byte[256 * 1024];
using var deadline = new CancellationTokenSource(Timeout);
using var linked = CancellationTokenSource.CreateLinkedTokenSource(
deadline.Token,
TestContext.Current.CancellationToken);
WebSocketReceiveResult result;
try
{
result = await socket.ReceiveAsync(buffer, linked.Token);
}
catch (OperationCanceledException) when (deadline.IsCancellationRequested)
{
throw new TimeoutException($"No terminal frame arrived within {Timeout}.");
}
TerminalFrame.TryRead(
buffer.AsSpan(0, result.Count), out var opcode, out var sessionId, out var payload)
.ShouldBeTrue();
return (opcode, sessionId, payload.ToArray());
}
/// <summary>Reads output frames until the text appears, acknowledging each as the page does.</summary>
private static async Task<string> ReadOutputUntilAsync(
ClientWebSocket socket,
uint sessionId,
string expected,
bool acknowledge)
{
var accumulated = new StringBuilder();
var deadline = TimeProvider.System.GetUtcNow() + Timeout;
while (TimeProvider.System.GetUtcNow() < deadline)
{
var frame = await ReceiveAsync(socket);
if (frame.Opcode == (byte)TerminalServerOpcode.SessionClosed)
{
throw new InvalidOperationException(
$"The session closed before '{expected}' arrived: "
+ $"{Encoding.UTF8.GetString(frame.Payload)}\nSeen so far:\n{accumulated}");
}
if (frame.Opcode != (byte)TerminalServerOpcode.Output)
{
continue;
}
if (acknowledge)
{
// Returning credit is what keeps the pump reading. Without it the session stalls at
// the window size and this loop would time out on a working implementation.
await SendAsync(
socket,
sessionId,
(byte)TerminalClientOpcode.Acknowledge,
TerminalFrame.CreateAcknowledgementPayload((uint)frame.Payload.Length));
}
accumulated.Append(Encoding.UTF8.GetString(frame.Payload));
if (accumulated.ToString().Contains(expected, StringComparison.Ordinal))
{
return accumulated.ToString();
}
}
throw new TimeoutException($"'{expected}' did not arrive within {Timeout}.\n{accumulated}");
}
}
@@ -302,6 +302,12 @@
"SSH.NET": "[2025.1.0, )"
}
},
"dodossh.client.terminal": {
"type": "Project",
"dependencies": {
"DodoSSH.Client.Ssh": "[1.0.0, )"
}
},
"BouncyCastle.Cryptography": {
"type": "CentralTransitive",
"requested": "[2.6.2, )",
@@ -58,7 +58,15 @@ public sealed class SyncCursorTests
public void RejectsATamperedTag()
{
var cursor = SyncCursor.Encode(Key, VaultId, 100);
var tampered = cursor[..^1] + (cursor[^1] == 'A' ? 'B' : 'A');
// The second-to-last character, never the last one. Base64 encodes 3 bytes per 4 characters,
// so when the input length is not a multiple of 3 the final character carries bits that
// decode to nothing — and altering only those produces a different string that decodes to
// identical bytes, verifies fine, and makes this test pass or fail depending on the random
// key. The penultimate character is fully significant at every input length.
var tampered = cursor[..^2] + (cursor[^2] == 'A' ? 'B' : 'A') + cursor[^1];
tampered.Equals(cursor, StringComparison.Ordinal).ShouldBeFalse();
SyncCursor.TryDecode(Key, tampered, VaultId, out _).ShouldBeFalse();
}