dsh-builtin-browser 0.5.2 → 0.5.3
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 +103 -0
- package/README.en.md +68 -68
- package/README.md +63 -92
- package/client.js +79 -10
- package/desktop-bridge/desktop-identity.json +9 -0
- package/desktop-bridge/install.mjs +220 -1
- package/docs/README.md +1 -1
- package/docs/architecture.md +1 -1
- package/docs/limitations.md +19 -1
- package/docs/tool-reference.md +2 -1
- package/lib/browser-electron/bridge-status.d.ts +5 -3
- package/lib/browser-electron/bridge-status.js +25 -8
- package/lib/browser-electron/desktop-identity.d.ts +58 -0
- package/lib/browser-electron/desktop-identity.js +236 -0
- package/lib/browser-electron/electron-provision.d.ts +59 -0
- package/lib/browser-electron/electron-provision.js +164 -0
- package/lib/browser-electron/entry.js +12 -0
- package/lib/browser-electron/host-main.js +68 -14
- package/lib/browser-electron/provider.d.ts +35 -2
- package/lib/browser-electron/provider.js +19 -4
- package/lib/browser-electron/remote-host.d.ts +3 -3
- package/lib/browser-electron/remote-host.js +25 -11
- package/lib/browser-electron/settings-store.d.ts +19 -0
- package/lib/browser-electron/settings-store.js +5 -1
- package/package.json +2 -3
- package/src/browser-electron/bridge-status.ts +28 -9
- package/src/browser-electron/desktop-identity.ts +260 -0
- package/src/browser-electron/electron-provision.ts +195 -0
- package/src/browser-electron/entry.ts +12 -0
- package/src/browser-electron/host-main.ts +62 -12
- package/src/browser-electron/provider.ts +47 -6
- package/src/browser-electron/remote-host.ts +26 -12
- package/src/browser-electron/settings-store.ts +24 -1
- package/src/types/electron-shim.d.ts +8 -0
|
@@ -738,7 +738,7 @@ export class ElectronBrowserProvider {
|
|
|
738
738
|
signal?.throwIfAborted();
|
|
739
739
|
const timeoutMs = 10_000;
|
|
740
740
|
try {
|
|
741
|
-
await withTimeout(present(handle, s.label), timeoutMs, signal, `browser: presenting the page view timed out after ${timeoutMs}ms`);
|
|
741
|
+
await withTimeout(present(handle, s.label, { quiet: this.isQuiet() }), timeoutMs, signal, `browser: presenting the page view timed out after ${timeoutMs}ms`);
|
|
742
742
|
this.showActive(s);
|
|
743
743
|
}
|
|
744
744
|
catch (error) {
|
|
@@ -2632,13 +2632,18 @@ export class ElectronBrowserProvider {
|
|
|
2632
2632
|
// can produce JPEG (CDP JPEG hangs on Electron 43).
|
|
2633
2633
|
const capturable = handle;
|
|
2634
2634
|
if (request?.fullPage !== true && typeof capturable.capture === 'function') {
|
|
2635
|
-
// Ensure the target view is the visible one before capturing.
|
|
2636
|
-
|
|
2635
|
+
// Ensure the target view is the visible one before capturing — unless quiet mode is on.
|
|
2636
|
+
// There, presenting the view is exactly what the user asked to avoid (it restores and
|
|
2637
|
+
// raises the window); the host switches the visible tab inside the window and, if the
|
|
2638
|
+
// window has no surface to capture, falls through to CDP.
|
|
2639
|
+
if (!this.isQuiet())
|
|
2640
|
+
this.showActive(s);
|
|
2637
2641
|
const timeoutMs = 30_000;
|
|
2638
2642
|
const shot = await withTimeout(capturable.capture({
|
|
2639
2643
|
...format === 'jpeg' ? { format, quality: request?.quality } : {},
|
|
2640
2644
|
...request?.maxWidth !== undefined ? { maxWidth: request.maxWidth } : {},
|
|
2641
2645
|
...request?.maxHeight !== undefined ? { maxHeight: request.maxHeight } : {},
|
|
2646
|
+
quiet: this.isQuiet(),
|
|
2642
2647
|
}), timeoutMs, signal, `browser: screenshot timed out after ${timeoutMs}ms`);
|
|
2643
2648
|
if (shot.base64 === '') {
|
|
2644
2649
|
throw new BrowserError('browser: capture returned an empty image (view not painted); retry shortly', 'BROWSER_SCREENSHOT_FAILED');
|
|
@@ -3089,6 +3094,16 @@ export class ElectronBrowserProvider {
|
|
|
3089
3094
|
if (!reported)
|
|
3090
3095
|
process.stderr.write(`[dsh-browser] user action failed: ${message}\n`);
|
|
3091
3096
|
}
|
|
3097
|
+
/**
|
|
3098
|
+
* Whether the operator asked for quiet mode (`ui.quiet`).
|
|
3099
|
+
*
|
|
3100
|
+
* Read live on every call rather than captured at construction: the panel writes the document
|
|
3101
|
+
* and the next operation is expected to honour it, without a restart.
|
|
3102
|
+
* @returns true when the carrier must present views without taking the screen over.
|
|
3103
|
+
*/
|
|
3104
|
+
isQuiet() {
|
|
3105
|
+
return this.settingsSource?.().ui.quiet === true;
|
|
3106
|
+
}
|
|
3092
3107
|
/**
|
|
3093
3108
|
* Ask the host to show the active tab's view, carrying the session label.
|
|
3094
3109
|
*
|
|
@@ -3101,7 +3116,7 @@ export class ElectronBrowserProvider {
|
|
|
3101
3116
|
* silently desynchronising the two and failing every screenshot.
|
|
3102
3117
|
*/
|
|
3103
3118
|
showActive(s) {
|
|
3104
|
-
this.host.showView?.(this.activeTab(s).handle, s.label);
|
|
3119
|
+
this.host.showView?.(this.activeTab(s).handle, s.label, { quiet: this.isQuiet() });
|
|
3105
3120
|
const autoExpand = this.settingsSource === undefined || this.settingsSource().ui.autoExpandOnce;
|
|
3106
3121
|
if (autoExpand)
|
|
3107
3122
|
return;
|
|
@@ -26,7 +26,7 @@
|
|
|
26
26
|
* unauthenticated peer can neither read traffic nor drive a session.
|
|
27
27
|
* @module dsh-browser/browser-electron/remote-host
|
|
28
28
|
*/
|
|
29
|
-
import type { BrowserUserAction, ElectronBrowserViewHost, ElectronViewHandle } from './provider.js';
|
|
29
|
+
import type { BrowserUserAction, ElectronBrowserViewHost, ElectronViewHandle, PresentOptions } from './provider.js';
|
|
30
30
|
/**
|
|
31
31
|
* Locate a SPAWNABLE Electron binary — one that runs a script given as an
|
|
32
32
|
* argument, i.e. a BARE electron, never a packaged app executable:
|
|
@@ -209,7 +209,7 @@ export declare class RemoteElectronViewHost implements ElectronBrowserViewHost {
|
|
|
209
209
|
private onChildExit;
|
|
210
210
|
createView(): ElectronViewHandle;
|
|
211
211
|
private ensureView;
|
|
212
|
-
showView(handle: ElectronViewHandle, label?: string): void;
|
|
212
|
+
showView(handle: ElectronViewHandle, label?: string, options?: PresentOptions): void;
|
|
213
213
|
/**
|
|
214
214
|
* (Re)present a view and WAIT for the child to confirm it, so the provider
|
|
215
215
|
* can dispatch CDP `Input.*` knowing the view has a display surface.
|
|
@@ -225,7 +225,7 @@ export declare class RemoteElectronViewHost implements ElectronBrowserViewHost {
|
|
|
225
225
|
* in order: its reply is queued behind the showView and so only arrives once
|
|
226
226
|
* the visibility change has been applied.
|
|
227
227
|
*/
|
|
228
|
-
presentView(handle: ElectronViewHandle, label?: string): Promise<void>;
|
|
228
|
+
presentView(handle: ElectronViewHandle, label?: string, options?: PresentOptions): Promise<void>;
|
|
229
229
|
/** Route a view into its session's own window (one window per session). */
|
|
230
230
|
groupView(handle: ElectronViewHandle, windowId: string, label?: string): void;
|
|
231
231
|
/** Register the provider's handler for user-initiated toolbar actions. */
|
|
@@ -95,13 +95,13 @@ function resolveElectronPathImpl(inputs) {
|
|
|
95
95
|
if (hostExe !== undefined)
|
|
96
96
|
return hostExe;
|
|
97
97
|
throw new Error('dsh-builtin-browser: cannot locate a spawnable Electron binary. ' +
|
|
98
|
-
'The electron package ships with the plugin
|
|
99
|
-
'
|
|
100
|
-
'
|
|
101
|
-
'
|
|
102
|
-
'
|
|
103
|
-
'
|
|
104
|
-
'
|
|
98
|
+
'The electron package ships with the plugin and its binary is downloaded on first use, not at install time ' +
|
|
99
|
+
'(issue #41: an install-time download made default profiles refuse the plugin). The plugin prepares it ' +
|
|
100
|
+
'automatically when the bundled carrier is selected; to do it by hand, run ' +
|
|
101
|
+
'`npx --no dsh-browser-install-electron` in the profile that installed the plugin, then retry. ' +
|
|
102
|
+
'Alternatively set ELECTRON_PATH to an electron executable. Note: the host\'s own executable cannot be ' +
|
|
103
|
+
'reused when it is a packaged Electron app (e.g. DSH Desktop.exe) — only a real electron binary can be ' +
|
|
104
|
+
'spawned.');
|
|
105
105
|
}
|
|
106
106
|
/** DSH install anchors: electron installed separately (profile / global prefix), newest wins. */
|
|
107
107
|
function anchoredElectronBinary() {
|
|
@@ -1154,13 +1154,19 @@ export class RemoteElectronViewHost {
|
|
|
1154
1154
|
this.views.set(id, view);
|
|
1155
1155
|
return view;
|
|
1156
1156
|
}
|
|
1157
|
-
showView(handle, label) {
|
|
1157
|
+
showView(handle, label, options) {
|
|
1158
1158
|
// Fire-and-forget by design (visibility is best-effort), but a rejected
|
|
1159
1159
|
// promise must not become an unhandled rejection (crash on Node >= 15).
|
|
1160
1160
|
// The label (session/task id) rides along so the child can show it in the
|
|
1161
1161
|
// window title — a human can then tell which task's page is visible.
|
|
1162
|
+
// `quiet` is only sent when it is on: the child's default is the documented
|
|
1163
|
+
// "present and raise" behaviour, so an old child keeps working either way.
|
|
1162
1164
|
void this.ready()
|
|
1163
|
-
.then(() => this.client?.call('showView', {
|
|
1165
|
+
.then(() => this.client?.call('showView', {
|
|
1166
|
+
viewId: handle.id,
|
|
1167
|
+
...label !== undefined ? { label } : {},
|
|
1168
|
+
...options?.quiet === true ? { quiet: true } : {},
|
|
1169
|
+
}))
|
|
1164
1170
|
.catch(() => { });
|
|
1165
1171
|
}
|
|
1166
1172
|
/**
|
|
@@ -1178,7 +1184,7 @@ export class RemoteElectronViewHost {
|
|
|
1178
1184
|
* in order: its reply is queued behind the showView and so only arrives once
|
|
1179
1185
|
* the visibility change has been applied.
|
|
1180
1186
|
*/
|
|
1181
|
-
async presentView(handle, label) {
|
|
1187
|
+
async presentView(handle, label, options) {
|
|
1182
1188
|
await this.ready();
|
|
1183
1189
|
const client = this.client;
|
|
1184
1190
|
if (client === undefined)
|
|
@@ -1189,7 +1195,15 @@ export class RemoteElectronViewHost {
|
|
|
1189
1195
|
if (handle instanceof DeferredRemoteView) {
|
|
1190
1196
|
await withTimeout(handle.ensureMaterialized(), PRESENT_TIMEOUT_MS, 'browser host did not materialize the view');
|
|
1191
1197
|
}
|
|
1192
|
-
await withTimeout(client.call('showView', {
|
|
1198
|
+
await withTimeout(client.call('showView', {
|
|
1199
|
+
viewId: handle.id,
|
|
1200
|
+
...label !== undefined ? { label } : {},
|
|
1201
|
+
// `needSurface` tells the child this is the pre-input barrier: under quiet mode this
|
|
1202
|
+
// is the only presentation allowed to un-minimize a window, because Chromium drops
|
|
1203
|
+
// `Input.*` without a display surface. One line below in the child, and only read
|
|
1204
|
+
// there when `quiet` is set.
|
|
1205
|
+
...options?.quiet === true ? { quiet: true, needSurface: true } : {},
|
|
1206
|
+
}), PRESENT_TIMEOUT_MS, 'browser host did not confirm the view presentation');
|
|
1193
1207
|
await withTimeout(client.call('ping'), PRESENT_TIMEOUT_MS, 'browser host stopped answering');
|
|
1194
1208
|
}
|
|
1195
1209
|
/** Route a view into its session's own window (one window per session). */
|
|
@@ -40,6 +40,25 @@ export interface BrowserSettings {
|
|
|
40
40
|
readonly closeWithSession: boolean;
|
|
41
41
|
/** Show the synthetic cursor/click feedback while the agent operates. */
|
|
42
42
|
readonly virtualCursor: boolean;
|
|
43
|
+
/**
|
|
44
|
+
* Quiet mode: drive the page without taking over the screen.
|
|
45
|
+
*
|
|
46
|
+
* Off (the default) keeps the contract this plugin is built on — human and agent share one
|
|
47
|
+
* window, so an operation raises it and the user can see what is being driven. On, the
|
|
48
|
+
* carrier never activates the application and never steals keyboard focus:
|
|
49
|
+
* - screenshots of a minimized or hidden window go through CDP `Page.captureScreenshot`
|
|
50
|
+
* instead of `capturePage()`, so grabbing an image stops being a reason to show a window;
|
|
51
|
+
* - navigation and tab switching only change which view is visible INSIDE the window; a
|
|
52
|
+
* minimized window stays minimized;
|
|
53
|
+
* - synthesized input still needs a display surface (Chromium drops `Input.*` for a view
|
|
54
|
+
* without one), so that one barrier may restore a minimized window — with
|
|
55
|
+
* `showInactive()`, which shows it without becoming the key window, and without
|
|
56
|
+
* `moveTop()`.
|
|
57
|
+
*
|
|
58
|
+
* Reported as issue #35: a minimized browser window was restored and focused by the next
|
|
59
|
+
* screenshot or click, pulling the user out of whatever they were typing in.
|
|
60
|
+
*/
|
|
61
|
+
readonly quiet: boolean;
|
|
43
62
|
};
|
|
44
63
|
/** Visual vs non-visual operation strategy. */
|
|
45
64
|
readonly vision: {
|
|
@@ -17,7 +17,7 @@ export const HEADLESS_MODES = ['auto', 'headless', 'windowed'];
|
|
|
17
17
|
export const DEFAULT_SETTINGS = {
|
|
18
18
|
history: { enabled: true, maxEntries: 5_000, maxAgeDays: 90 },
|
|
19
19
|
cookies: { persist: true },
|
|
20
|
-
ui: { autoExpandOnce: true, closeWithSession: false, virtualCursor: true },
|
|
20
|
+
ui: { autoExpandOnce: true, closeWithSession: false, virtualCursor: true, quiet: false },
|
|
21
21
|
vision: { strategy: 'auto' },
|
|
22
22
|
// Bundled by default: it needs nothing installed, and on the desktop the carrier
|
|
23
23
|
// is the sidebar anyway. Choosing a system browser is an explicit opt-in because
|
|
@@ -197,6 +197,10 @@ export function resolveSettings(raw, warn) {
|
|
|
197
197
|
autoExpandOnce: bool(ui?.autoExpandOnce, DEFAULT_SETTINGS.ui.autoExpandOnce),
|
|
198
198
|
closeWithSession: bool(ui?.closeWithSession, DEFAULT_SETTINGS.ui.closeWithSession),
|
|
199
199
|
virtualCursor: bool(ui?.virtualCursor, DEFAULT_SETTINGS.ui.virtualCursor),
|
|
200
|
+
// Presentation preference, not a capability gate: a mistyped value keeps the documented
|
|
201
|
+
// default (off) instead of being read as "on", because quiet mode changes how every
|
|
202
|
+
// operation presents itself and should never be the accidental result of a bad edit.
|
|
203
|
+
quiet: bool(ui?.quiet, DEFAULT_SETTINGS.ui.quiet),
|
|
200
204
|
},
|
|
201
205
|
vision: { strategy: vision?.strategy === 'nonVisual' ? 'nonVisual' : DEFAULT_SETTINGS.vision.strategy },
|
|
202
206
|
browser: {
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "dsh-builtin-browser",
|
|
3
|
-
"version": "0.5.
|
|
4
|
-
"description": "Shared real browser plugin for DeepSeek Harness: install-and-use
|
|
3
|
+
"version": "0.5.3",
|
|
4
|
+
"description": "Shared real browser plugin for DeepSeek Harness: install-and-use 鈥?a visible native browser the human can take over, driven by the agent over CDP. DOM-level interaction (React/Vue safe), per-task session isolation, cookie persistence (dsh_browser_auth), CAPTCHA detection, batch form fill (dsh_browser_fill), authenticated download, history/replay, action restriction",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "lib/index.js",
|
|
7
7
|
"types": "lib/index.d.ts",
|
|
@@ -50,7 +50,6 @@
|
|
|
50
50
|
"scripts": {
|
|
51
51
|
"build": "tsc -p tsconfig.json",
|
|
52
52
|
"test": "tsc -p tsconfig.json && node --test \"tests/*.test.mjs\"",
|
|
53
|
-
"postinstall": "node scripts/install-electron.mjs",
|
|
54
53
|
"prepack": "npm run build"
|
|
55
54
|
},
|
|
56
55
|
"keywords": [
|
|
@@ -19,29 +19,32 @@
|
|
|
19
19
|
import { existsSync, readFileSync, readdirSync, statSync } from 'node:fs'
|
|
20
20
|
import { join } from 'node:path'
|
|
21
21
|
|
|
22
|
+
import { readDesktopIdentity } from './desktop-identity.js'
|
|
23
|
+
|
|
22
24
|
/**
|
|
23
25
|
* Find the desktop install to report on.
|
|
24
26
|
*
|
|
25
|
-
*
|
|
26
|
-
*
|
|
27
|
-
*
|
|
27
|
+
* Reported as issue #40: this used to probe for a *generic* Electron layout and return the first
|
|
28
|
+
* directory that had one. Any Electron app has that layout, so a stranger's app was reported as
|
|
29
|
+
* "DSH Desktop, bridge missing" — together with a ready-to-run installer command aimed at it. The
|
|
30
|
+
* probe now verifies the same identity the installer does (see `desktop-identity.js`), so the
|
|
31
|
+
* answer is about DSH Desktop and nothing else.
|
|
28
32
|
* @param localAppData - the base directory; defaults to the environment's.
|
|
29
33
|
* @returns the install directory, or undefined when nothing matches.
|
|
30
34
|
*/
|
|
31
35
|
export function findDesktopInstall(localAppData = process.env.LOCALAPPDATA ?? ''): string | undefined {
|
|
32
36
|
if (localAppData === '') return undefined
|
|
33
37
|
const programs = join(localAppData, 'Programs')
|
|
34
|
-
const
|
|
35
|
-
|| existsSync(join(candidate, 'resources', 'app.asar'))
|
|
38
|
+
const isDesktop = (candidate: string): boolean => readDesktopIdentity(candidate).ok
|
|
36
39
|
for (const named of ['DSH Desktop', 'DeepSeek Harness']) {
|
|
37
40
|
const candidate = join(programs, named)
|
|
38
|
-
if (
|
|
41
|
+
if (isDesktop(candidate)) return candidate
|
|
39
42
|
}
|
|
40
43
|
try {
|
|
41
44
|
for (const entry of readdirSync(programs, { withFileTypes: true })) {
|
|
42
45
|
if (!entry.isDirectory()) continue
|
|
43
46
|
const candidate = join(programs, entry.name)
|
|
44
|
-
if (
|
|
47
|
+
if (isDesktop(candidate)) return candidate
|
|
45
48
|
}
|
|
46
49
|
} catch {
|
|
47
50
|
// No Programs directory: nothing to report on, which is a state rather than an error.
|
|
@@ -100,16 +103,32 @@ export function readBridgeStatus(installRoot: string): BridgeStatus {
|
|
|
100
103
|
const archivePath = join(resources, 'app.asar')
|
|
101
104
|
const backupPath = `${mainPath}.before-bridge`
|
|
102
105
|
|
|
106
|
+
// Identity first, and before any other reading. Two reasons, both measured in issue #40: a
|
|
107
|
+
// stranger's app must not be reported as DSH Desktop, and this status also carries a *command* —
|
|
108
|
+
// pointing that command at a directory whose identity was never verified is how the installer got
|
|
109
|
+
// aimed at an application that merely looked like Electron.
|
|
110
|
+
const identity = readDesktopIdentity(installRoot)
|
|
111
|
+
if (!identity.ok) {
|
|
112
|
+
return {
|
|
113
|
+
state: 'missing',
|
|
114
|
+
present: false,
|
|
115
|
+
installRoot,
|
|
116
|
+
archivePresent: safeExists(archivePath),
|
|
117
|
+
detail: `not a DSH Desktop install: ${identity.reason}`,
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
|
|
103
121
|
const archivePresent = safeExists(archivePath)
|
|
104
122
|
const mainPresent = safeExists(mainPath)
|
|
105
123
|
if (!mainPresent && !archivePresent) {
|
|
124
|
+
// Unreachable once identity has passed (identity requires the loaded main entry), kept as the
|
|
125
|
+
// fail-closed branch for a tree that changed between the two reads.
|
|
106
126
|
return {
|
|
107
127
|
state: 'missing',
|
|
108
128
|
present: false,
|
|
109
129
|
installRoot,
|
|
110
130
|
archivePresent,
|
|
111
|
-
|
|
112
|
-
detail: 'not a DSH Desktop install: no resources/app/lib/main.js and no resources/app.asar',
|
|
131
|
+
detail: 'not a DSH Desktop install: no resources/app/lib/main.js and no resources/app.asar',
|
|
113
132
|
}
|
|
114
133
|
}
|
|
115
134
|
let backupAt
|
|
@@ -0,0 +1,260 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* What proves a directory is a DSH Desktop install.
|
|
3
|
+
*
|
|
4
|
+
* Reported as issue #40. Every reader of an install directory used to accept a *generic* Electron
|
|
5
|
+
* layout (`resources/app/lib/main.js` or `resources/app.asar`) as proof, and that is not proof of
|
|
6
|
+
* anything: any Electron app has it. The consequence was measured — a throwaway app in a temp
|
|
7
|
+
* directory, whose own package.json said `unrelated-meeting-app`, was accepted by discovery, got a
|
|
8
|
+
* "bridge not installed" verdict with a ready-to-run installer command aimed at it, and (with that
|
|
9
|
+
* command) had its entry file rewritten and the bridge copied in.
|
|
10
|
+
*
|
|
11
|
+
* So identity is one rule, in one file (`desktop-bridge/desktop-identity.json`), read by both the
|
|
12
|
+
* installer and this module. Nothing else may decide what a DSH Desktop install is.
|
|
13
|
+
*
|
|
14
|
+
* Two properties are load-bearing and are why this is not a one-line `name ===` check:
|
|
15
|
+
*
|
|
16
|
+
* - **The archive wins.** Electron loads `resources/app.asar` in preference to `resources/app`, and
|
|
17
|
+
* a desktop update leaves the old extraction lying around. Reading identity from the extraction
|
|
18
|
+
* while the archive holds a different build would verify the wrong bytes, so when the archive is
|
|
19
|
+
* present that is what is read — and the sibling directory is not consulted at all.
|
|
20
|
+
* - **Unreadable means not DSH.** Every failure path (missing file, truncated pickle, unsupported
|
|
21
|
+
* archive version, malformed JSON, unreadable name) refuses. There is no "assume yes" branch: the
|
|
22
|
+
* caller is about to write into, or delete from, this directory.
|
|
23
|
+
* @module dsh-browser/browser-electron/desktop-identity
|
|
24
|
+
*/
|
|
25
|
+
import { closeSync, existsSync, openSync, readFileSync, readSync } from 'node:fs'
|
|
26
|
+
import { join } from 'node:path'
|
|
27
|
+
|
|
28
|
+
/** The identity rule, as data. */
|
|
29
|
+
interface IdentityRule {
|
|
30
|
+
readonly packageNames: readonly string[]
|
|
31
|
+
readonly mainEntry: string
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/**
|
|
35
|
+
* The rule shipped in `desktop-bridge/desktop-identity.json`, used when the file cannot be read.
|
|
36
|
+
*
|
|
37
|
+
* A copy exists here only as a fallback for a broken package layout; the test suite asserts that it
|
|
38
|
+
* equals the JSON, so the two can never drift apart silently.
|
|
39
|
+
*/
|
|
40
|
+
export const FALLBACK_RULE: IdentityRule = {
|
|
41
|
+
packageNames: ['@deepseek-ai/dsh-desktop', 'dsh-desktop'],
|
|
42
|
+
mainEntry: 'lib/main.js',
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/** A verified install. */
|
|
46
|
+
export interface DesktopIdentity {
|
|
47
|
+
readonly ok: true
|
|
48
|
+
/** The install root that was verified. */
|
|
49
|
+
readonly root: string
|
|
50
|
+
/** Which shape was verified — the archive when it exists, the extraction only without one. */
|
|
51
|
+
readonly layout: 'packed' | 'unpacked'
|
|
52
|
+
/** `name` from the package the caller will actually run. */
|
|
53
|
+
readonly packageName: string
|
|
54
|
+
/** `version`, when the package declares one. */
|
|
55
|
+
readonly version?: string
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/** A refusal, with a reason a human can act on. */
|
|
59
|
+
export interface IdentityRefusal {
|
|
60
|
+
readonly ok: false
|
|
61
|
+
readonly reason: string
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/**
|
|
65
|
+
* Read the identity rule.
|
|
66
|
+
*
|
|
67
|
+
* Resolved relative to this module, which in both the repository and the published tarball puts
|
|
68
|
+
* `desktop-bridge/` beside `lib/`. A missing file is not fatal — the fallback is the same rule —
|
|
69
|
+
* but a *malformed* one is an error the caller should not ignore, so it is reported through the
|
|
70
|
+
* refusal path rather than silently swapped for the fallback.
|
|
71
|
+
* @returns the rule, or an error string.
|
|
72
|
+
*/
|
|
73
|
+
export function readIdentityRule(): IdentityRule | { readonly error: string } {
|
|
74
|
+
try {
|
|
75
|
+
const path = new URL('../../desktop-bridge/desktop-identity.json', import.meta.url)
|
|
76
|
+
const raw = JSON.parse(readFileSync(path, 'utf8')) as Partial<IdentityRule>
|
|
77
|
+
const names = raw.packageNames
|
|
78
|
+
const main = raw.mainEntry
|
|
79
|
+
if (!Array.isArray(names) || names.length === 0 || names.some(n => typeof n !== 'string')) {
|
|
80
|
+
return { error: 'desktop-identity.json: packageNames must be a non-empty array of strings' }
|
|
81
|
+
}
|
|
82
|
+
if (typeof main !== 'string' || main === '') {
|
|
83
|
+
return { error: 'desktop-identity.json: mainEntry must be a non-empty string' }
|
|
84
|
+
}
|
|
85
|
+
return { packageNames: names, mainEntry: main }
|
|
86
|
+
} catch (error) {
|
|
87
|
+
if (error instanceof Error && 'code' in error && (error as NodeJS.ErrnoException).code === 'ENOENT') {
|
|
88
|
+
return FALLBACK_RULE
|
|
89
|
+
}
|
|
90
|
+
return { error: `desktop-identity.json could not be read: ${String(error)}` }
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
/**
|
|
95
|
+
* One entry of a Chromium pickle header.
|
|
96
|
+
*
|
|
97
|
+
* `offset` is relative to the content area that follows the header; `unpacked` entries carry no
|
|
98
|
+
* bytes in the archive and live beside it instead.
|
|
99
|
+
*/
|
|
100
|
+
interface AsarEntry {
|
|
101
|
+
readonly size: number
|
|
102
|
+
readonly offset?: string
|
|
103
|
+
readonly unpacked?: boolean
|
|
104
|
+
readonly files?: Record<string, AsarEntry>
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
/**
|
|
108
|
+
* Parse an asar header, the same way the installer does.
|
|
109
|
+
*
|
|
110
|
+
* Layout, for the next reader: an 8-byte outer pickle (`[size][jsonLength]`), then the header
|
|
111
|
+
* pickle whose first 4 bytes are the JSON length, then the JSON tree. File content starts right
|
|
112
|
+
* after the header pickle.
|
|
113
|
+
* @param archive - the archive path.
|
|
114
|
+
* @returns the header tree and the offset where content starts, or an error string.
|
|
115
|
+
*/
|
|
116
|
+
function readAsarHeader(archive: string): { header: { files?: Record<string, AsarEntry> }; contentBase: number } | { error: string } {
|
|
117
|
+
let fd: number | undefined
|
|
118
|
+
try {
|
|
119
|
+
fd = openSync(archive, 'r')
|
|
120
|
+
const outer = Buffer.alloc(8)
|
|
121
|
+
if (readSync(fd, outer, 0, 8, 0) !== 8) return { error: 'the archive header is truncated' }
|
|
122
|
+
const headerSize = outer.readUInt32LE(4)
|
|
123
|
+
if (headerSize < 8 || headerSize > 64 * 1024 * 1024) return { error: `implausible archive header size (${headerSize})` }
|
|
124
|
+
const header = Buffer.alloc(headerSize)
|
|
125
|
+
if (readSync(fd, header, 0, headerSize, 8) !== headerSize) return { error: 'the archive header is truncated' }
|
|
126
|
+
const jsonLength = header.readUInt32LE(4)
|
|
127
|
+
if (jsonLength <= 0 || jsonLength > headerSize - 8) return { error: 'the archive header has an implausible JSON length' }
|
|
128
|
+
return { header: JSON.parse(header.toString('utf8', 8, 8 + jsonLength)), contentBase: 8 + headerSize }
|
|
129
|
+
} catch (error) {
|
|
130
|
+
return { error: `the archive header could not be read: ${String(error)}` }
|
|
131
|
+
} finally {
|
|
132
|
+
if (fd !== undefined) {
|
|
133
|
+
try { closeSync(fd) } catch { /* already closed */ }
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
/**
|
|
139
|
+
* Walk a slash-separated path inside an asar header tree.
|
|
140
|
+
* @param tree - the header's `files` node.
|
|
141
|
+
* @param path - e.g. `lib/main.js`.
|
|
142
|
+
* @returns the entry, or undefined when the path does not exist.
|
|
143
|
+
*/
|
|
144
|
+
function entryAt(tree: Record<string, AsarEntry> | undefined, path: string): AsarEntry | undefined {
|
|
145
|
+
let node: AsarEntry | undefined
|
|
146
|
+
let files: Record<string, AsarEntry> | undefined = tree
|
|
147
|
+
for (const part of path.split('/')) {
|
|
148
|
+
if (files === undefined) return undefined
|
|
149
|
+
node = files[part]
|
|
150
|
+
if (node === undefined) return undefined
|
|
151
|
+
files = node.files
|
|
152
|
+
}
|
|
153
|
+
return node
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
/**
|
|
157
|
+
* Read one file out of an asar archive without extracting the tree.
|
|
158
|
+
* @param archive - the archive path.
|
|
159
|
+
* @param path - a slash-separated path inside the archive.
|
|
160
|
+
* @returns the bytes, or undefined when the entry is absent or unreadable.
|
|
161
|
+
*/
|
|
162
|
+
export function readAsarFile(archive: string, path: string): Buffer | undefined {
|
|
163
|
+
const parsed = readAsarHeader(archive)
|
|
164
|
+
if ('error' in parsed) return undefined
|
|
165
|
+
const entry = entryAt(parsed.header.files, path)
|
|
166
|
+
if (entry === undefined || entry.files !== undefined || entry.unpacked === true) return undefined
|
|
167
|
+
if (typeof entry.offset !== 'string' || typeof entry.size !== 'number' || entry.size < 0) return undefined
|
|
168
|
+
let fd: number | undefined
|
|
169
|
+
try {
|
|
170
|
+
fd = openSync(archive, 'r')
|
|
171
|
+
const buffer = Buffer.alloc(entry.size)
|
|
172
|
+
const read = readSync(fd, buffer, 0, entry.size, parsed.contentBase + Number(entry.offset))
|
|
173
|
+
return read === entry.size ? buffer : undefined
|
|
174
|
+
} catch {
|
|
175
|
+
return undefined
|
|
176
|
+
} finally {
|
|
177
|
+
if (fd !== undefined) {
|
|
178
|
+
try { closeSync(fd) } catch { /* already closed */ }
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
/**
|
|
184
|
+
* Whether an install directory is DSH Desktop.
|
|
185
|
+
*
|
|
186
|
+
* Everything the caller does next (stop the app, delete a tree, extract, rename, write) depends on
|
|
187
|
+
* this being right, so every uncertainty resolves to a refusal that names what was found.
|
|
188
|
+
* @param installRoot - the directory a user or the discovery probe named.
|
|
189
|
+
* @returns the verified identity, or a refusal with a reason.
|
|
190
|
+
*/
|
|
191
|
+
export function readDesktopIdentity(installRoot: string): DesktopIdentity | IdentityRefusal {
|
|
192
|
+
const rule = readIdentityRule()
|
|
193
|
+
if ('error' in rule) return { ok: false, reason: rule.error }
|
|
194
|
+
const resources = join(installRoot, 'resources')
|
|
195
|
+
const appDir = join(resources, 'app')
|
|
196
|
+
const archive = join(resources, 'app.asar')
|
|
197
|
+
|
|
198
|
+
let archivePresent: boolean
|
|
199
|
+
try {
|
|
200
|
+
archivePresent = existsSync(archive)
|
|
201
|
+
} catch {
|
|
202
|
+
return { ok: false, reason: `cannot inspect ${archive}` }
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
const layout: 'packed' | 'unpacked' = archivePresent ? 'packed' : 'unpacked'
|
|
206
|
+
let manifestText: string | undefined
|
|
207
|
+
let mainPresent: boolean
|
|
208
|
+
if (archivePresent) {
|
|
209
|
+
const parsed = readAsarHeader(archive)
|
|
210
|
+
if ('error' in parsed) {
|
|
211
|
+
return { ok: false, reason: `${archive} could not be read: ${parsed.error}` }
|
|
212
|
+
}
|
|
213
|
+
const manifest = entryAt(parsed.header.files, 'package.json')
|
|
214
|
+
if (manifest === undefined || manifest.files !== undefined || manifest.unpacked === true) {
|
|
215
|
+
return { ok: false, reason: `${archive} has no plain package.json; an archive without one is not proof of identity` }
|
|
216
|
+
}
|
|
217
|
+
manifestText = readAsarFile(archive, 'package.json')?.toString('utf8')
|
|
218
|
+
if (manifestText === undefined) {
|
|
219
|
+
return { ok: false, reason: `${archive}: package.json is listed but its bytes cannot be read` }
|
|
220
|
+
}
|
|
221
|
+
mainPresent = entryAt(parsed.header.files, rule.mainEntry) !== undefined
|
|
222
|
+
} else {
|
|
223
|
+
const manifestPath = join(appDir, 'package.json')
|
|
224
|
+
try {
|
|
225
|
+
manifestText = readFileSync(manifestPath, 'utf8')
|
|
226
|
+
} catch {
|
|
227
|
+
return { ok: false, reason: `${manifestPath} is missing; a directory without a package manifest is not a DSH Desktop install` }
|
|
228
|
+
}
|
|
229
|
+
mainPresent = existsSync(join(appDir, ...rule.mainEntry.split('/')))
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
let manifest: { name?: unknown; version?: unknown }
|
|
233
|
+
try {
|
|
234
|
+
manifest = JSON.parse(manifestText) as { name?: unknown; version?: unknown }
|
|
235
|
+
} catch {
|
|
236
|
+
return { ok: false, reason: 'the package manifest is not valid JSON' }
|
|
237
|
+
}
|
|
238
|
+
const name = typeof manifest.name === 'string' ? manifest.name : ''
|
|
239
|
+
if (!rule.packageNames.includes(name)) {
|
|
240
|
+
return {
|
|
241
|
+
ok: false,
|
|
242
|
+
reason: `the app calls itself ${name === '' ? '(no name)' : JSON.stringify(name)}, which is not one of `
|
|
243
|
+
+ `${rule.packageNames.join(' / ')} — refusing to touch a different application`,
|
|
244
|
+
}
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
// The main entry is the file the installer patches and the shell runs; if it is not there, this
|
|
248
|
+
// is not an install this plugin can reason about even though the manifest looks right.
|
|
249
|
+
if (!mainPresent) {
|
|
250
|
+
return { ok: false, reason: `${rule.mainEntry} is not present under ${archivePresent ? archive : appDir}` }
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
return {
|
|
254
|
+
ok: true,
|
|
255
|
+
root: installRoot,
|
|
256
|
+
layout,
|
|
257
|
+
packageName: name,
|
|
258
|
+
...typeof manifest.version === 'string' ? { version: manifest.version } : {},
|
|
259
|
+
}
|
|
260
|
+
}
|