dsh-builtin-browser 1.0.1 → 1.0.4
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 +55 -0
- package/README.md +1 -1
- package/assets/browser-panel-locales.mjs +37 -5
- package/assets/browser-policy.d.mts +29 -0
- package/assets/browser-policy.mjs +40 -0
- package/desktop-bridge/desktop-discovery.d.mts +1 -1
- package/desktop-bridge/desktop-discovery.mjs +59 -9
- package/desktop-bridge/desktop-identity.json +12 -0
- package/desktop-bridge/install.mjs +14 -7
- package/desktop-bridge/plugin-browser-bridge.js +19 -7
- package/docs/acceptance-2026-11-27.md +67 -0
- package/docs/architecture.md +1 -1
- package/docs/development.md +33 -4
- package/docs/dsh-0.2.3-host-patch-task.md +34 -0
- package/docs/hardcoding-audit.md +28 -8
- package/docs/known-issues.md +26 -0
- package/docs/limitations.md +6 -2
- package/docs/tool-reference.md +1 -1
- package/docs/v1.1.0-bu-data-batching-task.md +66 -0
- package/docs/v1.1.0-compat-hardcoding-task.md +85 -0
- package/dsh-host-patch/README.md +4 -0
- package/dsh-host-patch/apply.mjs +61 -13
- package/dsh-host-patch/rc3-revision9.json.gz +0 -0
- package/dsh-host-patch/rc5-revision9.json.gz +0 -0
- package/dsh-host-patch/tauri/desktop-main.cjs +62 -0
- package/dsh-host-patch/tauri/sidebar-session.cjs +104 -0
- package/dsh-host-patch/tauri-revision1.json +39 -0
- package/dsh-host-patch/tauri.json +43 -0
- package/dsh-host-patch/v023-alpha2.json +153 -0
- package/lib/browser/anti-bot.js +215 -0
- package/lib/browser/deep-dom.js +39 -0
- package/lib/browser/runtime.js +15 -0
- package/lib/browser/takeover-target.js +13 -6
- package/lib/browser/types.js +30 -1
- package/lib/browser-electron/authenticated-route.js +16 -2
- package/lib/browser-electron/automatic-maintenance.js +16 -10
- package/lib/browser-electron/bridge-connection.js +3 -8
- package/lib/browser-electron/bridge-install.js +2 -1
- package/lib/browser-electron/bridge-status.js +55 -26
- package/lib/browser-electron/desktop-bridge-host.js +7 -6
- package/lib/browser-electron/desktop-identity.js +28 -5
- package/lib/browser-electron/desktop-shell.js +64 -0
- package/lib/browser-electron/electron-provision.js +105 -18
- package/lib/browser-electron/entry.js +129 -44
- package/lib/browser-electron/extension-browser.js +4 -4
- package/lib/browser-electron/foreground-watch.js +134 -0
- package/lib/browser-electron/guest-cookie-jar.js +13 -13
- package/lib/browser-electron/guest-route.js +181 -32
- package/lib/browser-electron/guest-runtime.js +61 -10
- package/lib/browser-electron/guest-storage.js +2 -2
- package/lib/browser-electron/history-store.js +1 -5
- package/lib/browser-electron/host-main.js +8 -4
- package/lib/browser-electron/host-patch-maintenance.js +14 -8
- package/lib/browser-electron/maintenance-route.js +2 -1
- package/lib/browser-electron/missing-system-browser.js +5 -9
- package/lib/browser-electron/preferred-browser.js +7 -3
- package/lib/browser-electron/preview-route.js +9 -13
- package/lib/browser-electron/process-ownership.js +1 -1
- package/lib/browser-electron/profile-command.js +2 -1
- package/lib/browser-electron/profile-extension.js +5 -0
- package/lib/browser-electron/profile-lease.js +152 -47
- package/lib/browser-electron/provider-core.js +527 -0
- package/lib/browser-electron/provider-interaction.js +963 -0
- package/lib/browser-electron/provider-media.js +518 -0
- package/lib/browser-electron/provider-navigation.js +301 -0
- package/lib/browser-electron/provider-observation.js +623 -0
- package/lib/browser-electron/provider-tabs.js +372 -0
- package/lib/browser-electron/provider.js +150 -3301
- package/lib/browser-electron/reference-route.js +9 -18
- package/lib/browser-electron/remote-host.js +79 -34
- package/lib/browser-electron/runtime-status.js +56 -6
- package/lib/browser-electron/settings-store.js +3 -6
- package/lib/browser-electron/sidebar-only-host.js +1 -1
- package/lib/browser-electron/system-browser.js +539 -172
- package/lib/browser-electron/tauri-host.js +208 -0
- package/lib/browser-electron/virtual-cursor.js +23 -13
- package/lib/browser-reference/service.js +22 -4
- package/lib/browser-reference/web-sources.js +1 -1
- package/lib/client.js +43409 -0
- package/lib/compat/host-features.js +75 -0
- package/lib/reference-source.js +1 -1
- package/lib/reference-text.js +23 -1
- package/lib/takeover-protocol.js +1 -1
- package/lib/tool-browser/block-recovery.js +69 -0
- package/lib/tool-browser/code-tool.js +170 -19
- package/lib/tool-browser/code-worker.js +115 -20
- package/lib/tool-browser/errors.js +34 -0
- package/lib/tool-browser/index.js +66 -3593
- package/lib/tool-browser/page-probe.js +227 -28
- package/lib/tool-browser/panel-page.js +2 -1
- package/lib/tool-browser/probe-client.js +157 -0
- package/lib/tool-browser/screenshot-annotations.js +108 -0
- package/lib/tool-browser/state.js +337 -0
- package/lib/tool-browser/takeover.js +1 -1
- package/lib/tool-browser/tools-debug.js +862 -0
- package/lib/tool-browser/tools-interaction.js +993 -0
- package/lib/tool-browser/tools-navigation.js +807 -0
- package/lib/tool-browser/tools-observation.js +461 -0
- package/lib/tool-browser/tools-reference.js +293 -0
- package/lib/web-guest.js +1 -0
- package/package.json +16 -36
- package/scripts/build-client.mjs +305 -0
- package/scripts/build.mjs +15 -12
- package/scripts/fix-exports.mjs +6 -16
- package/scripts/install-electron.mjs +55 -5
- package/scripts/pack.mjs +99 -0
- package/scripts/publish-manifest.mjs +56 -0
- package/scripts/verify-exports.mjs +26 -15
- package/skills/dsh-builtin-browser/SKILL.md +27 -2
- package/skills/dsh-builtin-browser/references/batch.md +15 -0
- package/src/browser/anti-bot.ts +251 -0
- package/src/browser/deep-dom.ts +40 -0
- package/src/browser/runtime.ts +18 -0
- package/src/browser/takeover-target.ts +16 -7
- package/src/browser/types.ts +56 -3
- package/src/browser-electron/authenticated-route.ts +29 -4
- package/src/browser-electron/automatic-maintenance.ts +23 -13
- package/src/browser-electron/bridge-connection.ts +11 -10
- package/src/browser-electron/bridge-install.ts +2 -1
- package/src/browser-electron/bridge-status.ts +61 -22
- package/src/browser-electron/desktop-bridge-host.ts +9 -7
- package/src/browser-electron/desktop-identity.ts +38 -5
- package/src/browser-electron/desktop-shell.ts +100 -0
- package/src/browser-electron/electron-provision.ts +104 -18
- package/src/browser-electron/entry.ts +1378 -1299
- package/src/browser-electron/extension-browser.ts +11 -4
- package/src/browser-electron/foreground-watch.ts +142 -0
- package/src/browser-electron/guest-cookie-jar.ts +3 -2
- package/src/browser-electron/guest-route.ts +180 -32
- package/src/browser-electron/guest-runtime.ts +61 -10
- package/src/browser-electron/guest-storage.ts +5 -2
- package/src/browser-electron/history-store.ts +3 -6
- package/src/browser-electron/host-main.ts +8 -4
- package/src/browser-electron/host-patch-maintenance.ts +18 -9
- package/src/browser-electron/maintenance-route.ts +2 -1
- package/src/browser-electron/missing-system-browser.ts +11 -10
- package/src/browser-electron/preferred-browser.ts +13 -3
- package/src/browser-electron/preview-route.ts +9 -12
- package/src/browser-electron/process-ownership.ts +9 -3
- package/src/browser-electron/profile-command.ts +2 -1
- package/src/browser-electron/profile-extension.ts +5 -0
- package/src/browser-electron/profile-lease.ts +131 -35
- package/src/browser-electron/provider-core.ts +1107 -0
- package/src/browser-electron/provider-interaction.ts +1034 -0
- package/src/browser-electron/provider-media.ts +589 -0
- package/src/browser-electron/provider-navigation.ts +323 -0
- package/src/browser-electron/provider-observation.ts +664 -0
- package/src/browser-electron/provider-tabs.ts +372 -0
- package/src/browser-electron/provider.ts +158 -4063
- package/src/browser-electron/reference-route.ts +598 -608
- package/src/browser-electron/remote-host.ts +118 -42
- package/src/browser-electron/runtime-status.ts +80 -13
- package/src/browser-electron/settings-store.ts +10 -6
- package/src/browser-electron/sidebar-only-host.ts +4 -2
- package/src/browser-electron/system-browser.ts +537 -184
- package/src/browser-electron/tauri-host.ts +194 -0
- package/src/browser-electron/virtual-cursor.ts +24 -14
- package/src/browser-reference/service.ts +38 -7
- package/src/browser-reference/web-sources.ts +4 -1
- package/src/client/apply-guard.ts +22 -0
- package/src/client/browser/BrowserController.ts +3 -3
- package/src/client/browser/IframeImpl.ts +182 -176
- package/src/client/browser/frame-history.ts +125 -0
- package/src/client/browser/frame-state.ts +27 -0
- package/src/client/browser/web-reference-source.ts +5 -1
- package/src/client/definition.tsx +36 -30
- package/src/client/electron/ElectronWebViewImpl.ts +20 -13
- package/src/client/electron/ElectronWebviewPresentation.ts +4 -2
- package/src/client/electron/NativeChildPresentation.ts +11 -3
- package/src/client/electron/NativeViewPage.ts +19 -5
- package/src/client/index.ts +333 -293
- package/src/client/locales.ts +9 -6
- package/src/client/reference/client/plugin.ts +21 -2
- package/src/client/reference/client/production/ReferenceCapsules.tsx +3 -3
- package/src/client/reference/client/production/assembly.ts +4 -28
- package/src/client/reference/client/production/availability.ts +0 -2
- package/src/client/reference/client/production/composer-attachments.ts +44 -0
- package/src/client/reference/client/production/draft-adapter.ts +4 -0
- package/src/client/reference/client/production/http-transport.ts +0 -5
- package/src/client/reference/client/production/production-submission.ts +50 -290
- package/src/client/reference/client/production/protocol.ts +7 -4
- package/src/client/reference/client/production/runtime.ts +41 -86
- package/src/client/reference/client/production/source-marker.ts +49 -13
- package/src/client/reference/client/production/user-text-rule.ts +10 -1
- package/src/client/reference/client/reveal.ts +3 -1
- package/src/client/reference/client/session-schedule.ts +36 -0
- package/src/client/settings/index.ts +8 -0
- package/src/client/settings/mount-guard.ts +31 -0
- package/src/client/settings/panel.ts +163 -52
- package/src/client/startpage/controller.ts +3 -6
- package/src/client/view/BrowserBody.tsx +2 -1
- package/src/client/view/IframePresentation.ts +37 -16
- package/src/client/view/StartPage.tsx +2 -1
- package/src/compat/host-features.ts +92 -0
- package/src/reference-source.ts +1 -1
- package/src/reference-text.ts +23 -1
- package/src/takeover-protocol.ts +11 -2
- package/src/tool-browser/block-recovery.ts +85 -0
- package/src/tool-browser/code-tool.ts +173 -19
- package/src/tool-browser/code-worker.ts +101 -15
- package/src/tool-browser/errors.ts +40 -0
- package/src/tool-browser/index.ts +66 -3534
- package/src/tool-browser/page-probe.ts +229 -28
- package/src/tool-browser/panel-page.ts +3 -1
- package/src/tool-browser/probe-client.ts +183 -0
- package/src/tool-browser/screenshot-annotations.ts +131 -0
- package/src/tool-browser/state.ts +375 -0
- package/src/tool-browser/takeover.ts +3 -2
- package/src/tool-browser/tools-debug.ts +806 -0
- package/src/tool-browser/tools-interaction.ts +956 -0
- package/src/tool-browser/tools-navigation.ts +786 -0
- package/src/tool-browser/tools-observation.ts +474 -0
- package/src/tool-browser/tools-reference.ts +294 -0
- package/src/web-guest.ts +35 -34
- package/dist/client.cjs +0 -43167
- package/dist/client.d.cts +0 -516
- package/dist/client.d.mts +0 -516
- package/dist/index.cjs +0 -92
- package/dist/index.d.mts +0 -2960
- package/dist/index.mjs +0 -24
- package/lib/browser-reference/submission-receipts.js +0 -139
- package/src/browser-reference/submission-receipts.ts +0 -122
|
@@ -23,8 +23,12 @@ class LazyNativeBrowserClient implements NativeBrowserClient {
|
|
|
23
23
|
private disposed = false
|
|
24
24
|
private detail = 'Optional browser extension is not connected; managed CDP fallback is available.'
|
|
25
25
|
private readonly listeners = new Set<Parameters<NativeBrowserClient['onEvent']>[0]>()
|
|
26
|
-
|
|
27
|
-
|
|
26
|
+
private readonly directory: string
|
|
27
|
+
private readonly browser: 'edge' | 'chrome'
|
|
28
|
+
constructor(directory: string, browser: 'edge' | 'chrome') {
|
|
29
|
+
this.directory = directory
|
|
30
|
+
this.browser = browser
|
|
31
|
+
}
|
|
28
32
|
|
|
29
33
|
status(): ExtensionConnectionStatus {
|
|
30
34
|
return this.client?.status() ?? { state: 'extension-missing', connected: false, browser: this.browser, detail: this.detail }
|
|
@@ -87,8 +91,11 @@ export class ExtensionBrowserViewHost implements ElectronBrowserViewHost {
|
|
|
87
91
|
private readonly detaching = new Map<BrowserSessionId, Set<Promise<unknown>>>()
|
|
88
92
|
private readonly unsubscribe: () => void
|
|
89
93
|
private disposed = false
|
|
90
|
-
|
|
91
|
-
|
|
94
|
+
readonly browser: 'edge' | 'chrome'
|
|
95
|
+
private readonly client: NativeBrowserClient
|
|
96
|
+
constructor(browser: 'edge' | 'chrome', client: NativeBrowserClient = new LazyNativeBrowserClient(extensionDirectory(browser), browser)) {
|
|
97
|
+
this.browser = browser
|
|
98
|
+
this.client = client
|
|
92
99
|
this.unsubscribe = client.onEvent(event => {
|
|
93
100
|
if (event.method === 'transport.disconnected') for (const view of this.views.values()) view.invalid = true
|
|
94
101
|
if (event.method === 'target.detached' || event.method === 'target.closed') {
|
|
@@ -0,0 +1,142 @@
|
|
|
1
|
+
import { spawn } from 'node:child_process'
|
|
2
|
+
|
|
3
|
+
export interface ForegroundEvent {
|
|
4
|
+
/** Process that owns the foreground window. */
|
|
5
|
+
readonly pid: number
|
|
6
|
+
/** Whether that window lies off every display (a minimized window does not count). */
|
|
7
|
+
readonly offscreen: boolean
|
|
8
|
+
/** That window's top-left corner, in DIPs like CDP window bounds. */
|
|
9
|
+
readonly left?: number
|
|
10
|
+
readonly top?: number
|
|
11
|
+
/** The browser took the foreground off every display with no input from the person, and the watcher gave it back. */
|
|
12
|
+
readonly yielded?: boolean
|
|
13
|
+
}
|
|
14
|
+
export interface ForegroundWatch { stop(): void }
|
|
15
|
+
/** `onFail` runs at most once, when the watcher cannot start or dies; `stop()` never triggers it. */
|
|
16
|
+
export type ForegroundWatcher = (onChange: (event: ForegroundEvent) => void, onFail: (reason: string) => void, browserPid?: number) => ForegroundWatch | undefined
|
|
17
|
+
|
|
18
|
+
const POLL_MS = 500
|
|
19
|
+
const PARENT_CHECK_MS = 4000
|
|
20
|
+
|
|
21
|
+
/*
|
|
22
|
+
* A foreground hook reports each activation within a millisecond; the poll only catches the
|
|
23
|
+
* foreground window moving on or off the displays, and a Stopwatch checks parent liveness
|
|
24
|
+
* every 4 s regardless of foreground event frequency.
|
|
25
|
+
*/
|
|
26
|
+
const script = (parent: number, browserPid: number): string => [
|
|
27
|
+
`$parent = ${parent}; $browser = ${browserPid}`,
|
|
28
|
+
'try {',
|
|
29
|
+
'Add-Type -TypeDefinition @"',
|
|
30
|
+
'using System; using System.Diagnostics; using System.Runtime.InteropServices;',
|
|
31
|
+
'public static class DshForeground {',
|
|
32
|
+
' [StructLayout(LayoutKind.Sequential)] public struct Rect { public int Left, Top, Right, Bottom; }',
|
|
33
|
+
' [StructLayout(LayoutKind.Sequential)] public struct InputInfo { public uint Size, Time; }',
|
|
34
|
+
' [StructLayout(LayoutKind.Sequential)] public struct Msg { public IntPtr Hwnd; public uint Message; public IntPtr W, L; public uint Time; public int X, Y; }',
|
|
35
|
+
' public delegate void Hook(IntPtr hook, uint e, IntPtr h, int o, int c, uint t, uint time);',
|
|
36
|
+
' [DllImport("user32.dll")] static extern IntPtr SetWinEventHook(uint min, uint max, IntPtr mod, Hook f, uint pid, uint tid, uint flags);',
|
|
37
|
+
' [DllImport("user32.dll")] static extern uint MsgWaitForMultipleObjects(uint n, IntPtr[] h, bool all, uint ms, uint mask);',
|
|
38
|
+
' [DllImport("user32.dll")] static extern bool PeekMessage(out Msg m, IntPtr h, uint a, uint b, uint remove);',
|
|
39
|
+
' [DllImport("user32.dll")] static extern bool TranslateMessage(ref Msg m);',
|
|
40
|
+
' [DllImport("user32.dll")] static extern IntPtr DispatchMessage(ref Msg m);',
|
|
41
|
+
' [DllImport("user32.dll")] static extern IntPtr GetForegroundWindow();',
|
|
42
|
+
' [DllImport("user32.dll")] static extern uint GetWindowThreadProcessId(IntPtr h, out uint p);',
|
|
43
|
+
' [DllImport("user32.dll")] static extern bool GetWindowRect(IntPtr h, out Rect r);',
|
|
44
|
+
' [DllImport("user32.dll")] static extern bool IsIconic(IntPtr h);',
|
|
45
|
+
' [DllImport("user32.dll")] static extern uint GetDpiForWindow(IntPtr h);',
|
|
46
|
+
' [DllImport("user32.dll")] static extern IntPtr MonitorFromRect(ref Rect r, uint flags);',
|
|
47
|
+
' [DllImport("user32.dll")] public static extern bool SetProcessDpiAwarenessContext(IntPtr c);',
|
|
48
|
+
' [DllImport("user32.dll")] public static extern bool SetProcessDPIAware();',
|
|
49
|
+
' [DllImport("user32.dll")] static extern bool SetForegroundWindow(IntPtr h);',
|
|
50
|
+
' [DllImport("user32.dll")] static extern bool AttachThreadInput(uint a, uint b, bool f);',
|
|
51
|
+
' [DllImport("kernel32.dll")] static extern uint GetCurrentThreadId();',
|
|
52
|
+
' [DllImport("user32.dll")] static extern bool GetLastInputInfo(ref InputInfo i);',
|
|
53
|
+
' static uint LastInput() { var i = new InputInfo(); i.Size = 8; GetLastInputInfo(ref i); return i.Time; }',
|
|
54
|
+
' static Hook keep; static string last = ""; static uint input, prevPid, browser; static IntPtr prev;',
|
|
55
|
+
' static void Sample() {',
|
|
56
|
+
' uint before = LastInput(), p; IntPtr h = GetForegroundWindow();',
|
|
57
|
+
// Transient null foreground (lock screen, UAC, window switch): keep prev intact instead of clearing it.
|
|
58
|
+
' if (h == IntPtr.Zero) { input = before; return; }',
|
|
59
|
+
' uint thread = GetWindowThreadProcessId(h, out p);',
|
|
60
|
+
' Rect r; GetWindowRect(h, out r);',
|
|
61
|
+
// Physical pixels from GetWindowRect, so dividing by the window DPI gives DIPs at any scaling.
|
|
62
|
+
' int off = IsIconic(h) || r.Right <= r.Left || MonitorFromRect(ref r, 0) != IntPtr.Zero ? 0 : 1;',
|
|
63
|
+
' uint dpi = GetDpiForWindow(h); if (dpi == 0) dpi = 96;',
|
|
64
|
+
' string line = p + " " + off + " " + Math.Round(r.Left * 96.0 / dpi) + " " + Math.Round(r.Top * 96.0 / dpi);',
|
|
65
|
+
// Chrome activates its own window for a tab a click opens; with no input since before the last read, no person did it.
|
|
66
|
+
// Always mark yielded even if SetForegroundWindow(prev) fails (e.g. elevated prev window under UIPI),
|
|
67
|
+
// and keep prev/prevPid unchanged so follow-up samples before focus settles cannot bypass the guard.
|
|
68
|
+
' bool yielded = false;',
|
|
69
|
+
' if (p == browser && off == 1 && prevPid != browser && prev != IntPtr.Zero && LastInput() == input) {',
|
|
70
|
+
' yielded = true; line += " 1";',
|
|
71
|
+
' uint me = GetCurrentThreadId(); AttachThreadInput(me, thread, true);',
|
|
72
|
+
' SetForegroundWindow(prev);',
|
|
73
|
+
' AttachThreadInput(me, thread, false);',
|
|
74
|
+
' }',
|
|
75
|
+
' if (line != last) { Console.Out.WriteLine(line); Console.Out.Flush(); last = line; }',
|
|
76
|
+
' if (!yielded) { prev = h; prevPid = p; }',
|
|
77
|
+
' input = before;',
|
|
78
|
+
' }',
|
|
79
|
+
' public static void Run(int parent, uint browserPid) {',
|
|
80
|
+
' browser = browserPid; input = LastInput(); keep = (a, e, h, o, c, t, time) => Sample();',
|
|
81
|
+
' SetWinEventHook(3, 3, IntPtr.Zero, keep, 0, 0, 0);',
|
|
82
|
+
' var parentClock = Stopwatch.StartNew();',
|
|
83
|
+
' Sample(); Msg m;',
|
|
84
|
+
' for (;;) {',
|
|
85
|
+
` if (MsgWaitForMultipleObjects(0, null, false, ${POLL_MS}, 0x4FF) == 0x102) Sample();`,
|
|
86
|
+
' while (PeekMessage(out m, IntPtr.Zero, 0, 0, 1)) { TranslateMessage(ref m); DispatchMessage(ref m); }',
|
|
87
|
+
` if (parentClock.ElapsedMilliseconds >= ${PARENT_CHECK_MS}) {`,
|
|
88
|
+
' parentClock.Restart();',
|
|
89
|
+
' try { Process.GetProcessById(parent).Dispose(); } catch (ArgumentException) { return; }',
|
|
90
|
+
' }',
|
|
91
|
+
' }',
|
|
92
|
+
' }',
|
|
93
|
+
'}',
|
|
94
|
+
'"@',
|
|
95
|
+
'} catch { exit 3 }',
|
|
96
|
+
'if (-not [DshForeground]::SetProcessDpiAwarenessContext([IntPtr](-4))) { [void][DshForeground]::SetProcessDPIAware() }',
|
|
97
|
+
'try { [DshForeground]::Run($parent, $browser) } catch { exit 4 }',
|
|
98
|
+
].join('\n')
|
|
99
|
+
|
|
100
|
+
/** One line of the watcher's output, `<pid> <0|1> [<left> <top> [1]]`, the last `1` when it gave the foreground back. */
|
|
101
|
+
export function parseForegroundLine(line: string): ForegroundEvent | undefined {
|
|
102
|
+
const match = /^(\d+) ([01])(?: (-?\d+) (-?\d+)( 1)?)?$/u.exec(line.trim())
|
|
103
|
+
if (match === null) return undefined
|
|
104
|
+
const event = { pid: Number(match[1]), offscreen: match[2] === '1' }
|
|
105
|
+
if (match[3] === undefined) return event
|
|
106
|
+
return { ...event, left: Number(match[3]), top: Number(match[4]), ...match[5] === undefined ? {} : { yielded: true } }
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
/**
|
|
110
|
+
* Report the foreground window's process, and whether that window is off every display, each time
|
|
111
|
+
* either changes. Windows only: CDP cannot tell a person activating a window from Chrome activating
|
|
112
|
+
* it for a tab an agent's click opened, but only the person's leaves input. The watcher exits with this process.
|
|
113
|
+
*/
|
|
114
|
+
export const watchForeground: ForegroundWatcher = (onChange, onFail, browserPid = 0) => {
|
|
115
|
+
if (process.platform !== 'win32') return undefined
|
|
116
|
+
let child
|
|
117
|
+
try {
|
|
118
|
+
child = spawn('powershell.exe', ['-NoProfile', '-NonInteractive', '-ExecutionPolicy', 'Bypass', '-EncodedCommand',
|
|
119
|
+
Buffer.from(script(process.pid, browserPid), 'utf16le').toString('base64')], { stdio: ['ignore', 'pipe', 'ignore'], windowsHide: true })
|
|
120
|
+
} catch (error) {
|
|
121
|
+
onFail(String(error))
|
|
122
|
+
return undefined
|
|
123
|
+
}
|
|
124
|
+
let stopped = false
|
|
125
|
+
let failed = false
|
|
126
|
+
const fail = (reason: string): void => { if (!stopped && !failed) { failed = true; onFail(reason) } }
|
|
127
|
+
child.on('error', error => fail(String(error)))
|
|
128
|
+
child.on('exit', (code, signal) => fail(`exited (${signal ?? code})`))
|
|
129
|
+
child.unref()
|
|
130
|
+
let buffer = ''
|
|
131
|
+
child.stdout?.setEncoding('utf8')
|
|
132
|
+
child.stdout?.on('data', (chunk: string) => {
|
|
133
|
+
buffer += chunk
|
|
134
|
+
for (let end = buffer.indexOf('\n'); end >= 0; end = buffer.indexOf('\n')) {
|
|
135
|
+
const event = parseForegroundLine(buffer.slice(0, end))
|
|
136
|
+
buffer = buffer.slice(end + 1)
|
|
137
|
+
if (event !== undefined) onChange(event)
|
|
138
|
+
}
|
|
139
|
+
})
|
|
140
|
+
;(child.stdout as { unref?: () => void } | null)?.unref?.()
|
|
141
|
+
return { stop: () => { stopped = true; try { child.kill() } catch { /* already gone */ } } }
|
|
142
|
+
}
|
|
@@ -79,8 +79,9 @@ function pathMatches(pathname: string, path: string): boolean {
|
|
|
79
79
|
|
|
80
80
|
export class GuestCookieJar {
|
|
81
81
|
private readonly store = new Map<string, ScopedCookie>()
|
|
82
|
-
|
|
83
|
-
constructor(
|
|
82
|
+
private readonly changed?: (cookies: readonly StoredCookie[]) => void
|
|
83
|
+
constructor(changed?: (cookies: readonly StoredCookie[]) => void, saved: readonly StoredCookie[] = []) {
|
|
84
|
+
this.changed = changed
|
|
84
85
|
for (const value of saved) {
|
|
85
86
|
const cookie = normalizeStoredCookie(value)
|
|
86
87
|
if (cookie !== undefined && (cookie.expiresAt === undefined || cookie.expiresAt > Date.now())) {
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { hostMessages } from '../../assets/browser-messages.mjs'
|
|
2
|
-
import { GUEST_ROUTE } from '../../assets/browser-policy.mjs'
|
|
2
|
+
import { GUEST_ROUTE, RELAXED_BROWSER_SANDBOX, WEB_BROWSER_SANDBOX } from '../../assets/browser-policy.mjs'
|
|
3
3
|
/**
|
|
4
4
|
* Web guests execute in CSP-sandboxed opaque origins, including direct document loads.
|
|
5
5
|
* Only this proxy prefix is available to guest network requests. App storage, APIs,
|
|
@@ -7,14 +7,20 @@ import { GUEST_ROUTE } from '../../assets/browser-policy.mjs'
|
|
|
7
7
|
* @module dsh-builtin-browser/browser-electron/guest-route
|
|
8
8
|
*/
|
|
9
9
|
import type { IncomingMessage, OutgoingHttpHeaders, ServerResponse } from 'node:http'
|
|
10
|
-
import { promises as dns } from 'node:dns'
|
|
10
|
+
import { promises as dns, type LookupAddress } from 'node:dns'
|
|
11
|
+
import { Agent, fetch as undiciFetch } from 'undici'
|
|
12
|
+
import { networkInterfaces } from 'node:os'
|
|
11
13
|
import { randomUUID } from 'node:crypto'
|
|
12
14
|
import { guestRuntimeScript } from './guest-runtime.ts'
|
|
15
|
+
import { blockRetryDelayMs, classifyBlock } from '../browser/anti-bot.ts'
|
|
13
16
|
import type { GuestCookieJar } from './guest-cookie-jar.ts'
|
|
14
17
|
import { localGuestCookies } from './guest-cookie-store.ts'
|
|
15
18
|
import { rewriteCss } from './guest-css.ts'
|
|
16
19
|
import { GuestStorage, localGuestStorage } from './guest-storage.ts'
|
|
17
20
|
|
|
21
|
+
/** Captured at load time so production uses undici's matching fetch while tests mocking globalThis.fetch still work. */
|
|
22
|
+
const defaultGlobalFetch = globalThis.fetch
|
|
23
|
+
|
|
18
24
|
/** Prefix every proxied document and subresource lives under. */
|
|
19
25
|
|
|
20
26
|
/**
|
|
@@ -41,6 +47,70 @@ function isSelfTarget(url: URL): boolean {
|
|
|
41
47
|
|
|
42
48
|
export { GUEST_ROUTE }
|
|
43
49
|
|
|
50
|
+
function blockedTarget(url: URL, host: string): boolean {
|
|
51
|
+
return !/^https?:$/u.test(url.protocol) || url.username !== '' || url.password !== ''
|
|
52
|
+
|| isSelfTarget(url) || url.hostname.toLowerCase().replace(/\.$/u, '') === host
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
async function lookupAll(hostname: string): Promise<LookupAddress[]> {
|
|
56
|
+
return await dns.lookup(hostname.replace(/^\[|\]$/gu, ''), { all: true })
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
async function addressesFor(hostname: string): Promise<string[]> {
|
|
60
|
+
return (await lookupAll(hostname)).map(record => record.address)
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
async function vettedAddress(url: URL, host: string, ownAddresses: readonly string[]): Promise<LookupAddress[] | undefined> {
|
|
64
|
+
if (blockedTarget(url, host)) return undefined
|
|
65
|
+
const records = await lookupAll(url.hostname)
|
|
66
|
+
const hostUrl = host === '' ? undefined : new URL('http://' + host)
|
|
67
|
+
const hostAddresses = hostUrl === undefined || isSelfTarget(hostUrl) ? [] : await addressesFor(host).catch(() => [])
|
|
68
|
+
const unsafe = records.length === 0 || records.some(({ address }) => {
|
|
69
|
+
const literal = new URL('http://' + (address.includes(':') ? '[' + address + ']' : address))
|
|
70
|
+
return isSelfTarget(literal) || hostAddresses.includes(address) || ownAddresses.includes(address)
|
|
71
|
+
})
|
|
72
|
+
return unsafe ? undefined : records
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
async function blockedResolvedTarget(url: URL, host: string, ownAddresses: readonly string[]): Promise<boolean> {
|
|
76
|
+
return await vettedAddress(url, host, ownAddresses) === undefined
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/**
|
|
80
|
+
* Connect to the address that was vetted, so a second DNS answer (rebinding) never picks the peer.
|
|
81
|
+
*
|
|
82
|
+
* Uses `undici`'s own `fetch` alongside its `Agent` so the dispatcher protocol stays paired across
|
|
83
|
+
* Node major versions (e.g. Node 24 vs Node 26+). When a test replaces `globalThis.fetch`, defer
|
|
84
|
+
* to that mock without injecting an external `undici` dispatcher into it.
|
|
85
|
+
*/
|
|
86
|
+
async function fetchVetted(url: URL, init: RequestInit, host: string, ownAddresses: readonly string[]): Promise<Response> {
|
|
87
|
+
const addresses = await vettedAddress(url, host, ownAddresses)
|
|
88
|
+
if (addresses === undefined) throw new UnsafeGuestTargetError('local and DSH host targets are not allowed')
|
|
89
|
+
if (globalThis.fetch !== defaultGlobalFetch) {
|
|
90
|
+
return await globalThis.fetch(url, init)
|
|
91
|
+
}
|
|
92
|
+
const dispatcher = new Agent({
|
|
93
|
+
connect: {
|
|
94
|
+
lookup: (_hostname: string, options: unknown, callback?: (...args: unknown[]) => void) => {
|
|
95
|
+
const done = typeof options === 'function' ? options as (...args: unknown[]) => void : callback!
|
|
96
|
+
const all = typeof options === 'object' && options !== null && (options as { all?: boolean }).all === true
|
|
97
|
+
if (all) done(null, addresses.map(record => ({ ...record })))
|
|
98
|
+
else done(null, addresses[0]?.address, addresses[0]?.family)
|
|
99
|
+
},
|
|
100
|
+
} as never,
|
|
101
|
+
})
|
|
102
|
+
const headers = init.headers === undefined ? undefined : Array.from(new Headers(init.headers))
|
|
103
|
+
try {
|
|
104
|
+
return await undiciFetch(url, {
|
|
105
|
+
...init,
|
|
106
|
+
...(headers === undefined ? {} : { headers }),
|
|
107
|
+
dispatcher,
|
|
108
|
+
} as Parameters<typeof undiciFetch>[1]) as unknown as Response
|
|
109
|
+
} finally {
|
|
110
|
+
void dispatcher.close().catch(() => {})
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
|
|
44
114
|
class UnsafeGuestTargetError extends Error {}
|
|
45
115
|
|
|
46
116
|
/** HTML responses larger than this pass through without rewriting. */
|
|
@@ -95,6 +165,22 @@ const SAFE_REQUEST_HEADERS = new Set([
|
|
|
95
165
|
'if-none-match', 'if-modified-since', 'cache-control',
|
|
96
166
|
])
|
|
97
167
|
|
|
168
|
+
function guestReferer(page: URL, target: URL, policy: string): string | undefined {
|
|
169
|
+
const sameOrigin = page.origin === target.origin
|
|
170
|
+
const downgrade = page.protocol === 'https:' && target.protocol === 'http:'
|
|
171
|
+
const origin = page.origin + '/'
|
|
172
|
+
switch (policy) {
|
|
173
|
+
case 'no-referrer': return undefined
|
|
174
|
+
case 'unsafe-url': return page.href
|
|
175
|
+
case 'origin': return origin
|
|
176
|
+
case 'same-origin': return sameOrigin ? page.href : undefined
|
|
177
|
+
case 'strict-origin': return downgrade ? undefined : origin
|
|
178
|
+
case 'origin-when-cross-origin': return sameOrigin ? page.href : origin
|
|
179
|
+
case 'no-referrer-when-downgrade': return downgrade ? undefined : page.href
|
|
180
|
+
default: return downgrade ? undefined : sameOrigin ? page.href : origin
|
|
181
|
+
}
|
|
182
|
+
}
|
|
183
|
+
|
|
98
184
|
function siteHeader(name: string): boolean {
|
|
99
185
|
return /^[!#$%&'*+.^_`|~\da-z-]+$/u.test(name)
|
|
100
186
|
&& !/^(?:cookie2?|authorization|host|origin|referer|connection|content-length|accept-encoding|user-agent|proxy-.*|sec-.*|x-dsh-.*|x-forwarded-.*|x-real-ip)$/u.test(name)
|
|
@@ -243,9 +329,9 @@ export function relayTag(_sessionId: string): string {
|
|
|
243
329
|
</script>`
|
|
244
330
|
}
|
|
245
331
|
|
|
246
|
-
function guestPolicy(authority: string): string {
|
|
332
|
+
function guestPolicy(authority: string, framed: boolean): string {
|
|
247
333
|
const sources = ['http:', 'https:'].map(protocol => new URL(protocol + '//' + authority).origin + GUEST_ROUTE).join(' ')
|
|
248
|
-
return "sandbox
|
|
334
|
+
return "sandbox " + (framed ? RELAXED_BROWSER_SANDBOX : WEB_BROWSER_SANDBOX) + "; default-src " + sources
|
|
249
335
|
+ "; script-src " + sources + " 'unsafe-inline' 'unsafe-eval'; style-src " + sources
|
|
250
336
|
+ " 'unsafe-inline'; img-src " + sources + " data: blob:; font-src " + sources + " data:; connect-src " + sources
|
|
251
337
|
+ "; frame-src " + sources + "; form-action " + sources
|
|
@@ -268,7 +354,7 @@ export async function handleGuest(
|
|
|
268
354
|
response.end('guest proxy: invalid host')
|
|
269
355
|
return
|
|
270
356
|
}
|
|
271
|
-
const policy = guestPolicy(authority)
|
|
357
|
+
const policy = guestPolicy(authority, request.headers['sec-fetch-dest'] === 'iframe')
|
|
272
358
|
const writeHead = (status: number, headers: OutgoingHttpHeaders = {}): void => {
|
|
273
359
|
response.writeHead(status, { ...headers, 'content-security-policy': policy })
|
|
274
360
|
}
|
|
@@ -279,7 +365,7 @@ export async function handleGuest(
|
|
|
279
365
|
const requested = String(request.headers['access-control-request-headers'] ?? '').toLowerCase().split(',').map(name => name.trim())
|
|
280
366
|
writeHead(204, {
|
|
281
367
|
'access-control-allow-methods': 'GET, HEAD, POST, PUT, PATCH, DELETE, OPTIONS',
|
|
282
|
-
'access-control-allow-headers': [...new Set([...SAFE_REQUEST_HEADERS, 'x-dsh-guest-sub', 'x-dsh-guest-headers', ...requested.filter(siteHeader)])].join(', '),
|
|
368
|
+
'access-control-allow-headers': [...new Set([...SAFE_REQUEST_HEADERS, 'x-dsh-guest-sub', 'x-dsh-guest-headers', 'x-dsh-guest-referer', 'x-dsh-guest-referrer-policy', ...requested.filter(siteHeader)])].join(', '),
|
|
283
369
|
})
|
|
284
370
|
response.end()
|
|
285
371
|
return
|
|
@@ -294,26 +380,11 @@ export async function handleGuest(
|
|
|
294
380
|
}
|
|
295
381
|
let host = ''
|
|
296
382
|
try { host = new URL('http://' + (request.headers.host ?? '')).hostname.toLowerCase().replace(/\.$/u, '') } catch {}
|
|
297
|
-
const blocked = (url: URL): boolean =>
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
(await dns.lookup(hostname.replace(/^\[|\]$/gu, ''), { all: true })).map(record => record.address)
|
|
303
|
-
const blockedResolved = async (url: URL): Promise<boolean> => {
|
|
304
|
-
if (blocked(url)) return true
|
|
305
|
-
const addresses = await addressesFor(url.hostname)
|
|
306
|
-
const hostUrl = host === '' ? undefined : new URL('http://' + host)
|
|
307
|
-
const hostAddresses = hostUrl === undefined || isSelfTarget(hostUrl) ? [] : await addressesFor(host).catch(() => [])
|
|
308
|
-
return addresses.length === 0 || addresses.some(address => {
|
|
309
|
-
const literal = new URL('http://' + (address.includes(':') ? '[' + address + ']' : address))
|
|
310
|
-
return isSelfTarget(literal) || hostAddresses.includes(address) || address === request.socket.localAddress
|
|
311
|
-
})
|
|
312
|
-
}
|
|
313
|
-
const fetchTarget = async (url: URL, options: RequestInit): Promise<Response> => {
|
|
314
|
-
if (await blockedResolved(url)) throw new UnsafeGuestTargetError('local and DSH host targets are not allowed')
|
|
315
|
-
return fetch(url, options)
|
|
316
|
-
}
|
|
383
|
+
const blocked = (url: URL): boolean => blockedTarget(url, host)
|
|
384
|
+
const blockedResolved = (url: URL): Promise<boolean> =>
|
|
385
|
+
blockedResolvedTarget(url, host, request.socket.localAddress === undefined ? [] : [request.socket.localAddress])
|
|
386
|
+
const fetchTarget = (url: URL, options: RequestInit): Promise<Response> =>
|
|
387
|
+
fetchVetted(url, options, host, request.socket.localAddress === undefined ? [] : [request.socket.localAddress])
|
|
317
388
|
if (blocked(target)) {
|
|
318
389
|
writeHead(403, { 'content-type': 'text/plain; charset=utf-8' })
|
|
319
390
|
response.end('guest proxy: local and DSH host targets are not allowed')
|
|
@@ -398,6 +469,18 @@ export async function handleGuest(
|
|
|
398
469
|
}
|
|
399
470
|
} catch {}
|
|
400
471
|
}
|
|
472
|
+
const pageReferer = request.headers['x-dsh-guest-referer']
|
|
473
|
+
if (subRequest && !headers.has('referer') && typeof pageReferer === 'string') {
|
|
474
|
+
try {
|
|
475
|
+
const page = new URL(pageReferer)
|
|
476
|
+
page.hash = ''
|
|
477
|
+
page.username = ''
|
|
478
|
+
page.password = ''
|
|
479
|
+
const policy = request.headers['x-dsh-guest-referrer-policy']
|
|
480
|
+
const value = blocked(page) ? undefined : guestReferer(page, target, typeof policy === 'string' ? policy : '')
|
|
481
|
+
if (value !== undefined) headers.set('referer', value)
|
|
482
|
+
} catch {}
|
|
483
|
+
}
|
|
401
484
|
let cookieJar: GuestCookieJar
|
|
402
485
|
try { cookieJar = cookies ?? localGuestCookies() } catch {
|
|
403
486
|
writeHead(503, { 'content-type': 'text/plain; charset=utf-8' })
|
|
@@ -470,15 +553,17 @@ export async function handleGuest(
|
|
|
470
553
|
}
|
|
471
554
|
upstream = await fetchTarget(target, { method, headers, body: body as BodyInit | undefined, redirect: 'manual' })
|
|
472
555
|
cookieJar.setCookies(target, upstream.headers.getSetCookie?.() ?? [])
|
|
473
|
-
//
|
|
474
|
-
//
|
|
475
|
-
//
|
|
476
|
-
|
|
556
|
+
// 反爬拦截识别 + 一次重试(分类器与页面内检测共用 `browser/anti-bot.ts`):站点(百度 `/s?wd=…`)在没有
|
|
557
|
+
// 「先访问过站点」的痕迹时回「安全验证」。罐子里可能已经带着上次挑战页的 Cookie,所以看**内容**而不看有没有 Cookie。
|
|
558
|
+
// 只对「可重试」类(拒绝访问 / 429 / 空 403)与需人工验证类做一次放慢节奏的重试:先停一下,取站点根补 Cookie、
|
|
559
|
+
// 带上根的 Referer 再请求一次。仍失败就把原页交给上层(页内检测会给出接管或换路的建议);网络(IP)封锁不重试。
|
|
477
560
|
if (safeNavigation && target.pathname !== '/' && /^text\/html/iu.test(upstream.headers.get('content-type') ?? '')
|
|
478
561
|
&& Number(upstream.headers.get('content-length') ?? '0') <= MAX_REWRITE_BYTES) {
|
|
479
562
|
const probe = await upstream.clone().text()
|
|
480
|
-
|
|
563
|
+
const verdict = classifyBlock({ status: upstream.status, text: probe.slice(0, 64 * 1024) })
|
|
564
|
+
if (verdict.blocked && verdict.recovery !== 'environment') {
|
|
481
565
|
try {
|
|
566
|
+
await new Promise(resolve => setTimeout(resolve, blockRetryDelayMs()))
|
|
482
567
|
await warmRoot()
|
|
483
568
|
const retried = await fetchTarget(target, { method, headers, redirect: 'manual' })
|
|
484
569
|
await upstream.body?.cancel()
|
|
@@ -548,7 +633,7 @@ export async function handleGuest(
|
|
|
548
633
|
const storageConfig = (destination === 'iframe' || destination === 'document') && request.headers['sec-fetch-mode'] === 'navigate'
|
|
549
634
|
&& /^[\w:-]{16,128}$/u.test(context)
|
|
550
635
|
? { token: (storage ?? localGuestStorage()).issue(target.origin, context), context, cookies: cookieJar.getDocumentCookie(target) } : undefined
|
|
551
|
-
const runtime = '<script data-dsh-guest-runtime="1">' + guestRuntimeScript(target.href, storageConfig) + '</script>'
|
|
636
|
+
const runtime = '<script data-dsh-guest-runtime="1">' + guestRuntimeScript(target.href, storageConfig, upstream.headers.get('referrer-policy') ?? '') + '</script>'
|
|
552
637
|
let body = rewriteDocument(raw, target)
|
|
553
638
|
if (/<head\b[^>]*>/iu.test(body)) body = body.replace(/<head\b[^>]*>/iu, match => match + runtime)
|
|
554
639
|
else if (/<html\b[^>]*>/iu.test(body)) body = body.replace(/<html\b[^>]*>/iu, match => match + '<head>' + runtime + '</head>')
|
|
@@ -566,3 +651,66 @@ export async function handleGuest(
|
|
|
566
651
|
failUpstream('response', error)
|
|
567
652
|
}
|
|
568
653
|
}
|
|
654
|
+
|
|
655
|
+
function realGuestUrl(raw: string): URL {
|
|
656
|
+
const parsed = new URL(raw, 'http://guest.invalid')
|
|
657
|
+
const inner = parsed.pathname === GUEST_ROUTE ? guestTarget(parsed.pathname + parsed.search) : undefined
|
|
658
|
+
if (inner !== undefined) return inner
|
|
659
|
+
if (parsed.origin === 'http://guest.invalid') throw new UnsafeGuestTargetError('a guest resource URL must be absolute')
|
|
660
|
+
return parsed
|
|
661
|
+
}
|
|
662
|
+
|
|
663
|
+
/**
|
|
664
|
+
* Fetch one resource a guest page loaded, on the server and under the proxy's own target rules.
|
|
665
|
+
* The Web sidebar's guest is an iframe with no browser session, so this is the only way a frozen
|
|
666
|
+
* quote can get an image's bytes. It sends what the proxy sent when the page loaded the image:
|
|
667
|
+
* guest documents are no-referrer, so no referer and the cookie jar's unscoped cookies, and it
|
|
668
|
+
* keeps the cookies each redirect hop sets.
|
|
669
|
+
*/
|
|
670
|
+
export async function fetchGuestResource(raw: string, options: {
|
|
671
|
+
readonly dshHost?: string
|
|
672
|
+
readonly maxBytes: number
|
|
673
|
+
readonly signal?: AbortSignal
|
|
674
|
+
readonly cookies?: GuestCookieJar
|
|
675
|
+
}): Promise<Buffer> {
|
|
676
|
+
const own = Object.values(networkInterfaces()).flatMap(list => (list ?? []).map(entry => entry.address))
|
|
677
|
+
let host = ''
|
|
678
|
+
try { host = options.dshHost === undefined ? '' : new URL('http://' + options.dshHost).hostname.toLowerCase().replace(/[.]$/u, '') } catch {}
|
|
679
|
+
let url = realGuestUrl(raw)
|
|
680
|
+
let jar: GuestCookieJar | undefined
|
|
681
|
+
try { jar = options.cookies ?? localGuestCookies() } catch { jar = undefined }
|
|
682
|
+
for (let hop = 0; hop <= 5; hop++) {
|
|
683
|
+
const headers = new Headers({
|
|
684
|
+
'user-agent': DESKTOP_UA, accept: 'image/avif,image/webp,image/apng,image/*,*/*;q=0.8', 'accept-encoding': 'identity',
|
|
685
|
+
})
|
|
686
|
+
const cookie = jar?.getCookieHeader(url)
|
|
687
|
+
if (cookie !== undefined && cookie !== '') headers.set('cookie', cookie)
|
|
688
|
+
const response = await fetchVetted(url, { headers, redirect: 'manual', ...options.signal === undefined ? {} : { signal: options.signal } }, host, own)
|
|
689
|
+
jar?.setCookies(url, response.headers.getSetCookie?.() ?? [])
|
|
690
|
+
const location = response.headers.get('location')
|
|
691
|
+
if (response.status >= 300 && response.status < 400 && location !== null) {
|
|
692
|
+
await response.body?.cancel()
|
|
693
|
+
url = new URL(location, url)
|
|
694
|
+
continue
|
|
695
|
+
}
|
|
696
|
+
if (!response.ok) {
|
|
697
|
+
await response.body?.cancel()
|
|
698
|
+
throw new Error('guest resource answered ' + response.status)
|
|
699
|
+
}
|
|
700
|
+
const chunks: Uint8Array[] = []
|
|
701
|
+
let size = 0
|
|
702
|
+
const reader = response.body?.getReader()
|
|
703
|
+
while (reader !== undefined) {
|
|
704
|
+
const { done, value } = await reader.read()
|
|
705
|
+
if (done) break
|
|
706
|
+
size += value.byteLength
|
|
707
|
+
if (size > options.maxBytes) {
|
|
708
|
+
await reader.cancel()
|
|
709
|
+
throw new Error('guest resource exceeds ' + options.maxBytes + ' bytes')
|
|
710
|
+
}
|
|
711
|
+
chunks.push(value)
|
|
712
|
+
}
|
|
713
|
+
return Buffer.concat(chunks)
|
|
714
|
+
}
|
|
715
|
+
throw new Error('guest resource redirected too many times')
|
|
716
|
+
}
|
|
@@ -1,14 +1,15 @@
|
|
|
1
1
|
import { guestReferenceHandlerScript } from '../browser-reference/page-script.ts'
|
|
2
2
|
import { guestStorageScript, type GuestStorageConfig } from './guest-storage-runtime.ts'
|
|
3
3
|
import { guestCssRuntimeScript } from './guest-css-runtime.ts'
|
|
4
|
+
import { GUEST_ROUTE } from '../../assets/browser-policy.mjs'
|
|
4
5
|
|
|
5
6
|
/** Early, self-contained interception for documents served from the guest proxy. */
|
|
6
|
-
export function guestRuntimeScript(pageUrl: string, storage?: GuestStorageConfig): string {
|
|
7
|
+
export function guestRuntimeScript(pageUrl: string, storage?: GuestStorageConfig, referrerPolicy = ''): string {
|
|
7
8
|
return `(() => {
|
|
8
9
|
if (window.__dshGuestRuntime) return;
|
|
9
10
|
window.__dshGuestRuntime = true;
|
|
10
11
|
let real = ${JSON.stringify(pageUrl).replace(/</gu, '\\u003c')};
|
|
11
|
-
const route =
|
|
12
|
+
const route = ${JSON.stringify(GUEST_ROUTE)};
|
|
12
13
|
const attempt = fn => { try { return fn(); } catch {} };
|
|
13
14
|
attempt(() => {
|
|
14
15
|
const cache = { match: async () => undefined, matchAll: async () => [], keys: async () => [],
|
|
@@ -32,6 +33,13 @@ export function guestRuntimeScript(pageUrl: string, storage?: GuestStorageConfig
|
|
|
32
33
|
const inner = proxyURL.searchParams.get('u');
|
|
33
34
|
if (inner) return new URL(inner);
|
|
34
35
|
}
|
|
36
|
+
const own = raw === '' || /^[?#]/.test(raw) ? undefined : new URL(raw, location.href);
|
|
37
|
+
if (own && own.origin === location.origin && own.pathname === route && !own.searchParams.has('u')) {
|
|
38
|
+
const url = new URL(real);
|
|
39
|
+
url.search = own.search;
|
|
40
|
+
url.hash = own.hash;
|
|
41
|
+
return url;
|
|
42
|
+
}
|
|
35
43
|
let url = new URL(raw, real);
|
|
36
44
|
if (url.origin === location.origin) {
|
|
37
45
|
url = new URL(url.pathname + url.search + url.hash, new URL(real).origin);
|
|
@@ -48,6 +56,23 @@ export function guestRuntimeScript(pageUrl: string, storage?: GuestStorageConfig
|
|
|
48
56
|
} catch { return value; }
|
|
49
57
|
};
|
|
50
58
|
window.__dshGuestToProxy = toProxy;
|
|
59
|
+
const policies = ['no-referrer', 'no-referrer-when-downgrade', 'origin', 'origin-when-cross-origin', 'same-origin', 'strict-origin', 'strict-origin-when-cross-origin', 'unsafe-url'];
|
|
60
|
+
const referrerPolicy = override => {
|
|
61
|
+
if (policies.includes(override)) return override;
|
|
62
|
+
const metas = attempt(() => [...document.querySelectorAll('meta[name="referrer" i]')]) || [];
|
|
63
|
+
const last = value => String(value || '').split(',').map(item => item.trim().toLowerCase()).reverse().find(item => policies.includes(item));
|
|
64
|
+
for (const meta of metas.reverse()) {
|
|
65
|
+
const token = last(meta.content);
|
|
66
|
+
if (token) return token;
|
|
67
|
+
}
|
|
68
|
+
return last(${JSON.stringify(referrerPolicy).replace(/</gu, '\\u003c')}) || '';
|
|
69
|
+
};
|
|
70
|
+
const requestInit = ['body', 'cache', 'credentials', 'duplex', 'headers', 'integrity', 'keepalive', 'method', 'mode', 'priority', 'redirect', 'referrer', 'referrerPolicy', 'signal', 'window'];
|
|
71
|
+
const refererHeaders = (set, override) => {
|
|
72
|
+
set('x-dsh-guest-referer', real);
|
|
73
|
+
const policy = referrerPolicy(override);
|
|
74
|
+
if (policy) set('x-dsh-guest-referrer-policy', policy);
|
|
75
|
+
};
|
|
51
76
|
const nativeFetch = window.fetch && window.fetch.bind(window);
|
|
52
77
|
window.__dshGuestFetch = nativeFetch;
|
|
53
78
|
attempt(() => {
|
|
@@ -59,6 +84,8 @@ export function guestRuntimeScript(pageUrl: string, storage?: GuestStorageConfig
|
|
|
59
84
|
const headers = new Headers(init && init.headers || (isRequest ? input.headers : undefined));
|
|
60
85
|
headers.set('x-dsh-guest-headers', [...headers.keys()].filter(name => !name.startsWith('x-dsh-')).join(','));
|
|
61
86
|
headers.set('x-dsh-guest-sub', '1');
|
|
87
|
+
const source = init && requestInit.some(name => init[name] !== undefined) ? init : isRequest ? input : {};
|
|
88
|
+
refererHeaders((name, value) => headers.set(name, value), source.referrer === '' ? 'no-referrer' : source.referrerPolicy || '');
|
|
62
89
|
const options = Object.assign({}, init, { headers, mode: 'cors', credentials: 'omit' });
|
|
63
90
|
return nativeFetch(isRequest ? new Request(new URL(url, location.href), input) : url, options);
|
|
64
91
|
} catch (error) { return Promise.reject(error); }
|
|
@@ -73,6 +100,7 @@ export function guestRuntimeScript(pageUrl: string, storage?: GuestStorageConfig
|
|
|
73
100
|
const result = open.call(this, method, toProxy(url), ...args);
|
|
74
101
|
names.set(this, new Set());
|
|
75
102
|
attempt(() => this.setRequestHeader('x-dsh-guest-sub', '1'));
|
|
103
|
+
attempt(() => refererHeaders((name, value) => this.setRequestHeader(name, value)));
|
|
76
104
|
return result;
|
|
77
105
|
};
|
|
78
106
|
XMLHttpRequest.prototype.setRequestHeader = function(name, value) {
|
|
@@ -90,8 +118,9 @@ export function guestRuntimeScript(pageUrl: string, storage?: GuestStorageConfig
|
|
|
90
118
|
attempt(() => {
|
|
91
119
|
navigator.sendBeacon = (url, data) => {
|
|
92
120
|
try {
|
|
93
|
-
|
|
94
|
-
|
|
121
|
+
const headers = { 'x-dsh-guest-sub': '1' };
|
|
122
|
+
refererHeaders((name, value) => { headers[name] = value; });
|
|
123
|
+
nativeFetch(toProxy(url), { method: 'POST', body: data, keepalive: true, headers }).catch(() => {});
|
|
95
124
|
return true;
|
|
96
125
|
} catch { return false; }
|
|
97
126
|
};
|
|
@@ -125,12 +154,17 @@ export function guestRuntimeScript(pageUrl: string, storage?: GuestStorageConfig
|
|
|
125
154
|
}; });
|
|
126
155
|
for (const name of ['pushState', 'replaceState']) attempt(() => {
|
|
127
156
|
const original = history[name];
|
|
157
|
+
const reason = name === 'pushState' ? 'push' : 'replace';
|
|
128
158
|
history[name] = function(state, title, url) {
|
|
129
|
-
if (url == null)
|
|
159
|
+
if (url == null) {
|
|
160
|
+
const result = original.call(this, state, title, url);
|
|
161
|
+
if (name === 'pushState') report(reason);
|
|
162
|
+
return result;
|
|
163
|
+
}
|
|
130
164
|
const next = attempt(() => realURL(url));
|
|
131
165
|
const result = original.call(this, state, title, toProxy(url));
|
|
132
166
|
if (next && /^https?:$/.test(next.protocol)) real = next.href;
|
|
133
|
-
report();
|
|
167
|
+
report(reason);
|
|
134
168
|
return result;
|
|
135
169
|
};
|
|
136
170
|
});
|
|
@@ -138,13 +172,29 @@ export function guestRuntimeScript(pageUrl: string, storage?: GuestStorageConfig
|
|
|
138
172
|
const documentId = String(Date.now()) + ':' + String(Math.random());
|
|
139
173
|
let referenceRequestId = 0;
|
|
140
174
|
const reference = ${guestReferenceHandlerScript()};
|
|
141
|
-
const
|
|
175
|
+
const navType = () => {
|
|
176
|
+
const entry = attempt(() => performance.getEntriesByType && performance.getEntriesByType('navigation')[0]);
|
|
177
|
+
return entry && typeof entry.type === 'string' ? entry.type : undefined;
|
|
178
|
+
};
|
|
179
|
+
const report = (reason) => attempt(() => {
|
|
180
|
+
const navigationType = navType();
|
|
181
|
+
parent.postMessage({
|
|
182
|
+
type: 'dsh.browser.guest.navigation',
|
|
183
|
+
url: real,
|
|
184
|
+
depth: history.length,
|
|
185
|
+
loadId,
|
|
186
|
+
documentId,
|
|
187
|
+
ready: document.readyState !== 'loading',
|
|
188
|
+
...(typeof reason === 'string' && reason ? { reason } : {}),
|
|
189
|
+
...(navigationType ? { navigationType } : {}),
|
|
190
|
+
}, '*');
|
|
191
|
+
});
|
|
142
192
|
attempt(() => window.addEventListener('message', event => {
|
|
143
193
|
if (event.source !== parent || !event.data) return;
|
|
144
194
|
if (event.data.type === 'dsh.browser.guest.navigation.request') {
|
|
145
195
|
if (!Number.isSafeInteger(event.data.loadId) || event.data.loadId <= 0) return;
|
|
146
196
|
loadId = event.data.loadId;
|
|
147
|
-
report();
|
|
197
|
+
report('sync');
|
|
148
198
|
} else if (event.data.type === 'dsh.browser.guest.reference.request') {
|
|
149
199
|
const data = event.data;
|
|
150
200
|
if (event.origin !== location.origin || data.loadId !== loadId || loadId === undefined || data.documentId !== documentId
|
|
@@ -172,11 +222,12 @@ export function guestRuntimeScript(pageUrl: string, storage?: GuestStorageConfig
|
|
|
172
222
|
else if (event.data.delta === 1) history.forward();
|
|
173
223
|
}
|
|
174
224
|
}));
|
|
175
|
-
attempt(() => window.addEventListener('DOMContentLoaded', report));
|
|
225
|
+
attempt(() => window.addEventListener('DOMContentLoaded', () => report('ready')));
|
|
226
|
+
attempt(() => window.addEventListener('pageshow', event => { if (event && event.persisted) report('pageshow'); }));
|
|
176
227
|
attempt(() => window.addEventListener('popstate', () => {
|
|
177
228
|
const next = attempt(() => realURL(location.href));
|
|
178
229
|
if (next) real = next.href;
|
|
179
|
-
report();
|
|
230
|
+
report('pop');
|
|
180
231
|
}));
|
|
181
232
|
attempt(() => {
|
|
182
233
|
const proxyResource = value => {
|
|
@@ -16,8 +16,11 @@ export class GuestStorage {
|
|
|
16
16
|
private readonly secret = randomBytes(32)
|
|
17
17
|
private local: Partitions = new Map()
|
|
18
18
|
private session: Partitions = new Map()
|
|
19
|
-
|
|
20
|
-
|
|
19
|
+
private readonly directory?: string
|
|
20
|
+
private readonly quota = 5 * 1024 * 1024
|
|
21
|
+
constructor(directory?: string, quota = 5 * 1024 * 1024) {
|
|
22
|
+
this.directory = directory
|
|
23
|
+
this.quota = quota
|
|
21
24
|
if (directory === undefined) return
|
|
22
25
|
let fd: number | undefined
|
|
23
26
|
try {
|