dsh-builtin-browser 0.5.7 → 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 (94) hide show
  1. package/CHANGELOG.md +66 -0
  2. package/README.en.md +48 -22
  3. package/README.md +48 -22
  4. package/client.js +469 -81
  5. package/desktop-bridge/install-and-start.cmd +4 -5
  6. package/desktop-bridge/install.mjs +251 -159
  7. package/desktop-bridge/maintenance-progress.ps1 +166 -0
  8. package/desktop-bridge/plugin-browser-bridge.js +151 -18
  9. package/desktop-bridge/request-desktop-quit.ps1 +170 -0
  10. package/docs/user-guide.md +28 -4
  11. package/lib/browser-electron/automatic-maintenance.d.ts +41 -0
  12. package/lib/browser-electron/automatic-maintenance.js +426 -0
  13. package/lib/browser-electron/bridge-auto.d.ts +93 -0
  14. package/lib/browser-electron/bridge-auto.js +113 -0
  15. package/lib/browser-electron/bridge-connection.d.ts +0 -2
  16. package/lib/browser-electron/bridge-connection.js +2 -4
  17. package/lib/browser-electron/bridge-endpoint.js +1 -19
  18. package/lib/browser-electron/bridge-install.d.ts +41 -4
  19. package/lib/browser-electron/bridge-install.js +131 -18
  20. package/lib/browser-electron/bridge-maintenance.d.ts +24 -0
  21. package/lib/browser-electron/bridge-maintenance.js +125 -0
  22. package/lib/browser-electron/bridge-status.d.ts +10 -3
  23. package/lib/browser-electron/bridge-status.js +76 -45
  24. package/lib/browser-electron/desktop-bridge-host.d.ts +5 -2
  25. package/lib/browser-electron/desktop-bridge-host.js +54 -33
  26. package/lib/browser-electron/desktop-identity.js +21 -9
  27. package/lib/browser-electron/electron-provision.js +5 -2
  28. package/lib/browser-electron/entry.js +104 -74
  29. package/lib/browser-electron/ephemeral-profile.js +67 -26
  30. package/lib/browser-electron/history-store.js +2 -2
  31. package/lib/browser-electron/host-main.js +26 -37
  32. package/lib/browser-electron/http-body.d.ts +24 -0
  33. package/lib/browser-electron/http-body.js +33 -0
  34. package/lib/browser-electron/json-reply.d.ts +13 -1
  35. package/lib/browser-electron/json-reply.js +16 -2
  36. package/lib/browser-electron/maintenance-broker.d.ts +35 -0
  37. package/lib/browser-electron/maintenance-broker.js +114 -0
  38. package/lib/browser-electron/maintenance-lifecycle.d.ts +32 -0
  39. package/lib/browser-electron/maintenance-lifecycle.js +67 -0
  40. package/lib/browser-electron/maintenance-route.d.ts +18 -0
  41. package/lib/browser-electron/maintenance-route.js +75 -0
  42. package/lib/browser-electron/paths.d.ts +4 -0
  43. package/lib/browser-electron/paths.js +19 -0
  44. package/lib/browser-electron/process.d.ts +14 -0
  45. package/lib/browser-electron/process.js +24 -0
  46. package/lib/browser-electron/provider.d.ts +7 -7
  47. package/lib/browser-electron/provider.js +13 -14
  48. package/lib/browser-electron/remote-host.js +18 -16
  49. package/lib/browser-electron/runtime-status.d.ts +27 -13
  50. package/lib/browser-electron/runtime-status.js +24 -4
  51. package/lib/browser-electron/settings-store.d.ts +11 -0
  52. package/lib/browser-electron/settings-store.js +8 -2
  53. package/lib/browser-electron/sidebar-only-host.d.ts +36 -0
  54. package/lib/browser-electron/sidebar-only-host.js +192 -0
  55. package/lib/browser-electron/system-browser.d.ts +1 -9
  56. package/lib/browser-electron/system-browser.js +19 -22
  57. package/lib/browser-electron/timing.d.ts +8 -0
  58. package/lib/browser-electron/timing.js +13 -0
  59. package/lib/browser-electron/windows-system.d.ts +3 -0
  60. package/lib/browser-electron/windows-system.js +19 -0
  61. package/lib/tool-browser/index.js +5 -4
  62. package/package.json +2 -2
  63. package/scripts/run-tests.mjs +32 -0
  64. package/scripts/verify-preview-route.mjs +19 -1
  65. package/src/browser-electron/automatic-maintenance.ts +414 -0
  66. package/src/browser-electron/bridge-auto.ts +158 -0
  67. package/src/browser-electron/bridge-connection.ts +2 -4
  68. package/src/browser-electron/bridge-endpoint.ts +1 -18
  69. package/src/browser-electron/bridge-install.ts +151 -20
  70. package/src/browser-electron/bridge-maintenance.ts +161 -0
  71. package/src/browser-electron/bridge-status.ts +78 -48
  72. package/src/browser-electron/desktop-bridge-host.ts +48 -32
  73. package/src/browser-electron/desktop-identity.ts +18 -9
  74. package/src/browser-electron/electron-provision.ts +5 -2
  75. package/src/browser-electron/entry.ts +91 -69
  76. package/src/browser-electron/ephemeral-profile.ts +65 -28
  77. package/src/browser-electron/history-store.ts +2 -2
  78. package/src/browser-electron/host-main.ts +23 -36
  79. package/src/browser-electron/http-body.ts +42 -0
  80. package/src/browser-electron/json-reply.ts +18 -3
  81. package/src/browser-electron/maintenance-broker.ts +142 -0
  82. package/src/browser-electron/maintenance-lifecycle.ts +86 -0
  83. package/src/browser-electron/maintenance-route.ts +64 -0
  84. package/src/browser-electron/paths.ts +21 -0
  85. package/src/browser-electron/process.ts +23 -0
  86. package/src/browser-electron/provider.ts +18 -18
  87. package/src/browser-electron/remote-host.ts +19 -19
  88. package/src/browser-electron/runtime-status.ts +52 -17
  89. package/src/browser-electron/settings-store.ts +20 -3
  90. package/src/browser-electron/sidebar-only-host.ts +199 -0
  91. package/src/browser-electron/system-browser.ts +19 -22
  92. package/src/browser-electron/timing.ts +16 -0
  93. package/src/browser-electron/windows-system.ts +23 -0
  94. package/src/tool-browser/index.ts +5 -4
@@ -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
+ }
@@ -621,13 +621,14 @@ export function toCdpCookie(cookie: ExportedCookie): Record<string, unknown> | u
621
621
  * `quiet` is the resolved `ui.quiet` switch. It does not mean "invisible": Chromium drops
622
622
  * synthesized `Input.*` for a view without a display surface, so input still needs one. It means
623
623
  * the carrier must get that surface without taking the screen over — no application activation
624
- * and no keyboard focus. Navigation and tab switching only reveal the view inside its window; the
625
- * pre-input barrier may restore a minimized window (it needs the surface), but even then it shows
626
- * it inactive instead of focusing or raising it. A host that cannot honour this (a headless probe,
627
- * the desktop sidebar) simply ignores it.
624
+ * and no operating-system keyboard focus. New windows open inactive; a minimized window and the
625
+ * foreground window's selected page remain under the operator's control. DOM focus and CDP input
626
+ * still target the task's page. Explicit sidebar navigation can select the task's pane.
628
627
  */
629
628
  export interface PresentOptions {
630
629
  readonly quiet?: boolean
630
+ /** Explicit navigation or tab selection may change the task's sidebar tab without OS activation. */
631
+ readonly select?: boolean
631
632
  }
632
633
 
633
634
  /**
@@ -910,7 +911,7 @@ export class ElectronBrowserProvider implements BrowserProvider {
910
911
  const tab: Tab = { id: `page:${match.id}`, handle, url: match.url }
911
912
  s.tabs.push(tab)
912
913
  s.activeIndex = s.tabs.length - 1
913
- this.showActive(s)
914
+ this.showActive(s, true)
914
915
  return true
915
916
  } catch {
916
917
  // The page went away between listing and adopting: fall through to an ordinary navigation.
@@ -996,7 +997,7 @@ export class ElectronBrowserProvider implements BrowserProvider {
996
997
  }
997
998
  const found = this.locateTab(session, tabId)
998
999
  found.s.activeIndex = found.index
999
- this.showActive(found.s)
1000
+ this.showActive(found.s, true)
1000
1001
  }
1001
1002
 
1002
1003
  /** Close one tab; closing the active tab activates the next. */
@@ -1137,7 +1138,7 @@ export class ElectronBrowserProvider implements BrowserProvider {
1137
1138
  tab.url = url
1138
1139
  await this.settleDocument(handle, before, signal)
1139
1140
  this.recordVisit(s, handle)
1140
- this.showActive(s)
1141
+ this.showActive(s, true)
1141
1142
  } catch (error) {
1142
1143
  if (!(error instanceof BrowserError && (error as { code?: string }).code === 'BROWSER_NAVIGATION_BLOCKED')) {
1143
1144
  this.record(s, 'navigate', { url }, false, { error: String(error) })
@@ -3139,9 +3140,8 @@ export class ElectronBrowserProvider implements BrowserProvider {
3139
3140
 
3140
3141
  /**
3141
3142
  * Download an HTTP(S) URL with the session's cookies to a local file.
3142
- * Admission is the shared {@link admitSavePath} gate; only the self-hosted
3143
- * host implements it (the desktop shell's embedded views delegate downloads
3144
- * to the real browser UI). Both admitted paths and screenshots are confined
3143
+ * Admission is the shared {@link admitSavePath} gate. The carrier downloads
3144
+ * with its own authenticated browser session. Both admitted paths and screenshots are confined
3145
3145
  * to `downloadDir`, so a prompt-injected agent cannot write arbitrary
3146
3146
  * machine paths.
3147
3147
  * @param session - the session whose cookies are used.
@@ -3173,7 +3173,7 @@ export class ElectronBrowserProvider implements BrowserProvider {
3173
3173
  const savePath = this.admitSavePath(request.savePath, 'download')
3174
3174
  const downloadable = handle
3175
3175
  if (typeof downloadable.download !== 'function') {
3176
- throw new BrowserError('browser: download is only available on the self-hosted browser', 'BROWSER_DOWNLOAD_UNSUPPORTED')
3176
+ throw new BrowserError('browser: the selected carrier does not provide file downloads', 'BROWSER_DOWNLOAD_UNSUPPORTED')
3177
3177
  }
3178
3178
  // The child fetches and writes the file; a slow/hung network can block
3179
3179
  // it well past the tool budget, so bound it. NOTE: unlike CDP calls,
@@ -3280,15 +3280,15 @@ export class ElectronBrowserProvider implements BrowserProvider {
3280
3280
  if (dropped > 0) {
3281
3281
  process.stderr.write(`[dsh-browser] restoreAuth: dropped ${dropped} of ${mapped.length} cookie(s) with no usable domain; the rest were still restored\n`)
3282
3282
  }
3283
- const result = await withTimeout(
3283
+ await withTimeout(
3284
3284
  handle.sendCommand('Storage.setCookies', { cookies: convertible }),
3285
3285
  timeoutMs,
3286
3286
  undefined,
3287
3287
  `browser: auth restore timed out after ${timeoutMs}ms`,
3288
3288
  )
3289
- // Storage.setCookies returns nothing, so the count comes from what was actually
3290
- // sent. Reading result.cookies here was always undefined, which rendered as
3291
- // "Restored 0 cookies." while the write had succeeded.
3289
+ // Storage.setCookies returns nothing, so the count comes from what was actually sent.
3290
+ // An earlier version read result.cookies here; it was always undefined and rendered as
3291
+ // "Restored 0 cookies." even though the write had succeeded.
3292
3292
  const restored = convertible.length
3293
3293
  this.record(s, 'restoreAuth', { count: cookies.length, dropped }, true, { result: `${restored} cookies (CDP)${dropped > 0 ? `; ${dropped} dropped` : ''}` })
3294
3294
  return restored
@@ -3901,10 +3901,10 @@ export class ElectronBrowserProvider implements BrowserProvider {
3901
3901
  * method did nothing at all on carriers without `collapse` (the self-hosted one),
3902
3902
  * silently desynchronising the two and failing every screenshot.
3903
3903
  */
3904
- private showActive(s: Session): void {
3904
+ private showActive(s: Session, select = false): void {
3905
3905
  const quiet = this.isQuiet()
3906
- this.host.showView?.(this.activeTab(s).handle, s.label, { quiet })
3907
- if (quiet) return
3906
+ this.host.showView?.(this.activeTab(s).handle, s.label, { quiet, ...select ? { select: true } : {} })
3907
+ if (quiet || select) return
3908
3908
  const autoExpand = this.settingsSource === undefined || this.settingsSource().ui.autoExpandOnce
3909
3909
  if (autoExpand) return
3910
3910
  // Best effort: a carrier that owns no presentation (self-hosted) simply has none.
@@ -34,6 +34,7 @@ import { createRequire } from 'node:module'
34
34
  import { existsSync, readFileSync, readdirSync, readlinkSync } from 'node:fs'
35
35
  import { basename, dirname, isAbsolute, join } from 'node:path'
36
36
  import { createServer, type Server, type Socket } from 'node:net'
37
+ import { withTimeoutShared } from './timing.js'
37
38
  import { fileURLToPath } from 'node:url'
38
39
  import type { BrowserUserAction, ElectronBrowserViewHost, ElectronViewHandle, PresentOptions, ScreenshotOptions } from './provider.js'
39
40
  import type { ExportedCookie } from '../browser/types.js'
@@ -263,15 +264,20 @@ function hostElectronViaProcessTree(): string | undefined {
263
264
  return undefined
264
265
  }
265
266
 
267
+ /** One scalar property of a Windows process, read through CIM. */
268
+ function cimQuery(pid: number, property: 'ExecutablePath' | 'ParentProcessId'): string {
269
+ const out = execFileSync('powershell.exe', [
270
+ '-NoProfile', '-NonInteractive', '-Command',
271
+ `(Get-CimInstance Win32_Process -Filter "ProcessId=${pid}").${property}`,
272
+ ], { encoding: 'utf8', windowsHide: true, timeout: 3000 })
273
+ return out.trim().split(/\r?\n/)[0] ?? ''
274
+ }
275
+
266
276
  /** The executable path of a running process, or undefined when unknown. */
267
277
  function processExecutable(pid: number): string | undefined {
268
278
  try {
269
279
  if (process.platform === 'win32') {
270
- const out = execFileSync('powershell.exe', [
271
- '-NoProfile', '-NonInteractive', '-Command',
272
- `(Get-CimInstance Win32_Process -Filter "ProcessId=${pid}").ExecutablePath`,
273
- ], { encoding: 'utf8', windowsHide: true, timeout: 3000 })
274
- const line = out.trim().split(/\r?\n/)[0] ?? ''
280
+ const line = cimQuery(pid, 'ExecutablePath')
275
281
  return line.length > 0 ? line : undefined
276
282
  }
277
283
  const exe = readlinkSync(`/proc/${pid}/exe`)
@@ -285,11 +291,7 @@ function processExecutable(pid: number): string | undefined {
285
291
  function processParent(pid: number): number | undefined {
286
292
  try {
287
293
  if (process.platform === 'win32') {
288
- const out = execFileSync('powershell.exe', [
289
- '-NoProfile', '-NonInteractive', '-Command',
290
- `(Get-CimInstance Win32_Process -Filter "ProcessId=${pid}").ParentProcessId`,
291
- ], { encoding: 'utf8', windowsHide: true, timeout: 3000 })
292
- const n = Number(out.trim().split(/\r?\n/)[0])
294
+ const n = Number(cimQuery(pid, 'ParentProcessId'))
293
295
  return Number.isInteger(n) && n > 1 ? n : undefined
294
296
  }
295
297
  const stat = readFileSync(`/proc/${pid}/stat`, 'utf8')
@@ -1425,21 +1427,19 @@ function appendHostLog(text: string): void {
1425
1427
  // history of a crash loop gets silently swallowed.
1426
1428
  writeFileSync(file, `${hostStamp()} log rotated: previous content exceeded ${String(HOST_LOG_MAX_BYTES)} bytes and was discarded\n`)
1427
1429
  }
1428
- } catch { /* first write, or unreadable: just append */ }
1429
- mkdirSync(dir, { recursive: true })
1430
+ } catch {
1431
+ // No readable file yet: the log directory may not exist. When statSync
1432
+ // succeeded the file exists, so its directory does too and creating it
1433
+ // again was a redundant syscall on every child stdout/stderr line.
1434
+ mkdirSync(dir, { recursive: true })
1435
+ }
1430
1436
  appendFileSync(file, text)
1431
1437
  } catch { /* diagnostics are best-effort only */ }
1432
1438
  }
1433
1439
 
1434
1440
  /** Reject a promise if it does not settle within the budget. */
1435
1441
  function withTimeout<T>(promise: Promise<T>, ms: number, message: string): Promise<T> {
1436
- return new Promise<T>((resolve, reject) => {
1437
- const timer = setTimeout(() => reject(new Error(`${message} (${ms}ms)`)), ms)
1438
- promise.then(
1439
- value => { clearTimeout(timer); resolve(value) },
1440
- error => { clearTimeout(timer); reject(error) },
1441
- )
1442
- })
1442
+ return withTimeoutShared(promise, ms, () => new Error(`${message} (${ms}ms)`))
1443
1443
  }
1444
1444
 
1445
1445
  /** Default host-main path relative to this module's build output. */