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,189 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The ephemeral browser profile: a throwaway directory under the DSH home, used when the
|
|
3
|
+
* user has turned profile persistence off, and deleted when the browser is released.
|
|
4
|
+
*
|
|
5
|
+
* Deleting on release is not enough by itself. A process killed outright — a DSH restart
|
|
6
|
+
* that ends in SIGKILL, "End task" in a task manager, a crashed host — never runs its
|
|
7
|
+
* cleanup, so the profile it was using survives on disk: the user asked for no profile to
|
|
8
|
+
* be kept and the machine keeps one anyway, holding cookies and history. Nothing can run
|
|
9
|
+
* at SIGKILL time, so the cleanup has to happen on the NEXT run instead, which is what
|
|
10
|
+
* this module provides.
|
|
11
|
+
*
|
|
12
|
+
* Ownership is a marker file inside the directory naming the process that claimed it. A
|
|
13
|
+
* directory whose owner is gone AND whose whole tree has not been written to for a while is
|
|
14
|
+
* abandoned. The age check is what keeps the sweep away from a profile an orphaned browser
|
|
15
|
+
* (a child that outlived the parent which was killed) may still be using: a live Chromium
|
|
16
|
+
* writes nested files continuously, so a tree with a recent write is not abandoned — even
|
|
17
|
+
* when the root directory's own timestamp is old, because writing a file does not update it.
|
|
18
|
+
*/
|
|
19
|
+
import { lstatSync, mkdirSync, readFileSync, readdirSync, rmSync, statSync, writeFileSync } from 'node:fs'
|
|
20
|
+
import { join } from 'node:path'
|
|
21
|
+
import { pidAlive } from './process.ts'
|
|
22
|
+
|
|
23
|
+
/** The marker file, named once because both the claim and the sweep read it. */
|
|
24
|
+
const OWNER_FILE = '.dsh-ephemeral-owner'
|
|
25
|
+
|
|
26
|
+
/**
|
|
27
|
+
* How long a profile is left alone regardless of ownership. An orphaned browser keeps
|
|
28
|
+
* writing to its profile, so this is what distinguishes "abandoned" from "in use by a
|
|
29
|
+
* process this one did not start".
|
|
30
|
+
*/
|
|
31
|
+
const ABANDONED_AFTER_MS = 60 * 60 * 1000
|
|
32
|
+
|
|
33
|
+
/**
|
|
34
|
+
* Ceiling on how much of a profile tree one sweep inspects. A tree we cannot fully inspect is
|
|
35
|
+
* not proven abandoned, so it is kept; this only bounds the cost of saying so.
|
|
36
|
+
*/
|
|
37
|
+
const MAX_SWEEP_ENTRIES = 20_000
|
|
38
|
+
|
|
39
|
+
/** Test seams; production passes neither. */
|
|
40
|
+
export interface SweepOptions {
|
|
41
|
+
/** The clock, for the age check. */
|
|
42
|
+
readonly now?: number
|
|
43
|
+
/** Liveness test for an owner pid. */
|
|
44
|
+
readonly alive?: (pid: number) => boolean
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/**
|
|
48
|
+
* The directory name an ephemeral profile for `kind` gets, before it is claimed.
|
|
49
|
+
*
|
|
50
|
+
* The sweep matches on the same shape, so the two must agree: a name built anywhere else
|
|
51
|
+
* is a directory the sweep will never find.
|
|
52
|
+
* @param kind - the detected browser product (`chrome`, `edge`, ...).
|
|
53
|
+
* @param id - a per-run unique suffix.
|
|
54
|
+
* @returns the directory NAME, not a path.
|
|
55
|
+
*/
|
|
56
|
+
export function ephemeralProfileName(kind: string, id: string): string {
|
|
57
|
+
return `${kind}-profile-ephemeral-${id}`
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/**
|
|
61
|
+
* Mark an ephemeral profile directory as this process's, so a later run can tell whether
|
|
62
|
+
* the process that created it is still there.
|
|
63
|
+
* @param dir - the profile directory (created if it does not exist yet).
|
|
64
|
+
* @param pid - the claiming process, defaulting to this one.
|
|
65
|
+
* @param now - the claim time, defaulting to the current clock.
|
|
66
|
+
* @returns true when the marker was written.
|
|
67
|
+
*/
|
|
68
|
+
export function claimEphemeralProfile(dir: string, pid: number = process.pid, now: number = Date.now()): boolean {
|
|
69
|
+
try {
|
|
70
|
+
mkdirSync(dir, { recursive: true })
|
|
71
|
+
writeFileSync(join(dir, OWNER_FILE), JSON.stringify({ pid, at: now }))
|
|
72
|
+
return true
|
|
73
|
+
} catch {
|
|
74
|
+
// The browser creates the directory itself when this fails, and cleanup is best
|
|
75
|
+
// effort throughout: a marker that could not be written must not stop the launch.
|
|
76
|
+
return false
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/**
|
|
81
|
+
* The claimed owner of an ephemeral profile, when it has one.
|
|
82
|
+
* @param dir - the profile directory.
|
|
83
|
+
* @returns the owner pid, or undefined when there is no readable marker.
|
|
84
|
+
*/
|
|
85
|
+
function readOwner(dir: string): number | undefined {
|
|
86
|
+
try {
|
|
87
|
+
const parsed = JSON.parse(readFileSync(join(dir, OWNER_FILE), 'utf8')) as { pid?: unknown }
|
|
88
|
+
return typeof parsed.pid === 'number' ? parsed.pid : undefined
|
|
89
|
+
} catch {
|
|
90
|
+
// No marker: a run from before this existed, or one killed before it wrote one. The
|
|
91
|
+
// age check has already applied, and a directory with no claimant that old is
|
|
92
|
+
// abandoned by any reading.
|
|
93
|
+
return undefined
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
/**
|
|
98
|
+
* The most recent write anywhere in a profile tree.
|
|
99
|
+
*
|
|
100
|
+
* A Chromium process writes nested files (`Default/Network/Cookies`, `Default/History`, ...).
|
|
101
|
+
* Writing a file does NOT refresh the mtime of the parent directory, so a quiet ROOT timestamp
|
|
102
|
+
* cannot prove the browser has exited — exactly the case where a killed DSH leaves a live child
|
|
103
|
+
* behind. Inspect the tree instead of just its root.
|
|
104
|
+
*
|
|
105
|
+
* Anything that cannot be inspected is reported as "written now", so the caller keeps the
|
|
106
|
+
* directory. When the evidence is incomplete, leaving a profile behind is the only safe outcome.
|
|
107
|
+
* Symbolic links are never followed, and an entry budget bounds the work.
|
|
108
|
+
* @param dir - the profile directory.
|
|
109
|
+
* @param now - the clock value used as the conservative "active" answer.
|
|
110
|
+
* @returns the newest mtime in the tree, or `-Infinity` when the tree holds nothing but our marker.
|
|
111
|
+
*/
|
|
112
|
+
function latestWriteMs(dir: string, now: number): number {
|
|
113
|
+
let latest = Number.NEGATIVE_INFINITY
|
|
114
|
+
let budget = MAX_SWEEP_ENTRIES
|
|
115
|
+
const pending = [dir]
|
|
116
|
+
while (pending.length > 0) {
|
|
117
|
+
const current = pending.pop() as string
|
|
118
|
+
let entries
|
|
119
|
+
try {
|
|
120
|
+
entries = readdirSync(current, { withFileTypes: true })
|
|
121
|
+
} catch {
|
|
122
|
+
return now
|
|
123
|
+
}
|
|
124
|
+
for (const entry of entries) {
|
|
125
|
+
if (budget-- <= 0) return now
|
|
126
|
+
// Our owner marker is written once at claim time; it is not browser activity.
|
|
127
|
+
if (current === dir && entry.name === OWNER_FILE) continue
|
|
128
|
+
const path = join(current, entry.name)
|
|
129
|
+
let stat
|
|
130
|
+
try {
|
|
131
|
+
stat = lstatSync(path)
|
|
132
|
+
} catch {
|
|
133
|
+
return now
|
|
134
|
+
}
|
|
135
|
+
if (stat.mtimeMs > latest) latest = stat.mtimeMs
|
|
136
|
+
if (stat.isDirectory() && !stat.isSymbolicLink()) pending.push(path)
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
return latest
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
/**
|
|
143
|
+
* Delete the ephemeral profiles under `root` that belong to processes which are gone.
|
|
144
|
+
*
|
|
145
|
+
* Called before a new one is claimed, because that is the only moment that can still act
|
|
146
|
+
* on a profile whose owner was killed: nothing runs when the signal lands.
|
|
147
|
+
* @param root - the plugin's profile root (`<DSH_HOME>/dsh-builtin-browser-host`).
|
|
148
|
+
* @param kind - the browser product, which selects the directory-name prefix.
|
|
149
|
+
* @param options - test seams for the clock and the liveness test.
|
|
150
|
+
* @returns the names of the directories that were removed.
|
|
151
|
+
*/
|
|
152
|
+
export function sweepAbandonedEphemeralProfiles(root: string, kind: string, options: SweepOptions = {}): string[] {
|
|
153
|
+
const now = options.now ?? Date.now()
|
|
154
|
+
const alive = options.alive ?? pidAlive
|
|
155
|
+
const prefix = `${kind}-profile-ephemeral-`
|
|
156
|
+
const removed: string[] = []
|
|
157
|
+
let names: string[]
|
|
158
|
+
try {
|
|
159
|
+
names = readdirSync(root)
|
|
160
|
+
} catch {
|
|
161
|
+
// No profile root yet: nothing has ever been written here, so nothing to sweep.
|
|
162
|
+
return removed
|
|
163
|
+
}
|
|
164
|
+
for (const name of names) {
|
|
165
|
+
if (!name.startsWith(prefix)) continue
|
|
166
|
+
const dir = join(root, name)
|
|
167
|
+
let rootMtime: number
|
|
168
|
+
try {
|
|
169
|
+
rootMtime = statSync(dir).mtimeMs
|
|
170
|
+
} catch {
|
|
171
|
+
continue
|
|
172
|
+
}
|
|
173
|
+
// Recent writes ANYWHERE in the tree mean a browser is still working in there. A killed DSH
|
|
174
|
+
// can leave its Chromium child running, and a child writing Default/Network/Cookies does not
|
|
175
|
+
// refresh the root directory's mtime. Judging the root alone deleted live profiles.
|
|
176
|
+
const ageMs = now - Math.max(rootMtime, latestWriteMs(dir, now))
|
|
177
|
+
if (ageMs < ABANDONED_AFTER_MS) continue
|
|
178
|
+
const owner = readOwner(dir)
|
|
179
|
+
if (owner !== undefined && alive(owner)) continue
|
|
180
|
+
try {
|
|
181
|
+
rmSync(dir, { recursive: true, force: true })
|
|
182
|
+
removed.push(name)
|
|
183
|
+
} catch {
|
|
184
|
+
// In use, or not ours to remove. Leaving it is the safe outcome and the next run
|
|
185
|
+
// tries again — the alternative is deleting a profile out from under a live browser.
|
|
186
|
+
}
|
|
187
|
+
}
|
|
188
|
+
return removed
|
|
189
|
+
}
|
|
@@ -0,0 +1,230 @@
|
|
|
1
|
+
import { extensionPageUrl, BROWSER_PROFILE_DIR } from '../../assets/browser-policy.mjs'
|
|
2
|
+
import { join } from 'node:path'
|
|
3
|
+
import { fileURLToPath } from 'node:url'
|
|
4
|
+
import { access } from 'node:fs/promises'
|
|
5
|
+
import type { NativeBrowserClient, ExtensionConnectionStatus } from '../../native-host/client.mjs'
|
|
6
|
+
import { readTabHandle, resolveSessionHandle, resolveTabHandle, sessionWireId, tabWireId, type BrowserTabWireId } from '../browser/handles.ts'
|
|
7
|
+
import type { BrowserSessionId, CarrierPage } from '../browser/types.ts'
|
|
8
|
+
import type { ElectronBrowserViewHost, ElectronViewHandle } from './provider.ts'
|
|
9
|
+
import { dshHome } from './paths.ts'
|
|
10
|
+
|
|
11
|
+
interface Lease { lease: string; tabId: number }
|
|
12
|
+
interface View {
|
|
13
|
+
readonly handle: ElectronViewHandle
|
|
14
|
+
readonly scope: BrowserSessionId
|
|
15
|
+
lease?: Lease
|
|
16
|
+
pending?: Promise<Lease>
|
|
17
|
+
invalid: boolean
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
class LazyNativeBrowserClient implements NativeBrowserClient {
|
|
21
|
+
private client?: NativeBrowserClient
|
|
22
|
+
private loading?: Promise<void>
|
|
23
|
+
private disposed = false
|
|
24
|
+
private detail = 'Optional browser extension is not connected; managed CDP fallback is available.'
|
|
25
|
+
private readonly listeners = new Set<Parameters<NativeBrowserClient['onEvent']>[0]>()
|
|
26
|
+
private readonly directory: string
|
|
27
|
+
private readonly browser: 'edge' | 'chrome'
|
|
28
|
+
constructor(directory: string, browser: 'edge' | 'chrome') {
|
|
29
|
+
this.directory = directory
|
|
30
|
+
this.browser = browser
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
status(): ExtensionConnectionStatus {
|
|
34
|
+
return this.client?.status() ?? { state: 'extension-missing', connected: false, browser: this.browser, detail: this.detail }
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
private async load(): Promise<void> {
|
|
38
|
+
try {
|
|
39
|
+
await access(new URL('../../browser-extension/manifest.json', import.meta.url))
|
|
40
|
+
const { NativeBrowserClient } = await import('../../native-host/client.mjs')
|
|
41
|
+
if (this.disposed) throw new Error('extension carrier was released')
|
|
42
|
+
this.client = new NativeBrowserClient(this.directory, this.browser)
|
|
43
|
+
this.client.onEvent(event => { for (const listener of this.listeners) listener(event) })
|
|
44
|
+
} catch (error) {
|
|
45
|
+
this.detail = `Extension carrier unavailable: ${String(error)}. Managed CDP fallback is available.`
|
|
46
|
+
throw new Error(this.detail, { cause: error })
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
async connect(): Promise<void> {
|
|
51
|
+
if (this.disposed) throw new Error('extension carrier was released')
|
|
52
|
+
await (this.loading ??= this.load())
|
|
53
|
+
await this.client!.connect()
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
async request(operation: Record<string, unknown>): Promise<unknown> {
|
|
57
|
+
await this.connect()
|
|
58
|
+
return this.client!.request(operation)
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
onEvent(listener: Parameters<NativeBrowserClient['onEvent']>[0]): () => void {
|
|
62
|
+
this.listeners.add(listener)
|
|
63
|
+
return () => { this.listeners.delete(listener) }
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
dispose(): void {
|
|
67
|
+
this.disposed = true
|
|
68
|
+
this.listeners.clear()
|
|
69
|
+
this.client?.dispose()
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
export function extensionDirectory(browser: 'edge' | 'chrome'): string {
|
|
74
|
+
return join(dshHome(), BROWSER_PROFILE_DIR, 'extension', browser)
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
export function extensionInstallHelp(browser: 'edge' | 'chrome') {
|
|
78
|
+
return {
|
|
79
|
+
platform: process.platform,
|
|
80
|
+
extensionDirectory: fileURLToPath(new URL('../../browser-extension/', import.meta.url)),
|
|
81
|
+
installer: fileURLToPath(new URL('../../native-host/install.mjs', import.meta.url)),
|
|
82
|
+
directory: extensionDirectory(browser),
|
|
83
|
+
node: process.execPath,
|
|
84
|
+
extensionsUrl: extensionPageUrl(browser),
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
export class ExtensionBrowserViewHost implements ElectronBrowserViewHost {
|
|
89
|
+
get referenceOverlayOwner(): 'client' | undefined { return 'client' }
|
|
90
|
+
private readonly views = new Map<string, View>()
|
|
91
|
+
private readonly detaching = new Map<BrowserSessionId, Set<Promise<unknown>>>()
|
|
92
|
+
private readonly unsubscribe: () => void
|
|
93
|
+
private disposed = false
|
|
94
|
+
readonly browser: 'edge' | 'chrome'
|
|
95
|
+
private readonly client: NativeBrowserClient
|
|
96
|
+
constructor(browser: 'edge' | 'chrome', client: NativeBrowserClient = new LazyNativeBrowserClient(extensionDirectory(browser), browser)) {
|
|
97
|
+
this.browser = browser
|
|
98
|
+
this.client = client
|
|
99
|
+
this.unsubscribe = client.onEvent(event => {
|
|
100
|
+
if (event.method === 'transport.disconnected') for (const view of this.views.values()) view.invalid = true
|
|
101
|
+
if (event.method === 'target.detached' || event.method === 'target.closed') {
|
|
102
|
+
for (const view of this.views.values()) if (view.lease?.lease === event.lease) view.invalid = true
|
|
103
|
+
}
|
|
104
|
+
})
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
connectionStatus(): ExtensionConnectionStatus { return this.client.status() }
|
|
108
|
+
|
|
109
|
+
connectedView(id: string): boolean {
|
|
110
|
+
const view = this.views.get(id)
|
|
111
|
+
return !this.disposed && !!view?.lease && !view.invalid && this.client.status().connected
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
async refreshStatus(): Promise<void> {
|
|
115
|
+
try { await this.prepare() } catch { /* Status retains the install/pair/disconnect diagnosis. */ }
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
async prepare(): Promise<void> {
|
|
119
|
+
if (this.disposed) throw new Error('extension carrier was released')
|
|
120
|
+
await this.client.connect()
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
createView(identity: BrowserTabWireId): ElectronViewHandle {
|
|
124
|
+
const scope = sessionWireId(readTabHandle(identity))
|
|
125
|
+
if (this.views.has(identity)) throw new Error('extension view already exists')
|
|
126
|
+
const handle: ElectronViewHandle = { id: identity, supportsCdpJpeg: true, sendCommand: async (method, params) => {
|
|
127
|
+
const lease = await this.ensureLease(view)
|
|
128
|
+
return await this.client.request({ kind: 'cdp', scope, view: identity, lease: lease.lease, method, params }) as Record<string, unknown>
|
|
129
|
+
} }
|
|
130
|
+
const view: View = { handle, scope, invalid: false }
|
|
131
|
+
this.views.set(identity, view)
|
|
132
|
+
return handle
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
private async ensureLease(view: View): Promise<Lease> {
|
|
136
|
+
if (this.disposed || view.invalid || this.views.get(view.handle.id) !== view) throw new Error('extension tab lease was released; explicitly reopen or reacquire the tab')
|
|
137
|
+
if (view.lease) return view.lease
|
|
138
|
+
view.pending ??= this.acquire(view, { kind: 'create' })
|
|
139
|
+
return view.pending
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
private async acquire(view: View, operation: Record<string, unknown>): Promise<Lease> {
|
|
143
|
+
await this.prepare()
|
|
144
|
+
const value = await this.client.request({ ...operation, scope: view.scope, view: view.handle.id }) as Lease
|
|
145
|
+
if (!value || typeof value.lease !== 'string' || !Number.isSafeInteger(value.tabId)) throw new Error('extension returned an invalid lease')
|
|
146
|
+
if (this.disposed || view.invalid || this.views.get(view.handle.id) !== view) {
|
|
147
|
+
await this.client.request({ kind: 'detach', scope: view.scope, view: view.handle.id, lease: value.lease }).catch(() => {})
|
|
148
|
+
throw new Error('extension view was released while attaching; tab left open')
|
|
149
|
+
}
|
|
150
|
+
view.lease = value
|
|
151
|
+
return value
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
destroyView(handle: ElectronViewHandle): void {
|
|
155
|
+
const view = this.views.get(handle.id)
|
|
156
|
+
if (!view) return
|
|
157
|
+
this.views.delete(handle.id)
|
|
158
|
+
view.invalid = true
|
|
159
|
+
const pending = view.lease && this.client.status().connected
|
|
160
|
+
? this.client.request({ kind: 'detach', scope: view.scope, view: handle.id, lease: view.lease.lease })
|
|
161
|
+
: view.pending?.catch(() => {})
|
|
162
|
+
if (pending) {
|
|
163
|
+
const tasks = this.detaching.get(view.scope) ?? new Set<Promise<unknown>>()
|
|
164
|
+
this.detaching.set(view.scope, tasks)
|
|
165
|
+
tasks.add(pending)
|
|
166
|
+
void pending.catch(() => {})
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
async retireSession(scope: BrowserSessionId): Promise<void> {
|
|
171
|
+
for (const view of this.views.values()) if (view.scope === scope) this.destroyView(view.handle)
|
|
172
|
+
const tasks = this.detaching.get(scope)
|
|
173
|
+
try { if (tasks) await Promise.all(tasks) }
|
|
174
|
+
finally { this.detaching.delete(scope) }
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
async listPages(scope: BrowserSessionId, options: { readonly requireRunning?: boolean } = {}): Promise<readonly CarrierPage[]> {
|
|
178
|
+
const identity = resolveSessionHandle(scope)
|
|
179
|
+
if (options.requireRunning && !this.client.status().connected) return []
|
|
180
|
+
await this.prepare()
|
|
181
|
+
const epoch = this.client.status().epoch
|
|
182
|
+
const pages = await this.client.request({ kind: 'list', scope }) as Array<{ tabId: number; title: string; url: string }>
|
|
183
|
+
if (!epoch || !Array.isArray(pages)) throw new Error('extension tab inventory is unavailable')
|
|
184
|
+
return pages.map(page => ({ id: tabWireId({ ...identity, tab: `page:extension:${epoch}:${page.tabId}` }), url: page.url, title: page.title }))
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
private pageId(id: BrowserTabWireId, scope: BrowserSessionId): number {
|
|
188
|
+
const { tab } = resolveTabHandle(resolveSessionHandle(scope), id)
|
|
189
|
+
const prefix = `page:extension:${this.client.status().epoch}:`
|
|
190
|
+
if (!this.client.status().connected || !tab.startsWith(prefix) || !/^\d+$/.test(tab.slice(prefix.length))) throw new Error('stale or foreign extension page; list tabs again')
|
|
191
|
+
const tabId = Number(tab.slice(prefix.length))
|
|
192
|
+
if (!Number.isSafeInteger(tabId)) throw new Error('invalid extension tab')
|
|
193
|
+
return tabId
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
async adoptPage(id: BrowserTabWireId, scope = sessionWireId(readTabHandle(id))): Promise<ElectronViewHandle> {
|
|
197
|
+
await this.prepare()
|
|
198
|
+
const tabId = this.pageId(id, scope)
|
|
199
|
+
const handle = this.createView(id), view = this.views.get(id)!
|
|
200
|
+
view.pending = this.acquire(view, { kind: 'attach', tabId })
|
|
201
|
+
try { await view.pending; return handle }
|
|
202
|
+
catch (error) { this.destroyView(handle); throw error }
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
async closePage(id: BrowserTabWireId, scope = sessionWireId(readTabHandle(id))): Promise<void> {
|
|
206
|
+
resolveTabHandle(resolveSessionHandle(scope), id)
|
|
207
|
+
const view = this.views.get(id)
|
|
208
|
+
if (view && !view.lease && !view.pending) { this.destroyView(view.handle); return }
|
|
209
|
+
const tabId = view ? (await this.ensureLease(view)).tabId : this.pageId(id, scope)
|
|
210
|
+
await this.client.request({ kind: 'close', scope, tabId })
|
|
211
|
+
if (view) this.destroyView(view.handle)
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
showView(): void {}
|
|
215
|
+
async presentView(): Promise<void> {}
|
|
216
|
+
focus(): void {}
|
|
217
|
+
|
|
218
|
+
dispose(): void {
|
|
219
|
+
if (this.disposed) return
|
|
220
|
+
this.disposed = true
|
|
221
|
+
const views = [...this.views.values()]
|
|
222
|
+
this.views.clear()
|
|
223
|
+
for (const view of views) view.invalid = true
|
|
224
|
+
this.unsubscribe()
|
|
225
|
+
void Promise.allSettled(views.map(async view => {
|
|
226
|
+
await view.pending?.catch(() => {})
|
|
227
|
+
if (view.lease && this.client.status().connected) await this.client.request({ kind: 'detach', scope: view.scope, view: view.handle.id, lease: view.lease.lease })
|
|
228
|
+
})).finally(() => { this.client.dispose() })
|
|
229
|
+
}
|
|
230
|
+
}
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
import { extensionMessages } from '../../assets/browser-messages.mjs'
|
|
2
|
+
import { EXTENSION_PROBE_TIMEOUT_MS, NATIVE_REGISTRATION_TIMEOUT_MS, NATIVE_REGISTRATION_MAX_BUFFER, extensionPageUrl, folderOpener } from '../../assets/browser-policy.mjs'
|
|
3
|
+
import { execFile, spawn } from 'node:child_process'
|
|
4
|
+
import { fileURLToPath } from 'node:url'
|
|
5
|
+
import { extensionDirectory, extensionInstallHelp } from './extension-browser.ts'
|
|
6
|
+
import { detectBrowser } from './system-browser.ts'
|
|
7
|
+
import { EXTENSION_ID, EXTENSION_STORE_URL } from '../../assets/browser-extension-identity.mjs'
|
|
8
|
+
|
|
9
|
+
export { EXTENSION_ID }
|
|
10
|
+
export const registrationStatus = new Map<string, { registered: boolean; detail: string }>()
|
|
11
|
+
const pending = new Map<string, Promise<void>>()
|
|
12
|
+
|
|
13
|
+
export function registerExtensionHosts(): Promise<void> {
|
|
14
|
+
return Promise.all((['edge', 'chrome'] as const).map(browser => {
|
|
15
|
+
const directory = extensionDirectory(browser)
|
|
16
|
+
let task = pending.get(directory)
|
|
17
|
+
if (!task) {
|
|
18
|
+
task = new Promise<void>(resolve => {
|
|
19
|
+
execFile(process.execPath, [fileURLToPath(new URL('../../native-host/install.mjs', import.meta.url)), '--browser', browser, '--directory', directory],
|
|
20
|
+
{ windowsHide: true, timeout: NATIVE_REGISTRATION_TIMEOUT_MS, maxBuffer: NATIVE_REGISTRATION_MAX_BUFFER }, error => {
|
|
21
|
+
registrationStatus.set(browser, { registered: !error, detail: error ? `Native host registration failed: ${error.message}` : 'Native host registered automatically.' })
|
|
22
|
+
resolve()
|
|
23
|
+
})
|
|
24
|
+
}).finally(() => pending.delete(directory))
|
|
25
|
+
pending.set(directory, task)
|
|
26
|
+
}
|
|
27
|
+
return task
|
|
28
|
+
})).then(() => {})
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
export const nativeRegistration = { ensure: registerExtensionHosts }
|
|
32
|
+
|
|
33
|
+
export async function probeExtension(browser: 'edge' | 'chrome'): Promise<boolean> {
|
|
34
|
+
let client: import('../../native-host/client.mjs').NativeBrowserClient | undefined
|
|
35
|
+
let timer: ReturnType<typeof setTimeout> | undefined
|
|
36
|
+
try {
|
|
37
|
+
const { NativeBrowserClient } = await import('../../native-host/client.mjs')
|
|
38
|
+
client = new NativeBrowserClient(extensionDirectory(browser), browser)
|
|
39
|
+
return await Promise.race([client.connect().then(() => true), new Promise<false>(resolve => { timer = setTimeout(() => resolve(false), EXTENSION_PROBE_TIMEOUT_MS) })])
|
|
40
|
+
} catch { return false }
|
|
41
|
+
finally { clearTimeout(timer); client?.dispose() }
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
function launch(command: string, args: string[]) {
|
|
45
|
+
return new Promise<void>((resolve, reject) => {
|
|
46
|
+
const child = spawn(command, args, { detached: true, stdio: 'ignore', windowsHide: true })
|
|
47
|
+
child.once('error', reject)
|
|
48
|
+
child.once('spawn', () => { child.unref(); resolve() })
|
|
49
|
+
})
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
export async function installExtension(browser: 'edge' | 'chrome', connected: boolean, deps = {
|
|
53
|
+
register: nativeRegistration.ensure, detect: detectBrowser, launch, platform: process.platform, storeUrl: EXTENSION_STORE_URL,
|
|
54
|
+
}) {
|
|
55
|
+
await deps.register()
|
|
56
|
+
if (connected) return { ok: true, connected: true, detail: extensionMessages.zh.connected }
|
|
57
|
+
const status = registrationStatus.get(browser)
|
|
58
|
+
if (status?.registered === false) return { ok: false, connected: false, detail: status.detail }
|
|
59
|
+
const executable = deps.detect(browser)
|
|
60
|
+
if (!executable) return { ok: false, connected: false, detail: `${browser} is not installed` }
|
|
61
|
+
await deps.launch(executable.path, [deps.storeUrl || extensionPageUrl(browser)])
|
|
62
|
+
if (!deps.storeUrl) {
|
|
63
|
+
const folder = extensionInstallHelp(browser).extensionDirectory
|
|
64
|
+
await deps.launch(folderOpener(deps.platform), [folder])
|
|
65
|
+
}
|
|
66
|
+
return { ok: true, connected: false, store: !!deps.storeUrl, detail: deps.storeUrl ? extensionMessages.zh.storeHint : extensionMessages.zh.loadHint }
|
|
67
|
+
}
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import { randomUUID } from 'node:crypto'
|
|
2
|
+
import { closeSync, constants, copyFileSync, linkSync, mkdirSync, openSync, unlinkSync, writeFileSync } from 'node:fs'
|
|
3
|
+
import { dirname, join } from 'node:path'
|
|
4
|
+
|
|
5
|
+
/** Write a complete new file without replacing any existing directory entry. */
|
|
6
|
+
export function writeFileNoReplace(file: string, contents: Uint8Array): void {
|
|
7
|
+
const directory = dirname(file)
|
|
8
|
+
mkdirSync(directory, { recursive: true })
|
|
9
|
+
// Never touch a predictable .part file: it may be somebody else's download or a link.
|
|
10
|
+
const temporary = join(directory, `.dsh-download-${randomUUID()}.part`)
|
|
11
|
+
const descriptor = openSync(temporary, 'wx', 0o600)
|
|
12
|
+
try {
|
|
13
|
+
writeFileSync(descriptor, contents)
|
|
14
|
+
// A hard-link commit is atomic and fails with EEXIST even if another writer created
|
|
15
|
+
// the final name after admission. rename() would silently replace it on Windows too.
|
|
16
|
+
try {
|
|
17
|
+
linkSync(temporary, file)
|
|
18
|
+
} catch (error) {
|
|
19
|
+
const code = (error as NodeJS.ErrnoException).code
|
|
20
|
+
if (!['ENOTSUP', 'EOPNOTSUPP', 'EPERM', 'EXDEV', 'ENOSYS'].includes(code ?? '')) throw error
|
|
21
|
+
// FAT/exFAT and some network shares cannot create hard links. Exclusive copy keeps
|
|
22
|
+
// the no-replacement guarantee there; unlike a hard link, it is not crash-atomic.
|
|
23
|
+
copyFileSync(temporary, file, constants.COPYFILE_EXCL)
|
|
24
|
+
}
|
|
25
|
+
} finally {
|
|
26
|
+
// Cleanup may be blocked by a scanner/lock after the final file was committed. It
|
|
27
|
+
// must neither turn that success into a failure nor hide the original write error.
|
|
28
|
+
try { closeSync(descriptor) } catch { /* best-effort cleanup */ }
|
|
29
|
+
try { unlinkSync(temporary) } catch { /* best-effort cleanup */ }
|
|
30
|
+
}
|
|
31
|
+
}
|
|
@@ -0,0 +1,142 @@
|
|
|
1
|
+
import { spawn } from 'node:child_process'
|
|
2
|
+
|
|
3
|
+
export interface ForegroundEvent {
|
|
4
|
+
/** Process that owns the foreground window. */
|
|
5
|
+
readonly pid: number
|
|
6
|
+
/** Whether that window lies off every display (a minimized window does not count). */
|
|
7
|
+
readonly offscreen: boolean
|
|
8
|
+
/** That window's top-left corner, in DIPs like CDP window bounds. */
|
|
9
|
+
readonly left?: number
|
|
10
|
+
readonly top?: number
|
|
11
|
+
/** The browser took the foreground off every display with no input from the person, and the watcher gave it back. */
|
|
12
|
+
readonly yielded?: boolean
|
|
13
|
+
}
|
|
14
|
+
export interface ForegroundWatch { stop(): void }
|
|
15
|
+
/** `onFail` runs at most once, when the watcher cannot start or dies; `stop()` never triggers it. */
|
|
16
|
+
export type ForegroundWatcher = (onChange: (event: ForegroundEvent) => void, onFail: (reason: string) => void, browserPid?: number) => ForegroundWatch | undefined
|
|
17
|
+
|
|
18
|
+
const POLL_MS = 500
|
|
19
|
+
const PARENT_CHECK_MS = 4000
|
|
20
|
+
|
|
21
|
+
/*
|
|
22
|
+
* A foreground hook reports each activation within a millisecond; the poll only catches the
|
|
23
|
+
* foreground window moving on or off the displays, and a Stopwatch checks parent liveness
|
|
24
|
+
* every 4 s regardless of foreground event frequency.
|
|
25
|
+
*/
|
|
26
|
+
const script = (parent: number, browserPid: number): string => [
|
|
27
|
+
`$parent = ${parent}; $browser = ${browserPid}`,
|
|
28
|
+
'try {',
|
|
29
|
+
'Add-Type -TypeDefinition @"',
|
|
30
|
+
'using System; using System.Diagnostics; using System.Runtime.InteropServices;',
|
|
31
|
+
'public static class DshForeground {',
|
|
32
|
+
' [StructLayout(LayoutKind.Sequential)] public struct Rect { public int Left, Top, Right, Bottom; }',
|
|
33
|
+
' [StructLayout(LayoutKind.Sequential)] public struct InputInfo { public uint Size, Time; }',
|
|
34
|
+
' [StructLayout(LayoutKind.Sequential)] public struct Msg { public IntPtr Hwnd; public uint Message; public IntPtr W, L; public uint Time; public int X, Y; }',
|
|
35
|
+
' public delegate void Hook(IntPtr hook, uint e, IntPtr h, int o, int c, uint t, uint time);',
|
|
36
|
+
' [DllImport("user32.dll")] static extern IntPtr SetWinEventHook(uint min, uint max, IntPtr mod, Hook f, uint pid, uint tid, uint flags);',
|
|
37
|
+
' [DllImport("user32.dll")] static extern uint MsgWaitForMultipleObjects(uint n, IntPtr[] h, bool all, uint ms, uint mask);',
|
|
38
|
+
' [DllImport("user32.dll")] static extern bool PeekMessage(out Msg m, IntPtr h, uint a, uint b, uint remove);',
|
|
39
|
+
' [DllImport("user32.dll")] static extern bool TranslateMessage(ref Msg m);',
|
|
40
|
+
' [DllImport("user32.dll")] static extern IntPtr DispatchMessage(ref Msg m);',
|
|
41
|
+
' [DllImport("user32.dll")] static extern IntPtr GetForegroundWindow();',
|
|
42
|
+
' [DllImport("user32.dll")] static extern uint GetWindowThreadProcessId(IntPtr h, out uint p);',
|
|
43
|
+
' [DllImport("user32.dll")] static extern bool GetWindowRect(IntPtr h, out Rect r);',
|
|
44
|
+
' [DllImport("user32.dll")] static extern bool IsIconic(IntPtr h);',
|
|
45
|
+
' [DllImport("user32.dll")] static extern uint GetDpiForWindow(IntPtr h);',
|
|
46
|
+
' [DllImport("user32.dll")] static extern IntPtr MonitorFromRect(ref Rect r, uint flags);',
|
|
47
|
+
' [DllImport("user32.dll")] public static extern bool SetProcessDpiAwarenessContext(IntPtr c);',
|
|
48
|
+
' [DllImport("user32.dll")] public static extern bool SetProcessDPIAware();',
|
|
49
|
+
' [DllImport("user32.dll")] static extern bool SetForegroundWindow(IntPtr h);',
|
|
50
|
+
' [DllImport("user32.dll")] static extern bool AttachThreadInput(uint a, uint b, bool f);',
|
|
51
|
+
' [DllImport("kernel32.dll")] static extern uint GetCurrentThreadId();',
|
|
52
|
+
' [DllImport("user32.dll")] static extern bool GetLastInputInfo(ref InputInfo i);',
|
|
53
|
+
' static uint LastInput() { var i = new InputInfo(); i.Size = 8; GetLastInputInfo(ref i); return i.Time; }',
|
|
54
|
+
' static Hook keep; static string last = ""; static uint input, prevPid, browser; static IntPtr prev;',
|
|
55
|
+
' static void Sample() {',
|
|
56
|
+
' uint before = LastInput(), p; IntPtr h = GetForegroundWindow();',
|
|
57
|
+
// Transient null foreground (lock screen, UAC, window switch): keep prev intact instead of clearing it.
|
|
58
|
+
' if (h == IntPtr.Zero) { input = before; return; }',
|
|
59
|
+
' uint thread = GetWindowThreadProcessId(h, out p);',
|
|
60
|
+
' Rect r; GetWindowRect(h, out r);',
|
|
61
|
+
// Physical pixels from GetWindowRect, so dividing by the window DPI gives DIPs at any scaling.
|
|
62
|
+
' int off = IsIconic(h) || r.Right <= r.Left || MonitorFromRect(ref r, 0) != IntPtr.Zero ? 0 : 1;',
|
|
63
|
+
' uint dpi = GetDpiForWindow(h); if (dpi == 0) dpi = 96;',
|
|
64
|
+
' string line = p + " " + off + " " + Math.Round(r.Left * 96.0 / dpi) + " " + Math.Round(r.Top * 96.0 / dpi);',
|
|
65
|
+
// Chrome activates its own window for a tab a click opens; with no input since before the last read, no person did it.
|
|
66
|
+
// Always mark yielded even if SetForegroundWindow(prev) fails (e.g. elevated prev window under UIPI),
|
|
67
|
+
// and keep prev/prevPid unchanged so follow-up samples before focus settles cannot bypass the guard.
|
|
68
|
+
' bool yielded = false;',
|
|
69
|
+
' if (p == browser && off == 1 && prevPid != browser && prev != IntPtr.Zero && LastInput() == input) {',
|
|
70
|
+
' yielded = true; line += " 1";',
|
|
71
|
+
' uint me = GetCurrentThreadId(); AttachThreadInput(me, thread, true);',
|
|
72
|
+
' SetForegroundWindow(prev);',
|
|
73
|
+
' AttachThreadInput(me, thread, false);',
|
|
74
|
+
' }',
|
|
75
|
+
' if (line != last) { Console.Out.WriteLine(line); Console.Out.Flush(); last = line; }',
|
|
76
|
+
' if (!yielded) { prev = h; prevPid = p; }',
|
|
77
|
+
' input = before;',
|
|
78
|
+
' }',
|
|
79
|
+
' public static void Run(int parent, uint browserPid) {',
|
|
80
|
+
' browser = browserPid; input = LastInput(); keep = (a, e, h, o, c, t, time) => Sample();',
|
|
81
|
+
' SetWinEventHook(3, 3, IntPtr.Zero, keep, 0, 0, 0);',
|
|
82
|
+
' var parentClock = Stopwatch.StartNew();',
|
|
83
|
+
' Sample(); Msg m;',
|
|
84
|
+
' for (;;) {',
|
|
85
|
+
` if (MsgWaitForMultipleObjects(0, null, false, ${POLL_MS}, 0x4FF) == 0x102) Sample();`,
|
|
86
|
+
' while (PeekMessage(out m, IntPtr.Zero, 0, 0, 1)) { TranslateMessage(ref m); DispatchMessage(ref m); }',
|
|
87
|
+
` if (parentClock.ElapsedMilliseconds >= ${PARENT_CHECK_MS}) {`,
|
|
88
|
+
' parentClock.Restart();',
|
|
89
|
+
' try { Process.GetProcessById(parent).Dispose(); } catch (ArgumentException) { return; }',
|
|
90
|
+
' }',
|
|
91
|
+
' }',
|
|
92
|
+
' }',
|
|
93
|
+
'}',
|
|
94
|
+
'"@',
|
|
95
|
+
'} catch { exit 3 }',
|
|
96
|
+
'if (-not [DshForeground]::SetProcessDpiAwarenessContext([IntPtr](-4))) { [void][DshForeground]::SetProcessDPIAware() }',
|
|
97
|
+
'try { [DshForeground]::Run($parent, $browser) } catch { exit 4 }',
|
|
98
|
+
].join('\n')
|
|
99
|
+
|
|
100
|
+
/** One line of the watcher's output, `<pid> <0|1> [<left> <top> [1]]`, the last `1` when it gave the foreground back. */
|
|
101
|
+
export function parseForegroundLine(line: string): ForegroundEvent | undefined {
|
|
102
|
+
const match = /^(\d+) ([01])(?: (-?\d+) (-?\d+)( 1)?)?$/u.exec(line.trim())
|
|
103
|
+
if (match === null) return undefined
|
|
104
|
+
const event = { pid: Number(match[1]), offscreen: match[2] === '1' }
|
|
105
|
+
if (match[3] === undefined) return event
|
|
106
|
+
return { ...event, left: Number(match[3]), top: Number(match[4]), ...match[5] === undefined ? {} : { yielded: true } }
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
/**
|
|
110
|
+
* Report the foreground window's process, and whether that window is off every display, each time
|
|
111
|
+
* either changes. Windows only: CDP cannot tell a person activating a window from Chrome activating
|
|
112
|
+
* it for a tab an agent's click opened, but only the person's leaves input. The watcher exits with this process.
|
|
113
|
+
*/
|
|
114
|
+
export const watchForeground: ForegroundWatcher = (onChange, onFail, browserPid = 0) => {
|
|
115
|
+
if (process.platform !== 'win32') return undefined
|
|
116
|
+
let child
|
|
117
|
+
try {
|
|
118
|
+
child = spawn('powershell.exe', ['-NoProfile', '-NonInteractive', '-ExecutionPolicy', 'Bypass', '-EncodedCommand',
|
|
119
|
+
Buffer.from(script(process.pid, browserPid), 'utf16le').toString('base64')], { stdio: ['ignore', 'pipe', 'ignore'], windowsHide: true })
|
|
120
|
+
} catch (error) {
|
|
121
|
+
onFail(String(error))
|
|
122
|
+
return undefined
|
|
123
|
+
}
|
|
124
|
+
let stopped = false
|
|
125
|
+
let failed = false
|
|
126
|
+
const fail = (reason: string): void => { if (!stopped && !failed) { failed = true; onFail(reason) } }
|
|
127
|
+
child.on('error', error => fail(String(error)))
|
|
128
|
+
child.on('exit', (code, signal) => fail(`exited (${signal ?? code})`))
|
|
129
|
+
child.unref()
|
|
130
|
+
let buffer = ''
|
|
131
|
+
child.stdout?.setEncoding('utf8')
|
|
132
|
+
child.stdout?.on('data', (chunk: string) => {
|
|
133
|
+
buffer += chunk
|
|
134
|
+
for (let end = buffer.indexOf('\n'); end >= 0; end = buffer.indexOf('\n')) {
|
|
135
|
+
const event = parseForegroundLine(buffer.slice(0, end))
|
|
136
|
+
buffer = buffer.slice(end + 1)
|
|
137
|
+
if (event !== undefined) onChange(event)
|
|
138
|
+
}
|
|
139
|
+
})
|
|
140
|
+
;(child.stdout as { unref?: () => void } | null)?.unref?.()
|
|
141
|
+
return { stop: () => { stopped = true; try { child.kill() } catch { /* already gone */ } } }
|
|
142
|
+
}
|