@ai-workbench/connect 0.7.55-rc.4 → 0.7.55-rc.6

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,下载复核一致)。
@@ -76,13 +76,11 @@ function Test-AiwbAdminOnly([string]$Path) {
76
76
  return $true
77
77
  }
78
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' }
79
+ # 开始前已存在的 ssh 目录、sshd_config、主机私钥、aiwb 目录与残留 *.tmp:须非重解析点(符号链接/junction)且只归管理员,否则内容不可信
80
+ # (普通用户可在 ProgramData 下预建 ssh 目录并写入 AuthorizedKeysCommand 等,或把 aiwb 建成 junction),不改权限继续用,报错整体撤回。
81
+ function Assert-AiwbAdminOnly([string]$Path) {
82
+ $item = Get-Item -LiteralPath $Path -Force
83
+ if (($item.Attributes -band [IO.FileAttributes]::ReparsePoint) -or -not (Test-AiwbAdminOnly $Path)) { throw 'AW_REMOTE_ACCESS_SSHD_INVALID' }
86
84
  }
87
85
 
88
86
  # OpenSSH Server 入站防火墙规则:FoD 建 OpenSSH-Server-In-TCP,官方 MSI 建 “OpenSSH SSH Server Preview (sshd)”(MSI 的 WixFirewallException)。
@@ -99,7 +97,9 @@ function Write-AiwbFile([string]$Path, [string]$Text, [string]$Sddl) {
99
97
  }
100
98
 
101
99
  # entry.ps1(ForceCommand):cd 到 AW_EMP_CWD(失败回 $HOME);shell 选法同 DSH pwsh-local(PowerShell 7 安装位置 → PATH 中 pwsh.exe → Windows PowerShell 5.1);
102
- # 有 SSH_ORIGINAL_COMMAND 则先固定 UTF-8 输出(同 DSH pwsh-local 的前缀)再以 -EncodedCommand 执行并透传退出码,无则交互;stdin 原样继承。
100
+ # 有 SSH_ORIGINAL_COMMAND 则先关进度流、固定 UTF-8 输出(DSH pwsh-local 的前缀)再以 -EncodedCommand 执行并透传退出码,无则交互;stdin 原样继承。
101
+ # 关进度流:stderr 被管道重定向时,Windows PowerShell 5.1 把进度记录(如模块自动加载的“正在准备首次使用模块”)序列化成 CLIXML 写到 stderr,
102
+ # 混入主机 agent 读到的输出;在内层命令前设 $ProgressPreference='SilentlyContinue'(about_Preference_Variables)即不再产生(实机:外层设无效、内层设即无)。
103
103
  function Get-AiwbEntry {
104
104
  return @'
105
105
  $ErrorActionPreference = 'Continue'
@@ -112,7 +112,7 @@ $candidates += "$env:SystemRoot\System32\WindowsPowerShell\v1.0\powershell.exe"
112
112
  $shell = 'pwsh'
113
113
  foreach ($c in $candidates) { if ([IO.File]::Exists($c)) { $shell = $c; break } }
114
114
  if ($env:SSH_ORIGINAL_COMMAND) {
115
- $pre = '[Console]::OutputEncoding = [System.Text.UTF8Encoding]::new($false); $OutputEncoding = [System.Text.UTF8Encoding]::new($false); '
115
+ $pre = '$ProgressPreference = ''SilentlyContinue''; [Console]::OutputEncoding = [System.Text.UTF8Encoding]::new($false); $OutputEncoding = [System.Text.UTF8Encoding]::new($false); '
116
116
  $enc = [Convert]::ToBase64String([Text.Encoding]::Unicode.GetBytes($pre + $env:SSH_ORIGINAL_COMMAND))
117
117
  & $shell -NoLogo -NoProfile -NonInteractive -EncodedCommand $enc
118
118
  exit $LASTEXITCODE
@@ -177,7 +177,7 @@ function Invoke-AiwbRemoteAccess([string]$User, [string]$Sid, [string]$Key) {
177
177
  $fwClosed = @()
178
178
  $backup = @{}
179
179
  foreach ($f in @($keys, $entry, $conf)) { if ([IO.File]::Exists($f)) { $backup[$f] = [IO.File]::ReadAllBytes($f) } else { $backup[$f] = $null } }
180
- $finished = $false; $code = 1
180
+ $finished = $false; $code = 1; $confTrusted = $false; $dirTrusted = $false
181
181
  try {
182
182
  if ($installed) {
183
183
  Install-AiwbSshd
@@ -186,15 +186,20 @@ function Invoke-AiwbRemoteAccess([string]$User, [string]$Sid, [string]$Key) {
186
186
  }
187
187
  $sshd = Get-AiwbSshdPath
188
188
  $bin = Split-Path -Parent $sshd
189
- # 从未启动过的 sshd 还没有 ProgramData\ssh 与 sshd_config:按 Win32-OpenSSH 自建该目录时的 SDDL 建目录,用安装目录的 sshd_config_default 作底本;已有的核验只归管理员。
189
+ # 从未启动过的 sshd 还没有 ProgramData\ssh 与 sshd_config:按 Win32-OpenSSH 自建该目录时的 SDDL 建目录,用安装目录的 sshd_config_default 作底本;已有的须只归管理员,否则撤回。
190
190
  if (-not (Test-Path -LiteralPath $sshDir)) {
191
191
  $sec = New-Object Security.AccessControl.DirectorySecurity
192
192
  $sec.SetSecurityDescriptorSddlForm('O:BAD:PAI(A;OICI;FA;;;SY)(A;OICI;FA;;;BA)(A;OICI;0x1200a9;;;AU)')
193
193
  [void][IO.Directory]::CreateDirectory($sshDir, $sec)
194
- } else { Repair-AiwbAdminOnly $sshDir 'O:BAD:PAI(A;OICI;FA;;;SY)(A;OICI;FA;;;BA)(A;OICI;0x1200a9;;;AU)' }
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)'
197
- if (-not (Test-Path -LiteralPath $dir)) { New-Item -ItemType Directory -Path $dir | Out-Null }
194
+ } else { Assert-AiwbAdminOnly $sshDir }
195
+ # 存在性用 Get-Item 判(不跟随链接,悬空链接也算存在);核验过或本次新建后才允许撤回时改写对应位置。
196
+ if (Get-Item -LiteralPath $conf -Force -ErrorAction SilentlyContinue) { Assert-AiwbAdminOnly $conf } else { Copy-Item -LiteralPath (Join-Path $bin 'sshd_config_default') -Destination $conf }
197
+ $confTrusted = $true
198
+ if (Get-Item -LiteralPath $dir -Force -ErrorAction SilentlyContinue) {
199
+ Assert-AiwbAdminOnly $dir
200
+ foreach ($t in @("$keys.tmp", "$entry.tmp")) { if (Get-Item -LiteralPath $t -Force -ErrorAction SilentlyContinue) { Assert-AiwbAdminOnly $t } }
201
+ } else { New-Item -ItemType Directory -Path $dir | Out-Null }
202
+ $dirTrusted = $true
198
203
  # aiwb 目录:所有者 Administrators,SYSTEM/管理员完全控制,登录用户只可读本目录;钥匙与入口:所有者 Administrators,去继承,SYSTEM/管理员完全控制,本人只读。
199
204
  Set-AiwbAcl $dir 'O:BAD:PAI(A;OICI;FA;;;SY)(A;OICI;FA;;;BA)(A;;0x1200a9;;;AU)'
200
205
  if (-not (Test-AiwbAdminOnly $dir)) { throw 'AW_REMOTE_ACCESS_SSHD_INVALID' }
@@ -205,9 +210,9 @@ function Invoke-AiwbRemoteAccess([string]$User, [string]$Sid, [string]$Key) {
205
210
  $text = [IO.File]::ReadAllText($conf, (New-Object Text.UTF8Encoding($false)))
206
211
  # sshd_config 原地改写(保留其 ACL);sshd 只在下面 -t 通过后才(重)启动读取。
207
212
  [IO.File]::WriteAllText($conf, (Set-AiwbSegment $text $User $env:ProgramData), (New-Object Text.UTF8Encoding($false)))
208
- # 主机钥匙:已有私钥核验只归管理员;只补缺的默认类型(ssh-keygen -A),新生成的私钥收紧为 SYSTEM/管理员;撤回时保留(同 Mac)。
213
+ # 主机钥匙:已有私钥须只归管理员(否则撤回);只补缺的默认类型(ssh-keygen -A),新生成的私钥收紧为 SYSTEM/管理员;撤回时保留(同 Mac)。
209
214
  $hostKeys = @(Get-ChildItem -LiteralPath $sshDir -Filter 'ssh_host_*_key' -ErrorAction SilentlyContinue | ForEach-Object { $_.FullName })
210
- foreach ($k in $hostKeys) { Repair-AiwbAdminOnly $k 'O:BAD:P(A;;FA;;;SY)(A;;FA;;;BA)' }
215
+ foreach ($k in $hostKeys) { Assert-AiwbAdminOnly $k }
211
216
  [void](Invoke-AiwbNative (Join-Path $bin 'ssh-keygen.exe') @('-A'))
212
217
  foreach ($k in @(Get-ChildItem -LiteralPath $sshDir -Filter 'ssh_host_*_key' -ErrorAction SilentlyContinue | ForEach-Object { $_.FullName })) {
213
218
  if ($hostKeys -notcontains $k) { Set-AiwbAcl $k 'O:BAD:P(A;;FA;;;SY)(A;;FA;;;BA)' }
@@ -226,7 +231,9 @@ function Invoke-AiwbRemoteAccess([string]$User, [string]$Sid, [string]$Key) {
226
231
  [Console]::Error.WriteLine([string]$_.Exception.Message)
227
232
  } finally {
228
233
  if (-not $finished) {
229
- foreach ($f in @($keys, $entry, $conf)) {
234
+ # 只改写核验过(或本次新建)的位置:不可信的 sshd_config / aiwb(如 junction)不经它写或删任何东西。
235
+ $restore = @(); if ($dirTrusted) { $restore += @($keys, $entry) }; if ($confTrusted) { $restore += $conf }
236
+ foreach ($f in $restore) {
230
237
  Remove-Item -LiteralPath "$f.tmp" -Force -ErrorAction SilentlyContinue
231
238
  if ($null -ne $backup[$f]) { [IO.File]::WriteAllBytes($f, [byte[]]$backup[$f]) } else { Remove-Item -LiteralPath $f -Force -ErrorAction SilentlyContinue }
232
239
  }
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
- }
@@ -29,11 +29,21 @@ export declare function windowsSegment(user: string, programData: string): strin
29
29
  export declare function windowsSetSegment(text: string, user: string, programData: string): string | undefined;
30
30
  /** sshd_config 里本人段内容与位置都符合(再写一次不会变)。 */
31
31
  export declare function windowsSegmentOk(text: string | undefined, user: string, programData: string): boolean;
32
+ /** 本版开通脚本(内联执行时)写入 entry.ps1 的确切内容:Get-AiwbEntry 的 here-string 正文(行已去缩进,行间 \n,无结尾换行)。 */
33
+ export declare function windowsEntry(script: string): string | undefined;
32
34
  /** 内联进 -EncodedCommand 的脚本正文:去掉整行注释、空行与行首缩进(只为缩短命令行,语句不变)。 */
33
35
  export declare function inlineScript(script: string): string;
36
+ /**
37
+ * -EncodedCommand 的内层正文:校验过的三个常量 + 一小段引导,引导把 gzip 后 base64 内联的脚本(UTF-8)在内存里解压,
38
+ * 以 scriptblock 在同一作用域执行(脚本末尾 exit 即进程退出码)。只为缩短命令行(CreateProcess/ShellExecuteEx 上限 32767 字符),
39
+ * 脚本语句不变、仍整段内联、不落盘。依据:.NET IO.Compression.GZipStream(RFC 1952,Node zlib.gzipSync 同格式)。
40
+ */
41
+ export declare function windowsAdminBody(script: string, user: string, sid: string, key: string): string;
42
+ /** Windows PowerShell 命令行(CreateProcess)上限 32767 字符;断言与回报按其一半留余量。 */
43
+ export declare const WINDOWS_COMMAND_LINE_MAX = 32767;
34
44
  /**
35
45
  * Windows UAC 提权(设计 C):外层 powershell -Command 以 ShellExecuteEx “runas” 动词(ProcessStartInfo Verb=runas、UseShellExecute、隐藏窗口,
36
- * 即 Start-Process -Verb RunAs 的同一底层调用)启动管理员 powershell 并等待,透传其退出码;脚本整段以 UTF-16LE base64 内联(-EncodedCommand),
46
+ * 即 Start-Process -Verb RunAs 的同一底层调用)启动管理员 powershell 并等待,透传其退出码;内层正文见 windowsAdminBody(以 UTF-16LE base64 经 -EncodedCommand 内联),
37
47
  * 参数为已校验的常量,不落到用户可写位置。用户在 UAC 点“否”时抛 Win32Exception 1223(ERROR_CANCELLED),外层以其 NativeErrorCode 退出。
38
48
  * 不用 Start-Process 本身:Windows PowerShell 5.1 的 Start-Process 把 Win32Exception 换成只带本地化文字的 InvalidOperationException,丢了错误码(实机核过)。
39
49
  */
@@ -65,6 +75,11 @@ interface RemoteAccessOptions {
65
75
  }
66
76
  /** 系统设置“共享 → 远程登录”详情面板的官方深链接(含“允许远程用户完全磁盘访问”开关;该开关属 TCC,只能本人点开)。 */
67
77
  export declare const REMOTE_LOGIN_SETTINGS = "x-apple.systempreferences:com.apple.Sharing-Settings.extension?Services_RemoteLogin";
78
+ /** Windows 规则判定:本人段符合(windowsSegmentOk)且 entry.ps1 内容等于本版脚本写入的内容(windowsEntry)。 */
79
+ export declare function windowsRulesOk(local: {
80
+ config?: string;
81
+ entry?: string;
82
+ }, user: string, programData: string, entryText: string | undefined): boolean;
68
83
  export declare function createRemoteAccess(options: RemoteAccessOptions): {
69
84
  sync(target: SshTarget, signal: AbortSignal): Promise<void>;
70
85
  /** 登记内容可能变了(如工具桥服务晚于本插件出现):等进行中的一次结束后再登记一次。 */
@@ -3,6 +3,7 @@ import { execFile } from 'node:child_process';
3
3
  import { stat } from 'node:fs/promises';
4
4
  import { connect } from 'node:net';
5
5
  import { win32 } from 'node:path';
6
+ import { gzipSync } from 'node:zlib';
6
7
  import { shellQuote } from "./ssh.js";
7
8
  import { windowsSecurity } from "./windows-security.js";
8
9
  import { NETWORK_DEFAULTS } from "./defaults.js";
@@ -72,12 +73,31 @@ export function windowsSetSegment(text, user, programData) {
72
73
  }
73
74
  /** sshd_config 里本人段内容与位置都符合(再写一次不会变)。 */
74
75
  export function windowsSegmentOk(text, user, programData) { return text !== undefined && windowsSetSegment(text, user, programData) === text; }
76
+ /** 本版开通脚本(内联执行时)写入 entry.ps1 的确切内容:Get-AiwbEntry 的 here-string 正文(行已去缩进,行间 \n,无结尾换行)。 */
77
+ export function windowsEntry(script) {
78
+ const inline = inlineScript(script), start = inline.indexOf("function Get-AiwbEntry {\nreturn @'\n");
79
+ if (start < 0)
80
+ return undefined;
81
+ const from = start + "function Get-AiwbEntry {\nreturn @'\n".length, end = inline.indexOf("\n'@", from);
82
+ return end < 0 ? undefined : inline.slice(from, end);
83
+ }
75
84
  /** 内联进 -EncodedCommand 的脚本正文:去掉整行注释、空行与行首缩进(只为缩短命令行,语句不变)。 */
76
85
  export function inlineScript(script) { return script.split(/\r?\n/).map(line => line.trim()).filter(line => line && !line.startsWith('#')).join('\n'); }
77
86
  const psLiteral = (value) => "'" + value.replaceAll(/['\u2018\u2019\u201A\u201B]/g, match => match + match) + "'";
87
+ /**
88
+ * -EncodedCommand 的内层正文:校验过的三个常量 + 一小段引导,引导把 gzip 后 base64 内联的脚本(UTF-8)在内存里解压,
89
+ * 以 scriptblock 在同一作用域执行(脚本末尾 exit 即进程退出码)。只为缩短命令行(CreateProcess/ShellExecuteEx 上限 32767 字符),
90
+ * 脚本语句不变、仍整段内联、不落盘。依据:.NET IO.Compression.GZipStream(RFC 1952,Node zlib.gzipSync 同格式)。
91
+ */
92
+ export function windowsAdminBody(script, user, sid, key) {
93
+ const packed = gzipSync(Buffer.from(inlineScript(script), 'utf8'), { level: 9 }).toString('base64');
94
+ 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))`;
95
+ }
96
+ /** Windows PowerShell 命令行(CreateProcess)上限 32767 字符;断言与回报按其一半留余量。 */
97
+ export const WINDOWS_COMMAND_LINE_MAX = 32767;
78
98
  /**
79
99
  * Windows UAC 提权(设计 C):外层 powershell -Command 以 ShellExecuteEx “runas” 动词(ProcessStartInfo Verb=runas、UseShellExecute、隐藏窗口,
80
- * 即 Start-Process -Verb RunAs 的同一底层调用)启动管理员 powershell 并等待,透传其退出码;脚本整段以 UTF-16LE base64 内联(-EncodedCommand),
100
+ * 即 Start-Process -Verb RunAs 的同一底层调用)启动管理员 powershell 并等待,透传其退出码;内层正文见 windowsAdminBody(以 UTF-16LE base64 经 -EncodedCommand 内联),
81
101
  * 参数为已校验的常量,不落到用户可写位置。用户在 UAC 点“否”时抛 Win32Exception 1223(ERROR_CANCELLED),外层以其 NativeErrorCode 退出。
82
102
  * 不用 Start-Process 本身:Windows PowerShell 5.1 的 Start-Process 把 Win32Exception 换成只带本地化文字的 InvalidOperationException,丢了错误码(实机核过)。
83
103
  */
@@ -87,8 +107,7 @@ export function windowsAdminCommand(script, user, sid, key, env = process.env) {
87
107
  const normalized = employeeKey(key);
88
108
  if (normalized === undefined || normalized !== key)
89
109
  throw Error('AW_REMOTE_ACCESS_KEY_INVALID');
90
- const body = `$AiwbUser=${psLiteral(user)};$AiwbSid=${psLiteral(sid)};$AiwbKey=${psLiteral(key)}\n` + inlineScript(script);
91
- const encoded = Buffer.from(body, 'utf16le').toString('base64');
110
+ const encoded = Buffer.from(windowsAdminBody(script, user, sid, key), 'utf16le').toString('base64');
92
111
  const outer = `try{$s=New-Object Diagnostics.ProcessStartInfo;$s.FileName=(Join-Path $PSHOME 'powershell.exe');$s.Arguments='-NoProfile -NonInteractive -ExecutionPolicy Bypass -EncodedCommand ${encoded}';$s.Verb='runas';$s.UseShellExecute=$true;$s.WindowStyle='Hidden';$p=[Diagnostics.Process]::Start($s);$p.WaitForExit();exit $p.ExitCode}catch{$e=$_.Exception;while($e){if($e -is [ComponentModel.Win32Exception]){exit $e.NativeErrorCode};$e=$e.InnerException};exit 1}`;
93
112
  return { command: `${env.SYSTEMROOT || env.windir || 'C:\\Windows'}\\System32\\WindowsPowerShell\\v1.0\\powershell.exe`, args: ['-NoProfile', '-NonInteractive', '-Command', outer] };
94
113
  }
@@ -135,14 +154,20 @@ catch (error) {
135
154
  return undefined;
136
155
  throw error;
137
156
  } };
138
- const windowsLocalAccess = (timeoutMs) => async (user) => {
157
+ // 规则在:sshd_config 本人段内容与位置都符合,且 entry.ps1 与本版脚本要写的内容逐字一致(插件升级后入口变了就再授权一次)。
158
+ const windowsLocalAccess = (timeoutMs, entryText) => async (user) => {
139
159
  const programData = process.env.ProgramData;
140
160
  if (!programData || !win32.isAbsolute(programData))
141
161
  throw Error('PROGRAMDATA_REQUIRED');
142
162
  const keys = await readOptional(win32.join(programData, 'ssh', 'aiwb', user.toLowerCase() + '.keys'));
143
163
  const config = await readOptional(win32.join(programData, 'ssh', 'sshd_config'));
144
- return { keys, sshdLoaded: await listening(timeoutMs), confExists: windowsSegmentOk(config, user, programData) };
164
+ const entry = await readOptional(win32.join(programData, 'ssh', 'aiwb', 'entry.ps1'));
165
+ return { keys, sshdLoaded: await listening(timeoutMs), confExists: windowsRulesOk({ config, entry }, user, programData, entryText) };
145
166
  };
167
+ /** Windows 规则判定:本人段符合(windowsSegmentOk)且 entry.ps1 内容等于本版脚本写入的内容(windowsEntry)。 */
168
+ export function windowsRulesOk(local, user, programData, entryText) {
169
+ return windowsSegmentOk(local.config, user, programData) && entryText !== undefined && local.entry === entryText;
170
+ }
146
171
  // 外层 powershell 以 UAC 结果退出:0 成功,1223 用户拒绝,其余失败。
147
172
  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 }); }));
148
173
  export function createRemoteAccess(options) {
@@ -172,9 +197,11 @@ export function createRemoteAccess(options) {
172
197
  return;
173
198
  }
174
199
  const windows = platform === 'win32';
175
- if (!needsSetup(await (options.localAccess ?? (windows ? windowsLocalAccess(options.listenTimeoutMs ?? NETWORK_DEFAULTS.dialTimeoutSeconds * 1000) : localAccess))(options.user), key))
200
+ // Windows 先读本版脚本:检测要比对 entry.ps1 内容;macOS 仍只在需要开通时才读。
201
+ const winBody = windows ? await (options.script ?? windowsScript)() : undefined;
202
+ if (!needsSetup(await (options.localAccess ?? (windows ? windowsLocalAccess(options.listenTimeoutMs ?? NETWORK_DEFAULTS.dialTimeoutSeconds * 1000, windowsEntry(winBody)) : localAccess))(options.user), key))
176
203
  return;
177
- const admin = windows ? windowsAdminCommand(await (options.script ?? windowsScript)(), options.user, (options.sid ?? (() => windowsSecurity.sid()))(), key) : adminCommand(await (options.script ?? script)(), options.user, key);
204
+ const admin = windows ? windowsAdminCommand(winBody, options.user, (options.sid ?? (() => windowsSecurity.sid()))(), key) : adminCommand(await (options.script ?? script)(), options.user, key);
178
205
  const result = await (options.runAdmin ?? (windows ? windowsRunAdmin : runAdmin))(admin.command, admin.args);
179
206
  if (!result.ok) {
180
207
  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.4",
3
+ "version": "0.7.55-rc.6",
4
4
  "type": "module",
5
5
  "engines": {
6
6
  "node": ">=24.13.1",