dsh-builtin-browser 0.5.6 → 0.5.7

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.
Files changed (63) hide show
  1. package/CHANGELOG.md +82 -0
  2. package/README.en.md +67 -99
  3. package/README.md +67 -100
  4. package/client.js +381 -322
  5. package/desktop-bridge/install.mjs +122 -33
  6. package/desktop-bridge/plugin-browser-bridge.js +9 -4
  7. package/docs/tool-reference.md +20 -1
  8. package/lib/browser/runtime.d.ts +3 -1
  9. package/lib/browser/runtime.js +9 -0
  10. package/lib/browser/types.d.ts +42 -0
  11. package/lib/browser-electron/authenticated-route.d.ts +27 -0
  12. package/lib/browser-electron/authenticated-route.js +39 -0
  13. package/lib/browser-electron/bridge-endpoint.js +7 -0
  14. package/lib/browser-electron/bridge-install.d.ts +48 -0
  15. package/lib/browser-electron/bridge-install.js +98 -0
  16. package/lib/browser-electron/bridge-status.js +21 -2
  17. package/lib/browser-electron/desktop-bridge-host.d.ts +7 -4
  18. package/lib/browser-electron/desktop-bridge-host.js +36 -15
  19. package/lib/browser-electron/electron-provision.d.ts +1 -1
  20. package/lib/browser-electron/electron-provision.js +31 -11
  21. package/lib/browser-electron/entry.js +84 -8
  22. package/lib/browser-electron/host-main.js +48 -27
  23. package/lib/browser-electron/provider.d.ts +9 -2
  24. package/lib/browser-electron/provider.js +76 -6
  25. package/lib/browser-electron/remote-host.js +4 -4
  26. package/lib/browser-electron/runtime-route.d.ts +3 -5
  27. package/lib/browser-electron/runtime-status.js +4 -2
  28. package/lib/browser-electron/settings-route.d.ts +5 -18
  29. package/lib/browser-electron/settings-route.js +4 -14
  30. package/lib/browser-electron/settings-store.d.ts +17 -0
  31. package/lib/browser-electron/settings-store.js +24 -0
  32. package/lib/browser-electron/system-browser.d.ts +5 -2
  33. package/lib/browser-electron/system-browser.js +12 -4
  34. package/lib/tool-browser/index.js +1041 -4
  35. package/lib/tool-browser/page-probe.d.ts +86 -0
  36. package/lib/tool-browser/page-probe.js +460 -0
  37. package/package.json +4 -2
  38. package/scripts/verify-runtime-status.mjs +14 -0
  39. package/skills/dsh-builtin-browser/SKILL.md +64 -0
  40. package/skills/dsh-builtin-browser/references/batch.md +23 -0
  41. package/skills/dsh-builtin-browser/references/deliver.md +31 -0
  42. package/skills/dsh-builtin-browser/references/locate.md +11 -0
  43. package/skills/dsh-builtin-browser/references/recover.md +11 -0
  44. package/skills/dsh-builtin-browser/references/verify.md +13 -0
  45. package/src/browser/runtime.ts +11 -0
  46. package/src/browser/types.ts +19 -0
  47. package/src/browser-electron/authenticated-route.ts +56 -0
  48. package/src/browser-electron/bridge-endpoint.ts +7 -0
  49. package/src/browser-electron/bridge-install.ts +122 -0
  50. package/src/browser-electron/bridge-status.ts +22 -2
  51. package/src/browser-electron/desktop-bridge-host.ts +33 -15
  52. package/src/browser-electron/electron-provision.ts +30 -12
  53. package/src/browser-electron/entry.ts +76 -8
  54. package/src/browser-electron/host-main.ts +41 -22
  55. package/src/browser-electron/provider.ts +90 -6
  56. package/src/browser-electron/remote-host.ts +4 -4
  57. package/src/browser-electron/runtime-route.ts +3 -5
  58. package/src/browser-electron/runtime-status.ts +4 -2
  59. package/src/browser-electron/settings-route.ts +9 -32
  60. package/src/browser-electron/settings-store.ts +39 -0
  61. package/src/browser-electron/system-browser.ts +9 -3
  62. package/src/tool-browser/index.ts +991 -7
  63. package/src/tool-browser/page-probe.ts +474 -0
@@ -362,7 +362,12 @@ function windowFor(windowId) {
362
362
  const existing = windows.get(key);
363
363
  if (existing !== undefined)
364
364
  return existing;
365
- const w = new BrowserWindow({ width: 1400, height: 900, show: true, title: 'dsh-browser' });
365
+ // `show: false` on purpose: creating a window must not be a presentation decision. With `show: true`
366
+ // the window appeared and took the screen the moment the first tool call created it — before any
367
+ // `showView` message could carry `ui.quiet`, so quiet mode had no effect at all on this carrier
368
+ // (measured: the setting was on and the window still popped up). The first presentation decides:
369
+ // quiet shows it inactive, a normal call shows it normally.
370
+ const w = new BrowserWindow({ width: 1400, height: 900, show: false, title: 'dsh-browser' });
366
371
  w.on('closed', () => {
367
372
  const closing = windows.get(key);
368
373
  windows.delete(key);
@@ -595,35 +600,46 @@ function revealViewInWindow(win, viewId, label) {
595
600
  * @param label - session/task label, when known, for the window title.
596
601
  * @param quiet - `ui.quiet`: present without taking the screen over.
597
602
  * @param needSurface - quiet mode only: this presentation is the barrier before synthesized
598
- * input, so the window has to be visible even if the user minimized it. A navigation or a tab
599
- * switch does not need that and leaves a minimized window alone.
603
+ * input, so a newly created window needs an invisible display surface. A minimized window
604
+ * stays minimized because restoring it can activate it.
600
605
  */
601
606
  function showViewInWindow(win, viewId, label, quiet = false, needSurface = false) {
602
- revealViewInWindow(win, viewId, label);
603
- // Raise this session's window so the human sees the page being worked on
604
- // (moveTop raises without stealing keyboard focus).
605
- //
606
- // Quiet mode (`ui.quiet`): the user asked not to be interrupted, so this must not
607
- // activate the application, steal keyboard focus, or pull the window in front of the one
608
- // they are using. Chromium drops `Input.*` for a view with no display surface, so the one
609
- // case that still needs a visible window — the barrier before synthesized input — restores
610
- // it with `showInactive()`, which shows it without becoming the key window, and never calls
611
- // `moveTop()`. Everything else (navigation, tab switching, screenshots) leaves a minimized
612
- // window minimized.
613
- try {
614
- if (quiet) {
615
- if (!needSurface)
607
+ if (quiet) {
608
+ if (win.window.isMinimized()) {
609
+ if (needSurface)
610
+ throw new Error('quiet mode will not restore a minimized browser window; restore it manually to send input');
611
+ return;
612
+ }
613
+ if (win.window.isVisible() && win.window.getOpacity() > 0) {
614
+ if (win.visibleViewId !== viewId) {
615
+ if (needSurface)
616
+ throw new Error('quiet mode will not replace a visible browser tab; select the target tab manually to send input');
616
617
  return;
617
- if (win.window.isMinimized())
618
- win.window.restore();
619
- if (!win.window.isVisible())
620
- win.window.showInactive();
618
+ }
619
+ revealViewInWindow(win, viewId, label);
620
+ return;
621
621
  }
622
- else {
623
- if (!win.window.isVisible())
624
- win.window.show();
625
- win.window.moveTop();
622
+ revealViewInWindow(win, viewId, label);
623
+ if (!needSurface || win.window.isVisible())
624
+ return;
625
+ win.window.setOpacity(0);
626
+ if (win.window.getOpacity() > 0)
627
+ throw new Error('quiet mode could not create an invisible browser surface');
628
+ win.window.setSkipTaskbar(true);
629
+ win.window.setFocusable(false);
630
+ win.window.showInactive();
631
+ return;
632
+ }
633
+ revealViewInWindow(win, viewId, label);
634
+ try {
635
+ if (win.window.getOpacity() === 0) {
636
+ win.window.setFocusable(true);
637
+ win.window.setOpacity(1);
638
+ win.window.setSkipTaskbar(false);
626
639
  }
640
+ if (!win.window.isVisible())
641
+ win.window.show();
642
+ win.window.moveTop();
627
643
  }
628
644
  catch { /* closing */ }
629
645
  }
@@ -839,7 +855,11 @@ async function handle(op, msg) {
839
855
  // and `document.hasFocus()` inside the page even read true.
840
856
  const contents = entry.webContentsView.webContents;
841
857
  const hadWebFocus = contents.isFocused();
842
- contents.focus();
858
+ if (msg.quiet === true && win.window.getOpacity() > 0 && !hadWebFocus) {
859
+ throw new Error('quiet mode will not take keyboard focus from the visible browser; focus the target page manually');
860
+ }
861
+ if (msg.quiet !== true || !hadWebFocus)
862
+ contents.focus();
843
863
  // Focus lands asynchronously, and a key dispatched in the same turn as
844
864
  // the request is still dropped, so hold the reply until the renderer can
845
865
  // take input. Only on the call where focus actually had to move.
@@ -880,7 +900,8 @@ async function handle(op, msg) {
880
900
  // The active tab has to be the visible one INSIDE the window, or the capture may read
881
901
  // another tab. Keep that switch contentView-local: show/restore/focus are precisely
882
902
  // what quiet mode forbids.
883
- revealViewInWindow(win, viewId);
903
+ if (!win.window.isVisible() || win.window.getOpacity() === 0)
904
+ revealViewInWindow(win, viewId);
884
905
  }
885
906
  else {
886
907
  try {
@@ -8,7 +8,7 @@
8
8
  */
9
9
  import { type VisitedPage } from './history-store.js';
10
10
  import type { BrowserSettings } from './settings-store.js';
11
- import type { BrowserA11yRequest, BrowserA11yResult, BrowserChallenge, BrowserCheckRequest, BrowserClearRequest, BrowserClickRequest, BrowserClickSequenceRequest, BrowserClickSequenceResult, BrowserContentRequest, BrowserContentResult, BrowserElementTarget, BrowserExecuteRequest, BrowserExecuteResult, BrowserFillRequest, BrowserFillResult, BrowserGetValueRequest, BrowserGetValueResult, BrowserHistoryEntry, BrowserOpenRequest, BrowserProvider, BrowserScrapeRequest, BrowserScrapeResult, BrowserScreenshotRequest, BrowserSelectRequest, BrowserSelectResult, BrowserSessionId, BrowserSetValueRequest, BrowserSetValueResult, BrowserSnapshotResult, BrowserTab, BrowserTypeRequest, BrowserWaitRequest, BrowserWaitResult, BrowserScrollRequest, BrowserKeyRequest, ExportedCookie } from '../browser/types.js';
11
+ import type { BrowserA11yRequest, BrowserA11yResult, BrowserChallenge, BrowserCheckRequest, BrowserClearRequest, BrowserClickRequest, BrowserClickSequenceRequest, BrowserClickSequenceResult, BrowserContentRequest, BrowserContentResult, BrowserElementTarget, BrowserExecuteRequest, BrowserPageOperationRequest, BrowserExecuteResult, BrowserFillRequest, BrowserFillResult, BrowserGetValueRequest, BrowserGetValueResult, BrowserHistoryEntry, BrowserOpenRequest, BrowserProvider, BrowserScrapeRequest, BrowserScrapeResult, BrowserScreenshotRequest, BrowserSelectRequest, BrowserSelectResult, BrowserSessionId, BrowserSetValueRequest, BrowserSetValueResult, BrowserSnapshotResult, BrowserTab, BrowserTypeRequest, BrowserWaitRequest, BrowserWaitResult, BrowserScrollRequest, BrowserKeyRequest, ExportedCookie } from '../browser/types.js';
12
12
  import type { CarrierPage, CarrierLossReason } from '../browser/types.js';
13
13
  /** Stable provider id registered with `ctx.browser`. */
14
14
  export declare const ELECTRON_BROWSER_PROVIDER_ID = "electron";
@@ -261,7 +261,7 @@ export interface ElectronViewHandle {
261
261
  * Optional: an adapter that cannot focus a view omits it, and the provider
262
262
  * then behaves exactly as before.
263
263
  */
264
- focus?(): Promise<void>;
264
+ focus?(options?: PresentOptions): Promise<void>;
265
265
  /**
266
266
  * Save a URL straight to disk, when the backing view can do that itself.
267
267
  *
@@ -452,6 +452,8 @@ export interface PresentOptions {
452
452
  export interface CommandOptions {
453
453
  /** Present the view first (default), or only use a page that is already there. */
454
454
  readonly present?: boolean;
455
+ /** Only use a guest already attached to this handle, without sidebar initialization. */
456
+ readonly initialize?: boolean;
455
457
  }
456
458
  /** Native capture options the self-hosted view handle understands. */
457
459
  export interface ScreenshotOptions {
@@ -617,6 +619,11 @@ export declare class ElectronBrowserProvider implements BrowserProvider {
617
619
  private focusView;
618
620
  /** Execute JS in the active tab's page context. */
619
621
  execute(session: BrowserSessionId, request: BrowserExecuteRequest, signal?: AbortSignal): Promise<BrowserExecuteResult>;
622
+ /** Run a fixed browser operation; the request cannot contain a script. */
623
+ pageOperation(session: BrowserSessionId, request: BrowserPageOperationRequest, signal?: AbortSignal): Promise<BrowserExecuteResult>;
624
+ /** Send page pointer input through CDP while preserving presentation and cancellation policy. */
625
+ private dispatchPointer;
626
+ private evaluatePage;
620
627
  /**
621
628
  * Poll until the active tab's page is ready (and optional URL/selector
622
629
  * match), or the budget runs out. Returns a verdict instead of throwing on
@@ -6,6 +6,7 @@
6
6
  * shell that owns the `BrowserWindow`.
7
7
  * @module dsh-browser/browser-electron
8
8
  */
9
+ import { pageOperationScript } from '../tool-browser/page-probe.js';
9
10
  import { randomUUID } from 'node:crypto';
10
11
  import { existsSync, lstatSync, mkdirSync, realpathSync } from 'node:fs';
11
12
  import { writeFileNoReplace } from './file-write.js';
@@ -661,7 +662,7 @@ export class ElectronBrowserProvider {
661
662
  */
662
663
  async documentProbe(handle) {
663
664
  try {
664
- const result = await withTimeout(handleSendEvaluate(handle, 'String(performance.timeOrigin) + "|" + document.readyState'), 3_000, undefined, 'browser: document probe timed out');
665
+ const result = await withTimeout(handleSendEvaluate(handle, 'String(performance.timeOrigin) + "|" + document.readyState', undefined, { present: false, initialize: false }), 3_000, undefined, 'browser: document probe timed out');
665
666
  if (!result.ok)
666
667
  return null;
667
668
  if (typeof result.value !== 'string')
@@ -794,14 +795,17 @@ export class ElectronBrowserProvider {
794
795
  async focusView(handle) {
795
796
  if (handle.focus === undefined)
796
797
  return;
798
+ const quiet = this.isQuiet();
797
799
  try {
798
800
  // Bounded, unlike the rest of this call: the child RPC has no timeout of its own,
799
801
  // and this runs before typing, so an unresponsive child would hang dsh_browser_key for
800
802
  // good. A timeout is caught below exactly like any other focus failure, so the
801
803
  // best-effort contract is unchanged.
802
- await withTimeout(handle.focus(), 5_000, undefined, 'browser: focusing the view timed out');
804
+ await withTimeout(handle.focus(quiet ? { quiet } : undefined), 5_000, undefined, 'browser: focusing the view timed out');
803
805
  }
804
- catch {
806
+ catch (error) {
807
+ if (quiet)
808
+ throw error;
805
809
  // Best-effort: a view that refuses focus must not fail the caller's key
806
810
  // press; the dispatch below reports a real channel failure itself.
807
811
  }
@@ -809,6 +813,69 @@ export class ElectronBrowserProvider {
809
813
  /** Execute JS in the active tab's page context. */
810
814
  async execute(session, request, signal) {
811
815
  this.assertActionAllowed('execute');
816
+ return this.evaluatePage(session, request, signal);
817
+ }
818
+ /** Run a fixed browser operation; the request cannot contain a script. */
819
+ async pageOperation(session, request, signal) {
820
+ const script = pageOperationScript(request);
821
+ if (request.operation === 'drag') {
822
+ return this.dispatchPointer(session, request.from, request.to, request.steps, signal);
823
+ }
824
+ if (request.operation === 'probe' && request.method === 'hoverAt') {
825
+ const point = { x: Number(request.args?.[0]), y: Number(request.args?.[1]) };
826
+ return this.dispatchPointer(session, point, undefined, 1, signal);
827
+ }
828
+ return this.evaluatePage(session, { script }, signal);
829
+ }
830
+ /** Send page pointer input through CDP while preserving presentation and cancellation policy. */
831
+ async dispatchPointer(session, from, to, steps, signal) {
832
+ const coordinates = [from.x, from.y, ...to === undefined ? [] : [to.x, to.y]];
833
+ if (coordinates.some(value => !Number.isFinite(value) || value < 0)) {
834
+ throw new BrowserError('browser: pointer coordinates must be finite nonnegative viewport pixels', 'BROWSER_POINTER_INVALID');
835
+ }
836
+ if (to !== undefined && this.settingsSource?.().vision.strategy === 'nonVisual') {
837
+ throw new BrowserError('browser: coordinate dragging requires the visual strategy', 'BROWSER_NON_VISUAL_COORDINATES');
838
+ }
839
+ const s = this.session(session);
840
+ const handle = await this.present(s, signal);
841
+ const viewport = await withTimeout(handleSendEvaluate(handle, '({width:innerWidth,height:innerHeight})'), 5_000, signal, 'browser: pointer viewport check timed out');
842
+ if (!viewport.ok)
843
+ throw new BrowserError('browser: could not read the pointer viewport', 'BROWSER_POINTER_INVALID');
844
+ const size = viewport.value;
845
+ if (from.x >= size.width || from.y >= size.height || (to !== undefined && (to.x >= size.width || to.y >= size.height))) {
846
+ return { ok: true, value: JSON.stringify(to === undefined ? false : { ok: false, reason: 'drag points must be inside the current viewport' }) };
847
+ }
848
+ const send = async (params) => {
849
+ signal?.throwIfAborted();
850
+ this.assertSameView(session, handle, this.activeTab(s).handle);
851
+ await withTimeout(handle.sendCommand('Input.dispatchMouseEvent', { ...params }), 5_000, signal, 'browser: pointer input timed out');
852
+ };
853
+ await send({ type: 'mouseMoved', x: from.x, y: from.y, buttons: 0 });
854
+ if (to === undefined)
855
+ return { ok: true, value: 'true' };
856
+ let at = from;
857
+ let held = true;
858
+ try {
859
+ await send({ type: 'mousePressed', x: from.x, y: from.y, button: 'left', buttons: 1, clickCount: 1 });
860
+ const count = Math.max(1, Math.min(Math.trunc(steps) || 12, 60));
861
+ for (let step = 1; step <= count; step += 1) {
862
+ const next = { x: from.x + (to.x - from.x) * step / count, y: from.y + (to.y - from.y) * step / count };
863
+ await send({ type: 'mouseMoved', ...next, button: 'left', buttons: 1 });
864
+ at = next;
865
+ }
866
+ // Native HTML drag targets need a final drag-over before releasing at the destination.
867
+ await send({ type: 'mouseMoved', ...to, button: 'left', buttons: 1 });
868
+ await send({ type: 'mouseReleased', ...to, button: 'left', buttons: 0, clickCount: 1 });
869
+ held = false;
870
+ return { ok: true, value: JSON.stringify({ ok: true, moved: count, at: to }) };
871
+ }
872
+ finally {
873
+ if (held) {
874
+ await withTimeout(handle.sendCommand('Input.dispatchMouseEvent', { type: 'mouseReleased', ...at, button: 'left', buttons: 0, clickCount: 1 }), 1_000, undefined, 'browser: pointer release timed out').catch(() => { });
875
+ }
876
+ }
877
+ }
878
+ async evaluatePage(session, request, signal) {
812
879
  const s = this.session(session);
813
880
  const { handle } = this.activeTab(s);
814
881
  signal?.throwIfAborted();
@@ -3122,7 +3189,10 @@ export class ElectronBrowserProvider {
3122
3189
  * silently desynchronising the two and failing every screenshot.
3123
3190
  */
3124
3191
  showActive(s) {
3125
- this.host.showView?.(this.activeTab(s).handle, s.label, { quiet: this.isQuiet() });
3192
+ const quiet = this.isQuiet();
3193
+ this.host.showView?.(this.activeTab(s).handle, s.label, { quiet });
3194
+ if (quiet)
3195
+ return;
3126
3196
  const autoExpand = this.settingsSource === undefined || this.settingsSource().ui.autoExpandOnce;
3127
3197
  if (autoExpand)
3128
3198
  return;
@@ -3269,13 +3339,13 @@ function scriptPoint(out) {
3269
3339
  const y = Number(point?.y);
3270
3340
  return Number.isFinite(x) && Number.isFinite(y) ? { x, y } : undefined;
3271
3341
  }
3272
- async function handleSendEvaluate(handle, expression, signal) {
3342
+ async function handleSendEvaluate(handle, expression, signal, options) {
3273
3343
  signal?.throwIfAborted();
3274
3344
  const result = await handle.sendCommand(CDP_RUNTIME_EVALUATE, {
3275
3345
  expression,
3276
3346
  returnByValue: true,
3277
3347
  awaitPromise: true,
3278
- });
3348
+ }, options);
3279
3349
  if (result.exceptionDetails !== undefined) {
3280
3350
  const detail = result.exceptionDetails;
3281
3351
  return { ok: false, exception: detail.exception?.description ?? detail.text ?? 'unknown exception' };
@@ -745,8 +745,8 @@ class RemoteView {
745
745
  });
746
746
  }
747
747
  /** Give this view web focus in the child, so keyboard input reaches the page. */
748
- focus() {
749
- return this.client.call('focus', { viewId: this.id });
748
+ focus(options) {
749
+ return this.client.call('focus', { viewId: this.id, ...options?.quiet ? { quiet: true } : {} });
750
750
  }
751
751
  /** Ask the child to download a URL to a local file (keeps cookies/login). */
752
752
  async download(url, savePath) {
@@ -1322,8 +1322,8 @@ class DeferredRemoteView {
1322
1322
  async capture(opts) {
1323
1323
  return this.withRecovery(view => view.capture(opts));
1324
1324
  }
1325
- async focus() {
1326
- return this.withRecovery(view => view.focus());
1325
+ async focus(options) {
1326
+ return this.withRecovery(view => view.focus(options));
1327
1327
  }
1328
1328
  async flushAuth() {
1329
1329
  return this.withRecovery(view => view.flushAuth());
@@ -1,11 +1,9 @@
1
1
  /**
2
2
  * The readiness endpoints the settings panel reads.
3
3
  *
4
- * Two of them, because the two questions have different weights: reading the state is a `GET` any
5
- * same-origin document may make, and starting a download is a `POST` held to the stricter admission
6
- * rule in `settings-route.ts`. No credential system exists here — that module's own comment says
7
- * what the rule buys — but a request that STARTS a 100 MB download is on the wrong side of the same
8
- * line the settings write is on, so it is checked the way a write is.
4
+ * The host authenticates both routes with its signed browser-session cookie. The read returns
5
+ * readiness, while a POST starts runtime preparation and also passes the settings write-origin
6
+ * checks.
9
7
  *
10
8
  * Both answer with the whole report rather than a delta: the panel replaces what it shows with what
11
9
  * it is told, so a stale poll can never leave a wrong state on screen.
@@ -31,10 +31,12 @@ export function readRuntimeStatus(deps) {
31
31
  // on a live install, and the kind of contradiction a reader cannot resolve.
32
32
  const snapshot = deps.provision();
33
33
  const runnable = deps.hasBinary();
34
- const state = runnable ? 'present' : snapshot.state;
34
+ const missingAfterReady = !runnable && (snapshot.state === 'present' || snapshot.state === 'ready');
35
+ const state = runnable ? 'present' : missingAfterReady ? 'failed' : snapshot.state;
35
36
  const electron = {
36
37
  state,
37
- detail: runnable ? 'an Electron runtime is already available' : snapshot.detail,
38
+ detail: runnable ? 'an Electron runtime is already available'
39
+ : missingAfterReady ? 'the previously prepared Electron runtime is missing; prepare it again' : snapshot.detail,
38
40
  at: runnable ? new Date().toISOString() : snapshot.at,
39
41
  };
40
42
  const bridgeStatus = deps.bridge();
@@ -1,22 +1,9 @@
1
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.
13
- *
14
- * What that buys and what it does not:
15
- * - a plain HTTP client (curl, a script, another process) cannot WRITE, because it sends no
16
- * `user-agent` and no `accept-language`;
17
- * - a page of THIS origin can, because a browser sending a same-origin write looks exactly
18
- * like the panel. That is inherent to exposing an HTTP endpoint at all, and it is why the
19
- * settings panel's own text must not promise a lock that does not exist.
2
+ * Browser-origin checks used after DSH authenticates each plugin HTTP request.
3
+ * Desktop protocol forwarding supplies the host session cookie while Chromium may omit Origin
4
+ * and Referer for the custom application scheme. These checks preserve that request shape and
5
+ * reject browser requests that explicitly name another web origin.
6
+ * @module dsh-browser/browser-electron/settings-route
20
7
  */
21
8
  import type { IncomingMessage } from 'node:http';
22
9
  /**
@@ -29,25 +29,15 @@ export function sameOrigin(request, writing = false) {
29
29
  return true;
30
30
  if (APP_SCHEMES.includes(schemeOf(String(request.headers.referer ?? '')) ?? ''))
31
31
  return true;
32
- // MEASURED on the running desktop, and what three earlier attempts each guessed wrong: a
33
- // request from the shell's own settings panel carries NO origin, NO sec-fetch-site and NO
34
- // referer. It is not "dsh-app://app" and it is not "null" — the headers are simply absent,
35
- // because Chromium attaches no cross-origin metadata to a request leaving a custom scheme.
36
- //
37
- // So the rule for that shape cannot be "a request without an Origin is a script", which is
38
- // what refused every desktop save, and it cannot lean on `Sec-Fetch-Site` either. It has to
39
- // test what a hand-rolled client does not send:
40
- // - a renderer sends a full Mozilla-compatible `user-agent` AND an `accept-language`;
41
- // - curl sends neither unless told to, and a local process that forges both can also read
42
- // the settings document directly — it sits readable on disk, as the panel's own text
43
- // says. This was never the boundary it looked like.
32
+ // Desktop custom-scheme requests can omit browser origin metadata. The route's host-cookie
33
+ // gate has already authenticated them; the renderer headers retain compatibility with older
34
+ // shells that omit Origin while forwarding settings writes.
44
35
  if (origin === '') {
45
36
  const agent = String(request.headers['user-agent'] ?? '');
46
37
  const language = String(request.headers['accept-language'] ?? '');
47
38
  if (/^Mozilla\/5\.0/.test(agent) && language !== '')
48
39
  return true;
49
- // Reads stay open: they return the document the panel is already showing, and refusing them
50
- // would only break hand-inspection of a file that sits readable on disk anyway.
40
+ // A missing Origin is valid for reads after the host-cookie gate has admitted the caller.
51
41
  return !writing;
52
42
  }
53
43
  // `cross-site` is another origin entirely; `same-site` is another origin of the same site
@@ -116,6 +116,23 @@ export interface BrowserSettings {
116
116
  /** Write cookies — importing login state (`dsh_browser_auth` restore). */
117
117
  readonly allowCredentialWrite: boolean;
118
118
  };
119
+ /**
120
+ * Where a downloaded file goes after it lands on disk.
121
+ *
122
+ * An ATTRIBUTE of a download, not a new concept: an empty `tool` means the behaviour is exactly
123
+ * what it was before this existed. The user owns the field, can point it at any MCP tool that
124
+ * takes a path (Feishu drive, Baidu Netdisk), and can empty it again at any time.
125
+ */
126
+ readonly delivery: {
127
+ /** MCP tool that receives the saved file. Empty = save locally and stop there. */
128
+ readonly tool: string;
129
+ /** Flat argument template; {path}, {name} and {size} are substituted into string values. */
130
+ readonly args: Readonly<Record<string, string>>;
131
+ /** `keep-local` reports both outcomes; `stop` reports the handoff failure as the result. */
132
+ readonly onFail: 'keep-local' | 'stop';
133
+ /** Per-site override: page host → tool name. */
134
+ readonly sites: Readonly<Record<string, string>>;
135
+ };
119
136
  }
120
137
  /** Defaults for every switch: the documented out-of-the-box behaviour. */
121
138
  export declare const DEFAULT_SETTINGS: BrowserSettings;
@@ -28,6 +28,9 @@ export const DEFAULT_SETTINGS = {
28
28
  // content, so watching is an explicit decision rather than something a remote client can arrange.
29
29
  remoteView: { enabled: false },
30
30
  actions: { allowExecute: true, allowDownload: true, allowCredentialWrite: true },
31
+ // Local by default: the file lands in downloadDir and nothing leaves the machine until the user
32
+ // names a tool here. {file_path} is the argument name both Feishu's and Netdisk's upload tools use.
33
+ delivery: { tool: '', args: { file_path: '{path}' }, onFail: 'keep-local', sites: {} },
31
34
  };
32
35
  /**
33
36
  * Absolute path of the settings file, beside the browser profile and the
@@ -181,6 +184,19 @@ export function resolveSettings(raw, warn) {
181
184
  const browser = section(source, 'browser');
182
185
  const actions = section(source, 'actions');
183
186
  const remoteView = section(source, 'remoteView');
187
+ // Read defensively: this section is hand-editable, and a bad value must fall back to "local only"
188
+ // rather than fail the whole document.
189
+ const deliverySection = (section(source, 'delivery') ?? {});
190
+ const strings = (value, fallback) => {
191
+ if (value === null || typeof value !== 'object' || Array.isArray(value))
192
+ return { ...fallback };
193
+ const out = {};
194
+ for (const [key, entry] of Object.entries(value)) {
195
+ if (typeof entry === 'string')
196
+ out[key] = entry;
197
+ }
198
+ return Object.keys(out).length === 0 ? { ...fallback } : out;
199
+ };
184
200
  // A section that is present but unreadable refuses its gates rather than defaulting them
185
201
  // open. The rest of a broken section keeps its defaults: refusing history or presentation
186
202
  // would punish the user for a bad file without protecting anything.
@@ -233,6 +249,14 @@ export function resolveSettings(raw, warn) {
233
249
  ? false
234
250
  : gate(remoteView.enabled, false),
235
251
  },
252
+ delivery: {
253
+ tool: typeof deliverySection.tool === 'string' && /^[A-Za-z0-9_.-]+$/.test(deliverySection.tool)
254
+ ? deliverySection.tool
255
+ : '',
256
+ args: strings(deliverySection.args, DEFAULT_SETTINGS.delivery.args),
257
+ onFail: deliverySection.onFail === 'stop' ? 'stop' : 'keep-local',
258
+ sites: strings(deliverySection.sites, {}),
259
+ },
236
260
  };
237
261
  }
238
262
  /**
@@ -85,6 +85,7 @@ export declare class SystemBrowserViewHost implements ElectronBrowserViewHost {
85
85
  * and why a display-less host needs headless at all (issue #32).
86
86
  */
87
87
  private readonly headlessMode;
88
+ private readonly isQuiet;
88
89
  /**
89
90
  * viewId -> the session that view rides, and the client that issued it.
90
91
  *
@@ -156,7 +157,7 @@ export declare class SystemBrowserViewHost implements ElectronBrowserViewHost {
156
157
  * Whether this launch should get a window. See {@link resolveLaunchMode} for how `auto` decides
157
158
  * and why a display-less host needs headless at all (issue #32).
158
159
  */
159
- headlessMode?: HeadlessMode);
160
+ headlessMode?: HeadlessMode, isQuiet?: () => boolean);
160
161
  /** Which product this host would drive (for diagnostics). */
161
162
  get kind(): DetectedBrowser['kind'];
162
163
  /** Whether the browser has actually been started yet (diagnostics and tests). */
@@ -284,7 +285,9 @@ export declare class SystemBrowserViewHost implements ElectronBrowserViewHost {
284
285
  * two, and the order is honoured either way.
285
286
  * @param handle - the view to present.
286
287
  */
287
- presentView(handle: ElectronViewHandle): Promise<void>;
288
+ presentView(handle: ElectronViewHandle, _label?: string, options?: {
289
+ readonly quiet?: boolean;
290
+ }): Promise<void>;
288
291
  /**
289
292
  * Best effort at bringing the browser's window forward.
290
293
  *
@@ -483,6 +483,7 @@ export class SystemBrowserViewHost {
483
483
  ephemeralDir;
484
484
  launcher;
485
485
  headlessMode;
486
+ isQuiet;
486
487
  /**
487
488
  * viewId -> the session that view rides, and the client that issued it.
488
489
  *
@@ -554,13 +555,14 @@ export class SystemBrowserViewHost {
554
555
  * Whether this launch should get a window. See {@link resolveLaunchMode} for how `auto` decides
555
556
  * and why a display-less host needs headless at all (issue #32).
556
557
  */
557
- headlessMode = 'auto') {
558
+ headlessMode = 'auto', isQuiet = () => false) {
558
559
  this.browser = browser;
559
560
  this.profileDir = profileDir;
560
561
  this.extraArgs = extraArgs;
561
562
  this.ephemeralDir = ephemeralDir;
562
563
  this.launcher = launcher;
563
564
  this.headlessMode = headlessMode;
565
+ this.isQuiet = isQuiet;
564
566
  }
565
567
  /** Which product this host would drive (for diagnostics). */
566
568
  get kind() {
@@ -740,7 +742,7 @@ export class SystemBrowserViewHost {
740
742
  const adopted = await this.adoptRunningBrowser('before launch');
741
743
  if (adopted !== undefined)
742
744
  return adopted;
743
- const launch = resolveLaunchMode(this.headlessMode);
745
+ const launch = resolveLaunchMode(this.isQuiet() ? 'headless' : this.headlessMode);
744
746
  const args = [
745
747
  '--remote-debugging-port=0',
746
748
  `--user-data-dir=${this.profileDir}`,
@@ -1102,6 +1104,7 @@ export class SystemBrowserViewHost {
1102
1104
  const ours = new Set(this.sessions.values());
1103
1105
  return (listed?.targetInfos ?? [])
1104
1106
  .filter(entry => entry.type === 'page' && typeof entry.targetId === 'string')
1107
+ .filter(entry => !/^edge:\/\/sync-confirmation-dialog(?:\/|$)/.test(entry.url ?? ''))
1105
1108
  .filter(entry => !ours.has(entry.targetId))
1106
1109
  .map(entry => ({
1107
1110
  id: entry.targetId,
@@ -1259,7 +1262,9 @@ export class SystemBrowserViewHost {
1259
1262
  * two, and the order is honoured either way.
1260
1263
  * @param handle - the view to present.
1261
1264
  */
1262
- async presentView(handle) {
1265
+ async presentView(handle, _label, options) {
1266
+ if (options?.quiet === true || this.isQuiet())
1267
+ return;
1263
1268
  try {
1264
1269
  await handle.sendCommand('Page.bringToFront');
1265
1270
  }
@@ -1479,7 +1484,10 @@ export class SystemBrowserViewHost {
1479
1484
  }
1480
1485
  /** Create one page, refusing to go on without an id. */
1481
1486
  async createTarget(client) {
1482
- const created = await client.send('Target.createTarget', { url: 'about:blank' });
1487
+ const created = await client.send('Target.createTarget', {
1488
+ url: 'about:blank',
1489
+ ...this.isQuiet() ? { background: true } : {},
1490
+ });
1483
1491
  const targetId = created?.targetId;
1484
1492
  if (typeof targetId !== 'string')
1485
1493
  throw new Error('dsh-builtin-browser: the browser did not create a page');