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,174 @@
|
|
|
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
|
+
private readonly executable: string
|
|
123
|
+
private readonly directory: string
|
|
124
|
+
private readonly options: ProcessOwnershipOptions
|
|
125
|
+
constructor(executable: string, directory: string,
|
|
126
|
+
options: ProcessOwnershipOptions) {
|
|
127
|
+
this.executable = executable
|
|
128
|
+
this.directory = directory
|
|
129
|
+
this.options = options
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
private live(child: ChildProcess): boolean {
|
|
133
|
+
return Number.isSafeInteger(child.pid) && child.exitCode === null && child.signalCode === null
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
async capture(child: ChildProcess): Promise<void> {
|
|
137
|
+
if (!this.options.managed || !this.live(child)) return
|
|
138
|
+
try {
|
|
139
|
+
const record = await (this.options.inspect ?? inspectProcess)(child.pid!)
|
|
140
|
+
if (!record || !this.live(child) || record.pid !== child.pid || !record.created) return
|
|
141
|
+
const directory = canonical(this.directory), argument = dataDirectory(record.argv)
|
|
142
|
+
if (!argument || personalProfile(directory) || canonical(argument) !== directory
|
|
143
|
+
|| canonical(record.executable) !== canonical(this.executable)) return
|
|
144
|
+
this.records.set(child, { identity: record, executable: canonical(record.executable), directory })
|
|
145
|
+
} catch { /* Fail closed. */ }
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
async verify(child: ChildProcess): Promise<boolean> {
|
|
149
|
+
const captured = this.records.get(child)
|
|
150
|
+
if (!captured || !this.live(child)) return false
|
|
151
|
+
const record = captured.identity
|
|
152
|
+
try {
|
|
153
|
+
const current = await (this.options.inspect ?? inspectProcess)(record.pid)
|
|
154
|
+
return this.live(child) && current !== undefined && current.pid === record.pid
|
|
155
|
+
&& current.created === record.created && current.executable === record.executable
|
|
156
|
+
&& JSON.stringify(current.argv) === JSON.stringify(record.argv)
|
|
157
|
+
&& canonical(current.executable) === captured.executable && canonical(this.executable) === captured.executable
|
|
158
|
+
&& canonical(dataDirectory(current.argv) ?? '') === captured.directory && this.ownsDirectory(child)
|
|
159
|
+
} catch { return false }
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
ownsDirectory(child: ChildProcess, path = this.directory): boolean {
|
|
163
|
+
const captured = this.records.get(child)
|
|
164
|
+
try {
|
|
165
|
+
return captured !== undefined && canonical(path) === captured.directory
|
|
166
|
+
&& canonical(this.directory) === captured.directory && !personalProfile(captured.directory)
|
|
167
|
+
} catch { return false }
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
async terminate(child: ChildProcess): Promise<boolean> {
|
|
171
|
+
if (!await this.verify(child) || !this.live(child)) return false
|
|
172
|
+
try { return child.kill() } catch { return false }
|
|
173
|
+
}
|
|
174
|
+
}
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* One shared definition of process liveness.
|
|
3
|
+
*
|
|
4
|
+
* Signal 0 performs the permission and existence checks and delivers nothing, so it is safe to
|
|
5
|
+
* call on a pid we only read from a file. `EPERM` means the process exists and belongs to
|
|
6
|
+
* someone else, which is still "alive" for the endpoint reader and the profile sweeper alike.
|
|
7
|
+
* @module dsh-browser/browser-electron/process
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* Whether a process with this pid exists, without signalling it.
|
|
12
|
+
* @param pid - the process id to test; a non-integer or non-positive value is never alive.
|
|
13
|
+
* @returns whether that process exists.
|
|
14
|
+
*/
|
|
15
|
+
export function pidAlive(pid: number): boolean {
|
|
16
|
+
if (!Number.isSafeInteger(pid) || pid <= 0) return false
|
|
17
|
+
try {
|
|
18
|
+
process.kill(pid, 0)
|
|
19
|
+
return true
|
|
20
|
+
} catch (error) {
|
|
21
|
+
return (error as NodeJS.ErrnoException)?.code === 'EPERM'
|
|
22
|
+
}
|
|
23
|
+
}
|
|
@@ -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,47 @@
|
|
|
1
|
+
import { PROFILE_COMMAND_TIMEOUT_MS } from '../../assets/browser-policy.mjs'
|
|
2
|
+
import { execFile, spawn } from 'node:child_process'
|
|
3
|
+
import { dirname, join } from 'node:path'
|
|
4
|
+
import { windowsPowerShellPath } from './windows-system.ts'
|
|
5
|
+
import { MaintenanceRecoveryError } from './maintenance-lifecycle.ts'
|
|
6
|
+
|
|
7
|
+
/** Terminate the complete package-manager tree before allowing a profile rollback. */
|
|
8
|
+
export async function runProfileCommand(command: string, args: readonly string[], environment: NodeJS.ProcessEnv, timeoutMs = PROFILE_COMMAND_TIMEOUT_MS): Promise<{ code: number; output: string }> {
|
|
9
|
+
const taskkill = process.platform === 'win32' ? join(dirname(dirname(dirname(windowsPowerShellPath(environment)))), 'taskkill.exe') : undefined
|
|
10
|
+
return await new Promise((resolve, reject) => {
|
|
11
|
+
const child = spawn(command, [...args], { env: environment, windowsHide: true, shell: false, detached: process.platform !== 'win32', stdio: ['ignore', 'pipe', 'pipe'] })
|
|
12
|
+
let output = '', timedOut = false
|
|
13
|
+
let termination: Promise<void> | undefined
|
|
14
|
+
const append = (data: Buffer): void => { output = (output + data.toString()).slice(-1_048_576) }
|
|
15
|
+
child.stdout.on('data', append)
|
|
16
|
+
child.stderr.on('data', append)
|
|
17
|
+
const timer = setTimeout(() => {
|
|
18
|
+
timedOut = true
|
|
19
|
+
if (child.pid === undefined) return
|
|
20
|
+
const pid = child.pid
|
|
21
|
+
termination = new Promise((done, reject) => {
|
|
22
|
+
if (taskkill !== undefined) {
|
|
23
|
+
execFile(taskkill, ['/PID', String(pid), '/T', '/F'], { windowsHide: true, timeout: 10_000 }, error => { if (error) reject(error); else done() })
|
|
24
|
+
} else {
|
|
25
|
+
try { process.kill(-pid, 'SIGKILL'); done() } catch (error) {
|
|
26
|
+
if ((error as NodeJS.ErrnoException).code === 'ESRCH') done()
|
|
27
|
+
else reject(error)
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
})
|
|
31
|
+
void termination.catch(error => {
|
|
32
|
+
child.unref()
|
|
33
|
+
child.stdout.destroy()
|
|
34
|
+
child.stderr.destroy()
|
|
35
|
+
reject(new MaintenanceRecoveryError(`${output}\nREINSTALL_ROLLBACK_FAILED: cannot confirm package-manager termination: ${String(error)}`))
|
|
36
|
+
})
|
|
37
|
+
}, timeoutMs)
|
|
38
|
+
child.once('error', error => { clearTimeout(timer); resolve({ code: 1, output: `REINSTALL_COMMAND_START_FAILED: ${error.message}` }) })
|
|
39
|
+
child.once('close', async (code, signal) => {
|
|
40
|
+
clearTimeout(timer)
|
|
41
|
+
try { await termination } catch (error) {
|
|
42
|
+
reject(new MaintenanceRecoveryError(`${output}\nREINSTALL_ROLLBACK_FAILED: cannot confirm package-manager termination: ${String(error)}`)); return
|
|
43
|
+
}
|
|
44
|
+
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() })
|
|
45
|
+
})
|
|
46
|
+
})
|
|
47
|
+
}
|
|
@@ -0,0 +1,129 @@
|
|
|
1
|
+
/** Profile-only extension maintenance through the installation's supported dsh plugin command. */
|
|
2
|
+
import { createHash } from 'node:crypto'
|
|
3
|
+
import { constants } from 'node:fs'
|
|
4
|
+
import { readFile, access, stat } from 'node:fs/promises'
|
|
5
|
+
import { join, resolve, isAbsolute } from 'node:path'
|
|
6
|
+
import type { BridgeAction, BridgeActionResult } from './bridge-install.ts'
|
|
7
|
+
import { BridgeConnection } from './bridge-connection.ts'
|
|
8
|
+
import { desktopPaths, readAsarFile } from './desktop-identity.ts'
|
|
9
|
+
import { runProfileCommand } from './profile-command.ts'
|
|
10
|
+
|
|
11
|
+
export const MAIN_EXTENSION_UNSUPPORTED = 'DESKTOP_MAIN_EXTENSION_UNSUPPORTED'
|
|
12
|
+
export const MAIN_EXTENSION_NAME = 'dsh-builtin-browser'
|
|
13
|
+
export interface MainExtensionStatus {
|
|
14
|
+
readonly state: 'not-installed' | 'pending-restart' | 'loaded' | 'failed'
|
|
15
|
+
readonly version?: string
|
|
16
|
+
readonly loadedAt?: string
|
|
17
|
+
readonly code?: string
|
|
18
|
+
}
|
|
19
|
+
export interface InstalledExtension { readonly version: string; readonly build: string }
|
|
20
|
+
|
|
21
|
+
export async function readHostExtensionStatus(home: string): Promise<MainExtensionStatus | undefined> {
|
|
22
|
+
let connection: BridgeConnection | undefined
|
|
23
|
+
try {
|
|
24
|
+
const endpoint = JSON.parse(await readFile(join(home, 'dsh-builtin-browser-bridge.json'), 'utf8')) as { port: number; token: string; pid: number }
|
|
25
|
+
if (!Number.isSafeInteger(endpoint.pid) || endpoint.pid <= 0 || !Number.isInteger(endpoint.port) || endpoint.port <= 0 || endpoint.port > 65535
|
|
26
|
+
|| typeof endpoint.token !== 'string' || endpoint.token === '') return undefined
|
|
27
|
+
process.kill(endpoint.pid, 0)
|
|
28
|
+
connection = new BridgeConnection(endpoint)
|
|
29
|
+
const answer = await connection.call({ op: 'version' }, 1_000)
|
|
30
|
+
const status = answer.mainExtension as MainExtensionStatus | undefined
|
|
31
|
+
if (answer.ok !== true || answer.homeId !== extensionHomeId(home) || status === null || typeof status !== 'object'
|
|
32
|
+
|| !['not-installed', 'pending-restart', 'loaded', 'failed'].includes(status.state)) return undefined
|
|
33
|
+
return { state: status.state, ...typeof status.version === 'string' ? { version: status.version } : {},
|
|
34
|
+
...typeof status.loadedAt === 'string' ? { loadedAt: status.loadedAt } : {}, ...typeof status.code === 'string' ? { code: status.code } : {} }
|
|
35
|
+
} catch { return undefined } finally { connection?.close() }
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
export function extensionHomeId(home: string): string {
|
|
39
|
+
const path = resolve(home)
|
|
40
|
+
return createHash('sha256').update(process.platform === 'win32' ? path.toLowerCase() : path).digest('hex')
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
export async function installedProfileExtension(home: string): Promise<InstalledExtension> {
|
|
44
|
+
const directory = join(home, 'profiles', 'desktop', 'node_modules', MAIN_EXTENSION_NAME)
|
|
45
|
+
const pkg = JSON.parse(await readFile(join(directory, 'package.json'), 'utf8')) as { name?: unknown; version?: unknown; dsh?: { desktop?: { main?: unknown } } }
|
|
46
|
+
if (pkg.name !== MAIN_EXTENSION_NAME || typeof pkg.version !== 'string' || pkg.dsh?.desktop?.main !== './desktop-bridge/main.mjs') {
|
|
47
|
+
throw new Error('EXTENSION_ENTRY_INVALID')
|
|
48
|
+
}
|
|
49
|
+
const build = createHash('sha256').update(await readFile(join(directory, 'desktop-bridge/plugin-browser-bridge.js'))).digest('hex')
|
|
50
|
+
return { version: pkg.version, build }
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
export async function profileDependencySpec(home: string): Promise<string> {
|
|
54
|
+
const manifest = JSON.parse(await readFile(join(home, 'profiles', 'desktop', 'package.json'), 'utf8')) as { dependencies?: Record<string, unknown> }
|
|
55
|
+
const dependency = manifest.dependencies?.[MAIN_EXTENSION_NAME]
|
|
56
|
+
if (typeof dependency !== 'string' || dependency.trim() === '') throw Object.assign(new Error('The Desktop profile has no dsh-builtin-browser dependency to reinstall.'), { code: 'REINSTALL_DEPENDENCY_MISSING' })
|
|
57
|
+
return dependency
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
export async function profileRuntimeDirectory(root: string): Promise<string> {
|
|
61
|
+
const directory = join(desktopPaths(root).resources, 'runtime')
|
|
62
|
+
const pnpm = join(directory, 'primary-runtime', 'dependencies', 'pnpm', 'bin', 'pnpm.mjs')
|
|
63
|
+
try {
|
|
64
|
+
await access(pnpm, constants.R_OK)
|
|
65
|
+
if (!(await stat(pnpm)).isFile()) throw new Error('Not a regular file')
|
|
66
|
+
} catch {
|
|
67
|
+
throw Object.assign(new Error(`The Desktop bundled package manager is missing or unreadable: ${pnpm}`), { code: 'REINSTALL_RUNTIME_MISSING' })
|
|
68
|
+
}
|
|
69
|
+
return directory
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
export async function profileExtensionCommand(action: BridgeAction, root: string, home: string, capturedSpec?: string): Promise<readonly string[]> {
|
|
73
|
+
if (!isAbsolute(root) || !isAbsolute(home)) throw new Error('invalid Desktop profile location')
|
|
74
|
+
const profile = join(home, 'profiles', 'desktop')
|
|
75
|
+
const dependency = action === 'install' ? capturedSpec ?? await profileDependencySpec(home) : undefined
|
|
76
|
+
if (action === 'install' && (typeof dependency !== 'string' || dependency.trim() === '')) throw new Error('REINSTALL_DEPENDENCY_MISSING')
|
|
77
|
+
const resources = desktopPaths(root).resources
|
|
78
|
+
const entry = 'dsh/node_modules/@deepseek-ai/dsh-desktop-host/lib/cli.js'
|
|
79
|
+
const archive = join(resources, 'app.asar')
|
|
80
|
+
let cli = join(archive, entry)
|
|
81
|
+
if (readAsarFile(archive, entry) === undefined) {
|
|
82
|
+
try { await access(cli) } catch { cli = join(resources, 'app', entry); await access(cli) }
|
|
83
|
+
}
|
|
84
|
+
const args = [cli, 'plugin', '--profile', 'desktop']
|
|
85
|
+
if (action === 'uninstall') return [...args, 'remove', MAIN_EXTENSION_NAME]
|
|
86
|
+
let spec = String(dependency)
|
|
87
|
+
if (/^(?:file|link):/.test(spec)) {
|
|
88
|
+
const colon = spec.indexOf(':')
|
|
89
|
+
spec = spec.slice(0, colon + 1) + resolve(profile, spec.slice(colon + 1))
|
|
90
|
+
}
|
|
91
|
+
return [...args, 'add', /^(?:file|link):/.test(spec) ? spec : `${MAIN_EXTENSION_NAME}@${spec}`]
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
export async function repairProfileExtension(action: BridgeAction, root: string, home: string, run: (
|
|
95
|
+
command: string, argv: readonly string[], environment: NodeJS.ProcessEnv, timeout?: number,
|
|
96
|
+
) => Promise<{ code: number; output: string }>, capturedSpec?: string): Promise<BridgeActionResult> {
|
|
97
|
+
const support = await profileRuntimeDirectory(root)
|
|
98
|
+
const invocation = await profileExtensionCommand(action, root, home, capturedSpec)
|
|
99
|
+
const packedCli = invocation[0].replaceAll('\\', '/').includes('/app.asar/')
|
|
100
|
+
const script = `process.env.ELECTRON_NO_ASAR = '1'; import { dirname, resolve } from 'node:path'; import { pathToFileURL } from 'node:url'; const { runDesktopCli } = await import(pathToFileURL(process.argv[1]).href); const support = ${JSON.stringify(support)}; await (runDesktopCli.length >= 2 ? runDesktopCli(resolve(dirname(process.argv[1]), '../../../..'), support) : runDesktopCli(support));`
|
|
101
|
+
const argv = ['--expose-internals', '--input-type=module', '--eval', script, '--', ...invocation]
|
|
102
|
+
const command = desktopPaths(root).executable
|
|
103
|
+
const environment = profileEnvironment(home, packedCli)
|
|
104
|
+
const result = await run(command, argv, environment, 300_000)
|
|
105
|
+
return { ok: result.code === 0, code: result.code, output: result.output.slice(-20_000), command: [command, ...argv].map(value => JSON.stringify(value)).join(' '), restarted: false }
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
function profileEnvironment(home: string, packedCli = false): NodeJS.ProcessEnv {
|
|
109
|
+
const env: NodeJS.ProcessEnv = { ...process.env }
|
|
110
|
+
for (const key of Object.keys(env)) {
|
|
111
|
+
if (key.toUpperCase() === 'ELECTRON_NO_ASAR') delete env[key]
|
|
112
|
+
}
|
|
113
|
+
// `CI` makes pnpm non-interactive. Without it a reconcile answered a supply-chain prompt with
|
|
114
|
+
// "?" and exited non-zero, the maintenance transaction rolled back, and the bridge stayed
|
|
115
|
+
// "已失效" — a repair path that could not repair. The reporter is pinned for the same reason:
|
|
116
|
+
// an unattended command must produce a log, not a question.
|
|
117
|
+
return { ...env, DSH_HOME: home, ELECTRON_RUN_AS_NODE: '1', ...(packedCli ? {} : { ELECTRON_NO_ASAR: '1' }),
|
|
118
|
+
CI: 'true', npm_config_reporter: 'append-only', PNPM_CONFIG_REPORTER: 'append-only',
|
|
119
|
+
npm_config_ignore_scripts: 'true', npm_config_auto_install_peers: 'false',
|
|
120
|
+
PNPM_CONFIG_IGNORE_SCRIPTS: 'true', PNPM_CONFIG_AUTO_INSTALL_PEERS: 'false' }
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
/** Best-effort reconciliation after the checkpoint has restored the profile files and plugin. */
|
|
124
|
+
export async function reconcileProfile(root: string, home: string, run: typeof runProfileCommand = runProfileCommand): Promise<void> {
|
|
125
|
+
const runtime = await profileRuntimeDirectory(root)
|
|
126
|
+
const result = await run(desktopPaths(root).executable, ['--expose-internals', join(runtime, 'primary-runtime', 'dependencies', 'pnpm', 'bin', 'pnpm.mjs'),
|
|
127
|
+
'--dir', join(home, 'profiles', 'desktop'), 'install', '--frozen-lockfile', '--ignore-scripts', '--config.auto-install-peers=false'], profileEnvironment(home), 300_000)
|
|
128
|
+
if (result.code !== 0) throw new Error(`REINSTALL_RECONCILE_FAILED: ${result.output}`)
|
|
129
|
+
}
|