@ai-workbench/connect 0.7.55-rc.1 → 0.7.55-rc.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -5,12 +5,14 @@
5
5
  # Microsoft Learn《OpenSSH for Windows》安装(Add-WindowsCapability OpenSSH.Server)、sshd 服务、密钥文件 ACL(去继承,管理员/SYSTEM 完全控制);
6
6
  # 微软官方 GitHub PowerShell/Win32-OpenSSH 的 MSI 安装(msiexec ADDLOCAL=Server)作 FoD 失败后备。
7
7
  # 不设 AllowUsers、不改全机 DefaultShell、不动 sshd_config 其他行:本人一段 Match 插在第一个 Match 之前(全局设置之后)。
8
- # 顺序:先收紧(钥匙→入口→规则→主机钥匙→sshd -t),最后才设自动并启动/重启 sshd;任一步失败恢复备份,不留“已开但未收紧”的状态。
8
+ # 顺序:先收紧(已有目录/文件核验只归管理员→钥匙→入口→规则→主机钥匙→sshd -t→关入站防火墙),最后才设自动并启动/重启 sshd;任一步失败恢复备份,不留“已开但未收紧”的状态。
9
9
  # 改文本的部分(Get-AiwbSegment/Set-AiwbSegment)与写 ACL 的部分(Set-AiwbAcl)可在非管理员下对副本验证:$AiwbLibraryOnly=$true 时只定义函数。
10
10
  $ErrorActionPreference = 'Stop'
11
11
  # 微软官方 GitHub PowerShell/Win32-OpenSSH 当前最新发行 10.4.0.0p1-Preview(2026-10-20,GitHub releases/latest),x64 MSI 与其 SHA256(GitHub 资产 digest,下载复核一致)。
12
12
  $AiwbMsiUrl = 'https://github.com/PowerShell/Win32-OpenSSH/releases/download/10.4.0.0p1-Preview/OpenSSH-Win64-v10.4.0.0.msi'
13
13
  $AiwbMsiSha256 = '788D8643464A01EB63640A2FD746F9ED23D106B5A901A35F88DC8CD40E446AC9'
14
+ # MSI 暂存的上级目录(只有 SYSTEM/管理员可写的新子目录建在其下);断言脚本在库模式下改指测试目录。
15
+ $AiwbTemp = Join-Path $env:SystemRoot 'Temp'
14
16
 
15
17
  function Test-AiwbUser([string]$User) { return $User -cmatch '\A[A-Za-z0-9._][A-Za-z0-9._-]*\z' }
16
18
  function Test-AiwbKey([string]$Key) { return ($Key -notmatch "[`r`n]") -and ($Key -cmatch '\Assh-ed25519 [A-Za-z0-9+/]+=*( [ -~]*)?\z') }
@@ -53,15 +55,41 @@ function Set-AiwbSegment([string]$Text, [string]$User, [string]$ProgramData) {
53
55
  return ($lines -join $nl) + $nl
54
56
  }
55
57
 
56
- # 以 SDDL 只写 DACL(所有者不动;SetAccessControl 只落改过的部分);D:P 为去继承。依据:.NET FileSystemSecurity.SetSecurityDescriptorSddlForm/File.SetAccessControl。
58
+ # 以 SDDL 写所有者(SDDL 带 O: 时)与 DACL;SetAccessControl 只落给出的部分;D:P 为去继承。依据:.NET FileSystemSecurity.SetSecurityDescriptorSddlForm/File.SetAccessControl。
57
59
  function Set-AiwbAcl([string]$Path, [string]$Sddl) {
60
+ $sections = 'Access'; if ($Sddl.StartsWith('O:')) { $sections = 'Owner,Access' }
58
61
  if ([IO.Directory]::Exists($Path)) {
59
- $acl = New-Object Security.AccessControl.DirectorySecurity; $acl.SetSecurityDescriptorSddlForm($Sddl, 'Access'); [IO.Directory]::SetAccessControl($Path, $acl)
62
+ $acl = New-Object Security.AccessControl.DirectorySecurity; $acl.SetSecurityDescriptorSddlForm($Sddl, $sections); [IO.Directory]::SetAccessControl($Path, $acl)
60
63
  } else {
61
- $acl = New-Object Security.AccessControl.FileSecurity; $acl.SetSecurityDescriptorSddlForm($Sddl, 'Access'); [IO.File]::SetAccessControl($Path, $acl)
64
+ $acl = New-Object Security.AccessControl.FileSecurity; $acl.SetSecurityDescriptorSddlForm($Sddl, $sections); [IO.File]::SetAccessControl($Path, $acl)
62
65
  }
63
66
  }
64
67
 
68
+ # 只归管理员:所有者是 Administrators 或 SYSTEM,且 SYSTEM/Administrators 之外的允许项不带写类权限
69
+ # (WRITE_DATA/ADD_FILE|APPEND_DATA/ADD_SUBDIRECTORY|WRITE_EA|DELETE_CHILD|WRITE_ATTRIBUTES|DELETE|WRITE_DAC|WRITE_OWNER|GENERIC_ALL|GENERIC_WRITE = 0x500D0156)。
70
+ function Test-AiwbAdminOnly([string]$Path) {
71
+ $acl = Get-Acl -LiteralPath $Path
72
+ if (@('S-1-5-32-544', 'S-1-5-18') -notcontains $acl.GetOwner([Security.Principal.SecurityIdentifier]).Value) { return $false }
73
+ foreach ($r in $acl.GetAccessRules($true, $true, [Security.Principal.SecurityIdentifier])) {
74
+ if ($r.AccessControlType -eq 'Allow' -and @('S-1-5-32-544', 'S-1-5-18') -notcontains $r.IdentityReference.Value -and ([int64]$r.FileSystemRights -band 0x500D0156)) { return $false }
75
+ }
76
+ return $true
77
+ }
78
+
79
+ # 已存在的 ssh 目录、sshd_config、主机私钥若不是只归管理员,重置为 Win32-OpenSSH 自建时的所有者与 DACL(同其 FixHostFilePermissions 的做法)并读回核验;
80
+ # 重置不了(如他人文件拒绝管理员改所有者)即报错、整体撤回。选择重置而不是直接报错:这些位置的正确权限是确定的(sshd 自己就按此建),重置只会收紧。
81
+ # 重置不随撤回恢复(同 macOS 撤回时保留主机钥匙:恢复成宽松权限没有意义)。
82
+ function Repair-AiwbAdminOnly([string]$Path, [string]$Sddl) {
83
+ if (Test-AiwbAdminOnly $Path) { return }
84
+ Set-AiwbAcl $Path $Sddl
85
+ if (-not (Test-AiwbAdminOnly $Path)) { throw 'AW_REMOTE_ACCESS_SSHD_INVALID' }
86
+ }
87
+
88
+ # OpenSSH Server 入站防火墙规则:FoD 建 OpenSSH-Server-In-TCP,官方 MSI 建 “OpenSSH SSH Server Preview (sshd)”(MSI 的 WixFirewallException)。
89
+ function Get-AiwbFirewallRules {
90
+ @(Get-NetFirewallRule -Name 'OpenSSH-Server-In-TCP' -ErrorAction SilentlyContinue) + @(Get-NetFirewallRule -DisplayName 'OpenSSH SSH Server Preview (sshd)' -ErrorAction SilentlyContinue) | Where-Object { $_ }
91
+ }
92
+
65
93
  # 先写 <文件>.tmp(UTF-8 无 BOM),设 ACL,再替换到位(同卷改名,ACL 随文件)。
66
94
  function Write-AiwbFile([string]$Path, [string]$Text, [string]$Sddl) {
67
95
  $tmp = "$Path.tmp"
@@ -105,7 +133,7 @@ function Install-AiwbSshd {
105
133
  if ($hash -ne $AiwbMsiSha256) { throw 'AW_REMOTE_ACCESS_MSI_HASH' }
106
134
  $sec = New-Object Security.AccessControl.DirectorySecurity
107
135
  $sec.SetSecurityDescriptorSddlForm('D:P(A;OICI;FA;;;SY)(A;OICI;FA;;;BA)')
108
- $dir = Join-Path $env:SystemRoot ('Temp\aiwb-openssh-' + [guid]::NewGuid().ToString('N'))
136
+ $dir = Join-Path $AiwbTemp ('aiwb-openssh-' + [guid]::NewGuid().ToString('N'))
109
137
  [void][IO.Directory]::CreateDirectory($dir, $sec)
110
138
  try {
111
139
  $msi = Join-Path $dir 'OpenSSH-Win64.msi'
@@ -117,6 +145,13 @@ function Install-AiwbSshd {
117
145
  if (-not (Get-Service -Name sshd -ErrorAction SilentlyContinue)) { throw 'AW_REMOTE_ACCESS_SSHD_MISSING' }
118
146
  }
119
147
 
148
+ # 运行 sshd.exe/ssh-keygen.exe 只取退出码:输出丢弃;在本函数内把错误偏好设为 Continue,免得 PowerShell 5.1 在 stderr 被重定向时把原生程序的 stderr 包成错误记录而中止。
149
+ function Invoke-AiwbNative([string]$Exe, [string[]]$Arguments) {
150
+ $ErrorActionPreference = 'Continue'
151
+ & $Exe @Arguments 2>&1 | Out-Null
152
+ return $LASTEXITCODE
153
+ }
154
+
120
155
  # sshd.exe 的位置取自服务登记(FoD 在 System32\OpenSSH,MSI 在 Program Files\OpenSSH)。
121
156
  function Get-AiwbSshdPath {
122
157
  $image = (Get-CimInstance -ClassName Win32_Service -Filter "Name='sshd'").PathName
@@ -133,42 +168,56 @@ function Invoke-AiwbRemoteAccess([string]$User, [string]$Sid, [string]$Key) {
133
168
  $keys = Join-Path $dir "$u.keys"
134
169
  $entry = Join-Path $dir 'entry.ps1'
135
170
  $conf = Join-Path $sshDir 'sshd_config'
136
- # 开始前状态:sshd 是否已装、启动类型与是否在跑;三个文件是否已存在(存在则先在内存里备份以便撤回)。
171
+ # 开始前状态:有没有 sshd 服务、启动类型与是否在跑、入站防火墙规则是否启用;三个文件是否已存在(存在则先在内存里备份以便撤回)。
137
172
  $svc = Get-Service -Name sshd -ErrorAction SilentlyContinue
138
- $installed = $false; $touched = $false
173
+ $installed = -not $svc; $touched = $false
139
174
  $startBefore = $null; $runningBefore = $false
140
175
  if ($svc) { $startBefore = $svc.StartType; $runningBefore = ($svc.Status -eq 'Running') }
176
+ $fwBefore = @{}; foreach ($r in (Get-AiwbFirewallRules)) { $fwBefore[$r.Name] = ([string]$r.Enabled -eq 'True') }
177
+ $fwClosed = @()
141
178
  $backup = @{}
142
179
  foreach ($f in @($keys, $entry, $conf)) { if ([IO.File]::Exists($f)) { $backup[$f] = [IO.File]::ReadAllBytes($f) } else { $backup[$f] = $null } }
143
180
  $finished = $false; $code = 1
144
181
  try {
145
- if (-not $svc) { Install-AiwbSshd; $installed = $true }
182
+ if ($installed) {
183
+ Install-AiwbSshd
184
+ # 安装器可能已把 sshd 启动(MSI):先停,收紧完再开。
185
+ Stop-Service -Name sshd -Force -ErrorAction SilentlyContinue
186
+ }
146
187
  $sshd = Get-AiwbSshdPath
147
188
  $bin = Split-Path -Parent $sshd
148
- # 从未启动过的 sshd 还没有 ProgramData\ssh 与 sshd_config:按 Win32-OpenSSH 自建该目录时的 SDDL 建目录,用安装目录的 sshd_config_default 作底本。
189
+ # 从未启动过的 sshd 还没有 ProgramData\ssh 与 sshd_config:按 Win32-OpenSSH 自建该目录时的 SDDL 建目录,用安装目录的 sshd_config_default 作底本;已有的核验只归管理员。
149
190
  if (-not (Test-Path -LiteralPath $sshDir)) {
150
191
  $sec = New-Object Security.AccessControl.DirectorySecurity
151
192
  $sec.SetSecurityDescriptorSddlForm('O:BAD:PAI(A;OICI;FA;;;SY)(A;OICI;FA;;;BA)(A;OICI;0x1200a9;;;AU)')
152
193
  [void][IO.Directory]::CreateDirectory($sshDir, $sec)
153
- }
194
+ } else { Repair-AiwbAdminOnly $sshDir 'O:BAD:PAI(A;OICI;FA;;;SY)(A;OICI;FA;;;BA)(A;OICI;0x1200a9;;;AU)' }
154
195
  if (-not [IO.File]::Exists($conf)) { Copy-Item -LiteralPath (Join-Path $bin 'sshd_config_default') -Destination $conf }
196
+ Repair-AiwbAdminOnly $conf 'O:BAD:PAI(A;;FA;;;SY)(A;;FA;;;BA)(A;;0x1200a9;;;AU)'
155
197
  if (-not (Test-Path -LiteralPath $dir)) { New-Item -ItemType Directory -Path $dir | Out-Null }
156
- # 目录:SYSTEM/管理员完全控制,登录用户只可读本目录;钥匙与入口:去继承,SYSTEM/管理员完全控制,本人只读。
157
- Set-AiwbAcl $dir 'D:PAI(A;OICI;FA;;;SY)(A;OICI;FA;;;BA)(A;;0x1200a9;;;AU)'
158
- $fileAcl = "D:P(A;;FA;;;SY)(A;;FA;;;BA)(A;;FR;;;$Sid)"
198
+ # aiwb 目录:所有者 Administrators,SYSTEM/管理员完全控制,登录用户只可读本目录;钥匙与入口:所有者 Administrators,去继承,SYSTEM/管理员完全控制,本人只读。
199
+ Set-AiwbAcl $dir 'O:BAD:PAI(A;OICI;FA;;;SY)(A;OICI;FA;;;BA)(A;;0x1200a9;;;AU)'
200
+ if (-not (Test-AiwbAdminOnly $dir)) { throw 'AW_REMOTE_ACCESS_SSHD_INVALID' }
201
+ $fileAcl = "O:BAD:P(A;;FA;;;SY)(A;;FA;;;BA)(A;;FR;;;$Sid)"
159
202
  Write-AiwbFile $keys "from=`"127.0.0.1,::1`",restrict,pty $Key`n" $fileAcl
160
203
  Write-AiwbFile $entry (Get-AiwbEntry) $fileAcl
161
- $text = ''; if ($null -ne $backup[$conf]) { $text = [Text.Encoding]::UTF8.GetString($backup[$conf]) }
162
- # sshd_config 原地改写(保留其原有 ACL);sshd 只在下面 -t 通过后才(重)启动读取。
204
+ # 底本是当前文件(已有的,或上面刚从 sshd_config_default 复制的)。
205
+ $text = [IO.File]::ReadAllText($conf, (New-Object Text.UTF8Encoding($false)))
206
+ # sshd_config 原地改写(保留其 ACL);sshd 只在下面 -t 通过后才(重)启动读取。
163
207
  [IO.File]::WriteAllText($conf, (Set-AiwbSegment $text $User $env:ProgramData), (New-Object Text.UTF8Encoding($false)))
164
- # 主机钥匙:只补缺的默认类型(ssh-keygen -A),新生成的私钥收紧为 SYSTEM/管理员;已有的不动、撤回时保留(同 Mac)。
208
+ # 主机钥匙:已有私钥核验只归管理员;只补缺的默认类型(ssh-keygen -A),新生成的私钥收紧为 SYSTEM/管理员;撤回时保留(同 Mac)。
165
209
  $hostKeys = @(Get-ChildItem -LiteralPath $sshDir -Filter 'ssh_host_*_key' -ErrorAction SilentlyContinue | ForEach-Object { $_.FullName })
166
- & (Join-Path $bin 'ssh-keygen.exe') -A | Out-Null
210
+ foreach ($k in $hostKeys) { Repair-AiwbAdminOnly $k 'O:BAD:P(A;;FA;;;SY)(A;;FA;;;BA)' }
211
+ [void](Invoke-AiwbNative (Join-Path $bin 'ssh-keygen.exe') @('-A'))
167
212
  foreach ($k in @(Get-ChildItem -LiteralPath $sshDir -Filter 'ssh_host_*_key' -ErrorAction SilentlyContinue | ForEach-Object { $_.FullName })) {
168
- if ($hostKeys -notcontains $k) { Set-AiwbAcl $k 'D:P(A;;FA;;;SY)(A;;FA;;;BA)' }
213
+ if ($hostKeys -notcontains $k) { Set-AiwbAcl $k 'O:BAD:P(A;;FA;;;SY)(A;;FA;;;BA)' }
214
+ }
215
+ if ((Invoke-AiwbNative $sshd @('-t')) -ne 0) { [Console]::Error.WriteLine('AW_REMOTE_ACCESS_SSHD_INVALID'); return 1 }
216
+ # 入站防火墙(待 owner 追认):N 只经 127.0.0.1:22 回环连入,不需要入站规则;本次新装或开始前没在跑的 sshd,关掉其入站规则,
217
+ # 免得本机所有账户可从局域网密码登录(与 macOS“只放行本人”等价);原本就在运行的 sshd 不动其防火墙。
218
+ if ($installed -or -not $runningBefore) {
219
+ foreach ($r in (Get-AiwbFirewallRules)) { if ([string]$r.Enabled -eq 'True') { Disable-NetFirewallRule -Name $r.Name; $fwClosed += $r.Name } }
169
220
  }
170
- & $sshd -t
171
- if ($LASTEXITCODE -ne 0) { [Console]::Error.WriteLine('AW_REMOTE_ACCESS_SSHD_INVALID'); return 1 }
172
221
  $touched = $true
173
222
  Set-Service -Name sshd -StartupType Automatic
174
223
  if ((Get-Service -Name sshd).Status -eq 'Running') { Restart-Service -Name sshd -Force } else { Start-Service -Name sshd }
@@ -181,13 +230,19 @@ function Invoke-AiwbRemoteAccess([string]$User, [string]$Sid, [string]$Key) {
181
230
  Remove-Item -LiteralPath "$f.tmp" -Force -ErrorAction SilentlyContinue
182
231
  if ($null -ne $backup[$f]) { [IO.File]::WriteAllBytes($f, [byte[]]$backup[$f]) } else { Remove-Item -LiteralPath $f -Force -ErrorAction SilentlyContinue }
183
232
  }
233
+ # 开始前没有 sshd 服务(本次新装,含安装中途出错):停止并设 Disabled;原有的按原启动类型与运行状态恢复。
184
234
  if ($installed) {
185
- Stop-Service -Name sshd -Force -ErrorAction SilentlyContinue
186
- Set-Service -Name sshd -StartupType Disabled -ErrorAction SilentlyContinue
235
+ if (Get-Service -Name sshd -ErrorAction SilentlyContinue) {
236
+ Stop-Service -Name sshd -Force -ErrorAction SilentlyContinue
237
+ Set-Service -Name sshd -StartupType Disabled -ErrorAction SilentlyContinue
238
+ }
187
239
  } elseif ($touched) {
188
240
  Set-Service -Name sshd -StartupType $startBefore -ErrorAction SilentlyContinue
189
241
  if ($runningBefore) { Restart-Service -Name sshd -Force -ErrorAction SilentlyContinue } else { Stop-Service -Name sshd -Force -ErrorAction SilentlyContinue }
190
242
  }
243
+ # 防火墙:本次关掉的、开始前就启用的规则重新启用;本次新装时随安装建出的规则(开始前不存在)关闭。
244
+ foreach ($name in $fwClosed) { if ($fwBefore[$name]) { Enable-NetFirewallRule -Name $name -ErrorAction SilentlyContinue } }
245
+ if ($installed) { foreach ($r in (Get-AiwbFirewallRules)) { if (-not $fwBefore.ContainsKey($r.Name) -and [string]$r.Enabled -eq 'True') { Disable-NetFirewallRule -Name $r.Name -ErrorAction SilentlyContinue } } }
191
246
  [Console]::Error.WriteLine('AW_REMOTE_ACCESS_ROLLED_BACK')
192
247
  }
193
248
  }
package/lib/connect.js CHANGED
@@ -4,11 +4,12 @@ import { dependency, fail as baseFail, ok, need } from "./needs.js";
4
4
  import { createStartup } from "./startup.js";
5
5
  import { parseLoginStatus } from "./auth-status.js";
6
6
  import { authFailure } from "./auth-diagnostics.js";
7
+ import { host as files } from "./private-files.js";
7
8
  function validEnrollment(e) {
8
9
  return typeof e === 'object' && e !== null && typeof e.host === 'string' && /^[a-zA-Z0-9][a-zA-Z0-9.-]*$/.test(e.host)
9
10
  && typeof e.username === 'string' && /^emp-[a-z0-9][a-z0-9-]*$/.test(e.username)
10
11
  && Number.isInteger(e.port) && e.port > 0 && e.port <= 65535
11
- && typeof e.knownHostsFile === 'string' && e.knownHostsFile.startsWith('/') && !/[\x00-\x1f\x7f]/.test(e.knownHostsFile)
12
+ && typeof e.knownHostsFile === 'string' && (files.platform === 'win32' ? /^[A-Za-z]:\\/.test(e.knownHostsFile) : e.knownHostsFile.startsWith('/')) && !/[\x00-\x1f\x7f]/.test(e.knownHostsFile)
12
13
  && typeof e.projectRoot === 'string' && e.projectRoot.length > 0 && !/[\x00-\x1f\x7f]/.test(e.projectRoot);
13
14
  }
14
15
  export function createConnect(ports, emit, options = {}) {
package/lib/index.js CHANGED
@@ -58,13 +58,18 @@ export function apply(ctx, config = {}) {
58
58
  if (ssh?.employeeAccess) {
59
59
  // 工具桥回连命令由工具桥插件以可选服务 aiWorkbenchToolbridge 提供({command}),登记时现取;没装工具桥则不上报。
60
60
  const toolbridge = () => { const service = ctx.get('aiWorkbenchToolbridge'); return typeof service?.command === 'string' ? service.command : undefined; };
61
- const access = createRemoteAccess({ ssh: { employeeAccess: ssh.employeeAccess }, user: userInfo().username, node: target => networkNodeName(config.network, target.username), toolbridge });
61
+ const access = createRemoteAccess({ ssh: { employeeAccess: ssh.employeeAccess }, user: userInfo().username, node: target => networkNodeName(config.network, target.username), toolbridge, listenTimeoutMs: (config.network?.dialTimeoutSeconds ?? NETWORK_DEFAULTS.dialTimeoutSeconds) * 1000 });
62
62
  // 每次连上(新的连接代次)做一次:写主机 emp.json,按需开通本机远程登录;不阻塞连接与登录。
63
63
  let seen = '';
64
64
  const lifetime = new AbortController();
65
65
  ctx.effect(() => { const off = api.onConnectionState(state => { const key = state.instanceId + ':' + state.epoch; if (state.phase !== 'connected' || key === seen)
66
66
  return; seen = key; void api.getSshTarget().then(r => { if (r.ok && !lifetime.signal.aborted)
67
67
  return access.sync(r.value, lifetime.signal); }); }); return () => { off(); lifetime.abort(); }; });
68
+ // cordis ctx.get 对未声明的服务不报错,只在提供方处于活动状态时返回其值,否则 undefined(@deepseek-ai/cordis src/reflect.ts get)。
69
+ // 工具桥晚于本插件出现(或重新提供)时,ctx.inject 回调在服务可用时运行:已连接则重新登记一次,把 toolbridge 补上。
70
+ ctx.inject(['aiWorkbenchToolbridge'], scope => { scope.effect(() => { if (api.getConnectionState().phase === 'connected' && seen)
71
+ void api.getSshTarget().then(r => { if (r.ok && !lifetime.signal.aborted)
72
+ return access.again(r.value, lifetime.signal); }); return () => { }; }); });
68
73
  }
69
74
  }, false);
70
75
  registerComponents(ctx, config.inventory, config.enrollmentMetadataMaxBytes ?? L_DEFAULTS.enrollmentMetadataMaxBytes);
@@ -59,11 +59,15 @@ interface RemoteAccessOptions {
59
59
  sid?: () => string;
60
60
  /** 工具桥插件提供的本机回连命令(可选服务 aiWorkbenchToolbridge);未装工具桥时为 undefined,登记不带该字段。 */
61
61
  toolbridge?: () => string | undefined;
62
+ /** Windows 检测 127.0.0.1:22 的连接超时(毫秒),取 network.dialTimeoutSeconds。 */
63
+ listenTimeoutMs?: number;
62
64
  warn?: (message: string) => void;
63
65
  }
64
66
  /** 系统设置“共享 → 远程登录”详情面板的官方深链接(含“允许远程用户完全磁盘访问”开关;该开关属 TCC,只能本人点开)。 */
65
67
  export declare const REMOTE_LOGIN_SETTINGS = "x-apple.systempreferences:com.apple.Sharing-Settings.extension?Services_RemoteLogin";
66
68
  export declare function createRemoteAccess(options: RemoteAccessOptions): {
67
69
  sync(target: SshTarget, signal: AbortSignal): Promise<void>;
70
+ /** 登记内容可能变了(如工具桥服务晚于本插件出现):等进行中的一次结束后再登记一次。 */
71
+ again(target: SshTarget, signal: AbortSignal): Promise<void>;
68
72
  };
69
73
  export {};
@@ -5,6 +5,7 @@ import { connect } from 'node:net';
5
5
  import { win32 } from 'node:path';
6
6
  import { shellQuote } from "./ssh.js";
7
7
  import { windowsSecurity } from "./windows-security.js";
8
+ import { NETWORK_DEFAULTS } from "./defaults.js";
8
9
  // TH2 约定 B/C:连上主机后把本机用户名、N 节点名、平台与工具桥回连命令经主机 helper 按来源设备登记,并读主机 emp 公钥;
9
10
  // 本机“远程登录”未按该钥匙开通时,macOS 用管理员授权框执行一次固定脚本(helper/remote-access.sh),
10
11
  // Windows 用 UAC 以管理员执行一次(helper/remote-access.ps1,设计 C,与 .sh 逐条对应)。
@@ -124,7 +125,8 @@ const openSettings = (url) => new Promise((resolve, reject) => execFile('/usr/bi
124
125
  const script = () => readFile(new URL('../helper/remote-access.sh', import.meta.url), 'utf8');
125
126
  const windowsScript = () => readFile(new URL('../helper/remote-access.ps1', import.meta.url), 'utf8');
126
127
  // Windows 现状只读获取(普通用户可做):钥匙文件与 sshd_config 读文本(Authenticated Users 可读);sshd 服务状态普通用户查不了,改为连 127.0.0.1:22 看是否在听。
127
- const listening = () => new Promise(resolve => { const socket = connect({ host: '127.0.0.1', port: 22 }); socket.once('connect', () => { socket.destroy(); resolve(true); }); socket.once('error', () => resolve(false)); });
128
+ // 超时沿用具名设置 network.dialTimeoutSeconds(默认 20 秒,见 defaults.ts),不新增设置;超时按“未在听”处理。
129
+ const listening = (timeoutMs) => new Promise(resolve => { const socket = connect({ host: '127.0.0.1', port: 22, timeout: timeoutMs }); socket.once('connect', () => { socket.destroy(); resolve(true); }); socket.once('timeout', () => { socket.destroy(); resolve(false); }); socket.once('error', () => resolve(false)); });
128
130
  const readOptional = async (path) => { try {
129
131
  return await readFile(path, 'utf8');
130
132
  }
@@ -133,13 +135,13 @@ catch (error) {
133
135
  return undefined;
134
136
  throw error;
135
137
  } };
136
- const windowsLocalAccess = async (user) => {
138
+ const windowsLocalAccess = (timeoutMs) => async (user) => {
137
139
  const programData = process.env.ProgramData;
138
140
  if (!programData || !win32.isAbsolute(programData))
139
141
  throw Error('PROGRAMDATA_REQUIRED');
140
142
  const keys = await readOptional(win32.join(programData, 'ssh', 'aiwb', user.toLowerCase() + '.keys'));
141
143
  const config = await readOptional(win32.join(programData, 'ssh', 'sshd_config'));
142
- return { keys, sshdLoaded: await listening(), confExists: windowsSegmentOk(config, user, programData) };
144
+ return { keys, sshdLoaded: await listening(timeoutMs), confExists: windowsSegmentOk(config, user, programData) };
143
145
  };
144
146
  // 外层 powershell 以 UAC 结果退出:0 成功,1223 用户拒绝,其余失败。
145
147
  const windowsRunAdmin = (command, args) => new Promise(resolve => execFile(command, args, { timeout: 0, windowsHide: true }, error => { const code = error ? error.code : 0; resolve({ ok: !error, cancelled: code === WINDOWS_CANCELLED }); }));
@@ -170,7 +172,7 @@ export function createRemoteAccess(options) {
170
172
  return;
171
173
  }
172
174
  const windows = platform === 'win32';
173
- if (!needsSetup(await (options.localAccess ?? (windows ? windowsLocalAccess : localAccess))(options.user), key))
175
+ if (!needsSetup(await (options.localAccess ?? (windows ? windowsLocalAccess(options.listenTimeoutMs ?? NETWORK_DEFAULTS.dialTimeoutSeconds * 1000) : localAccess))(options.user), key))
174
176
  return;
175
177
  const admin = windows ? windowsAdminCommand(await (options.script ?? windowsScript)(), options.user, (options.sid ?? (() => windowsSecurity.sid()))(), key) : adminCommand(await (options.script ?? script)(), options.user, key);
176
178
  const result = await (options.runAdmin ?? (windows ? windowsRunAdmin : runAdmin))(admin.command, admin.args);
@@ -199,5 +201,7 @@ export function createRemoteAccess(options) {
199
201
  flight = current;
200
202
  return current;
201
203
  },
204
+ /** 登记内容可能变了(如工具桥服务晚于本插件出现):等进行中的一次结束后再登记一次。 */
205
+ again(target, signal) { return (flight ?? Promise.resolve()).then(() => this.sync(target, signal)); },
202
206
  };
203
207
  }
package/lib/ssh.d.ts CHANGED
@@ -2,6 +2,11 @@ import type { SshTarget } from './api.ts';
2
2
  import type { CommandResult, Ports } from './ports.ts';
3
3
  export declare function shellQuote(s: string): string;
4
4
  export declare function proxyCommand(binary: string, runtimeDir: string): string;
5
+ /**
6
+ * Windows:Win32-OpenSSH 8.6 在 ProxyCommand 失败、ssh 自身 stderr 为管道且未给 -E 时不退出(N 合同 Windows 节,实机复现);
7
+ * 加 `-E <L 私有信任目录内 ssh.log>`(ssh 自身诊断追加写入该文件,X 等消费方可读;不用 NUL 以保留诊断)。macOS 不变。
8
+ */
9
+ export declare function sshLogFile(t: Pick<SshTarget, 'knownHostsFile'>): string | undefined;
5
10
  export declare function sshArgs(t: SshTarget): string[];
6
11
  export interface Runner {
7
12
  run(cmd: string, args: string[], signal: AbortSignal, input?: string): Promise<CommandResult>;
package/lib/ssh.js CHANGED
@@ -1,4 +1,6 @@
1
1
  import { readFile } from 'node:fs/promises';
2
+ import { win32 } from 'node:path';
3
+ import { host as files } from "./private-files.js";
2
4
  import { randomUUID } from 'node:crypto';
3
5
  import { fail, ok } from "./needs.js";
4
6
  import { AuthDiagnosticError, authFailure, outputSummary } from "./auth-diagnostics.js";
@@ -12,8 +14,14 @@ export function proxyCommand(binary, runtimeDir) {
12
14
  throw new Error('ABSOLUTE_PROXY_PATH_REQUIRED');
13
15
  return `${shellQuote(binary)} ssh-proxy --runtime-dir ${shellQuote(runtimeDir)} %h %p`;
14
16
  }
17
+ /**
18
+ * Windows:Win32-OpenSSH 8.6 在 ProxyCommand 失败、ssh 自身 stderr 为管道且未给 -E 时不退出(N 合同 Windows 节,实机复现);
19
+ * 加 `-E <L 私有信任目录内 ssh.log>`(ssh 自身诊断追加写入该文件,X 等消费方可读;不用 NUL 以保留诊断)。macOS 不变。
20
+ */
21
+ export function sshLogFile(t) { return files.platform === 'win32' ? win32.join(win32.dirname(t.knownHostsFile), 'ssh.log') : undefined; }
15
22
  export function sshArgs(t) {
16
- return ['-F', '/dev/null', '-T', '-o', 'IdentityAgent=none', '-o', 'PubkeyAuthentication=no', '-o', 'PasswordAuthentication=no', '-o', 'KbdInteractiveAuthentication=no', '-o', 'PreferredAuthentications=none', '-o', 'UpdateHostKeys=no', '-o', 'CanonicalizeHostname=no', '-o', 'BatchMode=yes', '-o', 'ServerAliveInterval=15', '-o', 'ServerAliveCountMax=3', '-o', 'StrictHostKeyChecking=yes', '-o', 'GlobalKnownHostsFile=/dev/null', '-o', 'UserKnownHostsFile=' + JSON.stringify(t.knownHostsFile.replaceAll('%', '%%')), '-o', 'ProxyCommand=' + t.proxyCommand, '-p', String(t.port), '-l', t.username, t.host];
23
+ const log = sshLogFile(t);
24
+ return ['-F', '/dev/null', ...log ? ['-E', log] : [], '-T', '-o', 'IdentityAgent=none', '-o', 'PubkeyAuthentication=no', '-o', 'PasswordAuthentication=no', '-o', 'KbdInteractiveAuthentication=no', '-o', 'PreferredAuthentications=none', '-o', 'UpdateHostKeys=no', '-o', 'CanonicalizeHostname=no', '-o', 'BatchMode=yes', '-o', 'ServerAliveInterval=15', '-o', 'ServerAliveCountMax=3', '-o', 'StrictHostKeyChecking=yes', '-o', 'GlobalKnownHostsFile=/dev/null', '-o', 'UserKnownHostsFile=' + JSON.stringify(t.knownHostsFile.replaceAll('%', '%%')), '-o', 'ProxyCommand=' + t.proxyCommand, '-p', String(t.port), '-l', t.username, t.host];
17
25
  }
18
26
  export async function runRemote(runner, t, command, signal, input) {
19
27
  const nonce = randomUUID(), source = await readFile(new URL('../helper/remote-command.cjs', import.meta.url), 'utf8');
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ai-workbench/connect",
3
- "version": "0.7.55-rc.1",
3
+ "version": "0.7.55-rc.2",
4
4
  "type": "module",
5
5
  "engines": {
6
6
  "node": ">=24.13.1",