Skip to content

Computer use for the Pi coding agent — Windows apps, browsers and desktops through native UI trees, screenshots and real input.

fix: secure native window identity channels (LPT-1026)

alexshpunt-clanker[bot]cfc4b77888f4
diff --git a/scripts/identity-auth.ps1 b/scripts/identity-auth.ps1
new file mode 100644
index 0000000..c425de9
--- /dev/null
+++ b/scripts/identity-auth.ps1
@@ -0,0 +1,27 @@
+# Server half of the relay proof for a Sandbox identity channel. The shared relay-auth.ps1 is loaded by the caller.
+function Accept-PiIdentityClient([Net.Sockets.TcpClient]$Client, $Auth, [Diagnostics.Stopwatch]$Clock) {
+ if ($Auth.session -isnot [string] -or $Auth.session -cnotmatch '^[a-zA-Z0-9_-]{1,80}$' -or
+ $Auth.key -isnot [string] -or $Auth.key -cnotmatch '^[a-f0-9]{64}$') { throw 'Invalid identity credentials.' }
+ [void](Get-PiRelayRemaining $Clock)
+ $stream = $Client.GetStream()
+ $nonceBytes = [byte[]]::new(32)
+ $rng = [Security.Cryptography.RandomNumberGenerator]::Create()
+ try { $rng.GetBytes($nonceBytes) } finally { $rng.Dispose() }
+ $nonce = -join ($nonceBytes | ForEach-Object { $_.ToString('x2') })
+ Write-PiRelayFrame $stream $Clock @{ version = 1; nonce = $nonce }
+ $request = Read-PiRelayFrame $stream $Clock
+ if ($request.version -is [string] -or $request.version -is [bool] -or $request.version -ne 1 -or
+ $request.session -isnot [string] -or $request.session -cne $Auth.session -or
+ $request.channel -isnot [string] -or $request.channel -cne 'identity' -or
+ $request.role -isnot [string] -or $request.role -cne 'client' -or
+ $request.nonce -isnot [string] -or $request.nonce -cnotmatch '^[a-f0-9]{64}$' -or
+ $request.proof -isnot [string] -or $request.proof -cnotmatch '^[a-f0-9]{64}$') { throw 'Identity authentication failed.' }
+ [byte[]]$key = for ($i = 0; $i -lt 64; $i += 2) { [Convert]::ToByte($Auth.key.Substring($i, 2), 16) }
+ $expected = Get-PiRelayProof $key 'client' $Auth.session 'identity' $nonce $request.nonce 'client'
+ if (-not (Test-PiRelayProof $request.proof $expected)) { throw 'Identity authentication failed.' }
+ $proof = Get-PiRelayProof $key 'server' $Auth.session 'identity' $nonce $request.nonce 'client'
+ Write-PiRelayFrame $stream $Clock @{ proof = $proof }
+ # The deadline belongs to authentication, not the lifetime of a window marker.
+ $stream.ReadTimeout = [Threading.Timeout]::Infinite
+ $stream.WriteTimeout = [Threading.Timeout]::Infinite
+}
diff --git a/scripts/identity-channel.cs b/scripts/identity-channel.cs
new file mode 100644
index 0000000..6ffbd13
--- /dev/null
+++ b/scripts/identity-channel.cs
@@ -0,0 +1,14 @@
+using System.IO;
+using System.Threading.Tasks;
+
+public static class PiIdentityPipe {
+ // Process stdin is buffered. Flush each request chunk rather than waiting for its pipe buffer to fill.
+ public static async Task CopyAndFlushAsync(Stream source, Stream destination) {
+ byte[] buffer = new byte[4096];
+ int count;
+ while ((count = await source.ReadAsync(buffer, 0, buffer.Length).ConfigureAwait(false)) != 0) {
+ await destination.WriteAsync(buffer, 0, count).ConfigureAwait(false);
+ await destination.FlushAsync().ConfigureAwait(false);
+ }
+ }
+}
diff --git a/scripts/identity-channel.ps1 b/scripts/identity-channel.ps1
new file mode 100644
index 0000000..82489a7
--- /dev/null
+++ b/scripts/identity-channel.ps1
@@ -0,0 +1,25 @@
+# Owned marker peers use only stdio; no local TCP endpoint is exposed.
+if (-not ('PiIdentityPipe' -as [type])) {
+ Add-Type -Path (Join-Path $PSScriptRoot 'identity-channel.cs')
+}
+function Start-PiIdentityPeer([string]$Peer) {
+ $encoded = [Convert]::ToBase64String([Text.Encoding]::Unicode.GetBytes((Get-Content -Raw -LiteralPath $Peer)))
+ $info = [Diagnostics.ProcessStartInfo]::new('powershell.exe', "-NoLogo -NoProfile -NonInteractive -EncodedCommand $encoded")
+ $info.UseShellExecute = $false
+ $info.RedirectStandardInput = $true
+ $info.RedirectStandardOutput = $true
+ $info.CreateNoWindow = $true
+ return [Diagnostics.Process]::Start($info)
+}
+function Stop-PiIdentityPeer($Process) {
+ if (-not $Process) { return }
+ try {
+ if (-not $Process.HasExited) {
+ try { $Process.StandardInput.Close() } catch [IO.IOException] { }
+ if (-not $Process.WaitForExit(5000)) {
+ $Process.Kill()
+ if (-not $Process.WaitForExit(2000)) { throw 'Identity peer shutdown is unconfirmed.' }
+ }
+ }
+ } finally { $Process.Dispose() }
+}
diff --git a/scripts/sandbox/guest-identity-bridge.ps1 b/scripts/sandbox/guest-identity-bridge.ps1
index 2b46804..13fe238 100644
--- a/scripts/sandbox/guest-identity-bridge.ps1
+++ b/scripts/sandbox/guest-identity-bridge.ps1
@@ -1,32 +1,96 @@
-# Runs in a Windows Sandbox guest session. For each host connection, start the window identity peer
-# (window-identity.ps1) and pump bytes between the socket and its stdio. Closing the connection ends the
-# peer's input, so it removes its window markers and exits.
-param([int]$Port = 47802, [string]$Peer = 'C:\pi\config\window-identity.ps1')
+# A Sandbox identity channel gets its own marker peer only after mutual proof. Closing input removes its markers.
+param(
+ [int]$Port = 47802,
+ [string]$Peer = 'C:\pi\config\window-identity.ps1',
+ [string]$Credentials = 'C:\pi\config\identity.json',
+ [string]$Address = '0.0.0.0'
+)
$ErrorActionPreference = 'Stop'
-$encoded = [Convert]::ToBase64String([Text.Encoding]::Unicode.GetBytes((Get-Content -Raw $Peer)))
-$listener = [Net.Sockets.TcpListener]::new([Net.IPAddress]::Any, $Port)
-$listener.Start()
-while ($true) {
- $client = $listener.AcceptTcpClient()
+$auth = Get-Content -Raw -LiteralPath $Credentials | ConvertFrom-Json
+if ($auth.session -isnot [string] -or $auth.session -cnotmatch '^[a-zA-Z0-9_-]{1,80}$' -or
+ $auth.key -isnot [string] -or $auth.key -cnotmatch '^[a-f0-9]{64}$') { throw 'Invalid identity credentials.' }
+# Compile the shared pipe helper once before workers enter the same AppDomain.
+. (Join-Path $PSScriptRoot 'identity-channel.ps1')
+$worker = {
+ param($Client, $Auth, $Clock, [string]$Peer, [string]$Helpers)
+ $ErrorActionPreference = 'Stop'
$process = $null
+ $up = $null; $down = $null
+ $authenticated = $false
try {
- $info = [Diagnostics.ProcessStartInfo]::new('powershell.exe', "-NoLogo -NoProfile -NonInteractive -EncodedCommand $encoded")
- $info.UseShellExecute = $false
- $info.RedirectStandardInput = $true
- $info.RedirectStandardOutput = $true
- $info.CreateNoWindow = $true
- $process = [Diagnostics.Process]::Start($info)
- $socket = $client.GetStream()
+ . (Join-Path $Helpers 'relay-auth.ps1')
+ . (Join-Path $Helpers 'identity-auth.ps1')
+ . (Join-Path $Helpers 'identity-channel.ps1')
+ Accept-PiIdentityClient $Client $Auth $Clock
+ $authenticated = $true
+ $process = Start-PiIdentityPeer $Peer
+ $socket = $Client.GetStream()
+ $up = [PiIdentityPipe]::CopyAndFlushAsync($socket, $process.StandardInput.BaseStream)
$down = $process.StandardOutput.BaseStream.CopyToAsync($socket)
- # The peer's stdin is a buffered stream: flush every chunk so each request line reaches it at once.
- $input = $process.StandardInput.BaseStream
- $buffer = [byte[]]::new(4096)
- while (($read = $socket.Read($buffer, 0, $buffer.Length)) -gt 0) { $input.Write($buffer, 0, $read); $input.Flush() }
- $process.StandardInput.Close()
- [void]$process.WaitForExit(10000)
- [void]$down.Wait(5000)
- } catch { } finally {
- if ($process -and -not $process.HasExited) { $process.Kill() }
- $client.Close()
+ [void][Threading.Tasks.Task]::WaitAny([Threading.Tasks.Task[]]@($up, $down))
+ } catch {
+ # Authentication failures close without service. Do not log the request or credentials.
+ if ($authenticated) { [Console]::Error.WriteLine('Window identity channel failed.') }
+ } finally {
+ # Unblock both network pumps before waiting for the peer's graceful EOF cleanup.
+ $Client.Close()
+ try { if ($process) { Stop-PiIdentityPeer $process } }
+ finally {
+ $tasks = @($up, $down) | Where-Object { $null -ne $_ }
+ if ($tasks.Count) {
+ try { [void][Threading.Tasks.Task]::WaitAll([Threading.Tasks.Task[]]$tasks, 1000) } catch {}
+ foreach ($task in $tasks) { if ($task.IsFaulted) { [void]$task.Exception } }
+ }
+ }
+ }
+}
+$maxClients = 32
+$pool = [RunspaceFactory]::CreateRunspacePool(1, $maxClients)
+$listener = [Net.Sockets.TcpListener]::new([Net.IPAddress]::Parse($Address), $Port)
+$jobs = [Collections.Generic.List[object]]::new()
+try {
+ $pool.Open()
+ $listener.Start()
+ $accept = $listener.AcceptTcpClientAsync()
+ while ($true) {
+ foreach ($job in @($jobs)) {
+ if ($job.result.IsCompleted) {
+ try { [void]$job.pipeline.EndInvoke($job.result) }
+ catch { [Console]::Error.WriteLine('Window identity worker failed.') }
+ finally { $job.pipeline.Dispose(); $job.client.Close(); [void]$jobs.Remove($job) }
+ }
+ }
+ if ($accept.IsCompleted) {
+ $client = $accept.GetAwaiter().GetResult()
+ $clock = [Diagnostics.Stopwatch]::StartNew()
+ $accept = $listener.AcceptTcpClientAsync()
+ if ($jobs.Count -ge $maxClients) { $client.Close(); continue }
+ $pipeline = [PowerShell]::Create()
+ try {
+ $pipeline.RunspacePool = $pool
+ [void]$pipeline.AddScript($worker.ToString()).AddArgument($client).AddArgument($auth).AddArgument($clock).AddArgument($Peer).AddArgument($PSScriptRoot)
+ $result = $pipeline.BeginInvoke()
+ $jobs.Add([pscustomobject]@{ client = $client; pipeline = $pipeline; result = $result })
+ } catch { $pipeline.Dispose(); $client.Close(); throw }
+ }
+ Start-Sleep -Milliseconds 20
+ }
+} finally {
+ $listener.Stop()
+ if ($client) { $client.Close() }
+ if ($accept) {
+ # Stop completes a pending accept; an already accepted but undispatched socket is owned here too.
+ try { $pending = $accept.GetAwaiter().GetResult(); $pending.Close() } catch {}
+ }
+ try {
+ # Unblock every worker before joining any one of them.
+ foreach ($job in @($jobs)) { $job.client.Close() }
+ foreach ($job in @($jobs)) {
+ try { [void]$job.pipeline.EndInvoke($job.result) }
+ catch { [Console]::Error.WriteLine('Window identity worker failed during shutdown.') }
+ finally { $job.pipeline.Dispose() }
+ }
+ } finally {
+ try { $pool.Close() } finally { $pool.Dispose() }
}
}
diff --git a/scripts/session/relay-auth.ps1 b/scripts/session/relay-auth.ps1
index 7ed01a7..369473d 100644
--- a/scripts/session/relay-auth.ps1
+++ b/scripts/session/relay-auth.ps1
@@ -21,10 +21,10 @@ function Write-PiRelayFrame($Stream, $Clock, $Frame) {
$bytes = [Text.Encoding]::UTF8.GetBytes((ConvertTo-Json -InputObject $Frame -Compress) + "`n")
$Stream.Write($bytes, 0, $bytes.Length)
}
-function Get-PiRelayProof([byte[]]$Key, [string]$Side, [string]$Session, [string]$Channel, [string]$ServerNonce, [string]$ClientNonce) {
+function Get-PiRelayProof([byte[]]$Key, [string]$Side, [string]$Session, [string]$Channel, [string]$ServerNonce, [string]$ClientNonce, [string]$Role = 'session') {
$mac = [Security.Cryptography.HMACSHA256]::new($Key)
try {
- $transcript = ConvertTo-Json -InputObject @('pi-relay', 1, $Side, $Session, $Channel, 'session', $ServerNonce, $ClientNonce) -Compress
+ $transcript = ConvertTo-Json -InputObject @('pi-relay', 1, $Side, $Session, $Channel, $Role, $ServerNonce, $ClientNonce) -Compress
return (-join ($mac.ComputeHash([Text.Encoding]::UTF8.GetBytes($transcript)) | ForEach-Object { $_.ToString('x2') }))
} finally { $mac.Dispose() }
}
diff --git a/scripts/session/session-start.ps1 b/scripts/session/session-start.ps1
index 17ad10e..eba5905 100644
--- a/scripts/session/session-start.ps1
+++ b/scripts/session/session-start.ps1
@@ -1,14 +1,12 @@
-# Runs inside an isolated agent session (MXC isolation_session) from its shared workspace. Starts the CUA driver
-# with its loopback HTTP endpoint and the window identity bridge, then keeps spare connections dialled out to the
-# authenticated Node host relay, each piped to the owned local process. It runs until the session is stopped.
+# Runs in an isolated MXC user session. Driver traffic uses its owned local endpoint; each authenticated
+# identity reverse channel owns one marker peer over stdio, with no identity TCP listener.
param([Parameter(Mandatory)][string]$Workspace)
$ErrorActionPreference = 'Stop'
. (Join-Path $Workspace 'relay-auth.ps1')
+. (Join-Path $Workspace 'identity-channel.ps1')
$config = Get-Content -Raw (Join-Path $Workspace 'session.json') | ConvertFrom-Json
-# Isolated sessions share one loopback among themselves, so each takes free ports rather than fixed ones.
function Get-FreePort { $l = [Net.Sockets.TcpListener]::new([Net.IPAddress]::Loopback, 0); $l.Start(); $port = $l.LocalEndpoint.Port; $l.Stop(); $port }
$driverPort = Get-FreePort
-$identityPort = Get-FreePort
$env:CUA_DRIVER_RS_MCP_HTTP_PORT = [string]$driverPort
$env:CUA_DRIVER_RS_MCP_HTTP_TOKEN = $config.token
$env:CUA_DRIVER_RS_TELEMETRY_ENABLED = 'false'
@@ -17,40 +15,54 @@ $env:DO_NOT_TRACK = '1'
$env:CUA_DRIVER_ALLOW_DEBUGGING_LAUNCH = '1'
$out = Join-Path $Workspace 'out'
New-Item -ItemType Directory -Force $out | Out-Null
-# No cursor overlay: the session has no desktop compositor, so the overlay window would paint over every capture.
-# Named pipes are shared by all sessions, so each session's driver takes its own daemon pipe.
+# No compositor in this session: an overlay would paint over captures. The daemon pipe is private to this user.
$pipe = '\\.\pipe\cua-driver-' + $env:USERNAME
$driver = Start-Process -PassThru -FilePath (Join-Path $Workspace 'runtime\cua-driver.exe') -ArgumentList 'serve', '--no-overlay', '--socket', $pipe -WindowStyle Hidden `
-RedirectStandardOutput (Join-Path $out 'driver.out') -RedirectStandardError (Join-Path $out 'driver.err')
-$identity = Start-Process powershell.exe -PassThru -WindowStyle Hidden -ArgumentList ('-NoProfile -ExecutionPolicy Bypass -File "{0}" -Port {1} -Peer "{2}"' -f `
- (Join-Path $Workspace 'guest-identity-bridge.ps1'), $identityPort, (Join-Path $Workspace 'window-identity.ps1'))
-
-# Each channel maps a host session port to a local port inside this session.
-$channels = @(@{ host = $config.hostDriverPort; local = $driverPort; name = 'driver'; pid = $driver.Id },
- @{ host = $config.hostIdentityPort; local = $identityPort; name = 'identity'; pid = $identity.Id })
+$channels = @(@{ host = $config.hostDriverPort; name = 'driver' }, @{ host = $config.hostIdentityPort; name = 'identity' })
$pairs = [Collections.Generic.List[object]]::new()
-while ($true) {
- foreach ($channel in $channels) {
- # Two spare connections per channel; a used one is replaced as soon as it closes.
- while (@($pairs | Where-Object { $_.channel -eq $channel.host }).Count -lt 2) {
- $local = $null; $remote = $null
- try {
- # Authenticate the host before connecting or forwarding any local application bytes.
- $remote = Connect-PiRelay $channel.host $config.relay $channel.name
- $local = [Net.Sockets.TcpClient]::new('127.0.0.1', $channel.local)
- # A sibling can race Get-FreePort. Check the already-established connection's server process before forwarding.
- $owner = Get-NetTCPConnection -State Established -LocalAddress '127.0.0.1' -LocalPort $channel.local `
- -RemoteAddress '127.0.0.1' -RemotePort $local.Client.LocalEndPoint.Port -OwningProcess $channel.pid -ErrorAction SilentlyContinue
- if (-not $owner) { throw 'The local endpoint is not owned by this session worker.' }
- $a = $remote.GetStream(); $b = $local.GetStream()
- $pairs.Add([pscustomobject]@{ channel = $channel.host; h = $remote; l = $local; up = $a.CopyToAsync($b); down = $b.CopyToAsync($a) })
- } catch {
- if ($local) { $local.Close() }
- if ($remote) { $remote.Close() }
- break
+function Close-PiSessionPair($Pair) {
+ $Pair.h.Close()
+ if ($Pair.l) { $Pair.l.Close() }
+ if ($Pair.peer) { Stop-PiIdentityPeer $Pair.peer }
+ # Observe any failed copy tasks after closing their owned streams.
+ $null = $Pair.up.Exception; $null = $Pair.down.Exception
+}
+try {
+ while ($true) {
+ foreach ($channel in $channels) {
+ # Two spares per authenticated channel. Identity spares have no markers until the controller sends a request.
+ while (@($pairs | Where-Object { $_.channel -eq $channel.host }).Count -lt 2) {
+ $local = $null; $remote = $null; $peer = $null
+ try {
+ $remote = Connect-PiRelay $channel.host $config.relay $channel.name
+ $a = $remote.GetStream()
+ if ($channel.name -eq 'driver') {
+ $local = [Net.Sockets.TcpClient]::new('127.0.0.1', $driverPort)
+ $owner = Get-NetTCPConnection -State Established -LocalAddress '127.0.0.1' -LocalPort $driverPort `
+ -RemoteAddress '127.0.0.1' -RemotePort $local.Client.LocalEndPoint.Port -OwningProcess $driver.Id -ErrorAction SilentlyContinue
+ if (-not $owner) { throw 'The local endpoint is not owned by this session worker.' }
+ $b = $local.GetStream()
+ $up = $a.CopyToAsync($b); $down = $b.CopyToAsync($a)
+ } else {
+ $peer = Start-PiIdentityPeer (Join-Path $Workspace 'window-identity.ps1')
+ $up = [PiIdentityPipe]::CopyAndFlushAsync($a, $peer.StandardInput.BaseStream)
+ $down = $peer.StandardOutput.BaseStream.CopyToAsync($a)
+ }
+ $pairs.Add([pscustomobject]@{ channel = $channel.host; h = $remote; l = $local; peer = $peer; up = $up; down = $down })
+ } catch {
+ if ($remote) { $remote.Close() }
+ if ($local) { $local.Close() }
+ if ($peer) { Stop-PiIdentityPeer $peer }
+ break
+ }
}
}
+ foreach ($p in @($pairs)) {
+ if ($p.up.IsCompleted -or $p.down.IsCompleted) { Close-PiSessionPair $p; [void]$pairs.Remove($p) }
+ }
+ Start-Sleep -Milliseconds 50
}
- foreach ($p in @($pairs)) { if ($p.up.IsCompleted -or $p.down.IsCompleted) { $p.h.Close(); $p.l.Close(); [void]$pairs.Remove($p) } }
- Start-Sleep -Milliseconds 50
+} finally {
+ foreach ($p in @($pairs)) { Close-PiSessionPair $p }
}
diff --git a/src/config.ts b/src/config.ts
index c519b35..c2768d9 100644
--- a/src/config.ts
+++ b/src/config.ts
@@ -46,6 +46,8 @@ export interface GuestEndpoint {
identityPort: number;
/** Authenticates the reverse relay before driver/identity application bytes. Never read from user config. */
relay?: RelayCredentials;
+ /** A Sandbox identity service's own proof credentials; separate from HTTP driver authorization. */
+ identityAuth?: RelayCredentials;
/** Which kind of guest the driver runs in; a Windows Sandbox when omitted. */
domain?: "windows-sandbox" | "windows-session";
}
diff --git a/src/driver.ts b/src/driver.ts
index 2ab8380..2e4bb36 100644
--- a/src/driver.ts
+++ b/src/driver.ts
@@ -181,7 +181,7 @@ export class McpDriver implements Driver {
return !result.isError;
}, visualSettings);
this.visuals = this.presentation.flash;
- if (this.windowLifetime) this.windowIdentity = new WindowIdentity(config.endpoint ? remoteIdentityPeer(config.endpoint.identityPort, "127.0.0.1", config.endpoint.relay)
+ if (this.windowLifetime) this.windowIdentity = new WindowIdentity(config.endpoint ? remoteIdentityPeer(config.endpoint.identityPort, "127.0.0.1", config.endpoint.identityAuth ?? config.endpoint.relay)
: hostIdentityPeer(config.ssh ? sshRunner(config.ssh) : localRunner(config.interop ?? process.env.WSL_INTEROP)));
}
diff --git a/src/isolated-session.ts b/src/isolated-session.ts
index e7b3edb..409ff59 100644
--- a/src/isolated-session.ts
+++ b/src/isolated-session.ts
@@ -7,8 +7,7 @@ import type { SandboxHost } from "./sandbox.ts";
import type { SessionRelay } from "./session-relay.ts";
const SCRIPTS = new URL("../scripts/session/", import.meta.url);
-const SANDBOX_SCRIPTS = new URL("../scripts/sandbox/", import.meta.url);
-const IDENTITY_SCRIPT = new URL("../scripts/window-identity.ps1", import.meta.url);
+const COMMON_SCRIPTS = new URL("../scripts/", import.meta.url);
/** The session lives until it is closed; MXC still needs a process timeout for its exec. */
const EXEC_TIMEOUT_MS = 24 * 60 * 60 * 1000;
const NETWORK = { egress: { default: "allow" }, ingress: { default: "allow", hostLoopback: "allow" } };
@@ -83,8 +82,8 @@ export class IsolatedSession {
await this.ps(`Copy-Item -Recurse -Force -LiteralPath ${psString(runtime)} -Destination ${psString(`${workspace}\\runtime`)}`, signal, 120_000);
for (const name of ["session-start.ps1", "relay-auth.ps1"])
await this.host.writeFile(`${shared}/${name}`, await readFile(new URL(name, SCRIPTS), "utf8"));
- await this.host.writeFile(`${shared}/guest-identity-bridge.ps1`, await readFile(new URL("guest-identity-bridge.ps1", SANDBOX_SCRIPTS), "utf8"));
- await this.host.writeFile(`${shared}/window-identity.ps1`, await readFile(IDENTITY_SCRIPT, "utf8"));
+ for (const name of ["window-identity.ps1", "identity-channel.ps1", "identity-channel.cs"])
+ await this.host.writeFile(`${shared}/${name}`, await readFile(new URL(name, COMMON_SCRIPTS), "utf8"));
const keys = { session: this.ref, clientKey: randomBytes(32).toString("hex"), sessionKey: randomBytes(32).toString("hex") };
this.relay = await this.host.reverseRelay(this.workdir.unix, keys, signal);
const [driverClient, driverSession, identityClient, identitySession] = this.relay.ports;
diff --git a/src/sandbox.ts b/src/sandbox.ts
index 17e1a7e..374cd71 100644
--- a/src/sandbox.ts
+++ b/src/sandbox.ts
@@ -8,6 +8,7 @@ import { ComputerRequestError } from "./computer-resources.ts";
import { SSH_OPTIONS, powershellOf, runnerFiles, type CommandRunner } from "./runner.ts";
import { startSessionRelay } from "./session-relay-host.ts";
import type { SessionRelay, SessionRelayKeys } from "./session-relay.ts";
+import type { RelayCredentials } from "./relay-auth.ts";
/** Host-side commands for the sandbox lifecycle; replaced by a fake in tests. */
export interface SandboxHost {
@@ -37,7 +38,8 @@ const GUEST_ROOT = "C:\\pi";
const DRIVER_GUEST_PORT = 47800;
const IDENTITY_GUEST_PORT = 47802;
const SCRIPTS = new URL("../scripts/sandbox/", import.meta.url);
-const IDENTITY_SCRIPT = new URL("../scripts/window-identity.ps1", import.meta.url);
+const COMMON_SCRIPTS = new URL("../scripts/", import.meta.url);
+const RELAY_AUTH_SCRIPT = new URL("../scripts/session/relay-auth.ps1", import.meta.url);
const psString = (value: string) => `'${value.replace(/'/g, "''")}'`;
const xml = (value: string) => value.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;");
@@ -205,9 +207,13 @@ export class WindowsSandbox {
await this.host.mkdir(`${unix}/out`);
for (const name of ["guest-setup.ps1", "guest-start.ps1", "guest-identity-bridge.ps1", "host-relay.ps1"])
await this.host.writeFile(`${unix}/config/${name}`, await readFile(new URL(name, SCRIPTS), "utf8"));
- await this.host.writeFile(`${unix}/config/window-identity.ps1`, await readFile(IDENTITY_SCRIPT, "utf8"));
+ for (const name of ["window-identity.ps1", "identity-auth.ps1", "identity-channel.ps1", "identity-channel.cs"])
+ await this.host.writeFile(`${unix}/config/${name}`, await readFile(new URL(name, COMMON_SCRIPTS), "utf8"));
+ await this.host.writeFile(`${unix}/config/relay-auth.ps1`, await readFile(RELAY_AUTH_SCRIPT, "utf8"));
const token = randomBytes(32).toString("hex");
+ const identityAuth = { session: this.ref, key: randomBytes(32).toString("hex") };
await this.host.writeFile(`${unix}/config/token.txt`, token);
+ await this.host.writeFile(`${unix}/config/identity.json`, JSON.stringify(identityAuth));
await this.host.writeFile(`${unix}/sandbox.wsb`, sandboxConfig(runtime, `${windows}\\config`, `${windows}\\out`, shares));
// A WindowsSandboxServer started by wsb.exe or WindowsSandbox.exe from WSL/SSH fails; launch through the user's shell
@@ -249,10 +255,10 @@ throw 'The sandbox user session did not become available within 120 s.'`, signal
await this.ps(`${this.wsb(`exec --id ${this.id} --run-as System -c 'powershell.exe -NoProfile -ExecutionPolicy Bypass -File ${GUEST_ROOT}\\config\\guest-setup.ps1'`)} *> $null
${this.wsb(`exec --id ${this.id} --run-as ExistingLogin -c 'powershell.exe -NoProfile -ExecutionPolicy Bypass -File ${GUEST_ROOT}\\config\\guest-start.ps1'`)} *> $null
((${this.wsb(`ip --id ${this.id} --raw`)} | Out-String | ConvertFrom-Json).Networks | Select-Object -First 1).IpV4Address`, signal, 120_000)
- .then(ip => this.startRelays(ip.trim(), token, signal));
+ .then(ip => this.startRelays(ip.trim(), token, identityAuth, signal));
}
- private async startRelays(ip: string, token: string, signal?: AbortSignal): Promise<void> {
+ private async startRelays(ip: string, token: string, identityAuth: RelayCredentials, signal?: AbortSignal): Promise<void> {
if (!/^\d+\.\d+\.\d+\.\d+$/.test(ip)) throw new Error("The sandbox reported no IPv4 address.");
const { windows, unix } = this.workdir!;
const relay = async (guestPort: number): Promise<Relay> => {
@@ -270,8 +276,9 @@ ${this.wsb(`exec --id ${this.id} --run-as ExistingLogin -c 'powershell.exe -NoPr
this.relays.push(await relay(DRIVER_GUEST_PORT));
this.relays.push(await relay(IDENTITY_GUEST_PORT));
// Another machine's relays listen on its loopback; reach them through SSH tunnels.
- this.tunnels = [await this.host.forward(this.relays[0].port, signal), await this.host.forward(this.relays[1].port, signal)];
- this.endpoint = { url: `http://127.0.0.1:${this.tunnels[0].port}/mcp`, token, identityPort: this.tunnels[1].port };
+ this.tunnels.push(await this.host.forward(this.relays[0].port, signal));
+ this.tunnels.push(await this.host.forward(this.relays[1].port, signal));
+ this.endpoint = { url: `http://127.0.0.1:${this.tunnels[0].port}/mcp`, token, identityPort: this.tunnels[1].port, identityAuth };
}
/** Stop the sandbox, its relays and its host folder. Safe to call more than once. */