@ai-workbench/connect 0.7.55-rc.5 → 0.7.55-rc.7

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,7 +5,7 @@
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,下载复核一致)。
@@ -32,27 +32,51 @@ function Get-AiwbSegment([string]$User, [string]$ProgramData) {
32
32
  )
33
33
  }
34
34
 
35
- # 返回改好的全文:已有本人段且它之前没有非本插件的 Match 行 → 原位整段替换;否则(没有,或被挪到别的 Match 之后)去掉旧段,
36
- # 插在第一个 Match 行(或其他员工段的开始标记)之前、全局设置之后;没有 Match 就放末尾。换行沿用原文(空文件用 CRLF);有头无尾的本人段不猜,报错。
35
+ # 按行切分并保留每行原有换行符(CRLF/LF/末行无换行):返回 Start(字符偏移)、Content、Eol。
36
+ function Get-AiwbLines([string]$Text) {
37
+ $out = New-Object 'System.Collections.Generic.List[object]'
38
+ foreach ($m in [regex]::Matches($Text, '([^\r\n]*)(\r\n|\n)?')) {
39
+ if ($m.Length -eq 0 -and $m.Index -ge $Text.Length) { break }
40
+ $out.Add([pscustomobject]@{ Start = $m.Index; Content = $m.Groups[1].Value; Eol = $m.Groups[2].Value })
41
+ }
42
+ return , $out
43
+ }
44
+
45
+ # 返回改好的全文,段外字节原样保留(各行原有换行、文件末尾有无换行、BOM 有无都不动):
46
+ # 已有本人段且它之前没有非本插件的 Match 行 → 原位整段替换;否则(没有,或被挪到别的 Match 之后)去掉旧段,
47
+ # 插在第一个 Match 行(或其他员工段的开始标记)的行首、全局设置之后;没有 Match 就放末尾。本人段用文件里占多数的换行(相同或没有时 CRLF);
48
+ # 放在无结尾换行的文件末尾时,段写成“换行 + 段”且自身不带结尾换行,文件仍以无换行结尾。有头无尾的本人段不猜,报错。
37
49
  function Set-AiwbSegment([string]$Text, [string]$User, [string]$ProgramData) {
50
+ # BOM 原样留在最前,其余按无 BOM 文本处理(按字符判,不用 StartsWith:.NET Framework 的区域性比较会忽略 U+FEFF)。
51
+ if ($Text.Length -gt 0 -and $Text[0] -eq [char]0xFEFF) { return [string][char]0xFEFF + (Set-AiwbSegment $Text.Substring(1) $User $ProgramData) }
38
52
  $u = $User.ToLowerInvariant()
39
- $nl = "`r`n"; if ($Text.Length -gt 0 -and -not $Text.Contains("`r`n")) { $nl = "`n" }
40
- $lines = New-Object 'System.Collections.Generic.List[string]'
41
- if ($Text.Length -gt 0) { foreach ($l in ($Text -split "\r?\n")) { $lines.Add($l) } }
42
- if ($lines.Count -gt 0 -and $lines[$lines.Count - 1] -eq '') { $lines.RemoveAt($lines.Count - 1) }
43
- $begin = $lines.IndexOf("# aiwb-begin $u"); $end = -1
44
- if ($begin -ge 0) { $end = $lines.IndexOf("# aiwb-end $u", $begin + 1); if ($end -lt 0) { throw 'AW_REMOTE_ACCESS_SSHD_INVALID' } }
53
+ $lines = Get-AiwbLines $Text
54
+ $crlf = @($lines | Where-Object { $_.Eol -eq "`r`n" }).Count; $lf = @($lines | Where-Object { $_.Eol -eq "`n" }).Count
55
+ $nl = "`r`n"; if ($lf -gt $crlf) { $nl = "`n" }
56
+ $begin = -1; $end = -1
57
+ for ($i = 0; $i -lt $lines.Count; $i++) { if ($lines[$i].Content -ceq "# aiwb-begin $u") { $begin = $i; break } }
58
+ if ($begin -ge 0) {
59
+ for ($i = $begin + 1; $i -lt $lines.Count; $i++) { if ($lines[$i].Content -ceq "# aiwb-end $u") { $end = $i; break } }
60
+ if ($end -lt 0) { throw 'AW_REMOTE_ACCESS_SSHD_INVALID' }
61
+ }
45
62
  $segment = [string[]](Get-AiwbSegment $User $ProgramData)
63
+ $rest = $Text; $pos = -1
46
64
  if ($begin -ge 0) {
65
+ $s = $lines[$begin].Start; $e = $lines[$end].Start + $lines[$end].Content.Length + $lines[$end].Eol.Length
66
+ # 段在文件末尾且无结尾换行:连同它前面那个换行(插入时加的)一起去掉。
67
+ if ($lines[$end].Eol -eq '' -and $begin -gt 0) { $s -= $lines[$begin - 1].Eol.Length }
47
68
  $foreign = $false
48
- for ($i = 0; $i -lt $begin; $i++) { if ($lines[$i] -match '\A\s*Match\s' -and -not ($i -gt 0 -and $lines[$i - 1].StartsWith('# aiwb-begin '))) { $foreign = $true } }
49
- $lines.RemoveRange($begin, $end - $begin + 1)
50
- if (-not $foreign) { $lines.InsertRange($begin, $segment); return ($lines -join $nl) + $nl }
69
+ for ($i = 0; $i -lt $begin; $i++) { if ($lines[$i].Content -match '\A\s*Match\s' -and -not ($i -gt 0 -and $lines[$i - 1].Content.StartsWith('# aiwb-begin '))) { $foreign = $true } }
70
+ $rest = $Text.Remove($s, $e - $s)
71
+ if (-not $foreign) { $pos = $s }
72
+ }
73
+ if ($pos -lt 0) {
74
+ $pos = $rest.Length
75
+ foreach ($l in (Get-AiwbLines $rest)) { if ($l.Content -match '\A\s*Match\s' -or $l.Content.StartsWith('# aiwb-begin ')) { $pos = $l.Start; break } }
51
76
  }
52
- $at = $lines.Count
53
- for ($i = 0; $i -lt $lines.Count; $i++) { if ($lines[$i] -match '\A\s*Match\s' -or $lines[$i].StartsWith('# aiwb-begin ')) { $at = $i; break } }
54
- $lines.InsertRange($at, $segment)
55
- return ($lines -join $nl) + $nl
77
+ if ($pos -eq $rest.Length -and $rest.Length -gt 0 -and $rest[$rest.Length - 1] -ne [char]10) { $block = $nl + ($segment -join $nl) }
78
+ else { $block = ($segment -join $nl) + $nl }
79
+ return $rest.Insert($pos, $block)
56
80
  }
57
81
 
58
82
  # 以 SDDL 写所有者(SDDL 带 O: 时)与 DACL;SetAccessControl 只落给出的部分;D:P 为去继承。依据:.NET FileSystemSecurity.SetSecurityDescriptorSddlForm/File.SetAccessControl。
@@ -76,13 +100,11 @@ function Test-AiwbAdminOnly([string]$Path) {
76
100
  return $true
77
101
  }
78
102
 
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' }
103
+ # 开始前已存在的 ssh 目录、sshd_config、主机私钥、aiwb 目录与残留 *.tmp:须非重解析点(符号链接/junction)且只归管理员,否则内容不可信
104
+ # (普通用户可在 ProgramData 下预建 ssh 目录并写入 AuthorizedKeysCommand 等,或把 aiwb 建成 junction),不改权限继续用,报错整体撤回。
105
+ function Assert-AiwbAdminOnly([string]$Path) {
106
+ $item = Get-Item -LiteralPath $Path -Force
107
+ if (($item.Attributes -band [IO.FileAttributes]::ReparsePoint) -or -not (Test-AiwbAdminOnly $Path)) { throw 'AW_REMOTE_ACCESS_SSHD_INVALID' }
86
108
  }
87
109
 
88
110
  # OpenSSH Server 入站防火墙规则:FoD 建 OpenSSH-Server-In-TCP,官方 MSI 建 “OpenSSH SSH Server Preview (sshd)”(MSI 的 WixFirewallException)。
@@ -179,7 +201,7 @@ function Invoke-AiwbRemoteAccess([string]$User, [string]$Sid, [string]$Key) {
179
201
  $fwClosed = @()
180
202
  $backup = @{}
181
203
  foreach ($f in @($keys, $entry, $conf)) { if ([IO.File]::Exists($f)) { $backup[$f] = [IO.File]::ReadAllBytes($f) } else { $backup[$f] = $null } }
182
- $finished = $false; $code = 1
204
+ $finished = $false; $code = 1; $confTrusted = $false; $dirTrusted = $false
183
205
  try {
184
206
  if ($installed) {
185
207
  Install-AiwbSshd
@@ -188,15 +210,20 @@ function Invoke-AiwbRemoteAccess([string]$User, [string]$Sid, [string]$Key) {
188
210
  }
189
211
  $sshd = Get-AiwbSshdPath
190
212
  $bin = Split-Path -Parent $sshd
191
- # 从未启动过的 sshd 还没有 ProgramData\ssh 与 sshd_config:按 Win32-OpenSSH 自建该目录时的 SDDL 建目录,用安装目录的 sshd_config_default 作底本;已有的核验只归管理员。
213
+ # 从未启动过的 sshd 还没有 ProgramData\ssh 与 sshd_config:按 Win32-OpenSSH 自建该目录时的 SDDL 建目录,用安装目录的 sshd_config_default 作底本;已有的须只归管理员,否则撤回。
192
214
  if (-not (Test-Path -LiteralPath $sshDir)) {
193
215
  $sec = New-Object Security.AccessControl.DirectorySecurity
194
216
  $sec.SetSecurityDescriptorSddlForm('O:BAD:PAI(A;OICI;FA;;;SY)(A;OICI;FA;;;BA)(A;OICI;0x1200a9;;;AU)')
195
217
  [void][IO.Directory]::CreateDirectory($sshDir, $sec)
196
- } else { Repair-AiwbAdminOnly $sshDir 'O:BAD:PAI(A;OICI;FA;;;SY)(A;OICI;FA;;;BA)(A;OICI;0x1200a9;;;AU)' }
197
- if (-not [IO.File]::Exists($conf)) { Copy-Item -LiteralPath (Join-Path $bin 'sshd_config_default') -Destination $conf }
198
- Repair-AiwbAdminOnly $conf 'O:BAD:PAI(A;;FA;;;SY)(A;;FA;;;BA)(A;;0x1200a9;;;AU)'
199
- if (-not (Test-Path -LiteralPath $dir)) { New-Item -ItemType Directory -Path $dir | Out-Null }
218
+ } else { Assert-AiwbAdminOnly $sshDir }
219
+ # 存在性用 Get-Item 判(不跟随链接,悬空链接也算存在);核验过或本次新建后才允许撤回时改写对应位置。
220
+ if (Get-Item -LiteralPath $conf -Force -ErrorAction SilentlyContinue) { Assert-AiwbAdminOnly $conf } else { Copy-Item -LiteralPath (Join-Path $bin 'sshd_config_default') -Destination $conf }
221
+ $confTrusted = $true
222
+ if (Get-Item -LiteralPath $dir -Force -ErrorAction SilentlyContinue) {
223
+ Assert-AiwbAdminOnly $dir
224
+ foreach ($t in @("$keys.tmp", "$entry.tmp")) { if (Get-Item -LiteralPath $t -Force -ErrorAction SilentlyContinue) { Assert-AiwbAdminOnly $t } }
225
+ } else { New-Item -ItemType Directory -Path $dir | Out-Null }
226
+ $dirTrusted = $true
200
227
  # aiwb 目录:所有者 Administrators,SYSTEM/管理员完全控制,登录用户只可读本目录;钥匙与入口:所有者 Administrators,去继承,SYSTEM/管理员完全控制,本人只读。
201
228
  Set-AiwbAcl $dir 'O:BAD:PAI(A;OICI;FA;;;SY)(A;OICI;FA;;;BA)(A;;0x1200a9;;;AU)'
202
229
  if (-not (Test-AiwbAdminOnly $dir)) { throw 'AW_REMOTE_ACCESS_SSHD_INVALID' }
@@ -204,12 +231,14 @@ function Invoke-AiwbRemoteAccess([string]$User, [string]$Sid, [string]$Key) {
204
231
  Write-AiwbFile $keys "from=`"127.0.0.1,::1`",restrict,pty $Key`n" $fileAcl
205
232
  Write-AiwbFile $entry (Get-AiwbEntry) $fileAcl
206
233
  # 底本是当前文件(已有的,或上面刚从 sshd_config_default 复制的)。
207
- $text = [IO.File]::ReadAllText($conf, (New-Object Text.UTF8Encoding($false)))
234
+ # 按字节读写:UTF8Encoding($false).GetString 不剥 BOM(BOM 作为 U+FEFF 留在文本里,写回时原样编码),段外字节不变。
235
+ $utf8 = New-Object Text.UTF8Encoding($false)
236
+ $text = $utf8.GetString([IO.File]::ReadAllBytes($conf))
208
237
  # sshd_config 原地改写(保留其 ACL);sshd 只在下面 -t 通过后才(重)启动读取。
209
- [IO.File]::WriteAllText($conf, (Set-AiwbSegment $text $User $env:ProgramData), (New-Object Text.UTF8Encoding($false)))
210
- # 主机钥匙:已有私钥核验只归管理员;只补缺的默认类型(ssh-keygen -A),新生成的私钥收紧为 SYSTEM/管理员;撤回时保留(同 Mac)。
238
+ [IO.File]::WriteAllBytes($conf, $utf8.GetBytes((Set-AiwbSegment $text $User $env:ProgramData)))
239
+ # 主机钥匙:已有私钥须只归管理员(否则撤回);只补缺的默认类型(ssh-keygen -A),新生成的私钥收紧为 SYSTEM/管理员;撤回时保留(同 Mac)。
211
240
  $hostKeys = @(Get-ChildItem -LiteralPath $sshDir -Filter 'ssh_host_*_key' -ErrorAction SilentlyContinue | ForEach-Object { $_.FullName })
212
- foreach ($k in $hostKeys) { Repair-AiwbAdminOnly $k 'O:BAD:P(A;;FA;;;SY)(A;;FA;;;BA)' }
241
+ foreach ($k in $hostKeys) { Assert-AiwbAdminOnly $k }
213
242
  [void](Invoke-AiwbNative (Join-Path $bin 'ssh-keygen.exe') @('-A'))
214
243
  foreach ($k in @(Get-ChildItem -LiteralPath $sshDir -Filter 'ssh_host_*_key' -ErrorAction SilentlyContinue | ForEach-Object { $_.FullName })) {
215
244
  if ($hostKeys -notcontains $k) { Set-AiwbAcl $k 'O:BAD:P(A;;FA;;;SY)(A;;FA;;;BA)' }
@@ -228,7 +257,9 @@ function Invoke-AiwbRemoteAccess([string]$User, [string]$Sid, [string]$Key) {
228
257
  [Console]::Error.WriteLine([string]$_.Exception.Message)
229
258
  } finally {
230
259
  if (-not $finished) {
231
- foreach ($f in @($keys, $entry, $conf)) {
260
+ # 只改写核验过(或本次新建)的位置:不可信的 sshd_config / aiwb(如 junction)不经它写或删任何东西。
261
+ $restore = @(); if ($dirTrusted) { $restore += @($keys, $entry) }; if ($confTrusted) { $restore += $conf }
262
+ foreach ($f in $restore) {
232
263
  Remove-Item -LiteralPath "$f.tmp" -Force -ErrorAction SilentlyContinue
233
264
  if ($null -ne $backup[$f]) { [IO.File]::WriteAllBytes($f, [byte[]]$backup[$f]) } else { Remove-Item -LiteralPath $f -Force -ErrorAction SilentlyContinue }
234
265
  }
package/lib/network.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import type { Enrollment, NetworkEvent } from './ports.ts';
1
+ import type { Enrollment } from './ports.ts';
2
2
  import type { Result } from './api.ts';
3
3
  export interface NetworkSettings {
4
4
  executable?: string;
@@ -12,16 +12,4 @@ export interface NetworkSettings {
12
12
  httpMaxHeaderBytes?: number;
13
13
  controlMaxBytes?: number;
14
14
  }
15
- /**
16
- * N 控制端点(设计 A 表,N 的 Go 实现同名同算法、同测试向量):darwin `<runtimeDir>/control.sock`;
17
- * win32 命名管道 `\\.\pipe\aw-net-<hex>`,`<hex>` = sha256(runtimeDir 的 UTF-8,原样大小写) 前 32 位小写十六进制。
18
- */
19
- export declare function controlEndpoint(runtimeDir: string, platform?: string): string;
20
15
  export declare function writeNetworkConfig(file: string, e: Enrollment, s: NetworkSettings): Promise<Result<void>>;
21
- export declare function createNetworkClient(s: NetworkSettings): {
22
- connect(e: Enrollment, signal: AbortSignal): Promise<Result<{
23
- proxyCommand: string;
24
- }>>;
25
- onState(listener: (event: NetworkEvent) => void): () => void;
26
- dispose(): void;
27
- };
package/lib/network.js CHANGED
@@ -1,20 +1,10 @@
1
- import { request } from 'node:http';
2
- import { lstat, writeFile, rename, rm } from 'node:fs/promises';
1
+ import { writeFile, rename, rm } from 'node:fs/promises';
3
2
  import { join, dirname, isAbsolute } from 'node:path';
4
- import { randomUUID, createHash } from 'node:crypto';
5
- import { need, dependency, ok, fail, NeedError } from "./needs.js";
6
- import { privateDirectory, checkPrivateDirectory, sealPrivate, host } from "./private-files.js";
3
+ import { randomUUID } from 'node:crypto';
4
+ import { dependency, ok, fail } from "./needs.js";
5
+ import { privateDirectory, sealPrivate } from "./private-files.js";
7
6
  import { nodeName } from "./node-name.js";
8
- import { proxyCommand } from "./ssh.js";
9
- /**
10
- * N 控制端点(设计 A 表,N 的 Go 实现同名同算法、同测试向量):darwin `<runtimeDir>/control.sock`;
11
- * win32 命名管道 `\\.\pipe\aw-net-<hex>`,`<hex>` = sha256(runtimeDir 的 UTF-8,原样大小写) 前 32 位小写十六进制。
12
- */
13
- export function controlEndpoint(runtimeDir, platform = host.platform) {
14
- return platform === 'win32' ? '\\\\.\\pipe\\aw-net-' + createHash('sha256').update(runtimeDir, 'utf8').digest('hex').slice(0, 32) : join(runtimeDir, 'control.sock');
15
- }
16
7
  function valid(s) { return [s.executable, s.runtimeDir, s.stateDir].every(p => typeof p === 'string' && isAbsolute(p) && !/[\x00-\x1f\x7f]/.test(p)) && s.logUpload === false && [s.statusRefreshIntervalSeconds, s.dialTimeoutSeconds, s.headerTimeoutSeconds, s.enrollmentObservationSeconds].every(n => typeof n === 'number' && Number.isFinite(n) && n >= 1e-9 && n <= 9223372036) && [s.statusRefreshIntervalSeconds, s.headerTimeoutSeconds].every(n => Number.isInteger(n * 1000) && n * 1000 >= 1 && n * 1000 <= 2147483647) && [s.httpMaxHeaderBytes].every(n => Number.isSafeInteger(n) && n > 0) && Number.isSafeInteger(s.controlMaxBytes) && s.controlMaxBytes > 0 && s.controlMaxBytes <= 2147483647; }
17
- function mapped(code) { return { NEED_ENROLLMENT: 'ENROLLMENT_REQUIRED', ENROLLMENT_REJECTED: 'ENROLLMENT_REJECTED', ENROLLMENT_KEY_REJECTED: 'ENROLLMENT_KEY_REJECTED', LOCAL_STATE_INVALID: 'ENROLLMENT_INVALID', HOST_OFFLINE: 'HOST_OFFLINE', HOST_NOT_VISIBLE: 'DEPENDENCY_REQUIRED', CONFIG_INVALID: 'SETTINGS_REQUIRED', CAPABILITY_NOT_IMPLEMENTED: 'DEPENDENCY_REQUIRED', NEED_HOST_CONTRACT: 'DEPENDENCY_REQUIRED', NETWORK_INTERRUPTED: 'CONNECTION_LOST', CONTROL_UNAVAILABLE: 'DEPENDENCY_REQUIRED' }[String(code)] ?? 'DEPENDENCY_REQUIRED'; }
18
8
  export async function writeNetworkConfig(file, e, s) {
19
9
  if (!valid(s) || !isAbsolute(file))
20
10
  return fail('SETTINGS_REQUIRED');
@@ -37,119 +27,3 @@ export async function writeNetworkConfig(file, e, s) {
37
27
  await rm(temp, { force: true });
38
28
  }
39
29
  }
40
- export function createNetworkClient(s) {
41
- const listeners = new Set();
42
- let timer, previous, refreshing = false, disposed = false;
43
- const pending = new Set();
44
- let expected;
45
- const bad = (code) => { throw new NeedError(need(code)); };
46
- async function socket() {
47
- if (!valid(s))
48
- bad('SETTINGS_REQUIRED');
49
- // win32:控制端点是命名管道(N 以只许本人与 SYSTEM 的 SDDL 建首实例),这里核 runtimeDir 私有。
50
- if (host.platform === 'win32') {
51
- await checkPrivateDirectory(s.runtimeDir);
52
- return;
53
- }
54
- const dir = await lstat(s.runtimeDir), sock = await lstat(join(s.runtimeDir, 'control.sock'));
55
- if (!dir.isDirectory() || dir.isSymbolicLink() || dir.uid !== process.getuid() || (dir.mode & 0o077) || !sock.isSocket() || sock.isSymbolicLink() || sock.uid !== process.getuid() || (sock.mode & 0o177))
56
- bad('DEPENDENCY_REQUIRED');
57
- }
58
- async function send(method, path, signal) {
59
- try {
60
- await socket();
61
- }
62
- catch (e) {
63
- if (e instanceof NeedError)
64
- throw e;
65
- bad('DEPENDENCY_REQUIRED');
66
- }
67
- if (disposed || signal.aborted)
68
- bad('CONNECTION_LOST');
69
- return new Promise((resolve, reject) => { const req = request({ socketPath: controlEndpoint(s.runtimeDir), path, method, signal, agent: false }, response => { clearTimeout(deadline); resolve(response); }); const deadline = setTimeout(() => req.destroy(new Error('CONTROL_HEADER_TIMEOUT')), s.headerTimeoutSeconds * 1000); req.on('error', () => { clearTimeout(deadline); reject(new NeedError(need('DEPENDENCY_REQUIRED'))); }); req.end(); });
70
- }
71
- async function json(res) { let size = 0; const chunks = []; try {
72
- for await (const chunk of res) {
73
- size += chunk.length;
74
- if (size > s.controlMaxBytes)
75
- bad('DEPENDENCY_REQUIRED');
76
- chunks.push(chunk);
77
- }
78
- return JSON.parse(Buffer.concat(chunks).toString('utf8'));
79
- }
80
- catch {
81
- res.destroy();
82
- bad('DEPENDENCY_REQUIRED');
83
- } }
84
- async function status(signal) {
85
- try {
86
- const res = await send('GET', '/v1/status', signal), v = await json(res);
87
- if (v?.apiVersion !== 1)
88
- return dependency('N v1 状态协议');
89
- if (res.statusCode !== 200 || v.error) {
90
- const result = fail(mapped(v.error?.code));
91
- if (!result.ok && result.error.code === 'HOST_OFFLINE' && v.host?.name === expected?.host && typeof v.host.lastSeenAt === 'string' && !Number.isNaN(Date.parse(v.host.lastSeenAt)))
92
- result.error.lastSeen = v.host.lastSeenAt;
93
- return result;
94
- }
95
- if (v.enrollment !== 'online')
96
- return fail(v.enrollment === 'needs_enrollment' ? 'ENROLLMENT_REQUIRED' : v.enrollment === 'rejected' ? 'ENROLLMENT_REJECTED' : 'CONNECTION_LOST');
97
- if (v.host?.name !== expected?.host)
98
- return dependency('与开通主机匹配的 N 状态');
99
- if (v.host.online === false) {
100
- const result = fail('HOST_OFFLINE');
101
- if (!result.ok && typeof v.host.lastSeenAt === 'string' && !Number.isNaN(Date.parse(v.host.lastSeenAt)))
102
- result.error.lastSeen = v.host.lastSeenAt;
103
- return result;
104
- }
105
- if (v.host.online !== true)
106
- return dependency('N 已核实的主机在线状态');
107
- return ok(undefined);
108
- }
109
- catch (e) {
110
- return e instanceof NeedError ? { ok: false, error: e.need } : dependency('N 私有控制 socket;未使用直连网络');
111
- }
112
- }
113
- async function refresh() { if (refreshing || !expected || disposed)
114
- return; refreshing = true; const c = new AbortController(); pending.add(c); try {
115
- const r = await status(c.signal), online = r.ok;
116
- if (previous !== undefined && previous !== online)
117
- for (const listener of listeners)
118
- listener({ kind: online ? 'restored' : 'lost' });
119
- previous = online;
120
- }
121
- finally {
122
- pending.delete(c);
123
- refreshing = false;
124
- } }
125
- return {
126
- async connect(e, signal) {
127
- expected = e;
128
- const result = await status(signal);
129
- previous = result.ok;
130
- if (!result.ok)
131
- return result;
132
- try {
133
- const exe = await lstat(s.executable);
134
- if (!exe.isFile() || exe.isSymbolicLink() || host.platform !== 'win32' && !(exe.mode & 0o111))
135
- return dependency('N 真实 helper 可执行程序');
136
- return ok({ proxyCommand: proxyCommand(s.executable, s.runtimeDir) });
137
- }
138
- catch {
139
- return dependency('N 真实 helper 可执行程序');
140
- }
141
- },
142
- onState(listener) { listeners.add(listener); if (valid(s) && !timer) {
143
- timer = setInterval(() => { void refresh(); }, s.statusRefreshIntervalSeconds * 1000);
144
- timer.unref();
145
- } return () => { listeners.delete(listener); if (!listeners.size && timer) {
146
- clearInterval(timer);
147
- timer = undefined;
148
- for (const c of pending)
149
- c.abort();
150
- } }; },
151
- dispose() { disposed = true; if (timer)
152
- clearInterval(timer); for (const c of pending)
153
- c.abort(); listeners.clear(); },
154
- };
155
- }
@@ -23,18 +23,23 @@ export declare function adminCommand(script: string, user: string, key: string):
23
23
  /** Windows 本人一段规则(与 helper/remote-access.ps1 Get-AiwbSegment 同文)。 */
24
24
  export declare function windowsSegment(user: string, programData: string): string[];
25
25
  /**
26
- * 与 remote-access.ps1 Set-AiwbSegment 同算法:已有本人段且它之前没有非本插件的 Match 行 → 原位整段替换;
27
- * 否则(没有,或被挪到别的 Match 之后)去掉旧段,插在第一个 Match 行(或其他员工段的开始标记)之前、全局设置之后。有头无尾返回 undefined。
26
+ * 与 remote-access.ps1 Set-AiwbSegment 同算法,段外字节原样保留(各行换行、末尾有无换行、BOM):已有本人段且它之前没有非本插件的 Match 行 → 原位整段替换;
27
+ * 否则去掉旧段,插在第一个 Match 行(或其他员工段的开始标记)行首;没有 Match 放末尾。本人段用占多数的换行(相同或没有时 CRLF);
28
+ * 放在无结尾换行的文件末尾时写成“换行 + 段”且不带结尾换行。有头无尾返回 undefined。
28
29
  */
29
30
  export declare function windowsSetSegment(text: string, user: string, programData: string): string | undefined;
30
31
  /** sshd_config 里本人段内容与位置都符合(再写一次不会变)。 */
31
32
  export declare function windowsSegmentOk(text: string | undefined, user: string, programData: string): boolean;
33
+ /** 本版开通脚本(内联执行时)写入 entry.ps1 的确切内容:Get-AiwbEntry 的 here-string 正文(行已去缩进,行间 \n,无结尾换行)。 */
34
+ export declare function windowsEntry(script: string): string | undefined;
32
35
  /** 内联进 -EncodedCommand 的脚本正文:去掉整行注释、空行与行首缩进(只为缩短命令行,语句不变)。 */
33
36
  export declare function inlineScript(script: string): string;
34
37
  /**
35
- * -EncodedCommand 的内层正文:校验过的三个常量 + 一小段引导,引导把 gzip 后 base64 内联的脚本(UTF-8)在内存里解压,
38
+ * -EncodedCommand 的内层正文:校验过的三个常量 + 一小段引导,引导把 gzip 后内联的脚本(UTF-8)在内存里解压,
36
39
  * 以 scriptblock 在同一作用域执行(脚本末尾 exit 即进程退出码)。只为缩短命令行(CreateProcess/ShellExecuteEx 上限 32767 字符),
37
40
  * 脚本语句不变、仍整段内联、不落盘。依据:.NET IO.Compression.GZipStream(RFC 1952,Node zlib.gzipSync 同格式)。
41
+ * gzip 字节按“一字节一字符”内联为 U+0100–U+01FF(不含任何引号字符):-EncodedCommand 本身已是 UTF-16 的 base64,
42
+ * 再套一层 base64 会让载荷多三分之一。
38
43
  */
39
44
  export declare function windowsAdminBody(script: string, user: string, sid: string, key: string): string;
40
45
  /** Windows PowerShell 命令行(CreateProcess)上限 32767 字符;断言与回报按其一半留余量。 */
@@ -73,6 +78,11 @@ interface RemoteAccessOptions {
73
78
  }
74
79
  /** 系统设置“共享 → 远程登录”详情面板的官方深链接(含“允许远程用户完全磁盘访问”开关;该开关属 TCC,只能本人点开)。 */
75
80
  export declare const REMOTE_LOGIN_SETTINGS = "x-apple.systempreferences:com.apple.Sharing-Settings.extension?Services_RemoteLogin";
81
+ /** Windows 规则判定:本人段符合(windowsSegmentOk)且 entry.ps1 内容等于本版脚本写入的内容(windowsEntry)。 */
82
+ export declare function windowsRulesOk(local: {
83
+ config?: string;
84
+ entry?: string;
85
+ }, user: string, programData: string, entryText: string | undefined): boolean;
76
86
  export declare function createRemoteAccess(options: RemoteAccessOptions): {
77
87
  sync(target: SshTarget, signal: AbortSignal): Promise<void>;
78
88
  /** 登记内容可能变了(如工具桥服务晚于本插件出现):等进行中的一次结束后再登记一次。 */
@@ -45,45 +45,72 @@ export function windowsSegment(user, programData) {
45
45
  const u = user.toLowerCase();
46
46
  return [`# aiwb-begin ${u}`, `Match User ${u}`, ` AuthorizedKeysFile __PROGRAMDATA__/ssh/aiwb/${u}.keys`, ' AuthenticationMethods publickey', ' AcceptEnv AW_EMP_CWD', ` ForceCommand powershell.exe -NoProfile -NonInteractive -ExecutionPolicy Bypass -File "${programData}\\ssh\\aiwb\\entry.ps1"`, `# aiwb-end ${u}`];
47
47
  }
48
+ /** 按行切分并保留每行原有换行(CRLF/LF/末行无换行),与 remote-access.ps1 Get-AiwbLines 同。 */
49
+ function lines(text) { const out = []; for (const m of text.matchAll(/([^\r\n]*)(\r\n|\n)?/g)) {
50
+ if (m[0].length === 0 && m.index >= text.length)
51
+ break;
52
+ out.push({ start: m.index, content: m[1], eol: m[2] ?? '' });
53
+ } return out; }
48
54
  /**
49
- * 与 remote-access.ps1 Set-AiwbSegment 同算法:已有本人段且它之前没有非本插件的 Match 行 → 原位整段替换;
50
- * 否则(没有,或被挪到别的 Match 之后)去掉旧段,插在第一个 Match 行(或其他员工段的开始标记)之前、全局设置之后。有头无尾返回 undefined。
55
+ * 与 remote-access.ps1 Set-AiwbSegment 同算法,段外字节原样保留(各行换行、末尾有无换行、BOM):已有本人段且它之前没有非本插件的 Match 行 → 原位整段替换;
56
+ * 否则去掉旧段,插在第一个 Match 行(或其他员工段的开始标记)行首;没有 Match 放末尾。本人段用占多数的换行(相同或没有时 CRLF);
57
+ * 放在无结尾换行的文件末尾时写成“换行 + 段”且不带结尾换行。有头无尾返回 undefined。
51
58
  */
52
59
  export function windowsSetSegment(text, user, programData) {
53
- const u = user.toLowerCase(), nl = text.length > 0 && !text.includes('\r\n') ? '\n' : '\r\n';
54
- const lines = text.length > 0 ? text.split(/\r?\n/) : [];
55
- if (lines.length && lines.at(-1) === '')
56
- lines.pop();
57
- const begin = lines.indexOf(`# aiwb-begin ${u}`), end = begin < 0 ? -1 : lines.indexOf(`# aiwb-end ${u}`, begin + 1);
60
+ // BOM 原样留在最前,其余按无 BOM 文本处理。
61
+ if (text.startsWith('\uFEFF')) {
62
+ const out = windowsSetSegment(text.slice(1), user, programData);
63
+ return out === undefined ? undefined : '\uFEFF' + out;
64
+ }
65
+ const u = user.toLowerCase(), all = lines(text);
66
+ const crlf = all.filter(l => l.eol === '\r\n').length, lf = all.filter(l => l.eol === '\n').length, nl = lf > crlf ? '\n' : '\r\n';
67
+ const begin = all.findIndex(l => l.content === `# aiwb-begin ${u}`), end = begin < 0 ? -1 : all.findIndex((l, i) => i > begin && l.content === `# aiwb-end ${u}`);
58
68
  if (begin >= 0 && end < 0)
59
69
  return undefined;
60
- const foreign = (i) => /^\s*Match\s/i.test(lines[i]) && !(i > 0 && lines[i - 1].startsWith('# aiwb-begin '));
61
70
  const segment = windowsSegment(user, programData);
62
- if (begin >= 0 && !lines.slice(0, begin).some((_, i) => foreign(i))) {
63
- lines.splice(begin, end - begin + 1, ...segment);
64
- return lines.join(nl) + nl;
71
+ let rest = text, pos = -1;
72
+ if (begin >= 0) {
73
+ let s = all[begin].start;
74
+ const e = all[end].start + all[end].content.length + all[end].eol.length;
75
+ if (all[end].eol === '' && begin > 0)
76
+ s -= all[begin - 1].eol.length;
77
+ const foreign = all.slice(0, begin).some((l, i) => /^\s*Match\s/i.test(l.content) && !(i > 0 && all[i - 1].content.startsWith('# aiwb-begin ')));
78
+ rest = text.slice(0, s) + text.slice(e);
79
+ if (!foreign)
80
+ pos = s;
81
+ }
82
+ if (pos < 0) {
83
+ pos = rest.length;
84
+ const hit = lines(rest).find(l => /^\s*Match\s/i.test(l.content) || l.content.startsWith('# aiwb-begin '));
85
+ if (hit)
86
+ pos = hit.start;
65
87
  }
66
- if (begin >= 0)
67
- lines.splice(begin, end - begin + 1);
68
- let at = lines.findIndex(line => /^\s*Match\s/i.test(line) || line.startsWith('# aiwb-begin '));
69
- if (at < 0)
70
- at = lines.length;
71
- lines.splice(at, 0, ...segment);
72
- return lines.join(nl) + nl;
88
+ const block = pos === rest.length && rest.length > 0 && !rest.endsWith('\n') ? nl + segment.join(nl) : segment.join(nl) + nl;
89
+ return rest.slice(0, pos) + block + rest.slice(pos);
73
90
  }
74
91
  /** sshd_config 里本人段内容与位置都符合(再写一次不会变)。 */
75
92
  export function windowsSegmentOk(text, user, programData) { return text !== undefined && windowsSetSegment(text, user, programData) === text; }
93
+ /** 本版开通脚本(内联执行时)写入 entry.ps1 的确切内容:Get-AiwbEntry 的 here-string 正文(行已去缩进,行间 \n,无结尾换行)。 */
94
+ export function windowsEntry(script) {
95
+ const inline = inlineScript(script), start = inline.indexOf("function Get-AiwbEntry {\nreturn @'\n");
96
+ if (start < 0)
97
+ return undefined;
98
+ const from = start + "function Get-AiwbEntry {\nreturn @'\n".length, end = inline.indexOf("\n'@", from);
99
+ return end < 0 ? undefined : inline.slice(from, end);
100
+ }
76
101
  /** 内联进 -EncodedCommand 的脚本正文:去掉整行注释、空行与行首缩进(只为缩短命令行,语句不变)。 */
77
102
  export function inlineScript(script) { return script.split(/\r?\n/).map(line => line.trim()).filter(line => line && !line.startsWith('#')).join('\n'); }
78
103
  const psLiteral = (value) => "'" + value.replaceAll(/['\u2018\u2019\u201A\u201B]/g, match => match + match) + "'";
79
104
  /**
80
- * -EncodedCommand 的内层正文:校验过的三个常量 + 一小段引导,引导把 gzip 后 base64 内联的脚本(UTF-8)在内存里解压,
105
+ * -EncodedCommand 的内层正文:校验过的三个常量 + 一小段引导,引导把 gzip 后内联的脚本(UTF-8)在内存里解压,
81
106
  * 以 scriptblock 在同一作用域执行(脚本末尾 exit 即进程退出码)。只为缩短命令行(CreateProcess/ShellExecuteEx 上限 32767 字符),
82
107
  * 脚本语句不变、仍整段内联、不落盘。依据:.NET IO.Compression.GZipStream(RFC 1952,Node zlib.gzipSync 同格式)。
108
+ * gzip 字节按“一字节一字符”内联为 U+0100–U+01FF(不含任何引号字符):-EncodedCommand 本身已是 UTF-16 的 base64,
109
+ * 再套一层 base64 会让载荷多三分之一。
83
110
  */
84
111
  export function windowsAdminBody(script, user, sid, key) {
85
- const packed = gzipSync(Buffer.from(inlineScript(script), 'utf8'), { level: 9 }).toString('base64');
86
- return `$AiwbUser=${psLiteral(user)};$AiwbSid=${psLiteral(sid)};$AiwbKey=${psLiteral(key)};$z=New-Object IO.Compression.GZipStream((New-Object IO.MemoryStream(,[Convert]::FromBase64String('${packed}'))),[IO.Compression.CompressionMode]::Decompress);$t=(New-Object IO.StreamReader($z,[Text.Encoding]::UTF8)).ReadToEnd();. ([scriptblock]::Create($t))`;
112
+ const packed = [...gzipSync(Buffer.from(inlineScript(script), 'utf8'), { level: 9 })].map(b => String.fromCharCode(0x100 + b)).join('');
113
+ return `$AiwbUser=${psLiteral(user)};$AiwbSid=${psLiteral(sid)};$AiwbKey=${psLiteral(key)};$z=New-Object IO.Compression.GZipStream((New-Object IO.MemoryStream(,[byte[]]@('${packed}'.ToCharArray()|ForEach-Object{[int]$_-256}))),[IO.Compression.CompressionMode]::Decompress);$t=(New-Object IO.StreamReader($z,[Text.Encoding]::UTF8)).ReadToEnd();. ([scriptblock]::Create($t))`;
87
114
  }
88
115
  /** Windows PowerShell 命令行(CreateProcess)上限 32767 字符;断言与回报按其一半留余量。 */
89
116
  export const WINDOWS_COMMAND_LINE_MAX = 32767;
@@ -146,14 +173,20 @@ catch (error) {
146
173
  return undefined;
147
174
  throw error;
148
175
  } };
149
- const windowsLocalAccess = (timeoutMs) => async (user) => {
176
+ // 规则在:sshd_config 本人段内容与位置都符合,且 entry.ps1 与本版脚本要写的内容逐字一致(插件升级后入口变了就再授权一次)。
177
+ const windowsLocalAccess = (timeoutMs, entryText) => async (user) => {
150
178
  const programData = process.env.ProgramData;
151
179
  if (!programData || !win32.isAbsolute(programData))
152
180
  throw Error('PROGRAMDATA_REQUIRED');
153
181
  const keys = await readOptional(win32.join(programData, 'ssh', 'aiwb', user.toLowerCase() + '.keys'));
154
182
  const config = await readOptional(win32.join(programData, 'ssh', 'sshd_config'));
155
- return { keys, sshdLoaded: await listening(timeoutMs), confExists: windowsSegmentOk(config, user, programData) };
183
+ const entry = await readOptional(win32.join(programData, 'ssh', 'aiwb', 'entry.ps1'));
184
+ return { keys, sshdLoaded: await listening(timeoutMs), confExists: windowsRulesOk({ config, entry }, user, programData, entryText) };
156
185
  };
186
+ /** Windows 规则判定:本人段符合(windowsSegmentOk)且 entry.ps1 内容等于本版脚本写入的内容(windowsEntry)。 */
187
+ export function windowsRulesOk(local, user, programData, entryText) {
188
+ return windowsSegmentOk(local.config, user, programData) && entryText !== undefined && local.entry === entryText;
189
+ }
157
190
  // 外层 powershell 以 UAC 结果退出:0 成功,1223 用户拒绝,其余失败。
158
191
  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 }); }));
159
192
  export function createRemoteAccess(options) {
@@ -183,9 +216,11 @@ export function createRemoteAccess(options) {
183
216
  return;
184
217
  }
185
218
  const windows = platform === 'win32';
186
- if (!needsSetup(await (options.localAccess ?? (windows ? windowsLocalAccess(options.listenTimeoutMs ?? NETWORK_DEFAULTS.dialTimeoutSeconds * 1000) : localAccess))(options.user), key))
219
+ // Windows 先读本版脚本:检测要比对 entry.ps1 内容;macOS 仍只在需要开通时才读。
220
+ const winBody = windows ? await (options.script ?? windowsScript)() : undefined;
221
+ if (!needsSetup(await (options.localAccess ?? (windows ? windowsLocalAccess(options.listenTimeoutMs ?? NETWORK_DEFAULTS.dialTimeoutSeconds * 1000, windowsEntry(winBody)) : localAccess))(options.user), key))
187
222
  return;
188
- const admin = windows ? windowsAdminCommand(await (options.script ?? windowsScript)(), options.user, (options.sid ?? (() => windowsSecurity.sid()))(), key) : adminCommand(await (options.script ?? script)(), options.user, key);
223
+ const admin = windows ? windowsAdminCommand(winBody, options.user, (options.sid ?? (() => windowsSecurity.sid()))(), key) : adminCommand(await (options.script ?? script)(), options.user, key);
189
224
  const result = await (options.runAdmin ?? (windows ? windowsRunAdmin : runAdmin))(admin.command, admin.args);
190
225
  if (!result.ok) {
191
226
  declined = true;
package/lib/ssh.d.ts CHANGED
@@ -1,7 +1,6 @@
1
1
  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
- export declare function proxyCommand(binary: string, runtimeDir: string): string;
5
4
  /**
6
5
  * Windows:Win32-OpenSSH 8.6 在 ProxyCommand 失败、ssh 自身 stderr 为管道且未给 -E 时不退出(N 合同 Windows 节,实机复现);
7
6
  * 加 `-E <L 私有信任目录内 ssh.log>`(ssh 自身诊断追加写入该文件,X 等消费方可读;不用 NUL 以保留诊断)。macOS 不变。
package/lib/ssh.js CHANGED
@@ -9,11 +9,6 @@ export function shellQuote(s) {
9
9
  throw new Error('INVALID_PROXY_PATH');
10
10
  return "'" + s.replaceAll("'", "'\\''") + "'";
11
11
  }
12
- export function proxyCommand(binary, runtimeDir) {
13
- if (!binary.startsWith('/') || !runtimeDir.startsWith('/'))
14
- throw new Error('ABSOLUTE_PROXY_PATH_REQUIRED');
15
- return `${shellQuote(binary)} ssh-proxy --runtime-dir ${shellQuote(runtimeDir)} %h %p`;
16
- }
17
12
  /**
18
13
  * Windows:Win32-OpenSSH 8.6 在 ProxyCommand 失败、ssh 自身 stderr 为管道且未给 -E 时不退出(N 合同 Windows 节,实机复现);
19
14
  * 加 `-E <L 私有信任目录内 ssh.log>`(ssh 自身诊断追加写入该文件,X 等消费方可读;不用 NUL 以保留诊断)。macOS 不变。
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ai-workbench/connect",
3
- "version": "0.7.55-rc.5",
3
+ "version": "0.7.55-rc.7",
4
4
  "type": "module",
5
5
  "engines": {
6
6
  "node": ">=24.13.1",