@dev-anywhere/proxy 0.9.8 → 0.9.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (39) hide show
  1. package/dist/{autostart-6DMQS43N.js → autostart-RRSXYZND.js} +97 -36
  2. package/dist/autostart-RRSXYZND.js.map +1 -0
  3. package/dist/{chunk-7EOSTWVO.js → chunk-4EIUH7CQ.js} +2 -2
  4. package/dist/{chunk-HEXGO236.js → chunk-E2S3REKI.js} +2 -2
  5. package/dist/chunk-G4QN6LOR.js +149 -0
  6. package/dist/chunk-G4QN6LOR.js.map +1 -0
  7. package/dist/{chunk-QZJBIFGW.js → chunk-UEIKYXS7.js} +2 -2
  8. package/dist/{chunk-AZ5MTPUR.js → chunk-VYAEW7G6.js} +2 -2
  9. package/dist/{chunk-JRSPTWQB.js → chunk-WTCJIDDT.js} +12 -1
  10. package/dist/chunk-WTCJIDDT.js.map +1 -0
  11. package/dist/{chunk-DEL6NNYV.js → chunk-YNDDXMND.js} +2 -2
  12. package/dist/{chunk-MPW6H537.js → chunk-Z2KUJ6SW.js} +3 -3
  13. package/dist/index.js +8 -8
  14. package/dist/{logger-2EQWS3V2.js → logger-6MR4NSOC.js} +2 -2
  15. package/dist/preview-worker.js +2 -2
  16. package/dist/{relay-token-SK3OOH2H.js → relay-token-KHOXKEF2.js} +3 -3
  17. package/dist/serve.js +7 -6
  18. package/dist/serve.js.map +1 -1
  19. package/dist/{service-host-YEX4IBZO.js → service-host-FAPIR5IX.js} +4 -4
  20. package/dist/session-worker.js +1 -1
  21. package/dist/{terminal-H6DLED7O.js → terminal-7ZS7U6OX.js} +7 -7
  22. package/dist/terminal-worker.js +7 -7
  23. package/dist/update-runner.js +135 -41
  24. package/dist/update-runner.js.map +1 -1
  25. package/package.json +3 -3
  26. package/dist/autostart-6DMQS43N.js.map +0 -1
  27. package/dist/chunk-77QVUYU7.js +0 -42
  28. package/dist/chunk-77QVUYU7.js.map +0 -1
  29. package/dist/chunk-JRSPTWQB.js.map +0 -1
  30. /package/dist/{chunk-7EOSTWVO.js.map → chunk-4EIUH7CQ.js.map} +0 -0
  31. /package/dist/{chunk-HEXGO236.js.map → chunk-E2S3REKI.js.map} +0 -0
  32. /package/dist/{chunk-QZJBIFGW.js.map → chunk-UEIKYXS7.js.map} +0 -0
  33. /package/dist/{chunk-AZ5MTPUR.js.map → chunk-VYAEW7G6.js.map} +0 -0
  34. /package/dist/{chunk-DEL6NNYV.js.map → chunk-YNDDXMND.js.map} +0 -0
  35. /package/dist/{chunk-MPW6H537.js.map → chunk-Z2KUJ6SW.js.map} +0 -0
  36. /package/dist/{logger-2EQWS3V2.js.map → logger-6MR4NSOC.js.map} +0 -0
  37. /package/dist/{relay-token-SK3OOH2H.js.map → relay-token-KHOXKEF2.js.map} +0 -0
  38. /package/dist/{service-host-YEX4IBZO.js.map → service-host-FAPIR5IX.js.map} +0 -0
  39. /package/dist/{terminal-H6DLED7O.js.map → terminal-7ZS7U6OX.js.map} +0 -0
@@ -7,18 +7,18 @@ import {
7
7
  } from "./chunk-5OARBB2B.js";
8
8
  import {
9
9
  createProfileServiceLifecycle
10
- } from "./chunk-MPW6H537.js";
10
+ } from "./chunk-Z2KUJ6SW.js";
11
11
  import {
12
12
  requestServiceHost
13
- } from "./chunk-DEL6NNYV.js";
14
- import "./chunk-AZ5MTPUR.js";
13
+ } from "./chunk-YNDDXMND.js";
14
+ import "./chunk-VYAEW7G6.js";
15
15
  import {
16
16
  IS_DEV,
17
17
  resolveTopLevelScript
18
18
  } from "./chunk-AS7W2D2X.js";
19
19
  import "./chunk-3NUN2VYO.js";
20
20
  import "./chunk-CFO5GU5U.js";
21
- import "./chunk-77QVUYU7.js";
21
+ import "./chunk-G4QN6LOR.js";
22
22
  import "./chunk-ZRCMGVGT.js";
23
23
  import {
24
24
  quoteWindowsArgument
@@ -337,7 +337,13 @@ import { win32 as win323 } from "path";
337
337
  var WINDOWS_SERVICE_POWERSHELL_PREAMBLE = `$ErrorActionPreference = 'Stop';
338
338
  $env:PSModulePath = $PSHOME + '\\Modules';
339
339
  $ProgressPreference = 'SilentlyContinue';
340
- [Console]::OutputEncoding = [Text.UTF8Encoding]::new($false);`;
340
+ [Console]::OutputEncoding = [Text.UTF8Encoding]::new($false);
341
+ function Get-DevAnywhereAccountSid([string]$Name) {
342
+ # SCM abbreviates the local machine as a dot; NTAccount needs the actual machine name.
343
+ if ($Name.StartsWith('.\\')) { $Name = [Environment]::MachineName + $Name.Substring(1); }
344
+ $account = New-Object Security.Principal.NTAccount($Name);
345
+ return $account.Translate([Security.Principal.SecurityIdentifier]).Value;
346
+ }`;
341
347
  function encoded(value) {
342
348
  return `Decode("${Buffer.from(checkAutostartText(value), "utf8").toString("base64")}")`;
343
349
  }
@@ -448,36 +454,81 @@ if (!(Test-Path -LiteralPath $servicePath -PathType Leaf)) {
448
454
  function windowsServiceRegistration(label, binaryPath) {
449
455
  return `$binaryPath = ${psString(quoteWindowsArgument(binaryPath))};
450
456
  if ($service) {
451
- $account = New-Object Security.Principal.NTAccount($service.StartName);
452
- if ($account.Translate([Security.Principal.SecurityIdentifier]).Value -ne $ownerSid) { throw 'Existing service belongs to another account'; }
457
+ if ((Get-DevAnywhereAccountSid $service.StartName) -ne $ownerSid) { throw 'Existing service belongs to another account'; }
453
458
  $result = Invoke-CimMethod -InputObject $service -MethodName Change -Arguments @{ PathName = $binaryPath; StartMode = 'Automatic' };
454
459
  if ($result.ReturnValue -ne 0) { throw ('Service update failed: ' + $result.ReturnValue); }
455
460
  } else {
456
- $credential = Get-Credential -UserName $ownerName -Message 'DEV Anywhere: enter this Windows account password for startup before desktop login (not the Windows Hello PIN)';
457
- if (!$credential) { throw 'Service installation cancelled'; }
458
- $account = New-Object Security.Principal.NTAccount($credential.UserName);
459
- if ($account.Translate([Security.Principal.SecurityIdentifier]).Value -ne $ownerSid) { throw 'Use the same account that owns this DEV Anywhere profile'; }
460
461
  Add-Type -AssemblyName System.ServiceProcess;
461
462
  Add-Type -AssemblyName System.Configuration.Install;
462
- $processInstaller = New-Object System.ServiceProcess.ServiceProcessInstaller;
463
- $processInstaller.Account = [System.ServiceProcess.ServiceAccount]::User;
464
- $processInstaller.Username = $ownerName;
465
- $processInstaller.Password = $credential.GetNetworkCredential().Password;
466
- $installer = New-Object System.ServiceProcess.ServiceInstaller;
467
- $installer.ServiceName = ${psString(label)};
468
- $installer.DisplayName = ${psString(`DEV Anywhere (${label})`)};
469
- $installer.Description = 'DEV Anywhere Proxy: run before desktop login as the profile owner';
470
- $installer.StartType = [System.ServiceProcess.ServiceStartMode]::Automatic;
471
- $processInstaller.Installers.Add($installer) | Out-Null;
472
- $processInstaller.Context = New-Object System.Configuration.Install.InstallContext($null, @('/LogToConsole=false'));
473
- $processInstaller.Context.Parameters['assemblypath'] = $binaryPath;
474
- $state = @{};
475
- try {
476
- # ServiceProcessInstaller grants SeServiceLogonRight and rolls it back on failed installation.
477
- $processInstaller.Install($state);
478
- $processInstaller.Commit($state);
479
- } catch { $processInstaller.Rollback($state); throw; }
480
- finally { $processInstaller.Password = $null; $credential = $null; }
463
+ Add-Type -ReferencedAssemblies 'System.dll','System.Configuration.Install.dll' -TypeDefinition @'
464
+ using System;
465
+ using System.Collections;
466
+ using System.ComponentModel;
467
+ using System.Configuration.Install;
468
+ using System.Runtime.InteropServices;
469
+ public sealed class DevAnywhereCredentialValidator : Installer {
470
+ public string Username { get; set; }
471
+ public string Password { get; set; }
472
+ public int LogonError { get; private set; }
473
+ [DllImport("advapi32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
474
+ private static extern bool LogonUser(string user, string domain, string password, int type, int provider, out IntPtr token);
475
+ [DllImport("kernel32.dll")]
476
+ private static extern bool CloseHandle(IntPtr handle);
477
+ public override void Install(IDictionary stateSaver) {
478
+ base.Install(stateSaver);
479
+ int separator = Username.IndexOf((char)92);
480
+ string domain = separator < 0 ? null : Username.Substring(0, separator);
481
+ string user = separator < 0 ? Username : Username.Substring(separator + 1);
482
+ IntPtr token;
483
+ // Validate the same service logon that SCM will use, after the parent grants its logon right.
484
+ if (!LogonUser(user, domain, Password, 5, 0, out token)) {
485
+ LogonError = Marshal.GetLastWin32Error();
486
+ throw new Win32Exception(LogonError);
487
+ }
488
+ CloseHandle(token);
489
+ }
490
+ }
491
+ '@;
492
+ while ($true) {
493
+ $credential = Get-Credential -UserName $ownerName -Message 'DEV Anywhere: enter this account password (Microsoft account password if applicable, not the Windows Hello PIN). Windows will verify it before installation.';
494
+ if (!$credential) { throw 'Service installation cancelled'; }
495
+ if ((Get-DevAnywhereAccountSid $credential.UserName) -ne $ownerSid) { throw 'Use the same account that owns this DEV Anywhere profile'; }
496
+ $processInstaller = New-Object System.ServiceProcess.ServiceProcessInstaller;
497
+ $processInstaller.Account = [System.ServiceProcess.ServiceAccount]::User;
498
+ $processInstaller.Username = $ownerName;
499
+ $processInstaller.Password = $credential.GetNetworkCredential().Password;
500
+ $validator = New-Object DevAnywhereCredentialValidator;
501
+ $validator.Username = $ownerName;
502
+ $validator.Password = $processInstaller.Password;
503
+ $installer = New-Object System.ServiceProcess.ServiceInstaller;
504
+ $installer.ServiceName = ${psString(label)};
505
+ $installer.DisplayName = ${psString(`DEV Anywhere (${label})`)};
506
+ $installer.Description = 'DEV Anywhere Proxy: run before desktop login as the profile owner';
507
+ $installer.StartType = [System.ServiceProcess.ServiceStartMode]::Automatic;
508
+ $processInstaller.Installers.Add($validator) | Out-Null;
509
+ $processInstaller.Installers.Add($installer) | Out-Null;
510
+ $processInstaller.Context = New-Object System.Configuration.Install.InstallContext($null, @('/LogToConsole=false'));
511
+ $processInstaller.Context.Parameters['assemblypath'] = $binaryPath;
512
+ $state = @{};
513
+ try {
514
+ # ServiceProcessInstaller grants SeServiceLogonRight and rolls it back on failed installation.
515
+ $processInstaller.Install($state);
516
+ $processInstaller.Commit($state);
517
+ Write-Host 'Windows \u670D\u52A1\u8D26\u6237\u9A8C\u8BC1\u901A\u8FC7\u3002';
518
+ break;
519
+ } catch {
520
+ $processInstaller.Rollback($state);
521
+ if ($validator.LogonError -eq 1326) {
522
+ Write-Warning 'Windows \u672A\u63A5\u53D7\u8FD9\u4E2A\u8D26\u6237\u5BC6\u7801\uFF0C\u8BF7\u91CD\u65B0\u8F93\u5165\u3002\u5FAE\u8F6F\u8D26\u6237\u9700\u586B\u5199\u5FAE\u8F6F\u8D26\u6237\u5BC6\u7801\uFF0C\u4E0D\u80FD\u4F7F\u7528 PIN\uFF1B\u53D6\u6D88\u51ED\u636E\u7A97\u53E3\u53EF\u9000\u51FA\u3002';
523
+ continue;
524
+ }
525
+ throw;
526
+ } finally {
527
+ $processInstaller.Password = $null;
528
+ $validator.Password = $null;
529
+ $credential = $null;
530
+ }
531
+ }
481
532
  }`;
482
533
  }
483
534
 
@@ -586,8 +637,7 @@ try {
586
637
  $ownerSid = ${psString(owner.sid)};
587
638
  ${lookup}
588
639
  if ($service) {
589
- $account = New-Object Security.Principal.NTAccount($service.StartName);
590
- if ($account.Translate([Security.Principal.SecurityIdentifier]).Value -ne $ownerSid) { throw 'Existing service belongs to another account'; }
640
+ if ((Get-DevAnywhereAccountSid $service.StartName) -ne $ownerSid) { throw 'Existing service belongs to another account'; }
591
641
  }
592
642
  ${script}
593
643
  } catch {
@@ -723,7 +773,18 @@ ${windowsServiceRegistration(label, wrapper.path)}`
723
773
  if (platform === "win32") {
724
774
  await windowsMutation(
725
775
  `if (!$service) { throw 'System service is not installed'; }
726
- Start-Service -Name ${psString(label)};`
776
+ try { Start-Service -Name ${psString(label)}; }
777
+ catch {
778
+ $failure = $_.Exception;
779
+ while ($failure.InnerException) { $failure = $failure.InnerException; }
780
+ if ($failure -is [ComponentModel.Win32Exception]) {
781
+ if ($failure.NativeErrorCode -eq 1069) {
782
+ throw 'Windows \u670D\u52A1\u8D26\u6237\u767B\u5F55\u5931\u8D25\uFF08\u9519\u8BEF 1069\uFF09\u3002\u8BF7\u5728 services.msc \u4E2D\u68C0\u67E5\u6B64\u670D\u52A1\u7684\u8D26\u6237\u5BC6\u7801\u548C\u767B\u5F55\u6743\u9650\uFF1BWindows Hello PIN \u4E0D\u80FD\u7528\u4F5C\u670D\u52A1\u5BC6\u7801\u3002';
783
+ }
784
+ throw ('Windows service could not start (error ' + $failure.NativeErrorCode + '): ' + $failure.Message);
785
+ }
786
+ throw;
787
+ }`
727
788
  );
728
789
  } else if (platform === "darwin") {
729
790
  requireUser();
@@ -838,7 +899,7 @@ async function startAutostartService(daemon, system = false) {
838
899
  }
839
900
  if (system) {
840
901
  if (daemon) throw new Error("The system service host must remain in the foreground");
841
- const { startSystemServiceHost } = await import("./service-host-YEX4IBZO.js");
902
+ const { startSystemServiceHost } = await import("./service-host-FAPIR5IX.js");
842
903
  await startSystemServiceHost();
843
904
  return;
844
905
  }
@@ -850,7 +911,7 @@ async function startAutostartService(daemon, system = false) {
850
911
  await startService();
851
912
  });
852
913
  } catch (error) {
853
- const { serviceLogger } = await import("./logger-2EQWS3V2.js");
914
+ const { serviceLogger } = await import("./logger-6MR4NSOC.js");
854
915
  const { flushLogger } = await import("./logger-24TGGN76.js");
855
916
  serviceLogger.error({ err: getErrorMessage(error) }, "Proxy automatic startup failed");
856
917
  await flushLogger(serviceLogger);
@@ -861,4 +922,4 @@ export {
861
922
  runAutostartCommand,
862
923
  startAutostartService
863
924
  };
864
- //# sourceMappingURL=autostart-6DMQS43N.js.map
925
+ //# sourceMappingURL=autostart-RRSXYZND.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/autostart.ts","../src/common/service-autostart.ts","../src/common/windows-autostart-launcher.ts","../src/common/autostart-definition.ts","../src/common/system-service-autostart.ts","../src/common/windows-service.ts","../src/common/autostart-mode.ts"],"sourcesContent":["import { homedir, userInfo } from \"node:os\";\nimport { fileURLToPath } from \"node:url\";\nimport { setTimeout as sleep } from \"node:timers/promises\";\nimport { IS_DEV, resolveTopLevelScript } from \"./common/env.js\";\nimport { isInitialized, PROFILE_NAME, SERVICE_HOST_PATH } from \"./common/paths.js\";\nimport { createServiceAutostart } from \"./common/service-autostart.js\";\nimport { createSystemServiceAutostart } from \"./common/system-service-autostart.js\";\nimport { switchAutostartMode } from \"./common/autostart-mode.js\";\nimport { requestServiceHost } from \"./common/service-host-control.js\";\nimport { createProfileServiceLifecycle } from \"./common/profile-service.js\";\nimport { refreshLoginShellPath } from \"./common/login-shell-path.js\";\nimport { getErrorMessage } from \"./common/process-probe.js\";\n\nexport async function runAutostartCommand(\n action: \"enable\" | \"disable\" | \"status\",\n options: { system?: boolean; now?: boolean } = {},\n): Promise<void> {\n try {\n if (options.now && (action !== \"enable\" || !options.system))\n throw new Error(\"--now requires autostart enable --system\");\n if (action === \"enable\" && !isInitialized()) {\n throw new Error('Dev Anywhere is not initialized. Run \"dev-anywhere init\" first.');\n }\n const entry = `${fileURLToPath(resolveTopLevelScript(\"index\"))}${IS_DEV ? \".ts\" : \".js\"}`;\n const account = userInfo();\n const settings = {\n platform: process.platform,\n home: homedir(),\n profile: PROFILE_NAME,\n executable: process.execPath,\n args: IS_DEV ? [\"--import\", import.meta.resolve(\"tsx\"), entry] : [entry],\n env: { ...process.env, SHELL: process.env.SHELL ?? account.shell ?? undefined },\n uid: process.getuid?.(),\n username: account.username,\n };\n const login = createServiceAutostart(settings);\n const system = createSystemServiceAutostart(settings);\n const autostart = options.system ? system : login;\n if (action === \"status\") {\n console.log(\n `${PROFILE_NAME}: ${(await autostart.status()) ? (options.system ? \"已设置开机自动启动(无需桌面登录)\" : \"已设置登录后自动启动\") : \"未设置此模式的自动启动\"}`,\n );\n if (options.system) {\n const host = await requestServiceHost(SERVICE_HOST_PATH, PROFILE_NAME, { action: \"probe\" });\n console.log(\n `Service: ${system.label}; ${host?.status === \"host\" ? `running (PID ${host.pid})` : \"not running\"}`,\n );\n }\n return;\n }\n if (action === \"enable\") await switchAutostartMode(autostart, options.system ? login : system);\n else await autostart.disable();\n if (options.now) {\n const wasRunning = await requestServiceHost(SERVICE_HOST_PATH, PROFILE_NAME, {\n action: \"probe\",\n });\n await system.activate();\n const deadline = Date.now() + 30_000;\n let ready = false;\n while (Date.now() < deadline) {\n const result = await requestServiceHost(SERVICE_HOST_PATH, PROFILE_NAME, {\n action: wasRunning ? \"restart\" : \"start\",\n intent: \"explicit\",\n });\n if (result?.status === \"failed\") throw new Error(result.message);\n if (result?.status === \"ready\") {\n ready = true;\n break;\n }\n await sleep(150);\n }\n if (!ready)\n throw new Error(\n \"System service is registered, but did not become ready; check the OS service status\",\n );\n }\n console.log(\n action === \"enable\"\n ? options.system\n ? `${PROFILE_NAME}: 已设置开机自动启动(无需桌面登录)。${options.now ? \"Proxy 已启动;新建会话可在退出桌面后继续使用。\" : \"下次开机生效;立即启动请加 --now。\"}`\n : `${PROFILE_NAME}: 已设置登录后自动启动,当前 Proxy 不受影响。`\n : `${PROFILE_NAME}: 已取消自动启动,当前 Proxy 不受影响。`,\n );\n } catch (error) {\n console.error(getErrorMessage(error));\n process.exitCode = 1;\n }\n}\n\n/** System login triggers enter the same lifecycle controller as manual CLI commands. */\nexport async function startAutostartService(daemon: boolean, system = false): Promise<void> {\n try {\n if (!isInitialized()) throw new Error(\"Proxy configuration is missing\");\n if (process.platform !== \"win32\") {\n const refreshed = await refreshLoginShellPath({\n env: { ...process.env, SHELL: process.env.SHELL ?? userInfo().shell ?? undefined },\n });\n if (refreshed.path !== undefined) process.env.PATH = refreshed.path;\n }\n if (system) {\n if (daemon) throw new Error(\"The system service host must remain in the foreground\");\n const { startSystemServiceHost } = await import(\"./service-host.js\");\n await startSystemServiceHost();\n return;\n }\n const lifecycle = createProfileServiceLifecycle();\n if (daemon) await lifecycle.start(\"explicit\");\n else\n await lifecycle.startForeground(async () => {\n const { startService } = await import(\"./serve.js\");\n await startService();\n });\n } catch (error) {\n const { serviceLogger } = await import(\"./common/logger.js\");\n const { flushLogger } = await import(\"@dev-anywhere/shared/logger\");\n serviceLogger.error({ err: getErrorMessage(error) }, \"Proxy automatic startup failed\");\n await flushLogger(serviceLogger);\n process.exit(1);\n }\n}\n","import { execFile } from \"node:child_process\";\nimport { mkdir, writeFile } from \"node:fs/promises\";\nimport { dirname, join, win32 } from \"node:path\";\nimport { promisify } from \"node:util\";\nimport { buildWindowsAutostartLauncher } from \"./windows-autostart-launcher.js\";\nimport {\n autostartLabel,\n checkAutostartText as checkText,\n xmlString as xml,\n unitValue,\n unitString,\n psString,\n readIfPresent,\n removeIfPresent,\n type AutostartOptions,\n} from \"./autostart-definition.js\";\n\nfunction encodePowerShell(script: string): string {\n return Buffer.from(script, \"utf16le\").toString(\"base64\");\n}\n\nconst execFileAsync = promisify(execFile);\n\n/** Registers a login trigger, not another process supervisor. Enabling never restarts a Proxy. */\nexport function createServiceAutostart(options: AutostartOptions) {\n const { platform, home, profile, executable, env } = options;\n if (![\"darwin\", \"linux\", \"win32\"].includes(platform)) {\n throw new Error(`Proxy autostart is not supported on ${platform}`);\n }\n const label = autostartLabel(home, profile);\n const args = [...options.args, \"--profile\", profile, \"serve\", \"autostart\", \"run\"];\n const run =\n options.run ??\n (async (command: string, commandArgs: string[]) => {\n const result = await execFileAsync(command, commandArgs, {\n timeout: 15_000,\n maxBuffer: 256 * 1024,\n windowsHide: true,\n encoding: \"utf8\",\n });\n return result.stdout;\n });\n const powershell = win32.join(\n env.SystemRoot ?? env.SYSTEMROOT ?? \"C:\\\\Windows\",\n \"System32\",\n \"WindowsPowerShell\",\n \"v1.0\",\n \"powershell.exe\",\n );\n const runPowerShell = (script: string) =>\n run(powershell, [\n \"-NoProfile\",\n \"-NonInteractive\",\n \"-EncodedCommand\",\n encodePowerShell(`$ErrorActionPreference = 'Stop';\\n${script}`),\n ]);\n const taskLookup = `$task = Get-ScheduledTask -ErrorAction Stop | Where-Object { $_.TaskPath -eq '\\\\' -and $_.TaskName -eq ${psString(label)} };`;\n const unit = `${label}.service`;\n const filePath =\n platform === \"darwin\"\n ? join(home, \"Library\", \"LaunchAgents\", `${label}.plist`)\n : join(env.XDG_CONFIG_HOME || join(home, \".config\"), \"systemd\", \"user\", unit);\n const domain = `gui/${options.uid}`;\n const launchdTarget = `${domain}/${label}`;\n\n const environment = {\n HOME: checkText(home),\n ...Object.fromEntries(\n [\"PATH\", \"SHELL\"].flatMap((key) => (env[key] ? [[key, checkText(env[key]!)]] : [])),\n ),\n };\n\n function definition(): string {\n if (platform === \"darwin\") {\n return `<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">\n<plist version=\"1.0\"><dict>\n<key>Label</key><string>${xml(label)}</string>\n<key>ProgramArguments</key><array>${[executable, ...args].map((arg) => `<string>${xml(arg)}</string>`).join(\"\")}</array>\n<key>WorkingDirectory</key><string>${xml(home)}</string>\n<key>EnvironmentVariables</key><dict>${Object.entries(environment)\n .map(([key, value]) => `<key>${xml(key)}</key><string>${xml(value)}</string>`)\n .join(\"\")}</dict>\n<key>RunAtLoad</key><true/>\n<key>KeepAlive</key><false/>\n</dict></plist>\n`;\n }\n // Keep the unit active after the short-lived start command exits. Otherwise systemd would\n // terminate the detached Proxy (and its updater) along with that command's control group.\n return `[Unit]\nDescription=DEV Anywhere Proxy (${checkText(profile)})\n\n[Service]\nType=oneshot\nRemainAfterExit=yes\nRestart=no\nWorkingDirectory=${unitValue(home)}\n${Object.entries(environment)\n .map(([key, value]) => `Environment=${unitString(`${key}=${value}`)}`)\n .join(\"\\n\")}\nExecStart=:${[executable, ...args, \"--daemon\"].map(unitString).join(\" \")}\nTimeoutStartSec=60\n\n[Install]\nWantedBy=default.target\n`;\n }\n\n function windowsTask(): string {\n const launcher = buildWindowsAutostartLauncher({ home, profile, executable, args });\n return `${launcher.compileScript}\n$user = [System.Security.Principal.WindowsIdentity]::GetCurrent().Name;\n$action = New-ScheduledTaskAction -Execute ${psString(launcher.path)} -WorkingDirectory ${psString(home)};\n$trigger = New-ScheduledTaskTrigger -AtLogOn -User $user;\n$principal = New-ScheduledTaskPrincipal -UserId $user -LogonType Interactive -RunLevel Limited;\n$settings = New-ScheduledTaskSettingsSet -AllowStartIfOnBatteries -DontStopIfGoingOnBatteries -ExecutionTimeLimit ([TimeSpan]::Zero) -MultipleInstances IgnoreNew -Priority 4;\nRegister-ScheduledTask -TaskPath '\\\\' -TaskName ${psString(label)} -Action $action -Trigger $trigger -Principal $principal -Settings $settings -Description 'DEV Anywhere Proxy: start at user login' -Force | Out-Null;`;\n }\n\n async function status(): Promise<boolean> {\n if (platform === \"win32\") {\n const output = await runPowerShell(\n `${taskLookup}\\n[bool]($task -and $task.Settings.Enabled) | ConvertTo-Json -Compress;`,\n );\n const enabled: unknown = JSON.parse(output.trim());\n if (typeof enabled !== \"boolean\") throw new Error(\"Invalid Windows autostart status\");\n return enabled;\n }\n if ((await readIfPresent(filePath)) === null) return false;\n if (platform === \"darwin\") {\n if (options.uid === undefined) throw new Error(\"Cannot determine the current macOS user\");\n const output = await run(\"/bin/launchctl\", [\"print-disabled\", domain]);\n return !output.includes(`\"${label}\" => true`);\n }\n const output = await run(\"systemctl\", [\n \"--user\",\n \"show\",\n unit,\n \"--property=UnitFileState\",\n \"--value\",\n ]);\n return output.trim() === \"enabled\";\n }\n\n async function enable(): Promise<void> {\n if (platform === \"win32\") {\n await runPowerShell(windowsTask());\n return;\n }\n if (platform === \"darwin\" && options.uid === undefined) {\n throw new Error(\"Cannot determine the current macOS user\");\n }\n const content = definition();\n await mkdir(dirname(filePath), { recursive: true });\n const previous = await readIfPresent(filePath);\n await writeFile(filePath, content, { mode: 0o600 });\n try {\n if (platform === \"darwin\") {\n // No bootstrap/kickstart: registration takes effect at the next login, without touching\n // a running Proxy. An existing system-disabled override must not defeat re-enabling.\n await run(\"/bin/launchctl\", [\"enable\", launchdTarget]);\n } else {\n await run(\"systemctl\", [\"--user\", \"daemon-reload\"]);\n await run(\"systemctl\", [\"--user\", \"enable\", unit]);\n }\n } catch (error) {\n if (previous === null) await removeIfPresent(filePath);\n else await writeFile(filePath, previous, { mode: 0o600 });\n throw error;\n }\n }\n\n async function disable(): Promise<void> {\n if (platform === \"win32\") {\n await runPowerShell(\n `${taskLookup}\\nif ($task) { $task | Unregister-ScheduledTask -Confirm:$false; }`,\n );\n return;\n }\n if ((await readIfPresent(filePath)) === null) return;\n if (platform === \"darwin\") {\n if (options.uid === undefined) throw new Error(\"Cannot determine the current macOS user\");\n await run(\"/bin/launchctl\", [\"disable\", launchdTarget]);\n } else {\n await run(\"systemctl\", [\"--user\", \"disable\", unit]);\n }\n await removeIfPresent(filePath);\n if (platform === \"linux\") await run(\"systemctl\", [\"--user\", \"daemon-reload\"]);\n // Never bootout, stop, or unregister with process termination: disabling only affects login.\n }\n\n return { enable, disable, status };\n}\n","import { createHash } from \"node:crypto\";\nimport { win32 } from \"node:path\";\nimport { quoteWindowsArgument } from \"./command-launch.js\";\nimport { buildProxyProfilePaths } from \"./paths.js\";\n\nfunction encodedString(value: string): string {\n if ([...value].some((char) => char.charCodeAt(0) <= 31 || char.charCodeAt(0) === 127)) {\n throw new Error(\"Autostart paths and environment must not contain control characters\");\n }\n return `Decode(\"${Buffer.from(value, \"utf8\").toString(\"base64\")}\")`;\n}\n\n/** Compile only during registration; the task runs this GUI executable, never PowerShell. */\nexport function buildWindowsAutostartLauncher(options: {\n home: string;\n profile: string;\n executable: string;\n args: readonly string[];\n}): { path: string; logPath: string; source: string; compileScript: string } {\n const paths = buildProxyProfilePaths(options.home, options.profile, \"win32\");\n const logPath = win32.join(paths.logDir, \"autostart-launcher.log\");\n const source = `using System;\nusing System.Diagnostics;\nusing System.IO;\nusing System.Text;\n\ninternal static class DevAnywhereAutostart {\n private static StreamWriter log;\n private static volatile bool logFailed;\n private static string Decode(string value) { return Encoding.UTF8.GetString(Convert.FromBase64String(value)); }\n private static void WriteLog(string stream, string message) {\n if (message == null) return;\n try { lock (log) { log.WriteLine(DateTime.UtcNow.ToString(\"o\") + \" \" + stream + \": \" + message); } }\n catch { logFailed = true; } // Keep draining output; report logging failures through the task exit code.\n }\n public static int Main() {\n try {\n string logPath = ${encodedString(logPath)};\n Directory.CreateDirectory(Path.GetDirectoryName(logPath));\n using (log = new StreamWriter(new FileStream(logPath, FileMode.Append, FileAccess.Write, FileShare.ReadWrite), new UTF8Encoding(false))) {\n log.AutoFlush = true;\n try {\n var info = new ProcessStartInfo();\n info.FileName = ${encodedString(options.executable)};\n info.Arguments = ${encodedString(options.args.map(quoteWindowsArgument).join(\" \"))};\n info.WorkingDirectory = ${encodedString(options.home)};\n info.EnvironmentVariables[\"USERPROFILE\"] = ${encodedString(options.home)};\n info.EnvironmentVariables[\"HOME\"] = ${encodedString(options.home)};\n info.UseShellExecute = false;\n info.CreateNoWindow = true;\n info.RedirectStandardInput = true;\n info.RedirectStandardOutput = true;\n info.RedirectStandardError = true;\n info.StandardOutputEncoding = Encoding.UTF8;\n info.StandardErrorEncoding = Encoding.UTF8;\n using (var child = new Process()) {\n child.StartInfo = info;\n child.OutputDataReceived += (sender, e) => WriteLog(\"stdout\", e.Data);\n child.ErrorDataReceived += (sender, e) => WriteLog(\"stderr\", e.Data);\n child.Start();\n child.StandardInput.Close();\n child.BeginOutputReadLine();\n child.BeginErrorReadLine();\n child.WaitForExit();\n return child.ExitCode != 0 ? child.ExitCode : (logFailed ? 1 : 0);\n }\n } catch (Exception error) { WriteLog(\"launcher\", error.ToString()); return 1; }\n }\n } catch { return 1; } // An unwritable log directory is also a failed task, not a silent success.\n }\n}\n`;\n const digest = createHash(\"sha256\").update(source).digest(\"hex\").slice(0, 20);\n const path = win32.join(paths.profileDir, \"autostart\", `launcher-${digest}.exe`);\n // The source contains only encoded paths/argv, not credentials or a snapshot of the user's env.\n const sourceBase64 = Buffer.from(source, \"utf8\").toString(\"base64\");\n const compileScript = `$launcherPath = '${path.replaceAll(\"'\", \"''\")}';\nif (!(Test-Path -LiteralPath $launcherPath -PathType Leaf)) {\n [System.IO.Directory]::CreateDirectory([System.IO.Path]::GetDirectoryName($launcherPath)) | Out-Null;\n $candidate = $launcherPath + '.' + [guid]::NewGuid().ToString('N') + '.tmp.exe';\n try {\n $source = [System.Text.Encoding]::UTF8.GetString([Convert]::FromBase64String('${sourceBase64}'));\n Add-Type -TypeDefinition $source -OutputAssembly $candidate -OutputType WindowsApplication -ErrorAction Stop;\n Move-Item -LiteralPath $candidate -Destination $launcherPath -ErrorAction Stop;\n } finally {\n if (Test-Path -LiteralPath $candidate) { Remove-Item -LiteralPath $candidate -Force; }\n }\n}`;\n return { path, logPath, source, compileScript };\n}\n","import { createHash } from \"node:crypto\";\nimport { readFile, unlink } from \"node:fs/promises\";\n\nexport interface AutostartOptions {\n platform: NodeJS.Platform;\n home: string;\n profile: string;\n executable: string;\n args: string[];\n env: NodeJS.ProcessEnv;\n uid?: number;\n username?: string;\n run?: (command: string, args: string[]) => Promise<string>;\n}\n\nexport function autostartLabel(home: string, profile: string): string {\n return `dev-anywhere-${createHash(\"sha256\").update(`${home}\\0${profile}`).digest(\"hex\").slice(0, 20)}`;\n}\n\nexport function checkAutostartText(value: string): string {\n if ([...value].some((char) => char.charCodeAt(0) <= 31 || char.charCodeAt(0) === 127)) {\n throw new Error(\"Autostart paths and environment must not contain control characters\");\n }\n return value;\n}\n\nexport function xmlString(value: string): string {\n return checkAutostartText(value).replace(\n /[&<>\"']/g,\n (char) => ({ \"&\": \"&amp;\", \"<\": \"&lt;\", \">\": \"&gt;\", '\"': \"&quot;\", \"'\": \"&apos;\" })[char]!,\n );\n}\n\n/** Scalar directives such as User= and WorkingDirectory= do not remove shell quotes. */\nexport function unitValue(value: string): string {\n return checkAutostartText(value).replaceAll(\"%\", \"%%\");\n}\n\nexport function unitString(value: string): string {\n return `\"${unitValue(value).replaceAll(\"\\\\\", \"\\\\\\\\\").replaceAll('\"', '\\\\\"')}\"`;\n}\n\nexport function psString(value: string): string {\n return `'${checkAutostartText(value).replaceAll(\"'\", \"''\")}'`;\n}\n\nexport async function readIfPresent(path: string): Promise<string | null> {\n try {\n return await readFile(path, \"utf8\");\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === \"ENOENT\") return null;\n throw error;\n }\n}\n\nexport async function removeIfPresent(path: string): Promise<void> {\n try {\n await unlink(path);\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== \"ENOENT\") throw error;\n }\n}\n","import { execFile, spawn } from \"node:child_process\";\nimport { mkdtemp, mkdir, rm, writeFile } from \"node:fs/promises\";\nimport { tmpdir } from \"node:os\";\nimport { dirname, join, win32 } from \"node:path\";\nimport { promisify } from \"node:util\";\nimport { z } from \"zod\";\nimport {\n autostartLabel,\n checkAutostartText,\n psString,\n readIfPresent,\n removeIfPresent,\n unitValue,\n unitString,\n xmlString,\n type AutostartOptions,\n} from \"./autostart-definition.js\";\nimport { buildProxyProfilePaths } from \"./paths.js\";\nimport {\n buildWindowsService,\n windowsServiceRegistration,\n WINDOWS_SERVICE_POWERSHELL_PREAMBLE,\n} from \"./windows-service.js\";\n\nconst execFileAsync = promisify(execFile);\nasync function runCommand(command: string, args: string[]): Promise<string> {\n const result = await execFileAsync(command, args, {\n windowsHide: true,\n timeout: 15_000,\n maxBuffer: 256 * 1024,\n encoding: \"utf8\",\n });\n return result.stdout;\n}\nasync function runInteractive(command: string, args: string[]): Promise<string> {\n return new Promise((resolve, reject) => {\n const child = spawn(command, args, { stdio: \"inherit\", windowsHide: false });\n child.once(\"error\", reject);\n child.once(\"exit\", (code) =>\n code === 0\n ? resolve(\"\")\n : reject(\n new Error(`System service registration command exited with code ${code ?? \"unknown\"}`),\n ),\n );\n });\n}\n\nexport function createSystemServiceAutostart(\n options: AutostartOptions & {\n /** Interactive elevation/password prompts happen only during registration and activation. */\n runInteractive?: typeof runInteractive;\n /** An isolated directory for definition tests; production uses the OS-owned directory. */\n systemDirectory?: string;\n },\n) {\n const { platform, home, profile, executable, env } = options;\n if (![\"darwin\", \"linux\", \"win32\"].includes(platform))\n throw new Error(`System services are not supported on ${platform}`);\n const label = `${autostartLabel(home, profile)}-system`;\n const unit = `${label}.service`;\n const paths = buildProxyProfilePaths(home, profile, platform);\n const filePath = join(\n options.systemDirectory ??\n (platform === \"darwin\" ? \"/Library/LaunchDaemons\" : \"/etc/systemd/system\"),\n platform === \"darwin\" ? `${label}.plist` : unit,\n );\n const run = options.run ?? runCommand;\n const interactive = options.runInteractive ?? runInteractive;\n const args = [...options.args, \"--profile\", profile, \"serve\", \"autostart\", \"run\", \"--system\"];\n const environment: Record<string, string> = {\n HOME: checkAutostartText(home),\n ...(platform === \"win32\" ? { USERPROFILE: checkAutostartText(home) } : {}),\n ...Object.fromEntries(\n [\n \"PATH\",\n \"SHELL\",\n \"XDG_CONFIG_HOME\",\n ...(platform === \"win32\" ? [\"APPDATA\", \"LOCALAPPDATA\"] : []),\n ].flatMap((key) => (env[key] ? [[key, checkAutostartText(env[key]!)]] : [])),\n ),\n };\n const powershell = win32.join(\n env.SystemRoot ?? env.SYSTEMROOT ?? \"C:\\\\Windows\",\n \"System32\",\n \"WindowsPowerShell\",\n \"v1.0\",\n \"powershell.exe\",\n );\n const lookup = `$service = Get-CimInstance -ClassName Win32_Service -Filter ${psString(`Name='${label}'`)} -ErrorAction Stop;`;\n const powerShell = (script: string) =>\n run(powershell, [\n \"-NoProfile\",\n \"-NonInteractive\",\n \"-EncodedCommand\",\n Buffer.from(`${WINDOWS_SERVICE_POWERSHELL_PREAMBLE}\\n${script}`, \"utf16le\").toString(\n \"base64\",\n ),\n ]);\n const privileged = (command: string, commandArgs: string[]) =>\n interactive(\"/usr/bin/sudo\", [command, ...commandArgs]);\n const requireUser = () => {\n if (!options.uid || !options.username)\n throw new Error(\n \"Run system-service registration as your normal user; it requests sudo only for installation\",\n );\n checkAutostartText(options.username);\n };\n async function stage<T>(\n content: string,\n fn: (path: string) => Promise<T>,\n suffix = \"definition\",\n ): Promise<T> {\n const directory = await mkdtemp(join(tmpdir(), \"dev-anywhere-service-\"));\n const path = join(directory, suffix);\n try {\n await writeFile(path, content, { mode: 0o600 });\n return await fn(path);\n } finally {\n await rm(directory, { recursive: true, force: true });\n }\n }\n async function windowsMutation(script: string) {\n // Capture the profile owner's identity BEFORE UAC, which may use a different administrator.\n const owner = z\n .object({ name: z.string().min(1), sid: z.string().regex(/^S-1-/) })\n .parse(\n JSON.parse(\n await powerShell(\n \"$identity = [Security.Principal.WindowsIdentity]::GetCurrent(); @{ name = $identity.Name; sid = $identity.User.Value } | ConvertTo-Json -Compress;\",\n ),\n ),\n );\n const source = `param([switch]$Elevated)\n${WINDOWS_SERVICE_POWERSHELL_PREAMBLE}\n$principal = New-Object Security.Principal.WindowsPrincipal([Security.Principal.WindowsIdentity]::GetCurrent());\nif (!$principal.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)) {\n if ($Elevated) { throw 'Administrator privileges are required to install a system service'; }\n $child = Start-Process -FilePath ${psString(powershell)} -ArgumentList @('-NoProfile', '-ExecutionPolicy', 'Bypass', '-File', ('\"' + $PSCommandPath + '\"'), '-Elevated') -Verb RunAs -Wait -PassThru;\n exit $child.ExitCode;\n}\ntry {\n $ownerName = ${psString(owner.name)};\n $ownerSid = ${psString(owner.sid)};\n ${lookup}\n if ($service) {\n if ((Get-DevAnywhereAccountSid $service.StartName) -ne $ownerSid) { throw 'Existing service belongs to another account'; }\n }\n ${script}\n} catch {\n Write-Error $_ -ErrorAction Continue;\n if ($Elevated) { Read-Host 'Service operation failed. Press Enter to close this window' | Out-Null; }\n exit 1;\n}\n`;\n // A file avoids Windows' command-line length limit; it contains no password or tokens.\n await stage(\n `\\ufeff${source}`,\n (path) =>\n interactive(powershell, [\"-NoProfile\", \"-ExecutionPolicy\", \"Bypass\", \"-File\", path]),\n \"register.ps1\",\n );\n }\n function definition(): string {\n requireUser();\n const user = options.username!;\n const userEnv = { ...environment, USER: user, LOGNAME: user };\n if (platform === \"darwin\")\n return `<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">\n<plist version=\"1.0\"><dict>\n<key>Label</key><string>${xmlString(label)}</string>\n<key>UserName</key><string>${xmlString(user)}</string>\n<key>ProgramArguments</key><array>${[executable, ...args].map((arg) => `<string>${xmlString(arg)}</string>`).join(\"\")}</array>\n<key>WorkingDirectory</key><string>${xmlString(home)}</string>\n<key>EnvironmentVariables</key><dict>${Object.entries(userEnv)\n .map(([key, value]) => `<key>${xmlString(key)}</key><string>${xmlString(value)}</string>`)\n .join(\"\")}</dict>\n<key>RunAtLoad</key><true/>\n<key>KeepAlive</key><false/>\n<key>ExitTimeOut</key><integer>120</integer>\n</dict></plist>\n`;\n return `[Unit]\nDescription=DEV Anywhere system service (${checkAutostartText(profile)})\nWants=network-online.target\nAfter=network-online.target\nRequiresMountsFor=${unitString(home)}\n\n[Service]\nType=simple\nUser=${unitValue(user)}\nWorkingDirectory=${unitValue(home)}\n${Object.entries(userEnv)\n .map(([key, value]) => `Environment=${unitString(`${key}=${value}`)}`)\n .join(\"\\n\")}\nExecStart=:${[executable, ...args].map(unitString).join(\" \")}\nRestart=no\nTimeoutStopSec=120\n\n[Install]\nWantedBy=multi-user.target\n`;\n }\n const install = (source: string) =>\n privileged(\"/usr/bin/install\", [\n \"-o\",\n \"root\",\n \"-g\",\n platform === \"darwin\" ? \"wheel\" : \"root\",\n \"-m\",\n \"644\",\n source,\n filePath,\n ]);\n async function status(): Promise<boolean> {\n if (platform === \"win32\") {\n return z\n .boolean()\n .parse(\n JSON.parse(\n (\n await powerShell(\n `${lookup}\\n[bool]($service -and $service.StartMode -eq 'Auto') | ConvertTo-Json -Compress;`,\n )\n ).trim(),\n ),\n );\n }\n if ((await readIfPresent(filePath)) === null) return false;\n if (platform === \"darwin\")\n return !(await run(\"/bin/launchctl\", [\"print-disabled\", \"system\"])).includes(\n `\"${label}\" => true`,\n );\n return (\n (\n await run(\"systemctl\", [\"--system\", \"show\", unit, \"--property=UnitFileState\", \"--value\"])\n ).trim() === \"enabled\"\n );\n }\n async function enable(): Promise<void> {\n if (platform === \"win32\") {\n const wrapper = buildWindowsService({\n home,\n profile,\n label,\n executable,\n args,\n env: environment,\n });\n await windowsMutation(\n `${wrapper.compileScript}\\n${windowsServiceRegistration(label, wrapper.path)}`,\n );\n } else {\n const content = definition();\n const previous = await readIfPresent(filePath);\n await stage(content, install);\n try {\n if (platform === \"darwin\")\n await privileged(\"/bin/launchctl\", [\"enable\", `system/${label}`]);\n else {\n await privileged(\"systemctl\", [\"--system\", \"daemon-reload\"]);\n await privileged(\"systemctl\", [\"--system\", \"enable\", unit]);\n }\n } catch (error) {\n if (previous === null) await privileged(\"/bin/rm\", [\"-f\", filePath]);\n else await stage(previous, install);\n if (platform === \"linux\") await privileged(\"systemctl\", [\"--system\", \"daemon-reload\"]);\n throw error;\n }\n }\n await mkdir(dirname(paths.systemAutostartPath), { recursive: true });\n await writeFile(paths.systemAutostartPath, `${label}\\n`, { mode: 0o600 });\n }\n async function disable(): Promise<void> {\n if (platform === \"win32\") {\n if (await status())\n await windowsMutation(`if ($service) {\n $result = Invoke-CimMethod -InputObject $service -MethodName ChangeStartMode -Arguments @{ StartMode = 'Disabled' };\n if ($result.ReturnValue -ne 0) { throw ('Service disable failed: ' + $result.ReturnValue); }\n}`);\n } else if ((await readIfPresent(filePath)) !== null) {\n requireUser();\n if (platform === \"darwin\") await privileged(\"/bin/launchctl\", [\"disable\", `system/${label}`]);\n else await privileged(\"systemctl\", [\"--system\", \"disable\", unit]);\n await privileged(\"/bin/rm\", [\"-f\", filePath]);\n if (platform === \"linux\") await privileged(\"systemctl\", [\"--system\", \"daemon-reload\"]);\n }\n await removeIfPresent(paths.systemAutostartPath);\n }\n async function activate(): Promise<void> {\n if (platform === \"win32\") {\n await windowsMutation(\n `if (!$service) { throw 'System service is not installed'; }\ntry { Start-Service -Name ${psString(label)}; }\ncatch {\n $failure = $_.Exception;\n while ($failure.InnerException) { $failure = $failure.InnerException; }\n if ($failure -is [ComponentModel.Win32Exception]) {\n if ($failure.NativeErrorCode -eq 1069) {\n throw 'Windows 服务账户登录失败(错误 1069)。请在 services.msc 中检查此服务的账户密码和登录权限;Windows Hello PIN 不能用作服务密码。';\n }\n throw ('Windows service could not start (error ' + $failure.NativeErrorCode + '): ' + $failure.Message);\n }\n throw;\n}`,\n );\n } else if (platform === \"darwin\") {\n requireUser();\n let loaded = false;\n try {\n await run(\"/bin/launchctl\", [\"print\", `system/${label}`]);\n loaded = true;\n } catch (error) {\n // launchctl uses ESRCH (3/113) for an unloaded service. Other failures must remain visible.\n if (![3, 113].includes(Number((error as { code?: unknown }).code))) throw error;\n }\n if (!loaded) await privileged(\"/bin/launchctl\", [\"bootstrap\", \"system\", filePath]);\n else await privileged(\"/bin/launchctl\", [\"kickstart\", `system/${label}`]);\n } else {\n requireUser();\n await privileged(\"systemctl\", [\"--system\", \"start\", unit]);\n }\n }\n return { label, filePath, enable, disable, status, activate };\n}\n","import { createHash } from \"node:crypto\";\nimport { win32 } from \"node:path\";\nimport { buildProxyProfilePaths } from \"./paths.js\";\nimport { quoteWindowsArgument } from \"./command-launch.js\";\nimport { checkAutostartText, psString } from \"./autostart-definition.js\";\n\n// A CLI launched from pwsh can inherit PowerShell 7 modules, incompatible with powershell.exe.\nexport const WINDOWS_SERVICE_POWERSHELL_PREAMBLE = `$ErrorActionPreference = 'Stop';\n$env:PSModulePath = $PSHOME + '\\\\Modules';\n$ProgressPreference = 'SilentlyContinue';\n[Console]::OutputEncoding = [Text.UTF8Encoding]::new($false);\nfunction Get-DevAnywhereAccountSid([string]$Name) {\n # SCM abbreviates the local machine as a dot; NTAccount needs the actual machine name.\n if ($Name.StartsWith('.\\\\')) { $Name = [Environment]::MachineName + $Name.Substring(1); }\n $account = New-Object Security.Principal.NTAccount($Name);\n return $account.Translate([Security.Principal.SecurityIdentifier]).Value;\n}`;\n\nfunction encoded(value: string): string {\n return `Decode(\"${Buffer.from(checkAutostartText(value), \"utf8\").toString(\"base64\")}\")`;\n}\n\n/** An SCM service, running as the user's account. Node itself does not implement ServiceMain. */\nexport function buildWindowsService(options: {\n home: string;\n profile: string;\n label: string;\n executable: string;\n args: string[];\n env: Record<string, string>;\n}) {\n const paths = buildProxyProfilePaths(options.home, options.profile, \"win32\");\n const logPath = win32.join(paths.logDir, \"system-service.log\");\n const source = `using System;\nusing System.Diagnostics;\nusing System.IO;\nusing System.ServiceProcess;\nusing System.Text;\nusing System.Threading;\n\npublic sealed class DevAnywhereService : ServiceBase {\n private Process child;\n private StreamWriter log;\n private volatile bool stopping;\n private static string Decode(string value) { return Encoding.UTF8.GetString(Convert.FromBase64String(value)); }\n public DevAnywhereService() {\n ServiceName = ${encoded(options.label)};\n CanStop = true; CanShutdown = true; AutoLog = false;\n }\n private void WriteLog(string stream, string message) {\n if (message == null || log == null) return;\n try { lock (log) { log.WriteLine(DateTime.UtcNow.ToString(\"o\") + \" \" + stream + \": \" + message); } }\n catch { } // Draining the child's pipes must continue even if its log disk fills.\n }\n private void StartChild() {\n string logPath = ${encoded(logPath)};\n Directory.CreateDirectory(Path.GetDirectoryName(logPath));\n log = new StreamWriter(new FileStream(logPath, FileMode.Append, FileAccess.Write, FileShare.ReadWrite), new UTF8Encoding(false));\n log.AutoFlush = true;\n var info = new ProcessStartInfo();\n info.FileName = ${encoded(options.executable)};\n info.Arguments = ${encoded(options.args.map(quoteWindowsArgument).join(\" \"))};\n info.WorkingDirectory = ${encoded(options.home)};\n ${Object.entries(options.env)\n .map(([key, value]) => `info.EnvironmentVariables[${encoded(key)}] = ${encoded(value)};`)\n .join(\"\\n \")}\n info.UseShellExecute = false;\n info.CreateNoWindow = true;\n info.RedirectStandardInput = true;\n info.RedirectStandardOutput = true;\n info.RedirectStandardError = true;\n info.StandardOutputEncoding = Encoding.UTF8;\n info.StandardErrorEncoding = Encoding.UTF8;\n child = new Process();\n child.StartInfo = info;\n child.OutputDataReceived += (sender, e) => WriteLog(\"stdout\", e.Data);\n child.ErrorDataReceived += (sender, e) => WriteLog(\"stderr\", e.Data);\n child.Start();\n child.BeginOutputReadLine();\n child.BeginErrorReadLine();\n }\n protected override void OnStart(string[] args) {\n StartChild();\n ThreadPool.QueueUserWorkItem(_ => {\n child.WaitForExit();\n if (!stopping) { ExitCode = child.ExitCode; Stop(); }\n });\n }\n private void StopChild(bool requestedStop) {\n stopping = true;\n if (child == null) return;\n if (!child.HasExited) {\n if (requestedStop) RequestAdditionalTime(120000);\n try { child.StandardInput.WriteLine(\"stop\"); child.StandardInput.Flush(); }\n catch (IOException) { }\n if (!child.WaitForExit(110000)) { child.Kill(); ExitCode = 1; }\n }\n }\n protected override void OnStop() { StopChild(true); }\n protected override void OnShutdown() { StopChild(false); }\n public static int Main(string[] args) {\n using (var service = new DevAnywhereService()) {\n // Native tests exercise the compiled process/pipe contract without installing an OS service.\n if (args.Length == 1 && (args[0] == \"--console-test\" || args[0] == \"--console-shutdown-test\")) {\n try {\n service.StartChild();\n ThreadPool.QueueUserWorkItem(_ => {\n Console.ReadLine();\n if (args[0] == \"--console-shutdown-test\") { service.OnShutdown(); return; }\n try { service.child.StandardInput.WriteLine(\"stop\"); service.child.StandardInput.Flush(); }\n catch (IOException) { }\n });\n service.child.WaitForExit();\n return service.child.ExitCode;\n } catch (Exception error) { service.WriteLog(\"host\", error.ToString()); return 1; }\n }\n ServiceBase.Run(service);\n return 0;\n }\n }\n}\n`;\n const digest = createHash(\"sha256\").update(source).digest(\"hex\").slice(0, 20);\n const path = win32.join(paths.profileDir, \"autostart\", `service-${digest}.exe`);\n const compileScript = `$servicePath = ${psString(path)};\nif (!(Test-Path -LiteralPath $servicePath -PathType Leaf)) {\n [IO.Directory]::CreateDirectory([IO.Path]::GetDirectoryName($servicePath)) | Out-Null;\n $candidate = $servicePath + '.' + [guid]::NewGuid().ToString('N') + '.tmp.exe';\n try {\n $source = [Text.Encoding]::UTF8.GetString([Convert]::FromBase64String('${Buffer.from(source).toString(\"base64\")}'));\n Add-Type -TypeDefinition $source -ReferencedAssemblies 'System.dll','System.ServiceProcess.dll' -OutputAssembly $candidate -OutputType WindowsApplication -ErrorAction Stop;\n Move-Item -LiteralPath $candidate -Destination $servicePath -ErrorAction Stop;\n } finally { if (Test-Path -LiteralPath $candidate) { Remove-Item -LiteralPath $candidate -Force; } }\n}`;\n return { path, source, logPath, compileScript };\n}\n\nexport function windowsServiceRegistration(label: string, binaryPath: string): string {\n return `$binaryPath = ${psString(quoteWindowsArgument(binaryPath))};\nif ($service) {\n if ((Get-DevAnywhereAccountSid $service.StartName) -ne $ownerSid) { throw 'Existing service belongs to another account'; }\n $result = Invoke-CimMethod -InputObject $service -MethodName Change -Arguments @{ PathName = $binaryPath; StartMode = 'Automatic' };\n if ($result.ReturnValue -ne 0) { throw ('Service update failed: ' + $result.ReturnValue); }\n} else {\n Add-Type -AssemblyName System.ServiceProcess;\n Add-Type -AssemblyName System.Configuration.Install;\n Add-Type -ReferencedAssemblies 'System.dll','System.Configuration.Install.dll' -TypeDefinition @'\nusing System;\nusing System.Collections;\nusing System.ComponentModel;\nusing System.Configuration.Install;\nusing System.Runtime.InteropServices;\npublic sealed class DevAnywhereCredentialValidator : Installer {\n public string Username { get; set; }\n public string Password { get; set; }\n public int LogonError { get; private set; }\n [DllImport(\"advapi32.dll\", CharSet = CharSet.Unicode, SetLastError = true)]\n private static extern bool LogonUser(string user, string domain, string password, int type, int provider, out IntPtr token);\n [DllImport(\"kernel32.dll\")]\n private static extern bool CloseHandle(IntPtr handle);\n public override void Install(IDictionary stateSaver) {\n base.Install(stateSaver);\n int separator = Username.IndexOf((char)92);\n string domain = separator < 0 ? null : Username.Substring(0, separator);\n string user = separator < 0 ? Username : Username.Substring(separator + 1);\n IntPtr token;\n // Validate the same service logon that SCM will use, after the parent grants its logon right.\n if (!LogonUser(user, domain, Password, 5, 0, out token)) {\n LogonError = Marshal.GetLastWin32Error();\n throw new Win32Exception(LogonError);\n }\n CloseHandle(token);\n }\n}\n'@;\n while ($true) {\n $credential = Get-Credential -UserName $ownerName -Message 'DEV Anywhere: enter this account password (Microsoft account password if applicable, not the Windows Hello PIN). Windows will verify it before installation.';\n if (!$credential) { throw 'Service installation cancelled'; }\n if ((Get-DevAnywhereAccountSid $credential.UserName) -ne $ownerSid) { throw 'Use the same account that owns this DEV Anywhere profile'; }\n $processInstaller = New-Object System.ServiceProcess.ServiceProcessInstaller;\n $processInstaller.Account = [System.ServiceProcess.ServiceAccount]::User;\n $processInstaller.Username = $ownerName;\n $processInstaller.Password = $credential.GetNetworkCredential().Password;\n $validator = New-Object DevAnywhereCredentialValidator;\n $validator.Username = $ownerName;\n $validator.Password = $processInstaller.Password;\n $installer = New-Object System.ServiceProcess.ServiceInstaller;\n $installer.ServiceName = ${psString(label)};\n $installer.DisplayName = ${psString(`DEV Anywhere (${label})`)};\n $installer.Description = 'DEV Anywhere Proxy: run before desktop login as the profile owner';\n $installer.StartType = [System.ServiceProcess.ServiceStartMode]::Automatic;\n $processInstaller.Installers.Add($validator) | Out-Null;\n $processInstaller.Installers.Add($installer) | Out-Null;\n $processInstaller.Context = New-Object System.Configuration.Install.InstallContext($null, @('/LogToConsole=false'));\n $processInstaller.Context.Parameters['assemblypath'] = $binaryPath;\n $state = @{};\n try {\n # ServiceProcessInstaller grants SeServiceLogonRight and rolls it back on failed installation.\n $processInstaller.Install($state);\n $processInstaller.Commit($state);\n Write-Host 'Windows 服务账户验证通过。';\n break;\n } catch {\n $processInstaller.Rollback($state);\n if ($validator.LogonError -eq 1326) {\n Write-Warning 'Windows 未接受这个账户密码,请重新输入。微软账户需填写微软账户密码,不能使用 PIN;取消凭据窗口可退出。';\n continue;\n }\n throw;\n } finally {\n $processInstaller.Password = $null;\n $validator.Password = $null;\n $credential = $null;\n }\n }\n}`;\n}\n","interface AutostartRegistration {\n status(): Promise<boolean>;\n enable(): Promise<void>;\n disable(): Promise<void>;\n}\n\n/** Install the replacement first. Failure must not leave the user with no startup registration. */\nexport async function switchAutostartMode(\n selected: AutostartRegistration,\n previous: AutostartRegistration,\n): Promise<void> {\n const alreadyEnabled = await selected.status();\n const previousEnabled = await previous.status();\n await selected.enable();\n try {\n await previous.disable();\n } catch (error) {\n // Disable can fail after changing OS state (for example when removing the old file fails).\n // Restore that mode before rolling back the replacement, so there is always a startup path.\n if (previousEnabled) await previous.enable();\n if (!alreadyEnabled) await selected.disable();\n throw error;\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,SAAS,SAAS,gBAAgB;AAClC,SAAS,qBAAqB;AAC9B,SAAS,cAAc,aAAa;;;ACFpC,SAAS,gBAAgB;AACzB,SAAS,OAAO,iBAAiB;AACjC,SAAS,SAAS,MAAM,SAAAA,cAAa;AACrC,SAAS,iBAAiB;;;ACH1B,SAAS,kBAAkB;AAC3B,SAAS,aAAa;AAItB,SAAS,cAAc,OAAuB;AAC5C,MAAI,CAAC,GAAG,KAAK,EAAE,KAAK,CAAC,SAAS,KAAK,WAAW,CAAC,KAAK,MAAM,KAAK,WAAW,CAAC,MAAM,GAAG,GAAG;AACrF,UAAM,IAAI,MAAM,qEAAqE;AAAA,EACvF;AACA,SAAO,WAAW,OAAO,KAAK,OAAO,MAAM,EAAE,SAAS,QAAQ,CAAC;AACjE;AAGO,SAAS,8BAA8B,SAK+B;AAC3E,QAAM,QAAQ,uBAAuB,QAAQ,MAAM,QAAQ,SAAS,OAAO;AAC3E,QAAM,UAAU,MAAM,KAAK,MAAM,QAAQ,wBAAwB;AACjE,QAAM,SAAS;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,yBAgBQ,cAAc,OAAO,CAAC;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,4BAMnB,cAAc,QAAQ,UAAU,CAAC;AAAA,6BAChC,cAAc,QAAQ,KAAK,IAAI,oBAAoB,EAAE,KAAK,GAAG,CAAC,CAAC;AAAA,oCACxD,cAAc,QAAQ,IAAI,CAAC;AAAA,uDACR,cAAc,QAAQ,IAAI,CAAC;AAAA,gDAClC,cAAc,QAAQ,IAAI,CAAC;AAAA;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AACA,QAAI,QAAQ;AACV,UAAI,OAAQ,OAAM,IAAI,MAAM,uDAAuD;AACnF,YAAM,EAAE,uBAAuB,IAAI,MAAM,OAAO,4BAAmB;AACnE,YAAM,uBAAuB;AAC7B;AAAA,IACF;AACA,UAAM,YAAY,8BAA8B;AAChD,QAAI,OAAQ,OAAM,UAAU,MAAM,UAAU;AAAA;AAE1C,YAAM,UAAU,gBAAgB,YAAY;AAC1C,cAAM,EAAE,aAAa,IAAI,MAAM,OAAO,YAAY;AAClD,cAAM,aAAa;AAAA,MACrB,CAAC;AAAA,EACL,SAAS,OAAO;AACd,UAAM,EAAE,cAAc,IAAI,MAAM,OAAO,sBAAoB;AAC3D,UAAM,EAAE,YAAY,IAAI,MAAM,OAAO,sBAA6B;AAClE,kBAAc,MAAM,EAAE,KAAK,gBAAgB,KAAK,EAAE,GAAG,gCAAgC;AACrF,UAAM,YAAY,aAAa;AAC/B,YAAQ,KAAK,CAAC;AAAA,EAChB;AACF;","names":["win32","createHash","win32","output","execFile","mkdir","writeFile","dirname","join","win32","promisify","createHash","win32","win32","createHash","execFileAsync","promisify","execFile","join","win32","writeFile","mkdir","dirname"]}
@@ -6,7 +6,7 @@ import {
6
6
  VALID_LOG_LEVELS,
7
7
  loadProxyRuntimeEnv,
8
8
  serviceLogger
9
- } from "./chunk-JRSPTWQB.js";
9
+ } from "./chunk-WTCJIDDT.js";
10
10
  import {
11
11
  CONFIG_PATH,
12
12
  PROFILE_NAME,
@@ -226,4 +226,4 @@ export {
226
226
  buildProviderEnv,
227
227
  saveAgentCliPath
228
228
  };
229
- //# sourceMappingURL=chunk-7EOSTWVO.js.map
229
+ //# sourceMappingURL=chunk-4EIUH7CQ.js.map
@@ -1,7 +1,7 @@
1
1
  #!/usr/bin/env node
2
2
  import {
3
3
  createProfileServiceLifecycle
4
- } from "./chunk-MPW6H537.js";
4
+ } from "./chunk-Z2KUJ6SW.js";
5
5
  import {
6
6
  TERMINAL_ADMISSION_FRAME_MAX_BYTES,
7
7
  TERMINAL_ADMISSION_VERSION,
@@ -244,4 +244,4 @@ export {
244
244
  requestTerminalAdmission,
245
245
  swapServeSocket
246
246
  };
247
- //# sourceMappingURL=chunk-HEXGO236.js.map
247
+ //# sourceMappingURL=chunk-E2S3REKI.js.map
@@ -0,0 +1,149 @@
1
+ #!/usr/bin/env node
2
+
3
+ // src/common/local-ipc-endpoint.ts
4
+ import { chmodSync, existsSync as existsSync2, mkdirSync as mkdirSync2 } from "fs";
5
+ import { dirname } from "path";
6
+
7
+ // src/common/safe-unlink.ts
8
+ import { unlinkSync } from "fs";
9
+ function unlinkIfPresent(path, unlink = unlinkSync) {
10
+ try {
11
+ unlink(path);
12
+ } catch (err) {
13
+ if (err.code === "ENOENT") return;
14
+ throw err;
15
+ }
16
+ }
17
+
18
+ // src/common/windows-pipe-permissions.ts
19
+ import { execFileSync } from "child_process";
20
+ import { createHash } from "crypto";
21
+ import { existsSync, mkdirSync, renameSync, rmSync } from "fs";
22
+ import { homedir } from "os";
23
+ import { join } from "path";
24
+ var SOURCE = `using System;
25
+ using System.ComponentModel;
26
+ using System.IO;
27
+ using System.IO.Pipes;
28
+ using System.Runtime.InteropServices;
29
+ using System.Security.AccessControl;
30
+ using System.Security.Principal;
31
+ using Microsoft.Win32.SafeHandles;
32
+
33
+ public static class DevAnywherePipePermissions {
34
+ [DllImport("kernel32.dll", SetLastError = true)]
35
+ private static extern bool GetNamedPipeServerProcessId(SafePipeHandle pipe, out uint pid);
36
+ [DllImport("advapi32.dll", SetLastError = true)]
37
+ private static extern bool SetKernelObjectSecurity(SafePipeHandle handle, uint information, byte[] descriptor);
38
+
39
+ public static int Main(string[] args) {
40
+ Console.OutputEncoding = new System.Text.UTF8Encoding(false);
41
+ try {
42
+ if (args.Length != 2 || !(args[0].StartsWith(@"\\\\.\\pipe\\") || args[0].StartsWith(@"\\\\?\\pipe\\")))
43
+ throw new ArgumentException("Expected a local named pipe and its server PID");
44
+ uint expectedPid = uint.Parse(args[1]);
45
+ var rights = PipeAccessRights.ReadWrite | PipeAccessRights.ReadPermissions |
46
+ PipeAccessRights.ChangePermissions | PipeAccessRights.TakeOwnership;
47
+ using (var pipe = new NamedPipeClientStream(".", args[0].Substring(9), rights,
48
+ PipeOptions.None, TokenImpersonationLevel.Identification, HandleInheritability.None)) {
49
+ pipe.Connect(3000);
50
+ uint serverPid;
51
+ if (!GetNamedPipeServerProcessId(pipe.SafePipeHandle, out serverPid))
52
+ throw new Win32Exception(Marshal.GetLastWin32Error());
53
+ if (serverPid != expectedPid) throw new InvalidOperationException("Named pipe belongs to another process");
54
+ using (var identity = WindowsIdentity.GetCurrent()) {
55
+ // Retain local administrative access and explicitly admit this account's desktop token.
56
+ // Keep other users, low-integrity processes and network logons out.
57
+ var descriptor = new RawSecurityDescriptor("D:P(D;;GA;;;NU)(A;;GA;;;SY)(A;;GA;;;BA)(A;;GA;;;" +
58
+ identity.User.Value + ")S:(ML;;NW;;;ME)");
59
+ var data = new byte[descriptor.BinaryLength];
60
+ descriptor.GetBinaryForm(data, 0);
61
+ if (!SetKernelObjectSecurity(pipe.SafePipeHandle, 0x80000014, data))
62
+ throw new Win32Exception(Marshal.GetLastWin32Error());
63
+ }
64
+ }
65
+ return 0;
66
+ } catch (Exception error) {
67
+ Console.Error.WriteLine("Cannot secure local pipe: " + error.Message);
68
+ return 1;
69
+ }
70
+ }
71
+ }
72
+ `;
73
+ var helperPath;
74
+ function permissionHelper() {
75
+ if (helperPath) return helperPath;
76
+ const directory = join(homedir(), ".dev-anywhere", "helpers");
77
+ const digest = createHash("sha256").update(SOURCE).digest("hex").slice(0, 20);
78
+ const executable = join(directory, `pipe-permissions-${digest}.exe`);
79
+ if (!existsSync(executable)) {
80
+ mkdirSync(directory, { recursive: true });
81
+ const candidate = `${executable}.${process.pid}.tmp.exe`;
82
+ const script = `$ErrorActionPreference = 'Stop';
83
+ $env:PSModulePath = $PSHOME + '\\Modules';
84
+ $source = [Text.Encoding]::UTF8.GetString([Convert]::FromBase64String('${Buffer.from(SOURCE).toString("base64")}'));
85
+ $output = [Text.Encoding]::UTF8.GetString([Convert]::FromBase64String('${Buffer.from(candidate).toString("base64")}'));
86
+ Add-Type -TypeDefinition $source -ReferencedAssemblies 'System.dll','System.Core.dll' -OutputAssembly $output -OutputType ConsoleApplication;`;
87
+ try {
88
+ execFileSync(
89
+ join(
90
+ process.env.SystemRoot ?? "C:\\Windows",
91
+ "System32",
92
+ "WindowsPowerShell",
93
+ "v1.0",
94
+ "powershell.exe"
95
+ ),
96
+ [
97
+ "-NoProfile",
98
+ "-NonInteractive",
99
+ "-EncodedCommand",
100
+ Buffer.from(script, "utf16le").toString("base64")
101
+ ],
102
+ { timeout: 3e4, windowsHide: true, stdio: "pipe" }
103
+ );
104
+ try {
105
+ renameSync(candidate, executable);
106
+ } catch (error) {
107
+ if (!existsSync(executable)) throw error;
108
+ }
109
+ } finally {
110
+ rmSync(candidate, { force: true });
111
+ }
112
+ }
113
+ helperPath = executable;
114
+ return executable;
115
+ }
116
+ function setWindowsPipePermissions(endpoint) {
117
+ execFileSync(permissionHelper(), [endpoint, String(process.pid)], {
118
+ timeout: 5e3,
119
+ windowsHide: true,
120
+ stdio: "pipe"
121
+ });
122
+ }
123
+
124
+ // src/common/local-ipc-endpoint.ts
125
+ function isNamedPipeEndpoint(endpoint) {
126
+ return /^\\\\[.?]\\pipe\\/i.test(endpoint);
127
+ }
128
+ function prepareLocalIpcEndpoint(endpoint) {
129
+ if (!isNamedPipeEndpoint(endpoint)) mkdirSync2(dirname(endpoint), { recursive: true });
130
+ }
131
+ function setLocalIpcEndpointPermissions(endpoint) {
132
+ if (isNamedPipeEndpoint(endpoint)) setWindowsPipePermissions(endpoint);
133
+ else chmodSync(endpoint, 384);
134
+ }
135
+ function removeLocalIpcEndpoint(endpoint) {
136
+ if (!isNamedPipeEndpoint(endpoint)) unlinkIfPresent(endpoint);
137
+ }
138
+ function localIpcEndpointMayExist(endpoint) {
139
+ return isNamedPipeEndpoint(endpoint) || existsSync2(endpoint);
140
+ }
141
+
142
+ export {
143
+ unlinkIfPresent,
144
+ prepareLocalIpcEndpoint,
145
+ setLocalIpcEndpointPermissions,
146
+ removeLocalIpcEndpoint,
147
+ localIpcEndpointMayExist
148
+ };
149
+ //# sourceMappingURL=chunk-G4QN6LOR.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/common/local-ipc-endpoint.ts","../src/common/safe-unlink.ts","../src/common/windows-pipe-permissions.ts"],"sourcesContent":["import { chmodSync, existsSync, mkdirSync } from \"node:fs\";\nimport { dirname } from \"node:path\";\nimport { unlinkIfPresent } from \"./safe-unlink.js\";\nimport { setWindowsPipePermissions } from \"./windows-pipe-permissions.js\";\n\nexport function isNamedPipeEndpoint(endpoint: string): boolean {\n return /^\\\\\\\\[.?]\\\\pipe\\\\/i.test(endpoint);\n}\n\nexport function prepareLocalIpcEndpoint(endpoint: string): void {\n if (!isNamedPipeEndpoint(endpoint)) mkdirSync(dirname(endpoint), { recursive: true });\n}\n\nexport function setLocalIpcEndpointPermissions(endpoint: string): void {\n // Do not enable readableAll/writableAll: access must stay limited to this account.\n // Listeners must not send data until the client writes and passes protocol admission.\n if (isNamedPipeEndpoint(endpoint)) setWindowsPipePermissions(endpoint);\n else chmodSync(endpoint, 0o600);\n}\n\nexport function removeLocalIpcEndpoint(endpoint: string): void {\n // Windows removes the pipe when its final handle closes. Unlink cannot remove a pipe.\n if (!isNamedPipeEndpoint(endpoint)) unlinkIfPresent(endpoint);\n}\n\n/** A cheap scan filter, not a liveness check. Named pipes must always be probed by connecting. */\nexport function localIpcEndpointMayExist(endpoint: string): boolean {\n return isNamedPipeEndpoint(endpoint) || existsSync(endpoint);\n}\n","import { unlinkSync } from \"node:fs\";\n\ntype UnlinkFn = (path: string) => void;\n\nexport function unlinkIfPresent(path: string, unlink: UnlinkFn = unlinkSync): void {\n try {\n unlink(path);\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code === \"ENOENT\") return;\n throw err;\n }\n}\n","import { execFileSync } from \"node:child_process\";\nimport { createHash } from \"node:crypto\";\nimport { existsSync, mkdirSync, renameSync, rmSync } from \"node:fs\";\nimport { homedir } from \"node:os\";\nimport { join } from \"node:path\";\n\n// An administrator's service token makes Administrators the default pipe owner. Its\n// unelevated desktop token cannot use that ACE. Grant the actual user SID explicitly.\nconst SOURCE = `using System;\nusing System.ComponentModel;\nusing System.IO;\nusing System.IO.Pipes;\nusing System.Runtime.InteropServices;\nusing System.Security.AccessControl;\nusing System.Security.Principal;\nusing Microsoft.Win32.SafeHandles;\n\npublic static class DevAnywherePipePermissions {\n [DllImport(\"kernel32.dll\", SetLastError = true)]\n private static extern bool GetNamedPipeServerProcessId(SafePipeHandle pipe, out uint pid);\n [DllImport(\"advapi32.dll\", SetLastError = true)]\n private static extern bool SetKernelObjectSecurity(SafePipeHandle handle, uint information, byte[] descriptor);\n\n public static int Main(string[] args) {\n Console.OutputEncoding = new System.Text.UTF8Encoding(false);\n try {\n if (args.Length != 2 || !(args[0].StartsWith(@\"\\\\\\\\.\\\\pipe\\\\\") || args[0].StartsWith(@\"\\\\\\\\?\\\\pipe\\\\\")))\n throw new ArgumentException(\"Expected a local named pipe and its server PID\");\n uint expectedPid = uint.Parse(args[1]);\n var rights = PipeAccessRights.ReadWrite | PipeAccessRights.ReadPermissions |\n PipeAccessRights.ChangePermissions | PipeAccessRights.TakeOwnership;\n using (var pipe = new NamedPipeClientStream(\".\", args[0].Substring(9), rights,\n PipeOptions.None, TokenImpersonationLevel.Identification, HandleInheritability.None)) {\n pipe.Connect(3000);\n uint serverPid;\n if (!GetNamedPipeServerProcessId(pipe.SafePipeHandle, out serverPid))\n throw new Win32Exception(Marshal.GetLastWin32Error());\n if (serverPid != expectedPid) throw new InvalidOperationException(\"Named pipe belongs to another process\");\n using (var identity = WindowsIdentity.GetCurrent()) {\n // Retain local administrative access and explicitly admit this account's desktop token.\n // Keep other users, low-integrity processes and network logons out.\n var descriptor = new RawSecurityDescriptor(\"D:P(D;;GA;;;NU)(A;;GA;;;SY)(A;;GA;;;BA)(A;;GA;;;\" +\n identity.User.Value + \")S:(ML;;NW;;;ME)\");\n var data = new byte[descriptor.BinaryLength];\n descriptor.GetBinaryForm(data, 0);\n if (!SetKernelObjectSecurity(pipe.SafePipeHandle, 0x80000014, data))\n throw new Win32Exception(Marshal.GetLastWin32Error());\n }\n }\n return 0;\n } catch (Exception error) {\n Console.Error.WriteLine(\"Cannot secure local pipe: \" + error.Message);\n return 1;\n }\n }\n}\n`;\n\nlet helperPath: string | undefined;\n\nfunction permissionHelper(): string {\n if (helperPath) return helperPath;\n const directory = join(homedir(), \".dev-anywhere\", \"helpers\");\n const digest = createHash(\"sha256\").update(SOURCE).digest(\"hex\").slice(0, 20);\n const executable = join(directory, `pipe-permissions-${digest}.exe`);\n if (!existsSync(executable)) {\n mkdirSync(directory, { recursive: true });\n const candidate = `${executable}.${process.pid}.tmp.exe`;\n const script = `$ErrorActionPreference = 'Stop';\n$env:PSModulePath = $PSHOME + '\\\\Modules';\n$source = [Text.Encoding]::UTF8.GetString([Convert]::FromBase64String('${Buffer.from(SOURCE).toString(\"base64\")}'));\n$output = [Text.Encoding]::UTF8.GetString([Convert]::FromBase64String('${Buffer.from(candidate).toString(\"base64\")}'));\nAdd-Type -TypeDefinition $source -ReferencedAssemblies 'System.dll','System.Core.dll' -OutputAssembly $output -OutputType ConsoleApplication;`;\n try {\n execFileSync(\n join(\n process.env.SystemRoot ?? \"C:\\\\Windows\",\n \"System32\",\n \"WindowsPowerShell\",\n \"v1.0\",\n \"powershell.exe\",\n ),\n [\n \"-NoProfile\",\n \"-NonInteractive\",\n \"-EncodedCommand\",\n Buffer.from(script, \"utf16le\").toString(\"base64\"),\n ],\n { timeout: 30_000, windowsHide: true, stdio: \"pipe\" },\n );\n try {\n renameSync(candidate, executable);\n } catch (error) {\n // Another process can finish compiling the same source first.\n if (!existsSync(executable)) throw error;\n }\n } finally {\n rmSync(candidate, { force: true });\n }\n }\n helperPath = executable;\n return executable;\n}\n\nexport function setWindowsPipePermissions(endpoint: string): void {\n execFileSync(permissionHelper(), [endpoint, String(process.pid)], {\n timeout: 5_000,\n windowsHide: true,\n stdio: \"pipe\",\n });\n}\n"],"mappings":";;;AAAA,SAAS,WAAW,cAAAA,aAAY,aAAAC,kBAAiB;AACjD,SAAS,eAAe;;;ACDxB,SAAS,kBAAkB;AAIpB,SAAS,gBAAgB,MAAc,SAAmB,YAAkB;AACjF,MAAI;AACF,WAAO,IAAI;AAAA,EACb,SAAS,KAAK;AACZ,QAAK,IAA8B,SAAS,SAAU;AACtD,UAAM;AAAA,EACR;AACF;;;ACXA,SAAS,oBAAoB;AAC7B,SAAS,kBAAkB;AAC3B,SAAS,YAAY,WAAW,YAAY,cAAc;AAC1D,SAAS,eAAe;AACxB,SAAS,YAAY;AAIrB,IAAM,SAAS;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAkDf,IAAI;AAEJ,SAAS,mBAA2B;AAClC,MAAI,WAAY,QAAO;AACvB,QAAM,YAAY,KAAK,QAAQ,GAAG,iBAAiB,SAAS;AAC5D,QAAM,SAAS,WAAW,QAAQ,EAAE,OAAO,MAAM,EAAE,OAAO,KAAK,EAAE,MAAM,GAAG,EAAE;AAC5E,QAAM,aAAa,KAAK,WAAW,oBAAoB,MAAM,MAAM;AACnE,MAAI,CAAC,WAAW,UAAU,GAAG;AAC3B,cAAU,WAAW,EAAE,WAAW,KAAK,CAAC;AACxC,UAAM,YAAY,GAAG,UAAU,IAAI,QAAQ,GAAG;AAC9C,UAAM,SAAS;AAAA;AAAA,yEAEsD,OAAO,KAA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BAAoB,QAAQ,KAAKC,YAAW,QAAQ;AAC7D;","names":["existsSync","mkdirSync","mkdirSync","existsSync"]}
@@ -38,7 +38,7 @@ import {
38
38
  } from "./chunk-HJOYOYGB.js";
39
39
  import {
40
40
  terminalLogger
41
- } from "./chunk-JRSPTWQB.js";
41
+ } from "./chunk-WTCJIDDT.js";
42
42
 
43
43
  // src/terminal-worker-args.ts
44
44
  import { z } from "zod";
@@ -358,4 +358,4 @@ export {
358
358
  buildHostedPtyArgs,
359
359
  PtyRuntime
360
360
  };
361
- //# sourceMappingURL=chunk-QZJBIFGW.js.map
361
+ //# sourceMappingURL=chunk-UEIKYXS7.js.map
@@ -1,7 +1,7 @@
1
1
  #!/usr/bin/env node
2
2
  import {
3
3
  setLocalIpcEndpointPermissions
4
- } from "./chunk-77QVUYU7.js";
4
+ } from "./chunk-G4QN6LOR.js";
5
5
 
6
6
  // src/common/service-control.ts
7
7
  import { connect, createServer } from "net";
@@ -207,4 +207,4 @@ export {
207
207
  requestServiceControl,
208
208
  startServiceControl
209
209
  };
210
- //# sourceMappingURL=chunk-AZ5MTPUR.js.map
210
+ //# sourceMappingURL=chunk-VYAEW7G6.js.map
@@ -38,11 +38,22 @@ function parsePort(value, source) {
38
38
  function nonEmpty(value) {
39
39
  return value && value.length > 0 ? value : void 0;
40
40
  }
41
+ function parseRetryInterval(value) {
42
+ if (!value) return void 0;
43
+ const interval = Number(value);
44
+ if (!Number.isInteger(interval) || interval < 1 || interval > 2147483647) {
45
+ throw new Error(
46
+ `Invalid DEV_ANYWHERE_AUTO_UPDATE_RETRY_INITIAL_MS=${JSON.stringify(value)}: expected integer milliseconds 1-2147483647`
47
+ );
48
+ }
49
+ return interval;
50
+ }
41
51
  function loadProxyRuntimeEnv(env2 = process.env) {
42
52
  return {
43
53
  relayUrl: nonEmpty(env2.RELAY_URL),
44
54
  relayProxyToken: nonEmpty(env2.RELAY_PROXY_TOKEN),
45
55
  hookPort: parsePort(env2.DEV_ANYWHERE_HOOK_PORT, "DEV_ANYWHERE_HOOK_PORT"),
56
+ autoUpdateRetryInitialMs: parseRetryInterval(env2.DEV_ANYWHERE_AUTO_UPDATE_RETRY_INITIAL_MS),
46
57
  claudeBin: nonEmpty(env2.CLAUDE_BIN),
47
58
  codexBin: nonEmpty(env2.CODEX_BIN),
48
59
  kimiBin: nonEmpty(env2.KIMI_BIN),
@@ -92,4 +103,4 @@ export {
92
103
  terminalLogger,
93
104
  autoUpdateLogger
94
105
  };
95
- //# sourceMappingURL=chunk-JRSPTWQB.js.map
106
+ //# sourceMappingURL=chunk-WTCJIDDT.js.map