WorkBuddy、CodeBuddy 桌面端增强助手:签到猫猫旅行成长计划查询、多账号独立备份、点切即用;免打扰模式让 AI 无人值守跑长任务;跨账号会话迁移、异常中断自动续接;暂存/快捷提示词;毛玻璃主题与更多实用功能。
fix(windows): enforce least-privilege process boundaries
Jinhui Zheng4878317d1bfc
diff --git a/README.md b/README.mdindex 122167e..254a4f1 100644--- a/README.md+++ b/README.md@@ -64,7 +64,7 @@ v1.0.3 演示图(非最新版)1. 在 [Releases](../../releases) 下载最新 `WorkDaddy-x.y.z-win64.zip`2. **解压到桌面以外的文件夹,双击一键安装脚本 `Install-WorkDaddy.cmd`**,安装后即可关闭该窗口:-3. 以后只需**右键以管理员身份运行 WorkDaddy 图标** 即可+3. 以后直接双击 WorkDaddy 图标即可;请勿以管理员身份运行4. 几秒后就会自动打开 WorkBuddy ,看到机器人按钮即成功;diff --git a/scripts/apply-update.ps1 b/scripts/apply-update.ps1index 01ba249..edce7df 100644--- a/scripts/apply-update.ps1+++ b/scripts/apply-update.ps1@@ -10,11 +10,31 @@ param([string]$Profile = '__WBS_DEFAULT_PROFILE__')+try {+ $identity = [Security.Principal.WindowsIdentity]::GetCurrent()+ $principal = New-Object Security.Principal.WindowsPrincipal($identity)+ $isElevated = $principal.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)+ if ($isElevated -ne $false) {+ [Console]::Error.WriteLine('拒绝以管理员权限运行 WorkDaddy 更新脚本;请使用普通用户终端。')+ exit 5+ }+} catch {+ [Console]::Error.WriteLine('无法确认当前 PowerShell 为普通用户权限;更新已停止。')+ exit 5+}+$ErrorActionPreference = 'Stop'+try { . (Join-Path $PSScriptRoot 'windows-process-boundary.ps1') } catch {+ [Console]::Error.WriteLine('无法加载 Windows 进程身份边界;更新已停止。')+ exit 5+}if ([string]::IsNullOrWhiteSpace($Profile) -or $Profile -eq '__WBS_DEFAULT_PROFILE__') { $Profile = 'workbuddy-cn' }if ($Profile -ne 'workbuddy-ai') { $Profile = 'workbuddy-cn' }$productName = if ($Profile -eq 'workbuddy-ai') { 'WorkDaddy AI' } else { 'WorkDaddy' }if ([string]::IsNullOrWhiteSpace($AppDir)) { $AppDir = Join-Path $env:LOCALAPPDATA (Join-Path 'Programs' $productName) }+if (-not (Test-SameWindowsPath -Left $PSScriptRoot -Right (Join-Path $AppDir 'scripts'))) {+ throw '更新脚本位置与目标安装目录不一致,拒绝替换'+}$dataRoot = Join-Path $env:APPDATA 'WorkDaddy'$DataDir = if ($Profile -eq 'workbuddy-ai') { Join-Path $dataRoot 'profiles\workbuddy-ai' } else { $dataRoot }$LogDir = Join-Path $DataDir 'update'@@ -40,83 +60,18 @@ function Stop-ApplyTranscript {}}-function Test-ExclusiveFile {- param([string]$Path)- if (-not (Test-Path -LiteralPath $Path)) { return $true }- $stream = $null- try {- $stream = [IO.File]::Open($Path, [IO.FileMode]::Open, [IO.FileAccess]::Read, [IO.FileShare]::None)- return $true- } catch {- return $false- } finally {- if ($stream) { $stream.Dispose() }- }-}--function Release-LockedLauncher {- param([string]$LauncherPath)- if (Test-ExclusiveFile $LauncherPath) { return $true }- $needle = ([IO.Path]::GetFullPath($LauncherPath)).Replace('/', '\').ToLowerInvariant()- try {- Get-CimInstance Win32_Process -Filter "Name = 'cmd.exe'" -ErrorAction SilentlyContinue | ForEach-Object {- $commandLine = ([string]$_.CommandLine).Replace('/', '\').ToLowerInvariant()- if ($commandLine.Contains($needle) -and $_.ProcessId -ne $PID) {- & taskkill /F /T /PID $_.ProcessId 2>$null | Out-Null- }- }- } catch {- Write-ApplyLog "扫描 launcher.cmd 锁失败: $($_.Exception.Message)"- }- for ($i = 0; $i -lt 20; $i++) {- if (Test-ExclusiveFile $LauncherPath) { return $true }- Start-Sleep -Milliseconds 300- }- return (Test-ExclusiveFile $LauncherPath)-}-function Stop-WatchdogAndPort {- $pidFile = Join-Path $DataDir 'watchdog.pid'- if (Test-Path -LiteralPath $pidFile) {- try {- $watchdogPid = [int]((Get-Content -LiteralPath $pidFile -Raw).Trim())- if ($watchdogPid -gt 0) {- Write-ApplyLog "停止 watchdog pid=$watchdogPid"- # 【重要】绝不能带 /T!taskkill 的 /T 按 ParentProcessId 递归连坐整棵子树,- # 而本脚本(powershell)就是 watchdog→daemon→powershell 链上的叶子,/T 会把自身也杀掉,- # 导致替换从未执行(apply.log 里做完「停止 watchdog」这步就没下文了)。- # 只精确杀 watchdog 一个进程即可;daemon 已被 daemon.js 自我退出,端口兜底逻辑单独处理。- & taskkill /F /PID $watchdogPid 2>$null | Out-Null- }- } catch {- Write-ApplyLog "停止 watchdog 失败: $($_.Exception.Message)"- }- }-- for ($wait = 0; $wait -lt 15; $wait++) {- $listening = @(netstat -ano | Select-String (":$Port\s") | Select-String 'LISTENING')- if ($listening.Count -eq 0) { return }- if ($wait -ge 3) {- foreach ($line in $listening) {- $parts = ($line.ToString().Trim() -split '\s+')- $portPid = $parts[$parts.Count - 1]- if ($portPid -match '^\d+$') {- Write-ApplyLog "端口 $Port 仍被 pid=$portPid 占用,强制结束"- # 同样不要 /T:占用端口的进程极可能是 daemon(本脚本的父链成员),/T 会连坐自身。- & taskkill /F /PID $portPid 2>$null | Out-Null- }- }- }- Start-Sleep -Seconds 1- }- $remaining = @(netstat -ano | Select-String (":$Port\s") | Select-String 'LISTENING')- if ($remaining.Count -gt 0) { throw "端口 $Port 在 15 秒后仍被占用" }+ Stop-VerifiedWorkDaddyLifecycle `+ -DataDir $DataDir `+ -Port ([int]$Port) `+ -ExpectedWatchdogScript (Join-Path $AppDir 'scripts\watchdog.js') `+ -ExpectedDaemonScript (Join-Path $AppDir 'scripts\daemon.js')}function Rollback-App {param([string]$OldDir, [string]$TargetDir)Write-ApplyLog "开始回滚旧版本"- try { Stop-WatchdogAndPort } catch { Write-ApplyLog "回滚前停止新版进程失败: $($_.Exception.Message)" }+ Stop-WatchdogAndPorttry { if (Test-Path -LiteralPath $TargetDir) { Remove-Item -LiteralPath $TargetDir -Recurse -Force -ErrorAction SilentlyContinue } } catch {}if (Test-Path -LiteralPath $OldDir) {try { Move-Item -LiteralPath $OldDir -Destination $TargetDir -Force -ErrorAction Stop } catch {@@ -139,13 +94,15 @@ function Rollback-App {$oldDir = "$AppDir.old"$tmpDir = Join-Path $env:TEMP ("workdaddy-update-" + [guid]::NewGuid().ToString('N'))$backupMade = $false+$lifecycleValidated = $falsetry {Write-ApplyLog "start attempt=$AttemptId src=$SrcZip dst=$AppDir port=$Port pid=$PID"if (-not (Test-Path -LiteralPath $SrcZip -PathType Leaf)) { throw "更新包不存在: $SrcZip" }Stop-WatchdogAndPort+ $lifecycleValidated = $trueforeach ($launcherPath in @((Join-Path $AppDir 'scripts\launcher.cmd'), (Join-Path $oldDir 'scripts\launcher.cmd'))) {- if (-not (Release-LockedLauncher $launcherPath)) { throw "无法释放 launcher.cmd 文件锁: $launcherPath" }+ if (-not (Release-VerifiedLauncherLock -LauncherPath $launcherPath)) { throw "无法释放 launcher.cmd 文件锁: $launcherPath" }}if (Test-Path -LiteralPath $oldDir) { Remove-Item -LiteralPath $oldDir -Recurse -Force -ErrorAction Stop }@@ -167,11 +124,14 @@ try {$sourceDaemonText = Get-Content -LiteralPath (Join-Path $srcRoot 'scripts\daemon.js') -Raw$sourceDaemonMatch = [regex]::Match($sourceDaemonText, "const DAEMON_VERSION = '([^']+)'")$sourceDaemonVersion = if ($sourceDaemonMatch.Success) { $sourceDaemonMatch.Groups[1].Value } else { '' }+ $sourceBuildMatch = [regex]::Match($sourceDaemonText, "const DAEMON_BUILD_ID = '([^']+)'")+ $sourceBuildId = if ($sourceBuildMatch.Success) { $sourceBuildMatch.Groups[1].Value } else { '' }$packageName = [IO.Path]::GetFileNameWithoutExtension($SrcZip)$packageVersionMatch = [regex]::Match($packageName, '([0-9]+\.[0-9]+\.[0-9]+)')$packageVersion = if ($packageVersionMatch.Success) { $packageVersionMatch.Groups[1].Value } else { '' }Write-ApplyLog "artifact inspect package=$packageName packageVersion=$packageVersion daemonVersion=$sourceDaemonVersion"if ([string]::IsNullOrWhiteSpace($sourceDaemonVersion)) { throw '更新包 daemon.js 缺少 DAEMON_VERSION' }+ if ([string]::IsNullOrWhiteSpace($sourceBuildId)) { throw '更新包 daemon.js 缺少 DAEMON_BUILD_ID' }if (-not [string]::IsNullOrWhiteSpace($packageVersion) -and $sourceDaemonVersion -ne $packageVersion) {throw "更新包内部 daemon 版本 $sourceDaemonVersion 与文件目标版本 $packageVersion 不一致"}@@ -194,15 +154,22 @@ try {for ($i = 0; $i -lt 60; $i++) {try {$status = Invoke-RestMethod -Uri ("http://127.0.0.1:{0}/api/status" -f $Port) -Method Get -TimeoutSec 2+ [void](Assert-DaemonStatusIdentity `+ -Status $status `+ -Port ([int]$Port) `+ -ExpectedProfile $Profile `+ -ExpectedVersion $sourceDaemonVersion `+ -ExpectedDaemonScript (Join-Path $AppDir 'scripts\daemon.js') `+ -ExpectedBuildId $sourceBuildId)if ($status.version) { $ready = $true; Write-ApplyLog "新版 daemon 已就绪 version=$($status.version)"; break }} catch {}Start-Sleep -Seconds 1}if (-not $ready) { throw '新版 daemon 在 60 秒内未就绪' }$runningVersion = [string]$status.version- Write-ApplyLog "running daemon version=$runningVersion expected=$packageVersion"- if (-not [string]::IsNullOrWhiteSpace($packageVersion) -and $runningVersion -ne $packageVersion) {- throw "新版 daemon 实际版本 $runningVersion 与目标版本 $packageVersion 不一致"+ Write-ApplyLog "running daemon version=$runningVersion expected=$sourceDaemonVersion"+ if ($runningVersion -ne $sourceDaemonVersion) {+ throw "新版 daemon 实际版本 $runningVersion 与包内 daemon 版本 $sourceDaemonVersion 不一致"}if (Test-Path -LiteralPath $oldDir) {@@ -217,7 +184,8 @@ try {Stop-ApplyTranscriptexit 1} finally {- try { if (Test-Path -LiteralPath $tmpDir) { Remove-Item -LiteralPath $tmpDir -Recurse -Force -ErrorAction SilentlyContinue } } catch {}- # 清除更新标记:无论成败都不再阻止 watchdog 拉起 daemon(避免留下「daemon 死光」的悬空状态)- try { Remove-Item -LiteralPath (Join-Path $LogDir 'pending.json') -Force -ErrorAction SilentlyContinue } catch {}+ if ($lifecycleValidated) {+ try { if (Test-Path -LiteralPath $tmpDir) { Remove-Item -LiteralPath $tmpDir -Recurse -Force -ErrorAction SilentlyContinue } } catch {}+ try { Remove-Item -LiteralPath (Join-Path $LogDir 'pending.json') -Force -ErrorAction SilentlyContinue } catch {}+ }}diff --git a/scripts/daemon.js b/scripts/daemon.jsindex 53f8e88..60de504 100644--- a/scripts/daemon.js+++ b/scripts/daemon.js@@ -27,6 +27,20 @@ const os = require('os');const crypto = require('crypto');const net = require('net');const { spawn, spawnSync } = require('child_process');+const {+ assertSameProcessIdentity,+ assertStandardWindowsPrivilege,+ buildNativeProcessQuery,+ filterVerifiedWindowsProcesses,+ parseCimProcessResult,+ resolveWindowsExecutable,+ sameWindowsPath,+ selectRunningProfileBinary,+ selectUniqueDiscoveredBinary,+} = require('./windows-process-boundary.js');+const DAEMON_PRIVILEGE = process.platform === 'win32'+ ? assertStandardWindowsPrivilege()+ : 'standard';// ws(WebSocketServer)用于 DevTools 代理:Electron 的 CDP server 拒绝带 Origin 的 WS 连接// (浏览器必带 Origin → DevTools 前端 "websocket disconnected"),daemon 代理中转去掉 Originlet wsLib = null;@@ -86,7 +100,6 @@ const { buildCreditResourceBody } = require('./credit-resource-queries.js');const { captureException, captureMessage } = require('./sentry-report.js');const { getProfile, profileDataDir, listInstalledModelSources } = require('./profiles.js');const { classifyTarget, looksLikeWbFamilyTarget, isTargetForProfile } = require('./cdp-targets.js');-const PROFILE = getProfile();const DATA_DIR = defaultDataDir();// 版本号:改动 daemon/inject/theme-patches/builtin 资产后递增,launcher 检测到运行中版本不一致会强制用 app 内置代码重启@@ -111,7 +124,7 @@ const DATA_DIR = defaultDataDir();// ③ 发布包内曾混入非 ASCII 文件名(安装失败自主解决提示词.txt),Windows .NET Expand-Archive 解压时// 文件名解码成非法字符直接抛「路径中具有非法字符」→ 备份/替换/回滚全部失效。// 修复:更新脚本改由 wscript.exe(GUI 子系统)+ apply-update.vbs 中介经 ShellExecute 启动独立进程树,-// daemon 随即自我退出释放文件锁;apply-update.ps1 对 watchdog 与端口进程一律 taskkill 不带 /T 精确杀,+// daemon 随即自我退出释放文件锁;apply-update.ps1 对 watchdog 与端口进程一律按 PID 精确结束,// 避免连坐自身;打包脚本 build-win-zip.sh 增加非 ASCII 文件名守护,杜绝中文/特殊字符条目进入安装包。// 另:daemon 单实例锁、启动竞态修复、注入结果校验与本地诊断快照;// 修复跨平台自动更新并展示按到期时间拆分的积分明细@@ -155,8 +168,9 @@ const DATA_DIR = defaultDataDir();// AI 端 CDP 误连国内端、watchdog 路径和退出确认问题。// 1.0.13:下载使用唯一临时文件并在校验通过后原子替换,防止并发更新造成 ENOENT。// 1.0.25:会话删除仅作用于数据库匹配记录,并在清理失败时保留可重试的数据库记录。-const DAEMON_VERSION = '1.0.25';-const DAEMON_BUILD_ID = 'release-1.0.25-20260824-session-delete-confinement';+// 1.0.26:Windows launcher/logout 取消脚本提权与镜像名结束,只操作同安装目录的已验证 PID。+const DAEMON_VERSION = '1.0.26';+const DAEMON_BUILD_ID = 'release-1.0.26-20260824-least-privilege';const HOST = '127.0.0.1';const IS_WIN = process.platform === 'win32'; // Windows 移植:平台分支开关(macOS 行为保持不变)// Windows 安装目录(install.ps1 铺、launcher 用、更新替换目标),对应 macOS 的 /Applications/WorkDaddy.app@@ -1564,32 +1578,69 @@ const WORKBUDDY_APP_NAME = path.basename(WORKBUDDY_APP).replace(/\.app$/i, '');// Windows:解析 WorkBuddy 可执行文件真实路径(安装盘可自定义,必须动态查)// 优先级:WBSWITCH_WORKBUDDY_BIN > 运行进程 Path > 注册表卸载项 > 常见路径let wbBinaryCache = null;+const PROFILE_BINARY_NAMES = new Set(+ PROFILE.id === 'workbuddy-ai' ? ['workbuddyai.exe'] :+ PROFILE.id === 'workbuddy-cn' ? ['workbuddy.exe'] : ['codebuddy.exe']+);+function queryWindowsWorkBuddyProcesses() {+ const names = [...PROFILE_BINARY_NAMES].map((name) => `\"${name}\"`).join(',');+ const helper = path.join(__dirname, 'windows-process-boundary.ps1');+ const command = buildNativeProcessQuery(helper,+ `$names=@(${names}); Get-CimInstance Win32_Process -ErrorAction Stop | Where-Object { $names -contains $_.Name }`);+ const result = spawnSync('powershell', ['-NoProfile', '-ExecutionPolicy', 'Bypass', '-Command', command], {+ encoding: 'utf8', timeout: 10000, windowsHide: true,+ });+ return parseCimProcessResult(result, {+ requireCommandLine: true, requireCurrentOwner: true, requireNativeArguments: true,+ });+}+function resolveWorkBuddyBinary() {if (!IS_WIN) return WORKBUDDY_BINARY;if (wbBinaryCache) return wbBinaryCache;- const tryFile = (p) => { try { if (p && fs.existsSync(p)) return p; } catch (_) {} return null; };+ const tryFile = (p) => {+ try {+ const candidate = String(p || '').trim().replace(/^"(.*)"(?:,\d+)?$/, '$1').replace(/,\d+$/, '');+ if (!candidate || !fs.existsSync(candidate)) return null;+ const resolved = resolveWindowsExecutable(candidate);+ const name = path.win32.basename(resolved).toLowerCase();+ return PROFILE_BINARY_NAMES.has(name) ? resolved : null;+ } catch (_) {+ return null;+ }+ };const { execFileSync } = require('child_process');const psCmd = (cmd) => execFileSync('powershell', ['-NoProfile', '-Command', cmd], { encoding: 'utf8', timeout: 8000, windowsHide: true });- // 1) 显式指定(launcher/install 传入最可靠)+ const runningBin = selectRunningProfileBinary(PROFILE_BINARY_NAMES, queryWindowsWorkBuddyProcesses());+ // 1) 显式指定;若当前 profile 已运行,必须与运行路径完全一致。const envBin = tryFile(process.env.WBSWITCH_WORKBUDDY_BIN);- if (envBin) return (wbBinaryCache = envBin);- // 2) 运行中的 WorkBuddy 进程 Path(最权威:多实例共享同一 exe)- try {- const out = psCmd('Get-Process WorkBuddy -ErrorAction SilentlyContinue | Select-Object -First 1 -ExpandProperty Path');- const p = out.trim().split(/\r?\n/).filter(Boolean).pop();- const hit = tryFile(p);- if (hit) return (wbBinaryCache = hit);- } catch (_) {}- // 3) 注册表卸载项(DisplayIcon = "D:\xxx\WorkBuddy.exe,0" 取逗号前)- try {- const out = psCmd("$k=@('HKLM:\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\*','HKLM:\\SOFTWARE\\WOW6432Node\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\*','HKCU:\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\*'); Get-ItemProperty $k -ErrorAction SilentlyContinue | Where-Object { $_.DisplayName -match 'WorkBuddy|CodeBuddy' } | Select-Object -First 1 DisplayIcon,InstallLocation | ForEach-Object { if($_.DisplayIcon){ ($_.DisplayIcon -replace ',.*$','').Trim() } elseif($_.InstallLocation){ Join-Path $_.InstallLocation 'WorkBuddy.exe' } }");- const p = out.trim().split(/\r?\n/).filter(Boolean).pop();- const hit = tryFile(p);- if (hit) return (wbBinaryCache = hit);- } catch (_) {}- // 4) 常见路径兜底(含 per-user 安装和 Electron/Squirrel 版本目录)+ if (process.env.WBSWITCH_WORKBUDDY_BIN && !envBin) {+ throw new Error('WBSWITCH_WORKBUDDY_BIN 不是可验证的当前 profile 主程序;登录信息未修改');+ }+ if (envBin) {+ if (runningBin && !sameWindowsPath(runningBin, envBin)) {+ throw new Error('检测到当前 profile 正从另一安装目录运行,登录信息未修改');+ }+ return (wbBinaryCache = envBin);+ }+ // 2) 运行中当前 profile 的主程序优先(便携安装)。+ if (runningBin) return (wbBinaryCache = runningBin);+ const discovered = [];+ const addCandidate = (candidate) => {+ const hit = tryFile(candidate);+ if (hit) discovered.push(hit);+ };+ // 3) 收集磁盘和注册表候选;无运行进程时只能接受唯一真实路径。+ addCandidate(PROFILE.appPath);+ const appPaths = psCmd("$k=@('HKCU:\\Software\\Microsoft\\Windows\\CurrentVersion\\App Paths\\WorkBuddy.exe','HKLM:\\Software\\Microsoft\\Windows\\CurrentVersion\\App Paths\\WorkBuddy.exe','HKCU:\\Software\\Microsoft\\Windows\\CurrentVersion\\App Paths\\CodeBuddy.exe','HKLM:\\Software\\Microsoft\\Windows\\CurrentVersion\\App Paths\\CodeBuddy.exe'); Get-ItemProperty $k -ErrorAction SilentlyContinue | ForEach-Object { if ($_.'(default)') { $_.'(default)' } elseif ($_.Path) { $_.Path } }");+ for (const candidate of appPaths.split(/\r?\n/).map((line) => line.trim()).filter(Boolean)) addCandidate(candidate);+ const registry = psCmd("$k=@('HKLM:\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\*','HKLM:\\SOFTWARE\\WOW6432Node\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\*','HKCU:\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\*'); Get-ItemProperty $k -ErrorAction SilentlyContinue | Where-Object { $_.DisplayName -match 'WorkBuddy|CodeBuddy' } | ForEach-Object { if($_.DisplayIcon){ ($_.DisplayIcon -replace ',.*$','').Trim() } elseif($_.InstallLocation){ Join-Path $_.InstallLocation 'WorkBuddy.exe' } }");+ for (const candidate of registry.split(/\r?\n/).map((line) => line.trim()).filter(Boolean)) addCandidate(candidate);+ // 4) 常见路径兜底(含探测机实际安装位)const cands = [+ PROFILE.appPath,path.join(process.env.LOCALAPPDATA || '', 'Programs', 'WorkBuddy', 'WorkBuddy.exe'),+ path.join(process.env.LOCALAPPDATA || '', 'Programs', 'WorkBuddyAI', 'WorkBuddyAI.exe'),path.join(process.env.ProgramFiles || '', 'WorkBuddy', 'WorkBuddy.exe'),path.join(process.env['ProgramFiles(x86)'] || '', 'WorkBuddy', 'WorkBuddy.exe'),path.join(process.env.LOCALAPPDATA || '', 'WorkBuddy', 'WorkBuddy.exe'),@@ -1599,44 +1650,38 @@ function resolveWorkBuddyBinary() {path.join(process.env.LOCALAPPDATA || '', 'Programs', 'CodeBuddy', 'WorkBuddy.exe'),'D:\\workbody\\WorkBuddy\\WorkBuddy.exe',];- if (PROFILE.id === 'workbuddy-ai') {- cands.unshift(- path.join(process.env.LOCALAPPDATA || '', 'Programs', 'WorkBuddyAI', 'WorkBuddyAI.exe'),- path.join(process.env.LOCALAPPDATA || '', 'WorkBuddyAI', 'WorkBuddyAI.exe')- );- }- for (const c of cands) {- const hit = tryFile(c);- if (hit) return (wbBinaryCache = hit);- }- try {- const roots = [- process.env.LOCALAPPDATA && path.join(process.env.LOCALAPPDATA, 'Programs', 'WorkBuddy'),- process.env.LOCALAPPDATA && path.join(process.env.LOCALAPPDATA, 'WorkBuddy'),- process.env.APPDATA && path.join(process.env.APPDATA, 'WorkBuddy'),- process.env.LOCALAPPDATA && path.join(process.env.LOCALAPPDATA, 'Programs', 'CodeBuddy'),- process.env.LOCALAPPDATA && path.join(process.env.LOCALAPPDATA, 'CodeBuddy'),- process.env.LOCALAPPDATA && path.join(process.env.LOCALAPPDATA, 'Programs', 'WorkBuddyAI'),- process.env.LOCALAPPDATA && path.join(process.env.LOCALAPPDATA, 'WorkBuddyAI'),- ].filter(Boolean);- const names = PROFILE.id === 'workbuddy-ai'- ? ['WorkBuddyAI.exe', 'WorkBuddy.exe']- : ['WorkBuddy.exe', 'CodeBuddy.exe'];- const psQuote = (value) => "'" + String(value).replace(/'/g, "''") + "'";- const command = [- '$roots=@(' + roots.map(psQuote).join(', ') + ')',- '$names=@(' + names.map(psQuote).join(', ') + ')',- 'foreach($root in $roots){',- 'if(-not (Test-Path -LiteralPath $root -PathType Container)){continue}',- '$hit=Get-ChildItem -LiteralPath $root -File -Recurse -Depth 5 -ErrorAction SilentlyContinue | Where-Object { $names -contains $_.Name } | Select-Object -First 1 -ExpandProperty FullName',- 'if($hit){$hit;break}',- '}',- ].join('; ');- const p = psCmd(command).trim().split(/\r?\n/).map((line) => line.trim()).filter(Boolean).pop();- const hit = tryFile(p);- if (hit) return (wbBinaryCache = hit);- } catch (_) {}- return null;+ cands.push(+ path.join(process.env.ProgramFiles || '', 'WorkBuddyAI', 'WorkBuddyAI.exe'),+ path.join(process.env.ProgramFiles || '', 'CodeBuddy', 'CodeBuddy.exe'),+ path.join(process.env.USERPROFILE || '', 'scoop', 'apps', 'workbuddy', 'current', 'WorkBuddy.exe'),+ 'D:\\workbuddy\\WorkBuddy.exe'+ );+ if (process.env.WBSWITCH_WORKBUDDY_DIR) {+ cands.push(path.join(process.env.WBSWITCH_WORKBUDDY_DIR, path.win32.basename(PROFILE.appPath)));+ }+ for (const candidate of cands) addCandidate(candidate);+ const scanRoots = [+ process.env.LOCALAPPDATA && path.join(process.env.LOCALAPPDATA, 'Programs', 'WorkBuddy'),+ process.env.LOCALAPPDATA && path.join(process.env.LOCALAPPDATA, 'WorkBuddy'),+ process.env.APPDATA && path.join(process.env.APPDATA, 'WorkBuddy'),+ process.env.LOCALAPPDATA && path.join(process.env.LOCALAPPDATA, 'Programs', 'CodeBuddy'),+ process.env.LOCALAPPDATA && path.join(process.env.LOCALAPPDATA, 'CodeBuddy'),+ process.env.LOCALAPPDATA && path.join(process.env.LOCALAPPDATA, 'Programs', 'WorkBuddyAI'),+ process.env.LOCALAPPDATA && path.join(process.env.LOCALAPPDATA, 'WorkBuddyAI'),+ ].filter(Boolean);+ const names = [...PROFILE_BINARY_NAMES];+ const psQuote = (value) => "'" + String(value).replace(/'/g, "''") + "'";+ const command = [+ '$roots=@(' + scanRoots.map(psQuote).join(', ') + ')',+ '$names=@(' + names.map(psQuote).join(', ') + ')',+ 'foreach($root in $roots){',+ 'if(-not (Test-Path -LiteralPath $root -PathType Container)){continue}',+ 'Get-ChildItem -LiteralPath $root -File -Recurse -Depth 5 -ErrorAction SilentlyContinue | Where-Object { $names -contains $_.Name } | Select-Object -ExpandProperty FullName',+ '}',+ ].join('; ');+ for (const candidate of psCmd(command).split(/\r?\n/).map((line) => line.trim()).filter(Boolean)) addCandidate(candidate);+ const selected = selectUniqueDiscoveredBinary(PROFILE_BINARY_NAMES, discovered);+ return selected ? (wbBinaryCache = selected) : null;}function runCommand(command, args, options = {}) {@@ -1699,56 +1744,80 @@ async function restoreWorkBuddyWindow(pid) {return true;}-function workBuddyRunning() {+function verifiedWindowsWorkBuddyProcesses(binary) {+ if (!binary) throw new Error('未找到 WorkBuddy 可执行文件,无法验证运行中的进程');+ const processes = queryWindowsWorkBuddyProcesses();+ const verified = filterVerifiedWindowsProcesses(binary, processes);+ if (processes.length !== verified.length) {+ throw new Error('存在当前 profile 进程,但没有进程属于已验证安装目录;登录信息未修改');+ }+ return verified;+}++function revalidateWindowsWorkBuddyProcess(original, binary) {+ const current = verifiedWindowsWorkBuddyProcesses(binary)+ .find((process) => process.ProcessId === original.ProcessId);+ if (!current) {+ throw new Error(`结束前无法再次验证 WorkBuddy PID=${original.ProcessId}`);+ }+ return assertSameProcessIdentity(original, current);+}++function workBuddyRunning(binary = null) {try {if (IS_WIN) {- const r = spawnSync(- 'tasklist',- ['/FI', 'IMAGENAME eq WorkBuddy.exe', '/FO', 'CSV', '/NH'],- { encoding: 'utf8', timeout: 5000, windowsHide: true }- );- return r.status === 0 && /"WorkBuddy\.exe"/i.test(r.stdout || '');+ return verifiedWindowsWorkBuddyProcesses(binary || resolveWorkBuddyBinary()).length > 0;}const r = spawnSync('pgrep', ['-f', WORKBUDDY_APP], { stdio: 'ignore', timeout: 5000 });return r.status === 0;- } catch (_) {+ } catch (error) {// 探测失败时按仍在运行处理,避免误删身份文件后拉起旧实例。+ if (IS_WIN) throw error;return true;}}-async function waitForWorkBuddyExit(timeoutMs = 10000) {+async function waitForWorkBuddyExit(timeoutMs = 10000, binary = null) {const deadline = Date.now() + timeoutMs;while (Date.now() < deadline) {- if (!workBuddyRunning()) return true;+ if (!workBuddyRunning(binary)) return true;await sleep(200);}- return !workBuddyRunning();-}--async function elevatedWindowsKill() {- const command =- "$p = Start-Process -FilePath 'taskkill.exe' -ArgumentList '/F','/T','/IM','WorkBuddy.exe' -Verb RunAs -Wait -PassThru; exit $p.ExitCode";- return runCommand('powershell', ['-NoProfile', '-ExecutionPolicy', 'Bypass', '-Command', command], { timeoutMs: 30000 });+ return !workBuddyRunning(binary);}/** 退出 WorkBuddy,并确认进程已经消失;失败时拒绝继续登录切换。 */async function quitWorkBuddy() {- if (!workBuddyRunning()) return true;-if (IS_WIN) {- await runCommand('taskkill', ['/IM', 'WorkBuddy.exe']);- if (await waitForWorkBuddyExit(1800)) return true;-- await runCommand('taskkill', ['/F', '/T', '/IM', 'WorkBuddy.exe']);- if (await waitForWorkBuddyExit(2500)) return true;+ const binary = resolveWorkBuddyBinary();+ if (!binary) throw new Error('未找到 WorkBuddy 可执行文件,无法安全退出;登录信息未修改');+ let processes = verifiedWindowsWorkBuddyProcesses(binary);+ if (!processes.length) return true;++ for (const process of processes) {+ const current = revalidateWindowsWorkBuddyProcess(process, binary);+ const result = await runCommand('taskkill', ['/PID', String(current.ProcessId)]);+ if (result.error || result.code !== 0) {+ throw result.error || new Error(`taskkill 无法结束已验证进程 PID=${process.ProcessId}`);+ }+ }+ if (await waitForWorkBuddyExit(1800, binary)) return true;++ processes = verifiedWindowsWorkBuddyProcesses(binary);+ for (const process of processes) {+ const current = revalidateWindowsWorkBuddyProcess(process, binary);+ const result = await runCommand('taskkill', ['/F', '/PID', String(current.ProcessId)]);+ if (result.error || result.code !== 0) {+ throw result.error || new Error(`taskkill 无法强制结束已验证进程 PID=${process.ProcessId}`);+ }+ }+ if (await waitForWorkBuddyExit(2500, binary)) return true;- // WorkBuddy 可能由管理员权限启动;普通 daemon 无法结束它时请求一次 UAC。- await elevatedWindowsKill();- if (await waitForWorkBuddyExit(5000)) return true;- throw new Error('无法确认 WorkBuddy 已退出(可能未通过管理员授权)');+ throw new Error('无法以普通用户权限安全退出 WorkBuddy。请手动关闭该程序;若它以管理员身份运行,请先退出后再重试。登录信息未修改');}+ if (!workBuddyRunning()) return true;+// 先尝试正常退出(给 Electron 一次处理机会),再强制 kill 并验证。await runCommand('osascript', ['-e', `tell application "${WORKBUDDY_APP_NAME}" to quit`]);if (await waitForWorkBuddyExit(2500)) return true;@@ -4383,6 +4452,8 @@ function handleApi(req, res) {ok: true,version: DAEMON_VERSION,buildId: DAEMON_BUILD_ID,+ pid: process.pid,+ privilege: DAEMON_PRIVILEGE,profile: { id: PROFILE.id, name: PROFILE.name, kind: PROFILE.kind, mode: PROFILE.mode, capabilities: PROFILE.capabilities },cdp: {connected: cdp.connected,diff --git a/scripts/install-win.ps1 b/scripts/install-win.ps1index f4c24c7..30a9fc3 100644--- a/scripts/install-win.ps1+++ b/scripts/install-win.ps1@@ -8,6 +8,24 @@ param([string]$Profile = '__WBS_DEFAULT_PROFILE__')+try {+ $identity = [Security.Principal.WindowsIdentity]::GetCurrent()+ $principal = New-Object Security.Principal.WindowsPrincipal($identity)+ $isElevated = $principal.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)+ if ($isElevated -ne $false) {+ [Console]::Error.WriteLine('拒绝以管理员权限运行 WorkDaddy 安装脚本;请使用普通用户终端。')+ exit 5+ }+} catch {+ [Console]::Error.WriteLine('无法确认当前 PowerShell 为普通用户权限;安装已停止。')+ exit 5+}++$ErrorActionPreference = 'Stop'+try { . (Join-Path $PSScriptRoot 'windows-process-boundary.ps1') } catch {+ [Console]::Error.WriteLine('无法加载 Windows 进程身份边界;安装已停止。')+ exit 5+}$ErrorActionPreference = 'Continue'if ([string]::IsNullOrWhiteSpace($Profile) -or $Profile -eq '__WBS_DEFAULT_PROFILE__') { $Profile = 'workbuddy-cn' }if ($Profile -ne 'workbuddy-ai') { $Profile = 'workbuddy-cn' }@@ -37,39 +55,6 @@ function Send-Sentry {} catch {}}-function Test-ExclusiveFile {- param([string]$Path)- if (-not (Test-Path -LiteralPath $Path)) { return $true }- $stream = $null- try {- $stream = [IO.File]::Open($Path, [IO.FileMode]::Open, [IO.FileAccess]::Read, [IO.FileShare]::None)- return $true- } catch {- return $false- } finally {- if ($stream) { $stream.Dispose() }- }-}--function Release-LockedLauncher {- param([string]$LauncherPath)- if (Test-ExclusiveFile $LauncherPath) { return $true }- $needle = ([IO.Path]::GetFullPath($LauncherPath)).Replace('/', '\').ToLowerInvariant()- try {- Get-CimInstance Win32_Process -Filter "Name = 'cmd.exe'" -ErrorAction SilentlyContinue | ForEach-Object {- $commandLine = ([string]$_.CommandLine).Replace('/', '\').ToLowerInvariant()- if ($commandLine.Contains($needle) -and $_.ProcessId -ne $PID) {- taskkill /F /T /PID $_.ProcessId 2>$null | Out-Null- }- }- } catch {}- for ($i = 0; $i -lt 10; $i++) {- if (Test-ExclusiveFile $LauncherPath) { return $true }- Start-Sleep -Milliseconds 300- }- return (Test-ExclusiveFile $LauncherPath)-}-Write-Host '=============================================================='Write-Host (" " + $productName + " Windows 安装")Write-Host '=============================================================='@@ -91,7 +76,7 @@ if ([StringComparer]::OrdinalIgnoreCase.Equals($sourceFull, $targetFull)) {Write-Host ' 源目录与安装目录相同,跳过自拷贝。'} else {$launcherToReplace = Join-Path $targetScripts 'launcher.cmd'- if (-not (Release-LockedLauncher $launcherToReplace)) {+ if (-not (Release-VerifiedLauncherLock -LauncherPath $launcherToReplace)) {Write-Host "复制前无法释放 launcher.cmd 文件锁: $launcherToReplace"Send-Sentry 'windows-install-launcher-lock' "无法释放 launcher.cmd 文件锁: $launcherToReplace" 2exit 2@@ -145,7 +130,7 @@ if (Test-Path $launcher) {}# 5) 创建桌面快捷方式(名称跟随安装包 profile)-# 优先使用 wscript.exe 隐藏入口,避免 Windows Terminal 为管理员 cmd 创建空白窗口;+# 优先使用 wscript.exe 隐藏入口,避免启动时出现多余的终端窗口;# 缺少隐藏入口时回退到 cmd.exe,兼容旧包/手工安装目录。$desktopDir = [Environment]::GetFolderPath('Desktop')if (-not $desktopDir) { $desktopDir = Join-Path $env:USERPROFILE 'Desktop' }@@ -163,7 +148,7 @@ try {$sc.Arguments = '/d /c call "' + $launcher + '"'}$sc.WorkingDirectory = (Split-Path $launcher)- $sc.Description = ($productName + ' – WorkBuddy 增强工具(请以管理员身份运行)') # 描述跟随安装包 profile(WorkDaddy / WorkDaddy AI)+ $sc.Description = ($productName + ' – WorkBuddy 增强工具') # 描述跟随安装包 profile(WorkDaddy / WorkDaddy AI)if (Test-Path $logoIco) { $sc.IconLocation = $logoIco + ',0' } # 用官方 logo,而非 cmd 默认图标$sc.Save()Write-Host (' 桌面快捷方式 : ' + $lnkPath)diff --git a/scripts/kill.js b/scripts/kill.jsdeleted file mode 100644index b9b0a05..0000000--- a/scripts/kill.js+++ /dev/null@@ -1,4 +0,0 @@-const {spawnSync}=require('child_process');-const r=spawnSync('taskkill',['/F','/T','/IM','WorkBuddy.exe'],{encoding:'utf8',windowsHide:true,timeout:10000});-console.log('status:',r.status);-console.log('stdout:',(r.stdout||'').split(/\r?\n/).filter(Boolean).slice(-6).join('\n'));diff --git a/scripts/launcher-hidden.vbs b/scripts/launcher-hidden.vbsindex d02cb05..a543032 100644--- a/scripts/launcher-hidden.vbs+++ b/scripts/launcher-hidden.vbs@@ -1,7 +1,6 @@Option Explicit-' Desktop shortcut entry point. wscript.exe has no console window, so running the-' shortcut as administrator cannot leave an empty Windows Terminal tab behind.+' Desktop shortcut entry point. wscript.exe starts launcher.cmd without a console window.Dim shell, fso, launcher, commandSet shell = CreateObject("WScript.Shell")Set fso = CreateObject("Scripting.FileSystemObject")diff --git a/scripts/launcher.cmd b/scripts/launcher.cmdindex 93f5513..63ec3bb 100644--- a/scripts/launcher.cmd+++ b/scripts/launcher.cmd@@ -5,8 +5,7 @@ setlocal EnableExtensionschcp 65001 >nul 2>&1cd /d "%~dp0" >nul 2>&1-rem 先输出一行 ASCII 状态:管理员启动时 Windows Terminal 可能在 Node 探测期间保持空白,-rem 这行也能区分“正在启动”和“入口没有执行”。+rem 先输出一行 ASCII 状态,便于区分“正在启动”和“入口没有执行”。echo WorkDaddy launcher starting...rem 定位 node:优先 WorkBuddy 托管运行时(.workbuddy\binaries\node\versions\*),其次 PATHdiff --git a/scripts/uninstall-win.ps1 b/scripts/uninstall-win.ps1index 0078e5d..4b50c0a 100644--- a/scripts/uninstall-win.ps1+++ b/scripts/uninstall-win.ps1@@ -7,17 +7,46 @@ param([string]$Profile = '__WBS_DEFAULT_PROFILE__')+try {+ $identity = [Security.Principal.WindowsIdentity]::GetCurrent()+ $principal = New-Object Security.Principal.WindowsPrincipal($identity)+ $isElevated = $principal.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)+ if ($isElevated -ne $false) {+ [Console]::Error.WriteLine('拒绝以管理员权限运行 WorkDaddy 卸载脚本;请使用普通用户终端。')+ exit 5+ }+} catch {+ [Console]::Error.WriteLine('无法确认当前 PowerShell 为普通用户权限;卸载已停止。')+ exit 5+}++$ErrorActionPreference = 'Stop'+try { . (Join-Path $PSScriptRoot 'windows-process-boundary.ps1') } catch {+ [Console]::Error.WriteLine('无法加载 Windows 进程身份边界;卸载已停止。')+ exit 5+}$ErrorActionPreference = 'Continue'if ([string]::IsNullOrWhiteSpace($Profile) -or $Profile -eq '__WBS_DEFAULT_PROFILE__') { $Profile = 'workbuddy-cn' }if ($Profile -ne 'workbuddy-ai') { $Profile = 'workbuddy-cn' }$productName = if ($Profile -eq 'workbuddy-ai') { 'WorkDaddy AI' } else { 'WorkDaddy' }if ([string]::IsNullOrWhiteSpace($AppDir)) { $AppDir = Join-Path $env:LOCALAPPDATA (Join-Path 'Programs' $productName) }+if (-not (Test-SameWindowsPath -Left $PSScriptRoot -Right (Join-Path $AppDir 'scripts'))) {+ throw '卸载脚本位置与目标安装目录不一致,拒绝删除'+}$dataRoot = Join-Path $env:APPDATA 'WorkDaddy'$dataDir = if ($Profile -eq 'workbuddy-ai') { Join-Path $dataRoot 'profiles\workbuddy-ai' } else { $dataRoot }+$port = if ($Profile -eq 'workbuddy-ai') { 47833 } else { 47832 }Write-Host ('卸载 ' + $productName + '...')-# 1) 移除登录自启(兼容 WorkDaddy / WorkDaddy AI 两个 profile)+# 1) 只有在 watchdog/daemon 身份确认或明确不存在后才允许任何卸载写操作。+Stop-VerifiedWorkDaddyLifecycle `+ -DataDir $dataDir `+ -Port $port `+ -ExpectedWatchdogScript (Join-Path $AppDir 'scripts\watchdog.js') `+ -ExpectedDaemonScript (Join-Path $AppDir 'scripts\daemon.js')++# 2) 移除登录自启(兼容 WorkDaddy / WorkDaddy AI 两个 profile)try {foreach ($runName in @('WorkDaddy', 'WorkDaddy AI')) {Remove-ItemProperty -Path 'HKCU:\Software\Microsoft\Windows\CurrentVersion\Run' -Name $runName -ErrorAction SilentlyContinue@@ -25,30 +54,18 @@ try {Write-Host ' 已移除登录自启项'} catch {}-# 2) 停止 watchdog + daemon-$pidFile = Join-Path $dataDir 'watchdog.pid'-if (Test-Path $pidFile) {- try {- $wpid = [int]((Get-Content $pidFile -Raw).Trim())- if ($wpid -gt 0) { taskkill /F /T /PID $wpid 2>$null | Out-Null }- } catch {}-}-foreach ($line in (netstat -ano | Select-String (':4783\d\s') | Select-String 'LISTENING')) {- $parts = ($line.ToString().Trim() -split '\s+')- $pid2 = $parts[$parts.Count - 1]- if ($pid2 -match '^\d+$') { taskkill /F /T /PID $pid2 2>$null | Out-Null }-}-# 3) 删除安装目录if (Test-Path $AppDir) {- Remove-Item -Recurse -Force $AppDir -ErrorAction SilentlyContinue+ Remove-Item -LiteralPath $AppDir -Recurse -Force -ErrorAction Stop+ if (Test-Path -LiteralPath $AppDir) { throw "安装目录删除失败: $AppDir" }Write-Host (' 已删除安装目录: ' + $AppDir)}# 4) 数据目录(可选)if ($RemoveData) {if (Test-Path $dataDir) {- Remove-Item -Recurse -Force $dataDir -ErrorAction SilentlyContinue+ Remove-Item -LiteralPath $dataDir -Recurse -Force -ErrorAction Stop+ if (Test-Path -LiteralPath $dataDir) { throw "数据目录删除失败: $dataDir" }Write-Host (' 已删除数据目录(含账号备份): ' + $dataDir)}} else {diff --git a/scripts/verify-win.cmd b/scripts/verify-win.cmdindex 6eb79f6..1f09898 100644--- a/scripts/verify-win.cmd+++ b/scripts/verify-win.cmd@@ -18,7 +18,7 @@ set "FAIL=0"rem ---- 1) 关键文件齐全 ----echo.echo [1/6] 检查关键文件...-for %%F in (daemon.js lib.js watchdog.js win-launcher.js win-inject-helper.js inject.js theme-patches.js launcher.cmd launcher-hidden.vbs install-win.cmd install-win.ps1 win\setup.sed) do (+for %%F in (daemon.js lib.js watchdog.js win-launcher.js windows-process-boundary.js windows-process-boundary.ps1 inject.js theme-patches.js launcher.cmd launcher-hidden.vbs install-win.cmd install-win.ps1 uninstall-win.ps1 apply-update.ps1 win\setup.sed) do (if not exist "%SCRIPT_DIR%%%F" (echo 缺失: %%~Fset /a FAIL+=1@@ -55,7 +55,7 @@ if errorlevel 1 (rem ---- 3) 脚本语法静态检查(node --check,不执行)----echo.echo [3/6] 校验 JS 语法...-for %%F in (daemon.js lib.js watchdog.js win-launcher.js inject.js theme-patches.js) do (+for %%F in (daemon.js lib.js watchdog.js win-launcher.js windows-process-boundary.js inject.js theme-patches.js) do ("%NODE%" --check "%SCRIPT_DIR%%%F" >nul 2>&1if errorlevel 1 (echo 语法错误: %%~F@@ -67,7 +67,7 @@ echo JS 语法检查完成rem ---- 4) PS1 合法性(PowerShell 解析但不执行)----echo.echo [4/6] 校验 PS1 脚本语法...-for %%F in (install-win.ps1) do (+for %%F in (windows-process-boundary.ps1 install-win.ps1 uninstall-win.ps1 apply-update.ps1) do (powershell -NoProfile -ExecutionPolicy Bypass -Command "$e=$null; [void][System.Management.Automation.Language.Parser]::ParseFile('%SCRIPT_DIR%%%F',[ref]$null,[ref]$e); if($e){Write-Host (' 语法错误: ' + $e.Message); exit 1} else {Write-Host (' OK: ' + '%%~nF')}; exit 0" >nul 2>&1if errorlevel 1 (echo 语法错误: %%~F@@ -75,9 +75,9 @@ for %%F in (install-win.ps1) do ())-rem ---- 5) 自启清理状态与安装目录回写测试(读态 + 安装目录可写性探测)----+rem ---- 5) 自启清理状态与安装目录回写测试(读态 + 安装目录可写性探测)----echo.-echo [5/6] 检查安装目标可写 + 旧自启状态...+echo [5/6] 检查安装目标可写 + 旧自启状态...set "APPDIR=%LOCALAPPDATA%\Programs\WorkDaddy"if exist "%APPDIR%\scripts\daemon.js" (echo 已安装版本: "%APPDIR%" 存在diff --git a/scripts/watchdog.js b/scripts/watchdog.jsindex 92359a5..41b7be1 100644--- a/scripts/watchdog.js+++ b/scripts/watchdog.js@@ -14,9 +14,19 @@const fs = require('fs');const path = require('path');const os = require('os');-const { spawn } = require('child_process');+const { spawn, spawnSync } = require('child_process');+const {+ assertSameProcessIdentity,+ assertStandardWindowsPrivilege,+ assertVerifiedNodeProcess,+ buildNativeProcessQuery,+ filterVerifiedNodeProcesses,+ parseCimProcessResult,+} = require('./windows-process-boundary.js');const { getProfile, profileDataDir } = require('./profiles.js');+if (process.platform === 'win32') assertStandardWindowsPrivilege();+const SCRIPTS_DIR = __dirname;const PROFILE_ID = process.env.WBSWITCH_PROFILE || 'workbuddy-cn';const PROFILE = getProfile(PROFILE_ID);@@ -26,6 +36,7 @@ const DATA_DIR =const PID_FILE = path.join(DATA_DIR, 'watchdog.pid');const LOG_FILE = path.join(DATA_DIR, 'watchdog.log');const UPDATE_PENDING_FILE = path.join(DATA_DIR, 'update', 'pending.json'); // 自动更新进行中标记(update 目录由 apply 流程创建)+const DAEMON_FILE = path.join(SCRIPTS_DIR, 'daemon.js');function log(...args) {const line = `[${new Date().toISOString()}] ${args.join(' ')}\n`;@@ -36,42 +47,143 @@ function log(...args) {try { process.stdout.write(line); } catch (_) {}}-/** 读取 PID 文件并检测进程是否存活(Windows: tasklist /FI) */-function pidFileAlive() {+function readPidFile() {try {- const pid = parseInt(fs.readFileSync(PID_FILE, 'utf8').trim(), 10);- if (!pid || pid === process.pid) return false;- const r = require('child_process').spawnSync(- 'tasklist',- ['/FI', 'PID eq ' + pid, '/FO', 'CSV', '/NH'],- { encoding: 'utf8', timeout: 5000, windowsHide: true }- );- return r.status === 0 && /node/i.test(r.stdout);- } catch (_) {- return false;+ const text = fs.readFileSync(PID_FILE, 'utf8').trim();+ const pid = Number(text);+ if (!Number.isSafeInteger(pid) || pid <= 0 || String(pid) !== text) {+ throw new Error('watchdog.pid 内容无效');+ }+ return pid;+ } catch (error) {+ if (error && error.code === 'ENOENT') return null;+ throw error;}}+function runProcessQuery(whereClause) {+ const helper = path.join(__dirname, 'windows-process-boundary.ps1');+ const command = buildNativeProcessQuery(helper,+ `Get-CimInstance Win32_Process -ErrorAction Stop | Where-Object { ${whereClause} }`);+ const result = spawnSync('powershell', ['-NoProfile', '-NonInteractive', '-ExecutionPolicy', 'Bypass', '-Command', command], {+ encoding: 'utf8', timeout: 10000, windowsHide: true,+ });+ return parseCimProcessResult(result, {+ requireCommandLine: true, requireCurrentOwner: true, requireNativeArguments: true,+ });+}++function queryProcess(pid) {+ return runProcessQuery(`[int]$_.ProcessId -eq ${pid}`);+}++function queryWatchdogProcessFamily(pid) {+ return runProcessQuery(`[int]$_.ProcessId -eq ${pid} -or [int]$_.ParentProcessId -eq ${pid}`);+}++function queryWatchdogProcesses() {+ return runProcessQuery("$_.Name -eq 'node.exe'");+}++function pidFileState() {+ const pid = readPidFile();+ if (!pid) {+ const untracked = filterVerifiedNodeProcesses(+ process.execPath, __filename, queryWatchdogProcesses()+ ).filter((item) => item.ProcessId !== process.pid)+ .map((item) => assertSameProcessIdentity(item, item));+ if (untracked.length) {+ return { kind: 'untracked', pid: null, processIds: untracked.map((item) => item.ProcessId) };+ }+ return { kind: 'absent', pid: null };+ }+ if (pid === process.pid) return { kind: 'self', pid };+ const processes = queryWatchdogProcessFamily(pid);+ if (!processes.length) return { kind: 'stale', pid };+ const watchdog = assertVerifiedNodeProcess(pid, process.execPath, __filename, processes);+ assertSameProcessIdentity(watchdog, watchdog);+ return { kind: 'verified', pid, watchdog, processes };+}++function removePidFileIf(pid) {+ const current = readPidFile();+ if (current !== pid) throw new Error('watchdog.pid 在操作期间发生变化,拒绝删除');+ fs.unlinkSync(PID_FILE);+}++function verifiedDaemonChildren(watchdogPid, processes) {+ const matches = filterVerifiedNodeProcesses(process.execPath, DAEMON_FILE, processes)+ .map((item) => assertSameProcessIdentity(item, item));+ for (const daemon of matches) {+ if (!Number.isSafeInteger(daemon.ParentProcessId) || daemon.ParentProcessId !== watchdogPid) {+ throw new Error(`无法验证 daemon PID=${daemon.ProcessId} 的 watchdog 父进程`);+ }+ }+ return matches;+}++function terminateVerifiedProcess(original, expectedScript, label, expectedParentPid, allowMissing = false) {+ const processes = queryProcess(original.ProcessId);+ if (!processes.length) {+ if (allowMissing) return false;+ throw new Error(`结束前无法再次验证 ${label} PID=${original.ProcessId}`);+ }+ const verified = assertVerifiedNodeProcess(+ original.ProcessId, process.execPath, expectedScript, processes+ );+ assertSameProcessIdentity(original, verified);+ if (expectedParentPid !== undefined && verified.ParentProcessId !== expectedParentPid) {+ throw new Error(`结束前无法再次验证 ${label} PID=${original.ProcessId} 的父进程`);+ }+ const result = spawnSync('taskkill', ['/F', '/PID', String(original.ProcessId)], {+ stdio: 'ignore', windowsHide: true, timeout: 10000,+ });+ if (result.error || result.status !== 0) {+ throw new Error(`无法结束已验证 ${label} PID=${original.ProcessId}`);+ }+ if (queryProcess(original.ProcessId).length) {+ throw new Error(`${label} PID=${original.ProcessId} 在结束后仍然存在`);+ }+ return true;+}++function stopVerifiedWatchdog() {+ const state = pidFileState();+ if (state.kind === 'absent') return;+ if (state.kind === 'self') throw new Error('stop 命令不能结束自身');+ if (state.kind === 'untracked') {+ throw new Error(`检测到没有 PID 文件的 watchdog 进程 PID=${state.processIds.join(',')},无法确定当前 profile,拒绝结束`);+ }+ if (state.kind === 'stale') throw new Error('无法验证 watchdog.pid 指向的进程,拒绝删除 PID 文件');+ const daemons = verifiedDaemonChildren(state.pid, state.processes);+ // 先结束守护进程,防止它在 daemon 退出后竞态拉起新实例;子进程逐个复验并结束。+ terminateVerifiedProcess(state.watchdog, __filename, 'watchdog');+ for (const daemon of daemons) {+ terminateVerifiedProcess(daemon, DAEMON_FILE, 'daemon', state.pid, true);+ }+ removePidFileIf(state.pid);+}+if (process.argv.includes('stop')) {log('收到 stop 指令,退出中...');- try {- const pid = parseInt(fs.readFileSync(PID_FILE, 'utf8').trim(), 10);- if (pid && pid !== process.pid) {- require('child_process').spawnSync('taskkill', ['/F', '/T', '/PID', String(pid)], { stdio: 'ignore', windowsHide: true });- }- } catch (_) {}- try { fs.unlinkSync(PID_FILE); } catch (_) {}+ stopVerifiedWatchdog();process.exit(0);}-// 单实例保护-if (pidFileAlive()) {+// 单实例保护:用户可写 PID 文件只作候选,必须用 CIM 路径和命令行证明真实身份。+const existing = pidFileState();+if (existing.kind === 'verified') {log('已有 watchdog 实例在运行,本实例退出');process.exit(0);}+if (existing.kind === 'self') throw new Error('watchdog.pid 意外指向当前进程');+if (existing.kind === 'stale') throw new Error('无法验证 watchdog.pid 指向的进程,拒绝删除 PID 文件');+if (existing.kind === 'untracked') {+ throw new Error(`检测到没有 PID 文件的 watchdog 进程 PID=${existing.processIds.join(',')},拒绝启动重复实例`);+}fs.mkdirSync(DATA_DIR, { recursive: true });-fs.writeFileSync(PID_FILE, String(process.pid));+fs.writeFileSync(PID_FILE, String(process.pid), { flag: 'wx' });let child = null;let stopping = false;@@ -80,7 +192,7 @@ let restartDelay = 3000; // 初始 3s,连续崩溃递增,上限 60sfunction startDaemon() {if (stopping) return;const node = process.execPath;- const args = ['--experimental-sqlite', path.join(SCRIPTS_DIR, 'daemon.js')];+ const args = ['--experimental-sqlite', DAEMON_FILE];log('启动 daemon: ' + node + ' ' + args.join(' '));child = spawn(node, args, { stdio: 'ignore', windowsHide: true, env: process.env });child.on('error', (e) => {@@ -115,7 +227,7 @@ function shutdown() {try { child.kill(); } catch (_) {}}setTimeout(() => {- try { fs.unlinkSync(PID_FILE); } catch (_) {}+ try { removePidFileIf(process.pid); } catch (_) {}process.exit(0);}, 800);}diff --git a/scripts/win-inject-helper.js b/scripts/win-inject-helper.jsdeleted file mode 100644index c1f0887..0000000--- a/scripts/win-inject-helper.js+++ /dev/null@@ -1,48 +0,0 @@-#!/usr/bin/env node-/**- * WorkDaddy 提权注入助手(win-launcher.js 的成人版重跑)- *- * 背景:WorkBuddy 常装在 C:\Program Files(受 UAC 保护的特权目录)。- * 若旧 WorkBuddy 进程本身已提升,结束它需要管理员权限;WorkBuddy 新 GUI 进程仍保持用户权限。- * 普通权限启动 launcher 时无法完成这一步(表现为黑屏空转、9222 起不来)。- *- * 本助手由 win-launcher.js 通过 Start-Process -Verb RunAs 以管理员身份拉起:- * 1) 转交系统里真实的 win-launcher.js 继续执行(此时进程已是管理员)- * 2) launcher 以管理员权限结束旧进程/接管 daemon,再通过 ShellExecute 以用户权限启动 WorkBuddy- *- * 用法(仅内部):- * node win-inject-helper.js [cdpPort]- * 通常由 launcher 派发,无需用户直接运行。- */-'use strict';--const path = require('path');-const { spawnSync } = require('child_process');--// 复用同一份 main 逻辑:以管理员身份重跑 win-launcher.js-// 传参 --inject-helper 会让 win-launcher 知道"正在提权流程中,别二次派发",避免死循环。-const LAUNCHER = path.join(__dirname, 'win-launcher.js');--// 校验当前确实是管理员-let elevated = false;-try {- elevated = spawnSync('net', ['session'], { stdio: 'ignore', windowsHide: true, timeout: 8000 }).status === 0;-} catch (_) {}--if (!elevated) {- console.error('错误:win-inject-helper 必须以管理员身份运行。');- process.exit(2);-}--// Windows 下重新分配一个真正的控制台窗口过于复杂;直接静默继续-// (launcher 会负责日志与提示)。把它作为子进程跑完。-const cdpPort = process.argv.slice(2).find((arg) => /^\d+$/.test(arg));-const args = ['--inject-helper'];-if (cdpPort) args.push('--cdp-port=' + cdpPort);-const cp = spawnSync(process.execPath, [LAUNCHER, ...args], {- stdio: 'inherit',- windowsHide: true,- timeout: 90000,-});--process.exit(cp.status === null ? 1 : cp.status);diff --git a/scripts/win-launcher.js b/scripts/win-launcher.jsindex 46b1340..ffd88cf 100644--- a/scripts/win-launcher.js+++ b/scripts/win-launcher.js@@ -18,6 +18,27 @@ const os = require('os');const net = require('net');const http = require('http');const { spawn, spawnSync } = require('child_process');+const {+ assertDaemonServiceIdentity,+ assertDaemonTerminationIdentity,+ assertSameProcessIdentity,+ assertStandardWindowsPrivilege,+ assertVerifiedNodeProcess,+ buildNativeProcessQuery,+ filterVerifiedNodeProcesses,+ filterVerifiedWindowsProcesses,+ parseCimProcessResult,+ resolveWindowsExecutable,+ sameWindowsPath,+ selectRunningProfileBinary,+ selectUniqueDiscoveredBinary,+} = require('./windows-process-boundary.js');+try {+ assertStandardWindowsPrivilege();+} catch (error) {+ console.error(error.message);+ process.exit(5);+}const { captureMessage, captureException } = require('./sentry-report.js');const { getProfile, profileDataDir } = require('./profiles.js');const { isTargetForProfile } = require('./cdp-targets.js');@@ -43,14 +64,16 @@ const DEFAULT_CDP_PORT = (PROFILE_CDP_PORTS[PROFILE.id] || [9222])[0];const cliCdpPort = process.argv.find((arg) => /^--cdp-port=\d+$/i.test(arg));let CDP_PORT = parseInt(process.env.WBSWITCH_CDP_PORT || (cliCdpPort ? cliCdpPort.split('=')[1] : '') || String(DEFAULT_CDP_PORT), 10);const CDP_PORT_FILE = path.join(DATA_DIR, 'cdp-port.json');-const ELEVATED_HELPER_MODE = process.argv.includes('--inject-helper');// 便携版/低速磁盘上的 WorkBuddy 首次启动可能超过 20 秒;超时只应在足够长的窗口后报告。const CDP_STARTUP_TIMEOUT_MS = 60000;-// PR#8 实机确认 WorkBuddy 两个版本分别使用 WorkBuddy.exe / WorkBuddyAI.exe。-// 两者都纳入探测和退出;路径过滤负责避免 CN launcher 误杀 AI 的同名族进程。+// 每个 profile 只查询自己的主程序镜像;其他 CodeBuddy/WorkBuddy profile 不参与退出判定。const PROFILE_PROCESS_NAMES = new Set(- PROFILE.kind === 'workbuddy' ? ['workbuddy.exe', 'workbuddyai.exe'] :- PROFILE.id === 'codebuddy-intl' ? ['codebuddy.exe'] : ['codebuddy.exe']+ PROFILE.id === 'workbuddy-ai' ? ['workbuddyai.exe'] :+ PROFILE.id === 'workbuddy-cn' ? ['workbuddy.exe'] : ['codebuddy.exe']+);+const PROFILE_BINARY_NAMES = new Set(+ PROFILE.id === 'workbuddy-ai' ? ['workbuddyai.exe'] :+ PROFILE.id === 'workbuddy-cn' ? ['workbuddy.exe'] : ['codebuddy.exe']);function log(...args) {@@ -98,49 +121,6 @@ function cdpPortCandidates() {return result;}-// 当前进程是否为管理员(Windows)-function isElevated() {- try {- const r = spawnSync(- 'net', ['session'], { stdio: 'ignore', windowsHide: true, timeout: 8000 }- );- return r.status === 0;- } catch (_) { return false; }-}--// 以管理员身份运行"重启注入助手"(child 脚本),launcher 本体保持普通权限。-// 返回是否已成功派发(派发后 launcher 立即退出,由助手完成真正的重启+注入)。-function spawnElevatedHelper() {- const nodeBin = process.execPath; // 当前 node- const childJs = path.join(SCRIPTS_DIR, 'win-inject-helper.js');- if (!fs.existsSync(childJs)) return false;- // 用 UTF-16LE 编码 PowerShell 命令,避免安装目录含中文时经过当前代码页导致路径乱码;- // Node 参数顺序必须是「脚本路径 → 脚本参数」,否则 --inject-helper 会被 Node 当成自身选项。- const childArg = '"' + childJs + '"';- const command = [- "$ErrorActionPreference = 'Stop'",- 'Start-Process -FilePath ' + psQuote(nodeBin) + ' ' +- '-ArgumentList @(' + [psQuote(childArg), psQuote('--inject-helper'), psQuote(String(CDP_PORT))].join(', ') + ') ' +- '-Verb RunAs -WindowStyle Hidden',- ].join('; ');- const encodedCommand = Buffer.from(command, 'utf16le').toString('base64');- const ps = [- '-NoProfile', '-ExecutionPolicy', 'Bypass',- '-EncodedCommand', encodedCommand,- ];- try {- const r = spawnSync('powershell', ps, { stdio: 'ignore', windowsHide: true, timeout: 15000 });- if (r.error || r.status !== 0) {- log('提权助手派发失败: ' + (r.error ? r.error.message : 'powershell exit ' + r.status));- return false;- }- return true;- } catch (e) {- log('提权助手派发异常: ' + e.message);- return false;- }-}-function portOpen(port) {return new Promise((resolve) => {const s = net.connect({ port, host: HOST });@@ -205,13 +185,17 @@ async function isWorkBuddyCdpAt(port, binary = null) {httpGet(port, '/json/list'),]);if (!version || version.status !== 200 || !targets || targets.status !== 200) return false;+ let list;try {- const info = JSON.parse(version.body || '{}');- const list = JSON.parse(targets.body || '[]');- if (Array.isArray(list) && list.some((target) => isTargetForProfile(target, PROFILE))) return true;- // 某些版本隐藏页面强信号;只有同安装目录进程的精确参数带着该端口时才允许兜底。- return Boolean(binary && workBuddyProcesses(binary).some((p) => processCdpPort(p) === Number(port)));- } catch (_) { return false; }+ JSON.parse(version.body || '{}');+ list = JSON.parse(targets.body || '[]');+ } catch (_) {+ return false;+ }+ if (Array.isArray(list) && list.some((target) => isTargetForProfile(target, PROFILE))) return true;+ // 某些版本隐藏页面强信号;只有同安装目录进程的精确参数带着该端口时才允许兜底。+ // CIM 查询错误由共享边界直接抛出,不能伪装成“没有目标进程”。+ return Boolean(binary && workBuddyProcesses(binary).some((p) => processCdpPort(p) === Number(port)));}async function configureCdpPort() {@@ -235,116 +219,58 @@ async function configureCdpPort() {throw new Error('9222-9232、9333 均被占用,无法启动 WorkBuddy CDP');}-function psOut(cmd) {- try {- return spawnSync('powershell', ['-NoProfile', '-Command', cmd], {- encoding: 'utf8', timeout: 10000, windowsHide: true,- }).stdout || '';- } catch (_) { return ''; }-}--// 进程名并不总是可靠:Electron 的单实例宿主可能以 CodeBuddy.exe 或辅助进程名存在。-// 通过 CIM 同时拿到路径、父 PID 和命令行,只在本地诊断使用;命令行正文绝不写入日志/Sentry。-function getWorkBuddyProcessesViaCim() {- const command = [- '$names=@("WorkBuddy.exe","CodeBuddy.exe","WorkBuddyAI.exe")',- 'Get-CimInstance Win32_Process -ErrorAction SilentlyContinue',- '| Where-Object { $names -contains $_.Name }',- '| Select-Object ProcessId,ParentProcessId,Name,ExecutablePath,CommandLine',- '| ConvertTo-Json -Compress',- ].join(' ');- const raw = psOut(command).trim();- if (!raw) return [];- try {- const parsed = JSON.parse(raw);- return (Array.isArray(parsed) ? parsed : [parsed]).filter((p) => p && Number(p.ProcessId) > 0);- } catch (_) {- return [];- }-}--function parseTasklistOutput(raw) {- const processes = [];- for (const line of String(raw || '').split(/\r?\n/)) {- const match = line.match(/^"([^"]+)","(\d+)"/);- if (!match) continue;- processes.push({- ProcessId: Number(match[2]),- ParentProcessId: null,- Name: match[1],- ExecutablePath: null,- CommandLine: '',- processSource: 'tasklist',- });- }- return processes;-}--function getWorkBuddyProcessesViaTasklist() {- const processes = [];- for (const name of PROFILE_PROCESS_NAMES) {- try {- const result = spawnSync('tasklist', ['/FI', 'IMAGENAME eq ' + name, '/FO', 'CSV', '/NH'], {- encoding: 'utf8', timeout: 5000, windowsHide: true,- });- processes.push(...parseTasklistOutput(result.stdout));- } catch (_) {}- }- return processes;+function strictPowerShellLines(cmd) {+ const result = spawnSync('powershell', ['-NoProfile', '-NonInteractive', '-Command', cmd], {+ encoding: 'utf8', timeout: 10000, windowsHide: true,+ });+ if (result.error) throw result.error;+ if (result.status !== 0) throw new Error(`PowerShell 路径发现失败: ${String(result.stderr || '').trim()}`);+ return String(result.stdout || '').split(/\r?\n/).map((line) => line.trim()).filter(Boolean);}+// 通过 CIM 查询当前 profile 主程序的路径、父 PID 和命令行;命令行正文绝不写入日志/Sentry。function getWorkBuddyProcesses() {- const cimProcesses = getWorkBuddyProcessesViaCim();- // CIM 偶发返回空或不可解析时,tasklist 仍能提供 PID,避免把运行中的客户端误判为不存在。- return cimProcesses.length ? cimProcesses : getWorkBuddyProcessesViaTasklist();+ const names = [...PROFILE_PROCESS_NAMES].map((name) => `\"${name}\"`).join(',');+ const command = buildNativeProcessQuery(+ path.join(SCRIPTS_DIR, 'windows-process-boundary.ps1'),+ `$names=@(${names}); Get-CimInstance Win32_Process -ErrorAction Stop | Where-Object { $names -contains $_.Name }`+ );+ const result = spawnSync('powershell', ['-NoProfile', '-ExecutionPolicy', 'Bypass', '-Command', command], {+ encoding: 'utf8', timeout: 10000, windowsHide: true,+ });+ return parseCimProcessResult(result, {+ requireCommandLine: true,+ requireCurrentOwner: true,+ requireNativeArguments: true,+ });}-function sameWindowsPath(a, b) {- if (!a || !b) return false;- return String(a).replace(/[\\/]+$/, '').toLowerCase() === String(b).replace(/[\\/]+$/, '').toLowerCase();+// 仅保留为本地端口诊断;daemon 启动成功必须走 exactDaemonStatus 完整身份校验。+function daemonRunning() {+ return portOpen(UI_PORT);}function workBuddyProcesses(binary = null) {- return getWorkBuddyProcesses().filter((p) => {- if (!PROFILE_PROCESS_NAMES.has(String(p.Name || '').toLowerCase())) return false;- if (!binary) return true;- // tasklist 回退没有路径,只接受与目标二进制同名的主进程,避免跨客户端误杀。- if (!p.ExecutablePath) return String(p.Name || '').toLowerCase() === path.basename(binary).toLowerCase();- // WorkBuddy 可能把 Electron 主进程拆成同目录下的 CodeBuddy.exe/辅助宿主;按安装目录归组。- return sameWindowsPath(p.ExecutablePath, binary) ||- sameWindowsPath(path.dirname(p.ExecutablePath), path.dirname(binary));- });-}--function targetProcessNames(binary = null) {- const names = new Set();- const normalized = String(binary || '').toLowerCase();- for (const p of getWorkBuddyProcesses()) {- if (!PROFILE_PROCESS_NAMES.has(String(p.Name || '').toLowerCase())) continue;- if (binary) {- if (!p.ExecutablePath && String(p.Name || '').toLowerCase() !== path.basename(binary).toLowerCase()) continue;- if (p.ExecutablePath && !(- sameWindowsPath(p.ExecutablePath, binary) ||- sameWindowsPath(path.dirname(p.ExecutablePath), path.dirname(binary))- )) continue;- }- names.add(String(p.Name).toLowerCase());+ const processes = getWorkBuddyProcesses();+ if (!binary) return processes;+ const verified = filterVerifiedWindowsProcesses(binary, processes);+ if (processes.length !== verified.length) {+ throw new Error('存在当前 profile 进程,但没有进程属于已验证安装目录,请先手动退出后重试');}- if (names.size) return names;- if (normalized.endsWith('workbuddyai.exe') || PROFILE.id === 'workbuddy-ai') return new Set(['workbuddyai.exe']);- return new Set(['workbuddy.exe']);+ return verified;}+// 只读诊断:tasklist 结果仅写入失败快照,绝不进入任何 taskkill 参数或退出判定。function tasklistProcessIds(names = PROFILE_PROCESS_NAMES) {const ids = new Set();for (const name of names) {try {- const r = spawnSync('tasklist', ['/FI', 'IMAGENAME eq ' + name, '/FO', 'CSV', '/NH'], {+ const result = spawnSync('tasklist', ['/FI', 'IMAGENAME eq ' + name, '/FO', 'CSV', '/NH'], {encoding: 'utf8', timeout: 5000, windowsHide: true,});- for (const line of String(r.stdout || '').split(/\r?\n/)) {- const m = line.match(/^"[^"]+","(\d+)"/);- if (m) ids.add(m[1]);+ for (const line of String(result.stdout || '').split(/\r?\n/)) {+ const match = line.match(/^"[^"]+","(\d+)"/);+ if (match) ids.add(match[1]);}} catch (_) {}}@@ -388,6 +314,18 @@ function readDaemonVersion() {} catch (_) { return ''; }}+function readDaemonIdentity() {+ try {+ const src = fs.readFileSync(path.join(SCRIPTS_DIR, 'daemon.js'), 'utf8');+ return {+ version: (src.match(/DAEMON_VERSION\s*=\s*'([^']+)'/) || [])[1] || '',+ buildId: (src.match(/DAEMON_BUILD_ID\s*=\s*'([^']+)'/) || [])[1] || '',+ };+ } catch (_) {+ return { version: '', buildId: '' };+ }+}+// ---------- 定位 node(托管优先:.workbuddy\binaries\node\versions\<v>\node.exe,其次 PATH) ----------function findNode() {const base = path.join(os.homedir(), '.workbuddy', 'binaries', 'node', 'versions');@@ -398,10 +336,11 @@ function findNode() {.filter((p) => fs.existsSync(p)).sort();} catch (_) {}- if (verDirs.length) return verDirs[verDirs.length - 1];+ if (verDirs.length) return resolveWindowsExecutable(verDirs[verDirs.length - 1]);try {- const r = spawnSync('node', ['-v'], { encoding: 'utf8', timeout: 3000, windowsHide: true });- if (r.status === 0) return 'node';+ const r = spawnSync('where.exe', ['node.exe'], { encoding: 'utf8', timeout: 3000, windowsHide: true });+ const candidate = String(r.stdout || '').split(/\r?\n/).map((line) => line.trim()).find(Boolean);+ if (r.status === 0 && candidate) return resolveWindowsExecutable(candidate);} catch (_) {}return null;}@@ -413,38 +352,44 @@ function findWorkBuddy() {const tryFile = (p) => {try {const candidate = String(p || '').trim().replace(/^"(.*)"(?:,\d+)?$/, '$1').replace(/,\d+$/, '');- if (candidate && fs.existsSync(candidate)) return candidate;+ if (!candidate || !fs.existsSync(candidate)) return null;+ const resolved = resolveWindowsExecutable(candidate);+ return PROFILE_BINARY_NAMES.has(path.win32.basename(resolved).toLowerCase()) ? resolved : null;} catch (_) {}return null;};+ const runningBin = selectRunningProfileBinary([...PROFILE_BINARY_NAMES], getWorkBuddyProcesses());const envBin = tryFile(process.env.WBSWITCH_WORKBUDDY_BIN);- if (envBin) return (wbBinaryCache = envBin);- const profileBin = tryFile(PROFILE.appPath);- if (profileBin) return (wbBinaryCache = profileBin);- try {- const p = psOut('Get-Process WorkBuddy -ErrorAction SilentlyContinue | Select-Object -First 1 -ExpandProperty Path').split(/\r?\n/).filter(Boolean).pop();- const hit = tryFile(p);- if (hit) return (wbBinaryCache = hit);- } catch (_) {}- try {- const p = psOut("Get-CimInstance Win32_Process -ErrorAction SilentlyContinue | Where-Object { $_.Name -match '^(WorkBuddy|CodeBuddy|WorkBuddyAI)\\.exe$' -and $_.ExecutablePath } | Select-Object -First 1 -ExpandProperty ExecutablePath").split(/\r?\n/).filter(Boolean).pop();- const hit = tryFile(p);- if (hit) return (wbBinaryCache = hit);- } catch (_) {}+ if (process.env.WBSWITCH_WORKBUDDY_BIN && !envBin) {+ throw new Error('WBSWITCH_WORKBUDDY_BIN 不是可验证的当前 profile 主程序');+ }+ if (envBin) {+ if (runningBin && !sameWindowsPath(runningBin, envBin)) {+ throw new Error('检测到当前 profile 正从另一安装目录运行,请先手动退出后重试');+ }+ return (wbBinaryCache = envBin);+ }+ if (runningBin) return (wbBinaryCache = runningBin);+ const discovered = [];+ const addCandidate = (candidate) => {+ const hit = tryFile(candidate);+ if (hit) discovered.push(hit);+ };+ addCandidate(PROFILE.appPath);// 便携版通常没有卸载项,但可能注册了 App Paths;优先读取其真实可执行路径。- try {- const p = psOut("$k=@('HKCU:\\Software\\Microsoft\\Windows\\CurrentVersion\\App Paths\\WorkBuddy.exe','HKLM:\\Software\\Microsoft\\Windows\\CurrentVersion\\App Paths\\WorkBuddy.exe','HKCU:\\Software\\Microsoft\\Windows\\CurrentVersion\\App Paths\\CodeBuddy.exe','HKLM:\\Software\\Microsoft\\Windows\\CurrentVersion\\App Paths\\CodeBuddy.exe'); Get-ItemProperty $k -ErrorAction SilentlyContinue | ForEach-Object { if ($_.'(default)') { $_.'(default)' } elseif ($_.Path) { $_.Path } } | Select-Object -First 1").split(/\r?\n/).filter(Boolean).pop();- const hit = tryFile(p);- if (hit) return (wbBinaryCache = hit);- } catch (_) {}- try {- const p = psOut("$k=@('HKLM:\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\*','HKLM:\\SOFTWARE\\WOW6432Node\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\*','HKCU:\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\*'); Get-ItemProperty $k -ErrorAction SilentlyContinue | Where-Object { $_.DisplayName -match 'WorkBuddy|CodeBuddy' } | Select-Object -First 1 DisplayIcon,InstallLocation | ForEach-Object { if($_.DisplayIcon){ ($_.DisplayIcon -replace ',.*$','').Trim() } elseif($_.InstallLocation){ Join-Path $_.InstallLocation 'WorkBuddy.exe' } }").split(/\r?\n/).filter(Boolean).pop();- const hit = tryFile(p);- if (hit) return (wbBinaryCache = hit);- } catch (_) {}+ for (const candidate of strictPowerShellLines("$k=@('HKCU:\\Software\\Microsoft\\Windows\\CurrentVersion\\App Paths\\WorkBuddy.exe','HKLM:\\Software\\Microsoft\\Windows\\CurrentVersion\\App Paths\\WorkBuddy.exe','HKCU:\\Software\\Microsoft\\Windows\\CurrentVersion\\App Paths\\CodeBuddy.exe','HKLM:\\Software\\Microsoft\\Windows\\CurrentVersion\\App Paths\\CodeBuddy.exe'); Get-ItemProperty $k -ErrorAction SilentlyContinue | ForEach-Object { if ($_.'(default)') { $_.'(default)' } elseif ($_.Path) { $_.Path } }")) {+ addCandidate(candidate);+ }+ for (const candidate of strictPowerShellLines("$k=@('HKLM:\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\*','HKLM:\\SOFTWARE\\WOW6432Node\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\*','HKCU:\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\*'); Get-ItemProperty $k -ErrorAction SilentlyContinue | Where-Object { $_.DisplayName -match 'WorkBuddy|CodeBuddy' } | ForEach-Object { if($_.DisplayIcon){ ($_.DisplayIcon -replace ',.*$','').Trim() } elseif($_.InstallLocation){ Join-Path $_.InstallLocation 'WorkBuddy.exe' } }")) {+ addCandidate(candidate);+ }const roots = [path.join(process.env.LOCALAPPDATA || '', 'Programs', 'WorkBuddy', 'WorkBuddy.exe'),+ path.join(process.env.LOCALAPPDATA || '', 'Programs', 'WorkBuddyAI', 'WorkBuddyAI.exe'),+ path.join(process.env.LOCALAPPDATA || '', 'Programs', 'CodeBuddy', 'CodeBuddy.exe'),path.join(process.env.ProgramFiles || '', 'WorkBuddy', 'WorkBuddy.exe'),+ path.join(process.env.ProgramFiles || '', 'WorkBuddyAI', 'WorkBuddyAI.exe'),+ path.join(process.env.ProgramFiles || '', 'CodeBuddy', 'CodeBuddy.exe'),path.join(process.env['ProgramFiles(x86)'] || '', 'WorkBuddy', 'WorkBuddy.exe'),path.join(process.env.LOCALAPPDATA || '', 'WorkBuddy', 'WorkBuddy.exe'),path.join(process.env.APPDATA || '', 'WorkBuddy', 'WorkBuddy.exe'),@@ -460,159 +405,282 @@ function findWorkBuddy() {path.join(process.env.LOCALAPPDATA || '', 'WorkBuddyAI', 'WorkBuddyAI.exe'));}- if (process.env.WBSWITCH_WORKBUDDY_DIR) roots.push(path.join(process.env.WBSWITCH_WORKBUDDY_DIR, 'WorkBuddy.exe'));- for (const candidate of roots) {- const hit = tryFile(candidate);- if (hit) return (wbBinaryCache = hit);- }- // 兼容 Electron/Squirrel 把 exe 放在 app-5.3.14 等版本子目录的安装方式;- // 只扫描明确的客户端目录,避免递归扫描整盘或整个用户目录。- try {- const scanDirs = [- path.join(process.env.LOCALAPPDATA || '', 'Programs', 'WorkBuddy'),- path.join(process.env.LOCALAPPDATA || '', 'WorkBuddy'),- path.join(process.env.APPDATA || '', 'WorkBuddy'),- path.join(process.env.LOCALAPPDATA || '', 'Programs', 'CodeBuddy'),- path.join(process.env.LOCALAPPDATA || '', 'CodeBuddy'),- ];- if (PROFILE.id === 'workbuddy-ai') {- scanDirs.unshift(- path.join(process.env.LOCALAPPDATA || '', 'Programs', 'WorkBuddyAI'),- path.join(process.env.LOCALAPPDATA || '', 'WorkBuddyAI')- );- }- const names = PROFILE.id === 'workbuddy-ai'- ? ['WorkBuddyAI.exe', 'WorkBuddy.exe']- : ['WorkBuddy.exe', 'CodeBuddy.exe'];- const rootArgs = scanDirs.map(psQuote).join(', ');- const nameArgs = names.map(psQuote).join(', ');- const command = [- '$roots=@(' + rootArgs + ')',- '$names=@(' + nameArgs + ')',- 'foreach($root in $roots){',- 'if(-not (Test-Path -LiteralPath $root -PathType Container)){continue}',- '$hit=Get-ChildItem -LiteralPath $root -File -Recurse -Depth 5 -ErrorAction SilentlyContinue | Where-Object { $names -contains $_.Name } | Select-Object -First 1 -ExpandProperty FullName',- 'if($hit){$hit;break}',- '}',- ].join('; ');- const p = psOut(command).split(/\r?\n/).map((line) => line.trim()).filter(Boolean).pop();- const hit = tryFile(p);- if (hit) return (wbBinaryCache = hit);- } catch (_) {}- // 兼容类似 D:\Software\workbuddy\WorkBuddy.exe 的便携目录。+ if (process.env.WBSWITCH_WORKBUDDY_DIR) {+ roots.push(path.join(process.env.WBSWITCH_WORKBUDDY_DIR, [...PROFILE_BINARY_NAMES][0]));+ }+ // 兼容类似 D:\\Software\\workbuddy\\WorkBuddy.exe 的便携目录,不递归扫描整盘。+ const driveRoots = strictPowerShellLines('(Get-PSDrive -PSProvider FileSystem).Root');+ for (const root of driveRoots) {+ roots.push(path.join(root, 'Software', 'workbuddy', 'WorkBuddy.exe'));+ roots.push(path.join(root, 'Software', 'workbuddy-ai', 'WorkBuddyAI.exe'));+ roots.push(path.join(root, 'Software', 'codebuddy', 'CodeBuddy.exe'));+ roots.push(path.join(root, 'workbuddy', 'WorkBuddy.exe'));+ roots.push(path.join(root, 'WorkBuddy', 'WorkBuddy.exe'));+ }+ for (const candidate of roots) addCandidate(candidate);+ // 兼容 Electron/Squirrel 的 app-<version> 子目录;收集全部命中后再要求唯一真实路径。+ const scanDirs = [+ path.join(process.env.LOCALAPPDATA || '', 'Programs', 'WorkBuddy'),+ path.join(process.env.LOCALAPPDATA || '', 'WorkBuddy'),+ path.join(process.env.APPDATA || '', 'WorkBuddy'),+ path.join(process.env.LOCALAPPDATA || '', 'Programs', 'CodeBuddy'),+ path.join(process.env.LOCALAPPDATA || '', 'CodeBuddy'),+ path.join(process.env.LOCALAPPDATA || '', 'Programs', 'WorkBuddyAI'),+ path.join(process.env.LOCALAPPDATA || '', 'WorkBuddyAI'),+ ];+ const psLiteral = (value) => "'" + String(value).replace(/'/g, "''") + "'";+ const scanCommand = [+ '$roots=@(' + scanDirs.map(psLiteral).join(', ') + ')',+ '$names=@(' + [...PROFILE_BINARY_NAMES].map(psLiteral).join(', ') + ')',+ 'foreach($root in $roots){',+ 'if(-not (Test-Path -LiteralPath $root -PathType Container)){continue}',+ 'Get-ChildItem -LiteralPath $root -File -Recurse -Depth 5 -ErrorAction SilentlyContinue | Where-Object { $names -contains $_.Name } | Select-Object -ExpandProperty FullName',+ '}',+ ].join('; ');+ for (const candidate of strictPowerShellLines(scanCommand)) addCandidate(candidate);+ const selected = selectUniqueDiscoveredBinary(PROFILE_BINARY_NAMES, discovered);+ return selected ? (wbBinaryCache = selected) : null;+}++// ---------- 1. 确保 daemon 运行 ----------+const WATCHDOG_PID_FILE = path.join(DATA_DIR, 'watchdog.pid');+const WATCHDOG_SCRIPT = path.join(SCRIPTS_DIR, 'watchdog.js');+const DAEMON_SCRIPT = path.join(SCRIPTS_DIR, 'daemon.js');++function listenerPids(port) {+ const result = spawnSync('netstat', ['-ano', '-p', 'tcp'], {+ encoding: 'utf8', timeout: 8000, windowsHide: true,+ });+ if (result.error || result.status !== 0) throw new Error('无法查询 daemon 监听进程');+ const pids = new Set();+ for (const line of String(result.stdout || '').split(/\r?\n/)) {+ const fields = line.trim().split(/\s+/);+ if (fields.length < 5 || !/LISTENING/i.test(fields[3]) || !fields[1].endsWith(':' + port)) continue;+ const pid = Number(fields[fields.length - 1]);+ if (!Number.isSafeInteger(pid) || pid <= 0) throw new Error('daemon 监听 PID 无效');+ pids.add(pid);+ }+ return [...pids];+}++function queryNodeProcesses(pids = null) {+ let source = "Get-CimInstance Win32_Process -Filter \"Name = 'node.exe'\" -ErrorAction Stop";+ if (pids !== null) {+ const safePids = [...new Set(pids.map(Number))];+ if (!safePids.length) return [];+ if (safePids.some((pid) => !Number.isSafeInteger(pid) || pid <= 0)) throw new Error('目标 Node PID 无效');+ source = `$ids=@(${safePids.join(',')}); ${source} | Where-Object { $ids -contains [int]$_.ProcessId }`;+ }+ const command = buildNativeProcessQuery(+ path.join(SCRIPTS_DIR, 'windows-process-boundary.ps1'), source+ );+ const result = spawnSync('powershell', ['-NoProfile', '-NonInteractive', '-ExecutionPolicy', 'Bypass', '-Command', command], {+ encoding: 'utf8', timeout: 10000, windowsHide: true,+ });+ return parseCimProcessResult(result, {+ requireCommandLine: true,+ requireCurrentOwner: true,+ requireNativeArguments: true,+ });+}++function uniqueNodeProcess(nodeBin, expectedScript) {+ const matches = filterVerifiedNodeProcesses(nodeBin, expectedScript, queryNodeProcesses());+ if (matches.length > 1) throw new Error(`目标 Node 入口存在多个进程: ${expectedScript}`);+ return matches[0] || null;+}++function readWatchdogPid() {try {- const driveRoots = psOut('(Get-PSDrive -PSProvider FileSystem).Root').split(/\r?\n/).map((x) => x.trim()).filter(Boolean);- for (const root of driveRoots) {- roots.push(path.join(root, 'Software', 'workbuddy', 'WorkBuddy.exe'));- roots.push(path.join(root, 'workbuddy', 'WorkBuddy.exe'));- roots.push(path.join(root, 'WorkBuddy', 'WorkBuddy.exe'));- }- } catch (_) {}- for (const candidate of roots) {- const hit = tryFile(candidate);- if (hit) return (wbBinaryCache = hit);+ const text = fs.readFileSync(WATCHDOG_PID_FILE, 'utf8').trim();+ const pid = Number(text);+ if (!Number.isSafeInteger(pid) || pid <= 0 || String(pid) !== text) throw new Error('watchdog.pid 内容无效');+ return pid;+ } catch (error) {+ if (error && error.code === 'ENOENT') return null;+ throw error;+ }+}++function watchdogState(nodeBin) {+ const pid = readWatchdogPid();+ const exact = uniqueNodeProcess(nodeBin, WATCHDOG_SCRIPT);+ if (!pid) return exact ? { kind: 'untracked', pid: null, process: exact } : { kind: 'absent', pid: null };+ const processes = queryNodeProcesses([pid]);+ if (processes.length === 0) {+ if (exact) throw new Error('watchdog.pid 指向不存在的 PID,但发现了另一个精确 watchdog 进程');+ return { kind: 'stale', pid };+ }+ const process = assertVerifiedNodeProcess(pid, nodeBin, WATCHDOG_SCRIPT, processes);+ if (!exact || exact.ProcessId !== pid) throw new Error('watchdog.pid 与枚举到的精确 watchdog 进程不一致');+ assertSameProcessIdentity(exact, process);+ return { kind: 'verified', pid, process };+}++function validateDaemonProcess(nodeBin, status = null) {+ const listeners = listenerPids(UI_PORT);+ if (listeners.length !== 1) throw new Error('daemon 监听 PID 不唯一或不存在');+ if (status && status.pid != null &&+ (!Number.isSafeInteger(status.pid) || status.pid <= 0 || status.pid !== listeners[0])) {+ throw new Error('daemon 状态 PID 无效或与监听 PID 不一致');+ }+ const processes = queryNodeProcesses(listeners);+ assertVerifiedNodeProcess(listeners[0], nodeBin, DAEMON_SCRIPT, processes);+ return { listenerPids: listeners, nodeProcesses: processes };+}++function exactDaemonStatus(nodeBin, status) {+ const identity = readDaemonIdentity();+ const processIdentity = validateDaemonProcess(nodeBin, status);+ assertDaemonServiceIdentity({+ status,+ expectedVersion: identity.version,+ expectedBuildId: identity.buildId,+ expectedProfileId: PROFILE.id,+ listenerPids: processIdentity.listenerPids,+ expectedNode: nodeBin,+ expectedScript: DAEMON_SCRIPT,+ nodeProcesses: processIdentity.nodeProcesses,+ });+ return status;+}++async function readStatus() {+ const response = await httpGet(UI_PORT, '/api/status');+ if (!response) return null;+ if (response.status !== 200) throw new Error(`daemon 状态接口返回 ${response.status}`);+ try { return JSON.parse(response.body); } catch (_) { throw new Error('daemon 状态接口返回无效 JSON'); }+}++async function waitForExactDaemon(nodeBin, attempts) {+ for (let i = 0; i < attempts; i++) {+ await sleep(400);+ const status = await readStatus();+ const listeners = listenerPids(UI_PORT);+ if (!status && listeners.length === 0) continue;+ return exactDaemonStatus(nodeBin, status);}return null;}-// ---------- 1. 确保 daemon 运行 -----------function watchdogAlive() {- try {- const pid = parseInt(fs.readFileSync(path.join(DATA_DIR, 'watchdog.pid'), 'utf8').trim(), 10);- if (!pid) return false;- const r = spawnSync('tasklist', ['/FI', 'PID eq ' + pid, '/FO', 'CSV', '/NH'], { encoding: 'utf8', timeout: 5000, windowsHide: true });- return r.status === 0 && /node/i.test(r.stdout);- } catch (_) { return false; }+function killVerifiedNodeProcess(process, nodeBin, expectedScript) {+ const pid = Number(process.ProcessId);+ const rows = queryNodeProcesses([pid]);+ if (rows.length === 0) return false;+ const current = assertVerifiedNodeProcess(pid, nodeBin, expectedScript, rows);+ assertSameProcessIdentity(process, current);+ const result = spawnSync('taskkill', ['/F', '/PID', String(pid)], {+ stdio: 'ignore', windowsHide: true, timeout: 10000,+ });+ if (result.error || result.status !== 0) throw new Error(`无法结束已验证进程 PID=${pid}`);+ if (queryNodeProcesses([pid]).length !== 0) throw new Error(`已验证进程 PID=${pid} 未退出`);+ return true;+}++function authorizeDaemonTermination(nodeBin, status) {+ const processIdentity = validateDaemonProcess(nodeBin, status);+ return assertDaemonTerminationIdentity({+ status,+ expectedProfileId: PROFILE.id,+ listenerPids: processIdentity.listenerPids,+ expectedNode: nodeBin,+ expectedScript: DAEMON_SCRIPT,+ nodeProcesses: processIdentity.nodeProcesses,+ });}-function daemonRunning() {- return portOpen(UI_PORT);+function removeWatchdogPidIf(pid) {+ const current = readWatchdogPid();+ if (current === null) return;+ if (current !== pid) throw new Error('watchdog.pid 在清理前发生变化');+ fs.unlinkSync(WATCHDOG_PID_FILE);}-async function ensureDaemon(nodeBin) {- fs.mkdirSync(path.join(DATA_DIR, 'accounts'), { recursive: true });- // 已有 daemon:检查版本一致性(旧版本代码继续注入会出兼容问题)- const st = await httpGet(UI_PORT, '/api/status');- if (st && st.status === 200) {- let runningVer = '';- try { runningVer = (JSON.parse(st.body).version || ''); } catch (_) {}- const want = readDaemonVersion();- if (runningVer === want) {- log('daemon 已在运行且版本一致 (' + runningVer + '),跳过启动');- return true;+async function stopDaemonByPort(nodeBin) {+ const watchdog = watchdogState(nodeBin);+ if (watchdog.kind === 'untracked') {+ throw new Error('发现没有当前 profile PID 文件的 watchdog 进程,拒绝复用或结束');+ }+ if (watchdog.kind === 'stale') throw new Error('无法验证 watchdog.pid 指向的进程,拒绝删除 PID 文件');+ const listeners = listenerPids(UI_PORT);+ if (listeners.length > 1) throw new Error('daemon 监听 PID 不唯一');+ const daemon = uniqueNodeProcess(nodeBin, DAEMON_SCRIPT);+ let authorizedDaemon = null;+ if (daemon || listeners.length) {+ const status = await readStatus();+ if (!status || listeners.length !== 1) {+ throw new Error('daemon 未绑定当前 UI 端口与当前 profile 状态,拒绝结束');}- log('检测到旧版 daemon (' + runningVer + ' != ' + want + '),强制重启');- stopDaemonByPort();- } else if (watchdogAlive()) {- log('watchdog 在运行但 daemon 未就绪,等待其拉起...');- for (let i = 0; i < 20; i++) {- await sleep(500);- if (daemonRunning()) { log('daemon 已就绪'); return true; }+ authorizedDaemon = authorizeDaemonTermination(nodeBin, status);+ if (!daemon || daemon.ProcessId !== authorizedDaemon.ProcessId) {+ throw new Error('daemon 监听 PID 与枚举到的精确 daemon 进程不一致');+ }+ const identity = readDaemonIdentity();+ if (status.version === identity.version && status.buildId === identity.buildId) {+ throw new Error('daemon 版本与构建已匹配,拒绝结束当前实例');}- log('等待超时,主动拉起 watchdog');}- // 启动 watchdog(它负责启动 daemon + 崩溃拉起)- if (!watchdogAlive()) {- log('启动 watchdog: ' + nodeBin);- const child = spawn(nodeBin, [path.join(SCRIPTS_DIR, 'watchdog.js')], { detached: true, stdio: 'ignore', windowsHide: true });- child.unref();+ if (watchdog.kind === 'verified') {+ killVerifiedNodeProcess(watchdog.process, nodeBin, WATCHDOG_SCRIPT);+ removeWatchdogPidIf(watchdog.pid);}- for (let i = 0; i < 30; i++) {- await sleep(400);- if (daemonRunning()) { log('daemon 已就绪'); return true; }+ if (authorizedDaemon) killVerifiedNodeProcess(authorizedDaemon, nodeBin, DAEMON_SCRIPT);+ await sleep(300);+ // 终止窗口内出现的 daemon 没有独立的端口与 status 绑定证据,绝不自动结束。+ const remainingDaemon = uniqueNodeProcess(nodeBin, DAEMON_SCRIPT);+ if (remainingDaemon) {+ throw new Error('发现未绑定当前 profile 状态的新 daemon 进程,拒绝结束');+ }+ await sleep(300);+ if (uniqueNodeProcess(nodeBin, DAEMON_SCRIPT) || listenerPids(UI_PORT).length || await portOpen(UI_PORT)) {+ throw new Error('daemon 停止失败,端口仍被占用');}- log('等待 daemon 就绪超时');- return daemonRunning();}-function stopDaemonByPort() {- // 杀 watchdog(会连带杀 daemon)→ 兜底按端口杀- try {- const pid = parseInt(fs.readFileSync(path.join(DATA_DIR, 'watchdog.pid'), 'utf8').trim(), 10);- if (pid) spawnSync('taskkill', ['/F', '/T', '/PID', String(pid)], { stdio: 'ignore', windowsHide: true });- try { fs.unlinkSync(path.join(DATA_DIR, 'watchdog.pid')); } catch (_) {}- } catch (_) {}- // 兜底:杀监听 UI 端口的进程- const out = spawnSync('netstat', ['-ano'], { encoding: 'utf8', timeout: 8000, windowsHide: true }).stdout || '';- const lines = out.split(/\r?\n/).filter((l) => l.includes(':' + UI_PORT) && /LISTENING/i.test(l));- const pids = new Set();- for (const l of lines) {- const m = l.trim().split(/\s+/);- const pid = m[m.length - 1];- if (pid && /^\d+$/.test(pid)) pids.add(pid);+async function ensureDaemon(nodeBin) {+ fs.mkdirSync(path.join(DATA_DIR, 'accounts'), { recursive: true });+ const status = await readStatus();+ const listeners = listenerPids(UI_PORT);+ if (status || listeners.length) {+ authorizeDaemonTermination(nodeBin, status);+ const identity = readDaemonIdentity();+ if (status.version === identity.version && status.buildId === identity.buildId) {+ exactDaemonStatus(nodeBin, status);+ log('daemon 身份、版本、构建和权限均已验证,跳过启动');+ return true;+ }+ log('daemon 版本或构建不匹配,停止已绑定当前 profile 的旧进程');+ await stopDaemonByPort(nodeBin);+ }++ let watchdog = watchdogState(nodeBin);+ if (watchdog.kind === 'untracked') {+ throw new Error('发现没有当前 profile PID 文件的 watchdog 进程,拒绝复用或结束');}- for (const pid of pids) {- spawnSync('taskkill', ['/F', '/T', '/PID', pid], { stdio: 'ignore', windowsHide: true });+ if (watchdog.kind === 'verified') {+ const ready = await waitForExactDaemon(nodeBin, 20);+ if (ready) return true;+ await stopDaemonByPort(nodeBin);+ watchdog = { kind: 'absent', pid: null };}- return pids.size > 0;+ if (watchdog.kind === 'stale') throw new Error('无法验证 watchdog.pid 指向的进程,拒绝删除 PID 文件');+ const orphanDaemon = uniqueNodeProcess(nodeBin, DAEMON_SCRIPT);+ if (orphanDaemon) {+ throw new Error('发现未绑定当前 UI 端口与当前 profile 状态的 daemon 进程,拒绝结束或启动重复实例');+ }+ log('启动 watchdog: ' + nodeBin);+ const child = spawn(nodeBin, [WATCHDOG_SCRIPT], { detached: true, stdio: 'ignore', windowsHide: true });+ child.unref();+ if (await waitForExactDaemon(nodeBin, 30)) {+ log('daemon 已通过完整身份校验');+ return true;+ }+ throw new Error('等待 daemon 完整身份校验超时');}// ---------- 2/3. WorkBuddy CDP 处理 ----------function workBuddyRunning(binary = null) {- const processes = workBuddyProcesses(binary);- if (processes.length) return true;- if (binary) {- // CIM 能看到同族进程但路径明确属于另一个安装目录时,不应把它当成当前客户端仍在运行。- // 路径未知则保守认为仍在运行,后续 tasklist/PID 回退会尝试结束并写出诊断。- const unknownPath = getWorkBuddyProcesses().some((p) =>- PROFILE_PROCESS_NAMES.has(String(p.Name || '').toLowerCase()) && !p.ExecutablePath- );- if (!unknownPath) return false;- }- // CIM 失败时保守回退到 tasklist,避免误判为已退出后把启动参数交给旧实例。- try {- const names = binary ? targetProcessNames(binary) : PROFILE_PROCESS_NAMES;- const filters = Array.from(names).map((name) =>- spawnSync('tasklist', ['/FI', 'IMAGENAME eq ' + name, '/FO', 'CSV', '/NH'], {- encoding: 'utf8', timeout: 5000, windowsHide: true,- })- );- return filters.some((r) => r.status === 0 && names.has(- String(r.stdout || '').match(/"([^"]+\.exe)"/i)?.[1]?.toLowerCase() || ''- ));- } catch (_) {- return true;- }+ return workBuddyProcesses(binary).length > 0;}function runTaskkill(args) {@@ -632,29 +700,6 @@ function runTaskkill(args) {});}-function runElevatedTaskkillPids(pids) {- const clean = Array.from(new Set(pids.map((pid) => String(pid)).filter((pid) => /^\d+$/.test(pid))));- if (!clean.length) return { code: 0, error: null };- const args = ['/F', '/T'];- for (const pid of clean) args.push('/PID', pid);- const command = [- '$p = Start-Process -FilePath ' + psQuote('taskkill.exe') +- ' -ArgumentList @(' + args.map(psQuote).join(', ') + ') -Verb RunAs -WindowStyle Hidden -Wait -PassThru',- 'exit $p.ExitCode',- ].join('; ');- try {- const result = spawnSync('powershell', [- '-NoProfile', '-ExecutionPolicy', 'Bypass', '-Command', command,- ], { encoding: 'utf8', windowsHide: true, timeout: 30000, stdio: 'ignore' });- return {- code: result.status,- error: result.error ? result.error.message : null,- };- } catch (e) {- return { code: null, error: e.message };- }-}-async function waitForWorkBuddyExit(timeoutMs, binary = null) {const deadline = Date.now() + timeoutMs;while (Date.now() < deadline) {@@ -668,7 +713,7 @@ function exitSnapshot(binary = null) {return {binary: binary ? path.basename(binary) : null,processes: processDiagnostics(binary),- tasklistPids: Array.from(tasklistProcessIds(targetProcessNames(binary))),+ unverifiedTasklistPids: Array.from(tasklistProcessIds()),};}@@ -676,108 +721,62 @@ async function killForExit(args, stage) {const result = await runTaskkill(args);const error = result.error ? result.error.message : '';log(`[exit] ${stage} taskkill=${args.join(' ')} code=${result.code == null ? 'null' : result.code}${error ? ' error=' + error : ''}`);+ if (result.error || result.code !== 0) {+ throw result.error || new Error(`${stage} taskkill 失败 (code=${result.code})`);+ }return result;}+async function killVerifiedWorkBuddyProcess(binary, process, force, stage) {+ const pid = Number(process.ProcessId);+ const current = workBuddyProcesses(binary).find((item) => Number(item.ProcessId) === pid);+ if (!current) return false;+ assertSameProcessIdentity(process, current);+ await killForExit([...(force ? ['/F'] : []), '/PID', String(pid)], stage);+ return true;+}+async function quitWorkBuddy(binary) {const initial = workBuddyProcesses(binary);- const targetNames = targetProcessNames(binary);if (!initial.length && !workBuddyRunning(binary)) return true;+ if (!initial.length) {+ throw new Error(`${PROFILE.name} 正在运行,但无法验证其绝对可执行路径;为避免误杀,已停止重启`);+ }+log(`[exit] 开始确认退出 profile=${PROFILE.id} snapshot=${JSON.stringify(exitSnapshot(binary))}`);- // 按实际 PID 精确结束安装目录中的进程树;CIM 不可用时退回 tasklist,避免- // “检测到仍在运行但没有 PID”导致无条件等待后上报无法退出。- const pids = new Set(initial.map((p) => String(Number(p.ProcessId))).filter((pid) => pid !== '0'));- if (!pids.size) for (const pid of tasklistProcessIds(targetNames)) pids.add(pid);- for (const pid of pids) {- await killForExit(['/T', '/PID', pid], '优雅结束进程树');+ // 按实际 PID 精确结束安装目录中的进程树:每个成员都先经 CIM 路径验证,+ // 再逐 PID 结束,不按镜像名或未验证 PID 兜底。+ for (const process of initial) {+ await killVerifiedWorkBuddyProcess(binary, process, false, '结束已验证进程');}if (await waitForWorkBuddyExit(2500, binary)) {log(`[exit] 已确认退出 profile=${PROFILE.id} snapshot=${JSON.stringify(exitSnapshot(binary))}`);return true;}- // 单实例宿主可能在第一次 taskkill 后重新生成辅助进程;刷新 PID 集合再强杀两轮。+ // 单实例宿主可能在第一次 taskkill 后重新生成辅助进程;刷新并重新验证 PID 后强杀两轮。for (let round = 1; round <= 2; round++) {- const current = new Set(workBuddyProcesses(binary).map((p) => String(Number(p.ProcessId))).filter((pid) => pid !== '0'));- if (!current.size) for (const pid of tasklistProcessIds(targetNames)) current.add(pid);+ const current = workBuddyProcesses(binary);log(`[exit] 强制结束第 ${round} 轮 snapshot=${JSON.stringify(exitSnapshot(binary))}`);- for (const pid of current) await killForExit(['/F', '/T', '/PID', pid], `强制结束第${round}轮`);+ for (const process of current) {+ await killVerifiedWorkBuddyProcess(binary, process, true, `强制结束第${round}轮`);+ }if (await waitForWorkBuddyExit(2500, binary)) {log(`[exit] 强制结束后已确认退出 profile=${PROFILE.id} snapshot=${JSON.stringify(exitSnapshot(binary))}`);return true;}}- // CIM 无法返回 PID 时按 PR#8 的两个精确镜像名兜底;最终结果仍必须经过检测确认。- for (const name of targetNames) await killForExit(['/F', '/T', '/IM', name], '镜像名兜底');- if (await waitForWorkBuddyExit(5000, binary)) {- log(`[exit] 镜像名兜底后已确认退出 profile=${PROFILE.id} snapshot=${JSON.stringify(exitSnapshot(binary))}`);- return true;- }- // 进程路径/CIM 信息缺失时,普通 taskkill 可能因旧 WorkBuddy 以管理员权限运行而失败。- // 最后只对已确认属于目标镜像的剩余 PID 请求一次 UAC,避免按名称误杀其他客户端。- const beforeElevated = exitSnapshot(binary);- const remainingPids = new Set([- ...beforeElevated.tasklistPids,- ...beforeElevated.processes.map((p) => p.pid).filter(Boolean),- ]);- if (remainingPids.size) {- const elevated = runElevatedTaskkillPids(Array.from(remainingPids));- log(`[exit] 提权 PID 兜底 taskkill=${Array.from(remainingPids).join(',')} code=${elevated.code == null ? 'null' : elevated.code}${elevated.error ? ' error=' + elevated.error : ''}`);- if (await waitForWorkBuddyExit(10000, binary)) {- log(`[exit] 提权 PID 兜底后已确认退出 profile=${PROFILE.id} snapshot=${JSON.stringify(exitSnapshot(binary))}`);- return true;- }- }const final = exitSnapshot(binary);log(`[exit] 无法确认退出 profile=${PROFILE.id} final=${JSON.stringify(final)}`);const names = final.processes.map((p) => p.name).filter(Boolean).join(',') || 'unknown';- const pidsLeft = final.processes.map((p) => p.pid).filter(Boolean).join(',') || final.tasklistPids.join(',') || 'unknown';- throw new Error(`${PROFILE.name} 无法确认已退出(剩余镜像=${names}; PID=${pidsLeft})`);-}--function psQuote(value) {- return "'" + String(value).replace(/'/g, "''") + "'";+ const pidsLeft = final.processes.map((p) => p.pid).filter(Boolean).join(',') || 'unknown';+ throw new Error(`${PROFILE.name} 无法以普通用户权限安全退出(剩余镜像=${names}; PID=${pidsLeft})。请手动关闭该程序;若它以管理员身份运行,请先退出后再重试`);}-/**- * 从管理员 launcher 启动 WorkBuddy 时,不能直接 spawn 子进程:Electron/Chromium- * 在部分 Windows 环境以高完整性令牌启动会出现白屏。通过 Explorer 的 ShellExecute- * 让桌面 shell 以当前用户令牌创建 GUI 进程;普通权限 launcher 仍走同一条路径。- */function launchWorkBuddy(wb) {const args = '--remote-debugging-port=' + CDP_PORT;- if (isElevated()) {- const command = [- '$shell = New-Object -ComObject Shell.Application',- '$shell.ShellExecute(' + [- psQuote(wb),- psQuote(args),- psQuote(path.dirname(wb)),- "'open'",- '1',- ].join(', ') + ')',- ].join('; ');- const result = spawnSync(- 'powershell',- ['-NoProfile', '-ExecutionPolicy', 'Bypass', '-Command', command],- { stdio: 'ignore', windowsHide: true, timeout: 15000 }- );- if (result.status === 0) {- log('WorkBuddy 已通过 Explorer ShellExecute 以当前用户权限启动');- return { method: 'shell-execute' };- }- log('ShellExecute 启动 WorkBuddy 失败,改用 explorer.exe 兜底 (code=' + result.status + ')');- try {- const shell = spawn('explorer.exe', [wb, args], { detached: true, stdio: 'ignore', windowsHide: true });- shell.unref();- return { method: 'explorer-fallback' };- } catch (e) {- log('explorer.exe 启动 WorkBuddy 失败: ' + e.message);- }- }-const child = spawn(wb, [args], {cwd: path.dirname(wb), detached: true, stdio: 'ignore', windowsHide: true,});@@ -889,13 +888,6 @@ if (require.main === module) (async () => {}await configureCdpPort();- // 提权助手接管时,先停掉普通权限启动的 watchdog/daemon,避免两个权限级别的- // daemon 同时占用端口;WorkBuddy GUI 后续仍由 ShellExecute 以用户权限启动。- if (ELEVATED_HELPER_MODE) {- log('提权流程:接管普通权限 daemon');- stopDaemonByPort();- await sleep(800);- }await ensureDaemon(nodeBin);// 已在 CDP 模式 → 幂等注入@@ -915,23 +907,11 @@ if (require.main === module) (async () => {return;}- // WorkBuddy 常装在 C:\Program Files(受保护特权目录),结束已提升的旧进程可能需要管理员权限。- // 若当前非管理员:派发提权助手(触发一次 UAC)后立即退出,由助手完成重启+注入,- // 避免普通双击时卡在黑屏空转等 20 秒。- if (!isElevated()) {- log('非管理员权限:派发提权助手重启 WorkBuddy(唤醒 UAC)');- console.log('需要管理员权限以重启 WorkBuddy 进入调试模式,正在请求授权...');- if (spawnElevatedHelper()) {- console.log('已发起提权请求,点击 UAC「是」后将自动完成重启与注入。');- process.exit(0);- }- // 派发失败则仍退回当前进程尝试(容错)- log('提权派发失败,退回当前进程直接重启');- }-log('重启 WorkBuddy(带 --remote-debugging-port=' + CDP_PORT + ',GUI 使用当前用户权限): ' + wb);console.log('正在以调试模式重启 WorkBuddy(约几秒)...');+ // 只在当前普通权限上下文中结束经过绝对路径验证的 PID。若目标以更高完整性+ // 运行或 CIM 无法证明路径,quitWorkBuddy 会 fail closed,不再执行用户可写的 UAC 脚本。await quitWorkBuddy(wb);await sleep(1000);const ok = await waitForWorkBuddyCdp(wb);@@ -957,12 +937,7 @@ if (require.main === module) (async () => {module.exports = {getWorkBuddyProcesses,- getWorkBuddyProcessesViaCim,- getWorkBuddyProcessesViaTasklist,- parseTasklistOutput,workBuddyProcesses,tasklistProcessIds,- targetProcessNames,workBuddyRunning,- isElevated,};diff --git a/scripts/windows-process-boundary.js b/scripts/windows-process-boundary.jsnew file mode 100644index 0000000..274ca5d--- /dev/null+++ b/scripts/windows-process-boundary.js@@ -0,0 +1,296 @@+'use strict';++const fs = require('fs');+const path = require('path');+const { spawnSync } = require('child_process');++const ALLOWED_WORKBUDDY_PROCESS_NAMES = new Set([+ 'workbuddy.exe',+ 'workbuddyai.exe',+ 'codebuddy.exe',+]);++function assertStandardWindowsPrivilege(run = spawnSync) {+ const command = "([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)";+ let result;+ try {+ result = run('powershell', ['-NoProfile', '-Command', command], {+ encoding: 'utf8', windowsHide: true, timeout: 8000,+ });+ } catch (error) {+ throw new Error(`无法确认 Windows 进程权限: ${error.message}`);+ }+ if (!result || result.error) {+ throw (result && result.error) || new Error('无法确认 Windows 进程权限');+ }+ if (result.status !== 0) {+ const detail = String(result.stderr || '').trim();+ throw new Error(`无法确认 Windows 进程权限${detail ? ': ' + detail : ''}`);+ }+ const value = String(result.stdout || '').trim().toLowerCase();+ if (value === 'false') return 'standard';+ if (value === 'true') throw new Error('拒绝以管理员或 elevated 权限运行 WorkDaddy');+ throw new Error('无法确认 Windows 进程是否为普通用户权限');+}++function validateProcessRecord(row, options = {}) {+ if (!row || typeof row !== 'object' || Array.isArray(row)) {+ throw new Error('CIM process query returned an invalid process record');+ }+ const pid = row.ProcessId;+ if (!Number.isSafeInteger(pid) || pid <= 0) throw new Error('CIM process record has an invalid PID');+ const name = typeof row.Name === 'string' ? row.Name.trim() : '';+ if (!name) throw new Error(`CIM process record ${pid} has no Name`);+ const executable = typeof row.ExecutablePath === 'string' ? row.ExecutablePath.trim() : '';+ if (!executable || !path.win32.isAbsolute(executable)) {+ throw new Error(`CIM process record ${pid} has no absolute executable path`);+ }+ if (options.requireCommandLine && (typeof row.CommandLine !== 'string' || !row.CommandLine.trim())) {+ throw new Error(`CIM process record ${pid} has no command line`);+ }+ let nativeArguments;+ if (options.requireNativeArguments) {+ if (row.ArgumentsSource !== 'CommandLineToArgvW' || !Array.isArray(row.Arguments) || !row.Arguments.length) {+ throw new Error(`CIM process record ${pid} has no trusted native Arguments`);+ }+ if (row.Arguments.some((argument) => typeof argument !== 'string' || argument.includes('\0'))) {+ throw new Error(`CIM process record ${pid} has invalid native Arguments`);+ }+ nativeArguments = [...row.Arguments];+ }+ const owner = typeof row.Owner === 'string' ? row.Owner.trim() : '';+ if (options.requireCurrentOwner) {+ if (!owner) throw new Error(`CIM process record ${pid} has no owner`);+ if (row.OwnerIsCurrent !== true) {+ throw new Error(`CIM process record ${pid} is not owned by the current user`);+ }+ }+ return {+ ...row,+ ProcessId: pid,+ Name: name,+ ExecutablePath: executable,+ ...(owner ? { Owner: owner } : {}),+ ...(nativeArguments ? { Arguments: nativeArguments } : {}),+ };+}++function parseCimProcessResult(result, options = {}) {+ if (!result || result.error) {+ throw (result && result.error) || new Error('CIM process query did not return a result');+ }+ if (result.status !== 0) {+ const detail = String(result.stderr || '').trim();+ throw new Error(`CIM process query exited with status ${result.status}${detail ? ': ' + detail : ''}`);+ }+ const output = String(result.stdout || '').trim();+ if (!output) return [];+ let parsed;+ try {+ parsed = JSON.parse(output);+ } catch (error) {+ throw new Error(`CIM process query returned invalid JSON: ${error.message}`);+ }+ const rows = Array.isArray(parsed) ? parsed : [parsed];+ return rows.map((row) => validateProcessRecord(row, options));+}++function resolveWindowsExecutable(value, realpath = fs.realpathSync.native) {+ const candidate = String(value || '').trim();+ if (!candidate || !path.win32.isAbsolute(candidate)) {+ throw new Error('Windows executable path must be absolute');+ }+ const resolved = String(realpath(candidate) || '').trim();+ if (!resolved || !path.win32.isAbsolute(resolved)) {+ throw new Error('Windows executable path could not be resolved');+ }+ return path.win32.normalize(resolved);+}++function sameWindowsPath(a, b) {+ return path.win32.normalize(String(a)).replace(/[\\/]+$/, '').toLowerCase() ===+ path.win32.normalize(String(b)).replace(/[\\/]+$/, '').toLowerCase();+}++function resolveWindowsCommandToken(value, realpath = fs.realpathSync.native) {+ if (typeof value !== 'string' || !value || value !== value.trim() || /[\r\n\0]/.test(value)) {+ throw new Error('Windows command token path contains leading, trailing, or control whitespace');+ }+ return resolveWindowsExecutable(value, realpath);+}++function buildNativeProcessQuery(helperPath, processSource) {+ const helper = String(helperPath || '');+ const source = String(processSource || '');+ if (!path.win32.isAbsolute(helper) || /[\r\n\0]/.test(helper) || !source.trim()) {+ throw new Error('Native process query requires a trusted absolute helper and source');+ }+ const quotedHelper = helper.replace(/'/g, "''");+ return `. '${quotedHelper}'; ${source} | ForEach-Object { ConvertTo-WorkDaddyProcessRecord -Process $_ } | ConvertTo-Json -Compress -Depth 4`;+}++function sameWindowsFilePath(a, b) {+ return path.win32.normalize(String(a)).toLowerCase() ===+ path.win32.normalize(String(b)).toLowerCase();+}++function assertSameProcessIdentity(original, current) {+ const requirements = { requireCommandLine: true, requireCurrentOwner: true, requireNativeArguments: true };+ const before = validateProcessRecord(original, requirements);+ const after = validateProcessRecord(current, requirements);+ if (before.ProcessId !== after.ProcessId ||+ before.Name.toLowerCase() !== after.Name.toLowerCase() ||+ !sameWindowsPath(before.ExecutablePath, after.ExecutablePath) ||+ before.CommandLine !== after.CommandLine ||+ before.Arguments.length !== after.Arguments.length ||+ before.Arguments.some((argument, index) => argument !== after.Arguments[index]) ||+ before.Owner.toLowerCase() !== after.Owner.toLowerCase()) {+ throw new Error(`Process identity or owner changed before termination for PID ${before.ProcessId}`);+ }+ return after;+}++function filterVerifiedWindowsProcesses(expectedBinary, processes, realpath = fs.realpathSync.native) {+ const expected = resolveWindowsExecutable(expectedBinary, realpath);+ const expectedDir = path.win32.dirname(expected);+ const expectedName = path.win32.basename(expected).toLowerCase();+ if (!ALLOWED_WORKBUDDY_PROCESS_NAMES.has(expectedName)) {+ throw new Error('Expected executable is not a WorkBuddy-family binary');+ }+ const verified = [];+ for (const item of Array.isArray(processes) ? processes : []) {+ const process = validateProcessRecord(item);+ const name = process.Name.toLowerCase();+ if (name !== expectedName) continue;+ let executable;+ try {+ executable = resolveWindowsExecutable(process.ExecutablePath, realpath);+ } catch (_) {+ throw new Error(`Cannot verify executable path for PID ${process.ProcessId}`);+ }+ if (path.win32.basename(executable).toLowerCase() !== name) {+ throw new Error(`Executable name does not match CIM Name for PID ${process.ProcessId}`);+ }+ if (!sameWindowsPath(path.win32.dirname(executable), expectedDir)) continue;+ verified.push({ ...process, ExecutablePath: executable });+ }+ return verified;+}++function selectVerifiedProcessPids(expectedBinary, processes, realpath = fs.realpathSync.native) {+ return filterVerifiedWindowsProcesses(expectedBinary, processes, realpath)+ .map((process) => process.ProcessId);+}++function selectRunningProfileBinary(profileNames, processes, realpath = fs.realpathSync.native) {+ const names = profileNames instanceof Set ? profileNames : new Set(profileNames || []);+ const binaries = new Map();+ for (const item of Array.isArray(processes) ? processes : []) {+ const process = validateProcessRecord(item);+ const name = process.Name.toLowerCase();+ if (!names.has(name)) continue;+ const executable = resolveWindowsExecutable(process.ExecutablePath, realpath);+ if (path.win32.basename(executable).toLowerCase() !== name) {+ throw new Error(`Executable name does not match CIM Name for PID ${process.ProcessId}`);+ }+ binaries.set(executable.toLowerCase(), executable);+ }+ if (binaries.size > 1) throw new Error('检测到当前 profile 在多个安装目录运行,无法安全选择目标');+ return binaries.size ? Array.from(binaries.values())[0] : null;+}++function selectUniqueDiscoveredBinary(profileNames, candidates, realpath = fs.realpathSync.native) {+ const names = profileNames instanceof Set ? profileNames : new Set(profileNames || []);+ const binaries = new Map();+ for (const candidate of Array.isArray(candidates) ? candidates : []) {+ const executable = resolveWindowsExecutable(candidate, realpath);+ if (!names.has(path.win32.basename(executable).toLowerCase())) continue;+ binaries.set(executable.toLowerCase(), executable);+ }+ if (binaries.size > 1) {+ throw new Error('检测到当前 profile 的多个安装目录;请用 WBSWITCH_WORKBUDDY_BIN 明确指定目标');+ }+ return binaries.size ? Array.from(binaries.values())[0] : null;+}++function filterVerifiedNodeProcesses(expectedNode, expectedScript, processes, realpath = fs.realpathSync.native) {+ const node = resolveWindowsExecutable(expectedNode, realpath);+ const script = resolveWindowsExecutable(expectedScript, realpath);+ const verified = [];+ for (const item of Array.isArray(processes) ? processes : []) {+ const process = validateProcessRecord(item, { requireCommandLine: true, requireNativeArguments: true });+ if (process.Name.toLowerCase() !== 'node.exe') continue;+ const executable = resolveWindowsExecutable(process.ExecutablePath, realpath);+ if (!sameWindowsFilePath(executable, node)) continue;+ const args = process.Arguments;+ let entryIndex = 1;+ let commandNodeMatches = false;+ try {+ commandNodeMatches = args.length > 0 && path.win32.isAbsolute(args[0]) &&+ sameWindowsFilePath(resolveWindowsCommandToken(args[0], realpath), node);+ } catch (_) {}+ if (!commandNodeMatches) continue;+ if (args[entryIndex] === '--experimental-sqlite') entryIndex++;+ const entry = args[entryIndex];+ let scriptMatch = false;+ if (entry && path.win32.isAbsolute(entry)) {+ try { scriptMatch = sameWindowsFilePath(resolveWindowsCommandToken(entry, realpath), script); } catch (_) {}+ }+ if (scriptMatch && args.length === entryIndex + 1) {+ verified.push({ ...process, ExecutablePath: executable });+ }+ }+ return verified;+}++function assertVerifiedNodeProcess(pid, expectedNode, expectedScript, processes, realpath = fs.realpathSync.native) {+ const numericPid = Number(pid);+ if (!Number.isSafeInteger(numericPid) || numericPid <= 0) throw new Error('Invalid process PID');+ const match = filterVerifiedNodeProcesses(expectedNode, expectedScript, processes, realpath)+ .find((process) => process.ProcessId === numericPid);+ if (!match) throw new Error(`Cannot verify node process identity for PID ${numericPid}`);+ return match;+}++function assertDaemonTerminationIdentity(options) {+ const status = options && options.status;+ if (!status || typeof status !== 'object') throw new Error('daemon status is missing');+ const profileId = status.profile && status.profile.id;+ if (profileId !== options.expectedProfileId) throw new Error('daemon profile mismatch');+ if (status.privilege !== 'standard') throw new Error('daemon privilege is not standard');+ const pid = status.pid;+ if (!Number.isSafeInteger(pid) || pid <= 0) throw new Error('daemon status PID is invalid');+ const listenerPids = Array.from(new Set((options.listenerPids || []).map(Number)));+ if (listenerPids.length !== 1 || listenerPids[0] !== pid) {+ throw new Error('daemon listener PID does not match status PID');+ }+ return assertVerifiedNodeProcess(+ pid, options.expectedNode, options.expectedScript, options.nodeProcesses, options.realpath+ );+}++function assertDaemonServiceIdentity(options) {+ const process = assertDaemonTerminationIdentity(options);+ const status = options.status;+ if (status.version !== options.expectedVersion) throw new Error('daemon version mismatch');+ if (status.buildId !== options.expectedBuildId) throw new Error('daemon buildId mismatch');+ return process;+}++module.exports = {+ ALLOWED_WORKBUDDY_PROCESS_NAMES,+ assertDaemonServiceIdentity,+ assertDaemonTerminationIdentity,+ assertSameProcessIdentity,+ assertStandardWindowsPrivilege,+ assertVerifiedNodeProcess,+ buildNativeProcessQuery,+ filterVerifiedNodeProcesses,+ filterVerifiedWindowsProcesses,+ parseCimProcessResult,+ resolveWindowsExecutable,+ sameWindowsPath,+ selectRunningProfileBinary,+ selectUniqueDiscoveredBinary,+ selectVerifiedProcessPids,+};diff --git a/scripts/windows-process-boundary.ps1 b/scripts/windows-process-boundary.ps1new file mode 100644index 0000000..2f969d8--- /dev/null+++ b/scripts/windows-process-boundary.ps1@@ -0,0 +1,442 @@+function ConvertTo-WindowsCommandLineArgs {+ param([Parameter(Mandatory = $true)][string]$CommandLine)+ if (-not ('WorkDaddyCommandLineParser' -as [type])) {+ Add-Type -TypeDefinition @'+using System;+using System.Runtime.InteropServices;++public static class WorkDaddyCommandLineParser {+ [DllImport("shell32.dll", SetLastError = true)]+ private static extern IntPtr CommandLineToArgvW(+ [MarshalAs(UnmanagedType.LPWStr)] string commandLine,+ out int argc);++ [DllImport("kernel32.dll")]+ private static extern IntPtr LocalFree(IntPtr memory);++ public static string[] Parse(string commandLine) {+ int argc;+ IntPtr argv = CommandLineToArgvW(commandLine, out argc);+ if (argv == IntPtr.Zero) throw new System.ComponentModel.Win32Exception();+ try {+ string[] result = new string[argc];+ for (int index = 0; index < argc; index++) {+ IntPtr item = Marshal.ReadIntPtr(argv, index * IntPtr.Size);+ result[index] = Marshal.PtrToStringUni(item);+ }+ return result;+ } finally {+ LocalFree(argv);+ }+ }+}+'@+ }+ return [WorkDaddyCommandLineParser]::Parse($CommandLine)+}++function Resolve-StrictWindowsPath {+ param(+ [Parameter(Mandatory = $true)][string]$Path,+ [scriptblock]$PathResolver+ )+ if ([string]::IsNullOrWhiteSpace($Path) -or -not [IO.Path]::IsPathRooted($Path)) {+ throw "路径不是绝对路径: $Path"+ }+ $resolved = if ($PathResolver) {+ & $PathResolver $Path+ } else {+ (Resolve-Path -LiteralPath $Path -ErrorAction Stop).ProviderPath+ }+ if ([string]::IsNullOrWhiteSpace([string]$resolved) -or -not [IO.Path]::IsPathRooted([string]$resolved)) {+ throw "无法解析绝对路径: $Path"+ }+ return [IO.Path]::GetFullPath([string]$resolved).TrimEnd('\', '/')+}++function Test-SameWindowsPath {+ param(+ [Parameter(Mandatory = $true)][string]$Left,+ [Parameter(Mandatory = $true)][string]$Right,+ [scriptblock]$PathResolver+ )+ try {+ $leftPath = Resolve-StrictWindowsPath -Path $Left -PathResolver $PathResolver+ $rightPath = Resolve-StrictWindowsPath -Path $Right -PathResolver $PathResolver+ return [StringComparer]::OrdinalIgnoreCase.Equals($leftPath, $rightPath)+ } catch {+ return $false+ }+}++function Test-StrictCommandTokenPath {+ param(+ [Parameter(Mandatory = $true)][string]$Token,+ [Parameter(Mandatory = $true)][string]$ExpectedPath,+ [scriptblock]$PathResolver+ )+ if ([string]::IsNullOrEmpty($Token) -or $Token -cne $Token.Trim() -or+ $Token.IndexOfAny([char[]]@([char]0, [char]10, [char]13)) -ge 0) { return $false }+ return Test-SameWindowsPath -Left $Token -Right $ExpectedPath -PathResolver $PathResolver+}++function ConvertTo-WorkDaddyProcessRecord {+ param([Parameter(Mandatory = $true)]$Process)+ $processId = 0+ if (-not [int]::TryParse([string]$Process.ProcessId, [ref]$processId) -or $processId -le 0 -or+ [string]::IsNullOrWhiteSpace([string]$Process.Name) -or+ [string]::IsNullOrWhiteSpace([string]$Process.ExecutablePath) -or+ [string]::IsNullOrWhiteSpace([string]$Process.CommandLine)) { throw 'CIM 进程身份字段不完整' }+ $ownerResult = Invoke-CimMethod -InputObject $Process -MethodName GetOwner -ErrorAction Stop+ if ($ownerResult.ReturnValue -ne 0 -or [string]::IsNullOrWhiteSpace([string]$ownerResult.User)) {+ throw "无法确认 PID $processId 的进程所有者"+ }+ $owner = if ([string]::IsNullOrWhiteSpace([string]$ownerResult.Domain)) {+ [string]$ownerResult.User+ } else { ([string]$ownerResult.Domain + '\' + [string]$ownerResult.User) }+ $arguments = [string[]]@(ConvertTo-WindowsCommandLineArgs -CommandLine ([string]$Process.CommandLine))+ if ($arguments.Count -eq 0 -or @($arguments | Where-Object { $null -eq $_ }).Count -ne 0) {+ throw "PID $processId 的原生 Arguments 无效"+ }+ $currentOwner = [Security.Principal.WindowsIdentity]::GetCurrent().Name+ return [pscustomobject]@{+ ProcessId = $processId+ ParentProcessId = [int]$Process.ParentProcessId+ Name = [string]$Process.Name+ ExecutablePath = Resolve-StrictWindowsPath -Path ([string]$Process.ExecutablePath)+ CommandLine = [string]$Process.CommandLine+ ArgumentsSource = 'CommandLineToArgvW'+ Arguments = $arguments+ Owner = $owner+ OwnerIsCurrent = [StringComparer]::OrdinalIgnoreCase.Equals($owner, $currentOwner)+ }+}++function Test-ExactNodeEntryCommandLine {+ param(+ [Parameter(Mandatory = $true)][string]$CommandLine,+ [Parameter(Mandatory = $true)][string]$ExpectedScript,+ [string]$ExpectedNode = '',+ [scriptblock]$PathResolver+ )+ try {+ $arguments = @(ConvertTo-WindowsCommandLineArgs -CommandLine $CommandLine)+ if ($arguments.Count -lt 2) { return $false }+ if (-not [string]::IsNullOrWhiteSpace($ExpectedNode) -and+ -not (Test-StrictCommandTokenPath -Token $arguments[0] -ExpectedPath $ExpectedNode -PathResolver $PathResolver)) {+ return $false+ }+ $entryIndex = 1+ if ($arguments[$entryIndex] -ceq '--experimental-sqlite') { $entryIndex++ }+ if ($entryIndex -ge $arguments.Count) { return $false }+ if ($arguments.Count -ne ($entryIndex + 1)) { return $false }+ return Test-StrictCommandTokenPath -Token $arguments[$entryIndex] -ExpectedPath $ExpectedScript -PathResolver $PathResolver+ } catch {+ return $false+ }+}++function Test-ExactCmdLauncherCommandLine {+ param(+ [Parameter(Mandatory = $true)][string]$CommandLine,+ [Parameter(Mandatory = $true)][string]$ExpectedLauncher,+ [string]$ExpectedCmd = '',+ [scriptblock]$PathResolver+ )+ try {+ $arguments = @(ConvertTo-WindowsCommandLineArgs -CommandLine $CommandLine)+ if ($arguments.Count -lt 1 -or+ (-not [string]::IsNullOrWhiteSpace($ExpectedCmd) -and+ -not (Test-StrictCommandTokenPath -Token $arguments[0] -ExpectedPath $ExpectedCmd -PathResolver $PathResolver))) {+ return $false+ }+ if ($arguments.Count -eq 5 -and+ $arguments[1] -ieq '/d' -and $arguments[2] -ieq '/c' -and+ $arguments[3] -ieq 'call') {+ return Test-StrictCommandTokenPath -Token $arguments[4] -ExpectedPath $ExpectedLauncher -PathResolver $PathResolver+ }+ if ($arguments.Count -eq 3 -and $arguments[1] -ieq '/c') {+ return Test-StrictCommandTokenPath -Token $arguments[2] -ExpectedPath $ExpectedLauncher -PathResolver $PathResolver+ }+ return $false+ } catch {+ return $false+ }+}++function Get-StrictProcessRecord {+ param([Parameter(Mandatory = $true)][int]$ProcessId)+ if ($ProcessId -le 0) { throw "无效 PID: $ProcessId" }+ $rows = @(Get-CimInstance Win32_Process -Filter ("ProcessId = {0}" -f $ProcessId) -ErrorAction Stop)+ if ($rows.Count -eq 0) { return $null }+ if ($rows.Count -ne 1) { throw "PID $ProcessId 的 CIM 记录不唯一" }+ $record = ConvertTo-WorkDaddyProcessRecord -Process $rows[0]+ if ([int]$record.ProcessId -ne $ProcessId) { throw "PID $ProcessId 的 CIM 记录不匹配" }+ return $record+}++function Assert-SameProcessOwner {+ param([Parameter(Mandatory = $true)]$Process)+ $currentOwner = [Security.Principal.WindowsIdentity]::GetCurrent().Name+ if (-not [StringComparer]::OrdinalIgnoreCase.Equals([string]$Process.Owner, $currentOwner)) {+ throw "PID $($Process.ProcessId) 不属于当前用户"+ }+}++function Assert-NodeProcessIdentity {+ param(+ [Parameter(Mandatory = $true)]$Process,+ [Parameter(Mandatory = $true)][int]$ExpectedPid,+ [Parameter(Mandatory = $true)][string]$ExpectedScript+ )+ if ([int]$Process.ProcessId -ne $ExpectedPid -or [string]$Process.Name -ine 'node.exe') {+ throw "PID $ExpectedPid 不是目标 Node 进程"+ }+ Assert-SameProcessOwner -Process $Process+ $executable = Resolve-StrictWindowsPath -Path ([string]$Process.ExecutablePath)+ if ([IO.Path]::GetFileName($executable) -ine 'node.exe') {+ throw "PID $ExpectedPid 的可执行文件不是 node.exe"+ }+ if (-not (Test-ExactNodeEntryCommandLine -CommandLine ([string]$Process.CommandLine) -ExpectedScript $ExpectedScript -ExpectedNode $executable)) {+ throw "PID $ExpectedPid 的 Node 入口脚本不匹配"+ }+ return $Process+}++function Assert-CmdLauncherIdentity {+ param(+ [Parameter(Mandatory = $true)]$Process,+ [Parameter(Mandatory = $true)][string]$ExpectedLauncher+ )+ if ([string]$Process.Name -ine 'cmd.exe') { throw "PID $($Process.ProcessId) 不是 cmd.exe" }+ Assert-SameProcessOwner -Process $Process+ $systemCmd = Join-Path ([Environment]::SystemDirectory) 'cmd.exe'+ if (-not (Test-SameWindowsPath -Left ([string]$Process.ExecutablePath) -Right $systemCmd)) {+ throw "PID $($Process.ProcessId) 的 cmd.exe 路径不匹配"+ }+ if (-not (Test-ExactCmdLauncherCommandLine -CommandLine ([string]$Process.CommandLine) -ExpectedLauncher $ExpectedLauncher -ExpectedCmd $systemCmd)) {+ throw "PID $($Process.ProcessId) 的 launcher.cmd 入口不匹配"+ }+ return $Process+}++function Get-UniqueNodeProcessForScript {+ param([Parameter(Mandatory = $true)][string]$ExpectedScript)+ $matches = @()+ $rows = @(Get-CimInstance Win32_Process -Filter "Name = 'node.exe'" -ErrorAction Stop)+ foreach ($row in $rows) {+ if ([string]$row.Name -ine 'node.exe' -or+ [string]::IsNullOrWhiteSpace([string]$row.CommandLine)) {+ throw 'Node 进程身份字段不完整,无法证明目标进程不存在'+ }+ if (-not (Test-ExactNodeEntryCommandLine -CommandLine ([string]$row.CommandLine) -ExpectedScript $ExpectedScript)) {+ continue+ }+ $processId = 0+ if (-not [int]::TryParse([string]$row.ProcessId, [ref]$processId) -or $processId -le 0) {+ throw '目标 Node 进程 PID 无效'+ }+ $record = Get-StrictProcessRecord -ProcessId $processId+ if ($null -eq $record) { throw "目标 Node 进程 PID=$processId 在身份验证期间消失" }+ $matches += ,(Assert-NodeProcessIdentity -Process $record -ExpectedPid $processId -ExpectedScript $ExpectedScript)+ }+ if ($matches.Count -gt 1) { throw "目标 Node 入口存在多个进程: $ExpectedScript" }+ if ($matches.Count -eq 0) { return $null }+ return $matches[0]+}++function Get-ListeningProcessIdsFromLines {+ param(+ [Parameter(Mandatory = $true)][int]$Port,+ [Parameter(Mandatory = $true)][string[]]$Lines+ )+ $ids = New-Object 'System.Collections.Generic.HashSet[int]'+ foreach ($line in $Lines) {+ $parts = ([string]$line).Trim() -split '\s+'+ if ($parts.Count -lt 5 -or $parts[3] -notmatch '^LISTENING$') { continue }+ if ($parts[1] -notmatch (':' + [regex]::Escape([string]$Port) + '$')) { continue }+ $parsed = 0+ if (-not [int]::TryParse($parts[$parts.Count - 1], [ref]$parsed) -or $parsed -le 0) {+ throw "端口 $Port 的监听 PID 无效"+ }+ [void]$ids.Add($parsed)+ }+ return @($ids)+}++function Get-UniqueListeningProcessId {+ param([Parameter(Mandatory = $true)][int]$Port)+ $netstat = Join-Path ([Environment]::SystemDirectory) 'netstat.exe'+ $lines = @(& $netstat -ano -p tcp 2>&1)+ if ($LASTEXITCODE -ne 0) { throw "无法查询端口 $Port 的监听进程" }+ $ids = @(Get-ListeningProcessIdsFromLines -Port $Port -Lines $lines)+ if ($ids.Count -gt 1) { throw "端口 $Port 的监听 PID 不唯一" }+ if ($ids.Count -eq 0) { return $null }+ return [int]$ids[0]+}++function Stop-VerifiedProcess {+ param([Parameter(Mandatory = $true)]$Process)+ $targetPid = [int]$Process.ProcessId+ $current = Get-StrictProcessRecord -ProcessId $targetPid+ if ($null -eq $current) { return }+ if (-not [StringComparer]::OrdinalIgnoreCase.Equals([string]$current.Name, [string]$Process.Name) -or+ -not [StringComparer]::OrdinalIgnoreCase.Equals([string]$current.ExecutablePath, [string]$Process.ExecutablePath) -or+ -not [StringComparer]::OrdinalIgnoreCase.Equals([string]$current.Owner, [string]$Process.Owner) -or+ -not [StringComparer]::Ordinal.Equals([string]$current.CommandLine, [string]$Process.CommandLine)) {+ throw "PID $targetPid 在终止前发生身份变化"+ }+ $taskkill = Join-Path ([Environment]::SystemDirectory) 'taskkill.exe'+ & $taskkill /F /PID $targetPid 2>$null | Out-Null+ if ($LASTEXITCODE -ne 0) { throw "taskkill 无法结束已验证进程 PID=$targetPid" }+ for ($attempt = 0; $attempt -lt 20; $attempt++) {+ if ($null -eq (Get-StrictProcessRecord -ProcessId $targetPid)) { return }+ Start-Sleep -Milliseconds 200+ }+ throw "已验证进程 PID=$targetPid 未退出"+}++function Stop-VerifiedWorkDaddyLifecycle {+ param(+ [Parameter(Mandatory = $true)][string]$DataDir,+ [Parameter(Mandatory = $true)][int]$Port,+ [Parameter(Mandatory = $true)][string]$ExpectedWatchdogScript,+ [Parameter(Mandatory = $true)][string]$ExpectedDaemonScript+ )+ $pidFile = Join-Path $DataDir 'watchdog.pid'+ $pidFileExists = Test-Path -LiteralPath $pidFile+ $watchdogPid = $null+ $staleWatchdogPidFile = $false+ if ($pidFileExists) {+ $pidText = (Get-Content -LiteralPath $pidFile -Raw -ErrorAction Stop).Trim()+ $parsedWatchdogPid = 0+ if ($pidText -notmatch '^[1-9][0-9]*$' -or+ -not [int]::TryParse($pidText, [ref]$parsedWatchdogPid) -or $parsedWatchdogPid -le 0) {+ throw 'watchdog.pid 内容无效'+ }+ $watchdogPid = $parsedWatchdogPid+ }++ # PID 文件只是候选;即使文件缺失,也要从完整 Node 列表证明精确入口不存在。+ $watchdog = Get-UniqueNodeProcessForScript -ExpectedScript $ExpectedWatchdogScript+ if ($pidFileExists) {+ $pidCandidate = Get-StrictProcessRecord -ProcessId $watchdogPid+ if ($null -ne $pidCandidate) {+ [void](Assert-NodeProcessIdentity -Process $pidCandidate -ExpectedPid $watchdogPid -ExpectedScript $ExpectedWatchdogScript)+ if ($null -eq $watchdog -or [int]$watchdog.ProcessId -ne $watchdogPid) {+ throw 'watchdog.pid 与枚举到的精确 watchdog 进程不一致'+ }+ } elseif ($null -ne $watchdog) {+ throw 'watchdog.pid 指向不存在的 PID,但发现了另一个精确 watchdog 进程'+ } else {+ $staleWatchdogPidFile = $true+ }+ }++ $listenerPid = Get-UniqueListeningProcessId -Port $Port+ $daemon = Get-UniqueNodeProcessForScript -ExpectedScript $ExpectedDaemonScript+ if ($null -ne $listenerPid) {+ $listener = Get-StrictProcessRecord -ProcessId $listenerPid+ if ($null -eq $listener) { throw "端口 $Port 的监听 PID 在验证期间消失" }+ [void](Assert-NodeProcessIdentity -Process $listener -ExpectedPid $listenerPid -ExpectedScript $ExpectedDaemonScript)+ if ($null -eq $daemon -or [int]$daemon.ProcessId -ne $listenerPid) {+ throw "端口 $Port 的监听 PID 与枚举到的精确 daemon 进程不一致"+ }+ }++ # 所有候选先完成身份验证;外来监听进程不会导致任何 WorkDaddy 进程被提前终止。+ if ($null -ne $watchdog) { Stop-VerifiedProcess -Process $watchdog }+ if ($null -ne $daemon) {+ if ((Get-UniqueListeningProcessId -Port $Port) -ne $listenerPid) {+ throw "端口 $Port 的监听 PID 在终止前发生变化"+ }+ Stop-VerifiedProcess -Process $daemon+ }+ if ($null -ne (Get-UniqueListeningProcessId -Port $Port)) {+ throw "端口 $Port 未释放"+ }+ if ($staleWatchdogPidFile) {+ if (-not (Test-Path -LiteralPath $pidFile)) { return }+ $currentPidText = (Get-Content -LiteralPath $pidFile -Raw -ErrorAction Stop).Trim()+ if ($currentPidText -cne [string]$watchdogPid) {+ throw 'watchdog.pid 在清理前发生变化'+ }+ if ($null -ne (Get-StrictProcessRecord -ProcessId $watchdogPid) -or+ $null -ne (Get-UniqueNodeProcessForScript -ExpectedScript $ExpectedWatchdogScript)) {+ throw 'watchdog.pid 在清理前不再能证明为 stale 状态'+ }+ Remove-Item -LiteralPath $pidFile -Force -ErrorAction Stop+ }+}++function Assert-DaemonStatusIdentity {+ param(+ [Parameter(Mandatory = $true)]$Status,+ [Parameter(Mandatory = $true)][int]$Port,+ [Parameter(Mandatory = $true)][string]$ExpectedProfile,+ [Parameter(Mandatory = $true)][ValidateScript({ -not [string]::IsNullOrWhiteSpace($_) })][string]$ExpectedVersion,+ [Parameter(Mandatory = $true)][string]$ExpectedDaemonScript,+ [string]$ExpectedBuildId = ''+ )+ $statusPid = 0+ if ($null -eq $Status -or+ (($Status.pid -isnot [int]) -and ($Status.pid -isnot [long])) -or+ [int64]$Status.pid -le 0 -or [int64]$Status.pid -gt [int]::MaxValue -or+ [string]$Status.privilege -cne 'standard' -or+ [string]$Status.profile.id -cne $ExpectedProfile) {+ throw 'daemon 状态身份字段无效'+ }+ $statusPid = [int]$Status.pid+ if ([string]$Status.version -cne $ExpectedVersion) {+ throw 'daemon version 不匹配'+ }+ if (-not [string]::IsNullOrWhiteSpace($ExpectedBuildId) -and [string]$Status.buildId -cne $ExpectedBuildId) {+ throw 'daemon buildId 不匹配'+ }+ $listenerPid = Get-UniqueListeningProcessId -Port $Port+ if ($null -eq $listenerPid -or $listenerPid -ne $statusPid) {+ throw 'daemon 状态 PID 与监听 PID 不一致'+ }+ $daemon = Get-StrictProcessRecord -ProcessId $listenerPid+ if ($null -eq $daemon) { throw 'daemon 监听进程在身份验证期间消失' }+ return Assert-NodeProcessIdentity -Process $daemon -ExpectedPid $listenerPid -ExpectedScript $ExpectedDaemonScript+}++function Test-ExclusiveFile {+ param([Parameter(Mandatory = $true)][string]$Path)+ if (-not (Test-Path -LiteralPath $Path)) { return $true }+ $stream = $null+ try {+ $stream = [IO.File]::Open($Path, [IO.FileMode]::Open, [IO.FileAccess]::Read, [IO.FileShare]::None)+ return $true+ } catch {+ return $false+ } finally {+ if ($stream) { $stream.Dispose() }+ }+}++function Release-VerifiedLauncherLock {+ param([Parameter(Mandatory = $true)][string]$LauncherPath)+ if (Test-ExclusiveFile -Path $LauncherPath) { return $true }+ $matches = @()+ $systemCmd = Join-Path ([Environment]::SystemDirectory) 'cmd.exe'+ $rows = @(Get-CimInstance Win32_Process -Filter "Name = 'cmd.exe'" -ErrorAction Stop)+ foreach ($row in $rows) {+ if ([string]::IsNullOrWhiteSpace([string]$row.CommandLine)) {+ throw '存在无法验证命令行的 cmd.exe,拒绝释放 launcher 锁'+ }+ if (Test-ExactCmdLauncherCommandLine -CommandLine ([string]$row.CommandLine) -ExpectedLauncher $LauncherPath -ExpectedCmd $systemCmd) {+ $record = Get-StrictProcessRecord -ProcessId ([int]$row.ProcessId)+ if ($null -eq $record) { throw 'launcher cmd.exe 在身份验证期间消失' }+ $matches += ,(Assert-CmdLauncherIdentity -Process $record -ExpectedLauncher $LauncherPath)+ }+ }+ if ($matches.Count -ne 1) { throw "launcher.cmd 锁进程数量不是 1: $($matches.Count)" }+ Stop-VerifiedProcess -Process $matches[0]+ for ($attempt = 0; $attempt -lt 20; $attempt++) {+ if (Test-ExclusiveFile -Path $LauncherPath) { return $true }+ Start-Sleep -Milliseconds 200+ }+ throw "launcher.cmd 文件锁未释放: $LauncherPath"+}diff --git a/test/update-layout.test.js b/test/update-layout.test.jsindex 7d38855..7eb83dc 100644--- a/test/update-layout.test.js+++ b/test/update-layout.test.js@@ -64,24 +64,25 @@ test('update progress hides zero-rate and unknown-ETA placeholder text', () => {test('Windows updater stops the watchdog before waiting for the API port', () => {const script = read('apply-update.ps1');const stop = script.indexOf('function Stop-WatchdogAndPort');- const wait = script.indexOf('for ($wait = 0; $wait -lt 15; $wait++)');+ const wait = script.indexOf('Invoke-RestMethod');assert.notEqual(stop, -1);assert.notEqual(wait, -1);assert.ok(stop < wait, 'watchdog shutdown must precede the port wait');+ assert.match(script, /Stop-VerifiedWorkDaddyLifecycle/);});test('Windows install and update release a locked launcher before replacing it', () => {const install = read('install-win.ps1');const update = read('apply-update.ps1');- assert.match(install, /FileShare\]\s*::None/);+ const boundary = read('windows-process-boundary.ps1');+ assert.match(boundary, /FileShare\]\s*::None/);assert.match(install, /launcher\.cmd/);- assert.match(install, /Get-CimInstance\s+Win32_Process/);- assert.match(install, /taskkill \/F \/T \/PID/);- assert.ok(install.indexOf('Release-LockedLauncher') < install.indexOf('robocopy $SrcDir $targetScripts'), 'install must release launcher before robocopy');- assert.match(update, /FileShare\]\s*::None/);+ assert.match(boundary, /Get-CimInstance\s+Win32_Process/);+ assert.match(boundary, /Test-ExactCmdLauncherCommandLine/);+ assert.doesNotMatch(boundary, /taskkill[^\r\n]*\/T\b/i);+ assert.ok(install.indexOf('Release-VerifiedLauncherLock') < install.indexOf('robocopy $SrcDir $targetScripts'), 'install must release launcher before robocopy');assert.match(update, /launcher\.cmd/);- assert.match(update, /Get-CimInstance\s+Win32_Process/);- assert.ok(update.indexOf('Release-LockedLauncher') < update.indexOf('Move-Item -LiteralPath $AppDir'), 'update must release launcher before moving the old app');+ assert.ok(update.indexOf('Release-VerifiedLauncherLock') < update.indexOf('Move-Item -LiteralPath $AppDir'), 'update must release launcher before moving the old app');});test('macOS updater stops the daemon before waiting for the API port', () => {@@ -213,10 +214,11 @@ test('macOS updater validates a cached/downloaded DMG before mounting it', () =>assert.match(daemon, /Content-Type|content-type/);});-test('Windows launcher covers both WorkBuddy images and records exit diagnostics', () => {+test('Windows launcher scopes process discovery to the active profile and records exit diagnostics', () => {const launcher = read('win-launcher.js');- assert.match(launcher, /WorkBuddy\.exe/);- assert.match(launcher, /WorkBuddyAI\.exe/);+ assert.match(launcher, /PROFILE\.id === 'workbuddy-ai' \? \['workbuddyai\.exe'\]/);+ assert.match(launcher, /PROFILE\.id === 'workbuddy-cn' \? \['workbuddy\.exe'\]/);+ assert.doesNotMatch(launcher, /\$names=@\("WorkBuddy\.exe","CodeBuddy\.exe","WorkBuddyAI\.exe"\)/);assert.match(launcher, /\[exit\]/);assert.match(launcher, /taskkill=/);assert.match(launcher, /tasklistProcessIds/);@@ -266,11 +268,12 @@ test('Windows launcher verifies the real WorkBuddy process tree and launch argumassert.match(launcher, /processes: processDiagnostics\(wb\)/);});-test('Windows launcher escalates a PID-only WorkBuddy exit fallback', () => {+test('Windows launcher refuses elevated or image-name exit fallbacks', () => {const launcher = read('win-launcher.js');- assert.match(launcher, /tasklistProcessIds\(targetNames\)/);- assert.match(launcher, /Start-Process[\s\S]*taskkill\.exe[\s\S]*-Verb RunAs/);- assert.match(launcher, /remainingPids|剩余 PID|tasklistPids/);+ assert.doesNotMatch(launcher, /Start-Process[\s\S]*taskkill\.exe[\s\S]*-Verb RunAs/);+ assert.doesNotMatch(launcher, /taskkill[^\n]*\/IM/);+ assert.doesNotMatch(launcher, /['"]\/T['"]/);+ assert.match(launcher, /请手动关闭该程序/);});test('daemon JSON responses are idempotent after headers or body were sent', () => {@@ -547,6 +550,14 @@ test('updaters reject an artifact whose internal daemon version disagrees with iassert.match(win, /新版 daemon 实际版本/);});+test('Windows update runtime must match the packaged daemon version even without a semver ZIP name', () => {+ const win = read('apply-update.ps1');+ assert.match(win, /-ExpectedVersion \$sourceDaemonVersion/);+ assert.match(win, /running daemon version=\$runningVersion expected=\$sourceDaemonVersion/);+ assert.match(win, /if \(\$runningVersion -ne \$sourceDaemonVersion\)/);+ assert.doesNotMatch(win, /if \(-not \[string\]::IsNullOrWhiteSpace\(\$packageVersion\) -and \$runningVersion -ne/);+});+test('sensitive local API routes require an injected token and do not expose wildcard CORS', () => {const daemon = read('daemon.js');const inject = read('inject.js');diff --git a/test/win-launcher-process.test.js b/test/win-launcher-process.test.jsindex 3d22f73..b97685a 100644--- a/test/win-launcher-process.test.js+++ b/test/win-launcher-process.test.js@@ -7,28 +7,15 @@ const launcher = require('../scripts/win-launcher.js');test('requiring the Windows launcher does not execute its startup flow', () => {assert.equal(typeof launcher.getWorkBuddyProcesses, 'function');- assert.equal(typeof launcher.getWorkBuddyProcessesViaCim, 'function');- assert.equal(typeof launcher.getWorkBuddyProcessesViaTasklist, 'function');+ assert.equal(typeof launcher.workBuddyProcesses, 'function');+ assert.equal(typeof launcher.tasklistProcessIds, 'function');+ assert.equal(typeof launcher.workBuddyRunning, 'function');});-test('tasklist CSV fallback parses process names and PIDs', () => {- const rows = launcher.parseTasklistOutput(- '"WorkBuddy.exe","10436","Console","1","123,456 K"\n' +- 'INFO: No tasks are running which match the specified criteria.\n'- );- assert.deepEqual(rows, [{- ProcessId: 10436,- ParentProcessId: null,- Name: 'WorkBuddy.exe',- ExecutablePath: null,- CommandLine: '',- processSource: 'tasklist',- }]);-});--test('tasklist fallback returns a safe array when the command is unavailable', () => {- assert.doesNotThrow(() => launcher.getWorkBuddyProcessesViaTasklist());- assert.ok(Array.isArray(launcher.getWorkBuddyProcessesViaTasklist()));+test('tasklist data remains diagnostic-only', () => {+ const ids = launcher.tasklistProcessIds();+ assert.ok(ids instanceof Set);+ assert.equal(launcher.getWorkBuddyProcessesViaTasklist, undefined);});test('process discovery always returns an array of positive-PID records', () => {@@ -42,6 +29,5 @@ test('process discovery always returns an array of positive-PID records', () =>test('process helpers preserve safe return types without a running client', () => {assert.ok(Array.isArray(launcher.workBuddyProcesses()));- assert.ok(launcher.targetProcessNames() instanceof Set);assert.equal(typeof launcher.workBuddyRunning(), 'boolean');});diff --git a/test/windows-launcher-boundary-repair.test.js b/test/windows-launcher-boundary-repair.test.jsnew file mode 100644index 0000000..16dc917--- /dev/null+++ b/test/windows-launcher-boundary-repair.test.js@@ -0,0 +1,202 @@+'use strict';++const assert = require('node:assert/strict');+const fs = require('node:fs');+const path = require('node:path');+const test = require('node:test');++const root = path.join(__dirname, '..');+const launcherSource = fs.readFileSync(path.join(root, 'scripts', 'win-launcher.js'), 'utf8');+const daemonSource = fs.readFileSync(path.join(root, 'scripts', 'daemon.js'), 'utf8');+const watchdogSource = fs.readFileSync(path.join(root, 'scripts', 'watchdog.js'), 'utf8');+const boundarySource = fs.readFileSync(path.join(root, 'scripts', 'windows-process-boundary.js'), 'utf8');+const powershellSource = fs.readFileSync(path.join(root, 'scripts', 'windows-process-boundary.ps1'), 'utf8');+const boundary = require('../scripts/windows-process-boundary.js');++const resolveWindows = (value) => path.win32.normalize(value);+const withNativeArguments = (row, args) => ({+ ...row,+ ArgumentsSource: 'CommandLineToArgvW',+ Arguments: args,+});++test('termination process records require a confirmed current owner', () => {+ const base = {+ ProcessId: 701,+ Name: 'node.exe',+ ExecutablePath: 'C:\\Node\\node.exe',+ CommandLine: '"C:\\Node\\node.exe" "C:\\WorkDaddy\\scripts\\daemon.js"',+ };+ const parse = (row) => boundary.parseCimProcessResult(+ { status: 0, stdout: JSON.stringify(row) },+ { requireCommandLine: true, requireCurrentOwner: true }+ );++ assert.equal(parse({ ...base, Owner: 'DESKTOP\\alice', OwnerIsCurrent: true })[0].Owner, 'DESKTOP\\alice');+ assert.throws(() => parse(base), /owner/i);+ assert.throws(+ () => parse({ ...base, Owner: 'DESKTOP\\bob', OwnerIsCurrent: false }),+ /owner|current/i+ );+});++test('same-process revalidation rejects PID reuse and owner changes', () => {+ const original = withNativeArguments({+ ProcessId: 702,+ Name: 'node.exe',+ ExecutablePath: 'C:\\Node\\node.exe',+ CommandLine: '"C:\\Node\\node.exe" "C:\\WorkDaddy\\scripts\\watchdog.js"',+ Owner: 'DESKTOP\\alice',+ OwnerIsCurrent: true,+ }, ['C:\\Node\\node.exe', 'C:\\WorkDaddy\\scripts\\watchdog.js']);+ assert.equal(boundary.assertSameProcessIdentity(original, { ...original }).ProcessId, 702);+ assert.throws(+ () => boundary.assertSameProcessIdentity(original, { ...original, Owner: 'DESKTOP\\bob' }),+ /identity|owner/i+ );+ assert.throws(+ () => boundary.assertSameProcessIdentity(original, { ...original, CommandLine: original.CommandLine + ' stop' }),+ /identity|command/i+ );+});++test('native argv evidence is mandatory, structured, and bound to expected paths', () => {+ const node = 'C:\\Node\\node.exe';+ const script = 'C:\\WorkDaddy\\daemon.js';+ const base = { ProcessId: 712, Name: 'node.exe', ExecutablePath: node, CommandLine: `"${node}" "${script}"` };+ assert.throws(() => boundary.filterVerifiedNodeProcesses(node, script, [base], resolveWindows), /Arguments|native/i);+ assert.throws(+ () => boundary.filterVerifiedNodeProcesses(node, script, [{ ...base, ArgumentsSource: 'untrusted', Arguments: [node, script] }], resolveWindows),+ /Arguments|native|source/i+ );+ assert.throws(+ () => boundary.filterVerifiedNodeProcesses(node, script, [{ ...base, ArgumentsSource: 'CommandLineToArgvW', Arguments: [node, 7] }], resolveWindows),+ /Arguments|string/i+ );+ assert.deepEqual(+ boundary.filterVerifiedNodeProcesses(node, script, [withNativeArguments(base, [node, 'C:\\Other\\daemon.js'])], resolveWindows),+ []+ );+ assert.equal(boundary.splitWindowsCommandLine, undefined);+ assert.doesNotMatch(boundarySource, /function\s+splitWindowsCommandLine/);+});++test('lifecycle entry matching rejects unexpected trailing arguments', () => {+ const node = 'C:\\Node\\node.exe';+ const script = 'C:\\WorkDaddy\\scripts\\watchdog.js';+ const row = (ProcessId, CommandLine, Arguments) => withNativeArguments(+ { ProcessId, Name: 'node.exe', ExecutablePath: node, CommandLine }, Arguments+ );+ const rows = [+ row(703, `"${node}" "${script}"`, [node, script]),+ row(704, `"${node}" "${script}" stop`, [node, script, 'stop']),+ row(705, `"${node}" "" "${script}"`, [node, '', script]),+ row(706, `"${node}" --experimental-sqlite "" "${script}"`, [node, '--experimental-sqlite', '', script]),+ row(707, `"${node}" ${String.raw`a\\\"b`} "${script}"`, [node, String.raw`a\"b`, script]),+ row(708, `"${node}"\r\n"${script}"`, [node, `\r\n${script}`]),+ row(709, `"${node}" """${script}"""`, [node, `"${script}"`]),+ row(710, `"${node}" "${script}""`, [node, `${script}"`]),+ row(711, `"${node}" "${script}\\\\"`, [node, `${script}\\`]),+ row(713, `"${node} " "${script}"`, [`${node} `, script]),+ row(714, `"${node}" "${script} "`, [node, `${script} `]),+ row(715, `"${node}" "${script}\r\n"`, [node, `${script}\r\n`]),+ ];+ assert.deepEqual(+ boundary.filterVerifiedNodeProcesses(node, script, rows, resolveWindows).map((row) => row.ProcessId),+ [703]+ );+});++test('launcher enumerates exact lifecycle entries and never kills process trees', () => {+ assert.doesNotMatch(launcherSource, /taskkill[^\r\n]*['"]\/T['"]/i);+ assert.doesNotMatch(launcherSource, /includeTree/);+ assert.match(launcherSource, /queryNodeProcesses\(\)/);+ assert.match(launcherSource, /uniqueNodeProcess\(nodeBin, WATCHDOG_SCRIPT\)/);+ assert.match(launcherSource, /uniqueNodeProcess\(nodeBin, DAEMON_SCRIPT\)/);+ assert.match(launcherSource, /assertSameProcessIdentity/);+ assert.match(launcherSource, /requireCurrentOwner:\s*true/);+ for (const source of [launcherSource, daemonSource, watchdogSource]) {+ assert.match(source, /buildNativeProcessQuery/);+ assert.match(source, /windows-process-boundary\.ps1/);+ assert.match(source, /-ExecutionPolicy['"],\s*['"]Bypass/);+ }+});++test('daemon termination authorization is bound to current profile status and listener', () => {+ const node = 'C:\\Node\\node.exe';+ const script = 'C:\\WorkDaddy\\scripts\\daemon.js';+ const process = withNativeArguments({+ ProcessId: 716,+ Name: 'node.exe',+ ExecutablePath: node,+ CommandLine: `"${node}" "${script}"`,+ }, [node, script]);+ const input = {+ status: { pid: 716, profile: { id: 'workbuddy-cn' }, privilege: 'standard' },+ expectedProfileId: 'workbuddy-cn',+ listenerPids: [716],+ expectedNode: node,+ expectedScript: script,+ nodeProcesses: [process],+ realpath: resolveWindows,+ };++ assert.equal(boundary.assertDaemonTerminationIdentity(input).ProcessId, 716);+ assert.throws(+ () => boundary.assertDaemonTerminationIdentity({+ ...input, status: { ...input.status, profile: { id: 'workbuddy-ai' } },+ }),+ /profile/i+ );+ let foreignProfilePathChecks = 0;+ assert.throws(+ () => boundary.assertDaemonTerminationIdentity({+ ...input,+ status: { ...input.status, profile: { id: 'workbuddy-ai' } },+ realpath: (value) => { foreignProfilePathChecks++; return resolveWindows(value); },+ }),+ /profile/i+ );+ assert.equal(foreignProfilePathChecks, 0);+ assert.throws(+ () => boundary.assertDaemonTerminationIdentity({+ ...input, status: { ...input.status, privilege: 'elevated' },+ }),+ /privilege/i+ );+ assert.throws(+ () => boundary.assertDaemonTerminationIdentity({ ...input, listenerPids: [717] }),+ /listener|PID/i+ );+});++test('launcher never adopts untracked watchdogs or kills unbound daemon entries', () => {+ const stateSource = launcherSource.slice(+ launcherSource.indexOf('function watchdogState'),+ launcherSource.indexOf('function validateDaemonProcess')+ );+ const stopSource = launcherSource.slice(+ launcherSource.indexOf('async function stopDaemonByPort'),+ launcherSource.indexOf('async function ensureDaemon')+ );+ const ensureSource = launcherSource.slice(+ launcherSource.indexOf('async function ensureDaemon'),+ launcherSource.indexOf('// ---------- 2/3.')+ );+ assert.match(stateSource, /!pid[\s\S]*kind:\s*'untracked'/);+ assert.match(stopSource, /watchdog\.kind === 'untracked'[\s\S]*throw new Error/);+ assert.match(ensureSource, /watchdog\.kind === 'untracked'[\s\S]*throw new Error/);+ assert.match(stopSource, /authorizeDaemonTermination/);+ assert.doesNotMatch(stopSource, /remainingDaemon[\s\S]*killVerifiedNodeProcess\(remainingDaemon/);+ const untrackedGuard = stopSource.indexOf("watchdog.kind === 'untracked'");+ const firstKill = stopSource.indexOf('killVerifiedNodeProcess(');+ const firstPidDelete = stopSource.indexOf('removeWatchdogPidIf(');+ assert.ok(untrackedGuard >= 0 && untrackedGuard < firstKill && untrackedGuard < firstPidDelete);+});++test('PowerShell reconciles only a proven stale watchdog PID file', () => {+ assert.match(powershellSource, /\$staleWatchdogPidFile\s*=\s*\$true/);+ assert.match(powershellSource, /Get-UniqueNodeProcessForScript -ExpectedScript \$ExpectedWatchdogScript/);+ assert.match(powershellSource, /watchdog\.pid 在清理前发生变化/);+ assert.match(powershellSource, /Remove-Item -LiteralPath \$pidFile -Force -ErrorAction Stop/);+});diff --git a/test/windows-powershell-boundary.test.js b/test/windows-powershell-boundary.test.jsnew file mode 100644index 0000000..91b5c20--- /dev/null+++ b/test/windows-powershell-boundary.test.js@@ -0,0 +1,88 @@+'use strict';++const assert = require('node:assert/strict');+const fs = require('node:fs');+const path = require('node:path');+const { spawnSync } = require('node:child_process');+const test = require('node:test');++const root = path.join(__dirname, '..');+const scriptsDir = path.join(root, 'scripts');+const helperPath = path.join(scriptsDir, 'windows-process-boundary.ps1');+const lifecycleScripts = ['install-win.ps1', 'uninstall-win.ps1', 'apply-update.ps1'];++test('PowerShell lifecycle scripts reject elevation before side effects', () => {+ for (const name of lifecycleScripts) {+ const source = fs.readFileSync(path.join(scriptsDir, name), 'utf8');+ const probe = source.indexOf('IsInRole');+ assert.ok(probe >= 0, `${name} lacks an inline privilege probe`);+ for (const marker of ['New-Item', 'Start-Transcript', 'Send-Sentry', 'Remove-Item', 'taskkill']) {+ const index = source.indexOf(marker);+ if (index >= 0) assert.ok(probe < index, `${name} performs ${marker} before its privilege probe`);+ }+ assert.doesNotMatch(source, /taskkill[^\r\n]*\/T\b/i, name);+ assert.doesNotMatch(source, /taskkill[^\r\n]*\/IM\b/i, name);+ assert.doesNotMatch(source, /CommandLine\)?\.Contains\s*\(/i, name);+ }+});++test('PowerShell boundary rejects a script appearing only in later argv', { skip: process.platform !== 'win32' }, () => {+ assert.equal(fs.existsSync(helperPath), true);+ const quotedHelper = helperPath.replace(/'/g, "''");+ const command = [+ `. '${quotedHelper}'`,+ '$resolver = { param($value) [IO.Path]::GetFullPath($value) }',+ "$expected = 'C:\\WorkDaddy\\scripts\\daemon.js'",+ "$good = Test-ExactNodeEntryCommandLine -CommandLine '\"C:\\Node\\node.exe\" --experimental-sqlite \"C:\\WorkDaddy\\scripts\\daemon.js\"' -ExpectedScript $expected -PathResolver $resolver",+ "$future = Test-ExactNodeEntryCommandLine -CommandLine '\"C:\\Node\\node.exe\" \"C:\\WorkDaddy\\scripts\\daemon.js\"' -ExpectedScript $expected -PathResolver $resolver",+ "$trailing = Test-ExactNodeEntryCommandLine -CommandLine '\"C:\\Node\\node.exe\" \"C:\\WorkDaddy\\scripts\\daemon.js\" stop' -ExpectedScript $expected -PathResolver $resolver",+ "$bad = Test-ExactNodeEntryCommandLine -CommandLine '\"C:\\Node\\node.exe\" C:\\Other\\other.js \"C:\\WorkDaddy\\scripts\\daemon.js\"' -ExpectedScript $expected -PathResolver $resolver",+ "$nodeSpace = Test-ExactNodeEntryCommandLine -CommandLine '\"C:\\Node\\node.exe \" \"C:\\WorkDaddy\\scripts\\daemon.js\"' -ExpectedNode 'C:\\Node\\node.exe' -ExpectedScript $expected -PathResolver $resolver",+ "$scriptSpace = Test-ExactNodeEntryCommandLine -CommandLine '\"C:\\Node\\node.exe\" \"C:\\WorkDaddy\\scripts\\daemon.js \"' -ExpectedScript $expected -PathResolver $resolver",+ '$scriptCrlf = Test-ExactNodeEntryCommandLine -CommandLine (\'"C:\\Node\\node.exe" "\' + $expected + "`r`n" + \'"\') -ExpectedScript $expected -PathResolver $resolver',+ "$cmdGood = Test-ExactCmdLauncherCommandLine -CommandLine '\"C:\\Windows\\System32\\cmd.exe\" /d /c call \"C:\\WorkDaddy\\scripts\\launcher.cmd\"' -ExpectedLauncher 'C:\\WorkDaddy\\scripts\\launcher.cmd' -PathResolver $resolver",+ "$cmdBad = Test-ExactCmdLauncherCommandLine -CommandLine '\"C:\\Windows\\System32\\cmd.exe\" /d /c call C:\\Other\\launcher.cmd C:\\WorkDaddy\\scripts\\launcher.cmd' -ExpectedLauncher 'C:\\WorkDaddy\\scripts\\launcher.cmd' -PathResolver $resolver",+ "$listeners = @(Get-ListeningProcessIdsFromLines -Port 47832 -Lines @('TCP 127.0.0.1:47832 0.0.0.0:0 LISTENING 777'))",+ "$ambiguous = @(Get-ListeningProcessIdsFromLines -Port 47832 -Lines @('TCP 127.0.0.1:47832 0.0.0.0:0 LISTENING 777','TCP [::1]:47832 [::]:0 LISTENING 778'))",+ `$foreign = [pscustomobject]@{ ProcessId = 777; Name = 'node.exe'; ExecutablePath = '${process.execPath.replace(/'/g, "''")}'; CommandLine = '\"${process.execPath.replace(/'/g, "''")}\" C:\\Other\\other.js \"${path.join(scriptsDir, 'daemon.js').replace(/'/g, "''")}\"'; Owner = [Security.Principal.WindowsIdentity]::GetCurrent().Name }`,+ '$foreignRejected = $false',+ `try { [void](Assert-NodeProcessIdentity -Process $foreign -ExpectedPid 777 -ExpectedScript '${path.join(scriptsDir, 'daemon.js').replace(/'/g, "''")}') } catch { $foreignRejected = $true }`,+ '$statusRejected = $false',+ `try { [void](Assert-DaemonStatusIdentity -Status ([pscustomobject]@{ pid = '777'; version = '1.0.14'; privilege = 'standard'; profile = [pscustomobject]@{ id = 'workbuddy-cn' } }) -Port 47832 -ExpectedProfile 'workbuddy-cn' -ExpectedVersion '1.0.14' -ExpectedDaemonScript '${path.join(scriptsDir, 'daemon.js').replace(/'/g, "''")}') } catch { $statusRejected = $true }`,+ '$versionRejected = $false',+ `try { [void](Assert-DaemonStatusIdentity -Status ([pscustomobject]@{ pid = 777; version = '1.0.13'; privilege = 'standard'; profile = [pscustomobject]@{ id = 'workbuddy-cn' } }) -Port 47832 -ExpectedProfile 'workbuddy-cn' -ExpectedVersion '1.0.14' -ExpectedDaemonScript '${path.join(scriptsDir, 'daemon.js').replace(/'/g, "''")}') } catch { $versionRejected = $_.Exception.Message -match 'version' }`,+ 'if ($good -and $future -and -not $trailing -and -not $bad -and -not $nodeSpace -and -not $scriptSpace -and -not $scriptCrlf -and $cmdGood -and -not $cmdBad -and $listeners.Count -eq 1 -and $listeners[0] -eq 777 -and $ambiguous.Count -eq 2 -and $foreignRejected -and $statusRejected -and $versionRejected) { exit 0 } else { exit 7 }',+ ].join('; ');+ const result = spawnSync('powershell.exe', ['-NoProfile', '-NonInteractive', '-Command', command], { encoding: 'utf8' });+ assert.equal(result.status, 0, result.stderr || result.stdout);+});++test('PowerShell source validates owner, exact launcher token, PID, and listener identity', () => {+ assert.equal(fs.existsSync(helperPath), true);+ const helper = fs.readFileSync(helperPath, 'utf8');+ assert.match(helper, /Invoke-CimMethod[^\r\n]*GetOwner/i);+ assert.match(helper, /Test-ExactCmdLauncherCommandLine/);+ assert.match(helper, /Get-UniqueListeningProcessId/);+ assert.match(helper, /function Get-UniqueNodeProcessForScript/);+ assert.match(helper, /\[Parameter\(Mandatory = \$true\)\]\[ValidateScript\(\{ -not \[string\]::IsNullOrWhiteSpace\(\$_\) \}\)\]\[string\]\$ExpectedVersion/);+ assert.match(helper, /\[string\]\$Status\.version -cne \$ExpectedVersion/);+ assert.match(helper, /Get-UniqueNodeProcessForScript -ExpectedScript \$ExpectedWatchdogScript/);+ assert.match(helper, /Get-UniqueNodeProcessForScript -ExpectedScript \$ExpectedDaemonScript/);+ assert.match(helper, /Stop-VerifiedProcess/);+ assert.match(helper, /watchdog\.pid 内容无效/);+ assert.match(helper, /\[int\]::TryParse/);+ for (const name of lifecycleScripts) {+ const source = fs.readFileSync(path.join(scriptsDir, name), 'utf8');+ assert.match(source, /windows-process-boundary\.ps1/);+ }+});++test('only the shared verified PowerShell boundary may invoke taskkill', () => {+ const helper = fs.readFileSync(helperPath, 'utf8');+ assert.match(helper, /function Stop-VerifiedProcess[\s\S]*\[Environment\]::SystemDirectory[\s\S]*& \$taskkill \/F \/PID/);+ assert.match(helper, /\$LASTEXITCODE -ne 0/);+ for (const name of lifecycleScripts) {+ const source = fs.readFileSync(path.join(scriptsDir, name), 'utf8');+ assert.doesNotMatch(source, /taskkill(?:\.exe)?\s/i, name);+ }+});diff --git a/test/windows-privilege-boundary.test.js b/test/windows-privilege-boundary.test.jsnew file mode 100644index 0000000..7440bfb--- /dev/null+++ b/test/windows-privilege-boundary.test.js@@ -0,0 +1,341 @@+'use strict';++const assert = require('node:assert/strict');+const { spawnSync } = require('node:child_process');+const fs = require('node:fs');+const os = require('node:os');+const path = require('node:path');+const test = require('node:test');++const root = path.join(__dirname, '..');+const scriptsDir = path.join(root, 'scripts');+const launcherSource = fs.readFileSync(path.join(scriptsDir, 'win-launcher.js'), 'utf8');+const daemonSource = fs.readFileSync(path.join(scriptsDir, 'daemon.js'), 'utf8');+const watchdogSource = fs.readFileSync(path.join(scriptsDir, 'watchdog.js'), 'utf8');+const installerSource = fs.readFileSync(path.join(scriptsDir, 'install-win.ps1'), 'utf8');+const readmeSource = fs.readFileSync(path.join(root, 'README.md'), 'utf8');+const hiddenLauncherSource = fs.readFileSync(path.join(scriptsDir, 'launcher-hidden.vbs'), 'utf8');+const cmdLauncherSource = fs.readFileSync(path.join(scriptsDir, 'launcher.cmd'), 'utf8');+const boundary = require('../scripts/windows-process-boundary.js');++const resolveWindows = (value) => path.win32.normalize(value);+const nativeProcess = (process, args) => ({+ ...process,+ ArgumentsSource: 'CommandLineToArgvW',+ Arguments: args,+});++test('privilege probe accepts only an explicit standard-user result', () => {+ const fake = (result) => () => result;+ assert.equal(boundary.assertStandardWindowsPrivilege(fake({ status: 0, stdout: 'False\r\n' })), 'standard');+ assert.throws(() => boundary.assertStandardWindowsPrivilege(fake({ status: 0, stdout: 'True\r\n' })), /管理员|elevated/i);+ assert.throws(() => boundary.assertStandardWindowsPrivilege(fake({ status: 0, stdout: '' })), /确认|determine/i);+ assert.throws(() => boundary.assertStandardWindowsPrivilege(fake({ status: 1, stderr: 'denied' })), /确认|determine|denied/i);+ assert.throws(() => boundary.assertStandardWindowsPrivilege(fake({ status: null, error: new Error('timeout') })), /timeout/);+});++test('CIM parsing rejects command failures and incomplete process identities', () => {+ const valid = { ProcessId: 101, ParentProcessId: 10, Name: 'WorkBuddyAI.exe', ExecutablePath: 'C:\\Apps\\WorkBuddyAI.exe' };+ assert.deepEqual(boundary.parseCimProcessResult({ status: 0, stdout: '' }), []);+ assert.deepEqual(boundary.parseCimProcessResult({ status: 0, stdout: JSON.stringify(valid) }), [valid]);+ assert.throws(() => boundary.parseCimProcessResult({ error: new Error('spawn failed'), status: null, stdout: '' }), /spawn failed/);+ assert.throws(() => boundary.parseCimProcessResult({ status: 1, stderr: 'access denied', stdout: '' }), /status|exit|access denied/i);+ assert.throws(() => boundary.parseCimProcessResult({ status: 0, stdout: '{broken' }), /JSON|parse/i);+ assert.throws(() => boundary.parseCimProcessResult({ status: 0, stdout: '{"ProcessId":101}' }), /Name|path|record/i);+ assert.throws(() => boundary.parseCimProcessResult({ status: 0, stdout: '{"ProcessId":0,"Name":"node.exe","ExecutablePath":"C:\\\\node.exe"}' }), /PID/i);+ assert.throws(() => boundary.parseCimProcessResult({ status: 0, stdout: JSON.stringify({ ...valid, ProcessId: '101' }) }), /PID/i);+ assert.throws(+ () => boundary.parseCimProcessResult({ status: 0, stdout: JSON.stringify({ ...valid, CommandLine: null }) }, { requireCommandLine: true }),+ /command/i+ );+});++test('profile process selection rejects multiple roots and ignores other CodeBuddy installs', () => {+ const expected = 'C:\\Program Files\\WorkBuddyAI\\WorkBuddyAI.exe';+ const rows = [+ { ProcessId: 101, Name: 'WorkBuddyAI.exe', ExecutablePath: expected },+ { ProcessId: 102, Name: 'CodeBuddy.exe', ExecutablePath: 'D:\\CodeBuddy\\CodeBuddy.exe' },+ { ProcessId: 103, Name: 'WorkBuddyAI.exe', ExecutablePath: 'D:\\Portable\\WorkBuddyAI.exe' },+ ];+ assert.deepEqual(boundary.filterVerifiedWindowsProcesses(expected, rows, resolveWindows).map((row) => row.ProcessId), [101]);+ assert.equal(+ boundary.selectRunningProfileBinary(new Set(['workbuddyai.exe']), rows.slice(0, 2), resolveWindows),+ path.win32.normalize(expected)+ );+ assert.throws(+ () => boundary.selectRunningProfileBinary(new Set(['workbuddyai.exe']), rows, resolveWindows),+ /多个|multiple|directory|目录/i+ );+});++test('node process identity requires exact executable, PID, and script argument', () => {+ const expectedNode = 'C:\\Node\\node.exe';+ const expectedScript = 'C:\\WorkDaddy\\scripts\\daemon.js';+ const rows = [+ nativeProcess({ ProcessId: 201, Name: 'node.exe', ExecutablePath: expectedNode, CommandLine: `"${expectedNode}" --experimental-sqlite "${expectedScript}"` }, [expectedNode, '--experimental-sqlite', expectedScript]),+ nativeProcess({ ProcessId: 202, Name: 'node.exe', ExecutablePath: expectedNode, CommandLine: `"${expectedNode}" C:\\Other\\daemon.js` }, [expectedNode, 'C:\\Other\\daemon.js']),+ nativeProcess({ ProcessId: 203, Name: 'node.exe', ExecutablePath: 'D:\\Node\\node.exe', CommandLine: `"D:\\Node\\node.exe" "${expectedScript}"` }, ['D:\\Node\\node.exe', expectedScript]),+ nativeProcess({ ProcessId: 204, Name: 'node.exe', ExecutablePath: expectedNode, CommandLine: `"${expectedNode}" C:\\Other\\other.js "${expectedScript}"` }, [expectedNode, 'C:\\Other\\other.js', expectedScript]),+ ];+ assert.deepEqual(+ boundary.filterVerifiedNodeProcesses(expectedNode, expectedScript, rows, resolveWindows).map((row) => row.ProcessId),+ [201]+ );+ assert.throws(+ () => boundary.assertVerifiedNodeProcess(202, expectedNode, expectedScript, rows, resolveWindows),+ /verify|验证|identity/i+ );+ assert.throws(+ () => boundary.assertVerifiedNodeProcess(204, expectedNode, expectedScript, rows, resolveWindows),+ /verify|验证|identity/i+ );+});++test('disk discovery rejects duplicate current-profile installations', () => {+ assert.equal(+ boundary.sameWindowsPath(boundary.selectUniqueDiscoveredBinary(+ new Set(['workbuddy.exe']),+ ['C:\\Apps\\WorkBuddy.exe', 'c:\\apps\\WORKBUDDY.exe'],+ resolveWindows+ ), path.win32.normalize('C:\\Apps\\WorkBuddy.exe')),+ true+ );+ assert.throws(+ () => boundary.selectUniqueDiscoveredBinary(+ new Set(['workbuddy.exe']),+ ['C:\\Apps\\WorkBuddy.exe', 'D:\\Portable\\WorkBuddy.exe'],+ resolveWindows+ ),+ /WBSWITCH_WORKBUDDY_BIN|多个|multiple/i+ );+});++test('daemon status identity binds metadata, listener PID, node path, and script path', () => {+ const expectedNode = 'C:\\Node\\node.exe';+ const expectedScript = 'C:\\WorkDaddy\\scripts\\daemon.js';+ const process = nativeProcess({+ ProcessId: 301, Name: 'node.exe', ExecutablePath: expectedNode,+ CommandLine: `"${expectedNode}" --experimental-sqlite "${expectedScript}"`,+ }, [expectedNode, '--experimental-sqlite', expectedScript]);+ const status = { version: '1.0.14', buildId: 'build-a', profile: { id: 'workbuddy-cn' }, privilege: 'standard', pid: 301 };+ const input = {+ status,+ expectedVersion: '1.0.14', expectedBuildId: 'build-a', expectedProfileId: 'workbuddy-cn',+ listenerPids: [301], nodeProcesses: [process], expectedNode, expectedScript, realpath: resolveWindows,+ };+ assert.equal(boundary.assertDaemonServiceIdentity(input).ProcessId, 301);+ assert.throws(() => boundary.assertDaemonServiceIdentity({ ...input, status: { ...status, buildId: 'old' } }), /build/i);+ assert.throws(() => boundary.assertDaemonServiceIdentity({ ...input, listenerPids: [999] }), /listener|监听|PID/i);+ assert.throws(() => boundary.assertDaemonServiceIdentity({ ...input, status: { ...status, privilege: 'elevated' } }), /privilege|权限/i);+ assert.throws(() => boundary.assertDaemonServiceIdentity({ ...input, status: { ...status, pid: '301' } }), /PID/i);+});++test('Windows entry points fail closed and expose a standard daemon identity', () => {+ assert.equal(fs.existsSync(path.join(scriptsDir, 'win-inject-helper.js')), false);+ assert.match(launcherSource, /assertStandardWindowsPrivilege/);+ assert.match(watchdogSource, /assertStandardWindowsPrivilege/);+ assert.match(daemonSource, /assertStandardWindowsPrivilege/);+ assert.match(daemonSource, /privilege:\s*DAEMON_PRIVILEGE/);+ assert.match(daemonSource, /pid:\s*process\.pid/);+ assert.match(launcherSource, /assertDaemonServiceIdentity/);+ const privilegeProbe = launcherSource.indexOf('assertStandardWindowsPrivilege();');+ const telemetryImport = launcherSource.indexOf('const { captureMessage');+ assert.ok(privilegeProbe >= 0 && telemetryImport > privilegeProbe);+ const privilegeFailure = launcherSource.slice(privilegeProbe, telemetryImport);+ assert.doesNotMatch(privilegeFailure, /reportAndExit|captureMessage|captureException|\blog\s*\(/);+ const ensureDaemonSource = launcherSource.slice(+ launcherSource.indexOf('async function ensureDaemon'),+ launcherSource.indexOf('// ---------- 2\/3.', launcherSource.indexOf('async function ensureDaemon'))+ );+ assert.doesNotMatch(ensureDaemonSource, /daemonRunning\s*\(/);+ assert.match(ensureDaemonSource, /exactDaemonStatus/);+ assert.match(watchdogSource, /assertVerifiedNodeProcess/);+ assert.match(watchdogSource, /filterVerifiedNodeProcesses/);+ assert.match(watchdogSource, /assertSameProcessIdentity/);+ assert.match(watchdogSource, /requireCurrentOwner:\s*true/);+ assert.match(watchdogSource, /requireNativeArguments:\s*true/);+ assert.match(watchdogSource, /ParentProcessId/);+ assert.match(watchdogSource, /flag:\s*['"]wx['"]/);+ assert.match(watchdogSource, /queryWatchdogProcesses\(\)/);+ assert.match(watchdogSource, /state\.kind === 'untracked'/);+ assert.doesNotMatch(watchdogSource, /taskkill[\s\S]{0,120}['"]\/T['"]/i);+ assert.match(watchdogSource, /terminateVerifiedProcess\(state\.watchdog/);+ assert.match(watchdogSource, /terminateVerifiedProcess\(daemon/);+ assert.match(watchdogSource, /if \(state\.kind === 'stale'\) throw new Error\(/);+ assert.doesNotMatch(watchdogSource, /state\.kind === 'stale'\) removePidFileIf/);+ assert.match(launcherSource, /if \(watchdog\.kind === 'stale'\) throw new Error\(/);+ assert.doesNotMatch(launcherSource, /watchdog\.kind === 'stale'[\s\S]{0,100}(?:unlinkSync|removePidFileIf)/);+ assert.doesNotMatch(launcherSource + daemonSource, /Start-Process[^\n]*-Verb\s+RunAs/i);+ assert.doesNotMatch(installerSource, /请以管理员身份运行/);+ assert.doesNotMatch(readmeSource, /右键以管理员身份运行 WorkDaddy/);+});++test('watchdog stop terminates only reverified watchdog and direct daemon PIDs', () => {+ const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'workdaddy-watchdog-stop-'));+ const preload = path.join(tempDir, 'preload.js');+ const callsFile = path.join(tempDir, 'calls.jsonl');+ const watchdogPid = 424201;+ const daemonPid = 424202;+ fs.writeFileSync(path.join(tempDir, 'watchdog.pid'), String(watchdogPid));+ fs.writeFileSync(preload, `+ const cp = require('node:child_process');+ const fs = require('node:fs');+ const node = ${JSON.stringify(process.execPath)};+ const watchdog = ${JSON.stringify(path.join(scriptsDir, 'watchdog.js'))};+ const daemon = ${JSON.stringify(path.join(scriptsDir, 'daemon.js'))};+ const callsFile = ${JSON.stringify(callsFile)};+ const alive = new Set(process.env.TEST_NO_DAEMON === '1' ? [${watchdogPid}] : [${watchdogPid}, ${daemonPid}]);+ const owner = 'DESKTOP\\alice';+ const rows = {+ ${watchdogPid}: { ProcessId: ${watchdogPid}, ParentProcessId: 100, Name: 'node.exe', ExecutablePath: node, CommandLine: '"' + node + '" --experimental-sqlite "' + watchdog + '"', ArgumentsSource: 'CommandLineToArgvW', Arguments: [node, '--experimental-sqlite', watchdog], Owner: owner, OwnerIsCurrent: process.env.TEST_FOREIGN_OWNER !== '1' },+ ${daemonPid}: { ProcessId: ${daemonPid}, ParentProcessId: ${watchdogPid}, Name: 'node.exe', ExecutablePath: node, CommandLine: '"' + node + '" --experimental-sqlite "' + daemon + '"', ArgumentsSource: 'CommandLineToArgvW', Arguments: [node, '--experimental-sqlite', daemon], Owner: owner, OwnerIsCurrent: process.env.TEST_FOREIGN_OWNER !== '1' },+ };+ cp.spawn = () => { throw new Error('unexpected daemon spawn'); };+ cp.spawnSync = (command, args) => {+ if (command === 'powershell') {+ const script = String(args[args.length - 1]);+ if (script.includes('WindowsBuiltInRole')) return { status: 0, stdout: 'False\\r\\n', stderr: '' };+ let selected = [];+ if (script.includes('ParentProcessId -eq ${watchdogPid}')) {+ selected = [rows[${watchdogPid}], rows[${daemonPid}]].filter((row) => alive.has(row.ProcessId));+ } else {+ const match = script.match(/ProcessId -eq (\\d+)/);+ if (match && alive.has(Number(match[1]))) selected = [rows[Number(match[1])]];+ }+ return { status: 0, stdout: selected.length ? JSON.stringify(selected.length === 1 ? selected[0] : selected) : '', stderr: '' };+ }+ if (command === 'taskkill') {+ fs.appendFileSync(callsFile, JSON.stringify(args) + '\\n');+ const pid = Number(args[args.indexOf('/PID') + 1]);+ alive.delete(pid);+ return { status: 0, stdout: '', stderr: '' };+ }+ throw new Error('unexpected command: ' + command);+ };+ `);+ try {+ const result = spawnSync(process.execPath, ['--require', preload, path.join(scriptsDir, 'watchdog.js'), 'stop'], {+ encoding: 'utf8',+ env: { ...process.env, WBSWITCH_DATA_DIR: tempDir },+ timeout: 10000,+ });+ assert.equal(result.status, 0, result.stderr);+ assert.equal(fs.existsSync(path.join(tempDir, 'watchdog.pid')), false);+ const calls = fs.readFileSync(callsFile, 'utf8').trim().split(/\r?\n/).map(JSON.parse);+ assert.deepEqual(calls, [+ ['/F', '/PID', String(watchdogPid)],+ ['/F', '/PID', String(daemonPid)],+ ]);++ fs.writeFileSync(path.join(tempDir, 'watchdog.pid'), String(watchdogPid));+ fs.writeFileSync(callsFile, '');+ const crashWindow = spawnSync(process.execPath, ['--require', preload, path.join(scriptsDir, 'watchdog.js'), 'stop'], {+ encoding: 'utf8',+ env: { ...process.env, WBSWITCH_DATA_DIR: tempDir, TEST_NO_DAEMON: '1' },+ timeout: 10000,+ });+ assert.equal(crashWindow.status, 0, crashWindow.stderr);+ assert.equal(fs.existsSync(path.join(tempDir, 'watchdog.pid')), false);+ assert.deepEqual(+ fs.readFileSync(callsFile, 'utf8').trim().split(/\r?\n/).map(JSON.parse),+ [['/F', '/PID', String(watchdogPid)]]+ );++ fs.writeFileSync(path.join(tempDir, 'watchdog.pid'), String(watchdogPid));+ fs.writeFileSync(callsFile, '');+ const foreignOwner = spawnSync(process.execPath, ['--require', preload, path.join(scriptsDir, 'watchdog.js'), 'stop'], {+ encoding: 'utf8',+ env: { ...process.env, WBSWITCH_DATA_DIR: tempDir, TEST_FOREIGN_OWNER: '1' },+ timeout: 10000,+ });+ assert.notEqual(foreignOwner.status, 0);+ assert.match(foreignOwner.stderr, /owner|current user|所有者|当前用户/i);+ assert.equal(fs.readFileSync(path.join(tempDir, 'watchdog.pid'), 'utf8'), String(watchdogPid));+ assert.equal(fs.readFileSync(callsFile, 'utf8'), '');+ } finally {+ fs.rmSync(tempDir, { recursive: true, force: true });+ }+});++test('watchdog startup refuses an exact untracked instance when the PID file is absent', () => {+ const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'workdaddy-watchdog-untracked-'));+ const preload = path.join(tempDir, 'preload.js');+ const untrackedPid = 424203;+ fs.writeFileSync(preload, `+ const cp = require('node:child_process');+ const node = ${JSON.stringify(process.execPath)};+ const watchdog = ${JSON.stringify(path.join(scriptsDir, 'watchdog.js'))};+ cp.spawn = () => { throw new Error('duplicate watchdog reached daemon spawn'); };+ cp.spawnSync = (command, args) => {+ if (command !== 'powershell') throw new Error('unexpected command: ' + command);+ const script = String(args[args.length - 1]);+ if (script.includes('WindowsBuiltInRole')) return { status: 0, stdout: 'False\\r\\n', stderr: '' };+ if (script.includes("Name -eq 'node.exe'")) {+ return { status: 0, stderr: '', stdout: JSON.stringify({+ ProcessId: ${untrackedPid}, ParentProcessId: 100, Name: 'node.exe', ExecutablePath: node,+ CommandLine: '"' + node + '" --experimental-sqlite "' + watchdog + '"',+ ArgumentsSource: 'CommandLineToArgvW', Arguments: [node, '--experimental-sqlite', watchdog],+ Owner: 'DESKTOP\\alice', OwnerIsCurrent: true,+ }) };+ }+ return { status: 0, stdout: '', stderr: '' };+ };+ `);+ try {+ const result = spawnSync(process.execPath, ['--require', preload, path.join(scriptsDir, 'watchdog.js')], {+ encoding: 'utf8',+ env: { ...process.env, WBSWITCH_DATA_DIR: tempDir },+ timeout: 10000,+ });+ assert.notEqual(result.status, 0);+ assert.match(result.stderr, /没有 PID 文件|untracked|重复实例/i);+ assert.equal(fs.existsSync(path.join(tempDir, 'watchdog.pid')), false);+ } finally {+ fs.rmSync(tempDir, { recursive: true, force: true });+ }+});++test('packaged scripts contain no WorkBuddy image-name kill or stale elevation helper', () => {+ const sources = [];+ const visit = (dir) => {+ for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {+ if (entry.name === 'node_modules' || entry.name === 'builtin') continue;+ const file = path.join(dir, entry.name);+ if (entry.isDirectory()) visit(file);+ else if (/\.(?:js|cmd|ps1|vbs|sh)$/i.test(entry.name)) sources.push([file, fs.readFileSync(file, 'utf8')]);+ }+ };+ visit(scriptsDir);+ for (const [file, source] of sources) {+ assert.doesNotMatch(source, /(?:taskkill(?:\.exe)?[^\r\n]*\/IM[^\r\n]*WorkBuddy|\/IM[^\r\n]*WorkBuddy)/i, file);+ assert.doesNotMatch(source, /win-inject-helper|--inject-helper/i, file);+ }+ assert.equal(fs.existsSync(path.join(scriptsDir, 'kill.js')), false);+});++test('logout and restart paths refuse unverified profile processes', () => {+ assert.match(launcherSource, /selectRunningProfileBinary/);+ assert.match(daemonSource, /selectRunningProfileBinary/);+ assert.match(launcherSource, /存在当前 profile 进程,但没有进程属于已验证安装目录/);+ assert.match(daemonSource, /存在当前 profile 进程,但没有进程属于已验证安装目录/);+ assert.match(daemonSource, /requireCurrentOwner:\s*true/);+ assert.match(daemonSource, /requireNativeArguments:\s*true/);+ assert.match(daemonSource, /assertSameProcessIdentity/);+ assert.match(daemonSource, /revalidateWindowsWorkBuddyProcess/);+ const quitFunction = daemonSource.slice(+ daemonSource.indexOf('async function quitWorkBuddy'),+ daemonSource.indexOf('/** 探测 WorkDaddy.app', daemonSource.indexOf('async function quitWorkBuddy'))+ );+ assert.match(quitFunction, /revalidateWindowsWorkBuddyProcess[\s\S]*taskkill[\s\S]*revalidateWindowsWorkBuddyProcess[\s\S]*taskkill/);+ const logoutStart = daemonSource.indexOf("p === '/api/logout'");+ const quitIndex = daemonSource.indexOf('await quitWorkBuddy()', logoutStart);+ const unlinkIndex = daemonSource.indexOf('fs.unlinkSync(AUTH_FILE)', logoutStart);+ assert.ok(logoutStart >= 0 && quitIndex > logoutStart && unlinkIndex > quitIndex);+});++test('Windows self-check includes the shared boundary and old admin comments are removed', () => {+ const verify = fs.readFileSync(path.join(scriptsDir, 'verify-win.cmd'), 'utf8');+ assert.match(verify, /win-launcher\.js windows-process-boundary\.js/);+ assert.doesNotMatch(verify, /win-inject-helper\.js/);+ assert.doesNotMatch(hiddenLauncherSource + cmdLauncherSource, /shortcut as administrator|管理员启动/i);+});