Skip to content

Spot it. Save it. Free, local-first Chrome extension for images, videos and prompts. Explore 2,000+ curated cases and connect your library to AI Agents via MCP. 提示词导演

4.9 KB
Raw Blame
import { execFile } from 'node:child_process';
import { promisify } from 'node:util';
import { win32 } from 'node:path';
import { CONNECTOR_TIMEOUT_MS } from './bridge-client.mjs';
const execute = promisify(execFile);
export const nativeRegistryKey = 'HKCU\\Software\\Google\\Chrome\\NativeMessagingHosts\\com.promptdirector.connector';
export function windowsCommand(name, env = process.env) {
  if (!env.SystemRoot) throw new Error('Windows 系统目录不可用,无法安全调用系统安装工具。');
  return win32.join(env.SystemRoot, 'System32', name);
}
export async function privateWindowsDirectory(root) {
  // Use Windows .NET ACL APIs directly: PowerShell command autoload can stall
  // in filtered MCP environments. Paths remain data, never executable code.
  const script = `$ErrorActionPreference='Stop'
function Trace($stage) { if ($env:PROMPTDIRECTOR_DEBUG) { [Console]::Error.WriteLine(([DateTime]::UtcNow.ToString('o'))+' '+$stage) } }
Trace 'script-start'
$p=$env:PROMPTDIRECTOR_PRIVATE_DIRECTORY
Trace 'directory-info'
$item=[IO.DirectoryInfo]::new($p)
Trace 'identity'
if (($item.Attributes -band [IO.FileAttributes]::ReparsePoint) -ne 0) { throw 'Connector directory cannot be a reparse point' }
$sid=[Security.Principal.WindowsIdentity]::GetCurrent().User
Trace 'get-acl'
$acl=$item.GetAccessControl()
Trace 'acl-read'
$owner=$acl.GetOwner([Security.Principal.SecurityIdentifier])
if ($owner.Value -ne $sid.Value) { throw 'Connector directory must belong to current user' }
$rules=@($acl.GetAccessRules($true,$true,[Security.Principal.SecurityIdentifier]))
$inheritance=[Security.AccessControl.InheritanceFlags]'ContainerInherit,ObjectInherit'
if ($acl.AreAccessRulesProtected -and $rules.Count -eq 1) {
 $r=$rules[0]
 if ($r.IdentityReference.Value -eq $sid.Value -and
     $r.AccessControlType -eq 'Allow' -and
     $r.FileSystemRights -eq [Security.AccessControl.FileSystemRights]::FullControl -and
     $r.InheritanceFlags -eq $inheritance -and
     $r.PropagationFlags -eq [Security.AccessControl.PropagationFlags]::None) { return }
}
$private=[Security.AccessControl.DirectorySecurity]::new()
$private.SetOwner($sid)
$private.SetAccessRuleProtection($true,$false)
$rule=[Security.AccessControl.FileSystemAccessRule]::new($sid,'FullControl','ContainerInherit,ObjectInherit','None','Allow')
$private.AddAccessRule($rule)
$item.SetAccessControl($private)
$actual=$item.GetAccessControl()
if (!$actual.AreAccessRulesProtected) { throw 'Private directory permissions were not applied' }
foreach($r in $actual.GetAccessRules($true,$true,[Security.Principal.SecurityIdentifier])) {
 if ($r.AccessControlType -eq 'Allow' -and $r.IdentityReference.Value -ne $sid.Value) { throw 'Unexpected directory access' }
}`;
  const started = Date.now();
  if (process.env.PROMPTDIRECTOR_DEBUG) console.error('[PromptDirector permissions] start');
  try {
    const result = await execute(windowsCommand('WindowsPowerShell\\v1.0\\powershell.exe'), ['-NoLogo', '-NoProfile', '-NonInteractive', '-EncodedCommand', Buffer.from(script, 'utf16le').toString('base64')], {
      windowsHide: true, timeout: CONNECTOR_TIMEOUT_MS, killSignal: 'SIGKILL', env: { ...process.env, PROMPTDIRECTOR_PRIVATE_DIRECTORY: root }
    });
    if (process.env.PROMPTDIRECTOR_DEBUG) console.error(`[PromptDirector permissions] ${Date.now() - started}ms\n${result.stderr}`);
  } catch (error) {
    if (error.killed) throw Object.assign(new Error('Windows 连接目录权限检查超时(PowerShell 无响应),请稍后重试或检查安全软件是否拦截 PowerShell。'), { code: 'connector_timeout' });
    throw new Error('无法保护 Windows 连接目录,请确认目录属于当前用户且允许设置私有访问权限。');
  }
}
export function windowsLauncher(plan) {
  const quote = value => {
    if (/["\r\n]/u.test(value)) throw new Error('Windows 安装路径含无效字符。');
    return value.replaceAll('%', '%%');
  };
  return `@echo off\r\nsetlocal DisableDelayedExpansion\r\nchcp 65001 >nul\r\nset "PROMPTDIRECTOR_CONNECTOR_HOME=${quote(plan.root)}"\r\n"${quote(plan.node)}" "${quote(win32.join(plan.runtime, 'native-host.mjs'))}" %*\r\n`;
}
export async function registerWindowsHost(registration, { key = nativeRegistryKey, run = execute } = {}) {
  const script = `$ErrorActionPreference='Stop'
$p='Registry::'+$env:PROMPTDIRECTOR_REGISTRY_KEY.Replace('HKCU\\','HKEY_CURRENT_USER\\')
New-Item -Path $p -Force | Out-Null
Set-Item -LiteralPath $p -Value $env:PROMPTDIRECTOR_NATIVE_MANIFEST
if ((Get-Item -LiteralPath $p).GetValue('') -cne $env:PROMPTDIRECTOR_NATIVE_MANIFEST) { throw 'Chrome registration readback mismatch' }`;
  await run(windowsCommand('WindowsPowerShell\\v1.0\\powershell.exe'), ['-NoLogo', '-NoProfile', '-NonInteractive', '-EncodedCommand', Buffer.from(script, 'utf16le').toString('base64')], {
    windowsHide: true, env: { ...process.env, PROMPTDIRECTOR_REGISTRY_KEY: key, PROMPTDIRECTOR_NATIVE_MANIFEST: registration }
  });
}