dsh-builtin-browser 0.5.6 → 0.5.8

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 (119) hide show
  1. package/CHANGELOG.md +148 -0
  2. package/README.en.md +75 -81
  3. package/README.md +75 -82
  4. package/client.js +831 -384
  5. package/desktop-bridge/install-and-start.cmd +4 -5
  6. package/desktop-bridge/install.mjs +322 -141
  7. package/desktop-bridge/maintenance-progress.ps1 +166 -0
  8. package/desktop-bridge/plugin-browser-bridge.js +157 -19
  9. package/desktop-bridge/request-desktop-quit.ps1 +170 -0
  10. package/docs/tool-reference.md +20 -1
  11. package/docs/user-guide.md +28 -4
  12. package/lib/browser/runtime.d.ts +3 -1
  13. package/lib/browser/runtime.js +9 -0
  14. package/lib/browser/types.d.ts +42 -0
  15. package/lib/browser-electron/authenticated-route.d.ts +27 -0
  16. package/lib/browser-electron/authenticated-route.js +39 -0
  17. package/lib/browser-electron/automatic-maintenance.d.ts +41 -0
  18. package/lib/browser-electron/automatic-maintenance.js +426 -0
  19. package/lib/browser-electron/bridge-auto.d.ts +93 -0
  20. package/lib/browser-electron/bridge-auto.js +113 -0
  21. package/lib/browser-electron/bridge-connection.d.ts +0 -2
  22. package/lib/browser-electron/bridge-connection.js +2 -4
  23. package/lib/browser-electron/bridge-endpoint.js +8 -19
  24. package/lib/browser-electron/bridge-install.d.ts +85 -0
  25. package/lib/browser-electron/bridge-install.js +211 -0
  26. package/lib/browser-electron/bridge-maintenance.d.ts +24 -0
  27. package/lib/browser-electron/bridge-maintenance.js +125 -0
  28. package/lib/browser-electron/bridge-status.d.ts +10 -3
  29. package/lib/browser-electron/bridge-status.js +74 -24
  30. package/lib/browser-electron/desktop-bridge-host.d.ts +11 -5
  31. package/lib/browser-electron/desktop-bridge-host.js +67 -25
  32. package/lib/browser-electron/desktop-identity.js +21 -9
  33. package/lib/browser-electron/electron-provision.d.ts +1 -1
  34. package/lib/browser-electron/electron-provision.js +36 -13
  35. package/lib/browser-electron/entry.js +173 -67
  36. package/lib/browser-electron/ephemeral-profile.js +67 -26
  37. package/lib/browser-electron/history-store.js +2 -2
  38. package/lib/browser-electron/host-main.js +48 -38
  39. package/lib/browser-electron/http-body.d.ts +24 -0
  40. package/lib/browser-electron/http-body.js +33 -0
  41. package/lib/browser-electron/json-reply.d.ts +13 -1
  42. package/lib/browser-electron/json-reply.js +16 -2
  43. package/lib/browser-electron/maintenance-broker.d.ts +35 -0
  44. package/lib/browser-electron/maintenance-broker.js +114 -0
  45. package/lib/browser-electron/maintenance-lifecycle.d.ts +32 -0
  46. package/lib/browser-electron/maintenance-lifecycle.js +67 -0
  47. package/lib/browser-electron/maintenance-route.d.ts +18 -0
  48. package/lib/browser-electron/maintenance-route.js +75 -0
  49. package/lib/browser-electron/paths.d.ts +4 -0
  50. package/lib/browser-electron/paths.js +19 -0
  51. package/lib/browser-electron/process.d.ts +14 -0
  52. package/lib/browser-electron/process.js +24 -0
  53. package/lib/browser-electron/provider.d.ts +16 -9
  54. package/lib/browser-electron/provider.js +87 -18
  55. package/lib/browser-electron/remote-host.js +22 -20
  56. package/lib/browser-electron/runtime-route.d.ts +3 -5
  57. package/lib/browser-electron/runtime-status.d.ts +27 -13
  58. package/lib/browser-electron/runtime-status.js +28 -6
  59. package/lib/browser-electron/settings-route.d.ts +5 -18
  60. package/lib/browser-electron/settings-route.js +4 -14
  61. package/lib/browser-electron/settings-store.d.ts +28 -0
  62. package/lib/browser-electron/settings-store.js +32 -2
  63. package/lib/browser-electron/sidebar-only-host.d.ts +36 -0
  64. package/lib/browser-electron/sidebar-only-host.js +192 -0
  65. package/lib/browser-electron/system-browser.d.ts +6 -11
  66. package/lib/browser-electron/system-browser.js +29 -24
  67. package/lib/browser-electron/timing.d.ts +8 -0
  68. package/lib/browser-electron/timing.js +13 -0
  69. package/lib/browser-electron/windows-system.d.ts +3 -0
  70. package/lib/browser-electron/windows-system.js +19 -0
  71. package/lib/tool-browser/index.js +1045 -7
  72. package/lib/tool-browser/page-probe.d.ts +86 -0
  73. package/lib/tool-browser/page-probe.js +460 -0
  74. package/package.json +5 -3
  75. package/scripts/run-tests.mjs +32 -0
  76. package/scripts/verify-preview-route.mjs +19 -1
  77. package/scripts/verify-runtime-status.mjs +14 -0
  78. package/skills/dsh-builtin-browser/SKILL.md +64 -0
  79. package/skills/dsh-builtin-browser/references/batch.md +23 -0
  80. package/skills/dsh-builtin-browser/references/deliver.md +31 -0
  81. package/skills/dsh-builtin-browser/references/locate.md +11 -0
  82. package/skills/dsh-builtin-browser/references/recover.md +11 -0
  83. package/skills/dsh-builtin-browser/references/verify.md +13 -0
  84. package/src/browser/runtime.ts +11 -0
  85. package/src/browser/types.ts +19 -0
  86. package/src/browser-electron/authenticated-route.ts +56 -0
  87. package/src/browser-electron/automatic-maintenance.ts +414 -0
  88. package/src/browser-electron/bridge-auto.ts +158 -0
  89. package/src/browser-electron/bridge-connection.ts +2 -4
  90. package/src/browser-electron/bridge-endpoint.ts +8 -18
  91. package/src/browser-electron/bridge-install.ts +253 -0
  92. package/src/browser-electron/bridge-maintenance.ts +161 -0
  93. package/src/browser-electron/bridge-status.ts +76 -26
  94. package/src/browser-electron/desktop-bridge-host.ts +60 -26
  95. package/src/browser-electron/desktop-identity.ts +18 -9
  96. package/src/browser-electron/electron-provision.ts +35 -14
  97. package/src/browser-electron/entry.ts +152 -62
  98. package/src/browser-electron/ephemeral-profile.ts +65 -28
  99. package/src/browser-electron/history-store.ts +2 -2
  100. package/src/browser-electron/host-main.ts +40 -34
  101. package/src/browser-electron/http-body.ts +42 -0
  102. package/src/browser-electron/json-reply.ts +18 -3
  103. package/src/browser-electron/maintenance-broker.ts +142 -0
  104. package/src/browser-electron/maintenance-lifecycle.ts +86 -0
  105. package/src/browser-electron/maintenance-route.ts +64 -0
  106. package/src/browser-electron/paths.ts +21 -0
  107. package/src/browser-electron/process.ts +23 -0
  108. package/src/browser-electron/provider.ts +106 -22
  109. package/src/browser-electron/remote-host.ts +23 -23
  110. package/src/browser-electron/runtime-route.ts +3 -5
  111. package/src/browser-electron/runtime-status.ts +56 -19
  112. package/src/browser-electron/settings-route.ts +9 -32
  113. package/src/browser-electron/settings-store.ts +59 -3
  114. package/src/browser-electron/sidebar-only-host.ts +199 -0
  115. package/src/browser-electron/system-browser.ts +26 -23
  116. package/src/browser-electron/timing.ts +16 -0
  117. package/src/browser-electron/windows-system.ts +23 -0
  118. package/src/tool-browser/index.ts +995 -10
  119. package/src/tool-browser/page-probe.ts +474 -0
@@ -13,8 +13,8 @@
13
13
  * @module dsh-browser/browser-electron/history-store
14
14
  */
15
15
  import { appendFileSync, existsSync, mkdirSync, readFileSync } from 'node:fs';
16
- import { homedir } from 'node:os';
17
16
  import { dirname, join } from 'node:path';
17
+ import { dshHome } from './paths.js';
18
18
  import { writeFileAtomic } from './settings-store.js';
19
19
  /** Default entry cap — mirrors the documented retention rule. */
20
20
  const DEFAULT_MAX_ENTRIES = 5_000;
@@ -28,7 +28,7 @@ const PRUNE_SLACK = 500;
28
28
  * @returns the history file path.
29
29
  */
30
30
  export function visitedHistoryPath() {
31
- const home = process.env.DSH_HOME ?? join(homedir(), '.dsh');
31
+ const home = dshHome();
32
32
  return join(home, 'dsh-builtin-browser-host', 'history.jsonl');
33
33
  }
34
34
  /**
@@ -32,6 +32,7 @@ import { electronRuntimeDiagnosticLines } from './runtime-diagnostics.js';
32
32
  import { createRpcLineReader } from './rpc-input.js';
33
33
  import { tmpdir } from 'node:os';
34
34
  import { join } from 'node:path';
35
+ import { withTimeoutShared } from './timing.js';
35
36
  // Report the binary actually running this child, even when ELECTRON_PATH
36
37
  // intentionally selects a different version from the plugin's dependency.
37
38
  // The parent mirrors stderr to the host log; discovery stays filesystem-only.
@@ -248,12 +249,7 @@ function ensureToolbarFiles() {
248
249
  * explicit error instead of a command that never settles.
249
250
  */
250
251
  function withTimeout(promise, ms, label) {
251
- return new Promise((resolve, reject) => {
252
- const timer = setTimeout(() => {
253
- reject(new Error(`${label} timed out after ${ms}ms`));
254
- }, ms);
255
- promise.then((value) => { clearTimeout(timer); resolve(value); }, (error) => { clearTimeout(timer); reject(error); });
256
- });
252
+ return withTimeoutShared(promise, ms, () => new Error(`${label} timed out after ${ms}ms`));
257
253
  }
258
254
  /**
259
255
  * CDP commands are bounded here as well as in the parent: a view whose
@@ -362,7 +358,12 @@ function windowFor(windowId) {
362
358
  const existing = windows.get(key);
363
359
  if (existing !== undefined)
364
360
  return existing;
365
- const w = new BrowserWindow({ width: 1400, height: 900, show: true, title: 'dsh-browser' });
361
+ // `show: false` on purpose: creating a window must not be a presentation decision. With `show: true`
362
+ // the window appeared and took the screen the moment the first tool call created it — before any
363
+ // `showView` message could carry `ui.quiet`, so quiet mode had no effect at all on this carrier
364
+ // (measured: the setting was on and the window still popped up). The first presentation decides:
365
+ // quiet shows it inactive, a normal call shows it normally.
366
+ const w = new BrowserWindow({ width: 1400, height: 900, show: false, title: 'dsh-browser' });
366
367
  w.on('closed', () => {
367
368
  const closing = windows.get(key);
368
369
  windows.delete(key);
@@ -458,10 +459,12 @@ function wireFocusRouting(win, view, focusKey) {
458
459
  if (input.type !== 'mouseDown')
459
460
  return;
460
461
  win.lastFocusedViewId = focusKey;
461
- try {
462
- view.webContents.focus();
462
+ if (win.window.isFocused()) {
463
+ try {
464
+ view.webContents.focus();
465
+ }
466
+ catch { /* destroyed */ }
463
467
  }
464
- catch { /* destroyed */ }
465
468
  });
466
469
  }
467
470
  /** Create the toolbar view for a window (best-effort; never fatal). */
@@ -594,36 +597,39 @@ function revealViewInWindow(win, viewId, label) {
594
597
  * @param viewId - the view to present.
595
598
  * @param label - session/task label, when known, for the window title.
596
599
  * @param quiet - `ui.quiet`: present without taking the screen over.
597
- * @param needSurface - quiet mode only: this presentation is the barrier before synthesized
598
- * input, so the window has to be visible even if the user minimized it. A navigation or a tab
599
- * switch does not need that and leaves a minimized window alone.
600
+ * @param _needSurface - pre-input barrier flag retained by the RPC protocol. Quiet presentation
601
+ * opens a new visible window without activation and preserves an existing foreground page.
600
602
  */
601
- function showViewInWindow(win, viewId, label, quiet = false, needSurface = false) {
603
+ function showViewInWindow(win, viewId, label, quiet = false, _needSurface = false) {
604
+ if (quiet) {
605
+ if (win.window.isMinimized())
606
+ return;
607
+ // Preserve the page the operator is actively reading. Other views remain addressable by
608
+ // their own CDP session, without switching the foreground window's selected page.
609
+ if (win.window.isFocused() && win.visibleViewId !== viewId)
610
+ return;
611
+ revealViewInWindow(win, viewId, label);
612
+ // Quiet means a normal usable window without activation, including on the first open.
613
+ // An invisible surface made the browser look broken even after navigation succeeded.
614
+ if (win.window.getOpacity() === 0) {
615
+ win.window.setOpacity(1);
616
+ win.window.setSkipTaskbar(false);
617
+ win.window.setFocusable(true);
618
+ }
619
+ if (!win.window.isVisible())
620
+ win.window.showInactive();
621
+ return;
622
+ }
602
623
  revealViewInWindow(win, viewId, label);
603
- // Raise this session's window so the human sees the page being worked on
604
- // (moveTop raises without stealing keyboard focus).
605
- //
606
- // Quiet mode (`ui.quiet`): the user asked not to be interrupted, so this must not
607
- // activate the application, steal keyboard focus, or pull the window in front of the one
608
- // they are using. Chromium drops `Input.*` for a view with no display surface, so the one
609
- // case that still needs a visible window — the barrier before synthesized input — restores
610
- // it with `showInactive()`, which shows it without becoming the key window, and never calls
611
- // `moveTop()`. Everything else (navigation, tab switching, screenshots) leaves a minimized
612
- // window minimized.
613
624
  try {
614
- if (quiet) {
615
- if (!needSurface)
616
- return;
617
- if (win.window.isMinimized())
618
- win.window.restore();
619
- if (!win.window.isVisible())
620
- win.window.showInactive();
621
- }
622
- else {
623
- if (!win.window.isVisible())
624
- win.window.show();
625
- win.window.moveTop();
625
+ if (win.window.getOpacity() === 0) {
626
+ win.window.setFocusable(true);
627
+ win.window.setOpacity(1);
628
+ win.window.setSkipTaskbar(false);
626
629
  }
630
+ if (!win.window.isVisible())
631
+ win.window.show();
632
+ win.window.moveTop();
627
633
  }
628
634
  catch { /* closing */ }
629
635
  }
@@ -839,7 +845,10 @@ async function handle(op, msg) {
839
845
  // and `document.hasFocus()` inside the page even read true.
840
846
  const contents = entry.webContentsView.webContents;
841
847
  const hadWebFocus = contents.isFocused();
842
- contents.focus();
848
+ // Electron webContents.focus() can activate its BrowserWindow. CDP input uses the
849
+ // target page's DOM focus and does not require that operating-system activation.
850
+ if (msg.quiet !== true)
851
+ contents.focus();
843
852
  // Focus lands asynchronously, and a key dispatched in the same turn as
844
853
  // the request is still dropped, so hold the reply until the renderer can
845
854
  // take input. Only on the call where focus actually had to move.
@@ -880,7 +889,8 @@ async function handle(op, msg) {
880
889
  // The active tab has to be the visible one INSIDE the window, or the capture may read
881
890
  // another tab. Keep that switch contentView-local: show/restore/focus are precisely
882
891
  // what quiet mode forbids.
883
- revealViewInWindow(win, viewId);
892
+ if (!win.window.isVisible() || win.window.getOpacity() === 0)
893
+ revealViewInWindow(win, viewId);
884
894
  }
885
895
  else {
886
896
  try {
@@ -0,0 +1,24 @@
1
+ /**
2
+ * Bounded request bodies shared by every plugin HTTP route. Keeping one implementation means the
3
+ * byte limit, UTF-8 decoding and oversize behaviour cannot drift between the settings and the
4
+ * maintenance endpoints.
5
+ * @module dsh-browser/browser-electron/http-body
6
+ */
7
+ import type { IncomingMessage } from 'node:http';
8
+ /**
9
+ * Read a body as UTF-8 text. Chunks are collected as Buffers and decoded once: setting an
10
+ * encoding on the stream and concatenating `String(chunk)` corrupts a multi-byte character that
11
+ * happens to be split across two TCP chunks.
12
+ * @param request - the incoming request.
13
+ * @param limit - maximum accepted bytes.
14
+ * @returns the body text.
15
+ */
16
+ export declare function readTextBody(request: IncomingMessage, limit?: number): Promise<string>;
17
+ /**
18
+ * Read and parse a JSON body. An empty body is an empty object, matching the settings route's
19
+ * long-standing behaviour.
20
+ * @param request - the incoming request.
21
+ * @param limit - maximum accepted bytes.
22
+ * @returns the parsed value.
23
+ */
24
+ export declare function readJsonBody<T>(request: IncomingMessage, limit?: number): Promise<T>;
@@ -0,0 +1,33 @@
1
+ /**
2
+ * Read a body as UTF-8 text. Chunks are collected as Buffers and decoded once: setting an
3
+ * encoding on the stream and concatenating `String(chunk)` corrupts a multi-byte character that
4
+ * happens to be split across two TCP chunks.
5
+ * @param request - the incoming request.
6
+ * @param limit - maximum accepted bytes.
7
+ * @returns the body text.
8
+ */
9
+ export async function readTextBody(request, limit = 64 * 1024) {
10
+ const chunks = [];
11
+ let size = 0;
12
+ for await (const chunk of request) {
13
+ const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(String(chunk));
14
+ size += buffer.length;
15
+ if (size > limit) {
16
+ request.destroy();
17
+ throw new Error(`request body exceeds ${limit} bytes`);
18
+ }
19
+ chunks.push(buffer);
20
+ }
21
+ return Buffer.concat(chunks).toString('utf8');
22
+ }
23
+ /**
24
+ * Read and parse a JSON body. An empty body is an empty object, matching the settings route's
25
+ * long-standing behaviour.
26
+ * @param request - the incoming request.
27
+ * @param limit - maximum accepted bytes.
28
+ * @returns the parsed value.
29
+ */
30
+ export async function readJsonBody(request, limit = 64 * 1024) {
31
+ const text = await readTextBody(request, limit);
32
+ return JSON.parse(text === '' ? '{}' : text);
33
+ }
@@ -11,11 +11,23 @@
11
11
  * - `nosniff` + a same-origin resource policy, because these bodies name paths and pids.
12
12
  * @module dsh-browser/browser-electron/json-reply
13
13
  */
14
- import type { ServerResponse } from 'node:http';
14
+ import type { OutgoingHttpHeaders, ServerResponse } from 'node:http';
15
15
  /**
16
16
  * Write one JSON body with no caching and no sniffing.
17
17
  * @param response - the response to write.
18
18
  * @param status - the HTTP status.
19
19
  * @param body - anything JSON-serialisable.
20
20
  */
21
+ /**
22
+ * Write an already-serialised JSON body with caller-supplied headers.
23
+ *
24
+ * Routes do not all need the same header set: readiness answers carry length and sniffing
25
+ * headers, while the settings route has always returned only a content type and no-store.
26
+ * Sharing the write keeps those exact header sets from drifting into each other.
27
+ * @param response - the response to write.
28
+ * @param status - the HTTP status.
29
+ * @param text - the serialised body.
30
+ * @param headers - the exact header set this route has always sent.
31
+ */
32
+ export declare function writeJsonText(response: ServerResponse, status: number, text: string, headers: OutgoingHttpHeaders): void;
21
33
  export declare function replyJson(response: ServerResponse, status: number, body: unknown): void;
@@ -4,14 +4,28 @@
4
4
  * @param status - the HTTP status.
5
5
  * @param body - anything JSON-serialisable.
6
6
  */
7
+ /**
8
+ * Write an already-serialised JSON body with caller-supplied headers.
9
+ *
10
+ * Routes do not all need the same header set: readiness answers carry length and sniffing
11
+ * headers, while the settings route has always returned only a content type and no-store.
12
+ * Sharing the write keeps those exact header sets from drifting into each other.
13
+ * @param response - the response to write.
14
+ * @param status - the HTTP status.
15
+ * @param text - the serialised body.
16
+ * @param headers - the exact header set this route has always sent.
17
+ */
18
+ export function writeJsonText(response, status, text, headers) {
19
+ response.writeHead(status, headers);
20
+ response.end(text);
21
+ }
7
22
  export function replyJson(response, status, body) {
8
23
  const text = JSON.stringify(body);
9
- response.writeHead(status, {
24
+ writeJsonText(response, status, text, {
10
25
  'content-type': 'application/json; charset=utf-8',
11
26
  'content-length': Buffer.byteLength(text),
12
27
  'cache-control': 'no-store, private',
13
28
  'x-content-type-options': 'nosniff',
14
29
  'cross-origin-resource-policy': 'same-origin',
15
30
  });
16
- response.end(text);
17
31
  }
@@ -0,0 +1,35 @@
1
+ export interface MaintenanceBrokerOptions {
2
+ readonly runtimePath: string;
3
+ readonly args: readonly string[];
4
+ readonly cwd: string;
5
+ /** Overrides for the explicitly inherited environment; undefined removes a variable. */
6
+ readonly environment?: Readonly<Record<string, string | undefined>>;
7
+ }
8
+ export interface MaintenanceBrokerExecution {
9
+ readonly windowsHide: true;
10
+ readonly shell: false;
11
+ readonly encoding: 'utf8';
12
+ readonly timeout: number;
13
+ readonly maxBuffer: number;
14
+ readonly env: NodeJS.ProcessEnv;
15
+ }
16
+ export type MaintenanceBrokerExecutor = (file: string, args: readonly string[], options: MaintenanceBrokerExecution) => Promise<{
17
+ readonly stdout: string;
18
+ readonly stderr: string;
19
+ }>;
20
+ export interface MaintenanceBrokerDeps {
21
+ /** Tests supply a fake executor; the real broker is prohibited inside the test runner. */
22
+ readonly execFile?: MaintenanceBrokerExecutor;
23
+ readonly platform?: NodeJS.Platform;
24
+ }
25
+ export interface MaintenanceBrokerResult {
26
+ readonly pid: number;
27
+ }
28
+ /** Quote one argument using the Windows C runtime's command-line decoding rules. */
29
+ export declare function quoteWin32Argument(value: string): string;
30
+ /**
31
+ * Create a hidden, independent local process. No shell evaluates runtime paths or arguments.
32
+ * WMI receives an explicit environment copied from this process, including any plan overrides;
33
+ * it therefore does not accidentally inherit the provider service's unrelated environment.
34
+ */
35
+ export declare function launchMaintenanceBroker(options: MaintenanceBrokerOptions, deps?: MaintenanceBrokerDeps): Promise<MaintenanceBrokerResult>;
@@ -0,0 +1,114 @@
1
+ /**
2
+ * Start a local Windows maintenance coordinator through WMI, outside the requesting app's tree.
3
+ * This primitive only creates the requested process; its caller owns maintenance authorization,
4
+ * the coordinator's plan, readiness handshake and normal application shutdown.
5
+ * @module dsh-browser/browser-electron/maintenance-broker
6
+ */
7
+ import { execFile } from 'node:child_process';
8
+ import { statSync } from 'node:fs';
9
+ import { win32 } from 'node:path';
10
+ import { encodePowerShellScript, windowsPowerShellPath } from './windows-system.js';
11
+ /** Quote one argument using the Windows C runtime's command-line decoding rules. */
12
+ export function quoteWin32Argument(value) {
13
+ if (typeof value !== 'string' || value.includes('\0'))
14
+ throw new Error('a Windows process argument must be a string without NUL');
15
+ // Backslashes are literal except immediately before a quote or the closing quote. At those
16
+ // positions each slash must be doubled, and an embedded quote receives one additional slash.
17
+ return '"' + value.replace(/(\\*)"/g, '$1$1\\"').replace(/(\\+)$/, '$1$1') + '"';
18
+ }
19
+ function absolutePath(value, label) {
20
+ if (typeof value !== 'string' || value.includes('\0') || value.includes('"')
21
+ || !/^(?:[A-Za-z]:[\\/]|\\\\[^\\/]+[\\/][^\\/]+)/.test(value)) {
22
+ throw new Error(`${label} must be a fully qualified Windows path without NUL or quotes`);
23
+ }
24
+ return win32.normalize(value);
25
+ }
26
+ /** Apply Windows' case-insensitive variable names before passing one explicit environment. */
27
+ function inheritEnvironment(overrides) {
28
+ const environment = { ...process.env };
29
+ for (const [key, value] of Object.entries(overrides ?? {})) {
30
+ if (key === '' || /[=\0]/.test(key) || (value !== undefined && (typeof value !== 'string' || value.includes('\0')))) {
31
+ throw new Error('maintenance environment names and values must be valid Windows environment strings');
32
+ }
33
+ for (const existing of Object.keys(environment))
34
+ if (existing.toUpperCase() === key.toUpperCase())
35
+ delete environment[existing];
36
+ if (value !== undefined)
37
+ environment[key] = value;
38
+ }
39
+ return environment;
40
+ }
41
+ function underTest(environment) {
42
+ return Object.entries(environment).some(([key, value]) => (key.toUpperCase() === 'DSH_BROWSER_TEST' && value === '1')
43
+ || (key.toUpperCase() === 'NODE_TEST_CONTEXT' && value !== undefined));
44
+ }
45
+ const defaultExecutor = (file, args, options) => new Promise((resolve, reject) => {
46
+ execFile(file, [...args], options, (error, stdout, stderr) => {
47
+ if (error !== null) {
48
+ const reason = stderr.trim() || error.code || 'PowerShell did not complete';
49
+ reject(new Error(`Windows maintenance broker failed: ${String(reason).slice(-1_000)}`));
50
+ }
51
+ else
52
+ resolve({ stdout, stderr });
53
+ });
54
+ });
55
+ /**
56
+ * Create a hidden, independent local process. No shell evaluates runtime paths or arguments.
57
+ * WMI receives an explicit environment copied from this process, including any plan overrides;
58
+ * it therefore does not accidentally inherit the provider service's unrelated environment.
59
+ */
60
+ export async function launchMaintenanceBroker(options, deps = {}) {
61
+ const environment = inheritEnvironment(options.environment);
62
+ if (deps.execFile === undefined && (underTest(process.env) || underTest(environment))) {
63
+ throw new Error('the real Windows maintenance broker is disabled in tests; inject a fake executor');
64
+ }
65
+ if ((deps.platform ?? process.platform) !== 'win32')
66
+ throw new Error('the maintenance broker requires Windows');
67
+ const runtimePath = absolutePath(options.runtimePath, 'runtimePath');
68
+ const cwd = absolutePath(options.cwd, 'cwd');
69
+ if (!statSync(runtimePath).isFile())
70
+ throw new Error('the maintenance runtime is not a file');
71
+ if (!statSync(cwd).isDirectory())
72
+ throw new Error('the maintenance working directory is not a directory');
73
+ if (!Array.isArray(options.args))
74
+ throw new Error('maintenance arguments must be an array');
75
+ const commandLine = [runtimePath, ...options.args].map(quoteWin32Argument).join(' ');
76
+ if (commandLine.length >= 32_767)
77
+ throw new Error('the maintenance command exceeds the Windows command-line limit');
78
+ const payload = Buffer.from(JSON.stringify({ commandLine, cwd }), 'utf8').toString('base64');
79
+ // The only interpolated script data is Base64 JSON. The full environment is inherited by
80
+ // execFile, then read as data here rather than embedded in the PowerShell command line.
81
+ const script = `$ErrorActionPreference = 'Stop'
82
+ [Console]::OutputEncoding = New-Object System.Text.UTF8Encoding($false)
83
+ try {
84
+ $plan = [System.Text.Encoding]::UTF8.GetString([System.Convert]::FromBase64String('${payload}')) | ConvertFrom-Json
85
+ $environment = [string[]]@([System.Environment]::GetEnvironmentVariables('Process').GetEnumerator() | ForEach-Object { [string]$_.Key + '=' + [string]$_.Value })
86
+ $startup = New-CimInstance -Namespace root/cimv2 -ClassName Win32_ProcessStartup -ClientOnly -Property @{ ShowWindow = [uint16]0; CreateFlags = [uint32]1024; EnvironmentVariables = $environment }
87
+ $result = Invoke-CimMethod -Namespace root/cimv2 -ClassName Win32_Process -MethodName Create -Arguments @{ CommandLine = [string]$plan.commandLine; CurrentDirectory = [string]$plan.cwd; ProcessStartupInformation = $startup }
88
+ @{ code = [uint32]$result.ReturnValue; pid = [uint32]$result.ProcessId } | ConvertTo-Json -Compress
89
+ } catch {
90
+ [Console]::Error.WriteLine($_.Exception.Message)
91
+ exit 1
92
+ }
93
+ `;
94
+ const encoded = encodePowerShellScript(script);
95
+ const powershellPath = windowsPowerShellPath();
96
+ if (encoded.length + powershellPath.length + 100 >= 32_767)
97
+ throw new Error('the encoded maintenance broker command exceeds the Windows command-line limit');
98
+ const result = await (deps.execFile ?? defaultExecutor)(powershellPath, ['-NoLogo', '-NoProfile', '-NonInteractive', '-EncodedCommand', encoded], { windowsHide: true, shell: false, encoding: 'utf8', timeout: 30_000, maxBuffer: 64_000, env: environment });
99
+ let record;
100
+ try {
101
+ record = JSON.parse(result.stdout.replace(/^\uFEFF/, '').trim());
102
+ }
103
+ catch {
104
+ throw new Error('the Windows maintenance broker returned an unreadable result');
105
+ }
106
+ if (record === null || typeof record !== 'object' || !Number.isSafeInteger(record.code) || Number(record.code) < 0) {
107
+ throw new Error('the Windows maintenance broker returned an invalid result');
108
+ }
109
+ if (record.code !== 0)
110
+ throw new Error(`Windows maintenance broker refused process creation (WMI code ${String(record.code)})`);
111
+ if (!Number.isSafeInteger(record.pid) || Number(record.pid) <= 0)
112
+ throw new Error('the Windows maintenance broker returned no valid process id');
113
+ return { pid: Number(record.pid) };
114
+ }
@@ -0,0 +1,32 @@
1
+ /** Explicit bridge maintenance lifecycle, independent of the Desktop-owned HTTP request. */
2
+ import type { BridgeAction, BridgeActionResult } from './bridge-install.js';
3
+ export type MaintenancePhase = 'armed' | 'closing' | 'installing' | 'restarting' | 'verifying' | 'completed' | 'cancelled' | 'failed';
4
+ export interface MaintenanceState {
5
+ readonly phase: MaintenancePhase;
6
+ readonly action: BridgeAction;
7
+ readonly at: string;
8
+ readonly ok?: boolean;
9
+ readonly restarted?: boolean;
10
+ readonly pid?: number;
11
+ readonly error?: string;
12
+ readonly output?: string;
13
+ }
14
+ /** Effects are supplied by the independent worker; tests cannot close or start an application. */
15
+ export interface MaintenanceLifecycleDeps {
16
+ /** Invoke the verified Desktop's own Quit menu item. Never confirm active-task dialogs. */
17
+ readonly requestQuit: () => Promise<void>;
18
+ /** Resolve only once every GUI/helper process belonging to this installation has exited. */
19
+ readonly waitUntilClosed: () => Promise<void>;
20
+ /** The existing installer retains its own identity, ancestry and running-process checks. */
21
+ readonly maintain: () => Promise<BridgeActionResult>;
22
+ /** Reopen exactly the verified installation after it has exited. */
23
+ readonly restart: () => Promise<number>;
24
+ /** Installation verifies the new authenticated bridge; uninstall verifies the process. */
25
+ readonly verify: (pid: number, action: BridgeAction) => Promise<void>;
26
+ readonly publish: (state: MaintenanceState) => Promise<void>;
27
+ }
28
+ /**
29
+ * A cancelled/failed quit never reaches the installer. After a confirmed exit, reopen Desktop even
30
+ * when maintenance fails, and retain that failure instead of reporting a successful installation.
31
+ */
32
+ export declare function runMaintenanceLifecycle(action: BridgeAction, deps: MaintenanceLifecycleDeps): Promise<MaintenanceState>;
@@ -0,0 +1,67 @@
1
+ /**
2
+ * A cancelled/failed quit never reaches the installer. After a confirmed exit, reopen Desktop even
3
+ * when maintenance fails, and retain that failure instead of reporting a successful installation.
4
+ */
5
+ export async function runMaintenanceLifecycle(action, deps) {
6
+ let closed = false;
7
+ let restarted = false;
8
+ let pid;
9
+ let outcome;
10
+ let publicationFailure;
11
+ const publish = async (phase, extra = {}) => {
12
+ const state = { phase, action, at: new Date().toISOString(), ...extra };
13
+ try {
14
+ await deps.publish(state);
15
+ }
16
+ catch (error) {
17
+ // Arming must be durable before any quit is requested. Later status I/O must never
18
+ // prevent reopening a Desktop that already exited normally.
19
+ if (phase === 'armed')
20
+ throw error;
21
+ publicationFailure ??= error;
22
+ }
23
+ return state;
24
+ };
25
+ await publish('armed');
26
+ try {
27
+ await deps.requestQuit();
28
+ await publish('closing');
29
+ await deps.waitUntilClosed();
30
+ closed = true;
31
+ }
32
+ catch (error) {
33
+ return await publish('cancelled', { ok: false, restarted: false, error: String(error) });
34
+ }
35
+ let failure;
36
+ try {
37
+ await publish('installing');
38
+ outcome = await deps.maintain();
39
+ if (!outcome.ok)
40
+ throw new Error(outcome.output || 'bridge maintenance failed');
41
+ }
42
+ catch (error) {
43
+ failure = error;
44
+ }
45
+ try {
46
+ // `closed` is set only by the successful closed-process barrier, never by a timeout.
47
+ if (!closed)
48
+ throw new Error('Desktop exit was not confirmed');
49
+ await publish('restarting');
50
+ pid = await deps.restart();
51
+ if (!Number.isSafeInteger(pid) || pid <= 0)
52
+ throw new Error('Desktop restart did not return a valid process');
53
+ restarted = true;
54
+ await publish('verifying', { pid, restarted });
55
+ await deps.verify(pid, failure === undefined ? action : 'uninstall');
56
+ }
57
+ catch (error) {
58
+ failure = failure === undefined ? error : new Error(`${String(failure)}; Desktop recovery: ${String(error)}`);
59
+ }
60
+ if (failure === undefined && publicationFailure !== undefined) {
61
+ failure = new Error(`Desktop maintenance finished, but progress could not be saved: ${String(publicationFailure)}`);
62
+ }
63
+ const details = { restarted, ...pid === undefined ? {} : { pid }, ...outcome?.output ? { output: outcome.output } : {} };
64
+ return failure === undefined
65
+ ? await publish('completed', { ...details, ok: true })
66
+ : await publish('failed', { ...details, ok: false, error: String(failure) });
67
+ }
@@ -0,0 +1,18 @@
1
+ /** Authenticated explicit maintenance protocol; older hosts cannot mistake it for direct install. */
2
+ import type { IncomingMessage, ServerResponse } from 'node:http';
3
+ import type { BridgeAction } from './bridge-install.js';
4
+ import type { AutomaticMaintenanceJob } from './automatic-maintenance.js';
5
+ export declare const AUTOMATIC_MAINTENANCE_ROUTE = "/dsh-builtin-browser/bridge-maintenance";
6
+ export interface AutomaticMaintenanceRouteDeps {
7
+ readonly supported: () => boolean;
8
+ readonly read: () => AutomaticMaintenanceJob | undefined;
9
+ readonly start: (action: BridgeAction, options?: {
10
+ readonly locale?: 'zh' | 'en';
11
+ }) => Promise<AutomaticMaintenanceJob>;
12
+ /** Commit only after the accepted response has been flushed to the client. */
13
+ readonly commit?: (id: string) => Promise<void>;
14
+ /** True while the legacy bridge-action route is running an installer. */
15
+ readonly busy?: () => boolean;
16
+ }
17
+ /** Register behind the host's signed-session authentication, as with settings writes. */
18
+ export declare function createAutomaticMaintenanceHandler(deps: AutomaticMaintenanceRouteDeps): (request: IncomingMessage, response: ServerResponse) => Promise<void>;
@@ -0,0 +1,75 @@
1
+ import { sameOrigin } from './settings-route.js';
2
+ import { isDirectLoopback } from './authenticated-route.js';
3
+ import { replyJson } from './json-reply.js';
4
+ import { readJsonBody } from './http-body.js';
5
+ export const AUTOMATIC_MAINTENANCE_ROUTE = '/dsh-builtin-browser/bridge-maintenance';
6
+ /** Register behind the host's signed-session authentication, as with settings writes. */
7
+ export function createAutomaticMaintenanceHandler(deps) {
8
+ let starting = false;
9
+ return async (request, response) => {
10
+ if (request.method !== 'GET' && request.method !== 'POST') {
11
+ replyJson(response, 405, { ok: false, error: 'method-not-allowed' });
12
+ return;
13
+ }
14
+ if (!sameOrigin(request, request.method === 'POST')) {
15
+ replyJson(response, 403, { ok: false, error: 'not-same-origin' });
16
+ return;
17
+ }
18
+ if (!isDirectLoopback(request)) {
19
+ replyJson(response, 403, { ok: false, error: 'local-request-required' });
20
+ return;
21
+ }
22
+ if (request.method === 'GET') {
23
+ const job = deps.read();
24
+ replyJson(response, 200, { ok: true, protocol: 1, supported: deps.supported(), ...job === undefined ? {} : { job } });
25
+ return;
26
+ }
27
+ if (!deps.supported()) {
28
+ replyJson(response, 409, { ok: false, error: 'automatic bridge maintenance requires Windows Desktop' });
29
+ return;
30
+ }
31
+ let action;
32
+ let locale;
33
+ try {
34
+ const value = await readJsonBody(request, 4096);
35
+ if (value?.action !== 'install' && value?.action !== 'uninstall')
36
+ throw new Error('action must be install or uninstall');
37
+ if (value.locale !== undefined && value.locale !== 'zh' && value.locale !== 'en')
38
+ throw new Error('locale must be zh or en');
39
+ action = value.action;
40
+ locale = value.locale;
41
+ }
42
+ catch (error) {
43
+ replyJson(response, 400, { ok: false, error: String(error) });
44
+ return;
45
+ }
46
+ if (starting || deps.busy?.() === true) {
47
+ replyJson(response, 409, { ok: false, error: 'bridge maintenance is already starting' });
48
+ return;
49
+ }
50
+ starting = true;
51
+ try {
52
+ const job = await deps.start(action, locale === undefined ? undefined : { locale });
53
+ if (deps.commit !== undefined) {
54
+ let fired = false;
55
+ const commitOnce = () => {
56
+ if (fired)
57
+ return;
58
+ fired = true;
59
+ void deps.commit?.(job.id).catch(error => { console.error('dsh-builtin-browser: bridge maintenance commit failed:', String(error)); });
60
+ };
61
+ // A client that refreshes or disconnects may fire `close` without `finish`; the worker
62
+ // must be committed (or explicitly cancelled) on either path, exactly once.
63
+ response.once('finish', commitOnce);
64
+ response.once('close', commitOnce);
65
+ }
66
+ replyJson(response, 202, { ok: true, accepted: true, protocol: 1, job });
67
+ }
68
+ catch (error) {
69
+ replyJson(response, 409, { ok: false, error: String(error) });
70
+ }
71
+ finally {
72
+ starting = false;
73
+ }
74
+ };
75
+ }
@@ -0,0 +1,4 @@
1
+ /** Absolute path of the DSH home directory; DSH_HOME overrides the per-user default. */
2
+ export declare function dshHome(): string;
3
+ /** Absolute path of the endpoint file the running desktop shell publishes. */
4
+ export declare function bridgeEndpointPath(): string;
@@ -0,0 +1,19 @@
1
+ /**
2
+ * Where DSH keeps the plugin's per-user state.
3
+ *
4
+ * Every reader — settings, history, the profile root, the maintenance plan and the desktop
5
+ * bridge endpoint — must resolve DSH_HOME the same way. The expression used to be inlined in
6
+ * each module, which let one of them drift to a different directory and produced two
7
+ * half-profiles that never met (see the note in entry.ts).
8
+ * @module dsh-browser/browser-electron/paths
9
+ */
10
+ import { homedir } from 'node:os';
11
+ import { join } from 'node:path';
12
+ /** Absolute path of the DSH home directory; DSH_HOME overrides the per-user default. */
13
+ export function dshHome() {
14
+ return process.env.DSH_HOME ?? join(homedir(), '.dsh');
15
+ }
16
+ /** Absolute path of the endpoint file the running desktop shell publishes. */
17
+ export function bridgeEndpointPath() {
18
+ return join(dshHome(), 'dsh-builtin-browser-bridge.json');
19
+ }