dsh-builtin-browser 0.5.7 → 0.5.8
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 +66 -0
- package/README.en.md +48 -22
- package/README.md +48 -22
- package/client.js +469 -81
- package/desktop-bridge/install-and-start.cmd +4 -5
- package/desktop-bridge/install.mjs +251 -159
- package/desktop-bridge/maintenance-progress.ps1 +166 -0
- package/desktop-bridge/plugin-browser-bridge.js +151 -18
- package/desktop-bridge/request-desktop-quit.ps1 +170 -0
- package/docs/user-guide.md +28 -4
- package/lib/browser-electron/automatic-maintenance.d.ts +41 -0
- package/lib/browser-electron/automatic-maintenance.js +426 -0
- package/lib/browser-electron/bridge-auto.d.ts +93 -0
- package/lib/browser-electron/bridge-auto.js +113 -0
- package/lib/browser-electron/bridge-connection.d.ts +0 -2
- package/lib/browser-electron/bridge-connection.js +2 -4
- package/lib/browser-electron/bridge-endpoint.js +1 -19
- package/lib/browser-electron/bridge-install.d.ts +41 -4
- package/lib/browser-electron/bridge-install.js +131 -18
- package/lib/browser-electron/bridge-maintenance.d.ts +24 -0
- package/lib/browser-electron/bridge-maintenance.js +125 -0
- package/lib/browser-electron/bridge-status.d.ts +10 -3
- package/lib/browser-electron/bridge-status.js +76 -45
- package/lib/browser-electron/desktop-bridge-host.d.ts +5 -2
- package/lib/browser-electron/desktop-bridge-host.js +54 -33
- package/lib/browser-electron/desktop-identity.js +21 -9
- package/lib/browser-electron/electron-provision.js +5 -2
- package/lib/browser-electron/entry.js +104 -74
- package/lib/browser-electron/ephemeral-profile.js +67 -26
- package/lib/browser-electron/history-store.js +2 -2
- package/lib/browser-electron/host-main.js +26 -37
- package/lib/browser-electron/http-body.d.ts +24 -0
- package/lib/browser-electron/http-body.js +33 -0
- package/lib/browser-electron/json-reply.d.ts +13 -1
- package/lib/browser-electron/json-reply.js +16 -2
- package/lib/browser-electron/maintenance-broker.d.ts +35 -0
- package/lib/browser-electron/maintenance-broker.js +114 -0
- package/lib/browser-electron/maintenance-lifecycle.d.ts +32 -0
- package/lib/browser-electron/maintenance-lifecycle.js +67 -0
- package/lib/browser-electron/maintenance-route.d.ts +18 -0
- package/lib/browser-electron/maintenance-route.js +75 -0
- package/lib/browser-electron/paths.d.ts +4 -0
- package/lib/browser-electron/paths.js +19 -0
- package/lib/browser-electron/process.d.ts +14 -0
- package/lib/browser-electron/process.js +24 -0
- package/lib/browser-electron/provider.d.ts +7 -7
- package/lib/browser-electron/provider.js +13 -14
- package/lib/browser-electron/remote-host.js +18 -16
- package/lib/browser-electron/runtime-status.d.ts +27 -13
- package/lib/browser-electron/runtime-status.js +24 -4
- package/lib/browser-electron/settings-store.d.ts +11 -0
- package/lib/browser-electron/settings-store.js +8 -2
- package/lib/browser-electron/sidebar-only-host.d.ts +36 -0
- package/lib/browser-electron/sidebar-only-host.js +192 -0
- package/lib/browser-electron/system-browser.d.ts +1 -9
- package/lib/browser-electron/system-browser.js +19 -22
- package/lib/browser-electron/timing.d.ts +8 -0
- package/lib/browser-electron/timing.js +13 -0
- package/lib/browser-electron/windows-system.d.ts +3 -0
- package/lib/browser-electron/windows-system.js +19 -0
- package/lib/tool-browser/index.js +5 -4
- package/package.json +2 -2
- package/scripts/run-tests.mjs +32 -0
- package/scripts/verify-preview-route.mjs +19 -1
- package/src/browser-electron/automatic-maintenance.ts +414 -0
- package/src/browser-electron/bridge-auto.ts +158 -0
- package/src/browser-electron/bridge-connection.ts +2 -4
- package/src/browser-electron/bridge-endpoint.ts +1 -18
- package/src/browser-electron/bridge-install.ts +151 -20
- package/src/browser-electron/bridge-maintenance.ts +161 -0
- package/src/browser-electron/bridge-status.ts +78 -48
- package/src/browser-electron/desktop-bridge-host.ts +48 -32
- package/src/browser-electron/desktop-identity.ts +18 -9
- package/src/browser-electron/electron-provision.ts +5 -2
- package/src/browser-electron/entry.ts +91 -69
- package/src/browser-electron/ephemeral-profile.ts +65 -28
- package/src/browser-electron/history-store.ts +2 -2
- package/src/browser-electron/host-main.ts +23 -36
- package/src/browser-electron/http-body.ts +42 -0
- package/src/browser-electron/json-reply.ts +18 -3
- package/src/browser-electron/maintenance-broker.ts +142 -0
- package/src/browser-electron/maintenance-lifecycle.ts +86 -0
- package/src/browser-electron/maintenance-route.ts +64 -0
- package/src/browser-electron/paths.ts +21 -0
- package/src/browser-electron/process.ts +23 -0
- package/src/browser-electron/provider.ts +18 -18
- package/src/browser-electron/remote-host.ts +19 -19
- package/src/browser-electron/runtime-status.ts +52 -17
- package/src/browser-electron/settings-store.ts +20 -3
- package/src/browser-electron/sidebar-only-host.ts +199 -0
- package/src/browser-electron/system-browser.ts +19 -22
- package/src/browser-electron/timing.ts +16 -0
- package/src/browser-electron/windows-system.ts +23 -0
- package/src/tool-browser/index.ts +5 -4
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Read a body as UTF-8 text. Chunks are collected as Buffers and decoded once: setting an
|
|
3
|
+
* encoding on the stream and concatenating `String(chunk)` corrupts a multi-byte character that
|
|
4
|
+
* happens to be split across two TCP chunks.
|
|
5
|
+
* @param request - the incoming request.
|
|
6
|
+
* @param limit - maximum accepted bytes.
|
|
7
|
+
* @returns the body text.
|
|
8
|
+
*/
|
|
9
|
+
export async function readTextBody(request, limit = 64 * 1024) {
|
|
10
|
+
const chunks = [];
|
|
11
|
+
let size = 0;
|
|
12
|
+
for await (const chunk of request) {
|
|
13
|
+
const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(String(chunk));
|
|
14
|
+
size += buffer.length;
|
|
15
|
+
if (size > limit) {
|
|
16
|
+
request.destroy();
|
|
17
|
+
throw new Error(`request body exceeds ${limit} bytes`);
|
|
18
|
+
}
|
|
19
|
+
chunks.push(buffer);
|
|
20
|
+
}
|
|
21
|
+
return Buffer.concat(chunks).toString('utf8');
|
|
22
|
+
}
|
|
23
|
+
/**
|
|
24
|
+
* Read and parse a JSON body. An empty body is an empty object, matching the settings route's
|
|
25
|
+
* long-standing behaviour.
|
|
26
|
+
* @param request - the incoming request.
|
|
27
|
+
* @param limit - maximum accepted bytes.
|
|
28
|
+
* @returns the parsed value.
|
|
29
|
+
*/
|
|
30
|
+
export async function readJsonBody(request, limit = 64 * 1024) {
|
|
31
|
+
const text = await readTextBody(request, limit);
|
|
32
|
+
return JSON.parse(text === '' ? '{}' : text);
|
|
33
|
+
}
|
|
@@ -11,11 +11,23 @@
|
|
|
11
11
|
* - `nosniff` + a same-origin resource policy, because these bodies name paths and pids.
|
|
12
12
|
* @module dsh-browser/browser-electron/json-reply
|
|
13
13
|
*/
|
|
14
|
-
import type { ServerResponse } from 'node:http';
|
|
14
|
+
import type { OutgoingHttpHeaders, ServerResponse } from 'node:http';
|
|
15
15
|
/**
|
|
16
16
|
* Write one JSON body with no caching and no sniffing.
|
|
17
17
|
* @param response - the response to write.
|
|
18
18
|
* @param status - the HTTP status.
|
|
19
19
|
* @param body - anything JSON-serialisable.
|
|
20
20
|
*/
|
|
21
|
+
/**
|
|
22
|
+
* Write an already-serialised JSON body with caller-supplied headers.
|
|
23
|
+
*
|
|
24
|
+
* Routes do not all need the same header set: readiness answers carry length and sniffing
|
|
25
|
+
* headers, while the settings route has always returned only a content type and no-store.
|
|
26
|
+
* Sharing the write keeps those exact header sets from drifting into each other.
|
|
27
|
+
* @param response - the response to write.
|
|
28
|
+
* @param status - the HTTP status.
|
|
29
|
+
* @param text - the serialised body.
|
|
30
|
+
* @param headers - the exact header set this route has always sent.
|
|
31
|
+
*/
|
|
32
|
+
export declare function writeJsonText(response: ServerResponse, status: number, text: string, headers: OutgoingHttpHeaders): void;
|
|
21
33
|
export declare function replyJson(response: ServerResponse, status: number, body: unknown): void;
|
|
@@ -4,14 +4,28 @@
|
|
|
4
4
|
* @param status - the HTTP status.
|
|
5
5
|
* @param body - anything JSON-serialisable.
|
|
6
6
|
*/
|
|
7
|
+
/**
|
|
8
|
+
* Write an already-serialised JSON body with caller-supplied headers.
|
|
9
|
+
*
|
|
10
|
+
* Routes do not all need the same header set: readiness answers carry length and sniffing
|
|
11
|
+
* headers, while the settings route has always returned only a content type and no-store.
|
|
12
|
+
* Sharing the write keeps those exact header sets from drifting into each other.
|
|
13
|
+
* @param response - the response to write.
|
|
14
|
+
* @param status - the HTTP status.
|
|
15
|
+
* @param text - the serialised body.
|
|
16
|
+
* @param headers - the exact header set this route has always sent.
|
|
17
|
+
*/
|
|
18
|
+
export function writeJsonText(response, status, text, headers) {
|
|
19
|
+
response.writeHead(status, headers);
|
|
20
|
+
response.end(text);
|
|
21
|
+
}
|
|
7
22
|
export function replyJson(response, status, body) {
|
|
8
23
|
const text = JSON.stringify(body);
|
|
9
|
-
response
|
|
24
|
+
writeJsonText(response, status, text, {
|
|
10
25
|
'content-type': 'application/json; charset=utf-8',
|
|
11
26
|
'content-length': Buffer.byteLength(text),
|
|
12
27
|
'cache-control': 'no-store, private',
|
|
13
28
|
'x-content-type-options': 'nosniff',
|
|
14
29
|
'cross-origin-resource-policy': 'same-origin',
|
|
15
30
|
});
|
|
16
|
-
response.end(text);
|
|
17
31
|
}
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
export interface MaintenanceBrokerOptions {
|
|
2
|
+
readonly runtimePath: string;
|
|
3
|
+
readonly args: readonly string[];
|
|
4
|
+
readonly cwd: string;
|
|
5
|
+
/** Overrides for the explicitly inherited environment; undefined removes a variable. */
|
|
6
|
+
readonly environment?: Readonly<Record<string, string | undefined>>;
|
|
7
|
+
}
|
|
8
|
+
export interface MaintenanceBrokerExecution {
|
|
9
|
+
readonly windowsHide: true;
|
|
10
|
+
readonly shell: false;
|
|
11
|
+
readonly encoding: 'utf8';
|
|
12
|
+
readonly timeout: number;
|
|
13
|
+
readonly maxBuffer: number;
|
|
14
|
+
readonly env: NodeJS.ProcessEnv;
|
|
15
|
+
}
|
|
16
|
+
export type MaintenanceBrokerExecutor = (file: string, args: readonly string[], options: MaintenanceBrokerExecution) => Promise<{
|
|
17
|
+
readonly stdout: string;
|
|
18
|
+
readonly stderr: string;
|
|
19
|
+
}>;
|
|
20
|
+
export interface MaintenanceBrokerDeps {
|
|
21
|
+
/** Tests supply a fake executor; the real broker is prohibited inside the test runner. */
|
|
22
|
+
readonly execFile?: MaintenanceBrokerExecutor;
|
|
23
|
+
readonly platform?: NodeJS.Platform;
|
|
24
|
+
}
|
|
25
|
+
export interface MaintenanceBrokerResult {
|
|
26
|
+
readonly pid: number;
|
|
27
|
+
}
|
|
28
|
+
/** Quote one argument using the Windows C runtime's command-line decoding rules. */
|
|
29
|
+
export declare function quoteWin32Argument(value: string): string;
|
|
30
|
+
/**
|
|
31
|
+
* Create a hidden, independent local process. No shell evaluates runtime paths or arguments.
|
|
32
|
+
* WMI receives an explicit environment copied from this process, including any plan overrides;
|
|
33
|
+
* it therefore does not accidentally inherit the provider service's unrelated environment.
|
|
34
|
+
*/
|
|
35
|
+
export declare function launchMaintenanceBroker(options: MaintenanceBrokerOptions, deps?: MaintenanceBrokerDeps): Promise<MaintenanceBrokerResult>;
|
|
@@ -0,0 +1,114 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Start a local Windows maintenance coordinator through WMI, outside the requesting app's tree.
|
|
3
|
+
* This primitive only creates the requested process; its caller owns maintenance authorization,
|
|
4
|
+
* the coordinator's plan, readiness handshake and normal application shutdown.
|
|
5
|
+
* @module dsh-browser/browser-electron/maintenance-broker
|
|
6
|
+
*/
|
|
7
|
+
import { execFile } from 'node:child_process';
|
|
8
|
+
import { statSync } from 'node:fs';
|
|
9
|
+
import { win32 } from 'node:path';
|
|
10
|
+
import { encodePowerShellScript, windowsPowerShellPath } from './windows-system.js';
|
|
11
|
+
/** Quote one argument using the Windows C runtime's command-line decoding rules. */
|
|
12
|
+
export function quoteWin32Argument(value) {
|
|
13
|
+
if (typeof value !== 'string' || value.includes('\0'))
|
|
14
|
+
throw new Error('a Windows process argument must be a string without NUL');
|
|
15
|
+
// Backslashes are literal except immediately before a quote or the closing quote. At those
|
|
16
|
+
// positions each slash must be doubled, and an embedded quote receives one additional slash.
|
|
17
|
+
return '"' + value.replace(/(\\*)"/g, '$1$1\\"').replace(/(\\+)$/, '$1$1') + '"';
|
|
18
|
+
}
|
|
19
|
+
function absolutePath(value, label) {
|
|
20
|
+
if (typeof value !== 'string' || value.includes('\0') || value.includes('"')
|
|
21
|
+
|| !/^(?:[A-Za-z]:[\\/]|\\\\[^\\/]+[\\/][^\\/]+)/.test(value)) {
|
|
22
|
+
throw new Error(`${label} must be a fully qualified Windows path without NUL or quotes`);
|
|
23
|
+
}
|
|
24
|
+
return win32.normalize(value);
|
|
25
|
+
}
|
|
26
|
+
/** Apply Windows' case-insensitive variable names before passing one explicit environment. */
|
|
27
|
+
function inheritEnvironment(overrides) {
|
|
28
|
+
const environment = { ...process.env };
|
|
29
|
+
for (const [key, value] of Object.entries(overrides ?? {})) {
|
|
30
|
+
if (key === '' || /[=\0]/.test(key) || (value !== undefined && (typeof value !== 'string' || value.includes('\0')))) {
|
|
31
|
+
throw new Error('maintenance environment names and values must be valid Windows environment strings');
|
|
32
|
+
}
|
|
33
|
+
for (const existing of Object.keys(environment))
|
|
34
|
+
if (existing.toUpperCase() === key.toUpperCase())
|
|
35
|
+
delete environment[existing];
|
|
36
|
+
if (value !== undefined)
|
|
37
|
+
environment[key] = value;
|
|
38
|
+
}
|
|
39
|
+
return environment;
|
|
40
|
+
}
|
|
41
|
+
function underTest(environment) {
|
|
42
|
+
return Object.entries(environment).some(([key, value]) => (key.toUpperCase() === 'DSH_BROWSER_TEST' && value === '1')
|
|
43
|
+
|| (key.toUpperCase() === 'NODE_TEST_CONTEXT' && value !== undefined));
|
|
44
|
+
}
|
|
45
|
+
const defaultExecutor = (file, args, options) => new Promise((resolve, reject) => {
|
|
46
|
+
execFile(file, [...args], options, (error, stdout, stderr) => {
|
|
47
|
+
if (error !== null) {
|
|
48
|
+
const reason = stderr.trim() || error.code || 'PowerShell did not complete';
|
|
49
|
+
reject(new Error(`Windows maintenance broker failed: ${String(reason).slice(-1_000)}`));
|
|
50
|
+
}
|
|
51
|
+
else
|
|
52
|
+
resolve({ stdout, stderr });
|
|
53
|
+
});
|
|
54
|
+
});
|
|
55
|
+
/**
|
|
56
|
+
* Create a hidden, independent local process. No shell evaluates runtime paths or arguments.
|
|
57
|
+
* WMI receives an explicit environment copied from this process, including any plan overrides;
|
|
58
|
+
* it therefore does not accidentally inherit the provider service's unrelated environment.
|
|
59
|
+
*/
|
|
60
|
+
export async function launchMaintenanceBroker(options, deps = {}) {
|
|
61
|
+
const environment = inheritEnvironment(options.environment);
|
|
62
|
+
if (deps.execFile === undefined && (underTest(process.env) || underTest(environment))) {
|
|
63
|
+
throw new Error('the real Windows maintenance broker is disabled in tests; inject a fake executor');
|
|
64
|
+
}
|
|
65
|
+
if ((deps.platform ?? process.platform) !== 'win32')
|
|
66
|
+
throw new Error('the maintenance broker requires Windows');
|
|
67
|
+
const runtimePath = absolutePath(options.runtimePath, 'runtimePath');
|
|
68
|
+
const cwd = absolutePath(options.cwd, 'cwd');
|
|
69
|
+
if (!statSync(runtimePath).isFile())
|
|
70
|
+
throw new Error('the maintenance runtime is not a file');
|
|
71
|
+
if (!statSync(cwd).isDirectory())
|
|
72
|
+
throw new Error('the maintenance working directory is not a directory');
|
|
73
|
+
if (!Array.isArray(options.args))
|
|
74
|
+
throw new Error('maintenance arguments must be an array');
|
|
75
|
+
const commandLine = [runtimePath, ...options.args].map(quoteWin32Argument).join(' ');
|
|
76
|
+
if (commandLine.length >= 32_767)
|
|
77
|
+
throw new Error('the maintenance command exceeds the Windows command-line limit');
|
|
78
|
+
const payload = Buffer.from(JSON.stringify({ commandLine, cwd }), 'utf8').toString('base64');
|
|
79
|
+
// The only interpolated script data is Base64 JSON. The full environment is inherited by
|
|
80
|
+
// execFile, then read as data here rather than embedded in the PowerShell command line.
|
|
81
|
+
const script = `$ErrorActionPreference = 'Stop'
|
|
82
|
+
[Console]::OutputEncoding = New-Object System.Text.UTF8Encoding($false)
|
|
83
|
+
try {
|
|
84
|
+
$plan = [System.Text.Encoding]::UTF8.GetString([System.Convert]::FromBase64String('${payload}')) | ConvertFrom-Json
|
|
85
|
+
$environment = [string[]]@([System.Environment]::GetEnvironmentVariables('Process').GetEnumerator() | ForEach-Object { [string]$_.Key + '=' + [string]$_.Value })
|
|
86
|
+
$startup = New-CimInstance -Namespace root/cimv2 -ClassName Win32_ProcessStartup -ClientOnly -Property @{ ShowWindow = [uint16]0; CreateFlags = [uint32]1024; EnvironmentVariables = $environment }
|
|
87
|
+
$result = Invoke-CimMethod -Namespace root/cimv2 -ClassName Win32_Process -MethodName Create -Arguments @{ CommandLine = [string]$plan.commandLine; CurrentDirectory = [string]$plan.cwd; ProcessStartupInformation = $startup }
|
|
88
|
+
@{ code = [uint32]$result.ReturnValue; pid = [uint32]$result.ProcessId } | ConvertTo-Json -Compress
|
|
89
|
+
} catch {
|
|
90
|
+
[Console]::Error.WriteLine($_.Exception.Message)
|
|
91
|
+
exit 1
|
|
92
|
+
}
|
|
93
|
+
`;
|
|
94
|
+
const encoded = encodePowerShellScript(script);
|
|
95
|
+
const powershellPath = windowsPowerShellPath();
|
|
96
|
+
if (encoded.length + powershellPath.length + 100 >= 32_767)
|
|
97
|
+
throw new Error('the encoded maintenance broker command exceeds the Windows command-line limit');
|
|
98
|
+
const result = await (deps.execFile ?? defaultExecutor)(powershellPath, ['-NoLogo', '-NoProfile', '-NonInteractive', '-EncodedCommand', encoded], { windowsHide: true, shell: false, encoding: 'utf8', timeout: 30_000, maxBuffer: 64_000, env: environment });
|
|
99
|
+
let record;
|
|
100
|
+
try {
|
|
101
|
+
record = JSON.parse(result.stdout.replace(/^\uFEFF/, '').trim());
|
|
102
|
+
}
|
|
103
|
+
catch {
|
|
104
|
+
throw new Error('the Windows maintenance broker returned an unreadable result');
|
|
105
|
+
}
|
|
106
|
+
if (record === null || typeof record !== 'object' || !Number.isSafeInteger(record.code) || Number(record.code) < 0) {
|
|
107
|
+
throw new Error('the Windows maintenance broker returned an invalid result');
|
|
108
|
+
}
|
|
109
|
+
if (record.code !== 0)
|
|
110
|
+
throw new Error(`Windows maintenance broker refused process creation (WMI code ${String(record.code)})`);
|
|
111
|
+
if (!Number.isSafeInteger(record.pid) || Number(record.pid) <= 0)
|
|
112
|
+
throw new Error('the Windows maintenance broker returned no valid process id');
|
|
113
|
+
return { pid: Number(record.pid) };
|
|
114
|
+
}
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
/** Explicit bridge maintenance lifecycle, independent of the Desktop-owned HTTP request. */
|
|
2
|
+
import type { BridgeAction, BridgeActionResult } from './bridge-install.js';
|
|
3
|
+
export type MaintenancePhase = 'armed' | 'closing' | 'installing' | 'restarting' | 'verifying' | 'completed' | 'cancelled' | 'failed';
|
|
4
|
+
export interface MaintenanceState {
|
|
5
|
+
readonly phase: MaintenancePhase;
|
|
6
|
+
readonly action: BridgeAction;
|
|
7
|
+
readonly at: string;
|
|
8
|
+
readonly ok?: boolean;
|
|
9
|
+
readonly restarted?: boolean;
|
|
10
|
+
readonly pid?: number;
|
|
11
|
+
readonly error?: string;
|
|
12
|
+
readonly output?: string;
|
|
13
|
+
}
|
|
14
|
+
/** Effects are supplied by the independent worker; tests cannot close or start an application. */
|
|
15
|
+
export interface MaintenanceLifecycleDeps {
|
|
16
|
+
/** Invoke the verified Desktop's own Quit menu item. Never confirm active-task dialogs. */
|
|
17
|
+
readonly requestQuit: () => Promise<void>;
|
|
18
|
+
/** Resolve only once every GUI/helper process belonging to this installation has exited. */
|
|
19
|
+
readonly waitUntilClosed: () => Promise<void>;
|
|
20
|
+
/** The existing installer retains its own identity, ancestry and running-process checks. */
|
|
21
|
+
readonly maintain: () => Promise<BridgeActionResult>;
|
|
22
|
+
/** Reopen exactly the verified installation after it has exited. */
|
|
23
|
+
readonly restart: () => Promise<number>;
|
|
24
|
+
/** Installation verifies the new authenticated bridge; uninstall verifies the process. */
|
|
25
|
+
readonly verify: (pid: number, action: BridgeAction) => Promise<void>;
|
|
26
|
+
readonly publish: (state: MaintenanceState) => Promise<void>;
|
|
27
|
+
}
|
|
28
|
+
/**
|
|
29
|
+
* A cancelled/failed quit never reaches the installer. After a confirmed exit, reopen Desktop even
|
|
30
|
+
* when maintenance fails, and retain that failure instead of reporting a successful installation.
|
|
31
|
+
*/
|
|
32
|
+
export declare function runMaintenanceLifecycle(action: BridgeAction, deps: MaintenanceLifecycleDeps): Promise<MaintenanceState>;
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A cancelled/failed quit never reaches the installer. After a confirmed exit, reopen Desktop even
|
|
3
|
+
* when maintenance fails, and retain that failure instead of reporting a successful installation.
|
|
4
|
+
*/
|
|
5
|
+
export async function runMaintenanceLifecycle(action, deps) {
|
|
6
|
+
let closed = false;
|
|
7
|
+
let restarted = false;
|
|
8
|
+
let pid;
|
|
9
|
+
let outcome;
|
|
10
|
+
let publicationFailure;
|
|
11
|
+
const publish = async (phase, extra = {}) => {
|
|
12
|
+
const state = { phase, action, at: new Date().toISOString(), ...extra };
|
|
13
|
+
try {
|
|
14
|
+
await deps.publish(state);
|
|
15
|
+
}
|
|
16
|
+
catch (error) {
|
|
17
|
+
// Arming must be durable before any quit is requested. Later status I/O must never
|
|
18
|
+
// prevent reopening a Desktop that already exited normally.
|
|
19
|
+
if (phase === 'armed')
|
|
20
|
+
throw error;
|
|
21
|
+
publicationFailure ??= error;
|
|
22
|
+
}
|
|
23
|
+
return state;
|
|
24
|
+
};
|
|
25
|
+
await publish('armed');
|
|
26
|
+
try {
|
|
27
|
+
await deps.requestQuit();
|
|
28
|
+
await publish('closing');
|
|
29
|
+
await deps.waitUntilClosed();
|
|
30
|
+
closed = true;
|
|
31
|
+
}
|
|
32
|
+
catch (error) {
|
|
33
|
+
return await publish('cancelled', { ok: false, restarted: false, error: String(error) });
|
|
34
|
+
}
|
|
35
|
+
let failure;
|
|
36
|
+
try {
|
|
37
|
+
await publish('installing');
|
|
38
|
+
outcome = await deps.maintain();
|
|
39
|
+
if (!outcome.ok)
|
|
40
|
+
throw new Error(outcome.output || 'bridge maintenance failed');
|
|
41
|
+
}
|
|
42
|
+
catch (error) {
|
|
43
|
+
failure = error;
|
|
44
|
+
}
|
|
45
|
+
try {
|
|
46
|
+
// `closed` is set only by the successful closed-process barrier, never by a timeout.
|
|
47
|
+
if (!closed)
|
|
48
|
+
throw new Error('Desktop exit was not confirmed');
|
|
49
|
+
await publish('restarting');
|
|
50
|
+
pid = await deps.restart();
|
|
51
|
+
if (!Number.isSafeInteger(pid) || pid <= 0)
|
|
52
|
+
throw new Error('Desktop restart did not return a valid process');
|
|
53
|
+
restarted = true;
|
|
54
|
+
await publish('verifying', { pid, restarted });
|
|
55
|
+
await deps.verify(pid, failure === undefined ? action : 'uninstall');
|
|
56
|
+
}
|
|
57
|
+
catch (error) {
|
|
58
|
+
failure = failure === undefined ? error : new Error(`${String(failure)}; Desktop recovery: ${String(error)}`);
|
|
59
|
+
}
|
|
60
|
+
if (failure === undefined && publicationFailure !== undefined) {
|
|
61
|
+
failure = new Error(`Desktop maintenance finished, but progress could not be saved: ${String(publicationFailure)}`);
|
|
62
|
+
}
|
|
63
|
+
const details = { restarted, ...pid === undefined ? {} : { pid }, ...outcome?.output ? { output: outcome.output } : {} };
|
|
64
|
+
return failure === undefined
|
|
65
|
+
? await publish('completed', { ...details, ok: true })
|
|
66
|
+
: await publish('failed', { ...details, ok: false, error: String(failure) });
|
|
67
|
+
}
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
/** Authenticated explicit maintenance protocol; older hosts cannot mistake it for direct install. */
|
|
2
|
+
import type { IncomingMessage, ServerResponse } from 'node:http';
|
|
3
|
+
import type { BridgeAction } from './bridge-install.js';
|
|
4
|
+
import type { AutomaticMaintenanceJob } from './automatic-maintenance.js';
|
|
5
|
+
export declare const AUTOMATIC_MAINTENANCE_ROUTE = "/dsh-builtin-browser/bridge-maintenance";
|
|
6
|
+
export interface AutomaticMaintenanceRouteDeps {
|
|
7
|
+
readonly supported: () => boolean;
|
|
8
|
+
readonly read: () => AutomaticMaintenanceJob | undefined;
|
|
9
|
+
readonly start: (action: BridgeAction, options?: {
|
|
10
|
+
readonly locale?: 'zh' | 'en';
|
|
11
|
+
}) => Promise<AutomaticMaintenanceJob>;
|
|
12
|
+
/** Commit only after the accepted response has been flushed to the client. */
|
|
13
|
+
readonly commit?: (id: string) => Promise<void>;
|
|
14
|
+
/** True while the legacy bridge-action route is running an installer. */
|
|
15
|
+
readonly busy?: () => boolean;
|
|
16
|
+
}
|
|
17
|
+
/** Register behind the host's signed-session authentication, as with settings writes. */
|
|
18
|
+
export declare function createAutomaticMaintenanceHandler(deps: AutomaticMaintenanceRouteDeps): (request: IncomingMessage, response: ServerResponse) => Promise<void>;
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
import { sameOrigin } from './settings-route.js';
|
|
2
|
+
import { isDirectLoopback } from './authenticated-route.js';
|
|
3
|
+
import { replyJson } from './json-reply.js';
|
|
4
|
+
import { readJsonBody } from './http-body.js';
|
|
5
|
+
export const AUTOMATIC_MAINTENANCE_ROUTE = '/dsh-builtin-browser/bridge-maintenance';
|
|
6
|
+
/** Register behind the host's signed-session authentication, as with settings writes. */
|
|
7
|
+
export function createAutomaticMaintenanceHandler(deps) {
|
|
8
|
+
let starting = false;
|
|
9
|
+
return async (request, response) => {
|
|
10
|
+
if (request.method !== 'GET' && request.method !== 'POST') {
|
|
11
|
+
replyJson(response, 405, { ok: false, error: 'method-not-allowed' });
|
|
12
|
+
return;
|
|
13
|
+
}
|
|
14
|
+
if (!sameOrigin(request, request.method === 'POST')) {
|
|
15
|
+
replyJson(response, 403, { ok: false, error: 'not-same-origin' });
|
|
16
|
+
return;
|
|
17
|
+
}
|
|
18
|
+
if (!isDirectLoopback(request)) {
|
|
19
|
+
replyJson(response, 403, { ok: false, error: 'local-request-required' });
|
|
20
|
+
return;
|
|
21
|
+
}
|
|
22
|
+
if (request.method === 'GET') {
|
|
23
|
+
const job = deps.read();
|
|
24
|
+
replyJson(response, 200, { ok: true, protocol: 1, supported: deps.supported(), ...job === undefined ? {} : { job } });
|
|
25
|
+
return;
|
|
26
|
+
}
|
|
27
|
+
if (!deps.supported()) {
|
|
28
|
+
replyJson(response, 409, { ok: false, error: 'automatic bridge maintenance requires Windows Desktop' });
|
|
29
|
+
return;
|
|
30
|
+
}
|
|
31
|
+
let action;
|
|
32
|
+
let locale;
|
|
33
|
+
try {
|
|
34
|
+
const value = await readJsonBody(request, 4096);
|
|
35
|
+
if (value?.action !== 'install' && value?.action !== 'uninstall')
|
|
36
|
+
throw new Error('action must be install or uninstall');
|
|
37
|
+
if (value.locale !== undefined && value.locale !== 'zh' && value.locale !== 'en')
|
|
38
|
+
throw new Error('locale must be zh or en');
|
|
39
|
+
action = value.action;
|
|
40
|
+
locale = value.locale;
|
|
41
|
+
}
|
|
42
|
+
catch (error) {
|
|
43
|
+
replyJson(response, 400, { ok: false, error: String(error) });
|
|
44
|
+
return;
|
|
45
|
+
}
|
|
46
|
+
if (starting || deps.busy?.() === true) {
|
|
47
|
+
replyJson(response, 409, { ok: false, error: 'bridge maintenance is already starting' });
|
|
48
|
+
return;
|
|
49
|
+
}
|
|
50
|
+
starting = true;
|
|
51
|
+
try {
|
|
52
|
+
const job = await deps.start(action, locale === undefined ? undefined : { locale });
|
|
53
|
+
if (deps.commit !== undefined) {
|
|
54
|
+
let fired = false;
|
|
55
|
+
const commitOnce = () => {
|
|
56
|
+
if (fired)
|
|
57
|
+
return;
|
|
58
|
+
fired = true;
|
|
59
|
+
void deps.commit?.(job.id).catch(error => { console.error('dsh-builtin-browser: bridge maintenance commit failed:', String(error)); });
|
|
60
|
+
};
|
|
61
|
+
// A client that refreshes or disconnects may fire `close` without `finish`; the worker
|
|
62
|
+
// must be committed (or explicitly cancelled) on either path, exactly once.
|
|
63
|
+
response.once('finish', commitOnce);
|
|
64
|
+
response.once('close', commitOnce);
|
|
65
|
+
}
|
|
66
|
+
replyJson(response, 202, { ok: true, accepted: true, protocol: 1, job });
|
|
67
|
+
}
|
|
68
|
+
catch (error) {
|
|
69
|
+
replyJson(response, 409, { ok: false, error: String(error) });
|
|
70
|
+
}
|
|
71
|
+
finally {
|
|
72
|
+
starting = false;
|
|
73
|
+
}
|
|
74
|
+
};
|
|
75
|
+
}
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Where DSH keeps the plugin's per-user state.
|
|
3
|
+
*
|
|
4
|
+
* Every reader — settings, history, the profile root, the maintenance plan and the desktop
|
|
5
|
+
* bridge endpoint — must resolve DSH_HOME the same way. The expression used to be inlined in
|
|
6
|
+
* each module, which let one of them drift to a different directory and produced two
|
|
7
|
+
* half-profiles that never met (see the note in entry.ts).
|
|
8
|
+
* @module dsh-browser/browser-electron/paths
|
|
9
|
+
*/
|
|
10
|
+
import { homedir } from 'node:os';
|
|
11
|
+
import { join } from 'node:path';
|
|
12
|
+
/** Absolute path of the DSH home directory; DSH_HOME overrides the per-user default. */
|
|
13
|
+
export function dshHome() {
|
|
14
|
+
return process.env.DSH_HOME ?? join(homedir(), '.dsh');
|
|
15
|
+
}
|
|
16
|
+
/** Absolute path of the endpoint file the running desktop shell publishes. */
|
|
17
|
+
export function bridgeEndpointPath() {
|
|
18
|
+
return join(dshHome(), 'dsh-builtin-browser-bridge.json');
|
|
19
|
+
}
|
|
@@ -0,0 +1,14 @@
|
|
|
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
|
+
* Whether a process with this pid exists, without signalling it.
|
|
11
|
+
* @param pid - the process id to test; a non-integer or non-positive value is never alive.
|
|
12
|
+
* @returns whether that process exists.
|
|
13
|
+
*/
|
|
14
|
+
export declare function pidAlive(pid: number): boolean;
|
|
@@ -0,0 +1,24 @@
|
|
|
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
|
+
* Whether a process with this pid exists, without signalling it.
|
|
11
|
+
* @param pid - the process id to test; a non-integer or non-positive value is never alive.
|
|
12
|
+
* @returns whether that process exists.
|
|
13
|
+
*/
|
|
14
|
+
export function pidAlive(pid) {
|
|
15
|
+
if (!Number.isSafeInteger(pid) || pid <= 0)
|
|
16
|
+
return false;
|
|
17
|
+
try {
|
|
18
|
+
process.kill(pid, 0);
|
|
19
|
+
return true;
|
|
20
|
+
}
|
|
21
|
+
catch (error) {
|
|
22
|
+
return error?.code === 'EPERM';
|
|
23
|
+
}
|
|
24
|
+
}
|
|
@@ -428,13 +428,14 @@ export declare function toCdpCookie(cookie: ExportedCookie): Record<string, unkn
|
|
|
428
428
|
* `quiet` is the resolved `ui.quiet` switch. It does not mean "invisible": Chromium drops
|
|
429
429
|
* synthesized `Input.*` for a view without a display surface, so input still needs one. It means
|
|
430
430
|
* the carrier must get that surface without taking the screen over — no application activation
|
|
431
|
-
* and no keyboard focus.
|
|
432
|
-
*
|
|
433
|
-
*
|
|
434
|
-
* the desktop sidebar) simply ignores it.
|
|
431
|
+
* and no operating-system keyboard focus. New windows open inactive; a minimized window and the
|
|
432
|
+
* foreground window's selected page remain under the operator's control. DOM focus and CDP input
|
|
433
|
+
* still target the task's page. Explicit sidebar navigation can select the task's pane.
|
|
435
434
|
*/
|
|
436
435
|
export interface PresentOptions {
|
|
437
436
|
readonly quiet?: boolean;
|
|
437
|
+
/** Explicit navigation or tab selection may change the task's sidebar tab without OS activation. */
|
|
438
|
+
readonly select?: boolean;
|
|
438
439
|
}
|
|
439
440
|
/**
|
|
440
441
|
* How a command should reach its page.
|
|
@@ -763,9 +764,8 @@ export declare class ElectronBrowserProvider implements BrowserProvider {
|
|
|
763
764
|
private admitSavePath;
|
|
764
765
|
/**
|
|
765
766
|
* Download an HTTP(S) URL with the session's cookies to a local file.
|
|
766
|
-
* Admission is the shared {@link admitSavePath} gate
|
|
767
|
-
*
|
|
768
|
-
* to the real browser UI). Both admitted paths and screenshots are confined
|
|
767
|
+
* Admission is the shared {@link admitSavePath} gate. The carrier downloads
|
|
768
|
+
* with its own authenticated browser session. Both admitted paths and screenshots are confined
|
|
769
769
|
* to `downloadDir`, so a prompt-injected agent cannot write arbitrary
|
|
770
770
|
* machine paths.
|
|
771
771
|
* @param session - the session whose cookies are used.
|
|
@@ -415,7 +415,7 @@ export class ElectronBrowserProvider {
|
|
|
415
415
|
const tab = { id: `page:${match.id}`, handle, url: match.url };
|
|
416
416
|
s.tabs.push(tab);
|
|
417
417
|
s.activeIndex = s.tabs.length - 1;
|
|
418
|
-
this.showActive(s);
|
|
418
|
+
this.showActive(s, true);
|
|
419
419
|
return true;
|
|
420
420
|
}
|
|
421
421
|
catch {
|
|
@@ -501,7 +501,7 @@ export class ElectronBrowserProvider {
|
|
|
501
501
|
}
|
|
502
502
|
const found = this.locateTab(session, tabId);
|
|
503
503
|
found.s.activeIndex = found.index;
|
|
504
|
-
this.showActive(found.s);
|
|
504
|
+
this.showActive(found.s, true);
|
|
505
505
|
}
|
|
506
506
|
/** Close one tab; closing the active tab activates the next. */
|
|
507
507
|
closeTab(session, tabId) {
|
|
@@ -632,7 +632,7 @@ export class ElectronBrowserProvider {
|
|
|
632
632
|
tab.url = url;
|
|
633
633
|
await this.settleDocument(handle, before, signal);
|
|
634
634
|
this.recordVisit(s, handle);
|
|
635
|
-
this.showActive(s);
|
|
635
|
+
this.showActive(s, true);
|
|
636
636
|
}
|
|
637
637
|
catch (error) {
|
|
638
638
|
if (!(error instanceof BrowserError && error.code === 'BROWSER_NAVIGATION_BLOCKED')) {
|
|
@@ -2494,9 +2494,8 @@ export class ElectronBrowserProvider {
|
|
|
2494
2494
|
}
|
|
2495
2495
|
/**
|
|
2496
2496
|
* Download an HTTP(S) URL with the session's cookies to a local file.
|
|
2497
|
-
* Admission is the shared {@link admitSavePath} gate
|
|
2498
|
-
*
|
|
2499
|
-
* to the real browser UI). Both admitted paths and screenshots are confined
|
|
2497
|
+
* Admission is the shared {@link admitSavePath} gate. The carrier downloads
|
|
2498
|
+
* with its own authenticated browser session. Both admitted paths and screenshots are confined
|
|
2500
2499
|
* to `downloadDir`, so a prompt-injected agent cannot write arbitrary
|
|
2501
2500
|
* machine paths.
|
|
2502
2501
|
* @param session - the session whose cookies are used.
|
|
@@ -2529,7 +2528,7 @@ export class ElectronBrowserProvider {
|
|
|
2529
2528
|
const savePath = this.admitSavePath(request.savePath, 'download');
|
|
2530
2529
|
const downloadable = handle;
|
|
2531
2530
|
if (typeof downloadable.download !== 'function') {
|
|
2532
|
-
throw new BrowserError('browser:
|
|
2531
|
+
throw new BrowserError('browser: the selected carrier does not provide file downloads', 'BROWSER_DOWNLOAD_UNSUPPORTED');
|
|
2533
2532
|
}
|
|
2534
2533
|
// The child fetches and writes the file; a slow/hung network can block
|
|
2535
2534
|
// it well past the tool budget, so bound it. NOTE: unlike CDP calls,
|
|
@@ -2621,10 +2620,10 @@ export class ElectronBrowserProvider {
|
|
|
2621
2620
|
if (dropped > 0) {
|
|
2622
2621
|
process.stderr.write(`[dsh-browser] restoreAuth: dropped ${dropped} of ${mapped.length} cookie(s) with no usable domain; the rest were still restored\n`);
|
|
2623
2622
|
}
|
|
2624
|
-
|
|
2625
|
-
// Storage.setCookies returns nothing, so the count comes from what was actually
|
|
2626
|
-
//
|
|
2627
|
-
// "Restored 0 cookies."
|
|
2623
|
+
await withTimeout(handle.sendCommand('Storage.setCookies', { cookies: convertible }), timeoutMs, undefined, `browser: auth restore timed out after ${timeoutMs}ms`);
|
|
2624
|
+
// Storage.setCookies returns nothing, so the count comes from what was actually sent.
|
|
2625
|
+
// An earlier version read result.cookies here; it was always undefined and rendered as
|
|
2626
|
+
// "Restored 0 cookies." even though the write had succeeded.
|
|
2628
2627
|
const restored = convertible.length;
|
|
2629
2628
|
this.record(s, 'restoreAuth', { count: cookies.length, dropped }, true, { result: `${restored} cookies (CDP)${dropped > 0 ? `; ${dropped} dropped` : ''}` });
|
|
2630
2629
|
return restored;
|
|
@@ -3188,10 +3187,10 @@ export class ElectronBrowserProvider {
|
|
|
3188
3187
|
* method did nothing at all on carriers without `collapse` (the self-hosted one),
|
|
3189
3188
|
* silently desynchronising the two and failing every screenshot.
|
|
3190
3189
|
*/
|
|
3191
|
-
showActive(s) {
|
|
3190
|
+
showActive(s, select = false) {
|
|
3192
3191
|
const quiet = this.isQuiet();
|
|
3193
|
-
this.host.showView?.(this.activeTab(s).handle, s.label, { quiet });
|
|
3194
|
-
if (quiet)
|
|
3192
|
+
this.host.showView?.(this.activeTab(s).handle, s.label, { quiet, ...select ? { select: true } : {} });
|
|
3193
|
+
if (quiet || select)
|
|
3195
3194
|
return;
|
|
3196
3195
|
const autoExpand = this.settingsSource === undefined || this.settingsSource().ui.autoExpandOnce;
|
|
3197
3196
|
if (autoExpand)
|