DeepSeek Harness Tauri 桌面版 | Only 8mb installer, zero environment setup, preset plugins, Windows / macOS / Linux.
feat(native): keep Cloudflare Access login inside the WebView (#1142)
Zuyang Liuabcb5411e99d
diff --git a/docs/specs/native.md b/docs/specs/native.mdindex c162f280..5a088a2b 100644--- a/docs/specs/native.md+++ b/docs/specs/native.md@@ -100,6 +100,7 @@ src-native/* 超时与预算集中在 `src-native/config/constants.ts`:默认端口 `3088` / `3080`、并发 40、单次探测 600 ms、历史探测 3 s、整体扫描预算 20 s、前台健康检查间隔 15 s。* 服务识别与健康检查只请求上游真实公开的 `/manifest.webmanifest`,严格校验 `name: 'DeepSeek Harness'` 与 `short_name: 'DSH'`;不请求不存在的认证状态端点,也不把任意 HTML 200 当作 DSH 服务。* 服务识别不代表登录成功。需要认证的主机由 WebView 完成配对,只有可信文档就绪消息才能确认连接成功;健康检查不读取或重放配对码。+* 主机前置 Cloudflare Access 时,需为 `/manifest.webmanifest` 单独建一个 Bypass 应用(该隧道路由不开 Protect with Access),否则启动自动重连与健康检查一律失败;扫码、点选历史与重新连接不经探测。* 探测与扫描拆成两个模块:`src-native/services/probe-bridge.ts` 的 `probeBridge(address, signal, timeoutMs?)` 探测单个地址(超时、网络错误、非 2xx、响应体不合法一律返回 `null`),`src-native/services/scan-candidates.ts` 的 `scanCandidates(candidates, { signal, concurrency, timeoutMs, budgetMs, onFound })` 以有界并发遍历候选地址并受总预算约束(参数非法直接抛 `RangeError`)。* 断开会清空当前连接并保留历史,紧接着的扫描跳过刚断开的精确 origin。@@ -132,6 +133,7 @@ src-native/* 局域网 HTTP 通过 `expo-build-properties` 的 `usesCleartextTraffic: true` 支持;HTTP 不提供传输保密性,仅用于可信局域网,公网优先 HTTPS。* 自动发现基于当前 IPv4 推导 `/24` 网段,不保证跨网段、VPN、访客 Wi-Fi 隔离或非默认端口;此时改用桌面端 / Bridge 生成的二维码,或在 `EXTRA_SCAN_PORTS` 追加端口。* 通知与 WebView 消息入口校验类型白名单、精确 scheme / host / port origin、原生事件 URL 与每个 WebView 的随机 nonce;外站顶层链接交由外部浏览器打开。+* 唯一例外是 Cloudflare Access 登录:受信 origin 的文档请求被服务端重定向到 `https://*.cloudflareaccess.com/cdn-cgi/access/login/…` 时,登录留在 WebView 内,流程中的 https 顶层跳转(团队域、IdP)放行,回到受信 origin 即结束,期间隐藏加载遮罩并暂停 20 s 超时,结束后 Android 清空返回历史;已加载文档里点开的同类链接仍走外部浏览器。Google 作为 IdP 会拒绝嵌入式 WebView(`disallowed_useragent`),需改用 One-time PIN 等。* 配对登录与会话保留在 WebView 内由 cookie jar 管理,**不**通过 RN `fetch` 登录。远程访问不再生成、保存或接受访问密码;SSH 密码与密钥口令不受影响。* 网关仅允许无凭据读取静态 `/manifest.webmanifest`,不为探测铸造上游会话。该例外只接受 `GET` / `HEAD`,拒绝跨源浏览器请求,不放行应用页面、API 或 WebSocket。* 上游没有独立的远程推送端点:系统挂起、进程被杀或关闭 App 后**不保证**继续收到新任务通知。diff --git a/src-native/config/constants.ts b/src-native/config/constants.tsindex d5ce456f..79cbba71 100644--- a/src-native/config/constants.ts+++ b/src-native/config/constants.ts@@ -14,3 +14,5 @@ export const FOCUS_TIMEOUT_MS = 15000export const NOTIFICATION_CHANNEL = 'dsh-bridge'export const CONNECTION_STORAGE_KEY = 'dsh-bridge/connections'export const MANIFEST_PATH = '/manifest.webmanifest'+export const ACCESS_TEAM_DOMAIN_SUFFIX = '.cloudflareaccess.com'+export const ACCESS_LOGIN_PATH = '/cdn-cgi/access/login/'diff --git a/src-native/ui/webview.test.tsx b/src-native/ui/webview.test.tsxindex 69223426..06e311b7 100644--- a/src-native/ui/webview.test.tsx+++ b/src-native/ui/webview.test.tsx@@ -94,6 +94,7 @@ vi.mock('react-native-webview', async () => {Object.assign(this, {injectJavaScript: vi.fn<(script: string) => void>(),goBack: vi.fn<() => void>(),+ clearHistory: vi.fn<() => void>(),})}@@ -136,6 +137,7 @@ function hydrate() {interface NativeViewRef {injectJavaScript: ReturnType<typeof vi.fn<(script: string) => void>>goBack: ReturnType<typeof vi.fn<() => void>>+ clearHistory: ReturnType<typeof vi.fn<() => void>>}function root() {@@ -1147,7 +1149,7 @@ describe('rendered Bridge WebView acknowledged notification focus', () => {})describe('rendered Bridge WebView native navigation and resource boundaries', () => {- it('treats missing Android isTopFrame as top-level and permits only exact-origin documents inside the WebView', async () => {+ it('treats missing Android isTopFrame as top-level and sends foreign top-level documents outside an Access login to the system browser', async () => {await mount()await act(async () => {expect(webView().props.onShouldStartLoadWithRequest({ url: 'http://bridge.test:3080/session?id=alpha' })).toBe(true)@@ -1310,3 +1312,251 @@ describe('rendered Bridge WebView native navigation and resource boundaries', ()expect(native.scheduleNotificationAsync).not.toHaveBeenCalled()})})++describe('rendered Bridge WebView Cloudflare Access login', () => {+ const accessLogin = 'https://team.cloudflareaccess.com/cdn-cgi/access/login/bridge.test?kid=aud&redirect_url=%2Ftasks'++ it('keeps the Access login redirected from the host document inside the WebView with the loader lifted and its deadline paused', async () => {+ await mount()+ expect(texts()).toContain('连接中…')+ await act(async () => {+ expect(webView().props.onShouldStartLoadWithRequest({ url: accessLogin })).toBe(true)+ })+ expect(texts()).not.toContain('连接中…')+ await act(async () => {+ expect(webView().props.onShouldStartLoadWithRequest({ url: 'https://github.com/login/oauth/authorize?client_id=team' })).toBe(true)+ expect(webView().props.onShouldStartLoadWithRequest({ url: 'https://team.cloudflareaccess.com/cdn-cgi/access/callback?code=idp' })).toBe(true)+ await vi.advanceTimersByTimeAsync(60000)+ })++ expect(texts()).not.toContain(slowLoading)+ expect(texts()).not.toContain('连接中…')+ expect(native.openURL).not.toHaveBeenCalled()+ expect(connection.loadError).toBeNull()+ })++ it('lifts an already shown slow-loading prompt when a late host redirect reaches the Access login', async () => {+ await mount()+ await act(async () => {+ await vi.advanceTimersByTimeAsync(20000)+ })+ expect(texts()).toContain(slowLoading)+ await act(async () => {+ expect(webView().props.onShouldStartLoadWithRequest({ url: accessLogin })).toBe(true)+ })++ expect(texts()).not.toContain(slowLoading)+ expect(texts()).not.toContain('连接中…')+ })++ it('restores the loader with a fresh twenty-second deadline once Access hands back to the host origin', async () => {+ await mount()+ await act(async () => {+ expect(webView().props.onShouldStartLoadWithRequest({ url: accessLogin })).toBe(true)+ })+ await act(async () => {+ await vi.advanceTimersByTimeAsync(30000)+ })+ await act(async () => {+ expect(webView().props.onShouldStartLoadWithRequest({ url: 'http://bridge.test:3080/cdn-cgi/access/authorized?token=jwt' })).toBe(true)+ })+ expect(texts()).toContain('连接中…')+ await act(async () => {+ await vi.advanceTimersByTimeAsync(19999)+ })+ expect(texts()).not.toContain(slowLoading)+ await act(async () => {+ await vi.advanceTimersByTimeAsync(1)+ })++ expect(texts()).toContain(slowLoading)+ })++ it('ends the Access login when a host document commits without a navigation decision, so identity provider hosts leave the app again', async () => {+ await mount()+ await act(async () => {+ expect(webView().props.onShouldStartLoadWithRequest({ url: accessLogin })).toBe(true)+ })+ await act(async () => {+ webView().props.onLoadStart({ nativeEvent: { url: 'http://bridge.test:3080/', loading: true } })+ })+ expect(texts()).toContain('连接中…')+ await act(async () => {+ expect(webView().props.onShouldStartLoadWithRequest({ url: 'https://github.com/login' })).toBe(false)+ })++ expect(native.openURL).toHaveBeenCalledExactlyOnceWith('https://github.com/login')+ })++ it('keeps insecure, credentialed and non-web navigations out of the WebView during the Access login, opening only the plain http one externally', async () => {+ await mount()+ await act(async () => {+ expect(webView().props.onShouldStartLoadWithRequest({ url: accessLogin })).toBe(true)+ })+ await act(async () => {+ for (const url of ['http://idp.test/authorize', 'https://[email protected]/authorize', 'https://:[email protected]/authorize', 'intent://authorize#Intent;scheme=idp;end'])+ expect(webView().props.onShouldStartLoadWithRequest({ url })).toBe(false)+ })++ expect(native.openURL).toHaveBeenCalledExactlyOnceWith('http://idp.test/authorize')+ })++ it('shows the recoverable connection failure when the Access login page fails to load', async () => {+ await mount()+ await act(async () => {+ expect(webView().props.onShouldStartLoadWithRequest({ url: accessLogin })).toBe(true)+ })+ await act(async () => {+ webView().props.onLoad({ nativeEvent: { url: accessLogin } })+ webView().props.onError({ nativeEvent: { url: accessLogin, code: -2, description: 'net::ERR_NAME_NOT_RESOLVED' } })+ })++ expect(connection.loadError).toBe(failure)+ expect(texts()).toContain(failure)+ expect(root().findAll(node => String(node.type) === 'Button').map(text)).toContain('重新连接')+ })++ it('keeps the slow-loading recovery when a timed-out host document reports same-document history', async () => {+ await mount()+ await act(async () => {+ await vi.advanceTimersByTimeAsync(20000)+ })+ expect(texts()).toContain(slowLoading)+ await act(async () => {+ webView().props.onLoadStart({ nativeEvent: { url: 'http://bridge.test:3080/', loading: false } })+ })++ expect(texts()).toContain(slowLoading)+ expect(texts()).not.toContain('连接中…')+ })++ it('drops Access and identity-provider pages from Android back history once the host document loads after the login', async () => {+ await mount()+ const view = await viewRef()+ const handler = [...native.backListeners][0]!+ await act(async () => {+ expect(webView().props.onShouldStartLoadWithRequest({ url: accessLogin })).toBe(true)+ })+ await act(async () => {+ expect(webView().props.onShouldStartLoadWithRequest({ url: 'http://bridge.test:3080/cdn-cgi/access/authorized?token=jwt' })).toBe(true)+ webView().props.onLoadStart({ nativeEvent: { url: 'http://bridge.test:3080/', loading: true } })+ webView().props.onLoad({ nativeEvent: { url: 'http://bridge.test:3080/' } })+ webView().props.onNavigationStateChange({ url: 'http://bridge.test:3080/', canGoBack: true })+ })++ expect(view.clearHistory).toHaveBeenCalledExactlyOnceWith()+ expect(handler()).toBe(false)+ expect(view.goBack).not.toHaveBeenCalled()+ })++ it('clears Android back history once per Access login, so later host history still goes back inside the WebView', async () => {+ await mount()+ const view = await viewRef()+ const handler = [...native.backListeners][0]!+ await act(async () => {+ expect(webView().props.onShouldStartLoadWithRequest({ url: accessLogin })).toBe(true)+ })+ await act(async () => {+ webView().props.onLoadStart({ nativeEvent: { url: 'http://bridge.test:3080/', loading: true } })+ webView().props.onLoad({ nativeEvent: { url: 'http://bridge.test:3080/' } })+ webView().props.onNavigationStateChange({ url: 'http://bridge.test:3080/', canGoBack: true })+ })+ await act(async () => {+ webView().props.onLoadStart({ nativeEvent: { url: 'http://bridge.test:3080/tasks', loading: true } })+ webView().props.onLoad({ nativeEvent: { url: 'http://bridge.test:3080/tasks' } })+ webView().props.onNavigationStateChange({ url: 'http://bridge.test:3080/tasks', canGoBack: true })+ })++ expect(view.clearHistory).toHaveBeenCalledOnce()+ expect(handler()).toBe(true)+ expect(view.goBack).toHaveBeenCalledExactlyOnceWith()+ })++ it('keeps Android back history when the loaded host document never went through an Access login', async () => {+ await mount()+ const view = await viewRef()+ const handler = [...native.backListeners][0]!+ await act(async () => {+ webView().props.onLoad({ nativeEvent: { url: alpha.url } })+ webView().props.onNavigationStateChange({ url: alpha.url, canGoBack: true })+ })++ expect(view.clearHistory).not.toHaveBeenCalled()+ expect(handler()).toBe(true)+ expect(view.goBack).toHaveBeenCalledExactlyOnceWith()+ })++ it('keeps sending a tapped Access login link to the system browser after Android reports same-document history of the loaded host document', async () => {+ await mount()+ await act(async () => {+ webView().props.onLoadStart({ nativeEvent: { url: alpha.url, loading: true } })+ webView().props.onLoad({ nativeEvent: { url: alpha.url } })+ webView().props.onLoadStart({ nativeEvent: { url: 'http://bridge.test:3080/tasks?session=alpha', loading: false } })+ })+ await act(async () => {+ expect(webView().props.onShouldStartLoadWithRequest({ url: accessLogin })).toBe(false)+ })++ expect(native.openURL).toHaveBeenCalledExactlyOnceWith(accessLogin)+ expect(texts()).toContain('连接中…')+ })++ it('closes the in-app Access window once the first foreign hop of a host navigation is refused', async () => {+ await mount()+ await act(async () => {+ expect(webView().props.onShouldStartLoadWithRequest({ url: 'http://bridge.test:3080/tasks' })).toBe(true)+ expect(webView().props.onShouldStartLoadWithRequest({ url: 'https://sso.test/start' })).toBe(false)+ expect(webView().props.onShouldStartLoadWithRequest({ url: accessLogin })).toBe(false)+ })++ expect(native.openURL.mock.calls).toEqual([['https://sso.test/start'], [accessLogin]])+ })++ it('sends an Access login link tapped from a loaded host document to the system browser', async () => {+ await mount()+ await act(async () => {+ webView().props.onLoad({ nativeEvent: { url: alpha.url } })+ })+ await act(async () => {+ expect(webView().props.onShouldStartLoadWithRequest({ url: accessLogin })).toBe(false)+ })++ expect(native.openURL).toHaveBeenCalledExactlyOnceWith(accessLogin)+ expect(texts()).toContain('连接中…')+ })++ it('re-arms the in-app Access login for the redirect of a new host navigation after the previous document loaded', async () => {+ await mount()+ await act(async () => {+ webView().props.onLoad({ nativeEvent: { url: alpha.url } })+ })+ await act(async () => {+ expect(webView().props.onShouldStartLoadWithRequest({ url: 'http://bridge.test:3080/tasks' })).toBe(true)+ expect(webView().props.onShouldStartLoadWithRequest({ url: accessLogin })).toBe(true)+ })++ expect(native.openURL).not.toHaveBeenCalled()+ expect(texts()).not.toContain('连接中…')+ })++ it('refuses lookalike, insecure, credentialed and non-login Cloudflare URLs even as a host document redirect', async () => {+ const refused = [+ 'https://team.cloudflareaccess.com/cdn-cgi/access/logout',+ 'https://team.cloudflareaccess.com.evil.test/cdn-cgi/access/login/bridge.test',+ 'https://cloudflareaccess.com/cdn-cgi/access/login/bridge.test',+ 'http://team.cloudflareaccess.com/cdn-cgi/access/login/bridge.test',+ ]+ await mount()+ await act(async () => {+ for (const url of refused) {+ expect(webView().props.onShouldStartLoadWithRequest({ url: alpha.url })).toBe(true)+ expect(webView().props.onShouldStartLoadWithRequest({ url })).toBe(false)+ }+ expect(webView().props.onShouldStartLoadWithRequest({ url: alpha.url })).toBe(true)+ expect(webView().props.onShouldStartLoadWithRequest({ url: 'https://user:[email protected]/cdn-cgi/access/login/bridge.test' })).toBe(false)+ })++ expect(native.openURL.mock.calls).toEqual(refused.map(url => [url]))+ expect(texts()).toContain('连接中…')+ })+})diff --git a/src-native/ui/webview.tsx b/src-native/ui/webview.tsxindex fea27aac..39e6c0f9 100644--- a/src-native/ui/webview.tsx+++ b/src-native/ui/webview.tsx@@ -18,7 +18,7 @@ import { Uniwind } from 'uniwind'import { useStore } from 'valtio-define'import { BreathingLight } from '@/components/breathing-light'import { Logo, Wordmark } from '@/components/icons'-import { SESSION_FORGET_TIMEOUT_MS, WEBVIEW_LOAD_TIMEOUT_MS } from '@/config/constants'+import { ACCESS_LOGIN_PATH, ACCESS_TEAM_DOMAIN_SUFFIX, SESSION_FORGET_TIMEOUT_MS, WEBVIEW_LOAD_TIMEOUT_MS } from '@/config/constants'import { useAppState } from '@/hooks/use-app-state'import { requestNotificationAccess, sendNativeNotification } from '@/hooks/use-notifications'import { connection } from '@/store/modules/connection'@@ -39,7 +39,12 @@ export function BridgeWebView({ address, generation }: { address: BridgeAddress,const canGoBackRef = useRef(false)const focusRequestRef = useRef<{ requestId: string, focus: NotificationFocus } | null>(null)const documentReadyRef = useRef(false)+ const redirectableRef = useRef(true)+ const authenticatingRef = useRef(false)+ const accessHistoryRef = useRef(false)+ const clearedHistoryRef = useRef(false)const [documentReady, setDocumentReady] = useState(false)+ const [authenticating, setAuthenticating] = useState(false)const [loadingTimedOut, setLoadingTimedOut] = useState(false)const [documentGeneration, setDocumentGeneration] = useState(0)const state = useStore(connection)@@ -85,11 +90,11 @@ export function BridgeWebView({ address, generation }: { address: BridgeAddress,}, [address.id, appState, documentReady, nonce, state.loadError, state.pendingFocus, state.focusGeneration])// keep:effect Offer recovery for a slow document without rejecting its later authenticated readiness.useEffect(() => {- if (documentReady || state.loadError)+ if (documentReady || state.loadError || authenticating)returnconst timeout = setTimeout(setLoadingTimedOut, WEBVIEW_LOAD_TIMEOUT_MS, true)return () => clearTimeout(timeout)- }, [documentGeneration, documentReady, state.loadError])+ }, [authenticating, documentGeneration, documentReady, state.loadError])// keep:effect Bound cookie clearing to this WebView's lifetime before removing its connection.useEffect(() => {if (state.forgettingOrigin !== address.id)@@ -121,15 +126,34 @@ export function BridgeWebView({ address, generation }: { address: BridgeAddress,connection.setNotice(t('connection.connectionFailed'))}}+ function authenticate(active: boolean) {+ authenticatingRef.current = active+ setAuthenticating(active)+ if (!active)+ return+ accessHistoryRef.current = true+ setLoadingTimedOut(false)+ }function allowNavigation(request: ShouldStartLoadRequest): boolean {if (request.isTopFrame === false)return trueif (isTrustedOrigin(request.url, address.id)) {mainUrlRef.current = request.url+ redirectableRef.current = true+ authenticate(false)return true}if (request.url === 'about:blank')return true+ const redirected = redirectableRef.current+ redirectableRef.current = false+ const url = URL.canParse(request.url) ? new URL(request.url) : null+ // Why: only our own document's server redirect may open Cloudflare Access login in-app; tapped links still leave for the system browser.+ if (url?.protocol === 'https:' && !url.username && !url.password+ && (authenticatingRef.current || (redirected && url.hostname.endsWith(ACCESS_TEAM_DOMAIN_SUFFIX) && url.pathname.startsWith(ACCESS_LOGIN_PATH)))) {+ authenticate(true)+ return true+ }void openExternal(request.url)return false}@@ -182,6 +206,7 @@ export function BridgeWebView({ address, generation }: { address: BridgeAddress,if (generation !== connection.viewGeneration || !isTrustedOrigin(url, address.id))returnmainUrlRef.current = url+ authenticate(false)if (!loading)returnfocusRequestRef.current = null@@ -191,8 +216,16 @@ export function BridgeWebView({ address, generation }: { address: BridgeAddress,setDocumentGeneration(value => value + 1)}function loaded(url: string) {- if (isTrustedOrigin(url, address.id))- ref.current?.injectJavaScript(shim)+ if (!isTrustedOrigin(url, address.id))+ return+ redirectableRef.current = false+ ref.current?.injectJavaScript(shim)+ if (!accessHistoryRef.current)+ return+ // Why: Android Back must not re-enter Access/IdP pages outside the login; this finish event's canGoBack predates the clear.+ accessHistoryRef.current = false+ clearedHistoryRef.current = true+ ref.current?.clearHistory?.()}function openDrawer() {connection.dismissHint()@@ -229,7 +262,8 @@ export function BridgeWebView({ address, generation }: { address: BridgeAddress,connection.markLoadFailed(generation, t('connection.connectionFailed'))}}onNavigationStateChange={(navigation) => {- canGoBackRef.current = navigation.canGoBack+ canGoBackRef.current = navigation.canGoBack && !clearedHistoryRef.current+ clearedHistoryRef.current = falseif (isTrustedOrigin(navigation.url, address.id))mainUrlRef.current = navigation.url}}@@ -249,7 +283,7 @@ export function BridgeWebView({ address, generation }: { address: BridgeAddress,</Pressable></Then></If>- <If cond={state.loading && !loadingTimedOut}>+ <If cond={state.loading && !loadingTimedOut && !authenticating}><Then><View className="absolute inset-0 items-center justify-center gap-7 bg-background px-8"><View className="items-center gap-3">