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.
- package/CHANGELOG.md +148 -0
- package/README.en.md +75 -81
- package/README.md +75 -82
- package/client.js +831 -384
- package/desktop-bridge/install-and-start.cmd +4 -5
- package/desktop-bridge/install.mjs +322 -141
- package/desktop-bridge/maintenance-progress.ps1 +166 -0
- package/desktop-bridge/plugin-browser-bridge.js +157 -19
- package/desktop-bridge/request-desktop-quit.ps1 +170 -0
- package/docs/tool-reference.md +20 -1
- package/docs/user-guide.md +28 -4
- package/lib/browser/runtime.d.ts +3 -1
- package/lib/browser/runtime.js +9 -0
- package/lib/browser/types.d.ts +42 -0
- package/lib/browser-electron/authenticated-route.d.ts +27 -0
- package/lib/browser-electron/authenticated-route.js +39 -0
- package/lib/browser-electron/automatic-maintenance.d.ts +41 -0
- package/lib/browser-electron/automatic-maintenance.js +426 -0
- package/lib/browser-electron/bridge-auto.d.ts +93 -0
- package/lib/browser-electron/bridge-auto.js +113 -0
- package/lib/browser-electron/bridge-connection.d.ts +0 -2
- package/lib/browser-electron/bridge-connection.js +2 -4
- package/lib/browser-electron/bridge-endpoint.js +8 -19
- package/lib/browser-electron/bridge-install.d.ts +85 -0
- package/lib/browser-electron/bridge-install.js +211 -0
- package/lib/browser-electron/bridge-maintenance.d.ts +24 -0
- package/lib/browser-electron/bridge-maintenance.js +125 -0
- package/lib/browser-electron/bridge-status.d.ts +10 -3
- package/lib/browser-electron/bridge-status.js +74 -24
- package/lib/browser-electron/desktop-bridge-host.d.ts +11 -5
- package/lib/browser-electron/desktop-bridge-host.js +67 -25
- package/lib/browser-electron/desktop-identity.js +21 -9
- package/lib/browser-electron/electron-provision.d.ts +1 -1
- package/lib/browser-electron/electron-provision.js +36 -13
- package/lib/browser-electron/entry.js +173 -67
- package/lib/browser-electron/ephemeral-profile.js +67 -26
- package/lib/browser-electron/history-store.js +2 -2
- package/lib/browser-electron/host-main.js +48 -38
- package/lib/browser-electron/http-body.d.ts +24 -0
- package/lib/browser-electron/http-body.js +33 -0
- package/lib/browser-electron/json-reply.d.ts +13 -1
- package/lib/browser-electron/json-reply.js +16 -2
- package/lib/browser-electron/maintenance-broker.d.ts +35 -0
- package/lib/browser-electron/maintenance-broker.js +114 -0
- package/lib/browser-electron/maintenance-lifecycle.d.ts +32 -0
- package/lib/browser-electron/maintenance-lifecycle.js +67 -0
- package/lib/browser-electron/maintenance-route.d.ts +18 -0
- package/lib/browser-electron/maintenance-route.js +75 -0
- package/lib/browser-electron/paths.d.ts +4 -0
- package/lib/browser-electron/paths.js +19 -0
- package/lib/browser-electron/process.d.ts +14 -0
- package/lib/browser-electron/process.js +24 -0
- package/lib/browser-electron/provider.d.ts +16 -9
- package/lib/browser-electron/provider.js +87 -18
- package/lib/browser-electron/remote-host.js +22 -20
- package/lib/browser-electron/runtime-route.d.ts +3 -5
- package/lib/browser-electron/runtime-status.d.ts +27 -13
- package/lib/browser-electron/runtime-status.js +28 -6
- package/lib/browser-electron/settings-route.d.ts +5 -18
- package/lib/browser-electron/settings-route.js +4 -14
- package/lib/browser-electron/settings-store.d.ts +28 -0
- package/lib/browser-electron/settings-store.js +32 -2
- package/lib/browser-electron/sidebar-only-host.d.ts +36 -0
- package/lib/browser-electron/sidebar-only-host.js +192 -0
- package/lib/browser-electron/system-browser.d.ts +6 -11
- package/lib/browser-electron/system-browser.js +29 -24
- package/lib/browser-electron/timing.d.ts +8 -0
- package/lib/browser-electron/timing.js +13 -0
- package/lib/browser-electron/windows-system.d.ts +3 -0
- package/lib/browser-electron/windows-system.js +19 -0
- package/lib/tool-browser/index.js +1045 -7
- package/lib/tool-browser/page-probe.d.ts +86 -0
- package/lib/tool-browser/page-probe.js +460 -0
- package/package.json +5 -3
- package/scripts/run-tests.mjs +32 -0
- package/scripts/verify-preview-route.mjs +19 -1
- package/scripts/verify-runtime-status.mjs +14 -0
- package/skills/dsh-builtin-browser/SKILL.md +64 -0
- package/skills/dsh-builtin-browser/references/batch.md +23 -0
- package/skills/dsh-builtin-browser/references/deliver.md +31 -0
- package/skills/dsh-builtin-browser/references/locate.md +11 -0
- package/skills/dsh-builtin-browser/references/recover.md +11 -0
- package/skills/dsh-builtin-browser/references/verify.md +13 -0
- package/src/browser/runtime.ts +11 -0
- package/src/browser/types.ts +19 -0
- package/src/browser-electron/authenticated-route.ts +56 -0
- package/src/browser-electron/automatic-maintenance.ts +414 -0
- package/src/browser-electron/bridge-auto.ts +158 -0
- package/src/browser-electron/bridge-connection.ts +2 -4
- package/src/browser-electron/bridge-endpoint.ts +8 -18
- package/src/browser-electron/bridge-install.ts +253 -0
- package/src/browser-electron/bridge-maintenance.ts +161 -0
- package/src/browser-electron/bridge-status.ts +76 -26
- package/src/browser-electron/desktop-bridge-host.ts +60 -26
- package/src/browser-electron/desktop-identity.ts +18 -9
- package/src/browser-electron/electron-provision.ts +35 -14
- package/src/browser-electron/entry.ts +152 -62
- package/src/browser-electron/ephemeral-profile.ts +65 -28
- package/src/browser-electron/history-store.ts +2 -2
- package/src/browser-electron/host-main.ts +40 -34
- package/src/browser-electron/http-body.ts +42 -0
- package/src/browser-electron/json-reply.ts +18 -3
- package/src/browser-electron/maintenance-broker.ts +142 -0
- package/src/browser-electron/maintenance-lifecycle.ts +86 -0
- package/src/browser-electron/maintenance-route.ts +64 -0
- package/src/browser-electron/paths.ts +21 -0
- package/src/browser-electron/process.ts +23 -0
- package/src/browser-electron/provider.ts +106 -22
- package/src/browser-electron/remote-host.ts +23 -23
- package/src/browser-electron/runtime-route.ts +3 -5
- package/src/browser-electron/runtime-status.ts +56 -19
- package/src/browser-electron/settings-route.ts +9 -32
- package/src/browser-electron/settings-store.ts +59 -3
- package/src/browser-electron/sidebar-only-host.ts +199 -0
- package/src/browser-electron/system-browser.ts +26 -23
- package/src/browser-electron/timing.ts +16 -0
- package/src/browser-electron/windows-system.ts +23 -0
- package/src/tool-browser/index.ts +995 -10
- package/src/tool-browser/page-probe.ts +474 -0
|
@@ -22,17 +22,27 @@ import { randomUUID } from 'node:crypto'
|
|
|
22
22
|
import { existsSync, mkdirSync, renameSync, statSync } from 'node:fs'
|
|
23
23
|
import { homedir } from 'node:os'
|
|
24
24
|
import { dirname, join } from 'node:path'
|
|
25
|
+
import { dshHome } from './paths.js'
|
|
25
26
|
import { setTimeout as wait } from 'node:timers/promises'
|
|
26
27
|
import { defaultHostMainPath, RemoteElectronViewHost } from './remote-host.js'
|
|
27
28
|
import { DesktopBridgeViewHost } from './desktop-bridge-host.js'
|
|
29
|
+
import { SidebarOnlyHost } from './sidebar-only-host.js'
|
|
28
30
|
import { detectBrowser, searchSummary, SystemBrowserViewHost } from './system-browser.js'
|
|
29
31
|
import { claimEphemeralProfile, ephemeralProfileName, sweepAbandonedEphemeralProfiles } from './ephemeral-profile.js'
|
|
30
32
|
import { MissingSystemBrowserHost } from './missing-system-browser.js'
|
|
31
33
|
import { SettingsStore, settingsPath } from './settings-store.js'
|
|
32
34
|
import { sameOrigin } from './settings-route.js'
|
|
35
|
+
import { authenticatedRoute, isDirectLoopback, type BrowserConnection, type BrowserHttpHandler } from './authenticated-route.js'
|
|
33
36
|
import { handleBridgeStatus, handlePreviewFrame, handlePreviewSessions, BRIDGE_STATUS_ROUTE, PREVIEW_ROUTE, PREVIEW_SESSIONS_ROUTE } from './preview-route.js'
|
|
34
37
|
import { findDesktopInstall, readBridgeStatus } from './bridge-status.js'
|
|
35
38
|
import { readBridgeEndpoint } from './bridge-endpoint.js'
|
|
39
|
+
import { runBridgeAction } from './bridge-install.js'
|
|
40
|
+
import { prepareBridgeMaintenance } from './bridge-maintenance.js'
|
|
41
|
+
import { commitAutomaticMaintenance, readAutomaticMaintenance, startAutomaticMaintenance } from './automatic-maintenance.js'
|
|
42
|
+
import { AUTOMATIC_MAINTENANCE_ROUTE, createAutomaticMaintenanceHandler } from './maintenance-route.js'
|
|
43
|
+
import { runWithManualBridgePreference } from './bridge-auto.js'
|
|
44
|
+
import { replyJson, writeJsonText } from './json-reply.js'
|
|
45
|
+
import { readJsonBody, readTextBody } from './http-body.js'
|
|
36
46
|
import { readRuntimeStatus } from './runtime-status.js'
|
|
37
47
|
import { handleRuntimeProvision, handleRuntimeStatus, RUNTIME_PROVISION_ROUTE, RUNTIME_STATUS_ROUTE } from './runtime-route.js'
|
|
38
48
|
|
|
@@ -152,11 +162,8 @@ export function apply(ctx: Context & { browser: BrowserRuntime }, config: Config
|
|
|
152
162
|
return
|
|
153
163
|
}
|
|
154
164
|
|
|
155
|
-
//
|
|
156
|
-
//
|
|
157
|
-
// upgrade is deliberately a swap of the whole provider: the two carriers own
|
|
158
|
-
// different lifetimes (a spawned child vs. the shell's view), and pretending
|
|
159
|
-
// otherwise would leave a stray window behind.
|
|
165
|
+
// Explicit sidebar selection stays on the desktop's carrier, including while its bridge
|
|
166
|
+
// reconnects. Other choices can use the independently hosted browser when appropriate.
|
|
160
167
|
const selfHosted = new RemoteElectronViewHost(defaultHostMainPath())
|
|
161
168
|
// The self-hosted carrier is the only one that needs Electron, and it is prepared HERE, lazily,
|
|
162
169
|
// rather than during package installation (issue #41: a `postinstall` download made a default
|
|
@@ -169,12 +176,22 @@ export function apply(ctx: Context & { browser: BrowserRuntime }, config: Config
|
|
|
169
176
|
if (wantedChannel === 'bundled' || wantedChannel === 'auto') {
|
|
170
177
|
void provisionElectronInBackground(message => ctx.logger?.info?.(`dsh-builtin-browser: ${message}`))
|
|
171
178
|
}
|
|
172
|
-
|
|
179
|
+
const requiredSidebar = (): SidebarOnlyHost => new SidebarOnlyHost(async () => {
|
|
180
|
+
for (const pause of [0, 1_000, 3_000, 8_000]) {
|
|
181
|
+
if (pause > 0) await wait(pause)
|
|
182
|
+
const sidebar = await DesktopBridgeViewHost.discover(sessionId, () => settings.get().ui.quiet)
|
|
183
|
+
if (sidebar !== undefined) return sidebar
|
|
184
|
+
if (DesktopBridgeViewHost.refusedIframePanel()) break
|
|
185
|
+
}
|
|
186
|
+
throw new Error('dsh-builtin-browser: the selected DSH sidebar is not connected. Check or repair the desktop bridge in Browser settings, then retry the same operation.')
|
|
187
|
+
})
|
|
188
|
+
const initialHost = wantedChannel === 'sidebar' ? requiredSidebar() : selfHosted
|
|
189
|
+
let unregister = ctx.browser.registerBrowserProvider(new ElectronBrowserProvider(initialHost, providerConfig))
|
|
173
190
|
let disposed = false
|
|
174
191
|
let carrierChoice = 0
|
|
175
192
|
let discovery: AbortController | undefined
|
|
176
193
|
/** The carrier an `adopt` installed, so a later choice can release it. */
|
|
177
|
-
let adoptedCarrier: ElectronBrowserViewHost | undefined
|
|
194
|
+
let adoptedCarrier: ElectronBrowserViewHost | undefined = initialHost === selfHosted ? undefined : initialHost
|
|
178
195
|
|
|
179
196
|
ctx.effect(() => () => {
|
|
180
197
|
disposed = true
|
|
@@ -204,12 +221,15 @@ export function apply(ctx: Context & { browser: BrowserRuntime }, config: Config
|
|
|
204
221
|
// A replaced carrier may finish an outstanding request after the new choice is installed.
|
|
205
222
|
if (disposed || adoptedCarrier !== adopted) return
|
|
206
223
|
try {
|
|
207
|
-
const
|
|
224
|
+
const sidebarSelected = settings.get().browser.channel === 'sidebar'
|
|
225
|
+
const restored = sidebarSelected ? requiredSidebar() : new RemoteElectronViewHost(defaultHostMainPath())
|
|
208
226
|
unregister()
|
|
209
227
|
unregister = ctx.browser.registerBrowserProvider(new ElectronBrowserProvider(restored, providerConfig))
|
|
210
228
|
adoptedCarrier = restored
|
|
211
229
|
ctx.logger?.warn?.(
|
|
212
|
-
|
|
230
|
+
sidebarSelected
|
|
231
|
+
? 'dsh-builtin-browser: the selected DSH sidebar connection was lost; the next operation will reconnect to the sidebar.'
|
|
232
|
+
: reason === 'shell-exited'
|
|
213
233
|
? 'dsh-builtin-browser: the desktop shell backed the sidebar browser and has exited, so the '
|
|
214
234
|
+ 'browser this plugin hosts itself takes over. Pages from the sidebar are gone with it; '
|
|
215
235
|
+ 'open the page again.'
|
|
@@ -264,7 +284,7 @@ export function apply(ctx: Context & { browser: BrowserRuntime }, config: Config
|
|
|
264
284
|
// A borrowed carrier can lose the process behind it, and this is the only notification that
|
|
265
285
|
// will ever arrive. Registering AFTER the swap succeeded means a listener can never fire
|
|
266
286
|
// against a provider that was never installed.
|
|
267
|
-
host.onLost?.(reason => { restoreSelfHosted(host, reason) })
|
|
287
|
+
if (!(host instanceof SidebarOnlyHost)) host.onLost?.(reason => { restoreSelfHosted(host, reason) })
|
|
268
288
|
// Released AFTER the replacement is installed, so the surface is never without a provider.
|
|
269
289
|
if (previous !== undefined && previous !== host) {
|
|
270
290
|
try { previous.dispose?.() } catch { /* the replacement is already serving */ }
|
|
@@ -282,7 +302,7 @@ export function apply(ctx: Context & { browser: BrowserRuntime }, config: Config
|
|
|
282
302
|
// exit code 1: a failed upgrade, which should only ever cost a warning, took the whole
|
|
283
303
|
// session down instead. Observed 2026-10-05 (crash-…-host.log, phase: running).
|
|
284
304
|
try {
|
|
285
|
-
const fallback = new RemoteElectronViewHost(defaultHostMainPath())
|
|
305
|
+
const fallback = settings.get().browser.channel === 'sidebar' ? requiredSidebar() : new RemoteElectronViewHost(defaultHostMainPath())
|
|
286
306
|
unregister = ctx.browser.registerBrowserProvider(new ElectronBrowserProvider(fallback, providerConfig))
|
|
287
307
|
adoptedCarrier = fallback
|
|
288
308
|
if (previous !== undefined && previous !== host) {
|
|
@@ -329,7 +349,11 @@ export function apply(ctx: Context & { browser: BrowserRuntime }, config: Config
|
|
|
329
349
|
// and a user who picked a browser that is not installed would never see the explanation
|
|
330
350
|
// written for exactly that case, because the sidebar would quietly replace it.
|
|
331
351
|
const explicitChoice: boolean = channel !== 'bundled' && channel !== 'auto' && channel !== 'sidebar'
|
|
332
|
-
if (channel
|
|
352
|
+
if (channel === 'sidebar') {
|
|
353
|
+
if (!(adoptedCarrier instanceof SidebarOnlyHost)) adopt(requiredSidebar(), 'using only the selected DSH sidebar', choice)
|
|
354
|
+
return
|
|
355
|
+
}
|
|
356
|
+
if (channel !== 'bundled') {
|
|
333
357
|
const detected = detectBrowser(channel)
|
|
334
358
|
if (detected === undefined) {
|
|
335
359
|
// `auto` promises to take whatever is available, so falling back is what it
|
|
@@ -352,7 +376,7 @@ export function apply(ctx: Context & { browser: BrowserRuntime }, config: Config
|
|
|
352
376
|
// `C:\Users\<user>\dsh-builtin-browser-host\` while its settings and history lived in
|
|
353
377
|
// `~/.dsh/dsh-builtin-browser-host/` — two half-profiles that never met, and a
|
|
354
378
|
// settings panel whose switches appeared not to apply.
|
|
355
|
-
const home =
|
|
379
|
+
const home = dshHome()
|
|
356
380
|
// Login state lives in the browser profile, so the cookies setting decides where
|
|
357
381
|
// that profile goes: a stable directory keeps the user signed in across restarts
|
|
358
382
|
// (the point of using their own browser), while turning persistence off gets a
|
|
@@ -373,7 +397,7 @@ export function apply(ctx: Context & { browser: BrowserRuntime }, config: Config
|
|
|
373
397
|
// The headless mode rides along so a display-less host (systemd, container, SSH-only server)
|
|
374
398
|
// still gets a working browser instead of "exited immediately after launch" — issue #32.
|
|
375
399
|
adopt(new SystemBrowserViewHost(detected, profileDir, [], persist ? undefined : profileDir,
|
|
376
|
-
undefined, settings.get().browser.headless),
|
|
400
|
+
undefined, settings.get().browser.headless, () => settings.get().ui.quiet),
|
|
377
401
|
`will drive the installed ${detected.kind} (${detected.path}${persist ? '' : ', ephemeral profile'})`)
|
|
378
402
|
}
|
|
379
403
|
} else if (adoptedCarrier !== undefined) {
|
|
@@ -385,9 +409,8 @@ export function apply(ctx: Context & { browser: BrowserRuntime }, config: Config
|
|
|
385
409
|
// An explicit choice was already adopted above; discovering the sidebar here would
|
|
386
410
|
// replace it, which is exactly what this guard prevents.
|
|
387
411
|
//
|
|
388
|
-
//
|
|
389
|
-
|
|
390
|
-
if (explicitChoice && channel !== 'sidebar') return
|
|
412
|
+
// Explicit sidebar selection was handled above by its reconnectable sidebar-only host.
|
|
413
|
+
if (explicitChoice) return
|
|
391
414
|
|
|
392
415
|
// The shell may not be up yet. `dsh web` starts before — or entirely without — the desktop app
|
|
393
416
|
// that hosts the bridge, and a one-shot discovery meant a bridge that appeared a second later
|
|
@@ -404,7 +427,7 @@ export function apply(ctx: Context & { browser: BrowserRuntime }, config: Config
|
|
|
404
427
|
if (signal.aborted || disposed) return
|
|
405
428
|
let sidebar: Awaited<ReturnType<typeof DesktopBridgeViewHost.discover>>
|
|
406
429
|
try {
|
|
407
|
-
sidebar = await DesktopBridgeViewHost.discover(sessionId)
|
|
430
|
+
sidebar = await DesktopBridgeViewHost.discover(sessionId, () => settings.get().ui.quiet)
|
|
408
431
|
} catch {
|
|
409
432
|
sidebar = undefined // discovery is documented not to throw; never let it stop the retries
|
|
410
433
|
}
|
|
@@ -431,17 +454,6 @@ export function apply(ctx: Context & { browser: BrowserRuntime }, config: Config
|
|
|
431
454
|
)
|
|
432
455
|
return
|
|
433
456
|
}
|
|
434
|
-
// The user explicitly asked for the sidebar, so silence would leave them with a setting
|
|
435
|
-
// that did nothing and no way to tell why. This is reachable on `dsh web`, and on a desktop
|
|
436
|
-
// whose shell never published a bridge endpoint. An automatic attempt stays quiet (the
|
|
437
|
-
// self-hosted window is a fine outcome); an explicit request does not.
|
|
438
|
-
if (channel === 'sidebar') {
|
|
439
|
-
ctx.logger?.warn?.(
|
|
440
|
-
'dsh-builtin-browser: the sidebar browser was requested but no desktop bridge was found — '
|
|
441
|
-
+ 'this DSH has no desktop shell, or its bridge never started. Falling back to the bundled '
|
|
442
|
-
+ 'browser; set browser.channel to another value to silence this.',
|
|
443
|
-
)
|
|
444
|
-
}
|
|
445
457
|
})()
|
|
446
458
|
}
|
|
447
459
|
|
|
@@ -472,13 +484,13 @@ export function apply(ctx: Context & { browser: BrowserRuntime }, config: Config
|
|
|
472
484
|
host.effect(() => host.webServer.register({
|
|
473
485
|
kind: 'exact',
|
|
474
486
|
path: PREVIEW_ROUTE,
|
|
475
|
-
handler: (request, response) => handlePreviewFrame(request, response, settings, browser),
|
|
487
|
+
handler: authenticated(ctx, (request, response) => handlePreviewFrame(request, response, settings, browser)),
|
|
476
488
|
}, 'dsh-builtin-browser: live view frame'))
|
|
477
489
|
// The list the panel needs before it can build a frame URL at all: session ids only.
|
|
478
490
|
host.effect(() => host.webServer.register({
|
|
479
491
|
kind: 'exact',
|
|
480
492
|
path: PREVIEW_SESSIONS_ROUTE,
|
|
481
|
-
handler: (request, response) => handlePreviewSessions(request, response, settings, browser),
|
|
493
|
+
handler: authenticated(ctx, (request, response) => handlePreviewSessions(request, response, settings, browser)),
|
|
482
494
|
}, 'dsh-builtin-browser: live view sessions')) })
|
|
483
495
|
} catch {
|
|
484
496
|
// No web server on this surface: watching is simply unavailable, and nothing else changes.
|
|
@@ -493,6 +505,71 @@ export function apply(ctx: Context & { browser: BrowserRuntime }, config: Config
|
|
|
493
505
|
* exactly like the other two.
|
|
494
506
|
* @param ctx - the plugin context.
|
|
495
507
|
*/
|
|
508
|
+
/** Where the panel asks to install or remove the bridge. */
|
|
509
|
+
const BRIDGE_ACTION_ROUTE = '/dsh-builtin-browser/bridge-action'
|
|
510
|
+
let bridgeActionRunning = false
|
|
511
|
+
|
|
512
|
+
/**
|
|
513
|
+
* Prepare external maintenance while Desktop remains open, or execute file maintenance from
|
|
514
|
+
* an independent local host after Desktop has exited.
|
|
515
|
+
* @param request - the incoming request (POST, JSON body `{action, prepare?}`).
|
|
516
|
+
* @param response - the response to write.
|
|
517
|
+
*/
|
|
518
|
+
async function handleBridgeAction(request: IncomingMessage, response: ServerResponse): Promise<void> {
|
|
519
|
+
if (request.method !== 'POST') { replyJson(response, 405, { error: 'method-not-allowed' }); return }
|
|
520
|
+
// Both creating a local launcher and changing installation files require write admission.
|
|
521
|
+
if (!sameOrigin(request, true)) { replyJson(response, 403, { error: 'not-same-origin' }); return }
|
|
522
|
+
if (!isDirectLoopback(request)) { replyJson(response, 403, { error: 'local-request-required' }); return }
|
|
523
|
+
let action: unknown
|
|
524
|
+
let preparationOnly = false
|
|
525
|
+
try {
|
|
526
|
+
const input = await readJsonBody<{ action?: unknown; prepare?: unknown }>(request)
|
|
527
|
+
action = input.action
|
|
528
|
+
if (input.prepare !== undefined && typeof input.prepare !== 'boolean') throw new Error('prepare must be a boolean')
|
|
529
|
+
preparationOnly = input.prepare === true
|
|
530
|
+
} catch (error) {
|
|
531
|
+
replyJson(response, 400, { ok: false, error: `unreadable body: ${String(error)}` })
|
|
532
|
+
return
|
|
533
|
+
}
|
|
534
|
+
if (action !== 'install' && action !== 'uninstall') {
|
|
535
|
+
replyJson(response, 400, { ok: false, error: 'action must be "install" or "uninstall"' })
|
|
536
|
+
return
|
|
537
|
+
}
|
|
538
|
+
const root = findDesktopInstall()
|
|
539
|
+
if (root === undefined) {
|
|
540
|
+
// Nothing to patch: say so instead of running an installer against a guess.
|
|
541
|
+
replyJson(response, 409, { ok: false, error: 'no DSH Desktop install was found on this machine' })
|
|
542
|
+
return
|
|
543
|
+
}
|
|
544
|
+
if (bridgeActionRunning) {
|
|
545
|
+
replyJson(response, 409, { ok: false, error: 'bridge-action-in-progress' })
|
|
546
|
+
return
|
|
547
|
+
}
|
|
548
|
+
const active = readAutomaticMaintenance()
|
|
549
|
+
if (!preparationOnly && active !== undefined && !['completed', 'failed', 'cancelled'].includes(active.phase)) {
|
|
550
|
+
replyJson(response, 409, { ok: false, error: 'an automatic bridge maintenance job is in progress' })
|
|
551
|
+
return
|
|
552
|
+
}
|
|
553
|
+
bridgeActionRunning = true
|
|
554
|
+
try {
|
|
555
|
+
if (preparationOnly) {
|
|
556
|
+
const result = await prepareBridgeMaintenance(action, root)
|
|
557
|
+
replyJson(response, 200, { ...result, action })
|
|
558
|
+
return
|
|
559
|
+
}
|
|
560
|
+
const result = await runWithManualBridgePreference(action, patch => settings.update(patch), () => runBridgeAction(action, root))
|
|
561
|
+
replyJson(response, 200, { ...result, action })
|
|
562
|
+
} catch (error) {
|
|
563
|
+
if (preparationOnly) {
|
|
564
|
+
replyJson(response, 500, { ok: false, error: `could not prepare bridge maintenance: ${String(error)}` })
|
|
565
|
+
return
|
|
566
|
+
}
|
|
567
|
+
replyJson(response, 500, { ok: false, error: String(error instanceof Error ? error.message : error) })
|
|
568
|
+
} finally {
|
|
569
|
+
bridgeActionRunning = false
|
|
570
|
+
}
|
|
571
|
+
}
|
|
572
|
+
|
|
496
573
|
function installBridgeStatusRoute(ctx: Context): void {
|
|
497
574
|
const injectStatus = (ctx as unknown as {
|
|
498
575
|
inject?: (deps: readonly string[], callback: (host: WebServerHost) => void) => void
|
|
@@ -500,11 +577,34 @@ export function apply(ctx: Context & { browser: BrowserRuntime }, config: Config
|
|
|
500
577
|
if (typeof injectStatus !== 'function') return
|
|
501
578
|
try {
|
|
502
579
|
injectStatus(['webServer'], (host) => {
|
|
580
|
+
const automaticMaintenance = createAutomaticMaintenanceHandler({
|
|
581
|
+
supported: () => process.platform === 'win32',
|
|
582
|
+
busy: () => bridgeActionRunning,
|
|
583
|
+
read: () => readAutomaticMaintenance(),
|
|
584
|
+
commit: async id => { await commitAutomaticMaintenance(id) },
|
|
585
|
+
start: async (action, options) => {
|
|
586
|
+
const root = findDesktopInstall()
|
|
587
|
+
if (root === undefined) throw new Error('no verified DSH Desktop installation was found')
|
|
588
|
+
return await runWithManualBridgePreference(action, patch => settings.update(patch),
|
|
589
|
+
async () => await startAutomaticMaintenance(action, root, options))
|
|
590
|
+
},
|
|
591
|
+
})
|
|
592
|
+
host.effect(() => host.webServer.register({
|
|
593
|
+
kind: 'exact', path: AUTOMATIC_MAINTENANCE_ROUTE,
|
|
594
|
+
handler: authenticated(ctx, automaticMaintenance),
|
|
595
|
+
}, 'dsh-builtin-browser: explicit automatic bridge maintenance'))
|
|
503
596
|
host.effect(() => host.webServer.register({
|
|
504
597
|
kind: 'exact',
|
|
505
598
|
path: BRIDGE_STATUS_ROUTE,
|
|
506
|
-
handler: (request, response) => handleBridgeStatus(request, response),
|
|
599
|
+
handler: authenticated(ctx, (request, response) => handleBridgeStatus(request, response)),
|
|
507
600
|
}, 'dsh-builtin-browser: bridge status'))
|
|
601
|
+
// The panel prepares a launcher without changing the running Desktop. Direct local
|
|
602
|
+
// maintenance remains available once Desktop has exited.
|
|
603
|
+
host.effect(() => host.webServer.register({
|
|
604
|
+
kind: 'exact',
|
|
605
|
+
path: BRIDGE_ACTION_ROUTE,
|
|
606
|
+
handler: authenticated(ctx, (request, response) => handleBridgeAction(request, response)),
|
|
607
|
+
}, 'dsh-builtin-browser: bridge action'))
|
|
508
608
|
})
|
|
509
609
|
} catch {
|
|
510
610
|
// No web server: the panel is unreachable, and the installer stays the interface.
|
|
@@ -513,6 +613,9 @@ export function apply(ctx: Context & { browser: BrowserRuntime }, config: Config
|
|
|
513
613
|
|
|
514
614
|
installSettingsRoute(ctx, settings, () => { chooseCarrier() })
|
|
515
615
|
|
|
616
|
+
// Bridge maintenance is explicit and requires DSH Desktop to be closed. Loading a provider
|
|
617
|
+
// never starts an installer, including with an older settings file's bridge.autoInstall=true.
|
|
618
|
+
|
|
516
619
|
/**
|
|
517
620
|
* Expose readiness — "can the browser serve a call right now" — for the settings panel.
|
|
518
621
|
*
|
|
@@ -535,6 +638,8 @@ export function apply(ctx: Context & { browser: BrowserRuntime }, config: Config
|
|
|
535
638
|
const deps = {
|
|
536
639
|
report: () => readRuntimeStatus({
|
|
537
640
|
channel: () => settings.get().browser.channel,
|
|
641
|
+
selectedCarrier: () => adoptedCarrier instanceof DesktopBridgeViewHost || adoptedCarrier instanceof SidebarOnlyHost ? 'sidebar'
|
|
642
|
+
: adoptedCarrier instanceof SystemBrowserViewHost ? 'system' : 'bundled',
|
|
538
643
|
hasBinary: hasElectronRuntime,
|
|
539
644
|
provision: provisionSnapshot,
|
|
540
645
|
bridge: () => {
|
|
@@ -561,12 +666,12 @@ export function apply(ctx: Context & { browser: BrowserRuntime }, config: Config
|
|
|
561
666
|
host.effect(() => host.webServer.register({
|
|
562
667
|
kind: 'exact',
|
|
563
668
|
path: RUNTIME_STATUS_ROUTE,
|
|
564
|
-
handler: (request, response) => handleRuntimeStatus(request, response, deps),
|
|
669
|
+
handler: authenticated(ctx, (request, response) => handleRuntimeStatus(request, response, deps)),
|
|
565
670
|
}, 'dsh-builtin-browser: runtime status'))
|
|
566
671
|
host.effect(() => host.webServer.register({
|
|
567
672
|
kind: 'exact',
|
|
568
673
|
path: RUNTIME_PROVISION_ROUTE,
|
|
569
|
-
handler: (request, response) => handleRuntimeProvision(request, response, deps),
|
|
674
|
+
handler: authenticated(ctx, (request, response) => handleRuntimeProvision(request, response, deps)),
|
|
570
675
|
}, 'dsh-builtin-browser: runtime provision'))
|
|
571
676
|
})
|
|
572
677
|
} catch {
|
|
@@ -602,7 +707,7 @@ export function apply(ctx: Context & { browser: BrowserRuntime }, config: Config
|
|
|
602
707
|
lastChannel = channel
|
|
603
708
|
ctx.logger?.info?.(`dsh-builtin-browser: settings changed on disk, re-choosing the carrier for channel "${channel}"`)
|
|
604
709
|
chooseCarrier()
|
|
605
|
-
},
|
|
710
|
+
}, 5_000)
|
|
606
711
|
// Unref-ed so a poll never holds the process open.
|
|
607
712
|
timer.unref?.()
|
|
608
713
|
ctx.effect(() => () => { clearInterval(timer) }, "dsh-builtin-browser: settings file watch")
|
|
@@ -667,6 +772,14 @@ interface PreviewBrowser {
|
|
|
667
772
|
watchableSessions?(): readonly string[]
|
|
668
773
|
}
|
|
669
774
|
|
|
775
|
+
/** Bind the host's signed browser-session authentication to a plugin route. */
|
|
776
|
+
function authenticated(ctx: Context, handler: BrowserHttpHandler): BrowserHttpHandler {
|
|
777
|
+
return authenticatedRoute(() => {
|
|
778
|
+
const surface = ctx as unknown as { get(name: string): BrowserConnection | undefined }
|
|
779
|
+
return surface.get('connection')
|
|
780
|
+
}, handler)
|
|
781
|
+
}
|
|
782
|
+
|
|
670
783
|
/** The host web-server surface this plugin uses, described structurally. */
|
|
671
784
|
interface WebServerHost {
|
|
672
785
|
readonly webServer: {
|
|
@@ -704,7 +817,7 @@ function installSettingsRoute(
|
|
|
704
817
|
host.effect(() => host.webServer.register({
|
|
705
818
|
kind: 'exact',
|
|
706
819
|
path: SETTINGS_ROUTE,
|
|
707
|
-
handler: (request, response) => handleSettingsRequest(request, response, settings, onChannelChange),
|
|
820
|
+
handler: authenticated(ctx, (request, response) => handleSettingsRequest(request, response, settings, onChannelChange)),
|
|
708
821
|
}, 'dsh-builtin-browser: settings'))
|
|
709
822
|
})
|
|
710
823
|
} catch {
|
|
@@ -727,11 +840,10 @@ async function handleSettingsRequest(
|
|
|
727
840
|
onChannelChange?: () => void,
|
|
728
841
|
): Promise<void> {
|
|
729
842
|
const json = (status: number, body: unknown): void => {
|
|
730
|
-
response.
|
|
843
|
+
writeJsonText(response, status, JSON.stringify(body), {
|
|
731
844
|
'content-type': 'application/json; charset=utf-8',
|
|
732
845
|
'cache-control': 'no-store',
|
|
733
846
|
})
|
|
734
|
-
response.end(JSON.stringify(body))
|
|
735
847
|
}
|
|
736
848
|
const method = request.method ?? 'GET'
|
|
737
849
|
if (!sameOrigin(request, method !== 'GET')) {
|
|
@@ -748,8 +860,8 @@ async function handleSettingsRequest(
|
|
|
748
860
|
return
|
|
749
861
|
}
|
|
750
862
|
try {
|
|
751
|
-
const
|
|
752
|
-
const patch: unknown =
|
|
863
|
+
const text = await readTextBody(request)
|
|
864
|
+
const patch: unknown = text.trim() === '' ? {} : JSON.parse(text)
|
|
753
865
|
const before = settings.get().browser.channel
|
|
754
866
|
const updated = settings.update(patch)
|
|
755
867
|
// A changed `browser.channel` is a request to switch carriers, not just a value to store. The
|
|
@@ -768,25 +880,3 @@ async function handleSettingsRequest(
|
|
|
768
880
|
}
|
|
769
881
|
}
|
|
770
882
|
|
|
771
|
-
/**
|
|
772
|
-
* Read a request body with a hard cap (the settings patch is tiny, and an
|
|
773
|
-
* unbounded read would let any same-origin caller exhaust memory).
|
|
774
|
-
* @param request - the incoming request.
|
|
775
|
-
* @param limit - maximum accepted characters.
|
|
776
|
-
* @returns the body text.
|
|
777
|
-
*/
|
|
778
|
-
function readBody(request: IncomingMessage, limit = 64 * 1024): Promise<string> {
|
|
779
|
-
return new Promise<string>((resolve, reject) => {
|
|
780
|
-
let text = ''
|
|
781
|
-
request.setEncoding('utf8')
|
|
782
|
-
request.on('data', chunk => {
|
|
783
|
-
text += String(chunk)
|
|
784
|
-
if (text.length > limit) {
|
|
785
|
-
request.destroy()
|
|
786
|
-
reject(new Error('settings patch too large'))
|
|
787
|
-
}
|
|
788
|
-
})
|
|
789
|
-
request.on('end', () => resolve(text))
|
|
790
|
-
request.on('error', reject)
|
|
791
|
-
})
|
|
792
|
-
}
|
|
@@ -10,14 +10,15 @@
|
|
|
10
10
|
* this module provides.
|
|
11
11
|
*
|
|
12
12
|
* Ownership is a marker file inside the directory naming the process that claimed it. A
|
|
13
|
-
* directory whose owner is gone AND
|
|
14
|
-
* abandoned. The age check is what keeps the sweep away from a profile an orphaned
|
|
15
|
-
*
|
|
16
|
-
*
|
|
17
|
-
*
|
|
13
|
+
* directory whose owner is gone AND whose whole tree has not been written to for a while is
|
|
14
|
+
* abandoned. The age check is what keeps the sweep away from a profile an orphaned browser
|
|
15
|
+
* (a child that outlived the parent which was killed) may still be using: a live Chromium
|
|
16
|
+
* writes nested files continuously, so a tree with a recent write is not abandoned — even
|
|
17
|
+
* when the root directory's own timestamp is old, because writing a file does not update it.
|
|
18
18
|
*/
|
|
19
|
-
import { mkdirSync, readFileSync, readdirSync, rmSync, statSync, writeFileSync } from 'node:fs'
|
|
19
|
+
import { lstatSync, mkdirSync, readFileSync, readdirSync, rmSync, statSync, writeFileSync } from 'node:fs'
|
|
20
20
|
import { join } from 'node:path'
|
|
21
|
+
import { pidAlive } from './process.js'
|
|
21
22
|
|
|
22
23
|
/** The marker file, named once because both the claim and the sweep read it. */
|
|
23
24
|
const OWNER_FILE = '.dsh-ephemeral-owner'
|
|
@@ -29,6 +30,12 @@ const OWNER_FILE = '.dsh-ephemeral-owner'
|
|
|
29
30
|
*/
|
|
30
31
|
const ABANDONED_AFTER_MS = 60 * 60 * 1000
|
|
31
32
|
|
|
33
|
+
/**
|
|
34
|
+
* Ceiling on how much of a profile tree one sweep inspects. A tree we cannot fully inspect is
|
|
35
|
+
* not proven abandoned, so it is kept; this only bounds the cost of saying so.
|
|
36
|
+
*/
|
|
37
|
+
const MAX_SWEEP_ENTRIES = 20_000
|
|
38
|
+
|
|
32
39
|
/** Test seams; production passes neither. */
|
|
33
40
|
export interface SweepOptions {
|
|
34
41
|
/** The clock, for the age check. */
|
|
@@ -37,23 +44,6 @@ export interface SweepOptions {
|
|
|
37
44
|
readonly alive?: (pid: number) => boolean
|
|
38
45
|
}
|
|
39
46
|
|
|
40
|
-
/**
|
|
41
|
-
* Whether a process with this pid exists.
|
|
42
|
-
*
|
|
43
|
-
* A signal of 0 performs the permission and existence checks without delivering anything.
|
|
44
|
-
* EPERM is a live process owned by someone else — alive, not gone.
|
|
45
|
-
* @param pid - the pid to test.
|
|
46
|
-
* @returns true when the process exists.
|
|
47
|
-
*/
|
|
48
|
-
function processAlive(pid: number): boolean {
|
|
49
|
-
try {
|
|
50
|
-
process.kill(pid, 0)
|
|
51
|
-
return true
|
|
52
|
-
} catch (error) {
|
|
53
|
-
return (error as NodeJS.ErrnoException).code === 'EPERM'
|
|
54
|
-
}
|
|
55
|
-
}
|
|
56
|
-
|
|
57
47
|
/**
|
|
58
48
|
* The directory name an ephemeral profile for `kind` gets, before it is claimed.
|
|
59
49
|
*
|
|
@@ -104,6 +94,51 @@ function readOwner(dir: string): number | undefined {
|
|
|
104
94
|
}
|
|
105
95
|
}
|
|
106
96
|
|
|
97
|
+
/**
|
|
98
|
+
* The most recent write anywhere in a profile tree.
|
|
99
|
+
*
|
|
100
|
+
* A Chromium process writes nested files (`Default/Network/Cookies`, `Default/History`, ...).
|
|
101
|
+
* Writing a file does NOT refresh the mtime of the parent directory, so a quiet ROOT timestamp
|
|
102
|
+
* cannot prove the browser has exited — exactly the case where a killed DSH leaves a live child
|
|
103
|
+
* behind. Inspect the tree instead of just its root.
|
|
104
|
+
*
|
|
105
|
+
* Anything that cannot be inspected is reported as "written now", so the caller keeps the
|
|
106
|
+
* directory. When the evidence is incomplete, leaving a profile behind is the only safe outcome.
|
|
107
|
+
* Symbolic links are never followed, and an entry budget bounds the work.
|
|
108
|
+
* @param dir - the profile directory.
|
|
109
|
+
* @param now - the clock value used as the conservative "active" answer.
|
|
110
|
+
* @returns the newest mtime in the tree, or `-Infinity` when the tree holds nothing but our marker.
|
|
111
|
+
*/
|
|
112
|
+
function latestWriteMs(dir: string, now: number): number {
|
|
113
|
+
let latest = Number.NEGATIVE_INFINITY
|
|
114
|
+
let budget = MAX_SWEEP_ENTRIES
|
|
115
|
+
const pending = [dir]
|
|
116
|
+
while (pending.length > 0) {
|
|
117
|
+
const current = pending.pop() as string
|
|
118
|
+
let entries
|
|
119
|
+
try {
|
|
120
|
+
entries = readdirSync(current, { withFileTypes: true })
|
|
121
|
+
} catch {
|
|
122
|
+
return now
|
|
123
|
+
}
|
|
124
|
+
for (const entry of entries) {
|
|
125
|
+
if (budget-- <= 0) return now
|
|
126
|
+
// Our owner marker is written once at claim time; it is not browser activity.
|
|
127
|
+
if (current === dir && entry.name === OWNER_FILE) continue
|
|
128
|
+
const path = join(current, entry.name)
|
|
129
|
+
let stat
|
|
130
|
+
try {
|
|
131
|
+
stat = lstatSync(path)
|
|
132
|
+
} catch {
|
|
133
|
+
return now
|
|
134
|
+
}
|
|
135
|
+
if (stat.mtimeMs > latest) latest = stat.mtimeMs
|
|
136
|
+
if (stat.isDirectory() && !stat.isSymbolicLink()) pending.push(path)
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
return latest
|
|
140
|
+
}
|
|
141
|
+
|
|
107
142
|
/**
|
|
108
143
|
* Delete the ephemeral profiles under `root` that belong to processes which are gone.
|
|
109
144
|
*
|
|
@@ -116,7 +151,7 @@ function readOwner(dir: string): number | undefined {
|
|
|
116
151
|
*/
|
|
117
152
|
export function sweepAbandonedEphemeralProfiles(root: string, kind: string, options: SweepOptions = {}): string[] {
|
|
118
153
|
const now = options.now ?? Date.now()
|
|
119
|
-
const alive = options.alive ??
|
|
154
|
+
const alive = options.alive ?? pidAlive
|
|
120
155
|
const prefix = `${kind}-profile-ephemeral-`
|
|
121
156
|
const removed: string[] = []
|
|
122
157
|
let names: string[]
|
|
@@ -129,14 +164,16 @@ export function sweepAbandonedEphemeralProfiles(root: string, kind: string, opti
|
|
|
129
164
|
for (const name of names) {
|
|
130
165
|
if (!name.startsWith(prefix)) continue
|
|
131
166
|
const dir = join(root, name)
|
|
132
|
-
let
|
|
167
|
+
let rootMtime: number
|
|
133
168
|
try {
|
|
134
|
-
|
|
169
|
+
rootMtime = statSync(dir).mtimeMs
|
|
135
170
|
} catch {
|
|
136
171
|
continue
|
|
137
172
|
}
|
|
138
|
-
// Recent writes mean a browser is still working in there. A killed DSH
|
|
139
|
-
// Chromium child running, and
|
|
173
|
+
// Recent writes ANYWHERE in the tree mean a browser is still working in there. A killed DSH
|
|
174
|
+
// can leave its Chromium child running, and a child writing Default/Network/Cookies does not
|
|
175
|
+
// refresh the root directory's mtime. Judging the root alone deleted live profiles.
|
|
176
|
+
const ageMs = now - Math.max(rootMtime, latestWriteMs(dir, now))
|
|
140
177
|
if (ageMs < ABANDONED_AFTER_MS) continue
|
|
141
178
|
const owner = readOwner(dir)
|
|
142
179
|
if (owner !== undefined && alive(owner)) continue
|
|
@@ -14,8 +14,8 @@
|
|
|
14
14
|
*/
|
|
15
15
|
|
|
16
16
|
import { appendFileSync, existsSync, mkdirSync, readFileSync } from 'node:fs'
|
|
17
|
-
import { homedir } from 'node:os'
|
|
18
17
|
import { dirname, join } from 'node:path'
|
|
18
|
+
import { dshHome } from './paths.js'
|
|
19
19
|
import type { VisitedPage } from '../browser/types.js'
|
|
20
20
|
import { writeFileAtomic } from './settings-store.js'
|
|
21
21
|
|
|
@@ -42,7 +42,7 @@ const PRUNE_SLACK = 500
|
|
|
42
42
|
* @returns the history file path.
|
|
43
43
|
*/
|
|
44
44
|
export function visitedHistoryPath(): string {
|
|
45
|
-
const home =
|
|
45
|
+
const home = dshHome()
|
|
46
46
|
return join(home, 'dsh-builtin-browser-host', 'history.jsonl')
|
|
47
47
|
}
|
|
48
48
|
|