Skip to content

The agent that grows with you

fix(desktop): repair Windows SSH transport runtime and read-only inventory

Luo, Yiliang6d115946863f
diff --git a/apps/desktop/electron/main.ts b/apps/desktop/electron/main.ts
index 70a245b235c..9a804ec04d3 100644
--- a/apps/desktop/electron/main.ts
+++ b/apps/desktop/electron/main.ts
@@ -14909,7 +14909,8 @@ async function probeSshProfileInventory(connection) {
try {
await ssh.open()
- const profiles = await remoteLifecycle.listRemoteHermesProfiles(ssh)
+ const platform = await detectRemotePlatform(ssh, sshConfig.remoteHermesPath || '')
+ const profiles = await remoteLifecycle.listRemoteHermesProfiles(ssh, platform)
if (profiles.length > 0) {
sshRosterCache.set(connection.id, profiles)
@@ -14919,7 +14920,7 @@ async function probeSshProfileInventory(connection) {
// install id at all, so two addresses for one machine never collapse into one roster row
// (#88828 wired this for remote/local only, through /api/status).
connectionInstallIds.set(connection.id, {
- id: await remoteLifecycle.readRemoteInstallId(ssh),
+ id: await remoteLifecycle.readRemoteInstallId(ssh, platform),
ts: Date.now()
})
} catch (error: any) {
diff --git a/apps/desktop/electron/remote-lifecycle.ts b/apps/desktop/electron/remote-lifecycle.ts
index 5ec95d2ad47..cb6aa9765ab 100644
--- a/apps/desktop/electron/remote-lifecycle.ts
+++ b/apps/desktop/electron/remote-lifecycle.ts
@@ -379,7 +379,13 @@ async function assertRemoteInstallUpdateClear(ssh, hermesHome, hermesPath = '')
throw error
}
-async function listRemoteHermesProfiles(ssh) {
+async function listRemoteHermesProfiles(ssh, platform: any = null) {
+ if (platform?.os === 'Windows') {
+ const { listWindowsRemoteProfiles } = await import('./windows-remote-inventory')
+
+ return listWindowsRemoteProfiles(ssh, platform)
+ }
+
const home = assertSafeRemoteHome(await probeRemoteHermesHome(ssh))
const dir = expandRemotePath(`${home}/profiles`)
let listing = ''
@@ -396,7 +402,13 @@ async function listRemoteHermesProfiles(ssh) {
return parseRemoteProfileListing(listing)
}
-async function readRemoteInstallId(ssh) {
+async function readRemoteInstallId(ssh, platform: any = null) {
+ if (platform?.os === 'Windows') {
+ const { readWindowsRemoteInstallId } = await import('./windows-remote-inventory')
+
+ return readWindowsRemoteInstallId(ssh, platform)
+ }
+
// The stable backend identity the roster collapses on (`hermes_cli/install_identity.py`:
// `<install root>/install_id`, opaque hex). Read from the INSTALL root, so an ssh connection
// pinned to `<root>/profiles/<name>` reports the same id as one pointed at the root — they are
diff --git a/apps/desktop/electron/windows-remote-inventory.test.ts b/apps/desktop/electron/windows-remote-inventory.test.ts
new file mode 100644
index 00000000000..0ca2acf9353
--- /dev/null
+++ b/apps/desktop/electron/windows-remote-inventory.test.ts
@@ -0,0 +1,245 @@
+import assert from 'node:assert/strict'
+import { spawnSync } from 'node:child_process'
+import fs from 'node:fs'
+import os from 'node:os'
+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 { windowsHelperArgv, windowsRuntimeProgramArgv } from './windows-runtime-command'
+
+const repo = path.resolve(import.meta.dirname, '../../..')
+const python = process.env.HERMES_TEST_PYTHON || path.join(repo, '.venv/bin/python')
+const runtime = { os: 'Windows', arch: 'AMD64', hermesHome: 'C:\\hermes', hermesPath: 'C:\\hermes\\bin\\hermes.exe', python: 'C:\\runtime\\python.exe' }
+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
+}
+
+test('the canonical runtime prefix is actually executed, including bootstrap and Unicode arguments', () => {
+ const program = "import json, os, sys; print(json.dumps([os.environ['HERMES_TEST_BOOT'], sys.argv[1], '$&'], ensure_ascii=False))"
+ const argv = windowsRuntimeProgramArgv(selected, program)
+ const result = spawnSync(argv[0], [...argv.slice(1), '用户/한글'], { encoding: 'utf8' })
+
+ assert.equal(result.status, 0, result.stderr)
+ assert.deepEqual(JSON.parse(result.stdout), ['selected', '用户/한글', '$&'])
+ assert.ok(windowsHelperArgv(selected, 'inspect', [runtime.hermesPath]).includes('inspect'))
+ assert.throws(() => windowsRuntimeProgramArgv({ ...runtime, runtimeCommand: [python, '-c', 'print(0)'] }, 'pass'), (e: any) => e.kind === 'update-required')
+})
+
+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)
+ calls.push(script)
+
+ if (script.includes('Get-Command hermes.exe')) {
+ return JSON.stringify({ ...runtime, python: '', launcherPath: runtime.hermesPath })
+ }
+
+ if (script.includes('.hermes-update-in-progress')) {
+ return 'CLEAR'
+ }
+
+ assert.match(script, /--print-runtime-command/)
+
+ return JSON.stringify({ python: runtime.python, runtimeCommand: [runtime.python, '-I', '-c', bootstrap] })
+ } }
+
+ const result = await probeWindowsRemote(ssh)
+
+ assert.equal(result.hermesPath, runtime.hermesPath)
+ assert.equal(result.python, runtime.python)
+ assert.ok(calls[0].includes('Test-Path -LiteralPath $candidatePython -PathType Leaf'))
+ assert.ok(calls[1].includes('.hermes-update-in-progress'))
+ assert.ok(calls[2].includes('Assert-NoReparse ([string]$command[0]) $false'))
+})
+
+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)
+
+ if (script.includes('Get-Command hermes.exe')) {return JSON.stringify({ ...runtime, launcherPath: runtime.hermesPath })}
+
+ if (script.includes('.hermes-update-in-progress')) {return 'HELD'}
+ imported = true
+
+ throw new Error('must not import')
+ } }
+
+ 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)
+
+ if (script.includes('Get-Command hermes.exe')) {return JSON.stringify({ ...runtime, launcherPath: runtime.hermesPath })}
+
+ if (script.includes('.hermes-update-in-progress')) {return 'CLEAR'}
+
+ return '{}'
+ } }
+
+ await assert.rejects(() => probeWindowsRemote(invalid), (e: any) => e.kind === 'update-required')
+})
+
+test('atomic spawn streams its whole script and explicitly pipes Unicode caller JSON after draining stdin', async () => {
+ 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)
+ assert.match(observed, /\$OutputEncoding=\[Text.UTF8Encoding\]::new\(\$false\)/)
+ assert.ok(observed.includes(payload))
+ assert.match(observed, /' \| & .*windows_ssh_runtime.*spawn/)
+ assert.match(observed, /FileShare\]::None/)
+
+ return JSON.stringify({ pid: 42, creationTimeNs: '1234567890123456789' })
+ } }
+
+ const result = await atomicWindowsSpawn(ssh, runtime, payload)
+
+ assert.equal(result.pid, 42)
+ assert.ok(observed.length > 1000)
+})
+
+test('Connect refuses an older helper before token upload or backend spawn on a boot-selected runtime', async () => {
+ const { connectWindowsRemote } = await import('./windows-remote-lifecycle')
+ let writes = 0
+
+ const ssh = { exec: async (command: string, options: { stdinData?: string }) => {
+ const script = streamed(command, options)
+
+ if (script.includes('Get-Command hermes.exe')) {return JSON.stringify({ ...runtime, launcherPath: runtime.hermesPath })}
+
+ if (script.includes('.hermes-update-in-progress')) {return 'CLEAR'}
+
+ if (script.includes('--print-runtime-command')) {return JSON.stringify({ python: runtime.python, runtimeCommand: [runtime.python, '-I', '-c', bootstrap] })}
+
+ if (script.includes("'inspect'")) {return JSON.stringify({ supported: true, path: runtime.hermesPath })}
+ writes += 1
+
+ throw new Error('write must not be reached')
+ } }
+
+ await assert.rejects(() => connectWindowsRemote({
+ ssh, ownershipId: 'a'.repeat(32), pickLocalPort: async () => 4444, forward: async () => {},
+ cancelForward: async () => {}, waitForHermes: async () => {}, probeReuseProof: async () => 'authenticated-ok'
+ }), (error: any) => error.kind === 'update-required')
+ assert.equal(writes, 0)
+})
+
+test('canonical profile predicate really filters tombstones, markerless dirs and rollback junk under a pinned home', () => {
+ const home = fs.mkdtempSync(path.join(os.tmpdir(), 'hermes-canonical-inventory-'))
+ const root = path.join(home, 'state-root')
+ const profiles = path.join(root, 'profiles')
+ fs.mkdirSync(path.join(profiles, '.deleted'), { recursive: true })
+ fs.writeFileSync(path.join(root, 'config.yaml'), '')
+
+ for (const name of ['bob', 'win-research', 'ghost', 'tombstoned', '.rollback-1', 'bad name']) {
+ fs.mkdirSync(path.join(profiles, name))
+
+ if (name !== 'ghost') {fs.writeFileSync(path.join(profiles, name, 'config.yaml'), '')}
+ }
+
+ fs.writeFileSync(path.join(profiles, '.deleted', 'tombstoned'), '')
+
+ try {
+ for (const hermesHome of [root, path.join(profiles, 'bob')]) {
+ const result = spawnSync(python, ['-c', WINDOWS_PROFILE_LIST_PY], {
+ cwd: repo, encoding: 'utf8', env: { PATH: process.env.PATH || '', HOME: home, HERMES_HOME: hermesHome, PYTHONPATH: repo }
+ })
+
+ assert.equal(result.status, 0, result.stderr)
+ assert.deepEqual(JSON.parse(result.stdout).profiles, ['default', 'bob', 'win-research'])
+ }
+
+ assert.equal(fs.existsSync(path.join(root, 'install_id')), false, 'inventory must not mint an identity')
+ } finally {
+ fs.rmSync(home, { recursive: true, force: true })
+ }
+})
+
+test('inventory programs guard ancestors, keep install-root anchoring and open identity no-follow', () => {
+ const roster = windowsInventoryScript(runtime, 'profiles')
+ const identity = windowsInventoryScript({ ...runtime, hermesHome: 'C:\\hermes\\profiles\\bob' }, 'install-id')
+
+ assert.match(roster, /Assert-NoReparse \$profilesDir \$true/)
+ assert.match(roster, /_iter_named_profile_dirs/)
+ assert.match(identity, /Split-Path -Leaf \$parent\) -ieq "profiles"/)
+ assert.match(identity, /GetFinalPathNameByHandle/)
+ assert.match(identity, /0x00200000/)
+ 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', () => {
+ 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 result = spawnSync(pwsh, ['-NoProfile', '-NonInteractive', '-EncodedCommand', token], {
+ input: encodedPowerShell(script), 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', () => {
+ 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_用户'
+ const payload = encodedPowerShell(`Write-Output '${marker}'`)
+ const old = 'powershell.exe -NoProfile -NonInteractive -ExecutionPolicy Bypass -Command [ScriptBlock]::Create([Text.Encoding]::Unicode.GetString([Convert]::FromBase64String([Console]::In.ReadToEnd()))).Invoke()'
+ fs.symlinkSync(pwsh, path.join(tools, 'powershell.exe'))
+
+ try {
+ const run = (command: string) => spawnSync(pwsh, ['-NoProfile', '-NonInteractive', '-Command', command], {
+ input: payload, encoding: 'utf8', timeout: 20000, env: { ...process.env, PATH: `${tools}${path.delimiter}${process.env.PATH}` }
+ })
+
+ const red = run(old)
+ const green = run(powerShellStdinCommand())
+
+ assert.notEqual(red.status, 0)
+ assert.match(red.stderr, /Invoke/)
+ assert.equal(green.status, 0, green.stderr)
+ assert.equal(green.stdout.trim(), marker)
+ } finally {
+ fs.rmSync(tools, { recursive: true, force: true })
+ }
+})
+
+test.runIf(Boolean(process.env.HERMES_TEST_PWSH))('real PowerShell parser accepts emitted probe, inventory, spawn and no-follow C# programs', async () => {
+ 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))
+
+ return JSON.stringify(runtime)
+ } })
+ const list = scripts.map(script => `'${encodedPowerShell(script)}'`).join(',')
+ const compile = windowsInventoryScript(runtime, 'install-id').match(/Add-Type -TypeDefinition @'[\s\S]*?'@/)?.[0]
+ 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
+ })
+
+ assert.equal(result.status, 0, result.stderr + result.stdout)
+ assert.equal(result.stdout.trim(), 'HERMES_PS_PROGRAMS_PARSE_OK')
+})
diff --git a/apps/desktop/electron/windows-remote-inventory.ts b/apps/desktop/electron/windows-remote-inventory.ts
new file mode 100644
index 00000000000..32a39c1a1b2
--- /dev/null
+++ b/apps/desktop/electron/windows-remote-inventory.ts
@@ -0,0 +1,110 @@
+import { parseRemoteProfileListing } from './connection-registry'
+import { assertWindowsRemoteInstallUpdateClear, encodedPowerShell, powerShellStdinCommand, 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.
+// No configs, credentials or sessions are opened, and inventory never creates a home or identity.
+export const WINDOWS_PROFILE_LIST_PY = [
+ 'import json, sys',
+ 'sys.dont_write_bytecode = True',
+ 'from hermes_cli.profiles import _iter_named_profile_dirs',
+ "print(json.dumps({'profiles': ['default', *[p.name for p in _iter_named_profile_dirs()]]}, ensure_ascii=False))"
+].join('\n')
+
+const ID_NOFOLLOW_PS = `Add-Type -TypeDefinition @'
+using System;
+using System.IO;
+using System.Text;
+using System.Runtime.InteropServices;
+using Microsoft.Win32.SafeHandles;
+public static class HermesInventoryNoFollow {
+ [DllImport("kernel32.dll", CharSet=CharSet.Unicode, SetLastError=true)]
+ private static extern SafeFileHandle CreateFile(string name, uint access, uint share, IntPtr security, uint creation, uint flags, IntPtr template);
+ [DllImport("kernel32.dll", CharSet=CharSet.Unicode, SetLastError=true)]
+ private static extern uint GetFinalPathNameByHandle(SafeFileHandle handle, StringBuilder path, uint size, uint flags);
+ public static FileStream OpenRead(string name) {
+ var handle=CreateFile(name, 0x80000000, 0x00000007, IntPtr.Zero, 3, 0x00200000, IntPtr.Zero);
+ if(handle.IsInvalid) Marshal.ThrowExceptionForHR(Marshal.GetHRForLastWin32Error());
+ try {
+ var path=new StringBuilder(32768);
+ var size=GetFinalPathNameByHandle(handle,path,32768,0);
+ var actual=path.ToString();
+ if(actual.StartsWith(@"\\\\?\\")) actual=actual.Substring(4);
+ if(size==0 || size>=32768 || !String.Equals(actual,Path.GetFullPath(name),StringComparison.OrdinalIgnoreCase)) throw new IOException("Inventory path escaped its expected location");
+ return new FileStream(handle, FileAccess.Read);
+ } catch { handle.Dispose(); throw; }
+ }
+}
+'@
+`
+
+export function windowsInventoryScript(runtime: WindowsRuntime, operation: 'install-id' | 'profiles'): string {
+ const prefix = [
+ '$ProgressPreference="SilentlyContinue"',
+ '$ErrorActionPreference="Stop"',
+ '[Console]::OutputEncoding=[Text.UTF8Encoding]::new($false)',
+ WINDOWS_NO_REPARSE_PS,
+ `$hermesHome=${psLiteral(runtime.hermesHome)}`,
+ 'if($hermesHome -notmatch "^[a-zA-Z]:[\\\\/]"){throw "Unsafe Windows Hermes home"}',
+ 'Assert-NoReparse $hermesHome $false',
+ '$installRoot=$hermesHome;$parent=Split-Path -Parent $hermesHome',
+ 'if((Split-Path -Leaf $parent) -ieq "profiles"){$installRoot=Split-Path -Parent $parent}',
+ 'Assert-NoReparse $installRoot $false'
+ ]
+
+ if (operation === 'profiles') {
+ const argv = windowsRuntimeProgramArgv(runtime, WINDOWS_PROFILE_LIST_PY)
+ prefix.push(
+ '$profilesDir=Join-Path $installRoot "profiles"',
+ 'Assert-NoReparse $profilesDir $true',
+ // Only metadata: reject links before the canonical predicate can follow any directory.
+ 'if(Test-Path -LiteralPath $profilesDir -PathType Container){foreach($entry in Get-ChildItem -LiteralPath $profilesDir -Force){Assert-NoReparse $entry.FullName $false;if($entry.PSIsContainer){foreach($child in Get-ChildItem -LiteralPath $entry.FullName -Force){Assert-NoReparse $child.FullName $false}}}}',
+ '$env:HERMES_HOME=$hermesHome',
+ `& ${argv.map(psLiteral).join(' ')}`,
+ 'if($LASTEXITCODE -ne 0){exit $LASTEXITCODE}'
+ )
+ } else {
+ prefix.push(
+ ID_NOFOLLOW_PS,
+ '$file=Join-Path $installRoot "install_id";$id=$null',
+ 'Assert-NoReparse $file $true',
+ 'if(Test-Path -LiteralPath $file -PathType Leaf){$stream=$null;$memory=$null;try{$stream=[HermesInventoryNoFollow]::OpenRead($file);Assert-NoReparse $file $false;$memory=New-Object IO.MemoryStream;$buffer=New-Object byte[] 256;$count=$stream.Read($buffer,0,256);if($count -lt 256){$id=[Text.Encoding]::UTF8.GetString($buffer,0,$count).Trim([char]0xFEFF).Trim().ToLowerInvariant()}}finally{if($memory){$memory.Dispose()};if($stream){$stream.Dispose()}}}',
+ '[ordered]@{id=$id}|ConvertTo-Json -Compress'
+ )
+ }
+
+ return prefix.join('\r\n')
+}
+
+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 parsed = JSON.parse(stripPowerShellNoise(output).pop() || 'null')
+
+ if (!parsed || typeof parsed !== 'object' || parsed.error) {throw new Error('Windows inventory did not return valid JSON.')}
+
+ return parsed
+}
+
+export async function listWindowsRemoteProfiles(ssh: any, runtime: WindowsRuntime): Promise<string[]> {
+ const result = await readInventory(ssh, runtime, 'profiles')
+
+ if (!Array.isArray(result.profiles) || !result.profiles.every((name: unknown) => typeof name === 'string') || !result.profiles.includes('default')) {
+ throw new Error('Windows inventory did not return canonical profile names.')
+ }
+
+ return parseRemoteProfileListing(result.profiles.join('\n'))
+}
+
+export async function readWindowsRemoteInstallId(ssh: any, runtime: WindowsRuntime): Promise<string | undefined> {
+ const result = await readInventory(ssh, runtime, 'install-id')
+
+ if (!Object.hasOwn(result, 'id')) {throw new Error('Windows inventory did not report its install identity.')}
+ const id = typeof result.id === 'string' ? result.id.trim().toLowerCase() : ''
+
+ return /^[0-9a-f]{32}$/.test(id) ? id : undefined
+}
diff --git a/apps/desktop/electron/windows-remote-lifecycle.test.ts b/apps/desktop/electron/windows-remote-lifecycle.test.ts
index 8dd81df0052..f5e12e8eb94 100644
--- a/apps/desktop/electron/windows-remote-lifecycle.test.ts
+++ b/apps/desktop/electron/windows-remote-lifecycle.test.ts
@@ -19,6 +19,7 @@ import {
helper,
helperCommand,
powerShellCommand,
+ probeWindowsFiles,
probeWindowsRemote,
psLiteral,
reusableWindowsLock,
@@ -137,7 +138,9 @@ function scriptFromInvocation(command: string, options: SshExecOptions = {}) {
const encoded = command.match(/-EncodedCommand\s+([^\s]+)$/)?.[1]
if (encoded) {
- return Buffer.from(encoded, 'base64').toString('utf16le')
+ const script = Buffer.from(encoded, 'base64').toString('utf16le')
+
+ if (!script.includes('[Console]::In.ReadToEnd()') || options.stdinData == null) {return script}
}
return Buffer.from(String(options.stdinData || '').trim(), 'base64').toString('utf16le')
@@ -316,7 +319,7 @@ test('Windows probe validates Hermes and Python topology before selection', asyn
)
const explicitCheck = script.indexOf('if($explicit){Assert-NoReparse $explicit $false;')
- const explicitPythonCheck = script.indexOf('Assert-NoReparse $explicitPython $false')
+ const explicitPythonCheck = script.indexOf('Assert-NoReparse $explicitPython $true')
const envHome = script.indexOf('$hermesHome=$env:HERMES_HOME')
// #118988: HERMES_HOME is trusted only when it is a directory on the remote; anything else
// (stale User-scope value, client path leaked over SSH) falls back to the remote default.
@@ -482,8 +485,8 @@ test('Windows platform probe streams long PowerShell scripts over stdin', async
})
assert.equal(result.os, 'Windows')
- assert.match(command, /-Command \[ScriptBlock\]::Create/)
- assert.doesNotMatch(command, /-EncodedCommand/)
+ 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')
@@ -595,7 +598,7 @@ test.skipIf(process.platform !== 'win32')('Windows platform probe executes in re
fs.writeFileSync(hermesPath, '')
fs.writeFileSync(path.join(tempDir, 'python.exe'), '')
- const result = await probeWindowsRemote(
+ const result = await probeWindowsFiles(
{
exec: (command: string, options: SshExecOptions = {}) => runLocalWindowsCommand(command, options.stdinData)
},
@@ -633,7 +636,7 @@ test('platform detection preserves POSIX and falls back to Windows PowerShell',
)
assert.equal(result.os, 'Windows')
- assert.match(calls[1], /-Command \[ScriptBlock\]::Create/)
+ assert.match(calls[1], /-EncodedCommand [A-Za-z0-9+/=]+$/)
})
test('platform detection surfaces transport failures as themselves, not unsupported-platform', async () => {
diff --git a/apps/desktop/electron/windows-remote-lifecycle.ts b/apps/desktop/electron/windows-remote-lifecycle.ts
index 6f05c4adedc..00433af503e 100644
--- a/apps/desktop/electron/windows-remote-lifecycle.ts
+++ b/apps/desktop/electron/windows-remote-lifecycle.ts
@@ -3,6 +3,7 @@ import crypto from 'node:crypto'
import { resolveReadyTimeoutMs } from './remote-lifecycle'
import { WINDOWS_CHECKOUT_LOCK_PS, WINDOWS_MARKER_JUDGE_PS } from './remote-update-marker-programs'
import { assertBootstrapNotSuperseded, redactSecrets, SSH_ERROR } from './ssh-connection'
+import { WINDOWS_NO_REPARSE_PS, windowsHelperArgv, windowsRuntimeProgramArgv } from './windows-runtime-command'
const LOCKFILE_SCHEMA_VERSION = 2
const PROTOCOL_VERSION = 1
@@ -36,14 +37,15 @@ function stripPowerShellNoise(stdout) {
.filter(line => line.trim() && !line.trimStart().startsWith('#< CLIXML'))
}
-// Keep long probes out of the remote command line. Windows' default OpenSSH
-// command shell is commonly cmd.exe, whose command-line limit is 8191 chars.
-// SshConnection.exec already supports streaming stdin to the remote command.
+// 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 'powershell.exe -NoProfile -NonInteractive -ExecutionPolicy Bypass -Command [ScriptBlock]::Create([Text.Encoding]::Unicode.GetString([Convert]::FromBase64String([Console]::In.ReadToEnd()))).Invoke()'
+ return powerShellCommand(
+ '[Console]::OutputEncoding=[Text.UTF8Encoding]::new($false);$payload=[Console]::In.ReadToEnd();$script=[Text.Encoding]::Unicode.GetString([Convert]::FromBase64String($payload));& ([scriptblock]::Create($script))'
+ )
}
-async function probeWindowsRemote(ssh, explicitHermesPath = '') {
+async function probeWindowsFiles(ssh, explicitHermesPath = '') {
const explicit = psLiteral(explicitHermesPath)
const script = [
@@ -62,7 +64,7 @@ async function probeWindowsRemote(ssh, explicitHermesPath = '') {
'}',
'}',
`$explicit=${explicit}`,
- 'if($explicit){Assert-NoReparse $explicit $false;$explicitPython=[IO.Path]::Combine([IO.Path]::GetDirectoryName($explicit), "python.exe");Assert-NoReparse $explicitPython $false}',
+ 'if($explicit){Assert-NoReparse $explicit $false;$explicitPython=[IO.Path]::Combine([IO.Path]::GetDirectoryName($explicit), "python.exe");Assert-NoReparse $explicitPython $true}',
// HERMES_HOME is only trusted when it names a directory on the REMOTE: a stale User-scope
// value (older install.ps1 persisted one) or a client path leaked over SSH otherwise fails
// assertSafeRemoteHome as "Unsafe remote Hermes home" (#118988).
@@ -86,13 +88,13 @@ async function probeWindowsRemote(ssh, explicitHermesPath = '') {
'$candidates+=$fallbackHomeCandidate',
'$candidates+=$fallbackProfileCandidate',
'$hermes=$null',
- 'foreach($candidate in $candidates){Assert-NoReparse $candidate $true;$candidatePython=[IO.Path]::Combine([IO.Path]::GetDirectoryName($candidate), "python.exe");Assert-NoReparse $candidatePython $true;try{$item=Get-Item -LiteralPath $candidate -Force -ErrorAction Stop;if(($item.Attributes -band [IO.FileAttributes]::ReparsePoint) -eq 0 -and -not $item.PSIsContainer){$hermes=$item.FullName;break}}catch [Management.Automation.ItemNotFoundException]{continue}}',
+ 'foreach($candidate in $candidates){Assert-NoReparse $candidate $true;$candidatePython=[IO.Path]::Combine([IO.Path]::GetDirectoryName($candidate), "python.exe");Assert-NoReparse $candidatePython $true;try{$item=Get-Item -LiteralPath $candidate -Force -ErrorAction Stop;if(($item.Attributes -band [IO.FileAttributes]::ReparsePoint) -eq 0 -and -not $item.PSIsContainer){$pair=Test-Path -LiteralPath $candidatePython -PathType Leaf;if($pair -or (Split-Path -Leaf (Split-Path -Parent $candidate)) -ieq "bin"){$hermes=$item.FullName;break}}}catch [Management.Automation.ItemNotFoundException]{continue}}',
'if(-not $hermes){throw "Hermes is not installed on the remote Windows host."}',
'Assert-NoReparse $hermes $false',
'if($explicit -and $hermes -ne $explicit){throw "The configured Hermes path is not an executable file."}',
'$python=[IO.Path]::Combine([IO.Path]::GetDirectoryName($hermes), "python.exe")',
- 'Assert-NoReparse $python $false',
- '[ordered]@{os="Windows";arch=$env:PROCESSOR_ARCHITECTURE;hermesHome=$hermesHome;hermesPath=$hermes;python=$python}|ConvertTo-Json -Compress'
+ 'if(Test-Path -LiteralPath $python -PathType Leaf){Assert-NoReparse $python $false}else{$python=""}',
+ '[ordered]@{os="Windows";arch=$env:PROCESSOR_ARCHITECTURE;hermesHome=$hermesHome;hermesPath=$hermes;launcherPath=$hermes;python=$python}|ConvertTo-Json -Compress'
].join('\r\n')
// Windows OpenSSH may serialize PowerShell's progress stream as
@@ -115,6 +117,56 @@ async function probeWindowsRemote(ssh, explicitHermesPath = '') {
return parsed
}
+async function probeWindowsRemote(ssh, explicitHermesPath = '') {
+ const parsed = await probeWindowsFiles(ssh, explicitHermesPath)
+
+ // Resolve only after the OS-only marker gate: never import a changing checkout.
+ if (parsed.launcherPath) {
+ await assertWindowsRemoteInstallUpdateClear(ssh, parsed.hermesHome)
+
+ return resolveWindowsLauncher(ssh, parsed)
+ }
+
+ return parsed
+}
+
+async function resolveWindowsLauncher(ssh: any, runtime: any) {
+ const script = [
+ '$ProgressPreference="SilentlyContinue"',
+ '$ErrorActionPreference="Stop"',
+ WINDOWS_NO_REPARSE_PS,
+ `Assert-NoReparse ${psLiteral(runtime.hermesPath)} $false`,
+ `$lines=@(& ${psLiteral(runtime.hermesPath)} '--print-runtime-command');$code=$LASTEXITCODE`,
+ 'if($code -ne 0){throw "The Hermes launcher does not support --print-runtime-command; refresh the Windows installation launcher."}',
+ '$command=$lines[-1]|ConvertFrom-Json',
+ 'if($command -isnot [array] -or $command.Count -lt 2 -or -not [IO.Path]::IsPathRooted([string]$command[0])){throw "Invalid Hermes runtime command"}',
+ 'foreach($part in $command){if($part -isnot [string] -or $part.Contains([char]0)){throw "Invalid Hermes runtime argument"}}',
+ 'Assert-NoReparse ([string]$command[0]) $false',
+ '[ordered]@{python=[string]$command[0];runtimeCommand=@($command)}|ConvertTo-Json -Depth 5 -Compress'
+ ].join('\r\n')
+
+ let resolved
+
+ try {
+ const output = await ssh.exec(powerShellStdinCommand(), { stdinData: `${encodedPowerShell(script)}\r\n` })
+ 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)) {
+ throw new Error('Invalid Windows launcher runtime response.')
+ }
+
+ windowsRuntimeProgramArgv({ ...runtime, ...resolved }, 'pass')
+ } catch (cause: any) {
+ if (TRANSPORT_KINDS.has(cause?.kind)) {throw cause}
+ const error: any = new Error('Refresh the remote Windows Hermes launcher: its boot-selecting runtime could not be resolved.')
+ error.kind = 'update-required'
+ error.cause = cause
+ throw error
+ }
+
+ return { ...runtime, ...resolved }
+}
+
// The checkouts whose update lock guards a dead marker (update_lock._reclaim_dead):
// the installer's `<install root>\hermes-agent` and the checkout of the runtime
// python (`<root>\venv\Scripts\python.exe`). Defines $checkoutRoots; needs $installRoot.
@@ -285,7 +337,7 @@ async function detectRemotePlatform(ssh, explicitHermesPath = '') {
}
function helperCommand(runtime, operation, args = []) {
- const argv = [runtime.python, '-m', 'hermes_cli.windows_ssh_runtime', operation, ...args]
+ const argv = windowsHelperArgv(runtime, operation, args)
const script = [
'$ProgressPreference="SilentlyContinue"',
@@ -311,13 +363,15 @@ async function helper(ssh, runtime, operation, args = [], stdinData?) {
return parsed
}
-function atomicWindowsSpawnCommand(runtime, reservation: any = {}) {
- const argv = [runtime.python, '-m', 'hermes_cli.windows_ssh_runtime', 'spawn']
- const helper = operation => [runtime.python, '-m', 'hermes_cli.windows_ssh_runtime', operation]
+function atomicWindowsSpawnCommand(runtime, reservation: any = {}, payload?: string) {
+ const argv = windowsHelperArgv(runtime, 'spawn')
+ const helper = operation => windowsHelperArgv(runtime, operation)
+ const invokeSpawn = `${payload == null ? '' : `${psLiteral(payload)} | `}& ${argv.map(psLiteral).join(' ')}`
const script = [
'$ProgressPreference="SilentlyContinue"',
'$ErrorActionPreference="Stop"',
+ '$OutputEncoding=[Text.UTF8Encoding]::new($false)',
WINDOWS_MARKER_JUDGE_PS,
WINDOWS_CHECKOUT_LOCK_PS,
`$hermesHome=${psLiteral(runtime.hermesHome)}`,
@@ -343,8 +397,8 @@ function atomicWindowsSpawnCommand(runtime, reservation: any = {}) {
`& ${helper('remove-lock').map(psLiteral).join(' ')} ${psLiteral(reservation.ownershipId)}|Out-Null}`
: '',
reservation.ownershipId
- ? ` $spawnLines=@(& ${argv.map(psLiteral).join(' ')}); $spawnExit=$LASTEXITCODE`
- : ` & ${argv.map(psLiteral).join(' ')}`,
+ ? ` $spawnLines=@(${invokeSpawn}); $spawnExit=$LASTEXITCODE`
+ : ` ${invokeSpawn}`,
reservation.ownershipId
? ' if($spawnExit -ne 0){exit $spawnExit}'
: ' if($LASTEXITCODE -ne 0){exit $LASTEXITCODE}',
@@ -362,7 +416,8 @@ function atomicWindowsSpawnCommand(runtime, reservation: any = {}) {
}
async function atomicWindowsSpawn(ssh, runtime, stdinData, reservation: any = {}) {
- const output = await ssh.exec(atomicWindowsSpawnCommand(runtime, reservation), { stdinData })
+ const encoded = atomicWindowsSpawnCommand(runtime, reservation, stdinData).split(' ').at(-1)
+ const output = await ssh.exec(powerShellStdinCommand(), { stdinData: `${encoded}\r\n` })
const lines = stripPowerShellNoise(output)
@@ -636,6 +691,12 @@ async function connectWindowsRemote(deps) {
await assertWindowsRemoteInstallUpdateClear(ssh, runtime.hermesHome, runtime.python)
const inspection = await helper(ssh, runtime, 'inspect', [runtime.hermesPath])
+ if (runtime.runtimeCommand && inspection.runtimeBootstrapOwnership !== 1) {
+ const error: any = new Error('The remote Windows SSH helper must be updated with boot-selecting runtime ownership support before connecting.')
+ error.kind = 'update-required'
+ throw error
+ }
+
if (!inspection.supported) {
const error: any = new Error('Update Hermes on the remote Windows host before connecting with Desktop SSH.')
error.kind = 'update-required'
@@ -836,6 +897,7 @@ function buildWindowsInteractiveCommand(remoteCwd = '') {
export {
assertWindowsRemoteInstallUpdateClear,
+ atomicWindowsSpawn,
atomicWindowsSpawnCommand,
buildWindowsInteractiveCommand,
connectWindowsRemote,
@@ -844,6 +906,8 @@ export {
helper,
helperCommand,
powerShellCommand,
+ powerShellStdinCommand,
+ probeWindowsFiles,
probeWindowsRemote,
psLiteral,
reusableWindowsLock,
diff --git a/apps/desktop/electron/windows-runtime-command.ts b/apps/desktop/electron/windows-runtime-command.ts
new file mode 100644
index 00000000000..c01acfe963e
--- /dev/null
+++ b/apps/desktop/electron/windows-runtime-command.ts
@@ -0,0 +1,48 @@
+// The published launcher owns PM activation. A Python guessed beside bin/hermes.exe does not.
+export interface WindowsRuntime {
+ os?: string
+ arch?: string
+ hermesHome: string
+ hermesPath: string
+ python: string
+ launcherPath?: string
+ runtimeCommand?: string[]
+}
+
+export function windowsRuntimeProgramArgv(runtime: WindowsRuntime, program: string): string[] {
+ if (!runtime.runtimeCommand) {return [runtime.python, '-c', program]}
+ const command = [...runtime.runtimeCommand]
+ const codeIndex = command.indexOf('-c')
+ const entry = /runpy\.run_module\((['"])hermes_cli\.main\1,\s*run_name=(['"])__main__\2,\s*alter_sys=True\)\s*$/
+
+ if (codeIndex >= 1 && codeIndex === command.length - 2 && entry.test(command[codeIndex + 1])) {
+ command[codeIndex + 1] = command[codeIndex + 1].replace(entry, () => `exec(${JSON.stringify(program)})`)
+
+ return command
+ }
+
+ // An unrecognized launcher is a capability gap, not permission to drop its bootstrap.
+ const error: any = new Error('The Windows launcher does not expose a supported boot-selecting runtime command; refresh its launcher.')
+ error.kind = 'update-required'
+ throw error
+}
+
+export function windowsHelperArgv(runtime: WindowsRuntime, operation: string, args: string[] = []): string[] {
+ if (!runtime.runtimeCommand) {return [runtime.python, '-m', 'hermes_cli.windows_ssh_runtime', operation, ...args]}
+
+ return [...windowsRuntimeProgramArgv(runtime,
+ "import runpy; runpy.run_module('hermes_cli.windows_ssh_runtime', run_name='__main__', alter_sys=True)"), operation, ...args]
+}
+
+// Same ancestor/leaf guard as the existing platform and marker probes.
+export const WINDOWS_NO_REPARSE_PS = [
+ 'function Assert-NoReparse([string]$candidate,[bool]$allowMissing=$false){',
+ 'if([string]::IsNullOrWhiteSpace($candidate)){throw "Empty Windows path"}',
+ '$current=[IO.Path]::GetFullPath($candidate);$first=$true',
+ 'while($true){',
+ 'try{$item=Get-Item -LiteralPath $current -Force -ErrorAction Stop}catch [Management.Automation.ItemNotFoundException]{if(-not $allowMissing -and $first){throw "Path was not found: $candidate"};$parent=[IO.Path]::GetDirectoryName($current);if(-not $parent -or $parent -eq $current){break};$current=$parent;$first=$false;continue}',
+ 'if(($item.Attributes -band [IO.FileAttributes]::ReparsePoint) -ne 0){throw "Path contains a link or reparse point: $current"}',
+ '$parent=$item.Parent.FullName;if(-not $parent -or $parent -eq $current){break};$current=$parent;$first=$false',
+ '}',
+ '}'
+].join('\r\n')
diff --git a/apps/desktop/electron/windows-ssh-repair.test.ts b/apps/desktop/electron/windows-ssh-repair.test.ts
new file mode 100644
index 00000000000..30d54b597ea
--- /dev/null
+++ b/apps/desktop/electron/windows-ssh-repair.test.ts
@@ -0,0 +1,132 @@
+import assert from 'node:assert/strict'
+
+import { test } from 'vitest'
+
+import { listRemoteHermesProfiles, readRemoteInstallId } from './remote-lifecycle'
+import { assertWindowsRemoteInstallUpdateClear, connectWindowsRemote, probeWindowsRemote } from './windows-remote-lifecycle'
+
+const runtime = {
+ os: 'Windows', arch: 'AMD64', hermesHome: 'C:\\Users\\A\\AppData\\Local\\hermes',
+ hermesPath: 'C:\\Users\\A\\AppData\\Local\\hermes\\bin\\hermes.exe',
+ python: 'C:\\Python\\python.exe'
+}
+
+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')
+
+ return Buffer.from(token, 'base64').toString('utf16le')
+}
+
+test('platform and marker bootstrap survive outer-shell parsing without inlining long payloads', async () => {
+ const calls: Array<{ 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'
+ } }
+
+ await probeWindowsRemote(ssh, 'C:\\用户\\Hermes\\hermes.exe')
+ 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/)
+ assert.ok(command.length < 8191)
+ const script = Buffer.from(String(options.stdinData).trim(), 'base64').toString('utf16le')
+ assert.ok(script.length > wrapper.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 }) => {
+ calls.push(command)
+ assert.doesNotMatch(command, /^echo|^if \[/)
+ const script = Buffer.from(String(options?.stdinData ?? '').trim(), 'base64').toString('utf16le') || decode(command)
+
+ if (script.includes('.hermes-update-in-progress')) {return 'CLEAR'}
+
+ return script.includes('install_id') ? JSON.stringify({ id: 'a'.repeat(32) }) : JSON.stringify({ profiles: ['default', 'bob', 'not legal', '.rollback', 'bob'] })
+ } }
+
+ assert.deepEqual(await listRemoteHermesProfiles(ssh, runtime), ['default', 'bob'])
+ assert.equal(await readRemoteInstallId(ssh, runtime), 'a'.repeat(32))
+ assert.ok(calls.length > 0)
+ const failed = { exec: async () => { throw new Error('fixture disconnected') } }
+ await assert.rejects(() => listRemoteHermesProfiles(failed, runtime))
+})
+
+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')
+
+ return script.includes('.hermes-update-in-progress') ? 'CLEAR' : '{}'
+ } }
+
+ await assert.rejects(() => listRemoteHermesProfiles(ssh, runtime))
+})
+
+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')
+
+ if (script.includes('Get-Command hermes.exe')) {return JSON.stringify({ ...runtime, python: '', launcherPath: runtime.hermesPath })}
+
+ if (script.includes('.hermes-update-in-progress')) {return 'CLEAR'}
+
+ return JSON.stringify({ python: runtime.python, runtimeCommand: [runtime.python, '-I', '-c', bootstrap] })
+ } }
+
+ const result = await probeWindowsRemote(ssh)
+
+ assert.equal(result.python, runtime.python)
+ assert.equal(result.hermesPath, runtime.hermesPath)
+})
+
+test('the complete connect path keeps atomic spawn off argv and delivers the explicit caller JSON', async () => {
+ 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')}
+
+ if (script.includes('Get-Command hermes.exe')) {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.match(script, /' \| & /)
+ spawned = true
+
+ return JSON.stringify({ pid: 42, creationTimeNs: '1234567890123456789' })
+ }
+
+ if (script.includes('.hermes-update-in-progress')) {return 'CLEAR'}
+
+ if (script.includes("'inspect'")) {return JSON.stringify({ supported: true, path: runtime.hermesPath, version: 'fixture' })}
+
+ if (script.includes("'read-lock'")) {return 'null'}
+
+ if (script.includes("'process-state'")) {return JSON.stringify({ alive: true, owned: true, indeterminate: false })}
+
+ if (script.includes("'read-log'")) {return JSON.stringify({ content: 'HERMES_BACKEND_READY port=5555' })}
+
+ return '{"ok":true}'
+ } }
+
+ const result = await connectWindowsRemote({
+ ssh, profile: 'bob', ownershipId: 'a'.repeat(32), pickLocalPort: async () => 4444,
+ forward: async () => {}, cancelForward: async () => {}, waitForHermes: async () => {}, probeReuseProof: async () => 'authenticated-ok'
+ })
+
+ assert.equal(spawned, true)
+ assert.equal(result.remotePort, 5555)
+})
diff --git a/hermes_cli/windows_ssh_runtime.py b/hermes_cli/windows_ssh_runtime.py
index 13f2a47900f..592fb1370b4 100644
--- a/hermes_cli/windows_ssh_runtime.py
+++ b/hermes_cli/windows_ssh_runtime.py
@@ -327,14 +327,14 @@ def process_state(pid: int, creation_time_ns: int, hermes_path: str, spawn_nonce
# layout — so match "a python running our module" (`-c` bootstrap or plain `-m`). Identity
# is anchored by the unforgeable creation-time + secret owner-nonce below.
is_python = os.path.basename(arg0).startswith("python")
- launches_module = (
- argv[1:3] == ["-m", "hermes_cli.main"]
- or (len(argv) > 2 and argv[1] == "-c" and "hermes_cli.main" in argv[2]))
+ from gateway.status_inline_source import inline_bootstrap_argv
+ logical_argv = inline_bootstrap_argv(argv) or argv
+ launches_module = logical_argv[1:3] == ["-m", "hermes_cli.main"]
executable_match = arg0 == expected or (is_python and launches_module)
try:
- serve = argv.index("serve")
- owner = argv.index("--ssh-owner-nonce", serve + 1)
- owned = executable_match and "--isolated" in argv[serve + 1:] and argv[owner + 1] == spawn_nonce
+ serve = logical_argv.index("serve")
+ owner = logical_argv.index("--ssh-owner-nonce", serve + 1)
+ owned = executable_match and "--isolated" in logical_argv[serve + 1:] and logical_argv[owner + 1] == spawn_nonce
except (ValueError, IndexError):
owned = False
return {"alive": process.is_running(), "owned": owned, "indeterminate": False,
@@ -426,6 +426,7 @@ def inspect_hermes(hermes_path: str) -> dict[str, Any]:
return {
"path": path,
"version": (version.stdout + version.stderr).splitlines()[0] if version.returncode == 0 else "",
+ "runtimeBootstrapOwnership": 1,
"supported": "--ssh-session-token-file" in help_text and "--ssh-owner-nonce" in help_text}
diff --git a/tests/hermes_cli/test_windows_ssh_runtime_ownership.py b/tests/hermes_cli/test_windows_ssh_runtime_ownership.py
new file mode 100644
index 00000000000..a89d8d70def
--- /dev/null
+++ b/tests/hermes_cli/test_windows_ssh_runtime_ownership.py
@@ -0,0 +1,53 @@
+"""Boot-selecting runtime ownership uses the actual argv parser on native processes."""
+from __future__ import annotations
+
+import os
+from pathlib import Path
+import subprocess
+import sys
+
+import psutil
+import pytest
+
+from hermes_cli.windows_ssh_runtime import process_state
+
+
+def test_isolated_bootstrap_is_owned_without_accepting_foreign_source(tmp_path):
+ package = tmp_path / "hermes_cli"
+ package.mkdir()
+ (package / "__init__.py").write_text("")
+ (package / "main.py").write_text("import time; time.sleep(30)\n")
+ source = ("import os, sys, runpy; "
+ f"sys.path.insert(0, {str(tmp_path)!r}); "
+ "runpy.run_module('hermes_cli.main', run_name='__main__', alter_sys=True)")
+ nonce = "a" * 16
+ env = {"PATH": os.defpath, "HOME": str(tmp_path)}
+ child = subprocess.Popen([sys.executable, "-I", "-c", source, "serve", "--isolated", "--ssh-owner-nonce", nonce], env=env)
+ try:
+ created = int(psutil.Process(child.pid).create_time() * 1_000_000_000)
+ launcher = str(tmp_path / "hermes.exe")
+ state = process_state(child.pid, created, launcher, nonce)
+ assert state["alive"] and state["owned"], state
+ assert not process_state(child.pid, created, launcher, "b" * 16)["owned"]
+ assert not process_state(child.pid, created + 1, launcher, nonce)["owned"]
+ finally:
+ child.terminate()
+ child.wait(timeout=5)
+
+
+def test_foreign_inline_source_carrying_a_module_name_is_not_ownership(monkeypatch, tmp_path):
+ argv = [sys.executable, "-c", "print('hermes_cli.main')", "serve", "--isolated", "--ssh-owner-nonce", "a" * 16]
+
+ class Process:
+ def create_time(self):
+ return 1_700_000_000.0
+ def cmdline(self):
+ return argv
+ def is_running(self):
+ return True
+
+ monkeypatch.setattr(psutil, "Process", lambda _pid: Process())
+ state = process_state(123, 1_700_000_000_000_000_000, str(tmp_path / "hermes.exe"), "a" * 16)
+ assert state["alive"]
+ assert not state["owned"], state