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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # 远程主机连接插件(L)
2
2
 
3
- `@ai-workbench/connect` 0.7.53,随总包 `@ai-workbench/workbench-toolbridge` 安装(员工不单独安装)。公开接口见 [contracts/connect-api.md](contracts/connect-api.md),员工首次设置见 [docs/CONNECT-SETUP.md](docs/CONNECT-SETUP.md)。
3
+ `@ai-workbench/connect` 0.7.55,随总包 `@ai-workbench/workbench-toolbridge` 安装(员工不单独安装)。公开接口见 [contracts/connect-api.md](contracts/connect-api.md),员工首次设置见 [docs/CONNECT-SETUP.md](docs/CONNECT-SETUP.md)。
4
4
 
5
5
  ## 做什么
6
6
 
@@ -32,27 +32,51 @@ function Get-AiwbSegment([string]$User, [string]$ProgramData) {
32
32
  )
33
33
  }
34
34
 
35
- # 返回改好的全文:已有本人段且它之前没有非本插件的 Match 行 → 原位整段替换;否则(没有,或被挪到别的 Match 之后)去掉旧段,
36
- # 插在第一个 Match 行(或其他员工段的开始标记)之前、全局设置之后;没有 Match 就放末尾。换行沿用原文(空文件用 CRLF);有头无尾的本人段不猜,报错。
35
+ # 按行切分并保留每行原有换行符(CRLF/LF/末行无换行):返回 Start(字符偏移)、Content、Eol。
36
+ function Get-AiwbLines([string]$Text) {
37
+ $out = New-Object 'System.Collections.Generic.List[object]'
38
+ foreach ($m in [regex]::Matches($Text, '([^\r\n]*)(\r\n|\n)?')) {
39
+ if ($m.Length -eq 0 -and $m.Index -ge $Text.Length) { break }
40
+ $out.Add([pscustomobject]@{ Start = $m.Index; Content = $m.Groups[1].Value; Eol = $m.Groups[2].Value })
41
+ }
42
+ return , $out
43
+ }
44
+
45
+ # 返回改好的全文,段外字节原样保留(各行原有换行、文件末尾有无换行、BOM 有无都不动):
46
+ # 已有本人段且它之前没有非本插件的 Match 行 → 原位整段替换;否则(没有,或被挪到别的 Match 之后)去掉旧段,
47
+ # 插在第一个 Match 行(或其他员工段的开始标记)的行首、全局设置之后;没有 Match 就放末尾。本人段用文件里占多数的换行(相同或没有时 CRLF);
48
+ # 放在无结尾换行的文件末尾时,段写成“换行 + 段”且自身不带结尾换行,文件仍以无换行结尾。有头无尾的本人段不猜,报错。
37
49
  function Set-AiwbSegment([string]$Text, [string]$User, [string]$ProgramData) {
50
+ # BOM 原样留在最前,其余按无 BOM 文本处理(按字符判,不用 StartsWith:.NET Framework 的区域性比较会忽略 U+FEFF)。
51
+ if ($Text.Length -gt 0 -and $Text[0] -eq [char]0xFEFF) { return [string][char]0xFEFF + (Set-AiwbSegment $Text.Substring(1) $User $ProgramData) }
38
52
  $u = $User.ToLowerInvariant()
39
- $nl = "`r`n"; if ($Text.Length -gt 0 -and -not $Text.Contains("`r`n")) { $nl = "`n" }
40
- $lines = New-Object 'System.Collections.Generic.List[string]'
41
- if ($Text.Length -gt 0) { foreach ($l in ($Text -split "\r?\n")) { $lines.Add($l) } }
42
- if ($lines.Count -gt 0 -and $lines[$lines.Count - 1] -eq '') { $lines.RemoveAt($lines.Count - 1) }
43
- $begin = $lines.IndexOf("# aiwb-begin $u"); $end = -1
44
- if ($begin -ge 0) { $end = $lines.IndexOf("# aiwb-end $u", $begin + 1); if ($end -lt 0) { throw 'AW_REMOTE_ACCESS_SSHD_INVALID' } }
53
+ $lines = Get-AiwbLines $Text
54
+ $crlf = @($lines | Where-Object { $_.Eol -eq "`r`n" }).Count; $lf = @($lines | Where-Object { $_.Eol -eq "`n" }).Count
55
+ $nl = "`r`n"; if ($lf -gt $crlf) { $nl = "`n" }
56
+ $begin = -1; $end = -1
57
+ for ($i = 0; $i -lt $lines.Count; $i++) { if ($lines[$i].Content -ceq "# aiwb-begin $u") { $begin = $i; break } }
58
+ if ($begin -ge 0) {
59
+ for ($i = $begin + 1; $i -lt $lines.Count; $i++) { if ($lines[$i].Content -ceq "# aiwb-end $u") { $end = $i; break } }
60
+ if ($end -lt 0) { throw 'AW_REMOTE_ACCESS_SSHD_INVALID' }
61
+ }
45
62
  $segment = [string[]](Get-AiwbSegment $User $ProgramData)
63
+ $rest = $Text; $pos = -1
46
64
  if ($begin -ge 0) {
65
+ $s = $lines[$begin].Start; $e = $lines[$end].Start + $lines[$end].Content.Length + $lines[$end].Eol.Length
66
+ # 段在文件末尾且无结尾换行:连同它前面那个换行(插入时加的)一起去掉。
67
+ if ($lines[$end].Eol -eq '' -and $begin -gt 0) { $s -= $lines[$begin - 1].Eol.Length }
47
68
  $foreign = $false
48
- for ($i = 0; $i -lt $begin; $i++) { if ($lines[$i] -match '\A\s*Match\s' -and -not ($i -gt 0 -and $lines[$i - 1].StartsWith('# aiwb-begin '))) { $foreign = $true } }
49
- $lines.RemoveRange($begin, $end - $begin + 1)
50
- if (-not $foreign) { $lines.InsertRange($begin, $segment); return ($lines -join $nl) + $nl }
69
+ for ($i = 0; $i -lt $begin; $i++) { if ($lines[$i].Content -match '\A\s*Match\s' -and -not ($i -gt 0 -and $lines[$i - 1].Content.StartsWith('# aiwb-begin '))) { $foreign = $true } }
70
+ $rest = $Text.Remove($s, $e - $s)
71
+ if (-not $foreign) { $pos = $s }
72
+ }
73
+ if ($pos -lt 0) {
74
+ $pos = $rest.Length
75
+ foreach ($l in (Get-AiwbLines $rest)) { if ($l.Content -match '\A\s*Match\s' -or $l.Content.StartsWith('# aiwb-begin ')) { $pos = $l.Start; break } }
51
76
  }
52
- $at = $lines.Count
53
- for ($i = 0; $i -lt $lines.Count; $i++) { if ($lines[$i] -match '\A\s*Match\s' -or $lines[$i].StartsWith('# aiwb-begin ')) { $at = $i; break } }
54
- $lines.InsertRange($at, $segment)
55
- return ($lines -join $nl) + $nl
77
+ if ($pos -eq $rest.Length -and $rest.Length -gt 0 -and $rest[$rest.Length - 1] -ne [char]10) { $block = $nl + ($segment -join $nl) }
78
+ else { $block = ($segment -join $nl) + $nl }
79
+ return $rest.Insert($pos, $block)
56
80
  }
57
81
 
58
82
  # 以 SDDL 写所有者(SDDL 带 O: 时)与 DACL;SetAccessControl 只落给出的部分;D:P 为去继承。依据:.NET FileSystemSecurity.SetSecurityDescriptorSddlForm/File.SetAccessControl。
@@ -207,9 +231,11 @@ function Invoke-AiwbRemoteAccess([string]$User, [string]$Sid, [string]$Key) {
207
231
  Write-AiwbFile $keys "from=`"127.0.0.1,::1`",restrict,pty $Key`n" $fileAcl
208
232
  Write-AiwbFile $entry (Get-AiwbEntry) $fileAcl
209
233
  # 底本是当前文件(已有的,或上面刚从 sshd_config_default 复制的)。
210
- $text = [IO.File]::ReadAllText($conf, (New-Object Text.UTF8Encoding($false)))
234
+ # 按字节读写:UTF8Encoding($false).GetString 不剥 BOM(BOM 作为 U+FEFF 留在文本里,写回时原样编码),段外字节不变。
235
+ $utf8 = New-Object Text.UTF8Encoding($false)
236
+ $text = $utf8.GetString([IO.File]::ReadAllBytes($conf))
211
237
  # sshd_config 原地改写(保留其 ACL);sshd 只在下面 -t 通过后才(重)启动读取。
212
- [IO.File]::WriteAllText($conf, (Set-AiwbSegment $text $User $env:ProgramData), (New-Object Text.UTF8Encoding($false)))
238
+ [IO.File]::WriteAllBytes($conf, $utf8.GetBytes((Set-AiwbSegment $text $User $env:ProgramData)))
213
239
  # 主机钥匙:已有私钥须只归管理员(否则撤回);只补缺的默认类型(ssh-keygen -A),新生成的私钥收紧为 SYSTEM/管理员;撤回时保留(同 Mac)。
214
240
  $hostKeys = @(Get-ChildItem -LiteralPath $sshDir -Filter 'ssh_host_*_key' -ErrorAction SilentlyContinue | ForEach-Object { $_.FullName })
215
241
  foreach ($k in $hostKeys) { Assert-AiwbAdminOnly $k }
@@ -23,8 +23,9 @@ export declare function adminCommand(script: string, user: string, key: string):
23
23
  /** Windows 本人一段规则(与 helper/remote-access.ps1 Get-AiwbSegment 同文)。 */
24
24
  export declare function windowsSegment(user: string, programData: string): string[];
25
25
  /**
26
- * 与 remote-access.ps1 Set-AiwbSegment 同算法:已有本人段且它之前没有非本插件的 Match 行 → 原位整段替换;
27
- * 否则(没有,或被挪到别的 Match 之后)去掉旧段,插在第一个 Match 行(或其他员工段的开始标记)之前、全局设置之后。有头无尾返回 undefined。
26
+ * 与 remote-access.ps1 Set-AiwbSegment 同算法,段外字节原样保留(各行换行、末尾有无换行、BOM):已有本人段且它之前没有非本插件的 Match 行 → 原位整段替换;
27
+ * 否则去掉旧段,插在第一个 Match 行(或其他员工段的开始标记)行首;没有 Match 放末尾。本人段用占多数的换行(相同或没有时 CRLF);
28
+ * 放在无结尾换行的文件末尾时写成“换行 + 段”且不带结尾换行。有头无尾返回 undefined。
28
29
  */
29
30
  export declare function windowsSetSegment(text: string, user: string, programData: string): string | undefined;
30
31
  /** sshd_config 里本人段内容与位置都符合(再写一次不会变)。 */
@@ -34,9 +35,11 @@ export declare function windowsEntry(script: string): string | undefined;
34
35
  /** 内联进 -EncodedCommand 的脚本正文:去掉整行注释、空行与行首缩进(只为缩短命令行,语句不变)。 */
35
36
  export declare function inlineScript(script: string): string;
36
37
  /**
37
- * -EncodedCommand 的内层正文:校验过的三个常量 + 一小段引导,引导把 gzip 后 base64 内联的脚本(UTF-8)在内存里解压,
38
+ * -EncodedCommand 的内层正文:校验过的三个常量 + 一小段引导,引导把 gzip 后内联的脚本(UTF-8)在内存里解压,
38
39
  * 以 scriptblock 在同一作用域执行(脚本末尾 exit 即进程退出码)。只为缩短命令行(CreateProcess/ShellExecuteEx 上限 32767 字符),
39
40
  * 脚本语句不变、仍整段内联、不落盘。依据:.NET IO.Compression.GZipStream(RFC 1952,Node zlib.gzipSync 同格式)。
41
+ * gzip 字节按“一字节一字符”内联为 U+0100–U+01FF(不含任何引号字符):-EncodedCommand 本身已是 UTF-16 的 base64,
42
+ * 再套一层 base64 会让载荷多三分之一。
40
43
  */
41
44
  export declare function windowsAdminBody(script: string, user: string, sid: string, key: string): string;
42
45
  /** Windows PowerShell 命令行(CreateProcess)上限 32767 字符;断言与回报按其一半留余量。 */
@@ -45,31 +45,48 @@ export function windowsSegment(user, programData) {
45
45
  const u = user.toLowerCase();
46
46
  return [`# aiwb-begin ${u}`, `Match User ${u}`, ` AuthorizedKeysFile __PROGRAMDATA__/ssh/aiwb/${u}.keys`, ' AuthenticationMethods publickey', ' AcceptEnv AW_EMP_CWD', ` ForceCommand powershell.exe -NoProfile -NonInteractive -ExecutionPolicy Bypass -File "${programData}\\ssh\\aiwb\\entry.ps1"`, `# aiwb-end ${u}`];
47
47
  }
48
+ /** 按行切分并保留每行原有换行(CRLF/LF/末行无换行),与 remote-access.ps1 Get-AiwbLines 同。 */
49
+ function lines(text) { const out = []; for (const m of text.matchAll(/([^\r\n]*)(\r\n|\n)?/g)) {
50
+ if (m[0].length === 0 && m.index >= text.length)
51
+ break;
52
+ out.push({ start: m.index, content: m[1], eol: m[2] ?? '' });
53
+ } return out; }
48
54
  /**
49
- * 与 remote-access.ps1 Set-AiwbSegment 同算法:已有本人段且它之前没有非本插件的 Match 行 → 原位整段替换;
50
- * 否则(没有,或被挪到别的 Match 之后)去掉旧段,插在第一个 Match 行(或其他员工段的开始标记)之前、全局设置之后。有头无尾返回 undefined。
55
+ * 与 remote-access.ps1 Set-AiwbSegment 同算法,段外字节原样保留(各行换行、末尾有无换行、BOM):已有本人段且它之前没有非本插件的 Match 行 → 原位整段替换;
56
+ * 否则去掉旧段,插在第一个 Match 行(或其他员工段的开始标记)行首;没有 Match 放末尾。本人段用占多数的换行(相同或没有时 CRLF);
57
+ * 放在无结尾换行的文件末尾时写成“换行 + 段”且不带结尾换行。有头无尾返回 undefined。
51
58
  */
52
59
  export function windowsSetSegment(text, user, programData) {
53
- const u = user.toLowerCase(), nl = text.length > 0 && !text.includes('\r\n') ? '\n' : '\r\n';
54
- const lines = text.length > 0 ? text.split(/\r?\n/) : [];
55
- if (lines.length && lines.at(-1) === '')
56
- lines.pop();
57
- const begin = lines.indexOf(`# aiwb-begin ${u}`), end = begin < 0 ? -1 : lines.indexOf(`# aiwb-end ${u}`, begin + 1);
60
+ // BOM 原样留在最前,其余按无 BOM 文本处理。
61
+ if (text.startsWith('\uFEFF')) {
62
+ const out = windowsSetSegment(text.slice(1), user, programData);
63
+ return out === undefined ? undefined : '\uFEFF' + out;
64
+ }
65
+ const u = user.toLowerCase(), all = lines(text);
66
+ const crlf = all.filter(l => l.eol === '\r\n').length, lf = all.filter(l => l.eol === '\n').length, nl = lf > crlf ? '\n' : '\r\n';
67
+ const begin = all.findIndex(l => l.content === `# aiwb-begin ${u}`), end = begin < 0 ? -1 : all.findIndex((l, i) => i > begin && l.content === `# aiwb-end ${u}`);
58
68
  if (begin >= 0 && end < 0)
59
69
  return undefined;
60
- const foreign = (i) => /^\s*Match\s/i.test(lines[i]) && !(i > 0 && lines[i - 1].startsWith('# aiwb-begin '));
61
70
  const segment = windowsSegment(user, programData);
62
- if (begin >= 0 && !lines.slice(0, begin).some((_, i) => foreign(i))) {
63
- lines.splice(begin, end - begin + 1, ...segment);
64
- return lines.join(nl) + nl;
71
+ let rest = text, pos = -1;
72
+ if (begin >= 0) {
73
+ let s = all[begin].start;
74
+ const e = all[end].start + all[end].content.length + all[end].eol.length;
75
+ if (all[end].eol === '' && begin > 0)
76
+ s -= all[begin - 1].eol.length;
77
+ const foreign = all.slice(0, begin).some((l, i) => /^\s*Match\s/i.test(l.content) && !(i > 0 && all[i - 1].content.startsWith('# aiwb-begin ')));
78
+ rest = text.slice(0, s) + text.slice(e);
79
+ if (!foreign)
80
+ pos = s;
81
+ }
82
+ if (pos < 0) {
83
+ pos = rest.length;
84
+ const hit = lines(rest).find(l => /^\s*Match\s/i.test(l.content) || l.content.startsWith('# aiwb-begin '));
85
+ if (hit)
86
+ pos = hit.start;
65
87
  }
66
- if (begin >= 0)
67
- lines.splice(begin, end - begin + 1);
68
- let at = lines.findIndex(line => /^\s*Match\s/i.test(line) || line.startsWith('# aiwb-begin '));
69
- if (at < 0)
70
- at = lines.length;
71
- lines.splice(at, 0, ...segment);
72
- return lines.join(nl) + nl;
88
+ const block = pos === rest.length && rest.length > 0 && !rest.endsWith('\n') ? nl + segment.join(nl) : segment.join(nl) + nl;
89
+ return rest.slice(0, pos) + block + rest.slice(pos);
73
90
  }
74
91
  /** sshd_config 里本人段内容与位置都符合(再写一次不会变)。 */
75
92
  export function windowsSegmentOk(text, user, programData) { return text !== undefined && windowsSetSegment(text, user, programData) === text; }
@@ -85,13 +102,15 @@ export function windowsEntry(script) {
85
102
  export function inlineScript(script) { return script.split(/\r?\n/).map(line => line.trim()).filter(line => line && !line.startsWith('#')).join('\n'); }
86
103
  const psLiteral = (value) => "'" + value.replaceAll(/['\u2018\u2019\u201A\u201B]/g, match => match + match) + "'";
87
104
  /**
88
- * -EncodedCommand 的内层正文:校验过的三个常量 + 一小段引导,引导把 gzip 后 base64 内联的脚本(UTF-8)在内存里解压,
105
+ * -EncodedCommand 的内层正文:校验过的三个常量 + 一小段引导,引导把 gzip 后内联的脚本(UTF-8)在内存里解压,
89
106
  * 以 scriptblock 在同一作用域执行(脚本末尾 exit 即进程退出码)。只为缩短命令行(CreateProcess/ShellExecuteEx 上限 32767 字符),
90
107
  * 脚本语句不变、仍整段内联、不落盘。依据:.NET IO.Compression.GZipStream(RFC 1952,Node zlib.gzipSync 同格式)。
108
+ * gzip 字节按“一字节一字符”内联为 U+0100–U+01FF(不含任何引号字符):-EncodedCommand 本身已是 UTF-16 的 base64,
109
+ * 再套一层 base64 会让载荷多三分之一。
91
110
  */
92
111
  export function windowsAdminBody(script, user, sid, key) {
93
- const packed = gzipSync(Buffer.from(inlineScript(script), 'utf8'), { level: 9 }).toString('base64');
94
- return `$AiwbUser=${psLiteral(user)};$AiwbSid=${psLiteral(sid)};$AiwbKey=${psLiteral(key)};$z=New-Object IO.Compression.GZipStream((New-Object IO.MemoryStream(,[Convert]::FromBase64String('${packed}'))),[IO.Compression.CompressionMode]::Decompress);$t=(New-Object IO.StreamReader($z,[Text.Encoding]::UTF8)).ReadToEnd();. ([scriptblock]::Create($t))`;
112
+ const packed = [...gzipSync(Buffer.from(inlineScript(script), 'utf8'), { level: 9 })].map(b => String.fromCharCode(0x100 + b)).join('');
113
+ return `$AiwbUser=${psLiteral(user)};$AiwbSid=${psLiteral(sid)};$AiwbKey=${psLiteral(key)};$z=New-Object IO.Compression.GZipStream((New-Object IO.MemoryStream(,[byte[]]@('${packed}'.ToCharArray()|ForEach-Object{[int]$_-256}))),[IO.Compression.CompressionMode]::Decompress);$t=(New-Object IO.StreamReader($z,[Text.Encoding]::UTF8)).ReadToEnd();. ([scriptblock]::Create($t))`;
95
114
  }
96
115
  /** Windows PowerShell 命令行(CreateProcess)上限 32767 字符;断言与回报按其一半留余量。 */
97
116
  export const WINDOWS_COMMAND_LINE_MAX = 32767;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ai-workbench/connect",
3
- "version": "0.7.55-rc.6",
3
+ "version": "0.7.55",
4
4
  "type": "module",
5
5
  "engines": {
6
6
  "node": ">=24.13.1",