dsh-builtin-browser 1.0.3 → 1.0.4
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/README.en.md +89 -0
- package/browser-extension/constants.mjs +20 -0
- package/browser-extension/controller.mjs +293 -0
- package/browser-extension/locales.mjs +15 -0
- package/browser-extension/manifest.json +12 -0
- package/browser-extension/options.html +14 -0
- package/browser-extension/options.mjs +9 -0
- package/browser-extension/permission-guard.mjs +13 -0
- package/browser-extension/worker.mjs +74 -0
- package/package.json +20 -2
- package/scripts/build-client.mjs +305 -0
- package/scripts/build.mjs +69 -0
- package/scripts/bundle-host.mjs +28 -0
- package/scripts/fix-exports.mjs +40 -0
- package/scripts/install-electron.mjs +101 -0
- package/scripts/pack.mjs +99 -0
- package/scripts/publish-manifest.mjs +56 -0
- package/scripts/verify-exports.mjs +58 -0
- package/scripts/verify-preview-sdk.mjs +93 -0
- package/skills/dsh-builtin-browser/SKILL.md +98 -0
- package/skills/dsh-builtin-browser/references/batch.md +68 -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/skills/dsh-debug-host/SKILL.md +56 -0
- package/skills/dsh-debug-self/SKILL.md +50 -0
- package/src/bridge-compatibility.ts +39 -0
- package/src/browser/anti-bot.ts +251 -0
- package/src/browser/deep-dom.ts +40 -0
- package/src/browser/handles.ts +89 -0
- package/src/browser/runtime.ts +578 -0
- package/src/browser/takeover-target.ts +45 -0
- package/src/browser/types.ts +870 -0
- package/src/browser-electron/authenticated-route.ts +109 -0
- package/src/browser-electron/automatic-maintenance.ts +736 -0
- package/src/browser-electron/bridge-auto.ts +159 -0
- package/src/browser-electron/bridge-connection.ts +386 -0
- package/src/browser-electron/bridge-endpoint.ts +129 -0
- package/src/browser-electron/bridge-install.ts +290 -0
- package/src/browser-electron/bridge-maintenance.ts +189 -0
- package/src/browser-electron/bridge-status.ts +386 -0
- package/src/browser-electron/desktop-bridge-host.ts +253 -0
- package/src/browser-electron/desktop-identity.ts +353 -0
- package/src/browser-electron/desktop-shell.ts +100 -0
- package/src/browser-electron/document-readiness.ts +45 -0
- package/src/browser-electron/electron-provision.ts +347 -0
- package/src/browser-electron/entry.ts +1378 -0
- package/src/browser-electron/ephemeral-profile.ts +189 -0
- package/src/browser-electron/extension-browser.ts +230 -0
- package/src/browser-electron/extension-setup.ts +67 -0
- package/src/browser-electron/file-write.ts +31 -0
- package/src/browser-electron/foreground-watch.ts +142 -0
- package/src/browser-electron/guest-cookie-jar.ts +177 -0
- package/src/browser-electron/guest-cookie-store.ts +59 -0
- package/src/browser-electron/guest-css-runtime.ts +76 -0
- package/src/browser-electron/guest-css.ts +68 -0
- package/src/browser-electron/guest-route.ts +716 -0
- package/src/browser-electron/guest-runtime.ts +408 -0
- package/src/browser-electron/guest-storage-runtime.ts +54 -0
- package/src/browser-electron/guest-storage.ts +120 -0
- package/src/browser-electron/history-store.ts +224 -0
- package/src/browser-electron/host-main.ts +1385 -0
- package/src/browser-electron/host-patch-maintenance.ts +121 -0
- package/src/browser-electron/http-body.ts +65 -0
- package/src/browser-electron/json-reply.ts +47 -0
- package/src/browser-electron/maintenance-broker.ts +166 -0
- package/src/browser-electron/maintenance-lifecycle.ts +91 -0
- package/src/browser-electron/maintenance-route.ts +68 -0
- package/src/browser-electron/missing-system-browser.ts +114 -0
- package/src/browser-electron/open-slot.ts +49 -0
- package/src/browser-electron/paths.ts +25 -0
- package/src/browser-electron/preferred-browser.ts +130 -0
- package/src/browser-electron/preview-route.ts +215 -0
- package/src/browser-electron/process-ownership.ts +174 -0
- package/src/browser-electron/process.ts +23 -0
- package/src/browser-electron/profile-checkpoint.ts +187 -0
- package/src/browser-electron/profile-command.ts +47 -0
- package/src/browser-electron/profile-extension.ts +129 -0
- package/src/browser-electron/profile-lease.ts +211 -0
- package/src/browser-electron/profile-residue.ts +49 -0
- package/src/browser-electron/provider-core.ts +1107 -0
- package/src/browser-electron/provider-interaction.ts +1034 -0
- package/src/browser-electron/provider-media.ts +589 -0
- package/src/browser-electron/provider-navigation.ts +323 -0
- package/src/browser-electron/provider-observation.ts +664 -0
- package/src/browser-electron/provider-tabs.ts +372 -0
- package/src/browser-electron/provider.ts +666 -0
- package/src/browser-electron/reference-route.ts +598 -0
- package/src/browser-electron/remote-host.ts +1538 -0
- package/src/browser-electron/rpc-input.ts +13 -0
- package/src/browser-electron/rpc-ops.ts +41 -0
- package/src/browser-electron/runtime-diagnostics.ts +38 -0
- package/src/browser-electron/runtime-route.ts +105 -0
- package/src/browser-electron/runtime-status.ts +309 -0
- package/src/browser-electron/settings-route.ts +64 -0
- package/src/browser-electron/settings-store.ts +593 -0
- package/src/browser-electron/shortcuts-route.ts +112 -0
- package/src/browser-electron/sidebar-only-host.ts +300 -0
- package/src/browser-electron/startpage-shortcuts.ts +213 -0
- package/src/browser-electron/system-browser.ts +1850 -0
- package/src/browser-electron/tauri-host.ts +194 -0
- package/src/browser-electron/timing.ts +16 -0
- package/src/browser-electron/virtual-cursor.ts +162 -0
- package/src/browser-electron/windows-system.ts +24 -0
- package/src/browser-reference/delivery.ts +384 -0
- package/src/browser-reference/entry.ts +631 -0
- package/src/browser-reference/export.ts +339 -0
- package/src/browser-reference/import.ts +303 -0
- package/src/browser-reference/page-script.ts +1537 -0
- package/src/browser-reference/service.ts +1346 -0
- package/src/browser-reference/store.ts +172 -0
- package/src/browser-reference/text-quote.ts +219 -0
- package/src/browser-reference/types.ts +195 -0
- package/src/browser-reference/visible.ts +367 -0
- package/src/browser-reference/web-sources.ts +106 -0
- package/src/client/apply-guard.ts +22 -0
- package/src/client/browser/BrowserController.ts +693 -0
- package/src/client/browser/BrowserFrame.ts +78 -0
- package/src/client/browser/BrowserNavigation.ts +169 -0
- package/src/client/browser/BrowserPage.ts +23 -0
- package/src/client/browser/BrowserPersistence.ts +44 -0
- package/src/client/browser/IframeImpl.ts +182 -0
- package/src/client/browser/child-tabs.ts +14 -0
- package/src/client/browser/frame-history.ts +125 -0
- package/src/client/browser/frame-state.ts +27 -0
- package/src/client/browser/iframe-reference.ts +67 -0
- package/src/client/browser/initialization.ts +262 -0
- package/src/client/browser/omnibox.ts +243 -0
- package/src/client/browser/store.ts +38 -0
- package/src/client/browser/takeover-channel.ts +72 -0
- package/src/client/browser/url.ts +46 -0
- package/src/client/browser/web-reference-source.ts +56 -0
- package/src/client/css-modules.d.ts +4 -0
- package/src/client/definition.tsx +36 -0
- package/src/client/electron/ElectronWebViewImpl.ts +371 -0
- package/src/client/electron/ElectronWebviewPresentation.ts +140 -0
- package/src/client/electron/NativeChildPresentation.ts +53 -0
- package/src/client/electron/NativeViewPage.ts +265 -0
- package/src/client/electron/pages.ts +23 -0
- package/src/client/electron/reference-overlay.ts +53 -0
- package/src/client/electron/workspace.ts +33 -0
- package/src/client/index.ts +333 -0
- package/src/client/locales.ts +860 -0
- package/src/client/pages.ts +28 -0
- package/src/client/reference/client/BrowserRefLink.tsx +142 -0
- package/src/client/reference/client/draft-reference.ts +167 -0
- package/src/client/reference/client/index.ts +7 -0
- package/src/client/reference/client/ordered-submission.ts +108 -0
- package/src/client/reference/client/pending-delivery.ts +216 -0
- package/src/client/reference/client/plugin.ts +208 -0
- package/src/client/reference/client/production/ReferenceCapsules.tsx +345 -0
- package/src/client/reference/client/production/ReferenceDock.module.css +193 -0
- package/src/client/reference/client/production/ReferenceDock.tsx +6 -0
- package/src/client/reference/client/production/ReferenceFeedback.tsx +15 -0
- package/src/client/reference/client/production/ReferenceMath.tsx +44 -0
- package/src/client/reference/client/production/ReferenceText.tsx +36 -0
- package/src/client/reference/client/production/assembly.ts +447 -0
- package/src/client/reference/client/production/asset-store.ts +144 -0
- package/src/client/reference/client/production/availability.ts +72 -0
- package/src/client/reference/client/production/bytes.ts +36 -0
- package/src/client/reference/client/production/composer-attachments.ts +44 -0
- package/src/client/reference/client/production/delivery-client.ts +211 -0
- package/src/client/reference/client/production/draft-adapter.ts +512 -0
- package/src/client/reference/client/production/http-transport.ts +212 -0
- package/src/client/reference/client/production/production-submission.ts +70 -0
- package/src/client/reference/client/production/protocol.ts +234 -0
- package/src/client/reference/client/production/reference-card.ts +240 -0
- package/src/client/reference/client/production/reference-labels.ts +29 -0
- package/src/client/reference/client/production/reply-link-bridge.ts +222 -0
- package/src/client/reference/client/production/reveal.ts +215 -0
- package/src/client/reference/client/production/runtime.ts +1056 -0
- package/src/client/reference/client/production/snapshot-adapter.ts +154 -0
- package/src/client/reference/client/production/source-marker.ts +99 -0
- package/src/client/reference/client/production/source-opener.ts +55 -0
- package/src/client/reference/client/production/styles.ts +104 -0
- package/src/client/reference/client/production/user-text-rule.ts +67 -0
- package/src/client/reference/client/reveal.ts +109 -0
- package/src/client/reference/client/scheme.ts +114 -0
- package/src/client/reference/client/session-schedule.ts +36 -0
- package/src/client/reference/client/types.ts +168 -0
- package/src/client/reference/css-modules.d.ts +4 -0
- package/src/client/reference/index.ts +11 -0
- package/src/client/reference-capture-owner.ts +162 -0
- package/src/client/reference-intents.ts +36 -0
- package/src/client/settings/index.ts +42 -0
- package/src/client/settings/mount-guard.ts +31 -0
- package/src/client/settings/panel.ts +2768 -0
- package/src/client/shortcut-open.ts +30 -0
- package/src/client/startpage/binding.ts +99 -0
- package/src/client/startpage/controller.ts +300 -0
- package/src/client/startpage/model.ts +279 -0
- package/src/client/view/Browser.module.css +751 -0
- package/src/client/view/BrowserBody.tsx +315 -0
- package/src/client/view/BrowserPresentation.ts +9 -0
- package/src/client/view/BrowserTitle.tsx +17 -0
- package/src/client/view/IframePresentation.ts +365 -0
- package/src/client/view/StartPage.tsx +598 -0
- package/src/client/view/TakeoverBanner.tsx +21 -0
- package/src/compat/host-features.ts +92 -0
- package/src/index.ts +110 -0
- package/src/reference-owner.ts +5 -0
- package/src/reference-page.ts +9 -0
- package/src/reference-source.ts +3 -0
- package/src/reference-text.ts +219 -0
- package/src/startpage-settings.ts +103 -0
- package/src/startpage.ts +71 -0
- package/src/takeover-protocol.ts +28 -0
- package/src/tool-browser/block-recovery.ts +85 -0
- package/src/tool-browser/code-tool.ts +555 -0
- package/src/tool-browser/code-worker.ts +725 -0
- package/src/tool-browser/element-fields.ts +167 -0
- package/src/tool-browser/errors.ts +40 -0
- package/src/tool-browser/index.ts +265 -0
- package/src/tool-browser/page-probe.ts +675 -0
- package/src/tool-browser/panel-page.ts +126 -0
- package/src/tool-browser/probe-client.ts +183 -0
- package/src/tool-browser/screenshot-annotations.ts +131 -0
- package/src/tool-browser/screenshot-image.ts +49 -0
- package/src/tool-browser/state.ts +375 -0
- package/src/tool-browser/takeover.ts +199 -0
- package/src/tool-browser/tools-debug.ts +806 -0
- package/src/tool-browser/tools-interaction.ts +956 -0
- package/src/tool-browser/tools-navigation.ts +786 -0
- package/src/tool-browser/tools-observation.ts +474 -0
- package/src/tool-browser/tools-reference.ts +294 -0
- package/src/types/electron-shim.d.ts +144 -0
- package/src/types.ts +85 -0
- package/src/web-guest.ts +35 -0
- package/tools/accept-desktop.mjs +148 -0
- package/dist/client.d.cts +0 -516
- package/dist/client.d.mts +0 -516
- package/dist/index.cjs +0 -92
- package/dist/index.d.mts +0 -2960
- package/dist/index.mjs +0 -24
- package/dsh-builtin-browser-1.0.3-publish.tgz +0 -0
- package/dsh-builtin-browser-1.0.3.tgz +0 -0
- package/dsh-host-patch/sources/main/0001-feat-sidebar-right-add-session-rendering-holds.patch.gz +0 -0
- package/dsh-host-patch/sources/main/0002-feat-desktop-load-trusted-profile-main-extensions.patch.gz +0 -0
- package/dsh-host-patch/sources/main/0003-feat-desktop-report-resolved-and-running-main-extens.patch.gz +0 -0
- package/dsh-host-patch/sources/main/0004-feat-desktop-compose-admitted-native-sidebar-views.patch.gz +0 -0
- package/dsh-host-patch/sources/main/0005-fix-client-admit-coded-browser-errors-in-native-comp.patch.gz +0 -0
- package/dsh-host-patch/sources/main/0006-fix-desktop-acknowledge-native-same-document-navigat.patch.gz +0 -0
- package/dsh-host-patch/sources/main/0007-fix-desktop-restore-auth-in-the-native-lease-partiti.patch.gz +0 -0
- package/dsh-host-patch/sources/main/0008-feat-desktop-adopt-native-children-in-admitted-sideb.patch.gz +0 -0
- package/dsh-host-patch/sources/main/0009-fix-desktop-publish-complete-native-child-close-reco.patch.gz +0 -0
- package/dsh-host-patch/sources/main/0010-fix-desktop-bundle-structured-errors-in-sandboxed-pr.patch.gz +0 -0
- package/dsh-host-patch/sources/main/0011-feat-desktop-offer-persistent-Sidebar-sessions-per-D.patch.gz +0 -0
- package/dsh-host-patch/sources/main/0012-feat-desktop-retain-sidebar-session-cookies-across-r.patch.gz +0 -0
- package/dsh-host-patch/sources/main/0013-fix-desktop-honor-sidebar-session-cookie-sidecar-con.patch.gz +0 -0
- package/dsh-host-patch/sources/main/0014-fix-desktop-retry-cookie-protection-without-failing-.patch.gz +0 -0
- package/dsh-host-patch/sources/main/0015-fix-desktop-preserve-host-only-cookie-identity-in-se.patch.gz +0 -0
- package/dsh-host-patch/sources/main/0016-fix-desktop-restore-session-cookies-before-checkpoin.patch.gz +0 -0
- package/dsh-host-patch/sources/main/0017-fix-desktop-restore-sidebar-cookies-once-before-gues.patch.gz +0 -0
- package/dsh-host-patch/sources/main/0018-fix-sidebar-right-follow-animated-native-slot-placem.patch.gz +0 -0
- package/dsh-host-patch/sources/manifest.json +0 -218
- package/dsh-host-patch/sources/rc3/0001-feat-sidebar-right-add-session-rendering-holds.patch.gz +0 -0
- package/dsh-host-patch/sources/rc3/0002-feat-desktop-load-trusted-profile-main-extensions.patch.gz +0 -0
- package/dsh-host-patch/sources/rc3/0003-feat-desktop-report-resolved-and-running-main-extens.patch.gz +0 -0
- package/dsh-host-patch/sources/rc3/0004-feat-desktop-compose-admitted-native-sidebar-views.patch.gz +0 -0
- package/dsh-host-patch/sources/rc3/0005-fix-client-admit-coded-browser-errors-in-native-comp.patch.gz +0 -0
- package/dsh-host-patch/sources/rc3/0006-fix-desktop-acknowledge-native-same-document-navigat.patch.gz +0 -0
- package/dsh-host-patch/sources/rc3/0007-fix-desktop-restore-auth-in-the-native-lease-partiti.patch.gz +0 -0
- package/dsh-host-patch/sources/rc3/0008-feat-desktop-adopt-native-children-in-admitted-sideb.patch.gz +0 -0
- package/dsh-host-patch/sources/rc3/0009-fix-desktop-publish-complete-native-child-close-reco.patch.gz +0 -0
- package/dsh-host-patch/sources/rc3/0010-fix-desktop-bundle-structured-errors-in-sandboxed-pr.patch.gz +0 -0
- package/dsh-host-patch/sources/rc3/0011-feat-desktop-offer-persistent-Sidebar-sessions-per-D.patch.gz +0 -0
- package/dsh-host-patch/sources/rc3/0012-feat-desktop-retain-sidebar-session-cookies-across-r.patch.gz +0 -0
- package/dsh-host-patch/sources/rc3/0013-fix-desktop-honor-sidebar-session-cookie-sidecar-con.patch.gz +0 -0
- package/dsh-host-patch/sources/rc3/0014-fix-desktop-retry-cookie-protection-without-failing-.patch.gz +0 -0
- package/dsh-host-patch/sources/rc3/0015-fix-desktop-preserve-host-only-cookie-identity-in-se.patch.gz +0 -0
- package/dsh-host-patch/sources/rc3/0016-fix-desktop-restore-session-cookies-before-checkpoin.patch.gz +0 -0
- package/dsh-host-patch/sources/rc3/0017-fix-desktop-restore-sidebar-cookies-once-before-gues.patch.gz +0 -0
- package/dsh-host-patch/sources/rc3/0018-fix-sidebar-right-follow-animated-native-slot-placem.patch.gz +0 -0
- package/dsh-host-patch/sources/rc5/0001-feat-sidebar-right-add-session-rendering-holds.patch.gz +0 -0
- package/dsh-host-patch/sources/rc5/0002-feat-desktop-load-trusted-profile-main-extensions.patch.gz +0 -0
- package/dsh-host-patch/sources/rc5/0003-feat-desktop-report-resolved-and-running-main-extens.patch.gz +0 -0
- package/dsh-host-patch/sources/rc5/0004-feat-desktop-compose-admitted-native-sidebar-views.patch.gz +0 -0
- package/dsh-host-patch/sources/rc5/0005-fix-client-admit-coded-browser-errors-in-native-comp.patch.gz +0 -0
- package/dsh-host-patch/sources/rc5/0006-fix-desktop-acknowledge-native-same-document-navigat.patch.gz +0 -0
- package/dsh-host-patch/sources/rc5/0007-fix-desktop-restore-auth-in-the-native-lease-partiti.patch.gz +0 -0
- package/dsh-host-patch/sources/rc5/0008-feat-desktop-adopt-native-children-in-admitted-sideb.patch.gz +0 -0
- package/dsh-host-patch/sources/rc5/0009-fix-desktop-publish-complete-native-child-close-reco.patch.gz +0 -0
- package/dsh-host-patch/sources/rc5/0010-fix-desktop-bundle-structured-errors-in-sandboxed-pr.patch.gz +0 -0
- package/dsh-host-patch/sources/rc5/0011-feat-desktop-offer-persistent-Sidebar-sessions-per-D.patch.gz +0 -0
- package/dsh-host-patch/sources/rc5/0012-feat-desktop-retain-sidebar-session-cookies-across-r.patch.gz +0 -0
- package/dsh-host-patch/sources/rc5/0013-fix-desktop-honor-sidebar-session-cookie-sidecar-con.patch.gz +0 -0
- package/dsh-host-patch/sources/rc5/0014-fix-desktop-retry-cookie-protection-without-failing-.patch.gz +0 -0
- package/dsh-host-patch/sources/rc5/0015-fix-desktop-preserve-host-only-cookie-identity-in-se.patch.gz +0 -0
- package/dsh-host-patch/sources/rc5/0016-fix-desktop-restore-session-cookies-before-checkpoin.patch.gz +0 -0
- package/dsh-host-patch/sources/rc5/0017-fix-desktop-restore-sidebar-cookies-once-before-gues.patch.gz +0 -0
- package/dsh-host-patch/sources/rc5/0018-fix-sidebar-right-follow-animated-native-slot-placem.patch.gz +0 -0
- package/dsh-host-patch/sources/series.json +0 -260
|
@@ -0,0 +1,1538 @@
|
|
|
1
|
+
import { BROWSER_PROFILE_DIR, LOOPBACK_IPV4 } from '../../assets/browser-policy.mjs'
|
|
2
|
+
/**
|
|
3
|
+
* Legacy standalone Electron browser host (not a supported package export): an
|
|
4
|
+
* {@link ElectronBrowserViewHost} implementation that spawns the plugin's own
|
|
5
|
+
* Electron child process (host-main.js) and drives it over line-delimited
|
|
6
|
+
* JSON-RPC on a loopback TCP socket.
|
|
7
|
+
*
|
|
8
|
+
* Protocol (one JSON object per line, both directions):
|
|
9
|
+
* -> { id, op: 'createView' } | { id, op: 'destroyView', viewId } |
|
|
10
|
+
* { id, op: 'showView', viewId } | { id, op: 'command', viewId, method, params }
|
|
11
|
+
* <- { id, op: 'hello', token } (the child's FIRST message — authenticates it)
|
|
12
|
+
* <- { id, ok: true, result? } | { id, ok: false, err }
|
|
13
|
+
*
|
|
14
|
+
* The child is Electron's main process; host-main.js owns the BrowserWindow,
|
|
15
|
+
* WebContentsViews, and webContents.debugger (CDP).
|
|
16
|
+
*
|
|
17
|
+
* Security: the RPC server accepts exactly ONE connection, and only after
|
|
18
|
+
* that connection proves knowledge of the random per-spawn token (passed to
|
|
19
|
+
* the child via its stdin (first line, never in argv). A local process that
|
|
20
|
+
* connects to the loopback port without the token can neither impersonate the
|
|
21
|
+
* child nor inject replies — it is disconnected as soon as its first line
|
|
22
|
+
* arrives. Commands are only written after the hello authenticates, and every
|
|
23
|
+
* other inbound op (including the fire-and-forget `userAction` / `viewClosed`
|
|
24
|
+
* notifications) is dispatched only once that check has passed, so an
|
|
25
|
+
* unauthenticated peer can neither read traffic nor drive a session.
|
|
26
|
+
* @module dsh-browser/browser-electron/remote-host
|
|
27
|
+
*/
|
|
28
|
+
|
|
29
|
+
import { execFileSync, spawn } from 'node:child_process'
|
|
30
|
+
import { appendFileSync, mkdirSync, rmSync, statSync, writeFileSync } from 'node:fs'
|
|
31
|
+
import { randomBytes, randomUUID } from 'node:crypto'
|
|
32
|
+
import { createRequire } from 'node:module'
|
|
33
|
+
import { existsSync, readFileSync, readdirSync, readlinkSync } from 'node:fs'
|
|
34
|
+
import { basename, dirname, isAbsolute, join } from 'node:path'
|
|
35
|
+
import { createServer, type Server, type Socket } from 'node:net'
|
|
36
|
+
import { withTimeoutShared } from './timing.ts'
|
|
37
|
+
import { browserHostLogPath, dshHome } from './paths.ts'
|
|
38
|
+
import { fileURLToPath } from 'node:url'
|
|
39
|
+
import type { BrowserUserAction, ElectronBrowserViewHost, ElectronViewHandle, PresentOptions, ScreenshotOptions } from './provider.ts'
|
|
40
|
+
import type { ExportedCookie } from '../browser/types.ts'
|
|
41
|
+
import { readTabHandle, tabWireId, type BrowserTabWireId } from '../browser/handles.ts'
|
|
42
|
+
|
|
43
|
+
/** How long to wait for the child to signal readiness before failing. */
|
|
44
|
+
const READY_TIMEOUT_MS = 20_000
|
|
45
|
+
|
|
46
|
+
/** Budget for the present/barrier round-trips (see presentView). */
|
|
47
|
+
const PRESENT_TIMEOUT_MS = 10_000
|
|
48
|
+
|
|
49
|
+
/** Safety cap on a single RPC reply line (base64 downloads are the big ones). */
|
|
50
|
+
const MAX_RPC_BUFFER_BYTES = 512 * 1024 * 1024
|
|
51
|
+
|
|
52
|
+
/**
|
|
53
|
+
* Locate a SPAWNABLE Electron binary — one that runs a script given as an
|
|
54
|
+
* argument, i.e. a BARE electron, never a packaged app executable:
|
|
55
|
+
* 0. ELECTRON_PATH (explicit override — user intent beats auto-discovery),
|
|
56
|
+
* 1. the plugin-managed runtime directory (`$DSH_HOME/dsh-builtin-browser-host/electron-runtime`),
|
|
57
|
+
* isolated from DSH profile node_modules so upgrades never wipe it,
|
|
58
|
+
* 2. the plugin's own electron package (or a prior install's node_modules / pnpm store),
|
|
59
|
+
* found by a pure filesystem walk — never require(), whose semantics
|
|
60
|
+
* differ inside an Electron main process (there it is the built-in API
|
|
61
|
+
* module, not the npm package) and which would trigger electron 44+'s
|
|
62
|
+
* lazy binary download;
|
|
63
|
+
* 3. every DSH install anchor (electron installed separately, e.g.
|
|
64
|
+
* `dsh plugin add electron` into the profile or a global prefix),
|
|
65
|
+
* choosing the NEWEST version found. Older Electron releases (e.g.
|
|
66
|
+
* 33.x) have a compositor defect that intermittently breaks page
|
|
67
|
+
* capture, so prefer the newest binary available in the environment,
|
|
68
|
+
* 4. the current process, when it IS a bare Electron (dev hosts, e.g.
|
|
69
|
+
* `electron .`): reuse the host binary. Packaged app executables
|
|
70
|
+
* (resources/app.asar beside the exe) are never reused — they ignore
|
|
71
|
+
* the script argument and launch the app itself, typically exiting
|
|
72
|
+
* immediately via the single-instance lock, which is exactly the
|
|
73
|
+
* "browser host exited (code=0)" failure on DSH Desktop;
|
|
74
|
+
* 5. last resort: the process ancestry, for hosts that run this plugin in a
|
|
75
|
+
* child Node process of their own bare-Electron main process.
|
|
76
|
+
* @returns the path to the Electron executable.
|
|
77
|
+
*/
|
|
78
|
+
/** The discovery inputs {@link resolveElectronPathImpl} selects over, injectable for tests. */
|
|
79
|
+
interface ElectronPathInputs {
|
|
80
|
+
/** ELECTRON_PATH (may be unset, empty, or pointing at a missing file). */
|
|
81
|
+
readonly override: string | undefined
|
|
82
|
+
/** True when running inside an Electron main process. */
|
|
83
|
+
readonly inElectron: boolean
|
|
84
|
+
/** process.execPath (candidate for in-process host reuse). */
|
|
85
|
+
readonly execPath: string
|
|
86
|
+
/** The plugin-managed runtime probe (`$DSH_HOME/dsh-builtin-browser-host/electron-runtime`). */
|
|
87
|
+
readonly managed?: () => string | undefined
|
|
88
|
+
/** The plugin's own electron package probe (bundled). */
|
|
89
|
+
readonly bundled: () => string | undefined
|
|
90
|
+
/** The DSH install-anchor probe. */
|
|
91
|
+
readonly anchored: () => string | undefined
|
|
92
|
+
/** The process-ancestry probe (last resort). */
|
|
93
|
+
readonly ancestry: () => string | undefined
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
/**
|
|
97
|
+
* Plugin-owned runtime root (`$DSH_HOME/dsh-builtin-browser-host/electron-runtime`).
|
|
98
|
+
* Lives outside DSH profile `node_modules` so plugin upgrades do not delete it
|
|
99
|
+
* as unreferenced residue and pnpm never blocks its postinstall.
|
|
100
|
+
*/
|
|
101
|
+
export function managedElectronDir(home: string = dshHome()): string {
|
|
102
|
+
return join(home, BROWSER_PROFILE_DIR, 'electron-runtime')
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
function managedElectronBinary(): string | undefined {
|
|
106
|
+
const pkgRoot = join(managedElectronDir(), 'node_modules', 'electron')
|
|
107
|
+
return electronDistExe(pkgRoot)
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
function resolveElectronPath(): string {
|
|
111
|
+
return resolveElectronPathImpl({
|
|
112
|
+
override: process.env.ELECTRON_PATH,
|
|
113
|
+
inElectron: typeof process.versions.electron === 'string',
|
|
114
|
+
execPath: process.execPath,
|
|
115
|
+
managed: managedElectronBinary,
|
|
116
|
+
bundled: bundledElectronBinary,
|
|
117
|
+
anchored: anchoredElectronBinary,
|
|
118
|
+
ancestry: hostElectronViaProcessTree,
|
|
119
|
+
})
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
/**
|
|
123
|
+
* Pure selection over the discovery probes, in order:
|
|
124
|
+
* 0. override (user intent) → 1. managed runtime → 2. bundled package → 3. anchors (newest) →
|
|
125
|
+
* 4. in-process BARE host → 5. process ancestry → throw.
|
|
126
|
+
* Packaged app executables are never reused (steps 4/5 skip them).
|
|
127
|
+
*/
|
|
128
|
+
function resolveElectronPathImpl(inputs: ElectronPathInputs): string {
|
|
129
|
+
// 0. Explicit override first: a user-set ELECTRON_PATH is a deliberate
|
|
130
|
+
// choice and must beat every auto-discovery (including the bundled
|
|
131
|
+
// package) — auto-discovery is a fallback, not an override.
|
|
132
|
+
const override = inputs.override
|
|
133
|
+
if (typeof override === 'string' && override.length > 0 && existsSync(override)) return override
|
|
134
|
+
// 1. Plugin-managed standalone runtime (on-demand download target).
|
|
135
|
+
const managed = inputs.managed?.()
|
|
136
|
+
if (managed !== undefined) return managed
|
|
137
|
+
// 2. The plugin's own electron package (filesystem probe). Never require():
|
|
138
|
+
// inside an Electron main process require('electron') is the built-in
|
|
139
|
+
// API module, not the npm package, and electron 44+ downloads its binary
|
|
140
|
+
// on first require — probing must stay side-effect free (available()
|
|
141
|
+
// would otherwise block DSH startup on the download).
|
|
142
|
+
const bundled = inputs.bundled()
|
|
143
|
+
if (bundled !== undefined) return bundled
|
|
144
|
+
// 3. DSH install anchors, newest wins. (The plugin's own tree — plain and
|
|
145
|
+
// pnpm store layouts — was already scanned in step 2; the anchors cover
|
|
146
|
+
// electron installed separately, e.g. `dsh plugin add electron` into the
|
|
147
|
+
// profile or a global prefix.)
|
|
148
|
+
const anchored = inputs.anchored()
|
|
149
|
+
if (anchored !== undefined) return anchored
|
|
150
|
+
// 4. The current process IS a bare Electron (dev hosts, e.g. `electron .`):
|
|
151
|
+
// reuse the host binary — it cannot be missing because we are running on
|
|
152
|
+
// it. A PACKAGED app executable (resources/app.asar beside it, e.g. DSH
|
|
153
|
+
// Desktop.exe) is NOT spawnable as bare electron: it ignores the script
|
|
154
|
+
// argument, launches the app itself, and typically exits immediately
|
|
155
|
+
// (single-instance lock) — so it is never reused.
|
|
156
|
+
if (inputs.inElectron) {
|
|
157
|
+
const exe = inputs.execPath
|
|
158
|
+
if (typeof exe === 'string' && exe.length > 0 && existsSync(exe) && isBareElectron(exe)) return exe
|
|
159
|
+
}
|
|
160
|
+
// 5. Last resort for bare-Electron hosts: walk the process ancestry (the
|
|
161
|
+
// plugin may run in a child Node process of an Electron main process).
|
|
162
|
+
const hostExe = inputs.ancestry()
|
|
163
|
+
if (hostExe !== undefined) return hostExe
|
|
164
|
+
throw new Error(
|
|
165
|
+
'dsh-builtin-browser: cannot locate a spawnable Electron binary. ' +
|
|
166
|
+
'Select "Standalone Electron window" in Settings → Browser and click "Prepare the bundled browser" ' +
|
|
167
|
+
'(or run `npx --no dsh-browser-install-electron`) to download it once into your DSH data directory, ' +
|
|
168
|
+
'or set ELECTRON_PATH to an existing electron executable. Note: a packaged Electron app executable ' +
|
|
169
|
+
'(e.g. DSH Desktop.exe) cannot be reused — only a bare electron binary can be spawned.',
|
|
170
|
+
)
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
/** DSH install anchors: electron installed separately (profile / global prefix), newest wins. */
|
|
174
|
+
function anchoredElectronBinary(): string | undefined {
|
|
175
|
+
const require = createRequire(import.meta.url)
|
|
176
|
+
const candidates: Array<{ version: string; path: string }> = []
|
|
177
|
+
const add = (version: string, path: string | undefined): void => {
|
|
178
|
+
if (path !== undefined) candidates.push({ version, path })
|
|
179
|
+
}
|
|
180
|
+
const anchors: string[] = []
|
|
181
|
+
const globalPrefix = process.env.npm_config_prefix ?? process.env.PREFIX
|
|
182
|
+
if (globalPrefix !== undefined) {
|
|
183
|
+
anchors.push(join(globalPrefix, 'node_modules'))
|
|
184
|
+
anchors.push(join(globalPrefix, 'node_modules', '@deepseek-ai', 'dsh', 'node_modules'))
|
|
185
|
+
}
|
|
186
|
+
if (process.env.DSH_HOME !== undefined) {
|
|
187
|
+
anchors.push(join(process.env.DSH_HOME, 'profiles', 'node_modules'))
|
|
188
|
+
}
|
|
189
|
+
for (const anchor of anchors) {
|
|
190
|
+
try {
|
|
191
|
+
const resolved: unknown = require.resolve('electron', { paths: [anchor] })
|
|
192
|
+
// Inside an Electron main process resolve('electron') yields the
|
|
193
|
+
// built-in module NAME (not a path) — requiring an absolute path keeps
|
|
194
|
+
// electronExeBeside from probing cwd-relative garbage like ./dist/.
|
|
195
|
+
if (typeof resolved === 'string' && resolved.length > 0 && isAbsolute(resolved)) {
|
|
196
|
+
add(versionOf(resolved), electronExeBeside(resolved))
|
|
197
|
+
}
|
|
198
|
+
} catch {
|
|
199
|
+
// continue probing
|
|
200
|
+
}
|
|
201
|
+
}
|
|
202
|
+
return pickNewest(candidates)
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
/**
|
|
206
|
+
* The plugin's own electron package binary, found by a pure filesystem walk
|
|
207
|
+
* (never require(), whose semantics differ inside an Electron main process —
|
|
208
|
+
* there `require('electron')` is the built-in API module, not the npm package
|
|
209
|
+
* — and which would trigger electron 44+'s lazy binary download when the dist
|
|
210
|
+
* is missing). Checks every `node_modules/electron` above this module,
|
|
211
|
+
* including pnpm virtual-store layouts, and returns the NEWEST ready binary.
|
|
212
|
+
* Scan ONLY the plugin's own install tree: never cwd or the executable's
|
|
213
|
+
* directory, which can sit inside an unrelated project whose node_modules may
|
|
214
|
+
* hold a different electron (executing the newest random binary in the
|
|
215
|
+
* filesystem is a supply-chain hazard with no benefit).
|
|
216
|
+
*/
|
|
217
|
+
function bundledElectronBinary(): string | undefined {
|
|
218
|
+
const candidates: Array<{ version: string; path: string }> = []
|
|
219
|
+
const consider = (pkgRoot: string, versionHint: string): void => {
|
|
220
|
+
const exe = electronDistExe(pkgRoot)
|
|
221
|
+
if (exe !== undefined) candidates.push({ version: versionHint || pkgVersion(pkgRoot), path: exe })
|
|
222
|
+
}
|
|
223
|
+
let dir = fileURLToPath(new URL('.', import.meta.url))
|
|
224
|
+
for (let depth = 0; depth < 8; depth++) {
|
|
225
|
+
// Plain (npm/yarn, hoisted) layout: <ancestor>/node_modules/electron.
|
|
226
|
+
const plain = join(dir, 'node_modules', 'electron')
|
|
227
|
+
if (existsSync(join(plain, 'package.json'))) consider(plain, '')
|
|
228
|
+
// pnpm layout: <ancestor>/node_modules/.pnpm or <ancestor>/.pnpm, with
|
|
229
|
+
// electron@<version>/node_modules/electron entries.
|
|
230
|
+
for (const storeRoot of [join(dir, 'node_modules', '.pnpm'), join(dir, '.pnpm')]) {
|
|
231
|
+
if (!existsSync(storeRoot)) continue
|
|
232
|
+
for (const entry of readdirSync(storeRoot)) {
|
|
233
|
+
if (!entry.startsWith('electron@')) continue
|
|
234
|
+
const pkg = join(storeRoot, entry, 'node_modules', 'electron')
|
|
235
|
+
// Strip pnpm's peer-dependency suffix (electron@44.0.0_@types+node@22).
|
|
236
|
+
if (existsSync(join(pkg, 'package.json'))) consider(pkg, entry.slice('electron@'.length).split('_')[0])
|
|
237
|
+
}
|
|
238
|
+
}
|
|
239
|
+
const parent = join(dir, '..')
|
|
240
|
+
if (parent === dir) break
|
|
241
|
+
dir = parent
|
|
242
|
+
}
|
|
243
|
+
return pickNewest(candidates)
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
/** The electron version from a package root's package.json, or '0.0.0'. */
|
|
247
|
+
function pkgVersion(pkgRoot: string): string {
|
|
248
|
+
try {
|
|
249
|
+
const pkg = JSON.parse(readFileSync(join(pkgRoot, 'package.json'), 'utf8')) as { version?: unknown }
|
|
250
|
+
return typeof pkg.version === 'string' && pkg.version.length > 0 ? pkg.version : '0.0.0'
|
|
251
|
+
} catch {
|
|
252
|
+
return '0.0.0'
|
|
253
|
+
}
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
/** The highest-versioned candidate's path, or undefined when none. */
|
|
257
|
+
function pickNewest(candidates: Array<{ version: string; path: string }>): string | undefined {
|
|
258
|
+
let best: { version: string; path: string } | undefined
|
|
259
|
+
for (const c of candidates) {
|
|
260
|
+
if (best === undefined || compareVersions(c.version, best.version) > 0) best = c
|
|
261
|
+
}
|
|
262
|
+
return best?.path
|
|
263
|
+
}
|
|
264
|
+
|
|
265
|
+
/**
|
|
266
|
+
* Last-resort Electron discovery: walk this process's ancestry looking for a
|
|
267
|
+
* parent process whose executable is a BARE Electron binary (only bare
|
|
268
|
+
* electron can be spawned with a script argument). Covers hosts that run the
|
|
269
|
+
* plugin in a child Node process of their own Electron main process: the host
|
|
270
|
+
* binary is already on disk and running, so reusing it needs no extra
|
|
271
|
+
* install. Filesystem-only on POSIX (/proc); on Windows a best-effort
|
|
272
|
+
* PowerShell CIM query is used — this path only runs when every other lookup
|
|
273
|
+
* failed, so its latency never touches the happy path, and a
|
|
274
|
+
* missing/blocked powershell simply yields nothing.
|
|
275
|
+
*/
|
|
276
|
+
function hostElectronViaProcessTree(): string | undefined {
|
|
277
|
+
let pid: number | undefined = process.ppid
|
|
278
|
+
for (let depth = 0; depth < 6 && pid !== undefined && pid > 1; depth++) {
|
|
279
|
+
const exe = processExecutable(pid)
|
|
280
|
+
if (exe !== undefined && isBareElectron(exe)) return exe
|
|
281
|
+
pid = processParent(pid)
|
|
282
|
+
}
|
|
283
|
+
return undefined
|
|
284
|
+
}
|
|
285
|
+
|
|
286
|
+
/** One scalar property of a Windows process, read through CIM. */
|
|
287
|
+
function cimQuery(pid: number, property: 'ExecutablePath' | 'ParentProcessId'): string {
|
|
288
|
+
const out = execFileSync('powershell.exe', [
|
|
289
|
+
'-NoProfile', '-NonInteractive', '-Command',
|
|
290
|
+
`(Get-CimInstance Win32_Process -Filter "ProcessId=${pid}").${property}`,
|
|
291
|
+
], { encoding: 'utf8', windowsHide: true, timeout: 3000 })
|
|
292
|
+
return out.trim().split(/\r?\n/)[0] ?? ''
|
|
293
|
+
}
|
|
294
|
+
|
|
295
|
+
/** The executable path of a running process, or undefined when unknown. */
|
|
296
|
+
function processExecutable(pid: number): string | undefined {
|
|
297
|
+
try {
|
|
298
|
+
if (process.platform === 'win32') {
|
|
299
|
+
const line = cimQuery(pid, 'ExecutablePath')
|
|
300
|
+
return line.length > 0 ? line : undefined
|
|
301
|
+
}
|
|
302
|
+
const exe = readlinkSync(`/proc/${pid}/exe`)
|
|
303
|
+
return exe.length > 0 ? exe : undefined
|
|
304
|
+
} catch {
|
|
305
|
+
return undefined
|
|
306
|
+
}
|
|
307
|
+
}
|
|
308
|
+
|
|
309
|
+
/** The parent pid of a running process, or undefined when unknown. */
|
|
310
|
+
function processParent(pid: number): number | undefined {
|
|
311
|
+
try {
|
|
312
|
+
if (process.platform === 'win32') {
|
|
313
|
+
const n = Number(cimQuery(pid, 'ParentProcessId'))
|
|
314
|
+
return Number.isInteger(n) && n > 1 ? n : undefined
|
|
315
|
+
}
|
|
316
|
+
const stat = readFileSync(`/proc/${pid}/stat`, 'utf8')
|
|
317
|
+
// Format: pid (comm) state ppid ... — comm is parenthesized and may
|
|
318
|
+
// itself contain spaces/parens, so parse from the LAST ')'; ppid is the
|
|
319
|
+
// second field after it.
|
|
320
|
+
const fields = stat.slice(stat.lastIndexOf(')') + 1).trim().split(/\s+/)
|
|
321
|
+
const n = Number(fields[1])
|
|
322
|
+
return Number.isInteger(n) && n > 1 ? n : undefined
|
|
323
|
+
} catch {
|
|
324
|
+
return undefined
|
|
325
|
+
}
|
|
326
|
+
}
|
|
327
|
+
|
|
328
|
+
/**
|
|
329
|
+
* True when the given executable is an Electron binary. The name match
|
|
330
|
+
* covers dev binaries (electron, electron.exe); the resources marker covers
|
|
331
|
+
* packaged apps whose exe carries the product name (e.g. "DSH Desktop.exe") —
|
|
332
|
+
* every Electron distribution ships `resources/electron.asar`,
|
|
333
|
+
* `resources/app.asar`, or `resources/default_app.asar` beside the binary.
|
|
334
|
+
*/
|
|
335
|
+
function isElectronBinary(exe: string): boolean {
|
|
336
|
+
if (basename(exe).toLowerCase().includes('electron')) return true
|
|
337
|
+
const resources = join(dirname(exe), 'resources')
|
|
338
|
+
return existsSync(join(resources, 'electron.asar'))
|
|
339
|
+
|| existsSync(join(resources, 'app.asar'))
|
|
340
|
+
|| existsSync(join(resources, 'default_app.asar'))
|
|
341
|
+
}
|
|
342
|
+
|
|
343
|
+
/**
|
|
344
|
+
* True when the executable is a BARE (unpackaged) Electron that can be
|
|
345
|
+
* spawned with a script argument (`exe script.js --rpc-port N`). Packaged
|
|
346
|
+
* apps carry their code inside a resources dir (`app.asar`, or an unpacked
|
|
347
|
+
* `app` dir) and are NOT spawnable as bare electron: they ignore the script
|
|
348
|
+
* argument and launch the app itself, typically exiting immediately via the
|
|
349
|
+
* single-instance lock — spawning e.g. DSH Desktop.exe is exactly the
|
|
350
|
+
* "browser host exited (code=0)" failure. A portable single-file build (no
|
|
351
|
+
* resources dir at all) likewise cannot run a script argument.
|
|
352
|
+
*/
|
|
353
|
+
function isBareElectron(exe: string): boolean {
|
|
354
|
+
const dir = dirname(exe)
|
|
355
|
+
// Windows/Linux keep resources beside the binary; macOS app bundles keep
|
|
356
|
+
// them in Contents/Resources, one level above the binary's MacOS dir.
|
|
357
|
+
const resourcesList = process.platform === 'darwin'
|
|
358
|
+
? [join(dir, '..', 'Resources'), join(dir, 'resources')]
|
|
359
|
+
: [join(dir, 'resources')]
|
|
360
|
+
for (const resources of resourcesList) {
|
|
361
|
+
if (existsSync(join(resources, 'app.asar')) || existsSync(join(resources, 'app'))) return false
|
|
362
|
+
}
|
|
363
|
+
// A real electron always ships a resources dir somewhere; requiring one
|
|
364
|
+
// keeps every not-actually-spawnable layout out.
|
|
365
|
+
if (!resourcesList.some(p => existsSync(p))) return false
|
|
366
|
+
return isElectronBinary(exe)
|
|
367
|
+
}
|
|
368
|
+
|
|
369
|
+
/** Extract an electron version like "43.4.0" from a path containing it. */
|
|
370
|
+
function versionOf(path: string): string {
|
|
371
|
+
const match = /electron@(\d+\.\d+\.\d+)/.exec(path)
|
|
372
|
+
return match?.[1] ?? '0.0.0'
|
|
373
|
+
}
|
|
374
|
+
|
|
375
|
+
/** Compare dotted numeric versions; higher wins. */
|
|
376
|
+
function compareVersions(a: string, b: string): number {
|
|
377
|
+
const pa = a.split('.').map(n => Number(n) || 0)
|
|
378
|
+
const pb = b.split('.').map(n => Number(n) || 0)
|
|
379
|
+
for (let i = 0; i < Math.max(pa.length, pb.length); i++) {
|
|
380
|
+
const d = (pa[i] ?? 0) - (pb[i] ?? 0)
|
|
381
|
+
if (d !== 0) return d
|
|
382
|
+
}
|
|
383
|
+
return 0
|
|
384
|
+
}
|
|
385
|
+
|
|
386
|
+
/** Candidate executable layouts used by the Electron npm package on one platform. */
|
|
387
|
+
function electronDistCandidates(pkgRoot: string, platform: NodeJS.Platform = process.platform): string[] {
|
|
388
|
+
// macOS keeps the runnable binary inside the Electron.app bundle; unlike
|
|
389
|
+
// Windows/Linux there is no dist/electron(.exe) sibling to probe.
|
|
390
|
+
if (platform === 'darwin') {
|
|
391
|
+
return [join(pkgRoot, 'dist', 'Electron.app', 'Contents', 'MacOS', 'Electron')]
|
|
392
|
+
}
|
|
393
|
+
return [
|
|
394
|
+
join(pkgRoot, 'dist', 'electron.exe'),
|
|
395
|
+
join(pkgRoot, 'dist', 'electron'),
|
|
396
|
+
]
|
|
397
|
+
}
|
|
398
|
+
|
|
399
|
+
/** From an electron package entry file, find the dist executable beside it. */
|
|
400
|
+
function electronExeBeside(entry: string, platform: NodeJS.Platform = process.platform): string | undefined {
|
|
401
|
+
const packageRoots = [dirname(entry), join(dirname(entry), '..')]
|
|
402
|
+
for (const packageRoot of packageRoots) {
|
|
403
|
+
const candidate = electronDistExe(packageRoot, platform)
|
|
404
|
+
if (candidate !== undefined) return candidate
|
|
405
|
+
}
|
|
406
|
+
return undefined
|
|
407
|
+
}
|
|
408
|
+
|
|
409
|
+
/** From an electron package root, find its dist executable. */
|
|
410
|
+
function electronDistExe(pkgRoot: string, platform: NodeJS.Platform = process.platform): string | undefined {
|
|
411
|
+
for (const candidate of electronDistCandidates(pkgRoot, platform)) {
|
|
412
|
+
if (existsSync(candidate)) return candidate
|
|
413
|
+
}
|
|
414
|
+
return undefined
|
|
415
|
+
}
|
|
416
|
+
|
|
417
|
+
/** One RPC round-trip with the child. */
|
|
418
|
+
interface Pending {
|
|
419
|
+
resolve(result: unknown): void
|
|
420
|
+
reject(err: Error): void
|
|
421
|
+
}
|
|
422
|
+
|
|
423
|
+
/**
|
|
424
|
+
* Thrown whenever the browser host (the Electron child) is gone — it exited,
|
|
425
|
+
* failed to start, or its RPC connection dropped. Operations against a dead
|
|
426
|
+
* host can never succeed, so the view layer treats this as "rebuild against a
|
|
427
|
+
* fresh host" instead of a page-level error. Kept module-private: callers
|
|
428
|
+
* observe the behavior (auto-restart), not the class.
|
|
429
|
+
*/
|
|
430
|
+
class HostGoneError extends Error {
|
|
431
|
+
constructor(message: string) {
|
|
432
|
+
super(message)
|
|
433
|
+
this.name = 'HostGoneError'
|
|
434
|
+
}
|
|
435
|
+
}
|
|
436
|
+
|
|
437
|
+
/**
|
|
438
|
+
* Line-delimited JSON-RPC client over a local TCP socket. Electron's main
|
|
439
|
+
* process on Windows does not receive piped stdin, so the parent listens on a
|
|
440
|
+
* loopback port and passes it to the child via `--rpc-port`; the child
|
|
441
|
+
* connects back and speaks the same one-JSON-per-line protocol.
|
|
442
|
+
*/
|
|
443
|
+
class ElectronChildClient {
|
|
444
|
+
private readonly child: import('node:child_process').ChildProcessWithoutNullStreams
|
|
445
|
+
private readonly pending = new Map<number, Pending>()
|
|
446
|
+
private nextId = 1
|
|
447
|
+
private buffer = ''
|
|
448
|
+
private socket: import('node:net').Socket | undefined
|
|
449
|
+
private connected = false
|
|
450
|
+
private outbox: string[] = []
|
|
451
|
+
/** Set once the child has exited; further calls fail fast instead of queueing. */
|
|
452
|
+
private dead = false
|
|
453
|
+
/**
|
|
454
|
+
* True until the first message proves the child knows the spawn token.
|
|
455
|
+
* Commands are queued (not written) until then, so a spoofed socket never
|
|
456
|
+
* sees any traffic.
|
|
457
|
+
*/
|
|
458
|
+
private awaitingHello = true
|
|
459
|
+
private helloTimer: ReturnType<typeof setTimeout> | undefined
|
|
460
|
+
private readonly hostMainPath: string
|
|
461
|
+
private readonly port: number
|
|
462
|
+
private readonly token: string
|
|
463
|
+
private readonly onExit?: () => void
|
|
464
|
+
private readonly onUserAction?: (action: BrowserUserAction) => void
|
|
465
|
+
private readonly onViewClosed?: (windowId: string) => void
|
|
466
|
+
private readonly executable?: string
|
|
467
|
+
private readonly userDataDir?: string
|
|
468
|
+
constructor(
|
|
469
|
+
hostMainPath: string,
|
|
470
|
+
port: number,
|
|
471
|
+
token: string,
|
|
472
|
+
onExit?: () => void,
|
|
473
|
+
onUserAction?: (action: BrowserUserAction) => void,
|
|
474
|
+
/**
|
|
475
|
+
* Called when the human closes a browser window. The session it showed is
|
|
476
|
+
* over: the provider releases it, while history and login state stay on disk
|
|
477
|
+
* so the next open is a clean session rather than a resurrected one.
|
|
478
|
+
*/
|
|
479
|
+
onViewClosed?: (windowId: string) => void,
|
|
480
|
+
/** Test seam: the executable to spawn instead of the resolved Electron
|
|
481
|
+
* binary. Absent -> resolveElectronPath() (production behavior). */
|
|
482
|
+
executable?: string,
|
|
483
|
+
/** Optional ephemeral userData dir when cookies.persist is false. */
|
|
484
|
+
userDataDir?: string,
|
|
485
|
+
) {
|
|
486
|
+
this.hostMainPath = hostMainPath
|
|
487
|
+
this.port = port
|
|
488
|
+
this.token = token
|
|
489
|
+
this.onExit = onExit
|
|
490
|
+
this.onUserAction = onUserAction
|
|
491
|
+
this.onViewClosed = onViewClosed
|
|
492
|
+
this.executable = executable
|
|
493
|
+
this.userDataDir = userDataDir
|
|
494
|
+
const electron = this.executable ?? resolveElectronPath()
|
|
495
|
+
const source = this.executable !== undefined
|
|
496
|
+
? 'provided'
|
|
497
|
+
: electron === process.env.ELECTRON_PATH ? 'ELECTRON_PATH' : 'auto'
|
|
498
|
+
// Record what is about to be spawned — with existence checks — BEFORE the
|
|
499
|
+
// attempt. When Electron cannot load the app entry it exits 1 with EMPTY
|
|
500
|
+
// stderr, and that signature is otherwise indistinguishable from a missing
|
|
501
|
+
// binary: writing both paths (and whether they exist) in advance is what
|
|
502
|
+
// turns the next occurrence into a named cause instead of a guess.
|
|
503
|
+
process.stderr.write(`[dsh-browser host] spawning electron: ${electron} source=${source}\n`)
|
|
504
|
+
appendHostLog(
|
|
505
|
+
`${hostStamp()} spawning: electron=${electron} (exists=${String(existsSync(electron))})`
|
|
506
|
+
+ ` source=${source}`
|
|
507
|
+
+ ` hostMain=${this.hostMainPath} (exists=${String(existsSync(this.hostMainPath))})`
|
|
508
|
+
+ ` port=${String(this.port)}\n`,
|
|
509
|
+
)
|
|
510
|
+
// ELECTRON_RUN_AS_NODE (even an empty string) makes Electron run as plain
|
|
511
|
+
// Node, breaking require('electron'); NODE_OPTIONS can inject flags that
|
|
512
|
+
// break the child. Rebuild the env without either.
|
|
513
|
+
const env: Record<string, string | undefined> = { ...process.env }
|
|
514
|
+
delete env.ELECTRON_RUN_AS_NODE
|
|
515
|
+
delete env.NODE_OPTIONS
|
|
516
|
+
// Windows GUI-subsystem processes (Electron included) never receive piped
|
|
517
|
+
// stdin, so the token written below is silently lost there. Pass it as an
|
|
518
|
+
// environment variable too (hidden from the process-listing tools that
|
|
519
|
+
// expose argv, and preferred over stdin only when stdin cannot deliver):
|
|
520
|
+
// the child reads env only as a fallback after stdin yields nothing.
|
|
521
|
+
env.DSH_BROWSER_RPC_TOKEN = token
|
|
522
|
+
if (this.userDataDir !== undefined) env.DSH_BROWSER_USER_DATA_DIR = this.userDataDir
|
|
523
|
+
this.child = spawn(electron, [hostMainPath, '--rpc-port', String(port)], {
|
|
524
|
+
stdio: ['pipe', 'pipe', 'pipe'],
|
|
525
|
+
windowsHide: false,
|
|
526
|
+
env,
|
|
527
|
+
})
|
|
528
|
+
this.child.stderr.setEncoding('utf8')
|
|
529
|
+
this.child.stderr.on('data', chunk => {
|
|
530
|
+
// Diagnostics only; never parse stderr as protocol. Mirror to a log file
|
|
531
|
+
// as well: under a plain `dsh web` self-host these lines only ever reach
|
|
532
|
+
// the DSH process's stderr, so a host that crashes in a restart loop left
|
|
533
|
+
// the user with a string of timeouts and no stack to act on.
|
|
534
|
+
const text = String(chunk)
|
|
535
|
+
process.stderr.write(`[dsh-browser host] ${text}`)
|
|
536
|
+
appendHostLog(text)
|
|
537
|
+
})
|
|
538
|
+
// Send the spawn token over stdin (first line). The child reads it from
|
|
539
|
+
// stdin instead of argv so the token is never visible in the process
|
|
540
|
+
// listing (WMI / Process Explorer / /proc/*). After writing, close stdin
|
|
541
|
+
// so the child knows the token has been fully delivered.
|
|
542
|
+
this.child.stdin?.write(token + '\n')
|
|
543
|
+
this.child.stdin?.end()
|
|
544
|
+
// A failed spawn (bad/corrupt binary) emits 'error' — without a listener
|
|
545
|
+
// that would crash the whole DSH process.
|
|
546
|
+
this.child.on('error', error => {
|
|
547
|
+
const line = `${hostStamp()} spawn error: ${String(error)} electron=${electron} hostMain=${this.hostMainPath}`
|
|
548
|
+
process.stderr.write(`[dsh-browser host] ${line}\n`)
|
|
549
|
+
appendHostLog(`${line}\n`)
|
|
550
|
+
// The cached availability answer is retired by `onExit` below, which this reaches
|
|
551
|
+
// through fail(): the decision needs the host's view of what is on disk, not the
|
|
552
|
+
// client's.
|
|
553
|
+
this.fail(new Error(`dsh-builtin-browser: browser host failed to start: ${String(error)}`))
|
|
554
|
+
})
|
|
555
|
+
this.child.on('exit', (code, signal) => {
|
|
556
|
+
// The exit code/signal is the other half of a crash report; without it a
|
|
557
|
+
// restart loop is indistinguishable from a clean stop. The timestamp, pid
|
|
558
|
+
// and both paths are what turn a bare `code=1` into a diagnosis: Electron
|
|
559
|
+
// exits 1 with empty stderr precisely when it cannot load the app entry,
|
|
560
|
+
// so the dated `exists=` line written at spawn is the other half.
|
|
561
|
+
const entryExists = existsSync(this.hostMainPath)
|
|
562
|
+
const line = `${hostStamp()} browser host exited (code=${String(code)} signal=${String(signal)})`
|
|
563
|
+
+ ` pid=${String(this.child?.pid)} electron=${electron} hostMain=${this.hostMainPath}`
|
|
564
|
+
+ ` entryExists=${String(entryExists)}`
|
|
565
|
+
// Comparing this with the `exists=` recorded at spawn is the whole
|
|
566
|
+
// diagnosis: present at spawn and absent now means the installation was
|
|
567
|
+
// replaced underneath a running host, which is exactly how Electron ends
|
|
568
|
+
// up unable to load the app entry and exits 1 with empty stderr.
|
|
569
|
+
+ (entryExists ? '' : ' [entry script missing at exit]')
|
|
570
|
+
appendHostLog(`${line}\n`)
|
|
571
|
+
this.fail(new Error(`dsh-builtin-browser: ${line}`))
|
|
572
|
+
})
|
|
573
|
+
}
|
|
574
|
+
|
|
575
|
+
/**
|
|
576
|
+
* Drop the escalation kill once there is nothing left for it to target.
|
|
577
|
+
*
|
|
578
|
+
* Called on the paths where the child is known to be gone — after an observed exit, and on
|
|
579
|
+
* release. It is deliberately NOT called from `fail()`: a dead socket says nothing about the
|
|
580
|
+
* process on the other end, and the timer exists for exactly the case where the child ignores
|
|
581
|
+
* the socket closing. Clearing it there disarmed the only escalation there was, which is how
|
|
582
|
+
* a child that ignored its socket could outlive dispose() and keep holding the profile.
|
|
583
|
+
*/
|
|
584
|
+
private clearKillGrace(): void {
|
|
585
|
+
if (this.killGraceTimer === undefined) return
|
|
586
|
+
clearTimeout(this.killGraceTimer)
|
|
587
|
+
this.killGraceTimer = undefined
|
|
588
|
+
}
|
|
589
|
+
|
|
590
|
+
/** Drop the "did not authenticate" deadline once it can no longer be meaningful. */
|
|
591
|
+
private clearHelloTimer(): void {
|
|
592
|
+
if (this.helloTimer === undefined) return
|
|
593
|
+
clearTimeout(this.helloTimer)
|
|
594
|
+
this.helloTimer = undefined
|
|
595
|
+
}
|
|
596
|
+
|
|
597
|
+
/** Reject everything in flight, mark the client dead, and notify the host. */
|
|
598
|
+
private fail(err: Error): void {
|
|
599
|
+
if (this.dead) return
|
|
600
|
+
this.dead = true
|
|
601
|
+
this.connected = false
|
|
602
|
+
// The authentication deadline outlives the socket it was armed for otherwise: it is
|
|
603
|
+
// keyed on `awaitingHello` alone, so a client that already failed on some other path
|
|
604
|
+
// kept a live timer until it fired (harmless, but it is a dangling timer in a process
|
|
605
|
+
// that may be shutting down).
|
|
606
|
+
this.clearHelloTimer()
|
|
607
|
+
// NOT clearKillGrace(): this path runs when the SOCKET died, which says nothing about
|
|
608
|
+
// whether the process did. Clearing the escalation here disarmed it for exactly the case it
|
|
609
|
+
// exists for — a child that ignores its socket closing — so dispose() could return with the
|
|
610
|
+
// child still running and still holding the profile. The timer clears itself when the child
|
|
611
|
+
// exits, and `kill()` replaces it on an explicit release.
|
|
612
|
+
// Tag every failure as "host gone" so the view layer can tell a dead host
|
|
613
|
+
// apart from a page-level error and rebuild against a fresh child.
|
|
614
|
+
const wrapped = err instanceof HostGoneError ? err : new HostGoneError(err.message)
|
|
615
|
+
for (const pending of this.pending.values()) pending.reject(wrapped)
|
|
616
|
+
this.pending.clear()
|
|
617
|
+
this.outbox = []
|
|
618
|
+
this.onExit?.()
|
|
619
|
+
}
|
|
620
|
+
|
|
621
|
+
/** Whether a connection (authenticated or still authenticating) is held. */
|
|
622
|
+
isAttached(): boolean {
|
|
623
|
+
return this.socket !== undefined
|
|
624
|
+
}
|
|
625
|
+
|
|
626
|
+
/**
|
|
627
|
+
* Accept the child's connection (called by the server). Exactly one socket
|
|
628
|
+
* is ever attached; the server drops any further connection. Commands stay
|
|
629
|
+
* queued until the child's first line authenticates with the spawn token.
|
|
630
|
+
*/
|
|
631
|
+
attach(socket: import('node:net').Socket): void {
|
|
632
|
+
if (this.socket !== undefined) {
|
|
633
|
+
// Already attached: this is a second connection; reject it.
|
|
634
|
+
socket.destroy()
|
|
635
|
+
return
|
|
636
|
+
}
|
|
637
|
+
this.socket = socket
|
|
638
|
+
socket.setEncoding('utf8')
|
|
639
|
+
// Without an 'error' listener a remote reset (ECONNRESET/EPIPE) throws an
|
|
640
|
+
// uncaught 'error' event and crashes the whole DSH process; 'close' below
|
|
641
|
+
// does the cleanup.
|
|
642
|
+
socket.on('error', error => {
|
|
643
|
+
process.stderr.write(`[dsh-browser host] socket error: ${String(error)}\n`)
|
|
644
|
+
})
|
|
645
|
+
socket.on('data', chunk => this.onData(chunk))
|
|
646
|
+
socket.on('close', () => {
|
|
647
|
+
this.connected = false
|
|
648
|
+
if (!this.dead) {
|
|
649
|
+
this.fail(new Error('dsh-builtin-browser: browser host connection closed'))
|
|
650
|
+
}
|
|
651
|
+
})
|
|
652
|
+
// The child must authenticate within the readiness budget; otherwise the
|
|
653
|
+
// connection is treated as hostile and torn down.
|
|
654
|
+
this.helloTimer = setTimeout(() => {
|
|
655
|
+
if (this.awaitingHello) {
|
|
656
|
+
socket.destroy()
|
|
657
|
+
this.fail(new Error('dsh-builtin-browser: browser host did not authenticate'))
|
|
658
|
+
}
|
|
659
|
+
}, READY_TIMEOUT_MS)
|
|
660
|
+
}
|
|
661
|
+
|
|
662
|
+
private onData(chunk: string | Buffer): void {
|
|
663
|
+
this.buffer += typeof chunk === 'string' ? chunk : chunk.toString('utf8')
|
|
664
|
+
// Safety net: a pathological child (or a reply larger than expected)
|
|
665
|
+
// must not grow the parent's memory without bound. The child caps
|
|
666
|
+
// downloads at 256 MiB, so a healthy stream never approaches this.
|
|
667
|
+
if (this.buffer.length > MAX_RPC_BUFFER_BYTES) {
|
|
668
|
+
this.buffer = ''
|
|
669
|
+
this.fail(new Error(`dsh-builtin-browser: RPC reply exceeded ${MAX_RPC_BUFFER_BYTES} bytes`))
|
|
670
|
+
return
|
|
671
|
+
}
|
|
672
|
+
let nl: number
|
|
673
|
+
while ((nl = this.buffer.indexOf('\n')) >= 0) {
|
|
674
|
+
const line = this.buffer.slice(0, nl).trim()
|
|
675
|
+
this.buffer = this.buffer.slice(nl + 1)
|
|
676
|
+
if (line === '') continue
|
|
677
|
+
let msg: { id?: number; op?: string; token?: string; ok?: boolean; result?: unknown; err?: string; action?: unknown; windowId?: unknown }
|
|
678
|
+
try {
|
|
679
|
+
msg = JSON.parse(line) as typeof msg
|
|
680
|
+
} catch {
|
|
681
|
+
// Non-protocol line; ignore.
|
|
682
|
+
continue
|
|
683
|
+
}
|
|
684
|
+
if (msg.op === 'userAction' || msg.op === 'viewClosed') {
|
|
685
|
+
// A fire-and-forget notification from the child's own UI (toolbar). These carry no
|
|
686
|
+
// reply and no pending id, and they hand the provider a session-level verb — so they
|
|
687
|
+
// are dispatched ONLY once the peer has proved it knows the spawn token.
|
|
688
|
+
//
|
|
689
|
+
// They used to be handled before the hello check, while the module comment claimed an
|
|
690
|
+
// unauthenticated peer "is disconnected immediately … a spoofed socket never sees
|
|
691
|
+
// traffic". Both were wrong: any loopback process that won the race for the single
|
|
692
|
+
// accepted socket could inject `viewClosed` and end the human's browser session
|
|
693
|
+
// before the token check rejected it. Only the loopback interface can connect, so
|
|
694
|
+
// this is a same-machine race rather than a remote attack — which is exactly the
|
|
695
|
+
// kind of thing the token exists to close.
|
|
696
|
+
if (this.awaitingHello) {
|
|
697
|
+
this.awaitingHello = false
|
|
698
|
+
this.clearHelloTimer()
|
|
699
|
+
this.socket?.destroy()
|
|
700
|
+
this.fail(new Error('dsh-builtin-browser: browser host sent a notification before authenticating'))
|
|
701
|
+
return
|
|
702
|
+
}
|
|
703
|
+
if (msg.op === 'userAction') {
|
|
704
|
+
// Route it straight to the host's user-action handler (which the provider registered).
|
|
705
|
+
this.onUserAction?.(msg.action as BrowserUserAction)
|
|
706
|
+
} else {
|
|
707
|
+
// The human closed the window, so the interface that session showed is gone. The
|
|
708
|
+
// provider decides what that ends — browsing history and login state survive on
|
|
709
|
+
// disk, only the session itself does not.
|
|
710
|
+
this.onViewClosed?.(typeof msg.windowId === 'string' ? msg.windowId : '')
|
|
711
|
+
}
|
|
712
|
+
continue
|
|
713
|
+
}
|
|
714
|
+
if (this.awaitingHello) {
|
|
715
|
+
// The FIRST line must be the child's hello carrying the spawn token.
|
|
716
|
+
// Anything else (or a wrong token) means a spoofed connection: drop
|
|
717
|
+
// it and fail every pending call rather than trust the line.
|
|
718
|
+
this.awaitingHello = false
|
|
719
|
+
this.clearHelloTimer()
|
|
720
|
+
if (msg.op !== 'hello' || msg.token !== this.token) {
|
|
721
|
+
this.socket?.destroy()
|
|
722
|
+
this.fail(new Error('dsh-builtin-browser: browser host authentication failed'))
|
|
723
|
+
return
|
|
724
|
+
}
|
|
725
|
+
this.connected = true
|
|
726
|
+
// Flush anything queued while disconnected — now that the peer is
|
|
727
|
+
// authenticated, it is safe to send commands.
|
|
728
|
+
if (this.outbox.length > 0) {
|
|
729
|
+
for (const line of this.outbox) this.socket?.write(line + '\n')
|
|
730
|
+
this.outbox = []
|
|
731
|
+
}
|
|
732
|
+
continue
|
|
733
|
+
}
|
|
734
|
+
if (typeof msg.id !== 'number') continue
|
|
735
|
+
const pending = this.pending.get(msg.id)
|
|
736
|
+
if (pending === undefined) continue
|
|
737
|
+
this.pending.delete(msg.id)
|
|
738
|
+
if (msg.ok === true) pending.resolve(msg.result)
|
|
739
|
+
else pending.reject(new Error(msg.err ?? 'browser host command failed'))
|
|
740
|
+
}
|
|
741
|
+
}
|
|
742
|
+
|
|
743
|
+
/** Send one command and await the reply. */
|
|
744
|
+
call<T = unknown>(op: string, payload: Record<string, unknown> = {}): Promise<T> {
|
|
745
|
+
if (this.dead) {
|
|
746
|
+
return Promise.reject(new HostGoneError('dsh-builtin-browser: browser host is not running'))
|
|
747
|
+
}
|
|
748
|
+
const id = this.nextId++
|
|
749
|
+
const line = JSON.stringify({ id, op, ...payload })
|
|
750
|
+
return new Promise<T>((resolve, reject) => {
|
|
751
|
+
this.pending.set(id, { resolve: resolve as (v: unknown) => void, reject })
|
|
752
|
+
if (this.connected && this.socket !== undefined) {
|
|
753
|
+
try {
|
|
754
|
+
this.socket.write(line + '\n')
|
|
755
|
+
} catch {
|
|
756
|
+
// The socket died between the dead check and the write; the 'close'
|
|
757
|
+
// handler fails the rest. Reject THIS call as host-gone so the
|
|
758
|
+
// caller can recover immediately instead of hanging.
|
|
759
|
+
this.pending.delete(id)
|
|
760
|
+
reject(new HostGoneError('dsh-builtin-browser: browser host connection closed'))
|
|
761
|
+
}
|
|
762
|
+
} else {
|
|
763
|
+
// Not connected yet: queue; attach() flushes on the child's arrival.
|
|
764
|
+
this.outbox.push(line)
|
|
765
|
+
}
|
|
766
|
+
})
|
|
767
|
+
}
|
|
768
|
+
|
|
769
|
+
/**
|
|
770
|
+
* How long the child gets to exit by itself after the socket closes, before it is killed.
|
|
771
|
+
* The child quits on that signal, so in practice this is a few dozen milliseconds; the timer
|
|
772
|
+
* exists for the case where it does not, and it is deliberately NOT unref'd — the parent must
|
|
773
|
+
* stay alive long enough to enforce it, or the escalation would be dropped with the process.
|
|
774
|
+
*/
|
|
775
|
+
private static readonly KILL_GRACE_MS = 500
|
|
776
|
+
private killGraceTimer: NodeJS.Timeout | undefined
|
|
777
|
+
|
|
778
|
+
/**
|
|
779
|
+
* Terminate the child, after giving it the chance to shut down properly.
|
|
780
|
+
*
|
|
781
|
+
* The socket goes first, because that is the signal the child actually handles: its `close`
|
|
782
|
+
* listener quits the app, and a normal quit is what lets Chromium write its profile out. Only
|
|
783
|
+
* a child still alive after the grace period is killed outright.
|
|
784
|
+
*
|
|
785
|
+
* This order used to be the other way round, justified by a comment claiming the child's own
|
|
786
|
+
* path "closes its window and flushes the profile", which made killing first the safer order.
|
|
787
|
+
* Both halves of that were wrong: the path ran `app.exit(0)`, which skips before-quit/will-quit
|
|
788
|
+
* and does not flush Chromium's profile writers at all; and on Windows `child.kill()` is
|
|
789
|
+
* TerminateProcess, which lands before the child can run any handler whatsoever. So the
|
|
790
|
+
* graceful path that comment was protecting never got to start, and the profile went
|
|
791
|
+
* unflushed on every single dispose.
|
|
792
|
+
*/
|
|
793
|
+
kill(): void {
|
|
794
|
+
this.clearHelloTimer()
|
|
795
|
+
try { this.socket?.destroy() } catch { /* already closed */ }
|
|
796
|
+
const child = this.child
|
|
797
|
+
this.clearKillGrace()
|
|
798
|
+
this.killGraceTimer = setTimeout(() => {
|
|
799
|
+
try { child.kill() } catch { /* already gone */ }
|
|
800
|
+
}, ElectronChildClient.KILL_GRACE_MS)
|
|
801
|
+
}
|
|
802
|
+
}
|
|
803
|
+
|
|
804
|
+
/** One view in the child: its id, used for every command. */
|
|
805
|
+
class RemoteView implements ElectronViewHandle {
|
|
806
|
+
readonly id: string
|
|
807
|
+
private readonly client: ElectronChildClient
|
|
808
|
+
constructor(id: string, client: ElectronChildClient) {
|
|
809
|
+
this.id = id
|
|
810
|
+
this.client = client
|
|
811
|
+
}
|
|
812
|
+
|
|
813
|
+
sendCommand(method: string, params?: Record<string, unknown>): Promise<Record<string, unknown>> {
|
|
814
|
+
return this.client.call<Record<string, unknown>>('command', {
|
|
815
|
+
viewId: this.id,
|
|
816
|
+
method,
|
|
817
|
+
params: params ?? {},
|
|
818
|
+
})
|
|
819
|
+
}
|
|
820
|
+
|
|
821
|
+
/** Give this view web focus in the child, so keyboard input reaches the page. */
|
|
822
|
+
focus(options?: PresentOptions): Promise<void> {
|
|
823
|
+
return this.client.call<void>('focus', { viewId: this.id, ...options?.quiet ? { quiet: true } : {} })
|
|
824
|
+
}
|
|
825
|
+
|
|
826
|
+
/** Ask the child to download a URL to a local file (keeps cookies/login). */
|
|
827
|
+
async download(url: string, savePath: string): Promise<void> {
|
|
828
|
+
// The child writes the file itself (temp + rename); only a small
|
|
829
|
+
// confirmation crosses the RPC, so large downloads never balloon the
|
|
830
|
+
// parent's memory or hit the single-line cap.
|
|
831
|
+
await this.client.call<{ path: string }>('download', { viewId: this.id, url, savePath })
|
|
832
|
+
}
|
|
833
|
+
|
|
834
|
+
/** Native capturePage snapshot of the view (base64 + mime). */
|
|
835
|
+
capture(opts?: ScreenshotOptions): Promise<{ base64: string; mime: string }> {
|
|
836
|
+
return this.client.call<{ base64: string; mime: string }>('capture', { viewId: this.id, ...opts ?? {} })
|
|
837
|
+
}
|
|
838
|
+
|
|
839
|
+
/** Export the session's cookies (login state). */
|
|
840
|
+
flushAuth(): Promise<ExportedCookie[]> {
|
|
841
|
+
return this.client.call<{ cookies: ExportedCookie[] }>('flushAuth', { viewId: this.id }).then(r => r.cookies)
|
|
842
|
+
}
|
|
843
|
+
|
|
844
|
+
/** Import cookies into the session (restore login state). */
|
|
845
|
+
restoreAuth(cookies: ExportedCookie[]): Promise<number> {
|
|
846
|
+
return this.client.call<{ restored: number }>('restoreAuth', { viewId: this.id, cookies }).then(r => r.restored)
|
|
847
|
+
}
|
|
848
|
+
}
|
|
849
|
+
|
|
850
|
+
/**
|
|
851
|
+
* How long a FAILED Electron-binary probe is remembered before the binary
|
|
852
|
+
* search runs again (`available()`). A success is kept for the host's lifetime.
|
|
853
|
+
*/
|
|
854
|
+
const PROBE_RETRY_MS = (() => {
|
|
855
|
+
const raw = Number(process.env.DSH_BROWSER_PROBE_RETRY_MS)
|
|
856
|
+
return Number.isFinite(raw) && raw >= 0 ? raw : 30000
|
|
857
|
+
})()
|
|
858
|
+
|
|
859
|
+
/**
|
|
860
|
+
* Retry schedule for a browser host that will not stay up, in milliseconds, indexed by the
|
|
861
|
+
* number of consecutive failed starts (see {@link RemoteElectronViewHost.noteStartFailure}).
|
|
862
|
+
*
|
|
863
|
+
* The first entry is 0 on purpose: an ordinary one-off death must still heal on the very
|
|
864
|
+
* next call, which is the behaviour remote-host-recovery.test.mjs pins. From the second
|
|
865
|
+
* failure on, each attempt is spaced. `available()` can only answer "is there a binary",
|
|
866
|
+
* so a binary that exists and crashes on every launch (`code=1` with empty stderr) would
|
|
867
|
+
* otherwise produce an endless crash loop, one window per tool call, with nothing to make
|
|
868
|
+
* it stop.
|
|
869
|
+
*/
|
|
870
|
+
const START_RETRY_SCHEDULE_MS: readonly number[] = [0, 500, 2_000, 8_000, 30_000]
|
|
871
|
+
|
|
872
|
+
/** Attempts after which the host stops retrying immediately and keeps the longest delay. */
|
|
873
|
+
const START_FAILURES_MAX = START_RETRY_SCHEDULE_MS.length
|
|
874
|
+
|
|
875
|
+
/** Two reports within this window describe the same dying child, not two attempts. */
|
|
876
|
+
const START_FAILURE_DEDUPE_MS = 1_000
|
|
877
|
+
|
|
878
|
+
/** Render a delay for a human-readable log line. */
|
|
879
|
+
function formatDelay(ms: number): string {
|
|
880
|
+
return ms >= 1_000 ? `${(ms / 1_000).toFixed(1)}s` : `${String(ms)}ms`
|
|
881
|
+
}
|
|
882
|
+
|
|
883
|
+
/**
|
|
884
|
+
* Self-hosted view host: spawns the plugin's Electron child on first use and
|
|
885
|
+
* keeps it alive until dispose(). Fallback when no desktop shell provides
|
|
886
|
+
* ctx.electronViewHost.
|
|
887
|
+
*/
|
|
888
|
+
export class RemoteElectronViewHost implements ElectronBrowserViewHost {
|
|
889
|
+
private client: ElectronChildClient | undefined
|
|
890
|
+
private server: Server | undefined
|
|
891
|
+
private pendingSocket: Socket | undefined
|
|
892
|
+
private readonly views = new Map<string, ElectronViewHandle>()
|
|
893
|
+
private readyPromise: Promise<void> | undefined
|
|
894
|
+
private disposed = false
|
|
895
|
+
/** Last probe result. A success is kept for the host's lifetime; a failure
|
|
896
|
+
* is retried after `PROBE_RETRY_MS` (see `available()`). */
|
|
897
|
+
private electronAvailable: boolean | undefined
|
|
898
|
+
/** Earliest time the next probe may run after a negative one. */
|
|
899
|
+
private nextProbeAt = 0
|
|
900
|
+
/** Consecutive child starts that did not survive; drives {@link startRetryAt}. */
|
|
901
|
+
private startFailures = 0
|
|
902
|
+
/** Earliest time `ready()` may spawn another child after a failed start. */
|
|
903
|
+
private startRetryAt: number | undefined
|
|
904
|
+
/** When the last start failure was reported, used to keep one death to one log line. */
|
|
905
|
+
private lastStartFailureAt = 0
|
|
906
|
+
/** Window groups (windowId per view), re-sent on every materialization so
|
|
907
|
+
* a restarted child still places views in the right windows. */
|
|
908
|
+
private readonly groups = new Map<string, { windowId: string; label?: string }>()
|
|
909
|
+
/** The provider's user-action handler; routes toolbar actions into sessions. */
|
|
910
|
+
private userActionHandler: ((action: BrowserUserAction) => void) | undefined
|
|
911
|
+
/**
|
|
912
|
+
* The provider's handler for a window the human closed. Closing the interface
|
|
913
|
+
* ends the session it showed: history and login state stay on disk, so the
|
|
914
|
+
* next open starts clean instead of resuming a window nobody can see.
|
|
915
|
+
*/
|
|
916
|
+
private viewClosedHandler: ((windowId: string) => void) | undefined
|
|
917
|
+
private readonly hostMainPath: string
|
|
918
|
+
private readonly spawnExecutable?: string
|
|
919
|
+
private readonly probe: () => void
|
|
920
|
+
private readonly ephemeralUserDataDir?: string
|
|
921
|
+
constructor(
|
|
922
|
+
hostMainPath: string,
|
|
923
|
+
/** Test seam: the executable to spawn instead of the resolved Electron
|
|
924
|
+
* binary. Absent -> resolveElectronPath() (production behavior). */
|
|
925
|
+
spawnExecutable?: string,
|
|
926
|
+
/** Test seam: the binary probe behind `available()`. Absent ->
|
|
927
|
+
* resolveElectronPath(). */
|
|
928
|
+
probe: () => void = resolveElectronPath,
|
|
929
|
+
/** Optional ephemeral userData directory when cookies.persist is false; removed on dispose(). */
|
|
930
|
+
ephemeralUserDataDir?: string,
|
|
931
|
+
) {
|
|
932
|
+
this.hostMainPath = hostMainPath
|
|
933
|
+
this.spawnExecutable = spawnExecutable
|
|
934
|
+
this.probe = probe
|
|
935
|
+
this.ephemeralUserDataDir = ephemeralUserDataDir
|
|
936
|
+
}
|
|
937
|
+
|
|
938
|
+
/**
|
|
939
|
+
* Cheap usability probe: can we find an Electron binary to spawn? The scan
|
|
940
|
+
* is filesystem-only (no network), per the seam's contract, so a missing
|
|
941
|
+
* binary surfaces as `BROWSER_PROVIDER_UNAVAILABLE` at provider selection
|
|
942
|
+
* instead of a confusing spawn failure on first use.
|
|
943
|
+
*
|
|
944
|
+
* A success is cached for the host's lifetime. A failure is NOT: an install
|
|
945
|
+
* (`npm i electron`, or the postinstall that fetches the binary) can land
|
|
946
|
+
* long after DSH started, and provider selection happens once per process —
|
|
947
|
+
* caching "no" permanently reported "no usable browser provider is
|
|
948
|
+
* registered" until DSH restarted, with no way back short of that. Retrying
|
|
949
|
+
* on a cooldown heals it by itself while keeping the scan off the hot path.
|
|
950
|
+
*/
|
|
951
|
+
available(): boolean {
|
|
952
|
+
if (this.electronAvailable === true) return true
|
|
953
|
+
if (Date.now() < this.nextProbeAt) return false
|
|
954
|
+
this.nextProbeAt = Date.now() + PROBE_RETRY_MS
|
|
955
|
+
try {
|
|
956
|
+
this.probe()
|
|
957
|
+
this.electronAvailable = true
|
|
958
|
+
} catch (error) {
|
|
959
|
+
this.electronAvailable = false
|
|
960
|
+
// The provider will be reported unavailable, so the detailed
|
|
961
|
+
// resolution error (install-electron / ELECTRON_PATH guidance) would
|
|
962
|
+
// otherwise never reach the user — surface it on stderr.
|
|
963
|
+
process.stderr.write(`[dsh-browser host] electron unavailable: ${error instanceof Error ? error.message : String(error)}\n`)
|
|
964
|
+
}
|
|
965
|
+
return this.electronAvailable
|
|
966
|
+
}
|
|
967
|
+
|
|
968
|
+
/**
|
|
969
|
+
* Retire a negative binary-probe cache immediately after on-demand provisioning
|
|
970
|
+
* finishes so the very next call sees the new binary without waiting out the
|
|
971
|
+
* cooldown or restarting DSH.
|
|
972
|
+
*/
|
|
973
|
+
refreshAvailability(): void {
|
|
974
|
+
if (this.electronAvailable === false) {
|
|
975
|
+
this.electronAvailable = undefined
|
|
976
|
+
this.nextProbeAt = 0
|
|
977
|
+
}
|
|
978
|
+
}
|
|
979
|
+
|
|
980
|
+
/**
|
|
981
|
+
* Retire the cached "an Electron binary is here" answer.
|
|
982
|
+
*
|
|
983
|
+
* A success is cached for the host's lifetime because rescanning on every tool call was
|
|
984
|
+
* the original bug — but the probe reads the FILESYSTEM, so it cannot see a binary that
|
|
985
|
+
* stops being usable afterwards. Only a real spawn attempt can observe that, which is why
|
|
986
|
+
* the two failure paths in {@link RemoteElectronViewHost.start} call this: the next
|
|
987
|
+
* `available()` rescans and reports what is actually on disk, instead of advertising a
|
|
988
|
+
* provider that cannot start.
|
|
989
|
+
*/
|
|
990
|
+
private forgetBinary(): void {
|
|
991
|
+
this.electronAvailable = undefined
|
|
992
|
+
this.nextProbeAt = 0
|
|
993
|
+
}
|
|
994
|
+
|
|
995
|
+
/**
|
|
996
|
+
* Whether the binary the host would spawn — or the entry it needs — is no longer there.
|
|
997
|
+
*
|
|
998
|
+
* Only asked after a launch actually failed, so a healthy path never pays for it. The
|
|
999
|
+
* entry script counts because Electron exits 1 with empty stderr when it cannot load it,
|
|
1000
|
+
* and resolution itself throws exactly when it can find nothing, which is the same answer.
|
|
1001
|
+
* @returns true when the next `available()` must rescan instead of reusing its cache.
|
|
1002
|
+
*/
|
|
1003
|
+
private binaryIsGone(): boolean {
|
|
1004
|
+
if (!existsSync(this.hostMainPath)) return true
|
|
1005
|
+
try {
|
|
1006
|
+
return !existsSync(this.spawnExecutable ?? resolveElectronPath())
|
|
1007
|
+
} catch {
|
|
1008
|
+
return true
|
|
1009
|
+
}
|
|
1010
|
+
}
|
|
1011
|
+
|
|
1012
|
+
/**
|
|
1013
|
+
* Ensure the child is up and ready (lazy on first use; restarts after a crash).
|
|
1014
|
+
*
|
|
1015
|
+
* Never throws synchronously. Callers are fire-and-forget
|
|
1016
|
+
* (`void this.ready().then(…).catch(…)`), and a synchronous throw escapes their
|
|
1017
|
+
* `.catch` entirely — the shape that let a failed toolbar report take the whole
|
|
1018
|
+
* DSH host down (issue #16). A disposed host is reported as a rejected promise
|
|
1019
|
+
* instead, which those callers already handle.
|
|
1020
|
+
*/
|
|
1021
|
+
private ready(): Promise<void> {
|
|
1022
|
+
// Fail fast on a disposed host: a recovery path can re-enter ready() after
|
|
1023
|
+
// dispose() cleared its state, and starting fresh here would spawn a child
|
|
1024
|
+
// nobody will ever kill.
|
|
1025
|
+
if (this.disposed) {
|
|
1026
|
+
const gone = Promise.reject(new HostGoneError('browser host disposed'))
|
|
1027
|
+
// Keep the rejection observable to callers while marking it handled here:
|
|
1028
|
+
// a fire-and-forget caller that forgot to attach a handler must not turn
|
|
1029
|
+
// this into an unhandled rejection either.
|
|
1030
|
+
gone.catch(() => undefined)
|
|
1031
|
+
return gone
|
|
1032
|
+
}
|
|
1033
|
+
if (this.readyPromise !== undefined) return this.readyPromise
|
|
1034
|
+
// Backoff gate for a host that keeps failing to START (see START_RETRY_SCHEDULE_MS).
|
|
1035
|
+
// The client is undefined exactly when the previous child is gone — a start failure, or
|
|
1036
|
+
// a child that died after it came up — so this only delays restarts, never first use.
|
|
1037
|
+
const retryAt = this.startRetryAt
|
|
1038
|
+
if (retryAt !== undefined && Date.now() < retryAt && this.client === undefined) {
|
|
1039
|
+
const waitMs = retryAt - Date.now()
|
|
1040
|
+
const waiting = Promise.reject(new HostGoneError(
|
|
1041
|
+
`browser host did not start; retrying in ${formatDelay(waitMs)} `
|
|
1042
|
+
+ `(attempt ${String(this.startFailures)}${this.startFailures >= START_FAILURES_MAX ? ', start attempts are now spaced out rather than immediate' : ''})`,
|
|
1043
|
+
))
|
|
1044
|
+
// Keep the rejection observable to callers while marking it handled here: the
|
|
1045
|
+
// fire-and-forget callers that drive this path attach their own handler, but one that
|
|
1046
|
+
// forgets must not turn the recovery gate into an unhandled rejection.
|
|
1047
|
+
waiting.catch(() => undefined)
|
|
1048
|
+
return waiting
|
|
1049
|
+
}
|
|
1050
|
+
const started = this.start()
|
|
1051
|
+
const wrapped = started.then(
|
|
1052
|
+
() => {
|
|
1053
|
+
// A child that came up clears the record: the next death is a new failure, not
|
|
1054
|
+
// another entry in this run of them.
|
|
1055
|
+
this.startFailures = 0
|
|
1056
|
+
this.startRetryAt = undefined
|
|
1057
|
+
},
|
|
1058
|
+
error => {
|
|
1059
|
+
// Record the failure BEFORE tearing anything down, and gate the teardown on the
|
|
1060
|
+
// retry state being gone rather than on readyPromise alone. Ordering matters: a
|
|
1061
|
+
// child that exits while the readiness call is still in flight fires the client's
|
|
1062
|
+
// 'exit' handler first (onChildExit invalidates this promise and starts the retry
|
|
1063
|
+
// clock), and the rejection then lands here — at which point clearing startRetryAt
|
|
1064
|
+
// would erase the very backoff that was just armed, so every tool call spawned
|
|
1065
|
+
// another dying child. noteStartFailure's dedupe window counts that pair once.
|
|
1066
|
+
this.noteStartFailure(error)
|
|
1067
|
+
// A failed startup must not poison the host forever: tear down whatever
|
|
1068
|
+
// was half-created and let the next call retry from scratch.
|
|
1069
|
+
if (this.readyPromise === wrapped) {
|
|
1070
|
+
this.readyPromise = undefined
|
|
1071
|
+
this.client?.kill()
|
|
1072
|
+
this.client = undefined
|
|
1073
|
+
this.server?.close()
|
|
1074
|
+
this.server = undefined
|
|
1075
|
+
this.pendingSocket?.destroy()
|
|
1076
|
+
this.pendingSocket = undefined
|
|
1077
|
+
}
|
|
1078
|
+
throw error
|
|
1079
|
+
},
|
|
1080
|
+
)
|
|
1081
|
+
this.readyPromise = wrapped
|
|
1082
|
+
return wrapped
|
|
1083
|
+
}
|
|
1084
|
+
|
|
1085
|
+
/**
|
|
1086
|
+
* Record one child that did not survive, and set the earliest retry time.
|
|
1087
|
+
*
|
|
1088
|
+
* `available()` answers "is there a binary to spawn" from the FILESYSTEM, and a success
|
|
1089
|
+
* there is cached for the host's lifetime (correctly — rescanning on every tool call was
|
|
1090
|
+
* the bug). That probe therefore cannot see the failure mode where the binary exists and
|
|
1091
|
+
* crashes on every launch: the signature `code=1` with empty stderr that host-log.test.mjs
|
|
1092
|
+
* asserts. Each browser call then spawned a child that died within milliseconds, with no
|
|
1093
|
+
* backoff and nothing that ever gives up — an endless crash loop, each iteration a window
|
|
1094
|
+
* flashing on screen.
|
|
1095
|
+
*
|
|
1096
|
+
* The first retry is immediate, so the ordinary transient death (the DSH restart in
|
|
1097
|
+
* remote-host-recovery.test.mjs) still heals on the very next call. After that the delay
|
|
1098
|
+
* grows: once {@link START_FAILURES_MAX} attempts have failed, every later attempt is
|
|
1099
|
+
* spaced by the table's last entry — the host keeps trying, but a permanently broken
|
|
1100
|
+
* install now costs one spawn per 30s instead of one per tool call. Nothing is marked
|
|
1101
|
+
* dead for good: a repaired installation heals on the next attempt, and `dispose()`
|
|
1102
|
+
* still stops everything immediately.
|
|
1103
|
+
* @param error - what the failed attempt reported.
|
|
1104
|
+
*/
|
|
1105
|
+
private noteStartFailure(error: unknown): void {
|
|
1106
|
+
// The same death arrives twice: the child's exit reports it, and ready() rejecting
|
|
1107
|
+
// reports it again. Counting both pushed the first retry to the 500ms step and made
|
|
1108
|
+
// the log say "attempt 2" for a first failure, while START_RETRY_SCHEDULE_MS[0] = 0
|
|
1109
|
+
// exists precisely so an ordinary death heals on the next call. So a report inside the
|
|
1110
|
+
// window is dropped ENTIRELY — the count and the log line alike.
|
|
1111
|
+
//
|
|
1112
|
+
// That last part used to be split in two: the guard below, and a second dedupe that only
|
|
1113
|
+
// suppressed the LOG. The second one read `now - this.lastStartFailureAt` after the line
|
|
1114
|
+
// above had already stored `failureAt` into that same field, so its window was 0-1ms wide
|
|
1115
|
+
// and the comparison was unconditionally true — the log line was never written at all.
|
|
1116
|
+
// Nothing noticed, because this function exists to make a silent failure visible and its
|
|
1117
|
+
// only output was the thing being dropped: a child that exists and dies instantly (code=1,
|
|
1118
|
+
// empty stderr) left no trace anywhere.
|
|
1119
|
+
const failureAt = Date.now()
|
|
1120
|
+
if (this.lastStartFailureAt !== undefined && failureAt - this.lastStartFailureAt < START_FAILURE_DEDUPE_MS) return
|
|
1121
|
+
this.lastStartFailureAt = failureAt
|
|
1122
|
+
this.startFailures += 1
|
|
1123
|
+
const index = Math.min(this.startFailures, START_RETRY_SCHEDULE_MS.length) - 1
|
|
1124
|
+
const delayMs = START_RETRY_SCHEDULE_MS[index] ?? 0
|
|
1125
|
+
this.startRetryAt = delayMs > 0 ? failureAt + delayMs : undefined
|
|
1126
|
+
const line = `${hostStamp()} browser host start failed (attempt ${String(this.startFailures)}`
|
|
1127
|
+
+ `${this.startFailures >= START_FAILURES_MAX ? ', giving up on immediate retries' : ''}): ${String(error)}`
|
|
1128
|
+
+ `${delayMs > 0 ? ` — next attempt in ${formatDelay(delayMs)}` : ''}`
|
|
1129
|
+
process.stderr.write(`[dsh-browser host] ${line}\n`)
|
|
1130
|
+
appendHostLog(`${line}\n`)
|
|
1131
|
+
}
|
|
1132
|
+
|
|
1133
|
+
private async start(): Promise<void> {
|
|
1134
|
+
// Listen on an ephemeral loopback port; the child connects back. The
|
|
1135
|
+
// server accepts exactly one connection: the child's. Any further
|
|
1136
|
+
// connection (a local process probing the port) is destroyed at once.
|
|
1137
|
+
const server = createServer(socket => {
|
|
1138
|
+
if (this.client !== undefined && this.client.isAttached()) {
|
|
1139
|
+
// A live child connection already exists — reject the extra one.
|
|
1140
|
+
socket.destroy()
|
|
1141
|
+
return
|
|
1142
|
+
}
|
|
1143
|
+
if (this.client !== undefined) {
|
|
1144
|
+
// The child's first connection arrived after the client was created.
|
|
1145
|
+
this.client.attach(socket)
|
|
1146
|
+
return
|
|
1147
|
+
}
|
|
1148
|
+
if (this.pendingSocket !== undefined) {
|
|
1149
|
+
// Only one connection may wait for the client; drop the older one.
|
|
1150
|
+
this.pendingSocket.destroy()
|
|
1151
|
+
}
|
|
1152
|
+
this.pendingSocket = socket
|
|
1153
|
+
})
|
|
1154
|
+
await new Promise<void>((resolve, reject) => {
|
|
1155
|
+
server.once('error', reject)
|
|
1156
|
+
server.listen(0, LOOPBACK_IPV4, () => resolve())
|
|
1157
|
+
})
|
|
1158
|
+
// A later server error (rare on a loopback ephemeral port) must not crash
|
|
1159
|
+
// the process; the client's fail path handles the actual recovery.
|
|
1160
|
+
server.on('error', error => {
|
|
1161
|
+
process.stderr.write(`[dsh-browser host] rpc server error: ${String(error)}\n`)
|
|
1162
|
+
})
|
|
1163
|
+
const address = server.address()
|
|
1164
|
+
const port = typeof address === 'object' && address !== null ? address.port : 0
|
|
1165
|
+
this.server = server
|
|
1166
|
+
// Random per-spawn token: the child must prove knowledge of it (via
|
|
1167
|
+
// stdin hello) before any command is written to the socket.
|
|
1168
|
+
const token = randomBytes(24).toString('hex')
|
|
1169
|
+
this.client = new ElectronChildClient(
|
|
1170
|
+
this.hostMainPath,
|
|
1171
|
+
port,
|
|
1172
|
+
token,
|
|
1173
|
+
() => this.onChildExit(),
|
|
1174
|
+
action => this.userActionHandler?.(action),
|
|
1175
|
+
windowId => this.viewClosedHandler?.(windowId),
|
|
1176
|
+
this.spawnExecutable,
|
|
1177
|
+
this.ephemeralUserDataDir,
|
|
1178
|
+
)
|
|
1179
|
+
if (this.pendingSocket !== undefined) {
|
|
1180
|
+
this.client.attach(this.pendingSocket)
|
|
1181
|
+
this.pendingSocket = undefined
|
|
1182
|
+
}
|
|
1183
|
+
// dispose() can race this spawn (it may run while start() is suspended
|
|
1184
|
+
// between the listen and the client creation): re-check here so a host
|
|
1185
|
+
// that was torn down mid-start does not leak a child nobody will kill.
|
|
1186
|
+
if (this.disposed) {
|
|
1187
|
+
this.client.kill()
|
|
1188
|
+
this.client = undefined
|
|
1189
|
+
try { server.close() } catch { /* already closed */ }
|
|
1190
|
+
if (this.server === server) this.server = undefined
|
|
1191
|
+
throw new HostGoneError('browser host disposed')
|
|
1192
|
+
}
|
|
1193
|
+
// Wait for the child's connection + authentication + readiness ping. The
|
|
1194
|
+
// ping is queued until the hello authenticates, so a spoofed socket
|
|
1195
|
+
// never observes it.
|
|
1196
|
+
await withTimeout(this.client.call('ping'), READY_TIMEOUT_MS, 'browser host did not become ready')
|
|
1197
|
+
}
|
|
1198
|
+
|
|
1199
|
+
/** The child died: tear down so the next use starts a fresh child. */
|
|
1200
|
+
private onChildExit(): void {
|
|
1201
|
+
// A disposed host still has to drop these: returning here left a child that had
|
|
1202
|
+
// already been replaced during a dispose race in no map at all, so nothing would
|
|
1203
|
+
// ever kill it. Only the restart is suppressed, not the cleanup.
|
|
1204
|
+
const wasDisposed = this.disposed
|
|
1205
|
+
if (!wasDisposed) process.stderr.write('[dsh-browser host] browser host gone; will restart on next use\n')
|
|
1206
|
+
// A child that started and then died is also a failed start, and it is the shape a crash
|
|
1207
|
+
// loop takes (the child comes up far enough to be pending on `ping`, then exits): count
|
|
1208
|
+
// it so the restart is spaced instead of attempted on every single tool call.
|
|
1209
|
+
if (!wasDisposed) this.noteStartFailure('the browser host process exited')
|
|
1210
|
+
// The cached `available()` answer came from the FILESYSTEM, so only a real attempt can
|
|
1211
|
+
// contradict it. A binary that stops being usable after the probe said yes — an
|
|
1212
|
+
// interrupted reinstall, a removed mount, a wiped cache — kept the provider advertised
|
|
1213
|
+
// as available for the rest of the process's life, because provider selection reads
|
|
1214
|
+
// that same cached yes; every later call then paid a doomed spawn. Both failure routes
|
|
1215
|
+
// (a spawn error, and a child that exits) arrive here, so this is the one place that
|
|
1216
|
+
// observes the loss, and it costs two stats on a path that is already failing.
|
|
1217
|
+
if (this.binaryIsGone()) this.forgetBinary()
|
|
1218
|
+
this.client = undefined
|
|
1219
|
+
this.server?.close()
|
|
1220
|
+
this.server = undefined
|
|
1221
|
+
this.pendingSocket?.destroy()
|
|
1222
|
+
this.pendingSocket = undefined
|
|
1223
|
+
this.readyPromise = undefined
|
|
1224
|
+
// Keep the views map: handles still resolve to ids, and
|
|
1225
|
+
// DeferredRemoteView re-materializes them against the fresh child on
|
|
1226
|
+
// their next use — sessions opened before the crash stay usable instead
|
|
1227
|
+
// of going stale (only the page state is lost).
|
|
1228
|
+
}
|
|
1229
|
+
|
|
1230
|
+
createView(identity?: BrowserTabWireId): ElectronViewHandle {
|
|
1231
|
+
// The seam is synchronous; the provider uses the handle immediately, so
|
|
1232
|
+
// commands are deferred until the child is up and the view materialized.
|
|
1233
|
+
const id = identity ?? tabWireId({ owner: 'standalone', session: randomUUID(), tab: randomUUID() })
|
|
1234
|
+
readTabHandle(id)
|
|
1235
|
+
const view = new DeferredRemoteView(id, () => this.ensureView(id))
|
|
1236
|
+
this.views.set(id, view)
|
|
1237
|
+
return view
|
|
1238
|
+
}
|
|
1239
|
+
|
|
1240
|
+
private async ensureView(id: string): Promise<RemoteView> {
|
|
1241
|
+
// A rebuild in flight during dispose() must not spawn a fresh child that
|
|
1242
|
+
// would then outlive the host (a zombie window nobody disposes).
|
|
1243
|
+
if (this.disposed) throw new HostGoneError('browser host disposed')
|
|
1244
|
+
await this.ready()
|
|
1245
|
+
// dispose() may have landed while the host was starting (ready() resolved
|
|
1246
|
+
// after dispose cleared its state): never materialize into a dead host.
|
|
1247
|
+
if (this.disposed) throw new HostGoneError('browser host disposed')
|
|
1248
|
+
const client = this.client
|
|
1249
|
+
if (client === undefined) throw new HostGoneError('browser host unavailable')
|
|
1250
|
+
// Re-send the window group before creating the view: the child routes the
|
|
1251
|
+
// view into its session's own window. Re-sending every materialization
|
|
1252
|
+
// also covers a child restart (the new child has no assignments yet).
|
|
1253
|
+
const group = this.groups.get(id)
|
|
1254
|
+
if (group !== undefined) {
|
|
1255
|
+
await client.call('groupView', { viewId: id, windowId: group.windowId, ...group.label !== undefined ? { label: group.label } : {} })
|
|
1256
|
+
}
|
|
1257
|
+
await client.call('createView', { viewId: id })
|
|
1258
|
+
// If the view was destroyed while the createView RPC was in flight, do
|
|
1259
|
+
// not re-insert a stale entry that would resurrect a dead child view.
|
|
1260
|
+
if (this.views.get(id) === undefined) {
|
|
1261
|
+
throw new Error('browser: view destroyed while starting')
|
|
1262
|
+
}
|
|
1263
|
+
const view = new RemoteView(id, client)
|
|
1264
|
+
this.views.set(id, view)
|
|
1265
|
+
return view
|
|
1266
|
+
}
|
|
1267
|
+
|
|
1268
|
+
showView(handle: ElectronViewHandle, label?: string, options?: PresentOptions): void {
|
|
1269
|
+
// Fire-and-forget by design (visibility is best-effort), but a rejected
|
|
1270
|
+
// promise must not become an unhandled rejection (crash on Node >= 15).
|
|
1271
|
+
// The label (session/task id) rides along so the child can show it in the
|
|
1272
|
+
// window title — a human can then tell which task's page is visible.
|
|
1273
|
+
// `quiet` is only sent when it is on: the child's default is the documented
|
|
1274
|
+
// "present and raise" behaviour, so an old child keeps working either way.
|
|
1275
|
+
void this.ready()
|
|
1276
|
+
.then(() => this.client?.call('showView', {
|
|
1277
|
+
viewId: handle.id,
|
|
1278
|
+
...label !== undefined ? { label } : {},
|
|
1279
|
+
...options?.quiet === true ? { quiet: true } : {},
|
|
1280
|
+
}))
|
|
1281
|
+
.catch(() => { /* host unavailable */ })
|
|
1282
|
+
}
|
|
1283
|
+
|
|
1284
|
+
/**
|
|
1285
|
+
* (Re)present a view and WAIT for the child to confirm it, so the provider
|
|
1286
|
+
* can dispatch CDP `Input.*` knowing the view has a display surface.
|
|
1287
|
+
*
|
|
1288
|
+
* Two things this fixes, both silent before:
|
|
1289
|
+
* - showing a view that does not exist yet is a no-op in the child, so the
|
|
1290
|
+
* view must be materialized first (a fresh tab's createView races the
|
|
1291
|
+
* provider's showActive);
|
|
1292
|
+
* - a view whose renderer was replaced by a navigation is "already
|
|
1293
|
+
* visible" and therefore skipped by the child's flicker-avoidance fast
|
|
1294
|
+
* path, leaving the new renderer without a surface.
|
|
1295
|
+
*
|
|
1296
|
+
* The barrier ping is meaningful because the child handles messages strictly
|
|
1297
|
+
* in order: its reply is queued behind the showView and so only arrives once
|
|
1298
|
+
* the visibility change has been applied.
|
|
1299
|
+
*/
|
|
1300
|
+
async presentView(handle: ElectronViewHandle, label?: string, options?: PresentOptions): Promise<void> {
|
|
1301
|
+
await this.ready()
|
|
1302
|
+
const client = this.client
|
|
1303
|
+
if (client === undefined) throw new HostGoneError('browser host unavailable')
|
|
1304
|
+
// A view created after the last createView does not exist in the child yet.
|
|
1305
|
+
// ensureMaterialized also rebuilds it against a fresh child after a host
|
|
1306
|
+
// death, which is the path that used to leave sessions timing out forever.
|
|
1307
|
+
if (handle instanceof DeferredRemoteView) {
|
|
1308
|
+
await withTimeout(handle.ensureMaterialized(), PRESENT_TIMEOUT_MS, 'browser host did not materialize the view')
|
|
1309
|
+
}
|
|
1310
|
+
await withTimeout(
|
|
1311
|
+
client.call('showView', {
|
|
1312
|
+
viewId: handle.id,
|
|
1313
|
+
...label !== undefined ? { label } : {},
|
|
1314
|
+
// `needSurface` tells the child this is the pre-input barrier: under quiet mode this
|
|
1315
|
+
// is the only presentation allowed to un-minimize a window, because Chromium drops
|
|
1316
|
+
// `Input.*` without a display surface. One line below in the child, and only read
|
|
1317
|
+
// there when `quiet` is set.
|
|
1318
|
+
...options?.quiet === true ? { quiet: true, needSurface: true } : {},
|
|
1319
|
+
}),
|
|
1320
|
+
PRESENT_TIMEOUT_MS,
|
|
1321
|
+
'browser host did not confirm the view presentation',
|
|
1322
|
+
)
|
|
1323
|
+
await withTimeout(client.call('ping'), PRESENT_TIMEOUT_MS, 'browser host stopped answering')
|
|
1324
|
+
}
|
|
1325
|
+
|
|
1326
|
+
/** Route a view into its session's own window (one window per session). */
|
|
1327
|
+
groupView(handle: ElectronViewHandle, windowId: string, label?: string): void {
|
|
1328
|
+
this.groups.set(handle.id, { windowId, ...label !== undefined ? { label } : {} })
|
|
1329
|
+
// Fire-and-forget: the child may not exist yet; ensureView re-sends the
|
|
1330
|
+
// group before every createView anyway.
|
|
1331
|
+
void this.ready()
|
|
1332
|
+
.then(() => this.client?.call('groupView', { viewId: handle.id, windowId, ...label !== undefined ? { label } : {} }))
|
|
1333
|
+
.catch(() => { /* host unavailable */ })
|
|
1334
|
+
}
|
|
1335
|
+
|
|
1336
|
+
/** Register the provider's handler for user-initiated toolbar actions. */
|
|
1337
|
+
onUserAction(handler: (action: BrowserUserAction) => void): void {
|
|
1338
|
+
this.userActionHandler = handler
|
|
1339
|
+
}
|
|
1340
|
+
|
|
1341
|
+
/** Register the provider's handler for windows the human closed. */
|
|
1342
|
+
onViewClosed(handler: (windowId: string) => void): void {
|
|
1343
|
+
this.viewClosedHandler = handler
|
|
1344
|
+
}
|
|
1345
|
+
|
|
1346
|
+
/** Surface a failed user action to the child's toolbar (address bar etc.). */
|
|
1347
|
+
notifyUserActionError(windowId: string, message: string): void {
|
|
1348
|
+
void this.ready()
|
|
1349
|
+
.then(() => this.client?.call('userActionError', { windowId, message }))
|
|
1350
|
+
.catch(() => { /* host unavailable */ })
|
|
1351
|
+
}
|
|
1352
|
+
|
|
1353
|
+
destroyView(handle: ElectronViewHandle): void {
|
|
1354
|
+
const view = this.views.get(handle.id)
|
|
1355
|
+
if (view === undefined) return
|
|
1356
|
+
this.views.delete(handle.id)
|
|
1357
|
+
void this.ready()
|
|
1358
|
+
.then(() => this.client?.call('destroyView', { viewId: handle.id }))
|
|
1359
|
+
.catch(() => { /* child already gone */ })
|
|
1360
|
+
}
|
|
1361
|
+
|
|
1362
|
+
/** Shut the child and the RPC server down. */
|
|
1363
|
+
dispose(): void {
|
|
1364
|
+
this.disposed = true
|
|
1365
|
+
this.client?.kill()
|
|
1366
|
+
this.client = undefined
|
|
1367
|
+
this.server?.close()
|
|
1368
|
+
this.server = undefined
|
|
1369
|
+
this.pendingSocket?.destroy()
|
|
1370
|
+
this.pendingSocket = undefined
|
|
1371
|
+
this.readyPromise = undefined
|
|
1372
|
+
this.views.clear()
|
|
1373
|
+
if (this.ephemeralUserDataDir !== undefined) {
|
|
1374
|
+
const dir = this.ephemeralUserDataDir
|
|
1375
|
+
setTimeout(() => {
|
|
1376
|
+
try { rmSync(dir, { recursive: true, force: true }) } catch { /* best-effort cleanup */ }
|
|
1377
|
+
}, 600).unref?.()
|
|
1378
|
+
}
|
|
1379
|
+
}
|
|
1380
|
+
}
|
|
1381
|
+
|
|
1382
|
+
/** A view handle that waits for child readiness before issuing commands. */
|
|
1383
|
+
class DeferredRemoteView implements ElectronViewHandle {
|
|
1384
|
+
private materialized: Promise<RemoteView> | undefined
|
|
1385
|
+
readonly id: string
|
|
1386
|
+
private readonly materialize: () => Promise<RemoteView>
|
|
1387
|
+
constructor(
|
|
1388
|
+
id: string,
|
|
1389
|
+
materialize: () => Promise<RemoteView>,
|
|
1390
|
+
) {
|
|
1391
|
+
this.id = id
|
|
1392
|
+
this.materialize = materialize
|
|
1393
|
+
}
|
|
1394
|
+
|
|
1395
|
+
/**
|
|
1396
|
+
* Materialize once and cache: every operation on the same handle must
|
|
1397
|
+
* target the SAME child view (re-materializing would re-run createView and
|
|
1398
|
+
* duplicate the window). A FAILED materialization is reset so a later call
|
|
1399
|
+
* (e.g. after the host restarted) can retry instead of being poisoned.
|
|
1400
|
+
*/
|
|
1401
|
+
private materializeOnce(): Promise<RemoteView> {
|
|
1402
|
+
if (this.materialized === undefined) {
|
|
1403
|
+
const pending = this.materialize()
|
|
1404
|
+
// Compare against the promise actually stored — the derived one — not against `pending`.
|
|
1405
|
+
// Storing `pending.catch(...)` and comparing `this.materialized === pending` compared two
|
|
1406
|
+
// different objects, so the test was never true and the reset never ran: a materialization
|
|
1407
|
+
// that failed with anything other than a HostGoneError (the child alive but not answering
|
|
1408
|
+
// a ping, say) poisoned the handle for good, and the retry the comment below promises was
|
|
1409
|
+
// unreachable.
|
|
1410
|
+
const guarded = pending.catch(error => {
|
|
1411
|
+
if (this.materialized === guarded) this.materialized = undefined
|
|
1412
|
+
throw error
|
|
1413
|
+
})
|
|
1414
|
+
this.materialized = guarded
|
|
1415
|
+
}
|
|
1416
|
+
return this.materialized
|
|
1417
|
+
}
|
|
1418
|
+
|
|
1419
|
+
/**
|
|
1420
|
+
* Run one operation against this view's backing child, automatically
|
|
1421
|
+
* recovering from a dead host. The cached materialization is bound to the
|
|
1422
|
+
* child it was created on; once that child is gone (exited, crashed, or its
|
|
1423
|
+
* connection dropped — e.g. the DSH process that spawned it was restarted),
|
|
1424
|
+
* any further operation on the same handle would otherwise fail forever
|
|
1425
|
+
* with "browser host is not running". Instead: drop the cache, rebuild the
|
|
1426
|
+
* view against a freshly spawned child, and retry the operation exactly
|
|
1427
|
+
* once — so sessions that survive a host death self-heal on their FIRST
|
|
1428
|
+
* call after it, without a manual dsh_browser_reset_session. Page-level errors
|
|
1429
|
+
* are never retried (the view itself is fine).
|
|
1430
|
+
*/
|
|
1431
|
+
private async withRecovery<T>(op: (view: RemoteView) => Promise<T>): Promise<T> {
|
|
1432
|
+
try {
|
|
1433
|
+
const view = await this.materializeOnce()
|
|
1434
|
+
return await op(view)
|
|
1435
|
+
} catch (error) {
|
|
1436
|
+
if (!(error instanceof HostGoneError)) throw error
|
|
1437
|
+
// The backing child is gone: a retry on the same materialization can
|
|
1438
|
+
// never succeed. Rebuild against a fresh child and retry once; a second
|
|
1439
|
+
// failure (fresh host also failing to start) surfaces to the caller.
|
|
1440
|
+
this.materialized = undefined
|
|
1441
|
+
const fresh = await this.materializeOnce()
|
|
1442
|
+
return op(fresh)
|
|
1443
|
+
}
|
|
1444
|
+
}
|
|
1445
|
+
|
|
1446
|
+
async sendCommand(method: string, params?: Record<string, unknown>): Promise<Record<string, unknown>> {
|
|
1447
|
+
return this.withRecovery(view => view.sendCommand(method, params))
|
|
1448
|
+
}
|
|
1449
|
+
|
|
1450
|
+
async download(url: string, savePath: string): Promise<void> {
|
|
1451
|
+
return this.withRecovery(view => view.download(url, savePath))
|
|
1452
|
+
}
|
|
1453
|
+
|
|
1454
|
+
async capture(opts?: ScreenshotOptions): Promise<{ base64: string; mime: string }> {
|
|
1455
|
+
return this.withRecovery(view => view.capture(opts))
|
|
1456
|
+
}
|
|
1457
|
+
|
|
1458
|
+
async focus(options?: PresentOptions): Promise<void> {
|
|
1459
|
+
return this.withRecovery(view => view.focus(options))
|
|
1460
|
+
}
|
|
1461
|
+
|
|
1462
|
+
async flushAuth(): Promise<ExportedCookie[]> {
|
|
1463
|
+
return this.withRecovery(view => view.flushAuth())
|
|
1464
|
+
}
|
|
1465
|
+
|
|
1466
|
+
async restoreAuth(cookies: ExportedCookie[]): Promise<number> {
|
|
1467
|
+
return this.withRecovery(view => view.restoreAuth(cookies))
|
|
1468
|
+
}
|
|
1469
|
+
|
|
1470
|
+
/** Materialize this view in the child (no-op when already there). */
|
|
1471
|
+
async ensureMaterialized(): Promise<void> {
|
|
1472
|
+
await this.withRecovery(async () => undefined)
|
|
1473
|
+
}
|
|
1474
|
+
}
|
|
1475
|
+
|
|
1476
|
+
/**
|
|
1477
|
+
* Append one host-diagnostics chunk to `$DSH_HOME/logs/dsh-builtin-browser-host.log`.
|
|
1478
|
+
* Best-effort and self-limiting: diagnostics must never break the host or grow
|
|
1479
|
+
* without bound, so failures are swallowed and the file is truncated when it
|
|
1480
|
+
* gets large (a crash loop writes quickly).
|
|
1481
|
+
*/
|
|
1482
|
+
const HOST_LOG_MAX_BYTES = 2 * 1024 * 1024
|
|
1483
|
+
|
|
1484
|
+
/**
|
|
1485
|
+
* ISO timestamp prefix for host-log lines. This log is the only place a spawn
|
|
1486
|
+
* failure is recorded, and an undated line cannot be lined up with anything else
|
|
1487
|
+
* that happened on the machine — a plugin update replacing the entry script, for
|
|
1488
|
+
* instance — which is precisely the question this log gets asked.
|
|
1489
|
+
*/
|
|
1490
|
+
function hostStamp(): string {
|
|
1491
|
+
return new Date().toISOString()
|
|
1492
|
+
}
|
|
1493
|
+
|
|
1494
|
+
function appendHostLog(text: string): void {
|
|
1495
|
+
try {
|
|
1496
|
+
const file = browserHostLogPath()
|
|
1497
|
+
const dir = dirname(file)
|
|
1498
|
+
try {
|
|
1499
|
+
if (statSync(file).size > HOST_LOG_MAX_BYTES) {
|
|
1500
|
+
// Discard the old bytes but leave a dated marker: truncating to empty
|
|
1501
|
+
// makes a rotation look like "nothing ever happened", which is how the
|
|
1502
|
+
// history of a crash loop gets silently swallowed.
|
|
1503
|
+
writeFileSync(file, `${hostStamp()} log rotated: previous content exceeded ${String(HOST_LOG_MAX_BYTES)} bytes and was discarded\n`)
|
|
1504
|
+
}
|
|
1505
|
+
} catch {
|
|
1506
|
+
// No readable file yet: the log directory may not exist. When statSync
|
|
1507
|
+
// succeeded the file exists, so its directory does too and creating it
|
|
1508
|
+
// again was a redundant syscall on every child stdout/stderr line.
|
|
1509
|
+
mkdirSync(dir, { recursive: true })
|
|
1510
|
+
}
|
|
1511
|
+
appendFileSync(file, text)
|
|
1512
|
+
} catch { /* diagnostics are best-effort only */ }
|
|
1513
|
+
}
|
|
1514
|
+
|
|
1515
|
+
/** Reject a promise if it does not settle within the budget. */
|
|
1516
|
+
function withTimeout<T>(promise: Promise<T>, ms: number, message: string): Promise<T> {
|
|
1517
|
+
return withTimeoutShared(promise, ms, () => new Error(`${message} (${ms}ms)`))
|
|
1518
|
+
}
|
|
1519
|
+
|
|
1520
|
+
/** Default host-main path relative to this module's build output. */
|
|
1521
|
+
export function defaultHostMainPath(): string {
|
|
1522
|
+
return fileURLToPath(new URL('./host-main.js', import.meta.url))
|
|
1523
|
+
}
|
|
1524
|
+
|
|
1525
|
+
/**
|
|
1526
|
+
* Test/diagnostic hooks (mirrors tool-browser's `internals` convention).
|
|
1527
|
+
* `isBareElectron` is the packaged-app discriminator behind the host-reuse
|
|
1528
|
+
* steps; `resolveElectronPath` is the full resolution order.
|
|
1529
|
+
*/
|
|
1530
|
+
export const internals = {
|
|
1531
|
+
electronDistCandidates,
|
|
1532
|
+
electronDistExe,
|
|
1533
|
+
electronExeBeside,
|
|
1534
|
+
isBareElectron,
|
|
1535
|
+
managedElectronBinary,
|
|
1536
|
+
resolveElectronPath,
|
|
1537
|
+
resolveElectronPathImpl,
|
|
1538
|
+
}
|