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
@@ -33,6 +33,7 @@ import { electronRuntimeDiagnosticLines } from './runtime-diagnostics.js'
33
33
  import { createRpcLineReader } from './rpc-input.js'
34
34
  import { tmpdir } from 'node:os'
35
35
  import { join } from 'node:path'
36
+ import { withTimeoutShared } from './timing.js'
36
37
 
37
38
  // Report the binary actually running this child, even when ELECTRON_PATH
38
39
  // intentionally selects a different version from the plugin's dependency.
@@ -293,15 +294,7 @@ function ensureToolbarFiles(): void {
293
294
  * explicit error instead of a command that never settles.
294
295
  */
295
296
  function withTimeout<T>(promise: Promise<T>, ms: number, label: string): Promise<T> {
296
- return new Promise<T>((resolve, reject) => {
297
- const timer = setTimeout(() => {
298
- reject(new Error(`${label} timed out after ${ms}ms`))
299
- }, ms)
300
- promise.then(
301
- (value) => { clearTimeout(timer); resolve(value) },
302
- (error) => { clearTimeout(timer); reject(error) },
303
- )
304
- })
297
+ return withTimeoutShared(promise, ms, () => new Error(`${label} timed out after ${ms}ms`))
305
298
  }
306
299
 
307
300
  /**
@@ -412,7 +405,12 @@ function windowFor(windowId: string | undefined): HostWindow {
412
405
  const key = windowId === undefined || windowId === '' ? SHARED_WINDOW_ID : windowId
413
406
  const existing = windows.get(key)
414
407
  if (existing !== undefined) return existing
415
- const w = new BrowserWindow({ width: 1400, height: 900, show: true, title: 'dsh-browser' })
408
+ // `show: false` on purpose: creating a window must not be a presentation decision. With `show: true`
409
+ // the window appeared and took the screen the moment the first tool call created it — before any
410
+ // `showView` message could carry `ui.quiet`, so quiet mode had no effect at all on this carrier
411
+ // (measured: the setting was on and the window still popped up). The first presentation decides:
412
+ // quiet shows it inactive, a normal call shows it normally.
413
+ const w = new BrowserWindow({ width: 1400, height: 900, show: false, title: 'dsh-browser' })
416
414
  w.on('closed', () => {
417
415
  const closing = windows.get(key)
418
416
  windows.delete(key)
@@ -495,7 +493,9 @@ function wireFocusRouting(win: HostWindow, view: WebContentsView, focusKey: stri
495
493
  view.webContents.on('input-event', (_event, input) => {
496
494
  if (input.type !== 'mouseDown') return
497
495
  win.lastFocusedViewId = focusKey
498
- try { view.webContents.focus() } catch { /* destroyed */ }
496
+ if (win.window.isFocused()) {
497
+ try { view.webContents.focus() } catch { /* destroyed */ }
498
+ }
499
499
  })
500
500
  }
501
501
 
@@ -615,31 +615,35 @@ function revealViewInWindow(win: HostWindow, viewId: string, label?: string): vo
615
615
  * @param viewId - the view to present.
616
616
  * @param label - session/task label, when known, for the window title.
617
617
  * @param quiet - `ui.quiet`: present without taking the screen over.
618
- * @param needSurface - quiet mode only: this presentation is the barrier before synthesized
619
- * input, so the window has to be visible even if the user minimized it. A navigation or a tab
620
- * switch does not need that and leaves a minimized window alone.
618
+ * @param _needSurface - pre-input barrier flag retained by the RPC protocol. Quiet presentation
619
+ * opens a new visible window without activation and preserves an existing foreground page.
621
620
  */
622
- function showViewInWindow(win: HostWindow, viewId: string, label?: string, quiet = false, needSurface = false): void {
621
+ function showViewInWindow(win: HostWindow, viewId: string, label?: string, quiet = false, _needSurface = false): void {
622
+ if (quiet) {
623
+ if (win.window.isMinimized()) return
624
+ // Preserve the page the operator is actively reading. Other views remain addressable by
625
+ // their own CDP session, without switching the foreground window's selected page.
626
+ if (win.window.isFocused() && win.visibleViewId !== viewId) return
627
+ revealViewInWindow(win, viewId, label)
628
+ // Quiet means a normal usable window without activation, including on the first open.
629
+ // An invisible surface made the browser look broken even after navigation succeeded.
630
+ if (win.window.getOpacity() === 0) {
631
+ win.window.setOpacity(1)
632
+ win.window.setSkipTaskbar(false)
633
+ win.window.setFocusable(true)
634
+ }
635
+ if (!win.window.isVisible()) win.window.showInactive()
636
+ return
637
+ }
623
638
  revealViewInWindow(win, viewId, label)
624
- // Raise this session's window so the human sees the page being worked on
625
- // (moveTop raises without stealing keyboard focus).
626
- //
627
- // Quiet mode (`ui.quiet`): the user asked not to be interrupted, so this must not
628
- // activate the application, steal keyboard focus, or pull the window in front of the one
629
- // they are using. Chromium drops `Input.*` for a view with no display surface, so the one
630
- // case that still needs a visible window — the barrier before synthesized input — restores
631
- // it with `showInactive()`, which shows it without becoming the key window, and never calls
632
- // `moveTop()`. Everything else (navigation, tab switching, screenshots) leaves a minimized
633
- // window minimized.
634
639
  try {
635
- if (quiet) {
636
- if (!needSurface) return
637
- if (win.window.isMinimized()) win.window.restore()
638
- if (!win.window.isVisible()) win.window.showInactive()
639
- } else {
640
- if (!win.window.isVisible()) win.window.show()
641
- win.window.moveTop()
640
+ if (win.window.getOpacity() === 0) {
641
+ win.window.setFocusable(true)
642
+ win.window.setOpacity(1)
643
+ win.window.setSkipTaskbar(false)
642
644
  }
645
+ if (!win.window.isVisible()) win.window.show()
646
+ win.window.moveTop()
643
647
  } catch { /* closing */ }
644
648
  }
645
649
 
@@ -821,7 +825,9 @@ async function handle(op: string, msg: { id: number; viewId?: string; windowId?:
821
825
  // and `document.hasFocus()` inside the page even read true.
822
826
  const contents = entry.webContentsView.webContents
823
827
  const hadWebFocus = contents.isFocused()
824
- contents.focus()
828
+ // Electron webContents.focus() can activate its BrowserWindow. CDP input uses the
829
+ // target page's DOM focus and does not require that operating-system activation.
830
+ if (msg.quiet !== true) contents.focus()
825
831
  // Focus lands asynchronously, and a key dispatched in the same turn as
826
832
  // the request is still dropped, so hold the reply until the renderer can
827
833
  // take input. Only on the call where focus actually had to move.
@@ -859,7 +865,7 @@ async function handle(op: string, msg: { id: number; viewId?: string; windowId?:
859
865
  // The active tab has to be the visible one INSIDE the window, or the capture may read
860
866
  // another tab. Keep that switch contentView-local: show/restore/focus are precisely
861
867
  // what quiet mode forbids.
862
- revealViewInWindow(win, viewId)
868
+ if (!win.window.isVisible() || win.window.getOpacity() === 0) revealViewInWindow(win, viewId)
863
869
  } else {
864
870
  try {
865
871
  if (!win.window.isVisible()) win.window.show()
@@ -0,0 +1,42 @@
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
+ /**
10
+ * Read a body as UTF-8 text. Chunks are collected as Buffers and decoded once: setting an
11
+ * encoding on the stream and concatenating `String(chunk)` corrupts a multi-byte character that
12
+ * happens to be split across two TCP chunks.
13
+ * @param request - the incoming request.
14
+ * @param limit - maximum accepted bytes.
15
+ * @returns the body text.
16
+ */
17
+ export async function readTextBody(request: IncomingMessage, limit = 64 * 1024): Promise<string> {
18
+ const chunks: Buffer[] = []
19
+ let size = 0
20
+ for await (const chunk of request) {
21
+ const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(String(chunk))
22
+ size += buffer.length
23
+ if (size > limit) {
24
+ request.destroy()
25
+ throw new Error(`request body exceeds ${limit} bytes`)
26
+ }
27
+ chunks.push(buffer)
28
+ }
29
+ return Buffer.concat(chunks).toString('utf8')
30
+ }
31
+
32
+ /**
33
+ * Read and parse a JSON body. An empty body is an empty object, matching the settings route's
34
+ * long-standing behaviour.
35
+ * @param request - the incoming request.
36
+ * @param limit - maximum accepted bytes.
37
+ * @returns the parsed value.
38
+ */
39
+ export async function readJsonBody<T>(request: IncomingMessage, limit = 64 * 1024): Promise<T> {
40
+ const text = await readTextBody(request, limit)
41
+ return JSON.parse(text === '' ? '{}' : text) as T
42
+ }
@@ -11,7 +11,7 @@
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
  /**
17
17
  * Write one JSON body with no caching and no sniffing.
@@ -19,14 +19,29 @@ import type { ServerResponse } from 'node:http'
19
19
  * @param status - the HTTP status.
20
20
  * @param body - anything JSON-serialisable.
21
21
  */
22
+ /**
23
+ * Write an already-serialised JSON body with caller-supplied headers.
24
+ *
25
+ * Routes do not all need the same header set: readiness answers carry length and sniffing
26
+ * headers, while the settings route has always returned only a content type and no-store.
27
+ * Sharing the write keeps those exact header sets from drifting into each other.
28
+ * @param response - the response to write.
29
+ * @param status - the HTTP status.
30
+ * @param text - the serialised body.
31
+ * @param headers - the exact header set this route has always sent.
32
+ */
33
+ export function writeJsonText(response: ServerResponse, status: number, text: string, headers: OutgoingHttpHeaders): void {
34
+ response.writeHead(status, headers)
35
+ response.end(text)
36
+ }
37
+
22
38
  export function replyJson(response: ServerResponse, status: number, body: unknown): void {
23
39
  const text = JSON.stringify(body)
24
- response.writeHead(status, {
40
+ writeJsonText(response, status, text, {
25
41
  'content-type': 'application/json; charset=utf-8',
26
42
  'content-length': Buffer.byteLength(text),
27
43
  'cache-control': 'no-store, private',
28
44
  'x-content-type-options': 'nosniff',
29
45
  'cross-origin-resource-policy': 'same-origin',
30
46
  })
31
- response.end(text)
32
47
  }
@@ -0,0 +1,142 @@
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
+
12
+ export interface MaintenanceBrokerOptions {
13
+ readonly runtimePath: string
14
+ readonly args: readonly string[]
15
+ readonly cwd: string
16
+ /** Overrides for the explicitly inherited environment; undefined removes a variable. */
17
+ readonly environment?: Readonly<Record<string, string | undefined>>
18
+ }
19
+
20
+ export interface MaintenanceBrokerExecution {
21
+ readonly windowsHide: true
22
+ readonly shell: false
23
+ readonly encoding: 'utf8'
24
+ readonly timeout: number
25
+ readonly maxBuffer: number
26
+ readonly env: NodeJS.ProcessEnv
27
+ }
28
+
29
+ export type MaintenanceBrokerExecutor = (
30
+ file: string,
31
+ args: readonly string[],
32
+ options: MaintenanceBrokerExecution,
33
+ ) => Promise<{ readonly stdout: string; readonly stderr: string }>
34
+
35
+ export interface MaintenanceBrokerDeps {
36
+ /** Tests supply a fake executor; the real broker is prohibited inside the test runner. */
37
+ readonly execFile?: MaintenanceBrokerExecutor
38
+ readonly platform?: NodeJS.Platform
39
+ }
40
+
41
+ export interface MaintenanceBrokerResult {
42
+ readonly pid: number
43
+ }
44
+
45
+ /** Quote one argument using the Windows C runtime's command-line decoding rules. */
46
+ export function quoteWin32Argument(value: string): string {
47
+ if (typeof value !== 'string' || value.includes('\0')) throw new Error('a Windows process argument must be a string without NUL')
48
+ // Backslashes are literal except immediately before a quote or the closing quote. At those
49
+ // positions each slash must be doubled, and an embedded quote receives one additional slash.
50
+ return '"' + value.replace(/(\\*)"/g, '$1$1\\"').replace(/(\\+)$/, '$1$1') + '"'
51
+ }
52
+
53
+ function absolutePath(value: string, label: string): string {
54
+ if (typeof value !== 'string' || value.includes('\0') || value.includes('"')
55
+ || !/^(?:[A-Za-z]:[\\/]|\\\\[^\\/]+[\\/][^\\/]+)/.test(value)) {
56
+ throw new Error(`${label} must be a fully qualified Windows path without NUL or quotes`)
57
+ }
58
+ return win32.normalize(value)
59
+ }
60
+
61
+ /** Apply Windows' case-insensitive variable names before passing one explicit environment. */
62
+ function inheritEnvironment(overrides: MaintenanceBrokerOptions['environment']): NodeJS.ProcessEnv {
63
+ const environment = { ...process.env }
64
+ for (const [key, value] of Object.entries(overrides ?? {})) {
65
+ if (key === '' || /[=\0]/.test(key) || (value !== undefined && (typeof value !== 'string' || value.includes('\0')))) {
66
+ throw new Error('maintenance environment names and values must be valid Windows environment strings')
67
+ }
68
+ for (const existing of Object.keys(environment)) if (existing.toUpperCase() === key.toUpperCase()) delete environment[existing]
69
+ if (value !== undefined) environment[key] = value
70
+ }
71
+ return environment
72
+ }
73
+
74
+ function underTest(environment: NodeJS.ProcessEnv): boolean {
75
+ return Object.entries(environment).some(([key, value]) =>
76
+ (key.toUpperCase() === 'DSH_BROWSER_TEST' && value === '1')
77
+ || (key.toUpperCase() === 'NODE_TEST_CONTEXT' && value !== undefined))
78
+ }
79
+
80
+ const defaultExecutor: MaintenanceBrokerExecutor = (file, args, options) => new Promise((resolve, reject) => {
81
+ execFile(file, [...args], options, (error, stdout, stderr) => {
82
+ if (error !== null) {
83
+ const reason = stderr.trim() || (error as NodeJS.ErrnoException).code || 'PowerShell did not complete'
84
+ reject(new Error(`Windows maintenance broker failed: ${String(reason).slice(-1_000)}`))
85
+ } else resolve({ stdout, stderr })
86
+ })
87
+ })
88
+
89
+ /**
90
+ * Create a hidden, independent local process. No shell evaluates runtime paths or arguments.
91
+ * WMI receives an explicit environment copied from this process, including any plan overrides;
92
+ * it therefore does not accidentally inherit the provider service's unrelated environment.
93
+ */
94
+ export async function launchMaintenanceBroker(
95
+ options: MaintenanceBrokerOptions,
96
+ deps: MaintenanceBrokerDeps = {},
97
+ ): Promise<MaintenanceBrokerResult> {
98
+ const environment = inheritEnvironment(options.environment)
99
+ if (deps.execFile === undefined && (underTest(process.env) || underTest(environment))) {
100
+ throw new Error('the real Windows maintenance broker is disabled in tests; inject a fake executor')
101
+ }
102
+ if ((deps.platform ?? process.platform) !== 'win32') throw new Error('the maintenance broker requires Windows')
103
+ const runtimePath = absolutePath(options.runtimePath, 'runtimePath')
104
+ const cwd = absolutePath(options.cwd, 'cwd')
105
+ if (!statSync(runtimePath).isFile()) throw new Error('the maintenance runtime is not a file')
106
+ if (!statSync(cwd).isDirectory()) throw new Error('the maintenance working directory is not a directory')
107
+ if (!Array.isArray(options.args)) throw new Error('maintenance arguments must be an array')
108
+ const commandLine = [runtimePath, ...options.args].map(quoteWin32Argument).join(' ')
109
+ if (commandLine.length >= 32_767) throw new Error('the maintenance command exceeds the Windows command-line limit')
110
+ const payload = Buffer.from(JSON.stringify({ commandLine, cwd }), 'utf8').toString('base64')
111
+ // The only interpolated script data is Base64 JSON. The full environment is inherited by
112
+ // execFile, then read as data here rather than embedded in the PowerShell command line.
113
+ const script = `$ErrorActionPreference = 'Stop'
114
+ [Console]::OutputEncoding = New-Object System.Text.UTF8Encoding($false)
115
+ try {
116
+ $plan = [System.Text.Encoding]::UTF8.GetString([System.Convert]::FromBase64String('${payload}')) | ConvertFrom-Json
117
+ $environment = [string[]]@([System.Environment]::GetEnvironmentVariables('Process').GetEnumerator() | ForEach-Object { [string]$_.Key + '=' + [string]$_.Value })
118
+ $startup = New-CimInstance -Namespace root/cimv2 -ClassName Win32_ProcessStartup -ClientOnly -Property @{ ShowWindow = [uint16]0; CreateFlags = [uint32]1024; EnvironmentVariables = $environment }
119
+ $result = Invoke-CimMethod -Namespace root/cimv2 -ClassName Win32_Process -MethodName Create -Arguments @{ CommandLine = [string]$plan.commandLine; CurrentDirectory = [string]$plan.cwd; ProcessStartupInformation = $startup }
120
+ @{ code = [uint32]$result.ReturnValue; pid = [uint32]$result.ProcessId } | ConvertTo-Json -Compress
121
+ } catch {
122
+ [Console]::Error.WriteLine($_.Exception.Message)
123
+ exit 1
124
+ }
125
+ `
126
+ const encoded = encodePowerShellScript(script)
127
+ const powershellPath = windowsPowerShellPath()
128
+ if (encoded.length + powershellPath.length + 100 >= 32_767) throw new Error('the encoded maintenance broker command exceeds the Windows command-line limit')
129
+ const result = await (deps.execFile ?? defaultExecutor)(powershellPath,
130
+ ['-NoLogo', '-NoProfile', '-NonInteractive', '-EncodedCommand', encoded],
131
+ { windowsHide: true, shell: false, encoding: 'utf8', timeout: 30_000, maxBuffer: 64_000, env: environment })
132
+ let record: { code?: unknown; pid?: unknown }
133
+ try { record = JSON.parse(result.stdout.replace(/^\uFEFF/, '').trim()) as typeof record } catch {
134
+ throw new Error('the Windows maintenance broker returned an unreadable result')
135
+ }
136
+ if (record === null || typeof record !== 'object' || !Number.isSafeInteger(record.code) || Number(record.code) < 0) {
137
+ throw new Error('the Windows maintenance broker returned an invalid result')
138
+ }
139
+ if (record.code !== 0) throw new Error(`Windows maintenance broker refused process creation (WMI code ${String(record.code)})`)
140
+ if (!Number.isSafeInteger(record.pid) || Number(record.pid) <= 0) throw new Error('the Windows maintenance broker returned no valid process id')
141
+ return { pid: Number(record.pid) }
142
+ }
@@ -0,0 +1,86 @@
1
+ /** Explicit bridge maintenance lifecycle, independent of the Desktop-owned HTTP request. */
2
+ import type { BridgeAction, BridgeActionResult } from './bridge-install.js'
3
+
4
+ export type MaintenancePhase = 'armed' | 'closing' | 'installing' | 'restarting' | 'verifying' | 'completed' | 'cancelled' | 'failed'
5
+
6
+ export interface MaintenanceState {
7
+ readonly phase: MaintenancePhase
8
+ readonly action: BridgeAction
9
+ readonly at: string
10
+ readonly ok?: boolean
11
+ readonly restarted?: boolean
12
+ readonly pid?: number
13
+ readonly error?: string
14
+ readonly output?: string
15
+ }
16
+
17
+ /** Effects are supplied by the independent worker; tests cannot close or start an application. */
18
+ export interface MaintenanceLifecycleDeps {
19
+ /** Invoke the verified Desktop's own Quit menu item. Never confirm active-task dialogs. */
20
+ readonly requestQuit: () => Promise<void>
21
+ /** Resolve only once every GUI/helper process belonging to this installation has exited. */
22
+ readonly waitUntilClosed: () => Promise<void>
23
+ /** The existing installer retains its own identity, ancestry and running-process checks. */
24
+ readonly maintain: () => Promise<BridgeActionResult>
25
+ /** Reopen exactly the verified installation after it has exited. */
26
+ readonly restart: () => Promise<number>
27
+ /** Installation verifies the new authenticated bridge; uninstall verifies the process. */
28
+ readonly verify: (pid: number, action: BridgeAction) => Promise<void>
29
+ readonly publish: (state: MaintenanceState) => Promise<void>
30
+ }
31
+
32
+ /**
33
+ * A cancelled/failed quit never reaches the installer. After a confirmed exit, reopen Desktop even
34
+ * when maintenance fails, and retain that failure instead of reporting a successful installation.
35
+ */
36
+ export async function runMaintenanceLifecycle(action: BridgeAction, deps: MaintenanceLifecycleDeps): Promise<MaintenanceState> {
37
+ let closed = false
38
+ let restarted = false
39
+ let pid: number | undefined
40
+ let outcome: BridgeActionResult | undefined
41
+ let publicationFailure: unknown
42
+ const publish = async (phase: MaintenancePhase, extra: Partial<MaintenanceState> = {}): Promise<MaintenanceState> => {
43
+ const state: MaintenanceState = { phase, action, at: new Date().toISOString(), ...extra }
44
+ try { await deps.publish(state) } catch (error) {
45
+ // Arming must be durable before any quit is requested. Later status I/O must never
46
+ // prevent reopening a Desktop that already exited normally.
47
+ if (phase === 'armed') throw error
48
+ publicationFailure ??= error
49
+ }
50
+ return state
51
+ }
52
+ await publish('armed')
53
+ try {
54
+ await deps.requestQuit()
55
+ await publish('closing')
56
+ await deps.waitUntilClosed()
57
+ closed = true
58
+ } catch (error) {
59
+ return await publish('cancelled', { ok: false, restarted: false, error: String(error) })
60
+ }
61
+ let failure: unknown
62
+ try {
63
+ await publish('installing')
64
+ outcome = await deps.maintain()
65
+ if (!outcome.ok) throw new Error(outcome.output || 'bridge maintenance failed')
66
+ } catch (error) { failure = error }
67
+ try {
68
+ // `closed` is set only by the successful closed-process barrier, never by a timeout.
69
+ if (!closed) throw new Error('Desktop exit was not confirmed')
70
+ await publish('restarting')
71
+ pid = await deps.restart()
72
+ if (!Number.isSafeInteger(pid) || pid <= 0) throw new Error('Desktop restart did not return a valid process')
73
+ restarted = true
74
+ await publish('verifying', { pid, restarted })
75
+ await deps.verify(pid, failure === undefined ? action : 'uninstall')
76
+ } catch (error) {
77
+ failure = failure === undefined ? error : new Error(`${String(failure)}; Desktop recovery: ${String(error)}`)
78
+ }
79
+ if (failure === undefined && publicationFailure !== undefined) {
80
+ failure = new Error(`Desktop maintenance finished, but progress could not be saved: ${String(publicationFailure)}`)
81
+ }
82
+ const details = { restarted, ...pid === undefined ? {} : { pid }, ...outcome?.output ? { output: outcome.output } : {} }
83
+ return failure === undefined
84
+ ? await publish('completed', { ...details, ok: true })
85
+ : await publish('failed', { ...details, ok: false, error: String(failure) })
86
+ }
@@ -0,0 +1,64 @@
1
+ /** Authenticated explicit maintenance protocol; older hosts cannot mistake it for direct install. */
2
+ import type { IncomingMessage, ServerResponse } from 'node:http'
3
+ import { sameOrigin } from './settings-route.js'
4
+ import { isDirectLoopback } from './authenticated-route.js'
5
+ import { replyJson } from './json-reply.js'
6
+ import { readJsonBody } from './http-body.js'
7
+ import type { BridgeAction } from './bridge-install.js'
8
+ import type { AutomaticMaintenanceJob } from './automatic-maintenance.js'
9
+
10
+ export const AUTOMATIC_MAINTENANCE_ROUTE = '/dsh-builtin-browser/bridge-maintenance'
11
+ export interface AutomaticMaintenanceRouteDeps {
12
+ readonly supported: () => boolean
13
+ readonly read: () => AutomaticMaintenanceJob | undefined
14
+ readonly start: (action: BridgeAction, options?: { readonly locale?: 'zh' | 'en' }) => Promise<AutomaticMaintenanceJob>
15
+ /** Commit only after the accepted response has been flushed to the client. */
16
+ readonly commit?: (id: string) => Promise<void>
17
+ /** True while the legacy bridge-action route is running an installer. */
18
+ readonly busy?: () => boolean
19
+ }
20
+
21
+ /** Register behind the host's signed-session authentication, as with settings writes. */
22
+ export function createAutomaticMaintenanceHandler(deps: AutomaticMaintenanceRouteDeps): (request: IncomingMessage, response: ServerResponse) => Promise<void> {
23
+ let starting = false
24
+ return async (request, response) => {
25
+ if (request.method !== 'GET' && request.method !== 'POST') { replyJson(response, 405, { ok: false, error: 'method-not-allowed' }); return }
26
+ if (!sameOrigin(request, request.method === 'POST')) { replyJson(response, 403, { ok: false, error: 'not-same-origin' }); return }
27
+ if (!isDirectLoopback(request)) { replyJson(response, 403, { ok: false, error: 'local-request-required' }); return }
28
+ if (request.method === 'GET') {
29
+ const job = deps.read()
30
+ replyJson(response, 200, { ok: true, protocol: 1, supported: deps.supported(), ...job === undefined ? {} : { job } })
31
+ return
32
+ }
33
+ if (!deps.supported()) { replyJson(response, 409, { ok: false, error: 'automatic bridge maintenance requires Windows Desktop' }); return }
34
+ let action: BridgeAction
35
+ let locale: 'zh' | 'en' | undefined
36
+ try {
37
+ const value = await readJsonBody<{ action?: unknown; locale?: unknown }>(request, 4096)
38
+ if (value?.action !== 'install' && value?.action !== 'uninstall') throw new Error('action must be install or uninstall')
39
+ if (value.locale !== undefined && value.locale !== 'zh' && value.locale !== 'en') throw new Error('locale must be zh or en')
40
+ action = value.action
41
+ locale = value.locale
42
+ } catch (error) { replyJson(response, 400, { ok: false, error: String(error) }); return }
43
+ if (starting || deps.busy?.() === true) { replyJson(response, 409, { ok: false, error: 'bridge maintenance is already starting' }); return }
44
+ starting = true
45
+ try {
46
+ const job = await deps.start(action, locale === undefined ? undefined : { locale })
47
+ if (deps.commit !== undefined) {
48
+ let fired = false
49
+ const commitOnce = (): void => {
50
+ if (fired) return
51
+ fired = true
52
+ void deps.commit?.(job.id).catch(error => { console.error('dsh-builtin-browser: bridge maintenance commit failed:', String(error)) })
53
+ }
54
+ // A client that refreshes or disconnects may fire `close` without `finish`; the worker
55
+ // must be committed (or explicitly cancelled) on either path, exactly once.
56
+ response.once('finish', commitOnce)
57
+ response.once('close', commitOnce)
58
+ }
59
+ replyJson(response, 202, { ok: true, accepted: true, protocol: 1, job })
60
+ } catch (error) {
61
+ replyJson(response, 409, { ok: false, error: String(error) })
62
+ } finally { starting = false }
63
+ }
64
+ }
@@ -0,0 +1,21 @@
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
+
13
+ /** Absolute path of the DSH home directory; DSH_HOME overrides the per-user default. */
14
+ export function dshHome(): string {
15
+ return process.env.DSH_HOME ?? join(homedir(), '.dsh')
16
+ }
17
+
18
+ /** Absolute path of the endpoint file the running desktop shell publishes. */
19
+ export function bridgeEndpointPath(): string {
20
+ return join(dshHome(), 'dsh-builtin-browser-bridge.json')
21
+ }
@@ -0,0 +1,23 @@
1
+ /**
2
+ * One shared definition of process liveness.
3
+ *
4
+ * Signal 0 performs the permission and existence checks and delivers nothing, so it is safe to
5
+ * call on a pid we only read from a file. `EPERM` means the process exists and belongs to
6
+ * someone else, which is still "alive" for the endpoint reader and the profile sweeper alike.
7
+ * @module dsh-browser/browser-electron/process
8
+ */
9
+
10
+ /**
11
+ * Whether a process with this pid exists, without signalling it.
12
+ * @param pid - the process id to test; a non-integer or non-positive value is never alive.
13
+ * @returns whether that process exists.
14
+ */
15
+ export function pidAlive(pid: number): boolean {
16
+ if (!Number.isSafeInteger(pid) || pid <= 0) return false
17
+ try {
18
+ process.kill(pid, 0)
19
+ return true
20
+ } catch (error) {
21
+ return (error as NodeJS.ErrnoException)?.code === 'EPERM'
22
+ }
23
+ }