import fs from 'node:fs'; import path from 'node:path'; import { execFileSync } from 'node:child_process'; import { createHash } from 'node:crypto'; import { projectEnvironment } from '../process-environment.mjs'; import { hostError } from '../../shared/contracts/desktop-host.mjs'; import { assertLocalTree } from './file-state.mjs'; export function protectUserDirectory(directory) { assertLocalTree(directory); if (process.platform !== 'win32') throw hostError('本机秘密目录需要Windows用户权限。'); const script = "$ErrorActionPreference='Stop';$ProgressPreference='SilentlyContinue';$awbPath=[Text.Encoding]::UTF8.GetString([Convert]::FromBase64String([Console]::In.ReadToEnd()));" + '$awbSid=[Security.Principal.WindowsIdentity]::GetCurrent().User;' + '$awbAcl=[IO.Directory]::GetAccessControl($awbPath,[Security.AccessControl.AccessControlSections]::Access);' + '$awbAcl.SetAccessRuleProtection($true,$false);' + 'foreach($awbExisting in $awbAcl.GetAccessRules($true,$false,[Security.Principal.SecurityIdentifier])){$awbAcl.RemoveAccessRuleSpecific($awbExisting)};' + '$awbRule=New-Object Security.AccessControl.FileSystemAccessRule($awbSid,"FullControl","ContainerInherit,ObjectInherit","None","Allow");' + '$awbAcl.AddAccessRule($awbRule);[IO.Directory]::SetAccessControl($awbPath,$awbAcl)'; try { execFileSync(path.join(process.env.SystemRoot || 'C:\\Windows', 'System32/WindowsPowerShell/v1.0/powershell.exe'), ['-NoProfile', '-NonInteractive', '-EncodedCommand', Buffer.from(script, 'utf16le').toString('base64')], { input: Buffer.from(directory, 'utf8').toString('base64'), encoding: 'utf8', stdio: ['pipe', 'pipe', 'pipe'], windowsHide: true, timeout: 15000, maxBuffer: 65536, env: projectEnvironment() }); } catch { throw hostError('无法为本机秘密目录设置当前Windows用户权限。', 'HOST_DIRECTORY_UNPROTECTED'); } } export function observeWindowsProcess(pid) { if (process.platform !== 'win32') throw hostError('此桌面宿主核验需要Windows。', 'HOST_PLATFORM_UNSUPPORTED'); if (!Number.isInteger(pid) || pid < 1 || pid > 2147483647) throw hostError('宿主PID无效。'); const script = "$ErrorActionPreference='Stop';$ProgressPreference='SilentlyContinue';[Console]::OutputEncoding=New-Object System.Text.UTF8Encoding($false);" + '$awbProcess=Get-CimInstance Win32_Process -Filter "ProcessId=' + pid + '";' + 'if($null -eq $awbProcess){Write-Output "null";exit 0};' + '$awbOwner=Invoke-CimMethod -InputObject $awbProcess -MethodName GetOwnerSid;' + 'if($awbOwner.ReturnValue -ne 0 -or -not $awbOwner.Sid){throw "Owner identity unavailable"};' + '[pscustomobject]@{pid=[int]$awbProcess.ProcessId;parentPid=[int]$awbProcess.ParentProcessId;' + 'createdAt=$awbProcess.CreationDate.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ss.fffZ");' + 'executable=$awbProcess.ExecutablePath;userSid=$awbOwner.Sid}|ConvertTo-Json -Compress'; try { const shell = path.join(process.env.SystemRoot || 'C:\\Windows', 'System32/WindowsPowerShell/v1.0/powershell.exe'); const output = execFileSync(shell, ['-NoProfile', '-NonInteractive', '-EncodedCommand', Buffer.from(script, 'utf16le').toString('base64')], { windowsHide: true, encoding: 'utf8', stdio: ['pipe', 'pipe', 'pipe'], timeout: 15000, maxBuffer: 65536, env: projectEnvironment() }); const value = JSON.parse(output.trim().replace(/^\uFEFF/, '')); if (value === null) return null; if (value.pid !== pid || !Number.isFinite(Date.parse(value.createdAt)) || !/^S-1-\d+(?:-\d+)+$/.test(value.userSid) || !value.executable || !fs.existsSync(value.executable)) throw new Error('Invalid observation'); return { ...value, executable: fs.realpathSync.native(value.executable) }; } catch { throw hostError('无法核对Windows宿主创建、用户或可执行身份;不会复用或停止未知进程。', 'HOST_PROCESS_UNVERIFIED'); } } export function binaryIdentity(file) { assertLocalTree(file); const absolute = fs.realpathSync.native(file), stat = fs.lstatSync(absolute); if (!stat.isFile() || stat.isSymbolicLink() || stat.nlink !== 1 || stat.size > 256 * 1024 * 1024) throw hostError('宿主可执行文件身份无效。'); return { path: absolute, bytes: stat.size, sha256: createHash('sha256').update(fs.readFileSync(absolute)).digest('hex') }; }