@ai-workbench/connect 0.7.54 → 0.7.55-rc.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -0
- package/helper/remote-access.ps1 +255 -0
- package/lib/account-enrollment.js +6 -4
- package/lib/browser-login.d.ts +10 -0
- package/lib/browser-login.js +15 -3
- package/lib/connect.js +2 -1
- package/lib/enrollment.js +8 -4
- package/lib/index.js +8 -1
- package/lib/network.d.ts +5 -0
- package/lib/network.js +19 -6
- package/lib/node-name.d.ts +5 -0
- package/lib/node-name.js +8 -0
- package/lib/private-files.d.ts +15 -0
- package/lib/private-files.js +62 -1
- package/lib/profile-activation.d.ts +8 -0
- package/lib/profile-activation.js +23 -19
- package/lib/profile-enrollment.js +59 -38
- package/lib/remote-access.d.ts +35 -1
- package/lib/remote-access.js +100 -7
- package/lib/ssh.d.ts +5 -0
- package/lib/ssh.js +9 -1
- package/lib/windows-security.d.ts +19 -0
- package/lib/windows-security.js +61 -0
- package/package.json +1 -1
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,255 @@
|
|
|
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
|
+
# MSI 暂存的上级目录(只有 SYSTEM/管理员可写的新子目录建在其下);断言脚本在库模式下改指测试目录。
|
|
15
|
+
$AiwbTemp = Join-Path $env:SystemRoot 'Temp'
|
|
16
|
+
|
|
17
|
+
function Test-AiwbUser([string]$User) { return $User -cmatch '\A[A-Za-z0-9._][A-Za-z0-9._-]*\z' }
|
|
18
|
+
function Test-AiwbKey([string]$Key) { return ($Key -notmatch "[`r`n]") -and ($Key -cmatch '\Assh-ed25519 [A-Za-z0-9+/]+=*( [ -~]*)?\z') }
|
|
19
|
+
function Test-AiwbSid([string]$Sid) { return $Sid -cmatch '\AS-1-[0-9]+(-[0-9]+)+\z' }
|
|
20
|
+
|
|
21
|
+
# 本人一段规则(用户名小写:Win32-OpenSSH 的 Match User 只认小写)。
|
|
22
|
+
function Get-AiwbSegment([string]$User, [string]$ProgramData) {
|
|
23
|
+
$u = $User.ToLowerInvariant()
|
|
24
|
+
return @(
|
|
25
|
+
"# aiwb-begin $u",
|
|
26
|
+
"Match User $u",
|
|
27
|
+
" AuthorizedKeysFile __PROGRAMDATA__/ssh/aiwb/$u.keys",
|
|
28
|
+
' AuthenticationMethods publickey',
|
|
29
|
+
' AcceptEnv AW_EMP_CWD',
|
|
30
|
+
" ForceCommand powershell.exe -NoProfile -NonInteractive -ExecutionPolicy Bypass -File `"$ProgramData\ssh\aiwb\entry.ps1`"",
|
|
31
|
+
"# aiwb-end $u"
|
|
32
|
+
)
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
# 返回改好的全文:已有本人段且它之前没有非本插件的 Match 行 → 原位整段替换;否则(没有,或被挪到别的 Match 之后)去掉旧段,
|
|
36
|
+
# 插在第一个 Match 行(或其他员工段的开始标记)之前、全局设置之后;没有 Match 就放末尾。换行沿用原文(空文件用 CRLF);有头无尾的本人段不猜,报错。
|
|
37
|
+
function Set-AiwbSegment([string]$Text, [string]$User, [string]$ProgramData) {
|
|
38
|
+
$u = $User.ToLowerInvariant()
|
|
39
|
+
$nl = "`r`n"; if ($Text.Length -gt 0 -and -not $Text.Contains("`r`n")) { $nl = "`n" }
|
|
40
|
+
$lines = New-Object 'System.Collections.Generic.List[string]'
|
|
41
|
+
if ($Text.Length -gt 0) { foreach ($l in ($Text -split "\r?\n")) { $lines.Add($l) } }
|
|
42
|
+
if ($lines.Count -gt 0 -and $lines[$lines.Count - 1] -eq '') { $lines.RemoveAt($lines.Count - 1) }
|
|
43
|
+
$begin = $lines.IndexOf("# aiwb-begin $u"); $end = -1
|
|
44
|
+
if ($begin -ge 0) { $end = $lines.IndexOf("# aiwb-end $u", $begin + 1); if ($end -lt 0) { throw 'AW_REMOTE_ACCESS_SSHD_INVALID' } }
|
|
45
|
+
$segment = [string[]](Get-AiwbSegment $User $ProgramData)
|
|
46
|
+
if ($begin -ge 0) {
|
|
47
|
+
$foreign = $false
|
|
48
|
+
for ($i = 0; $i -lt $begin; $i++) { if ($lines[$i] -match '\A\s*Match\s' -and -not ($i -gt 0 -and $lines[$i - 1].StartsWith('# aiwb-begin '))) { $foreign = $true } }
|
|
49
|
+
$lines.RemoveRange($begin, $end - $begin + 1)
|
|
50
|
+
if (-not $foreign) { $lines.InsertRange($begin, $segment); return ($lines -join $nl) + $nl }
|
|
51
|
+
}
|
|
52
|
+
$at = $lines.Count
|
|
53
|
+
for ($i = 0; $i -lt $lines.Count; $i++) { if ($lines[$i] -match '\A\s*Match\s' -or $lines[$i].StartsWith('# aiwb-begin ')) { $at = $i; break } }
|
|
54
|
+
$lines.InsertRange($at, $segment)
|
|
55
|
+
return ($lines -join $nl) + $nl
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
# 以 SDDL 写所有者(SDDL 带 O: 时)与 DACL;SetAccessControl 只落给出的部分;D:P 为去继承。依据:.NET FileSystemSecurity.SetSecurityDescriptorSddlForm/File.SetAccessControl。
|
|
59
|
+
function Set-AiwbAcl([string]$Path, [string]$Sddl) {
|
|
60
|
+
$sections = 'Access'; if ($Sddl.StartsWith('O:')) { $sections = 'Owner,Access' }
|
|
61
|
+
if ([IO.Directory]::Exists($Path)) {
|
|
62
|
+
$acl = New-Object Security.AccessControl.DirectorySecurity; $acl.SetSecurityDescriptorSddlForm($Sddl, $sections); [IO.Directory]::SetAccessControl($Path, $acl)
|
|
63
|
+
} else {
|
|
64
|
+
$acl = New-Object Security.AccessControl.FileSecurity; $acl.SetSecurityDescriptorSddlForm($Sddl, $sections); [IO.File]::SetAccessControl($Path, $acl)
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
# 只归管理员:所有者是 Administrators 或 SYSTEM,且 SYSTEM/Administrators 之外的允许项不带写类权限
|
|
69
|
+
# (WRITE_DATA/ADD_FILE|APPEND_DATA/ADD_SUBDIRECTORY|WRITE_EA|DELETE_CHILD|WRITE_ATTRIBUTES|DELETE|WRITE_DAC|WRITE_OWNER|GENERIC_ALL|GENERIC_WRITE = 0x500D0156)。
|
|
70
|
+
function Test-AiwbAdminOnly([string]$Path) {
|
|
71
|
+
$acl = Get-Acl -LiteralPath $Path
|
|
72
|
+
if (@('S-1-5-32-544', 'S-1-5-18') -notcontains $acl.GetOwner([Security.Principal.SecurityIdentifier]).Value) { return $false }
|
|
73
|
+
foreach ($r in $acl.GetAccessRules($true, $true, [Security.Principal.SecurityIdentifier])) {
|
|
74
|
+
if ($r.AccessControlType -eq 'Allow' -and @('S-1-5-32-544', 'S-1-5-18') -notcontains $r.IdentityReference.Value -and ([int64]$r.FileSystemRights -band 0x500D0156)) { return $false }
|
|
75
|
+
}
|
|
76
|
+
return $true
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
# 已存在的 ssh 目录、sshd_config、主机私钥若不是只归管理员,重置为 Win32-OpenSSH 自建时的所有者与 DACL(同其 FixHostFilePermissions 的做法)并读回核验;
|
|
80
|
+
# 重置不了(如他人文件拒绝管理员改所有者)即报错、整体撤回。选择重置而不是直接报错:这些位置的正确权限是确定的(sshd 自己就按此建),重置只会收紧。
|
|
81
|
+
# 重置不随撤回恢复(同 macOS 撤回时保留主机钥匙:恢复成宽松权限没有意义)。
|
|
82
|
+
function Repair-AiwbAdminOnly([string]$Path, [string]$Sddl) {
|
|
83
|
+
if (Test-AiwbAdminOnly $Path) { return }
|
|
84
|
+
Set-AiwbAcl $Path $Sddl
|
|
85
|
+
if (-not (Test-AiwbAdminOnly $Path)) { throw 'AW_REMOTE_ACCESS_SSHD_INVALID' }
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
# OpenSSH Server 入站防火墙规则:FoD 建 OpenSSH-Server-In-TCP,官方 MSI 建 “OpenSSH SSH Server Preview (sshd)”(MSI 的 WixFirewallException)。
|
|
89
|
+
function Get-AiwbFirewallRules {
|
|
90
|
+
@(Get-NetFirewallRule -Name 'OpenSSH-Server-In-TCP' -ErrorAction SilentlyContinue) + @(Get-NetFirewallRule -DisplayName 'OpenSSH SSH Server Preview (sshd)' -ErrorAction SilentlyContinue) | Where-Object { $_ }
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
# 先写 <文件>.tmp(UTF-8 无 BOM),设 ACL,再替换到位(同卷改名,ACL 随文件)。
|
|
94
|
+
function Write-AiwbFile([string]$Path, [string]$Text, [string]$Sddl) {
|
|
95
|
+
$tmp = "$Path.tmp"
|
|
96
|
+
[IO.File]::WriteAllText($tmp, $Text, (New-Object Text.UTF8Encoding($false)))
|
|
97
|
+
Set-AiwbAcl $tmp $Sddl
|
|
98
|
+
Move-Item -LiteralPath $tmp -Destination $Path -Force
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
# 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 原样继承。
|
|
103
|
+
function Get-AiwbEntry {
|
|
104
|
+
return @'
|
|
105
|
+
$ErrorActionPreference = 'Continue'
|
|
106
|
+
$moved = $false
|
|
107
|
+
if ($env:AW_EMP_CWD) { try { Set-Location -LiteralPath $env:AW_EMP_CWD -ErrorAction Stop; $moved = $true } catch { } }
|
|
108
|
+
if (-not $moved) { try { Set-Location -LiteralPath $HOME -ErrorAction Stop } catch { exit 1 } }
|
|
109
|
+
$candidates = @("$env:ProgramFiles\PowerShell\7\pwsh.exe")
|
|
110
|
+
foreach ($e in ("$env:PATH" -split ';')) { $t = $e.Trim().Trim('"'); if ($t) { $candidates += ($t.TrimEnd('\') + '\pwsh.exe') } }
|
|
111
|
+
$candidates += "$env:SystemRoot\System32\WindowsPowerShell\v1.0\powershell.exe"
|
|
112
|
+
$shell = 'pwsh'
|
|
113
|
+
foreach ($c in $candidates) { if ([IO.File]::Exists($c)) { $shell = $c; break } }
|
|
114
|
+
if ($env:SSH_ORIGINAL_COMMAND) {
|
|
115
|
+
$pre = '[Console]::OutputEncoding = [System.Text.UTF8Encoding]::new($false); $OutputEncoding = [System.Text.UTF8Encoding]::new($false); '
|
|
116
|
+
$enc = [Convert]::ToBase64String([Text.Encoding]::Unicode.GetBytes($pre + $env:SSH_ORIGINAL_COMMAND))
|
|
117
|
+
& $shell -NoLogo -NoProfile -NonInteractive -EncodedCommand $enc
|
|
118
|
+
exit $LASTEXITCODE
|
|
119
|
+
}
|
|
120
|
+
& $shell -NoLogo
|
|
121
|
+
exit $LASTEXITCODE
|
|
122
|
+
'@
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
# 系统 FoD 安装 OpenSSH Server;失败(如 WSUS/离线 0x800f0954)改装固定版本官方 MSI:先整份下载到内存核 SHA256,
|
|
126
|
+
# 再写进新建时即只许 SYSTEM/管理员访问的目录(不落到用户可写位置),msiexec 静默只装 Server,装完删除。
|
|
127
|
+
function Install-AiwbSshd {
|
|
128
|
+
try { Add-WindowsCapability -Online -Name 'OpenSSH.Server~~~~0.0.1.0' | Out-Null } catch { }
|
|
129
|
+
if (Get-Service -Name sshd -ErrorAction SilentlyContinue) { return }
|
|
130
|
+
[Net.ServicePointManager]::SecurityProtocol = [Net.ServicePointManager]::SecurityProtocol -bor [Net.SecurityProtocolType]::Tls12
|
|
131
|
+
$bytes = (Invoke-WebRequest -UseBasicParsing -Uri $AiwbMsiUrl).Content
|
|
132
|
+
$hash = -join ([Security.Cryptography.SHA256]::Create().ComputeHash([byte[]]$bytes) | ForEach-Object { $_.ToString('X2') })
|
|
133
|
+
if ($hash -ne $AiwbMsiSha256) { throw 'AW_REMOTE_ACCESS_MSI_HASH' }
|
|
134
|
+
$sec = New-Object Security.AccessControl.DirectorySecurity
|
|
135
|
+
$sec.SetSecurityDescriptorSddlForm('D:P(A;OICI;FA;;;SY)(A;OICI;FA;;;BA)')
|
|
136
|
+
$dir = Join-Path $AiwbTemp ('aiwb-openssh-' + [guid]::NewGuid().ToString('N'))
|
|
137
|
+
[void][IO.Directory]::CreateDirectory($dir, $sec)
|
|
138
|
+
try {
|
|
139
|
+
$msi = Join-Path $dir 'OpenSSH-Win64.msi'
|
|
140
|
+
$fs = New-Object IO.FileStream($msi, [IO.FileMode]::CreateNew, [IO.FileAccess]::Write)
|
|
141
|
+
try { $fs.Write([byte[]]$bytes, 0, $bytes.Length) } finally { $fs.Dispose() }
|
|
142
|
+
$p = Start-Process -FilePath (Join-Path $env:SystemRoot 'System32\msiexec.exe') -ArgumentList @('/i', "`"$msi`"", 'ADDLOCAL=Server', '/qn') -Wait -PassThru -WindowStyle Hidden
|
|
143
|
+
if ($p.ExitCode -ne 0 -and $p.ExitCode -ne 3010) { throw 'AW_REMOTE_ACCESS_MSI_FAILED' }
|
|
144
|
+
} finally { Remove-Item -LiteralPath $dir -Recurse -Force -ErrorAction SilentlyContinue }
|
|
145
|
+
if (-not (Get-Service -Name sshd -ErrorAction SilentlyContinue)) { throw 'AW_REMOTE_ACCESS_SSHD_MISSING' }
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
# 运行 sshd.exe/ssh-keygen.exe 只取退出码:输出丢弃;在本函数内把错误偏好设为 Continue,免得 PowerShell 5.1 在 stderr 被重定向时把原生程序的 stderr 包成错误记录而中止。
|
|
149
|
+
function Invoke-AiwbNative([string]$Exe, [string[]]$Arguments) {
|
|
150
|
+
$ErrorActionPreference = 'Continue'
|
|
151
|
+
& $Exe @Arguments 2>&1 | Out-Null
|
|
152
|
+
return $LASTEXITCODE
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
# sshd.exe 的位置取自服务登记(FoD 在 System32\OpenSSH,MSI 在 Program Files\OpenSSH)。
|
|
156
|
+
function Get-AiwbSshdPath {
|
|
157
|
+
$image = (Get-CimInstance -ClassName Win32_Service -Filter "Name='sshd'").PathName
|
|
158
|
+
if ($image -match '\A"([^"]+)"') { return $Matches[1] }
|
|
159
|
+
return ($image -split ' ')[0]
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
function Invoke-AiwbRemoteAccess([string]$User, [string]$Sid, [string]$Key) {
|
|
163
|
+
if (-not (Test-AiwbUser $User) -or -not (Test-AiwbSid $Sid)) { [Console]::Error.WriteLine('AW_REMOTE_ACCESS_USER_INVALID'); return 2 }
|
|
164
|
+
if (-not (Test-AiwbKey $Key)) { [Console]::Error.WriteLine('AW_REMOTE_ACCESS_KEY_INVALID'); return 2 }
|
|
165
|
+
$u = $User.ToLowerInvariant()
|
|
166
|
+
$sshDir = Join-Path $env:ProgramData 'ssh'
|
|
167
|
+
$dir = Join-Path $sshDir 'aiwb'
|
|
168
|
+
$keys = Join-Path $dir "$u.keys"
|
|
169
|
+
$entry = Join-Path $dir 'entry.ps1'
|
|
170
|
+
$conf = Join-Path $sshDir 'sshd_config'
|
|
171
|
+
# 开始前状态:有没有 sshd 服务、启动类型与是否在跑、入站防火墙规则是否启用;三个文件是否已存在(存在则先在内存里备份以便撤回)。
|
|
172
|
+
$svc = Get-Service -Name sshd -ErrorAction SilentlyContinue
|
|
173
|
+
$installed = -not $svc; $touched = $false
|
|
174
|
+
$startBefore = $null; $runningBefore = $false
|
|
175
|
+
if ($svc) { $startBefore = $svc.StartType; $runningBefore = ($svc.Status -eq 'Running') }
|
|
176
|
+
$fwBefore = @{}; foreach ($r in (Get-AiwbFirewallRules)) { $fwBefore[$r.Name] = ([string]$r.Enabled -eq 'True') }
|
|
177
|
+
$fwClosed = @()
|
|
178
|
+
$backup = @{}
|
|
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
|
|
181
|
+
try {
|
|
182
|
+
if ($installed) {
|
|
183
|
+
Install-AiwbSshd
|
|
184
|
+
# 安装器可能已把 sshd 启动(MSI):先停,收紧完再开。
|
|
185
|
+
Stop-Service -Name sshd -Force -ErrorAction SilentlyContinue
|
|
186
|
+
}
|
|
187
|
+
$sshd = Get-AiwbSshdPath
|
|
188
|
+
$bin = Split-Path -Parent $sshd
|
|
189
|
+
# 从未启动过的 sshd 还没有 ProgramData\ssh 与 sshd_config:按 Win32-OpenSSH 自建该目录时的 SDDL 建目录,用安装目录的 sshd_config_default 作底本;已有的核验只归管理员。
|
|
190
|
+
if (-not (Test-Path -LiteralPath $sshDir)) {
|
|
191
|
+
$sec = New-Object Security.AccessControl.DirectorySecurity
|
|
192
|
+
$sec.SetSecurityDescriptorSddlForm('O:BAD:PAI(A;OICI;FA;;;SY)(A;OICI;FA;;;BA)(A;OICI;0x1200a9;;;AU)')
|
|
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 }
|
|
198
|
+
# aiwb 目录:所有者 Administrators,SYSTEM/管理员完全控制,登录用户只可读本目录;钥匙与入口:所有者 Administrators,去继承,SYSTEM/管理员完全控制,本人只读。
|
|
199
|
+
Set-AiwbAcl $dir 'O:BAD:PAI(A;OICI;FA;;;SY)(A;OICI;FA;;;BA)(A;;0x1200a9;;;AU)'
|
|
200
|
+
if (-not (Test-AiwbAdminOnly $dir)) { throw 'AW_REMOTE_ACCESS_SSHD_INVALID' }
|
|
201
|
+
$fileAcl = "O:BAD:P(A;;FA;;;SY)(A;;FA;;;BA)(A;;FR;;;$Sid)"
|
|
202
|
+
Write-AiwbFile $keys "from=`"127.0.0.1,::1`",restrict,pty $Key`n" $fileAcl
|
|
203
|
+
Write-AiwbFile $entry (Get-AiwbEntry) $fileAcl
|
|
204
|
+
# 底本是当前文件(已有的,或上面刚从 sshd_config_default 复制的)。
|
|
205
|
+
$text = [IO.File]::ReadAllText($conf, (New-Object Text.UTF8Encoding($false)))
|
|
206
|
+
# sshd_config 原地改写(保留其 ACL);sshd 只在下面 -t 通过后才(重)启动读取。
|
|
207
|
+
[IO.File]::WriteAllText($conf, (Set-AiwbSegment $text $User $env:ProgramData), (New-Object Text.UTF8Encoding($false)))
|
|
208
|
+
# 主机钥匙:已有私钥核验只归管理员;只补缺的默认类型(ssh-keygen -A),新生成的私钥收紧为 SYSTEM/管理员;撤回时保留(同 Mac)。
|
|
209
|
+
$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)' }
|
|
211
|
+
[void](Invoke-AiwbNative (Join-Path $bin 'ssh-keygen.exe') @('-A'))
|
|
212
|
+
foreach ($k in @(Get-ChildItem -LiteralPath $sshDir -Filter 'ssh_host_*_key' -ErrorAction SilentlyContinue | ForEach-Object { $_.FullName })) {
|
|
213
|
+
if ($hostKeys -notcontains $k) { Set-AiwbAcl $k 'O:BAD:P(A;;FA;;;SY)(A;;FA;;;BA)' }
|
|
214
|
+
}
|
|
215
|
+
if ((Invoke-AiwbNative $sshd @('-t')) -ne 0) { [Console]::Error.WriteLine('AW_REMOTE_ACCESS_SSHD_INVALID'); return 1 }
|
|
216
|
+
# 入站防火墙(待 owner 追认):N 只经 127.0.0.1:22 回环连入,不需要入站规则;本次新装或开始前没在跑的 sshd,关掉其入站规则,
|
|
217
|
+
# 免得本机所有账户可从局域网密码登录(与 macOS“只放行本人”等价);原本就在运行的 sshd 不动其防火墙。
|
|
218
|
+
if ($installed -or -not $runningBefore) {
|
|
219
|
+
foreach ($r in (Get-AiwbFirewallRules)) { if ([string]$r.Enabled -eq 'True') { Disable-NetFirewallRule -Name $r.Name; $fwClosed += $r.Name } }
|
|
220
|
+
}
|
|
221
|
+
$touched = $true
|
|
222
|
+
Set-Service -Name sshd -StartupType Automatic
|
|
223
|
+
if ((Get-Service -Name sshd).Status -eq 'Running') { Restart-Service -Name sshd -Force } else { Start-Service -Name sshd }
|
|
224
|
+
$finished = $true; $code = 0
|
|
225
|
+
} catch {
|
|
226
|
+
[Console]::Error.WriteLine([string]$_.Exception.Message)
|
|
227
|
+
} finally {
|
|
228
|
+
if (-not $finished) {
|
|
229
|
+
foreach ($f in @($keys, $entry, $conf)) {
|
|
230
|
+
Remove-Item -LiteralPath "$f.tmp" -Force -ErrorAction SilentlyContinue
|
|
231
|
+
if ($null -ne $backup[$f]) { [IO.File]::WriteAllBytes($f, [byte[]]$backup[$f]) } else { Remove-Item -LiteralPath $f -Force -ErrorAction SilentlyContinue }
|
|
232
|
+
}
|
|
233
|
+
# 开始前没有 sshd 服务(本次新装,含安装中途出错):停止并设 Disabled;原有的按原启动类型与运行状态恢复。
|
|
234
|
+
if ($installed) {
|
|
235
|
+
if (Get-Service -Name sshd -ErrorAction SilentlyContinue) {
|
|
236
|
+
Stop-Service -Name sshd -Force -ErrorAction SilentlyContinue
|
|
237
|
+
Set-Service -Name sshd -StartupType Disabled -ErrorAction SilentlyContinue
|
|
238
|
+
}
|
|
239
|
+
} elseif ($touched) {
|
|
240
|
+
Set-Service -Name sshd -StartupType $startBefore -ErrorAction SilentlyContinue
|
|
241
|
+
if ($runningBefore) { Restart-Service -Name sshd -Force -ErrorAction SilentlyContinue } else { Stop-Service -Name sshd -Force -ErrorAction SilentlyContinue }
|
|
242
|
+
}
|
|
243
|
+
# 防火墙:本次关掉的、开始前就启用的规则重新启用;本次新装时随安装建出的规则(开始前不存在)关闭。
|
|
244
|
+
foreach ($name in $fwClosed) { if ($fwBefore[$name]) { Enable-NetFirewallRule -Name $name -ErrorAction SilentlyContinue } }
|
|
245
|
+
if ($installed) { foreach ($r in (Get-AiwbFirewallRules)) { if (-not $fwBefore.ContainsKey($r.Name) -and [string]$r.Enabled -eq 'True') { Disable-NetFirewallRule -Name $r.Name -ErrorAction SilentlyContinue } } }
|
|
246
|
+
[Console]::Error.WriteLine('AW_REMOTE_ACCESS_ROLLED_BACK')
|
|
247
|
+
}
|
|
248
|
+
}
|
|
249
|
+
return $code
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
if (-not $AiwbLibraryOnly) {
|
|
253
|
+
$script:AiwbCode = Invoke-AiwbRemoteAccess -User $AiwbUser -Sid $AiwbSid -Key $AiwbKey
|
|
254
|
+
exit ([int]($script:AiwbCode | Select-Object -Last 1))
|
|
255
|
+
}
|
|
@@ -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
|
|
48
|
-
|
|
49
|
-
|
|
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 }) };
|
package/lib/browser-login.d.ts
CHANGED
|
@@ -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;
|
package/lib/browser-login.js
CHANGED
|
@@ -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
|
|
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/connect.js
CHANGED
|
@@ -4,11 +4,12 @@ import { dependency, fail as baseFail, ok, need } from "./needs.js";
|
|
|
4
4
|
import { createStartup } from "./startup.js";
|
|
5
5
|
import { parseLoginStatus } from "./auth-status.js";
|
|
6
6
|
import { authFailure } from "./auth-diagnostics.js";
|
|
7
|
+
import { host as files } from "./private-files.js";
|
|
7
8
|
function validEnrollment(e) {
|
|
8
9
|
return typeof e === 'object' && e !== null && typeof e.host === 'string' && /^[a-zA-Z0-9][a-zA-Z0-9.-]*$/.test(e.host)
|
|
9
10
|
&& typeof e.username === 'string' && /^emp-[a-z0-9][a-z0-9-]*$/.test(e.username)
|
|
10
11
|
&& Number.isInteger(e.port) && e.port > 0 && e.port <= 65535
|
|
11
|
-
&& typeof e.knownHostsFile === 'string' && e.knownHostsFile.startsWith('/') && !/[\x00-\x1f\x7f]/.test(e.knownHostsFile)
|
|
12
|
+
&& typeof e.knownHostsFile === 'string' && (files.platform === 'win32' ? /^[A-Za-z]:\\/.test(e.knownHostsFile) : e.knownHostsFile.startsWith('/')) && !/[\x00-\x1f\x7f]/.test(e.knownHostsFile)
|
|
12
13
|
&& typeof e.projectRoot === 'string' && e.projectRoot.length > 0 && !/[\x00-\x1f\x7f]/.test(e.projectRoot);
|
|
13
14
|
}
|
|
14
15
|
export function createConnect(ports, emit, options = {}) {
|
package/lib/enrollment.js
CHANGED
|
@@ -1,15 +1,18 @@
|
|
|
1
|
-
import {
|
|
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
|
-
|
|
11
|
-
|
|
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,13 +56,20 @@ export function apply(ctx, config = {}) {
|
|
|
56
56
|
api.quota = quota;
|
|
57
57
|
const ssh = ports.ssh;
|
|
58
58
|
if (ssh?.employeeAccess) {
|
|
59
|
-
|
|
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, listenTimeoutMs: (config.network?.dialTimeoutSeconds ?? NETWORK_DEFAULTS.dialTimeoutSeconds) * 1000 });
|
|
60
62
|
// 每次连上(新的连接代次)做一次:写主机 emp.json,按需开通本机远程登录;不阻塞连接与登录。
|
|
61
63
|
let seen = '';
|
|
62
64
|
const lifetime = new AbortController();
|
|
63
65
|
ctx.effect(() => { const off = api.onConnectionState(state => { const key = state.instanceId + ':' + state.epoch; if (state.phase !== 'connected' || key === seen)
|
|
64
66
|
return; seen = key; void api.getSshTarget().then(r => { if (r.ok && !lifetime.signal.aborted)
|
|
65
67
|
return access.sync(r.value, lifetime.signal); }); }); return () => { off(); lifetime.abort(); }; });
|
|
68
|
+
// cordis ctx.get 对未声明的服务不报错,只在提供方处于活动状态时返回其值,否则 undefined(@deepseek-ai/cordis src/reflect.ts get)。
|
|
69
|
+
// 工具桥晚于本插件出现(或重新提供)时,ctx.inject 回调在服务可用时运行:已连接则重新登记一次,把 toolbridge 补上。
|
|
70
|
+
ctx.inject(['aiWorkbenchToolbridge'], scope => { scope.effect(() => { if (api.getConnectionState().phase === 'connected' && seen)
|
|
71
|
+
void api.getSshTarget().then(r => { if (r.ok && !lifetime.signal.aborted)
|
|
72
|
+
return access.again(r.value, lifetime.signal); }); return () => { }; }); });
|
|
66
73
|
}
|
|
67
74
|
}, false);
|
|
68
75
|
registerComponents(ctx, config.inventory, config.enrollmentMetadataMaxBytes ?? L_DEFAULTS.enrollmentMetadataMaxBytes);
|
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 {
|
|
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:
|
|
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:
|
|
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
|
}
|
package/lib/node-name.js
ADDED
|
@@ -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()}`;
|
package/lib/private-files.d.ts
CHANGED
|
@@ -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>;
|
package/lib/private-files.js
CHANGED
|
@@ -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 {
|
|
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 ??
|
|
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
|
-
|
|
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 ??
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
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
|
|
245
|
+
await sealPrivate(source, true);
|
|
246
|
+
await checkPrivateDirectory(source);
|
|
228
247
|
}
|
|
229
248
|
}
|
|
230
|
-
|
|
231
|
-
await
|
|
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
|
-
|
|
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
|
-
|
|
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();
|
package/lib/remote-access.d.ts
CHANGED
|
@@ -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
|
-
/**
|
|
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,11 +55,19 @@ 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;
|
|
62
|
+
/** Windows 检测 127.0.0.1:22 的连接超时(毫秒),取 network.dialTimeoutSeconds。 */
|
|
63
|
+
listenTimeoutMs?: number;
|
|
32
64
|
warn?: (message: string) => void;
|
|
33
65
|
}
|
|
34
66
|
/** 系统设置“共享 → 远程登录”详情面板的官方深链接(含“允许远程用户完全磁盘访问”开关;该开关属 TCC,只能本人点开)。 */
|
|
35
67
|
export declare const REMOTE_LOGIN_SETTINGS = "x-apple.systempreferences:com.apple.Sharing-Settings.extension?Services_RemoteLogin";
|
|
36
68
|
export declare function createRemoteAccess(options: RemoteAccessOptions): {
|
|
37
69
|
sync(target: SshTarget, signal: AbortSignal): Promise<void>;
|
|
70
|
+
/** 登记内容可能变了(如工具桥服务晚于本插件出现):等进行中的一次结束后再登记一次。 */
|
|
71
|
+
again(target: SshTarget, signal: AbortSignal): Promise<void>;
|
|
38
72
|
};
|
|
39
73
|
export {};
|
package/lib/remote-access.js
CHANGED
|
@@ -1,11 +1,17 @@
|
|
|
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
|
-
|
|
6
|
-
|
|
7
|
+
import { windowsSecurity } from "./windows-security.js";
|
|
8
|
+
import { NETWORK_DEFAULTS } from "./defaults.js";
|
|
9
|
+
// TH2 约定 B/C:连上主机后把本机用户名、N 节点名、平台与工具桥回连命令经主机 helper 按来源设备登记,并读主机 emp 公钥;
|
|
10
|
+
// 本机“远程登录”未按该钥匙开通时,macOS 用管理员授权框执行一次固定脚本(helper/remote-access.sh),
|
|
11
|
+
// Windows 用 UAC 以管理员执行一次(helper/remote-access.ps1,设计 C,与 .sh 逐条对应)。
|
|
7
12
|
const KEY = /^ssh-ed25519 [A-Za-z0-9+/]+=*( [ -~]*)?$/;
|
|
8
13
|
const USER = /^[A-Za-z0-9._][A-Za-z0-9._-]*$/;
|
|
14
|
+
const SID = /^S-1-\d+(-\d+)+$/;
|
|
9
15
|
/** 只认 ed25519 公钥;返回去掉注释的“类型 base64”两段,注释不进入授权文件。 */
|
|
10
16
|
export function employeeKey(text) {
|
|
11
17
|
const line = text.trim();
|
|
@@ -33,6 +39,61 @@ export function adminCommand(script, user, key) {
|
|
|
33
39
|
const shell = `/bin/sh -c '${script.replaceAll("'", "'\\''")}' aiwb-remote-access ${shellQuote(user)} ${shellQuote(key)}`;
|
|
34
40
|
return { command: '/usr/bin/osascript', args: ['-e', `do shell script ${appleString(shell)} with administrator privileges`] };
|
|
35
41
|
}
|
|
42
|
+
/** Windows 本人一段规则(与 helper/remote-access.ps1 Get-AiwbSegment 同文)。 */
|
|
43
|
+
export function windowsSegment(user, programData) {
|
|
44
|
+
const u = user.toLowerCase();
|
|
45
|
+
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}`];
|
|
46
|
+
}
|
|
47
|
+
/**
|
|
48
|
+
* 与 remote-access.ps1 Set-AiwbSegment 同算法:已有本人段且它之前没有非本插件的 Match 行 → 原位整段替换;
|
|
49
|
+
* 否则(没有,或被挪到别的 Match 之后)去掉旧段,插在第一个 Match 行(或其他员工段的开始标记)之前、全局设置之后。有头无尾返回 undefined。
|
|
50
|
+
*/
|
|
51
|
+
export function windowsSetSegment(text, user, programData) {
|
|
52
|
+
const u = user.toLowerCase(), nl = text.length > 0 && !text.includes('\r\n') ? '\n' : '\r\n';
|
|
53
|
+
const lines = text.length > 0 ? text.split(/\r?\n/) : [];
|
|
54
|
+
if (lines.length && lines.at(-1) === '')
|
|
55
|
+
lines.pop();
|
|
56
|
+
const begin = lines.indexOf(`# aiwb-begin ${u}`), end = begin < 0 ? -1 : lines.indexOf(`# aiwb-end ${u}`, begin + 1);
|
|
57
|
+
if (begin >= 0 && end < 0)
|
|
58
|
+
return undefined;
|
|
59
|
+
const foreign = (i) => /^\s*Match\s/i.test(lines[i]) && !(i > 0 && lines[i - 1].startsWith('# aiwb-begin '));
|
|
60
|
+
const segment = windowsSegment(user, programData);
|
|
61
|
+
if (begin >= 0 && !lines.slice(0, begin).some((_, i) => foreign(i))) {
|
|
62
|
+
lines.splice(begin, end - begin + 1, ...segment);
|
|
63
|
+
return lines.join(nl) + nl;
|
|
64
|
+
}
|
|
65
|
+
if (begin >= 0)
|
|
66
|
+
lines.splice(begin, end - begin + 1);
|
|
67
|
+
let at = lines.findIndex(line => /^\s*Match\s/i.test(line) || line.startsWith('# aiwb-begin '));
|
|
68
|
+
if (at < 0)
|
|
69
|
+
at = lines.length;
|
|
70
|
+
lines.splice(at, 0, ...segment);
|
|
71
|
+
return lines.join(nl) + nl;
|
|
72
|
+
}
|
|
73
|
+
/** sshd_config 里本人段内容与位置都符合(再写一次不会变)。 */
|
|
74
|
+
export function windowsSegmentOk(text, user, programData) { return text !== undefined && windowsSetSegment(text, user, programData) === text; }
|
|
75
|
+
/** 内联进 -EncodedCommand 的脚本正文:去掉整行注释、空行与行首缩进(只为缩短命令行,语句不变)。 */
|
|
76
|
+
export function inlineScript(script) { return script.split(/\r?\n/).map(line => line.trim()).filter(line => line && !line.startsWith('#')).join('\n'); }
|
|
77
|
+
const psLiteral = (value) => "'" + value.replaceAll(/['\u2018\u2019\u201A\u201B]/g, match => match + match) + "'";
|
|
78
|
+
/**
|
|
79
|
+
* Windows UAC 提权(设计 C):外层 powershell -Command 以 ShellExecuteEx “runas” 动词(ProcessStartInfo Verb=runas、UseShellExecute、隐藏窗口,
|
|
80
|
+
* 即 Start-Process -Verb RunAs 的同一底层调用)启动管理员 powershell 并等待,透传其退出码;脚本整段以 UTF-16LE base64 内联(-EncodedCommand),
|
|
81
|
+
* 参数为已校验的常量,不落到用户可写位置。用户在 UAC 点“否”时抛 Win32Exception 1223(ERROR_CANCELLED),外层以其 NativeErrorCode 退出。
|
|
82
|
+
* 不用 Start-Process 本身:Windows PowerShell 5.1 的 Start-Process 把 Win32Exception 换成只带本地化文字的 InvalidOperationException,丢了错误码(实机核过)。
|
|
83
|
+
*/
|
|
84
|
+
export function windowsAdminCommand(script, user, sid, key, env = process.env) {
|
|
85
|
+
if (!USER.test(user) || !SID.test(sid))
|
|
86
|
+
throw Error('AW_REMOTE_ACCESS_USER_INVALID');
|
|
87
|
+
const normalized = employeeKey(key);
|
|
88
|
+
if (normalized === undefined || normalized !== key)
|
|
89
|
+
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');
|
|
92
|
+
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
|
+
return { command: `${env.SYSTEMROOT || env.windir || 'C:\\Windows'}\\System32\\WindowsPowerShell\\v1.0\\powershell.exe`, args: ['-NoProfile', '-NonInteractive', '-Command', outer] };
|
|
94
|
+
}
|
|
95
|
+
/** ERROR_CANCELLED(Microsoft Learn《System Error Codes (1000-1299)》):UAC 被拒绝。 */
|
|
96
|
+
export const WINDOWS_CANCELLED = 1223;
|
|
36
97
|
const missing = (error) => error.code === 'ENOENT';
|
|
37
98
|
// launchctl print 对 system 域只读,普通用户可执行;退出码 0 即服务已载入(Apple launchctl(1))。
|
|
38
99
|
const sshdLoaded = () => new Promise(resolve => execFile('/bin/launchctl', ['print', 'system/com.openssh.sshd'], { timeout: 0 }, error => resolve(!error)));
|
|
@@ -62,6 +123,28 @@ const runAdmin = (command, args) => new Promise(resolve => execFile(command, arg
|
|
|
62
123
|
export const REMOTE_LOGIN_SETTINGS = 'x-apple.systempreferences:com.apple.Sharing-Settings.extension?Services_RemoteLogin';
|
|
63
124
|
const openSettings = (url) => new Promise((resolve, reject) => execFile('/usr/bin/open', [url], { timeout: 0 }, error => error ? reject(error) : resolve()));
|
|
64
125
|
const script = () => readFile(new URL('../helper/remote-access.sh', import.meta.url), 'utf8');
|
|
126
|
+
const windowsScript = () => readFile(new URL('../helper/remote-access.ps1', import.meta.url), 'utf8');
|
|
127
|
+
// Windows 现状只读获取(普通用户可做):钥匙文件与 sshd_config 读文本(Authenticated Users 可读);sshd 服务状态普通用户查不了,改为连 127.0.0.1:22 看是否在听。
|
|
128
|
+
// 超时沿用具名设置 network.dialTimeoutSeconds(默认 20 秒,见 defaults.ts),不新增设置;超时按“未在听”处理。
|
|
129
|
+
const listening = (timeoutMs) => new Promise(resolve => { const socket = connect({ host: '127.0.0.1', port: 22, timeout: timeoutMs }); socket.once('connect', () => { socket.destroy(); resolve(true); }); socket.once('timeout', () => { socket.destroy(); resolve(false); }); socket.once('error', () => resolve(false)); });
|
|
130
|
+
const readOptional = async (path) => { try {
|
|
131
|
+
return await readFile(path, 'utf8');
|
|
132
|
+
}
|
|
133
|
+
catch (error) {
|
|
134
|
+
if (missing(error))
|
|
135
|
+
return undefined;
|
|
136
|
+
throw error;
|
|
137
|
+
} };
|
|
138
|
+
const windowsLocalAccess = (timeoutMs) => async (user) => {
|
|
139
|
+
const programData = process.env.ProgramData;
|
|
140
|
+
if (!programData || !win32.isAbsolute(programData))
|
|
141
|
+
throw Error('PROGRAMDATA_REQUIRED');
|
|
142
|
+
const keys = await readOptional(win32.join(programData, 'ssh', 'aiwb', user.toLowerCase() + '.keys'));
|
|
143
|
+
const config = await readOptional(win32.join(programData, 'ssh', 'sshd_config'));
|
|
144
|
+
return { keys, sshdLoaded: await listening(timeoutMs), confExists: windowsSegmentOk(config, user, programData) };
|
|
145
|
+
};
|
|
146
|
+
// 外层 powershell 以 UAC 结果退出:0 成功,1223 用户拒绝,其余失败。
|
|
147
|
+
const windowsRunAdmin = (command, args) => new Promise(resolve => execFile(command, args, { timeout: 0, windowsHide: true }, error => { const code = error ? error.code : 0; resolve({ ok: !error, cancelled: code === WINDOWS_CANCELLED }); }));
|
|
65
148
|
export function createRemoteAccess(options) {
|
|
66
149
|
// 取消或失败后本进程不再弹,下次 DSH 启动再试(约定 B)。
|
|
67
150
|
let declined = false, flight;
|
|
@@ -72,27 +155,35 @@ export function createRemoteAccess(options) {
|
|
|
72
155
|
warn('远程登录开通:本机用户名或网络节点名不可用,跳过。');
|
|
73
156
|
return;
|
|
74
157
|
}
|
|
75
|
-
const
|
|
158
|
+
const platform = options.platform ?? process.platform, supported = platform === 'darwin' || platform === 'win32';
|
|
159
|
+
// 设备登记带平台(设计 C)与工具桥插件运行时提供的回连命令(设计 D);没装工具桥就不带 toolbridge,主机按缺省处理;平台缺省主机按 darwin。
|
|
160
|
+
const toolbridge = supported ? options.toolbridge?.() : undefined;
|
|
161
|
+
const device = supported ? { user: options.user, node, platform, ...toolbridge === undefined ? {} : { toolbridge } } : { user: options.user, node };
|
|
162
|
+
const remote = await options.ssh.employeeAccess(target, JSON.stringify(device), signal);
|
|
76
163
|
if (!remote.ok) {
|
|
77
164
|
warn('远程登录开通:未能写入主机员工资料或读取主机钥匙(' + remote.error.code + ')。');
|
|
78
165
|
return;
|
|
79
166
|
}
|
|
80
|
-
if (
|
|
167
|
+
if (!supported || declined || signal.aborted)
|
|
81
168
|
return;
|
|
82
169
|
const key = employeeKey(remote.value);
|
|
83
170
|
if (!key) {
|
|
84
171
|
warn('远程登录开通:主机员工钥匙缺失或格式不符,跳过。');
|
|
85
172
|
return;
|
|
86
173
|
}
|
|
87
|
-
|
|
174
|
+
const windows = platform === 'win32';
|
|
175
|
+
if (!needsSetup(await (options.localAccess ?? (windows ? windowsLocalAccess(options.listenTimeoutMs ?? NETWORK_DEFAULTS.dialTimeoutSeconds * 1000) : localAccess))(options.user), key))
|
|
88
176
|
return;
|
|
89
|
-
const admin = adminCommand(await (options.script ?? script)(), options.user, key);
|
|
90
|
-
const result = await (options.runAdmin ?? runAdmin)(admin.command, admin.args);
|
|
177
|
+
const admin = windows ? windowsAdminCommand(await (options.script ?? windowsScript)(), options.user, (options.sid ?? (() => windowsSecurity.sid()))(), key) : adminCommand(await (options.script ?? script)(), options.user, key);
|
|
178
|
+
const result = await (options.runAdmin ?? (windows ? windowsRunAdmin : runAdmin))(admin.command, admin.args);
|
|
91
179
|
if (!result.ok) {
|
|
92
180
|
declined = true;
|
|
93
181
|
warn(result.cancelled ? '远程登录开通:员工取消了授权,本次运行不再询问。' : '远程登录开通:管理员脚本未成功,本次运行不再询问。');
|
|
94
182
|
return;
|
|
95
183
|
}
|
|
184
|
+
// Windows 没有 TCC“完全磁盘访问”对应项:开通成功后不打开任何设置面板。
|
|
185
|
+
if (windows)
|
|
186
|
+
return;
|
|
96
187
|
// 开通成功后打开一次“远程登录”详情,员工自己打开完全磁盘访问开关(owner 11-18);打不开只记警告。
|
|
97
188
|
try {
|
|
98
189
|
await (options.openSettings ?? openSettings)(REMOTE_LOGIN_SETTINGS);
|
|
@@ -110,5 +201,7 @@ export function createRemoteAccess(options) {
|
|
|
110
201
|
flight = current;
|
|
111
202
|
return current;
|
|
112
203
|
},
|
|
204
|
+
/** 登记内容可能变了(如工具桥服务晚于本插件出现):等进行中的一次结束后再登记一次。 */
|
|
205
|
+
again(target, signal) { return (flight ?? Promise.resolve()).then(() => this.sync(target, signal)); },
|
|
113
206
|
};
|
|
114
207
|
}
|
package/lib/ssh.d.ts
CHANGED
|
@@ -2,6 +2,11 @@ import type { SshTarget } from './api.ts';
|
|
|
2
2
|
import type { CommandResult, Ports } from './ports.ts';
|
|
3
3
|
export declare function shellQuote(s: string): string;
|
|
4
4
|
export declare function proxyCommand(binary: string, runtimeDir: string): string;
|
|
5
|
+
/**
|
|
6
|
+
* Windows:Win32-OpenSSH 8.6 在 ProxyCommand 失败、ssh 自身 stderr 为管道且未给 -E 时不退出(N 合同 Windows 节,实机复现);
|
|
7
|
+
* 加 `-E <L 私有信任目录内 ssh.log>`(ssh 自身诊断追加写入该文件,X 等消费方可读;不用 NUL 以保留诊断)。macOS 不变。
|
|
8
|
+
*/
|
|
9
|
+
export declare function sshLogFile(t: Pick<SshTarget, 'knownHostsFile'>): string | undefined;
|
|
5
10
|
export declare function sshArgs(t: SshTarget): string[];
|
|
6
11
|
export interface Runner {
|
|
7
12
|
run(cmd: string, args: string[], signal: AbortSignal, input?: string): Promise<CommandResult>;
|
package/lib/ssh.js
CHANGED
|
@@ -1,4 +1,6 @@
|
|
|
1
1
|
import { readFile } from 'node:fs/promises';
|
|
2
|
+
import { win32 } from 'node:path';
|
|
3
|
+
import { host as files } from "./private-files.js";
|
|
2
4
|
import { randomUUID } from 'node:crypto';
|
|
3
5
|
import { fail, ok } from "./needs.js";
|
|
4
6
|
import { AuthDiagnosticError, authFailure, outputSummary } from "./auth-diagnostics.js";
|
|
@@ -12,8 +14,14 @@ export function proxyCommand(binary, runtimeDir) {
|
|
|
12
14
|
throw new Error('ABSOLUTE_PROXY_PATH_REQUIRED');
|
|
13
15
|
return `${shellQuote(binary)} ssh-proxy --runtime-dir ${shellQuote(runtimeDir)} %h %p`;
|
|
14
16
|
}
|
|
17
|
+
/**
|
|
18
|
+
* Windows:Win32-OpenSSH 8.6 在 ProxyCommand 失败、ssh 自身 stderr 为管道且未给 -E 时不退出(N 合同 Windows 节,实机复现);
|
|
19
|
+
* 加 `-E <L 私有信任目录内 ssh.log>`(ssh 自身诊断追加写入该文件,X 等消费方可读;不用 NUL 以保留诊断)。macOS 不变。
|
|
20
|
+
*/
|
|
21
|
+
export function sshLogFile(t) { return files.platform === 'win32' ? win32.join(win32.dirname(t.knownHostsFile), 'ssh.log') : undefined; }
|
|
15
22
|
export function sshArgs(t) {
|
|
16
|
-
|
|
23
|
+
const log = sshLogFile(t);
|
|
24
|
+
return ['-F', '/dev/null', ...log ? ['-E', log] : [], '-T', '-o', 'IdentityAgent=none', '-o', 'PubkeyAuthentication=no', '-o', 'PasswordAuthentication=no', '-o', 'KbdInteractiveAuthentication=no', '-o', 'PreferredAuthentications=none', '-o', 'UpdateHostKeys=no', '-o', 'CanonicalizeHostname=no', '-o', 'BatchMode=yes', '-o', 'ServerAliveInterval=15', '-o', 'ServerAliveCountMax=3', '-o', 'StrictHostKeyChecking=yes', '-o', 'GlobalKnownHostsFile=/dev/null', '-o', 'UserKnownHostsFile=' + JSON.stringify(t.knownHostsFile.replaceAll('%', '%%')), '-o', 'ProxyCommand=' + t.proxyCommand, '-p', String(t.port), '-l', t.username, t.host];
|
|
17
25
|
}
|
|
18
26
|
export async function runRemote(runner, t, command, signal, input) {
|
|
19
27
|
const nonce = randomUUID(), source = await readFile(new URL('../helper/remote-command.cjs', import.meta.url), 'utf8');
|
|
@@ -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
|
+
};
|