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

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.
package/README.md CHANGED
@@ -11,6 +11,7 @@
11
11
  - Claude/Codex 登录:在主机上查官方 CLI 的真实登录状态;登录用员工默认浏览器(Claude 粘贴一次授权码,Codex 设备码),凭据只存主机。
12
12
  - 登出:官方 CLI 登出成功后,经主机 `aw-acp ls --json` + `aw-acp stop <id>` 结束该品牌仍在运行的会话;任一步未成功即如实报登出失败。
13
13
  - 远程登录开通:每次连上主机按 Tailscale SSH 来源登记该电脑(独立远程用户名、SSH 配置和 known_hosts),主机会话与工具桥固定回连本轮的发起电脑,同员工多台电脑可同时使用。macOS 上本机未按主机钥匙开通、远程登录被关或规则缺失时,弹一次系统管理员授权框执行 `helper/remote-access.sh`:只允许主机上本人的 emp 钥匙经本机回环连入(`from="127.0.0.1,::1",restrict,pty`、`ForceCommand`),先收紧后开启(校验前用 `ssh-keygen -A` 补齐从未开过远程登录的 Mac 缺的主机钥匙),失败整体撤回;成功后打开一次系统设置“远程登录”详情面板,员工自己打开“允许远程用户完全磁盘访问”(TCC 授权无法由命令开启);取消后本次运行不再询问。
14
+ Windows(x64)上改为弹一次 UAC 以管理员执行 `helper/remote-access.ps1`(员工不是本机管理员时,需要管理员在场输入一次管理员账号密码):按需安装/开启系统自带 OpenSSH Server(系统可选功能装不上时改装微软官方 Win32-OpenSSH 固定版本 MSI),在 `sshd_config` 里只为本人加一段 `Match User`(不改其他行、不影响本机其他 SSH 用户),远程命令在 PowerShell 中执行;没有“完全磁盘访问”这一步,成功后不打开任何设置。设备登记同时报平台与工具桥回连命令(Windows 上工具桥走命名管道)。
14
15
 
15
16
  给远程助手插件(X)的接口:`ensureReady(provider)` 返回可信主机目标,连接与登录状态订阅,以及 `sshArgs(target)` 在主机上以 emp 账号跑命令或开流。
16
17
 
@@ -0,0 +1,200 @@
1
+ # 员工电脑“远程登录”开通(Windows;与 helper/remote-access.sh 逐条对应,设计 C)。由 L 经 UAC 以管理员执行一次:
2
+ # powershell.exe -NoProfile -NonInteractive -ExecutionPolicy Bypass -EncodedCommand <"$AiwbUser='<用户名>';$AiwbSid='<SID>';$AiwbKey='<公钥>';" + 本文件>
3
+ # 只放行本机回环来的、持主机 emp 钥匙的连接(N 在 tsnet :22 转发到 127.0.0.1:22)。
4
+ # 依据:OpenSSH sshd_config(5) Match/AuthorizedKeysFile/ForceCommand/AcceptEnv,authorized_keys(5) from=/restrict/pty;
5
+ # Microsoft Learn《OpenSSH for Windows》安装(Add-WindowsCapability OpenSSH.Server)、sshd 服务、密钥文件 ACL(去继承,管理员/SYSTEM 完全控制);
6
+ # 微软官方 GitHub PowerShell/Win32-OpenSSH 的 MSI 安装(msiexec ADDLOCAL=Server)作 FoD 失败后备。
7
+ # 不设 AllowUsers、不改全机 DefaultShell、不动 sshd_config 其他行:本人一段 Match 插在第一个 Match 之前(全局设置之后)。
8
+ # 顺序:先收紧(钥匙→入口→规则→主机钥匙→sshd -t),最后才设自动并启动/重启 sshd;任一步失败恢复备份,不留“已开但未收紧”的状态。
9
+ # 改文本的部分(Get-AiwbSegment/Set-AiwbSegment)与写 ACL 的部分(Set-AiwbAcl)可在非管理员下对副本验证:$AiwbLibraryOnly=$true 时只定义函数。
10
+ $ErrorActionPreference = 'Stop'
11
+ # 微软官方 GitHub PowerShell/Win32-OpenSSH 当前最新发行 10.4.0.0p1-Preview(2026-10-20,GitHub releases/latest),x64 MSI 与其 SHA256(GitHub 资产 digest,下载复核一致)。
12
+ $AiwbMsiUrl = 'https://github.com/PowerShell/Win32-OpenSSH/releases/download/10.4.0.0p1-Preview/OpenSSH-Win64-v10.4.0.0.msi'
13
+ $AiwbMsiSha256 = '788D8643464A01EB63640A2FD746F9ED23D106B5A901A35F88DC8CD40E446AC9'
14
+
15
+ function Test-AiwbUser([string]$User) { return $User -cmatch '\A[A-Za-z0-9._][A-Za-z0-9._-]*\z' }
16
+ function Test-AiwbKey([string]$Key) { return ($Key -notmatch "[`r`n]") -and ($Key -cmatch '\Assh-ed25519 [A-Za-z0-9+/]+=*( [ -~]*)?\z') }
17
+ function Test-AiwbSid([string]$Sid) { return $Sid -cmatch '\AS-1-[0-9]+(-[0-9]+)+\z' }
18
+
19
+ # 本人一段规则(用户名小写:Win32-OpenSSH 的 Match User 只认小写)。
20
+ function Get-AiwbSegment([string]$User, [string]$ProgramData) {
21
+ $u = $User.ToLowerInvariant()
22
+ return @(
23
+ "# aiwb-begin $u",
24
+ "Match User $u",
25
+ " AuthorizedKeysFile __PROGRAMDATA__/ssh/aiwb/$u.keys",
26
+ ' AuthenticationMethods publickey',
27
+ ' AcceptEnv AW_EMP_CWD',
28
+ " ForceCommand powershell.exe -NoProfile -NonInteractive -ExecutionPolicy Bypass -File `"$ProgramData\ssh\aiwb\entry.ps1`"",
29
+ "# aiwb-end $u"
30
+ )
31
+ }
32
+
33
+ # 返回改好的全文:已有本人段且它之前没有非本插件的 Match 行 → 原位整段替换;否则(没有,或被挪到别的 Match 之后)去掉旧段,
34
+ # 插在第一个 Match 行(或其他员工段的开始标记)之前、全局设置之后;没有 Match 就放末尾。换行沿用原文(空文件用 CRLF);有头无尾的本人段不猜,报错。
35
+ function Set-AiwbSegment([string]$Text, [string]$User, [string]$ProgramData) {
36
+ $u = $User.ToLowerInvariant()
37
+ $nl = "`r`n"; if ($Text.Length -gt 0 -and -not $Text.Contains("`r`n")) { $nl = "`n" }
38
+ $lines = New-Object 'System.Collections.Generic.List[string]'
39
+ if ($Text.Length -gt 0) { foreach ($l in ($Text -split "\r?\n")) { $lines.Add($l) } }
40
+ if ($lines.Count -gt 0 -and $lines[$lines.Count - 1] -eq '') { $lines.RemoveAt($lines.Count - 1) }
41
+ $begin = $lines.IndexOf("# aiwb-begin $u"); $end = -1
42
+ if ($begin -ge 0) { $end = $lines.IndexOf("# aiwb-end $u", $begin + 1); if ($end -lt 0) { throw 'AW_REMOTE_ACCESS_SSHD_INVALID' } }
43
+ $segment = [string[]](Get-AiwbSegment $User $ProgramData)
44
+ if ($begin -ge 0) {
45
+ $foreign = $false
46
+ 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 } }
47
+ $lines.RemoveRange($begin, $end - $begin + 1)
48
+ if (-not $foreign) { $lines.InsertRange($begin, $segment); return ($lines -join $nl) + $nl }
49
+ }
50
+ $at = $lines.Count
51
+ 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 } }
52
+ $lines.InsertRange($at, $segment)
53
+ return ($lines -join $nl) + $nl
54
+ }
55
+
56
+ # 以 SDDL 只写 DACL(所有者不动;SetAccessControl 只落改过的部分);D:P 为去继承。依据:.NET FileSystemSecurity.SetSecurityDescriptorSddlForm/File.SetAccessControl。
57
+ function Set-AiwbAcl([string]$Path, [string]$Sddl) {
58
+ if ([IO.Directory]::Exists($Path)) {
59
+ $acl = New-Object Security.AccessControl.DirectorySecurity; $acl.SetSecurityDescriptorSddlForm($Sddl, 'Access'); [IO.Directory]::SetAccessControl($Path, $acl)
60
+ } else {
61
+ $acl = New-Object Security.AccessControl.FileSecurity; $acl.SetSecurityDescriptorSddlForm($Sddl, 'Access'); [IO.File]::SetAccessControl($Path, $acl)
62
+ }
63
+ }
64
+
65
+ # 先写 <文件>.tmp(UTF-8 无 BOM),设 ACL,再替换到位(同卷改名,ACL 随文件)。
66
+ function Write-AiwbFile([string]$Path, [string]$Text, [string]$Sddl) {
67
+ $tmp = "$Path.tmp"
68
+ [IO.File]::WriteAllText($tmp, $Text, (New-Object Text.UTF8Encoding($false)))
69
+ Set-AiwbAcl $tmp $Sddl
70
+ Move-Item -LiteralPath $tmp -Destination $Path -Force
71
+ }
72
+
73
+ # entry.ps1(ForceCommand):cd 到 AW_EMP_CWD(失败回 $HOME);shell 选法同 DSH pwsh-local(PowerShell 7 安装位置 → PATH 中 pwsh.exe → Windows PowerShell 5.1);
74
+ # 有 SSH_ORIGINAL_COMMAND 则先固定 UTF-8 输出(同 DSH pwsh-local 的前缀)再以 -EncodedCommand 执行并透传退出码,无则交互;stdin 原样继承。
75
+ function Get-AiwbEntry {
76
+ return @'
77
+ $ErrorActionPreference = 'Continue'
78
+ $moved = $false
79
+ if ($env:AW_EMP_CWD) { try { Set-Location -LiteralPath $env:AW_EMP_CWD -ErrorAction Stop; $moved = $true } catch { } }
80
+ if (-not $moved) { try { Set-Location -LiteralPath $HOME -ErrorAction Stop } catch { exit 1 } }
81
+ $candidates = @("$env:ProgramFiles\PowerShell\7\pwsh.exe")
82
+ foreach ($e in ("$env:PATH" -split ';')) { $t = $e.Trim().Trim('"'); if ($t) { $candidates += ($t.TrimEnd('\') + '\pwsh.exe') } }
83
+ $candidates += "$env:SystemRoot\System32\WindowsPowerShell\v1.0\powershell.exe"
84
+ $shell = 'pwsh'
85
+ foreach ($c in $candidates) { if ([IO.File]::Exists($c)) { $shell = $c; break } }
86
+ if ($env:SSH_ORIGINAL_COMMAND) {
87
+ $pre = '[Console]::OutputEncoding = [System.Text.UTF8Encoding]::new($false); $OutputEncoding = [System.Text.UTF8Encoding]::new($false); '
88
+ $enc = [Convert]::ToBase64String([Text.Encoding]::Unicode.GetBytes($pre + $env:SSH_ORIGINAL_COMMAND))
89
+ & $shell -NoLogo -NoProfile -NonInteractive -EncodedCommand $enc
90
+ exit $LASTEXITCODE
91
+ }
92
+ & $shell -NoLogo
93
+ exit $LASTEXITCODE
94
+ '@
95
+ }
96
+
97
+ # 系统 FoD 安装 OpenSSH Server;失败(如 WSUS/离线 0x800f0954)改装固定版本官方 MSI:先整份下载到内存核 SHA256,
98
+ # 再写进新建时即只许 SYSTEM/管理员访问的目录(不落到用户可写位置),msiexec 静默只装 Server,装完删除。
99
+ function Install-AiwbSshd {
100
+ try { Add-WindowsCapability -Online -Name 'OpenSSH.Server~~~~0.0.1.0' | Out-Null } catch { }
101
+ if (Get-Service -Name sshd -ErrorAction SilentlyContinue) { return }
102
+ [Net.ServicePointManager]::SecurityProtocol = [Net.ServicePointManager]::SecurityProtocol -bor [Net.SecurityProtocolType]::Tls12
103
+ $bytes = (Invoke-WebRequest -UseBasicParsing -Uri $AiwbMsiUrl).Content
104
+ $hash = -join ([Security.Cryptography.SHA256]::Create().ComputeHash([byte[]]$bytes) | ForEach-Object { $_.ToString('X2') })
105
+ if ($hash -ne $AiwbMsiSha256) { throw 'AW_REMOTE_ACCESS_MSI_HASH' }
106
+ $sec = New-Object Security.AccessControl.DirectorySecurity
107
+ $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'))
109
+ [void][IO.Directory]::CreateDirectory($dir, $sec)
110
+ try {
111
+ $msi = Join-Path $dir 'OpenSSH-Win64.msi'
112
+ $fs = New-Object IO.FileStream($msi, [IO.FileMode]::CreateNew, [IO.FileAccess]::Write)
113
+ try { $fs.Write([byte[]]$bytes, 0, $bytes.Length) } finally { $fs.Dispose() }
114
+ $p = Start-Process -FilePath (Join-Path $env:SystemRoot 'System32\msiexec.exe') -ArgumentList @('/i', "`"$msi`"", 'ADDLOCAL=Server', '/qn') -Wait -PassThru -WindowStyle Hidden
115
+ if ($p.ExitCode -ne 0 -and $p.ExitCode -ne 3010) { throw 'AW_REMOTE_ACCESS_MSI_FAILED' }
116
+ } finally { Remove-Item -LiteralPath $dir -Recurse -Force -ErrorAction SilentlyContinue }
117
+ if (-not (Get-Service -Name sshd -ErrorAction SilentlyContinue)) { throw 'AW_REMOTE_ACCESS_SSHD_MISSING' }
118
+ }
119
+
120
+ # sshd.exe 的位置取自服务登记(FoD 在 System32\OpenSSH,MSI 在 Program Files\OpenSSH)。
121
+ function Get-AiwbSshdPath {
122
+ $image = (Get-CimInstance -ClassName Win32_Service -Filter "Name='sshd'").PathName
123
+ if ($image -match '\A"([^"]+)"') { return $Matches[1] }
124
+ return ($image -split ' ')[0]
125
+ }
126
+
127
+ function Invoke-AiwbRemoteAccess([string]$User, [string]$Sid, [string]$Key) {
128
+ if (-not (Test-AiwbUser $User) -or -not (Test-AiwbSid $Sid)) { [Console]::Error.WriteLine('AW_REMOTE_ACCESS_USER_INVALID'); return 2 }
129
+ if (-not (Test-AiwbKey $Key)) { [Console]::Error.WriteLine('AW_REMOTE_ACCESS_KEY_INVALID'); return 2 }
130
+ $u = $User.ToLowerInvariant()
131
+ $sshDir = Join-Path $env:ProgramData 'ssh'
132
+ $dir = Join-Path $sshDir 'aiwb'
133
+ $keys = Join-Path $dir "$u.keys"
134
+ $entry = Join-Path $dir 'entry.ps1'
135
+ $conf = Join-Path $sshDir 'sshd_config'
136
+ # 开始前状态:sshd 是否已装、启动类型与是否在跑;三个文件是否已存在(存在则先在内存里备份以便撤回)。
137
+ $svc = Get-Service -Name sshd -ErrorAction SilentlyContinue
138
+ $installed = $false; $touched = $false
139
+ $startBefore = $null; $runningBefore = $false
140
+ if ($svc) { $startBefore = $svc.StartType; $runningBefore = ($svc.Status -eq 'Running') }
141
+ $backup = @{}
142
+ foreach ($f in @($keys, $entry, $conf)) { if ([IO.File]::Exists($f)) { $backup[$f] = [IO.File]::ReadAllBytes($f) } else { $backup[$f] = $null } }
143
+ $finished = $false; $code = 1
144
+ try {
145
+ if (-not $svc) { Install-AiwbSshd; $installed = $true }
146
+ $sshd = Get-AiwbSshdPath
147
+ $bin = Split-Path -Parent $sshd
148
+ # 从未启动过的 sshd 还没有 ProgramData\ssh 与 sshd_config:按 Win32-OpenSSH 自建该目录时的 SDDL 建目录,用安装目录的 sshd_config_default 作底本。
149
+ if (-not (Test-Path -LiteralPath $sshDir)) {
150
+ $sec = New-Object Security.AccessControl.DirectorySecurity
151
+ $sec.SetSecurityDescriptorSddlForm('O:BAD:PAI(A;OICI;FA;;;SY)(A;OICI;FA;;;BA)(A;OICI;0x1200a9;;;AU)')
152
+ [void][IO.Directory]::CreateDirectory($sshDir, $sec)
153
+ }
154
+ if (-not [IO.File]::Exists($conf)) { Copy-Item -LiteralPath (Join-Path $bin 'sshd_config_default') -Destination $conf }
155
+ 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)"
159
+ Write-AiwbFile $keys "from=`"127.0.0.1,::1`",restrict,pty $Key`n" $fileAcl
160
+ 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 通过后才(重)启动读取。
163
+ [IO.File]::WriteAllText($conf, (Set-AiwbSegment $text $User $env:ProgramData), (New-Object Text.UTF8Encoding($false)))
164
+ # 主机钥匙:只补缺的默认类型(ssh-keygen -A),新生成的私钥收紧为 SYSTEM/管理员;已有的不动、撤回时保留(同 Mac)。
165
+ $hostKeys = @(Get-ChildItem -LiteralPath $sshDir -Filter 'ssh_host_*_key' -ErrorAction SilentlyContinue | ForEach-Object { $_.FullName })
166
+ & (Join-Path $bin 'ssh-keygen.exe') -A | Out-Null
167
+ 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)' }
169
+ }
170
+ & $sshd -t
171
+ if ($LASTEXITCODE -ne 0) { [Console]::Error.WriteLine('AW_REMOTE_ACCESS_SSHD_INVALID'); return 1 }
172
+ $touched = $true
173
+ Set-Service -Name sshd -StartupType Automatic
174
+ if ((Get-Service -Name sshd).Status -eq 'Running') { Restart-Service -Name sshd -Force } else { Start-Service -Name sshd }
175
+ $finished = $true; $code = 0
176
+ } catch {
177
+ [Console]::Error.WriteLine([string]$_.Exception.Message)
178
+ } finally {
179
+ if (-not $finished) {
180
+ foreach ($f in @($keys, $entry, $conf)) {
181
+ Remove-Item -LiteralPath "$f.tmp" -Force -ErrorAction SilentlyContinue
182
+ if ($null -ne $backup[$f]) { [IO.File]::WriteAllBytes($f, [byte[]]$backup[$f]) } else { Remove-Item -LiteralPath $f -Force -ErrorAction SilentlyContinue }
183
+ }
184
+ if ($installed) {
185
+ Stop-Service -Name sshd -Force -ErrorAction SilentlyContinue
186
+ Set-Service -Name sshd -StartupType Disabled -ErrorAction SilentlyContinue
187
+ } elseif ($touched) {
188
+ Set-Service -Name sshd -StartupType $startBefore -ErrorAction SilentlyContinue
189
+ if ($runningBefore) { Restart-Service -Name sshd -Force -ErrorAction SilentlyContinue } else { Stop-Service -Name sshd -Force -ErrorAction SilentlyContinue }
190
+ }
191
+ [Console]::Error.WriteLine('AW_REMOTE_ACCESS_ROLLED_BACK')
192
+ }
193
+ }
194
+ return $code
195
+ }
196
+
197
+ if (-not $AiwbLibraryOnly) {
198
+ $script:AiwbCode = Invoke-AiwbRemoteAccess -User $AiwbUser -Sid $AiwbSid -Key $AiwbKey
199
+ exit ([int]($script:AiwbCode | Select-Object -Last 1))
200
+ }
@@ -1,6 +1,6 @@
1
1
  import { mkdtemp, writeFile, rm, realpath } from 'node:fs/promises';
2
2
  import { join } from 'node:path';
3
- import { privateDirectory } from "./private-files.js";
3
+ import { privateDirectory, sealPrivate } from "./private-files.js";
4
4
  import { NeedError, need } from "./needs.js";
5
5
  // 产品默认开通地址随总包发布,不是员工设置。
6
6
  export const ACCOUNT_ENROLLMENT_URL = 'https://mini-awhost.tail9816d2.ts.net/enrollment/login';
@@ -44,9 +44,11 @@ export async function downloadEnrollment(credentials, options) {
44
44
  if (await realpath(root) !== root)
45
45
  throw failure();
46
46
  source = await mkdtemp(join(root, '.account-login-'));
47
- await writeFile(join(source, 'enroll.json'), JSON.stringify(body.enrollment) + '\n', { mode: 0o600, flag: 'wx' });
48
- await writeFile(join(source, 'ssh-rule.json'), JSON.stringify(body.sshRule) + '\n', { mode: 0o600, flag: 'wx' });
49
- await writeFile(join(source, 'authkey'), body.authKey + '\n', { mode: 0o600, flag: 'wx' });
47
+ await sealPrivate(source, true);
48
+ for (const [name, text] of [['enroll.json', JSON.stringify(body.enrollment)], ['ssh-rule.json', JSON.stringify(body.sshRule)], ['authkey', body.authKey]]) {
49
+ await writeFile(join(source, name), text + '\n', { mode: 0o600, flag: 'wx' });
50
+ await sealPrivate(join(source, name));
51
+ }
50
52
  body.authKey = '';
51
53
  const target = source;
52
54
  return { source: target, cleanup: () => rm(target, { recursive: true, force: true }) };
@@ -1,5 +1,15 @@
1
1
  import type { BrowserLoginState, Result } from './api.ts';
2
2
  import type { LoginBoot, LoginInteraction } from './login.ts';
3
+ /**
4
+ * Windows 打开默认浏览器:照抄 npm `open` 11.0.4(index.js win32 分支 + powershell-utils 0.2.1)——
5
+ * `%SYSTEMROOT%\System32\WindowsPowerShell\v1.0\powershell.exe -NoProfile -NonInteractive -ExecutionPolicy Bypass -EncodedCommand <UTF-16LE base64>`,
6
+ * 命令为 `$ProgressPreference = 'SilentlyContinue'; Start '<URL>'`,URL 以单引号字面量传入(ASCII 与 U+2018–U+201B 单引号一律双写),
7
+ * windowsVerbatimArguments、stdio ignore,等 PowerShell 退出。
8
+ */
9
+ export declare function windowsBrowserCommand(url: string, env?: NodeJS.ProcessEnv): {
10
+ command: string;
11
+ args: string[];
12
+ };
3
13
  export declare function openDefaultBrowser(url: string, signal: AbortSignal, platform?: NodeJS.Platform): Promise<void>;
4
14
  export declare function createBrowserLogin(open?: (url: string, signal: AbortSignal) => Promise<void>): {
5
15
  getState: () => BrowserLoginState;
@@ -1,13 +1,25 @@
1
1
  import { randomUUID } from 'node:crypto';
2
2
  import { spawn } from 'node:child_process';
3
3
  import { fail, ok } from "./needs.js";
4
- // The public authorization URL goes to macOS open; pasted codes only go to the host CLI stdin.
4
+ // The public authorization URL goes to macOS open / Windows PowerShell Start; pasted codes only go to the host CLI stdin.
5
+ /**
6
+ * Windows 打开默认浏览器:照抄 npm `open` 11.0.4(index.js win32 分支 + powershell-utils 0.2.1)——
7
+ * `%SYSTEMROOT%\System32\WindowsPowerShell\v1.0\powershell.exe -NoProfile -NonInteractive -ExecutionPolicy Bypass -EncodedCommand <UTF-16LE base64>`,
8
+ * 命令为 `$ProgressPreference = 'SilentlyContinue'; Start '<URL>'`,URL 以单引号字面量传入(ASCII 与 U+2018–U+201B 单引号一律双写),
9
+ * windowsVerbatimArguments、stdio ignore,等 PowerShell 退出。
10
+ */
11
+ export function windowsBrowserCommand(url, env = process.env) {
12
+ const literal = "'" + url.replaceAll(/['\u2018\u2019\u201A\u201B]/g, match => match + match) + "'";
13
+ const encoded = Buffer.from(["$ProgressPreference = 'SilentlyContinue';", 'Start', literal].join(' '), 'utf16le').toString('base64');
14
+ return { command: `${env.SYSTEMROOT || env.windir || 'C:\\Windows'}\\System32\\WindowsPowerShell\\v1.0\\powershell.exe`, args: ['-NoProfile', '-NonInteractive', '-ExecutionPolicy', 'Bypass', '-EncodedCommand', encoded] };
15
+ }
5
16
  export async function openDefaultBrowser(url, signal, platform = process.platform) {
6
17
  if (signal.aborted)
7
18
  throw Error('BROWSER_CANCELLED');
8
- if (platform !== 'darwin')
19
+ if (platform !== 'darwin' && platform !== 'win32')
9
20
  throw Error('BROWSER_PLATFORM_UNSUPPORTED');
10
- const child = spawn('/usr/bin/open', [url], { shell: false, stdio: 'ignore' });
21
+ const windows = platform === 'win32' ? windowsBrowserCommand(url) : undefined;
22
+ const child = windows ? spawn(windows.command, windows.args, { shell: false, stdio: 'ignore', windowsVerbatimArguments: true }) : spawn('/usr/bin/open', [url], { shell: false, stdio: 'ignore' });
11
23
  let failed = false;
12
24
  const abort = () => child.kill();
13
25
  signal.addEventListener('abort', abort, { once: true });
package/lib/enrollment.js CHANGED
@@ -1,15 +1,18 @@
1
- import { lstat, open, rename, rm } from 'node:fs/promises';
1
+ import { open, rename, rm } from 'node:fs/promises';
2
2
  import { join, isAbsolute } from 'node:path';
3
3
  import { randomUUID } from 'node:crypto';
4
4
  import { fail, ok } from "./needs.js";
5
- import { privateDirectory, privateFile, readPrivate } from "./private-files.js";
5
+ import { privateDirectory, privateFile, readPrivate, checkPrivateDirectory, sealPrivate } from "./private-files.js";
6
6
  export async function readEnrollment(packageDir, trustDir, maxMetadataBytes) {
7
7
  try {
8
8
  if (!isAbsolute(packageDir) || !isAbsolute(trustDir))
9
9
  return fail('ENROLLMENT_INVALID');
10
- const dir = await lstat(packageDir);
11
- if (!dir.isDirectory() || dir.isSymbolicLink() || dir.uid !== process.getuid() || (dir.mode & 0o077) !== 0)
10
+ try {
11
+ await checkPrivateDirectory(packageDir);
12
+ }
13
+ catch {
12
14
  return fail('ENROLLMENT_INVALID');
15
+ }
13
16
  const wire = JSON.parse(await readPrivate(join(packageDir, 'enroll.json'), maxMetadataBytes));
14
17
  if (wire.schemaVersion !== 1 || !/^emp-[a-z0-9][a-z0-9-]*$/.test(wire.employee?.username) || wire.employee.username.length > 32)
15
18
  return fail('ENROLLMENT_INVALID');
@@ -56,6 +59,7 @@ export async function readEnrollment(packageDir, trustDir, maxMetadataBytes) {
56
59
  try {
57
60
  await file.writeFile(keys.join('\n') + '\n');
58
61
  await file.close();
62
+ await sealPrivate(temp);
59
63
  await rename(temp, destination);
60
64
  }
61
65
  finally {
package/lib/index.js CHANGED
@@ -56,7 +56,9 @@ export function apply(ctx, config = {}) {
56
56
  api.quota = quota;
57
57
  const ssh = ports.ssh;
58
58
  if (ssh?.employeeAccess) {
59
- const access = createRemoteAccess({ ssh: { employeeAccess: ssh.employeeAccess }, user: userInfo().username, node: target => networkNodeName(config.network, target.username) });
59
+ // 工具桥回连命令由工具桥插件以可选服务 aiWorkbenchToolbridge 提供({command}),登记时现取;没装工具桥则不上报。
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 });
60
62
  // 每次连上(新的连接代次)做一次:写主机 emp.json,按需开通本机远程登录;不阻塞连接与登录。
61
63
  let seen = '';
62
64
  const lifetime = new AbortController();
package/lib/network.d.ts CHANGED
@@ -12,6 +12,11 @@ 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;
15
20
  export declare function writeNetworkConfig(file: string, e: Enrollment, s: NetworkSettings): Promise<Result<void>>;
16
21
  export declare function createNetworkClient(s: NetworkSettings): {
17
22
  connect(e: Enrollment, signal: AbortSignal): Promise<Result<{
package/lib/network.js CHANGED
@@ -1,11 +1,18 @@
1
1
  import { request } from 'node:http';
2
2
  import { lstat, writeFile, rename, rm } from 'node:fs/promises';
3
3
  import { join, dirname, isAbsolute } from 'node:path';
4
- import { hostname } from 'node:os';
5
- import { randomUUID } from 'node:crypto';
4
+ import { randomUUID, createHash } from 'node:crypto';
6
5
  import { need, dependency, ok, fail, NeedError } from "./needs.js";
7
- import { privateDirectory } from "./private-files.js";
6
+ import { privateDirectory, checkPrivateDirectory, sealPrivate, host } from "./private-files.js";
7
+ import { nodeName } from "./node-name.js";
8
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
+ }
9
16
  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; }
10
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'; }
11
18
  export async function writeNetworkConfig(file, e, s) {
@@ -14,9 +21,10 @@ export async function writeNetworkConfig(file, e, s) {
14
21
  let temp;
15
22
  try {
16
23
  await privateDirectory(dirname(file));
17
- const config = { apiVersion: 1, stateDir: s.stateDir, runtimeDir: s.runtimeDir, nodeName: `aw-${e.username}-${hostname()}-${process.getuid()}`, ...(e.authKeyFile ? { authKeyFile: e.authKeyFile } : {}), host: { name: e.host, sshPort: e.port, employee: e.username, knownHostsFile: e.knownHostsFile }, statusRefreshIntervalSeconds: s.statusRefreshIntervalSeconds, dialTimeoutSeconds: s.dialTimeoutSeconds, headerTimeoutSeconds: s.headerTimeoutSeconds, enrollmentObservationSeconds: s.enrollmentObservationSeconds, logUpload: s.logUpload, httpMaxHeaderBytes: s.httpMaxHeaderBytes };
24
+ const config = { apiVersion: 1, stateDir: s.stateDir, runtimeDir: s.runtimeDir, nodeName: nodeName(e.username), ...(e.authKeyFile ? { authKeyFile: e.authKeyFile } : {}), host: { name: e.host, sshPort: e.port, employee: e.username, knownHostsFile: e.knownHostsFile }, statusRefreshIntervalSeconds: s.statusRefreshIntervalSeconds, dialTimeoutSeconds: s.dialTimeoutSeconds, headerTimeoutSeconds: s.headerTimeoutSeconds, enrollmentObservationSeconds: s.enrollmentObservationSeconds, logUpload: s.logUpload, httpMaxHeaderBytes: s.httpMaxHeaderBytes };
18
25
  temp = join(dirname(file), '.network-' + randomUUID());
19
26
  await writeFile(temp, JSON.stringify(config), { flag: 'wx', mode: 0o600 });
27
+ await sealPrivate(temp);
20
28
  await rename(temp, file);
21
29
  temp = undefined;
22
30
  return ok(undefined);
@@ -38,6 +46,11 @@ export function createNetworkClient(s) {
38
46
  async function socket() {
39
47
  if (!valid(s))
40
48
  bad('SETTINGS_REQUIRED');
49
+ // win32:控制端点是命名管道(N 以只许本人与 SYSTEM 的 SDDL 建首实例),这里核 runtimeDir 私有。
50
+ if (host.platform === 'win32') {
51
+ await checkPrivateDirectory(s.runtimeDir);
52
+ return;
53
+ }
41
54
  const dir = await lstat(s.runtimeDir), sock = await lstat(join(s.runtimeDir, 'control.sock'));
42
55
  if (!dir.isDirectory() || dir.isSymbolicLink() || dir.uid !== process.getuid() || (dir.mode & 0o077) || !sock.isSocket() || sock.isSymbolicLink() || sock.uid !== process.getuid() || (sock.mode & 0o177))
43
56
  bad('DEPENDENCY_REQUIRED');
@@ -53,7 +66,7 @@ export function createNetworkClient(s) {
53
66
  }
54
67
  if (disposed || signal.aborted)
55
68
  bad('CONNECTION_LOST');
56
- return new Promise((resolve, reject) => { const req = request({ socketPath: join(s.runtimeDir, 'control.sock'), 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(); });
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(); });
57
70
  }
58
71
  async function json(res) { let size = 0; const chunks = []; try {
59
72
  for await (const chunk of res) {
@@ -118,7 +131,7 @@ export function createNetworkClient(s) {
118
131
  return result;
119
132
  try {
120
133
  const exe = await lstat(s.executable);
121
- if (!exe.isFile() || exe.isSymbolicLink() || !(exe.mode & 0o111))
134
+ if (!exe.isFile() || exe.isSymbolicLink() || host.platform !== 'win32' && !(exe.mode & 0o111))
122
135
  return dependency('N 真实 helper 可执行程序');
123
136
  return ok({ proxyCommand: proxyCommand(s.executable, s.runtimeDir) });
124
137
  }
@@ -0,0 +1,5 @@
1
+ /**
2
+ * N 节点名 `aw-<员工账号>-<本机名>-<本机用户号>`:macOS 用 uid;Windows 用当前用户 SID 的末段 RID
3
+ * (同一账户稳定、与 uid 同为本机账户编号,不含用户名等个人信息)。
4
+ */
5
+ export declare const nodeName: (employee: string) => string;
@@ -0,0 +1,8 @@
1
+ import { hostname } from 'node:os';
2
+ import { host } from "./private-files.js";
3
+ import { rid } from "./windows-security.js";
4
+ /**
5
+ * N 节点名 `aw-<员工账号>-<本机名>-<本机用户号>`:macOS 用 uid;Windows 用当前用户 SID 的末段 RID
6
+ * (同一账户稳定、与 uid 同为本机账户编号,不含用户名等个人信息)。
7
+ */
8
+ export const nodeName = (employee) => `aw-${employee}-${hostname()}-${host.platform === 'win32' ? rid(host.security.sid()) : process.getuid()}`;
@@ -1,3 +1,18 @@
1
+ import type { Stats } from 'node:fs';
2
+ import { type WindowsSecurity } from './windows-security.ts';
3
+ /** 平台与 Windows 安全接口;测试注入 win32 与替身,产品取当前进程平台。 */
4
+ export declare const host: {
5
+ platform: string;
6
+ security: WindowsSecurity;
7
+ };
8
+ /** win32:本进程新建的文件/目录收紧为私有(macOS 由 mode 0600/0700 在创建时完成,这里为空操作)。 */
9
+ export declare function sealPrivate(path: string, directory?: boolean): Promise<void>;
10
+ /** 目录 fsync:macOS 照旧;Windows 不能对目录句柄 FlushFileBuffers(实机 EPERM),NTFS 元数据由日志保证,跳过(同 LevelDB env_windows 不同步目录)。 */
11
+ export declare function syncDirectory(path: string): Promise<void>;
1
12
  export declare function privateDirectory(path: string): Promise<void>;
13
+ /** win32 只核私有目录,不建不改(读取他人交付的目录时用)。 */
14
+ export declare function checkPrivateDirectory(path: string): Promise<void>;
2
15
  export declare function privateFile(path: string): Promise<void>;
3
16
  export declare function readPrivate(path: string, maxBytes?: number): Promise<string>;
17
+ /** 文件私有性(profile-enrollment 的来源文件核对用):win32 走 ACL,macOS 由调用方按 uid/mode 判。 */
18
+ export declare function windowsPrivateFile(path: string, before: Stats): Promise<void>;
@@ -1,21 +1,80 @@
1
1
  import { lstat, mkdir, open } from 'node:fs/promises';
2
2
  import { constants } from 'node:fs';
3
+ import { join, relative, sep } from 'node:path';
4
+ import { privateSddl, windowsSecurity } from "./windows-security.js";
5
+ // darwin:uid + 0700/0600(不变)。win32:设计 A 表私有性,ACL 经 windows-security 读写。
6
+ /** 平台与 Windows 安全接口;测试注入 win32 与替身,产品取当前进程平台。 */
7
+ export const host = { platform: process.platform, security: windowsSecurity };
8
+ const windows = () => host.platform === 'win32';
9
+ /** win32:lstat 不是重解析点(符号链接/junction 由 Node 报为 symlink)、类型对、文件硬链接数 1,且 ACL 私有。 */
10
+ async function windowsPrivate(path, directory, before) {
11
+ const s = before ?? await lstat(path);
12
+ if (s.isSymbolicLink() || (directory ? !s.isDirectory() : !s.isFile() || s.nlink !== 1))
13
+ throw new Error(directory ? 'PRIVATE_DIRECTORY_REQUIRED' : 'PRIVATE_FILE_REQUIRED');
14
+ const acl = await host.security.inspect(path);
15
+ if (acl.reparse || !privateSddl(acl.sddl, host.security.sid()))
16
+ throw new Error(directory ? 'PRIVATE_DIRECTORY_REQUIRED' : 'PRIVATE_FILE_REQUIRED');
17
+ return s;
18
+ }
19
+ /** win32:本进程新建的文件/目录收紧为私有(macOS 由 mode 0600/0700 在创建时完成,这里为空操作)。 */
20
+ export async function sealPrivate(path, directory = false) { if (windows())
21
+ await host.security.protect(path, directory); }
22
+ /** 目录 fsync:macOS 照旧;Windows 不能对目录句柄 FlushFileBuffers(实机 EPERM),NTFS 元数据由日志保证,跳过(同 LevelDB env_windows 不同步目录)。 */
23
+ export async function syncDirectory(path) { if (windows())
24
+ return; const d = await open(path, 'r'); try {
25
+ await d.sync();
26
+ }
27
+ finally {
28
+ await d.close();
29
+ } }
3
30
  export async function privateDirectory(path) {
31
+ if (windows()) {
32
+ // 本次新建的各级目录(mkdir 返回第一级新建目录)收紧为私有;已存在的只核不改(同 macOS mkdir mode 只作用于新建)。
33
+ const first = await mkdir(path, { recursive: true });
34
+ if (first !== undefined) {
35
+ const start = first.replace(/^\\\\\?\\/, '');
36
+ let current = start;
37
+ const rest = relative(start, path);
38
+ await sealPrivate(current, true);
39
+ for (const part of rest ? rest.split(sep) : []) {
40
+ current = join(current, part);
41
+ await sealPrivate(current, true);
42
+ }
43
+ }
44
+ await windowsPrivate(path, true);
45
+ return;
46
+ }
4
47
  await mkdir(path, { recursive: true, mode: 0o700 });
5
48
  const s = await lstat(path);
6
49
  if (!s.isDirectory() || s.isSymbolicLink() || s.uid !== process.getuid() || (s.mode & 0o077) !== 0)
7
50
  throw new Error('PRIVATE_DIRECTORY_REQUIRED');
8
51
  }
52
+ /** win32 只核私有目录,不建不改(读取他人交付的目录时用)。 */
53
+ export async function checkPrivateDirectory(path) {
54
+ if (windows()) {
55
+ await windowsPrivate(path, true);
56
+ return;
57
+ }
58
+ const s = await lstat(path);
59
+ if (!s.isDirectory() || s.isSymbolicLink() || s.uid !== process.getuid() || (s.mode & 0o077) !== 0)
60
+ throw new Error('PRIVATE_DIRECTORY_REQUIRED');
61
+ }
9
62
  export async function privateFile(path) {
63
+ if (windows()) {
64
+ await windowsPrivate(path, false);
65
+ return;
66
+ }
10
67
  const s = await lstat(path);
11
68
  if (!s.isFile() || s.isSymbolicLink() || s.uid !== process.getuid() || (s.mode & 0o177) !== 0)
12
69
  throw new Error('PRIVATE_FILE_REQUIRED');
13
70
  }
14
71
  export async function readPrivate(path, maxBytes) {
72
+ // win32 无 O_NOFOLLOW:先 lstat 核私有,打开后以 卷序列号+FileIndex 核仍是同一文件(被换掉即拒绝)。
73
+ const before = windows() ? await windowsPrivate(path, false) : undefined;
15
74
  const h = await open(path, constants.O_RDONLY | constants.O_NOFOLLOW);
16
75
  try {
17
76
  const s = await h.stat();
18
- if (!s.isFile() || s.uid !== process.getuid() || (s.mode & 0o177) !== 0)
77
+ if (!s.isFile() || (before ? s.dev !== before.dev || s.ino !== before.ino : s.uid !== process.getuid() || (s.mode & 0o177) !== 0))
19
78
  throw new Error('PRIVATE_FILE_REQUIRED');
20
79
  if (maxBytes === undefined)
21
80
  return await h.readFile('utf8');
@@ -39,3 +98,5 @@ export async function readPrivate(path, maxBytes) {
39
98
  await h.close();
40
99
  }
41
100
  }
101
+ /** 文件私有性(profile-enrollment 的来源文件核对用):win32 走 ACL,macOS 由调用方按 uid/mode 判。 */
102
+ export async function windowsPrivateFile(path, before) { await windowsPrivate(path, false, before); }
@@ -19,6 +19,14 @@ export interface AssemblySettings {
19
19
  }
20
20
  /** N 节点名:管理员设置优先,否则按员工账号、本机名与 uid 生成(与写给 N 的配置同源)。 */
21
21
  export declare const networkNodeName: (settings: AssemblySettings | undefined, employee: string) => string;
22
+ /**
23
+ * N 默认 stateDir/runtimeDir(设计 A 表):darwin `~/Library/Application Support/ai-workbench/network` 与 `/tmp/aw-net-<uid>`;
24
+ * win32 `%LOCALAPPDATA%\ai-workbench\network` 与 `%LOCALAPPDATA%\ai-workbench\network-run`(LOCALAPPDATA 缺失即报错,不回退)。
25
+ */
26
+ export declare function networkDirectories(platform?: string, env?: NodeJS.ProcessEnv): {
27
+ stateDir: string;
28
+ runtimeDir: string;
29
+ };
22
30
  interface Options {
23
31
  profileDir: string;
24
32
  metadataMaxBytes: number;
@@ -1,13 +1,26 @@
1
1
  import { open, rename, rm, realpath } from 'node:fs/promises';
2
- import { join, isAbsolute } from 'node:path';
3
- import { hostname, homedir } from 'node:os';
2
+ import { join, isAbsolute, win32 } from 'node:path';
3
+ import { homedir } from 'node:os';
4
4
  import { randomUUID } from 'node:crypto';
5
5
  import { ok, fail } from "./needs.js";
6
6
  import { mapNetworkNeed } from "./provider.js";
7
- import { privateDirectory, privateFile, readPrivate } from "./private-files.js";
7
+ import { privateDirectory, privateFile, readPrivate, sealPrivate, syncDirectory, host } from "./private-files.js";
8
+ import { nodeName } from "./node-name.js";
8
9
  import { NETWORK_DEFAULTS } from "./defaults.js";
9
10
  /** N 节点名:管理员设置优先,否则按员工账号、本机名与 uid 生成(与写给 N 的配置同源)。 */
10
- export const networkNodeName = (settings, employee) => settings?.nodeName ?? `aw-${employee}-${hostname()}-${process.getuid()}`;
11
+ export const networkNodeName = (settings, employee) => settings?.nodeName ?? nodeName(employee);
12
+ /**
13
+ * N 默认 stateDir/runtimeDir(设计 A 表):darwin `~/Library/Application Support/ai-workbench/network` 与 `/tmp/aw-net-<uid>`;
14
+ * win32 `%LOCALAPPDATA%\ai-workbench\network` 与 `%LOCALAPPDATA%\ai-workbench\network-run`(LOCALAPPDATA 缺失即报错,不回退)。
15
+ */
16
+ export function networkDirectories(platform = host.platform, env = process.env) {
17
+ if (platform !== 'win32')
18
+ return { stateDir: join(homedir(), 'Library', 'Application Support', 'ai-workbench', 'network'), runtimeDir: '/tmp/aw-net-' + process.getuid() };
19
+ const base = env.LOCALAPPDATA;
20
+ if (!base || !win32.isAbsolute(base))
21
+ throw Error('LOCALAPPDATA_REQUIRED');
22
+ return { stateDir: win32.join(base, 'ai-workbench', 'network'), runtimeDir: win32.join(base, 'ai-workbench', 'network-run') };
23
+ }
11
24
  // Own handoff configuration only. Never reads N's identity files, journal or key contents.
12
25
  export function createProfileActivation(options) {
13
26
  const root = join(options.profileDir, 'ai-workbench-connect'), recordFile = join(root, 'network-activation.json');
@@ -22,14 +35,9 @@ export function createProfileActivation(options) {
22
35
  finally {
23
36
  await h.close();
24
37
  }
38
+ await sealPrivate(temp);
25
39
  await rename(temp, file);
26
- const d = await open(join(file, '..'), 'r');
27
- try {
28
- await d.sync();
29
- }
30
- finally {
31
- await d.close();
32
- }
40
+ await syncDirectory(join(file, '..'));
33
41
  }
34
42
  finally {
35
43
  await rm(temp, { force: true });
@@ -52,9 +60,11 @@ export function createProfileActivation(options) {
52
60
  if (await realpath(p) !== p)
53
61
  return fail('ENROLLMENT_INVALID');
54
62
  const s = { ...NETWORK_DEFAULTS, ...options.settings };
63
+ let dirs;
64
+ const defaults = () => dirs ??= networkDirectories();
55
65
  const settings = { configFile: s.configFile ?? join(configDir, 'config.json'), helperLogFile: s.helperLogFile ?? join(logDir, 'network.log'), startupObservationSeconds: s.startupObservationSeconds, shutdownObservationSeconds: s.shutdownObservationSeconds, controlResponseMaxBytes: s.controlResponseMaxBytes };
56
66
  const target = { host: e.host, username: e.username, port: e.port, knownHostsFile: e.knownHostsFile };
57
- const expected = { apiVersion: 1, stateDir: s.stateDir ?? join(homedir(), 'Library', 'Application Support', 'ai-workbench', 'network'), runtimeDir: s.runtimeDir ?? '/tmp/aw-net-' + process.getuid(), nodeName: networkNodeName(s, e.username), host: { name: e.host, sshPort: e.port, employee: e.username, knownHostsFile: e.knownHostsFile }, logUpload: s.logUpload, statusRefreshIntervalSeconds: s.statusRefreshIntervalSeconds, dialTimeoutSeconds: s.dialTimeoutSeconds, headerTimeoutSeconds: s.headerTimeoutSeconds, enrollmentObservationSeconds: s.enrollmentObservationSeconds, httpMaxHeaderBytes: s.httpMaxHeaderBytes };
67
+ const expected = { apiVersion: 1, stateDir: s.stateDir ?? defaults().stateDir, runtimeDir: s.runtimeDir ?? defaults().runtimeDir, nodeName: networkNodeName(s, e.username), host: { name: e.host, sshPort: e.port, employee: e.username, knownHostsFile: e.knownHostsFile }, logUpload: s.logUpload, statusRefreshIntervalSeconds: s.statusRefreshIntervalSeconds, dialTimeoutSeconds: s.dialTimeoutSeconds, headerTimeoutSeconds: s.headerTimeoutSeconds, enrollmentObservationSeconds: s.enrollmentObservationSeconds, httpMaxHeaderBytes: s.httpMaxHeaderBytes };
58
68
  const canonical = (v) => JSON.stringify(v, (_, x) => x && typeof x === 'object' && !Array.isArray(x) ? Object.fromEntries(Object.entries(x).sort(([a], [b]) => a.localeCompare(b))) : x);
59
69
  const registration = { schemaVersion: 1, settings, target };
60
70
  let stored = false;
@@ -177,13 +187,7 @@ export function createProfileActivation(options) {
177
187
  throw error;
178
188
  }
179
189
  await rm(file);
180
- const d = await open(join(file, '..'), 'r');
181
- try {
182
- await d.sync();
183
- }
184
- finally {
185
- await d.close();
186
- }
190
+ await syncDirectory(join(file, '..'));
187
191
  }
188
192
  },
189
193
  activate(e, signal) { const target = JSON.stringify([e.host, e.username, e.port, e.knownHostsFile, e.projectRoot]); if (flight)
@@ -3,7 +3,7 @@ import { constants } from 'node:fs';
3
3
  import { join, isAbsolute, resolve, dirname, basename } from 'node:path';
4
4
  import { randomUUID, createHash } from 'node:crypto';
5
5
  import { readEnrollment } from "./enrollment.js";
6
- import { privateDirectory, privateFile, readPrivate } from "./private-files.js";
6
+ import { privateDirectory, privateFile, readPrivate, sealPrivate, syncDirectory, checkPrivateDirectory, windowsPrivateFile, host as files } from "./private-files.js";
7
7
  import { ok, fail, need, NeedError } from "./needs.js";
8
8
  // 钥匙仅作不透明文件复制;内容的解析、消费与事务清理由 N 独占。
9
9
  export function createProfileEnrollment(options) {
@@ -22,7 +22,35 @@ export function createProfileEnrollment(options) {
22
22
  const canonical = async (path) => { if (!isAbsolute(path) || await realpath(path) !== resolve(path))
23
23
  throw Error('NON_CANONICAL_DIRECTORY'); };
24
24
  const privateSource = (source) => dirname(source) === dataDir && /^enrollment-source-[a-f0-9-]{36}$/.test(basename(source));
25
+ // win32:类型/硬链接数/重解析点/ACL 私有(见 private-files);tighten 时不私有就先收紧再核(同 macOS chmod 600),打开后以 卷序列号+FileIndex 核同一文件。
26
+ const windowsSourceFile = async (path, tighten) => {
27
+ let before = await lstat(path);
28
+ if (!before.isFile() || before.isSymbolicLink() || before.nlink !== 1)
29
+ throw Error('SOURCE_FILE_INVALID');
30
+ try {
31
+ await windowsPrivateFile(path, before);
32
+ }
33
+ catch {
34
+ if (!tighten)
35
+ throw Error('SOURCE_FILE_INVALID');
36
+ await sealPrivate(path);
37
+ before = await lstat(path);
38
+ await windowsPrivateFile(path, before);
39
+ }
40
+ const h = await open(path, 'r');
41
+ try {
42
+ const stat = await h.stat();
43
+ if (stat.dev !== before.dev || stat.ino !== before.ino || !stat.isFile() || stat.nlink !== 1)
44
+ throw Error('SOURCE_FILE_INVALID');
45
+ return stat;
46
+ }
47
+ finally {
48
+ await h.close();
49
+ }
50
+ };
25
51
  const sourceFile = async (path, tighten = false) => {
52
+ if (files.platform === 'win32')
53
+ return windowsSourceFile(path, tighten);
26
54
  const before = await lstat(path);
27
55
  if (!before.isFile() || before.uid !== process.getuid() || before.nlink !== 1)
28
56
  throw Error('SOURCE_FILE_INVALID');
@@ -56,17 +84,12 @@ export function createProfileEnrollment(options) {
56
84
  finally {
57
85
  await h.close();
58
86
  }
87
+ await sealPrivate(temp);
59
88
  if (disposed || paused)
60
89
  throw Error('ACTIVATION_CANCELLED');
61
90
  await rename(temp, file);
62
91
  onCommit();
63
- const d = await open(dataDir, 'r');
64
- try {
65
- await d.sync();
66
- }
67
- finally {
68
- await d.close();
69
- }
92
+ await syncDirectory(dataDir);
70
93
  }
71
94
  finally {
72
95
  await rm(temp, { force: true });
@@ -101,6 +124,7 @@ export function createProfileEnrollment(options) {
101
124
  staging = join(dataDir, '.enrollment-source-' + id);
102
125
  destination = join(dataDir, 'enrollment-source-' + id);
103
126
  await mkdir(staging, { mode: 0o700 });
127
+ await sealPrivate(staging, true);
104
128
  const metadata = JSON.parse(await readPrivate(join(source, 'enroll.json'), options.metadataMaxBytes));
105
129
  const names = ['enroll.json', 'ssh-rule.json', ...(result.value.enrollment.authKeyFile ? [metadata.authKeyDelivery.path] : [])];
106
130
  for (const name of new Set(names)) {
@@ -118,15 +142,10 @@ export function createProfileEnrollment(options) {
118
142
  finally {
119
143
  await h.close();
120
144
  }
145
+ await sealPrivate(to);
121
146
  await sourceFile(to);
122
147
  }
123
- const directory = await open(staging, 'r');
124
- try {
125
- await directory.sync();
126
- }
127
- finally {
128
- await directory.close();
129
- }
148
+ await syncDirectory(staging);
130
149
  await rename(staging, destination);
131
150
  staging = undefined;
132
151
  const copied = await validate(destination, false, true);
@@ -216,19 +235,32 @@ export function createProfileEnrollment(options) {
216
235
  async function validate(source, tighten = false, relocated = false) {
217
236
  try {
218
237
  await canonical(source);
219
- const directory = await open(source, constants.O_RDONLY | constants.O_DIRECTORY | constants.O_NOFOLLOW);
220
- try {
221
- const d = await directory.stat();
222
- if (!d.isDirectory() || d.uid !== process.getuid() || (d.mode & 0o700) !== 0o700)
223
- return fail('ENROLLMENT_INVALID');
224
- if ((d.mode & 0o777) !== 0o700) {
238
+ if (files.platform === 'win32') {
239
+ try {
240
+ await checkPrivateDirectory(source);
241
+ }
242
+ catch {
225
243
  if (!tighten)
226
244
  return fail('ENROLLMENT_INVALID');
227
- await directory.chmod(0o700);
245
+ await sealPrivate(source, true);
246
+ await checkPrivateDirectory(source);
228
247
  }
229
248
  }
230
- finally {
231
- await directory.close();
249
+ else {
250
+ const directory = await open(source, constants.O_RDONLY | constants.O_DIRECTORY | constants.O_NOFOLLOW);
251
+ try {
252
+ const d = await directory.stat();
253
+ if (!d.isDirectory() || d.uid !== process.getuid() || (d.mode & 0o700) !== 0o700)
254
+ return fail('ENROLLMENT_INVALID');
255
+ if ((d.mode & 0o777) !== 0o700) {
256
+ if (!tighten)
257
+ return fail('ENROLLMENT_INVALID');
258
+ await directory.chmod(0o700);
259
+ }
260
+ }
261
+ finally {
262
+ await directory.close();
263
+ }
232
264
  }
233
265
  await sourceFile(join(source, 'enroll.json'), tighten);
234
266
  const metadata = await readPrivate(join(source, 'enroll.json'), options.metadataMaxBytes);
@@ -299,14 +331,9 @@ export function createProfileEnrollment(options) {
299
331
  finally {
300
332
  await h.close();
301
333
  }
334
+ await sealPrivate(temp);
302
335
  await rename(temp, file);
303
- const d = await open(dataDir, 'r');
304
- try {
305
- await d.sync();
306
- }
307
- finally {
308
- await d.close();
309
- }
336
+ await syncDirectory(dataDir);
310
337
  }
311
338
  finally {
312
339
  await rm(temp, { force: true });
@@ -350,13 +377,7 @@ export function createProfileEnrollment(options) {
350
377
  if (privateSource(record.source))
351
378
  await rm(record.source, { recursive: true, force: true });
352
379
  await rm(file, { force: true });
353
- const d = await open(dataDir, 'r');
354
- try {
355
- await d.sync();
356
- }
357
- finally {
358
- await d.close();
359
- }
380
+ await syncDirectory(dataDir);
360
381
  record = undefined;
361
382
  paused = false;
362
383
  abort = new AbortController();
@@ -4,7 +4,10 @@ import type { Ports } from './ports.ts';
4
4
  export declare function employeeKey(text: string): string | undefined;
5
5
  /** 本机 /etc/ssh/aiwb/<用户>.keys 里已授权的钥匙(同格式两段);缺失或格式不符返回 undefined。 */
6
6
  export declare function authorizedKey(text: string | undefined): string | undefined;
7
- /** 本机现状:钥匙文件内容、sshd 是否已由 launchd 载入、本人的 sshd 规则文件是否在。 */
7
+ /**
8
+ * 本机现状:钥匙文件内容、sshd 是否在(macOS launchd 已载入;Windows 本机 127.0.0.1:22 在听)、
9
+ * 本人的 sshd 规则在(macOS 规则文件存在;Windows sshd_config 里本人段内容与位置都符合)。
10
+ */
8
11
  export interface LocalAccess {
9
12
  keys?: string;
10
13
  sshdLoaded: boolean;
@@ -17,6 +20,29 @@ export declare function adminCommand(script: string, user: string, key: string):
17
20
  command: '/usr/bin/osascript';
18
21
  args: string[];
19
22
  };
23
+ /** Windows 本人一段规则(与 helper/remote-access.ps1 Get-AiwbSegment 同文)。 */
24
+ export declare function windowsSegment(user: string, programData: string): string[];
25
+ /**
26
+ * 与 remote-access.ps1 Set-AiwbSegment 同算法:已有本人段且它之前没有非本插件的 Match 行 → 原位整段替换;
27
+ * 否则(没有,或被挪到别的 Match 之后)去掉旧段,插在第一个 Match 行(或其他员工段的开始标记)之前、全局设置之后。有头无尾返回 undefined。
28
+ */
29
+ export declare function windowsSetSegment(text: string, user: string, programData: string): string | undefined;
30
+ /** sshd_config 里本人段内容与位置都符合(再写一次不会变)。 */
31
+ export declare function windowsSegmentOk(text: string | undefined, user: string, programData: string): boolean;
32
+ /** 内联进 -EncodedCommand 的脚本正文:去掉整行注释、空行与行首缩进(只为缩短命令行,语句不变)。 */
33
+ export declare function inlineScript(script: string): string;
34
+ /**
35
+ * Windows UAC 提权(设计 C):外层 powershell -Command 以 ShellExecuteEx “runas” 动词(ProcessStartInfo Verb=runas、UseShellExecute、隐藏窗口,
36
+ * 即 Start-Process -Verb RunAs 的同一底层调用)启动管理员 powershell 并等待,透传其退出码;脚本整段以 UTF-16LE base64 内联(-EncodedCommand),
37
+ * 参数为已校验的常量,不落到用户可写位置。用户在 UAC 点“否”时抛 Win32Exception 1223(ERROR_CANCELLED),外层以其 NativeErrorCode 退出。
38
+ * 不用 Start-Process 本身:Windows PowerShell 5.1 的 Start-Process 把 Win32Exception 换成只带本地化文字的 InvalidOperationException,丢了错误码(实机核过)。
39
+ */
40
+ export declare function windowsAdminCommand(script: string, user: string, sid: string, key: string, env?: NodeJS.ProcessEnv): {
41
+ command: string;
42
+ args: string[];
43
+ };
44
+ /** ERROR_CANCELLED(Microsoft Learn《System Error Codes (1000-1299)》):UAC 被拒绝。 */
45
+ export declare const WINDOWS_CANCELLED = 1223;
20
46
  interface RemoteAccessOptions {
21
47
  ssh: Required<Pick<NonNullable<Ports['ssh']>, 'employeeAccess'>>;
22
48
  user: string;
@@ -29,6 +55,10 @@ interface RemoteAccessOptions {
29
55
  }>;
30
56
  openSettings?: (url: string) => Promise<void>;
31
57
  script?: () => Promise<string>;
58
+ /** Windows:当前用户 SID(钥匙与入口文件只给本人读)。 */
59
+ sid?: () => string;
60
+ /** 工具桥插件提供的本机回连命令(可选服务 aiWorkbenchToolbridge);未装工具桥时为 undefined,登记不带该字段。 */
61
+ toolbridge?: () => string | undefined;
32
62
  warn?: (message: string) => void;
33
63
  }
34
64
  /** 系统设置“共享 → 远程登录”详情面板的官方深链接(含“允许远程用户完全磁盘访问”开关;该开关属 TCC,只能本人点开)。 */
@@ -1,11 +1,16 @@
1
1
  import { readFile } from 'node:fs/promises';
2
2
  import { execFile } from 'node:child_process';
3
3
  import { stat } from 'node:fs/promises';
4
+ import { connect } from 'node:net';
5
+ import { win32 } from 'node:path';
4
6
  import { shellQuote } from "./ssh.js";
5
- // TH2 约定 B/C:连上主机后把本机用户名与 N 节点名经主机 helper 按来源设备登记,并读主机 emp 公钥;
6
- // 本机“远程登录”未按该钥匙开通时,用 macOS 管理员授权框执行一次固定脚本(helper/remote-access.sh)。
7
+ import { windowsSecurity } from "./windows-security.js";
8
+ // TH2 约定 B/C:连上主机后把本机用户名、N 节点名、平台与工具桥回连命令经主机 helper 按来源设备登记,并读主机 emp 公钥;
9
+ // 本机“远程登录”未按该钥匙开通时,macOS 用管理员授权框执行一次固定脚本(helper/remote-access.sh),
10
+ // Windows 用 UAC 以管理员执行一次(helper/remote-access.ps1,设计 C,与 .sh 逐条对应)。
7
11
  const KEY = /^ssh-ed25519 [A-Za-z0-9+/]+=*( [ -~]*)?$/;
8
12
  const USER = /^[A-Za-z0-9._][A-Za-z0-9._-]*$/;
13
+ const SID = /^S-1-\d+(-\d+)+$/;
9
14
  /** 只认 ed25519 公钥;返回去掉注释的“类型 base64”两段,注释不进入授权文件。 */
10
15
  export function employeeKey(text) {
11
16
  const line = text.trim();
@@ -33,6 +38,61 @@ export function adminCommand(script, user, key) {
33
38
  const shell = `/bin/sh -c '${script.replaceAll("'", "'\\''")}' aiwb-remote-access ${shellQuote(user)} ${shellQuote(key)}`;
34
39
  return { command: '/usr/bin/osascript', args: ['-e', `do shell script ${appleString(shell)} with administrator privileges`] };
35
40
  }
41
+ /** Windows 本人一段规则(与 helper/remote-access.ps1 Get-AiwbSegment 同文)。 */
42
+ export function windowsSegment(user, programData) {
43
+ const u = user.toLowerCase();
44
+ 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}`];
45
+ }
46
+ /**
47
+ * 与 remote-access.ps1 Set-AiwbSegment 同算法:已有本人段且它之前没有非本插件的 Match 行 → 原位整段替换;
48
+ * 否则(没有,或被挪到别的 Match 之后)去掉旧段,插在第一个 Match 行(或其他员工段的开始标记)之前、全局设置之后。有头无尾返回 undefined。
49
+ */
50
+ export function windowsSetSegment(text, user, programData) {
51
+ const u = user.toLowerCase(), nl = text.length > 0 && !text.includes('\r\n') ? '\n' : '\r\n';
52
+ const lines = text.length > 0 ? text.split(/\r?\n/) : [];
53
+ if (lines.length && lines.at(-1) === '')
54
+ lines.pop();
55
+ const begin = lines.indexOf(`# aiwb-begin ${u}`), end = begin < 0 ? -1 : lines.indexOf(`# aiwb-end ${u}`, begin + 1);
56
+ if (begin >= 0 && end < 0)
57
+ return undefined;
58
+ const foreign = (i) => /^\s*Match\s/i.test(lines[i]) && !(i > 0 && lines[i - 1].startsWith('# aiwb-begin '));
59
+ const segment = windowsSegment(user, programData);
60
+ if (begin >= 0 && !lines.slice(0, begin).some((_, i) => foreign(i))) {
61
+ lines.splice(begin, end - begin + 1, ...segment);
62
+ return lines.join(nl) + nl;
63
+ }
64
+ if (begin >= 0)
65
+ lines.splice(begin, end - begin + 1);
66
+ let at = lines.findIndex(line => /^\s*Match\s/i.test(line) || line.startsWith('# aiwb-begin '));
67
+ if (at < 0)
68
+ at = lines.length;
69
+ lines.splice(at, 0, ...segment);
70
+ return lines.join(nl) + nl;
71
+ }
72
+ /** sshd_config 里本人段内容与位置都符合(再写一次不会变)。 */
73
+ export function windowsSegmentOk(text, user, programData) { return text !== undefined && windowsSetSegment(text, user, programData) === text; }
74
+ /** 内联进 -EncodedCommand 的脚本正文:去掉整行注释、空行与行首缩进(只为缩短命令行,语句不变)。 */
75
+ export function inlineScript(script) { return script.split(/\r?\n/).map(line => line.trim()).filter(line => line && !line.startsWith('#')).join('\n'); }
76
+ const psLiteral = (value) => "'" + value.replaceAll(/['\u2018\u2019\u201A\u201B]/g, match => match + match) + "'";
77
+ /**
78
+ * Windows UAC 提权(设计 C):外层 powershell -Command 以 ShellExecuteEx “runas” 动词(ProcessStartInfo Verb=runas、UseShellExecute、隐藏窗口,
79
+ * 即 Start-Process -Verb RunAs 的同一底层调用)启动管理员 powershell 并等待,透传其退出码;脚本整段以 UTF-16LE base64 内联(-EncodedCommand),
80
+ * 参数为已校验的常量,不落到用户可写位置。用户在 UAC 点“否”时抛 Win32Exception 1223(ERROR_CANCELLED),外层以其 NativeErrorCode 退出。
81
+ * 不用 Start-Process 本身:Windows PowerShell 5.1 的 Start-Process 把 Win32Exception 换成只带本地化文字的 InvalidOperationException,丢了错误码(实机核过)。
82
+ */
83
+ export function windowsAdminCommand(script, user, sid, key, env = process.env) {
84
+ if (!USER.test(user) || !SID.test(sid))
85
+ throw Error('AW_REMOTE_ACCESS_USER_INVALID');
86
+ const normalized = employeeKey(key);
87
+ if (normalized === undefined || normalized !== key)
88
+ throw Error('AW_REMOTE_ACCESS_KEY_INVALID');
89
+ const body = `$AiwbUser=${psLiteral(user)};$AiwbSid=${psLiteral(sid)};$AiwbKey=${psLiteral(key)}\n` + inlineScript(script);
90
+ const encoded = Buffer.from(body, 'utf16le').toString('base64');
91
+ 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}`;
92
+ return { command: `${env.SYSTEMROOT || env.windir || 'C:\\Windows'}\\System32\\WindowsPowerShell\\v1.0\\powershell.exe`, args: ['-NoProfile', '-NonInteractive', '-Command', outer] };
93
+ }
94
+ /** ERROR_CANCELLED(Microsoft Learn《System Error Codes (1000-1299)》):UAC 被拒绝。 */
95
+ export const WINDOWS_CANCELLED = 1223;
36
96
  const missing = (error) => error.code === 'ENOENT';
37
97
  // launchctl print 对 system 域只读,普通用户可执行;退出码 0 即服务已载入(Apple launchctl(1))。
38
98
  const sshdLoaded = () => new Promise(resolve => execFile('/bin/launchctl', ['print', 'system/com.openssh.sshd'], { timeout: 0 }, error => resolve(!error)));
@@ -62,6 +122,27 @@ const runAdmin = (command, args) => new Promise(resolve => execFile(command, arg
62
122
  export const REMOTE_LOGIN_SETTINGS = 'x-apple.systempreferences:com.apple.Sharing-Settings.extension?Services_RemoteLogin';
63
123
  const openSettings = (url) => new Promise((resolve, reject) => execFile('/usr/bin/open', [url], { timeout: 0 }, error => error ? reject(error) : resolve()));
64
124
  const script = () => readFile(new URL('../helper/remote-access.sh', import.meta.url), 'utf8');
125
+ const windowsScript = () => readFile(new URL('../helper/remote-access.ps1', import.meta.url), 'utf8');
126
+ // 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
+ const readOptional = async (path) => { try {
129
+ return await readFile(path, 'utf8');
130
+ }
131
+ catch (error) {
132
+ if (missing(error))
133
+ return undefined;
134
+ throw error;
135
+ } };
136
+ const windowsLocalAccess = async (user) => {
137
+ const programData = process.env.ProgramData;
138
+ if (!programData || !win32.isAbsolute(programData))
139
+ throw Error('PROGRAMDATA_REQUIRED');
140
+ const keys = await readOptional(win32.join(programData, 'ssh', 'aiwb', user.toLowerCase() + '.keys'));
141
+ const config = await readOptional(win32.join(programData, 'ssh', 'sshd_config'));
142
+ return { keys, sshdLoaded: await listening(), confExists: windowsSegmentOk(config, user, programData) };
143
+ };
144
+ // 外层 powershell 以 UAC 结果退出:0 成功,1223 用户拒绝,其余失败。
145
+ 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 }); }));
65
146
  export function createRemoteAccess(options) {
66
147
  // 取消或失败后本进程不再弹,下次 DSH 启动再试(约定 B)。
67
148
  let declined = false, flight;
@@ -72,27 +153,35 @@ export function createRemoteAccess(options) {
72
153
  warn('远程登录开通:本机用户名或网络节点名不可用,跳过。');
73
154
  return;
74
155
  }
75
- const remote = await options.ssh.employeeAccess(target, JSON.stringify({ user: options.user, node }), signal);
156
+ const platform = options.platform ?? process.platform, supported = platform === 'darwin' || platform === 'win32';
157
+ // 设备登记带平台(设计 C)与工具桥插件运行时提供的回连命令(设计 D);没装工具桥就不带 toolbridge,主机按缺省处理;平台缺省主机按 darwin。
158
+ const toolbridge = supported ? options.toolbridge?.() : undefined;
159
+ const device = supported ? { user: options.user, node, platform, ...toolbridge === undefined ? {} : { toolbridge } } : { user: options.user, node };
160
+ const remote = await options.ssh.employeeAccess(target, JSON.stringify(device), signal);
76
161
  if (!remote.ok) {
77
162
  warn('远程登录开通:未能写入主机员工资料或读取主机钥匙(' + remote.error.code + ')。');
78
163
  return;
79
164
  }
80
- if ((options.platform ?? process.platform) !== 'darwin' || declined || signal.aborted)
165
+ if (!supported || declined || signal.aborted)
81
166
  return;
82
167
  const key = employeeKey(remote.value);
83
168
  if (!key) {
84
169
  warn('远程登录开通:主机员工钥匙缺失或格式不符,跳过。');
85
170
  return;
86
171
  }
87
- if (!needsSetup(await (options.localAccess ?? localAccess)(options.user), key))
172
+ const windows = platform === 'win32';
173
+ if (!needsSetup(await (options.localAccess ?? (windows ? windowsLocalAccess : localAccess))(options.user), key))
88
174
  return;
89
- const admin = adminCommand(await (options.script ?? script)(), options.user, key);
90
- const result = await (options.runAdmin ?? runAdmin)(admin.command, admin.args);
175
+ const admin = windows ? windowsAdminCommand(await (options.script ?? windowsScript)(), options.user, (options.sid ?? (() => windowsSecurity.sid()))(), key) : adminCommand(await (options.script ?? script)(), options.user, key);
176
+ const result = await (options.runAdmin ?? (windows ? windowsRunAdmin : runAdmin))(admin.command, admin.args);
91
177
  if (!result.ok) {
92
178
  declined = true;
93
179
  warn(result.cancelled ? '远程登录开通:员工取消了授权,本次运行不再询问。' : '远程登录开通:管理员脚本未成功,本次运行不再询问。');
94
180
  return;
95
181
  }
182
+ // Windows 没有 TCC“完全磁盘访问”对应项:开通成功后不打开任何设置面板。
183
+ if (windows)
184
+ return;
96
185
  // 开通成功后打开一次“远程登录”详情,员工自己打开完全磁盘访问开关(owner 11-18);打不开只记警告。
97
186
  try {
98
187
  await (options.openSettings ?? openSettings)(REMOTE_LOGIN_SETTINGS);
@@ -0,0 +1,19 @@
1
+ /** 本机 Windows 安全接口;测试注入替身。 */
2
+ export interface WindowsSecurity {
3
+ /** 当前进程用户的 SID(S-1-...)。 */
4
+ sid(): string;
5
+ /** 读所有者与 DACL(SDDL)及是否重解析点。 */
6
+ inspect(path: string): Promise<{
7
+ sddl: string;
8
+ reparse: boolean;
9
+ }>;
10
+ /** 把 DACL 换成受保护的“本人/SYSTEM/Administrators 完全控制”(目录带对象与容器继承)。 */
11
+ protect(path: string, directory: boolean): Promise<void>;
12
+ }
13
+ /** whoami /user /fo csv /nh 的输出 → SID;不认的输出返回 undefined。 */
14
+ export declare function parseWhoami(text: string): string | undefined;
15
+ /** SID 末段(RID):Windows 上与 macOS uid 同用途(节点名后缀)。 */
16
+ export declare function rid(sid: string): string;
17
+ /** SDDL 判定:所有者是本人、DACL 受保护、每条 ACE 都是“允许”且对象只在 本人/SYSTEM/Administrators 之内。 */
18
+ export declare function privateSddl(sddl: string, sid: string): boolean;
19
+ export declare const windowsSecurity: WindowsSecurity;
@@ -0,0 +1,61 @@
1
+ import { execFile, execFileSync } from 'node:child_process';
2
+ import { lstat } from 'node:fs/promises';
3
+ import { join } from 'node:path';
4
+ const SYSTEM = 'S-1-5-18', ADMINS = 'S-1-5-32-544';
5
+ const ALIAS = { SY: SYSTEM, BA: ADMINS };
6
+ const system32 = () => join(process.env.SystemRoot ?? process.env.windir ?? 'C:\\Windows', 'System32');
7
+ const run = (file, args, env) => new Promise((resolve, reject) => execFile(file, args, { encoding: 'utf8', windowsHide: true, timeout: 0, ...env ? { env } : {} }, (error, stdout) => error ? reject(error) : resolve(stdout)));
8
+ /** whoami /user /fo csv /nh 的输出 → SID;不认的输出返回 undefined。 */
9
+ export function parseWhoami(text) { return /"(S-1-\d+(?:-\d+)+)"\s*$/.exec(text.trim())?.[1]; }
10
+ /** SID 末段(RID):Windows 上与 macOS uid 同用途(节点名后缀)。 */
11
+ export function rid(sid) { const last = /-(\d+)$/.exec(sid)?.[1]; if (!last)
12
+ throw Error('WINDOWS_SID_INVALID'); return last; }
13
+ /** SDDL 判定:所有者是本人、DACL 受保护、每条 ACE 都是“允许”且对象只在 本人/SYSTEM/Administrators 之内。 */
14
+ export function privateSddl(sddl, sid) {
15
+ const owner = /^O:([^:]+?)(?=[GDS]:|$)/.exec(sddl)?.[1];
16
+ if (owner === undefined || (ALIAS[owner] ?? owner) !== sid)
17
+ return false;
18
+ const dacl = /D:([A-Z_]*)((?:\([^)]*\))*)$/.exec(sddl);
19
+ if (!dacl || !dacl[1].includes('P') || dacl[1].includes('NO_ACCESS_CONTROL'))
20
+ return false;
21
+ const allowed = new Set([sid, SYSTEM, ADMINS]);
22
+ for (const ace of dacl[2].match(/\([^)]*\)/g) ?? []) {
23
+ const parts = ace.slice(1, -1).split(';');
24
+ if (parts.length !== 6 || parts[0] !== 'A' || !allowed.has(ALIAS[parts[5]] ?? parts[5]))
25
+ return false;
26
+ }
27
+ return true;
28
+ }
29
+ // 结果按 路径+卷序列号+FileIndex+ChangeTime 缓存:NTFS 在 ACL/所有者改动时更新 ChangeTime(Node ctimeMs,Windows 实机已核),变了就重读。
30
+ const cache = new Map();
31
+ let sidValue;
32
+ const INSPECT = "$ErrorActionPreference='Stop';$i=Get-Item -LiteralPath $env:AW_ACL_PATH -Force;$s=$i.GetAccessControl('Owner,Access').GetSecurityDescriptorSddlForm('Owner,Access');[Console]::Out.Write((ConvertTo-Json -Compress @{sddl=$s;reparse=[bool]($i.Attributes -band [IO.FileAttributes]::ReparsePoint)}))";
33
+ export const windowsSecurity = {
34
+ sid() {
35
+ if (sidValue)
36
+ return sidValue;
37
+ const sid = parseWhoami(execFileSync(join(system32(), 'whoami.exe'), ['/user', '/fo', 'csv', '/nh'], { encoding: 'utf8', windowsHide: true }));
38
+ if (!sid)
39
+ throw Error('WINDOWS_SID_UNAVAILABLE');
40
+ return sidValue = sid;
41
+ },
42
+ async inspect(path) {
43
+ const before = await lstat(path), hit = cache.get(path);
44
+ if (hit && hit.dev === before.dev && hit.ino === before.ino && hit.ctimeMs === before.ctimeMs)
45
+ return hit.value;
46
+ // 路径经环境变量传入,不进命令文本(无引号转义问题)。
47
+ const out = JSON.parse(await run(join(system32(), 'WindowsPowerShell', 'v1.0', 'powershell.exe'), ['-NoProfile', '-NonInteractive', '-Command', INSPECT], { ...process.env, AW_ACL_PATH: path }));
48
+ if (typeof out?.sddl !== 'string' || typeof out.reparse !== 'boolean')
49
+ throw Error('WINDOWS_ACL_UNREADABLE');
50
+ const value = { sddl: out.sddl, reparse: out.reparse }, after = await lstat(path);
51
+ if (after.dev === before.dev && after.ino === before.ino && after.ctimeMs === before.ctimeMs)
52
+ cache.set(path, { dev: after.dev, ino: after.ino, ctimeMs: after.ctimeMs, value });
53
+ return value;
54
+ },
55
+ async protect(path, directory) {
56
+ const inherit = directory ? '(OI)(CI)' : '';
57
+ // 先清掉显式授权(/reset),再去继承并只授三方(/inheritance:r /grant:r),效果同 macOS chmod 600/700。
58
+ await run(join(system32(), 'icacls.exe'), [path, '/reset', '/Q']);
59
+ await run(join(system32(), 'icacls.exe'), [path, '/inheritance:r', '/grant:r', `*${this.sid()}:${inherit}F`, `*${SYSTEM}:${inherit}F`, `*${ADMINS}:${inherit}F`, '/Q']);
60
+ },
61
+ };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ai-workbench/connect",
3
- "version": "0.7.54",
3
+ "version": "0.7.55-rc.1",
4
4
  "type": "module",
5
5
  "engines": {
6
6
  "node": ">=24.13.1",