Skip to content

The agent that grows with you

fix(desktop): send Windows SSH PowerShell scripts without stdin

yoniebans1f8f96153679
diff --git a/apps/desktop/electron/windows-remote-inventory.test.ts b/apps/desktop/electron/windows-remote-inventory.test.ts
index a56b4b676c7..e5b90ced0e2 100644
--- a/apps/desktop/electron/windows-remote-inventory.test.ts
+++ b/apps/desktop/electron/windows-remote-inventory.test.ts
@@ -7,7 +7,7 @@ import path from 'node:path'
import { test } from 'vitest'
import { WINDOWS_PROFILE_LIST_PY, windowsInventoryScript } from './windows-remote-inventory'
-import { atomicWindowsSpawn, atomicWindowsSpawnCommand, encodedPowerShell, powerShellStdinCommand, probeWindowsFiles, probeWindowsRemote } from './windows-remote-lifecycle'
+import { atomicWindowsSpawn, atomicWindowsSpawnCommand, compressedPowerShellCommand, decodePowerShellCommand, encodedPowerShell, probeWindowsFiles, probeWindowsRemote } from './windows-remote-lifecycle'
import { WINDOWS_NO_REPARSE_PS, windowsHelperArgv, windowsRuntimeProgramArgv } from './windows-runtime-command'
const repo = path.resolve(import.meta.dirname, '../../..')
@@ -16,11 +16,8 @@ const runtime = { os: 'Windows', arch: 'AMD64', hermesHome: 'C:\\hermes', hermes
const bootstrap = "import os, sys, runpy; os.environ['HERMES_TEST_BOOT']='selected'; runpy.run_module('hermes_cli.main', run_name='__main__', alter_sys=True)"
const selected = { ...runtime, runtimeCommand: [python, '-I', '-c', bootstrap] }
-function streamed(command: string, options: { stdinData?: string } = {}) {
- const token = command.match(/-EncodedCommand\s+(\S+)$/)?.[1]
- const wrapper = token ? Buffer.from(token, 'base64').toString('utf16le') : ''
-
- return wrapper.includes('ReadToEnd') ? Buffer.from(String(options.stdinData || '').trim(), 'base64').toString('utf16le') : wrapper
+function streamed(command: string) {
+ return decodePowerShellCommand(command)
}
test('the canonical runtime prefix is actually executed, including bootstrap and Unicode arguments', () => {
@@ -53,8 +50,8 @@ test('injected Python program survives the observed PowerShell 5.1 double-quote
test('PATH bin launcher is resolved independently of its absent sibling Python, after the marker gate', async () => {
const calls: string[] = []
- const ssh = { exec: async (command: string, options: { stdinData?: string }) => {
- const script = streamed(command, options)
+ const ssh = { exec: async (command: string) => {
+ const script = streamed(command)
calls.push(script)
if (script.includes('Get-Command hermes -CommandType Application')) {
@@ -82,8 +79,8 @@ test('PATH bin launcher is resolved independently of its absent sibling Python,
test('held marker stops launcher imports and unrecognized runtime capabilities fail clearly', async () => {
let imported = false
- const blocked = { exec: async (command: string, options: { stdinData?: string }) => {
- const script = streamed(command, options)
+ const blocked = { exec: async (command: string) => {
+ const script = streamed(command)
if (script.includes('Get-Command hermes -CommandType Application')) {return JSON.stringify({ ...runtime, launcherPath: runtime.hermesPath })}
@@ -96,8 +93,8 @@ test('held marker stops launcher imports and unrecognized runtime capabilities f
await assert.rejects(() => probeWindowsRemote(blocked), (e: any) => e.kind === 'update-in-progress')
assert.equal(imported, false)
- const invalid = { exec: async (command: string, options: { stdinData?: string }) => {
- const script = streamed(command, options)
+ const invalid = { exec: async (command: string) => {
+ const script = streamed(command)
if (script.includes('Get-Command hermes -CommandType Application')) {return JSON.stringify({ ...runtime, launcherPath: runtime.hermesPath })}
@@ -113,9 +110,10 @@ test('atomic spawn streams its whole script and explicitly pipes Unicode caller
const payload = JSON.stringify({ ownershipId: 'a'.repeat(32), spawnNonce: 'b'.repeat(16), profile: 'bob', hermesPath: 'C:\\用户\\hermes.exe' })
let observed = ''
- const ssh = { exec: async (command: string, options: { stdinData?: string }) => {
- assert.ok(command.length < 1024)
- observed = streamed(command, options)
+ const ssh = { exec: async (command: string, options: { stdinData?: string } = {}) => {
+ assert.ok(command.length < 8191)
+ assert.equal(options.stdinData, undefined)
+ observed = streamed(command)
assert.match(observed, /\$OutputEncoding=\[Text.UTF8Encoding\]::new\(\$false\)/)
assert.ok(observed.includes(payload))
assert.match(observed, /' \| & .*windows_ssh_runtime.*spawn/)
@@ -134,8 +132,8 @@ test('Connect refuses an older helper before token upload or backend spawn on a
const { connectWindowsRemote } = await import('./windows-remote-lifecycle')
let writes = 0
- const ssh = { exec: async (command: string, options: { stdinData?: string }) => {
- const script = streamed(command, options)
+ const ssh = { exec: async (command: string) => {
+ const script = streamed(command)
if (script.includes('Get-Command hermes -CommandType Application')) {return JSON.stringify({ ...runtime, launcherPath: runtime.hermesPath })}
@@ -199,21 +197,22 @@ test('inventory programs guard ancestors, keep install-root anchoring and open i
assert.doesNotMatch(identity, /read_or_create_install_id|WriteAllText|CreateDirectory/)
})
-test.runIf(Boolean(process.env.HERMES_TEST_PWSH))('real local PowerShell bootstrap preserves Unicode and pipes JSON after script stdin is consumed', () => {
+test.runIf(Boolean(process.env.HERMES_TEST_PWSH))('real local PowerShell runs a long compressed script, preserving Unicode and piped JSON', () => {
const pwsh = String(process.env.HERMES_TEST_PWSH)
const payload = JSON.stringify({ marker: '用户/한글', length: 12000 })
const script = `$OutputEncoding=[Text.UTF8Encoding]::new($false);${"# padding\r\n".repeat(1500)}'${payload}' | & '${python}' -c 'import json,sys; print(json.dumps(json.load(sys.stdin),ensure_ascii=False))'`
- const token = powerShellStdinCommand().split(' ').at(-1)!
+ const command = compressedPowerShellCommand(script)
+ assert.ok(command.length < 8191)
- const result = spawnSync(pwsh, ['-NoProfile', '-NonInteractive', '-EncodedCommand', token], {
- input: encodedPowerShell(script), encoding: 'utf8', timeout: 20000
+ const result = spawnSync(pwsh, ['-NoProfile', '-NonInteractive', '-EncodedCommand', command.split(' ').at(-1)!], {
+ encoding: 'utf8', timeout: 20000
})
assert.equal(result.status, 0, result.stderr)
assert.deepEqual(JSON.parse(result.stdout.trim()), JSON.parse(payload))
})
-test.runIf(Boolean(process.env.HERMES_TEST_PWSH))('real outer PowerShell rejects the old Invoke wrapper and accepts the encoded bootstrap', () => {
+test.runIf(Boolean(process.env.HERMES_TEST_PWSH))('real outer PowerShell rejects the old Invoke wrapper and accepts the compressed command', () => {
const pwsh = String(process.env.HERMES_TEST_PWSH)
const tools = fs.mkdtempSync(path.join(os.tmpdir(), 'hermes-outer-powershell-'))
const marker = 'HERMES_LOCAL_OUTER_SHELL_OK_用户'
@@ -227,7 +226,7 @@ test.runIf(Boolean(process.env.HERMES_TEST_PWSH))('real outer PowerShell rejects
})
const red = run(old)
- const green = run(powerShellStdinCommand())
+ const green = run(compressedPowerShellCommand(`Write-Output '${marker}'`))
assert.notEqual(red.status, 0)
assert.match(red.stderr, /Invoke/)
@@ -242,8 +241,8 @@ test.runIf(Boolean(process.env.HERMES_TEST_PWSH))('real PowerShell parser accept
const pwsh = String(process.env.HERMES_TEST_PWSH)
const scripts = [windowsInventoryScript(runtime, 'profiles'), windowsInventoryScript(runtime, 'install-id')]
scripts.push(streamed(atomicWindowsSpawnCommand(runtime)))
- await probeWindowsFiles({ exec: async (command: string, options: { stdinData?: string }) => {
- scripts.push(streamed(command, options))
+ await probeWindowsFiles({ exec: async (command: string) => {
+ scripts.push(streamed(command))
return JSON.stringify(runtime)
} })
@@ -252,12 +251,18 @@ test.runIf(Boolean(process.env.HERMES_TEST_PWSH))('real PowerShell parser accept
assert.ok(compile)
const program = `$errorsFound=@();foreach($b in @(${list})){$text=[Text.Encoding]::Unicode.GetString([Convert]::FromBase64String($b));$tokens=$null;$parseErrors=$null;[Management.Automation.Language.Parser]::ParseInput($text,[ref]$tokens,[ref]$parseErrors)|Out-Null;$errorsFound+=@($parseErrors)};${compile};if($errorsFound.Count){$errorsFound|ForEach-Object {$_.Message};exit 1};'HERMES_PS_PROGRAMS_PARSE_OK'`
- const result = spawnSync(pwsh, ['-NoProfile', '-NonInteractive', '-EncodedCommand', powerShellStdinCommand().split(' ').at(-1)!], {
- input: encodedPowerShell(program), encoding: 'utf8', timeout: 20000
- })
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'hermes-ps-parse-'))
+ const file = path.join(dir, 'parse.ps1')
+ fs.writeFileSync(file, `\uFEFF${program}`, 'utf8')
+
+ try {
+ const result = spawnSync(pwsh, ['-NoProfile', '-NonInteractive', '-ExecutionPolicy', 'Bypass', '-File', file], { encoding: 'utf8', timeout: 20000 })
- assert.equal(result.status, 0, result.stderr + result.stdout)
- assert.equal(result.stdout.trim(), 'HERMES_PS_PROGRAMS_PARSE_OK')
+ assert.equal(result.status, 0, result.stderr + result.stdout)
+ assert.equal(result.stdout.trim(), 'HERMES_PS_PROGRAMS_PARSE_OK')
+ } finally {
+ fs.rmSync(dir, { recursive: true, force: true })
+ }
})
test.runIf(Boolean(process.env.HERMES_TEST_PWSH))('no-reparse guard checks a leaf file and every ancestor, not FileInfo.Parent', () => {
diff --git a/apps/desktop/electron/windows-remote-inventory.ts b/apps/desktop/electron/windows-remote-inventory.ts
index 32a39c1a1b2..43eef8c2299 100644
--- a/apps/desktop/electron/windows-remote-inventory.ts
+++ b/apps/desktop/electron/windows-remote-inventory.ts
@@ -1,5 +1,5 @@
import { parseRemoteProfileListing } from './connection-registry'
-import { assertWindowsRemoteInstallUpdateClear, encodedPowerShell, powerShellStdinCommand, psLiteral, stripPowerShellNoise } from './windows-remote-lifecycle'
+import { assertWindowsRemoteInstallUpdateClear, compressedPowerShellCommand, psLiteral, stripPowerShellNoise } from './windows-remote-lifecycle'
import { WINDOWS_NO_REPARSE_PS, type WindowsRuntime, windowsRuntimeProgramArgv } from './windows-runtime-command'
// Use the canonical identity/tombstone predicate without list_profile_names' OSError suppression.
@@ -79,9 +79,7 @@ export function windowsInventoryScript(runtime: WindowsRuntime, operation: 'inst
async function readInventory(ssh: any, runtime: WindowsRuntime, operation: 'install-id' | 'profiles'): Promise<any> {
await assertWindowsRemoteInstallUpdateClear(ssh, runtime.hermesHome, runtime.python)
- const output = await ssh.exec(powerShellStdinCommand(), {
- stdinData: `${encodedPowerShell(windowsInventoryScript(runtime, operation))}\r\n`
- })
+ const output = await ssh.exec(compressedPowerShellCommand(windowsInventoryScript(runtime, operation)))
const parsed = JSON.parse(stripPowerShellNoise(output).pop() || 'null')
diff --git a/apps/desktop/electron/windows-remote-lifecycle.test.ts b/apps/desktop/electron/windows-remote-lifecycle.test.ts
index 1d960179b95..4ceed67f4bc 100644
--- a/apps/desktop/electron/windows-remote-lifecycle.test.ts
+++ b/apps/desktop/electron/windows-remote-lifecycle.test.ts
@@ -14,6 +14,7 @@ import {
atomicWindowsSpawnCommand,
buildWindowsInteractiveCommand,
connectWindowsRemote,
+ decodePowerShellCommand,
detectRemotePlatform,
encodedPowerShell,
helper,
@@ -35,8 +36,7 @@ test('Windows spawn holds the update mutex across marker check and helper spawn'
python: 'C:\\Users\\andre\\.hermes\\python.exe'
})
- const encoded = command.match(/-EncodedCommand\s+([^\s]+)$/)?.[1]
- const script = encoded ? Buffer.from(encoded, 'base64').toString('utf16le') : ''
+ const script = decodePowerShellCommand(command)
assert.match(script, /\.hermes-update-in-progress/)
assert.match(
script,
@@ -62,8 +62,7 @@ test('Windows spawn publishes the initial ownership record before releasing the
}
)
- const encoded = command.split(' ').at(-1) || ''
- const script = encoded ? Buffer.from(encoded, 'base64').toString('utf16le') : ''
+ const script = decodePowerShellCommand(command)
assert.match(script, /read-lock/)
assert.match(script, /write-lock/)
@@ -135,12 +134,10 @@ function sshWith(exec) {
type SshExecOptions = { stdinData?: string | Buffer }
function scriptFromInvocation(command: string, options: SshExecOptions = {}) {
- const encoded = command.match(/-EncodedCommand\s+([^\s]+)$/)?.[1]
+ const decoded = decodePowerShellCommand(command)
- if (encoded) {
- const script = Buffer.from(encoded, 'base64').toString('utf16le')
-
- if (!script.includes('[Console]::In.ReadToEnd()') || options.stdinData == null) {return script}
+ if (decoded) {
+ return decoded
}
return Buffer.from(String(options.stdinData || '').trim(), 'base64').toString('utf16le')
@@ -465,14 +462,16 @@ test('helper parsing ignores CLIXML progress blocks around its JSON line', async
}
})
-test('Windows platform probe streams long PowerShell scripts over stdin', async () => {
- let command = ''
- let stdinData = ''
+test('Windows platform probe and marker gate send their scripts without stdin', async () => {
+ let probeCommand = ''
+ let probeStdinData: string | Buffer | undefined
+ let markerCommand = ''
+ let markerStdinData: string | Buffer | undefined
const result = await probeWindowsRemote({
async exec(nextCommand: string, options: SshExecOptions = {}) {
- command = nextCommand
- stdinData = String(options.stdinData || '')
+ probeCommand = nextCommand
+ probeStdinData = options.stdinData
return JSON.stringify({
os: 'Windows',
@@ -484,22 +483,36 @@ test('Windows platform probe streams long PowerShell scripts over stdin', async
}
})
+ await assertWindowsRemoteInstallUpdateClear(
+ {
+ async exec(nextCommand: string, options: SshExecOptions = {}) {
+ markerCommand = nextCommand
+ markerStdinData = options.stdinData
+
+ return 'CLEAR'
+ }
+ },
+ 'C:\\\\h',
+ 'C:\\\\h\\\\python.exe'
+ )
+
assert.equal(result.os, 'Windows')
- assert.match(command, /-EncodedCommand [A-Za-z0-9+/=]+$/)
- assert.doesNotMatch(command, /-Command /)
- assert.ok(command.length < 1024)
- assert.match(stdinData, /^[A-Za-z0-9+/=\r\n]+$/)
- const decodedScript = Buffer.from(stdinData.trim(), 'base64').toString('utf16le')
- assert.match(decodedScript, /Assert-NoReparse/)
+ assert.equal(probeStdinData, undefined)
+ assert.equal(markerStdinData, undefined)
+ assert.match(probeCommand, /-EncodedCommand [A-Za-z0-9+/=]+$/)
+ assert.match(markerCommand, /-EncodedCommand [A-Za-z0-9+/=]+$/)
+ assert.doesNotMatch(probeCommand, /-Command /)
+ assert.match(decodePowerShellCommand(probeCommand), /Assert-NoReparse/)
+ assert.match(decodePowerShellCommand(markerCommand), /HermesMarkerNoFollow/)
})
-test('Windows platform probe preserves Unicode paths in its UTF-16LE stdin payload', async () => {
- let stdinData = ''
+test('Windows platform probe preserves Unicode paths in its compressed command', async () => {
+ let command = ''
await probeWindowsRemote(
{
- async exec(_command: string, options: SshExecOptions = {}) {
- stdinData = String(options.stdinData || '')
+ async exec(nextCommand: string) {
+ command = nextCommand
return JSON.stringify({
os: 'Windows',
@@ -513,16 +526,15 @@ test('Windows platform probe preserves Unicode paths in its UTF-16LE stdin paylo
'C:\\Users\\한글\\hermes.exe'
)
- const decodedScript = Buffer.from(stdinData.trim(), 'base64').toString('utf16le')
- assert.ok(decodedScript.includes('C:\\Users\\한글\\hermes.exe'))
+ assert.ok(decodePowerShellCommand(command).includes('C:\\Users\\한글\\hermes.exe'))
})
-test('every Windows probe command fits the cmd.exe 8191-char limit (#106716)', async () => {
+test('every Windows remote command fits the cmd.exe 8191-char limit (#106716)', async () => {
// cmd.exe (the default OpenSSH shell on Windows) rejects command lines of
// 8192+ chars with "The command line is too long", which used to surface as
// a misleading unsupported-platform error. Every command the Windows remote
- // lifecycle sends must stay under that limit; long probe scripts travel
- // over stdin instead.
+ // lifecycle sends must stay under that limit without streaming scripts over
+ // stdin.
const commands: string[] = []
const ssh = sshWith(async (command, options) => {
@@ -549,18 +561,36 @@ test('every Windows probe command fits the cmd.exe 8191-char limit (#106716)', a
const longExplicit = `C:\\${'h'.repeat(200)}\\hermes.exe`
await probeWindowsRemote(ssh, longExplicit)
- await assertWindowsRemoteInstallUpdateClear(ssh, longHome)
+ await assertWindowsRemoteInstallUpdateClear(ssh, longHome, `${longHome}\\python.exe`)
commands.push(
+ atomicWindowsSpawnCommand(
+ { hermesHome: longHome, python: `${longHome}\\python.exe` },
+ {
+ ownershipId: 'f'.repeat(32),
+ spawnNonce: '0123456789abcdef',
+ profile: 'p'.repeat(64),
+ hermesPath: longExplicit,
+ hermesHome: longHome,
+ tokenFingerprint: 'a'.repeat(32),
+ startedAt: '2026-07-14T00:00:00.000Z'
+ },
+ JSON.stringify({
+ ownershipId: 'f'.repeat(32),
+ spawnNonce: '0123456789abcdef',
+ profile: 'p'.repeat(64),
+ hermesPath: longExplicit
+ })
+ ),
helperCommand({ python: `${longHome}\\python.exe` }, 'inspect', [longExplicit]),
buildWindowsInteractiveCommand(longHome)
)
- assert.ok(commands.length >= 4)
+ assert.ok(commands.length >= 5)
for (const command of commands) {
assert.ok(
command.length < 8191,
- `probe command is ${command.length} chars (limit 8191): ${command.slice(0, 80)}...`
+ `Windows command is ${command.length} chars (limit 8191): ${command.slice(0, 80)}...`
)
}
})
@@ -613,6 +643,51 @@ test.skipIf(process.platform !== 'win32')('Windows platform probe executes in re
}
})
+test.skipIf(process.platform !== 'win32')(
+ 'Windows marker gate finishes in real PowerShell when end of input never arrives',
+ async () => {
+ // Windows OpenSSH does not always deliver the client's end of input to the remote PowerShell.
+ const runWithOpenStdin = (command: string, stdinData?: string | Buffer) =>
+ new Promise<string>((resolve, reject) => {
+ const child = spawn('cmd.exe', ['/d', '/s', '/c', command], { windowsHide: true })
+ const stdout: Buffer[] = []
+
+ const timer = setTimeout(() => {
+ spawn('taskkill', ['/T', '/F', '/PID', String(child.pid)], { windowsHide: true })
+ reject(new Error('remote script was still waiting after 20 s'))
+ }, 20_000)
+
+ child.stdout.on('data', chunk => stdout.push(chunk))
+ child.once('error', reject)
+ child.once('close', code => {
+ clearTimeout(timer)
+
+ if (code === 0) {
+ resolve(Buffer.concat(stdout).toString('utf8'))
+ } else {
+ reject(new Error(`command exited with ${code}`))
+ }
+ })
+
+ if (stdinData != null) {
+ child.stdin.write(stdinData)
+ }
+ })
+
+ const home = fs.mkdtempSync(path.join(os.tmpdir(), 'hermes-marker-'))
+
+ try {
+ await assertWindowsRemoteInstallUpdateClear(
+ { exec: (command: string, options: SshExecOptions = {}) => runWithOpenStdin(command, options.stdinData) },
+ home
+ )
+ } finally {
+ fs.rmSync(home, { recursive: true, force: true })
+ }
+ },
+ 30_000
+)
+
test('platform detection preserves POSIX and falls back to Windows PowerShell', async () => {
assert.deepEqual(await detectRemotePlatform(sshWith(async () => 'Linux\nx86_64\n')), { os: 'Linux', arch: 'x86_64' })
const calls: string[] = []
diff --git a/apps/desktop/electron/windows-remote-lifecycle.ts b/apps/desktop/electron/windows-remote-lifecycle.ts
index fca9dca40ec..0c97f3c5e48 100644
--- a/apps/desktop/electron/windows-remote-lifecycle.ts
+++ b/apps/desktop/electron/windows-remote-lifecycle.ts
@@ -1,4 +1,5 @@
import crypto from 'node:crypto'
+import zlib from 'node:zlib'
import { resolveReadyTimeoutMs } from './remote-lifecycle'
import { WINDOWS_CHECKOUT_LOCK_PS, WINDOWS_MARKER_JUDGE_PS } from './remote-update-marker-programs'
@@ -37,12 +38,73 @@ function stripPowerShellNoise(stdout) {
.filter(line => line.trim() && !line.trimStart().startsWith('#< CLIXML'))
}
-// A bare -Command expression is evaluated by an outer PowerShell SSH shell.
-// Encode only the bootstrap; long Unicode payloads still travel on stdin.
-function powerShellStdinCommand() {
- return powerShellCommand(
- '[Console]::OutputEncoding=[Text.UTF8Encoding]::new($false);$payload=[Console]::In.ReadToEnd();$script=[Text.Encoding]::Unicode.GetString([Convert]::FromBase64String($payload));& ([scriptblock]::Create($script))'
- )
+// Long scripts travel inside a self-contained -EncodedCommand, never on stdin:
+// Windows OpenSSH does not reliably deliver a stdin payload and its end of input
+// to the remote PowerShell, which then blocks past the exec timeout and outlives
+// the session. Deflate keeps the command under cmd.exe's 8191-char limit; the
+// bytes are packed 15 bits per BMP character, skipping U+2000..U+20FF, where
+// PowerShell reads U+2018..U+201B as single quotes.
+function compressedPowerShellBootstrap(script) {
+ const deflated = zlib.deflateRawSync(Buffer.from(script, 'utf8'), { level: 9 })
+ let chars = ''
+ let bitBuf = 0
+ let bitCount = 0
+
+ for (const byte of deflated) {
+ bitBuf |= byte << bitCount
+ bitCount += 8
+
+ while (bitCount >= 15) {
+ const value = bitBuf & 0x7fff
+ chars += String.fromCharCode((value < 0x1f00 ? 0x0100 : 0x0200) + value)
+ bitBuf >>>= 15
+ bitCount -= 15
+ }
+ }
+
+ if (bitCount > 0) {
+ const value = bitBuf & 0x7fff
+ chars += String.fromCharCode((value < 0x1f00 ? 0x0100 : 0x0200) + value)
+ }
+
+ return `$ProgressPreference="SilentlyContinue";[Console]::OutputEncoding=[Text.UTF8Encoding]::new($false);$m=[IO.MemoryStream]::new();$b=0;$n=0;foreach($c in [char[]]'${chars}'){$v=[int]$c;$v-=if($v-lt8192){256}else{512};$b=$b-bor($v-shl$n);$n+=15;while($n-ge8){$m.WriteByte($b-band255);$b=$b-shr8;$n-=8}};$m.Position=0;& ([ScriptBlock]::Create([IO.StreamReader]::new([IO.Compression.DeflateStream]::new($m,[IO.Compression.CompressionMode]::Decompress),[Text.Encoding]::UTF8).ReadToEnd()))`
+}
+
+function compressedPowerShellCommand(script) {
+ return powerShellCommand(compressedPowerShellBootstrap(script))
+}
+
+function decodePowerShellCommand(command) {
+ const encoded = String(command || '').match(/-EncodedCommand\s+([^\s]+)$/)?.[1]
+
+ if (!encoded) {
+ return ''
+ }
+
+ const outer = Buffer.from(encoded, 'base64').toString('utf16le')
+ const packed = outer.match(/foreach\(\$c in \[char\[\]\]'([^']+)'\)\{\$v=\[int\]\$c;/)?.[1]
+
+ if (!packed) {
+ return outer
+ }
+
+ const deflated: number[] = []
+ let bitBuf = 0
+ let bitCount = 0
+
+ for (let index = 0; index < packed.length; index += 1) {
+ const code = packed.charCodeAt(index)
+ bitBuf |= (code - (code < 0x2000 ? 0x0100 : 0x0200)) << bitCount
+ bitCount += 15
+
+ while (bitCount >= 8) {
+ deflated.push(bitBuf & 0xff)
+ bitBuf >>>= 8
+ bitCount -= 8
+ }
+ }
+
+ return zlib.inflateRawSync(Buffer.from(deflated)).toString('utf8')
}
async function probeWindowsFiles(ssh, explicitHermesPath = '') {
@@ -106,9 +168,7 @@ async function probeWindowsFiles(ssh, explicitHermesPath = '') {
// probe parses, ahead of, after, or on the same line as the probe JSON
// (module auto-load racing the exec read). stripPowerShellNoise drops every
// block; the JSON is the last meaningful line.
- const lines = stripPowerShellNoise(
- await ssh.exec(powerShellStdinCommand(), { stdinData: `${encodedPowerShell(script)}\r\n` })
- )
+ const lines = stripPowerShellNoise(await ssh.exec(compressedPowerShellCommand(script)))
const parsed = JSON.parse(lines[lines.length - 1] || 'null')
@@ -152,7 +212,7 @@ async function resolveWindowsLauncher(ssh: any, runtime: any) {
let resolved
try {
- const output = await ssh.exec(powerShellStdinCommand(), { stdinData: `${encodedPowerShell(script)}\r\n` })
+ const output = await ssh.exec(compressedPowerShellCommand(script))
resolved = JSON.parse(stripPowerShellNoise(output).pop() || 'null')
if (!Array.isArray(resolved?.runtimeCommand) || !resolved.runtimeCommand.every(part => typeof part === 'string' && !part.includes('\0')) || typeof resolved.python !== 'string' || !/^[a-z]:[\\/]/i.test(resolved.python)) {
@@ -242,13 +302,6 @@ public static class HermesMarkerNoFollow {
return script
}
-// The marker probe rides the same stdin transport as the platform probe
-// (powerShellStdinCommand): its script, with the C# no-follow reader, is far
-// over cmd.exe's 8191-char command-line limit.
-function windowsUpdateMarkerProbeStdinData(hermesHome, python = '') {
- return `${encodedPowerShell(windowsUpdateMarkerProbeScript(hermesHome, python))}\r\n`
-}
-
/**
* Fail-closed install marker gate for a fresh/relaunched Desktop process.
* This uses only PowerShell/.NET and therefore never imports the remote
@@ -263,9 +316,7 @@ async function assertWindowsRemoteInstallUpdateClear(ssh, hermesHome, python = '
// CLEAR gate into a fail-closed 'update-in-progress' verdict.
observation =
stripPowerShellNoise(
- await ssh.exec(powerShellStdinCommand(), {
- stdinData: windowsUpdateMarkerProbeStdinData(hermesHome, python)
- })
+ await ssh.exec(compressedPowerShellCommand(windowsUpdateMarkerProbeScript(hermesHome, python)))
).pop() || ''
} catch (cause) {
const error: any = new Error('Could not prove that the remote Hermes install is clear for SSH startup.')
@@ -430,12 +481,11 @@ function atomicWindowsSpawnCommand(runtime, reservation: any = {}, payload?: str
.filter(line => line !== '')
.join(';')
- return powerShellCommand(script)
+ return compressedPowerShellCommand(script)
}
-async function atomicWindowsSpawn(ssh, runtime, stdinData, reservation: any = {}) {
- const encoded = atomicWindowsSpawnCommand(runtime, reservation, stdinData).split(' ').at(-1)
- const output = await ssh.exec(powerShellStdinCommand(), { stdinData: `${encoded}\r\n` })
+async function atomicWindowsSpawn(ssh, runtime, payload, reservation: any = {}) {
+ const output = await ssh.exec(atomicWindowsSpawnCommand(runtime, reservation, payload))
const lines = stripPowerShellNoise(output)
@@ -924,13 +974,14 @@ export {
atomicWindowsSpawn,
atomicWindowsSpawnCommand,
buildWindowsInteractiveCommand,
+ compressedPowerShellCommand,
connectWindowsRemote,
+ decodePowerShellCommand,
detectRemotePlatform,
encodedPowerShell,
helper,
helperCommand,
powerShellCommand,
- powerShellStdinCommand,
probeWindowsFiles,
probeWindowsRemote,
psLiteral,
diff --git a/apps/desktop/electron/windows-ssh-repair.test.ts b/apps/desktop/electron/windows-ssh-repair.test.ts
index e644e943dda..0c74c98ff59 100644
--- a/apps/desktop/electron/windows-ssh-repair.test.ts
+++ b/apps/desktop/electron/windows-ssh-repair.test.ts
@@ -7,7 +7,7 @@ import path from 'node:path'
import { test } from 'vitest'
import { listRemoteHermesProfiles, readRemoteInstallId } from './remote-lifecycle'
-import { assertWindowsRemoteInstallUpdateClear, connectWindowsRemote, probeWindowsFiles, probeWindowsRemote, windowsHelperOwnsRuntime } from './windows-remote-lifecycle'
+import { assertWindowsRemoteInstallUpdateClear, connectWindowsRemote, decodePowerShellCommand, probeWindowsFiles, probeWindowsRemote, windowsHelperOwnsRuntime } from './windows-remote-lifecycle'
const runtime = {
os: 'Windows', arch: 'AMD64', hermesHome: 'C:\\Users\\A\\AppData\\Local\\hermes',
@@ -16,16 +16,15 @@ const runtime = {
}
function decode(command: string) {
- const token = command.match(/-EncodedCommand\s+(\S+)$/)?.[1]
- assert.ok(token, 'outer shells must receive the bootstrap as one encoded argument')
+ assert.match(command, /-EncodedCommand\s+\S+$/, 'outer shells must receive the script as one encoded argument')
- return Buffer.from(token, 'base64').toString('utf16le')
+ return decodePowerShellCommand(command)
}
-test('platform and marker bootstrap survive outer-shell parsing without inlining long payloads', async () => {
+test('platform and marker scripts survive outer-shell parsing as one compressed argument without stdin', async () => {
const calls: Array<{ command: string; options: { stdinData?: string } }> = []
- const ssh = { exec: async (command: string, options: { stdinData?: string }) => {
+ const ssh = { exec: async (command: string, options: { stdinData?: string } = {}) => {
calls.push({ command, options })
return calls.length === 1 ? JSON.stringify(runtime) : 'CLEAR'
@@ -35,22 +34,21 @@ test('platform and marker bootstrap survive outer-shell parsing without inlining
await assertWindowsRemoteInstallUpdateClear(ssh, runtime.hermesHome, runtime.python)
for (const { command, options } of calls) {
- const wrapper = decode(command)
- assert.match(wrapper, /ReadToEnd/)
- assert.match(wrapper, /FromBase64String/)
+ const outer = Buffer.from(command.split(' ').at(-1)!, 'base64').toString('utf16le')
+ assert.match(outer, /DeflateStream/)
assert.ok(command.length < 8191)
- const script = Buffer.from(String(options.stdinData).trim(), 'base64').toString('utf16le')
- assert.ok(script.length > wrapper.length)
+ assert.equal(options.stdinData, undefined)
+ assert.ok(decode(command).length > outer.length)
}
})
test('Windows roster and install id never dispatch POSIX syntax or hide a failed read', async () => {
const calls: string[] = []
- const ssh = { exec: async (command: string, options: { stdinData?: string }) => {
+ const ssh = { exec: async (command: string) => {
calls.push(command)
assert.doesNotMatch(command, /^echo|^if \[/)
- const script = Buffer.from(String(options?.stdinData ?? '').trim(), 'base64').toString('utf16le') || decode(command)
+ const script = decode(command)
if (script.includes('.hermes-update-in-progress')) {return 'CLEAR'}
@@ -65,8 +63,8 @@ test('Windows roster and install id never dispatch POSIX syntax or hide a failed
})
test('Windows inventory rejects malformed helper output instead of fabricating default', async () => {
- const ssh = { exec: async (_command: string, options: { stdinData?: string }) => {
- const script = Buffer.from(String(options?.stdinData ?? '').trim(), 'base64').toString('utf16le')
+ const ssh = { exec: async (command: string) => {
+ const script = decodePowerShellCommand(command)
return script.includes('.hermes-update-in-progress') ? 'CLEAR' : '{}'
} }
@@ -77,8 +75,8 @@ test('Windows inventory rejects malformed helper output instead of fabricating d
test('a bin launcher does not require a nonexistent sibling Python and resolves after the update gate', async () => {
const bootstrap = "import os, sys, runpy; runpy.run_module('hermes_cli.main', run_name='__main__', alter_sys=True)"
- const ssh = { exec: async (command: string, options: { stdinData?: string }) => {
- const script = Buffer.from(String(options?.stdinData || '').trim(), 'base64').toString('utf16le')
+ const ssh = { exec: async (command: string) => {
+ const script = decodePowerShellCommand(command)
if (script.includes('Get-Command hermes -CommandType Application')) {return JSON.stringify({ ...runtime, python: '', launcherPath: runtime.hermesPath })}
@@ -97,16 +95,14 @@ test('the complete connect path keeps atomic spawn off argv and delivers the exp
let spawned = false
const ssh = { exec: async (command: string, options: { stdinData?: string } = {}) => {
- const token = command.match(/-EncodedCommand\s+(\S+)$/)?.[1]
- let script = token ? Buffer.from(token, 'base64').toString('utf16le') : ''
-
- if (!token || script.includes('ReadToEnd')) {script = Buffer.from(String(options.stdinData || '').trim(), 'base64').toString('utf16le')}
+ const script = decodePowerShellCommand(command) || ''
if (script.includes('Get-Command hermes -CommandType Application')) {return JSON.stringify(runtime)}
if (script.includes("'spawn'")) {
- assert.ok(command.length < 8191, 'Connect must not inline its atomic spawn script')
- assert.ok(script.includes('"profile":"bob"'), 'script stdin cannot also serve as helper JSON stdin')
+ assert.ok(command.length < 8191, "Connect's atomic spawn command must fit cmd.exe's limit")
+ assert.equal(options.stdinData, undefined)
+ assert.ok(script.includes('"profile":"bob"'), 'the caller JSON travels inside the spawn script')
assert.match(script, /' \| & /)
spawned = true