dsh-builtin-browser 1.0.3 → 1.1.0
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 +16 -1
- 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/desktop-bridge/desktop-identity.json +10 -2
- package/desktop-bridge/install.mjs +28 -2
- package/docs/issue-replies-2026-11-28.md +141 -0
- package/dsh-host-patch/apply.mjs +1 -1
- package/dsh-host-patch/rc3.json +4 -4
- package/dsh-host-patch/rc5.json +4 -4
- package/dsh-host-patch/v023-alpha2.json +2 -2
- package/lib/browser-electron/bridge-status.js +24 -1
- package/lib/browser-electron/desktop-identity.js +47 -8
- package/lib/client.js +2 -1
- package/native-host/install.mjs +5 -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 +412 -0
- package/src/browser-electron/desktop-bridge-host.ts +253 -0
- package/src/browser-electron/desktop-identity.ts +400 -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 +2773 -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,121 @@
|
|
|
1
|
+
/** Explicit Web maintenance for the sidebar bundle selected by DSH's client module registry. */
|
|
2
|
+
import { accessSync, constants, existsSync, readFileSync, realpathSync, statSync } from 'node:fs'
|
|
3
|
+
import { dirname, join } from 'node:path'
|
|
4
|
+
import type { IncomingMessage, ServerResponse } from 'node:http'
|
|
5
|
+
import type { HostPatchResult } from './bridge-install.ts'
|
|
6
|
+
import { sameOrigin } from './settings-route.ts'
|
|
7
|
+
import { isDirectLoopback } from './authenticated-route.ts'
|
|
8
|
+
import { readJsonBody } from './http-body.ts'
|
|
9
|
+
import { replyJson } from './json-reply.ts'
|
|
10
|
+
|
|
11
|
+
import { HOST_PATCH_ROUTE } from '../../assets/browser-policy.mjs'
|
|
12
|
+
export { HOST_PATCH_ROUTE }
|
|
13
|
+
|
|
14
|
+
const sidebar = '@deepseek-ai/dsh-client-ui-sidebar-right'
|
|
15
|
+
|
|
16
|
+
/** The registry owns the exact npm or source-checkout bundle served by this Host. */
|
|
17
|
+
export interface ServedClientModules {
|
|
18
|
+
clientPath(id: string): string | undefined
|
|
19
|
+
rebuilt?(id: string): unknown
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
interface PatchState extends HostPatchResult {
|
|
23
|
+
readonly surface: 'web' | 'desktop' | 'tauri'
|
|
24
|
+
readonly canInstall: boolean
|
|
25
|
+
readonly canRestore: boolean
|
|
26
|
+
readonly restartRequired: boolean
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/** Bind to the live optional service, never resolve a second copy relative to the plugin. */
|
|
30
|
+
export function servedClientModules(value: unknown): ServedClientModules | undefined {
|
|
31
|
+
if (value !== null && typeof value === 'object' && 'clientPath' in value && typeof value.clientPath === 'function') {
|
|
32
|
+
return value as ServedClientModules
|
|
33
|
+
}
|
|
34
|
+
return undefined
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/** Locate only the package whose lib/client.js the running registry actually advertises. */
|
|
38
|
+
export function servedSidebarPackage(modules: ServedClientModules | undefined): string {
|
|
39
|
+
const path = modules?.clientPath(sidebar)
|
|
40
|
+
if (path === undefined) throw new Error('The running DSH client registry has no sidebar bundle; host patch maintenance is unavailable.')
|
|
41
|
+
const file = realpathSync(path)
|
|
42
|
+
const directory = dirname(dirname(file))
|
|
43
|
+
const manifest = JSON.parse(readFileSync(join(directory, 'package.json'), 'utf8'))
|
|
44
|
+
if (manifest.name !== sidebar || realpathSync(join(directory, 'lib/client.js')) !== file) {
|
|
45
|
+
throw new Error('The served sidebar bundle is not the supported package lib/client.js.')
|
|
46
|
+
}
|
|
47
|
+
return directory
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/** Same authenticated, same-origin, local-only maintenance admission as Desktop settings. */
|
|
51
|
+
export function createHostPatchMaintenance(deps: {
|
|
52
|
+
readonly modules: () => ServedClientModules | undefined
|
|
53
|
+
readonly desktop: () => boolean
|
|
54
|
+
/** The electron-rs runtime directory of the DSH Tauri hosting this process, if any. */
|
|
55
|
+
readonly tauri?: () => string | undefined
|
|
56
|
+
}): (request: IncomingMessage, response: ServerResponse) => Promise<void> {
|
|
57
|
+
let running = false
|
|
58
|
+
return async (request, response) => {
|
|
59
|
+
if (request.method !== 'GET' && request.method !== 'POST') { replyJson(response, 405, { ok: false, error: 'method-not-allowed' }); return }
|
|
60
|
+
if (!sameOrigin(request, request.method === 'POST') || !isDirectLoopback(request)) {
|
|
61
|
+
replyJson(response, 403, { ok: false, error: 'same-origin-local-request-required' }); return
|
|
62
|
+
}
|
|
63
|
+
const tauri = deps.tauri?.()
|
|
64
|
+
if (tauri === undefined && deps.desktop()) {
|
|
65
|
+
replyJson(response, request.method === 'GET' ? 200 : 409, { ok: request.method === 'GET', hostPatch: { surface: 'desktop', status: 'absent', canInstall: false, canRestore: false,
|
|
66
|
+
restartRequired: false, reason: 'Use Desktop bridge maintenance to change host files after Desktop exits.' } }); return
|
|
67
|
+
}
|
|
68
|
+
let directory: string
|
|
69
|
+
const modules = deps.modules()
|
|
70
|
+
const surface = tauri === undefined ? 'web' : 'tauri'
|
|
71
|
+
const target = tauri === undefined ? 'lib/client.js' : 'runtime/browser.cjs'
|
|
72
|
+
try { directory = tauri ?? servedSidebarPackage(modules) }
|
|
73
|
+
catch (error) {
|
|
74
|
+
replyJson(response, request.method === 'GET' ? 200 : 409, { ok: request.method === 'GET', hostPatch: {
|
|
75
|
+
surface: 'web', status: 'anchors mismatch', canInstall: false, canRestore: false, restartRequired: false, reason: String(error),
|
|
76
|
+
} }); return
|
|
77
|
+
}
|
|
78
|
+
const patcher = await import(new URL('../../dsh-host-patch/apply.mjs', import.meta.url).href)
|
|
79
|
+
const read = (): PatchState => {
|
|
80
|
+
const result: HostPatchResult = patcher.hostPatchStatus(directory)
|
|
81
|
+
let writable = true
|
|
82
|
+
let reason = result.reason
|
|
83
|
+
try {
|
|
84
|
+
for (const path of [dirname(join(directory, target)), join(directory, target)]) {
|
|
85
|
+
if ((statSync(path).mode & 0o222) === 0) throw new Error('read-only permissions')
|
|
86
|
+
accessSync(path, constants.W_OK)
|
|
87
|
+
}
|
|
88
|
+
} catch (error) { writable = false; reason = `The ${surface === 'web' ? 'served sidebar package' : 'DSH Tauri runtime'} is not writable: ` + String(error) }
|
|
89
|
+
const needed = typeof patcher.hostPatchNeeded === 'function' ? patcher.hostPatchNeeded(directory) : undefined
|
|
90
|
+
return { ...result, ...(reason === undefined ? {} : { reason }), surface,
|
|
91
|
+
...(needed === undefined ? {} : { needed }),
|
|
92
|
+
canInstall: writable && result.status === 'absent',
|
|
93
|
+
canRestore: writable && result.status === 'applied' && existsSync(join(directory, `${target}.before-dsh-host-patch`)),
|
|
94
|
+
restartRequired: false }
|
|
95
|
+
}
|
|
96
|
+
if (request.method === 'GET') { replyJson(response, 200, { ok: true, hostPatch: read() }); return }
|
|
97
|
+
if (running) { replyJson(response, 409, { ok: false, error: 'host patch maintenance is already running' }); return }
|
|
98
|
+
let action: 'install' | 'restore'
|
|
99
|
+
try {
|
|
100
|
+
const input = await readJsonBody<{ action?: unknown }>(request, 4096)
|
|
101
|
+
if (input?.action !== 'install' && input?.action !== 'restore') throw new Error('action must be install or restore')
|
|
102
|
+
action = input.action
|
|
103
|
+
} catch (error) { replyJson(response, 400, { ok: false, error: String(error) }); return }
|
|
104
|
+
const before = read()
|
|
105
|
+
if (action === 'install' ? !before.canInstall : !before.canRestore) {
|
|
106
|
+
replyJson(response, 409, { ok: false, hostPatch: before, error: before.reason ?? 'This action is not available for the served sidebar package.' }); return
|
|
107
|
+
}
|
|
108
|
+
running = true
|
|
109
|
+
try {
|
|
110
|
+
const result: HostPatchResult = action === 'install' ? patcher.applyHostPatch(directory) : patcher.restoreHostPatch(directory)
|
|
111
|
+
const ok = result.status === (action === 'install' ? 'applied' : 'absent')
|
|
112
|
+
let restartRequired = ok && result.changed === true
|
|
113
|
+
let reason = result.reason
|
|
114
|
+
if (restartRequired && surface === 'web' && typeof modules?.rebuilt === 'function') {
|
|
115
|
+
try { modules.rebuilt(sidebar); restartRequired = false }
|
|
116
|
+
catch (error) { reason = 'Files changed, but DSH could not refresh its bundle cache: ' + String(error) }
|
|
117
|
+
}
|
|
118
|
+
replyJson(response, ok ? 200 : 409, { ok, hostPatch: { ...read(), ...result, ...(reason === undefined ? {} : { reason }), restartRequired } })
|
|
119
|
+
} finally { running = false }
|
|
120
|
+
}
|
|
121
|
+
}
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Bounded request bodies shared by every plugin HTTP route. Keeping one implementation means the
|
|
3
|
+
* byte limit, UTF-8 decoding and oversize behaviour cannot drift between the settings and the
|
|
4
|
+
* maintenance endpoints.
|
|
5
|
+
* @module dsh-browser/browser-electron/http-body
|
|
6
|
+
*/
|
|
7
|
+
import type { IncomingMessage } from 'node:http'
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* Read a body as UTF-8 text. Chunks are collected as Buffers and decoded once: setting an
|
|
11
|
+
* encoding on the stream and concatenating `String(chunk)` corrupts a multi-byte character that
|
|
12
|
+
* happens to be split across two TCP chunks.
|
|
13
|
+
* @param request - the incoming request.
|
|
14
|
+
* @param limit - maximum accepted bytes.
|
|
15
|
+
* @returns the body text.
|
|
16
|
+
*/
|
|
17
|
+
export async function readTextBody(request: IncomingMessage, limit = 64 * 1024): Promise<string> {
|
|
18
|
+
const chunks: Buffer[] = []
|
|
19
|
+
let size = 0
|
|
20
|
+
for await (const chunk of request) {
|
|
21
|
+
const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(String(chunk))
|
|
22
|
+
size += buffer.length
|
|
23
|
+
if (size > limit) {
|
|
24
|
+
request.destroy()
|
|
25
|
+
throw new Error(`request body exceeds ${limit} bytes`)
|
|
26
|
+
}
|
|
27
|
+
chunks.push(buffer)
|
|
28
|
+
}
|
|
29
|
+
return Buffer.concat(chunks).toString('utf8')
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/**
|
|
33
|
+
* Read a bounded binary body. The reference-import route takes ZIP bytes directly instead of a
|
|
34
|
+
* base64 JSON wrapper: a wrapper would inflate the limit by a third and add a decoding step that
|
|
35
|
+
* can hide an oversize body until after it has been allocated.
|
|
36
|
+
* @param request - the incoming request.
|
|
37
|
+
* @param limit - maximum accepted bytes.
|
|
38
|
+
* @returns the raw body.
|
|
39
|
+
*/
|
|
40
|
+
export async function readBinaryBody(request: IncomingMessage, limit = 32 * 1024 * 1024): Promise<Buffer> {
|
|
41
|
+
const chunks: Buffer[] = []
|
|
42
|
+
let size = 0
|
|
43
|
+
for await (const chunk of request) {
|
|
44
|
+
const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(String(chunk))
|
|
45
|
+
size += buffer.length
|
|
46
|
+
if (size > limit) {
|
|
47
|
+
request.destroy()
|
|
48
|
+
throw new Error(`request body exceeds ${limit} bytes`)
|
|
49
|
+
}
|
|
50
|
+
chunks.push(buffer)
|
|
51
|
+
}
|
|
52
|
+
return Buffer.concat(chunks)
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/**
|
|
56
|
+
* Read and parse a JSON body. An empty body is an empty object, matching the settings route's
|
|
57
|
+
* long-standing behaviour.
|
|
58
|
+
* @param request - the incoming request.
|
|
59
|
+
* @param limit - maximum accepted bytes.
|
|
60
|
+
* @returns the parsed value.
|
|
61
|
+
*/
|
|
62
|
+
export async function readJsonBody<T>(request: IncomingMessage, limit = 64 * 1024): Promise<T> {
|
|
63
|
+
const text = await readTextBody(request, limit)
|
|
64
|
+
return JSON.parse(text === '' ? '{}' : text) as T
|
|
65
|
+
}
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* One JSON reply, written the same way by every route this plugin serves.
|
|
3
|
+
*
|
|
4
|
+
* Its own module rather than a helper inside one route file: there are four endpoints now, and the
|
|
5
|
+
* second one that needed this had to import it from the live-view route — which reads as though the
|
|
6
|
+
* readiness endpoints belong to the preview. They do not; only the header rules are shared.
|
|
7
|
+
*
|
|
8
|
+
* The header set is the substance, not boilerplate:
|
|
9
|
+
* - `content-length` computed from the bytes actually written, so a proxy cannot truncate;
|
|
10
|
+
* - `no-store` because every answer here is a reading of the current moment;
|
|
11
|
+
* - `nosniff` + a same-origin resource policy, because these bodies name paths and pids.
|
|
12
|
+
* @module dsh-browser/browser-electron/json-reply
|
|
13
|
+
*/
|
|
14
|
+
import type { OutgoingHttpHeaders, ServerResponse } from 'node:http'
|
|
15
|
+
|
|
16
|
+
/**
|
|
17
|
+
* Write one JSON body with no caching and no sniffing.
|
|
18
|
+
* @param response - the response to write.
|
|
19
|
+
* @param status - the HTTP status.
|
|
20
|
+
* @param body - anything JSON-serialisable.
|
|
21
|
+
*/
|
|
22
|
+
/**
|
|
23
|
+
* Write an already-serialised JSON body with caller-supplied headers.
|
|
24
|
+
*
|
|
25
|
+
* Routes do not all need the same header set: readiness answers carry length and sniffing
|
|
26
|
+
* headers, while the settings route has always returned only a content type and no-store.
|
|
27
|
+
* Sharing the write keeps those exact header sets from drifting into each other.
|
|
28
|
+
* @param response - the response to write.
|
|
29
|
+
* @param status - the HTTP status.
|
|
30
|
+
* @param text - the serialised body.
|
|
31
|
+
* @param headers - the exact header set this route has always sent.
|
|
32
|
+
*/
|
|
33
|
+
export function writeJsonText(response: ServerResponse, status: number, text: string, headers: OutgoingHttpHeaders): void {
|
|
34
|
+
response.writeHead(status, headers)
|
|
35
|
+
response.end(text)
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
export function replyJson(response: ServerResponse, status: number, body: unknown): void {
|
|
39
|
+
const text = JSON.stringify(body)
|
|
40
|
+
writeJsonText(response, status, text, {
|
|
41
|
+
'content-type': 'application/json; charset=utf-8',
|
|
42
|
+
'content-length': Buffer.byteLength(text),
|
|
43
|
+
'cache-control': 'no-store, private',
|
|
44
|
+
'x-content-type-options': 'nosniff',
|
|
45
|
+
'cross-origin-resource-policy': 'same-origin',
|
|
46
|
+
})
|
|
47
|
+
}
|
|
@@ -0,0 +1,166 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Start a local maintenance coordinator outside the requesting app's tree: through WMI on Windows,
|
|
3
|
+
* as a detached session leader on macOS (which survives the app quitting).
|
|
4
|
+
* This primitive only creates the requested process; its caller owns maintenance authorization,
|
|
5
|
+
* the coordinator's plan, readiness handshake and normal application shutdown.
|
|
6
|
+
* @module dsh-browser/browser-electron/maintenance-broker
|
|
7
|
+
*/
|
|
8
|
+
import { execFile, spawn } from 'node:child_process'
|
|
9
|
+
import { statSync } from 'node:fs'
|
|
10
|
+
import { isAbsolute, posix, win32 } from 'node:path'
|
|
11
|
+
import { encodePowerShellScript, windowsPowerShellPath } from './windows-system.ts'
|
|
12
|
+
|
|
13
|
+
export interface MaintenanceBrokerOptions {
|
|
14
|
+
readonly runtimePath: string
|
|
15
|
+
readonly args: readonly string[]
|
|
16
|
+
readonly cwd: string
|
|
17
|
+
/** Overrides for the explicitly inherited environment; undefined removes a variable. */
|
|
18
|
+
readonly environment?: Readonly<Record<string, string | undefined>>
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
export interface MaintenanceBrokerExecution {
|
|
22
|
+
readonly windowsHide: true
|
|
23
|
+
readonly shell: false
|
|
24
|
+
readonly encoding: 'utf8'
|
|
25
|
+
readonly timeout: number
|
|
26
|
+
readonly maxBuffer: number
|
|
27
|
+
readonly env: NodeJS.ProcessEnv
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
export type MaintenanceBrokerExecutor = (
|
|
31
|
+
file: string,
|
|
32
|
+
args: readonly string[],
|
|
33
|
+
options: MaintenanceBrokerExecution,
|
|
34
|
+
) => Promise<{ readonly stdout: string; readonly stderr: string }>
|
|
35
|
+
|
|
36
|
+
export interface MaintenanceBrokerDeps {
|
|
37
|
+
/** Tests supply a fake executor; the real broker is prohibited inside the test runner. */
|
|
38
|
+
readonly execFile?: MaintenanceBrokerExecutor
|
|
39
|
+
readonly platform?: NodeJS.Platform
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
export interface MaintenanceBrokerResult {
|
|
43
|
+
readonly pid: number
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/** Quote one argument using the Windows C runtime's command-line decoding rules. */
|
|
47
|
+
export function quoteWin32Argument(value: string): string {
|
|
48
|
+
if (typeof value !== 'string' || value.includes('\0')) throw new Error('a Windows process argument must be a string without NUL')
|
|
49
|
+
// Backslashes are literal except immediately before a quote or the closing quote. At those
|
|
50
|
+
// positions each slash must be doubled, and an embedded quote receives one additional slash.
|
|
51
|
+
return '"' + value.replace(/(\\*)"/g, '$1$1\\"').replace(/(\\+)$/, '$1$1') + '"'
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
function absolutePath(value: string, label: string): string {
|
|
55
|
+
if (typeof value !== 'string' || value.includes('\0') || value.includes('"')
|
|
56
|
+
|| !/^(?:[A-Za-z]:[\\/]|\\\\[^\\/]+[\\/][^\\/]+)/.test(value)) {
|
|
57
|
+
throw new Error(`${label} must be a fully qualified Windows path without NUL or quotes`)
|
|
58
|
+
}
|
|
59
|
+
return win32.normalize(value)
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/** Apply Windows' case-insensitive variable names before passing one explicit environment. */
|
|
63
|
+
function inheritEnvironment(overrides: MaintenanceBrokerOptions['environment']): NodeJS.ProcessEnv {
|
|
64
|
+
const environment = { ...process.env }
|
|
65
|
+
for (const [key, value] of Object.entries(overrides ?? {})) {
|
|
66
|
+
if (key === '' || /[=\0]/.test(key) || (value !== undefined && (typeof value !== 'string' || value.includes('\0')))) {
|
|
67
|
+
throw new Error('maintenance environment names and values must be valid Windows environment strings')
|
|
68
|
+
}
|
|
69
|
+
for (const existing of Object.keys(environment)) if (existing.toUpperCase() === key.toUpperCase()) delete environment[existing]
|
|
70
|
+
if (value !== undefined) environment[key] = value
|
|
71
|
+
}
|
|
72
|
+
return environment
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
function underTest(environment: NodeJS.ProcessEnv): boolean {
|
|
76
|
+
return Object.entries(environment).some(([key, value]) =>
|
|
77
|
+
(key.toUpperCase() === 'DSH_BROWSER_TEST' && value === '1')
|
|
78
|
+
|| (key.toUpperCase() === 'NODE_TEST_CONTEXT' && value !== undefined))
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
const defaultExecutor: MaintenanceBrokerExecutor = (file, args, options) => new Promise((resolve, reject) => {
|
|
82
|
+
execFile(file, [...args], options, (error, stdout, stderr) => {
|
|
83
|
+
if (error !== null) {
|
|
84
|
+
const reason = stderr.trim() || (error as NodeJS.ErrnoException).code || 'PowerShell did not complete'
|
|
85
|
+
reject(new Error(`Windows maintenance broker failed: ${String(reason).slice(-1_000)}`))
|
|
86
|
+
} else resolve({ stdout, stderr })
|
|
87
|
+
})
|
|
88
|
+
})
|
|
89
|
+
|
|
90
|
+
/** macOS: a new session (setsid) with no inherited stdio, so the coordinator outlives Desktop. */
|
|
91
|
+
async function launchDetached(options: MaintenanceBrokerOptions, environment: NodeJS.ProcessEnv): Promise<MaintenanceBrokerResult> {
|
|
92
|
+
for (const [label, value] of [['runtimePath', options.runtimePath], ['cwd', options.cwd]] as const) {
|
|
93
|
+
if (typeof value !== 'string' || value.includes('\0') || !isAbsolute(value)) throw new Error(`${label} must be an absolute path without NUL`)
|
|
94
|
+
}
|
|
95
|
+
const runtimePath = posix.normalize(options.runtimePath)
|
|
96
|
+
const cwd = posix.normalize(options.cwd)
|
|
97
|
+
if (!statSync(runtimePath).isFile()) throw new Error('the maintenance runtime is not a file')
|
|
98
|
+
if (!statSync(cwd).isDirectory()) throw new Error('the maintenance working directory is not a directory')
|
|
99
|
+
if (!Array.isArray(options.args)) throw new Error('maintenance arguments must be an array')
|
|
100
|
+
return await new Promise((resolve, reject) => {
|
|
101
|
+
const child = spawn(runtimePath, [...options.args], { cwd, env: environment, detached: true, stdio: 'ignore', shell: false })
|
|
102
|
+
child.once('error', error => { reject(new Error(`maintenance broker failed: ${String(error)}`)) })
|
|
103
|
+
child.once('spawn', () => {
|
|
104
|
+
child.unref()
|
|
105
|
+
if (!Number.isSafeInteger(child.pid) || Number(child.pid) <= 0) reject(new Error('the maintenance broker returned no valid process id'))
|
|
106
|
+
else resolve({ pid: Number(child.pid) })
|
|
107
|
+
})
|
|
108
|
+
})
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
/**
|
|
112
|
+
* Create a hidden, independent local process. No shell evaluates runtime paths or arguments.
|
|
113
|
+
* WMI receives an explicit environment copied from this process, including any plan overrides;
|
|
114
|
+
* it therefore does not accidentally inherit the provider service's unrelated environment.
|
|
115
|
+
*/
|
|
116
|
+
export async function launchMaintenanceBroker(
|
|
117
|
+
options: MaintenanceBrokerOptions,
|
|
118
|
+
deps: MaintenanceBrokerDeps = {},
|
|
119
|
+
): Promise<MaintenanceBrokerResult> {
|
|
120
|
+
const environment = inheritEnvironment(options.environment)
|
|
121
|
+
if (deps.execFile === undefined && (underTest(process.env) || underTest(environment))) {
|
|
122
|
+
throw new Error('the real Windows maintenance broker is disabled in tests; inject a fake executor')
|
|
123
|
+
}
|
|
124
|
+
const platform = deps.platform ?? process.platform
|
|
125
|
+
if (platform === 'darwin') return await launchDetached(options, environment)
|
|
126
|
+
if (platform !== 'win32') throw new Error('the maintenance broker requires Windows or macOS')
|
|
127
|
+
const runtimePath = absolutePath(options.runtimePath, 'runtimePath')
|
|
128
|
+
const cwd = absolutePath(options.cwd, 'cwd')
|
|
129
|
+
if (!statSync(runtimePath).isFile()) throw new Error('the maintenance runtime is not a file')
|
|
130
|
+
if (!statSync(cwd).isDirectory()) throw new Error('the maintenance working directory is not a directory')
|
|
131
|
+
if (!Array.isArray(options.args)) throw new Error('maintenance arguments must be an array')
|
|
132
|
+
const commandLine = [runtimePath, ...options.args].map(quoteWin32Argument).join(' ')
|
|
133
|
+
if (commandLine.length >= 32_767) throw new Error('the maintenance command exceeds the Windows command-line limit')
|
|
134
|
+
const payload = Buffer.from(JSON.stringify({ commandLine, cwd }), 'utf8').toString('base64')
|
|
135
|
+
// The only interpolated script data is Base64 JSON. The full environment is inherited by
|
|
136
|
+
// execFile, then read as data here rather than embedded in the PowerShell command line.
|
|
137
|
+
const script = `$ErrorActionPreference = 'Stop'
|
|
138
|
+
[Console]::OutputEncoding = New-Object System.Text.UTF8Encoding($false)
|
|
139
|
+
try {
|
|
140
|
+
$plan = [System.Text.Encoding]::UTF8.GetString([System.Convert]::FromBase64String('${payload}')) | ConvertFrom-Json
|
|
141
|
+
$environment = [string[]]@([System.Environment]::GetEnvironmentVariables('Process').GetEnumerator() | ForEach-Object { [string]$_.Key + '=' + [string]$_.Value })
|
|
142
|
+
$startup = New-CimInstance -Namespace root/cimv2 -ClassName Win32_ProcessStartup -ClientOnly -Property @{ ShowWindow = [uint16]0; CreateFlags = [uint32]1024; EnvironmentVariables = $environment }
|
|
143
|
+
$result = Invoke-CimMethod -Namespace root/cimv2 -ClassName Win32_Process -MethodName Create -Arguments @{ CommandLine = [string]$plan.commandLine; CurrentDirectory = [string]$plan.cwd; ProcessStartupInformation = $startup }
|
|
144
|
+
@{ code = [uint32]$result.ReturnValue; pid = [uint32]$result.ProcessId } | ConvertTo-Json -Compress
|
|
145
|
+
} catch {
|
|
146
|
+
[Console]::Error.WriteLine($_.Exception.Message)
|
|
147
|
+
exit 1
|
|
148
|
+
}
|
|
149
|
+
`
|
|
150
|
+
const encoded = encodePowerShellScript(script)
|
|
151
|
+
const powershellPath = windowsPowerShellPath()
|
|
152
|
+
if (encoded.length + powershellPath.length + 100 >= 32_767) throw new Error('the encoded maintenance broker command exceeds the Windows command-line limit')
|
|
153
|
+
const result = await (deps.execFile ?? defaultExecutor)(powershellPath,
|
|
154
|
+
['-NoLogo', '-NoProfile', '-NonInteractive', '-EncodedCommand', encoded],
|
|
155
|
+
{ windowsHide: true, shell: false, encoding: 'utf8', timeout: 30_000, maxBuffer: 64_000, env: environment })
|
|
156
|
+
let record: { code?: unknown; pid?: unknown }
|
|
157
|
+
try { record = JSON.parse(result.stdout.replace(/^\uFEFF/, '').trim()) as typeof record } catch {
|
|
158
|
+
throw new Error('the Windows maintenance broker returned an unreadable result')
|
|
159
|
+
}
|
|
160
|
+
if (record === null || typeof record !== 'object' || !Number.isSafeInteger(record.code) || Number(record.code) < 0) {
|
|
161
|
+
throw new Error('the Windows maintenance broker returned an invalid result')
|
|
162
|
+
}
|
|
163
|
+
if (record.code !== 0) throw new Error(`Windows maintenance broker refused process creation (WMI code ${String(record.code)})`)
|
|
164
|
+
if (!Number.isSafeInteger(record.pid) || Number(record.pid) <= 0) throw new Error('the Windows maintenance broker returned no valid process id')
|
|
165
|
+
return { pid: Number(record.pid) }
|
|
166
|
+
}
|
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
/** Explicit bridge maintenance lifecycle, independent of the Desktop-owned HTTP request. */
|
|
2
|
+
import type { BridgeAction, BridgeActionResult } from './bridge-install.ts'
|
|
3
|
+
|
|
4
|
+
export type MaintenancePhase = 'armed' | 'closing' | 'installing' | 'restarting' | 'verifying' | 'completed' | 'cancelled' | 'failed'
|
|
5
|
+
export type MaintenanceAction = BridgeAction | 'reinstall'
|
|
6
|
+
|
|
7
|
+
export class MaintenanceRecoveryError extends Error {}
|
|
8
|
+
|
|
9
|
+
export interface MaintenanceState {
|
|
10
|
+
readonly phase: MaintenancePhase
|
|
11
|
+
readonly action: MaintenanceAction
|
|
12
|
+
readonly at: string
|
|
13
|
+
readonly ok?: boolean
|
|
14
|
+
readonly restarted?: boolean
|
|
15
|
+
readonly pid?: number
|
|
16
|
+
readonly error?: string
|
|
17
|
+
readonly progressError?: string
|
|
18
|
+
readonly output?: string
|
|
19
|
+
readonly hostPatch?: BridgeActionResult['hostPatch']
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
/** Effects are supplied by the independent worker; tests cannot close or start an application. */
|
|
23
|
+
export interface MaintenanceLifecycleDeps {
|
|
24
|
+
/** Invoke the verified Desktop's own Quit menu item. Never confirm active-task dialogs. */
|
|
25
|
+
readonly requestQuit: () => Promise<void>
|
|
26
|
+
/** Resolve only once every GUI/helper process belonging to this installation has exited. */
|
|
27
|
+
readonly waitUntilClosed: () => Promise<void>
|
|
28
|
+
/** The existing installer retains its own identity, ancestry and running-process checks. */
|
|
29
|
+
readonly maintain: () => Promise<BridgeActionResult>
|
|
30
|
+
/** Reopen exactly the verified installation after it has exited. */
|
|
31
|
+
readonly restart: () => Promise<number>
|
|
32
|
+
/** Installation verifies the new authenticated bridge; uninstall verifies the process. */
|
|
33
|
+
readonly verify: (pid: number, action: MaintenanceAction) => Promise<void>
|
|
34
|
+
readonly publish: (state: MaintenanceState) => Promise<void>
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/**
|
|
38
|
+
* A cancelled/failed quit never reaches the installer. After a confirmed exit, reopen Desktop even
|
|
39
|
+
* when maintenance fails, and retain that failure instead of reporting a successful installation.
|
|
40
|
+
*/
|
|
41
|
+
export async function runMaintenanceLifecycle(action: MaintenanceAction, deps: MaintenanceLifecycleDeps): Promise<MaintenanceState> {
|
|
42
|
+
let closed = false
|
|
43
|
+
let restarted = false
|
|
44
|
+
let pid: number | undefined
|
|
45
|
+
let outcome: BridgeActionResult | undefined
|
|
46
|
+
let publicationFailure: unknown
|
|
47
|
+
const publish = async (phase: MaintenancePhase, extra: Partial<MaintenanceState> = {}): Promise<MaintenanceState> => {
|
|
48
|
+
const state: MaintenanceState = { phase, action, at: new Date().toISOString(), ...extra }
|
|
49
|
+
try { await deps.publish(state) } catch (error) {
|
|
50
|
+
// Arming must be durable before any quit is requested. Later status I/O must never
|
|
51
|
+
// prevent reopening a Desktop that already exited normally.
|
|
52
|
+
if (phase === 'armed') throw error
|
|
53
|
+
publicationFailure ??= error
|
|
54
|
+
console.error(`[dsh-browser maintenance] cannot publish ${phase} progress: ${String(error)}`)
|
|
55
|
+
}
|
|
56
|
+
return publicationFailure === undefined ? state : { ...state, progressError: String(publicationFailure) }
|
|
57
|
+
}
|
|
58
|
+
await publish('armed')
|
|
59
|
+
try {
|
|
60
|
+
await deps.requestQuit()
|
|
61
|
+
await publish('closing')
|
|
62
|
+
await deps.waitUntilClosed()
|
|
63
|
+
closed = true
|
|
64
|
+
} catch (error) {
|
|
65
|
+
return await publish('cancelled', { ok: false, restarted: false, error: String(error) })
|
|
66
|
+
}
|
|
67
|
+
let failure: unknown
|
|
68
|
+
try {
|
|
69
|
+
await publish('installing')
|
|
70
|
+
outcome = await deps.maintain()
|
|
71
|
+
if (!outcome.ok) throw new Error(outcome.output || 'bridge maintenance failed')
|
|
72
|
+
} catch (error) { failure = error }
|
|
73
|
+
try {
|
|
74
|
+
// `closed` is set only by the successful closed-process barrier, never by a timeout.
|
|
75
|
+
if (!closed) throw new Error('Desktop exit was not confirmed')
|
|
76
|
+
await publish('restarting')
|
|
77
|
+
pid = await deps.restart()
|
|
78
|
+
if (!Number.isSafeInteger(pid) || pid <= 0) throw new Error('Desktop restart did not return a valid process')
|
|
79
|
+
restarted = true
|
|
80
|
+
await publish('verifying', { pid, restarted })
|
|
81
|
+
await deps.verify(pid, failure === undefined ? action : 'uninstall')
|
|
82
|
+
} catch (error) {
|
|
83
|
+
failure = failure === undefined ? error : new Error(`${String(failure)}; Desktop recovery: ${String(error)}`)
|
|
84
|
+
}
|
|
85
|
+
const details = { restarted, ...pid === undefined ? {} : { pid }, ...outcome?.output ? { output: outcome.output } : {},
|
|
86
|
+
...publicationFailure === undefined ? {} : { progressError: String(publicationFailure) },
|
|
87
|
+
...outcome?.hostPatch === undefined ? {} : { hostPatch: outcome.hostPatch } }
|
|
88
|
+
return failure === undefined
|
|
89
|
+
? await publish('completed', { ...details, ok: true })
|
|
90
|
+
: await publish('failed', { ...details, ok: false, error: String(failure) })
|
|
91
|
+
}
|
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
/** Authenticated explicit maintenance protocol; older hosts cannot mistake it for direct install. */
|
|
2
|
+
import type { IncomingMessage, ServerResponse } from 'node:http'
|
|
3
|
+
import { sameOrigin } from './settings-route.ts'
|
|
4
|
+
import { isDirectLoopback } from './authenticated-route.ts'
|
|
5
|
+
import { replyJson } from './json-reply.ts'
|
|
6
|
+
import { readJsonBody } from './http-body.ts'
|
|
7
|
+
import type { AutomaticMaintenanceJob, AutomaticMaintenanceOptions } from './automatic-maintenance.ts'
|
|
8
|
+
|
|
9
|
+
import { AUTOMATIC_MAINTENANCE_ROUTE } from '../../assets/browser-policy.mjs'
|
|
10
|
+
export { AUTOMATIC_MAINTENANCE_ROUTE }
|
|
11
|
+
export interface AutomaticMaintenanceRouteDeps {
|
|
12
|
+
readonly supported: () => boolean
|
|
13
|
+
/** How Desktop is asked to quit: `menu` waits for the panel to open the native menu, `self` needs nothing from it. */
|
|
14
|
+
readonly quit?: () => 'menu' | 'self'
|
|
15
|
+
readonly read: () => AutomaticMaintenanceJob | undefined
|
|
16
|
+
readonly start: (action: 'reinstall', options?: AutomaticMaintenanceOptions) => Promise<AutomaticMaintenanceJob>
|
|
17
|
+
/** Commit only after the accepted response has been flushed to the client. */
|
|
18
|
+
readonly commit?: (id: string) => Promise<void>
|
|
19
|
+
/** True while the legacy bridge-action route is running an installer. */
|
|
20
|
+
readonly busy?: () => boolean
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/** Register behind the host's signed-session authentication, as with settings writes. */
|
|
24
|
+
export function createAutomaticMaintenanceHandler(deps: AutomaticMaintenanceRouteDeps): (request: IncomingMessage, response: ServerResponse) => Promise<void> {
|
|
25
|
+
let starting = false
|
|
26
|
+
return async (request, response) => {
|
|
27
|
+
if (request.method !== 'GET' && request.method !== 'POST') { replyJson(response, 405, { ok: false, error: 'method-not-allowed' }); return }
|
|
28
|
+
if (!sameOrigin(request, request.method === 'POST')) { replyJson(response, 403, { ok: false, error: 'not-same-origin' }); return }
|
|
29
|
+
if (!isDirectLoopback(request)) { replyJson(response, 403, { ok: false, error: 'local-request-required' }); return }
|
|
30
|
+
if (request.method === 'GET') {
|
|
31
|
+
const job = deps.read()
|
|
32
|
+
replyJson(response, 200, { ok: true, protocol: 1, supported: deps.supported(), ...job === undefined ? {} : { job } })
|
|
33
|
+
return
|
|
34
|
+
}
|
|
35
|
+
if (!deps.supported()) { replyJson(response, 409, { ok: false, error: 'automatic bridge maintenance requires DSH Desktop on Windows or macOS' }); return }
|
|
36
|
+
let action: 'reinstall'
|
|
37
|
+
let locale: 'zh' | 'en' | undefined
|
|
38
|
+
try {
|
|
39
|
+
const value = await readJsonBody<{ action?: unknown; locale?: unknown; mode?: unknown; hostStatus?: unknown }>(request, 4096)
|
|
40
|
+
if (value?.action !== 'reinstall') throw new Error('action must be reinstall')
|
|
41
|
+
if (value.mode !== undefined || value.hostStatus !== undefined) throw new Error('mode and hostStatus are no longer supported')
|
|
42
|
+
if (value.locale !== undefined && value.locale !== 'zh' && value.locale !== 'en') throw new Error('locale must be zh or en')
|
|
43
|
+
action = value.action
|
|
44
|
+
locale = value.locale
|
|
45
|
+
} catch (error) { replyJson(response, 400, { ok: false, error: String(error) }); return }
|
|
46
|
+
if (starting || deps.busy?.() === true) { replyJson(response, 409, { ok: false, error: 'bridge maintenance is already starting' }); return }
|
|
47
|
+
starting = true
|
|
48
|
+
try {
|
|
49
|
+
const options = { ...locale === undefined ? {} : { locale } }
|
|
50
|
+
const job = await deps.start(action, Object.keys(options).length === 0 ? undefined : options)
|
|
51
|
+
if (deps.commit !== undefined) {
|
|
52
|
+
let fired = false
|
|
53
|
+
const commitOnce = (): void => {
|
|
54
|
+
if (fired) return
|
|
55
|
+
fired = true
|
|
56
|
+
void deps.commit?.(job.id).catch(error => { console.error('dsh-builtin-browser: bridge maintenance commit failed:', String(error)) })
|
|
57
|
+
}
|
|
58
|
+
// A client that refreshes or disconnects may fire `close` without `finish`; the worker
|
|
59
|
+
// must be committed (or explicitly cancelled) on either path, exactly once.
|
|
60
|
+
response.once('finish', commitOnce)
|
|
61
|
+
response.once('close', commitOnce)
|
|
62
|
+
}
|
|
63
|
+
replyJson(response, 202, { ok: true, accepted: true, protocol: 1, quit: deps.quit?.() ?? 'menu', job })
|
|
64
|
+
} catch (error) {
|
|
65
|
+
replyJson(response, 409, { ok: false, error: String(error), ...(error instanceof Error && 'code' in error ? { code: error.code } : {}) })
|
|
66
|
+
} finally { starting = false }
|
|
67
|
+
}
|
|
68
|
+
}
|