DeepSeek Harness Tauri 桌面版 | Only 8mb installer, zero environment setup, preset plugins, Windows / macOS / Linux.
fix: 远程配对、native 发现与隧道启动 (#1043)
Mao Mr4385b848d947
diff --git a/docs/specs/native.md b/docs/specs/native.mdindex 1486fd4c..601a3b7d 100644--- a/docs/specs/native.md+++ b/docs/specs/native.md@@ -57,7 +57,7 @@ pnpm typecheck:native # tsc --project tsconfig.native.json --noEmit```src-native/├── app/ # expo-router 路由:_layout.tsx / index.tsx / scan.tsx-├── apis/ # HTTP 访问层:getAuthStatus / getManifest+├── apis/ # HTTP 访问层:getManifest├── components/ # 品牌与装饰组件(鲸鱼、字标、状态点、脉冲动画等)├── config/ # 常量、React Query client 与 query key├── hooks/ # 原生能力封装(通知、应用状态、主机健康轮询)@@ -85,8 +85,8 @@ src-native/### 3.2 apis-* `src-native/apis/index.types.ts` 是宿主 HTTP 契约的类型 SSOT(`AuthStatus`、`BridgeManifest`、路径参数类型)。-* `src-native/apis/index.ts` 提供 `getAuthStatus` / `getManifest`:内部 `fetch` + 校验,非 2xx、响应体不合法或校验失败一律返回 `null`(含义是「这个 origin 不是 DSH Mobile 宿主」)。+* `src-native/apis/index.types.ts` 是宿主 HTTP 契约的类型 SSOT(`BridgeManifest`、路径参数类型)。+* `src-native/apis/index.ts` 提供 `getManifest`:内部 `fetch` + 校验,非 2xx、响应体不合法或校验失败一律返回 `null`(未能确认这个 origin 的 DSH 服务身份)。* `src-native/utils/bridge-protocol.ts` 以 **type-only** 方式引用这些类型,避免协议工具与访问层耦合。---@@ -98,7 +98,8 @@ src-native/* **主动发现**由用户操作触发:点击「自动扫描局域网」,或断开连接后紧接的那轮扫描。* 探测成功由可信 DSH 文档就绪消息确认,不以原生 `onLoad` 或 HTTP 200 判定。* 超时与预算集中在 `src-native/config/constants.ts`:默认端口 `3088` / `3080`、并发 40、单次探测 600 ms、历史探测 3 s、整体扫描预算 20 s、前台健康检查间隔 15 s。-* 服务识别走上游公开的 `/__dsh_bridge__/auth-status`,旧响应缺少身份字段时再校验 `/manifest.webmanifest`;不把任意 HTML 200 当作 DSH 服务。+* 服务识别与健康检查只请求上游真实公开的 `/manifest.webmanifest`,严格校验 `name: 'DeepSeek Harness'` 与 `short_name: 'DSH'`;不请求不存在的认证状态端点,也不把任意 HTML 200 当作 DSH 服务。+* 服务识别不代表登录成功。需要认证的主机由 WebView 完成配对,只有可信文档就绪消息才能确认连接成功;健康检查不读取或重放配对码。* 探测与扫描拆成两个模块:`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。@@ -131,7 +132,8 @@ 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;外站顶层链接交由外部浏览器打开。-* 密码登录保留在 WebView 内由 cookie jar 管理,**不**通过 RN `fetch` 登录。+* 配对登录与会话保留在 WebView 内由 cookie jar 管理,**不**通过 RN `fetch` 登录。远程访问不再生成、保存或接受访问密码;SSH 密码与密钥口令不受影响。+* 网关仅允许无凭据读取静态 `/manifest.webmanifest`,不为探测铸造上游会话。该例外只接受 `GET` / `HEAD`,拒绝跨源浏览器请求,不放行应用页面、API 或 WebSocket。* 上游没有独立的远程推送端点:系统挂起、进程被杀或关闭 App 后**不保证**继续收到新任务通知。---diff --git a/packages/dsh-tauri-remote/src/client/apis/index.type.ts b/packages/dsh-tauri-remote/src/client/apis/index.type.tsindex 68e871c1..ca0ad6a5 100644--- a/packages/dsh-tauri-remote/src/client/apis/index.type.ts+++ b/packages/dsh-tauri-remote/src/client/apis/index.type.ts@@ -25,7 +25,7 @@ export type GetApiTauriRemoteAccessResponse = {listening: false | true;listen: { address: string; port: number };port: number;- auth: { enabled: false | true; scope: "public_only" | "all"; hasPassword?: false | true; hasToken?: false | true; token?: string };+ auth: { enabled: false | true; scope: "public_only" | "all"; hasToken?: false | true; token?: string };addresses: { address: string; family: "ipv4" | "ipv6"; interface: string; scope: "loopback" | "private" | "public" | "link-local"; score: number; recommended: false | true }[];recommended?: string;link?: string;@@ -33,7 +33,6 @@ export type GetApiTauriRemoteAccessResponse = {qr?: string;linkSource?: "loopback" | "lan";pairing?: { code: string; expiresAt: number; usedSeq: number; link?: string; qr?: string; tunnelLink?: string; tunnelQr?: string };- generatedPassword?: string;tunnel?: { state: "error" | "starting" | "stopped" | "running"; events: { seq: number; ts: string; kind: "state" | "process" | "progress"; line: string }[]; token?: string; url?: string; port?: number; link?: string; qr?: string; progress?: { stage: "ready" | "spawn" | "download" | "verify" | "check" | "extract" | "domain"; url?: string; received?: number; total?: number }; error?: string; mode: "quick" | "token"; enabled: false | true; hostname: null | string };localPort?: number;error?: string;@@ -49,7 +48,7 @@ export type PostApiTauriRemoteAccessResponse =listening: false | true;listen: { address: string; port: number };port: number;- auth: { enabled: false | true; scope: "public_only" | "all"; hasPassword?: false | true; hasToken?: false | true; token?: string };+ auth: { enabled: false | true; scope: "public_only" | "all"; hasToken?: false | true; token?: string };addresses: { address: string; family: "ipv4" | "ipv6"; interface: string; scope: "loopback" | "private" | "public" | "link-local"; score: number; recommended: false | true }[];recommended?: string;link?: string;@@ -57,7 +56,6 @@ export type PostApiTauriRemoteAccessResponse =qr?: string;linkSource?: "loopback" | "lan";pairing?: { code: string; expiresAt: number; usedSeq: number; link?: string; qr?: string; tunnelLink?: string; tunnelQr?: string };- generatedPassword?: string;tunnel?: { state: "error" | "starting" | "stopped" | "running"; events: { seq: number; ts: string; kind: "state" | "process" | "progress"; line: string }[]; token?: string; url?: string; port?: number; link?: string; qr?: string; progress?: { stage: "ready" | "spawn" | "download" | "verify" | "check" | "extract" | "domain"; url?: string; received?: number; total?: number }; error?: string; mode: "quick" | "token"; enabled: false | true; hostname: null | string };localPort?: number;error?: string;@@ -73,7 +71,7 @@ export type PostApiTauriRemoteAccessTunnelResponse =listening: false | true;listen: { address: string; port: number };port: number;- auth: { enabled: false | true; scope: "public_only" | "all"; hasPassword?: false | true; hasToken?: false | true; token?: string };+ auth: { enabled: false | true; scope: "public_only" | "all"; hasToken?: false | true; token?: string };addresses: { address: string; family: "ipv4" | "ipv6"; interface: string; scope: "loopback" | "private" | "public" | "link-local"; score: number; recommended: false | true }[];recommended?: string;link?: string;@@ -81,7 +79,6 @@ export type PostApiTauriRemoteAccessTunnelResponse =qr?: string;linkSource?: "loopback" | "lan";pairing?: { code: string; expiresAt: number; usedSeq: number; link?: string; qr?: string; tunnelLink?: string; tunnelQr?: string };- generatedPassword?: string;tunnel?: { state: "error" | "starting" | "stopped" | "running"; events: { seq: number; ts: string; kind: "state" | "process" | "progress"; line: string }[]; token?: string; url?: string; port?: number; link?: string; qr?: string; progress?: { stage: "ready" | "spawn" | "download" | "verify" | "check" | "extract" | "domain"; url?: string; received?: number; total?: number }; error?: string; mode: "quick" | "token"; enabled: false | true; hostname: null | string };localPort?: number;error?: string;@@ -97,7 +94,7 @@ export type DeleteApiTauriRemoteAccessTunnelResponse =listening: false | true;listen: { address: string; port: number };port: number;- auth: { enabled: false | true; scope: "public_only" | "all"; hasPassword?: false | true; hasToken?: false | true; token?: string };+ auth: { enabled: false | true; scope: "public_only" | "all"; hasToken?: false | true; token?: string };addresses: { address: string; family: "ipv4" | "ipv6"; interface: string; scope: "loopback" | "private" | "public" | "link-local"; score: number; recommended: false | true }[];recommended?: string;link?: string;@@ -105,7 +102,6 @@ export type DeleteApiTauriRemoteAccessTunnelResponse =qr?: string;linkSource?: "loopback" | "lan";pairing?: { code: string; expiresAt: number; usedSeq: number; link?: string; qr?: string; tunnelLink?: string; tunnelQr?: string };- generatedPassword?: string;tunnel?: { state: "error" | "starting" | "stopped" | "running"; events: { seq: number; ts: string; kind: "state" | "process" | "progress"; line: string }[]; token?: string; url?: string; port?: number; link?: string; qr?: string; progress?: { stage: "ready" | "spawn" | "download" | "verify" | "check" | "extract" | "domain"; url?: string; received?: number; total?: number }; error?: string; mode: "quick" | "token"; enabled: false | true; hostname: null | string };localPort?: number;error?: string;@@ -148,7 +144,6 @@ export interface PostApiTauriRemoteAccessBody {port?: number;authEnabled?: false | true;scope?: "public_only" | "all";- password?: null | string;}export interface PostApiTauriRemoteAccessTunnelBody {mode?: "quick" | "token";diff --git a/packages/dsh-tauri-remote/src/client/components/access-section.test.tsx b/packages/dsh-tauri-remote/src/client/components/access-section.test.tsxindex d50aa2f1..b5446f3c 100644--- a/packages/dsh-tauri-remote/src/client/components/access-section.test.tsx+++ b/packages/dsh-tauri-remote/src/client/components/access-section.test.tsx@@ -41,7 +41,7 @@ const REMOVED = []function authPayload(overrides: Record<string, unknown> = {}): Record<string, unknown> {- return { enabled: true, scope: 'all', hasPassword: false, hasToken: true, ...overrides }+ return { enabled: true, scope: 'all', hasToken: true, ...overrides }}function tunnelPayload(overrides: Record<string, unknown> = {}): Record<string, unknown> {@@ -99,6 +99,8 @@ beforeEach(() => {afterEach(() => {cleanup()+ vi.restoreAllMocks()+ vi.useRealTimers()})describe('接入面板', () => {@@ -290,17 +292,30 @@ describe('接入面板', () => {expect(screen.queryByText(en['access.tunnel.progress.ready'])).toBeNull()})- it('隧道启动期按阶段显示进度:下载阶段带百分比', async () => {+ it('下载阶段只显示带百分比的下载进度,不叠加隧道启动中', async () => {route = () => replies.ok(statusPayload({tunnel: tunnelPayload({ enabled: true, state: 'starting', progress: { stage: 'download', url: 'https://github.com/cloudflare/cloudflared/releases/latest/download/cloudflared-darwin-arm64.tgz', received: 3_200_000, total: 6_400_000 } }),}))render(<AccessSection t={t} />)await screen.findByTestId('access-tunnel-progress')expect(screen.getByTestId('access-tunnel-progress-line').textContent).toBe(`${en['access.tunnel.progress.download']} 50%`)+ expect(screen.queryByText(en['access.tunnel.state.starting'])).toBeNull()expect(screen.queryByTestId('state-dot')).toBeNull()expect(screen.getByTestId('access-tunnel-progress-bar').querySelector('div')?.getAttribute('style')).toContain('width: 50%')})+ it('非下载阶段只显示单一启动文案,不展示下载进度条', async () => {+ route = () => replies.ok(statusPayload({+ tunnel: tunnelPayload({ enabled: true, state: 'starting', progress: { stage: 'spawn', received: 6_400_000, total: 6_400_000 } }),+ }))+ render(<AccessSection t={t} />)+ const state = await screen.findByTestId('access-tunnel-state')+ expect(state.textContent).toBe(en['access.tunnel.state.starting'])+ expect(screen.getAllByText(en['access.tunnel.state.starting'])).toHaveLength(1)+ expect(screen.queryByTestId('access-tunnel-progress')).toBeNull()+ expect(screen.queryByTestId('access-tunnel-progress-bar')).toBeNull()+ })+it('隧道失败时错误、重试与停止都可见', async () => {route = () => replies.ok(statusPayload({tunnel: tunnelPayload({ enabled: true, state: 'error', error: 'cloudflared 下载失败(已尝试:https://…)' }),diff --git a/packages/dsh-tauri-remote/src/client/components/access-section.tsx b/packages/dsh-tauri-remote/src/client/components/access-section.tsxindex 6a09a405..3d919b2b 100644--- a/packages/dsh-tauri-remote/src/client/components/access-section.tsx+++ b/packages/dsh-tauri-remote/src/client/components/access-section.tsx@@ -120,6 +120,7 @@ export function AccessSection({ t }: AccessSectionProps): ReactElement {const token = status.auth.tokenconst pairing = status.pairingconst countdown = pairing === undefined ? '' : countdownOf(pairing.expiresAt, now)+ const downloading = tunnel.state === 'starting' && tunnel.progress?.stage === 'download'const progressPercent = tunnel.progress === undefined ? null : progressPercentOf(tunnel.progress)async function setExposure(next: boolean): Promise<void> {@@ -270,10 +271,14 @@ export function AccessSection({ t }: AccessSectionProps): ReactElement {: null}<Row title={t('access.tunnel.state')}><div className="flex flex-none items-center gap-[8px]" data-testid="access-tunnel-actions">- <span className="inline-flex items-center gap-[6px] text-[12px] leading-[18px] text-secondary" data-testid="access-tunnel-state">- {tunnelKeyOf(tunnel) === 'access.tunnel.state.running' ? <StateDot state="done" size={6} /> : null}- {t(tunnelKeyOf(tunnel))}- </span>+ {downloading+ ? null+ : (+ <span className="inline-flex items-center gap-[6px] text-[12px] leading-[18px] text-secondary" data-testid="access-tunnel-state">+ {tunnelKeyOf(tunnel) === 'access.tunnel.state.running' ? <StateDot state="done" size={6} /> : null}+ {t(tunnelKeyOf(tunnel))}+ </span>+ )}{dirtyTunnel? (<>@@ -291,7 +296,7 @@ export function AccessSection({ t }: AccessSectionProps): ReactElement {)}</div></Row>- {tunnel.progress === undefined || tunnelKeyOf(tunnel) === 'access.tunnel.state.running'+ {!downloading || tunnel.progress === undefined? null: (<div className="flex flex-col gap-[6px] pt-[12px] pb-[12px]" data-testid="access-tunnel-progress">diff --git a/packages/dsh-tauri-remote/src/client/register/poll.test.ts b/packages/dsh-tauri-remote/src/client/register/poll.test.tsindex 3273eee3..1449cfbe 100644--- a/packages/dsh-tauri-remote/src/client/register/poll.test.ts+++ b/packages/dsh-tauri-remote/src/client/register/poll.test.ts@@ -1,7 +1,8 @@import type { ClientContext } from 'dsh-tauri/client'-import type { MachineRow } from '../types/index'+import type { AccessStatus, MachineRow } from '../types/index'import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'+import * as accessService from '../service/access'import { store } from '../store/index'import { answer, replies, resetWire, sent } from '../test-utils/client-mock'import { pollFeature } from './poll'@@ -29,12 +30,14 @@ beforeEach(() => {resetWire()store.machines.reset()store.sync.reset()+ store.access.reset()answer(call => call.url === `${baseURL}/machines`? replies.ok({ items: [{ ...machineA, state: 'connecting', progress: { phase: 'handshake' } }] }): replies.ok({ items: [] }))})afterEach(() => {+ vi.restoreAllMocks()vi.useRealTimers()})@@ -77,6 +80,75 @@ describe('pollFeature', () => {stop()})+ it('polls access during the first long tunnel mutation even when the saved snapshot is still stopped', async () => {+ vi.useFakeTimers()+ const mutation = Promise.withResolvers<ReturnType<typeof replies.ok>>()+ const downloading = { enabled: true, tunnel: { enabled: true, mode: 'quick', state: 'starting', progress: { stage: 'download', received: 1, total: 2 } } }+ answer(call => call.http === 'POST' ? mutation.promise : replies.ok(downloading))+ store.access.snapshot = {+ version: 1,+ enabled: false,+ state: 'stopped',+ listening: false,+ listen: { address: '127.0.0.1', port: 3088 },+ port: 3088,+ auth: { enabled: true, scope: 'all' },+ addresses: [],+ events: [],+ tunnel: { enabled: false, mode: 'quick', hostname: null, state: 'stopped', events: [] },+ }+ const stop = pollFeature.call({} as unknown as ClientContext)+ const pending = accessService.startTunnel({ mode: 'quick' })+ try {+ await vi.advanceTimersByTimeAsync(MACHINES_INTERVAL_MS)+ expect(sent.map(call => [call.http, call.url])).toEqual([+ ['POST', `${baseURL}/access/tunnel`],+ ['GET', `${baseURL}/access`],+ ])+ expect(store.access.busy).toBe(true)+ expect(store.access.snapshot?.tunnel.progress).toEqual({ stage: 'download', received: 1, total: 2 })+ mutation.resolve(replies.ok(downloading))+ await pending+ }+ finally {+ stop()+ mutation.resolve(replies.ok(downloading))+ await pending+ }+ })++ it('polls starting tunnels while busy and stops access polling when ready', async () => {+ vi.useFakeTimers()+ const snapshot: AccessStatus = {+ version: 1,+ enabled: false,+ state: 'stopped',+ listening: false,+ listen: { address: '127.0.0.1', port: 3088 },+ port: 3088,+ auth: { enabled: true, scope: 'all' },+ addresses: [],+ events: [],+ tunnel: { enabled: true, mode: 'quick', hostname: null, state: 'starting', events: [], progress: { stage: 'download', received: 1, total: 2 } },+ }+ store.access.commit(snapshot)+ store.access.beginBusy()+ answer(() => replies.ok(snapshot))+ const stop = pollFeature.call({} as unknown as ClientContext)+ try {+ await vi.advanceTimersByTimeAsync(MACHINES_INTERVAL_MS)+ expect(urls()).toEqual([`${baseURL}/access`])+ expect(store.access.busy).toBe(true)+ store.access.endBusy()+ store.access.commit({ ...snapshot, tunnel: { ...snapshot.tunnel, state: 'running' } })+ await vi.advanceTimersByTimeAsync(MACHINES_INTERVAL_MS * 2)+ expect(urls()).toEqual([`${baseURL}/access`])+ }+ finally {+ stop()+ }+ })+it('disposes the interval when the feature unloads', async () => {vi.useFakeTimers()const stop = pollFeature.call({} as unknown as ClientContext)diff --git a/packages/dsh-tauri-remote/src/client/register/poll.ts b/packages/dsh-tauri-remote/src/client/register/poll.tsindex ee76487d..df98e360 100644--- a/packages/dsh-tauri-remote/src/client/register/poll.ts+++ b/packages/dsh-tauri-remote/src/client/register/poll.ts@@ -13,17 +13,15 @@ function machinesInFlight(): boolean {return Object.values(store.machines.statuses).some(status => ACTIVE_STATES.includes(status.state))}-/** 隧道从启动到拿到公网域名之间只有事件在动,面板需要跟着刷新;其余时刻靠操作回包更新。 */-function tunnelStarting(): boolean {- const snapshot = store.access.snapshot- return snapshot !== null && !store.access.busy && snapshot.tunnel.state === 'starting'+function accessInFlight(): boolean {+ return store.access.busy || store.access.snapshot?.tunnel.state === 'starting'}export const pollFeature = defineRegister((controller) => {controller.interval(() => {if (controller.isDisposed())return- if (tunnelStarting())+ if (accessInFlight())void refreshAccess()if (machinesInFlight() || store.sync.applying)void poll()diff --git a/packages/dsh-tauri-remote/src/client/service/access.test.ts b/packages/dsh-tauri-remote/src/client/service/access.test.tsindex 78e87145..870fc7a7 100644--- a/packages/dsh-tauri-remote/src/client/service/access.test.ts+++ b/packages/dsh-tauri-remote/src/client/service/access.test.ts@@ -1,5 +1,5 @@import type { WireCall, WireReply } from '../test-utils/client-mock'-import { beforeEach, describe, expect, it, vi } from 'vitest'+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'import { store } from '../store/index'import { answer, replies, resetWire, sent } from '../test-utils/client-mock'import * as service from './access'@@ -9,7 +9,7 @@ vi.mock('dsh-tauri/client', async () => (await import('../test-utils/client-mockconst BASE = '/api/tauri/remote/access'let queued: WireReply[] = []-let route: (call: WireCall) => WireReply = () => replies.ok({})+let route: (call: WireCall) => WireReply | Promise<WireReply> = () => replies.ok({})function once(...next: WireReply[]): void {queued.push(...next)@@ -23,6 +23,14 @@ beforeEach(() => {answer(call => queued.shift() ?? route(call))})+afterEach(() => {+ vi.restoreAllMocks()+})++const DOWNLOADING = { enabled: true, tunnel: { enabled: true, mode: 'quick', state: 'starting', progress: { stage: 'download', received: 1, total: 2 } } }++const RUNNING = { enabled: true, tunnel: { enabled: true, mode: 'quick', state: 'running' } }+describe('接入面板数据层', () => {it('回包缺字段时按默认值收敛,绝不抛错', async () => {route = () => replies.ok({ state: 'listening', listening: true })@@ -80,15 +88,111 @@ describe('接入面板数据层', () => {})it('变更失败时保留错误文案并复位 busy', async () => {- once(replies.ok({}), replies.fail('访问密码太短', 400))+ once(replies.ok({}), replies.fail('监听地址不可用', 400))await service.load()- const result = await service.apply({ password: 'x' })- expect(result.ok).toBe(false)- expect(result.error).toContain('访问密码太短')+ const result = await service.apply({ address: 'missing' })+ expect(result).toEqual({ ok: false, error: '请求失败 (400): 监听地址不可用' })expect(store.access.status).toBe('error')expect(store.access.busy).toBe(false)})+ it('旧回包的访问密码字段被丢弃,配对码和永久码不受影响', async () => {+ route = () => replies.ok({+ auth: { enabled: true, scope: 'all', hasPassword: true, hasToken: true, token: '01234567' },+ generatedPassword: 'legacy-secret',+ pairing: { code: 'AB23CD45', expiresAt: 300000 },+ })+ await service.load()++ expect(store.access.snapshot?.auth).toEqual({ enabled: true, scope: 'all', hasToken: true, token: '01234567' })+ expect(store.access.snapshot).not.toHaveProperty('generatedPassword')+ expect(store.access.snapshot?.pairing).toEqual({ code: 'AB23CD45', expiresAt: 300000 })+ })++ it('get 乱序返回时旧 stopped 快照不能覆盖已提交的下载进度', async () => {+ const older = Promise.withResolvers<WireReply>()+ const newer = Promise.withResolvers<WireReply>()+ let reads = 0+ route = () => (++reads === 1 ? older.promise : newer.promise)+ const first = service.refresh()+ const second = service.refresh()+ newer.resolve(replies.ok(DOWNLOADING))+ await second+ expect(store.access.snapshot?.tunnel.progress).toEqual({ stage: 'download', received: 1, total: 2 })+ older.resolve(replies.ok({}))+ await first+ expect(store.access.snapshot?.tunnel.progress).toEqual({ stage: 'download', received: 1, total: 2 })+ })++ it('get 乱序失败时不抹掉较新进度或新增旧错误', async () => {+ const older = Promise.withResolvers<WireReply>()+ const newer = Promise.withResolvers<WireReply>()+ let reads = 0+ route = () => (++reads === 1 ? older.promise : newer.promise)+ const first = service.refresh()+ const second = service.refresh()+ newer.resolve(replies.ok(DOWNLOADING))+ await second+ older.resolve(replies.fail('stale failure'))+ await first+ expect(store.access.status).toBe('ready')+ expect(store.access.error).toBeNull()+ expect(store.access.snapshot?.tunnel.progress).toEqual({ stage: 'download', received: 1, total: 2 })+ })++ it('长启动回包较旧时保留期间轮询进度并释放 busy', async () => {+ const mutation = Promise.withResolvers<WireReply>()+ route = call => call.http === 'POST' ? mutation.promise : replies.ok(DOWNLOADING)+ const pending = service.startTunnel({ mode: 'quick' })+ await service.refresh()+ expect(store.access.busy).toBe(true)+ expect(store.access.snapshot?.tunnel.progress).toEqual({ stage: 'download', received: 1, total: 2 })++ mutation.resolve(replies.ok({}))+ await expect(pending).resolves.toEqual({ ok: true })+ expect(store.access.snapshot?.tunnel.progress).toEqual({ stage: 'download', received: 1, total: 2 })+ expect(store.access.busy).toBe(false)+ })++ it('长启动完成后读取权威最终状态,不停留于期间的下载进度', async () => {+ const mutation = Promise.withResolvers<WireReply>()+ let current: unknown = DOWNLOADING+ route = call => call.http === 'POST' ? mutation.promise : replies.ok(current)+ const pending = service.startTunnel({ mode: 'quick' })+ await service.refresh()+ expect(store.access.snapshot?.tunnel.state).toBe('starting')+ current = RUNNING+ mutation.resolve(replies.ok(RUNNING))+ await pending+ expect(store.access.snapshot?.tunnel.state).toBe('running')+ expect(store.access.busy).toBe(false)+ })++ it('启动完成后迟到的 GET 不能覆盖动作最终快照', async () => {+ const mutation = Promise.withResolvers<WireReply>()+ const poll = Promise.withResolvers<WireReply>()+ route = call => call.http === 'POST' ? mutation.promise : poll.promise+ const pending = service.startTunnel({ mode: 'quick' })+ const reading = service.refresh()+ mutation.resolve(replies.ok(RUNNING))+ await pending+ expect(store.access.snapshot?.tunnel.state).toBe('running')+ poll.resolve(replies.ok(DOWNLOADING))+ await reading+ expect(store.access.snapshot?.tunnel.state).toBe('running')+ })++ it('动作失败仍保留自身错误,期间 polling 不遮蔽失败且 busy 复位', async () => {+ const mutation = Promise.withResolvers<WireReply>()+ route = call => call.http === 'POST' ? mutation.promise : replies.ok(DOWNLOADING)+ const pending = service.startTunnel({ mode: 'quick' })+ await service.refresh()+ mutation.resolve(replies.fail('download denied'))+ await expect(pending).resolves.toEqual({ ok: false, error: '请求失败 (400): download denied' })+ expect(store.access.error).toBe('请求失败 (400): download denied')+ expect(store.access.busy).toBe(false)+ })+it('隧道启停走面板专用路由并提交回包', async () => {once(replies.ok({}),diff --git a/packages/dsh-tauri-remote/src/client/service/access.ts b/packages/dsh-tauri-remote/src/client/service/access.tsindex 20712281..954eeb33 100644--- a/packages/dsh-tauri-remote/src/client/service/access.ts+++ b/packages/dsh-tauri-remote/src/client/service/access.ts@@ -14,25 +14,18 @@ const TUNNEL_PROGRESS_STAGES: readonly TunnelProgressStage[] = ['check', 'downloconst EMPTY_TUNNEL: AccessTunnel = { enabled: false, mode: 'quick', hostname: null, state: 'stopped', events: [] }-let requests = 0-let lastSaved = 0-export async function load(): Promise<void> {store.access.beginLoad()await refresh()}-/** 轮询用:不改状态机的 loading 档,避免面板在后台刷新时闪回加载态。 */export async function refresh(): Promise<void> {- const mine = ++requests+ const mine = store.access.beginRequest()try {- const next = accessStatusOf(await request<unknown>(BASE, { method: 'get' }))- if (mine >= lastSaved)- store.access.commit(next)+ store.access.commit(accessStatusOf(await request<unknown>(BASE, { method: 'get' })), mine)}catch (error) {- if (mine >= lastSaved)- store.access.fail(messageOf(error))+ store.access.fail(messageOf(error), mine)}}@@ -56,18 +49,22 @@ export async function stopTunnel(): Promise<ServiceResult> {return await mutate(async () => await request<unknown>(`${BASE}/tunnel`, { method: 'delete' }))}-// --- internal ---async function mutate(run: () => Promise<unknown>): Promise<ServiceResult> {- const mine = ++requests+ const mine = store.access.invalidateRequests()store.access.beginBusy()try {const next = accessStatusOf(await run())- lastSaved = Math.max(lastSaved, mine)- store.access.commit(next)+ const refreshed = store.access.savedSeq > mine+ store.access.invalidateRequests()+ if (refreshed)+ await refresh()+ else+ store.access.commit(next)return { ok: true }}catch (error) {const message = messageOf(error)+ store.access.invalidateRequests()store.access.fail(message)return { ok: false, error: message }}@@ -93,7 +90,6 @@ function accessStatusOf(value: unknown): AccessStatus {events: listOf(raw.events).map(eventOf).filter(entry => entry !== undefined),...textField('recommended', raw.recommended),...linkSourceField(raw.linkSource),- ...textField('generatedPassword', raw.generatedPassword),...textField('link', raw.link),...textField('maskLink', raw.maskLink),...textField('qr', raw.qr),@@ -128,7 +124,6 @@ function authOf(value: unknown): AccessStatus['auth'] {return {enabled: booleanOf(raw.enabled) ?? false,scope: scopeOf(raw.scope) ?? 'public_only',- ...booleanField('hasPassword', raw.hasPassword),...booleanField('hasToken', raw.hasToken),...textField('token', raw.token),}diff --git a/packages/dsh-tauri-remote/src/client/store/modules/access.ts b/packages/dsh-tauri-remote/src/client/store/modules/access.tsindex 42547c4f..540a0a9b 100644--- a/packages/dsh-tauri-remote/src/client/store/modules/access.ts+++ b/packages/dsh-tauri-remote/src/client/store/modules/access.ts@@ -7,6 +7,8 @@ function initialState(): AccessViewState {status: 'idle',error: null,busy: false,+ requestSeq: 0,+ savedSeq: 0,snapshot: null,}}@@ -15,18 +17,34 @@ export const access = defineStore({state: (): AccessViewState => initialState(),actions: {reset(): void {- Object.assign(this, initialState())+ const seq = this.requestSeq + 1+ Object.assign(this, initialState(), { requestSeq: seq, savedSeq: seq })+ },+ beginRequest(): number {+ return ++this.requestSeq+ },+ invalidateRequests(): number {+ this.savedSeq = ++this.requestSeq+ return this.savedSeq},beginLoad(): void {this.status = 'loading'this.error = null},- commit(snapshot: AccessStatus): void {+ commit(snapshot: AccessStatus, seq?: number): void {+ const savedSeq = seq ?? this.requestSeq+ if (savedSeq < this.savedSeq)+ return+ this.savedSeq = savedSeqthis.snapshot = snapshotthis.status = 'ready'this.error = null},- fail(message: string): void {+ fail(message: string, seq?: number): void {+ const savedSeq = seq ?? this.requestSeq+ if (savedSeq < this.savedSeq)+ return+ this.savedSeq = savedSeqthis.status = 'error'this.error = message},diff --git a/packages/dsh-tauri-remote/src/client/store/modules/access.types.ts b/packages/dsh-tauri-remote/src/client/store/modules/access.types.tsindex 404f3cc5..e91b065e 100644--- a/packages/dsh-tauri-remote/src/client/store/modules/access.types.ts+++ b/packages/dsh-tauri-remote/src/client/store/modules/access.types.ts@@ -6,5 +6,7 @@ export interface AccessViewState {status: AccessLoadStatuserror: string | nullbusy: boolean+ requestSeq: number+ savedSeq: numbersnapshot: AccessStatus | null}diff --git a/packages/dsh-tauri-remote/src/client/types/index.ts b/packages/dsh-tauri-remote/src/client/types/index.tsindex 73f3289e..5fbb0611 100644--- a/packages/dsh-tauri-remote/src/client/types/index.ts+++ b/packages/dsh-tauri-remote/src/client/types/index.ts@@ -177,7 +177,7 @@ export interface AccessStatus {listening: booleanlisten: { address: string, port: number }port: number- auth: { enabled: boolean, scope: AccessScope, hasPassword?: boolean, hasToken?: boolean, token?: string }+ auth: { enabled: boolean, scope: AccessScope, hasToken?: boolean, token?: string }addresses: readonly AccessAddress[]recommended?: stringlink?: string@@ -185,7 +185,6 @@ export interface AccessStatus {qr?: stringlinkSource?: AccessLinkSourcepairing?: AccessPairing- generatedPassword?: stringtunnel: AccessTunnellocalPort?: numbererror?: string@@ -199,8 +198,6 @@ export interface AccessBody {port?: numberauthEnabled?: booleanscope?: AccessScope- /** `null` 表示清除已设密码。 */- password?: string | null}export interface TunnelBody {diff --git a/packages/dsh-tauri-remote/src/host/server/routes/access/tunnel/post.ts b/packages/dsh-tauri-remote/src/host/server/routes/access/tunnel/post.tsindex 187ff89f..5fb03f93 100644--- a/packages/dsh-tauri-remote/src/host/server/routes/access/tunnel/post.ts+++ b/packages/dsh-tauri-remote/src/host/server/routes/access/tunnel/post.ts@@ -14,10 +14,9 @@ export default defineEventHandler<EventHandlerRequest, Promise<RemoteAccessStatuconst credential = textOf(body.token, 'token')const host = textOf(body.hostname, 'hostname')tunnel.assertStartable(mode, credential, host)- const ensured = await access.ensureAuth()+ await access.ensureAuth()await tunnel.start(mode, credential, host)- const status = await access.status()- return ensured.generatedPassword === undefined ? status : { ...status, generatedPassword: ensured.generatedPassword }+ return await access.status()})})diff --git a/packages/dsh-tauri-remote/src/host/service/access.test.ts b/packages/dsh-tauri-remote/src/host/service/access.test.tsindex 86a71739..eb29762e 100644--- a/packages/dsh-tauri-remote/src/host/service/access.test.ts+++ b/packages/dsh-tauri-remote/src/host/service/access.test.ts@@ -11,7 +11,6 @@ import { toDataURL } from 'qrcode'import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'import { ensureSourceSession, setCurrentHostInstance } from '../config/runtime'import { server as remoteServer } from '../server'-import { verifyPassword } from '../utils/auth'import { access } from './access'import { defaultAccessDocument, enumerateAddresses, isReachableAddress, readAccessDocument, writeAccessDocument } from './access.utils'import { gateway } from './gateway'@@ -103,8 +102,8 @@ function call(port: number, path: string, options: { source?: string, cookie?: s})}-function signIn(port: number, password: string): Promise<Reply> {- return call(port, '/', { source: 'public', method: 'POST', form: `password=${encodeURIComponent(password)}` })+function signIn(port: number, code: string): Promise<Reply> {+ return call(port, '/', { source: 'public', method: 'POST', form: `code=${encodeURIComponent(code)}` })}function freePort(): Promise<number> {@@ -243,6 +242,26 @@ async function enable(address = '127.0.0.1', port?: number): Promise<RemoteAcces}describe('access 监听生命周期', () => {+ it('开启暴露仅使用配对码,不生成或保存访问密码', async () => {+ const status = await enable()+ expect(status.auth.enabled).toBe(true)+ expect(status.pairing?.code).toMatch(/^[2-9A-HJ-NP-Z]{8}$/u)+ expect(status).not.toHaveProperty('generatedPassword')+ expect(status.auth).not.toHaveProperty('hasPassword')+ expect(storedDocument().auth).toEqual({ enabled: true, token: null, scope: 'public_only' })+ })++ it('隧道前置认证仅使用配对码,重复调用不生成永久凭据', async () => {+ const status = await access.ensureAuth()+ expect(status.auth.enabled).toBe(true)+ expect(status).not.toHaveProperty('generatedPassword')+ expect(status.auth).not.toHaveProperty('hasPassword')+ expect(storedDocument().auth).toEqual({ enabled: true, token: null, scope: 'public_only' })+ const code = access.policy().pairingCode+ await access.ensureAuth()+ expect(access.policy().pairingCode).toBe(code)+ })+it('apply 开启回环监听后网关真实转发到本机 DSH 上游并注入原生 cookie', async () => {const status = await enable()expect(status.listening).toBe(true)@@ -265,28 +284,14 @@ describe('access 监听生命周期', () => {expect(status.maskLink).toBe(`http://127.0.0.1:${status.port}/`)})- it('开启暴露时没有凭据就自动生成随机强密码并自动开认证', async () => {- const status = await enable()- expect(status.generatedPassword).toMatch(/^[2-9A-HJ-NP-Za-km-z]{20}$/u)- expect(status.auth.enabled).toBe(true)- expect(status.auth.hasPassword).toBe(true)- expect(JSON.stringify(storedDocument())).not.toContain(status.generatedPassword ?? '')- expect((await access.status()).generatedPassword).toBeUndefined()- })-- it('已有凭据时不覆盖,且不把明文写进事件环', async () => {- await access.apply({ password: 'keep-me-please' })+ it('启用暴露保留已有链接 Token,不把凭据写进事件环', async () => {+ await access.rotate()+ const token = storedDocument().auth.token+ expect(token).toBeTruthy()const status = await enable()- expect(status.generatedPassword).toBeUndefined()- expect(status.auth.hasPassword).toBe(true)- expect(status.events.map(event => event.line).join('\n')).not.toContain('keep-me-please')- })-- it('ensureAuth 为隧道补齐认证:无凭据时生成、已有密码时只开开关', async () => {- const generated = await access.ensureAuth()- expect(generated.generatedPassword).toMatch(/^[2-9A-HJ-NP-Za-km-z]{20}$/u)- expect((await access.ensureAuth()).generatedPassword).toBeUndefined()- expect((await access.status()).auth.enabled).toBe(true)+ expect(status.auth.token).toBe(token)+ expect(storedDocument().auth.token).toBe(token)+ expect(status.events.map(event => event.line).join('\n')).not.toContain(token ?? '')})it('access.json 损坏时所有写操作拒绝,且不覆盖原文件', async () => {@@ -358,25 +363,15 @@ describe('access 监听生命周期', () => {expect(status.qr).toBe(await toDataURL(status.link ?? ''))})- it('暴露到非回环地址且没有凭据时自动生成密码,并在事件里写明', async () => {- const address = requireReachable()- const port = await freePort()- const status = await enable(address, port)- expect(status.state).toBe('listening')- expect(status.auth.hasPassword).toBe(true)- const notice = status.events.find(event => event.kind === 'auth')- expect(notice?.line).toContain('已自动生成随机强密码')- })-it('显式关掉认证再暴露时,仍对公网与隧道来源给出未配置引导', async () => {const address = requireReachable()const port = await freePort()- await access.apply({ password: 'explicit-close-pass', authEnabled: false, enabled: true, address, port })+ await access.apply({ authEnabled: false, enabled: true, address, port })const status = await access.status()expect(status.state).toBe('listening')expect(status.auth.enabled).toBe(false)const warning = status.events.find(event => event.kind === 'auth')- expect(warning?.line).toContain('未配置访问密码或链接 Token')+ expect(warning?.line).toContain('未开启访问认证')})it('重启后按上次的 enabled 与监听配置自动恢复', async () => {@@ -389,9 +384,7 @@ describe('access 监听生命周期', () => {expect(restored.port).toBe(applied.port)expect(restored.link).toBe(applied.link)const stored = storedDocument()- expect({ ...stored, auth: { ...stored.auth, enabled: false, password: null } })- .toEqual({ ...defaultAccessDocument(), enabled: true, listen: { address: '127.0.0.1', port } })- expect(stored.auth.password).not.toBeNull()+ expect(stored).toEqual({ ...defaultAccessDocument(), enabled: true, listen: { address: '127.0.0.1', port }, auth: { enabled: true, token: null, scope: 'public_only' } })})it('恢复失败时保持关闭并给出可读原因,且不静默改写配置', async () => {@@ -540,9 +533,9 @@ describe('access 临时码消费与长轮询(真实路由和网关)', () =>})describe('access 认证与来源判定(经真实网关)', () => {- it('开启暴露即自动带凭据:私网免密放行,公网与隧道来源进入登录而非未配置引导', async () => {+ it('开启暴露即使用配对码:私网放行,公网与隧道来源进入配对而非未配置引导', async () => {const status = await enable()- expect(status.auth.hasPassword).toBe(true)+ expect(status.pairing?.code).toMatch(/^[2-9A-HJ-NP-Z]{8}$/u)expect((await call(status.port, '/api/probe', { source: 'private' })).status).toBe(200)const publicReply = await call(status.port, '/api/probe', { source: 'public' })expect(publicReply.status).toBe(401)@@ -557,13 +550,13 @@ describe('access 认证与来源判定(经真实网关)', () => {await access.apply({ authEnabled: false })const publicReply = await call(status.port, '/api/probe', { source: 'public' })expect(publicReply.status).toBe(403)- expect(publicReply.body).toContain('尚未配置访问认证')+ expect(publicReply.body).toContain('尚未启用配对认证')expect((await call(status.port, '/api/probe', { source: 'tunnel' })).status).toBe(403)})it('scope=public_only 时私网免密、公网要求认证;scope=all 时私网也要求认证', async () => {const status = await enable()- await access.apply({ authEnabled: true, password: 'hunter2', scope: 'public_only' })+ await access.apply({ authEnabled: true, scope: 'public_only' })expect((await call(status.port, '/api/probe', { source: 'private' })).status).toBe(200)expect((await call(status.port, '/api/probe', { source: 'public' })).status).toBe(401)await access.apply({ scope: 'all' })@@ -592,7 +585,7 @@ describe('access 认证与来源判定(经真实网关)', () => {it('作废 Token 后旧链接失效,已签发的会话不受影响', async () => {const status = await enable()- await access.apply({ authEnabled: true, password: 'hunter2', scope: 'public_only' })+ await access.apply({ authEnabled: true, scope: 'public_only' })const rotated = await access.rotate()const token = tokenOf(rotated.link)const exchanged = await call(status.port, `/?auth=${token}`, { source: 'public' })@@ -604,14 +597,14 @@ describe('access 认证与来源判定(经真实网关)', () => {expect((await call(status.port, '/api/probe', { source: 'public', cookie })).status).toBe(200)})- it('密码连续错误达阈值后封禁并返回可读剩余时间', async () => {+ it('配对码连续错误达阈值后封禁并返回可读剩余时间', async () => {const status = await enable()- await access.apply({ authEnabled: true, password: 'hunter2', scope: 'public_only' })+ await access.apply({ authEnabled: true, scope: 'public_only' })const attempts: number[] = []for (let index = 0; index < 5; index++)attempts.push((await signIn(status.port, 'wrong')).status)expect(attempts).toEqual([401, 401, 401, 401, 429])- const banned = await signIn(status.port, 'hunter2')+ const banned = await signIn(status.port, status.pairing?.code ?? '')expect(banned.status).toBe(429)expect(banned.body).toContain('认证失败次数过多')})@@ -625,15 +618,4 @@ describe('access 认证与来源判定(经真实网关)', () => {expect(status.events.map(event => event.line)).toContain('access.json 丢弃未知键 rogue')expect(Object.keys(JSON.parse(readFileSync(documentFile(), 'utf8')))).toEqual(['version', 'enabled', 'listen', 'auth', 'tunnel'])})-- it('密码只以哈希落盘且校验通过,明文不出现在配置文档里', async () => {- await access.apply({ password: 'hunter2' })- const password = storedDocument().auth.password- expect(password?.algo).toBe('pbkdf2-sha256')- expect(verifyPassword('hunter2', password)).toBe(true)- expect(readFileSync(documentFile(), 'utf8')).not.toContain('hunter2')- const cleared = await access.apply({ password: null })- expect(cleared.auth.hasPassword).toBe(false)- expect(storedDocument().auth.password).toBeNull()- })})diff --git a/packages/dsh-tauri-remote/src/host/service/access.ts b/packages/dsh-tauri-remote/src/host/service/access.tsindex 2e99038d..15d00649 100644--- a/packages/dsh-tauri-remote/src/host/service/access.ts+++ b/packages/dsh-tauri-remote/src/host/service/access.ts@@ -4,7 +4,7 @@ import { defineService } from 'dsh-tauri'import { toDataURL } from 'qrcode'import { messageOf } from '../../shared/error'import { hostServicePort, localUpstream, mintAuthenticatedUrl } from '../config/runtime'-import { createLinkToken, createSessionSecret, generateAccessPassword, hashPassword } from '../utils/auth'+import { createLinkToken, createSessionSecret } from '../utils/auth'import { isAuthConfigured } from '../utils/source'import { addressProblemOf, buildLink, buildTunnelLink, enumerateAddresses, isLoopbackListen, linkHostOf, maskLinkOf, pairingLinksOf, patchAccessDocument, policyOf, readAccessDocument, writeAccessDocument } from './access.utils'import { gateway } from './gateway'@@ -58,7 +58,6 @@ export const access = defineService({auth: {enabled: document.auth.enabled,scope: document.auth.scope,- hasPassword: document.auth.password !== null,hasToken: document.auth.token !== null,...document.auth.token === null ? {} : { token: document.auth.token },},@@ -94,26 +93,22 @@ export const access = defineService({throw new Error(CORRUPT_DOCUMENT)for (const warning of parsed.warnings)note('state', warning)- const patched = patchAccessDocument(parsed.document, body, enumerateAddresses())- const generatedPassword = patched.enabled ? autoPasswordOf(patched) : undefined- const next = generatedPassword === undefined ? patched : withGeneratedPassword(patched, generatedPassword)+ const next = patchAccessDocument(parsed.document, body, enumerateAddresses())+ if (body.enabled === true && body.authEnabled === undefined)+ next.auth.enabled = truewriteAccessDocument(next)await activate(next)- return { ...await access.status(), ...generatedPassword === undefined ? {} : { generatedPassword } }+ return await access.status()},- /** 公网隧道前置:认证未开则开;没有可用凭据则自动生成密码(返回明文供面板一次性展示)。 */async ensureAuth(): Promise<RemoteAccessStatus> {const parsed = readAccessDocument()if (parsed.corrupt)throw new Error(CORRUPT_DOCUMENT)- const generatedPassword = autoPasswordOf(parsed.document)- const next = generatedPassword === undefined- ? { ...parsed.document, auth: { ...parsed.document.auth, enabled: true } }- : withGeneratedPassword(parsed.document, generatedPassword)+ const next = { ...parsed.document, auth: { ...parsed.document.auth, enabled: true } }writeAccessDocument(next)await activate(next)- return { ...await access.status(), ...generatedPassword === undefined ? {} : { generatedPassword } }+ return await access.status()},async rotate(): Promise<RemoteAccessStatus> {@@ -158,18 +153,6 @@ export const access = defineService({},})-// --- internal ----/** 只在完全没有凭据时生成:已有密码或链接 Token 说明用户已做过选择,认证开关本身不再被改写。 */-function autoPasswordOf(document: RemoteAccessDocument): string | undefined {- const auth = document.auth- return auth.password === null && auth.token === null ? generateAccessPassword() : undefined-}--function withGeneratedPassword(document: RemoteAccessDocument, password: string): RemoteAccessDocument {- note('auth', '未设置访问密码:已自动生成随机强密码并开启访问认证(明文仅在面板显示一次)')- return { ...document, auth: { ...document.auth, enabled: true, password: hashPassword(password) } }-}-async function activate(document: RemoteAccessDocument): Promise<void> {if (!document.enabled) {await gateway.stop(ENTRY_ID)@@ -200,7 +183,7 @@ async function activate(document: RemoteAccessDocument): Promise<void> {failure = undefinednote('state', `入站暴露已监听 ${entry.host}:${entry.port}`)if (!isLoopbackListen(document.listen.address) && !isAuthConfigured(access.policy()))- note('auth', '未配置访问密码或链接 Token:公网与隧道来源将被 403 拒绝,私网来源可直连')+ note('auth', '未开启访问认证:公网与隧道来源将被 403 拒绝,私网来源可直连')}catch (error) {await fail(messageOf(error))diff --git a/packages/dsh-tauri-remote/src/host/service/access.types.ts b/packages/dsh-tauri-remote/src/host/service/access.types.tsindex 9456ec01..d60eeb8f 100644--- a/packages/dsh-tauri-remote/src/host/service/access.types.ts+++ b/packages/dsh-tauri-remote/src/host/service/access.types.ts@@ -1,4 +1,4 @@-import type { RemoteAuthScope, RemotePasswordRecord, RemoteTunnelConfig, RemoteTunnelStatus } from '../types/index'+import type { RemoteAuthScope, RemoteTunnelConfig, RemoteTunnelStatus } from '../types/index'export interface RemoteAccessListen {address: string@@ -7,7 +7,6 @@ export interface RemoteAccessListen {export interface RemoteAccessAuthDocument {enabled: boolean- password: RemotePasswordRecord | nulltoken: string | nullscope: RemoteAuthScope}@@ -20,14 +19,12 @@ export interface RemoteAccessDocument {tunnel: RemoteTunnelConfig}-/** `POST /access` 请求体:字段缺省表示保持原值(`password` 只写,`null` 表示清除已设密码)。 */export interface RemoteAccessBody {enabled?: booleanaddress?: stringport?: numberauthEnabled?: booleanscope?: RemoteAuthScope- password?: string | null}export type RemoteLinkSource = 'loopback' | 'lan'@@ -78,7 +75,7 @@ export interface RemoteAccessStatus {listen: RemoteAccessListen/** 真实监听端口;未监听时为 0。 */port: number- auth: { enabled: boolean, scope: RemoteAuthScope, hasPassword?: boolean, hasToken?: boolean, token?: string }+ auth: { enabled: boolean, scope: RemoteAuthScope, hasToken?: boolean, token?: string }addresses: RemoteAccessAddress[]recommended?: string/** 完整链接(含链接 Token);仅回环来源可见。 */@@ -91,8 +88,6 @@ export interface RemoteAccessStatus {linkSource?: RemoteLinkSource/** 临时配对码与其分享链接/二维码;仅回环来源可见。 */pairing?: RemoteAccessPairing- /** 本次请求刚自动生成的访问密码明文:只在响应里出现一次,不落盘、不进事件环。 */- generatedPassword?: string/** 公网隧道读面:配置 + 运行期状态(完整分支才带 Token 与链接二维码)。 */tunnel?: RemoteTunnelStatuslocalPort?: numberdiff --git a/packages/dsh-tauri-remote/src/host/service/access.utils.test.ts b/packages/dsh-tauri-remote/src/host/service/access.utils.test.tsindex c5a4366e..778f2a6d 100644--- a/packages/dsh-tauri-remote/src/host/service/access.utils.test.ts+++ b/packages/dsh-tauri-remote/src/host/service/access.utils.test.ts@@ -4,7 +4,6 @@ import { existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync,import { tmpdir } from 'node:os'import { dirname, join } from 'pathe'import { afterEach, beforeEach, describe, expect, it } from 'vitest'-import { verifyPassword } from '../utils/auth'import { ACCESS_DOCUMENT_VERSION, addressProblemOf, buildLink, DEFAULT_ACCESS_ADDRESS, DEFAULT_ACCESS_PORT, defaultAccessDocument, enumerateAddresses, isReachableAddress, isSelectableAddress, linkHostOf, maskLinkOf, pairingLinksOf, parseAccessDocument, patchAccessDocument, policyOf, rankAddresses, readAccessDocument, redactStatus, serializeAccessDocument, writeAccessDocument } from './access.utils'const homes: string[] = []@@ -64,7 +63,7 @@ function statusFixture(): RemoteAccessStatus {listening: true,listen: { address: '192.168.1.5', port: 3088 },port: 3089,- auth: { enabled: true, scope: 'public_only', hasPassword: true, hasToken: true },+ auth: { enabled: true, scope: 'public_only', hasToken: true },addresses: [entry('192.168.1.5', { recommended: true })],recommended: '192.168.1.5',link: 'http://192.168.1.5:3089/?auth=secret-token',@@ -90,6 +89,15 @@ function statusFixture(): RemoteAccessStatus {}describe('parseAccessDocument', () => {+ it('已删除的访问密码按未知键丢弃,不进入认证配置或再次落盘', () => {+ const parsed = parseAccessDocument(JSON.stringify({+ auth: { enabled: true, password: { algo: 'pbkdf2-sha256', salt: 'c2FsdA==', iterations: 1000, hash: 'aGFzaA==' }, token: 'keep-token', scope: 'all' },+ }))+ expect(parsed.document.auth).toEqual({ enabled: true, token: 'keep-token', scope: 'all' })+ expect(parsed.warnings).toEqual(['access.json 丢弃未知键 auth.password'])+ expect(serializeAccessDocument(parsed.document)).not.toContain('password')+ })+it('文件缺失或全为空白时回落默认文档且不算损坏', () => {const missing = parseAccessDocument(undefined)expect(missing.document).toEqual(defaultAccessDocument())@@ -115,7 +123,7 @@ describe('parseAccessDocument', () => {})it('丢弃 listen / auth 段里的未知键并告警', () => {- const parsed = parseAccessDocument(JSON.stringify({ listen: { address: '10.0.0.2', port: 4000, extra: true }, auth: { enabled: true, password: null, token: null, scope: 'all', extra: 1 } }))+ const parsed = parseAccessDocument(JSON.stringify({ listen: { address: '10.0.0.2', port: 4000, extra: true }, auth: { enabled: true, token: null, scope: 'all', extra: 1 } }))expect(parsed.warnings).toEqual(['access.json 丢弃未知键 listen.extra', 'access.json 丢弃未知键 auth.extra'])expect(parsed.document.auth.scope).toBe('all')})@@ -133,7 +141,7 @@ describe('parseAccessDocument', () => {const parsed = parseAccessDocument('{}')expect(parsed.document.listen.address).toBe(DEFAULT_ACCESS_ADDRESS)expect(parsed.document.listen.port).toBe(DEFAULT_ACCESS_PORT)- expect(parsed.document.auth).toEqual({ enabled: false, password: null, token: null, scope: 'public_only' })+ expect(parsed.document.auth).toEqual({ enabled: false, token: null, scope: 'public_only' })})it('非法 listen.port 与 listen.address 各自回落并告警', () => {@@ -165,19 +173,6 @@ describe('parseAccessDocument', () => {expect(parsed.warnings).toEqual(['access.json 的 tunnel 非法,已回落默认'])})- it('形态合法但不可用的密码记录原样保留,供网关判定「认证存储损坏」', () => {- const password = { algo: 'pbkdf2-sha256', salt: 'not-base64!!', iterations: 600000, hash: 'short' }- const parsed = parseAccessDocument(JSON.stringify({ auth: { enabled: true, password } }))- expect(parsed.document.auth.password).toEqual(password)- expect(parsed.warnings).toEqual([])- })-- it('形态非法的密码记录丢弃并告警', () => {- const parsed = parseAccessDocument(JSON.stringify({ auth: { password: { algo: 'sha1', salt: 'x', iterations: 1, hash: 'y' } } }))- expect(parsed.document.auth.password).toBeNull()- expect(parsed.warnings).toEqual(['access.json 的 auth.password 非法,已丢弃'])- })-it('序列化结果可被原样解析回来', () => {const document = { ...defaultAccessDocument(), enabled: true, listen: { address: '10.0.0.2', port: 4000 } }expect(serializeAccessDocument(document).endsWith('\n')).toBe(true)@@ -186,15 +181,15 @@ describe('parseAccessDocument', () => {})describe('readAccessDocument / writeAccessDocument', () => {- it('落盘为 0600 文件与 0700 目录,且不残留临时文件', () => {+ it('按平台文件模式落盘,POSIX 限制为 0600 / 0700,且不残留临时文件', () => {writeAccessDocument({ ...defaultAccessDocument(), enabled: true })- expect(statSync(accessFile()).mode & 0o777).toBe(0o600)- expect(statSync(dirname(accessFile())).mode & 0o777).toBe(0o700)+ expect(statSync(accessFile()).mode & 0o777).toBe(process.platform === 'win32' ? 0o666 : 0o600)+ expect(statSync(dirname(accessFile())).mode & 0o777).toBe(process.platform === 'win32' ? 0o666 : 0o700)expect(readdirSync(dirname(accessFile()))).toEqual(['access.json'])})it('写入后读回同一份文档', () => {- const document = { ...defaultAccessDocument(), enabled: true, listen: { address: '192.168.1.5', port: 4100 }, auth: { enabled: true, password: null, token: 'tok', scope: 'all' as const } }+ const document = { ...defaultAccessDocument(), enabled: true, listen: { address: '192.168.1.5', port: 4100 }, auth: { enabled: true, token: 'tok', scope: 'all' as const } }writeAccessDocument(document)expect(readAccessDocument().document).toEqual(document)})@@ -328,28 +323,12 @@ describe('buildLink / maskLinkOf', () => {})describe('patchAccessDocument', () => {- it('password: null 清除已设密码,字符串则写入新哈希', () => {- const document = { ...defaultAccessDocument(), auth: { enabled: true, password: { algo: 'pbkdf2-sha256' as const, salt: 's', iterations: 1, hash: 'h' }, token: null, scope: 'public_only' as const } }- expect(patchAccessDocument(document, { password: null }, []).auth.password).toBeNull()- const written = patchAccessDocument(document, { password: 'next-pass' }, []).auth.password- expect(written?.algo).toBe('pbkdf2-sha256')- expect(written?.hash).not.toBe('h')- })-- it('缺省字段保持原值,password 为只写字段', () => {- const document = { ...defaultAccessDocument(), enabled: true, auth: { enabled: true, password: null, token: 'keep', scope: 'all' as const } }+ it('缺省字段保持原值', () => {+ const document = { ...defaultAccessDocument(), enabled: true, auth: { enabled: true, token: 'keep', scope: 'all' as const } }const next = patchAccessDocument(document, { port: 4100 }, [entry('10.1.2.3')])expect(next.enabled).toBe(true)expect(next.listen).toEqual({ address: DEFAULT_ACCESS_ADDRESS, port: 4100 })- expect(next.auth).toEqual({ enabled: true, password: null, token: 'keep', scope: 'all' })- })-- it('提交密码时只存哈希且可被校验通过', () => {- const next = patchAccessDocument(defaultAccessDocument(), { password: 'hunter2' }, [])- expect(next.auth.password?.algo).toBe('pbkdf2-sha256')- expect(next.auth.password?.hash).not.toContain('hunter2')- expect(verifyPassword('hunter2', next.auth.password)).toBe(true)- expect(verifyPassword('hunter3', next.auth.password)).toBe(false)+ expect(next.auth).toEqual({ enabled: true, token: 'keep', scope: 'all' })})it('非法端口、作用域与开关类型一律抛错', () => {@@ -357,7 +336,6 @@ describe('patchAccessDocument', () => {expect(() => patchAccessDocument(defaultAccessDocument(), { port: 65536 }, [])).toThrowError('invalid port')expect(() => patchAccessDocument(defaultAccessDocument(), { scope: 'lan_only' as never }, [])).toThrowError('invalid scope')expect(() => patchAccessDocument(defaultAccessDocument(), { enabled: 'yes' as never }, [])).toThrowError('invalid enabled')- expect(() => patchAccessDocument(defaultAccessDocument(), { password: '' }, [])).toThrowError('invalid password')})it('地址必须是当前存在的网卡、通配或回环之一', () => {@@ -376,7 +354,7 @@ describe('redactStatus', () => {expect(redacted.link).toBeUndefined()expect(redacted.qr).toBeUndefined()expect(redacted.localPort).toBeUndefined()- expect(redacted.auth).toEqual({ enabled: true, scope: 'public_only', hasPassword: true, hasToken: true })+ expect(redacted.auth).toEqual({ enabled: true, scope: 'public_only', hasToken: true })expect(redacted.maskLink).toBe('http://192.168.1.5:3089/?auth=***')expect(redacted.listen).toEqual({ address: '192.168.1.5', port: 3088 })expect(redacted.port).toBe(3089)@@ -421,7 +399,7 @@ describe('pairingLinksOf', () => {describe('policyOf', () => {it('把文档映射为网关认证快照', () => {- const document = { ...defaultAccessDocument(), auth: { enabled: true, password: null, token: 'tok', scope: 'all' as const } }- expect(policyOf(document, 'secret')).toEqual({ enabled: true, scope: 'all', password: null, linkToken: 'tok', sessionSecret: 'secret' })+ const document = { ...defaultAccessDocument(), auth: { enabled: true, token: 'tok', scope: 'all' as const } }+ expect(policyOf(document, 'secret')).toEqual({ enabled: true, scope: 'all', linkToken: 'tok', sessionSecret: 'secret' })})})diff --git a/packages/dsh-tauri-remote/src/host/service/access.utils.ts b/packages/dsh-tauri-remote/src/host/service/access.utils.tsindex 31376952..73bd89c8 100644--- a/packages/dsh-tauri-remote/src/host/service/access.utils.ts+++ b/packages/dsh-tauri-remote/src/host/service/access.utils.ts@@ -1,12 +1,11 @@import type { NetworkInterfaceInfo } from 'node:os'-import type { RemoteAuthPolicy, RemoteAuthScope, RemotePasswordRecord, RemoteTunnelStatus } from '../types/index'+import type { RemoteAuthPolicy, RemoteAuthScope, RemoteTunnelStatus } from '../types/index'import type { RemoteAccessAddress, RemoteAccessBody, RemoteAccessDocument, RemoteAccessParse, RemoteAccessStatus, RemoteAddressFamily, RemoteAddressScope } from './access.types'import { randomBytes } from 'node:crypto'import { mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from 'node:fs'import { networkInterfaces } from 'node:os'import { dirname } from 'pathe'import { accessDocumentPath } from '../config/runtime'-import { hashPassword } from '../utils/auth'import { classifyPeer } from '../utils/source'export const ACCESS_DOCUMENT_VERSION = 1@@ -19,7 +18,7 @@ const DOCUMENT_KEYS = new Set(['version', 'enabled', 'listen', 'auth', 'tunnel']const LISTEN_KEYS = new Set(['address', 'port'])-const AUTH_KEYS = new Set(['enabled', 'password', 'token', 'scope'])+const AUTH_KEYS = new Set(['enabled', 'token', 'scope'])const TUNNEL_KEYS = new Set(['enabled', 'mode', 'token', 'hostname'])@@ -43,7 +42,7 @@ export function defaultAccessDocument(): RemoteAccessDocument {version: ACCESS_DOCUMENT_VERSION,enabled: false,listen: { address: DEFAULT_ACCESS_ADDRESS, port: DEFAULT_ACCESS_PORT },- auth: { enabled: false, password: null, token: null, scope: 'public_only' },+ auth: { enabled: false, token: null, scope: 'public_only' },tunnel: { enabled: false, mode: 'quick', token: null, hostname: null },}}@@ -128,14 +127,6 @@ export function patchAccessDocument(document: RemoteAccessDocument, body: Remotethrow new TypeError('invalid scope')next.auth.scope = body.scope}- if (body.password === null) {- next.auth.password = null- }- else if (body.password !== undefined) {- if (typeof body.password !== 'string' || body.password === '')- throw new TypeError('invalid password')- next.auth.password = hashPassword(body.password)- }return next}@@ -149,7 +140,6 @@ export function policyOf(document: RemoteAccessDocument, sessionSecret: string):return {enabled: document.auth.enabled,scope: document.auth.scope,- password: document.auth.password,linkToken: document.auth.token,sessionSecret,}@@ -250,7 +240,6 @@ export function redactStatus(status: RemoteAccessStatus): RemoteAccessStatus {auth: {enabled: status.auth.enabled,scope: status.auth.scope,- ...status.auth.hasPassword === undefined ? {} : { hasPassword: status.auth.hasPassword },...status.auth.hasToken === undefined ? {} : { hasToken: status.auth.hasToken },},addresses: status.addresses,@@ -333,13 +322,6 @@ function readAuth(value: unknown, document: RemoteAccessDocument, warnings: stridocument.auth.scope = value.scopeelse if (value.scope !== undefined)warnings.push('access.json 的 auth.scope 非法,已回落 public_only')- if (value.password !== null && value.password !== undefined) {- const record = passwordRecordOf(value.password)- if (record === undefined)- warnings.push('access.json 的 auth.password 非法,已丢弃')- else- document.auth.password = record- }if (typeof value.token === 'string' && value.token !== '')document.auth.token = value.tokenelse if (value.token !== undefined && value.token !== null)@@ -375,18 +357,6 @@ function readTunnel(value: unknown, document: RemoteAccessDocument, warnings: stwarnings.push('access.json 的 tunnel.hostname 非法,已丢弃')}-/** 只校验形态、不校验可用性:损坏的记录必须原样保留,才能让 S2 的「认证存储损坏」引导生效(S2 §11)。 */-function passwordRecordOf(value: unknown): RemotePasswordRecord | undefined {- if (!isPlainObject(value))- return undefined- const iterations = value.iterations- if (value.algo !== 'pbkdf2-sha256' || typeof value.salt !== 'string' || typeof value.hash !== 'string')- return undefined- if (typeof iterations !== 'number' || !Number.isInteger(iterations) || iterations <= 0)- return undefined- return { algo: 'pbkdf2-sha256', salt: value.salt, iterations, hash: value.hash }-}-function plainObjectOf(text: string): Record<string, unknown> | undefined {let raw: unknowntry {diff --git a/packages/dsh-tauri-remote/src/host/service/gateway.auth.ts b/packages/dsh-tauri-remote/src/host/service/gateway.auth.tsindex 149c0d60..8a48721e 100644--- a/packages/dsh-tauri-remote/src/host/service/gateway.auth.ts+++ b/packages/dsh-tauri-remote/src/host/service/gateway.auth.ts@@ -87,6 +87,6 @@ async function renderGatewayAuthHtml(): Promise<string> {throw new Error('Gateway auth theme is missing dark tokens')const css = `${theme}@media(prefers-color-scheme:dark){${dark}}${styles.join('')}*{box-sizing:border-box}html{color-scheme:light dark}body{margin:0;min-height:100svh;display:grid;place-items:center;padding:24px;background:var(--dsw-alias-bg-base);color:var(--dsw-alias-label-primary);font-family:var(--dsw-font-family)}main{width:min(100%,360px);text-align:center}main>svg{color:var(--dsw-alias-state-business-primary)}h1{font-size:24px;line-height:32px;font-weight:600;margin:20px 0 32px}form{display:grid;gap:16px}label{font-size:14px;line-height:22px;text-align:left}form>span{height:44px}input{font:inherit}form>button{height:44px;width:100%}[role=alert]{color:var(--dsw-alias-state-error-primary);font-size:14px;line-height:22px;margin:0 0 16px}`- const body = renderToStaticMarkup(createElement('main', null, createElement(FishLogo, { size: 64 }), createElement('h1', null, 'DeepSeek Harness'), '__GATEWAY_AUTH_MESSAGE__', createElement('form', { method: 'post' }, createElement('label', { htmlFor: 'password' }, '请输入配对码'), createElement(Input, { id: 'password', name: 'password', type: 'password', autoComplete: 'current-password', autoFocus: true, required: true }), createElement(Button, { type: 'submit', variant: 'primary' }, '连接'))))+ const body = renderToStaticMarkup(createElement('main', null, createElement(FishLogo, { size: 64 }), createElement('h1', null, 'DeepSeek Harness'), '__GATEWAY_AUTH_MESSAGE__', createElement('form', { id: 'loginForm', method: 'post' }, createElement('label', { htmlFor: 'code' }, '请输入配对码'), createElement(Input, { id: 'code', name: 'code', type: 'text', autoComplete: 'one-time-code', autoCapitalize: 'characters', spellCheck: false, autoFocus: true, required: true }), createElement(Button, { type: 'submit', variant: 'primary' }, '连接'))))return `<!doctype html><html lang="zh-CN"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>DeepSeek Harness</title><style>${css}</style></head><body>${body}</body></html>`}diff --git a/packages/dsh-tauri-remote/src/host/service/gateway.test.ts b/packages/dsh-tauri-remote/src/host/service/gateway.test.tsindex aedcbfcc..d10d1d66 100644--- a/packages/dsh-tauri-remote/src/host/service/gateway.test.ts+++ b/packages/dsh-tauri-remote/src/host/service/gateway.test.ts@@ -1,7 +1,7 @@import type { IncomingHttpHeaders, IncomingMessage } from 'node:http'import type { AddressInfo } from 'node:net'import type { Duplex } from 'node:stream'-import type { RemoteAuthPolicy, RemoteGatewayEntryKind, RemoteGatewayEvent, RemoteGatewayStartOptions, RemotePasswordRecord } from '../types/index'+import type { RemoteAuthPolicy, RemoteGatewayEntryKind, RemoteGatewayEvent, RemoteGatewayStartOptions } from '../types/index'import { Buffer } from 'node:buffer'import { createHash } from 'node:crypto'import { once } from 'node:events'@@ -12,7 +12,7 @@ import * as zlib from 'node:zlib'import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'import { GATEWAY_SESSION_HEADER, GATEWAY_SOURCE_HEADER } from '../config/constants'import { ensureSourceSession } from '../config/runtime'-import { createLinkToken, hashPassword, signSession, verifySession } from '../utils/auth'+import { createLinkToken, signSession, verifySession } from '../utils/auth'import { classifySource } from '../utils/source'import { gateway } from './gateway'import { consumePairingCode, PAIRING_TTL_MS, pairingCodeOf, resetPairingCode } from './pairing'@@ -167,6 +167,12 @@ function startFakeUpstream(): Promise<FakeUpstream> {return}}+ if (url.pathname === '/manifest.webmanifest' && (request.method === 'GET' || request.method === 'HEAD')) {+ const body = '{"name":"DeepSeek Harness","short_name":"DSH","icons":[{"src":"/favicon.ico","type":"image/x-icon","sizes":"48x48"}]}'+ response.writeHead(200, { 'content-type': 'application/manifest+json', 'content-length': String(Buffer.byteLength(body)) })+ response.end(request.method === 'HEAD' ? undefined : body)+ return+ }if (!sessionGranted(request.headers)) {response.writeHead(401, { 'content-type': 'application/json' })response.end('{"error":"unauthorized"}')@@ -648,7 +654,7 @@ function navigation(): IncomingHttpHeaders {}function policyOf(overrides: Partial<RemoteAuthPolicy> = {}): RemoteAuthPolicy {- return { enabled: true, scope: 'public_only', password: hashPassword('s3cret', 1000), linkToken: null, sessionSecret: 'session-secret', ...overrides }+ return { enabled: true, scope: 'public_only', linkToken: 'AB23CD45', sessionSecret: 'session-secret', ...overrides }}async function startEntry(kind: RemoteGatewayEntryKind, upstream: FakeUpstream, options: Partial<RemoteGatewayStartOptions> = {}) {@@ -1021,7 +1027,7 @@ describe('gateway 来源门禁判定矩阵(真实 HTTP 管线)', () => {it('把物理回环来源之外的私网来源按真实 TCP 对端地址判定', async () => {const external = externalAddress()if (external === undefined)- throw new Error('本机不存在非内部 IPv4 地址,无法断言真实私网来源')+ throw new Error('本机不存在非内部私网 IPv4 地址,无法断言真实私网来源')const status = await gateway.start({ id: 'entry', kind: 'inbound', upstream: upstream.origin, port: 0, host: '0.0.0.0', auth: () => policyOf({ scope: 'all' }) })const reply = await new Promise<Coded>((resolve, reject) => {const request = httpRequest({ host: external, port: status.port, path: '/api/ping', headers: { connection: 'close' } }, (response) => {@@ -1035,6 +1041,47 @@ describe('gateway 来源门禁判定矩阵(真实 HTTP 管线)', () => {expect(reply.status).toBe(401)})+ it.each(['GET', 'HEAD'] as const)('未登录隧道 %s 只公开 DSH manifest,不铸造会话或消费配对码', async (method) => {+ const first = pairingCodeOf()+ const tokenProvider = vi.fn(upstream.mintUrlFor)+ const status = await startEntry('tunnel', upstream, { auth: () => policyOf({ pairingCode: first.code, consumePairingCode }), tokenProvider })+ const reply = await call(status.port, '/manifest.webmanifest', { method })+ expect(reply.status).toBe(200)+ expect(reply.headers['content-type']).toBe('application/manifest+json')+ expect(reply.headers['set-cookie']).toBeUndefined()+ expect(reply.body.toString()).toBe(method === 'HEAD' ? '' : '{"name":"DeepSeek Harness","short_name":"DSH","icons":[{"src":"/favicon.ico","type":"image/x-icon","sizes":"48x48"}]}')+ expect(tokenProvider).not.toHaveBeenCalled()+ expect(pairingCodeOf().usedSeq).toBe(0)+ expect(upstream.calls.map(entry => entry.url)).toEqual(['/manifest.webmanifest'])+ expect((await call(status.port, '/api/probe')).status).toBe(403)+ const headers = { 'sec-fetch-site': 'same-origin' }+ expect((await call(status.port, '/api/probe', { headers })).status).toBe(401)+ expect((await call(status.port, '/', { headers: { ...headers, ...navigation() } })).status).toBe(401)+ expect((await call(status.port, '/manifest.webmanifest', { method: 'POST', headers })).status).toBe(401)+ expect((await call(status.port, '/manifest.webmanifest/extra', { headers })).status).toBe(401)+ await expect(upgraded(status.port, '/manifest.webmanifest', headers)).rejects.toThrow('401')+ expect(upstream.upgrades).toHaveLength(0)+ expect(upstream.calls.map(entry => entry.url)).toEqual(['/manifest.webmanifest'])+ const linked = await call(status.port, `/manifest.webmanifest?auth=${first.code}`)+ expect(linked.status).toBe(200)+ expect(linked.headers['set-cookie']).toBeUndefined()+ expect(linked.body.toString()).not.toContain(first.code)+ expect(JSON.stringify(linked.headers)).not.toContain(first.code)+ expect(pairingCodeOf().usedSeq).toBe(0)+ expect(tokenProvider).not.toHaveBeenCalled()+ })++ it('公开 manifest 仍先拒绝跨站 Origin 和 Host 不一致的请求', async () => {+ const status = await startEntry('tunnel', upstream, { auth: () => policyOf(), publicHost: () => 'trusted.example.com' })+ const replies = [+ await call(status.port, '/manifest.webmanifest', { headers: { origin: 'https://evil.example.com', host: '127.0.0.1' } }),+ await call(status.port, '/manifest.webmanifest', { headers: { origin: 'https://evil.example.com', host: 'trusted.example.com' } }),+ await call(status.port, '/manifest.webmanifest', { headers: { 'sec-fetch-site': 'cross-site' } }),+ ]+ expect(replies.map(reply => reply.status)).toEqual([403, 403, 403])+ expect(upstream.calls).toHaveLength(0)+ })+it('未配置认证时的导航请求得到引导页面而非空白拒绝', async () => {const status = await startEntry('inbound', upstream)const reply = await call(status.port, '/api/ping', { headers: markerHeaders('public', navigation()) })@@ -1043,30 +1090,21 @@ describe('gateway 来源门禁判定矩阵(真实 HTTP 管线)', () => {expect(reply.body.toString()).toContain('访问被拒绝')})- it('认证存储损坏时视为未配置认证,公网与隧道来源被拒绝并引导重设密码', async () => {- const corrupt: RemotePasswordRecord = { algo: 'pbkdf2-sha256', salt: 'c2FsdA==', iterations: 1000, hash: 'aGFzaA==' }- const status = await gateway.start({ id: 'entry', kind: 'inbound', upstream: upstream.origin, port: 0, tokenProvider: upstream.mintUrlFor, auth: () => policyOf({ password: corrupt }) })+ it.each(['disabled', 'missing'] as const)('配对认证为 %s 时仍拒绝公网、隧道和 Upgrade,回环保持放行', async (mode) => {+ const policy = mode === 'disabled' ? policyOf({ enabled: false, pairingCode: 'EF67GH89' }) : policyOf({ linkToken: null, pairingCode: '' })+ const status = await startEntry('inbound', upstream, { tokenProvider: upstream.mintUrlFor, auth: () => policy })const page = await call(status.port, '/api/ping', { headers: markerHeaders('public', navigation()) })expect(page.status).toBe(403)expect(page.headers['content-type']).toContain('text/html')- expect(page.body.toString()).toContain('重新设置访问密码')+ expect(page.body.toString()).toContain('启用认证并获取配对码')+ expect(page.body.toString()).not.toContain('密码')const api = await call(status.port, '/api/ping', { headers: markerHeaders('tunnel') })expect(api.status).toBe(403)- expect(JSON.parse(api.body.toString()).error).toContain('认证存储损坏')-+ expect(JSON.parse(api.body.toString()).error).toContain('尚未启用配对认证')await expect(upgraded(status.port, '/api/remote.mux', markerHeaders('tunnel'))).rejects.toThrow('403')-- const loopback = await call(status.port, '/api/ping')- expect(loopback.status).toBe(200)- })-- it('认证存储损坏但有链接 Token 时仍按需认证处理', async () => {- const corrupt: RemotePasswordRecord = { algo: 'pbkdf2-sha256', salt: 'c2FsdA==', iterations: 1000, hash: 'aGFzaA==' }- const status = await gateway.start({ id: 'entry', kind: 'inbound', upstream: upstream.origin, port: 0, tokenProvider: upstream.mintUrlFor, auth: () => policyOf({ password: corrupt, linkToken: 'link-token' }) })- const visitor = await call(status.port, '/?auth=link-token', { headers: markerHeaders('tunnel', navigation()) })- expect(visitor.status).toBe(302)- expect(String(visitor.headers['set-cookie'])).toContain('dsh_remote_session=')+ expect(upstream.calls).toHaveLength(0)+ expect((await call(status.port, '/api/ping')).status).toBe(200)})it('需认证的导航请求得到内置登录页,API 请求得到 401 与可读错误体', async () => {@@ -1076,7 +1114,7 @@ describe('gateway 来源门禁判定矩阵(真实 HTTP 管线)', () => {expect(page.headers['content-type']).toContain('text/html')expect(page.headers['cache-control']).toBe('no-store')expect(page.headers['referrer-policy']).toBe('no-referrer')- expect(page.body.toString()).toContain('<form method="post">')+ expect(page.body.toString()).toContain('<form id="loginForm" method="post">')const api = await call(status.port, '/api/ping', { headers: markerHeaders('public') })expect(api.status).toBe(401)@@ -1212,12 +1250,44 @@ describe('gateway 跨站来源拦截', () => {})describe('gateway 认证要素', () => {- it('密码登录成功后签发会话并 302 回跳原始访问路径', async () => {+ it.each(['GET', 'POST'] as const)('仅临时配对码的策略经 %s 签发会话而非拒绝公网', async (method) => {+ const first = pairingCodeOf()+ const policy = policyOf({ linkToken: null, pairingCode: first.code, consumePairingCode })+ const status = await startEntry('tunnel', upstream, { auth: () => policy, tokenProvider: upstream.mintUrlFor })+ const headers = { 'sec-fetch-site': 'same-origin', ...navigation() }+ const path = method === 'GET' ? `/?auth=${first.code.toLowerCase()}` : '/chat/42?tab=two'+ const options = method === 'GET' ? { headers } : { method, headers: { ...headers, 'content-type': 'application/x-www-form-urlencoded' }, body: `code=${first.code.toLowerCase()}` }+ const login = await call(status.port, path, options)+ expect(login.status).toBe(302)+ expect(login.headers.location).toBe(method === 'GET' ? '/' : '/chat/42?tab=two')+ expect(pairingCodeOf().usedSeq).toBe(1)+ const cookie = (login.headers['set-cookie'] ?? [])[0]?.split(';')[0] ?? ''+ expect(cookie).toContain('dsh_remote_session=')+ expect((await call(status.port, '/api/ping', { headers: { ...headers, cookie } })).status).toBe(200)+ })++ it.each(['linkToken', 'pairingCode'] as const)('旧 password 字段携带有效 %s 也不签发会话或消费配对码', async (credential) => {+ const first = pairingCodeOf()+ const code = credential === 'linkToken' ? 'AB23CD45' : first.code+ const policy = policyOf({ linkToken: credential === 'linkToken' ? code : null, pairingCode: first.code, consumePairingCode })+ const status = await startEntry('tunnel', upstream, { auth: () => policy })+ const rejected = await call(status.port, '/', {+ method: 'POST',+ headers: { 'sec-fetch-site': 'same-origin', 'content-type': 'application/x-www-form-urlencoded', ...navigation() },+ body: `password=${code.toLowerCase()}`,+ })+ expect(rejected.status).toBe(401)+ expect(rejected.headers['set-cookie']).toBeUndefined()+ expect(pairingCodeOf().usedSeq).toBe(0)+ expect(upstream.calls).toHaveLength(0)+ })++ it('配对码表单登录成功后签发会话并 302 回跳原始访问路径', async () => {const status = await startEntry('inbound', upstream, { auth: () => policyOf({ linkToken: 'link-token' }), tokenProvider: upstream.mintUrlFor })const login = await call(status.port, '/chat/42', {method: 'POST',headers: markerHeaders('public', { 'content-type': 'application/x-www-form-urlencoded', ...navigation() }),- body: 'password=s3cret',+ body: 'code=link-token',})expect(login.status).toBe(302)expect(login.headers.location).toBe('/chat/42')@@ -1233,16 +1303,16 @@ describe('gateway 认证要素', () => {})it.each(['inbound', 'tunnel'] as const)('永久配对码可在 %s 入口的原登录表单手输并签发会话', async (kind) => {- const status = await startEntry(kind, upstream, { auth: () => policyOf({ password: null, linkToken: '01234567' }), tokenProvider: upstream.mintUrlFor })+ const status = await startEntry(kind, upstream, { auth: () => policyOf({ linkToken: '01234567' }), tokenProvider: upstream.mintUrlFor })const headers = markerHeaders('public', { 'sec-fetch-site': 'same-origin', ...navigation() })const page = await call(status.port, '/api/ping?tab=two', { headers })expect(page.status).toBe(401)- expect(page.body.toString()).toContain('<form method="post">')- expect(page.body.toString()).toContain('name="password"')+ expect(page.body.toString()).toContain('<form id="loginForm" method="post">')+ expect(page.body.toString()).toContain('name="code"')const login = await call(status.port, '/api/ping?tab=two', {method: 'POST',headers: { ...headers, 'content-type': 'application/x-www-form-urlencoded' },- body: 'password=01234567',+ body: 'code=01234567',})expect(login.status).toBe(302)expect(login.headers.location).toBe('/api/ping?tab=two')@@ -1262,10 +1332,10 @@ describe('gateway 认证要素', () => {const submission = {method: 'POST',headers: markerHeaders('public', { 'content-type': 'application/x-www-form-urlencoded', ...navigation() }),- body: 'password=01234567',+ body: 'code=01234567',}expect((await call(status.port, '/', submission)).status).toBe(302)- policy = policyOf()+ policy = policyOf({ linkToken: 'WX67YZ89' })const revoked = await call(status.port, '/', submission)expect(revoked.status).toBe(401)expect(revoked.headers['set-cookie']).toBeUndefined()@@ -1273,12 +1343,12 @@ describe('gateway 认证要素', () => {})it.each(['linkToken', 'pairingCode'] as const)('%s 配对码的小写 GET 与手输 POST 都签发会话', async (credential) => {- const policy = policyOf({ password: null, linkToken: credential === 'linkToken' ? 'AB23CD45' : 'WX67YZ89', ...credential === 'pairingCode' ? { pairingCode: 'AB23CD45' } : {} })+ const policy = policyOf({ linkToken: credential === 'linkToken' ? 'AB23CD45' : 'WX67YZ89', ...credential === 'pairingCode' ? { pairingCode: 'AB23CD45' } : {} })const status = await startEntry('tunnel', upstream, { auth: () => policy, tokenProvider: upstream.mintUrlFor })const headers = { 'sec-fetch-site': 'same-origin', ...navigation() }const replies = [await call(status.port, '/?auth=ab23cd45', { headers }),- await call(status.port, '/api/ping?tab=two', { method: 'POST', headers: { ...headers, 'content-type': 'application/x-www-form-urlencoded' }, body: 'password=ab23cd45' }),+ await call(status.port, '/api/ping?tab=two', { method: 'POST', headers: { ...headers, 'content-type': 'application/x-www-form-urlencoded' }, body: 'code=ab23cd45' }),]for (const [index, reply] of replies.entries()) {expect(reply.status).toBe(302)@@ -1295,7 +1365,7 @@ describe('gateway 认证要素', () => {})it.each(['linkToken', 'pairingCode'] as const)('%s 配对码更换后小写 GET 与手输 POST 均拒绝旧码且已签会话仍有效', async (credential) => {- let policy = policyOf({ password: null, linkToken: credential === 'linkToken' ? 'AB23CD45' : 'WX67YZ89', ...credential === 'pairingCode' ? { pairingCode: 'AB23CD45' } : {} })+ let policy = policyOf({ linkToken: credential === 'linkToken' ? 'AB23CD45' : 'WX67YZ89', ...credential === 'pairingCode' ? { pairingCode: 'AB23CD45' } : {} })const status = await startEntry('tunnel', upstream, { auth: () => policy, tokenProvider: upstream.mintUrlFor })const headers = { 'sec-fetch-site': 'same-origin', ...navigation() }const hit = await call(status.port, '/?auth=AB23CD45', { headers })@@ -1304,7 +1374,7 @@ describe('gateway 认证要素', () => {policy = { ...policy, [credential]: 'EF67GH89' }const replies = [await call(status.port, '/?auth=ab23cd45', { headers }),- await call(status.port, '/', { method: 'POST', headers: { ...headers, 'content-type': 'application/x-www-form-urlencoded' }, body: 'password=ab23cd45' }),+ await call(status.port, '/', { method: 'POST', headers: { ...headers, 'content-type': 'application/x-www-form-urlencoded' }, body: 'code=ab23cd45' }),]for (const reply of replies) {expect(reply.status).toBe(401)@@ -1320,7 +1390,7 @@ describe('gateway 认证要素', () => {const clock = vi.spyOn(Date, 'now').mockReturnValue(now)try {const code = pairingCodeOf().code.toLowerCase()- const status = await startEntry('tunnel', upstream, { auth: () => policyOf({ password: null, linkToken: 'WX67YZ89', pairingCode: pairingCodeOf().code }), tokenProvider: upstream.mintUrlFor })+ const status = await startEntry('tunnel', upstream, { auth: () => policyOf({ linkToken: 'WX67YZ89', pairingCode: pairingCodeOf().code }), tokenProvider: upstream.mintUrlFor })const headers = { 'sec-fetch-site': 'same-origin', ...navigation() }const hit = await call(status.port, `/?auth=${code}`, { headers })expect(hit.status).toBe(302)@@ -1330,7 +1400,7 @@ describe('gateway 认证要素', () => {clock.mockReturnValue(now + 300_000)const expired = [await call(status.port, `/?auth=${code}`, { headers }),- await call(status.port, '/', { method: 'POST', headers: { ...headers, 'content-type': 'application/x-www-form-urlencoded' }, body: `password=${code}` }),+ await call(status.port, '/', { method: 'POST', headers: { ...headers, 'content-type': 'application/x-www-form-urlencoded' }, body: `code=${code}` }),]expect(expired.map(reply => reply.status)).toEqual([401, 401])for (const reply of expired)@@ -1346,11 +1416,11 @@ describe('gateway 认证要素', () => {it.each(['GET', 'POST'] as const)('临时配对码经 %s 只成功一次,旧码失效但已签会话仍有效', async (method) => {const first = pairingCodeOf()- const policy = policyOf({ password: null, linkToken: 'WX67YZ89', pairingCode: first.code, consumePairingCode })+ const policy = policyOf({ linkToken: 'WX67YZ89', pairingCode: first.code, consumePairingCode })const status = await startEntry('tunnel', upstream, { auth: () => policy, tokenProvider: upstream.mintUrlFor })const headers = { 'sec-fetch-site': 'same-origin', ...navigation() }const path = method === 'GET' ? `/?auth=${first.code.toLowerCase()}` : '/chat/42?tab=two'- const options = method === 'GET' ? { headers } : { method, headers: { ...headers, 'content-type': 'application/x-www-form-urlencoded' }, body: `password=${first.code.toLowerCase()}` }+ const options = method === 'GET' ? { headers } : { method, headers: { ...headers, 'content-type': 'application/x-www-form-urlencoded' }, body: `code=${first.code.toLowerCase()}` }const login = await call(status.port, path, options)expect(login.status).toBe(302)expect(login.headers.location).toBe(method === 'GET' ? '/' : '/chat/42?tab=two')@@ -1367,12 +1437,12 @@ describe('gateway 认证要素', () => {it('并发 GET 与 POST 竞争同一码时只签发一份会话', async () => {const first = pairingCodeOf()- const policy = policyOf({ password: null, linkToken: 'WX67YZ89', pairingCode: first.code, consumePairingCode })+ const policy = policyOf({ linkToken: 'WX67YZ89', pairingCode: first.code, consumePairingCode })const status = await startEntry('tunnel', upstream, { auth: () => policy })const headers = { 'sec-fetch-site': 'same-origin', ...navigation() }const replies = await Promise.all([call(status.port, `/?auth=${first.code.toLowerCase()}`, { headers }),- call(status.port, '/', { method: 'POST', headers: { ...headers, 'content-type': 'application/x-www-form-urlencoded' }, body: `password=${first.code.toLowerCase()}` }),+ call(status.port, '/', { method: 'POST', headers: { ...headers, 'content-type': 'application/x-www-form-urlencoded' }, body: `code=${first.code.toLowerCase()}` }),])expect(replies.map(reply => reply.status).sort()).toEqual([302, 401])expect(replies.filter(reply => reply.headers['set-cookie'] !== undefined)).toHaveLength(1)@@ -1380,7 +1450,7 @@ describe('gateway 认证要素', () => {expect(upstream.calls).toHaveLength(0)})- it('永久码、密码、错误码和有效会话均不消费临时码', async () => {+ it('永久码、错误码和有效会话均不消费临时码', async () => {const first = pairingCodeOf()const policy = policyOf({ linkToken: first.code, pairingCode: first.code, consumePairingCode })const status = await startEntry('tunnel', upstream, { auth: () => policy, tokenProvider: upstream.mintUrlFor })@@ -1388,9 +1458,6 @@ describe('gateway 认证要素', () => {const permanent = await call(status.port, `/?auth=${first.code.toLowerCase()}`, { headers })expect(permanent.status).toBe(302)expect(pairingCodeOf()).toBe(first)- const password = await call(status.port, '/', { method: 'POST', headers: { ...headers, 'content-type': 'application/x-www-form-urlencoded' }, body: 'password=s3cret' })- expect(password.status).toBe(302)- expect(pairingCodeOf()).toBe(first)expect((await call(status.port, '/?auth=invalid', { headers })).status).toBe(401)expect(pairingCodeOf()).toBe(first)const cookie = (permanent.headers['set-cookie'] ?? [])[0]?.split(';')[0] ?? ''@@ -1406,12 +1473,12 @@ describe('gateway 认证要素', () => {clock.mockReturnValue(now)const first = pairingCodeOf()let reads = 0- const policy = policyOf({ password: null, linkToken: 'WX67YZ89', pairingCode: first.code, consumePairingCode })+ const policy = policyOf({ linkToken: 'WX67YZ89', pairingCode: first.code, consumePairingCode })const status = await startEntry('tunnel', upstream, { auth: () => {reads += 1return policy} })- const body = `password=${first.code.toLowerCase()}`+ const body = `code=${first.code.toLowerCase()}`const request = httpRequest({ host: '127.0.0.1', port: status.port, path: '/', method: 'POST', headers: { 'connection': 'close', 'sec-fetch-site': 'same-origin', ...navigation(), 'content-type': 'application/x-www-form-urlencoded', 'content-length': Buffer.byteLength(body) } })const pending = new Promise<Coded>((resolve, reject) => {request.on('response', (response) => {@@ -1422,7 +1489,7 @@ describe('gateway 认证要素', () => {request.on('error', reject)})try {- request.write('password=')+ request.write('code=')await vi.waitFor(() => expect(reads).toBeGreaterThan(0))if (reason === 'used')expect(consumePairingCode(first.code)).toBe(true)@@ -1443,20 +1510,20 @@ describe('gateway 认证要素', () => {})it('局域网免密分支仍消费根链接与根登录表单,普通 LAN 请求和回环不消费', async () => {- const policy = policyOf({ password: null, linkToken: 'WX67YZ89', pairingCode: pairingCodeOf().code, consumePairingCode })+ const policy = policyOf({ linkToken: 'WX67YZ89', pairingCode: pairingCodeOf().code, consumePairingCode })const status = await startEntry('inbound', upstream, { auth: () => policy, tokenProvider: upstream.mintUrlFor })const privateHeaders = markerHeaders('private', navigation())const code = pairingCodeOf().codeexpect((await call(status.port, '/', { headers: privateHeaders })).status).toBe(200)expect((await call(status.port, `/?auth=${code}`, { headers: markerHeaders('loopback') })).status).toBe(200)- expect((await call(status.port, '/api/echo', { method: 'POST', headers: { ...privateHeaders, 'content-type': 'application/x-www-form-urlencoded' }, body: `password=${code}` })).status).toBe(200)+ expect((await call(status.port, '/api/echo', { method: 'POST', headers: { ...privateHeaders, 'content-type': 'application/x-www-form-urlencoded' }, body: `code=${code}` })).status).toBe(200)expect(pairingCodeOf().usedSeq).toBe(0)const login = await call(status.port, `/?auth=${code.toLowerCase()}`, { headers: privateHeaders })expect(login.status).toBe(302)expect(pairingCodeOf().usedSeq).toBe(1)expect((await call(status.port, `/?auth=${code}`, { headers: privateHeaders })).status).toBe(401)const next = pairingCodeOf().code- const form = { method: 'POST', headers: { ...privateHeaders, 'content-type': 'application/x-www-form-urlencoded' }, body: `password=${next.toLowerCase()}` }+ const form = { method: 'POST', headers: { ...privateHeaders, 'content-type': 'application/x-www-form-urlencoded' }, body: `code=${next.toLowerCase()}` }expect((await call(status.port, '/', form)).status).toBe(302)expect(pairingCodeOf().usedSeq).toBe(2)expect((await call(status.port, '/', form)).status).toBe(401)@@ -1467,23 +1534,23 @@ describe('gateway 认证要素', () => {const status = await startEntry('inbound', upstream, { auth: () => policyOf({ linkToken: 'link-token' }), tokenProvider: upstream.mintUrlFor })const page = await call(status.port, '/chat/42?tab=two', { headers: markerHeaders('public', navigation()) })expect(page.status).toBe(401)- expect(page.body.toString()).toContain('<form method="post">')+ expect(page.body.toString()).toContain('<form id="loginForm" method="post">')const login = await call(status.port, '/chat/42?tab=two', {method: 'POST',headers: markerHeaders('public', { 'content-type': 'application/x-www-form-urlencoded', ...navigation() }),- body: 'password=s3cret',+ body: 'code=link-token',})expect(login.headers.referer).toBeUndefined()expect(login.status).toBe(302)expect(login.headers.location).toBe('/chat/42?tab=two')})- it('aPI 客户端带 password 字段的 POST 不是登录提交:回 401 且不误发会话', async () => {+ it('aPI 客户端带 code 字段的 POST 不是登录提交:回 401 且不误发会话', async () => {const status = await startEntry('inbound', upstream, { auth: () => policyOf({ linkToken: 'link-token' }) })const shaped = await call(status.port, '/api/echo', {method: 'POST',headers: markerHeaders('public', { 'content-type': 'application/x-www-form-urlencoded', 'accept': 'application/json' }),- body: 'password=s3cret',+ body: 'code=link-token',})expect(shaped.status).toBe(401)expect(shaped.headers['set-cookie']).toBeUndefined()@@ -1492,23 +1559,23 @@ describe('gateway 认证要素', () => {const notUrlencoded = await call(status.port, '/api/echo', {method: 'POST',headers: markerHeaders('public', { 'content-type': 'application/json', ...navigation() }),- body: '{"password":"s3cret"}',+ body: '{"code":"link-token"}',})expect(notUrlencoded.status).toBe(401)expect(notUrlencoded.headers['set-cookie']).toBeUndefined()expect(upstream.calls.some(entry => entry.url === '/api/echo')).toBe(false)})- it('密码错误时重新渲染登录页并计入限速,连续失败触发封禁', async () => {+ it('配对码错误时重新渲染登录页并计入限速,连续失败触发封禁', async () => {const status = await startEntry('inbound', upstream, { auth: () => policyOf({ linkToken: 'link-token' }) })const attempt = async () => await call(status.port, '/', {method: 'POST',headers: markerHeaders('public', { 'content-type': 'application/x-www-form-urlencoded', ...navigation() }),- body: 'password=wrong',+ body: 'code=wrong',})const first = await attempt()expect(first.status).toBe(401)- expect(first.body.toString()).toContain('密码不正确')+ expect(first.body.toString()).toContain('配对码不正确或已失效')for (let index = 1; index < 5; index++)await attempt()const banned = await attempt()@@ -1628,7 +1695,7 @@ describe('gateway 限速分桶', () => {const attempt = async (clientIp: string) => await call(status.port, '/', {method: 'POST',headers: { 'cf-connecting-ip': clientIp, 'sec-fetch-site': 'same-origin', 'content-type': 'application/x-www-form-urlencoded', ...navigation() },- body: 'password=wrong',+ body: 'code=wrong',})for (let index = 0; index < 5; index++)await attempt('203.0.113.7')@@ -1643,7 +1710,7 @@ describe('gateway 限速分桶', () => {const attempt = async (clientIp: string) => await call(status.port, '/', {method: 'POST',headers: markerHeaders('public', { 'cf-connecting-ip': clientIp, 'content-type': 'application/x-www-form-urlencoded', ...navigation() }),- body: 'password=wrong',+ body: 'code=wrong',})for (let index = 0; index < 5; index++)await attempt('203.0.113.7')@@ -1656,7 +1723,7 @@ describe('gateway 限速分桶', () => {const attempt = async () => await call(status.port, '/', {method: 'POST',headers: markerHeaders('public', { 'content-type': 'application/x-www-form-urlencoded', ...navigation() }),- body: 'password=wrong',+ body: 'code=wrong',})for (let index = 0; index < 6; index++)await attempt()@@ -1904,7 +1971,7 @@ describe('gateway 处理失败边界', () => {response.on('end', () => resolve())response.on('aborted', () => resolve())})- request.write('password=s3c')+ request.write('code=AB2')setTimeout(() => {request.destroy()resolve()@@ -2345,7 +2412,7 @@ describe('gateway 监听生命周期', () => {function externalAddress(): string | undefined {return Object.values(networkInterfaces()).flat()- .find(entry => entry !== undefined && !entry.internal && entry.family === 'IPv4' && !entry.address.startsWith('127.'))+ .find(entry => entry !== undefined && !entry.internal && entry.family === 'IPv4' && /^(?:10\.|192\.168\.|172\.(?:1[6-9]|2\d|3[01])\.|169\.254\.|100\.(?:6[4-9]|[7-9]\d|1[01]\d|12[0-7])\.)/.test(entry.address))?.address}diff --git a/packages/dsh-tauri-remote/src/host/service/gateway.ts b/packages/dsh-tauri-remote/src/host/service/gateway.tsindex 1fda0a61..75ce2046 100644--- a/packages/dsh-tauri-remote/src/host/service/gateway.ts+++ b/packages/dsh-tauri-remote/src/host/service/gateway.ts@@ -7,8 +7,8 @@ import { pipeline } from 'node:stream'import { defineService } from 'dsh-tauri'import { messageOf } from '../../shared/error'import { ensureSourceSession } from '../config/runtime'-import { rateLimitAfterFailure, rateLimitBlockedMs, signSession, tokenMatches, verifyPassword, verifySession } from '../utils/auth'-import { classifySource, decideSourceAccess, isAuthConfigured, isAuthStorageBroken, rateLimitKeyOf } from '../utils/source'+import { rateLimitAfterFailure, rateLimitBlockedMs, signSession, tokenMatches, verifySession } from '../utils/auth'+import { classifySource, decideSourceAccess, isAuthConfigured, rateLimitKeyOf } from '../utils/source'import { authorityFor, cookiePairsOf, createCompressor, createDecompressor, deniedHtml, entryUrlOf, forwardHeadersOf, isCrossSiteRequest, isNavigationRequest, isReplayable, isUpgradeOf, loginPageHtml, mergeCookieHeader, parseCookieHeader, parseFormField, responseHeadersOf, responsePlanOf, supportsZstd, tunnelClientIpOf, upstreamPortOf } from './gateway.utils'const LOOPBACK = '127.0.0.1'@@ -23,7 +23,7 @@ const SESSION_COOKIE = 'dsh_remote_session'const AUTH_QUERY = 'auth'-const LOGIN_FIELD = 'password'+const LOGIN_FIELD = 'code'const FORM_BODY_LIMIT = 4096@@ -35,9 +35,7 @@ const MINT_TIMEOUT_MS = 10_000const TOKEN_TIMEOUT_MS = 10_000-const DENIED_REASON = '尚未配置访问认证(密码或链接 Token),公网与隧道来源一律拒绝。请在本机回环来源的「远程 → 访问入口」中设置访问密码或链接 Token。'--const BROKEN_AUTH_REASON = '认证存储损坏,已视为未配置访问认证:公网与隧道来源一律拒绝。请在本机回环来源的「远程 → 访问入口」中重新设置访问密码。'+const DENIED_REASON = '尚未启用配对认证,公网与隧道来源一律拒绝。请在本机回环来源的「远程 → 访问入口」中启用认证并获取配对码。'const CROSS_SITE_REASON = '跨站来源的请求被拒绝:请用访问链接里的同一域名打开页面后重试;若你是在别的站点里嵌入访问地址,改成本机回环来源或带 ?auth= 的链接。'@@ -275,20 +273,25 @@ function handleRequest(entry: GatewayEntry, request: IncomingMessage, response:}async function dispatchRequest(entry: GatewayEntry, request: IncomingMessage, response: ServerResponse): Promise<void> {- if (isCrossSiteRequest(entry.kind, request.headers, entry.publicHost?.())) {+ const url = new URL(request.url ?? '/', 'http://gateway.invalid')+ const manifest = url.pathname === '/manifest.webmanifest' && (request.method === 'GET' || request.method === 'HEAD')+ if (isCrossSiteRequest(entry.kind, request.headers, entry.publicHost?.(), manifest)) {writeDenied(request, response, CROSS_SITE_REASON)emit(entry, 'source', `已拦下跨站来源请求:${request.method ?? 'GET'} ${request.url ?? '/'}`)return}const session = ensureSourceSession()const source = sourceOf(entry, request, session)+ if (manifest) {+ await forward(entry, request, response, source, session, false)+ return+ }const policy = entry.auth?.()const decision = decideSourceAccess(source, policy)if (decision === 'deny') {- writeDenied(request, response, denyReasonOf(policy))+ writeDenied(request, response, DENIED_REASON)return}- const url = new URL(request.url ?? '/', 'http://gateway.invalid')const exchange = entry.kind !== 'outbound' && source !== 'loopback' && isAuthConfigured(policy) && url.pathname === '/' && ((request.method === 'GET' && url.searchParams.has(AUTH_QUERY)) || isLoginSubmission(request))if (decision === 'authenticate' || exchange) {if (policy === undefined || !await admitAuthenticated(entry, request, response, source, policy))@@ -302,10 +305,6 @@ function sourceOf(entry: GatewayEntry, request: IncomingMessage, session: stringreturn entry.kind === 'tunnel' ? 'tunnel' : classifySource(request.headers, request.socket.remoteAddress, session)}-function denyReasonOf(policy: RemoteAuthPolicy | undefined): string {- return isAuthStorageBroken(policy) ? BROKEN_AUTH_REASON : DENIED_REASON-}-async function admitAuthenticated(entry: GatewayEntry, request: IncomingMessage, response: ServerResponse, source: RemoteSourceClass, policy: RemoteAuthPolicy): Promise<boolean> {const now = Date.now()const bucket = rateLimitKeyOf(source, request.socket.remoteAddress, entry.kind === 'tunnel' ? tunnelClientIpOf(request.headers) : undefined)@@ -324,26 +323,25 @@ async function admitAuthenticated(entry: GatewayEntry, request: IncomingMessage,writeSessionRedirect(response, policy, url.pathname, now)return false}- failAuth(bucket, now, request, response, '链接已失效,请输入访问密码。')+ failAuth(bucket, now, request, response, '链接已失效,请输入新的配对码。')return false}if (isLoginSubmission(request)) {const submitted = parseFormField(await readFormBody(request), LOGIN_FIELD)const latest = entry.auth?.()const completedAt = Date.now()- if (submitted !== undefined && isAuthConfigured(latest) && (verifyPassword(submitted, latest.password) || tokenMatches(submitted, latest.linkToken) || (latest.consumePairingCode?.(submitted) ?? tokenMatches(submitted, latest.pairingCode ?? null)))) {+ if (submitted !== undefined && isAuthConfigured(latest) && (tokenMatches(submitted, latest.linkToken) || (latest.consumePairingCode?.(submitted) ?? tokenMatches(submitted, latest.pairingCode ?? null)))) {authFailures.delete(bucket)writeSessionRedirect(response, latest, `${url.pathname}${url.search}`, completedAt)return false}- failAuth(bucket, completedAt, request, response, '密码不正确。')+ failAuth(bucket, completedAt, request, response, '配对码不正确或已失效。')return false}writeAuthChallenge(request, response, undefined, 401, 0)return false}-/** 登录表单是导航形态的 urlencoded POST:API 客户端带 password 字段的 POST 不得被当成登录(S2 §7.3)。 */function isLoginSubmission(request: IncomingMessage): boolean {if (request.method !== 'POST' || !isNavigationRequest(request.headers))return false@@ -421,7 +419,7 @@ function writeJson(response: ServerResponse, status: number, message: string, reresponse.end(body)}-async function forward(entry: GatewayEntry, request: IncomingMessage, response: ServerResponse, source: RemoteSourceClass, session: string): Promise<void> {+async function forward(entry: GatewayEntry, request: IncomingMessage, response: ServerResponse, source: RemoteSourceClass, session: string, mint = true): Promise<void> {const inject = entry.kind !== 'outbound'const headers = forwardHeadersOf(request.headers, {authority: entry.authority,@@ -429,7 +427,7 @@ async function forward(entry: GatewayEntry, request: IncomingMessage, response:...inject ? { source, session } : { source: 'public', session: 'outbound' },...entry.kind === 'outbound' ? { identity: true } : {},})- const cookie = await ensureMintedCookie(entry)+ const cookie = mint ? await ensureMintedCookie(entry) : undefinedif (cookie !== undefined)headers.cookie = mergeCookieHeader(cookieHeaderOf(headers.cookie), [cookie])await sendUpstream(entry, request, response, headers, { retryable: true, credential: cookie !== undefined }, source)@@ -626,7 +624,7 @@ async function dispatchUpgrade(entry: GatewayEntry, request: IncomingMessage, soconst admitted = decision === 'allow'|| (decision === 'authenticate' && policy !== undefined && verifySession(parseCookieHeader(cookieHeaderOf(request.headers.cookie)).get(SESSION_COOKIE), policy.sessionSecret, Date.now()))if (!admitted) {- rejectUpgrade(socket, decision === 'deny' ? 403 : 401, decision === 'deny' ? denyReasonOf(policy) : '需要认证后才能访问。')+ rejectUpgrade(socket, decision === 'deny' ? 403 : 401, decision === 'deny' ? DENIED_REASON : '需要认证后才能访问。')return}const inject = entry.kind !== 'outbound'diff --git a/packages/dsh-tauri-remote/src/host/service/gateway.utils.test.ts b/packages/dsh-tauri-remote/src/host/service/gateway.utils.test.tsindex cb6b5cef..29f01ccc 100644--- a/packages/dsh-tauri-remote/src/host/service/gateway.utils.test.ts+++ b/packages/dsh-tauri-remote/src/host/service/gateway.utils.test.ts@@ -195,6 +195,19 @@ describe('request shape predicates', () => {expect(isCrossSiteRequest('tunnel', { 'host': '127.0.0.1:38999', 'sec-fetch-site': 'cross-site', 'sec-fetch-mode': 'navigate' })).toBe(false)})+ it('permits a public headerless probe only when explicitly allowed without weakening declared-source checks', () => {+ const headers = { host: '127.0.0.1:38999' }+ expect(isCrossSiteRequest('tunnel', headers)).toBe(true)+ expect(isCrossSiteRequest('tunnel', headers, undefined, true)).toBe(false)+ expect(isCrossSiteRequest('tunnel', { ...headers, origin: 'https://evil.example' }, undefined, true)).toBe(true)+ expect(isCrossSiteRequest('tunnel', { ...headers, referer: 'https://evil.example/' }, undefined, true)).toBe(true)+ expect(isCrossSiteRequest('tunnel', { ...headers, origin: '' }, undefined, true)).toBe(true)+ expect(isCrossSiteRequest('tunnel', { ...headers, 'sec-fetch-site': 'cross-site' }, undefined, true)).toBe(true)+ expect(isCrossSiteRequest('tunnel', { ...headers, 'sec-fetch-site': 'same-site' }, undefined, true)).toBe(true)+ expect(isCrossSiteRequest('tunnel', { ...headers, 'sec-fetch-mode': 'cors' }, undefined, true)).toBe(true)+ expect(isCrossSiteRequest('tunnel', { host: 'trusted.example', origin: 'https://evil.example' }, 'trusted.example', true)).toBe(true)+ })+it('still compares Origin against Host on the tunnel leg while the tunnel domain survives', () => {expect(isCrossSiteRequest('tunnel', { host: 's2-probe.trycloudflare.com', origin: 'https://s2-probe.trycloudflare.com' })).toBe(false)expect(isCrossSiteRequest('tunnel', { host: 's2-probe.trycloudflare.com', origin: 'https://evil.example' })).toBe(true)@@ -339,9 +352,9 @@ describe('cookie helpers', () => {})it('reads a urlencoded form field and ignores blanks', () => {- expect(parseFormField('password=s3cret&next=%2F', 'password')).toBe('s3cret')- expect(parseFormField('password=&next=%2F', 'password')).toBeUndefined()- expect(parseFormField('next=%2F', 'password')).toBeUndefined()+ expect(parseFormField('code=AB23CD45&next=%2F', 'code')).toBe('AB23CD45')+ expect(parseFormField('code=&next=%2F', 'code')).toBeUndefined()+ expect(parseFormField('next=%2F', 'code')).toBeUndefined()})})@@ -380,11 +393,11 @@ describe('compressors', () => {})describe('loginPageHtml', () => {- it('posts the password back to the current URL without inventing another route', () => {+ it('posts the pairing code back to the current URL without a password field or another route', () => {const html = loginPageHtml()- expect(html).toContain('<form method="post">')- expect(html).toContain('name="password"')- expect(html).not.toContain('action=')+ expect(html).toContain('<form id="loginForm" method="post">')+ expect(html).toContain('name="code"')+ expect(html).not.toMatch(/password|action=/i)})it('renders the official branding and accessible pairing form without client assets', () => {@@ -392,8 +405,9 @@ describe('loginPageHtml', () => {expect(html).toContain('<h1>DeepSeek Harness</h1>')expect(html).toContain('<svg')expect(html).toContain('viewBox="0 0 23.16 17.04"')- expect(html).toContain('<label for="password">请输入配对码</label>')- expect(html).toMatch(/<input[^>]*id="password"[^>]*name="password"/)+ expect(html).toContain('<label for="code">请输入配对码</label>')+ expect(html).toMatch(/<input[^>]*id="code"[^>]*type="text"[^>]*name="code"/)+ expect(html).toMatch(/autocomplete="one-time-code"/i)expect(html).toMatch(/<button[^>]*type="submit"[^>]*>连接<\/button>/)expect(html).not.toMatch(/<script|<link|\bsrc=|maxlength=|__ModuleLoader__/i)})diff --git a/packages/dsh-tauri-remote/src/host/service/gateway.utils.ts b/packages/dsh-tauri-remote/src/host/service/gateway.utils.tsindex 1e2336e8..32a43a1c 100644--- a/packages/dsh-tauri-remote/src/host/service/gateway.utils.ts+++ b/packages/dsh-tauri-remote/src/host/service/gateway.utils.ts@@ -121,7 +121,9 @@ export function isNavigationRequest(headers: IncomingHttpHeaders): boolean {* 元数据缺失且又无 Origin / Referer 可对时一律拒绝。* 跨站的文档导航(壳层 iframe、外站链接)一律放行:落地文档的源随即变成入口自身,后续请求都同源。*/-export function isCrossSiteRequest(kind: RemoteGatewayEntryKind, headers: IncomingHttpHeaders, publicHost?: string | undefined): boolean {+export function isCrossSiteRequest(kind: RemoteGatewayEntryKind, headers: IncomingHttpHeaders, publicHost?: string | undefined, allowHeaderless = false): boolean {+ if (allowHeaderless && headers.origin === undefined && headers.referer === undefined && headers['sec-fetch-site'] === undefined && headers['sec-fetch-mode'] === undefined)+ return falseconst rewritten = hostRewritten(kind, headers)const origin = headerText(headers.origin)if (origin !== undefined && origin !== '') {diff --git a/packages/dsh-tauri-remote/src/host/service/tunnel.test.ts b/packages/dsh-tauri-remote/src/host/service/tunnel.test.tsindex 70f0e05b..366e4da9 100644--- a/packages/dsh-tauri-remote/src/host/service/tunnel.test.ts+++ b/packages/dsh-tauri-remote/src/host/service/tunnel.test.ts@@ -11,7 +11,7 @@ import { tunnel } from './tunnel'const HOST_PORT = 45_678-const POLICY: RemoteAuthPolicy = { enabled: true, scope: 'public_only', password: null, linkToken: 'link-token', sessionSecret: 'session-secret' }+const POLICY: RemoteAuthPolicy = { enabled: true, scope: 'public_only', linkToken: 'link-token', sessionSecret: 'session-secret' }interface Spawned {env?: NodeJS.ProcessEnv@@ -80,6 +80,7 @@ beforeEach(() => {})afterEach(async () => {+ vi.restoreAllMocks()await tunnel.dispose()await gateway.dispose()setCurrentHostInstance(undefined)@@ -158,6 +159,54 @@ describe('tunnel 生命周期', () => {expect((await tunnel.status()).error).toContain('落盘')})+ it.each(['落盘失败', '进程退出'])('%s 后重启必须等旧入口回收,不能被旧清理覆盖状态', async (cause) => {+ await tunnel.start('quick')+ const originalStop = gateway.stop+ const originalStart = gateway.start+ let release: () => void = () => {}+ const gate = new Promise<void>((resolve) => {+ release = resolve+ })+ let entered = false+ let completed = false+ const cleanup = vi.spyOn(gateway, 'stop').mockImplementationOnce(async (id) => {+ await originalStop(id)+ entered = true+ await gate+ completed = true+ })+ try {+ if (cause === '落盘失败') {+ writeFileSync(join(process.env.DSH_HOME ?? '', 'remote', 'access.json'), '{ broken')+ spawned[0]!.handlers.onLine('INF Your quick Tunnel has been created! Visit it at https://bold-fox-abc.trycloudflare.com')+ }+ else {+ spawned[0]!.crash(1)+ }+ await vi.waitFor(() => expect(entered).toBe(true))+ expect((await tunnel.status()).state).toBe('error')+ writeAccessDocument(defaultAccessDocument())+ const order: boolean[] = []+ vi.spyOn(gateway, 'start').mockImplementationOnce(async (options) => {+ order.push(completed)+ release()+ return await originalStart(options)+ })+ const restarting = tunnel.start('quick')+ setImmediate(release)+ await restarting+ await cleanup.mock.results[0]!.value+ expect(order).toEqual([true])+ const status = await tunnel.status()+ expect(status.state).toBe('starting')+ expect(status.port).toBe(gateway.status('tunnel')?.port)+ expect(spawned).toHaveLength(2)+ }+ finally {+ release()+ }+ })+it('token 模式缺凭据或主机名时拒绝启动,且不落盘、不装入口、不起进程', async () => {await expect(tunnel.start('token')).rejects.toThrowError('Tunnel Token')await expect(tunnel.start('token', 'cf-token')).rejects.toThrowError('公开主机名')diff --git a/packages/dsh-tauri-remote/src/host/service/tunnel.ts b/packages/dsh-tauri-remote/src/host/service/tunnel.tsindex 875b6ef1..613959f3 100644--- a/packages/dsh-tauri-remote/src/host/service/tunnel.ts+++ b/packages/dsh-tauri-remote/src/host/service/tunnel.ts@@ -72,7 +72,6 @@ export const tunnel = defineService({}},- /** 纯校验:不合法的入参在改动认证状态之前就抛错,避免「启动失败却已经生成密码」。 */assertStartable(mode: RemoteTunnelMode, token?: string, hostname?: string): void {tunnelConfigOf(mode, token, hostname)},@@ -316,7 +315,10 @@ function onLine(mode: RemoteTunnelMode, line: string, generation: number): void}catch (error) {// access.json 损坏时写入会抛错:这里必须自己兜住,否则异常从子进程日志回调里冒出去。- void fail(`已拿到隧道域名但无法落盘:${messageOf(error)}`)+ void enqueue(async () => {+ if (generation === activation)+ await fail(`已拿到隧道域名但无法落盘:${messageOf(error)}`)+ })return}void ready(found)@@ -333,7 +335,10 @@ function onExit(code: number | null, signal: NodeJS.Signals | null, generation:url = undefinedfailure = `cloudflared 已退出(${signal ?? code ?? '未知原因'})`note('state', failure)- void gateway.stop(ENTRY_ID)+ void enqueue(async () => {+ if (generation === activation)+ await gateway.stop(ENTRY_ID)+ })}function hostOf(value: string): string | null {diff --git a/packages/dsh-tauri-remote/src/host/types/index.ts b/packages/dsh-tauri-remote/src/host/types/index.tsindex 5e2dd935..ba69d32d 100644--- a/packages/dsh-tauri-remote/src/host/types/index.ts+++ b/packages/dsh-tauri-remote/src/host/types/index.ts@@ -209,19 +209,10 @@ export type RemoteAccessDecision = 'allow' | 'authenticate' | 'deny'export type RemoteAuthScope = 'public_only' | 'all'-/** 访问密码的落盘形态;`salt` 与 `hash` 均为 base64(S2 §7.4)。 */-export interface RemotePasswordRecord {- algo: 'pbkdf2-sha256'- salt: string- iterations: number- hash: string-}-/** 认证要素快照:由持久化配置推导,每次请求重新读取,使配置变更即时生效。 */export interface RemoteAuthPolicy {enabled: booleanscope: RemoteAuthScope- password: RemotePasswordRecord | nulllinkToken: string | nullsessionSecret: string/** 当前临时配对码:与永久凭据并行的额外凭据,5 分钟轮换。 */diff --git a/packages/dsh-tauri-remote/src/host/utils/auth.test.ts b/packages/dsh-tauri-remote/src/host/utils/auth.test.tsindex 0ab8cbea..3c08a041 100644--- a/packages/dsh-tauri-remote/src/host/utils/auth.test.ts+++ b/packages/dsh-tauri-remote/src/host/utils/auth.test.ts@@ -1,119 +1,53 @@-import type { RemotePasswordRecord } from '../types/index'import { describe, expect, it } from 'vitest'-import { createLinkToken, createSessionSecret, hashPassword, isPasswordRecordUsable, rateLimitAfterFailure, rateLimitBlockedMs, signSession, tokenMatches, verifyPassword, verifySession } from './auth'--const ITERATIONS = 1000--const SESSION_TTL_MS = 30 * 24 * 60 * 60 * 1000+import { createLinkToken, createSessionSecret, rateLimitAfterFailure, rateLimitBlockedMs, signSession, tokenMatches, verifySession } from './auth'const FAILURE_LIMIT = 5const BAN_MS = 5 * 60 * 1000-function recordOf(password: string): RemotePasswordRecord {- return hashPassword(password, ITERATIONS)-}--describe('hashPassword', () => {- it('produces a pbkdf2-sha256 record with the configured iteration count', () => {- const record = recordOf('correct horse')- expect(record.algo).toBe('pbkdf2-sha256')- expect(record.iterations).toBe(ITERATIONS)- expect(record.salt).not.toBe('')- expect(record.hash).not.toBe('')- })-- it('defaults to the pinned iteration constant', () => {- expect(hashPassword('correct horse')).toMatchObject({ iterations: 600_000 })- })-- it('salts every record independently, so the same password hashes differently', () => {- expect(recordOf('correct horse').hash).not.toBe(recordOf('correct horse').hash)- expect(recordOf('correct horse').salt).not.toBe(recordOf('correct horse').salt)- })-})--describe('verifyPassword', () => {- it('accepts the exact password and rejects any other', () => {- const record = recordOf('correct horse')- expect(verifyPassword('correct horse', record)).toBe(true)- expect(verifyPassword('correct hors', record)).toBe(false)- expect(verifyPassword('correct horse ', record)).toBe(false)- expect(verifyPassword('Correct horse', record)).toBe(false)- expect(verifyPassword('', record)).toBe(false)- })-- it('rejects a record that carries no password at all', () => {- expect(verifyPassword('correct horse', null)).toBe(false)- })+const SESSION_VALUE = 'v1.1700000000000.1702592000000.f16b0583c93fa78f45152f9dcf0b91d5b8e2d4c1642f816307ba020269546e85'- it.each([- { algo: 'pbkdf2-sha256', salt: 'not-base64!', iterations: ITERATIONS, hash: 'aGFzaA==' },- { algo: 'pbkdf2-sha256', salt: 'c2FsdA==', iterations: ITERATIONS, hash: 'not-base64!' },- { algo: 'pbkdf2-sha256', salt: 'c2FsdA==', iterations: 0, hash: 'aGFzaA==' },- { algo: 'pbkdf2-sha256', salt: 'c2FsdA==', iterations: 1.5, hash: 'aGFzaA==' },- { algo: 'scrypt', salt: 'c2FsdA==', iterations: ITERATIONS, hash: 'aGFzaA==' },- ])('treats the corrupted record %j as unverifiable instead of throwing', (record) => {- expect(verifyPassword('correct horse', record as unknown as RemotePasswordRecord)).toBe(false)- })-})+const SESSION_SECRET = 'session-secret'-describe('isPasswordRecordUsable', () => {- it('accepts a freshly hashed record and rejects a missing one', () => {- expect(isPasswordRecordUsable(recordOf('correct horse'))).toBe(true)- expect(isPasswordRecordUsable(null)).toBe(false)- })+const ISSUED_AT = 1_700_000_000_000- it.each([- { algo: 'pbkdf2-sha256', salt: 'not-base64!', iterations: ITERATIONS, hash: 'aGFzaA==' },- { algo: 'pbkdf2-sha256', salt: '', iterations: ITERATIONS, hash: 'aGFzaA==' },- { algo: 'pbkdf2-sha256', salt: 'c2FsdA==', iterations: ITERATIONS, hash: 'not-base64!' },- { algo: 'pbkdf2-sha256', salt: 'c2FsdA==', iterations: ITERATIONS, hash: 'aGFzaA==' },- { algo: 'pbkdf2-sha256', salt: 'c2FsdA==', iterations: 0, hash: 'aGFzaA==' },- { algo: 'pbkdf2-sha256', salt: 'c2FsdA==', iterations: -1, hash: 'aGFzaA==' },- { algo: 'scrypt', salt: 'c2FsdA==', iterations: ITERATIONS, hash: 'aGFzaA==' },- ])('rejects the corrupted record %j', (record) => {- expect(isPasswordRecordUsable(record as unknown as RemotePasswordRecord)).toBe(false)- })-})+const EXPIRES_AT = 1_702_592_000_000describe('signSession / verifySession', () => {- const SECRET = createSessionSecret()-- it('round-trips a freshly signed session and reports its issue and expiry times', () => {- const now = 1_700_000_000_000- const ticket = signSession(SECRET, now)- expect(ticket.issuedAt).toBe(now)- expect(ticket.expiresAt).toBe(now + SESSION_TTL_MS)- expect(ticket.value.split('.')).toEqual([expect.any(String), String(now), String(now + SESSION_TTL_MS), expect.any(String)])- expect(verifySession(ticket.value, SECRET, now)).toBe(true)- expect(verifySession(ticket.value, SECRET, ticket.expiresAt - 1)).toBe(true)+ it('matches the fixed HMAC-SHA256 session fixture and verifies it before expiry', () => {+ expect(signSession(SESSION_SECRET, ISSUED_AT)).toEqual({ value: SESSION_VALUE, issuedAt: ISSUED_AT, expiresAt: EXPIRES_AT })+ expect(verifySession(SESSION_VALUE, SESSION_SECRET, ISSUED_AT)).toBe(true)+ expect(verifySession(SESSION_VALUE, SESSION_SECRET, EXPIRES_AT - 1)).toBe(true)})- it('rejects an expired session', () => {- const now = 1_700_000_000_000- const ticket = signSession(SECRET, now, 1000)- expect(verifySession(ticket.value, SECRET, now + 1001)).toBe(false)- expect(verifySession(ticket.value, SECRET, now + 1000)).toBe(false)+ it('rejects an expired session at and after its expiry', () => {+ expect(verifySession(SESSION_VALUE, SESSION_SECRET, EXPIRES_AT)).toBe(false)+ expect(verifySession(SESSION_VALUE, SESSION_SECRET, EXPIRES_AT + 1)).toBe(false)})- it('rejects a tampered expiry, a tampered issue time, a tampered signature and a foreign secret', () => {- const now = 1_700_000_000_000- const ticket = signSession(SECRET, now)- const [version, , , mac] = ticket.value.split('.')- expect(verifySession(`${version}.${now + 999_999}.${now + 999_999}.${mac}`, SECRET, now)).toBe(false)- expect(verifySession(`${version}.${now - 1}.${now + SESSION_TTL_MS}.${mac}`, SECRET, now)).toBe(false)- expect(verifySession(`${ticket.value}x`, SECRET, now)).toBe(false)- expect(verifySession(`${version}.${now}.${now + SESSION_TTL_MS}.${mac?.toUpperCase()}`, SECRET, now)).toBe(false)- expect(verifySession(ticket.value, createSessionSecret(), now)).toBe(false)+ it('rejects a tampered expiry, issue time, signature and a foreign secret', () => {+ const [, , , mac] = SESSION_VALUE.split('.')+ expect(verifySession(`v1.${ISSUED_AT + 999_999}.${EXPIRES_AT + 999_999}.${mac}`, SESSION_SECRET, ISSUED_AT)).toBe(false)+ expect(verifySession(`v1.${ISSUED_AT - 1}.${EXPIRES_AT}.${mac}`, SESSION_SECRET, ISSUED_AT)).toBe(false)+ expect(verifySession(`${SESSION_VALUE}x`, SESSION_SECRET, ISSUED_AT)).toBe(false)+ expect(verifySession(`v1.${ISSUED_AT}.${EXPIRES_AT}.${mac?.toUpperCase()}`, SESSION_SECRET, ISSUED_AT)).toBe(false)+ expect(verifySession(SESSION_VALUE, 'foreign-secret', ISSUED_AT)).toBe(false)})it.each([undefined, '', 'v1', 'v1.123', 'v1.123.456', 'v2.1.9999999999999.abc', 'v1.abc.def.ghi'])('rejects the malformed session value %j', (value) => {- expect(verifySession(value, SECRET, 1_700_000_000_000)).toBe(false)+ expect(verifySession(value, SESSION_SECRET, ISSUED_AT)).toBe(false)})it('refuses to verify anything while no secret is configured', () => {- expect(verifySession(signSession(SECRET, 1).value, '', 0)).toBe(false)+ expect(verifySession(SESSION_VALUE, '', ISSUED_AT)).toBe(false)+ })+})++describe('createSessionSecret', () => {+ it('generates independent 32-byte base64url secrets', () => {+ const first = createSessionSecret()+ expect(first).toMatch(/^[\w-]{43}$/u)+ expect(createSessionSecret()).not.toBe(first)})})diff --git a/packages/dsh-tauri-remote/src/host/utils/auth.ts b/packages/dsh-tauri-remote/src/host/utils/auth.tsindex f3e09671..bd7da947 100644--- a/packages/dsh-tauri-remote/src/host/utils/auth.ts+++ b/packages/dsh-tauri-remote/src/host/utils/auth.ts@@ -1,6 +1,6 @@-import type { RemoteAuthFailureRecord, RemotePasswordRecord, RemoteSessionTicket } from '../types/index'+import type { RemoteAuthFailureRecord, RemoteSessionTicket } from '../types/index'import { Buffer } from 'node:buffer'-import { createHmac, pbkdf2Sync, randomBytes, randomInt, timingSafeEqual } from 'node:crypto'+import { createHmac, randomBytes, randomInt, timingSafeEqual } from 'node:crypto'const SESSION_TTL_MS = 30 * 24 * 60 * 60 * 1000@@ -8,43 +8,14 @@ const AUTH_FAILURE_LIMIT = 5const AUTH_BAN_MS = 5 * 60 * 1000-/** OWASP 对 PBKDF2-SHA256 的现行建议下限(本机实测约 48ms/次)。 */-const PBKDF2_ITERATIONS = 600_000--const HASH_BYTES = 32--const SALT_BYTES = 16-const SECRET_BYTES = 32-const PASSWORD_LENGTH = 20-const LINK_TOKEN_LENGTH = 8const LINK_TOKEN_ALPHABET = '23456789ABCDEFGHJKLMNPQRSTUVWXYZ'const SESSION_VERSION = 'v1'-export function hashPassword(password: string, iterations = PBKDF2_ITERATIONS): RemotePasswordRecord {- const salt = randomBytes(SALT_BYTES)- return {- algo: 'pbkdf2-sha256',- salt: salt.toString('base64'),- iterations,- hash: derive(password, salt, iterations).toString('base64'),- }-}--export function verifyPassword(password: string, record: RemotePasswordRecord | null): boolean {- const usable = usablePasswordOf(record)- return usable !== undefined && matches(derive(password, usable.salt, usable.iterations), usable.hash)-}--/** 密码记录可用性:算法、迭代次数、salt 与 hash 编码及长度全部合规才可用(S2 §11 的损坏判定复用同一份规则)。 */-export function isPasswordRecordUsable(record: RemotePasswordRecord | null): record is RemotePasswordRecord {- return usablePasswordOf(record) !== undefined-}-export function signSession(secret: string, now: number, ttlMs = SESSION_TTL_MS): RemoteSessionTicket {const expiresAt = now + ttlMsreturn { value: `${SESSION_VERSION}.${now}.${expiresAt}.${signatureOf(secret, now, expiresAt)}`, issuedAt: now, expiresAt }@@ -67,15 +38,6 @@ export function createLinkToken(): string {return Array.from({ length: LINK_TOKEN_LENGTH }, () => LINK_TOKEN_ALPHABET[randomInt(LINK_TOKEN_ALPHABET.length)]).join('')}-export function generateAccessPassword(length = PASSWORD_LENGTH): string {- const alphabet = '23456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'- const bytes = randomBytes(length)- let password = ''- for (const byte of bytes)- password += alphabet[byte % alphabet.length]- return password-}-export function createSessionSecret(): string {return randomBytes(SECRET_BYTES).toString('base64url')}@@ -102,21 +64,6 @@ export function rateLimitBlockedMs(record: RemoteAuthFailureRecord | undefined,return record === undefined ? 0 : Math.max(0, record.bannedUntil - now)}-// --- internal ----function usablePasswordOf(record: RemotePasswordRecord | null): { salt: Buffer, hash: Buffer, iterations: number } | undefined {- if (record === null || record.algo !== 'pbkdf2-sha256' || !Number.isInteger(record.iterations) || record.iterations <= 0)- return undefined- const salt = decodeBase64(record.salt)- const hash = decodeBase64(record.hash)- if (salt === undefined || salt.length === 0 || hash === undefined || hash.length !== HASH_BYTES)- return undefined- return { salt, hash, iterations: record.iterations }-}--function derive(password: string, salt: Buffer, iterations: number): Buffer {- return pbkdf2Sync(password, salt, iterations, HASH_BYTES, 'sha256')-}-function signatureOf(secret: string, issuedAt: number, expiresAt: number): string {return createHmac('sha256', secret).update(`${SESSION_VERSION}.${issuedAt}.${expiresAt}`).digest('hex')}@@ -124,8 +71,3 @@ function signatureOf(secret: string, issuedAt: number, expiresAt: number): strinfunction matches(left: Buffer, right: Buffer): boolean {return left.length === right.length && timingSafeEqual(left, right)}--function decodeBase64(value: string): Buffer | undefined {- const decoded = Buffer.from(value, 'base64')- return decoded.toString('base64') === value ? decoded : undefined-}diff --git a/packages/dsh-tauri-remote/src/host/utils/cloudflared.test.ts b/packages/dsh-tauri-remote/src/host/utils/cloudflared.test.tsindex 20cee097..fb4018ec 100644--- a/packages/dsh-tauri-remote/src/host/utils/cloudflared.test.ts+++ b/packages/dsh-tauri-remote/src/host/utils/cloudflared.test.ts@@ -1,17 +1,35 @@import { Buffer } from 'node:buffer'+import { execFile } from 'node:child_process'import { existsSync, mkdtempSync, rmSync } from 'node:fs'import { tmpdir } from 'node:os'import { join } from 'pathe'-import { describe, expect, it } from 'vitest'+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'import { cloudflaredAsset, cloudflaredDownloadUrls, fetchCloudflaredRelease, isCloudflaredVersion, parseQuickTunnelUrl, quickTunnelArgs, resolveCloudflared, tokenTunnelArgs, tokenTunnelEnv } from './cloudflared'+vi.mock('node:child_process', () => ({+ execFile: vi.fn((_binary: string, _args: string[], _options: object, callback: (error: Error) => void) => callback(new Error('ENOENT'))),+ spawn: vi.fn(),+}))++beforeEach(() => {+ vi.stubEnv('CLOUDFLARED_PATH', '')+ vi.stubEnv('CLOUDFLARED_VERSION', '')+})++afterEach(() => {+ vi.unstubAllGlobals()+ vi.unstubAllEnvs()+ vi.clearAllMocks()+ vi.restoreAllMocks()+})+describe('cloudflared 平台表', () => {it('覆盖受支持的平台组合', () => {- expect(cloudflaredAsset('darwin', 'arm64')).toEqual({ asset: 'cloudflared-darwin-arm64.tgz', executable: 'cloudflared', archive: true })- expect(cloudflaredAsset('darwin', 'x64')).toEqual({ asset: 'cloudflared-darwin-amd64.tgz', executable: 'cloudflared', archive: true })- expect(cloudflaredAsset('linux', 'x64')).toEqual({ asset: 'cloudflared-linux-amd64', executable: 'cloudflared', archive: false })- expect(cloudflaredAsset('linux', 'arm64')).toEqual({ asset: 'cloudflared-linux-arm64', executable: 'cloudflared', archive: false })- expect(cloudflaredAsset('win32', 'x64')).toEqual({ asset: 'cloudflared-windows-amd64.exe', executable: 'cloudflared.exe', archive: false })+ expect(cloudflaredAsset('darwin', 'arm64')).toEqual({ asset: 'cloudflared-darwin-arm64.tgz', executable: 'cloudflared', archive: true, digest: 'sha256:a2f79ff7b9420aa537d74af239f376da170bbabeb529aec416002adac6a72e70' })+ expect(cloudflaredAsset('darwin', 'x64')).toEqual({ asset: 'cloudflared-darwin-amd64.tgz', executable: 'cloudflared', archive: true, digest: 'sha256:903845b81828c8cb3c5d13d816a2de71c06a3da5785469df8eb0e1b736d92f9f' })+ expect(cloudflaredAsset('linux', 'x64')).toEqual({ asset: 'cloudflared-linux-amd64', executable: 'cloudflared', archive: false, digest: 'sha256:d33ff2d14475178d2012c2c56beba87389ac5ded27649519f198a7d3134a99db' })+ expect(cloudflaredAsset('linux', 'arm64')).toEqual({ asset: 'cloudflared-linux-arm64', executable: 'cloudflared', archive: false, digest: 'sha256:e6422b9d4f72d3194bc5a38676f13667c06666523217b842a877d72a80b5ac08' })+ expect(cloudflaredAsset('win32', 'x64')).toEqual({ asset: 'cloudflared-windows-amd64.exe', executable: 'cloudflared.exe', archive: false, digest: 'sha256:86aee4017b26625cee8484c113558f48effa4cd47f7aa05fcf425604e5d2b23c' })})it('不支持的平台没有资产,调用方据此给出可读错误', () => {@@ -57,6 +75,30 @@ describe('下载源与命令行', () => {}})+ it.each([+ [403, undefined],+ [429, ''],+ [403, '2026.10.0'],+ ])('官方发布 API 返回 %i(版本 %s)时使用固定版本的官方摘要', async (status, version) => {+ const fetcher = vi.fn(async () => new Response(null, { status }))+ vi.stubGlobal('fetch', fetcher)+ await expect(fetchCloudflaredRelease('cloudflared-linux-amd64', version)).resolves.toEqual({+ tag: '2026.10.0',+ digest: 'sha256:d33ff2d14475178d2012c2c56beba87389ac5ded27649519f198a7d3134a99db',+ })+ expect(fetcher).toHaveBeenCalledTimes(1)+ })++ it.each([+ [403, 'cloudflared-linux-amd64', '2026.9.0'],+ [403, 'cloudflared-freebsd-amd64', undefined],+ [404, 'cloudflared-linux-amd64', undefined],+ [500, 'cloudflared-linux-amd64', undefined],+ ])('元数据 HTTP %i(资产 %s,版本 %s)没有可信兜底时保留错误', async (status, asset, version) => {+ vi.stubGlobal('fetch', async () => new Response(null, { status }))+ await expect(fetchCloudflaredRelease(asset, version)).rejects.toThrow(`发布元数据不可用(HTTP ${status})`)+ })+it('quick 模式指向本机隧道入口且关闭自动更新', () => {expect(quickTunnelArgs('http://127.0.0.1:3089')).toEqual(['tunnel', '--no-autoupdate', '--url', 'http://127.0.0.1:3089'])})@@ -69,6 +111,37 @@ describe('下载源与命令行', () => {})describe('下载校验', () => {+ it('发布 API 403 时仍尝试固定 tag 下载,但拒绝写出摘要不匹配的文件', async () => {+ const home = mkdtempSync(join(tmpdir(), 'dsh-cloudflared-rate-limit-'))+ const executable = process.platform === 'win32' ? 'cloudflared.exe' : 'cloudflared'+ const names: Record<string, string> = {+ 'darwin-arm64': 'cloudflared-darwin-arm64.tgz',+ 'darwin-x64': 'cloudflared-darwin-amd64.tgz',+ 'linux-x64': 'cloudflared-linux-amd64',+ 'linux-arm64': 'cloudflared-linux-arm64',+ 'win32-x64': 'cloudflared-windows-amd64.exe',+ }+ const url = `https://github.com/cloudflare/cloudflared/releases/download/2026.10.0/${names[`${process.platform}-${process.arch}`]}`+ const fetcher = vi.fn(async (input: string | URL) => String(input).includes('api.github.com')+ ? new Response(null, { status: 403 })+ : new Response(Buffer.from('junk'), { headers: { 'content-length': '4' } }))+ vi.stubEnv('DSH_HOME', home)+ vi.stubGlobal('fetch', fetcher)+ try {+ await expect(resolveCloudflared()).rejects.toThrow('SHA-256 校验失败')+ expect(fetcher.mock.calls.map(([input]) => String(input))).toEqual([+ 'https://api.github.com/repos/cloudflare/cloudflared/releases/latest',+ url,+ `https://ghfast.top/${url}`,+ ])+ expect(existsSync(join(home, 'remote', 'bin', executable))).toBe(false)+ expect(vi.mocked(execFile).mock.calls.map(([binary]) => binary)).toEqual(['cloudflared'])+ }+ finally {+ rmSync(home, { recursive: true, force: true })+ }+ })+it('摘要不匹配时拒绝执行,且不写出可执行文件', async () => {const originalFetch = globalThis.fetchconst home = mkdtempSync(join(tmpdir(), 'dsh-cloudflared-verify-'))diff --git a/packages/dsh-tauri-remote/src/host/utils/cloudflared.ts b/packages/dsh-tauri-remote/src/host/utils/cloudflared.tsindex 8f8f581a..238348f0 100644--- a/packages/dsh-tauri-remote/src/host/utils/cloudflared.ts+++ b/packages/dsh-tauri-remote/src/host/utils/cloudflared.ts@@ -18,6 +18,9 @@ const RELEASE_API = 'https://api.github.com/repos/cloudflare/cloudflared/releaseconst RELEASE_TIMEOUT_MS = 20_000+// ponytail: API 限流时固定已核验版本,升级时同步官方资产摘要。+const FALLBACK_VERSION = '2026.10.0'+const MIRROR_PREFIX = 'https://ghfast.top/'const STATE_DIR = 'remote'@@ -44,14 +47,15 @@ export interface CloudflaredAsset {asset: stringexecutable: stringarchive: boolean+ digest: string}const ASSETS: Record<string, CloudflaredAsset> = {- 'darwin-arm64': { asset: 'cloudflared-darwin-arm64.tgz', executable: 'cloudflared', archive: true },- 'darwin-x64': { asset: 'cloudflared-darwin-amd64.tgz', executable: 'cloudflared', archive: true },- 'linux-x64': { asset: 'cloudflared-linux-amd64', executable: 'cloudflared', archive: false },- 'linux-arm64': { asset: 'cloudflared-linux-arm64', executable: 'cloudflared', archive: false },- 'win32-x64': { asset: 'cloudflared-windows-amd64.exe', executable: 'cloudflared.exe', archive: false },+ 'darwin-arm64': { asset: 'cloudflared-darwin-arm64.tgz', executable: 'cloudflared', archive: true, digest: 'sha256:a2f79ff7b9420aa537d74af239f376da170bbabeb529aec416002adac6a72e70' },+ 'darwin-x64': { asset: 'cloudflared-darwin-amd64.tgz', executable: 'cloudflared', archive: true, digest: 'sha256:903845b81828c8cb3c5d13d816a2de71c06a3da5785469df8eb0e1b736d92f9f' },+ 'linux-x64': { asset: 'cloudflared-linux-amd64', executable: 'cloudflared', archive: false, digest: 'sha256:d33ff2d14475178d2012c2c56beba87389ac5ded27649519f198a7d3134a99db' },+ 'linux-arm64': { asset: 'cloudflared-linux-arm64', executable: 'cloudflared', archive: false, digest: 'sha256:e6422b9d4f72d3194bc5a38676f13667c06666523217b842a877d72a80b5ac08' },+ 'win32-x64': { asset: 'cloudflared-windows-amd64.exe', executable: 'cloudflared.exe', archive: false, digest: 'sha256:86aee4017b26625cee8484c113558f48effa4cd47f7aa05fcf425604e5d2b23c' },}export function cloudflaredAsset(platform: string = process.platform, arch: string = process.arch): CloudflaredAsset | undefined {@@ -75,8 +79,12 @@ export interface CloudflaredRelease {export async function fetchCloudflaredRelease(asset: string, version?: string): Promise<CloudflaredRelease> {const url = version === undefined || version === '' ? RELEASE_API : `https://api.github.com/repos/cloudflare/cloudflared/releases/tags/${version}`const response = await fetch(url, { signal: AbortSignal.timeout(RELEASE_TIMEOUT_MS), headers: { accept: 'application/vnd.github+json' } })- if (!response.ok)+ if (!response.ok) {+ const fallback = Object.values(ASSETS).find(entry => entry.asset === asset)+ if ((response.status === 403 || response.status === 429) && (version === undefined || version === '' || version === FALLBACK_VERSION) && fallback !== undefined)+ return { tag: FALLBACK_VERSION, digest: fallback.digest }throw new Error(`发布元数据不可用(HTTP ${response.status})`)+ }const body = await response.json() as { tag_name?: unknown, assets?: unknown }const tag = typeof body.tag_name === 'string' ? body.tag_name : ''const entries = Array.isArray(body.assets) ? body.assets : []diff --git a/packages/dsh-tauri-remote/src/host/utils/source.test.ts b/packages/dsh-tauri-remote/src/host/utils/source.test.tsindex ac052db9..17ab2456 100644--- a/packages/dsh-tauri-remote/src/host/utils/source.test.ts+++ b/packages/dsh-tauri-remote/src/host/utils/source.test.ts@@ -1,17 +1,13 @@import type { IncomingHttpHeaders } from 'node:http'-import type { RemoteAccessDecision, RemoteAuthPolicy, RemotePasswordRecord, RemoteSourceClass } from '../types/index'+import type { RemoteAccessDecision, RemoteAuthPolicy, RemoteSourceClass } from '../types/index'import { describe, expect, it } from 'vitest'-import { classifyPeer, classifySource, decideSourceAccess, isAuthConfigured, isAuthStorageBroken, isIpAddress, isLoopbackPeer, isLoopbackSource, rateLimitKeyOf } from './source'+import { classifyPeer, classifySource, decideSourceAccess, isAuthConfigured, isIpAddress, isLoopbackPeer, isLoopbackSource, rateLimitKeyOf } from './source'const SESSION = 'session-token'-const PASSWORD: RemotePasswordRecord = { algo: 'pbkdf2-sha256', salt: 'c2FsdA==', iterations: 1, hash: 'AQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQE=' }--const CORRUPT_PASSWORD: RemotePasswordRecord = { ...PASSWORD, hash: 'aGFzaA==' }-const NO_AUTH: undefined = undefined-const PUBLIC_ONLY: RemoteAuthPolicy = { enabled: true, scope: 'public_only', password: PASSWORD, linkToken: null, sessionSecret: SESSION }+const PUBLIC_ONLY: RemoteAuthPolicy = { enabled: true, scope: 'public_only', linkToken: 'AB23CD45', sessionSecret: SESSION }const ALL_SOURCES: RemoteAuthPolicy = { ...PUBLIC_ONLY, scope: 'all' }@@ -154,29 +150,28 @@ describe('isLoopbackSource', () => {})describe('isAuthConfigured', () => {+ it('treats an enabled pairing-only policy as configured', () => {+ const pairingOnly: RemoteAuthPolicy = { ...PUBLIC_ONLY, linkToken: null, pairingCode: 'AB23CD45' }+ expect(isAuthConfigured(pairingOnly)).toBe(true)+ expect(isAuthConfigured({ ...pairingOnly, enabled: false })).toBe(false)+ expect(decideSourceAccess('public', pairingOnly)).toBe('authenticate')+ expect(decideSourceAccess('tunnel', pairingOnly)).toBe('authenticate')+ expect(decideSourceAccess('private', pairingOnly)).toBe('allow')+ expect(decideSourceAccess('private', { ...pairingOnly, scope: 'all' })).toBe('authenticate')+ })+it('requires the switch plus at least one credential', () => {expect(isAuthConfigured(NO_AUTH)).toBe(false)expect(isAuthConfigured({ ...PUBLIC_ONLY, enabled: false })).toBe(false)- expect(isAuthConfigured({ ...PUBLIC_ONLY, password: null, linkToken: null })).toBe(false)- expect(isAuthConfigured({ ...PUBLIC_ONLY, password: null, linkToken: '' })).toBe(false)+ expect(isAuthConfigured({ ...PUBLIC_ONLY, linkToken: null })).toBe(false)+ expect(isAuthConfigured({ ...PUBLIC_ONLY, linkToken: '' })).toBe(false)expect(isAuthConfigured(PUBLIC_ONLY)).toBe(true)- expect(isAuthConfigured({ ...PUBLIC_ONLY, password: null, linkToken: 'token' })).toBe(true)+ expect(isAuthConfigured({ ...PUBLIC_ONLY, linkToken: 'token' })).toBe(true)})- it('treats a corrupted password record without a link token as unconfigured', () => {- expect(isAuthConfigured({ ...PUBLIC_ONLY, password: CORRUPT_PASSWORD })).toBe(false)- expect(isAuthConfigured({ ...PUBLIC_ONLY, password: CORRUPT_PASSWORD, linkToken: 'token' })).toBe(true)- })-})--describe('isAuthStorageBroken', () => {- it('reports corruption only while no usable credential remains', () => {- expect(isAuthStorageBroken(NO_AUTH)).toBe(false)- expect(isAuthStorageBroken(PUBLIC_ONLY)).toBe(false)- expect(isAuthStorageBroken({ ...PUBLIC_ONLY, password: null, linkToken: null })).toBe(false)- expect(isAuthStorageBroken({ ...PUBLIC_ONLY, password: CORRUPT_PASSWORD })).toBe(true)- expect(isAuthStorageBroken({ ...PUBLIC_ONLY, password: CORRUPT_PASSWORD, linkToken: 'token' })).toBe(false)- expect(isAuthStorageBroken({ ...PUBLIC_ONLY, password: CORRUPT_PASSWORD, enabled: false })).toBe(false)+ it.each([undefined, ''])('does not configure authentication with an empty pairing code %j', (pairingCode) => {+ expect(isAuthConfigured({ ...PUBLIC_ONLY, linkToken: null, pairingCode })).toBe(false)+ expect(isAuthConfigured({ ...PUBLIC_ONLY, linkToken: '', pairingCode })).toBe(false)})})@@ -209,22 +204,22 @@ describe('decideSourceAccess', () => {}it('treats an enabled switch without any credential as unconfigured', () => {- const halfOpen: RemoteAuthPolicy = { ...PUBLIC_ONLY, password: null, linkToken: null }+ const halfOpen: RemoteAuthPolicy = { ...PUBLIC_ONLY, linkToken: null }expect(decideSourceAccess('public', halfOpen)).toBe('deny')expect(decideSourceAccess('private', halfOpen)).toBe('allow')})- it('treats a corrupted password record without a link token as unconfigured', () => {- const corrupted: RemoteAuthPolicy = { ...PUBLIC_ONLY, password: CORRUPT_PASSWORD }- expect(decideSourceAccess('public', corrupted)).toBe('deny')- expect(decideSourceAccess('tunnel', corrupted)).toBe('deny')- expect(decideSourceAccess('private', corrupted)).toBe('allow')- expect(decideSourceAccess('loopback', corrupted)).toBe('allow')+ it('does not open public or tunnel sources when pairing is disabled', () => {+ const disabled: RemoteAuthPolicy = { ...PUBLIC_ONLY, enabled: false, pairingCode: 'EF67GH89' }+ expect(decideSourceAccess('public', disabled)).toBe('deny')+ expect(decideSourceAccess('tunnel', disabled)).toBe('deny')+ expect(decideSourceAccess('private', disabled)).toBe('allow')+ expect(decideSourceAccess('loopback', disabled)).toBe('allow')})it('keeps the physical loopback source free of authentication in every configuration', () => {expect(decideSourceAccess('loopback', ALL_SOURCES)).toBe('allow')- expect(decideSourceAccess('loopback', { ...ALL_SOURCES, password: null, linkToken: null })).toBe('allow')+ expect(decideSourceAccess('loopback', { ...ALL_SOURCES, linkToken: null })).toBe('allow')})})diff --git a/packages/dsh-tauri-remote/src/host/utils/source.ts b/packages/dsh-tauri-remote/src/host/utils/source.tsindex 9205bbc8..d729d0c7 100644--- a/packages/dsh-tauri-remote/src/host/utils/source.ts+++ b/packages/dsh-tauri-remote/src/host/utils/source.ts@@ -3,7 +3,6 @@ import type { RemoteAccessDecision, RemoteAuthPolicy, RemoteSourceClass } from 'import { Buffer } from 'node:buffer'import { timingSafeEqual } from 'node:crypto'import { GATEWAY_SESSION_HEADER, GATEWAY_SOURCE_HEADER } from '../config/constants'-import { isPasswordRecordUsable } from './auth'export type PeerSourceClass = Exclude<RemoteSourceClass, 'tunnel'>@@ -42,16 +41,8 @@ export function isLoopbackSource(headers: IncomingHttpHeaders, peerAddress: strireturn classifySource(headers, peerAddress, session) === 'loopback'}-/** 认证配置是否成立:启用且至少存在一种**可用**凭据(未损坏的密码记录或非空链接 Token),否则等同未配置(S2 §7.4/§11)。 */export function isAuthConfigured(policy: RemoteAuthPolicy | undefined): policy is RemoteAuthPolicy {- if (policy === undefined || !policy.enabled)- return false- return isPasswordRecordUsable(policy.password) || (policy.linkToken !== null && policy.linkToken !== '')-}--/** 凭据存在但不可用(密码记录损坏且无链接 Token)→ 引导「重新设置密码」而不是空白的未配置拒绝(S2 §11)。 */-export function isAuthStorageBroken(policy: RemoteAuthPolicy | undefined): boolean {- return policy !== undefined && policy.enabled && policy.password !== null && !isAuthConfigured(policy)+ return policy?.enabled === true && ((typeof policy.linkToken === 'string' && policy.linkToken !== '') || (typeof policy.pairingCode === 'string' && policy.pairingCode !== ''))}/** 判定矩阵(S2 §7.2):回环恒放行,不提供 lan_only 档位。 */diff --git a/src-native/apis/index.ts b/src-native/apis/index.tsindex b35c59fb..f58e6f42 100644--- a/src-native/apis/index.ts+++ b/src-native/apis/index.ts@@ -1,29 +1,7 @@-import type { AuthStatus, BridgeManifest, GetAuthStatusPaths, GetManifestPaths } from './index.types'-import { AUTH_STATUS_PATH, MANIFEST_PATH } from '@/config/constants'-import { isBridgeManifest, parseAuthStatus } from '@/utils/bridge-protocol'+import type { BridgeManifest, GetManifestPaths } from './index.types'+import { MANIFEST_PATH } from '@/config/constants'+import { isBridgeManifest } from '@/utils/bridge-protocol'-/**- * 探测宿主的鉴权状态。网络错误由调用方(probe)捕获;- * 非 2xx 或响应体不合法一律返回 null —— 表示「这个 origin 不是 DSH 宿主」。- */-export async function getAuthStatus(paths: GetAuthStatusPaths, init?: RequestInit): Promise<AuthStatus | null> {- const response = await fetch(new URL(AUTH_STATUS_PATH, paths.baseURL).toString(), {- headers: { Accept: 'application/json' },- cache: 'no-store',- redirect: 'error',- ...init,- })-- if (!response.ok)- return null-- return parseAuthStatus(await response.json())-}--/**- * 读取宿主 manifest,用于判断宿主是否允许 loopback 连接。- * 非 2xx 或校验失败返回 null。- */export async function getManifest(paths: GetManifestPaths, init?: RequestInit): Promise<BridgeManifest | null> {const response = await fetch(new URL(MANIFEST_PATH, paths.baseURL).toString(), {headers: { Accept: 'application/manifest+json' },diff --git a/src-native/apis/index.types.ts b/src-native/apis/index.types.tsindex f89954c4..f8f21c02 100644--- a/src-native/apis/index.types.ts+++ b/src-native/apis/index.types.ts@@ -1,21 +1,7 @@-/** `getAuthStatus` 的路径参数:宿主 origin(`BridgeAddress.id`)。 */-export interface GetAuthStatusPaths {- baseURL: string-}--/** `getManifest` 的路径参数:宿主 origin(`BridgeAddress.id`)。 */export interface GetManifestPaths {baseURL: string}-/** `GET /__dsh_bridge__/auth-status` 响应体。 */-export interface AuthStatus {- enabled: boolean- mode?: string- allowLoopback?: boolean-}--/** `GET /manifest.webmanifest` 响应体中本 App 依赖的两个字段。 */export interface BridgeManifest {name: stringshort_name: stringdiff --git a/src-native/config/constants.ts b/src-native/config/constants.tsindex 9dcfd1c6..79db2980 100644--- a/src-native/config/constants.ts+++ b/src-native/config/constants.ts@@ -12,5 +12,4 @@ export const FOCUS_RETRY_INTERVAL_MS = 200export const FOCUS_TIMEOUT_MS = 15000export const NOTIFICATION_CHANNEL = 'dsh-bridge'export const CONNECTION_STORAGE_KEY = 'dsh-bridge/connections'-export const AUTH_STATUS_PATH = '/__dsh_bridge__/auth-status'export const MANIFEST_PATH = '/manifest.webmanifest'diff --git a/src-native/i18n/locales/en-US.json b/src-native/i18n/locales/en-US.jsonindex d69eb00e..f77caa5d 100644--- a/src-native/i18n/locales/en-US.json+++ b/src-native/i18n/locales/en-US.json@@ -26,7 +26,6 @@"connection.swipeAccessibility": "Dismiss swipe guide","connection.closeDrawer": "Close connection details","connection.hostOffline": "Host temporarily unavailable",- "connection.tokenRequired": "This host requires an access token. Scan the desktop QR code or sign in inside the page.","connection.available": "Available","connection.unavailable": "Unavailable","connection.checking": "Checking",diff --git a/src-native/i18n/locales/zh-CN.json b/src-native/i18n/locales/zh-CN.jsonindex 16b2e845..047906b6 100644--- a/src-native/i18n/locales/zh-CN.json+++ b/src-native/i18n/locales/zh-CN.json@@ -26,7 +26,6 @@"connection.swipeAccessibility": "关闭滑动引导","connection.closeDrawer": "关闭连接信息","connection.hostOffline": "主机暂时不可用",- "connection.tokenRequired": "该主机需要访问令牌,请用桌面端二维码扫码连接,或在页面内登录。","connection.available": "可用","connection.unavailable": "不可用","connection.checking": "正在检测",diff --git a/src-native/services/probe-bridge.test.ts b/src-native/services/probe-bridge.test.tsindex 5dad3ef7..a2584b27 100644--- a/src-native/services/probe-bridge.test.ts+++ b/src-native/services/probe-bridge.test.ts@@ -1,4 +1,5 @@import type { BridgeAddress } from '@/utils/bridge-protocol'+import { FetchError } from 'expo/src/winter/fetch/FetchErrors'import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'import { deferred, deferredNetwork, jsonResponse } from './bridge.test-utils'import { probeBridge } from './probe-bridge'@@ -10,6 +11,7 @@ const address: BridgeAddress = {port: 8443,token: 'not-for-discovery',}+const manifest = { name: 'DeepSeek Harness', short_name: 'DSH' }beforeEach(() => {vi.useFakeTimers()@@ -23,35 +25,17 @@ afterEach(() => {})describe('probeBridge identity', () => {- it('accepts the strict bridge auth response and probes only the stable origin without credentials', async () => {- const fetchMock = vi.fn<typeof fetch>().mockResolvedValue(jsonResponse({ enabled: true, mode: 'token_only', allowLoopback: false, token: 'response-secret' }))- vi.stubGlobal('fetch', fetchMock)- const signal = new AbortController().signal- const removeListener = vi.spyOn(signal, 'removeEventListener')- expect(await probeBridge(address, signal)).toEqual({ ...address, auth: { enabled: true, mode: 'token_only', allowLoopback: false } })- expect(fetchMock).toHaveBeenCalledTimes(1)- expect(fetchMock).toHaveBeenCalledWith('https://bridge.local:8443/__dsh_bridge__/auth-status', {- signal: expect.any(AbortSignal),- headers: { Accept: 'application/json' },- cache: 'no-store',- redirect: 'error',+ it('recognizes the deployed DSH manifest without the nonexistent auth-status endpoint or pairing credentials', async () => {+ const fetchMock = vi.fn<typeof fetch>(async (input) => {+ if (String(input) === 'https://bridge.local:8443/manifest.webmanifest')+ return jsonResponse({ name: 'DeepSeek Harness', short_name: 'DSH', start_url: './', scope: './', display: 'fullscreen' })+ return new Response(null, { status: 404 })})- expect(removeListener).toHaveBeenCalledWith('abort', expect.any(Function))- expect(vi.getTimerCount()).toBe(0)- })-- it('requires the literal DSH manifest for a legacy auth response without allowLoopback', async () => {- const fetchMock = vi.fn<typeof fetch>()- .mockResolvedValueOnce(jsonResponse({ enabled: false }))- .mockResolvedValueOnce(jsonResponse({ name: 'DeepSeek Harness', short_name: 'DSH' }))vi.stubGlobal('fetch', fetchMock)- expect(await probeBridge(address, new AbortController().signal)).toEqual({ ...address, auth: { enabled: false } })- expect(fetchMock.mock.calls.map(call => call[0])).toEqual([- 'https://bridge.local:8443/__dsh_bridge__/auth-status',- 'https://bridge.local:8443/manifest.webmanifest',- ])- expect(fetchMock.mock.calls[1]?.[1]).toEqual({- signal: fetchMock.mock.calls[0]?.[1]?.signal,++ expect(await probeBridge(address, new AbortController().signal)).toEqual(address)+ expect(fetchMock).toHaveBeenCalledExactlyOnceWith('https://bridge.local:8443/manifest.webmanifest', {+ signal: expect.any(AbortSignal),headers: { Accept: 'application/manifest+json' },cache: 'no-store',redirect: 'error',@@ -62,67 +46,55 @@ describe('probeBridge identity', () => {it.each([null,[],- {},- { enabled: 'false', allowLoopback: true },- { enabled: true, mode: 1, allowLoopback: false },- { enabled: false, allowLoopback: 'true' },- ])('rejects malformed auth identity %j before manifest fallback', async (body) => {- const fetchMock = vi.fn<typeof fetch>().mockResolvedValue(jsonResponse(body))- vi.stubGlobal('fetch', fetchMock)- expect(await probeBridge(address, new AbortController().signal)).toBeNull()- expect(fetchMock).toHaveBeenCalledTimes(1)- expect(vi.getTimerCount()).toBe(0)- })-- it.each([{},{ name: 'DeepSeek Harness' },{ short_name: 'DSH' },{ name: 'Other app', short_name: 'DSH' },{ name: 'DeepSeek Harness', short_name: 'OTHER' },{ name: 'deepseek harness', short_name: 'DSH' },- ])('does not identify a legacy service with a foreign manifest %j', async (body) => {- const fetchMock = vi.fn<typeof fetch>()- .mockResolvedValueOnce(jsonResponse({ enabled: false }))- .mockResolvedValueOnce(jsonResponse(body))+ { enabled: false, allowLoopback: true },+ ])('does not identify a service with a foreign manifest %j', async (body) => {+ const fetchMock = vi.fn<typeof fetch>().mockResolvedValue(jsonResponse(body))vi.stubGlobal('fetch', fetchMock)expect(await probeBridge(address, new AbortController().signal)).toBeNull()- expect(fetchMock).toHaveBeenCalledTimes(2)+ expect(fetchMock).toHaveBeenCalledTimes(1)+ expect(vi.getTimerCount()).toBe(0)})- it('rejects an HTTP error rather than interpreting its auth body', async () => {- const response = jsonResponse({ enabled: false, allowLoopback: true }, 401)+ it.each([401, 403, 404, 503])('rejects HTTP %s even with a matching manifest body', async (status) => {+ const response = jsonResponse(manifest, status)const json = vi.spyOn(response, 'json')- const fetchMock = vi.fn<typeof fetch>().mockResolvedValue(response)- vi.stubGlobal('fetch', fetchMock)+ vi.stubGlobal('fetch', vi.fn<typeof fetch>().mockResolvedValue(response))expect(await probeBridge(address, new AbortController().signal)).toBeNull()expect(json).not.toHaveBeenCalled()- expect(fetchMock).toHaveBeenCalledTimes(1)})- it('rejects a failing manifest HTTP status even with a matching identity body', async () => {- vi.stubGlobal('fetch', vi.fn<typeof fetch>()- .mockResolvedValueOnce(jsonResponse({ enabled: false }))- .mockResolvedValueOnce(jsonResponse({ name: 'DeepSeek Harness', short_name: 'DSH' }, 404)))+ it.each(['not JSON', '<!doctype html><title>DeepSeek Harness</title><form>请输入配对码</form>'])('rejects HTTP 200 without a valid manifest: %s', async (body) => {+ vi.stubGlobal('fetch', vi.fn<typeof fetch>().mockResolvedValue(new Response(body)))expect(await probeBridge(address, new AbortController().signal)).toBeNull()+ expect(vi.getTimerCount()).toBe(0)})- it('rejects invalid JSON from the auth endpoint', async () => {- vi.stubGlobal('fetch', vi.fn<typeof fetch>().mockResolvedValue(new Response('not JSON')))+ it('handles a rejected network request as an unavailable bridge', async () => {+ vi.stubGlobal('fetch', vi.fn<typeof fetch>().mockRejectedValue(new TypeError('Network unavailable')))expect(await probeBridge(address, new AbortController().signal)).toBeNull()expect(vi.getTimerCount()).toBe(0)})- it('rejects invalid JSON from the legacy manifest endpoint', async () => {- vi.stubGlobal('fetch', vi.fn<typeof fetch>()- .mockResolvedValueOnce(jsonResponse({ enabled: false }))- .mockResolvedValueOnce(new Response('not JSON')))- expect(await probeBridge(address, new AbortController().signal)).toBeNull()+ it('handles the actual Expo57 FetchError without caller cancellation as an unavailable bridge', async () => {+ const caller = new AbortController()+ const error = FetchError.createFromError(new Error('Failed to connect to /10.0.0.1:3080'))+ vi.stubGlobal('fetch', vi.fn<typeof fetch>().mockRejectedValue(error))++ await expect(probeBridge(address, caller.signal)).resolves.toBeNull()+ expect(caller.signal.aborted).toBe(false)+ expect(vi.getTimerCount()).toBe(0)})- it('handles a rejected network request as an unavailable bridge', async () => {- vi.stubGlobal('fetch', vi.fn<typeof fetch>().mockRejectedValue(new TypeError('Network unavailable')))- expect(await probeBridge(address, new AbortController().signal)).toBeNull()+ it('propagates unexpected failures instead of hiding a programming error as an offline host', async () => {+ const error = new Error('Unexpected request implementation failure')+ vi.stubGlobal('fetch', vi.fn<typeof fetch>().mockRejectedValue(error))+ await expect(probeBridge(address, new AbortController().signal)).rejects.toBe(error)expect(vi.getTimerCount()).toBe(0)})})@@ -162,27 +134,25 @@ describe('probeBridge cancellation', () => {expect(vi.getTimerCount()).toBe(0)})- it('uses one timeout budget across auth and manifest requests', async () => {- const network = deferredNetwork()+ it('keeps the request timeout active while its manifest body is being parsed', async () => {+ const body = deferred<unknown>()+ const response = jsonResponse(manifest)+ vi.spyOn(response, 'json').mockReturnValue(body.promise)+ const fetchMock = vi.fn<typeof fetch>().mockResolvedValue(response)+ vi.stubGlobal('fetch', fetchMock)const pending = probeBridge(address, new AbortController().signal, 100)- await vi.advanceTimersByTimeAsync(60)- network.requests[0]!.resolve(jsonResponse({ enabled: false }))- await vi.advanceTimersByTimeAsync(0)- expect(network.requests.map(request => request.url)).toEqual([- 'https://bridge.local:8443/__dsh_bridge__/auth-status',- 'https://bridge.local:8443/manifest.webmanifest',- ])- await vi.advanceTimersByTimeAsync(39)- expect(network.requests[1]?.signal.aborted).toBe(false)+ await vi.advanceTimersByTimeAsync(99)+ expect(fetchMock.mock.calls[0]?.[1]?.signal?.aborted).toBe(false)await vi.advanceTimersByTimeAsync(1)+ expect(fetchMock.mock.calls[0]?.[1]?.signal?.aborted).toBe(true)+ body.resolve(manifest)expect(await pending).toBeNull()- expect(network.requests[1]?.signal.aborted).toBe(true)- expect(network.active()).toBe(0)+ expect(vi.getTimerCount()).toBe(0)})- it('discards an auth body that finishes parsing after the caller aborts', async () => {+ it('discards a manifest body that finishes parsing after the caller aborts', async () => {const body = deferred<unknown>()- const response = jsonResponse({})+ const response = jsonResponse(manifest)vi.spyOn(response, 'json').mockReturnValue(body.promise)const fetchMock = vi.fn<typeof fetch>().mockResolvedValue(response)vi.stubGlobal('fetch', fetchMock)@@ -190,7 +160,7 @@ describe('probeBridge cancellation', () => {const pending = probeBridge(address, caller.signal)await vi.advanceTimersByTimeAsync(0)caller.abort()- body.resolve({ enabled: false })+ body.resolve(manifest)expect(await pending).toBeNull()expect(fetchMock).toHaveBeenCalledTimes(1)})@@ -202,7 +172,7 @@ describe('probeBridge cancellation', () => {const caller = new AbortController()const pending = probeBridge(address, caller.signal)caller.abort()- response.resolve(jsonResponse({ enabled: false, allowLoopback: true }))+ response.resolve(jsonResponse(manifest))expect(await pending).toBeNull()expect(fetchMock.mock.calls[0]?.[1]?.signal?.aborted).toBe(true)})diff --git a/src-native/services/probe-bridge.ts b/src-native/services/probe-bridge.tsindex 0fa066be..317526ae 100644--- a/src-native/services/probe-bridge.ts+++ b/src-native/services/probe-bridge.ts@@ -1,17 +1,9 @@-import type { AuthStatus } from '@/apis/index.types'import type { BridgeAddress } from '@/utils/bridge-protocol'-import { getAuthStatus, getManifest } from '@/apis/index'+import { FetchError } from 'expo/src/winter/fetch/FetchErrors'+import { getManifest } from '@/apis/index'import { PROBE_TIMEOUT_MS } from '@/config/constants'-export interface BridgeHost extends BridgeAddress {- auth: AuthStatus-}--/**- * 探测单个候选地址是否为可用的 DSH 宿主。- * 超时、网络错误、非 2xx、响应体不合法一律返回 null(扫描靠 null 判定「不可用」)。- */-export async function probeBridge(address: BridgeAddress, signal: AbortSignal, timeoutMs = PROBE_TIMEOUT_MS): Promise<BridgeHost | null> {+export async function probeBridge(address: BridgeAddress, signal: AbortSignal, timeoutMs = PROBE_TIMEOUT_MS): Promise<BridgeAddress | null> {if (signal.aborted)return nullconst controller = new AbortController()@@ -21,19 +13,13 @@ export async function probeBridge(address: BridgeAddress, signal: AbortSignal, t}signal.addEventListener('abort', abort, { once: true })try {- const auth = await getAuthStatus({ baseURL: address.id }, { signal: controller.signal })- if (!auth || controller.signal.aborted)- return null- // 旧版宿主不返回 allowLoopback,此时用 manifest 兜底确认这是一台 DSH 宿主。- if (auth.allowLoopback === undefined) {- const manifest = await getManifest({ baseURL: address.id }, { signal: controller.signal })- if (!manifest || controller.signal.aborted)- return null- }- return { ...address, auth }+ const manifest = await getManifest({ baseURL: address.id }, { signal: controller.signal })+ return manifest && !controller.signal.aborted ? address : null}- catch {- return null+ catch (error) {+ if (controller.signal.aborted || error instanceof TypeError || error instanceof SyntaxError || error instanceof FetchError)+ return null+ throw error}finally {clearTimeout(timeout)diff --git a/src-native/services/scan-candidates.test.ts b/src-native/services/scan-candidates.test.tsindex d51f479c..c1908344 100644--- a/src-native/services/scan-candidates.test.ts+++ b/src-native/services/scan-candidates.test.ts@@ -1,3 +1,4 @@+import { FetchError } from 'expo/src/winter/fetch/FetchErrors'import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'import { deferredNetwork, jsonResponse } from './bridge.test-utils'import { scanCandidates } from './scan-candidates'@@ -25,25 +26,25 @@ describe('scanCandidates scheduling', () => {{ host: '10.0.0.5', port: 3080 },], { signal: new AbortController().signal, concurrency: 2, timeoutMs: 1000, budgetMs: 5000, onFound })expect(network.requests.map(request => request.url)).toEqual([- 'http://10.0.0.1:3080/__dsh_bridge__/auth-status',- 'http://10.0.0.2:3080/__dsh_bridge__/auth-status',+ 'http://10.0.0.1:3080/manifest.webmanifest',+ 'http://10.0.0.2:3080/manifest.webmanifest',])expect(network.active()).toBe(2)- network.requests[1]!.resolve(jsonResponse({ enabled: false, allowLoopback: true }))+ network.requests[1]!.resolve(jsonResponse({ name: 'DeepSeek Harness', short_name: 'DSH' }))await vi.advanceTimersByTimeAsync(0)expect(network.requests).toHaveLength(3)expect(onFound.mock.calls.map(call => call[0].id)).toEqual(['http://10.0.0.2:3080'])- network.requests[0]!.resolve(jsonResponse({ enabled: false, allowLoopback: true }))+ network.requests[0]!.resolve(jsonResponse({ name: 'DeepSeek Harness', short_name: 'DSH' }))await vi.advanceTimersByTimeAsync(0)expect(network.requests).toHaveLength(4)- network.requests[2]!.resolve(jsonResponse({ enabled: false, allowLoopback: true }))+ network.requests[2]!.resolve(jsonResponse({ name: 'DeepSeek Harness', short_name: 'DSH' }))await vi.advanceTimersByTimeAsync(0)expect(network.requests).toHaveLength(5)- network.requests[3]!.resolve(jsonResponse({ enabled: false, allowLoopback: true }))- network.requests[4]!.resolve(jsonResponse({ enabled: false, allowLoopback: true }))+ network.requests[3]!.resolve(jsonResponse({ name: 'DeepSeek Harness', short_name: 'DSH' }))+ network.requests[4]!.resolve(jsonResponse({ name: 'DeepSeek Harness', short_name: 'DSH' }))const found = await pendingexpect(found.map(host => host.id)).toEqual(['http://10.0.0.2:3080', 'http://10.0.0.1:3080', 'http://10.0.0.3:3080', 'http://10.0.0.4:3080', 'http://10.0.0.5:3080'])- expect(found[0]).toEqual({ id: 'http://10.0.0.2:3080', url: 'http://10.0.0.2:3080/', host: '10.0.0.2', port: 3080, auth: { enabled: false, allowLoopback: true } })+ expect(found[0]).toEqual({ id: 'http://10.0.0.2:3080', url: 'http://10.0.0.2:3080/', host: '10.0.0.2', port: 3080 })expect(onFound.mock.calls.map(call => call[0].id)).toEqual(['http://10.0.0.2:3080', 'http://10.0.0.1:3080', 'http://10.0.0.3:3080', 'http://10.0.0.4:3080', 'http://10.0.0.5:3080'])expect(network.maximum()).toBe(2)expect(network.active()).toBe(0)@@ -57,10 +58,10 @@ describe('scanCandidates scheduling', () => {expect(network.requests).toHaveLength(40)expect(network.active()).toBe(40)for (const request of network.requests.slice())- request.resolve(jsonResponse({ enabled: false, allowLoopback: true }))+ request.resolve(jsonResponse({ name: 'DeepSeek Harness', short_name: 'DSH' }))await vi.advanceTimersByTimeAsync(0)expect(network.requests).toHaveLength(41)- network.requests[40]!.resolve(jsonResponse({ enabled: false, allowLoopback: true }))+ network.requests[40]!.resolve(jsonResponse({ name: 'DeepSeek Harness', short_name: 'DSH' }))expect(await pending).toHaveLength(41)expect(network.maximum()).toBe(40)expect(vi.getTimerCount()).toBe(0)@@ -77,11 +78,35 @@ describe('scanCandidates scheduling', () => {await vi.advanceTimersByTimeAsync(1)expect(network.requests[0]?.signal.aborted).toBe(true)expect(network.requests[1]?.signal.aborted).toBe(false)- network.requests[1]!.resolve(jsonResponse({ enabled: false, allowLoopback: true }))+ network.requests[1]!.resolve(jsonResponse({ name: 'DeepSeek Harness', short_name: 'DSH' }))expect((await pending).map(host => host.id)).toEqual(['http://10.0.0.2:3080'])expect(network.maximum()).toBe(1)})+ it('continues past an Expo57 connection refusal and discovers the next LAN DSH', async () => {+ const fetchMock = vi.fn<typeof fetch>()+ .mockRejectedValueOnce(FetchError.createFromError(new Error('Failed to connect to /10.0.0.1:3080')))+ .mockResolvedValueOnce(jsonResponse({ name: 'DeepSeek Harness', short_name: 'DSH' }))+ vi.stubGlobal('fetch', fetchMock)+ const caller = new AbortController()+ const onFound = vi.fn()++ await expect(scanCandidates([+ { host: '10.0.0.1', port: 3080 },+ { host: '10.0.0.2', port: 3080 },+ ], { signal: caller.signal, concurrency: 1, onFound })).resolves.toEqual([+ { id: 'http://10.0.0.2:3080', url: 'http://10.0.0.2:3080/', host: '10.0.0.2', port: 3080 },+ ])+ expect(fetchMock.mock.calls.map(([url]) => url)).toEqual([+ 'http://10.0.0.1:3080/manifest.webmanifest',+ 'http://10.0.0.2:3080/manifest.webmanifest',+ ])+ expect(onFound).toHaveBeenCalledExactlyOnceWith({ id: 'http://10.0.0.2:3080', url: 'http://10.0.0.2:3080/', host: '10.0.0.2', port: 3080 })+ expect(caller.signal.aborted).toBe(false)+ expect(fetchMock.mock.calls.every(([, init]) => init?.signal?.aborted === false)).toBe(true)+ expect(vi.getTimerCount()).toBe(0)+ })+it('aborts all active requests at the scan budget and returns only prior discoveries', async () => {const network = deferredNetwork()const onFound = vi.fn()@@ -91,7 +116,7 @@ describe('scanCandidates scheduling', () => {{ host: '10.0.0.3', port: 3080 },{ host: '10.0.0.4', port: 3080 },], { signal: new AbortController().signal, concurrency: 2, timeoutMs: 1000, budgetMs: 50, onFound })- network.requests[0]!.resolve(jsonResponse({ enabled: false, allowLoopback: true }))+ network.requests[0]!.resolve(jsonResponse({ name: 'DeepSeek Harness', short_name: 'DSH' }))await vi.advanceTimersByTimeAsync(49)expect(network.requests).toHaveLength(3)expect(network.active()).toBe(2)@@ -113,7 +138,7 @@ describe('scanCandidates scheduling', () => {{ host: '10.0.0.2', port: 3080 },{ host: '10.0.0.3', port: 3080 },], { signal: caller.signal, concurrency: 2, onFound })- network.requests[0]!.resolve(jsonResponse({ enabled: false, allowLoopback: true }))+ network.requests[0]!.resolve(jsonResponse({ name: 'DeepSeek Harness', short_name: 'DSH' }))expect((await pending).map(host => host.id)).toEqual(['http://10.0.0.1:3080'])expect(onFound).toHaveBeenCalledTimes(1)expect(network.requests).toHaveLength(2)@@ -134,7 +159,7 @@ describe('scanCandidates scheduling', () => {onFound() { throw error },})const rejection = expect(pending).rejects.toBe(error)- network.requests[0]!.resolve(jsonResponse({ enabled: false, allowLoopback: true }))+ network.requests[0]!.resolve(jsonResponse({ name: 'DeepSeek Harness', short_name: 'DSH' }))await rejectionexpect(network.requests[1]?.signal.aborted).toBe(true)expect(network.active()).toBe(0)@@ -152,7 +177,7 @@ describe('scanCandidates scheduling', () => {{ host: '10.0.0.3', port: 3080 },], { signal: new AbortController().signal, concurrency: 256, onFound })).toEqual([])expect(fetchMock).toHaveBeenCalledTimes(1)- expect(fetchMock.mock.calls[0]?.[0]).toBe('http://10.0.0.3:3080/__dsh_bridge__/auth-status')+ expect(fetchMock.mock.calls[0]?.[0]).toBe('http://10.0.0.3:3080/manifest.webmanifest')expect(onFound).not.toHaveBeenCalled()expect(vi.getTimerCount()).toBe(0)})diff --git a/src-native/services/scan-candidates.ts b/src-native/services/scan-candidates.tsindex 8f2b1240..4a60f405 100644--- a/src-native/services/scan-candidates.ts+++ b/src-native/services/scan-candidates.ts@@ -1,4 +1,4 @@-import type { BridgeHost } from './probe-bridge'+import type { BridgeAddress } from '@/utils/bridge-protocol'import type { ScanCandidate } from '@/utils/discovery'import { PROBE_TIMEOUT_MS, SCAN_BUDGET_MS, SCAN_CONCURRENCY } from '@/config/constants'import { parseQrPayload } from '@/utils/bridge-protocol'@@ -9,7 +9,7 @@ export interface ScanOptions {concurrency?: numbertimeoutMs?: numberbudgetMs?: number- onFound?: (host: BridgeHost) => void+ onFound?: (host: BridgeAddress) => void}/**@@ -22,7 +22,7 @@ export async function scanCandidates(candidates: readonly ScanCandidate[], {timeoutMs = PROBE_TIMEOUT_MS,budgetMs = SCAN_BUDGET_MS,onFound,-}: ScanOptions): Promise<BridgeHost[]> {+}: ScanOptions): Promise<BridgeAddress[]> {if (!Number.isInteger(concurrency) || concurrency < 1 || concurrency > 256)throw new RangeError('Scan concurrency must be between 1 and 256')if (!Number.isFinite(budgetMs) || budgetMs <= 0 || !Number.isFinite(timeoutMs) || timeoutMs <= 0)@@ -35,7 +35,7 @@ export async function scanCandidates(candidates: readonly ScanCandidate[], {}signal.addEventListener('abort', abort, { once: true })const deadline = setTimeout(abort, budgetMs)- const found: BridgeHost[] = []+ const found: BridgeAddress[] = []let cursor = 0async function worker() {while (!controller.signal.aborted && cursor < candidates.length) {diff --git a/src-native/store/modules/connection/runtime.test.ts b/src-native/store/modules/connection/runtime.test.tsindex 43b64954..f782f197 100644--- a/src-native/store/modules/connection/runtime.test.ts+++ b/src-native/store/modules/connection/runtime.test.ts@@ -1,5 +1,4 @@import type { HistoryEntry } from './index'-import type { BridgeHost } from '@/services/probe-bridge'import type { ScanOptions } from '@/services/scan-candidates'import type { BridgeAddress } from '@/utils/bridge-protocol'import type { ScanCandidate } from '@/utils/discovery'@@ -48,7 +47,6 @@ const recentAlpha: HistoryEntry = { ...alpha, lastConnectedAt: 20 }const recentBeta: HistoryEntry = { ...beta, lastConnectedAt: 10 }const noHosts = i18n.t('connection.noHosts')const noNetwork = i18n.t('connection.noNetwork')-const tokenRequired = i18n.t('connection.tokenRequired')const hostOffline = i18n.t('connection.hostOffline')const releases: (() => void)[] = []let runtime: typeof import('./runtime')@@ -59,14 +57,6 @@ function hydrate(history: HistoryEntry[] = [], tokens: Record<string, string> =connection.markHydrated(tokens)}-function openHost(address: BridgeAddress): BridgeHost {- return { ...address, auth: { enabled: false, allowLoopback: false } }-}--function lockedHost(address: BridgeAddress): BridgeHost {- return { ...address, auth: { enabled: true, mode: 'token_only', allowLoopback: false } }-}-function deferred<T>(fallback: T) {const pending = Promise.withResolvers<T>()releases.push(releasePendingFixture)@@ -91,7 +81,7 @@ function recordedScan(index = 0): Parameters<typeof import('@/services/scan-candreturn call}-function publish(host: BridgeHost, index = 0): void {+function publish(host: BridgeAddress, index = 0): void {const options: ScanOptions = recordedScan(index)[1]if (!options.onFound)throw new Error('Expected a discovery callback at the bridge-client boundary')@@ -183,7 +173,7 @@ function describeDirectConnections() {async function supersedeHistoryWithDirectConnection() {hydrate([recentAlpha])- const probe = deferred<BridgeHost | null>(null)+ const probe = deferred<BridgeAddress | null>(null)boundary.probe.mockReturnValue(probe.promise)const scanning = runtime.startAutoScan()const signal = recordedProbe()[1]@@ -192,7 +182,7 @@ function describeDirectConnections() {runtime.connectAddress(beta)expect(signal.aborted).toBe(true)const generation = connection.scanGeneration- probe.resolve(openHost(alpha))+ probe.resolve(alpha)await scanningexpect(connection.current).toEqual(beta)@@ -209,7 +199,7 @@ function describeDirectConnections() {async function supersedeLanWithDirectConnection() {hydrate()- const scan = deferred<BridgeHost[]>([])+ const scan = deferred<BridgeAddress[]>([])boundary.scan.mockReturnValue(scan.promise)const scanning = runtime.startAutoScan()await vi.advanceTimersByTimeAsync(0)@@ -217,8 +207,8 @@ function describeDirectConnections() {runtime.connectAddress(beta)expect(signal.aborted).toBe(true)- publish(openHost(gamma))- scan.resolve([openHost(gamma)])+ publish(gamma)+ scan.resolve([gamma])await scanningexpect(connection.current).toEqual(beta)@@ -236,19 +226,19 @@ function describeDiscovery() {async function prioritizeHistoryOrder() {hydrate([recentAlpha, recentBeta])- const newest = deferred<BridgeHost | null>(null)- const older = deferred<BridgeHost | null>(null)+ const newest = deferred<BridgeAddress | null>(null)+ const older = deferred<BridgeAddress | null>(null)boundary.probe.mockReturnValueOnce(newest.promise).mockReturnValueOnce(older.promise)const scanning = runtime.startAutoScan()const signal = recordedProbe()[1]expect(boundary.probe.mock.calls).toEqual([[recentAlpha, signal, 3000], [recentBeta, signal, 3000]])expect(connection.health).toEqual({ 'http://10.0.0.20:4444': 'checking', 'http://10.0.0.2:3082': 'checking' })- older.resolve(openHost(beta))+ older.resolve(beta)await vi.advanceTimersByTimeAsync(0)expect(connection.current).toBeNull()expect(boundary.ip).not.toHaveBeenCalled()- newest.resolve(openHost(alpha))+ newest.resolve(alpha)await scanningexpect(connection.current).toEqual(alpha)@@ -266,7 +256,7 @@ function describeDiscovery() {async function fallBackWithinHistory() {hydrate([recentAlpha, recentBeta])- boundary.probe.mockResolvedValueOnce(null).mockResolvedValueOnce(openHost(beta))+ boundary.probe.mockResolvedValueOnce(null).mockResolvedValueOnce(beta)await runtime.startAutoScan()@@ -276,26 +266,26 @@ function describeDiscovery() {expect(boundary.scan).not.toHaveBeenCalled()}- it('skips reachable token-only history without credentials in favor of a usable history entry', filterLockedHistory)-- async function filterLockedHistory() {+ it('opens identified history without a saved code and waits for WebView pairing instead of claiming authentication', async () => {hydrate([recentAlpha, recentBeta])- boundary.probe.mockResolvedValueOnce(lockedHost(alpha)).mockResolvedValueOnce(openHost(beta))+ boundary.probe.mockResolvedValueOnce(alpha).mockResolvedValueOnce(beta)await runtime.startAutoScan()- expect(connection.current).toEqual(beta)+ expect(connection.current).toEqual(alpha)expect(connection.tokens).toEqual({})expect(connection.health[alpha.id]).toBe('available')+ expect(connection.loading).toBe(true)+ expect(connection.history).toEqual([recentAlpha, recentBeta])expect(boundary.scan).not.toHaveBeenCalled()expect(connection.notice).toBeNull()- }+ })- it('reuses the exact saved origin token when probing token-only history', acceptAuthenticatedHistory)+ it('reuses the exact saved origin token when probing identified history', acceptAuthenticatedHistory)async function acceptAuthenticatedHistory() {hydrate([recentAlpha], { 'http://10.0.0.20:4444': 'fixture-saved-token' })- boundary.probe.mockResolvedValue(lockedHost({ ...alpha, token: 'fixture-saved-token' }))+ boundary.probe.mockResolvedValue({ ...alpha, token: 'fixture-saved-token' })await runtime.startAutoScan()@@ -307,21 +297,6 @@ function describeDiscovery() {expect(boundary.scan).not.toHaveBeenCalled()}- it('retains the token-required notice from unusable history when the LAN has no usable host', retainHistoryTokenRequirement)-- async function retainHistoryTokenRequirement() {- hydrate([recentAlpha])- boundary.probe.mockResolvedValue(lockedHost(alpha))-- await runtime.startAutoScan()-- expect(boundary.scan).toHaveBeenCalledTimes(1)- expect(connection.current).toBeNull()- expect(connection.stage).toBe('idle')- expect(connection.notice).toBe(tokenRequired)- expect(connection.tokens).toEqual({})- }-it('passes history custom ports into the real subnet candidate builder while excluding self and subnet boundaries', includeHistoryPorts)async function includeHistoryPorts() {@@ -378,65 +353,40 @@ function describeDiscovery() {expect(vi.getTimerCount()).toBe(0)}- it('keeps scanning after a token-only LAN host without a token and accepts the next usable discovery', filterLockedLanHost)-- async function filterLockedLanHost() {+ it('stops at the first identified LAN host without a saved code and waits for WebView pairing', async () => {hydrate()- const scan = deferred<BridgeHost[]>([])+ const scan = deferred<BridgeAddress[]>([])boundary.scan.mockReturnValue(scan.promise)const scanning = runtime.startAutoScan()await vi.advanceTimersByTimeAsync(0)- const signal = recordedScan()[1].signal- publish(lockedHost(beta))- expect(signal.aborted).toBe(false)- expect(connection.current).toBeNull()- publish(openHost(gamma))- expect(signal.aborted).toBe(true)- scan.resolve([lockedHost(beta), openHost(gamma)])+ publish(beta)+ expect(recordedScan()[1].signal.aborted).toBe(true)+ publish(gamma)+ scan.resolve([beta, gamma])await scanning- expect(connection.current).toEqual(gamma)+ expect(connection.current).toEqual(beta)expect(connection.stage).toBe('connected')+ expect(connection.loading).toBe(true)expect(connection.notice).toBeNull()expect(connection.history).toEqual([])expect(connection.tokens).toEqual({})expect(vi.getTimerCount()).toBe(0)- }-- it('reports token-required when every LAN discovery needs an unavailable token', reportLockedLanHosts)-- async function reportLockedLanHosts() {- hydrate()- const scan = deferred<BridgeHost[]>([])- boundary.scan.mockReturnValue(scan.promise)- const scanning = runtime.startAutoScan()- await vi.advanceTimersByTimeAsync(0)-- publish(lockedHost(beta))- publish(lockedHost(gamma))- expect(recordedScan()[1].signal.aborted).toBe(false)- scan.resolve([lockedHost(beta), lockedHost(gamma)])- await scanning-- expect(connection.current).toBeNull()- expect(connection.stage).toBe('idle')- expect(connection.notice).toBe(tokenRequired)- expect(connection.tokens).toEqual({})- }+ })- it('accepts a token-only LAN discovery using a saved token for the exact origin', acceptAuthenticatedLanHost)+ it('accepts an identified LAN discovery using a saved token for the exact origin', acceptAuthenticatedLanHost)async function acceptAuthenticatedLanHost() {hydrate([], { 'http://10.0.0.2:3082': 'fixture-saved-token' })- const scan = deferred<BridgeHost[]>([])+ const scan = deferred<BridgeAddress[]>([])boundary.scan.mockReturnValue(scan.promise)const scanning = runtime.startAutoScan()await vi.advanceTimersByTimeAsync(0)- publish(lockedHost(beta))+ publish(beta)expect(recordedScan()[1].signal.aborted).toBe(true)- scan.resolve([lockedHost(beta)])+ scan.resolve([beta])await scanningexpect(connection.current).toEqual({ ...beta, token: 'fixture-saved-token' })@@ -448,18 +398,19 @@ function describeDiscovery() {async function isolateLanTokensByOrigin() {hydrate([], { 'http://10.0.0.2:3080': 'fixture-sibling-token' })- const scan = deferred<BridgeHost[]>([])+ const scan = deferred<BridgeAddress[]>([])boundary.scan.mockReturnValue(scan.promise)const scanning = runtime.startAutoScan()await vi.advanceTimersByTimeAsync(0)- publish(lockedHost(beta))- expect(recordedScan()[1].signal.aborted).toBe(false)- scan.resolve([lockedHost(beta)])+ publish(beta)+ expect(recordedScan()[1].signal.aborted).toBe(true)+ scan.resolve([beta])await scanning- expect(connection.current).toBeNull()- expect(connection.notice).toBe(tokenRequired)+ expect(connection.current).toEqual(beta)+ expect(connection.loading).toBe(true)+ expect(connection.notice).toBeNull()expect(connection.tokens).toEqual({ 'http://10.0.0.2:3080': 'fixture-sibling-token' })}@@ -487,7 +438,7 @@ function describeDiscovery() {describe('history-only re-entry', () => {it('preserves history ordering and saved tokens without reading the LAN address', async () => {hydrate([recentAlpha, recentBeta], { 'http://10.0.0.20:4444': 'fixture-saved-token' })- boundary.probe.mockResolvedValueOnce(lockedHost({ ...alpha, token: 'fixture-saved-token' })).mockResolvedValueOnce(openHost(beta))+ boundary.probe.mockResolvedValueOnce({ ...alpha, token: 'fixture-saved-token' }).mockResolvedValueOnce(beta)await runtime.startAutoScan({ historyOnly: true })@@ -502,7 +453,7 @@ describe('history-only re-entry', () => {it('falls back within saved history rather than scanning new LAN hosts', async () => {hydrate([recentAlpha, recentBeta])- boundary.probe.mockResolvedValueOnce(null).mockResolvedValueOnce(openHost(beta))+ boundary.probe.mockResolvedValueOnce(null).mockResolvedValueOnce(beta)await runtime.startAutoScan({ historyOnly: true })@@ -528,15 +479,16 @@ describe('history-only re-entry', () => {expect(vi.getTimerCount()).toBe(0)})- it('keeps unusable token-only history for QR login without silently searching the LAN', async () => {+ it('opens identified history for WebView pairing without silently searching the LAN or recording success', async () => {hydrate([recentAlpha])- boundary.probe.mockResolvedValue(lockedHost(alpha))+ boundary.probe.mockResolvedValue(alpha)await runtime.startAutoScan({ historyOnly: true })- expect(connection.current).toBeNull()- expect(connection.stage).toBe('idle')- expect(connection.notice).toBe(tokenRequired)+ expect(connection.current).toEqual(alpha)+ expect(connection.stage).toBe('connected')+ expect(connection.loading).toBe(true)+ expect(connection.notice).toBeNull()expect(connection.health[alpha.id]).toBe('available')expect(connection.history).toEqual([recentAlpha])expect(connection.tokens).toEqual({})@@ -546,13 +498,13 @@ describe('history-only re-entry', () => {it('lets an explicit QR address cancel history reconnection and discard its late result', async () => {hydrate([recentAlpha])- const probe = deferred<BridgeHost | null>(null)+ const probe = deferred<BridgeAddress | null>(null)boundary.probe.mockReturnValue(probe.promise)const reconnecting = runtime.startAutoScan({ historyOnly: true })const signal = recordedProbe()[1]runtime.connectAddress(beta)- probe.resolve(openHost(alpha))+ probe.resolve(alpha)await reconnectingexpect(signal.aborted).toBe(true)@@ -571,7 +523,7 @@ function describeCancellation() {async function cancelHistoryProbe() {hydrate([recentAlpha])- const probe = deferred<BridgeHost | null>(null)+ const probe = deferred<BridgeAddress | null>(null)boundary.probe.mockReturnValue(probe.promise)const scanning = runtime.startAutoScan()const signal = recordedProbe()[1]@@ -580,7 +532,7 @@ function describeCancellation() {runtime.cancelAutoScan()expect(signal.aborted).toBe(true)expect(connection.scanGeneration).toBeGreaterThan(generation)- probe.resolve(openHost(alpha))+ probe.resolve(alpha)await scanningexpect(connection.current).toBeNull()@@ -617,7 +569,7 @@ function describeCancellation() {async function cancelLanDiscovery() {hydrate()- const scan = deferred<BridgeHost[]>([])+ const scan = deferred<BridgeAddress[]>([])boundary.scan.mockReturnValue(scan.promise)const scanning = runtime.startAutoScan()await vi.advanceTimersByTimeAsync(0)@@ -625,8 +577,8 @@ function describeCancellation() {runtime.cancelAutoScan()expect(signal.aborted).toBe(true)- publish(openHost(gamma))- scan.resolve([openHost(gamma)])+ publish(gamma)+ scan.resolve([gamma])await scanningexpect(connection.current).toBeNull()@@ -640,8 +592,8 @@ function describeCancellation() {async function invalidateSupersededScan() {hydrate()- const older = deferred<BridgeHost[]>([])- const newer = deferred<BridgeHost[]>([])+ const older = deferred<BridgeAddress[]>([])+ const newer = deferred<BridgeAddress[]>([])boundary.scan.mockReturnValueOnce(older.promise).mockReturnValueOnce(newer.promise)const first = runtime.startAutoScan()await vi.advanceTimersByTimeAsync(0)@@ -650,12 +602,12 @@ function describeCancellation() {await vi.advanceTimersByTimeAsync(0)expect(oldSignal.aborted).toBe(true)- publish(openHost(gamma), 1)- newer.resolve([openHost(gamma)])+ publish(gamma, 1)+ newer.resolve([gamma])await secondconst generation = connection.scanGeneration- publish(openHost(beta), 0)- older.resolve([openHost(beta)])+ publish(beta, 0)+ older.resolve([beta])await firstexpect(connection.current).toEqual(gamma)@@ -671,8 +623,8 @@ function describeCancellation() {async function stopAllRuntimeWork() {hydrate([recentAlpha])runtime.connectAddress(alpha)- const scanProbe = deferred<BridgeHost | null>(null)- const healthProbe = deferred<BridgeHost | null>(null)+ const scanProbe = deferred<BridgeAddress | null>(null)+ const healthProbe = deferred<BridgeAddress | null>(null)boundary.probe.mockReturnValueOnce(scanProbe.promise).mockReturnValueOnce(healthProbe.promise)const scanning = runtime.startAutoScan()const refreshing = runtime.refreshHealth()@@ -683,8 +635,8 @@ function describeCancellation() {runtime.stopConnectionRuntime()expect(scanSignal.aborted).toBe(true)expect(healthSignal.aborted).toBe(true)- scanProbe.resolve(openHost(alpha))- healthProbe.resolve(openHost(alpha))+ scanProbe.resolve(alpha)+ healthProbe.resolve(alpha)await Promise.all([scanning, refreshing])expect(connection.stage).toBe('idle')@@ -704,7 +656,7 @@ function describeScanDeadlines() {async function enforceHistoryDeadline() {hydrate([recentAlpha])- const probe = deferred<BridgeHost | null>(null)+ const probe = deferred<BridgeAddress | null>(null)boundary.probe.mockReturnValue(probe.promise)const scanning = runtime.startAutoScan()const signal = recordedProbe()[1]@@ -716,7 +668,7 @@ function describeScanDeadlines() {expect(signal.aborted).toBe(true)expect(connection.stage).toBe('idle')expect(connection.notice).toBe(noHosts)- probe.resolve(openHost(alpha))+ probe.resolve(alpha)await scanningexpect(connection.current).toBeNull()@@ -730,9 +682,9 @@ function describeScanDeadlines() {async function shareTotalDeadline() {hydrate([recentAlpha])- const probe = deferred<BridgeHost | null>(null)+ const probe = deferred<BridgeAddress | null>(null)const ip = deferred('')- const scan = deferred<BridgeHost[]>([])+ const scan = deferred<BridgeAddress[]>([])boundary.probe.mockReturnValue(probe.promise)boundary.ip.mockReturnValue(ip.promise)boundary.scan.mockReturnValue(scan.promise)@@ -786,19 +738,19 @@ function describeScanDeadlines() {async function rejectExpiredChosenHost() {hydrate()- const scan = deferred<BridgeHost[]>([])+ const scan = deferred<BridgeAddress[]>([])boundary.scan.mockReturnValue(scan.promise)const scanning = runtime.startAutoScan()await vi.advanceTimersByTimeAsync(0)await vi.advanceTimersByTimeAsync(19999)- publish(openHost(gamma))+ publish(gamma)expect(recordedScan()[1].signal.aborted).toBe(true)expect(connection.stage).toBe('scanning')await vi.advanceTimersByTimeAsync(1)expect(connection.stage).toBe('idle')expect(connection.notice).toBe(noHosts)- scan.resolve([openHost(gamma)])+ scan.resolve([gamma])await scanningexpect(connection.current).toBeNull()@@ -811,7 +763,7 @@ function describeScanDeadlines() {async function discardDiscoveryAfterDeadline() {hydrate()- const scan = deferred<BridgeHost[]>([])+ const scan = deferred<BridgeAddress[]>([])boundary.scan.mockReturnValue(scan.promise)const scanning = runtime.startAutoScan()await vi.advanceTimersByTimeAsync(0)@@ -819,8 +771,8 @@ function describeScanDeadlines() {await vi.advanceTimersByTimeAsync(20000)expect(recordedScan()[1].signal.aborted).toBe(true)expect(connection.stage).toBe('idle')- publish(openHost(gamma))- scan.resolve([openHost(gamma)])+ publish(gamma)+ scan.resolve([gamma])await scanningexpect(connection.current).toBeNull()@@ -839,7 +791,7 @@ function describeDisconnectDiscovery() {async function skipDisconnectedHistory() {hydrate([recentAlpha, recentBeta])runtime.connectAddress(alpha)- boundary.probe.mockResolvedValue(openHost(beta))+ boundary.probe.mockResolvedValue(beta)runtime.disconnectAndScan()expect(connection.current).toBeNull()@@ -899,15 +851,15 @@ function describeHealthRefresh() {async function preventOverlappingHealthWork() {hydrate([recentAlpha])runtime.connectAddress(alpha)- const probe = deferred<BridgeHost | null>(null)- boundary.probe.mockReturnValueOnce(probe.promise).mockResolvedValueOnce(openHost(alpha))+ const probe = deferred<BridgeAddress | null>(null)+ boundary.probe.mockReturnValueOnce(probe.promise).mockResolvedValueOnce(alpha)const first = runtime.refreshHealth()await runtime.refreshHealth()expect(boundary.probe).toHaveBeenCalledTimes(1)expect(recordedProbe()[0]).toEqual(alpha)expect(recordedProbe()[2]).toBe(3000)- probe.resolve(openHost(alpha))+ probe.resolve(alpha)await firstawait runtime.refreshHealth()@@ -961,7 +913,7 @@ function describeHealthRefresh() {async function isolatePreviousOriginHealth() {hydrate([recentAlpha])runtime.connectAddress(alpha)- const probe = deferred<BridgeHost | null>(null)+ const probe = deferred<BridgeAddress | null>(null)boundary.probe.mockReturnValue(probe.promise)const refreshing = runtime.refreshHealth()@@ -981,7 +933,7 @@ function describeHealthRefresh() {async function discardHealthFromPreviousConnection() {hydrate([recentAlpha])runtime.connectAddress(alpha)- const probe = deferred<BridgeHost | null>(null)+ const probe = deferred<BridgeAddress | null>(null)boundary.probe.mockReturnValue(probe.promise)const refreshing = runtime.refreshHealth()const oldGeneration = connection.viewGeneration@@ -1002,8 +954,8 @@ function describeHealthRefresh() {async function retainNewHealthControllerOwnership() {hydrate([recentAlpha])runtime.connectAddress(alpha)- const oldProbe = deferred<BridgeHost | null>(null)- const newProbe = deferred<BridgeHost | null>(null)+ const oldProbe = deferred<BridgeAddress | null>(null)+ const newProbe = deferred<BridgeAddress | null>(null)boundary.probe.mockReturnValueOnce(oldProbe.promise).mockReturnValueOnce(newProbe.promise)const oldRefresh = runtime.refreshHealth()const oldSignal = recordedProbe(0)[1]@@ -1020,7 +972,7 @@ function describeHealthRefresh() {await runtime.refreshHealth()expect(boundary.probe).toHaveBeenCalledTimes(2)expect(newSignal.aborted).toBe(false)- newProbe.resolve(openHost(alpha))+ newProbe.resolve(alpha)await newRefreshexpect(connection.health[alpha.id]).toBe('available')@@ -1032,7 +984,7 @@ function describeHealthRefresh() {async function notifyOfflineTransitions() {hydrate([recentAlpha])runtime.connectAddress(alpha)- boundary.probe.mockResolvedValueOnce(null).mockResolvedValueOnce(null).mockResolvedValueOnce(openHost(alpha)).mockResolvedValueOnce(null)+ boundary.probe.mockResolvedValueOnce(null).mockResolvedValueOnce(null).mockResolvedValueOnce(alpha).mockResolvedValueOnce(null)await runtime.refreshHealth()@@ -1066,7 +1018,7 @@ function describeHealthRefresh() {hydrate([recentAlpha])runtime.connectAddress(alpha)connection.setNotice('Fixture unrelated notice')- boundary.probe.mockResolvedValue(openHost(alpha))+ boundary.probe.mockResolvedValue(alpha)await runtime.refreshHealth()diff --git a/src-native/store/modules/connection/runtime.ts b/src-native/store/modules/connection/runtime.tsindex d5141d26..deb2dfbc 100644--- a/src-native/store/modules/connection/runtime.ts+++ b/src-native/store/modules/connection/runtime.ts@@ -1,4 +1,3 @@-import type { BridgeHost } from '@/services/probe-bridge'import type { BridgeAddress } from '@/utils/bridge-protocol'import * as Network from 'expo-network'import { EXTRA_SCAN_PORTS, HISTORY_PROBE_TIMEOUT_MS, SCAN_BUDGET_MS } from '@/config/constants'@@ -54,19 +53,12 @@ export async function startAutoScan({ skipId, historyOnly = false }: { skipId?:}))if (controller.signal.aborted || generation !== connection.scanGeneration)return- let needsToken = falsefor (const host of previous) {- if (!host)- continue- if (host.auth.enabled && host.auth.mode === 'token_only' && !host.token) {- needsToken = true- continue- }- if (connection.accept(host, generation))+ if (host && connection.accept(host, generation))return}if (historyOnly) {- connection.finishScan(generation, needsToken ? i18n.t('connection.tokenRequired') : i18n.t('connection.noHistoryAvailable'))+ connection.finishScan(generation, i18n.t('connection.noHistoryAvailable'))return}const selfIp = await Network.getIpAddressAsync()@@ -87,18 +79,13 @@ export async function startAutoScan({ skipId, historyOnly = false }: { skipId?:connection.finishScan(generation, i18n.t('connection.noNetwork'))return}- let chosen: BridgeHost | undefined+ let chosen: BridgeAddress | undefinedawait scanCandidates(candidates, {signal: controller.signal,onFound(host) {if (expired || controller.signal.aborted || generation !== connection.scanGeneration)return- const saved = withSavedToken(host)- if (host.auth.enabled && host.auth.mode === 'token_only' && !saved.token) {- needsToken = true- return- }- chosen = { ...host, ...saved }+ chosen = withSavedToken(host)controller.abort()},})@@ -108,10 +95,7 @@ export async function startAutoScan({ skipId, historyOnly = false }: { skipId?:connection.accept(chosen, generation)}else {- let notice: string = i18n.t('connection.noHosts')- if (needsToken)- notice = i18n.t('connection.tokenRequired')- connection.finishScan(generation, notice)+ connection.finishScan(generation, i18n.t('connection.noHosts'))}}catch (error) {diff --git a/src-native/ui/_layout.test.tsx b/src-native/ui/_layout.test.tsxindex 8d557b32..973d7e2c 100644--- a/src-native/ui/_layout.test.tsx+++ b/src-native/ui/_layout.test.tsx@@ -401,7 +401,7 @@ beforeEach(async () => {native.readToken.mockResolvedValue(null)native.writeToken.mockResolvedValue(undefined)native.deleteToken.mockResolvedValue(undefined)- native.fetch.mockImplementation(async () => Response.json({ enabled: false, allowLoopback: true }))+ native.fetch.mockImplementation(async () => Response.json({ name: 'DeepSeek Harness', short_name: 'DSH' }))native.getIpAddressAsync.mockResolvedValue('0.0.0.0')native.getLastNotificationResponseAsync.mockResolvedValue(null)native.clearLastNotificationResponseAsync.mockResolvedValue(undefined)@@ -545,12 +545,12 @@ describe('rendered root entry selection', () => {expect(texts()).toContain('寻找可用连接')// 只锁定探测到的主机集合与顺序:水合后的健康查询与历史自动接入各探一轮,重复轮次不是本用例的契约。expect([...new Set(native.fetch.mock.calls.map(([url]) => url))]).toEqual([- 'http://bridge.local:3080/__dsh_bridge__/auth-status',- 'https://second.local/__dsh_bridge__/auth-status',+ 'http://bridge.local:3080/manifest.webmanifest',+ 'https://second.local/manifest.webmanifest',])expect(native.getIpAddressAsync).not.toHaveBeenCalled()await act(async () => {- older.resolve(Response.json({ enabled: false, allowLoopback: true }))+ older.resolve(Response.json({ name: 'DeepSeek Harness', short_name: 'DSH' }))await vi.advanceTimersByTimeAsync(0)})expect(connection.current).toBeNull()@@ -754,6 +754,47 @@ describe('rendered root notification focus', () => {})describe('rendered root lifecycle resources', () => {+ it('keeps QR pairing healthy through real fifteen-second checks without replaying its consumed code and still reports a real outage', async () => {+ native.fetch.mockImplementation(async (input) => {+ if (String(input) === `${alpha.id}/manifest.webmanifest`)+ return Response.json({ name: 'DeepSeek Harness', short_name: 'DSH' })+ return new Response(null, { status: 404 })+ })+ await mount()+ await press('扫码连接')+ const camera = root().find(node => String(node.type) === 'CameraView')+ await act(async () => {+ camera.props.onBarcodeScanned({ data: `${alpha.url}?auth=once-only-code` })+ })+ expect(webView().props.source).toEqual({ uri: `${alpha.url}?auth=once-only-code` })+ await ready(alpha.id)+ const instance = await webViewInstance()+ const generation = connection.viewGeneration++ for (let interval = 0; interval < 3; interval++) {+ await act(async () => {+ await vi.advanceTimersByTimeAsync(15000)+ })+ expect(connection.health[alpha.id]).toBe('available')+ expect(connection.notice).toBeNull()+ expect(native.scheduleNotificationAsync).not.toHaveBeenCalled()+ }+ expect(native.fetch).toHaveBeenCalledTimes(3)+ expect(native.fetch.mock.calls.every(([url]) => String(url) === `${alpha.id}/manifest.webmanifest`)).toBe(true)+ expect(await webViewInstance()).toBe(instance)+ expect(connection.viewGeneration).toBe(generation)++ native.fetch.mockResolvedValue(new Response(null, { status: 503 }))+ await act(async () => {+ await vi.advanceTimersByTimeAsync(15000)+ })+ expect(connection.health[alpha.id]).toBe('unavailable')+ const { i18n } = await import('@/i18n')+ expect(connection.notice).toBe(i18n.t('connection.hostOffline'))+ expect(native.scheduleNotificationAsync).not.toHaveBeenCalled()+ expect(await webViewInstance()).toBe(instance)+ })+it('refreshes health on foreground return and active intervals, but not while backgrounded', async () => {// 客户端环境由文件顶部的 `vi.hoisted` 提供:`isServer` 在 query-core 模块加载时就已确定,// 测试内再补 `window` 不会生效,只会掩盖「前台按间隔轮询」这条设备行为。@@ -777,7 +818,7 @@ describe('rendered root lifecycle resources', () => {expect(texts()).toContain('主机暂时不可用')expect(button('bridge.local:3080,不可用').props.accessibilityLabel).toBe('bridge.local:3080,不可用')native.fetch.mockClear()- native.fetch.mockImplementation(async () => Response.json({ enabled: false, allowLoopback: true }))+ native.fetch.mockImplementation(async () => Response.json({ name: 'DeepSeek Harness', short_name: 'DSH' }))await act(async () => {await vi.advanceTimersByTimeAsync(15000)})diff --git a/src-native/ui/index.test.tsx b/src-native/ui/index.test.tsxindex b1ddd76b..e905f4a7 100644--- a/src-native/ui/index.test.tsx+++ b/src-native/ui/index.test.tsx@@ -247,7 +247,7 @@ beforeEach(async () => {native.appListeners.clear()native.backListeners.clear()native.navigation.isFocused.mockReturnValue(true)- native.fetch.mockImplementation(async () => Response.json({ enabled: false, allowLoopback: true }))+ native.fetch.mockImplementation(async () => Response.json({ name: 'DeepSeek Harness', short_name: 'DSH' }))native.getIpAddressAsync.mockResolvedValue('192.168.1.50')native.getPermissionsAsync.mockResolvedValue({ granted: true })native.requestPermissionsAsync.mockResolvedValue({ granted: true })@@ -279,6 +279,28 @@ afterEach(async () => {})describe('rendered Home scanning and idle actions', () => {+ it('discovers the LAN DSH serving its public manifest instead of the nonexistent auth-status route', async () => {+ const origin = 'http://192.168.1.2:3088'+ native.fetch.mockImplementation(async (input) => {+ if (String(input) === `${origin}/manifest.webmanifest`)+ return Response.json({ name: 'DeepSeek Harness', short_name: 'DSH' })+ return new Response(null, { status: 404 })+ })+ hydrate()+ connection.cancelScan()+ await mount()++ await press('自动扫描局域网')++ expect(connection.current).toEqual({ id: origin, url: `${origin}/`, host: '192.168.1.2', port: 3088 })+ expect(webView().props.source).toEqual({ uri: `${origin}/` })+ expect(connection.loading).toBe(true)+ expect(connection.history).toEqual([])+ expect(connection.notice).toBeNull()+ expect(native.getIpAddressAsync).toHaveBeenCalledTimes(1)+ expect(native.fetch.mock.calls.every(([url]) => new URL(String(url)).pathname === '/manifest.webmanifest')).toBe(true)+ })+it('cancels the active discovery and reveals usable idle actions without a late timeout notice', async () => {hydrate(history.slice(0, 1))holdNetwork()@@ -477,6 +499,38 @@ describe('rendered Home connection editing', () => {})describe('rendered Home connection drawer', () => {+ it('keeps a successfully paired page available when a left swipe refreshes the real DSH manifest', async () => {+ native.fetch.mockImplementation(async (input) => {+ if (String(input) === `${alpha.id}/manifest.webmanifest`)+ return Response.json({ name: 'DeepSeek Harness', short_name: 'DSH' })+ return new Response(null, { status: 404 })+ })+ hydrate()+ runtime.connectAddress({ ...alpha, token: 'consumed-pairing-code' })+ await mount()+ await ready()+ const { WebView } = await import('react-native-webview')+ const instance = root().findByType(WebView).instance+ const generation = connection.viewGeneration++ await act(async () => drawer().props.onOpen())++ expect(drawer().props.open).toBe(true)+ expect(connection.health[alpha.id]).toBe('available')+ expect(connection.notice).toBeNull()+ expect(texts()).not.toContain('主机暂时不可用')+ expect(native.scheduleNotificationAsync).not.toHaveBeenCalled()+ expect(root().findByType(WebView).instance).toBe(instance)+ expect(connection.viewGeneration).toBe(generation)+ expect(webView().props.source).toEqual({ uri: 'http://one.local:3080/tasks?auth=consumed-pairing-code' })+ expect(native.fetch).toHaveBeenCalledExactlyOnceWith(`${alpha.id}/manifest.webmanifest`, {+ signal: expect.any(AbortSignal),+ headers: { Accept: 'application/manifest+json' },+ cache: 'no-store',+ redirect: 'error',+ })+ })+it('opens the right slide drawer from a wider inner-edge region and presents five recent hosts with accessible status', async () => {hydrate(history)connection.cancelScan()@@ -651,7 +705,7 @@ describe('rendered Home connection drawer', () => {await press('刷新最近连接')await press('刷新最近连接')expect(native.fetch).toHaveBeenCalledTimes(3)- expect(native.fetch.mock.calls[2]![0]).toBe('http://one.local:3080/__dsh_bridge__/auth-status')+ expect(native.fetch.mock.calls[2]![0]).toBe('http://one.local:3080/manifest.webmanifest')expect(connection.viewGeneration).toBe(0)})diff --git a/src-native/ui/webview.test.tsx b/src-native/ui/webview.test.tsxindex 4aaad7a0..50934d22 100644--- a/src-native/ui/webview.test.tsx+++ b/src-native/ui/webview.test.tsx@@ -230,7 +230,8 @@ class BrowserMessageEvent extends Event {}}-function createPage(selectSession?: (sessionId: string) => void, kind: 'app' | 'login' | 'unverified' = 'app') {+function createPage(selectSession?: (sessionId: string) => void, kind: 'app' | 'login' | 'unverified' = 'app', html?: string) {+ const ids = new Set(Array.from(html?.matchAll(/\bid="([^"]+)"/g) ?? [], match => match[1]))const posts: string[] = []const events = new EventTarget()const documentEvents = new EventTarget()@@ -253,7 +254,7 @@ function createPage(selectSession?: (sessionId: string) => void, kind: 'app' | 'body: null,head: { appendChild: (style: { id: string, textContent: string }) => styles.set(style.id, style) },createElement: () => ({ id: '', textContent: '' }),- getElementById: (id: string) => styles.get(id) ?? (kind === 'login' && id === 'loginForm' ? {} : null),+ getElementById: (id: string) => styles.get(id) ?? (ids.has(id) || (kind === 'login' && id === 'loginForm') ? {} : null),querySelectorAll: () => [],addEventListener: (type: string, listener: EventListener, options?: AddEventListenerOptions) => documentEvents.addEventListener(type, listener, options),removeEventListener: (type: string, listener: EventListener, options?: EventListenerOptions) => documentEvents.removeEventListener(type, listener, options),@@ -322,6 +323,28 @@ afterEach(async () => {})describe('rendered Bridge WebView document lifecycle', () => {+ it('reveals the real gateway pairing form after trusted SSR readiness instead of leaving it behind the fullscreen loader', async () => {+ vi.useRealTimers()+ const { loginPageHtml } = await vi.importActual<{ loginPageHtml: (message?: string) => string }>('../../packages/dsh-tauri-remote/src/host/service/gateway.utils')+ vi.useFakeTimers()+ await mount()+ const page = createPage(undefined, 'unverified', loginPageHtml())++ expect(page.posts).toHaveLength(1)+ const raw = page.posts[0]!+ expect(JSON.parse(raw)).toEqual({ channel: 'dsh-bridge', origin: alpha.id, nonce, payload: { type: 'dsh://bridge-ready' } })+ await rawMessage(raw, 'https://foreign.test/')+ expect(connection.loading).toBe(true)+ await rawMessage(JSON.stringify({ ...JSON.parse(raw), nonce: 'stale-nonce' }))+ expect(connection.loading).toBe(true)+ await rawMessage(raw)++ expect(connection.loading).toBe(false)+ expect(connection.loadError).toBeNull()+ const { i18n } = await import('@/i18n')+ expect(texts()).not.toContain(i18n.t('connection.loading'))+ })+it.each(['android', 'ios'])('declares only the safe-area edges already padded natively on %s', async (platform) => {native.platform.OS = platformawait mount()diff --git a/src-native/utils/bridge-protocol.test.ts b/src-native/utils/bridge-protocol.test.tsindex b1e9b2b0..b32ddec7 100644--- a/src-native/utils/bridge-protocol.test.ts+++ b/src-native/utils/bridge-protocol.test.ts@@ -1,5 +1,5 @@import { afterEach, describe, expect, it, vi } from 'vitest'-import { buildConnectUrl, connectionLabel, isBridgeManifest, isRecord, isTrustedOrigin, parseAuthStatus, parseQrPayload } from './bridge-protocol'+import { buildConnectUrl, connectionLabel, isBridgeManifest, isRecord, isTrustedOrigin, parseQrPayload } from './bridge-protocol'afterEach(() => {vi.restoreAllMocks()@@ -128,25 +128,6 @@ describe('protocol response validation', () => {expect(isRecord({ enabled: false })).toBe(true)})- it.each([- null,- [],- {},- { enabled: 'true' },- { enabled: 1 },- { enabled: false, mode: null },- { enabled: true, mode: 4 },- { enabled: true, allowLoopback: 'true' },- { enabled: true, allowLoopback: null },- ])('rejects malformed auth status %j', (value) => {- expect(parseAuthStatus(value)).toBeNull()- })-- it('returns only validated auth fields', () => {- expect(parseAuthStatus({ enabled: true, mode: 'token_only', allowLoopback: false, token: 'secret', extra: true })).toEqual({ enabled: true, mode: 'token_only', allowLoopback: false })- expect(parseAuthStatus({ enabled: false })).toEqual({ enabled: false })- })-it.each([null,[],diff --git a/src-native/utils/bridge-protocol.ts b/src-native/utils/bridge-protocol.tsindex 9c60d19b..b9b93016 100644--- a/src-native/utils/bridge-protocol.ts+++ b/src-native/utils/bridge-protocol.ts@@ -1,4 +1,4 @@-import type { AuthStatus, BridgeManifest } from '@/apis/index.types'+import type { BridgeManifest } from '@/apis/index.types'export interface BridgeAddress {id: string@@ -13,21 +13,6 @@ export function isRecord(value: unknown): value is Record<string, unknown> {return typeof value === 'object' && value !== null && !Array.isArray(value)}-export function parseAuthStatus(value: unknown): AuthStatus | null {- if (!isRecord(value) || typeof value.enabled !== 'boolean')- return null- if (value.mode !== undefined && typeof value.mode !== 'string')- return null- if (value.allowLoopback !== undefined && typeof value.allowLoopback !== 'boolean')- return null- const status: AuthStatus = { enabled: value.enabled }- if (typeof value.mode === 'string')- status.mode = value.mode- if (typeof value.allowLoopback === 'boolean')- status.allowLoopback = value.allowLoopback- return status-}-export function isBridgeManifest(value: unknown): value is BridgeManifest {return isRecord(value) && value.name === 'DeepSeek Harness' && value.short_name === 'DSH'}diff --git a/src/apis/remote.types.ts b/src/apis/remote.types.tsindex 68e871c1..ca0ad6a5 100644--- a/src/apis/remote.types.ts+++ b/src/apis/remote.types.ts@@ -25,7 +25,7 @@ export type GetApiTauriRemoteAccessResponse = {listening: false | true;listen: { address: string; port: number };port: number;- auth: { enabled: false | true; scope: "public_only" | "all"; hasPassword?: false | true; hasToken?: false | true; token?: string };+ auth: { enabled: false | true; scope: "public_only" | "all"; hasToken?: false | true; token?: string };addresses: { address: string; family: "ipv4" | "ipv6"; interface: string; scope: "loopback" | "private" | "public" | "link-local"; score: number; recommended: false | true }[];recommended?: string;link?: string;@@ -33,7 +33,6 @@ export type GetApiTauriRemoteAccessResponse = {qr?: string;linkSource?: "loopback" | "lan";pairing?: { code: string; expiresAt: number; usedSeq: number; link?: string; qr?: string; tunnelLink?: string; tunnelQr?: string };- generatedPassword?: string;tunnel?: { state: "error" | "starting" | "stopped" | "running"; events: { seq: number; ts: string; kind: "state" | "process" | "progress"; line: string }[]; token?: string; url?: string; port?: number; link?: string; qr?: string; progress?: { stage: "ready" | "spawn" | "download" | "verify" | "check" | "extract" | "domain"; url?: string; received?: number; total?: number }; error?: string; mode: "quick" | "token"; enabled: false | true; hostname: null | string };localPort?: number;error?: string;@@ -49,7 +48,7 @@ export type PostApiTauriRemoteAccessResponse =listening: false | true;listen: { address: string; port: number };port: number;- auth: { enabled: false | true; scope: "public_only" | "all"; hasPassword?: false | true; hasToken?: false | true; token?: string };+ auth: { enabled: false | true; scope: "public_only" | "all"; hasToken?: false | true; token?: string };addresses: { address: string; family: "ipv4" | "ipv6"; interface: string; scope: "loopback" | "private" | "public" | "link-local"; score: number; recommended: false | true }[];recommended?: string;link?: string;@@ -57,7 +56,6 @@ export type PostApiTauriRemoteAccessResponse =qr?: string;linkSource?: "loopback" | "lan";pairing?: { code: string; expiresAt: number; usedSeq: number; link?: string; qr?: string; tunnelLink?: string; tunnelQr?: string };- generatedPassword?: string;tunnel?: { state: "error" | "starting" | "stopped" | "running"; events: { seq: number; ts: string; kind: "state" | "process" | "progress"; line: string }[]; token?: string; url?: string; port?: number; link?: string; qr?: string; progress?: { stage: "ready" | "spawn" | "download" | "verify" | "check" | "extract" | "domain"; url?: string; received?: number; total?: number }; error?: string; mode: "quick" | "token"; enabled: false | true; hostname: null | string };localPort?: number;error?: string;@@ -73,7 +71,7 @@ export type PostApiTauriRemoteAccessTunnelResponse =listening: false | true;listen: { address: string; port: number };port: number;- auth: { enabled: false | true; scope: "public_only" | "all"; hasPassword?: false | true; hasToken?: false | true; token?: string };+ auth: { enabled: false | true; scope: "public_only" | "all"; hasToken?: false | true; token?: string };addresses: { address: string; family: "ipv4" | "ipv6"; interface: string; scope: "loopback" | "private" | "public" | "link-local"; score: number; recommended: false | true }[];recommended?: string;link?: string;@@ -81,7 +79,6 @@ export type PostApiTauriRemoteAccessTunnelResponse =qr?: string;linkSource?: "loopback" | "lan";pairing?: { code: string; expiresAt: number; usedSeq: number; link?: string; qr?: string; tunnelLink?: string; tunnelQr?: string };- generatedPassword?: string;tunnel?: { state: "error" | "starting" | "stopped" | "running"; events: { seq: number; ts: string; kind: "state" | "process" | "progress"; line: string }[]; token?: string; url?: string; port?: number; link?: string; qr?: string; progress?: { stage: "ready" | "spawn" | "download" | "verify" | "check" | "extract" | "domain"; url?: string; received?: number; total?: number }; error?: string; mode: "quick" | "token"; enabled: false | true; hostname: null | string };localPort?: number;error?: string;@@ -97,7 +94,7 @@ export type DeleteApiTauriRemoteAccessTunnelResponse =listening: false | true;listen: { address: string; port: number };port: number;- auth: { enabled: false | true; scope: "public_only" | "all"; hasPassword?: false | true; hasToken?: false | true; token?: string };+ auth: { enabled: false | true; scope: "public_only" | "all"; hasToken?: false | true; token?: string };addresses: { address: string; family: "ipv4" | "ipv6"; interface: string; scope: "loopback" | "private" | "public" | "link-local"; score: number; recommended: false | true }[];recommended?: string;link?: string;@@ -105,7 +102,6 @@ export type DeleteApiTauriRemoteAccessTunnelResponse =qr?: string;linkSource?: "loopback" | "lan";pairing?: { code: string; expiresAt: number; usedSeq: number; link?: string; qr?: string; tunnelLink?: string; tunnelQr?: string };- generatedPassword?: string;tunnel?: { state: "error" | "starting" | "stopped" | "running"; events: { seq: number; ts: string; kind: "state" | "process" | "progress"; line: string }[]; token?: string; url?: string; port?: number; link?: string; qr?: string; progress?: { stage: "ready" | "spawn" | "download" | "verify" | "check" | "extract" | "domain"; url?: string; received?: number; total?: number }; error?: string; mode: "quick" | "token"; enabled: false | true; hostname: null | string };localPort?: number;error?: string;@@ -148,7 +144,6 @@ export interface PostApiTauriRemoteAccessBody {port?: number;authEnabled?: false | true;scope?: "public_only" | "all";- password?: null | string;}export interface PostApiTauriRemoteAccessTunnelBody {mode?: "quick" | "token";diff --git a/src/i18n/locales/en-US.json b/src/i18n/locales/en-US.jsonindex 1183e0cf..644956b2 100644--- a/src/i18n/locales/en-US.json+++ b/src/i18n/locales/en-US.json@@ -609,15 +609,13 @@"remote.share.stage.domain": "Assigning domain","remote.share.stage.ready": "Ready","remote.share.download_progress": "{{received}} / {{total}} MB",+ "remote.share.download_received": "{{received}} MB","remote.share.tunnel_stop": "Stop tunnel","remote.share.tunnel_failed": "Tunnel failed to start","remote.share.pairing": "Temporary pairing code","remote.share.pairing_absent": "The host did not provide a pairing code.","remote.share.pairing_expires": "Expires in {{time}}","remote.share.pairing_hint": "Enter the code on the other device; valid for 5 minutes.",- "remote.share.password": "Access password generated just now",- "remote.share.password_hint": "The plaintext appears only here and cannot be retrieved later; copy it before closing.",- "remote.share.password_dismiss": "Saved it","config.appearance": "Appearance","appearance.description": "Device-local desktop colours, text scale, and layout. These settings are not synced to other Harness clients.","appearance.palette": "Colour palette",diff --git a/src/i18n/locales/zh-CN.json b/src/i18n/locales/zh-CN.jsonindex 976159cd..fc158d6a 100644--- a/src/i18n/locales/zh-CN.json+++ b/src/i18n/locales/zh-CN.json@@ -609,15 +609,13 @@"remote.share.stage.domain": "分配域名","remote.share.stage.ready": "就绪","remote.share.download_progress": "{{received}} / {{total}} MB",+ "remote.share.download_received": "{{received}} MB","remote.share.tunnel_stop": "停止隧道","remote.share.tunnel_failed": "隧道启动失败","remote.share.pairing": "临时配对码","remote.share.pairing_absent": "宿主暂未提供配对码。","remote.share.pairing_expires": "{{time}} 后过期","remote.share.pairing_hint": "设备输入配对连接,5 分钟内有效。",- "remote.share.password": "本次自动生成的访问密码",- "remote.share.password_hint": "明文只在本次出现,关闭后无法再取回;请先复制保存。",- "remote.share.password_dismiss": "我已保存","config.appearance": "外观","appearance.description": "仅保存在本机的桌面配色、字号与布局,不会同步到其他 Harness 客户端。","appearance.palette": "配色方案",diff --git a/src/layout/components/remote-share.test.tsx b/src/layout/components/remote-share.test.tsxindex 3d44564e..7cd383ae 100644--- a/src/layout/components/remote-share.test.tsx+++ b/src/layout/components/remote-share.test.tsx@@ -1,7 +1,11 @@// @vitest-environment jsdom+import type { ReactElement } from 'react'+import { QueryClient, QueryClientProvider } from '@tanstack/react-query'import { clearMocks, mockIPC } from '@tauri-apps/api/mocks'-import { act, cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'+import { act, cleanup, fireEvent, render as renderElement, screen, waitFor } from '@testing-library/react'import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'+import en from '@/i18n/locales/en-US.json'+import zh from '@/i18n/locales/zh-CN.json'import { RemoteShare } from './remote-share'vi.mock('react-i18next', () => ({@@ -38,6 +42,12 @@ Element.prototype.getAnimations = function () {return []}+let queryClient: QueryClient++function render(element: ReactElement) {+ return renderElement(<QueryClientProvider client={queryClient}>{element}</QueryClientProvider>)+}+const QR = 'data:image/png;base64,qr'const PAIR_CODE = '482913'const LAN_LINK = 'http://192.168.1.5:3080/?auth=482913'@@ -86,6 +96,7 @@ function clickTunnelTab() {}beforeEach(() => {+ queryClient = new QueryClient({ defaultOptions: { queries: { retry: false, gcTime: 0 }, mutations: { retry: false, gcTime: 0 } } })openUrlSpy.mockReset().mockResolvedValue(undefined)mockIPC((command, args) => {if (command === 'open_external_url')@@ -106,6 +117,7 @@ beforeEach(() => {afterEach(() => {cleanup()+ queryClient.clear()clearMocks()vi.restoreAllMocks()vi.useRealTimers()@@ -241,7 +253,7 @@ describe('remoteShare 临时码消费订阅', () => {await waitFor(() => expect(watch.polls).toHaveLength(1))clickTunnelTab()fireEvent.click(screen.getByText('remote.share.tunnel_enable'))- expect(postAccessTunnelSpy).toHaveBeenCalledTimes(1)+ await waitFor(() => expect(postAccessTunnelSpy).toHaveBeenCalledTimes(1))await act(async () => watch.polls[0]!.resolve(consumedStatus(1)))expect(screen.getByRole('dialog')).not.toBeNull()@@ -380,17 +392,47 @@ describe('remoteShare 远程分享弹层', () => {expect(screen.queryByText('remote.share.tunnel_failed')).toBeNull()})- it('隧道启动中:显示阶段与下载进度', async () => {+ it('下载阶段只显示下载文案与进度,不叠加正在启动隧道', async () => {getAccessSpy.mockResolvedValue(statusOf({tunnel: { state: 'starting', mode: 'quick', progress: { stage: 'download', received: 1048576, total: 4194304 } },}))- render(<RemoteShare onManage={vi.fn()} />)+ render(<RemoteShare />)+ await openShare()+ clickTunnelTab()++ await screen.findByRole('progressbar')+ expect(screen.getAllByText('remote.share.stage.download')).toHaveLength(1)+ expect(screen.getByText('remote.share.download_progress').textContent).toBe('remote.share.download_progress')+ expect(screen.getByRole('progressbar').getAttribute('aria-valuenow')).toBe('25')+ expect(screen.queryByText(/remote\.share\.tunnel_starting/u)).toBeNull()+ })++ it.each([undefined, 0])('下载总量 %s 时仍显示不定进度,不叠加启动文案', async (total) => {+ getAccessSpy.mockResolvedValue(statusOf({+ tunnel: { state: 'starting', mode: 'quick', progress: { stage: 'download', received: 1048576, total } },+ }))+ render(<RemoteShare />)+ await openShare()+ clickTunnelTab()++ await screen.findByRole('progressbar')+ expect(screen.getByRole('progressbar').getAttribute('aria-valuenow')).toBeNull()+ expect(screen.getAllByText('remote.share.stage.download')).toHaveLength(1)+ expect(screen.getByText('remote.share.download_received').textContent).toBe('remote.share.download_received')+ expect(screen.queryByText(/remote\.share\.tunnel_starting/u)).toBeNull()+ })++ it('下载结束后的启动阶段不再展示残留下载字节', async () => {+ getAccessSpy.mockResolvedValue(statusOf({+ tunnel: { state: 'starting', mode: 'quick', progress: { stage: 'spawn', received: 4194304, total: 4194304 } },+ }))+ render(<RemoteShare />)await openShare()clickTunnelTab()- expect(await screen.findByText('remote.share.stage.download')).toBeTruthy()- expect(screen.getByText('remote.share.download_progress')).toBeTruthy()- expect(screen.getByText(/remote\.share\.tunnel_starting/u).textContent).toBe('remote.share.tunnel_starting(remote.share.stage.download)')+ expect((await screen.findByText(/remote\.share\.tunnel_starting/u)).textContent).toBe('remote.share.tunnel_starting(remote.share.stage.spawn)')+ expect(screen.queryByRole('progressbar')).toBeNull()+ expect(screen.queryByText('remote.share.stage.download')).toBeNull()})it('隧道失败:显示原因并可重试', async () => {@@ -461,55 +503,122 @@ describe('remoteShare 远程分享弹层', () => {expect(screen.getByTestId('remote-share-pairing').textContent).toBe(PAIR_CODE)})- it('动作返回的访问密码明文只在弹层里保留,可复制可关闭', async () => {+ it('旧动作回包的访问密码不再展示,分享仅保留配对码与链接', async () => {postAccessSpy.mockResolvedValue(statusOf({ ...listening, generatedPassword: 'Gen-Pass-1234' }))- render(<RemoteShare onManage={vi.fn()} />)+ render(<RemoteShare />)await openShare()fireEvent.click(await screen.findByText('remote.share.lan_enable'))- expect((await screen.findByTestId('remote-share-password')).textContent).toBe('Gen-Pass-1234')- fireEvent.click(screen.getByTestId('remote-share-password-copy'))- await waitFor(() => expect(clipboardSpy).toHaveBeenCalledWith('Gen-Pass-1234', 'remote.share.copied'))-- fireEvent.click(screen.getByTestId('remote-share-password-dismiss'))+ expect((await screen.findByTestId('remote-share-pairing')).textContent).toBe(PAIR_CODE)+ expect(screen.getByText(LAN_LINK).textContent).toBe(LAN_LINK)expect(screen.queryByTestId('remote-share-password')).toBeNull()+ expect(screen.queryByText('Gen-Pass-1234')).toBeNull()+ expect(screen.queryByText('remote.share.password')).toBeNull()})- it('动作进行中打到轮询:结果不被丢弃,按钮也不会永久锁死', async () => {- vi.useFakeTimers()- try {- let resolveTunnel: ((value: unknown) => void) | undefined- postAccessTunnelSpy.mockImplementation(() => new Promise((resolve) => {- resolveTunnel = resolve- }))- getAccessSpy.mockResolvedValue(statusOf({- tunnel: { enabled: false, mode: 'quick', state: 'stopped', events: [] },- }))- render(<RemoteShare onManage={vi.fn()} />)- fireEvent.click(screen.getByRole('button', { name: 'remote.share' }))- await vi.advanceTimersByTimeAsync(0)- fireEvent.click(screen.getByText('remote.share.tab_tunnel'))- fireEvent.click(screen.getByText('remote.share.tunnel_enable'))- await vi.advanceTimersByTimeAsync(0)- expect(postAccessTunnelSpy).toHaveBeenCalledTimes(1)-- await vi.advanceTimersByTimeAsync(5000)- expect(getAccessSpy).toHaveBeenCalledTimes(1)-- resolveTunnel?.(statusOf({- pairing: pairingOf({ tunnelLink: TUNNEL_LINK, tunnelQr: QR }),- tunnel: { state: 'running', mode: 'quick' },- }))- await vi.advanceTimersByTimeAsync(0)-- expect(screen.getByText(TUNNEL_LINK)).toBeTruthy()- expect((screen.getByText('remote.share.tunnel_stop') as HTMLButtonElement).disabled).toBe(false)- }- finally {- vi.useRealTimers()+ it('两种语言移除访问密码文案,保留 SSH 密码与未知总量下载提示', () => {+ for (const locale of [en, zh]) {+ expect(Object.keys(locale).filter(key => key.startsWith('remote.share.password'))).toEqual([])+ expect(locale['remote.auth.password']).toBeTypeOf('string')+ expect(locale).toHaveProperty('remote.share.download_received', '{{received}} MB')}})+ it('首次隧道下载尚未返回时持续轮询进度,较旧动作快照不覆盖刚取得的下载', async () => {+ vi.useFakeTimers({ toFake: ['Date', 'setInterval', 'clearInterval'] })+ const mutation = Promise.withResolvers<unknown>()+ postAccessTunnelSpy.mockReturnValue(mutation.promise)+ getAccessSpy.mockResolvedValueOnce(statusOf()).mockResolvedValue(statusOf({+ tunnel: { enabled: true, mode: 'quick', state: 'starting', progress: { stage: 'download', received: 1048576, total: 4194304 } },+ }))+ render(<RemoteShare />)+ await openShare()+ await screen.findByText('remote.share.lan_enable')+ clickTunnelTab()+ fireEvent.click(screen.getByText('remote.share.tunnel_enable'))+ await waitFor(() => expect(postAccessTunnelSpy).toHaveBeenCalledExactlyOnceWith({ mode: 'quick' }))++ await act(async () => vi.advanceTimersByTimeAsync(5000))++ expect(getAccessSpy).toHaveBeenCalledTimes(2)+ expect(screen.getByRole('progressbar').getAttribute('aria-valuenow')).toBe('25')+ expect(screen.queryByText('remote.share.tunnel_off_desc')).toBeNull()+ expect(screen.queryByText(/remote\.share\.tunnel_starting/u)).toBeNull()+ expect((screen.getByText('remote.share.tunnel_stop') as HTMLButtonElement).disabled).toBe(true)++ await act(async () => mutation.resolve(statusOf()))+ await waitFor(() => expect((screen.getByText('remote.share.tunnel_stop') as HTMLButtonElement).disabled).toBe(false))++ expect(screen.getByRole('progressbar').getAttribute('aria-valuenow')).toBe('25')+ expect(screen.queryByText('remote.share.tunnel_enable')).toBeNull()+ })++ it('启动动作结束后忽略在结束前捕获的轮询快照,后续轮询仍可更新为运行', async () => {+ vi.useFakeTimers({ toFake: ['Date', 'setInterval', 'clearInterval'] })+ const mutation = Promise.withResolvers<unknown>()+ const poll = Promise.withResolvers<unknown>()+ postAccessTunnelSpy.mockReturnValue(mutation.promise)+ getAccessSpy.mockResolvedValueOnce(statusOf()).mockReturnValueOnce(poll.promise)+ render(<RemoteShare />)+ await openShare()+ await screen.findByText('remote.share.lan_enable')+ clickTunnelTab()+ fireEvent.click(screen.getByText('remote.share.tunnel_enable'))+ await act(async () => vi.advanceTimersByTimeAsync(5000))+ expect(getAccessSpy).toHaveBeenCalledTimes(2)++ const running = statusOf({+ pairing: pairingOf({ tunnelLink: TUNNEL_LINK, tunnelQr: QR }),+ tunnel: { state: 'running', mode: 'quick' },+ })+ getAccessSpy.mockResolvedValue(running)+ await act(async () => mutation.resolve(running))+ expect(screen.getByText(TUNNEL_LINK).textContent).toBe(TUNNEL_LINK)+ await act(async () => poll.resolve(statusOf({ tunnel: { state: 'starting', progress: { stage: 'download', received: 1, total: 2 } } })))+ expect(screen.getByText(TUNNEL_LINK).textContent).toBe(TUNNEL_LINK)+ expect(screen.queryByRole('progressbar')).toBeNull()+ expect((screen.getByText('remote.share.tunnel_stop') as HTMLButtonElement).disabled).toBe(false)+ })++ it('普通轮询乱序返回时,旧 stopped 快照不覆盖新下载进度', async () => {+ vi.useFakeTimers({ toFake: ['Date', 'setInterval', 'clearInterval'] })+ const older = Promise.withResolvers<unknown>()+ const newer = Promise.withResolvers<unknown>()+ getAccessSpy.mockResolvedValueOnce(statusOf()).mockReturnValueOnce(older.promise).mockReturnValueOnce(newer.promise)+ render(<RemoteShare />)+ await openShare()+ await screen.findByText('remote.share.lan_enable')+ clickTunnelTab()+ await act(async () => vi.advanceTimersByTimeAsync(10000))+ expect(getAccessSpy).toHaveBeenCalledTimes(3)++ await act(async () => newer.resolve(statusOf({ tunnel: { state: 'starting', progress: { stage: 'download', received: 1, total: 2 } } })))+ expect(screen.getByRole('progressbar').getAttribute('aria-valuenow')).toBe('50')+ await act(async () => older.resolve(statusOf()))+ expect(screen.getByRole('progressbar').getAttribute('aria-valuenow')).toBe('50')+ expect(screen.queryByText('remote.share.tunnel_enable')).toBeNull()+ })++ it('长启动请求失败后仍给出错误并解除按钮锁,不被进度 polling 掩盖', async () => {+ vi.useFakeTimers({ toFake: ['Date', 'setInterval', 'clearInterval'] })+ const mutation = Promise.withResolvers<unknown>()+ postAccessTunnelSpy.mockReturnValue(mutation.promise)+ getAccessSpy.mockResolvedValueOnce(statusOf()).mockResolvedValue(statusOf({+ tunnel: { state: 'starting', progress: { stage: 'download', received: 1, total: 2 } },+ }))+ render(<RemoteShare />)+ await openShare()+ await screen.findByText('remote.share.lan_enable')+ clickTunnelTab()+ fireEvent.click(screen.getByText('remote.share.tunnel_enable'))+ await act(async () => vi.advanceTimersByTimeAsync(5000))+ expect(getAccessSpy).toHaveBeenCalledTimes(2)+ await act(async () => mutation.reject(new Error('download denied')))++ expect(screen.getByText(/download denied/u).textContent).toContain('download denied')+ expect((screen.getByText('remote.share.tunnel_stop') as HTMLButtonElement).disabled).toBe(false)+ })+it('齿轮保留在标题右侧且打通设置定位链路,缺席时点击不动作', async () => {const manageSpy = vi.fn()const { unmount } = render(<RemoteShare onManage={manageSpy} />)diff --git a/src/layout/components/remote-share.tsx b/src/layout/components/remote-share.tsxindex bdef9ce6..e406922a 100644--- a/src/layout/components/remote-share.tsx+++ b/src/layout/components/remote-share.tsx@@ -1,6 +1,7 @@import { ArrowUpRightFromSquare, Copy, Gear, Smartphone, TriangleExclamation } from '@gravity-ui/icons'import { Button, Description, Label, Popover, ProgressBar, Spinner, Tabs } from '@heroui/react'import { useIntervalFn, useUnmount, useUnmountedRef, useWatch } from '@reause/core'+import { useMutation } from '@tanstack/react-query'import { invoke } from '@tauri-apps/api/core'import { useRef, useState } from 'react'import { useTranslation } from 'react-i18next'@@ -46,7 +47,6 @@ interface AccessStatus {error?: stringwarnings?: string[]pairing?: AccessPairing- generatedPassword?: stringtunnel?: AccessTunnel}@@ -83,11 +83,9 @@ export function RemoteShare({ onManage }: { onManage?: () => void }) {const [open, setOpen] = useState(false)const [status, setStatus] = useState<AccessStatus | null>(null)const [error, setError] = useState<string | null>(null)- const [busy, setBusy] = useState(false)- const [generatedPassword, setGeneratedPassword] = useState<string | null>(null)const [now, setNow] = useState(() => Date.now())const requestSeqRef = useRef(0)- const mutationSeqRef = useRef(0)+ const savedSeqRef = useRef(0)const busyRef = useRef(false)const refreshedExpiryRef = useRef<number | null>(null)const openRef = useRef(false)@@ -122,49 +120,54 @@ export function RemoteShare({ onManage }: { onManage?: () => void }) {}async function load(consumed = false) {- if (busyRef.current || !openRef.current || unmountedRef.current)+ if (!openRef.current || unmountedRef.current)returnconst seq = ++requestSeqRef.currenttry {const raw = await getAccess() as unknown as AccessStatusif (seq !== requestSeqRef.current || unmountedRef.current)return+ savedSeqRef.current = sequpdateStatus(raw, consumed)}catch (err) {if (seq !== requestSeqRef.current || unmountedRef.current)return+ savedSeqRef.current = seqsetError(String(err))}}- async function run(action: () => Promise<unknown>) {+ const { mutate, isPending: busy } = useMutation({+ mutationFn: async ({ action }: { action: () => Promise<unknown>, session: number, seq: number }) => await action() as AccessStatus,+ onSuccess: async (raw, { session, seq }) => {+ if (session !== sessionRef.current || !openRef.current || unmountedRef.current)+ return+ const refreshed = savedSeqRef.current > seq+ requestSeqRef.current += 1+ if (refreshed)+ await load()+ else+ updateStatus(raw)+ },+ onError: (err, { session }) => {+ if (session !== sessionRef.current || !openRef.current || unmountedRef.current)+ return+ requestSeqRef.current += 1+ setError(String(err))+ },+ onSettled: () => {+ busyRef.current = false+ },+ })++ function run(action: () => Promise<unknown>) {if (busyRef.current || !openRef.current || unmountedRef.current)returnconst seq = ++requestSeqRef.current- const mutation = ++mutationSeqRef.currentbusyRef.current = true- setBusy(true)setError(null)- try {- const raw = await action() as AccessStatus- if (seq !== requestSeqRef.current || unmountedRef.current)- return- updateStatus(raw)- if (typeof raw?.generatedPassword === 'string' && raw.generatedPassword !== '')- setGeneratedPassword(raw.generatedPassword)- }- catch (err) {- if (seq !== requestSeqRef.current || unmountedRef.current)- return- setError(String(err))- }- finally {- if (mutation === mutationSeqRef.current && !unmountedRef.current) {- busyRef.current = false- setBusy(false)- }- }+ mutate({ action, session: sessionRef.current, seq })}async function watchPairingUse(session: number, baseline: number) {@@ -259,6 +262,12 @@ export function RemoteShare({ onManage }: { onManage?: () => void }) {const stage = tunnel?.progress?.stageconst received = tunnel?.progress?.receivedconst total = tunnel?.progress?.total+ const downloading = stage === 'download'+ const knownTotal = total !== undefined && Number.isFinite(total) && total > 0+ const downloadPercent = knownTotal ? Math.max(0, Math.min(100, ((received ?? 0) / total) * 100)) : undefined+ const downloadLabel = knownTotal+ ? t('remote.share.download_progress', { received: megabytesOf(received), total: megabytesOf(total) })+ : t('remote.share.download_received', { received: megabytesOf(received) })const pairingCode = (<div className="flex flex-col gap-1.5 rounded-lg border border-line/40 px-2.5 py-2"><span className="text-[11px] text-muted">{t('remote.share.pairing')}</span>@@ -280,38 +289,6 @@ export function RemoteShare({ onManage }: { onManage?: () => void }) {</div>)- const passwordBlock = generatedPassword === null- ? null- : (- <div className="flex flex-col gap-1.5 rounded-lg border border-warning/40 px-2.5 py-2">- <span className="text-[11px] text-muted">{t('remote.share.password')}</span>- <div className="flex items-center gap-2">- <span className="break-all font-mono text-xs text-ink" data-testid="remote-share-password">{generatedPassword}</span>- <Button- className="ml-auto size-7 shrink-0"- isIconOnly- size="sm"- variant="ghost"- aria-label={t('remote.share.copy')}- data-testid="remote-share-password-copy"- onPress={() => copyLink(generatedPassword)}- >- <Copy className="size-3.5" />- </Button>- <Button- className="h-7 shrink-0 text-[11px]"- size="sm"- variant="ghost"- data-testid="remote-share-password-dismiss"- onPress={() => setGeneratedPassword(null)}- >- {t('remote.share.password_dismiss')}- </Button>- </div>- <span className="text-[11px] leading-4 text-muted">{t('remote.share.password_hint')}</span>- </div>- )-return (<Popover isOpen={open} onOpenChange={changeOpen}><Button@@ -437,7 +414,6 @@ export function RemoteShare({ onManage }: { onManage?: () => void }) {</>)}{pairingCode}- {passwordBlock}</If></Tabs.Panel>@@ -464,31 +440,34 @@ export function RemoteShare({ onManage }: { onManage?: () => void }) {<If cond={status !== null && tunnelState === 'starting'}><div className="flex flex-col gap-4 justify-center items-center">- <Description className="flex items-center gap-1.5 text-xs">- <Spinner className="size-3" />- {t('remote.share.tunnel_starting')}- <If cond={stage}>- (- {t(`remote.share.stage.${stage}`)}- )- </If>- </Description>- {total !== undefined && (- <>- <ProgressBar- size="sm"- value={Math.min(100, ((received ?? 0) / (total || 1)) * 100)}- className="w-full"- valueLabel={t('remote.share.download_progress', { received: megabytesOf(received), total: megabytesOf(total) })}- >- <Label>{t('remote.share.stage.download')}</Label>- <ProgressBar.Output className="text-xs text-muted tabular-nums" />- <ProgressBar.Track>- <ProgressBar.Fill className="bg-info" />- </ProgressBar.Track>- </ProgressBar>- </>- )}+ <If+ cond={downloading}+ else={(+ <Description className="flex items-center gap-1.5 text-xs">+ <Spinner className="size-3" />+ {t('remote.share.tunnel_starting')}+ <If cond={stage}>+ (+ {t(`remote.share.stage.${stage}`)}+ )+ </If>+ </Description>+ )}+ >+ <ProgressBar+ size="sm"+ value={downloadPercent}+ isIndeterminate={!knownTotal}+ className="w-full"+ valueLabel={downloadLabel}+ >+ <Label>{t('remote.share.stage.download')}</Label>+ <ProgressBar.Output className="text-xs text-muted tabular-nums">{downloadLabel}</ProgressBar.Output>+ <ProgressBar.Track>+ <ProgressBar.Fill className="bg-info" />+ </ProgressBar.Track>+ </ProgressBar>+ </If><ButtonclassName="h-8 w-full text-xs"variant="tertiary"@@ -545,7 +524,6 @@ export function RemoteShare({ onManage }: { onManage?: () => void }) {)}{pairingCode}- {passwordBlock}<ButtonclassName="h-8 w-full text-xs"diff --git a/src/layout/components/view-menu.test.tsx b/src/layout/components/view-menu.test.tsxindex a3c9124c..650b282e 100644--- a/src/layout/components/view-menu.test.tsx+++ b/src/layout/components/view-menu.test.tsx@@ -29,6 +29,7 @@ vi.mock('@/store', () => ({ store }))vi.mock('valtio-define', () => ({ useStore: (value: unknown) => value }))vi.mock('@tauri-apps/plugin-os', () => ({ type: () => 'macos' }))vi.mock('@tanstack/react-query', () => ({+ useMutation: () => ({ mutate: vi.fn(), isPending: false }),useQuery: () => ({ data: [] }),useQueryClient: () => ({ ensureQueryData: () => Promise.resolve('dsh-tauri') }),}))diff --git a/test/e2e/plugins/dsh-tauri-remote-access.e2e.ts b/test/e2e/plugins/dsh-tauri-remote-access.e2e.tsindex 39919c01..95d15faf 100644--- a/test/e2e/plugins/dsh-tauri-remote-access.e2e.ts+++ b/test/e2e/plugins/dsh-tauri-remote-access.e2e.ts@@ -1,16 +1,3 @@-/**- * 批次 · `dsh-tauri-remote` 入站暴露(S4/S5)在真实 `dsh web` 宿主里的路由契约。- *- * 复用 globalSetup 的共享宿主(`DSH_E2E_PLUGIN=dsh-tauri-remote`),因此断言的是**打包产物**:- * 插件从 `src-tauri/resources` 加载,`/access` 的二维码生成必须证明 qrcode 已被构建期内联。- *- * 三条边界都在外部世界:HTTP 状态码、真实监听端口上的转发响应、`<DSH_HOME>/remote/access.json`- * 的落盘形态。每个改状态的用例都在 `finally` 里关掉暴露并清空凭据,绝不把端口与凭据留给后续用例。- *- * 隧道只覆盖**参数校验**:quick 模式会真的去下载 cloudflared(网络依赖),进程生命周期由- * `service/tunnel.test.ts` 用注入的桩进程覆盖,不在共享宿主里起真进程。- */-import type { Server } from 'node:http'import { existsSync, readFileSync } from 'node:fs'import { createServer } from 'node:http'@@ -19,7 +6,6 @@ import { afterEach, describe, expect, inject, it } from 'vitest'const BASE = '/api/tauri/remote'const ACCESS = `${BASE}/access`-const TOKEN = `${ACCESS}/token`const TUNNEL = `${ACCESS}/tunnel`interface AccessStatus {@@ -28,12 +14,12 @@ interface AccessStatus {listening: booleanlisten: { address: string, port: number }port: number- auth: { enabled: boolean, scope: string, hasPassword?: boolean, hasToken?: boolean }+ auth: { enabled: boolean, scope: string, hasToken?: boolean }link?: stringmaskLink?: stringqr?: stringlinkSource?: string- generatedPassword?: string+ pairing?: { code: string, expiresAt: number, usedSeq: number, link?: string, qr?: string }tunnel: { enabled: boolean, mode: string, state: string, url?: string, qr?: string, progress?: { stage: string, received?: number, total?: number } }localPort?: numbererror?: string@@ -74,9 +60,8 @@ async function disable(): Promise<AccessStatus> {return response.body}-/** 每个用例收尾:关暴露、关认证、清密码并把监听地址复位,乱序执行时不把状态留给下一个用例。 */afterEach(async () => {- await writeAccess({ enabled: false, authEnabled: false, password: null, address: '127.0.0.1' })+ await writeAccess({ enabled: false, authEnabled: false, address: '127.0.0.1' })})describe('入站暴露路由(真实 dsh 宿主)', () => {@@ -90,7 +75,8 @@ describe('入站暴露路由(真实 dsh 宿主)', () => {expect(status.tunnel.state).toBe('stopped')expect(status.tunnel.mode).toBe('quick')expect(status.auth.hasToken).toBe(false)- expect(status.auth.hasPassword).toBe(false)+ expect(status.auth).not.toHaveProperty('hasPassword')+ expect(status).not.toHaveProperty('generatedPassword')})it('开启回环监听:真实端口可转发,localPort 取自宿主 webserver 的实监听端口', async () => {@@ -104,7 +90,9 @@ describe('入站暴露路由(真实 dsh 宿主)', () => {expect(started.body.linkSource).toBe('loopback')expect(started.body.qr, '面板需要本地核对用二维码,回环监听也生成').toMatch(/^data:image\/png;base64,/u)expect(started.body.auth.enabled, '开启暴露即自动带认证').toBe(true)- expect(started.body.auth.hasPassword, '没有凭据时自动生成密码').toBe(true)+ expect(started.body.pairing?.code).toMatch(/^[2-9A-HJ-NP-Z]{8}$/u)+ expect(started.body.auth).not.toHaveProperty('hasPassword')+ expect(started.body).not.toHaveProperty('generatedPassword')const proxied = await fetch(`http://127.0.0.1:${port}/`)expect(proxied.status).toBe(200)@@ -115,30 +103,52 @@ describe('入站暴露路由(真实 dsh 宿主)', () => {expect(stopped.link).toBeUndefined()}, 60_000)- it('链接 Token 可签发与作废,链接与二维码只在有 Token 时带 auth 参数', async () => {+ it('配对码换会话后立即轮换,旧码不可重放且既有会话仍可访问', async () => {const port = await freePort()- await writeAccess({ enabled: true, address: '0.0.0.0', port, authEnabled: true, password: 'e2e-access-pass', scope: 'public_only' })- try {- const issued = await fetch(url(TOKEN), { method: 'POST', headers: apiHeaders() })- expect(issued.status).toBe(200)- const withToken = await issued.json() as AccessStatus- expect(withToken.auth.hasToken).toBe(true)- expect(withToken.auth.hasPassword).toBe(true)- expect(withToken.link).toMatch(/\?auth=/u)- expect(withToken.qr, '非回环监听给出二维码,证明打包产物里的二维码编码可用').toMatch(/^data:image\/png;base64,/u)- expect(withToken.maskLink).toContain('?auth=***')-- const revoked = await fetch(url(TOKEN), { method: 'DELETE', headers: apiHeaders() })- expect(revoked.status).toBe(200)- const withoutToken = await revoked.json() as AccessStatus- expect(withoutToken.auth.hasToken).toBe(false)- expect(withoutToken.link).not.toContain('?auth=')- }- finally {- await disable()- }+ const started = await writeAccess({ enabled: true, address: '0.0.0.0', port, authEnabled: true, scope: 'all' })+ expect(started.status).toBe(200)+ const pairing = started.body.pairing+ expect(pairing?.link).toContain(`?auth=${pairing?.code}`)+ expect(pairing?.qr).toMatch(/^data:image\/png;base64,/u)+ const origin = `http://127.0.0.1:${started.body.port}`+ const source = { 'x-dsh-remote-source': 'public', 'accept': 'application/json' }+ const challenge = await fetch(`${origin}/`, { headers: { ...source, accept: 'text/html' } })+ expect(challenge.status).toBe(401)+ const html = await challenge.text()+ expect(html).toContain('<form id="loginForm" method="post">')+ expect(html).toContain('name="code"')+ expect(html).not.toContain('name="password"')+ const exchanged = await fetch(`${origin}/?auth=${pairing?.code}`, { headers: source, redirect: 'manual' })+ expect(exchanged.status).toBe(302)+ expect(exchanged.headers.get('location')).toBe('/')+ const cookie = exchanged.headers.getSetCookie().map(value => value.split(';')[0] ?? '').find(value => value.startsWith('dsh_remote_session='))+ expect(cookie).toBeTruthy()+ const next = await readAccess()+ expect(next.pairing?.usedSeq).toBe((pairing?.usedSeq ?? 0) + 1)+ expect(next.pairing?.code).not.toBe(pairing?.code)+ expect((await fetch(`${origin}/?auth=${pairing?.code}`, { headers: source, redirect: 'manual' })).status).toBe(401)+ expect((await fetch(`${origin}/`, { headers: { ...source, cookie: cookie ?? '' } })).status).toBe(200)}, 60_000)+ it('原生健康检查无需会话,只有 manifest 可匿名读取且不消费配对码', async () => {+ const port = await freePort()+ const started = await writeAccess({ enabled: true, address: '127.0.0.1', port, authEnabled: true, scope: 'all' })+ expect(started.status).toBe(200)+ const origin = `http://127.0.0.1:${port}`+ const headers = { 'x-dsh-remote-source': 'public', 'accept': 'application/json' }+ const manifest = await fetch(`${origin}/manifest.webmanifest`, { headers })+ expect(manifest.status).toBe(200)+ expect(await manifest.json()).toMatchObject({ name: 'DeepSeek Harness', short_name: 'DSH' })+ expect(manifest.headers.get('set-cookie')).toBeNull()+ const head = await fetch(`${origin}/manifest.webmanifest?auth=${started.body.pairing?.code}`, { method: 'HEAD', headers })+ expect(head.status).toBe(200)+ expect(await head.text()).toBe('')+ expect((await readAccess()).pairing).toEqual(started.body.pairing)+ expect((await fetch(`${origin}/`, { headers })).status).toBe(401)+ expect((await fetch(`${origin}${ACCESS}`, { headers })).status).toBe(401)+ expect((await fetch(`${origin}/manifest.webmanifest`, { headers: { ...headers, origin: 'https://evil.example' } })).status).toBe(403)+ })+it('隧道参数校验:具名模式缺凭据或主机名时 400,且不落盘', async () => {const missingCredential = await fetch(url(TUNNEL), { method: 'POST', headers: apiHeaders(), body: JSON.stringify({ mode: 'token' }) })expect(missingCredential.status).toBe(400)