@ai-workbench/connect 0.7.55-rc.5 → 0.7.55-rc.6
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/helper/remote-access.ps1 +22 -17
- package/lib/network.d.ts +1 -13
- package/lib/network.js +4 -130
- package/lib/remote-access.d.ts +7 -0
- package/lib/remote-access.js +20 -4
- package/lib/ssh.d.ts +0 -1
- package/lib/ssh.js +0 -5
- package/package.json +1 -1
package/helper/remote-access.ps1
CHANGED
|
@@ -5,7 +5,7 @@
|
|
|
5
5
|
# Microsoft Learn《OpenSSH for Windows》安装(Add-WindowsCapability OpenSSH.Server)、sshd 服务、密钥文件 ACL(去继承,管理员/SYSTEM 完全控制);
|
|
6
6
|
# 微软官方 GitHub PowerShell/Win32-OpenSSH 的 MSI 安装(msiexec ADDLOCAL=Server)作 FoD 失败后备。
|
|
7
7
|
# 不设 AllowUsers、不改全机 DefaultShell、不动 sshd_config 其他行:本人一段 Match 插在第一个 Match 之前(全局设置之后)。
|
|
8
|
-
#
|
|
8
|
+
# 顺序:先收紧(已有目录/文件须只归管理员→钥匙→入口→规则→主机钥匙→sshd -t→关入站防火墙),最后才设自动并启动/重启 sshd;任一步失败恢复备份,不留“已开但未收紧”的状态。
|
|
9
9
|
# 改文本的部分(Get-AiwbSegment/Set-AiwbSegment)与写 ACL 的部分(Set-AiwbAcl)可在非管理员下对副本验证:$AiwbLibraryOnly=$true 时只定义函数。
|
|
10
10
|
$ErrorActionPreference = 'Stop'
|
|
11
11
|
# 微软官方 GitHub PowerShell/Win32-OpenSSH 当前最新发行 10.4.0.0p1-Preview(2026-10-20,GitHub releases/latest),x64 MSI 与其 SHA256(GitHub 资产 digest,下载复核一致)。
|
|
@@ -76,13 +76,11 @@ function Test-AiwbAdminOnly([string]$Path) {
|
|
|
76
76
|
return $true
|
|
77
77
|
}
|
|
78
78
|
|
|
79
|
-
#
|
|
80
|
-
#
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
if (Test-AiwbAdminOnly $Path) {
|
|
84
|
-
Set-AiwbAcl $Path $Sddl
|
|
85
|
-
if (-not (Test-AiwbAdminOnly $Path)) { throw 'AW_REMOTE_ACCESS_SSHD_INVALID' }
|
|
79
|
+
# 开始前已存在的 ssh 目录、sshd_config、主机私钥、aiwb 目录与残留 *.tmp:须非重解析点(符号链接/junction)且只归管理员,否则内容不可信
|
|
80
|
+
# (普通用户可在 ProgramData 下预建 ssh 目录并写入 AuthorizedKeysCommand 等,或把 aiwb 建成 junction),不改权限继续用,报错整体撤回。
|
|
81
|
+
function Assert-AiwbAdminOnly([string]$Path) {
|
|
82
|
+
$item = Get-Item -LiteralPath $Path -Force
|
|
83
|
+
if (($item.Attributes -band [IO.FileAttributes]::ReparsePoint) -or -not (Test-AiwbAdminOnly $Path)) { throw 'AW_REMOTE_ACCESS_SSHD_INVALID' }
|
|
86
84
|
}
|
|
87
85
|
|
|
88
86
|
# OpenSSH Server 入站防火墙规则:FoD 建 OpenSSH-Server-In-TCP,官方 MSI 建 “OpenSSH SSH Server Preview (sshd)”(MSI 的 WixFirewallException)。
|
|
@@ -179,7 +177,7 @@ function Invoke-AiwbRemoteAccess([string]$User, [string]$Sid, [string]$Key) {
|
|
|
179
177
|
$fwClosed = @()
|
|
180
178
|
$backup = @{}
|
|
181
179
|
foreach ($f in @($keys, $entry, $conf)) { if ([IO.File]::Exists($f)) { $backup[$f] = [IO.File]::ReadAllBytes($f) } else { $backup[$f] = $null } }
|
|
182
|
-
$finished = $false; $code = 1
|
|
180
|
+
$finished = $false; $code = 1; $confTrusted = $false; $dirTrusted = $false
|
|
183
181
|
try {
|
|
184
182
|
if ($installed) {
|
|
185
183
|
Install-AiwbSshd
|
|
@@ -188,15 +186,20 @@ function Invoke-AiwbRemoteAccess([string]$User, [string]$Sid, [string]$Key) {
|
|
|
188
186
|
}
|
|
189
187
|
$sshd = Get-AiwbSshdPath
|
|
190
188
|
$bin = Split-Path -Parent $sshd
|
|
191
|
-
# 从未启动过的 sshd 还没有 ProgramData\ssh 与 sshd_config:按 Win32-OpenSSH 自建该目录时的 SDDL 建目录,用安装目录的 sshd_config_default
|
|
189
|
+
# 从未启动过的 sshd 还没有 ProgramData\ssh 与 sshd_config:按 Win32-OpenSSH 自建该目录时的 SDDL 建目录,用安装目录的 sshd_config_default 作底本;已有的须只归管理员,否则撤回。
|
|
192
190
|
if (-not (Test-Path -LiteralPath $sshDir)) {
|
|
193
191
|
$sec = New-Object Security.AccessControl.DirectorySecurity
|
|
194
192
|
$sec.SetSecurityDescriptorSddlForm('O:BAD:PAI(A;OICI;FA;;;SY)(A;OICI;FA;;;BA)(A;OICI;0x1200a9;;;AU)')
|
|
195
193
|
[void][IO.Directory]::CreateDirectory($sshDir, $sec)
|
|
196
|
-
} else {
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
194
|
+
} else { Assert-AiwbAdminOnly $sshDir }
|
|
195
|
+
# 存在性用 Get-Item 判(不跟随链接,悬空链接也算存在);核验过或本次新建后才允许撤回时改写对应位置。
|
|
196
|
+
if (Get-Item -LiteralPath $conf -Force -ErrorAction SilentlyContinue) { Assert-AiwbAdminOnly $conf } else { Copy-Item -LiteralPath (Join-Path $bin 'sshd_config_default') -Destination $conf }
|
|
197
|
+
$confTrusted = $true
|
|
198
|
+
if (Get-Item -LiteralPath $dir -Force -ErrorAction SilentlyContinue) {
|
|
199
|
+
Assert-AiwbAdminOnly $dir
|
|
200
|
+
foreach ($t in @("$keys.tmp", "$entry.tmp")) { if (Get-Item -LiteralPath $t -Force -ErrorAction SilentlyContinue) { Assert-AiwbAdminOnly $t } }
|
|
201
|
+
} else { New-Item -ItemType Directory -Path $dir | Out-Null }
|
|
202
|
+
$dirTrusted = $true
|
|
200
203
|
# aiwb 目录:所有者 Administrators,SYSTEM/管理员完全控制,登录用户只可读本目录;钥匙与入口:所有者 Administrators,去继承,SYSTEM/管理员完全控制,本人只读。
|
|
201
204
|
Set-AiwbAcl $dir 'O:BAD:PAI(A;OICI;FA;;;SY)(A;OICI;FA;;;BA)(A;;0x1200a9;;;AU)'
|
|
202
205
|
if (-not (Test-AiwbAdminOnly $dir)) { throw 'AW_REMOTE_ACCESS_SSHD_INVALID' }
|
|
@@ -207,9 +210,9 @@ function Invoke-AiwbRemoteAccess([string]$User, [string]$Sid, [string]$Key) {
|
|
|
207
210
|
$text = [IO.File]::ReadAllText($conf, (New-Object Text.UTF8Encoding($false)))
|
|
208
211
|
# sshd_config 原地改写(保留其 ACL);sshd 只在下面 -t 通过后才(重)启动读取。
|
|
209
212
|
[IO.File]::WriteAllText($conf, (Set-AiwbSegment $text $User $env:ProgramData), (New-Object Text.UTF8Encoding($false)))
|
|
210
|
-
#
|
|
213
|
+
# 主机钥匙:已有私钥须只归管理员(否则撤回);只补缺的默认类型(ssh-keygen -A),新生成的私钥收紧为 SYSTEM/管理员;撤回时保留(同 Mac)。
|
|
211
214
|
$hostKeys = @(Get-ChildItem -LiteralPath $sshDir -Filter 'ssh_host_*_key' -ErrorAction SilentlyContinue | ForEach-Object { $_.FullName })
|
|
212
|
-
foreach ($k in $hostKeys) {
|
|
215
|
+
foreach ($k in $hostKeys) { Assert-AiwbAdminOnly $k }
|
|
213
216
|
[void](Invoke-AiwbNative (Join-Path $bin 'ssh-keygen.exe') @('-A'))
|
|
214
217
|
foreach ($k in @(Get-ChildItem -LiteralPath $sshDir -Filter 'ssh_host_*_key' -ErrorAction SilentlyContinue | ForEach-Object { $_.FullName })) {
|
|
215
218
|
if ($hostKeys -notcontains $k) { Set-AiwbAcl $k 'O:BAD:P(A;;FA;;;SY)(A;;FA;;;BA)' }
|
|
@@ -228,7 +231,9 @@ function Invoke-AiwbRemoteAccess([string]$User, [string]$Sid, [string]$Key) {
|
|
|
228
231
|
[Console]::Error.WriteLine([string]$_.Exception.Message)
|
|
229
232
|
} finally {
|
|
230
233
|
if (-not $finished) {
|
|
231
|
-
|
|
234
|
+
# 只改写核验过(或本次新建)的位置:不可信的 sshd_config / aiwb(如 junction)不经它写或删任何东西。
|
|
235
|
+
$restore = @(); if ($dirTrusted) { $restore += @($keys, $entry) }; if ($confTrusted) { $restore += $conf }
|
|
236
|
+
foreach ($f in $restore) {
|
|
232
237
|
Remove-Item -LiteralPath "$f.tmp" -Force -ErrorAction SilentlyContinue
|
|
233
238
|
if ($null -ne $backup[$f]) { [IO.File]::WriteAllBytes($f, [byte[]]$backup[$f]) } else { Remove-Item -LiteralPath $f -Force -ErrorAction SilentlyContinue }
|
|
234
239
|
}
|
package/lib/network.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type { Enrollment
|
|
1
|
+
import type { Enrollment } from './ports.ts';
|
|
2
2
|
import type { Result } from './api.ts';
|
|
3
3
|
export interface NetworkSettings {
|
|
4
4
|
executable?: string;
|
|
@@ -12,16 +12,4 @@ export interface NetworkSettings {
|
|
|
12
12
|
httpMaxHeaderBytes?: number;
|
|
13
13
|
controlMaxBytes?: number;
|
|
14
14
|
}
|
|
15
|
-
/**
|
|
16
|
-
* N 控制端点(设计 A 表,N 的 Go 实现同名同算法、同测试向量):darwin `<runtimeDir>/control.sock`;
|
|
17
|
-
* win32 命名管道 `\\.\pipe\aw-net-<hex>`,`<hex>` = sha256(runtimeDir 的 UTF-8,原样大小写) 前 32 位小写十六进制。
|
|
18
|
-
*/
|
|
19
|
-
export declare function controlEndpoint(runtimeDir: string, platform?: string): string;
|
|
20
15
|
export declare function writeNetworkConfig(file: string, e: Enrollment, s: NetworkSettings): Promise<Result<void>>;
|
|
21
|
-
export declare function createNetworkClient(s: NetworkSettings): {
|
|
22
|
-
connect(e: Enrollment, signal: AbortSignal): Promise<Result<{
|
|
23
|
-
proxyCommand: string;
|
|
24
|
-
}>>;
|
|
25
|
-
onState(listener: (event: NetworkEvent) => void): () => void;
|
|
26
|
-
dispose(): void;
|
|
27
|
-
};
|
package/lib/network.js
CHANGED
|
@@ -1,20 +1,10 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import { lstat, writeFile, rename, rm } from 'node:fs/promises';
|
|
1
|
+
import { writeFile, rename, rm } from 'node:fs/promises';
|
|
3
2
|
import { join, dirname, isAbsolute } from 'node:path';
|
|
4
|
-
import { randomUUID
|
|
5
|
-
import {
|
|
6
|
-
import { privateDirectory,
|
|
3
|
+
import { randomUUID } from 'node:crypto';
|
|
4
|
+
import { dependency, ok, fail } from "./needs.js";
|
|
5
|
+
import { privateDirectory, sealPrivate } from "./private-files.js";
|
|
7
6
|
import { nodeName } from "./node-name.js";
|
|
8
|
-
import { proxyCommand } from "./ssh.js";
|
|
9
|
-
/**
|
|
10
|
-
* N 控制端点(设计 A 表,N 的 Go 实现同名同算法、同测试向量):darwin `<runtimeDir>/control.sock`;
|
|
11
|
-
* win32 命名管道 `\\.\pipe\aw-net-<hex>`,`<hex>` = sha256(runtimeDir 的 UTF-8,原样大小写) 前 32 位小写十六进制。
|
|
12
|
-
*/
|
|
13
|
-
export function controlEndpoint(runtimeDir, platform = host.platform) {
|
|
14
|
-
return platform === 'win32' ? '\\\\.\\pipe\\aw-net-' + createHash('sha256').update(runtimeDir, 'utf8').digest('hex').slice(0, 32) : join(runtimeDir, 'control.sock');
|
|
15
|
-
}
|
|
16
7
|
function valid(s) { return [s.executable, s.runtimeDir, s.stateDir].every(p => typeof p === 'string' && isAbsolute(p) && !/[\x00-\x1f\x7f]/.test(p)) && s.logUpload === false && [s.statusRefreshIntervalSeconds, s.dialTimeoutSeconds, s.headerTimeoutSeconds, s.enrollmentObservationSeconds].every(n => typeof n === 'number' && Number.isFinite(n) && n >= 1e-9 && n <= 9223372036) && [s.statusRefreshIntervalSeconds, s.headerTimeoutSeconds].every(n => Number.isInteger(n * 1000) && n * 1000 >= 1 && n * 1000 <= 2147483647) && [s.httpMaxHeaderBytes].every(n => Number.isSafeInteger(n) && n > 0) && Number.isSafeInteger(s.controlMaxBytes) && s.controlMaxBytes > 0 && s.controlMaxBytes <= 2147483647; }
|
|
17
|
-
function mapped(code) { return { NEED_ENROLLMENT: 'ENROLLMENT_REQUIRED', ENROLLMENT_REJECTED: 'ENROLLMENT_REJECTED', ENROLLMENT_KEY_REJECTED: 'ENROLLMENT_KEY_REJECTED', LOCAL_STATE_INVALID: 'ENROLLMENT_INVALID', HOST_OFFLINE: 'HOST_OFFLINE', HOST_NOT_VISIBLE: 'DEPENDENCY_REQUIRED', CONFIG_INVALID: 'SETTINGS_REQUIRED', CAPABILITY_NOT_IMPLEMENTED: 'DEPENDENCY_REQUIRED', NEED_HOST_CONTRACT: 'DEPENDENCY_REQUIRED', NETWORK_INTERRUPTED: 'CONNECTION_LOST', CONTROL_UNAVAILABLE: 'DEPENDENCY_REQUIRED' }[String(code)] ?? 'DEPENDENCY_REQUIRED'; }
|
|
18
8
|
export async function writeNetworkConfig(file, e, s) {
|
|
19
9
|
if (!valid(s) || !isAbsolute(file))
|
|
20
10
|
return fail('SETTINGS_REQUIRED');
|
|
@@ -37,119 +27,3 @@ export async function writeNetworkConfig(file, e, s) {
|
|
|
37
27
|
await rm(temp, { force: true });
|
|
38
28
|
}
|
|
39
29
|
}
|
|
40
|
-
export function createNetworkClient(s) {
|
|
41
|
-
const listeners = new Set();
|
|
42
|
-
let timer, previous, refreshing = false, disposed = false;
|
|
43
|
-
const pending = new Set();
|
|
44
|
-
let expected;
|
|
45
|
-
const bad = (code) => { throw new NeedError(need(code)); };
|
|
46
|
-
async function socket() {
|
|
47
|
-
if (!valid(s))
|
|
48
|
-
bad('SETTINGS_REQUIRED');
|
|
49
|
-
// win32:控制端点是命名管道(N 以只许本人与 SYSTEM 的 SDDL 建首实例),这里核 runtimeDir 私有。
|
|
50
|
-
if (host.platform === 'win32') {
|
|
51
|
-
await checkPrivateDirectory(s.runtimeDir);
|
|
52
|
-
return;
|
|
53
|
-
}
|
|
54
|
-
const dir = await lstat(s.runtimeDir), sock = await lstat(join(s.runtimeDir, 'control.sock'));
|
|
55
|
-
if (!dir.isDirectory() || dir.isSymbolicLink() || dir.uid !== process.getuid() || (dir.mode & 0o077) || !sock.isSocket() || sock.isSymbolicLink() || sock.uid !== process.getuid() || (sock.mode & 0o177))
|
|
56
|
-
bad('DEPENDENCY_REQUIRED');
|
|
57
|
-
}
|
|
58
|
-
async function send(method, path, signal) {
|
|
59
|
-
try {
|
|
60
|
-
await socket();
|
|
61
|
-
}
|
|
62
|
-
catch (e) {
|
|
63
|
-
if (e instanceof NeedError)
|
|
64
|
-
throw e;
|
|
65
|
-
bad('DEPENDENCY_REQUIRED');
|
|
66
|
-
}
|
|
67
|
-
if (disposed || signal.aborted)
|
|
68
|
-
bad('CONNECTION_LOST');
|
|
69
|
-
return new Promise((resolve, reject) => { const req = request({ socketPath: controlEndpoint(s.runtimeDir), path, method, signal, agent: false }, response => { clearTimeout(deadline); resolve(response); }); const deadline = setTimeout(() => req.destroy(new Error('CONTROL_HEADER_TIMEOUT')), s.headerTimeoutSeconds * 1000); req.on('error', () => { clearTimeout(deadline); reject(new NeedError(need('DEPENDENCY_REQUIRED'))); }); req.end(); });
|
|
70
|
-
}
|
|
71
|
-
async function json(res) { let size = 0; const chunks = []; try {
|
|
72
|
-
for await (const chunk of res) {
|
|
73
|
-
size += chunk.length;
|
|
74
|
-
if (size > s.controlMaxBytes)
|
|
75
|
-
bad('DEPENDENCY_REQUIRED');
|
|
76
|
-
chunks.push(chunk);
|
|
77
|
-
}
|
|
78
|
-
return JSON.parse(Buffer.concat(chunks).toString('utf8'));
|
|
79
|
-
}
|
|
80
|
-
catch {
|
|
81
|
-
res.destroy();
|
|
82
|
-
bad('DEPENDENCY_REQUIRED');
|
|
83
|
-
} }
|
|
84
|
-
async function status(signal) {
|
|
85
|
-
try {
|
|
86
|
-
const res = await send('GET', '/v1/status', signal), v = await json(res);
|
|
87
|
-
if (v?.apiVersion !== 1)
|
|
88
|
-
return dependency('N v1 状态协议');
|
|
89
|
-
if (res.statusCode !== 200 || v.error) {
|
|
90
|
-
const result = fail(mapped(v.error?.code));
|
|
91
|
-
if (!result.ok && result.error.code === 'HOST_OFFLINE' && v.host?.name === expected?.host && typeof v.host.lastSeenAt === 'string' && !Number.isNaN(Date.parse(v.host.lastSeenAt)))
|
|
92
|
-
result.error.lastSeen = v.host.lastSeenAt;
|
|
93
|
-
return result;
|
|
94
|
-
}
|
|
95
|
-
if (v.enrollment !== 'online')
|
|
96
|
-
return fail(v.enrollment === 'needs_enrollment' ? 'ENROLLMENT_REQUIRED' : v.enrollment === 'rejected' ? 'ENROLLMENT_REJECTED' : 'CONNECTION_LOST');
|
|
97
|
-
if (v.host?.name !== expected?.host)
|
|
98
|
-
return dependency('与开通主机匹配的 N 状态');
|
|
99
|
-
if (v.host.online === false) {
|
|
100
|
-
const result = fail('HOST_OFFLINE');
|
|
101
|
-
if (!result.ok && typeof v.host.lastSeenAt === 'string' && !Number.isNaN(Date.parse(v.host.lastSeenAt)))
|
|
102
|
-
result.error.lastSeen = v.host.lastSeenAt;
|
|
103
|
-
return result;
|
|
104
|
-
}
|
|
105
|
-
if (v.host.online !== true)
|
|
106
|
-
return dependency('N 已核实的主机在线状态');
|
|
107
|
-
return ok(undefined);
|
|
108
|
-
}
|
|
109
|
-
catch (e) {
|
|
110
|
-
return e instanceof NeedError ? { ok: false, error: e.need } : dependency('N 私有控制 socket;未使用直连网络');
|
|
111
|
-
}
|
|
112
|
-
}
|
|
113
|
-
async function refresh() { if (refreshing || !expected || disposed)
|
|
114
|
-
return; refreshing = true; const c = new AbortController(); pending.add(c); try {
|
|
115
|
-
const r = await status(c.signal), online = r.ok;
|
|
116
|
-
if (previous !== undefined && previous !== online)
|
|
117
|
-
for (const listener of listeners)
|
|
118
|
-
listener({ kind: online ? 'restored' : 'lost' });
|
|
119
|
-
previous = online;
|
|
120
|
-
}
|
|
121
|
-
finally {
|
|
122
|
-
pending.delete(c);
|
|
123
|
-
refreshing = false;
|
|
124
|
-
} }
|
|
125
|
-
return {
|
|
126
|
-
async connect(e, signal) {
|
|
127
|
-
expected = e;
|
|
128
|
-
const result = await status(signal);
|
|
129
|
-
previous = result.ok;
|
|
130
|
-
if (!result.ok)
|
|
131
|
-
return result;
|
|
132
|
-
try {
|
|
133
|
-
const exe = await lstat(s.executable);
|
|
134
|
-
if (!exe.isFile() || exe.isSymbolicLink() || host.platform !== 'win32' && !(exe.mode & 0o111))
|
|
135
|
-
return dependency('N 真实 helper 可执行程序');
|
|
136
|
-
return ok({ proxyCommand: proxyCommand(s.executable, s.runtimeDir) });
|
|
137
|
-
}
|
|
138
|
-
catch {
|
|
139
|
-
return dependency('N 真实 helper 可执行程序');
|
|
140
|
-
}
|
|
141
|
-
},
|
|
142
|
-
onState(listener) { listeners.add(listener); if (valid(s) && !timer) {
|
|
143
|
-
timer = setInterval(() => { void refresh(); }, s.statusRefreshIntervalSeconds * 1000);
|
|
144
|
-
timer.unref();
|
|
145
|
-
} return () => { listeners.delete(listener); if (!listeners.size && timer) {
|
|
146
|
-
clearInterval(timer);
|
|
147
|
-
timer = undefined;
|
|
148
|
-
for (const c of pending)
|
|
149
|
-
c.abort();
|
|
150
|
-
} }; },
|
|
151
|
-
dispose() { disposed = true; if (timer)
|
|
152
|
-
clearInterval(timer); for (const c of pending)
|
|
153
|
-
c.abort(); listeners.clear(); },
|
|
154
|
-
};
|
|
155
|
-
}
|
package/lib/remote-access.d.ts
CHANGED
|
@@ -29,6 +29,8 @@ export declare function windowsSegment(user: string, programData: string): strin
|
|
|
29
29
|
export declare function windowsSetSegment(text: string, user: string, programData: string): string | undefined;
|
|
30
30
|
/** sshd_config 里本人段内容与位置都符合(再写一次不会变)。 */
|
|
31
31
|
export declare function windowsSegmentOk(text: string | undefined, user: string, programData: string): boolean;
|
|
32
|
+
/** 本版开通脚本(内联执行时)写入 entry.ps1 的确切内容:Get-AiwbEntry 的 here-string 正文(行已去缩进,行间 \n,无结尾换行)。 */
|
|
33
|
+
export declare function windowsEntry(script: string): string | undefined;
|
|
32
34
|
/** 内联进 -EncodedCommand 的脚本正文:去掉整行注释、空行与行首缩进(只为缩短命令行,语句不变)。 */
|
|
33
35
|
export declare function inlineScript(script: string): string;
|
|
34
36
|
/**
|
|
@@ -73,6 +75,11 @@ interface RemoteAccessOptions {
|
|
|
73
75
|
}
|
|
74
76
|
/** 系统设置“共享 → 远程登录”详情面板的官方深链接(含“允许远程用户完全磁盘访问”开关;该开关属 TCC,只能本人点开)。 */
|
|
75
77
|
export declare const REMOTE_LOGIN_SETTINGS = "x-apple.systempreferences:com.apple.Sharing-Settings.extension?Services_RemoteLogin";
|
|
78
|
+
/** Windows 规则判定:本人段符合(windowsSegmentOk)且 entry.ps1 内容等于本版脚本写入的内容(windowsEntry)。 */
|
|
79
|
+
export declare function windowsRulesOk(local: {
|
|
80
|
+
config?: string;
|
|
81
|
+
entry?: string;
|
|
82
|
+
}, user: string, programData: string, entryText: string | undefined): boolean;
|
|
76
83
|
export declare function createRemoteAccess(options: RemoteAccessOptions): {
|
|
77
84
|
sync(target: SshTarget, signal: AbortSignal): Promise<void>;
|
|
78
85
|
/** 登记内容可能变了(如工具桥服务晚于本插件出现):等进行中的一次结束后再登记一次。 */
|
package/lib/remote-access.js
CHANGED
|
@@ -73,6 +73,14 @@ export function windowsSetSegment(text, user, programData) {
|
|
|
73
73
|
}
|
|
74
74
|
/** sshd_config 里本人段内容与位置都符合(再写一次不会变)。 */
|
|
75
75
|
export function windowsSegmentOk(text, user, programData) { return text !== undefined && windowsSetSegment(text, user, programData) === text; }
|
|
76
|
+
/** 本版开通脚本(内联执行时)写入 entry.ps1 的确切内容:Get-AiwbEntry 的 here-string 正文(行已去缩进,行间 \n,无结尾换行)。 */
|
|
77
|
+
export function windowsEntry(script) {
|
|
78
|
+
const inline = inlineScript(script), start = inline.indexOf("function Get-AiwbEntry {\nreturn @'\n");
|
|
79
|
+
if (start < 0)
|
|
80
|
+
return undefined;
|
|
81
|
+
const from = start + "function Get-AiwbEntry {\nreturn @'\n".length, end = inline.indexOf("\n'@", from);
|
|
82
|
+
return end < 0 ? undefined : inline.slice(from, end);
|
|
83
|
+
}
|
|
76
84
|
/** 内联进 -EncodedCommand 的脚本正文:去掉整行注释、空行与行首缩进(只为缩短命令行,语句不变)。 */
|
|
77
85
|
export function inlineScript(script) { return script.split(/\r?\n/).map(line => line.trim()).filter(line => line && !line.startsWith('#')).join('\n'); }
|
|
78
86
|
const psLiteral = (value) => "'" + value.replaceAll(/['\u2018\u2019\u201A\u201B]/g, match => match + match) + "'";
|
|
@@ -146,14 +154,20 @@ catch (error) {
|
|
|
146
154
|
return undefined;
|
|
147
155
|
throw error;
|
|
148
156
|
} };
|
|
149
|
-
|
|
157
|
+
// 规则在:sshd_config 本人段内容与位置都符合,且 entry.ps1 与本版脚本要写的内容逐字一致(插件升级后入口变了就再授权一次)。
|
|
158
|
+
const windowsLocalAccess = (timeoutMs, entryText) => async (user) => {
|
|
150
159
|
const programData = process.env.ProgramData;
|
|
151
160
|
if (!programData || !win32.isAbsolute(programData))
|
|
152
161
|
throw Error('PROGRAMDATA_REQUIRED');
|
|
153
162
|
const keys = await readOptional(win32.join(programData, 'ssh', 'aiwb', user.toLowerCase() + '.keys'));
|
|
154
163
|
const config = await readOptional(win32.join(programData, 'ssh', 'sshd_config'));
|
|
155
|
-
|
|
164
|
+
const entry = await readOptional(win32.join(programData, 'ssh', 'aiwb', 'entry.ps1'));
|
|
165
|
+
return { keys, sshdLoaded: await listening(timeoutMs), confExists: windowsRulesOk({ config, entry }, user, programData, entryText) };
|
|
156
166
|
};
|
|
167
|
+
/** Windows 规则判定:本人段符合(windowsSegmentOk)且 entry.ps1 内容等于本版脚本写入的内容(windowsEntry)。 */
|
|
168
|
+
export function windowsRulesOk(local, user, programData, entryText) {
|
|
169
|
+
return windowsSegmentOk(local.config, user, programData) && entryText !== undefined && local.entry === entryText;
|
|
170
|
+
}
|
|
157
171
|
// 外层 powershell 以 UAC 结果退出:0 成功,1223 用户拒绝,其余失败。
|
|
158
172
|
const windowsRunAdmin = (command, args) => new Promise(resolve => execFile(command, args, { timeout: 0, windowsHide: true }, error => { const code = error ? error.code : 0; resolve({ ok: !error, cancelled: code === WINDOWS_CANCELLED }); }));
|
|
159
173
|
export function createRemoteAccess(options) {
|
|
@@ -183,9 +197,11 @@ export function createRemoteAccess(options) {
|
|
|
183
197
|
return;
|
|
184
198
|
}
|
|
185
199
|
const windows = platform === 'win32';
|
|
186
|
-
|
|
200
|
+
// Windows 先读本版脚本:检测要比对 entry.ps1 内容;macOS 仍只在需要开通时才读。
|
|
201
|
+
const winBody = windows ? await (options.script ?? windowsScript)() : undefined;
|
|
202
|
+
if (!needsSetup(await (options.localAccess ?? (windows ? windowsLocalAccess(options.listenTimeoutMs ?? NETWORK_DEFAULTS.dialTimeoutSeconds * 1000, windowsEntry(winBody)) : localAccess))(options.user), key))
|
|
187
203
|
return;
|
|
188
|
-
const admin = windows ? windowsAdminCommand(
|
|
204
|
+
const admin = windows ? windowsAdminCommand(winBody, options.user, (options.sid ?? (() => windowsSecurity.sid()))(), key) : adminCommand(await (options.script ?? script)(), options.user, key);
|
|
189
205
|
const result = await (options.runAdmin ?? (windows ? windowsRunAdmin : runAdmin))(admin.command, admin.args);
|
|
190
206
|
if (!result.ok) {
|
|
191
207
|
declined = true;
|
package/lib/ssh.d.ts
CHANGED
|
@@ -1,7 +1,6 @@
|
|
|
1
1
|
import type { SshTarget } from './api.ts';
|
|
2
2
|
import type { CommandResult, Ports } from './ports.ts';
|
|
3
3
|
export declare function shellQuote(s: string): string;
|
|
4
|
-
export declare function proxyCommand(binary: string, runtimeDir: string): string;
|
|
5
4
|
/**
|
|
6
5
|
* Windows:Win32-OpenSSH 8.6 在 ProxyCommand 失败、ssh 自身 stderr 为管道且未给 -E 时不退出(N 合同 Windows 节,实机复现);
|
|
7
6
|
* 加 `-E <L 私有信任目录内 ssh.log>`(ssh 自身诊断追加写入该文件,X 等消费方可读;不用 NUL 以保留诊断)。macOS 不变。
|
package/lib/ssh.js
CHANGED
|
@@ -9,11 +9,6 @@ export function shellQuote(s) {
|
|
|
9
9
|
throw new Error('INVALID_PROXY_PATH');
|
|
10
10
|
return "'" + s.replaceAll("'", "'\\''") + "'";
|
|
11
11
|
}
|
|
12
|
-
export function proxyCommand(binary, runtimeDir) {
|
|
13
|
-
if (!binary.startsWith('/') || !runtimeDir.startsWith('/'))
|
|
14
|
-
throw new Error('ABSOLUTE_PROXY_PATH_REQUIRED');
|
|
15
|
-
return `${shellQuote(binary)} ssh-proxy --runtime-dir ${shellQuote(runtimeDir)} %h %p`;
|
|
16
|
-
}
|
|
17
12
|
/**
|
|
18
13
|
* Windows:Win32-OpenSSH 8.6 在 ProxyCommand 失败、ssh 自身 stderr 为管道且未给 -E 时不退出(N 合同 Windows 节,实机复现);
|
|
19
14
|
* 加 `-E <L 私有信任目录内 ssh.log>`(ssh 自身诊断追加写入该文件,X 等消费方可读;不用 NUL 以保留诊断)。macOS 不变。
|