dsh-builtin-browser 0.5.8 → 1.0.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +410 -1
- package/README.en.md +16 -64
- package/README.md +33 -64
- package/assets/browser-carriers.svg +20 -0
- package/assets/browser-extension-identity.d.mts +2 -0
- package/assets/browser-extension-identity.mjs +2 -0
- package/assets/browser-messages.d.mts +5 -0
- package/assets/browser-messages.mjs +64 -0
- package/assets/browser-panel-locales.d.mts +2 -0
- package/assets/browser-panel-locales.mjs +380 -0
- package/assets/browser-policy.d.mts +37 -0
- package/assets/browser-policy.mjs +37 -0
- package/assets/browser-products.d.mts +6 -0
- package/assets/browser-products.mjs +76 -0
- package/assets/screenshots/1-main.png +0 -0
- package/assets/screenshots/2-form-fill.png +0 -0
- package/assets/screenshots/3-challenge.png +0 -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/cordis.patch.yml +23 -48
- package/desktop-bridge/desktop-discovery.d.mts +2 -0
- package/desktop-bridge/desktop-discovery.mjs +36 -0
- package/desktop-bridge/desktop-identity.json +17 -1
- package/desktop-bridge/desktop-processes.d.mts +1 -0
- package/desktop-bridge/desktop-processes.mjs +15 -0
- package/desktop-bridge/guest-proxy.mjs +109 -0
- package/desktop-bridge/install.mjs +197 -74
- package/desktop-bridge/main.mjs +11 -0
- package/desktop-bridge/maintenance-files.d.mts +8 -0
- package/desktop-bridge/maintenance-files.mjs +28 -0
- package/desktop-bridge/maintenance-progress.ps1 +2 -2
- package/desktop-bridge/native-guests.mjs +41 -0
- package/desktop-bridge/plugin-browser-bridge.js +618 -370
- package/desktop-bridge/profile-loader.mjs +26 -0
- package/dist/client.cjs +43167 -0
- package/dist/client.d.cts +516 -0
- package/dist/client.d.mts +516 -0
- package/dist/index.cjs +92 -0
- package/dist/index.d.mts +2960 -0
- package/dist/index.mjs +24 -0
- package/docs/HANDOVER-2026-11-15.md +178 -0
- package/docs/README.md +10 -19
- package/docs/architecture.md +17 -145
- package/docs/child-tabs.md +13 -0
- package/docs/desktop-acceptance.md +9 -0
- package/docs/development.md +88 -18
- package/docs/extension-browser.md +44 -0
- package/docs/hardcoding-audit.md +64 -0
- package/docs/limitations.md +23 -73
- package/docs/pr64-extension-status.md +46 -0
- package/docs/pr64-maintenance.md +25 -0
- package/docs/pr64-native-children.md +52 -0
- package/docs/pr64-native-views.md +60 -0
- package/docs/tool-reference.md +87 -11
- package/docs/user-guide.md +47 -255
- package/docs/why-browser.md +6 -39
- package/dsh-host-patch/README.md +60 -0
- package/dsh-host-patch/apply.mjs +194 -0
- package/dsh-host-patch/legacy-bridge.mjs +53 -0
- package/dsh-host-patch/rc3-revision1.json +90 -0
- package/dsh-host-patch/rc3-revision2.json +112 -0
- package/dsh-host-patch/rc3-revision3.json.gz +0 -0
- package/dsh-host-patch/rc3-revision4.json.gz +0 -0
- package/dsh-host-patch/rc3-revision5.json.gz +0 -0
- package/dsh-host-patch/rc3-revision6.json.gz +0 -0
- package/dsh-host-patch/rc3-revision7.json.gz +0 -0
- package/dsh-host-patch/rc3-revision8.json.gz +0 -0
- package/dsh-host-patch/rc3.json +148 -0
- package/dsh-host-patch/rc5-revision1.json +90 -0
- package/dsh-host-patch/rc5-revision2.json +112 -0
- package/dsh-host-patch/rc5-revision3.json.gz +0 -0
- package/dsh-host-patch/rc5-revision4.json.gz +0 -0
- package/dsh-host-patch/rc5-revision5.json.gz +0 -0
- package/dsh-host-patch/rc5-revision6.json.gz +0 -0
- package/dsh-host-patch/rc5-revision7.json.gz +0 -0
- package/dsh-host-patch/rc5-revision8.json.gz +0 -0
- package/dsh-host-patch/rc5.json +148 -0
- package/lib/bridge-compatibility.js +38 -0
- package/lib/browser/handles.js +78 -0
- package/lib/browser/runtime.js +155 -43
- package/lib/browser/takeover-target.js +24 -0
- package/lib/browser-electron/authenticated-route.js +23 -0
- package/lib/browser-electron/automatic-maintenance.js +394 -51
- package/lib/browser-electron/bridge-auto.js +2 -1
- package/lib/browser-electron/bridge-connection.js +8 -1
- package/lib/browser-electron/bridge-install.js +27 -2
- package/lib/browser-electron/bridge-maintenance.js +35 -10
- package/lib/browser-electron/bridge-status.js +98 -27
- package/lib/browser-electron/desktop-bridge-host.js +193 -560
- package/lib/browser-electron/desktop-identity.js +40 -2
- package/lib/browser-electron/document-readiness.js +34 -0
- package/lib/browser-electron/electron-provision.js +14 -44
- package/lib/browser-electron/entry.js +659 -252
- package/lib/browser-electron/extension-browser.js +234 -0
- package/lib/browser-electron/extension-setup.js +69 -0
- package/lib/browser-electron/guest-cookie-jar.LICENSE.txt +32 -0
- package/lib/browser-electron/guest-cookie-jar.js +10559 -0
- package/lib/browser-electron/guest-cookie-store.js +74 -0
- package/lib/browser-electron/guest-css-runtime.js +75 -0
- package/lib/browser-electron/guest-css.js +106 -0
- package/lib/browser-electron/guest-route.js +603 -0
- package/lib/browser-electron/guest-runtime.js +356 -0
- package/lib/browser-electron/guest-storage-runtime.js +52 -0
- package/lib/browser-electron/guest-storage.js +163 -0
- package/lib/browser-electron/history-store.js +2 -1
- package/lib/browser-electron/host-main.js +162 -7
- package/lib/browser-electron/host-patch-maintenance.js +141 -0
- package/lib/browser-electron/http-body.js +22 -0
- package/lib/browser-electron/maintenance-broker.js +35 -5
- package/lib/browser-electron/maintenance-lifecycle.js +7 -5
- package/lib/browser-electron/maintenance-route.js +9 -6
- package/lib/browser-electron/open-slot.js +47 -0
- package/lib/browser-electron/paths.js +4 -1
- package/lib/browser-electron/preferred-browser.js +144 -0
- package/lib/browser-electron/preview-route.js +11 -8
- package/lib/browser-electron/process-ownership.js +198 -0
- package/lib/browser-electron/profile-checkpoint.js +222 -0
- package/lib/browser-electron/profile-command.js +60 -0
- package/lib/browser-electron/profile-extension.js +126 -0
- package/lib/browser-electron/profile-lease.js +157 -0
- package/lib/browser-electron/profile-residue.js +61 -0
- package/lib/browser-electron/provider.js +719 -262
- package/lib/browser-electron/reference-route.js +635 -0
- package/lib/browser-electron/remote-host.js +12 -13
- package/lib/browser-electron/runtime-route.js +6 -5
- package/lib/browser-electron/runtime-status.js +30 -29
- package/lib/browser-electron/settings-store.js +10 -5
- package/lib/browser-electron/shortcuts-route.js +108 -0
- package/lib/browser-electron/sidebar-only-host.js +119 -18
- package/lib/browser-electron/startpage-shortcuts.js +172 -0
- package/lib/browser-electron/system-browser.js +352 -371
- package/lib/browser-electron/windows-system.js +2 -1
- package/lib/browser-reference/delivery.js +326 -0
- package/lib/browser-reference/entry.js +597 -0
- package/lib/browser-reference/export.js +298 -0
- package/lib/browser-reference/import.js +295 -0
- package/lib/browser-reference/page-script.js +1406 -0
- package/lib/browser-reference/service.js +1062 -0
- package/lib/browser-reference/store.js +177 -0
- package/lib/browser-reference/submission-receipts.js +139 -0
- package/lib/browser-reference/text-quote.js +167 -0
- package/lib/browser-reference/types.js +11 -0
- package/lib/browser-reference/visible.js +311 -0
- package/lib/browser-reference/web-sources.js +97 -0
- package/lib/index.js +10 -3
- package/lib/reference-owner.js +5 -0
- package/lib/reference-page.js +12 -0
- package/lib/reference-source.js +2 -0
- package/lib/reference-text.js +188 -0
- package/lib/startpage-settings.js +63 -0
- package/lib/startpage.js +44 -0
- package/lib/takeover-protocol.js +2 -0
- package/lib/tool-browser/code-tool.js +416 -0
- package/lib/tool-browser/code-worker.js +872 -0
- package/lib/tool-browser/index.js +940 -76
- package/lib/tool-browser/page-probe.js +3 -3
- package/lib/tool-browser/panel-page.js +95 -0
- package/lib/tool-browser/screenshot-image.js +51 -0
- package/lib/tool-browser/takeover.js +205 -0
- package/lib/types.js +1 -0
- package/lib/web-guest.js +26 -0
- package/native-host/client.d.mts +17 -0
- package/native-host/client.mjs +100 -0
- package/native-host/host.mjs +150 -0
- package/native-host/identity.d.mts +2 -0
- package/native-host/identity.mjs +1 -0
- package/native-host/install.mjs +168 -0
- package/native-host/protocol.mjs +75 -0
- package/package.json +80 -92
- package/scripts/build.mjs +66 -0
- package/scripts/bundle-host.mjs +28 -0
- package/scripts/fix-exports.mjs +50 -0
- package/scripts/install-electron.mjs +11 -26
- package/scripts/verify-exports.mjs +47 -0
- package/scripts/verify-preview-sdk.mjs +93 -0
- package/skills/dsh-builtin-browser/SKILL.md +56 -47
- package/skills/dsh-builtin-browser/references/batch.md +31 -1
- 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/handles.ts +89 -0
- package/src/browser/runtime.ts +146 -50
- package/src/browser/takeover-target.ts +36 -0
- package/src/browser/types.ts +19 -7
- package/src/browser-electron/authenticated-route.ts +29 -1
- package/src/browser-electron/automatic-maintenance.ts +368 -56
- package/src/browser-electron/bridge-auto.ts +5 -4
- package/src/browser-electron/bridge-connection.ts +20 -2
- package/src/browser-electron/bridge-endpoint.ts +3 -3
- package/src/browser-electron/bridge-install.ts +40 -4
- package/src/browser-electron/bridge-maintenance.ts +42 -14
- package/src/browser-electron/bridge-status.ts +94 -23
- package/src/browser-electron/desktop-bridge-host.ts +185 -585
- package/src/browser-electron/desktop-identity.ts +53 -2
- package/src/browser-electron/document-readiness.ts +45 -0
- package/src/browser-electron/electron-provision.ts +12 -45
- package/src/browser-electron/entry.ts +1299 -882
- package/src/browser-electron/ephemeral-profile.ts +1 -1
- package/src/browser-electron/extension-browser.ts +223 -0
- package/src/browser-electron/extension-setup.ts +67 -0
- package/src/browser-electron/guest-cookie-jar.ts +176 -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 +568 -0
- package/src/browser-electron/guest-runtime.ts +357 -0
- package/src/browser-electron/guest-storage-runtime.ts +54 -0
- package/src/browser-electron/guest-storage.ts +117 -0
- package/src/browser-electron/history-store.ts +5 -4
- package/src/browser-electron/host-main.ts +156 -11
- package/src/browser-electron/host-patch-maintenance.ts +112 -0
- package/src/browser-electron/http-body.ts +23 -0
- package/src/browser-electron/maintenance-broker.ts +29 -5
- package/src/browser-electron/maintenance-lifecycle.ts +14 -9
- package/src/browser-electron/maintenance-route.ts +17 -14
- package/src/browser-electron/missing-system-browser.ts +2 -2
- package/src/browser-electron/open-slot.ts +49 -0
- package/src/browser-electron/paths.ts +5 -1
- package/src/browser-electron/preferred-browser.ts +120 -0
- package/src/browser-electron/preview-route.ts +18 -11
- package/src/browser-electron/process-ownership.ts +168 -0
- package/src/browser-electron/profile-checkpoint.ts +187 -0
- package/src/browser-electron/profile-command.ts +46 -0
- package/src/browser-electron/profile-extension.ts +124 -0
- package/src/browser-electron/profile-lease.ts +115 -0
- package/src/browser-electron/profile-residue.ts +49 -0
- package/src/browser-electron/provider.ts +771 -289
- package/src/browser-electron/reference-route.ts +608 -0
- package/src/browser-electron/remote-host.ts +15 -15
- package/src/browser-electron/runtime-route.ts +11 -10
- package/src/browser-electron/runtime-status.ts +51 -32
- package/src/browser-electron/settings-store.ts +27 -7
- package/src/browser-electron/shortcuts-route.ts +112 -0
- package/src/browser-electron/sidebar-only-host.ts +118 -19
- package/src/browser-electron/startpage-shortcuts.ts +213 -0
- package/src/browser-electron/system-browser.ts +309 -338
- package/src/browser-electron/windows-system.ts +2 -1
- 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 +1315 -0
- package/src/browser-reference/store.ts +172 -0
- package/src/browser-reference/submission-receipts.ts +122 -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 +103 -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 +176 -0
- package/src/client/browser/child-tabs.ts +14 -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 +52 -0
- package/src/client/css-modules.d.ts +4 -0
- package/src/client/definition.tsx +30 -0
- package/src/client/electron/ElectronWebViewImpl.ts +364 -0
- package/src/client/electron/ElectronWebviewPresentation.ts +138 -0
- package/src/client/electron/NativeChildPresentation.ts +45 -0
- package/src/client/electron/NativeViewPage.ts +251 -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 +293 -0
- package/src/client/locales.ts +857 -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 +189 -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 +471 -0
- package/src/client/reference/client/production/asset-store.ts +144 -0
- package/src/client/reference/client/production/availability.ts +74 -0
- package/src/client/reference/client/production/bytes.ts +36 -0
- package/src/client/reference/client/production/delivery-client.ts +211 -0
- package/src/client/reference/client/production/draft-adapter.ts +508 -0
- package/src/client/reference/client/production/http-transport.ts +217 -0
- package/src/client/reference/client/production/production-submission.ts +310 -0
- package/src/client/reference/client/production/protocol.ts +231 -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 +1101 -0
- package/src/client/reference/client/production/snapshot-adapter.ts +154 -0
- package/src/client/reference/client/production/source-marker.ts +63 -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 +58 -0
- package/src/client/reference/client/reveal.ts +107 -0
- package/src/client/reference/client/scheme.ts +114 -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 +34 -0
- package/{client.js → src/client/settings/panel.ts} +2657 -2231
- package/src/client/shortcut-open.ts +30 -0
- package/src/client/startpage/binding.ts +99 -0
- package/src/client/startpage/controller.ts +303 -0
- package/src/client/startpage/model.ts +279 -0
- package/src/client/view/Browser.module.css +751 -0
- package/src/client/view/BrowserBody.tsx +314 -0
- package/src/client/view/BrowserPresentation.ts +9 -0
- package/src/client/view/BrowserTitle.tsx +17 -0
- package/src/client/view/IframePresentation.ts +344 -0
- package/src/client/view/StartPage.tsx +597 -0
- package/src/client/view/TakeoverBanner.tsx +21 -0
- package/src/index.ts +110 -73
- 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 +197 -0
- package/src/startpage-settings.ts +103 -0
- package/src/startpage.ts +71 -0
- package/src/takeover-protocol.ts +19 -0
- package/src/tool-browser/code-tool.ts +401 -0
- package/src/tool-browser/code-worker.ts +639 -0
- package/src/tool-browser/index.ts +908 -77
- package/src/tool-browser/page-probe.ts +4 -4
- package/src/tool-browser/panel-page.ts +124 -0
- package/src/tool-browser/screenshot-image.ts +49 -0
- package/src/tool-browser/takeover.ts +198 -0
- package/src/types/electron-shim.d.ts +20 -0
- package/src/types.ts +85 -0
- package/src/web-guest.ts +34 -0
- package/tools/accept-desktop.mjs +148 -0
- package/lib/browser/runtime.d.ts +0 -175
- package/lib/browser/types.d.ts +0 -797
- package/lib/browser-electron/authenticated-route.d.ts +0 -27
- package/lib/browser-electron/automatic-maintenance.d.ts +0 -41
- package/lib/browser-electron/bridge-auto.d.ts +0 -93
- package/lib/browser-electron/bridge-connection.d.ts +0 -93
- package/lib/browser-electron/bridge-endpoint.d.ts +0 -30
- package/lib/browser-electron/bridge-install.d.ts +0 -85
- package/lib/browser-electron/bridge-maintenance.d.ts +0 -24
- package/lib/browser-electron/bridge-status.d.ts +0 -50
- package/lib/browser-electron/desktop-bridge-host.d.ts +0 -248
- package/lib/browser-electron/desktop-identity.d.ts +0 -58
- package/lib/browser-electron/electron-provision.d.ts +0 -92
- package/lib/browser-electron/entry.d.ts +0 -64
- package/lib/browser-electron/ephemeral-profile.d.ts +0 -37
- package/lib/browser-electron/file-write.d.ts +0 -2
- package/lib/browser-electron/history-store.d.ts +0 -98
- package/lib/browser-electron/host-main.d.ts +0 -26
- package/lib/browser-electron/http-body.d.ts +0 -24
- package/lib/browser-electron/json-reply.d.ts +0 -33
- package/lib/browser-electron/maintenance-broker.d.ts +0 -35
- package/lib/browser-electron/maintenance-lifecycle.d.ts +0 -32
- package/lib/browser-electron/maintenance-route.d.ts +0 -18
- package/lib/browser-electron/missing-system-browser.d.ts +0 -54
- package/lib/browser-electron/paths.d.ts +0 -4
- package/lib/browser-electron/preview-route.d.ts +0 -89
- package/lib/browser-electron/process.d.ts +0 -14
- package/lib/browser-electron/provider.d.ts +0 -959
- package/lib/browser-electron/remote-host.d.ts +0 -256
- package/lib/browser-electron/rpc-input.d.ts +0 -4
- package/lib/browser-electron/rpc-ops.d.ts +0 -18
- package/lib/browser-electron/runtime-diagnostics.d.ts +0 -12
- package/lib/browser-electron/runtime-route.d.ts +0 -55
- package/lib/browser-electron/runtime-status.d.ts +0 -116
- package/lib/browser-electron/settings-route.d.ts +0 -15
- package/lib/browser-electron/settings-store.d.ts +0 -224
- package/lib/browser-electron/sidebar-only-host.d.ts +0 -36
- package/lib/browser-electron/system-browser.d.ts +0 -367
- package/lib/browser-electron/timing.d.ts +0 -8
- package/lib/browser-electron/virtual-cursor.d.ts +0 -67
- package/lib/browser-electron/windows-system.d.ts +0 -3
- package/lib/index.d.ts +0 -30
- package/lib/tool-browser/element-fields.d.ts +0 -145
- package/lib/tool-browser/index.d.ts +0 -53
- package/lib/tool-browser/page-probe.d.ts +0 -86
- package/scripts/consumer-install-check.mjs +0 -72
- package/scripts/run-tests.mjs +0 -32
- package/scripts/verify-host-compat.mjs +0 -195
- package/scripts/verify-preview-route.mjs +0 -168
- package/scripts/verify-runtime-status.mjs +0 -179
|
@@ -0,0 +1,120 @@
|
|
|
1
|
+
import { EXTENSION_READY_TIMEOUT_MS } from '../../assets/browser-policy.mjs'
|
|
2
|
+
import { ExtensionBrowserViewHost } from './extension-browser.ts'
|
|
3
|
+
import type { NativeBrowserClient } from '../../native-host/client.mjs'
|
|
4
|
+
import type { ElectronBrowserViewHost, ElectronViewHandle } from './provider.ts'
|
|
5
|
+
import { readTabHandle, sessionWireId, type BrowserTabWireId } from '../browser/handles.ts'
|
|
6
|
+
import type { BrowserSessionId } from '../browser/types.ts'
|
|
7
|
+
|
|
8
|
+
export async function extensionReady(connect: () => Promise<void>, milliseconds = EXTENSION_READY_TIMEOUT_MS): Promise<boolean> {
|
|
9
|
+
const deadline = Date.now() + milliseconds
|
|
10
|
+
let timer: ReturnType<typeof setTimeout> | undefined
|
|
11
|
+
const attempt = async () => {
|
|
12
|
+
do {
|
|
13
|
+
try { await connect(); return true } catch {}
|
|
14
|
+
await new Promise(resolve => setTimeout(resolve, Math.min(100, Math.max(0, deadline - Date.now()))))
|
|
15
|
+
} while (Date.now() < deadline)
|
|
16
|
+
return false
|
|
17
|
+
}
|
|
18
|
+
try { return await Promise.race([attempt(), new Promise<false>(resolve => { timer = setTimeout(() => resolve(false), milliseconds) })]) }
|
|
19
|
+
finally { clearTimeout(timer) }
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
export class PreferredBrowserViewHost implements ElectronBrowserViewHost {
|
|
23
|
+
private readonly routes = new Map<BrowserSessionId, Promise<ElectronBrowserViewHost>>()
|
|
24
|
+
private readonly decisions = new Map<BrowserSessionId, ElectronBrowserViewHost>()
|
|
25
|
+
private readonly mapped = new Map<string, { handle: ElectronViewHandle; real?: Promise<{ host: ElectronBrowserViewHost; handle: ElectronViewHandle }>; dead: boolean }>()
|
|
26
|
+
private released = false
|
|
27
|
+
private selected?: 'extension' | 'cdp'
|
|
28
|
+
fallbackReason?: string
|
|
29
|
+
private readonly extension: ExtensionBrowserViewHost
|
|
30
|
+
|
|
31
|
+
constructor(readonly browser: 'edge' | 'chrome', readonly fallback: ElectronBrowserViewHost & { connectionStatus?: () => { connected: boolean; detail: string } }, client?: NativeBrowserClient, private readonly bound = EXTENSION_READY_TIMEOUT_MS) {
|
|
32
|
+
this.extension = new ExtensionBrowserViewHost(browser, client)
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
activeCarrier(): 'extension' | 'cdp' { return this.selected ?? (this.extension.connectionStatus().connected ? 'extension' : 'cdp') }
|
|
36
|
+
get disposed(): boolean { return this.released }
|
|
37
|
+
connectionStatus() { return this.extension.connectionStatus() }
|
|
38
|
+
async refreshStatus() { await this.extension.refreshStatus() }
|
|
39
|
+
async prepare(scope?: BrowserSessionId) { if (scope) await (await this.route(scope)).prepare?.(scope) }
|
|
40
|
+
referenceOverlayOwnerFor(scope: BrowserSessionId): 'client' | undefined {
|
|
41
|
+
const host = this.decisions.get(scope)
|
|
42
|
+
return host ? host.referenceOverlayOwner : 'client'
|
|
43
|
+
}
|
|
44
|
+
connectedView(id: string) {
|
|
45
|
+
const view = this.mapped.get(id)
|
|
46
|
+
return !!view && !view.dead && (this.decisions.get(sessionWireId(readTabHandle(id))) === this.fallback
|
|
47
|
+
? this.fallback.connectionStatus?.().connected === true : this.extension.connectedView(id))
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
private route(scope: BrowserSessionId): Promise<ElectronBrowserViewHost> {
|
|
51
|
+
if (this.released) return Promise.reject(new Error('browser carrier was released'))
|
|
52
|
+
let route = this.routes.get(scope)
|
|
53
|
+
if (!route) {
|
|
54
|
+
route = (async () => {
|
|
55
|
+
const ready = await extensionReady(() => this.extension.prepare(), this.bound)
|
|
56
|
+
if (this.released) throw new Error('browser carrier was released')
|
|
57
|
+
this.selected = ready ? 'extension' : 'cdp'
|
|
58
|
+
const state = this.extension.connectionStatus().state
|
|
59
|
+
this.fallbackReason = ready ? undefined : state === 'disabled' ? 'disabled' : state === 'extension-missing' ? 'extension-not-installed' : 'not-connected'
|
|
60
|
+
const host = ready ? this.extension : this.fallback
|
|
61
|
+
this.decisions.set(scope, host)
|
|
62
|
+
return host
|
|
63
|
+
})()
|
|
64
|
+
this.routes.set(scope, route)
|
|
65
|
+
}
|
|
66
|
+
return route
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
createView(id: BrowserTabWireId): ElectronViewHandle {
|
|
70
|
+
if (this.mapped.has(id)) throw new Error('browser view already exists')
|
|
71
|
+
const view: { handle: ElectronViewHandle; real?: Promise<{ host: ElectronBrowserViewHost; handle: ElectronViewHandle }>; dead: boolean } = {
|
|
72
|
+
dead: false, handle: { id, supportsCdpJpeg: true, sendCommand: async (method, params) => {
|
|
73
|
+
if (view.dead || this.released) throw new Error('browser view was released')
|
|
74
|
+
view.real ??= this.route(sessionWireId(readTabHandle(id))).then(host => {
|
|
75
|
+
if (view.dead || this.released) throw new Error('browser view was released')
|
|
76
|
+
return { host, handle: host.createView(id) }
|
|
77
|
+
})
|
|
78
|
+
const real = await view.real
|
|
79
|
+
return real.handle.sendCommand(method, params)
|
|
80
|
+
} },
|
|
81
|
+
}
|
|
82
|
+
this.mapped.set(id, view)
|
|
83
|
+
return view.handle
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
destroyView(handle: ElectronViewHandle) {
|
|
87
|
+
const view = this.mapped.get(handle.id)
|
|
88
|
+
if (!view) return
|
|
89
|
+
view.dead = true; this.mapped.delete(handle.id)
|
|
90
|
+
void view.real?.then(real => real.host.destroyView(real.handle)).catch(() => {})
|
|
91
|
+
}
|
|
92
|
+
async listPages(scope: BrowserSessionId, options: { requireRunning?: boolean } = {}) {
|
|
93
|
+
if (options.requireRunning && !this.routes.has(scope)) return []
|
|
94
|
+
return (await this.route(scope)).listPages?.(scope, options) ?? []
|
|
95
|
+
}
|
|
96
|
+
async adoptPage(id: BrowserTabWireId, scope = sessionWireId(readTabHandle(id))) {
|
|
97
|
+
const host = await this.route(scope)
|
|
98
|
+
if (!host.adoptPage) throw new Error('carrier does not support page adoption')
|
|
99
|
+
const handle = await host.adoptPage(id, scope)
|
|
100
|
+
this.mapped.set(id, { handle, real: Promise.resolve({ host, handle }), dead: false })
|
|
101
|
+
return handle
|
|
102
|
+
}
|
|
103
|
+
async closePage(id: BrowserTabWireId, scope = sessionWireId(readTabHandle(id))) {
|
|
104
|
+
const host = await this.route(scope)
|
|
105
|
+
if (!host.closePage) throw new Error('carrier does not support explicit close')
|
|
106
|
+
await host.closePage(id, scope)
|
|
107
|
+
const view = this.mapped.get(id)
|
|
108
|
+
if (view) this.destroyView(view.handle)
|
|
109
|
+
}
|
|
110
|
+
async retireSession(scope: BrowserSessionId) {
|
|
111
|
+
try { await (await this.routes.get(scope))?.retireSession?.(scope) }
|
|
112
|
+
finally { this.routes.delete(scope); this.decisions.delete(scope) }
|
|
113
|
+
}
|
|
114
|
+
dispose() {
|
|
115
|
+
if (this.released) return
|
|
116
|
+
this.released = true
|
|
117
|
+
for (const view of [...this.mapped.values()]) this.destroyView(view.handle)
|
|
118
|
+
this.extension.dispose(); this.fallback.dispose?.()
|
|
119
|
+
}
|
|
120
|
+
}
|
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
import { PREVIEW_ROUTE, PREVIEW_SESSIONS_ROUTE, BRIDGE_STATUS_ROUTE } from '../../assets/browser-policy.mjs'
|
|
2
|
+
import { URL_PARSE_BASE } from '../../assets/browser-policy.mjs'
|
|
1
3
|
/**
|
|
2
4
|
* The live-view frame endpoint (issue #34): one JPEG per request, for a remote operator watching the
|
|
3
5
|
* page the agent is driving.
|
|
@@ -13,13 +15,14 @@
|
|
|
13
15
|
* @module dsh-browser/browser-electron/preview-route
|
|
14
16
|
*/
|
|
15
17
|
import type { IncomingMessage, ServerResponse } from 'node:http'
|
|
16
|
-
import type { BrowserError } from '../browser/types.
|
|
17
|
-
import { replyJson } from './json-reply.
|
|
18
|
-
import { sameOrigin } from './settings-route.
|
|
19
|
-
import { findDesktopInstall, readBridgeStatus } from './bridge-status.
|
|
18
|
+
import type { BrowserError } from '../browser/types.ts'
|
|
19
|
+
import { replyJson } from './json-reply.ts'
|
|
20
|
+
import { sameOrigin } from './settings-route.ts'
|
|
21
|
+
import { findDesktopInstall, readBridgeStatus } from './bridge-status.ts'
|
|
22
|
+
import type { MainExtensionStatus } from './profile-extension.ts'
|
|
20
23
|
|
|
21
24
|
/** Where the frame endpoint lives. The viewer must use exactly this path, same origin. */
|
|
22
|
-
export
|
|
25
|
+
export { PREVIEW_ROUTE }
|
|
23
26
|
|
|
24
27
|
/**
|
|
25
28
|
* Where the viewer asks which sessions it may watch.
|
|
@@ -29,7 +32,7 @@ export const PREVIEW_ROUTE = '/dsh-builtin-browser/browser-view/frame'
|
|
|
29
32
|
* is exactly what the design forbids. So the list is served, and it contains nothing but ids of
|
|
30
33
|
* sessions that currently have a page — no URLs, no titles, no target handles.
|
|
31
34
|
*/
|
|
32
|
-
export
|
|
35
|
+
export { PREVIEW_SESSIONS_ROUTE }
|
|
33
36
|
|
|
34
37
|
/**
|
|
35
38
|
* Where the settings panel asks whether the desktop bridge is installed.
|
|
@@ -39,7 +42,7 @@ export const PREVIEW_SESSIONS_ROUTE = '/dsh-builtin-browser/browser-view/session
|
|
|
39
42
|
* The reading is taken from the install tree on disk, so it is true even when the plugin has just
|
|
40
43
|
* started and remembers nothing.
|
|
41
44
|
*/
|
|
42
|
-
export
|
|
45
|
+
export { BRIDGE_STATUS_ROUTE }
|
|
43
46
|
|
|
44
47
|
|
|
45
48
|
/** What the route needs from the settings document. */
|
|
@@ -125,7 +128,7 @@ export async function handlePreviewFrame(
|
|
|
125
128
|
replyJson(response, 403, { error: 'remote-view-disabled' })
|
|
126
129
|
return
|
|
127
130
|
}
|
|
128
|
-
const url = new URL(request.url ?? '/',
|
|
131
|
+
const url = new URL(request.url ?? '/', URL_PARSE_BASE)
|
|
129
132
|
const session = url.searchParams.get('session') ?? ''
|
|
130
133
|
if (session === '') {
|
|
131
134
|
replyJson(response, 400, { error: 'session-required' })
|
|
@@ -189,6 +192,9 @@ export async function handleBridgeStatus(
|
|
|
189
192
|
request: IncomingMessage,
|
|
190
193
|
response: ServerResponse,
|
|
191
194
|
localAppData?: string,
|
|
195
|
+
mainExtension?: MainExtensionStatus,
|
|
196
|
+
registry?: () => readonly string[],
|
|
197
|
+
conventions?: () => readonly string[],
|
|
192
198
|
): Promise<void> {
|
|
193
199
|
if (request.method !== 'GET') {
|
|
194
200
|
replyJson(response, 405, { error: 'method-not-allowed' })
|
|
@@ -198,14 +204,15 @@ export async function handleBridgeStatus(
|
|
|
198
204
|
replyJson(response, 403, { error: 'not-same-origin' })
|
|
199
205
|
return
|
|
200
206
|
}
|
|
201
|
-
const installRoot = findDesktopInstall(localAppData)
|
|
207
|
+
const installRoot = findDesktopInstall(localAppData, registry, conventions)
|
|
202
208
|
const status = installRoot === undefined
|
|
203
209
|
? {
|
|
204
210
|
state: 'missing' as const,
|
|
205
211
|
present: false,
|
|
206
212
|
archivePresent: false,
|
|
207
|
-
detail: 'no DSH Desktop install found
|
|
213
|
+
detail: 'no DSH Desktop install found in the usual roots, at DSH_DESKTOP_PATH or DSH_DESKTOP_APP, '
|
|
214
|
+
+ 'in the uninstall registry, or at this platform\'s conventional locations',
|
|
208
215
|
}
|
|
209
|
-
: readBridgeStatus(installRoot)
|
|
216
|
+
: readBridgeStatus(installRoot, mainExtension)
|
|
210
217
|
replyJson(response, 200, { ok: true, bridge: status })
|
|
211
218
|
}
|
|
@@ -0,0 +1,168 @@
|
|
|
1
|
+
import { PERSONAL_PROFILE_DIRS } from '../../assets/browser-products.mjs'
|
|
2
|
+
import { windowsPowerShellPath } from './windows-system.ts'
|
|
3
|
+
import { execFile } from 'node:child_process'
|
|
4
|
+
import { readFile, readlink } from 'node:fs/promises'
|
|
5
|
+
import { realpathSync } from 'node:fs'
|
|
6
|
+
import { homedir } from 'node:os'
|
|
7
|
+
import { isAbsolute, join, relative, resolve, sep } from 'node:path'
|
|
8
|
+
import { promisify } from 'node:util'
|
|
9
|
+
import type { ChildProcess } from 'node:child_process'
|
|
10
|
+
|
|
11
|
+
export interface ProcessIdentity {
|
|
12
|
+
readonly pid: number
|
|
13
|
+
readonly created: string
|
|
14
|
+
readonly executable: string
|
|
15
|
+
readonly argv: readonly string[]
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
export type ProcessInspector = (pid: number) => Promise<ProcessIdentity | undefined>
|
|
19
|
+
export interface ProcessOwnershipOptions {
|
|
20
|
+
readonly managed: boolean
|
|
21
|
+
readonly inspect?: ProcessInspector
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
const execute = promisify(execFile)
|
|
25
|
+
const windowsInspection = String.raw`
|
|
26
|
+
$ErrorActionPreference='Stop'
|
|
27
|
+
try {
|
|
28
|
+
[Console]::OutputEncoding = New-Object System.Text.UTF8Encoding($false)
|
|
29
|
+
$p=Get-CimInstance Win32_Process -Filter ('ProcessId='+$env:DSH_INSPECT_PID)
|
|
30
|
+
if($null -eq $p -or !$p.ExecutablePath -or !$p.CommandLine -or !$p.CreationDate) { throw 'Process identity is unavailable' }
|
|
31
|
+
@{pid=[int]$p.ProcessId;created=$p.CreationDate.ToUniversalTime().Ticks.ToString();
|
|
32
|
+
executable=$p.ExecutablePath;commandLine=$p.CommandLine} | ConvertTo-Json -Compress
|
|
33
|
+
} catch { [Console]::Error.WriteLine($_.Exception.Message); exit 2 }
|
|
34
|
+
`
|
|
35
|
+
|
|
36
|
+
export function parseWindowsCommandLine(command: string): string[] {
|
|
37
|
+
const argv: string[] = []
|
|
38
|
+
let value = '', quoted = false, started = false
|
|
39
|
+
for (let i = 0; i < command.length; i++) {
|
|
40
|
+
const char = command[i]!
|
|
41
|
+
if ((char === ' ' || char === '\t') && !quoted) {
|
|
42
|
+
if (started) argv.push(value)
|
|
43
|
+
value = ''; started = false
|
|
44
|
+
continue
|
|
45
|
+
}
|
|
46
|
+
started = true
|
|
47
|
+
if (char === '\\') {
|
|
48
|
+
let count = 1
|
|
49
|
+
while (command[i + 1] === '\\') { count++; i++ }
|
|
50
|
+
if (command[i + 1] !== '"') { value += '\\'.repeat(count); continue }
|
|
51
|
+
value += '\\'.repeat(Math.floor(count / 2))
|
|
52
|
+
if (count % 2) { value += '"'; i++; continue }
|
|
53
|
+
i++
|
|
54
|
+
} else if (char !== '"') { value += char; continue }
|
|
55
|
+
if (quoted && command[i + 1] === '"') { value += '"'; i++ }
|
|
56
|
+
else quoted = !quoted
|
|
57
|
+
}
|
|
58
|
+
if (started) argv.push(value)
|
|
59
|
+
return argv
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
export async function inspectProcess(pid: number, diagnose?: (reason: string) => void): Promise<ProcessIdentity | undefined> {
|
|
63
|
+
if (!Number.isSafeInteger(pid) || pid <= 0) return undefined
|
|
64
|
+
try {
|
|
65
|
+
if (process.platform === 'win32') {
|
|
66
|
+
const { stdout } = await execute(windowsPowerShellPath(),
|
|
67
|
+
['-NoProfile', '-NonInteractive', '-EncodedCommand', Buffer.from(windowsInspection, 'utf16le').toString('base64')],
|
|
68
|
+
{ windowsHide: true, timeout: 15000, maxBuffer: 128 * 1024, env: { ...process.env, DSH_INSPECT_PID: String(pid) } })
|
|
69
|
+
const result = JSON.parse(stdout.replace(/^\uFEFF/u, ''))
|
|
70
|
+
if (result.pid !== pid || typeof result.created !== 'string' || !result.created
|
|
71
|
+
|| typeof result.executable !== 'string' || !result.executable
|
|
72
|
+
|| typeof result.commandLine !== 'string' || !result.commandLine) throw new Error('Windows returned an incomplete or mismatched process identity')
|
|
73
|
+
return { pid, created: result.created, executable: result.executable, argv: parseWindowsCommandLine(result.commandLine) }
|
|
74
|
+
}
|
|
75
|
+
if (process.platform === 'linux') {
|
|
76
|
+
const root = `/proc/${pid}`
|
|
77
|
+
const before = await readFile(`${root}/stat`, 'utf8')
|
|
78
|
+
const executable = await readlink(`${root}/exe`)
|
|
79
|
+
const command = await readFile(`${root}/cmdline`, 'utf8')
|
|
80
|
+
const after = await readFile(`${root}/stat`, 'utf8')
|
|
81
|
+
const start = (stat: string): string | undefined => stat.slice(stat.lastIndexOf(')') + 2).split(' ')[19]
|
|
82
|
+
const created = start(before)
|
|
83
|
+
if (!created || created !== start(after) || !command.endsWith('\0')) return undefined
|
|
84
|
+
return { pid, created, executable, argv: command.slice(0, -1).split('\0') }
|
|
85
|
+
}
|
|
86
|
+
} catch (error) { diagnose?.(String(error).slice(-2000)) }
|
|
87
|
+
return undefined
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
function canonical(path: string): string {
|
|
91
|
+
const actual = realpathSync(path)
|
|
92
|
+
return process.platform === 'win32' ? actual.toLowerCase() : actual
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
function personalProfile(path: string): boolean {
|
|
96
|
+
const roots = process.platform === 'win32'
|
|
97
|
+
? PERSONAL_PROFILE_DIRS.win32
|
|
98
|
+
.map(name => join(process.env.LOCALAPPDATA || homedir(), name))
|
|
99
|
+
: process.platform === 'darwin'
|
|
100
|
+
? PERSONAL_PROFILE_DIRS.darwin.map(name => join(homedir(), 'Library', 'Application Support', name))
|
|
101
|
+
: PERSONAL_PROFILE_DIRS.linux.map(name => join(process.env.XDG_CONFIG_HOME || join(homedir(), '.config'), name))
|
|
102
|
+
return roots.some(root => {
|
|
103
|
+
let actual: string
|
|
104
|
+
try { actual = canonical(root) } catch { actual = resolve(root); if (process.platform === 'win32') actual = actual.toLowerCase() }
|
|
105
|
+
const child = relative(actual, path)
|
|
106
|
+
return child === '' || (child !== '..' && !child.startsWith(`..${sep}`) && !isAbsolute(child))
|
|
107
|
+
})
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
function dataDirectory(argv: readonly string[]): string | undefined {
|
|
111
|
+
const values: string[] = []
|
|
112
|
+
for (let i = 1; i < argv.length; i++) {
|
|
113
|
+
const arg = argv[i]!
|
|
114
|
+
if (arg === '--user-data-dir') values.push(argv[++i] ?? '')
|
|
115
|
+
else if (arg.startsWith('--user-data-dir=')) values.push(arg.slice('--user-data-dir='.length))
|
|
116
|
+
}
|
|
117
|
+
return values.length === 1 && values[0] !== '' ? values[0] : undefined
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
export class BrowserProcessOwnership {
|
|
121
|
+
private readonly records = new WeakMap<ChildProcess, { identity: ProcessIdentity; executable: string; directory: string }>()
|
|
122
|
+
|
|
123
|
+
constructor(private readonly executable: string, private readonly directory: string,
|
|
124
|
+
private readonly options: ProcessOwnershipOptions) {}
|
|
125
|
+
|
|
126
|
+
private live(child: ChildProcess): boolean {
|
|
127
|
+
return Number.isSafeInteger(child.pid) && child.exitCode === null && child.signalCode === null
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
async capture(child: ChildProcess): Promise<void> {
|
|
131
|
+
if (!this.options.managed || !this.live(child)) return
|
|
132
|
+
try {
|
|
133
|
+
const record = await (this.options.inspect ?? inspectProcess)(child.pid!)
|
|
134
|
+
if (!record || !this.live(child) || record.pid !== child.pid || !record.created) return
|
|
135
|
+
const directory = canonical(this.directory), argument = dataDirectory(record.argv)
|
|
136
|
+
if (!argument || personalProfile(directory) || canonical(argument) !== directory
|
|
137
|
+
|| canonical(record.executable) !== canonical(this.executable)) return
|
|
138
|
+
this.records.set(child, { identity: record, executable: canonical(record.executable), directory })
|
|
139
|
+
} catch { /* Fail closed. */ }
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
async verify(child: ChildProcess): Promise<boolean> {
|
|
143
|
+
const captured = this.records.get(child)
|
|
144
|
+
if (!captured || !this.live(child)) return false
|
|
145
|
+
const record = captured.identity
|
|
146
|
+
try {
|
|
147
|
+
const current = await (this.options.inspect ?? inspectProcess)(record.pid)
|
|
148
|
+
return this.live(child) && current !== undefined && current.pid === record.pid
|
|
149
|
+
&& current.created === record.created && current.executable === record.executable
|
|
150
|
+
&& JSON.stringify(current.argv) === JSON.stringify(record.argv)
|
|
151
|
+
&& canonical(current.executable) === captured.executable && canonical(this.executable) === captured.executable
|
|
152
|
+
&& canonical(dataDirectory(current.argv) ?? '') === captured.directory && this.ownsDirectory(child)
|
|
153
|
+
} catch { return false }
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
ownsDirectory(child: ChildProcess, path = this.directory): boolean {
|
|
157
|
+
const captured = this.records.get(child)
|
|
158
|
+
try {
|
|
159
|
+
return captured !== undefined && canonical(path) === captured.directory
|
|
160
|
+
&& canonical(this.directory) === captured.directory && !personalProfile(captured.directory)
|
|
161
|
+
} catch { return false }
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
async terminate(child: ChildProcess): Promise<boolean> {
|
|
165
|
+
if (!await this.verify(child) || !this.live(child)) return false
|
|
166
|
+
try { return child.kill() } catch { return false }
|
|
167
|
+
}
|
|
168
|
+
}
|
|
@@ -0,0 +1,187 @@
|
|
|
1
|
+
import { copyFile, lstat, mkdir, readdir, readFile, readlink, rename, rm, rmdir, stat, symlink, writeFile } from 'node:fs/promises'
|
|
2
|
+
import { dirname, join, resolve } from 'node:path'
|
|
3
|
+
import { installedProfileExtension, MAIN_EXTENSION_NAME } from './profile-extension.ts'
|
|
4
|
+
import { MaintenanceRecoveryError } from './maintenance-lifecycle.ts'
|
|
5
|
+
import { runProfileCommand } from './profile-command.ts'
|
|
6
|
+
|
|
7
|
+
type Entry = { path: string } & (
|
|
8
|
+
| { kind: 'missing' | 'directory' | 'file' }
|
|
9
|
+
| { kind: 'link'; target: string; type: 'directory' | 'file' }
|
|
10
|
+
)
|
|
11
|
+
interface CheckpointIO {
|
|
12
|
+
readonly copyFile: typeof copyFile
|
|
13
|
+
readonly symlink: typeof symlink
|
|
14
|
+
readonly readdir: typeof readdir
|
|
15
|
+
readonly reconcile: () => Promise<void>
|
|
16
|
+
}
|
|
17
|
+
const pluginPath = join('node_modules', MAIN_EXTENSION_NAME)
|
|
18
|
+
const manifestPaths = ['package.json', 'pnpm-lock.yaml', join('node_modules', '.modules.yaml')]
|
|
19
|
+
|
|
20
|
+
async function describe(profile: string, path: string, packageEntry = false): Promise<Entry> {
|
|
21
|
+
const source = join(profile, path)
|
|
22
|
+
let info
|
|
23
|
+
try { info = await lstat(source) } catch (error) {
|
|
24
|
+
if ((error as NodeJS.ErrnoException).code === 'ENOENT') return { path, kind: 'missing' }
|
|
25
|
+
throw error
|
|
26
|
+
}
|
|
27
|
+
if (info.isSymbolicLink()) {
|
|
28
|
+
const target = await readlink(source)
|
|
29
|
+
let type: 'directory' | 'file' = 'directory'
|
|
30
|
+
if (!packageEntry) {
|
|
31
|
+
try { type = (await stat(source)).isDirectory() ? 'directory' : 'file' } catch (error) {
|
|
32
|
+
if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
return { path, kind: 'link', target, type }
|
|
36
|
+
}
|
|
37
|
+
return { path, kind: info.isDirectory() ? 'directory' : 'file' }
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
async function inventory(profile: string, io: CheckpointIO): Promise<Entry[]> {
|
|
41
|
+
const entries: Entry[] = []
|
|
42
|
+
for (const name of (await io.readdir(join(profile, 'node_modules'))).sort()) {
|
|
43
|
+
const path = join('node_modules', name), entry = await describe(profile, path, true)
|
|
44
|
+
entries.push(entry)
|
|
45
|
+
if (name.startsWith('@') && entry.kind === 'directory') {
|
|
46
|
+
for (const child of (await io.readdir(join(profile, path))).sort()) entries.push(await describe(profile, join(path, child), true))
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
return entries
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
async function saveProfile(profile: string, before: string, io: CheckpointIO): Promise<{ entries: Entry[]; modules: Entry[] }> {
|
|
53
|
+
const entries: Entry[] = []
|
|
54
|
+
const visit = async (path: string, packageEntry = false): Promise<void> => {
|
|
55
|
+
const entry = await describe(profile, path, packageEntry)
|
|
56
|
+
entries.push(entry)
|
|
57
|
+
const destination = join(before, 'files', path)
|
|
58
|
+
if (entry.kind === 'directory') {
|
|
59
|
+
await mkdir(destination, { recursive: true })
|
|
60
|
+
for (const name of (await io.readdir(join(profile, path))).sort()) await visit(join(path, name))
|
|
61
|
+
} else if (entry.kind === 'file') {
|
|
62
|
+
await mkdir(dirname(destination), { recursive: true })
|
|
63
|
+
await io.copyFile(join(profile, path), destination)
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
if ((await lstat(join(profile, 'node_modules'))).isSymbolicLink()) throw new Error('REINSTALL_CHECKPOINT_LINKED_MODULES: node_modules must be a real directory')
|
|
67
|
+
const modules = await inventory(profile, io)
|
|
68
|
+
for (const path of manifestPaths) await visit(path)
|
|
69
|
+
await visit(pluginPath, true)
|
|
70
|
+
await writeFile(join(before, 'metadata.json'), JSON.stringify({ version: 2, entries, modules }))
|
|
71
|
+
return { entries, modules }
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
async function restoreLink(profile: string, entry: Extract<Entry, { kind: 'link' }>, io: CheckpointIO): Promise<void> {
|
|
75
|
+
const destination = join(profile, entry.path)
|
|
76
|
+
await mkdir(dirname(destination), { recursive: true })
|
|
77
|
+
try {
|
|
78
|
+
await io.symlink(entry.type === 'directory' && process.platform === 'win32' ? resolve(dirname(destination), entry.target) : entry.target,
|
|
79
|
+
destination, entry.type === 'directory' ? 'junction' : 'file')
|
|
80
|
+
} catch (error) { throw new Error(`REINSTALL_LINK_RESTORE_FAILED: ${entry.type} link ${entry.path}: ${String(error)}`) }
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
async function restoreFiles(profile: string, before: string, entries: readonly Entry[], io: CheckpointIO): Promise<void> {
|
|
84
|
+
const errors: string[] = []
|
|
85
|
+
for (const path of [...manifestPaths, pluginPath]) {
|
|
86
|
+
try { await rm(join(profile, path), { recursive: true, force: true }) } catch (error) { errors.push(`${path}: ${String(error)}`) }
|
|
87
|
+
}
|
|
88
|
+
for (const entry of entries) {
|
|
89
|
+
try {
|
|
90
|
+
const destination = join(profile, entry.path)
|
|
91
|
+
if (entry.kind === 'directory') await mkdir(destination, { recursive: true })
|
|
92
|
+
else if (entry.kind === 'file') {
|
|
93
|
+
await mkdir(dirname(destination), { recursive: true })
|
|
94
|
+
await io.copyFile(join(before, 'files', entry.path), destination)
|
|
95
|
+
} else if (entry.kind === 'link') await restoreLink(profile, entry, io)
|
|
96
|
+
} catch (error) { errors.push(`${entry.path}: ${String(error)}`) }
|
|
97
|
+
}
|
|
98
|
+
if (errors.length > 0) throw new Error(errors.join('; '))
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
function unrelated(entries: readonly Entry[]): string {
|
|
102
|
+
return JSON.stringify(entries.filter(entry => entry.path !== pluginPath && !manifestPaths.includes(entry.path) && entry.path !== join('node_modules', '.ignored')))
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
async function recoverModules(profile: string, modules: readonly Entry[], io: CheckpointIO): Promise<void> {
|
|
106
|
+
const ignored = join('node_modules', '.ignored')
|
|
107
|
+
const recover = async (entry: Entry): Promise<void> => {
|
|
108
|
+
if (entry.path === pluginPath || manifestPaths.includes(entry.path) || entry.path === ignored) return
|
|
109
|
+
const current = await describe(profile, entry.path, true)
|
|
110
|
+
if (JSON.stringify(current) === JSON.stringify(entry)) return
|
|
111
|
+
if (current.kind !== 'missing') throw new Error(`REINSTALL_UNRELATED_PACKAGE_CHANGED: ${entry.path}`)
|
|
112
|
+
if (entry.kind === 'link') await restoreLink(profile, entry, io)
|
|
113
|
+
else {
|
|
114
|
+
const relative = entry.path.slice('node_modules'.length + 1), parts = relative.split(/[\\/]/)
|
|
115
|
+
for (let i = 0; i < parts.length; i++) {
|
|
116
|
+
const parent = await describe(profile, join(ignored, ...parts.slice(0, i)), true)
|
|
117
|
+
if (parent.kind !== 'directory') throw new Error(`REINSTALL_ORPHAN_RECOVERY_FAILED: unsafe or missing .ignored path for ${entry.path}`)
|
|
118
|
+
}
|
|
119
|
+
await mkdir(dirname(join(profile, entry.path)), { recursive: true })
|
|
120
|
+
await rename(join(profile, ignored, relative), join(profile, entry.path))
|
|
121
|
+
for (let i = parts.length - 1; i >= 0; i--) {
|
|
122
|
+
if (i === 0 && modules.some(entry => entry.path === ignored)) break
|
|
123
|
+
try { await rmdir(join(profile, ignored, ...parts.slice(0, i))) } catch (error) {
|
|
124
|
+
if (!['ENOENT', 'ENOTEMPTY'].includes((error as NodeJS.ErrnoException).code ?? '')) throw error
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
const errors: string[] = []
|
|
130
|
+
for (const entry of modules) {
|
|
131
|
+
try { await recover(entry) } catch (error) { errors.push(String(error)) }
|
|
132
|
+
}
|
|
133
|
+
if (errors.length > 0) throw new Error(errors.join('; '))
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
async function verifyProfile(home: string): Promise<void> {
|
|
137
|
+
await installedProfileExtension(home)
|
|
138
|
+
const script = `const {createRequire} = await import('node:module'); const {readFile} = await import('node:fs/promises'); await readFile(createRequire(process.argv[1]).resolve(${JSON.stringify(MAIN_EXTENSION_NAME)}));`
|
|
139
|
+
const isElectron = process.versions.electron !== undefined
|
|
140
|
+
const argv = [...(isElectron ? ['--expose-internals'] : []), '--input-type=module', '--eval', script, '--', join(home, 'profiles', 'desktop', 'package.json')]
|
|
141
|
+
const env: NodeJS.ProcessEnv = { ...process.env, ...(isElectron ? { ELECTRON_RUN_AS_NODE: '1', ELECTRON_NO_ASAR: '1' } : {}) }
|
|
142
|
+
const result = await runProfileCommand(process.execPath, argv, env, 10_000)
|
|
143
|
+
if (result.code !== 0) throw new Error(`REINSTALL_PROFILE_RESOLUTION_FAILED: ${result.output}`)
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
/** The checkpoint lives beside the staged worker, never inside the removable profile. */
|
|
147
|
+
export async function withProfileCheckpoint<T>(home: string, directory: string, operation: () => Promise<T>, options: Pick<CheckpointIO, 'reconcile'> & Partial<CheckpointIO>): Promise<T> {
|
|
148
|
+
const profile = join(home, 'profiles', 'desktop'), before = join(directory, 'profile-before')
|
|
149
|
+
const io = { copyFile, symlink, readdir, ...options }
|
|
150
|
+
let saved: { entries: Entry[]; modules: Entry[] }
|
|
151
|
+
let created = false
|
|
152
|
+
try {
|
|
153
|
+
await verifyProfile(home)
|
|
154
|
+
await mkdir(before)
|
|
155
|
+
created = true
|
|
156
|
+
saved = await saveProfile(profile, before, io)
|
|
157
|
+
} catch (error) {
|
|
158
|
+
if (created) await rm(before, { recursive: true, force: true })
|
|
159
|
+
throw new Error(`REINSTALL_CHECKPOINT_FAILED: profile unchanged: ${String(error)}`)
|
|
160
|
+
}
|
|
161
|
+
try {
|
|
162
|
+
const result = await operation()
|
|
163
|
+
if (unrelated(await inventory(profile, io)) !== unrelated(saved.modules)) throw new Error('REINSTALL_UNRELATED_PACKAGES_CHANGED: package manager changed unrelated entries; restoring the profile')
|
|
164
|
+
await verifyProfile(home)
|
|
165
|
+
return result
|
|
166
|
+
} catch (failure) {
|
|
167
|
+
const attempt = async (restore: () => Promise<void>): Promise<string | undefined> => {
|
|
168
|
+
try { await restore(); return undefined } catch (error) { return String(error) }
|
|
169
|
+
}
|
|
170
|
+
let filesError = await attempt(() => restoreFiles(profile, before, saved.entries, io))
|
|
171
|
+
let modulesError = await attempt(() => recoverModules(profile, saved.modules, io))
|
|
172
|
+
let resolutionError = await attempt(() => verifyProfile(home))
|
|
173
|
+
let reconcileError: string | undefined
|
|
174
|
+
if (filesError === undefined && (modulesError !== undefined || resolutionError !== undefined)) {
|
|
175
|
+
reconcileError = await attempt(() => io.reconcile())
|
|
176
|
+
filesError = await attempt(() => restoreFiles(profile, before, saved.entries, io))
|
|
177
|
+
modulesError = await attempt(() => recoverModules(profile, saved.modules, io))
|
|
178
|
+
resolutionError = await attempt(() => verifyProfile(home))
|
|
179
|
+
}
|
|
180
|
+
const restored = filesError === undefined && resolutionError === undefined
|
|
181
|
+
? 'REINSTALL_PROFILE_RESTORED: profile manifests and plugin restored directly and plugin resolution verified'
|
|
182
|
+
: 'Profile restoration could not be fully verified'
|
|
183
|
+
const errors = [filesError, modulesError, resolutionError, reconcileError].filter(error => error !== undefined)
|
|
184
|
+
if (errors.length > 0) throw new MaintenanceRecoveryError(`REINSTALL_ROLLBACK_FAILED: ${errors.join('; ')}; ${restored}; original failure: ${String(failure)}; checkpoint: ${before}`)
|
|
185
|
+
throw new Error(`${String(failure)}; ${restored}`)
|
|
186
|
+
}
|
|
187
|
+
}
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
import { execFile, spawn } from 'node:child_process'
|
|
2
|
+
import { dirname, join } from 'node:path'
|
|
3
|
+
import { windowsPowerShellPath } from './windows-system.ts'
|
|
4
|
+
import { MaintenanceRecoveryError } from './maintenance-lifecycle.ts'
|
|
5
|
+
|
|
6
|
+
/** Terminate the complete package-manager tree before allowing a profile rollback. */
|
|
7
|
+
export async function runProfileCommand(command: string, args: readonly string[], environment: NodeJS.ProcessEnv, timeoutMs = 60_000): Promise<{ code: number; output: string }> {
|
|
8
|
+
const taskkill = process.platform === 'win32' ? join(dirname(dirname(dirname(windowsPowerShellPath(environment)))), 'taskkill.exe') : undefined
|
|
9
|
+
return await new Promise((resolve, reject) => {
|
|
10
|
+
const child = spawn(command, [...args], { env: environment, windowsHide: true, shell: false, detached: process.platform !== 'win32', stdio: ['ignore', 'pipe', 'pipe'] })
|
|
11
|
+
let output = '', timedOut = false
|
|
12
|
+
let termination: Promise<void> | undefined
|
|
13
|
+
const append = (data: Buffer): void => { output = (output + data.toString()).slice(-1_048_576) }
|
|
14
|
+
child.stdout.on('data', append)
|
|
15
|
+
child.stderr.on('data', append)
|
|
16
|
+
const timer = setTimeout(() => {
|
|
17
|
+
timedOut = true
|
|
18
|
+
if (child.pid === undefined) return
|
|
19
|
+
const pid = child.pid
|
|
20
|
+
termination = new Promise((done, reject) => {
|
|
21
|
+
if (taskkill !== undefined) {
|
|
22
|
+
execFile(taskkill, ['/PID', String(pid), '/T', '/F'], { windowsHide: true, timeout: 10_000 }, error => { if (error) reject(error); else done() })
|
|
23
|
+
} else {
|
|
24
|
+
try { process.kill(-pid, 'SIGKILL'); done() } catch (error) {
|
|
25
|
+
if ((error as NodeJS.ErrnoException).code === 'ESRCH') done()
|
|
26
|
+
else reject(error)
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
})
|
|
30
|
+
void termination.catch(error => {
|
|
31
|
+
child.unref()
|
|
32
|
+
child.stdout.destroy()
|
|
33
|
+
child.stderr.destroy()
|
|
34
|
+
reject(new MaintenanceRecoveryError(`${output}\nREINSTALL_ROLLBACK_FAILED: cannot confirm package-manager termination: ${String(error)}`))
|
|
35
|
+
})
|
|
36
|
+
}, timeoutMs)
|
|
37
|
+
child.once('error', error => { clearTimeout(timer); resolve({ code: 1, output: `REINSTALL_COMMAND_START_FAILED: ${error.message}` }) })
|
|
38
|
+
child.once('close', async (code, signal) => {
|
|
39
|
+
clearTimeout(timer)
|
|
40
|
+
try { await termination } catch (error) {
|
|
41
|
+
reject(new MaintenanceRecoveryError(`${output}\nREINSTALL_ROLLBACK_FAILED: cannot confirm package-manager termination: ${String(error)}`)); return
|
|
42
|
+
}
|
|
43
|
+
resolve({ code: timedOut ? 1 : code ?? 1, output: `${output}${timedOut ? `\nREINSTALL_COMMAND_TIMEOUT: exceeded ${timeoutMs}ms; package-manager tree terminated` : signal === null ? '' : `\nREINSTALL_COMMAND_SIGNAL: ${signal}`}`.trim() })
|
|
44
|
+
})
|
|
45
|
+
})
|
|
46
|
+
}
|