dsh-builtin-browser 1.0.3 → 1.1.0
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 +16 -1
- package/README.en.md +89 -0
- package/browser-extension/constants.mjs +20 -0
- package/browser-extension/controller.mjs +293 -0
- package/browser-extension/locales.mjs +15 -0
- package/browser-extension/manifest.json +12 -0
- package/browser-extension/options.html +14 -0
- package/browser-extension/options.mjs +9 -0
- package/browser-extension/permission-guard.mjs +13 -0
- package/browser-extension/worker.mjs +74 -0
- package/desktop-bridge/desktop-identity.json +10 -2
- package/desktop-bridge/install.mjs +28 -2
- package/docs/issue-replies-2026-11-28.md +141 -0
- package/dsh-host-patch/apply.mjs +1 -1
- package/dsh-host-patch/rc3.json +4 -4
- package/dsh-host-patch/rc5.json +4 -4
- package/dsh-host-patch/v023-alpha2.json +2 -2
- package/lib/browser-electron/bridge-status.js +24 -1
- package/lib/browser-electron/desktop-identity.js +47 -8
- package/lib/client.js +2 -1
- package/native-host/install.mjs +5 -0
- package/package.json +20 -2
- package/scripts/build-client.mjs +305 -0
- package/scripts/build.mjs +69 -0
- package/scripts/bundle-host.mjs +28 -0
- package/scripts/fix-exports.mjs +40 -0
- package/scripts/install-electron.mjs +101 -0
- package/scripts/pack.mjs +99 -0
- package/scripts/publish-manifest.mjs +56 -0
- package/scripts/verify-exports.mjs +58 -0
- package/scripts/verify-preview-sdk.mjs +93 -0
- package/skills/dsh-builtin-browser/SKILL.md +98 -0
- package/skills/dsh-builtin-browser/references/batch.md +68 -0
- package/skills/dsh-builtin-browser/references/deliver.md +31 -0
- package/skills/dsh-builtin-browser/references/locate.md +11 -0
- package/skills/dsh-builtin-browser/references/recover.md +11 -0
- package/skills/dsh-builtin-browser/references/verify.md +13 -0
- package/skills/dsh-debug-host/SKILL.md +56 -0
- package/skills/dsh-debug-self/SKILL.md +50 -0
- package/src/bridge-compatibility.ts +39 -0
- package/src/browser/anti-bot.ts +251 -0
- package/src/browser/deep-dom.ts +40 -0
- package/src/browser/handles.ts +89 -0
- package/src/browser/runtime.ts +578 -0
- package/src/browser/takeover-target.ts +45 -0
- package/src/browser/types.ts +870 -0
- package/src/browser-electron/authenticated-route.ts +109 -0
- package/src/browser-electron/automatic-maintenance.ts +736 -0
- package/src/browser-electron/bridge-auto.ts +159 -0
- package/src/browser-electron/bridge-connection.ts +386 -0
- package/src/browser-electron/bridge-endpoint.ts +129 -0
- package/src/browser-electron/bridge-install.ts +290 -0
- package/src/browser-electron/bridge-maintenance.ts +189 -0
- package/src/browser-electron/bridge-status.ts +412 -0
- package/src/browser-electron/desktop-bridge-host.ts +253 -0
- package/src/browser-electron/desktop-identity.ts +400 -0
- package/src/browser-electron/desktop-shell.ts +100 -0
- package/src/browser-electron/document-readiness.ts +45 -0
- package/src/browser-electron/electron-provision.ts +347 -0
- package/src/browser-electron/entry.ts +1378 -0
- package/src/browser-electron/ephemeral-profile.ts +189 -0
- package/src/browser-electron/extension-browser.ts +230 -0
- package/src/browser-electron/extension-setup.ts +67 -0
- package/src/browser-electron/file-write.ts +31 -0
- package/src/browser-electron/foreground-watch.ts +142 -0
- package/src/browser-electron/guest-cookie-jar.ts +177 -0
- package/src/browser-electron/guest-cookie-store.ts +59 -0
- package/src/browser-electron/guest-css-runtime.ts +76 -0
- package/src/browser-electron/guest-css.ts +68 -0
- package/src/browser-electron/guest-route.ts +716 -0
- package/src/browser-electron/guest-runtime.ts +408 -0
- package/src/browser-electron/guest-storage-runtime.ts +54 -0
- package/src/browser-electron/guest-storage.ts +120 -0
- package/src/browser-electron/history-store.ts +224 -0
- package/src/browser-electron/host-main.ts +1385 -0
- package/src/browser-electron/host-patch-maintenance.ts +121 -0
- package/src/browser-electron/http-body.ts +65 -0
- package/src/browser-electron/json-reply.ts +47 -0
- package/src/browser-electron/maintenance-broker.ts +166 -0
- package/src/browser-electron/maintenance-lifecycle.ts +91 -0
- package/src/browser-electron/maintenance-route.ts +68 -0
- package/src/browser-electron/missing-system-browser.ts +114 -0
- package/src/browser-electron/open-slot.ts +49 -0
- package/src/browser-electron/paths.ts +25 -0
- package/src/browser-electron/preferred-browser.ts +130 -0
- package/src/browser-electron/preview-route.ts +215 -0
- package/src/browser-electron/process-ownership.ts +174 -0
- package/src/browser-electron/process.ts +23 -0
- package/src/browser-electron/profile-checkpoint.ts +187 -0
- package/src/browser-electron/profile-command.ts +47 -0
- package/src/browser-electron/profile-extension.ts +129 -0
- package/src/browser-electron/profile-lease.ts +211 -0
- package/src/browser-electron/profile-residue.ts +49 -0
- 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 +666 -0
- package/src/browser-electron/reference-route.ts +598 -0
- package/src/browser-electron/remote-host.ts +1538 -0
- package/src/browser-electron/rpc-input.ts +13 -0
- package/src/browser-electron/rpc-ops.ts +41 -0
- package/src/browser-electron/runtime-diagnostics.ts +38 -0
- package/src/browser-electron/runtime-route.ts +105 -0
- package/src/browser-electron/runtime-status.ts +309 -0
- package/src/browser-electron/settings-route.ts +64 -0
- package/src/browser-electron/settings-store.ts +593 -0
- package/src/browser-electron/shortcuts-route.ts +112 -0
- package/src/browser-electron/sidebar-only-host.ts +300 -0
- package/src/browser-electron/startpage-shortcuts.ts +213 -0
- package/src/browser-electron/system-browser.ts +1850 -0
- package/src/browser-electron/tauri-host.ts +194 -0
- package/src/browser-electron/timing.ts +16 -0
- package/src/browser-electron/virtual-cursor.ts +162 -0
- package/src/browser-electron/windows-system.ts +24 -0
- package/src/browser-reference/delivery.ts +384 -0
- package/src/browser-reference/entry.ts +631 -0
- package/src/browser-reference/export.ts +339 -0
- package/src/browser-reference/import.ts +303 -0
- package/src/browser-reference/page-script.ts +1537 -0
- package/src/browser-reference/service.ts +1346 -0
- package/src/browser-reference/store.ts +172 -0
- package/src/browser-reference/text-quote.ts +219 -0
- package/src/browser-reference/types.ts +195 -0
- package/src/browser-reference/visible.ts +367 -0
- package/src/browser-reference/web-sources.ts +106 -0
- package/src/client/apply-guard.ts +22 -0
- package/src/client/browser/BrowserController.ts +693 -0
- package/src/client/browser/BrowserFrame.ts +78 -0
- package/src/client/browser/BrowserNavigation.ts +169 -0
- package/src/client/browser/BrowserPage.ts +23 -0
- package/src/client/browser/BrowserPersistence.ts +44 -0
- package/src/client/browser/IframeImpl.ts +182 -0
- package/src/client/browser/child-tabs.ts +14 -0
- package/src/client/browser/frame-history.ts +125 -0
- package/src/client/browser/frame-state.ts +27 -0
- package/src/client/browser/iframe-reference.ts +67 -0
- package/src/client/browser/initialization.ts +262 -0
- package/src/client/browser/omnibox.ts +243 -0
- package/src/client/browser/store.ts +38 -0
- package/src/client/browser/takeover-channel.ts +72 -0
- package/src/client/browser/url.ts +46 -0
- package/src/client/browser/web-reference-source.ts +56 -0
- package/src/client/css-modules.d.ts +4 -0
- package/src/client/definition.tsx +36 -0
- package/src/client/electron/ElectronWebViewImpl.ts +371 -0
- package/src/client/electron/ElectronWebviewPresentation.ts +140 -0
- package/src/client/electron/NativeChildPresentation.ts +53 -0
- package/src/client/electron/NativeViewPage.ts +265 -0
- package/src/client/electron/pages.ts +23 -0
- package/src/client/electron/reference-overlay.ts +53 -0
- package/src/client/electron/workspace.ts +33 -0
- package/src/client/index.ts +333 -0
- package/src/client/locales.ts +860 -0
- package/src/client/pages.ts +28 -0
- package/src/client/reference/client/BrowserRefLink.tsx +142 -0
- package/src/client/reference/client/draft-reference.ts +167 -0
- package/src/client/reference/client/index.ts +7 -0
- package/src/client/reference/client/ordered-submission.ts +108 -0
- package/src/client/reference/client/pending-delivery.ts +216 -0
- package/src/client/reference/client/plugin.ts +208 -0
- package/src/client/reference/client/production/ReferenceCapsules.tsx +345 -0
- package/src/client/reference/client/production/ReferenceDock.module.css +193 -0
- package/src/client/reference/client/production/ReferenceDock.tsx +6 -0
- package/src/client/reference/client/production/ReferenceFeedback.tsx +15 -0
- package/src/client/reference/client/production/ReferenceMath.tsx +44 -0
- package/src/client/reference/client/production/ReferenceText.tsx +36 -0
- package/src/client/reference/client/production/assembly.ts +447 -0
- package/src/client/reference/client/production/asset-store.ts +144 -0
- package/src/client/reference/client/production/availability.ts +72 -0
- package/src/client/reference/client/production/bytes.ts +36 -0
- package/src/client/reference/client/production/composer-attachments.ts +44 -0
- package/src/client/reference/client/production/delivery-client.ts +211 -0
- package/src/client/reference/client/production/draft-adapter.ts +512 -0
- package/src/client/reference/client/production/http-transport.ts +212 -0
- package/src/client/reference/client/production/production-submission.ts +70 -0
- package/src/client/reference/client/production/protocol.ts +234 -0
- package/src/client/reference/client/production/reference-card.ts +240 -0
- package/src/client/reference/client/production/reference-labels.ts +29 -0
- package/src/client/reference/client/production/reply-link-bridge.ts +222 -0
- package/src/client/reference/client/production/reveal.ts +215 -0
- package/src/client/reference/client/production/runtime.ts +1056 -0
- package/src/client/reference/client/production/snapshot-adapter.ts +154 -0
- package/src/client/reference/client/production/source-marker.ts +99 -0
- package/src/client/reference/client/production/source-opener.ts +55 -0
- package/src/client/reference/client/production/styles.ts +104 -0
- package/src/client/reference/client/production/user-text-rule.ts +67 -0
- package/src/client/reference/client/reveal.ts +109 -0
- package/src/client/reference/client/scheme.ts +114 -0
- package/src/client/reference/client/session-schedule.ts +36 -0
- package/src/client/reference/client/types.ts +168 -0
- package/src/client/reference/css-modules.d.ts +4 -0
- package/src/client/reference/index.ts +11 -0
- package/src/client/reference-capture-owner.ts +162 -0
- package/src/client/reference-intents.ts +36 -0
- package/src/client/settings/index.ts +42 -0
- package/src/client/settings/mount-guard.ts +31 -0
- package/src/client/settings/panel.ts +2773 -0
- package/src/client/shortcut-open.ts +30 -0
- package/src/client/startpage/binding.ts +99 -0
- package/src/client/startpage/controller.ts +300 -0
- package/src/client/startpage/model.ts +279 -0
- package/src/client/view/Browser.module.css +751 -0
- package/src/client/view/BrowserBody.tsx +315 -0
- package/src/client/view/BrowserPresentation.ts +9 -0
- package/src/client/view/BrowserTitle.tsx +17 -0
- package/src/client/view/IframePresentation.ts +365 -0
- package/src/client/view/StartPage.tsx +598 -0
- package/src/client/view/TakeoverBanner.tsx +21 -0
- package/src/compat/host-features.ts +92 -0
- package/src/index.ts +110 -0
- package/src/reference-owner.ts +5 -0
- package/src/reference-page.ts +9 -0
- package/src/reference-source.ts +3 -0
- package/src/reference-text.ts +219 -0
- package/src/startpage-settings.ts +103 -0
- package/src/startpage.ts +71 -0
- package/src/takeover-protocol.ts +28 -0
- package/src/tool-browser/block-recovery.ts +85 -0
- package/src/tool-browser/code-tool.ts +555 -0
- package/src/tool-browser/code-worker.ts +725 -0
- package/src/tool-browser/element-fields.ts +167 -0
- package/src/tool-browser/errors.ts +40 -0
- package/src/tool-browser/index.ts +265 -0
- package/src/tool-browser/page-probe.ts +675 -0
- package/src/tool-browser/panel-page.ts +126 -0
- package/src/tool-browser/probe-client.ts +183 -0
- package/src/tool-browser/screenshot-annotations.ts +131 -0
- package/src/tool-browser/screenshot-image.ts +49 -0
- package/src/tool-browser/state.ts +375 -0
- package/src/tool-browser/takeover.ts +199 -0
- 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/types/electron-shim.d.ts +144 -0
- package/src/types.ts +85 -0
- package/src/web-guest.ts +35 -0
- package/tools/accept-desktop.mjs +148 -0
- 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/dsh-builtin-browser-1.0.3-publish.tgz +0 -0
- package/dsh-builtin-browser-1.0.3.tgz +0 -0
- package/dsh-host-patch/sources/main/0001-feat-sidebar-right-add-session-rendering-holds.patch.gz +0 -0
- package/dsh-host-patch/sources/main/0002-feat-desktop-load-trusted-profile-main-extensions.patch.gz +0 -0
- package/dsh-host-patch/sources/main/0003-feat-desktop-report-resolved-and-running-main-extens.patch.gz +0 -0
- package/dsh-host-patch/sources/main/0004-feat-desktop-compose-admitted-native-sidebar-views.patch.gz +0 -0
- package/dsh-host-patch/sources/main/0005-fix-client-admit-coded-browser-errors-in-native-comp.patch.gz +0 -0
- package/dsh-host-patch/sources/main/0006-fix-desktop-acknowledge-native-same-document-navigat.patch.gz +0 -0
- package/dsh-host-patch/sources/main/0007-fix-desktop-restore-auth-in-the-native-lease-partiti.patch.gz +0 -0
- package/dsh-host-patch/sources/main/0008-feat-desktop-adopt-native-children-in-admitted-sideb.patch.gz +0 -0
- package/dsh-host-patch/sources/main/0009-fix-desktop-publish-complete-native-child-close-reco.patch.gz +0 -0
- package/dsh-host-patch/sources/main/0010-fix-desktop-bundle-structured-errors-in-sandboxed-pr.patch.gz +0 -0
- package/dsh-host-patch/sources/main/0011-feat-desktop-offer-persistent-Sidebar-sessions-per-D.patch.gz +0 -0
- package/dsh-host-patch/sources/main/0012-feat-desktop-retain-sidebar-session-cookies-across-r.patch.gz +0 -0
- package/dsh-host-patch/sources/main/0013-fix-desktop-honor-sidebar-session-cookie-sidecar-con.patch.gz +0 -0
- package/dsh-host-patch/sources/main/0014-fix-desktop-retry-cookie-protection-without-failing-.patch.gz +0 -0
- package/dsh-host-patch/sources/main/0015-fix-desktop-preserve-host-only-cookie-identity-in-se.patch.gz +0 -0
- package/dsh-host-patch/sources/main/0016-fix-desktop-restore-session-cookies-before-checkpoin.patch.gz +0 -0
- package/dsh-host-patch/sources/main/0017-fix-desktop-restore-sidebar-cookies-once-before-gues.patch.gz +0 -0
- package/dsh-host-patch/sources/main/0018-fix-sidebar-right-follow-animated-native-slot-placem.patch.gz +0 -0
- package/dsh-host-patch/sources/manifest.json +0 -218
- package/dsh-host-patch/sources/rc3/0001-feat-sidebar-right-add-session-rendering-holds.patch.gz +0 -0
- package/dsh-host-patch/sources/rc3/0002-feat-desktop-load-trusted-profile-main-extensions.patch.gz +0 -0
- package/dsh-host-patch/sources/rc3/0003-feat-desktop-report-resolved-and-running-main-extens.patch.gz +0 -0
- package/dsh-host-patch/sources/rc3/0004-feat-desktop-compose-admitted-native-sidebar-views.patch.gz +0 -0
- package/dsh-host-patch/sources/rc3/0005-fix-client-admit-coded-browser-errors-in-native-comp.patch.gz +0 -0
- package/dsh-host-patch/sources/rc3/0006-fix-desktop-acknowledge-native-same-document-navigat.patch.gz +0 -0
- package/dsh-host-patch/sources/rc3/0007-fix-desktop-restore-auth-in-the-native-lease-partiti.patch.gz +0 -0
- package/dsh-host-patch/sources/rc3/0008-feat-desktop-adopt-native-children-in-admitted-sideb.patch.gz +0 -0
- package/dsh-host-patch/sources/rc3/0009-fix-desktop-publish-complete-native-child-close-reco.patch.gz +0 -0
- package/dsh-host-patch/sources/rc3/0010-fix-desktop-bundle-structured-errors-in-sandboxed-pr.patch.gz +0 -0
- package/dsh-host-patch/sources/rc3/0011-feat-desktop-offer-persistent-Sidebar-sessions-per-D.patch.gz +0 -0
- package/dsh-host-patch/sources/rc3/0012-feat-desktop-retain-sidebar-session-cookies-across-r.patch.gz +0 -0
- package/dsh-host-patch/sources/rc3/0013-fix-desktop-honor-sidebar-session-cookie-sidecar-con.patch.gz +0 -0
- package/dsh-host-patch/sources/rc3/0014-fix-desktop-retry-cookie-protection-without-failing-.patch.gz +0 -0
- package/dsh-host-patch/sources/rc3/0015-fix-desktop-preserve-host-only-cookie-identity-in-se.patch.gz +0 -0
- package/dsh-host-patch/sources/rc3/0016-fix-desktop-restore-session-cookies-before-checkpoin.patch.gz +0 -0
- package/dsh-host-patch/sources/rc3/0017-fix-desktop-restore-sidebar-cookies-once-before-gues.patch.gz +0 -0
- package/dsh-host-patch/sources/rc3/0018-fix-sidebar-right-follow-animated-native-slot-placem.patch.gz +0 -0
- package/dsh-host-patch/sources/rc5/0001-feat-sidebar-right-add-session-rendering-holds.patch.gz +0 -0
- package/dsh-host-patch/sources/rc5/0002-feat-desktop-load-trusted-profile-main-extensions.patch.gz +0 -0
- package/dsh-host-patch/sources/rc5/0003-feat-desktop-report-resolved-and-running-main-extens.patch.gz +0 -0
- package/dsh-host-patch/sources/rc5/0004-feat-desktop-compose-admitted-native-sidebar-views.patch.gz +0 -0
- package/dsh-host-patch/sources/rc5/0005-fix-client-admit-coded-browser-errors-in-native-comp.patch.gz +0 -0
- package/dsh-host-patch/sources/rc5/0006-fix-desktop-acknowledge-native-same-document-navigat.patch.gz +0 -0
- package/dsh-host-patch/sources/rc5/0007-fix-desktop-restore-auth-in-the-native-lease-partiti.patch.gz +0 -0
- package/dsh-host-patch/sources/rc5/0008-feat-desktop-adopt-native-children-in-admitted-sideb.patch.gz +0 -0
- package/dsh-host-patch/sources/rc5/0009-fix-desktop-publish-complete-native-child-close-reco.patch.gz +0 -0
- package/dsh-host-patch/sources/rc5/0010-fix-desktop-bundle-structured-errors-in-sandboxed-pr.patch.gz +0 -0
- package/dsh-host-patch/sources/rc5/0011-feat-desktop-offer-persistent-Sidebar-sessions-per-D.patch.gz +0 -0
- package/dsh-host-patch/sources/rc5/0012-feat-desktop-retain-sidebar-session-cookies-across-r.patch.gz +0 -0
- package/dsh-host-patch/sources/rc5/0013-fix-desktop-honor-sidebar-session-cookie-sidecar-con.patch.gz +0 -0
- package/dsh-host-patch/sources/rc5/0014-fix-desktop-retry-cookie-protection-without-failing-.patch.gz +0 -0
- package/dsh-host-patch/sources/rc5/0015-fix-desktop-preserve-host-only-cookie-identity-in-se.patch.gz +0 -0
- package/dsh-host-patch/sources/rc5/0016-fix-desktop-restore-session-cookies-before-checkpoin.patch.gz +0 -0
- package/dsh-host-patch/sources/rc5/0017-fix-desktop-restore-sidebar-cookies-once-before-gues.patch.gz +0 -0
- package/dsh-host-patch/sources/rc5/0018-fix-sidebar-right-follow-animated-native-slot-placem.patch.gz +0 -0
- package/dsh-host-patch/sources/series.json +0 -260
|
@@ -0,0 +1,716 @@
|
|
|
1
|
+
import { hostMessages } from '../../assets/browser-messages.mjs'
|
|
2
|
+
import { GUEST_ROUTE, RELAXED_BROWSER_SANDBOX, WEB_BROWSER_SANDBOX } from '../../assets/browser-policy.mjs'
|
|
3
|
+
/**
|
|
4
|
+
* Web guests execute in CSP-sandboxed opaque origins, including direct document loads.
|
|
5
|
+
* Only this proxy prefix is available to guest network requests. App storage, APIs,
|
|
6
|
+
* cookies and authenticated reference submission remain in the owning app frame.
|
|
7
|
+
* @module dsh-builtin-browser/browser-electron/guest-route
|
|
8
|
+
*/
|
|
9
|
+
import type { IncomingMessage, OutgoingHttpHeaders, ServerResponse } from 'node:http'
|
|
10
|
+
import { promises as dns, type LookupAddress } from 'node:dns'
|
|
11
|
+
import { Agent, fetch as undiciFetch } from 'undici'
|
|
12
|
+
import { networkInterfaces } from 'node:os'
|
|
13
|
+
import { randomUUID } from 'node:crypto'
|
|
14
|
+
import { guestRuntimeScript } from './guest-runtime.ts'
|
|
15
|
+
import { blockRetryDelayMs, classifyBlock } from '../browser/anti-bot.ts'
|
|
16
|
+
import type { GuestCookieJar } from './guest-cookie-jar.ts'
|
|
17
|
+
import { localGuestCookies } from './guest-cookie-store.ts'
|
|
18
|
+
import { rewriteCss } from './guest-css.ts'
|
|
19
|
+
import { GuestStorage, localGuestStorage } from './guest-storage.ts'
|
|
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
|
+
|
|
24
|
+
/** Prefix every proxied document and subresource lives under. */
|
|
25
|
+
|
|
26
|
+
/**
|
|
27
|
+
* Whether a proxied target is this machine (or this host) itself.
|
|
28
|
+
*
|
|
29
|
+
* The sidebar must never proxy DSH into itself: the guest would fetch the very server that is serving it,
|
|
30
|
+
* and the connection came back as "guest proxy: cannot reach 127.0.0.1:3102: fetch failed" — a message that
|
|
31
|
+
* reads like a network fault instead of "this is not allowed". Debugging DSH deliberately uses the
|
|
32
|
+
* built-in browser instead (see the sidebar skill card).
|
|
33
|
+
* @param url - the requested target.
|
|
34
|
+
* @returns true for loopback, link-local and private hosts.
|
|
35
|
+
*/
|
|
36
|
+
function isSelfTarget(url: URL): boolean {
|
|
37
|
+
const host = url.hostname.toLowerCase().replace(/\.$/u, '')
|
|
38
|
+
if (host.endsWith('.localhost') || host === '[::]' || host.startsWith('[::ffff:')
|
|
39
|
+
|| /^\[(?:f[cd]|fe[89ab])/u.test(host) || /^169\.254\./u.test(host)) return true
|
|
40
|
+
if (host === 'localhost' || host === '127.0.0.1' || host === '[::1]' || host === '::1' || host === '0.0.0.0') return true
|
|
41
|
+
if (/^(?:0|127)\./u.test(host)) return true
|
|
42
|
+
if (/^100\.(?:6[4-9]|[7-9]\d|1[01]\d|12[0-7])\./u.test(host)) return true
|
|
43
|
+
if (/^10\./u.test(host) || /^192\.168\./u.test(host)) return true
|
|
44
|
+
if (/^172\.(1[6-9]|2\d|3[01])\./u.test(host)) return true
|
|
45
|
+
return false
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
export { GUEST_ROUTE }
|
|
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
|
+
|
|
114
|
+
class UnsafeGuestTargetError extends Error {}
|
|
115
|
+
|
|
116
|
+
/** HTML responses larger than this pass through without rewriting. */
|
|
117
|
+
const MAX_REWRITE_BYTES = 4 * 1024 * 1024
|
|
118
|
+
const MAX_REQUEST_BODY_BYTES = 10 * 1024 * 1024
|
|
119
|
+
|
|
120
|
+
const UPSTREAM_ERROR_CODES = new Set([
|
|
121
|
+
'ENOTFOUND', 'EAI_AGAIN', 'ECONNREFUSED', 'ECONNRESET', 'ETIMEDOUT',
|
|
122
|
+
'UND_ERR_CONNECT_TIMEOUT', 'UND_ERR_HEADERS_TIMEOUT', 'UND_ERR_BODY_TIMEOUT', 'UND_ERR_SOCKET',
|
|
123
|
+
'UNABLE_TO_VERIFY_LEAF_SIGNATURE', 'UNABLE_TO_GET_ISSUER_CERT_LOCALLY', 'DEPTH_ZERO_SELF_SIGNED_CERT',
|
|
124
|
+
'SELF_SIGNED_CERT_IN_CHAIN', 'CERT_HAS_EXPIRED', 'ERR_TLS_CERT_ALTNAME_INVALID',
|
|
125
|
+
'ERR_SSL_TLSV1_ALERT_NO_APPLICATION_PROTOCOL',
|
|
126
|
+
])
|
|
127
|
+
|
|
128
|
+
function upstreamErrorCode(error: unknown): string | undefined {
|
|
129
|
+
const cause = error !== null && typeof error === 'object' && 'cause' in error ? error.cause : undefined
|
|
130
|
+
for (const value of [error, cause]) {
|
|
131
|
+
if (value !== null && typeof value === 'object' && 'code' in value
|
|
132
|
+
&& typeof value.code === 'string' && UPSTREAM_ERROR_CODES.has(value.code)) return value.code
|
|
133
|
+
}
|
|
134
|
+
return undefined
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
/** Decode CSS bytes honoring BOM, Content-Type charset, and @charset; unknown encodings pass through untouched. */
|
|
138
|
+
function decodeCssBytes(bytes: Buffer, contentType: string): string | undefined {
|
|
139
|
+
let label: string | undefined
|
|
140
|
+
if (bytes.length >= 3 && bytes[0] === 0xef && bytes[1] === 0xbb && bytes[2] === 0xbf) label = 'utf-8'
|
|
141
|
+
else if (bytes.length >= 2 && bytes[0] === 0xff && bytes[1] === 0xfe) label = 'utf-16le'
|
|
142
|
+
else if (bytes.length >= 2 && bytes[0] === 0xfe && bytes[1] === 0xff) label = 'utf-16be'
|
|
143
|
+
else {
|
|
144
|
+
const headerMatch = /;\s*charset\s*=\s*(?:"([^"]+)"|'([^']+)'|([^\s;]+))/iu.exec(contentType)
|
|
145
|
+
label = headerMatch?.[1] ?? headerMatch?.[2] ?? headerMatch?.[3]
|
|
146
|
+
if (label === undefined) {
|
|
147
|
+
const head = bytes.subarray(0, 1024).toString('latin1')
|
|
148
|
+
label = /^@charset\s+"([^"]+)";/u.exec(head)?.[1] ?? 'utf-8'
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
try { return new TextDecoder(label).decode(bytes).replace(/^@charset\s+"[^"]+";\s*/iu, '') }
|
|
152
|
+
catch { return undefined }
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
/** Document content types eligible for rewriting. */
|
|
156
|
+
const REWRITABLE = /^(text\/|application\/(json|javascript|xhtml\+xml|xml|rss\+xml|atom\+xml))/iu
|
|
157
|
+
|
|
158
|
+
/** A desktop Chrome identity; several sites refuse a request without one. */
|
|
159
|
+
const DESKTOP_UA = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36'
|
|
160
|
+
|
|
161
|
+
/** Only site request metadata may leave the app; never forward DSH cookies or internal headers. */
|
|
162
|
+
const SAFE_REQUEST_HEADERS = new Set([
|
|
163
|
+
'accept', 'accept-language', 'content-type', 'content-language', 'x-requested-with',
|
|
164
|
+
'x-csrf-token', 'x-xsrf-token', 'range', 'if-range',
|
|
165
|
+
'if-none-match', 'if-modified-since', 'cache-control',
|
|
166
|
+
])
|
|
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
|
+
|
|
184
|
+
function siteHeader(name: string): boolean {
|
|
185
|
+
return /^[!#$%&'*+.^_`|~\da-z-]+$/u.test(name)
|
|
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)
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
/** Response headers that would break a same-origin document. */
|
|
190
|
+
const DROP_RESPONSE_HEADERS = new Set([
|
|
191
|
+
'content-security-policy', 'content-security-policy-report-only', 'x-frame-options',
|
|
192
|
+
'content-encoding', 'content-length', 'transfer-encoding', 'connection', 'keep-alive',
|
|
193
|
+
'alt-svc', 'alternate-protocol', 'upgrade', 'http2-settings', 'trailer', 'te',
|
|
194
|
+
'strict-transport-security', 'cross-origin-opener-policy', 'cross-origin-embedder-policy',
|
|
195
|
+
'cross-origin-resource-policy', 'permissions-policy', 'set-cookie', 'refresh',
|
|
196
|
+
])
|
|
197
|
+
|
|
198
|
+
/**
|
|
199
|
+
* Encode a target URL for the proxy prefix.
|
|
200
|
+
* @param target - absolute http(s) URL.
|
|
201
|
+
* @returns the path the iframe navigates to.
|
|
202
|
+
*/
|
|
203
|
+
export function guestPath(target: string): string {
|
|
204
|
+
// The host's route registry only registers EXACT paths, so the target rides in a query parameter
|
|
205
|
+
// instead of the path. Every rewritten reference keeps the same shape.
|
|
206
|
+
return `${GUEST_ROUTE}?u=${encodeURIComponent(target)}`
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
/**
|
|
210
|
+
* Decode a request path back to a target URL.
|
|
211
|
+
* @param rawUrl - the incoming request URL (path + query).
|
|
212
|
+
* @returns the absolute target, or undefined when the request is not a canonical proxied URL.
|
|
213
|
+
*/
|
|
214
|
+
export function guestTarget(rawUrl: string): URL | undefined {
|
|
215
|
+
const index = rawUrl.indexOf('?')
|
|
216
|
+
if (index === -1) return undefined
|
|
217
|
+
const path = rawUrl.slice(0, index)
|
|
218
|
+
if (path !== GUEST_ROUTE) return undefined
|
|
219
|
+
let decoded: string
|
|
220
|
+
try {
|
|
221
|
+
decoded = new URLSearchParams(rawUrl.slice(index + 1)).get('u') ?? ''
|
|
222
|
+
} catch {
|
|
223
|
+
return undefined
|
|
224
|
+
}
|
|
225
|
+
if (decoded === '') return undefined
|
|
226
|
+
try {
|
|
227
|
+
const url = new URL(decoded)
|
|
228
|
+
if (url.protocol !== 'http:' && url.protocol !== 'https:') return undefined
|
|
229
|
+
return url
|
|
230
|
+
} catch {
|
|
231
|
+
return undefined
|
|
232
|
+
}
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
function decodeAttribute(value: string): string {
|
|
236
|
+
const named: Record<string, string> = { amp: '&', quot: '"', apos: "'", lt: '<', gt: '>' }
|
|
237
|
+
return value.replace(/&(?:#(x[\da-f]+|\d+);?|(amp|quot|apos|lt|gt);)/giu, (match, numeric?: string, name?: string) => {
|
|
238
|
+
if (numeric === undefined) return named[name?.toLowerCase() ?? ''] ?? match
|
|
239
|
+
const point = /^x/iu.test(numeric) ? Number.parseInt(numeric.slice(1), 16) : Number(numeric)
|
|
240
|
+
return point === 0 || point > 0x10ffff || (point >= 0xd800 && point <= 0xdfff) ? '\ufffd' : String.fromCodePoint(point)
|
|
241
|
+
})
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
function escapeAttribute(value: string, quote: string): string {
|
|
245
|
+
return value.replace(/[&<>"'`=\s]/gu, char => {
|
|
246
|
+
if (char === '&') return '&'
|
|
247
|
+
if (char === '<') return '<'
|
|
248
|
+
if (char === '>') return '>'
|
|
249
|
+
return quote === '' || char === quote ? `&#${char.codePointAt(0)};` : char
|
|
250
|
+
})
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
function proxyReference(raw: string, base: URL): string | undefined {
|
|
254
|
+
const trimmed = raw.trim()
|
|
255
|
+
if (trimmed === '' || trimmed.startsWith('#')) return undefined
|
|
256
|
+
try {
|
|
257
|
+
const absolute = new URL(trimmed, base)
|
|
258
|
+
if (absolute.protocol !== 'http:' && absolute.protocol !== 'https:') return undefined
|
|
259
|
+
return guestPath(absolute.href)
|
|
260
|
+
} catch {
|
|
261
|
+
return undefined
|
|
262
|
+
}
|
|
263
|
+
}
|
|
264
|
+
|
|
265
|
+
function stripDocumentPolicies(html: string): string {
|
|
266
|
+
return html.replace(
|
|
267
|
+
/<!--[\s\S]*?-->|<(script|style|textarea|title)\b(?:[^>"']|"[^"]*"|'[^']*')*>[\s\S]*?<\/\1\s*>|<meta\b(?:[^>"']|"[^"]*"|'[^']*')*>/giu,
|
|
268
|
+
tag => {
|
|
269
|
+
if (!/^<meta\s/iu.test(tag)) return tag
|
|
270
|
+
for (const attribute of tag.matchAll(/\s+([^\s"'<>/=]+)(?:\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s"'=<>`]+)))?/gu)) {
|
|
271
|
+
if (attribute[1]?.toLowerCase() !== 'http-equiv') continue
|
|
272
|
+
const policy = decodeAttribute(attribute[2] ?? attribute[3] ?? attribute[4] ?? '').trim().toLowerCase()
|
|
273
|
+
return policy === 'content-security-policy' || policy === 'content-security-policy-report-only' ? '' : tag
|
|
274
|
+
}
|
|
275
|
+
return tag
|
|
276
|
+
},
|
|
277
|
+
)
|
|
278
|
+
}
|
|
279
|
+
|
|
280
|
+
/**
|
|
281
|
+
* Rewrite one document so its own links and assets stay inside the proxy.
|
|
282
|
+
* @param html - the fetched document.
|
|
283
|
+
* @param base - the original document URL used for relative references.
|
|
284
|
+
* @returns the rewritten document.
|
|
285
|
+
*/
|
|
286
|
+
export function rewriteDocument(html: string, base: URL): string {
|
|
287
|
+
const proxied = (raw: string): string | undefined => proxyReference(raw, base)
|
|
288
|
+
const attributes = (tag: string): string => {
|
|
289
|
+
const isLink = /^<link\b/iu.test(tag)
|
|
290
|
+
return tag.replace(
|
|
291
|
+
/(\s+)([^\s"'<>/=]+)(\s*=\s*)(?:"([^"]*)"|'([^']*)'|([^\s"'<>`]+))/gu,
|
|
292
|
+
(match, space: string, name: string, equals: string, doubleQuoted?: string, singleQuoted?: string, bare?: string) => {
|
|
293
|
+
const value = decodeAttribute(doubleQuoted ?? singleQuoted ?? bare ?? '')
|
|
294
|
+
const attribute = name.toLowerCase()
|
|
295
|
+
if (isLink && attribute === 'integrity') return ''
|
|
296
|
+
let next: string | undefined
|
|
297
|
+
if (['href', 'src', 'poster', 'data-src', 'action'].includes(attribute)) next = proxied(value)
|
|
298
|
+
else if (attribute === 'srcset') {
|
|
299
|
+
next = value.split(',').map(part => {
|
|
300
|
+
const [url, descriptor] = part.trim().split(/\s+/u)
|
|
301
|
+
const rewritten = url === undefined ? undefined : proxied(url)
|
|
302
|
+
if (rewritten === undefined) return part.trim()
|
|
303
|
+
return descriptor === undefined ? rewritten : `${rewritten} ${descriptor}`
|
|
304
|
+
}).join(', ')
|
|
305
|
+
} else if (attribute === 'style') next = rewriteCss(value, proxied)
|
|
306
|
+
if (next === undefined) return match
|
|
307
|
+
const quote = singleQuoted === undefined ? '"' : "'"
|
|
308
|
+
return space + name + equals + quote + escapeAttribute(next, quote) + quote
|
|
309
|
+
},
|
|
310
|
+
)
|
|
311
|
+
}
|
|
312
|
+
return stripDocumentPolicies(html).replace(
|
|
313
|
+
/<!--[\s\S]*?-->|(<(script|style|textarea|title|xmp|iframe|noembed|noframes)\b(?:[^>"']|"[^"]*"|'[^']*')*>)([\s\S]*?)(<\/\2\s*>|$)|<[a-z][a-z\d:-]*\b(?:[^>"']|"[^"]*"|'[^']*')*>/giu,
|
|
314
|
+
(markup, open: string | undefined, kind: string | undefined, content: string, close: string) => {
|
|
315
|
+
if (markup.startsWith('<!--')) return markup
|
|
316
|
+
if (open === undefined) return attributes(markup)
|
|
317
|
+
return attributes(open) + (kind?.toLowerCase() === 'style' ? rewriteCss(content, proxied) : content) + close
|
|
318
|
+
},
|
|
319
|
+
)
|
|
320
|
+
}
|
|
321
|
+
|
|
322
|
+
/** Relay reference data to the owning app frame, never authenticated API requests. */
|
|
323
|
+
export function relayTag(_sessionId: string): string {
|
|
324
|
+
return `<script data-dsh-ref-guest-relay="1">
|
|
325
|
+
window.addEventListener('message', function (event) {
|
|
326
|
+
if (event.source !== window || !event.data || event.data.type !== 'dsh-browser-ref:intent') return;
|
|
327
|
+
if (parent !== window) parent.postMessage(event.data, '*');
|
|
328
|
+
});
|
|
329
|
+
</script>`
|
|
330
|
+
}
|
|
331
|
+
|
|
332
|
+
function guestPolicy(authority: string, framed: boolean): string {
|
|
333
|
+
const sources = ['http:', 'https:'].map(protocol => new URL(protocol + '//' + authority).origin + GUEST_ROUTE).join(' ')
|
|
334
|
+
return "sandbox " + (framed ? RELAXED_BROWSER_SANDBOX : WEB_BROWSER_SANDBOX) + "; default-src " + sources
|
|
335
|
+
+ "; script-src " + sources + " 'unsafe-inline' 'unsafe-eval'; style-src " + sources
|
|
336
|
+
+ " 'unsafe-inline'; img-src " + sources + " data: blob:; font-src " + sources + " data:; connect-src " + sources
|
|
337
|
+
+ "; frame-src " + sources + "; form-action " + sources
|
|
338
|
+
+ "; object-src 'none'; worker-src 'none'; base-uri 'none'"
|
|
339
|
+
}
|
|
340
|
+
|
|
341
|
+
/** Forward a document or sub-request, keeping upstream cookies off the DSH origin. */
|
|
342
|
+
export async function handleGuest(
|
|
343
|
+
request: IncomingMessage,
|
|
344
|
+
response: ServerResponse,
|
|
345
|
+
overlayScript: string,
|
|
346
|
+
sessionId: string,
|
|
347
|
+
cookies?: GuestCookieJar,
|
|
348
|
+
storage?: GuestStorage,
|
|
349
|
+
): Promise<void> {
|
|
350
|
+
const method = request.method ?? 'GET'
|
|
351
|
+
const authority = request.headers.host ?? ''
|
|
352
|
+
if (!/^(?:\[[\da-f:]+\]|[a-z\d.-]+)(?::\d+)?$/iu.test(authority)) {
|
|
353
|
+
response.writeHead(400)
|
|
354
|
+
response.end('guest proxy: invalid host')
|
|
355
|
+
return
|
|
356
|
+
}
|
|
357
|
+
const policy = guestPolicy(authority, request.headers['sec-fetch-dest'] === 'iframe')
|
|
358
|
+
const writeHead = (status: number, headers: OutgoingHttpHeaders = {}): void => {
|
|
359
|
+
response.writeHead(status, { ...headers, 'content-security-policy': policy })
|
|
360
|
+
}
|
|
361
|
+
response.setHeader('referrer-policy', 'no-referrer')
|
|
362
|
+
response.setHeader('x-content-type-options', 'nosniff')
|
|
363
|
+
response.setHeader('access-control-allow-origin', 'null')
|
|
364
|
+
if (method === 'OPTIONS') {
|
|
365
|
+
const requested = String(request.headers['access-control-request-headers'] ?? '').toLowerCase().split(',').map(name => name.trim())
|
|
366
|
+
writeHead(204, {
|
|
367
|
+
'access-control-allow-methods': 'GET, HEAD, POST, PUT, PATCH, DELETE, OPTIONS',
|
|
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(', '),
|
|
369
|
+
})
|
|
370
|
+
response.end()
|
|
371
|
+
return
|
|
372
|
+
}
|
|
373
|
+
const query = new URLSearchParams((request.url ?? '').split('?')[1] ?? '')
|
|
374
|
+
const session = query.get('s') ?? sessionId
|
|
375
|
+
const target = guestTarget(request.url ?? '')
|
|
376
|
+
if (target === undefined) {
|
|
377
|
+
writeHead(400, { 'content-type': 'text/plain; charset=utf-8' })
|
|
378
|
+
response.end('guest proxy: a canonical http(s) URL is required')
|
|
379
|
+
return
|
|
380
|
+
}
|
|
381
|
+
let host = ''
|
|
382
|
+
try { host = new URL('http://' + (request.headers.host ?? '')).hostname.toLowerCase().replace(/\.$/u, '') } catch {}
|
|
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])
|
|
388
|
+
if (blocked(target)) {
|
|
389
|
+
writeHead(403, { 'content-type': 'text/plain; charset=utf-8' })
|
|
390
|
+
response.end('guest proxy: local and DSH host targets are not allowed')
|
|
391
|
+
return
|
|
392
|
+
}
|
|
393
|
+
const storageToken = query.get('storage-token')
|
|
394
|
+
if (storageToken !== null) {
|
|
395
|
+
response.setHeader('cache-control', 'no-store')
|
|
396
|
+
response.setHeader('content-type', 'application/json')
|
|
397
|
+
if (method !== 'POST') { writeHead(405); response.end(); return }
|
|
398
|
+
let size = 0
|
|
399
|
+
const chunks: Buffer[] = []
|
|
400
|
+
try {
|
|
401
|
+
for await (const chunk of request) {
|
|
402
|
+
const bytes = Buffer.from(chunk)
|
|
403
|
+
size += bytes.length
|
|
404
|
+
if (size > 32 * 1024 * 1024) throw Object.assign(new Error(), { name: 'QuotaExceededError' })
|
|
405
|
+
chunks.push(bytes)
|
|
406
|
+
}
|
|
407
|
+
const input: unknown = JSON.parse(Buffer.concat(chunks).toString('utf8'))
|
|
408
|
+
const store = storage ?? localGuestStorage()
|
|
409
|
+
let value: unknown
|
|
410
|
+
if (input && typeof input === 'object' && 'area' in input && input.area === 'cookies') {
|
|
411
|
+
store.authorize(storageToken, target.origin)
|
|
412
|
+
const operation = input as Record<string, unknown>
|
|
413
|
+
const jar = cookies ?? localGuestCookies()
|
|
414
|
+
if (operation.op === 'get') value = jar.getDocumentCookie(target)
|
|
415
|
+
else if (operation.op === 'set' && typeof operation.value === 'string') {
|
|
416
|
+
jar.setDocumentCookie(target, operation.value); value = jar.getDocumentCookie(target)
|
|
417
|
+
} else throw new TypeError('Invalid cookie operation')
|
|
418
|
+
} else value = store.execute(storageToken, target.origin, input)
|
|
419
|
+
writeHead(200); response.end(JSON.stringify({ ok: true, value }))
|
|
420
|
+
} catch (error) {
|
|
421
|
+
const name = error instanceof Error && ['SecurityError', 'TypeError', 'QuotaExceededError', 'UnknownError'].includes(error.name)
|
|
422
|
+
? error.name : 'UnknownError'
|
|
423
|
+
writeHead(name === 'SecurityError' ? 403 : 400)
|
|
424
|
+
response.end(JSON.stringify({ ok: false, name }))
|
|
425
|
+
}
|
|
426
|
+
return
|
|
427
|
+
}
|
|
428
|
+
const destination = request.headers['sec-fetch-dest']
|
|
429
|
+
const subRequest = request.headers['x-dsh-guest-sub'] === '1'
|
|
430
|
+
|| (typeof destination === 'string' && destination !== 'document' && destination !== 'iframe')
|
|
431
|
+
const failUpstream = (kind: 'request' | 'response' | 'target', error: unknown): void => {
|
|
432
|
+
const message = kind === 'target' ? 'guest proxy: target is not allowed' : `guest proxy: upstream ${kind} failed`
|
|
433
|
+
writeHead(kind === 'target' ? 403 : 502, {
|
|
434
|
+
'content-type': subRequest ? 'text/plain; charset=utf-8' : 'text/html; charset=utf-8',
|
|
435
|
+
'cache-control': 'no-store',
|
|
436
|
+
})
|
|
437
|
+
if (subRequest) { response.end(message); return }
|
|
438
|
+
const code = upstreamErrorCode(error)
|
|
439
|
+
response.end('<!doctype html><html><head><meta charset="utf-8"><title>' + hostMessages.bilingual.unavailableTitle + '</title>'
|
|
440
|
+
+ '<script data-dsh-guest-runtime="1">' + guestRuntimeScript(target.href) + '</script>'
|
|
441
|
+
+ '<style>body{font:16px/1.6 system-ui,sans-serif;margin:48px auto;padding:0 24px;max-width:640px;color:#334155}h1{font-size:24px}code{overflow-wrap:anywhere}button{font:inherit;padding:6px 20px;cursor:pointer}</style>'
|
|
442
|
+
+ '</head><body><h1>' + hostMessages.bilingual.unavailableTitle + '</h1><p>' + hostMessages.bilingual.unavailableDetail + '</p>'
|
|
443
|
+
+ '<p><code>' + message + (code === undefined ? '' : ' (' + code + ')') + '</code></p>'
|
|
444
|
+
+ '<button type="button" onclick="location.reload()">' + hostMessages.bilingual.retry + '</button></body></html>')
|
|
445
|
+
}
|
|
446
|
+
const headers = new Headers()
|
|
447
|
+
const siteHeaders = new Set(request.headers['x-dsh-guest-sub'] === '1'
|
|
448
|
+
? String(request.headers['x-dsh-guest-headers'] ?? '').toLowerCase().split(',').filter(siteHeader) : [])
|
|
449
|
+
for (const [name, value] of Object.entries(request.headers)) {
|
|
450
|
+
if ((!SAFE_REQUEST_HEADERS.has(name.toLowerCase()) && !siteHeaders.has(name.toLowerCase())) || value === undefined) continue
|
|
451
|
+
headers.set(name, Array.isArray(value) ? value.join(', ') : value)
|
|
452
|
+
}
|
|
453
|
+
if (!subRequest) {
|
|
454
|
+
headers.delete('if-none-match')
|
|
455
|
+
headers.delete('if-modified-since')
|
|
456
|
+
}
|
|
457
|
+
headers.set('accept-encoding', 'identity')
|
|
458
|
+
headers.set('user-agent', DESKTOP_UA)
|
|
459
|
+
if (!headers.has('accept-language')) headers.set('accept-language', 'zh-CN,zh;q=0.9,en;q=0.8')
|
|
460
|
+
// 页面内跳转的 Referer 会是我们自己的代理地址(iframe 里的上一页),对站点毫无意义;把它还原成
|
|
461
|
+
// 「上一页的真实地址」,站点才当成站内导航处理。百度对 `/s?wd=…` 直接服务端拉取一律回「安全验证」,
|
|
462
|
+
// 带上正确的 Referer 与首页 Cookie 后才会给结果页。
|
|
463
|
+
const referer = request.headers.referer
|
|
464
|
+
if (typeof referer === 'string') {
|
|
465
|
+
try {
|
|
466
|
+
const previous = guestTarget(new URL(referer).pathname + new URL(referer).search)
|
|
467
|
+
if (previous !== undefined && !blocked(previous)) {
|
|
468
|
+
headers.set('referer', previous.href)
|
|
469
|
+
}
|
|
470
|
+
} catch {}
|
|
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
|
+
}
|
|
484
|
+
let cookieJar: GuestCookieJar
|
|
485
|
+
try { cookieJar = cookies ?? localGuestCookies() } catch {
|
|
486
|
+
writeHead(503, { 'content-type': 'text/plain; charset=utf-8' })
|
|
487
|
+
response.end('guest proxy: cookie storage unavailable')
|
|
488
|
+
return
|
|
489
|
+
}
|
|
490
|
+
const refreshCookies = (url = target): void => {
|
|
491
|
+
const previous = headers.get('referer')
|
|
492
|
+
const cookie = cookieJar.getCookieHeader(url, false, previous ? { site: new URL(previous), topLevel: !subRequest, method } : undefined)
|
|
493
|
+
if (cookie) headers.set('cookie', cookie)
|
|
494
|
+
else headers.delete('cookie')
|
|
495
|
+
}
|
|
496
|
+
refreshCookies()
|
|
497
|
+
// 站内导航的伪装头。
|
|
498
|
+
//
|
|
499
|
+
// 代理发出去的是「服务端 fetch」:没有 Origin,`sec-fetch-*` 也不存在,站点一眼就能判定这不是
|
|
500
|
+
// 用户在站内点出来的请求。百度对这类请求一律回「安全验证」,而验证页本身的内容要由它的接口
|
|
501
|
+
// 再取一次(跨域,取不到),于是侧栏里就是白屏——用户看到的是「点搜索没反应」。
|
|
502
|
+
// 这几个头全部指向目标站点自己,转发出去与「用户在该站内点了一下」没有区别。
|
|
503
|
+
headers.set('sec-fetch-site', 'same-origin')
|
|
504
|
+
headers.set('sec-fetch-mode', subRequest ? 'cors' : 'navigate')
|
|
505
|
+
headers.set('sec-fetch-dest', subRequest ? 'empty' : 'document')
|
|
506
|
+
if (!subRequest || method !== 'GET') headers.set('origin', target.origin)
|
|
507
|
+
if (!subRequest) {
|
|
508
|
+
headers.set('sec-fetch-user', '?1')
|
|
509
|
+
headers.set('upgrade-insecure-requests', '1')
|
|
510
|
+
}
|
|
511
|
+
const safeNavigation = !subRequest && (method === 'GET' || method === 'HEAD')
|
|
512
|
+
const warmRoot = async (): Promise<void> => {
|
|
513
|
+
const root = new URL('/', target.origin)
|
|
514
|
+
refreshCookies(root)
|
|
515
|
+
try {
|
|
516
|
+
const warm = await fetchTarget(root, { method: 'GET', headers, redirect: 'manual' })
|
|
517
|
+
cookieJar.setCookies(root, warm.headers.getSetCookie?.() ?? [])
|
|
518
|
+
await warm.body?.cancel()
|
|
519
|
+
headers.set('referer', root.href)
|
|
520
|
+
} finally { refreshCookies() }
|
|
521
|
+
}
|
|
522
|
+
// 深链接预热:直接拉 `https://host/s?…` 这类页面时,站点看到的是「没有站点 Cookie 的首跳」,
|
|
523
|
+
// 百度会回「安全验证」。先取一次站点根,把服务端种的 Cookie 收进自己的罐子,并把 Referer 指向它,
|
|
524
|
+
// 这次跳转就变成一次正常的站内导航。只在罐子里还没有该站 Cookie 且目标不是根路径时做一次。
|
|
525
|
+
if (safeNavigation && !headers.has('cookie') && target.pathname !== '/' && !headers.has('referer')) {
|
|
526
|
+
try { await warmRoot() } catch { /* 预热失败就按原样请求 */ }
|
|
527
|
+
}
|
|
528
|
+
let upstream: Response
|
|
529
|
+
try {
|
|
530
|
+
let body: Buffer | undefined
|
|
531
|
+
if (method !== 'GET' && method !== 'HEAD') {
|
|
532
|
+
const chunks: Buffer[] = []
|
|
533
|
+
let size = 0
|
|
534
|
+
const tooLarge = (): void => {
|
|
535
|
+
request.pause()
|
|
536
|
+
writeHead(413, { 'content-type': 'text/plain; charset=utf-8', connection: 'close' })
|
|
537
|
+
response.end('guest proxy: request body exceeds 10 MiB')
|
|
538
|
+
}
|
|
539
|
+
if (Number(request.headers['content-length']) > MAX_REQUEST_BODY_BYTES) {
|
|
540
|
+
tooLarge()
|
|
541
|
+
return
|
|
542
|
+
}
|
|
543
|
+
for await (const chunk of request.iterator({ destroyOnReturn: false })) {
|
|
544
|
+
const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk)
|
|
545
|
+
size += buffer.length
|
|
546
|
+
if (size > MAX_REQUEST_BODY_BYTES) {
|
|
547
|
+
tooLarge()
|
|
548
|
+
return
|
|
549
|
+
}
|
|
550
|
+
chunks.push(buffer)
|
|
551
|
+
}
|
|
552
|
+
body = Buffer.concat(chunks)
|
|
553
|
+
}
|
|
554
|
+
upstream = await fetchTarget(target, { method, headers, body: body as BodyInit | undefined, redirect: 'manual' })
|
|
555
|
+
cookieJar.setCookies(target, upstream.headers.getSetCookie?.() ?? [])
|
|
556
|
+
// 反爬拦截识别 + 一次重试(分类器与页面内检测共用 `browser/anti-bot.ts`):站点(百度 `/s?wd=…`)在没有
|
|
557
|
+
// 「先访问过站点」的痕迹时回「安全验证」。罐子里可能已经带着上次挑战页的 Cookie,所以看**内容**而不看有没有 Cookie。
|
|
558
|
+
// 只对「可重试」类(拒绝访问 / 429 / 空 403)与需人工验证类做一次放慢节奏的重试:先停一下,取站点根补 Cookie、
|
|
559
|
+
// 带上根的 Referer 再请求一次。仍失败就把原页交给上层(页内检测会给出接管或换路的建议);网络(IP)封锁不重试。
|
|
560
|
+
if (safeNavigation && target.pathname !== '/' && /^text\/html/iu.test(upstream.headers.get('content-type') ?? '')
|
|
561
|
+
&& Number(upstream.headers.get('content-length') ?? '0') <= MAX_REWRITE_BYTES) {
|
|
562
|
+
const probe = await upstream.clone().text()
|
|
563
|
+
const verdict = classifyBlock({ status: upstream.status, text: probe.slice(0, 64 * 1024) })
|
|
564
|
+
if (verdict.blocked && verdict.recovery !== 'environment') {
|
|
565
|
+
try {
|
|
566
|
+
await new Promise(resolve => setTimeout(resolve, blockRetryDelayMs()))
|
|
567
|
+
await warmRoot()
|
|
568
|
+
const retried = await fetchTarget(target, { method, headers, redirect: 'manual' })
|
|
569
|
+
await upstream.body?.cancel()
|
|
570
|
+
upstream = retried
|
|
571
|
+
} catch { /* 重试失败就用首次响应 */ }
|
|
572
|
+
}
|
|
573
|
+
}
|
|
574
|
+
} catch (error) {
|
|
575
|
+
failUpstream(error instanceof UnsafeGuestTargetError ? 'target' : 'request', error)
|
|
576
|
+
return
|
|
577
|
+
}
|
|
578
|
+
try {
|
|
579
|
+
cookieJar.setCookies(target, upstream.headers.getSetCookie?.() ?? [])
|
|
580
|
+
const out = new Headers()
|
|
581
|
+
for (const [name, value] of upstream.headers) {
|
|
582
|
+
if (!DROP_RESPONSE_HEADERS.has(name.toLowerCase()) && !name.toLowerCase().startsWith('access-control-')) out.set(name, value)
|
|
583
|
+
}
|
|
584
|
+
const location = upstream.headers.get('location')
|
|
585
|
+
if (location !== null && upstream.status >= 300 && upstream.status < 400) {
|
|
586
|
+
let next: URL | undefined
|
|
587
|
+
try {
|
|
588
|
+
const candidate = new URL(location, target)
|
|
589
|
+
if (!await blockedResolved(candidate)) next = candidate
|
|
590
|
+
} catch {}
|
|
591
|
+
if (next === undefined) {
|
|
592
|
+
await upstream.body?.cancel()
|
|
593
|
+
writeHead(403, { 'content-type': 'text/plain; charset=utf-8' })
|
|
594
|
+
response.end('guest proxy: redirect target is not allowed')
|
|
595
|
+
return
|
|
596
|
+
}
|
|
597
|
+
out.set('location', guestPath(next.href) + (session === '' ? '' : '&s=' + encodeURIComponent(session)))
|
|
598
|
+
}
|
|
599
|
+
const type = upstream.headers.get('content-type') ?? 'application/octet-stream'
|
|
600
|
+
const length = Number(upstream.headers.get('content-length') ?? '0')
|
|
601
|
+
if (method === 'HEAD' || upstream.body === null) {
|
|
602
|
+
writeHead(upstream.status, Object.fromEntries(out))
|
|
603
|
+
response.end()
|
|
604
|
+
return
|
|
605
|
+
}
|
|
606
|
+
if (/^text\/css(?:;|$)/iu.test(type) && !(upstream.status >= 300 && upstream.status < 400)) {
|
|
607
|
+
const bytes = Buffer.from(await upstream.arrayBuffer())
|
|
608
|
+
const decoded = decodeCssBytes(bytes, type)
|
|
609
|
+
if (decoded === undefined) {
|
|
610
|
+
writeHead(upstream.status, Object.fromEntries(out))
|
|
611
|
+
response.end(bytes)
|
|
612
|
+
return
|
|
613
|
+
}
|
|
614
|
+
const css = rewriteCss(decoded, value => proxyReference(value, target))
|
|
615
|
+
out.delete('etag')
|
|
616
|
+
out.delete('content-md5')
|
|
617
|
+
out.set('content-type', 'text/css; charset=utf-8')
|
|
618
|
+
writeHead(upstream.status, Object.fromEntries(out))
|
|
619
|
+
response.end(css)
|
|
620
|
+
return
|
|
621
|
+
}
|
|
622
|
+
if (subRequest || !REWRITABLE.test(type) || !/^(text\/html|application\/xhtml\+xml)(?:;|$)/iu.test(type)
|
|
623
|
+
|| length > MAX_REWRITE_BYTES || (upstream.status >= 300 && upstream.status < 400)) {
|
|
624
|
+
const body = Buffer.from(await upstream.arrayBuffer())
|
|
625
|
+
writeHead(upstream.status, Object.fromEntries(out))
|
|
626
|
+
response.end(/^(text\/html|application\/xhtml\+xml)(?:;|$)/iu.test(type)
|
|
627
|
+
? Buffer.from(stripDocumentPolicies(body.toString('latin1')), 'latin1') : body)
|
|
628
|
+
return
|
|
629
|
+
}
|
|
630
|
+
const raw = await upstream.text()
|
|
631
|
+
// Fetch metadata is browser-controlled: scripts must not fetch another site's storage capability.
|
|
632
|
+
const context = query.get('storage-context') ?? randomUUID()
|
|
633
|
+
const storageConfig = (destination === 'iframe' || destination === 'document') && request.headers['sec-fetch-mode'] === 'navigate'
|
|
634
|
+
&& /^[\w:-]{16,128}$/u.test(context)
|
|
635
|
+
? { token: (storage ?? localGuestStorage()).issue(target.origin, context), context, cookies: cookieJar.getDocumentCookie(target) } : undefined
|
|
636
|
+
const runtime = '<script data-dsh-guest-runtime="1">' + guestRuntimeScript(target.href, storageConfig, upstream.headers.get('referrer-policy') ?? '') + '</script>'
|
|
637
|
+
let body = rewriteDocument(raw, target)
|
|
638
|
+
if (/<head\b[^>]*>/iu.test(body)) body = body.replace(/<head\b[^>]*>/iu, match => match + runtime)
|
|
639
|
+
else if (/<html\b[^>]*>/iu.test(body)) body = body.replace(/<html\b[^>]*>/iu, match => match + '<head>' + runtime + '</head>')
|
|
640
|
+
else body = runtime + body
|
|
641
|
+
const tail = '\n' + overlayScript + '\n' + relayTag(session)
|
|
642
|
+
body = /<\/body\s*>/iu.test(body) ? body.replace(/<\/body\s*>/iu, match => tail + match) : body + tail
|
|
643
|
+
out.delete('etag')
|
|
644
|
+
out.delete('content-md5')
|
|
645
|
+
out.set('content-type', type)
|
|
646
|
+
out.delete('last-modified')
|
|
647
|
+
out.set('cache-control', 'no-store')
|
|
648
|
+
writeHead(upstream.status, Object.fromEntries(out))
|
|
649
|
+
response.end(body)
|
|
650
|
+
} catch (error) {
|
|
651
|
+
failUpstream('response', error)
|
|
652
|
+
}
|
|
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
|
+
}
|