dsh-builtin-browser 0.4.1 → 0.4.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.en.md +61 -23
- package/README.md +59 -23
- package/client.js +60 -5
- package/cordis.patch.yml +21 -0
- package/desktop-bridge/plugin-browser-bridge.js +12 -4
- package/docs/architecture.md +12 -2
- package/docs/tool-reference.md +12 -12
- package/docs/user-guide.md +10 -3
- package/docs/why-browser.md +1 -1
- package/lib/browser/types.d.ts +25 -1
- package/lib/browser-electron/bridge-connection.d.ts +31 -5
- package/lib/browser-electron/bridge-connection.js +143 -21
- package/lib/browser-electron/entry.d.ts +1 -1
- package/lib/browser-electron/entry.js +61 -35
- package/lib/browser-electron/ephemeral-profile.d.ts +37 -0
- package/lib/browser-electron/ephemeral-profile.js +146 -0
- package/lib/browser-electron/history-store.d.ts +25 -0
- package/lib/browser-electron/history-store.js +51 -4
- package/lib/browser-electron/host-main.js +75 -27
- package/lib/browser-electron/provider.d.ts +44 -1
- package/lib/browser-electron/provider.js +379 -48
- package/lib/browser-electron/remote-host.d.ts +52 -3
- package/lib/browser-electron/remote-host.js +244 -23
- package/lib/browser-electron/settings-route.d.ts +28 -0
- package/lib/browser-electron/settings-route.js +28 -0
- package/lib/browser-electron/settings-store.d.ts +40 -0
- package/lib/browser-electron/settings-store.js +107 -11
- package/lib/browser-electron/system-browser.d.ts +71 -3
- package/lib/browser-electron/system-browser.js +311 -40
- package/lib/tool-browser/index.js +142 -33
- package/package.json +5 -3
- package/scripts/verify-host-compat.mjs +195 -0
- package/src/browser/types.ts +25 -1
- package/src/browser-electron/bridge-connection.ts +142 -21
- package/src/browser-electron/entry.ts +58 -33
- package/src/browser-electron/ephemeral-profile.ts +152 -0
- package/src/browser-electron/history-store.ts +51 -4
- package/src/browser-electron/host-main.ts +105 -35
- package/src/browser-electron/provider.ts +401 -51
- package/src/browser-electron/remote-host.ts +261 -36
- package/src/browser-electron/settings-route.ts +46 -0
- package/src/browser-electron/settings-store.ts +121 -11
- package/src/browser-electron/system-browser.ts +302 -26
- package/src/tool-browser/index.ts +143 -35
|
@@ -19,9 +19,11 @@
|
|
|
19
19
|
* that connection proves knowledge of the random per-spawn token (passed to
|
|
20
20
|
* the child via its stdin (first line, never in argv). A local process that
|
|
21
21
|
* connects to the loopback port without the token can neither impersonate the
|
|
22
|
-
* child nor inject replies — it is disconnected
|
|
23
|
-
* only written after the hello authenticates,
|
|
24
|
-
*
|
|
22
|
+
* child nor inject replies — it is disconnected as soon as its first line
|
|
23
|
+
* arrives. Commands are only written after the hello authenticates, and every
|
|
24
|
+
* other inbound op (including the fire-and-forget `userAction` / `viewClosed`
|
|
25
|
+
* notifications) is dispatched only once that check has passed, so an
|
|
26
|
+
* unauthenticated peer can neither read traffic nor drive a session.
|
|
25
27
|
* @module dsh-browser/browser-electron/remote-host
|
|
26
28
|
*/
|
|
27
29
|
import type { BrowserUserAction, ElectronBrowserViewHost, ElectronViewHandle } from './provider.js';
|
|
@@ -113,6 +115,12 @@ export declare class RemoteElectronViewHost implements ElectronBrowserViewHost {
|
|
|
113
115
|
private electronAvailable;
|
|
114
116
|
/** Earliest time the next probe may run after a negative one. */
|
|
115
117
|
private nextProbeAt;
|
|
118
|
+
/** Consecutive child starts that did not survive; drives {@link startRetryAt}. */
|
|
119
|
+
private startFailures;
|
|
120
|
+
/** Earliest time `ready()` may spawn another child after a failed start. */
|
|
121
|
+
private startRetryAt;
|
|
122
|
+
/** When the last start failure was reported, used to keep one death to one log line. */
|
|
123
|
+
private lastStartFailureAt;
|
|
116
124
|
/** Window groups (windowId per view), re-sent on every materialization so
|
|
117
125
|
* a restarted child still places views in the right windows. */
|
|
118
126
|
private readonly groups;
|
|
@@ -145,6 +153,26 @@ export declare class RemoteElectronViewHost implements ElectronBrowserViewHost {
|
|
|
145
153
|
* on a cooldown heals it by itself while keeping the scan off the hot path.
|
|
146
154
|
*/
|
|
147
155
|
available(): boolean;
|
|
156
|
+
/**
|
|
157
|
+
* Retire the cached "an Electron binary is here" answer.
|
|
158
|
+
*
|
|
159
|
+
* A success is cached for the host's lifetime because rescanning on every tool call was
|
|
160
|
+
* the original bug — but the probe reads the FILESYSTEM, so it cannot see a binary that
|
|
161
|
+
* stops being usable afterwards. Only a real spawn attempt can observe that, which is why
|
|
162
|
+
* the two failure paths in {@link RemoteElectronViewHost.start} call this: the next
|
|
163
|
+
* `available()` rescans and reports what is actually on disk, instead of advertising a
|
|
164
|
+
* provider that cannot start.
|
|
165
|
+
*/
|
|
166
|
+
private forgetBinary;
|
|
167
|
+
/**
|
|
168
|
+
* Whether the binary the host would spawn — or the entry it needs — is no longer there.
|
|
169
|
+
*
|
|
170
|
+
* Only asked after a launch actually failed, so a healthy path never pays for it. The
|
|
171
|
+
* entry script counts because Electron exits 1 with empty stderr when it cannot load it,
|
|
172
|
+
* and resolution itself throws exactly when it can find nothing, which is the same answer.
|
|
173
|
+
* @returns true when the next `available()` must rescan instead of reusing its cache.
|
|
174
|
+
*/
|
|
175
|
+
private binaryIsGone;
|
|
148
176
|
/**
|
|
149
177
|
* Ensure the child is up and ready (lazy on first use; restarts after a crash).
|
|
150
178
|
*
|
|
@@ -155,6 +183,27 @@ export declare class RemoteElectronViewHost implements ElectronBrowserViewHost {
|
|
|
155
183
|
* instead, which those callers already handle.
|
|
156
184
|
*/
|
|
157
185
|
private ready;
|
|
186
|
+
/**
|
|
187
|
+
* Record one child that did not survive, and set the earliest retry time.
|
|
188
|
+
*
|
|
189
|
+
* `available()` answers "is there a binary to spawn" from the FILESYSTEM, and a success
|
|
190
|
+
* there is cached for the host's lifetime (correctly — rescanning on every tool call was
|
|
191
|
+
* the bug). That probe therefore cannot see the failure mode where the binary exists and
|
|
192
|
+
* crashes on every launch: the signature `code=1` with empty stderr that host-log.test.mjs
|
|
193
|
+
* asserts. Each browser call then spawned a child that died within milliseconds, with no
|
|
194
|
+
* backoff and nothing that ever gives up — an endless crash loop, each iteration a window
|
|
195
|
+
* flashing on screen.
|
|
196
|
+
*
|
|
197
|
+
* The first retry is immediate, so the ordinary transient death (the DSH restart in
|
|
198
|
+
* remote-host-recovery.test.mjs) still heals on the very next call. After that the delay
|
|
199
|
+
* grows: once {@link START_FAILURES_MAX} attempts have failed, every later attempt is
|
|
200
|
+
* spaced by the table's last entry — the host keeps trying, but a permanently broken
|
|
201
|
+
* install now costs one spawn per 30s instead of one per tool call. Nothing is marked
|
|
202
|
+
* dead for good: a repaired installation heals on the next attempt, and `dispose()`
|
|
203
|
+
* still stops everything immediately.
|
|
204
|
+
* @param error - what the failed attempt reported.
|
|
205
|
+
*/
|
|
206
|
+
private noteStartFailure;
|
|
158
207
|
private start;
|
|
159
208
|
/** The child died: tear down so the next use starts a fresh child. */
|
|
160
209
|
private onChildExit;
|
|
@@ -19,9 +19,11 @@
|
|
|
19
19
|
* that connection proves knowledge of the random per-spawn token (passed to
|
|
20
20
|
* the child via its stdin (first line, never in argv). A local process that
|
|
21
21
|
* connects to the loopback port without the token can neither impersonate the
|
|
22
|
-
* child nor inject replies — it is disconnected
|
|
23
|
-
* only written after the hello authenticates,
|
|
24
|
-
*
|
|
22
|
+
* child nor inject replies — it is disconnected as soon as its first line
|
|
23
|
+
* arrives. Commands are only written after the hello authenticates, and every
|
|
24
|
+
* other inbound op (including the fire-and-forget `userAction` / `viewClosed`
|
|
25
|
+
* notifications) is dispatched only once that check has passed, so an
|
|
26
|
+
* unauthenticated peer can neither read traffic nor drive a session.
|
|
25
27
|
* @module dsh-browser/browser-electron/remote-host
|
|
26
28
|
*/
|
|
27
29
|
import { execFileSync, spawn } from 'node:child_process';
|
|
@@ -458,6 +460,9 @@ class ElectronChildClient {
|
|
|
458
460
|
const line = `${hostStamp()} spawn error: ${String(error)} electron=${electron} hostMain=${this.hostMainPath}`;
|
|
459
461
|
process.stderr.write(`[dsh-browser host] ${line}\n`);
|
|
460
462
|
appendHostLog(`${line}\n`);
|
|
463
|
+
// The cached availability answer is retired by `onExit` below, which this reaches
|
|
464
|
+
// through fail(): the decision needs the host's view of what is on disk, not the
|
|
465
|
+
// client's.
|
|
461
466
|
this.fail(new Error(`dsh-builtin-browser: browser host failed to start: ${String(error)}`));
|
|
462
467
|
});
|
|
463
468
|
this.child.on('exit', (code, signal) => {
|
|
@@ -479,12 +484,38 @@ class ElectronChildClient {
|
|
|
479
484
|
this.fail(new Error(`dsh-builtin-browser: ${line}`));
|
|
480
485
|
});
|
|
481
486
|
}
|
|
487
|
+
/**
|
|
488
|
+
* Drop the escalation kill once there is nothing left for it to target.
|
|
489
|
+
*
|
|
490
|
+
* Without this the timer would keep the parent's event loop alive for its full grace period
|
|
491
|
+
* after exactly the ordinary exit it was armed to catch as the bad case — and the child does
|
|
492
|
+
* not need killing once `fail()` has run for it.
|
|
493
|
+
*/
|
|
494
|
+
clearKillGrace() {
|
|
495
|
+
if (this.killGraceTimer === undefined)
|
|
496
|
+
return;
|
|
497
|
+
clearTimeout(this.killGraceTimer);
|
|
498
|
+
this.killGraceTimer = undefined;
|
|
499
|
+
}
|
|
500
|
+
/** Drop the "did not authenticate" deadline once it can no longer be meaningful. */
|
|
501
|
+
clearHelloTimer() {
|
|
502
|
+
if (this.helloTimer === undefined)
|
|
503
|
+
return;
|
|
504
|
+
clearTimeout(this.helloTimer);
|
|
505
|
+
this.helloTimer = undefined;
|
|
506
|
+
}
|
|
482
507
|
/** Reject everything in flight, mark the client dead, and notify the host. */
|
|
483
508
|
fail(err) {
|
|
484
509
|
if (this.dead)
|
|
485
510
|
return;
|
|
486
511
|
this.dead = true;
|
|
487
512
|
this.connected = false;
|
|
513
|
+
// The authentication deadline outlives the socket it was armed for otherwise: it is
|
|
514
|
+
// keyed on `awaitingHello` alone, so a client that already failed on some other path
|
|
515
|
+
// kept a live timer until it fired (harmless, but it is a dangling timer in a process
|
|
516
|
+
// that may be shutting down).
|
|
517
|
+
this.clearHelloTimer();
|
|
518
|
+
this.clearKillGrace();
|
|
488
519
|
// Tag every failure as "host gone" so the view layer can tell a dead host
|
|
489
520
|
// apart from a page-level error and rebuild against a fresh child.
|
|
490
521
|
const wrapped = err instanceof HostGoneError ? err : new HostGoneError(err.message);
|
|
@@ -557,19 +588,35 @@ class ElectronChildClient {
|
|
|
557
588
|
// Non-protocol line; ignore.
|
|
558
589
|
continue;
|
|
559
590
|
}
|
|
560
|
-
if (msg.op === 'userAction') {
|
|
561
|
-
//
|
|
562
|
-
//
|
|
563
|
-
//
|
|
564
|
-
|
|
565
|
-
|
|
566
|
-
|
|
567
|
-
|
|
568
|
-
//
|
|
569
|
-
// the
|
|
570
|
-
//
|
|
571
|
-
//
|
|
572
|
-
this.
|
|
591
|
+
if (msg.op === 'userAction' || msg.op === 'viewClosed') {
|
|
592
|
+
// A fire-and-forget notification from the child's own UI (toolbar). These carry no
|
|
593
|
+
// reply and no pending id, and they hand the provider a session-level verb — so they
|
|
594
|
+
// are dispatched ONLY once the peer has proved it knows the spawn token.
|
|
595
|
+
//
|
|
596
|
+
// They used to be handled before the hello check, while the module comment claimed an
|
|
597
|
+
// unauthenticated peer "is disconnected immediately … a spoofed socket never sees
|
|
598
|
+
// traffic". Both were wrong: any loopback process that won the race for the single
|
|
599
|
+
// accepted socket could inject `viewClosed` and end the human's browser session
|
|
600
|
+
// before the token check rejected it. Only the loopback interface can connect, so
|
|
601
|
+
// this is a same-machine race rather than a remote attack — which is exactly the
|
|
602
|
+
// kind of thing the token exists to close.
|
|
603
|
+
if (this.awaitingHello) {
|
|
604
|
+
this.awaitingHello = false;
|
|
605
|
+
this.clearHelloTimer();
|
|
606
|
+
this.socket?.destroy();
|
|
607
|
+
this.fail(new Error('dsh-builtin-browser: browser host sent a notification before authenticating'));
|
|
608
|
+
return;
|
|
609
|
+
}
|
|
610
|
+
if (msg.op === 'userAction') {
|
|
611
|
+
// Route it straight to the host's user-action handler (which the provider registered).
|
|
612
|
+
this.onUserAction?.(msg.action);
|
|
613
|
+
}
|
|
614
|
+
else {
|
|
615
|
+
// The human closed the window, so the interface that session showed is gone. The
|
|
616
|
+
// provider decides what that ends — browsing history and login state survive on
|
|
617
|
+
// disk, only the session itself does not.
|
|
618
|
+
this.onViewClosed?.(typeof msg.windowId === 'string' ? msg.windowId : '');
|
|
619
|
+
}
|
|
573
620
|
continue;
|
|
574
621
|
}
|
|
575
622
|
if (this.awaitingHello) {
|
|
@@ -577,10 +624,7 @@ class ElectronChildClient {
|
|
|
577
624
|
// Anything else (or a wrong token) means a spoofed connection: drop
|
|
578
625
|
// it and fail every pending call rather than trust the line.
|
|
579
626
|
this.awaitingHello = false;
|
|
580
|
-
|
|
581
|
-
clearTimeout(this.helloTimer);
|
|
582
|
-
this.helloTimer = undefined;
|
|
583
|
-
}
|
|
627
|
+
this.clearHelloTimer();
|
|
584
628
|
if (msg.op !== 'hello' || msg.token !== this.token) {
|
|
585
629
|
this.socket?.destroy();
|
|
586
630
|
this.fail(new Error('dsh-builtin-browser: browser host authentication failed'));
|
|
@@ -635,13 +679,43 @@ class ElectronChildClient {
|
|
|
635
679
|
}
|
|
636
680
|
});
|
|
637
681
|
}
|
|
638
|
-
/**
|
|
682
|
+
/**
|
|
683
|
+
* How long the child gets to exit by itself after the socket closes, before it is killed.
|
|
684
|
+
* The child quits on that signal, so in practice this is a few dozen milliseconds; the timer
|
|
685
|
+
* exists for the case where it does not, and it is deliberately NOT unref'd — the parent must
|
|
686
|
+
* stay alive long enough to enforce it, or the escalation would be dropped with the process.
|
|
687
|
+
*/
|
|
688
|
+
static KILL_GRACE_MS = 500;
|
|
689
|
+
killGraceTimer;
|
|
690
|
+
/**
|
|
691
|
+
* Terminate the child, after giving it the chance to shut down properly.
|
|
692
|
+
*
|
|
693
|
+
* The socket goes first, because that is the signal the child actually handles: its `close`
|
|
694
|
+
* listener quits the app, and a normal quit is what lets Chromium write its profile out. Only
|
|
695
|
+
* a child still alive after the grace period is killed outright.
|
|
696
|
+
*
|
|
697
|
+
* This order used to be the other way round, justified by a comment claiming the child's own
|
|
698
|
+
* path "closes its window and flushes the profile", which made killing first the safer order.
|
|
699
|
+
* Both halves of that were wrong: the path ran `app.exit(0)`, which skips before-quit/will-quit
|
|
700
|
+
* and does not flush Chromium's profile writers at all; and on Windows `child.kill()` is
|
|
701
|
+
* TerminateProcess, which lands before the child can run any handler whatsoever. So the
|
|
702
|
+
* graceful path that comment was protecting never got to start, and the profile went
|
|
703
|
+
* unflushed on every single dispose.
|
|
704
|
+
*/
|
|
639
705
|
kill() {
|
|
706
|
+
this.clearHelloTimer();
|
|
640
707
|
try {
|
|
641
708
|
this.socket?.destroy();
|
|
642
709
|
}
|
|
643
710
|
catch { /* already closed */ }
|
|
644
|
-
this.child
|
|
711
|
+
const child = this.child;
|
|
712
|
+
this.clearKillGrace();
|
|
713
|
+
this.killGraceTimer = setTimeout(() => {
|
|
714
|
+
try {
|
|
715
|
+
child.kill();
|
|
716
|
+
}
|
|
717
|
+
catch { /* already gone */ }
|
|
718
|
+
}, ElectronChildClient.KILL_GRACE_MS);
|
|
645
719
|
}
|
|
646
720
|
}
|
|
647
721
|
/** One view in the child: its id, used for every command. */
|
|
@@ -691,6 +765,26 @@ const PROBE_RETRY_MS = (() => {
|
|
|
691
765
|
const raw = Number(process.env.DSH_BROWSER_PROBE_RETRY_MS);
|
|
692
766
|
return Number.isFinite(raw) && raw >= 0 ? raw : 30000;
|
|
693
767
|
})();
|
|
768
|
+
/**
|
|
769
|
+
* Retry schedule for a browser host that will not stay up, in milliseconds, indexed by the
|
|
770
|
+
* number of consecutive failed starts (see {@link RemoteElectronViewHost.noteStartFailure}).
|
|
771
|
+
*
|
|
772
|
+
* The first entry is 0 on purpose: an ordinary one-off death must still heal on the very
|
|
773
|
+
* next call, which is the behaviour remote-host-recovery.test.mjs pins. From the second
|
|
774
|
+
* failure on, each attempt is spaced. `available()` can only answer "is there a binary",
|
|
775
|
+
* so a binary that exists and crashes on every launch (`code=1` with empty stderr) would
|
|
776
|
+
* otherwise produce an endless crash loop, one window per tool call, with nothing to make
|
|
777
|
+
* it stop.
|
|
778
|
+
*/
|
|
779
|
+
const START_RETRY_SCHEDULE_MS = [0, 500, 2_000, 8_000, 30_000];
|
|
780
|
+
/** Attempts after which the host stops retrying immediately and keeps the longest delay. */
|
|
781
|
+
const START_FAILURES_MAX = START_RETRY_SCHEDULE_MS.length;
|
|
782
|
+
/** Two reports within this window describe the same dying child, not two attempts. */
|
|
783
|
+
const START_FAILURE_DEDUPE_MS = 1_000;
|
|
784
|
+
/** Render a delay for a human-readable log line. */
|
|
785
|
+
function formatDelay(ms) {
|
|
786
|
+
return ms >= 1_000 ? `${(ms / 1_000).toFixed(1)}s` : `${String(ms)}ms`;
|
|
787
|
+
}
|
|
694
788
|
/**
|
|
695
789
|
* Self-hosted view host: spawns the plugin's Electron child on first use and
|
|
696
790
|
* keeps it alive until dispose(). Fallback when no desktop shell provides
|
|
@@ -711,6 +805,12 @@ export class RemoteElectronViewHost {
|
|
|
711
805
|
electronAvailable;
|
|
712
806
|
/** Earliest time the next probe may run after a negative one. */
|
|
713
807
|
nextProbeAt = 0;
|
|
808
|
+
/** Consecutive child starts that did not survive; drives {@link startRetryAt}. */
|
|
809
|
+
startFailures = 0;
|
|
810
|
+
/** Earliest time `ready()` may spawn another child after a failed start. */
|
|
811
|
+
startRetryAt;
|
|
812
|
+
/** When the last start failure was reported, used to keep one death to one log line. */
|
|
813
|
+
lastStartFailureAt = 0;
|
|
714
814
|
/** Window groups (windowId per view), re-sent on every materialization so
|
|
715
815
|
* a restarted child still places views in the right windows. */
|
|
716
816
|
groups = new Map();
|
|
@@ -765,6 +865,38 @@ export class RemoteElectronViewHost {
|
|
|
765
865
|
}
|
|
766
866
|
return this.electronAvailable;
|
|
767
867
|
}
|
|
868
|
+
/**
|
|
869
|
+
* Retire the cached "an Electron binary is here" answer.
|
|
870
|
+
*
|
|
871
|
+
* A success is cached for the host's lifetime because rescanning on every tool call was
|
|
872
|
+
* the original bug — but the probe reads the FILESYSTEM, so it cannot see a binary that
|
|
873
|
+
* stops being usable afterwards. Only a real spawn attempt can observe that, which is why
|
|
874
|
+
* the two failure paths in {@link RemoteElectronViewHost.start} call this: the next
|
|
875
|
+
* `available()` rescans and reports what is actually on disk, instead of advertising a
|
|
876
|
+
* provider that cannot start.
|
|
877
|
+
*/
|
|
878
|
+
forgetBinary() {
|
|
879
|
+
this.electronAvailable = undefined;
|
|
880
|
+
this.nextProbeAt = 0;
|
|
881
|
+
}
|
|
882
|
+
/**
|
|
883
|
+
* Whether the binary the host would spawn — or the entry it needs — is no longer there.
|
|
884
|
+
*
|
|
885
|
+
* Only asked after a launch actually failed, so a healthy path never pays for it. The
|
|
886
|
+
* entry script counts because Electron exits 1 with empty stderr when it cannot load it,
|
|
887
|
+
* and resolution itself throws exactly when it can find nothing, which is the same answer.
|
|
888
|
+
* @returns true when the next `available()` must rescan instead of reusing its cache.
|
|
889
|
+
*/
|
|
890
|
+
binaryIsGone() {
|
|
891
|
+
if (!existsSync(this.hostMainPath))
|
|
892
|
+
return true;
|
|
893
|
+
try {
|
|
894
|
+
return !existsSync(this.spawnExecutable ?? resolveElectronPath());
|
|
895
|
+
}
|
|
896
|
+
catch {
|
|
897
|
+
return true;
|
|
898
|
+
}
|
|
899
|
+
}
|
|
768
900
|
/**
|
|
769
901
|
* Ensure the child is up and ready (lazy on first use; restarts after a crash).
|
|
770
902
|
*
|
|
@@ -788,8 +920,35 @@ export class RemoteElectronViewHost {
|
|
|
788
920
|
}
|
|
789
921
|
if (this.readyPromise !== undefined)
|
|
790
922
|
return this.readyPromise;
|
|
923
|
+
// Backoff gate for a host that keeps failing to START (see START_RETRY_SCHEDULE_MS).
|
|
924
|
+
// The client is undefined exactly when the previous child is gone — a start failure, or
|
|
925
|
+
// a child that died after it came up — so this only delays restarts, never first use.
|
|
926
|
+
const retryAt = this.startRetryAt;
|
|
927
|
+
if (retryAt !== undefined && Date.now() < retryAt && this.client === undefined) {
|
|
928
|
+
const waitMs = retryAt - Date.now();
|
|
929
|
+
const waiting = Promise.reject(new HostGoneError(`browser host did not start; retrying in ${formatDelay(waitMs)} `
|
|
930
|
+
+ `(attempt ${String(this.startFailures)}${this.startFailures >= START_FAILURES_MAX ? ', start attempts are now spaced out rather than immediate' : ''})`));
|
|
931
|
+
// Keep the rejection observable to callers while marking it handled here: the
|
|
932
|
+
// fire-and-forget callers that drive this path attach their own handler, but one that
|
|
933
|
+
// forgets must not turn the recovery gate into an unhandled rejection.
|
|
934
|
+
waiting.catch(() => undefined);
|
|
935
|
+
return waiting;
|
|
936
|
+
}
|
|
791
937
|
const started = this.start();
|
|
792
|
-
const wrapped = started.
|
|
938
|
+
const wrapped = started.then(() => {
|
|
939
|
+
// A child that came up clears the record: the next death is a new failure, not
|
|
940
|
+
// another entry in this run of them.
|
|
941
|
+
this.startFailures = 0;
|
|
942
|
+
this.startRetryAt = undefined;
|
|
943
|
+
}, error => {
|
|
944
|
+
// Record the failure BEFORE tearing anything down, and gate the teardown on the
|
|
945
|
+
// retry state being gone rather than on readyPromise alone. Ordering matters: a
|
|
946
|
+
// child that exits while the readiness call is still in flight fires the client's
|
|
947
|
+
// 'exit' handler first (onChildExit invalidates this promise and starts the retry
|
|
948
|
+
// clock), and the rejection then lands here — at which point clearing startRetryAt
|
|
949
|
+
// would erase the very backoff that was just armed, so every tool call spawned
|
|
950
|
+
// another dying child. noteStartFailure's dedupe window counts that pair once.
|
|
951
|
+
this.noteStartFailure(error);
|
|
793
952
|
// A failed startup must not poison the host forever: tear down whatever
|
|
794
953
|
// was half-created and let the next call retry from scratch.
|
|
795
954
|
if (this.readyPromise === wrapped) {
|
|
@@ -806,6 +965,54 @@ export class RemoteElectronViewHost {
|
|
|
806
965
|
this.readyPromise = wrapped;
|
|
807
966
|
return wrapped;
|
|
808
967
|
}
|
|
968
|
+
/**
|
|
969
|
+
* Record one child that did not survive, and set the earliest retry time.
|
|
970
|
+
*
|
|
971
|
+
* `available()` answers "is there a binary to spawn" from the FILESYSTEM, and a success
|
|
972
|
+
* there is cached for the host's lifetime (correctly — rescanning on every tool call was
|
|
973
|
+
* the bug). That probe therefore cannot see the failure mode where the binary exists and
|
|
974
|
+
* crashes on every launch: the signature `code=1` with empty stderr that host-log.test.mjs
|
|
975
|
+
* asserts. Each browser call then spawned a child that died within milliseconds, with no
|
|
976
|
+
* backoff and nothing that ever gives up — an endless crash loop, each iteration a window
|
|
977
|
+
* flashing on screen.
|
|
978
|
+
*
|
|
979
|
+
* The first retry is immediate, so the ordinary transient death (the DSH restart in
|
|
980
|
+
* remote-host-recovery.test.mjs) still heals on the very next call. After that the delay
|
|
981
|
+
* grows: once {@link START_FAILURES_MAX} attempts have failed, every later attempt is
|
|
982
|
+
* spaced by the table's last entry — the host keeps trying, but a permanently broken
|
|
983
|
+
* install now costs one spawn per 30s instead of one per tool call. Nothing is marked
|
|
984
|
+
* dead for good: a repaired installation heals on the next attempt, and `dispose()`
|
|
985
|
+
* still stops everything immediately.
|
|
986
|
+
* @param error - what the failed attempt reported.
|
|
987
|
+
*/
|
|
988
|
+
noteStartFailure(error) {
|
|
989
|
+
// The same death arrives twice: the child's exit reports it, and ready() rejecting
|
|
990
|
+
// reports it again. Counting both pushed the first retry to the 500ms step and made
|
|
991
|
+
// the log say "attempt 2" for a first failure, while START_RETRY_SCHEDULE_MS[0] = 0
|
|
992
|
+
// exists precisely so an ordinary death heals on the next call. So a report inside the
|
|
993
|
+
// window is dropped ENTIRELY — the count and the log line alike.
|
|
994
|
+
//
|
|
995
|
+
// That last part used to be split in two: the guard below, and a second dedupe that only
|
|
996
|
+
// suppressed the LOG. The second one read `now - this.lastStartFailureAt` after the line
|
|
997
|
+
// above had already stored `failureAt` into that same field, so its window was 0-1ms wide
|
|
998
|
+
// and the comparison was unconditionally true — the log line was never written at all.
|
|
999
|
+
// Nothing noticed, because this function exists to make a silent failure visible and its
|
|
1000
|
+
// only output was the thing being dropped: a child that exists and dies instantly (code=1,
|
|
1001
|
+
// empty stderr) left no trace anywhere.
|
|
1002
|
+
const failureAt = Date.now();
|
|
1003
|
+
if (this.lastStartFailureAt !== undefined && failureAt - this.lastStartFailureAt < START_FAILURE_DEDUPE_MS)
|
|
1004
|
+
return;
|
|
1005
|
+
this.lastStartFailureAt = failureAt;
|
|
1006
|
+
this.startFailures += 1;
|
|
1007
|
+
const index = Math.min(this.startFailures, START_RETRY_SCHEDULE_MS.length) - 1;
|
|
1008
|
+
const delayMs = START_RETRY_SCHEDULE_MS[index] ?? 0;
|
|
1009
|
+
this.startRetryAt = delayMs > 0 ? failureAt + delayMs : undefined;
|
|
1010
|
+
const line = `${hostStamp()} browser host start failed (attempt ${String(this.startFailures)}`
|
|
1011
|
+
+ `${this.startFailures >= START_FAILURES_MAX ? ', giving up on immediate retries' : ''}): ${String(error)}`
|
|
1012
|
+
+ `${delayMs > 0 ? ` — next attempt in ${formatDelay(delayMs)}` : ''}`;
|
|
1013
|
+
process.stderr.write(`[dsh-browser host] ${line}\n`);
|
|
1014
|
+
appendHostLog(`${line}\n`);
|
|
1015
|
+
}
|
|
809
1016
|
async start() {
|
|
810
1017
|
// Listen on an ephemeral loopback port; the child connects back. The
|
|
811
1018
|
// server accepts exactly one connection: the child's. Any further
|
|
@@ -874,6 +1081,20 @@ export class RemoteElectronViewHost {
|
|
|
874
1081
|
const wasDisposed = this.disposed;
|
|
875
1082
|
if (!wasDisposed)
|
|
876
1083
|
process.stderr.write('[dsh-browser host] browser host gone; will restart on next use\n');
|
|
1084
|
+
// A child that started and then died is also a failed start, and it is the shape a crash
|
|
1085
|
+
// loop takes (the child comes up far enough to be pending on `ping`, then exits): count
|
|
1086
|
+
// it so the restart is spaced instead of attempted on every single tool call.
|
|
1087
|
+
if (!wasDisposed)
|
|
1088
|
+
this.noteStartFailure('the browser host process exited');
|
|
1089
|
+
// The cached `available()` answer came from the FILESYSTEM, so only a real attempt can
|
|
1090
|
+
// contradict it. A binary that stops being usable after the probe said yes — an
|
|
1091
|
+
// interrupted reinstall, a removed mount, a wiped cache — kept the provider advertised
|
|
1092
|
+
// as available for the rest of the process's life, because provider selection reads
|
|
1093
|
+
// that same cached yes; every later call then paid a doomed spawn. Both failure routes
|
|
1094
|
+
// (a spawn error, and a child that exits) arrive here, so this is the one place that
|
|
1095
|
+
// observes the loss, and it costs two stats on a path that is already failing.
|
|
1096
|
+
if (this.binaryIsGone())
|
|
1097
|
+
this.forgetBinary();
|
|
877
1098
|
this.client = undefined;
|
|
878
1099
|
this.server?.close();
|
|
879
1100
|
this.server = undefined;
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Admission for the settings route: who may read the document, and who may write it.
|
|
3
|
+
*
|
|
4
|
+
* Its own module for a blunt reason — `entry.ts` imports the host's peer packages (cordis, the
|
|
5
|
+
* tools registry) and therefore cannot be loaded by the test suite, while this is precisely the
|
|
6
|
+
* logic whose failure is invisible in a browser: too strict and the panel silently stops being
|
|
7
|
+
* able to save, too loose and any process on the machine can rewrite the operator's switches.
|
|
8
|
+
*
|
|
9
|
+
* It is NOT authentication, and cannot be. The plugin has no credential to check: DSH hands
|
|
10
|
+
* plugin routes the raw request (`packages/host/webserver/src/index.ts` registers handlers with
|
|
11
|
+
* no gate of its own), so the strongest same-origin evidence available is what a browser
|
|
12
|
+
* reliably sends — `Sec-Fetch-Site`, plus `Origin` on every write, same-origin included.
|
|
13
|
+
*
|
|
14
|
+
* What that buys and what it does not:
|
|
15
|
+
* - a plain HTTP client (curl, a script, another process) cannot WRITE any more, because it
|
|
16
|
+
* sends no `Origin`;
|
|
17
|
+
* - a page of THIS origin still can, because a browser sending a same-origin write looks
|
|
18
|
+
* exactly like the panel. That is inherent to exposing an HTTP endpoint at all, and it is
|
|
19
|
+
* why the settings panel's own text must not promise a lock that does not exist.
|
|
20
|
+
*/
|
|
21
|
+
import type { IncomingMessage } from 'node:http';
|
|
22
|
+
/**
|
|
23
|
+
* Whether a request may touch the settings document.
|
|
24
|
+
* @param request - the incoming request.
|
|
25
|
+
* @param writing - true for PUT/POST, which is held to the stricter rule.
|
|
26
|
+
* @returns whether the request is admitted.
|
|
27
|
+
*/
|
|
28
|
+
export declare function sameOrigin(request: IncomingMessage, writing?: boolean): boolean;
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Whether a request may touch the settings document.
|
|
3
|
+
* @param request - the incoming request.
|
|
4
|
+
* @param writing - true for PUT/POST, which is held to the stricter rule.
|
|
5
|
+
* @returns whether the request is admitted.
|
|
6
|
+
*/
|
|
7
|
+
export function sameOrigin(request, writing = false) {
|
|
8
|
+
const site = String(request.headers['sec-fetch-site'] ?? '').toLowerCase();
|
|
9
|
+
// `cross-site` is another origin entirely; `same-site` is another origin of the same site
|
|
10
|
+
// (a.example.com -> b.example.com), which is not this panel either. Both are refused.
|
|
11
|
+
if (site === 'cross-site' || site === 'same-site')
|
|
12
|
+
return false;
|
|
13
|
+
const origin = String(request.headers.origin ?? '').trim();
|
|
14
|
+
// `Origin: null` is what a sandboxed or opaque-origin document sends. Never this panel.
|
|
15
|
+
if (origin === 'null')
|
|
16
|
+
return false;
|
|
17
|
+
// Reads are let through without an Origin: they return the document the panel is already
|
|
18
|
+
// showing, and refusing them would only break hand-inspection of a file that sits readable
|
|
19
|
+
// on disk anyway. Writes are not: a browser always sends `Origin` on one.
|
|
20
|
+
if (origin === '')
|
|
21
|
+
return !writing;
|
|
22
|
+
try {
|
|
23
|
+
return new URL(origin).host.toLowerCase() === String(request.headers.host ?? '').trim().toLowerCase();
|
|
24
|
+
}
|
|
25
|
+
catch {
|
|
26
|
+
return false;
|
|
27
|
+
}
|
|
28
|
+
}
|
|
@@ -44,6 +44,22 @@ export interface BrowserSettings {
|
|
|
44
44
|
readonly credentials: {
|
|
45
45
|
readonly allowRead: boolean;
|
|
46
46
|
};
|
|
47
|
+
/**
|
|
48
|
+
* What the agent is allowed to DO, as opposed to what it may look at.
|
|
49
|
+
*
|
|
50
|
+
* These are OPERATOR switches: the settings panel is not reachable from the model, so a
|
|
51
|
+
* value here refuses whatever the model asks for, and no tool can lift it. That is what
|
|
52
|
+
* separates them from `browser_restrict`, which is the model's own soft guardrail. All
|
|
53
|
+
* three default to on, which is the documented out-of-the-box behaviour.
|
|
54
|
+
*/
|
|
55
|
+
readonly actions: {
|
|
56
|
+
/** Run arbitrary page scripts in the active tab (`browser_execute`). */
|
|
57
|
+
readonly allowExecute: boolean;
|
|
58
|
+
/** Download a URL to disk (`browser_download`). */
|
|
59
|
+
readonly allowDownload: boolean;
|
|
60
|
+
/** Write cookies — importing login state (`browser_auth` restore). */
|
|
61
|
+
readonly allowCredentialWrite: boolean;
|
|
62
|
+
};
|
|
47
63
|
}
|
|
48
64
|
/** Defaults for every switch: the documented out-of-the-box behaviour. */
|
|
49
65
|
export declare const DEFAULT_SETTINGS: BrowserSettings;
|
|
@@ -90,3 +106,27 @@ export declare class SettingsStore {
|
|
|
90
106
|
*/
|
|
91
107
|
update(patch: unknown): BrowserSettings;
|
|
92
108
|
}
|
|
109
|
+
/**
|
|
110
|
+
* Replace a file's contents atomically: write a sibling temporary file, then rename it over
|
|
111
|
+
* the target.
|
|
112
|
+
*
|
|
113
|
+
* `writeFileSync(target, …)` truncates and rewrites in place, so a crash, a full disk or an
|
|
114
|
+
* antivirus lock in the middle leaves HALF a JSON document. That used to be silent: the reader
|
|
115
|
+
* resolved an unparseable file to the defaults, so a torn write flipped `credentials.allowRead`
|
|
116
|
+
* and the action switches back ON, and the next successful update wrote those defaults to disk
|
|
117
|
+
* for good. The read side no longer does that (see {@link SETTINGS_WHEN_UNREADABLE}) — but the
|
|
118
|
+
* write side still has to stop producing torn files at all, because half a document is not
|
|
119
|
+
* something this plugin should ever leave behind.
|
|
120
|
+
*
|
|
121
|
+
* The rename is the commit point: a reader sees either the old document or the new one,
|
|
122
|
+
* never a partial one. It stays in the same directory so the rename is atomic on Windows
|
|
123
|
+
* as well as POSIX (`renameSync` maps to MoveFileEx there: same-volume replaces are
|
|
124
|
+
* atomic, cross-volume ones are not supported at all).
|
|
125
|
+
*
|
|
126
|
+
* The temporary is written with a unique suffix rather than a fixed `.tmp`, so two writers
|
|
127
|
+
* (the settings panel and a second DSH process) cannot rename each other's half-written
|
|
128
|
+
* file into place. Shared with the history store, which had the same hole.
|
|
129
|
+
* @param file - the target path.
|
|
130
|
+
* @param contents - the complete new document.
|
|
131
|
+
*/
|
|
132
|
+
export declare function writeFileAtomic(file: string, contents: string): void;
|